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/domain.py ADDED
@@ -0,0 +1,549 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """What a domain plugin tells the core about itself (CORE.md §3)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from collections.abc import Callable, Mapping
8
+ from dataclasses import dataclass, field
9
+ from types import MappingProxyType
10
+ from typing import Any
11
+
12
+ from .errors import ExitCode, ForgeError
13
+ from .schema import Field
14
+ from .versions import RESERVED_PREFIXES, RESERVED_TYPES, TEAM_WALL, VERSIONED
15
+ from .workflow import BUILTIN_CHECKS, Check, Workflow, gate_kind_of
16
+
17
+ _NAME = re.compile(r"^[a-z][a-z0-9]*$")
18
+ _PREFIX = re.compile(r"^[A-Z][A-Z0-9]*$")
19
+ _EVENT_TYPE = re.compile(r"^[a-z][a-z0-9_]*$")
20
+ _ROLE = re.compile(r"^[a-z][a-z-]*$")
21
+ _ITEM_PREFIX = re.compile(r"^[A-Z]+$")
22
+ _GATE_KIND = re.compile(r"^[A-Z][A-Z0-9_]*$")
23
+
24
+ _RULING = re.compile(r"^[a-z][a-z_]*$")
25
+
26
+ #: Front-matter keys the core owns (CONTRACT §4); a domain's item schema adds others.
27
+ CORE_FRONT_MATTER = ("schema", "id", "title", "type", "state", "created")
28
+
29
+ #: Roles every domain has. The orchestrator is the main Claude Code session; the
30
+ #: operator is the human, and is never taken from an agent definition.
31
+ ORCHESTRATOR = "orchestrator"
32
+ OPERATOR = "operator"
33
+ CORE_ROLES: tuple[str, ...] = (ORCHESTRATOR, OPERATOR)
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Parent:
38
+ """How an item type names its parent: the front-matter field and the types allowed.
39
+
40
+ ``label`` titles the parent column in the ledger (default: the field name).
41
+ ``required`` refuses to create the item without one.
42
+ """
43
+
44
+ field: str
45
+ types: tuple[str, ...]
46
+ required: bool = False
47
+ label: str = ""
48
+
49
+ @property
50
+ def title(self) -> str:
51
+ return self.label or self.field.replace("_", " ").capitalize()
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ItemType:
56
+ """A kind of work item: its name, ID prefix and where its primary file lives.
57
+
58
+ ``path`` is relative to the state folder and contains ``{id}``. ``body`` is
59
+ the new file's text after the front-matter; ``{id}`` and ``{title}`` are
60
+ filled in.
61
+ """
62
+
63
+ name: str
64
+ prefix: str
65
+ path: str = "active/{id}/spec.md"
66
+ initial_state: str = "INTAKE"
67
+ body: str = "# {id} \u2014 {title}\n"
68
+ parent: Parent | None = None
69
+
70
+ def __post_init__(self) -> None:
71
+ if not _NAME.match(self.name):
72
+ raise ValueError(f"item type names are lowercase letters and digits: {self.name!r}")
73
+ if not _ITEM_PREFIX.match(self.prefix):
74
+ raise ValueError(f"item prefixes are uppercase letters: {self.prefix!r}")
75
+ parts = self.path.split("/")
76
+ if "{id}" not in self.path or self.path.startswith("/") or ".." in parts:
77
+ raise ValueError(f"item path must be relative and contain {{id}}: {self.path!r}")
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class GateKind:
82
+ """A kind of operator decision, with the rulings it can take.
83
+
84
+ ``project`` gates are not on an item. ``item_types`` limits which items the
85
+ gate can be opened on (empty: any). ``passing`` lists the rulings that
86
+ satisfy a plain ``gate:KIND`` condition. The other tuples name rulings that
87
+ need a ``note``, a ``review_by`` date (after today), or a ``party`` (who the
88
+ risk is shared with or transferred to). ``revise_targets``, when set, must
89
+ be given with ``revise``.
90
+ """
91
+
92
+ name: str
93
+ rulings: tuple[str, ...]
94
+ project: bool = False
95
+ item_types: tuple[str, ...] = ()
96
+ passing: tuple[str, ...] = ("accept",)
97
+ revise_targets: tuple[str, ...] = ()
98
+ note_required: tuple[str, ...] = ()
99
+ review_required: tuple[str, ...] = ()
100
+ party_required: tuple[str, ...] = ()
101
+
102
+ def __post_init__(self) -> None:
103
+ if not _GATE_KIND.match(self.name):
104
+ raise ValueError(f"gate kinds are upper-case: {self.name!r}")
105
+ if not self.rulings or not all(_RULING.match(r) for r in self.rulings):
106
+ raise ValueError(f"{self.name}: rulings are lower-case words joined by _")
107
+ for label, names in (
108
+ ("passing", self.passing),
109
+ ("note_required", self.note_required),
110
+ ("review_required", self.review_required),
111
+ ("party_required", self.party_required),
112
+ ):
113
+ unknown = sorted(set(names) - set(self.rulings))
114
+ if unknown:
115
+ raise ValueError(f"{self.name}: {label} names unknown rulings {unknown}")
116
+ if self.revise_targets and "revise" not in self.rulings:
117
+ raise ValueError(f"{self.name}: revise targets without a revise ruling")
118
+
119
+
120
+ ANY_ROLE = "*"
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class Migration:
125
+ """Upgrade one record of ``kind`` from ``from_version`` to ``from_version + 1``.
126
+
127
+ ``kind`` is ``events``, ``front_matter`` or ``config``. ``apply`` gets a copy
128
+ of the record and returns the upgraded record; the version key is set for
129
+ it. An event's ``id``, ``ts`` and ``prev`` are kept whatever it returns.
130
+ """
131
+
132
+ kind: str
133
+ from_version: int
134
+ apply: Callable[[dict[str, Any]], dict[str, Any]]
135
+ summary: str
136
+
137
+
138
+ def _lessons_became_insights(event: dict[str, Any]) -> dict[str, Any]:
139
+ """Events v1 → v2: the core's ``lesson`` record is now an ``insight``."""
140
+ if event.get("type") != "lesson":
141
+ return event
142
+ data = dict(event.get("data") or {})
143
+ old = data.pop("lesson_id", None)
144
+ if isinstance(old, str):
145
+ data["insight_id"] = old.replace("LESSON-", "INSIGHT-", 1)
146
+ return {**event, "type": "insight", "data": data}
147
+
148
+
149
+ def _forge_became_publish(config: dict[str, Any]) -> dict[str, Any]:
150
+ """Config v1 → v2: the ``forge`` section is now ``publish``.
151
+
152
+ It says where the team's work is published (a git host, an LMS), not which
153
+ git host the project uses.
154
+ """
155
+ if "forge" not in config:
156
+ return config
157
+ if "publish" in config:
158
+ raise ForgeError(
159
+ ExitCode.DATA,
160
+ "config_conflict",
161
+ "config.yaml has both forge and publish; keep publish and remove forge",
162
+ )
163
+ out = {k: v for k, v in config.items() if k != "forge"}
164
+ out["publish"] = config["forge"]
165
+ return out
166
+
167
+
168
+ #: Migrations the core itself needs, applied for every team.
169
+ CORE_MIGRATIONS = (
170
+ Migration("events", 1, _lessons_became_insights, "lessons became insights"),
171
+ Migration("config", 1, _forge_became_publish, "the forge section became publish"),
172
+ )
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class Wall:
177
+ """Something a role may not read or write (CONTRACT §9.1).
178
+
179
+ ``applies_to`` lists restricted roles; ``*`` means every agent role (team
180
+ roles, the orchestrator, and agents with no role), less ``exempt``. The
181
+ operator is never restricted. Path patterns are relative to the repository
182
+ root, or start with ``~/`` for the user's home; ``{state}`` is the state
183
+ folder, ``{item}`` an item ID, ``*`` one path segment and ``**`` any depth.
184
+ A pattern with ``{item}`` applies only while that item is in one of
185
+ ``while_states`` (if given). ``item_types`` are item types the restricted
186
+ roles may not write through the CLI.
187
+
188
+ A wall can also name content an item points at. ``about`` lists item types;
189
+ for each live item of those types (in ``while_states``, if given), patterns
190
+ may use ``{field:NAME}`` (the item's field), ``{parent}`` (its parent's ID)
191
+ and ``{parent.field:NAME}`` (its parent's field), and ``{item}`` is that
192
+ item's own ID. If a value is missing, or is not a plain relative path, the
193
+ pattern is skipped for that item: a missing value never widens a wall.
194
+ """
195
+
196
+ name: str
197
+ applies_to: tuple[str, ...]
198
+ exempt: tuple[str, ...] = ()
199
+ read: tuple[str, ...] = ()
200
+ write: tuple[str, ...] = ()
201
+ item_types: tuple[str, ...] = ()
202
+ while_states: tuple[str, ...] = ()
203
+ reason: str = ""
204
+ about: tuple[str, ...] = ()
205
+
206
+ def restricts(self, role: str | None) -> bool:
207
+ """Whether ``role`` (``None``: an agent with no role) is behind this wall."""
208
+ if role == OPERATOR or (role is not None and role in self.exempt):
209
+ return False
210
+ return ANY_ROLE in self.applies_to or (role is not None and role in self.applies_to)
211
+
212
+
213
+ PLACEHOLDER = re.compile(r"\{([^{}]*)\}")
214
+ _FIELD_REF = re.compile(r"^(parent\.)?field:([a-z][a-z0-9_]*)$")
215
+
216
+
217
+ def placeholders(pattern: str) -> list[str]:
218
+ """The ``{…}`` names in a wall pattern, in order."""
219
+ return PLACEHOLDER.findall(pattern)
220
+
221
+
222
+ def field_ref(name: str) -> tuple[bool, str] | None:
223
+ """``(of_parent, field)`` for ``field:X`` or ``parent.field:X``; else ``None``."""
224
+ match = _FIELD_REF.match(name)
225
+ return (bool(match.group(1)), match.group(2)) if match else None
226
+
227
+
228
+ def names_item(pattern: str) -> bool:
229
+ """Whether a pattern is expanded per item (``about``), not matched as is."""
230
+ return any(name == "parent" or field_ref(name) for name in placeholders(pattern))
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class MessageRule:
235
+ """Who may message whom, and in which kinds (empty: every kind).
236
+
237
+ ``*`` in ``sources`` or ``targets`` means any team role.
238
+ """
239
+
240
+ sources: tuple[str, ...]
241
+ targets: tuple[str, ...]
242
+ kinds: tuple[str, ...] = ()
243
+
244
+ def allows(self, sender: str, to: str, kind: str) -> bool:
245
+ return (
246
+ (sender in self.sources or ANY_ROLE in self.sources)
247
+ and (to in self.targets or ANY_ROLE in self.targets)
248
+ and (not self.kinds or kind in self.kinds)
249
+ )
250
+
251
+
252
+ @dataclass(frozen=True)
253
+ class Domain:
254
+ """A domain plugin's identity and its additions to the core.
255
+
256
+ Everything a domain adds is additive: it cannot remove or loosen core rules.
257
+ """
258
+
259
+ name: str
260
+ title: str
261
+ state_dir: str
262
+ env_prefix: str
263
+ event_types: tuple[str, ...] = ()
264
+ roles: tuple[str, ...] = ()
265
+ item_types: tuple[ItemType, ...] = ()
266
+ item_schema: Mapping[str, Field] = field(default_factory=lambda: MappingProxyType({}))
267
+ workflows: Mapping[str, Workflow] = field(default_factory=lambda: MappingProxyType({}))
268
+ checks: Mapping[str, Check] = field(default_factory=lambda: MappingProxyType({}))
269
+ gate_kinds: tuple[GateKind, ...] = ()
270
+ desk_only: tuple[str, ...] = ()
271
+ desk_only_item_types: tuple[str, ...] = ()
272
+ severities: tuple[str, ...] = ("critical", "high", "medium", "low")
273
+ finding_sources: tuple[str, ...] = ()
274
+ no_accept_sources: tuple[str, ...] = ()
275
+ message_rules: tuple[MessageRule, ...] = ()
276
+ walls: tuple[Wall, ...] = ()
277
+ archivers: tuple[str, ...] = () # team roles that may archive, beside the core roles
278
+ migrations: tuple[Migration, ...] = ()
279
+ config_schema: Mapping[str, Field] = field(default_factory=lambda: MappingProxyType({}))
280
+ default_config: str = ""
281
+
282
+ def __post_init__(self) -> None:
283
+ if not _NAME.match(self.name):
284
+ raise ValueError(f"domain name must be lowercase letters and digits: {self.name!r}")
285
+ if not _PREFIX.match(self.env_prefix):
286
+ raise ValueError(
287
+ f"env_prefix must be uppercase letters and digits: {self.env_prefix!r}"
288
+ )
289
+ if not self.state_dir.startswith(".") or "/" in self.state_dir:
290
+ raise ValueError(f"state_dir must be a hidden directory name: {self.state_dir!r}")
291
+ for event_type in self.event_types:
292
+ if not _EVENT_TYPE.match(event_type):
293
+ raise ValueError(f"invalid event type name: {event_type!r}")
294
+ for role in self.roles:
295
+ if not _ROLE.match(role):
296
+ raise ValueError(f"role names are lowercase words joined by hyphens: {role!r}")
297
+ if role in CORE_ROLES:
298
+ raise ValueError(f"{role!r} is a core role; domains do not redeclare it")
299
+ if len(set(self.roles)) != len(self.roles):
300
+ raise ValueError("duplicate role name")
301
+ names = [t.name for t in self.item_types]
302
+ prefixes = [t.prefix for t in self.item_types]
303
+ if len(set(names)) != len(names) or len(set(prefixes)) != len(prefixes):
304
+ raise ValueError("item type names and prefixes must be unique")
305
+ taken = sorted({*names, *prefixes} & (RESERVED_TYPES | RESERVED_PREFIXES))
306
+ if taken:
307
+ raise ValueError(f"item types use names the core reserves: {', '.join(taken)}")
308
+ for item_type in self.item_types:
309
+ parent = item_type.parent
310
+ if parent is None:
311
+ continue
312
+ if parent.field not in self.item_schema:
313
+ raise ValueError(
314
+ f"{item_type.name}: parent field {parent.field!r} is not in item_schema"
315
+ )
316
+ unknown = sorted(set(parent.types) - set(names)) if parent.types else ["(none)"]
317
+ if unknown:
318
+ raise ValueError(
319
+ f"{item_type.name}: parent types not item types: {', '.join(unknown)}"
320
+ )
321
+ clash = sorted(set(self.item_schema) & set(CORE_FRONT_MATTER))
322
+ if clash:
323
+ raise ValueError(f"item schema redefines core front-matter keys: {', '.join(clash)}")
324
+ self._check_workflows()
325
+ self._check_gates()
326
+ self._check_findings()
327
+ self._check_messages()
328
+ self._check_walls()
329
+ unknown = sorted(set(self.archivers) - set(self.roles))
330
+ if unknown:
331
+ raise ValueError(f"archivers: not domain roles: {', '.join(unknown)}")
332
+ self._check_migrations()
333
+
334
+ @property
335
+ def all_migrations(self) -> tuple[Migration, ...]:
336
+ """The core's migrations, then the team's."""
337
+ return (*CORE_MIGRATIONS, *self.migrations)
338
+
339
+ def _check_migrations(self) -> None:
340
+ """Each kind's migrations form one unbroken chain ending at the current version."""
341
+ for kind in sorted({m.kind for m in self.migrations}):
342
+ if kind not in VERSIONED:
343
+ raise ValueError(f"migrations: unknown kind {kind!r}")
344
+ current = VERSIONED[kind][1]
345
+ steps = sorted(m.from_version for m in self.all_migrations if m.kind == kind)
346
+ if len(set(steps)) != len(steps):
347
+ raise ValueError(f"migrations: two {kind} migrations from the same version")
348
+ if steps != list(range(steps[0], current)) or steps[0] < 0:
349
+ raise ValueError(
350
+ f"migrations: {kind} steps {steps} must run unbroken up to {current}"
351
+ )
352
+
353
+ def migration(self, kind: str, from_version: int) -> Migration | None:
354
+ return next(
355
+ (m for m in self.all_migrations if m.kind == kind and m.from_version == from_version),
356
+ None,
357
+ )
358
+
359
+ @property
360
+ def team_wall(self) -> Wall:
361
+ """The core's wall: a team's state belongs to its own roles and the operator."""
362
+ return Wall(
363
+ TEAM_WALL,
364
+ (ANY_ROLE,),
365
+ exempt=tuple(self.all_roles),
366
+ read=("{state}/**",),
367
+ write=("{state}/**",),
368
+ reason=f"{self.state_dir}/ belongs to {self.title}'s own roles",
369
+ )
370
+
371
+ @property
372
+ def all_walls(self) -> tuple[Wall, ...]:
373
+ """The core's team wall, then the team's own walls."""
374
+ return (self.team_wall, *self.walls)
375
+
376
+ def _check_walls(self) -> None:
377
+ names = [w.name for w in self.walls]
378
+ if len(set(names)) != len(names):
379
+ raise ValueError("duplicate wall name")
380
+ if TEAM_WALL in names:
381
+ raise ValueError(f"wall name {TEAM_WALL!r} is the core's")
382
+ known = {*self.all_roles, ANY_ROLE}
383
+ types = {t.name for t in self.item_types}
384
+ for wall in self.walls:
385
+ unknown = sorted(set((*wall.applies_to, *wall.exempt)) - known)
386
+ if unknown or not wall.applies_to:
387
+ raise ValueError(f"wall {wall.name}: unknown roles {', '.join(unknown)}")
388
+ if not (wall.read or wall.write or wall.item_types):
389
+ raise ValueError(f"wall {wall.name} denies nothing")
390
+ bad_types = sorted(set(wall.item_types) - types)
391
+ if bad_types:
392
+ raise ValueError(f"wall {wall.name}: unknown item types {', '.join(bad_types)}")
393
+ bad_about = sorted(set(wall.about) - types)
394
+ if bad_about:
395
+ raise ValueError(f"wall {wall.name}: unknown item types {', '.join(bad_about)}")
396
+ for pattern in (*wall.read, *wall.write):
397
+ if pattern.startswith("/") or ".." in pattern.split("/"):
398
+ raise ValueError(f"wall {wall.name}: {pattern!r} must be relative or ~/")
399
+ self._check_placeholders(wall, pattern)
400
+
401
+ def _check_placeholders(self, wall: Wall, pattern: str) -> None:
402
+ for name in placeholders(pattern):
403
+ ref = field_ref(name)
404
+ if name in ("state", "item"):
405
+ continue
406
+ if name != "parent" and ref is None:
407
+ raise ValueError(f"wall {wall.name}: unknown placeholder {{{name}}} in {pattern!r}")
408
+ if not wall.about:
409
+ raise ValueError(f"wall {wall.name}: {{{name}}} needs the item types in about")
410
+ if ref is not None and ref[1] not in self.item_schema:
411
+ raise ValueError(f"wall {wall.name}: no field {ref[1]!r} in the item schema")
412
+ if name == "parent" or (ref is not None and ref[0]):
413
+ orphans = [t for t in wall.about if self.item_type(t).parent is None]
414
+ if orphans:
415
+ raise ValueError(
416
+ f"wall {wall.name}: {{{name}}} but {', '.join(orphans)} has no parent"
417
+ )
418
+
419
+ def _check_messages(self) -> None:
420
+ known = {*self.roles, ANY_ROLE}
421
+ for rule in self.message_rules:
422
+ unknown = sorted(set((*rule.sources, *rule.targets)) - known)
423
+ if unknown or not rule.sources or not rule.targets:
424
+ raise ValueError(f"message rule names unknown roles: {', '.join(unknown)}")
425
+
426
+ def check_pairs_remove(self, entries: tuple[str, ...] | list[str]) -> None:
427
+ """Every entry is ``from>to`` for a pair some rule allows."""
428
+ for entry in entries:
429
+ sender, sep, to = entry.partition(">")
430
+ if (
431
+ not sep
432
+ or sender == to
433
+ or not any(
434
+ (sender in r.sources or ANY_ROLE in r.sources)
435
+ and (to in r.targets or ANY_ROLE in r.targets)
436
+ for r in self.message_rules
437
+ )
438
+ or sender not in self.roles
439
+ or to not in self.roles
440
+ ):
441
+ raise ValueError(f"pairs_remove entry {entry!r} is not an allowed from>to pair")
442
+
443
+ def _check_findings(self) -> None:
444
+ if not self.severities or len(set(self.severities)) != len(self.severities):
445
+ raise ValueError("severities must be a non-empty list of distinct names")
446
+ unknown = sorted(set(self.finding_sources) - set(self.roles))
447
+ if unknown:
448
+ raise ValueError(f"finding_sources: not domain roles: {', '.join(unknown)}")
449
+ extra = sorted(set(self.no_accept_sources) - set(self.finding_sources))
450
+ if extra:
451
+ raise ValueError(f"no_accept_sources: not finding sources: {', '.join(extra)}")
452
+
453
+ def _check_gates(self) -> None:
454
+ names = [k.name for k in self.gate_kinds]
455
+ if len(set(names)) != len(names):
456
+ raise ValueError("duplicate gate kind")
457
+ types = {t.name for t in self.item_types}
458
+ unknown_desk = sorted(set(self.desk_only_item_types) - types)
459
+ if unknown_desk:
460
+ raise ValueError(f"desk_only_item_types: unknown item types {', '.join(unknown_desk)}")
461
+ for kind in self.gate_kinds:
462
+ unknown = sorted(set(kind.item_types) - types)
463
+ if unknown:
464
+ raise ValueError(f"{kind.name}: unknown item types {', '.join(unknown)}")
465
+ self.check_desk_only(self.desk_only)
466
+ if self.gate_kinds:
467
+ checks = self.all_checks
468
+ for wf in self.workflows.values():
469
+ for cond in wf.all_conditions():
470
+ if checks[cond.name].is_gate and gate_kind_of(cond) not in names:
471
+ raise ValueError(f"{wf.type}: {cond} names no gate kind")
472
+
473
+ def gate_kind(self, name: str) -> GateKind | None:
474
+ """The gate kind called ``name``, if the domain declares it."""
475
+ return next((k for k in self.gate_kinds if k.name == name), None)
476
+
477
+ def check_desk_only(self, entries: tuple[str, ...] | list[str]) -> None:
478
+ """Every entry is ``KIND`` or ``KIND-<severity>`` for a declared kind."""
479
+ names = {k.name for k in self.gate_kinds}
480
+ for entry in entries:
481
+ kind = entry if entry in names else entry.rsplit("-", 1)[0]
482
+ if kind not in names or (kind != entry and not entry[len(kind) + 1 :]):
483
+ raise ValueError(f"desk_only entry {entry!r} is not a gate kind or KIND-severity")
484
+
485
+ def _check_workflows(self) -> None:
486
+ reused = sorted(set(self.checks) & set(BUILTIN_CHECKS))
487
+ if reused:
488
+ raise ValueError(f"checks reuse built-in names: {', '.join(reused)}")
489
+ if not self.workflows:
490
+ return
491
+ types = {t.name: t for t in self.item_types}
492
+ if set(self.workflows) != set(types):
493
+ raise ValueError("every item type needs exactly one workflow")
494
+ checks = self.all_checks
495
+ for name, wf in self.workflows.items():
496
+ if wf.initial != types[name].initial_state:
497
+ raise ValueError(
498
+ f"{name}: workflow starts at {wf.initial} but the item type at "
499
+ f"{types[name].initial_state}"
500
+ )
501
+ for t in wf.transitions:
502
+ for cond in t.requires:
503
+ if cond.name not in checks:
504
+ raise ValueError(f"{name}: unknown check {cond.name!r}")
505
+ try:
506
+ checks[cond.name].validate(cond.arg, self)
507
+ except ValueError as exc:
508
+ raise ValueError(f"{name}: {cond}: {exc}") from exc
509
+
510
+ @property
511
+ def all_checks(self) -> Mapping[str, Check]:
512
+ """Built-in checks plus the domain's."""
513
+ return {**BUILTIN_CHECKS, **self.checks}
514
+
515
+ @property
516
+ def parent_fields(self) -> tuple[str, ...]:
517
+ """The front-matter fields that name a parent, in item-type order, without repeats."""
518
+ return tuple(dict.fromkeys(t.parent.field for t in self.item_types if t.parent))
519
+
520
+ @property
521
+ def parent_title(self) -> str:
522
+ """The ledger's parent column title: one shared label, or "Parent"."""
523
+ titles = {t.parent.title for t in self.item_types if t.parent}
524
+ return titles.pop() if len(titles) == 1 else "Parent"
525
+
526
+ def parent_id(self, type_name: str, fields: Mapping[str, Any]) -> str | None:
527
+ """The parent an item of ``type_name`` with ``fields`` names, if its type has one."""
528
+ try:
529
+ parent = self.item_type(type_name).parent
530
+ except KeyError:
531
+ return None
532
+ value = fields.get(parent.field) if parent else None
533
+ return value if isinstance(value, str) and value else None
534
+
535
+ def item_type(self, name: str) -> ItemType:
536
+ """The item type called ``name``; ``KeyError`` if there is none."""
537
+ for item_type in self.item_types:
538
+ if item_type.name == name:
539
+ return item_type
540
+ raise KeyError(name)
541
+
542
+ @property
543
+ def all_roles(self) -> tuple[str, ...]:
544
+ """Core roles followed by the domain's own."""
545
+ return CORE_ROLES + self.roles
546
+
547
+ def env(self, suffix: str) -> str:
548
+ """The name of a domain environment variable, e.g. ``CODERSFORGE_ROLE``."""
549
+ return f"{self.env_prefix}_{suffix}"
teaimforge/errors.py ADDED
@@ -0,0 +1,36 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Exit codes and the error type every command raises (core contract)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from enum import IntEnum
7
+
8
+
9
+ class ExitCode(IntEnum):
10
+ """Process exit codes. Stable across every domain."""
11
+
12
+ OK = 0
13
+ USAGE = 1
14
+ REFUSED = 2
15
+ NOT_FOUND = 3
16
+ CONFLICT = 4
17
+ DATA = 5
18
+ INTERNAL = 10
19
+
20
+
21
+ class ForgeError(Exception):
22
+ """An error that ends a command with a specific exit code.
23
+
24
+ ``reason`` is a short, stable, machine-readable word (for example
25
+ ``missing_identity``); ``detail`` is a human-readable sentence.
26
+ """
27
+
28
+ def __init__(self, code: ExitCode, reason: str, detail: str) -> None:
29
+ super().__init__(detail)
30
+ self.code = code
31
+ self.reason = reason
32
+ self.detail = detail
33
+
34
+ def envelope(self) -> dict[str, dict[str, int | str]]:
35
+ """The ``--json`` error document (core contract)."""
36
+ return {"error": {"code": int(self.code), "reason": self.reason, "detail": self.detail}}