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,745 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Workflows: the state machine for each item type.
|
|
3
|
+
|
|
4
|
+
A domain ships its workflows as YAML and registers the named checks the YAML
|
|
5
|
+
refers to. The YAML says which transitions exist and what each one requires;
|
|
6
|
+
the checks are tested Python. A project may make a workflow stricter in
|
|
7
|
+
``config.yaml`` (extra requirements, or a state inserted into a transition),
|
|
8
|
+
never looser.
|
|
9
|
+
|
|
10
|
+
Every workflow also has two states of its own, unless it turns them off:
|
|
11
|
+
``PARKED`` (from any open state, back only to where it came from) and
|
|
12
|
+
``ABANDONED`` (from any open state, terminal). Both need a note.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import date
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
import yaml
|
|
24
|
+
|
|
25
|
+
from .errors import ExitCode, ForgeError
|
|
26
|
+
from .schema import Field, validate
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from .items import Item
|
|
30
|
+
|
|
31
|
+
PARKED = "PARKED"
|
|
32
|
+
ABANDONED = "ABANDONED"
|
|
33
|
+
RESERVED_STATES = (PARKED, ABANDONED)
|
|
34
|
+
WORKFLOW_SCHEMA_VERSION = 1
|
|
35
|
+
|
|
36
|
+
_STATE = re.compile(r"^[A-Z][A-Z_]*$")
|
|
37
|
+
_CONDITION = re.compile(r"^([a-z][a-z_]*)(?::(.+))?$")
|
|
38
|
+
_GATE_KIND = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
|
39
|
+
_RULING = re.compile(r"^[a-z][a-z_]*$")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def gate_kind_of(cond: Condition) -> str:
|
|
43
|
+
"""The gate kind a gate condition names: ``G2`` for ``gate_revise:G2/spec``."""
|
|
44
|
+
return re.split(r"[/=]", cond.arg or "", maxsplit=1)[0]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _passing(ctx: CheckContext, kind: str) -> tuple[str, ...]:
|
|
48
|
+
gate_kind = ctx.domain.gate_kind(kind) if ctx.domain is not None else None
|
|
49
|
+
return gate_kind.passing if gate_kind is not None else ("accept",)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ------------------------------------------------------------------ the model
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Condition:
|
|
57
|
+
"""A named check and its argument: ``gate:G1``, ``field_in:severity=high``."""
|
|
58
|
+
|
|
59
|
+
name: str
|
|
60
|
+
arg: str | None = None
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def parse(cls, text: str) -> Condition:
|
|
64
|
+
match = _CONDITION.match(text)
|
|
65
|
+
if not match:
|
|
66
|
+
raise ValueError(f"{text!r} is not a condition like 'name' or 'name:argument'")
|
|
67
|
+
return cls(match.group(1), match.group(2))
|
|
68
|
+
|
|
69
|
+
def __str__(self) -> str:
|
|
70
|
+
return self.name if self.arg is None else f"{self.name}:{self.arg}"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Transition:
|
|
75
|
+
"""One edge. ``via`` names the command that makes it; ``move`` refuses those."""
|
|
76
|
+
|
|
77
|
+
source: str
|
|
78
|
+
target: str
|
|
79
|
+
requires: tuple[Condition, ...] = ()
|
|
80
|
+
via: str | None = None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class Workflow:
|
|
85
|
+
"""The state machine for one item type."""
|
|
86
|
+
|
|
87
|
+
type: str
|
|
88
|
+
initial: str
|
|
89
|
+
terminal: tuple[str, ...]
|
|
90
|
+
transitions: tuple[Transition, ...]
|
|
91
|
+
park: bool = True
|
|
92
|
+
abandon: bool = True
|
|
93
|
+
abandon_requires: tuple[Condition, ...] = ()
|
|
94
|
+
|
|
95
|
+
def all_conditions(self) -> tuple[Condition, ...]:
|
|
96
|
+
"""Every condition the workflow uses."""
|
|
97
|
+
found = [c for t in self.transitions for c in t.requires]
|
|
98
|
+
return tuple(dict.fromkeys((*found, *self.abandon_requires)))
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def states(self) -> tuple[str, ...]:
|
|
102
|
+
"""Declared states in first-seen order (without PARKED and ABANDONED)."""
|
|
103
|
+
seen: dict[str, None] = {self.initial: None}
|
|
104
|
+
for t in self.transitions:
|
|
105
|
+
for state in (t.source, t.target):
|
|
106
|
+
if state not in RESERVED_STATES:
|
|
107
|
+
seen.setdefault(state, None)
|
|
108
|
+
return tuple(seen)
|
|
109
|
+
|
|
110
|
+
def is_open(self, state: str) -> bool:
|
|
111
|
+
"""Whether ``state`` can still be worked on (and so parked or abandoned)."""
|
|
112
|
+
return state not in self.terminal and state != ABANDONED
|
|
113
|
+
|
|
114
|
+
def edges(self, source: str, target: str) -> tuple[Transition, ...]:
|
|
115
|
+
"""The alternatives for ``source → target``."""
|
|
116
|
+
return tuple(t for t in self.transitions if t.source == source and t.target == target)
|
|
117
|
+
|
|
118
|
+
def via_edges(self, via: str) -> tuple[Transition, ...]:
|
|
119
|
+
"""The transitions only the ``via`` command makes."""
|
|
120
|
+
return tuple(t for t in self.transitions if t.via == via)
|
|
121
|
+
|
|
122
|
+
def targets(self, source: str) -> tuple[str, ...]:
|
|
123
|
+
"""Where ``move`` can take an item from ``source``."""
|
|
124
|
+
found: dict[str, None] = {}
|
|
125
|
+
for t in self.transitions:
|
|
126
|
+
if t.source == source and t.via is None:
|
|
127
|
+
found.setdefault(t.target, None)
|
|
128
|
+
if self.is_open(source) and source != PARKED:
|
|
129
|
+
if self.park:
|
|
130
|
+
found.setdefault(PARKED, None)
|
|
131
|
+
if self.abandon:
|
|
132
|
+
found.setdefault(ABANDONED, None)
|
|
133
|
+
return tuple(found)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class CheckContext:
|
|
138
|
+
"""What a check may look at: the item, the whole log, the config, and today."""
|
|
139
|
+
|
|
140
|
+
item: Item
|
|
141
|
+
events: Sequence[Mapping[str, Any]]
|
|
142
|
+
config: Mapping[str, Any]
|
|
143
|
+
today: date
|
|
144
|
+
domain: Any = None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True)
|
|
148
|
+
class Outcome:
|
|
149
|
+
"""A check's answer. ``why`` says what is missing; ``gate`` names the gate that passed."""
|
|
150
|
+
|
|
151
|
+
ok: bool
|
|
152
|
+
why: str = ""
|
|
153
|
+
gate: str | None = None
|
|
154
|
+
unavailable: bool = False
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _no_argument(arg: str | None, _domain: Any) -> None:
|
|
158
|
+
if arg is not None:
|
|
159
|
+
raise ValueError("takes no argument")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class Check:
|
|
164
|
+
"""A named condition: how to describe it, test it, and validate its argument."""
|
|
165
|
+
|
|
166
|
+
label: Callable[[str | None], str]
|
|
167
|
+
test: Callable[[CheckContext, str | None], Outcome]
|
|
168
|
+
validate: Callable[[str | None, Any], None] = _no_argument
|
|
169
|
+
is_gate: bool = False
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def simple_check(label: str, test: Callable[[CheckContext], Outcome]) -> Check:
|
|
173
|
+
"""A check with no argument."""
|
|
174
|
+
return Check(label=lambda _: label, test=lambda ctx, _: test(ctx))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def pending_check(label: str) -> Check:
|
|
178
|
+
"""A condition the forge cannot evaluate yet. It always refuses, and says why."""
|
|
179
|
+
return Check(
|
|
180
|
+
label=lambda _: label,
|
|
181
|
+
test=lambda _ctx, _arg: Outcome(
|
|
182
|
+
False, f"{label}: not recorded yet in this version", unavailable=True
|
|
183
|
+
),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ------------------------------------------------------------------ built-in checks
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def gate_history(
|
|
191
|
+
events: Sequence[Mapping[str, Any]], item_id: str, kind: str
|
|
192
|
+
) -> list[tuple[str, Mapping[str, Any] | None, bool]]:
|
|
193
|
+
"""Gates of ``kind`` on the item, oldest first: ``(gate_id, ruling_data, used)``.
|
|
194
|
+
|
|
195
|
+
``used`` is true once a ``state`` event has cited the gate: a gate authorizes
|
|
196
|
+
one transition.
|
|
197
|
+
"""
|
|
198
|
+
opened: list[str] = []
|
|
199
|
+
rulings: dict[str, Mapping[str, Any]] = {}
|
|
200
|
+
used: set[str] = set()
|
|
201
|
+
for event in events:
|
|
202
|
+
data = event.get("data", {})
|
|
203
|
+
etype = event["type"]
|
|
204
|
+
if etype == "gate_opened" and event.get("item") == item_id and data.get("kind") == kind:
|
|
205
|
+
opened.append(data["gate"])
|
|
206
|
+
elif etype == "gate_ruled" and "gate" in data:
|
|
207
|
+
rulings.setdefault(data["gate"], data)
|
|
208
|
+
elif etype == "state" and "gate" in data:
|
|
209
|
+
used.add(data["gate"])
|
|
210
|
+
return [(g, rulings.get(g), g in used) for g in opened]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _latest_gate(ctx: CheckContext, kind: str) -> tuple[str, Mapping[str, Any]] | Outcome:
|
|
214
|
+
history = gate_history(ctx.events, ctx.item.id, kind)
|
|
215
|
+
if not history:
|
|
216
|
+
return Outcome(False, f"no {kind} gate has been opened")
|
|
217
|
+
gate_id, ruling, used = history[-1]
|
|
218
|
+
if ruling is None:
|
|
219
|
+
return Outcome(False, f"{gate_id} has not been ruled")
|
|
220
|
+
if used:
|
|
221
|
+
return Outcome(False, f"{gate_id} was already used; open a new {kind} gate")
|
|
222
|
+
return gate_id, ruling
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _gate(ctx: CheckContext, arg: str | None) -> Outcome:
|
|
226
|
+
latest = _latest_gate(ctx, str(arg))
|
|
227
|
+
if isinstance(latest, Outcome):
|
|
228
|
+
return latest
|
|
229
|
+
gate_id, ruling = latest
|
|
230
|
+
if ruling.get("ruling") in _passing(ctx, str(arg)):
|
|
231
|
+
return Outcome(True, gate=gate_id)
|
|
232
|
+
return Outcome(False, f"{gate_id} was ruled {ruling.get('ruling')}")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _gate_ruled(ctx: CheckContext, arg: str | None) -> Outcome:
|
|
236
|
+
kind, _, wanted = str(arg).partition("=")
|
|
237
|
+
latest = _latest_gate(ctx, kind)
|
|
238
|
+
if isinstance(latest, Outcome):
|
|
239
|
+
return latest
|
|
240
|
+
gate_id, ruling = latest
|
|
241
|
+
if ruling.get("ruling") == wanted:
|
|
242
|
+
return Outcome(True, gate=gate_id)
|
|
243
|
+
return Outcome(False, f"{gate_id} was ruled {ruling.get('ruling')}, not {wanted}")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _gate_pending(ctx: CheckContext, arg: str | None) -> Outcome:
|
|
247
|
+
history = gate_history(ctx.events, ctx.item.id, str(arg))
|
|
248
|
+
if history and history[-1][1] is None:
|
|
249
|
+
return Outcome(True)
|
|
250
|
+
return Outcome(False, f"no {arg} gate is waiting for a ruling")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _gate_revise(ctx: CheckContext, arg: str | None) -> Outcome:
|
|
254
|
+
kind, _, target = str(arg).partition("/")
|
|
255
|
+
latest = _latest_gate(ctx, kind)
|
|
256
|
+
if isinstance(latest, Outcome):
|
|
257
|
+
return latest
|
|
258
|
+
gate_id, ruling = latest
|
|
259
|
+
if ruling.get("ruling") != "revise":
|
|
260
|
+
return Outcome(False, f"{gate_id} was ruled {ruling.get('ruling')}, not revise")
|
|
261
|
+
if target and ruling.get("revise_target") != target:
|
|
262
|
+
return Outcome(False, f"{gate_id} was revised to {ruling.get('revise_target')}")
|
|
263
|
+
return Outcome(True, gate=gate_id)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _gate_if_opened(ctx: CheckContext, arg: str | None) -> Outcome:
|
|
267
|
+
history = gate_history(ctx.events, ctx.item.id, str(arg))
|
|
268
|
+
if not history:
|
|
269
|
+
return Outcome(True)
|
|
270
|
+
gate_id, ruling, _ = history[-1]
|
|
271
|
+
if ruling is not None and ruling.get("ruling") in _passing(ctx, str(arg)):
|
|
272
|
+
return Outcome(True)
|
|
273
|
+
state = "has not been ruled" if ruling is None else f"was ruled {ruling.get('ruling')}"
|
|
274
|
+
return Outcome(False, f"{gate_id} {state}")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _field_in(ctx: CheckContext, arg: str | None) -> Outcome:
|
|
278
|
+
name, _, values = str(arg).partition("=")
|
|
279
|
+
allowed = values.split(",")
|
|
280
|
+
actual = ctx.item.fields.get(name)
|
|
281
|
+
if actual in allowed:
|
|
282
|
+
return Outcome(True)
|
|
283
|
+
return Outcome(False, f"{name} is {actual if actual is not None else 'not set'}")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _check_gate_kind(arg: str | None, _domain: Any) -> None:
|
|
287
|
+
if arg is None or not _GATE_KIND.match(arg):
|
|
288
|
+
raise ValueError("needs a gate kind, like gate:G1")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _check_revise(arg: str | None, _domain: Any) -> None:
|
|
292
|
+
kind, _, target = (arg or "").partition("/")
|
|
293
|
+
if not _GATE_KIND.match(kind) or (target and not re.match(r"^[a-z][a-z_]*$", target)):
|
|
294
|
+
raise ValueError("needs a gate kind and optional target, like gate_revise:G2/requirements")
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _check_gate_ruled(arg: str | None, domain: Any) -> None:
|
|
298
|
+
kind, sep, ruling = (arg or "").partition("=")
|
|
299
|
+
if not sep or not _GATE_KIND.match(kind) or not _RULING.match(ruling):
|
|
300
|
+
raise ValueError("needs a gate kind and ruling, like gate_ruled:RESPONSE=mitigate")
|
|
301
|
+
gate_kind = domain.gate_kind(kind) if domain is not None and domain.gate_kinds else None
|
|
302
|
+
if gate_kind is not None and ruling not in gate_kind.rulings:
|
|
303
|
+
raise ValueError(f"{kind} has no ruling {ruling!r}")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _check_field_in(arg: str | None, domain: Any) -> None:
|
|
307
|
+
name, sep, values = (arg or "").partition("=")
|
|
308
|
+
if not sep or not name or not values or "" in values.split(","):
|
|
309
|
+
raise ValueError("needs field=value[,value…], like field_in:severity=critical,high")
|
|
310
|
+
if domain is not None and name not in domain.item_schema:
|
|
311
|
+
raise ValueError(f"{name!r} is not a front-matter field")
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _revise_label(arg: str | None) -> str:
|
|
315
|
+
kind, _, target = str(arg).partition("/")
|
|
316
|
+
return f"{kind} revise" + (f" ({target})" if target else "")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _field_label(arg: str | None) -> str:
|
|
320
|
+
name, _, values = str(arg).partition("=")
|
|
321
|
+
return f"{name} {' or '.join(values.split(','))}"
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
#: Checks every domain has. A domain's own checks may not reuse these names.
|
|
325
|
+
BUILTIN_CHECKS: Mapping[str, Check] = {
|
|
326
|
+
"gate": Check(lambda a: f"{a} accept", _gate, _check_gate_kind, is_gate=True),
|
|
327
|
+
"gate_revise": Check(_revise_label, _gate_revise, _check_revise, is_gate=True),
|
|
328
|
+
"gate_ruled": Check(
|
|
329
|
+
lambda a: f"{str(a).partition('=')[0]} ruled {str(a).partition('=')[2]}",
|
|
330
|
+
_gate_ruled,
|
|
331
|
+
_check_gate_ruled,
|
|
332
|
+
is_gate=True,
|
|
333
|
+
),
|
|
334
|
+
"gate_pending": Check(
|
|
335
|
+
lambda a: f"new {a} gate opened", _gate_pending, _check_gate_kind, is_gate=True
|
|
336
|
+
),
|
|
337
|
+
"gate_if_opened": Check(
|
|
338
|
+
lambda a: f"{a} passed (if opened)", _gate_if_opened, _check_gate_kind, is_gate=True
|
|
339
|
+
),
|
|
340
|
+
"field_in": Check(_field_label, _field_in, _check_field_in),
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
# ------------------------------------------------------------------ loading
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
_TRANSITION = Field(
|
|
348
|
+
"section",
|
|
349
|
+
children={
|
|
350
|
+
"from": Field("str", required=True),
|
|
351
|
+
"to": Field("str", required=True),
|
|
352
|
+
"requires": Field("list", default=[], item=Field("str")),
|
|
353
|
+
"via": Field("str", nullable=True),
|
|
354
|
+
},
|
|
355
|
+
)
|
|
356
|
+
_FILE = Field(
|
|
357
|
+
"section",
|
|
358
|
+
children={
|
|
359
|
+
"schema": Field("int", required=True, minimum=1),
|
|
360
|
+
"workflows": Field(
|
|
361
|
+
"map",
|
|
362
|
+
item=Field(
|
|
363
|
+
"section",
|
|
364
|
+
children={
|
|
365
|
+
"initial": Field("str", required=True),
|
|
366
|
+
"terminal": Field("list", required=True, item=Field("str")),
|
|
367
|
+
"park": Field("bool", default=True),
|
|
368
|
+
"abandon": Field("bool", default=True),
|
|
369
|
+
"abandon_requires": Field("list", default=[], item=Field("str")),
|
|
370
|
+
"transitions": Field("list", required=True, item=_TRANSITION),
|
|
371
|
+
},
|
|
372
|
+
),
|
|
373
|
+
),
|
|
374
|
+
},
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
#: The ``workflows`` key of ``config.yaml``: stricter-only changes, per item type.
|
|
378
|
+
OVERRIDES_SCHEMA = Field(
|
|
379
|
+
"map",
|
|
380
|
+
default={},
|
|
381
|
+
item=Field(
|
|
382
|
+
"section",
|
|
383
|
+
children={
|
|
384
|
+
"require": Field(
|
|
385
|
+
"list",
|
|
386
|
+
default=[],
|
|
387
|
+
item=Field(
|
|
388
|
+
"section",
|
|
389
|
+
children={
|
|
390
|
+
"from": Field("str", required=True),
|
|
391
|
+
"to": Field("str", required=True),
|
|
392
|
+
"requires": Field("list", required=True, item=Field("str")),
|
|
393
|
+
},
|
|
394
|
+
),
|
|
395
|
+
),
|
|
396
|
+
"insert": Field(
|
|
397
|
+
"list",
|
|
398
|
+
default=[],
|
|
399
|
+
item=Field(
|
|
400
|
+
"section",
|
|
401
|
+
children={
|
|
402
|
+
"state": Field("str", required=True),
|
|
403
|
+
"between": Field("list", required=True, item=Field("str")),
|
|
404
|
+
"requires": Field("list", default=[], item=Field("str")),
|
|
405
|
+
},
|
|
406
|
+
),
|
|
407
|
+
),
|
|
408
|
+
},
|
|
409
|
+
),
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _conditions(
|
|
414
|
+
texts: Sequence[str], checks: Mapping[str, Check], domain: Any
|
|
415
|
+
) -> tuple[Condition, ...]:
|
|
416
|
+
out = []
|
|
417
|
+
for text in texts:
|
|
418
|
+
cond = Condition.parse(text)
|
|
419
|
+
check = checks.get(cond.name)
|
|
420
|
+
if check is None:
|
|
421
|
+
raise ValueError(f"unknown check {cond.name!r}")
|
|
422
|
+
try:
|
|
423
|
+
check.validate(cond.arg, domain)
|
|
424
|
+
except ValueError as exc:
|
|
425
|
+
raise ValueError(f"{text}: {exc}") from exc
|
|
426
|
+
kinds = {k.name for k in getattr(domain, "gate_kinds", ())}
|
|
427
|
+
if kinds and check.is_gate and gate_kind_of(cond) not in kinds:
|
|
428
|
+
raise ValueError(f"{text}: no such gate kind")
|
|
429
|
+
out.append(cond)
|
|
430
|
+
if len(set(out)) != len(out):
|
|
431
|
+
raise ValueError("a condition is listed twice")
|
|
432
|
+
return tuple(out)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _check_shape(wf: Workflow) -> None:
|
|
436
|
+
"""States are well-formed, reachable, and no open state is a dead end."""
|
|
437
|
+
for state in (
|
|
438
|
+
wf.initial,
|
|
439
|
+
*wf.terminal,
|
|
440
|
+
*(s for t in wf.transitions for s in (t.source, t.target)),
|
|
441
|
+
):
|
|
442
|
+
if not _STATE.match(state):
|
|
443
|
+
raise ValueError(f"state names are upper-case words joined by _: {state!r}")
|
|
444
|
+
if wf.initial in RESERVED_STATES:
|
|
445
|
+
raise ValueError(f"{wf.initial} cannot be the initial state")
|
|
446
|
+
seen: set[tuple[str, str, tuple[Condition, ...], str | None]] = set()
|
|
447
|
+
for t in wf.transitions:
|
|
448
|
+
if t.target in RESERVED_STATES:
|
|
449
|
+
raise ValueError(f"{t.source} → {t.target}: {t.target} transitions are built in")
|
|
450
|
+
if t.source == PARKED or (t.source == ABANDONED and t.via is None):
|
|
451
|
+
raise ValueError(f"{t.source} → {t.target}: only a 'via' command may leave {t.source}")
|
|
452
|
+
if t.source == t.target:
|
|
453
|
+
raise ValueError(f"{t.source} → {t.target}: a state cannot move to itself")
|
|
454
|
+
key = (t.source, t.target, t.requires, t.via)
|
|
455
|
+
if key in seen:
|
|
456
|
+
raise ValueError(f"{t.source} → {t.target} is listed twice")
|
|
457
|
+
seen.add(key)
|
|
458
|
+
states = set(wf.states)
|
|
459
|
+
for state in wf.terminal:
|
|
460
|
+
if state not in states:
|
|
461
|
+
raise ValueError(f"terminal state {state} has no transitions into it")
|
|
462
|
+
if any(t.source == state and t.via is None for t in wf.transitions):
|
|
463
|
+
raise ValueError(f"terminal state {state} has a 'move' transition out of it")
|
|
464
|
+
for state in states - set(wf.terminal):
|
|
465
|
+
if not any(t.source == state and t.via is None for t in wf.transitions):
|
|
466
|
+
raise ValueError(f"{state} is not terminal but has no way out")
|
|
467
|
+
reached, frontier = {wf.initial}, [wf.initial]
|
|
468
|
+
while frontier:
|
|
469
|
+
here = frontier.pop()
|
|
470
|
+
for t in wf.transitions:
|
|
471
|
+
if t.source == here and t.target not in reached:
|
|
472
|
+
reached.add(t.target)
|
|
473
|
+
frontier.append(t.target)
|
|
474
|
+
if wf.abandon:
|
|
475
|
+
reached |= {t.target for t in wf.transitions if t.source == ABANDONED}
|
|
476
|
+
unreached = sorted(states - reached)
|
|
477
|
+
if unreached:
|
|
478
|
+
raise ValueError(f"unreachable from {wf.initial}: {', '.join(unreached)}")
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def load_workflows(
|
|
482
|
+
text: str, where: str, checks: Mapping[str, Check], domain: Any = None
|
|
483
|
+
) -> dict[str, Workflow]:
|
|
484
|
+
"""Parse and check a domain's workflow file. Any mistake is a ``ValueError``."""
|
|
485
|
+
try:
|
|
486
|
+
raw = validate(yaml.safe_load(text), _FILE, "")
|
|
487
|
+
except (ForgeError, yaml.YAMLError) as exc:
|
|
488
|
+
detail = exc.detail if isinstance(exc, ForgeError) else str(exc)
|
|
489
|
+
raise ValueError(f"{where}: {detail}") from exc
|
|
490
|
+
if raw["schema"] != WORKFLOW_SCHEMA_VERSION:
|
|
491
|
+
raise ValueError(f"{where}: unsupported workflow schema {raw['schema']}")
|
|
492
|
+
out: dict[str, Workflow] = {}
|
|
493
|
+
for type_name, spec in raw["workflows"].items():
|
|
494
|
+
try:
|
|
495
|
+
transitions = tuple(
|
|
496
|
+
Transition(t["from"], t["to"], _conditions(t["requires"], checks, domain), t["via"])
|
|
497
|
+
for t in spec["transitions"]
|
|
498
|
+
)
|
|
499
|
+
wf = Workflow(
|
|
500
|
+
type=type_name,
|
|
501
|
+
initial=spec["initial"],
|
|
502
|
+
terminal=tuple(spec["terminal"]),
|
|
503
|
+
transitions=transitions,
|
|
504
|
+
park=spec["park"],
|
|
505
|
+
abandon=spec["abandon"],
|
|
506
|
+
abandon_requires=_conditions(spec["abandon_requires"], checks, domain),
|
|
507
|
+
)
|
|
508
|
+
if wf.abandon_requires and not wf.abandon:
|
|
509
|
+
raise ValueError("abandon_requires with abandon: false")
|
|
510
|
+
_check_shape(wf)
|
|
511
|
+
except ValueError as exc:
|
|
512
|
+
raise ValueError(f"{where}: {type_name}: {exc}") from exc
|
|
513
|
+
out[type_name] = wf
|
|
514
|
+
return out
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def apply_overrides(
|
|
518
|
+
workflows: Mapping[str, Workflow],
|
|
519
|
+
overrides: Mapping[str, Any],
|
|
520
|
+
checks: Mapping[str, Check],
|
|
521
|
+
domain: Any = None,
|
|
522
|
+
) -> dict[str, Workflow]:
|
|
523
|
+
"""A project's stricter workflows (CONTRACT §6). Mistakes are DATA errors.
|
|
524
|
+
|
|
525
|
+
``require`` adds conditions to every alternative of an existing transition.
|
|
526
|
+
``insert`` puts a new state into an existing transition A → B: A → NEW gets
|
|
527
|
+
the given requirements and NEW → B keeps A → B's. Neither can add a way
|
|
528
|
+
around a requirement, so the result is never looser than the original.
|
|
529
|
+
"""
|
|
530
|
+
out = dict(workflows)
|
|
531
|
+
for type_name, spec in overrides.items():
|
|
532
|
+
where = f"workflows.{type_name}"
|
|
533
|
+
if type_name not in out:
|
|
534
|
+
raise _override_error(where, f"no workflow for item type {type_name!r}")
|
|
535
|
+
wf = out[type_name]
|
|
536
|
+
transitions = list(wf.transitions)
|
|
537
|
+
for i, rule in enumerate(spec.get("require", [])):
|
|
538
|
+
path = f"{where}.require[{i}]"
|
|
539
|
+
hits = [
|
|
540
|
+
n
|
|
541
|
+
for n, t in enumerate(transitions)
|
|
542
|
+
if (t.source, t.target) == (rule["from"], rule["to"]) and t.via is None
|
|
543
|
+
]
|
|
544
|
+
if not hits:
|
|
545
|
+
raise _override_error(path, f"{rule['from']} → {rule['to']} is not a transition")
|
|
546
|
+
extra = _override_conditions(rule["requires"], checks, domain, path)
|
|
547
|
+
for n in hits:
|
|
548
|
+
t = transitions[n]
|
|
549
|
+
merged = t.requires + tuple(c for c in extra if c not in t.requires)
|
|
550
|
+
transitions[n] = Transition(t.source, t.target, merged, t.via)
|
|
551
|
+
for i, rule in enumerate(spec.get("insert", [])):
|
|
552
|
+
path = f"{where}.insert[{i}]"
|
|
553
|
+
between = rule["between"]
|
|
554
|
+
if len(between) != 2:
|
|
555
|
+
raise _override_error(path, "between takes two states: [FROM, TO]")
|
|
556
|
+
source, target = between
|
|
557
|
+
new = rule["state"]
|
|
558
|
+
if (
|
|
559
|
+
not _STATE.match(new)
|
|
560
|
+
or new in RESERVED_STATES
|
|
561
|
+
or new in {s for t in transitions for s in (t.source, t.target)}
|
|
562
|
+
):
|
|
563
|
+
raise _override_error(path, f"{new!r} must be a new upper-case state name")
|
|
564
|
+
edges = [
|
|
565
|
+
t for t in transitions if (t.source, t.target) == (source, target) and t.via is None
|
|
566
|
+
]
|
|
567
|
+
if not edges:
|
|
568
|
+
raise _override_error(path, f"{source} → {target} is not a transition")
|
|
569
|
+
first = _override_conditions(rule["requires"], checks, domain, path)
|
|
570
|
+
transitions = [t for t in transitions if t not in edges]
|
|
571
|
+
transitions.append(Transition(source, new, first))
|
|
572
|
+
transitions.extend(Transition(new, target, t.requires) for t in edges)
|
|
573
|
+
changed = Workflow(
|
|
574
|
+
wf.type, wf.initial, wf.terminal, tuple(transitions), wf.park, wf.abandon
|
|
575
|
+
)
|
|
576
|
+
try:
|
|
577
|
+
_check_shape(changed)
|
|
578
|
+
except ValueError as exc: # pragma: no cover - the two operations preserve shape
|
|
579
|
+
raise _override_error(where, str(exc)) from exc
|
|
580
|
+
out[type_name] = changed
|
|
581
|
+
return out
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _override_conditions(
|
|
585
|
+
texts: Sequence[str], checks: Mapping[str, Check], domain: Any, path: str
|
|
586
|
+
) -> tuple[Condition, ...]:
|
|
587
|
+
try:
|
|
588
|
+
return _conditions(texts, checks, domain)
|
|
589
|
+
except ValueError as exc:
|
|
590
|
+
raise _override_error(path, str(exc)) from exc
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _override_error(path: str, message: str) -> ForgeError:
|
|
594
|
+
return ForgeError(ExitCode.DATA, "config_invalid", f"{path}: {message}")
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
# ------------------------------------------------------------------ deciding a move
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
@dataclass(frozen=True)
|
|
601
|
+
class Decision:
|
|
602
|
+
"""The result of asking whether an item may move."""
|
|
603
|
+
|
|
604
|
+
allowed: bool
|
|
605
|
+
reason: str = "" # error reason code when refused
|
|
606
|
+
detail: str = ""
|
|
607
|
+
gate: str | None = None
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def label(cond: Condition, checks: Mapping[str, Check]) -> str:
|
|
611
|
+
"""Human words for a condition: ``G1 accept``, ``findings open``."""
|
|
612
|
+
return checks[cond.name].label(cond.arg)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def decide( # noqa: PLR0913 - the item, where it is and where it goes, plus context
|
|
616
|
+
wf: Workflow,
|
|
617
|
+
ctx: CheckContext,
|
|
618
|
+
current: str,
|
|
619
|
+
target: str,
|
|
620
|
+
*,
|
|
621
|
+
checks: Mapping[str, Check],
|
|
622
|
+
parked_from: str | None = None,
|
|
623
|
+
via: str | None = None,
|
|
624
|
+
) -> Decision:
|
|
625
|
+
"""Whether ``ctx.item`` may move from ``current`` to ``target``, and why not.
|
|
626
|
+
|
|
627
|
+
With ``via``, only that command's edges count: this is how a command such as
|
|
628
|
+
``archive`` asks for the transition ``move`` refuses with ``use_command``.
|
|
629
|
+
"""
|
|
630
|
+
arrow = f"{current} → {target}"
|
|
631
|
+
if via is not None:
|
|
632
|
+
own = [e for e in wf.edges(current, target) if e.via == via]
|
|
633
|
+
if not own:
|
|
634
|
+
return Decision(False, "transition_not_allowed", f"{arrow} is not made by {via}")
|
|
635
|
+
return _first_passing(own, ctx, checks, arrow)
|
|
636
|
+
if target not in (*wf.states, *RESERVED_STATES):
|
|
637
|
+
return Decision(
|
|
638
|
+
False, "unknown_state", f"{target} is not a {wf.type} state: {', '.join(wf.states)}"
|
|
639
|
+
)
|
|
640
|
+
if (
|
|
641
|
+
target == ABANDONED
|
|
642
|
+
and wf.abandon_requires
|
|
643
|
+
and (current == PARKED or target in wf.targets(current))
|
|
644
|
+
):
|
|
645
|
+
return _first_passing(
|
|
646
|
+
[Transition(current, ABANDONED, wf.abandon_requires)], ctx, checks, arrow
|
|
647
|
+
)
|
|
648
|
+
if current == PARKED:
|
|
649
|
+
if target == parked_from or (target == ABANDONED and wf.abandon):
|
|
650
|
+
return Decision(True)
|
|
651
|
+
return Decision(
|
|
652
|
+
False,
|
|
653
|
+
"transition_not_allowed",
|
|
654
|
+
f"a parked item returns to {parked_from} or is abandoned",
|
|
655
|
+
)
|
|
656
|
+
if target in RESERVED_STATES:
|
|
657
|
+
if target in wf.targets(current):
|
|
658
|
+
return Decision(True)
|
|
659
|
+
return Decision(False, "transition_not_allowed", f"{arrow} is not allowed")
|
|
660
|
+
edges = wf.edges(current, target)
|
|
661
|
+
if not edges:
|
|
662
|
+
options = ", ".join(wf.targets(current)) or "none"
|
|
663
|
+
return Decision(
|
|
664
|
+
False, "transition_not_allowed", f"{arrow} is not allowed. From {current}: {options}"
|
|
665
|
+
)
|
|
666
|
+
movable = [e for e in edges if e.via is None]
|
|
667
|
+
if not movable:
|
|
668
|
+
return Decision(False, "use_command", f"{arrow} happens through '{edges[0].via}', not move")
|
|
669
|
+
return _first_passing(movable, ctx, checks, arrow)
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _first_passing(
|
|
673
|
+
edges: Sequence[Transition], ctx: CheckContext, checks: Mapping[str, Check], arrow: str
|
|
674
|
+
) -> Decision:
|
|
675
|
+
"""Allow the first alternative whose requirements all pass; else explain them all."""
|
|
676
|
+
failures: list[list[tuple[Condition, Outcome]]] = []
|
|
677
|
+
for edge in edges:
|
|
678
|
+
results = [(c, checks[c.name].test(ctx, c.arg)) for c in edge.requires]
|
|
679
|
+
missing = [(c, o) for c, o in results if not o.ok]
|
|
680
|
+
if not missing:
|
|
681
|
+
gate = next((o.gate for _, o in results if o.gate), None)
|
|
682
|
+
return Decision(True, gate=gate)
|
|
683
|
+
failures.append(missing)
|
|
684
|
+
detail = f"{arrow} needs " + "; or ".join(
|
|
685
|
+
", ".join(f"{label(c, checks)} ({o.why})" for c, o in alt) for alt in failures
|
|
686
|
+
)
|
|
687
|
+
if any(all(checks[c.name].is_gate for c, _ in alt) for alt in failures):
|
|
688
|
+
reason = "gate_not_ruled"
|
|
689
|
+
elif any(not any(o.unavailable for _, o in alt) for alt in failures):
|
|
690
|
+
reason = "condition_unmet"
|
|
691
|
+
else:
|
|
692
|
+
reason = "condition_unavailable"
|
|
693
|
+
return Decision(False, reason, detail)
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
# ------------------------------------------------------------------ documentation
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def to_mermaid(wf: Workflow, checks: Mapping[str, Check]) -> str:
|
|
700
|
+
"""A ``stateDiagram-v2`` for the docs. PARKED and ABANDONED are left out."""
|
|
701
|
+
lines = ["stateDiagram-v2", f" [*] --> {wf.initial}"]
|
|
702
|
+
for t in wf.transitions:
|
|
703
|
+
if t.source in RESERVED_STATES:
|
|
704
|
+
continue
|
|
705
|
+
words = [label(c, checks) for c in t.requires]
|
|
706
|
+
if t.via:
|
|
707
|
+
words.append(f"via {t.via}")
|
|
708
|
+
suffix = f": {' and '.join(words)}" if words else ""
|
|
709
|
+
lines.append(f" {t.source} --> {t.target}{suffix}")
|
|
710
|
+
lines.extend(
|
|
711
|
+
f" {state} --> [*]"
|
|
712
|
+
for state in wf.terminal
|
|
713
|
+
if not any(t.source == state for t in wf.transitions)
|
|
714
|
+
)
|
|
715
|
+
return "\n".join(lines)
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def to_markdown(
|
|
719
|
+
workflows: Mapping[str, Workflow], checks: Mapping[str, Check], titles: Mapping[str, str]
|
|
720
|
+
) -> str:
|
|
721
|
+
"""One section per workflow: a diagram and a table of conditioned transitions."""
|
|
722
|
+
parts: list[str] = []
|
|
723
|
+
for type_name, wf in workflows.items():
|
|
724
|
+
parts.append(f"#### {titles.get(type_name, type_name)}\n")
|
|
725
|
+
parts.append("```mermaid\n" + to_mermaid(wf, checks) + "\n```\n")
|
|
726
|
+
extras = []
|
|
727
|
+
if not wf.park:
|
|
728
|
+
extras.append("cannot be parked")
|
|
729
|
+
if not wf.abandon:
|
|
730
|
+
extras.append("cannot be abandoned")
|
|
731
|
+
if extras:
|
|
732
|
+
parts.append(f"This type {' and '.join(extras)}.\n")
|
|
733
|
+
if wf.abandon_requires:
|
|
734
|
+
words = " and ".join(label(c, checks) for c in wf.abandon_requires)
|
|
735
|
+
parts.append(f"Abandoning needs {words}.\n")
|
|
736
|
+
rows = [t for t in wf.transitions if t.requires]
|
|
737
|
+
if rows:
|
|
738
|
+
parts.append("| From | To | Requires (all of) |\n|---|---|---|")
|
|
739
|
+
parts.extend(
|
|
740
|
+
f"| {t.source} | {t.target} | "
|
|
741
|
+
f"{'; '.join(f'`{c}` — {label(c, checks)}' for c in t.requires)} |"
|
|
742
|
+
for t in rows
|
|
743
|
+
)
|
|
744
|
+
parts.append("")
|
|
745
|
+
return "\n".join(parts).rstrip("\n") + "\n"
|