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,194 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""The ledger: readable views generated from the log.
|
|
3
|
+
|
|
4
|
+
``LEDGER.md`` shows what needs the operator, what is in progress, planned,
|
|
5
|
+
parked, done and abandoned. ``lessons/LESSONS.md`` lists every lesson by tag.
|
|
6
|
+
Both are generated, never edited: the same log always produces the same bytes
|
|
7
|
+
(nothing in them depends on the clock), so a check regenerates them in memory
|
|
8
|
+
and compares.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from .domain import Domain
|
|
19
|
+
from .gates import Gate, fold_gates
|
|
20
|
+
from .index import replay
|
|
21
|
+
from .items import Item, _write_atomic
|
|
22
|
+
from .lessons import Lesson, fold_lessons
|
|
23
|
+
from .paths import Layout
|
|
24
|
+
from .workflow import ABANDONED, PARKED
|
|
25
|
+
|
|
26
|
+
LEDGER_FILE = "LEDGER.md"
|
|
27
|
+
LESSONS_FILE = "lessons/LESSONS.md"
|
|
28
|
+
_DASH = " \u2014 "
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _cell(text: object) -> str:
|
|
32
|
+
"""Text safe inside a Markdown table cell."""
|
|
33
|
+
return str(text if text is not None else "").replace("|", "\\|").replace("\n", " ")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _table(header: Sequence[str], rows: Sequence[Sequence[object]]) -> list[str]:
|
|
37
|
+
lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
|
|
38
|
+
lines.extend("| " + " | ".join(_cell(c) for c in row) + " |" for row in rows)
|
|
39
|
+
return lines
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Ledger:
|
|
44
|
+
"""The generated files for one project."""
|
|
45
|
+
|
|
46
|
+
layout: Layout
|
|
47
|
+
domain: Domain
|
|
48
|
+
project: str
|
|
49
|
+
|
|
50
|
+
def paths(self) -> dict[str, Path]:
|
|
51
|
+
return {
|
|
52
|
+
LEDGER_FILE: self.layout.state / LEDGER_FILE,
|
|
53
|
+
LESSONS_FILE: self.layout.state / LESSONS_FILE,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
def render(self, events: Iterable[Mapping[str, Any]]) -> dict[str, str]:
|
|
57
|
+
"""Both files' text, from the log."""
|
|
58
|
+
log = list(events)
|
|
59
|
+
items = list(replay(log, self.domain))
|
|
60
|
+
gates = [g for g in fold_gates(log).values() if g.is_open]
|
|
61
|
+
lessons = list(fold_lessons(log).values())
|
|
62
|
+
return {
|
|
63
|
+
LEDGER_FILE: self._ledger(items, gates),
|
|
64
|
+
LESSONS_FILE: self._lessons(lessons),
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
def stale(self, events: Iterable[Mapping[str, Any]]) -> list[str]:
|
|
68
|
+
"""The generated files that are missing or differ from what the log says."""
|
|
69
|
+
wanted = self.render(events)
|
|
70
|
+
paths = self.paths()
|
|
71
|
+
return [
|
|
72
|
+
name
|
|
73
|
+
for name, text in wanted.items()
|
|
74
|
+
if not paths[name].is_file() or paths[name].read_text(encoding="utf-8") != text
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
def write(self, events: Iterable[Mapping[str, Any]]) -> list[str]:
|
|
78
|
+
"""Regenerate both files. Returns the ones that changed."""
|
|
79
|
+
wanted = self.render(events)
|
|
80
|
+
changed = []
|
|
81
|
+
for name, path in self.paths().items():
|
|
82
|
+
if not path.is_file() or path.read_text(encoding="utf-8") != wanted[name]:
|
|
83
|
+
_write_atomic(path, wanted[name])
|
|
84
|
+
changed.append(name)
|
|
85
|
+
return changed
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------ LEDGER.md
|
|
88
|
+
|
|
89
|
+
def _group(self, item: Item) -> str:
|
|
90
|
+
if item.archived:
|
|
91
|
+
return "archived"
|
|
92
|
+
if item.state == PARKED:
|
|
93
|
+
return "parked"
|
|
94
|
+
if item.state == ABANDONED:
|
|
95
|
+
return "abandoned"
|
|
96
|
+
workflow = self.domain.workflows.get(item.type)
|
|
97
|
+
if workflow is None:
|
|
98
|
+
return "progress"
|
|
99
|
+
if not workflow.is_open(item.state):
|
|
100
|
+
return "done"
|
|
101
|
+
return "planned" if item.state == workflow.initial else "progress"
|
|
102
|
+
|
|
103
|
+
def _ledger(self, items: Sequence[Item], gates: Sequence[Gate]) -> str:
|
|
104
|
+
titles = {i.id: i.title for i in items}
|
|
105
|
+
lines = [
|
|
106
|
+
f"# {self.domain.title} ledger \u2014 {self.project}",
|
|
107
|
+
"",
|
|
108
|
+
f"Generated from the event log by `{self.domain.name} ledger`. "
|
|
109
|
+
"Do not edit: changes are overwritten.",
|
|
110
|
+
"",
|
|
111
|
+
f"## Needs you ({len(gates)})",
|
|
112
|
+
"",
|
|
113
|
+
]
|
|
114
|
+
if gates:
|
|
115
|
+
for gate in gates:
|
|
116
|
+
on = (
|
|
117
|
+
f"{_DASH}on {gate.item}{_DASH}{titles.get(gate.item, '?')}" if gate.item else ""
|
|
118
|
+
)
|
|
119
|
+
desk = " (desk-only)" if gate.desk_only else ""
|
|
120
|
+
lines.append(f"- {gate.id}{_DASH}{gate.summary}{on}{desk}")
|
|
121
|
+
else:
|
|
122
|
+
lines.append("Nothing is waiting for a decision.")
|
|
123
|
+
groups: dict[str, list[Item]] = {
|
|
124
|
+
k: [] for k in ("progress", "planned", "parked", "done", "abandoned")
|
|
125
|
+
}
|
|
126
|
+
archived = 0
|
|
127
|
+
for item in items:
|
|
128
|
+
group = self._group(item)
|
|
129
|
+
if group == "archived":
|
|
130
|
+
archived += 1
|
|
131
|
+
else:
|
|
132
|
+
groups[group].append(item)
|
|
133
|
+
headings = {
|
|
134
|
+
"progress": "In progress",
|
|
135
|
+
"planned": "Planned",
|
|
136
|
+
"parked": "Parked",
|
|
137
|
+
"done": "Done",
|
|
138
|
+
"abandoned": "Abandoned",
|
|
139
|
+
}
|
|
140
|
+
for key, heading in headings.items():
|
|
141
|
+
rows = groups[key]
|
|
142
|
+
lines += ["", f"## {heading} ({len(rows)})", ""]
|
|
143
|
+
if not rows:
|
|
144
|
+
lines.append("None.")
|
|
145
|
+
continue
|
|
146
|
+
lines += _table(
|
|
147
|
+
("ID", "Title", "Type", "State", "Epic", "Assigned"),
|
|
148
|
+
[
|
|
149
|
+
(
|
|
150
|
+
i.id,
|
|
151
|
+
i.title,
|
|
152
|
+
i.type,
|
|
153
|
+
i.state,
|
|
154
|
+
i.fields.get("epic") or "",
|
|
155
|
+
i.assignee or "",
|
|
156
|
+
)
|
|
157
|
+
for i in rows
|
|
158
|
+
],
|
|
159
|
+
)
|
|
160
|
+
lines += ["", f"## Archived ({archived})", ""]
|
|
161
|
+
lines.append(
|
|
162
|
+
f"{archived} rolled up under `archive/`; `{self.domain.name} show <ID>` describes one."
|
|
163
|
+
if archived
|
|
164
|
+
else "None."
|
|
165
|
+
)
|
|
166
|
+
return "\n".join(lines) + "\n"
|
|
167
|
+
|
|
168
|
+
# ------------------------------------------------------------ LESSONS.md
|
|
169
|
+
|
|
170
|
+
def _lessons(self, lessons: Sequence[Lesson]) -> str:
|
|
171
|
+
lines = [
|
|
172
|
+
f"# Lessons \u2014 {self.project}",
|
|
173
|
+
"",
|
|
174
|
+
f"Generated from the event log by `{self.domain.name} ledger`. "
|
|
175
|
+
"Do not edit: record lessons with `lesson add`.",
|
|
176
|
+
"",
|
|
177
|
+
]
|
|
178
|
+
if not lessons:
|
|
179
|
+
lines.append("No lessons yet.")
|
|
180
|
+
return "\n".join(lines) + "\n"
|
|
181
|
+
lines += _table(
|
|
182
|
+
("ID", "Lesson", "Tags", "From", "By"),
|
|
183
|
+
[
|
|
184
|
+
(x.id, x.summary, ", ".join(x.tags), x.from_item or "", x.actor)
|
|
185
|
+
for x in sorted(lessons, key=lambda x: x.id)
|
|
186
|
+
],
|
|
187
|
+
)
|
|
188
|
+
tags = sorted({t for x in lessons for t in x.tags})
|
|
189
|
+
if tags:
|
|
190
|
+
lines += ["", "## By tag", ""]
|
|
191
|
+
for tag in tags:
|
|
192
|
+
ids = ", ".join(x.id for x in sorted(lessons, key=lambda x: x.id) if tag in x.tags)
|
|
193
|
+
lines.append(f"- **{tag}**: {ids}")
|
|
194
|
+
return "\n".join(lines) + "\n"
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Lessons: what the team learned, tagged so later work can load it.
|
|
3
|
+
|
|
4
|
+
Any role can record a lesson. Lesson IDs are ``LESSON-<NNNN>``, allocated one
|
|
5
|
+
past the highest ever recorded and never reused. A lesson may name the item it
|
|
6
|
+
came from; its tags are how context loading finds it later.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .domain import Domain
|
|
17
|
+
from .errors import ExitCode, ForgeError
|
|
18
|
+
from .events import EventStore
|
|
19
|
+
from .identity import Identity
|
|
20
|
+
from .items import fold, format_id, parse_id
|
|
21
|
+
from .paths import Layout
|
|
22
|
+
|
|
23
|
+
PREFIX = "LESSON"
|
|
24
|
+
MAX_SUMMARY = 500
|
|
25
|
+
MAX_TAGS = 10
|
|
26
|
+
|
|
27
|
+
_TAG = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
|
28
|
+
_LESSON_ID = re.compile(r"^LESSON-(\d{4,})$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Lesson:
|
|
33
|
+
"""A lesson as the log describes it."""
|
|
34
|
+
|
|
35
|
+
id: str
|
|
36
|
+
summary: str
|
|
37
|
+
tags: tuple[str, ...]
|
|
38
|
+
actor: str
|
|
39
|
+
recorded: str
|
|
40
|
+
from_item: str | None = None
|
|
41
|
+
|
|
42
|
+
def label(self) -> str:
|
|
43
|
+
return f"{self.id} — {self.summary}"
|
|
44
|
+
|
|
45
|
+
def as_dict(self) -> dict[str, Any]:
|
|
46
|
+
return {
|
|
47
|
+
"id": self.id,
|
|
48
|
+
"summary": self.summary,
|
|
49
|
+
"tags": list(self.tags),
|
|
50
|
+
"actor": self.actor,
|
|
51
|
+
"recorded": self.recorded,
|
|
52
|
+
"from_item": self.from_item,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def fold_lessons(events: Iterable[Mapping[str, Any]]) -> dict[str, Lesson]:
|
|
57
|
+
"""Every lesson, from the log."""
|
|
58
|
+
lessons: dict[str, Lesson] = {}
|
|
59
|
+
for event in events:
|
|
60
|
+
data = event.get("data", {})
|
|
61
|
+
if event["type"] == "lesson" and isinstance(data.get("lesson_id"), str):
|
|
62
|
+
lessons[data["lesson_id"]] = Lesson(
|
|
63
|
+
id=data["lesson_id"],
|
|
64
|
+
summary=data.get("summary", ""),
|
|
65
|
+
tags=tuple(data.get("tags", [])),
|
|
66
|
+
actor=event["actor"],
|
|
67
|
+
recorded=event["ts"],
|
|
68
|
+
from_item=data.get("from_item"),
|
|
69
|
+
)
|
|
70
|
+
return lessons
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _next_id(lessons: Iterable[str]) -> str:
|
|
74
|
+
numbers = [int(m.group(1)) for i in lessons if (m := _LESSON_ID.match(i))]
|
|
75
|
+
return format_id(PREFIX, max(numbers, default=0) + 1)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def check_tags(tags: Sequence[str]) -> tuple[str, ...]:
|
|
79
|
+
"""Lower-case words joined by hyphens, at most 40 characters, at most 10 tags."""
|
|
80
|
+
clean = tuple(dict.fromkeys(t.strip().lower() for t in tags if t.strip()))
|
|
81
|
+
bad = [t for t in clean if not _TAG.match(t)]
|
|
82
|
+
if bad or len(clean) > MAX_TAGS:
|
|
83
|
+
raise ForgeError(
|
|
84
|
+
ExitCode.USAGE,
|
|
85
|
+
"invalid_tag",
|
|
86
|
+
f"tags are lower-case words joined by hyphens, at most {MAX_TAGS}; "
|
|
87
|
+
f"bad: {', '.join(bad) or 'too many'}",
|
|
88
|
+
)
|
|
89
|
+
return clean
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class Lessons:
|
|
94
|
+
"""Record lessons as one pinned identity."""
|
|
95
|
+
|
|
96
|
+
layout: Layout
|
|
97
|
+
domain: Domain
|
|
98
|
+
identity: Identity | None = None
|
|
99
|
+
store: EventStore = field(init=False)
|
|
100
|
+
|
|
101
|
+
def __post_init__(self) -> None:
|
|
102
|
+
self.store = EventStore(self.layout, self.domain)
|
|
103
|
+
|
|
104
|
+
def all(self) -> dict[str, Lesson]:
|
|
105
|
+
return fold_lessons(self.store.events())
|
|
106
|
+
|
|
107
|
+
def add(
|
|
108
|
+
self, summary: str, *, from_item: str | None = None, tags: Sequence[str] = ()
|
|
109
|
+
) -> Lesson:
|
|
110
|
+
"""Write ``lesson``."""
|
|
111
|
+
if self.identity is None:
|
|
112
|
+
raise ForgeError(ExitCode.INTERNAL, "no_identity", "lesson writes need an identity")
|
|
113
|
+
who = self.identity
|
|
114
|
+
text = summary.strip()
|
|
115
|
+
if not text or len(text) > MAX_SUMMARY:
|
|
116
|
+
raise ForgeError(
|
|
117
|
+
ExitCode.USAGE, "invalid_summary", f"a summary is 1-{MAX_SUMMARY} characters"
|
|
118
|
+
)
|
|
119
|
+
clean = check_tags(tags)
|
|
120
|
+
if from_item is not None:
|
|
121
|
+
parse_id(from_item)
|
|
122
|
+
with self.store.transaction() as tx:
|
|
123
|
+
events = list(tx.events())
|
|
124
|
+
title = None
|
|
125
|
+
if from_item is not None:
|
|
126
|
+
item = fold(events, self.domain).get(from_item)
|
|
127
|
+
if item is None:
|
|
128
|
+
raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {from_item}")
|
|
129
|
+
title = item.title
|
|
130
|
+
lesson_id = _next_id(fold_lessons(events))
|
|
131
|
+
data: dict[str, Any] = {"lesson_id": lesson_id, "tags": list(clean), "summary": text}
|
|
132
|
+
if from_item is not None:
|
|
133
|
+
data["from_item"] = from_item
|
|
134
|
+
event = tx.append(
|
|
135
|
+
"lesson",
|
|
136
|
+
actor=who.role,
|
|
137
|
+
session=who.session,
|
|
138
|
+
data=data,
|
|
139
|
+
item=from_item,
|
|
140
|
+
title=title,
|
|
141
|
+
)
|
|
142
|
+
return Lesson(lesson_id, text, clean, who.role, event["ts"], from_item)
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Messages between roles, relayed by the orchestrator.
|
|
3
|
+
|
|
4
|
+
No role addresses another directly. The orchestrator records each message it
|
|
5
|
+
relays with ``send``, naming the role it came from and the role it goes to.
|
|
6
|
+
The domain's rules say which pairs may talk and in which kinds; a project can
|
|
7
|
+
remove pairs (``messaging.pairs_remove``) but never add one. A message to a
|
|
8
|
+
pair that is not allowed is still recorded, as ``blocked`` with reason
|
|
9
|
+
``pair_denied``, so the attempt is on the log.
|
|
10
|
+
|
|
11
|
+
After ``sent``, a message is ``delivered`` by the orchestrator, then ``acked``
|
|
12
|
+
or ``snoozed`` by its recipient. A snoozed message is delivered again once its
|
|
13
|
+
``until`` time passes.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections.abc import Iterable, Mapping
|
|
19
|
+
from dataclasses import dataclass, replace
|
|
20
|
+
from datetime import UTC, datetime
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from .domain import ORCHESTRATOR, Domain
|
|
24
|
+
from .errors import ExitCode, ForgeError
|
|
25
|
+
from .events import EventStore
|
|
26
|
+
from .identity import Identity
|
|
27
|
+
from .paths import Layout
|
|
28
|
+
from .ulid import is_ulid, new_ulid
|
|
29
|
+
|
|
30
|
+
KINDS = ("question", "answer", "finding", "proposal", "handoff")
|
|
31
|
+
PRIORITIES = ("urgent", "normal", "low")
|
|
32
|
+
STATES = ("delivered", "acked", "snoozed")
|
|
33
|
+
MAX_BODY = 8 * 1024 # bytes of UTF-8
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Message:
|
|
38
|
+
"""A message as the log describes it."""
|
|
39
|
+
|
|
40
|
+
id: str
|
|
41
|
+
sender: str
|
|
42
|
+
to: str
|
|
43
|
+
kind: str
|
|
44
|
+
priority: str
|
|
45
|
+
body: str
|
|
46
|
+
outcome: str
|
|
47
|
+
sent: str
|
|
48
|
+
state: str = "sent"
|
|
49
|
+
reply_to: str | None = None
|
|
50
|
+
reason: str | None = None
|
|
51
|
+
until: str | None = None
|
|
52
|
+
|
|
53
|
+
def label(self) -> str:
|
|
54
|
+
"""``msg_… — developer → architect — question``."""
|
|
55
|
+
return f"{self.id} — {self.sender} → {self.to} — {self.kind}"
|
|
56
|
+
|
|
57
|
+
def as_dict(self) -> dict[str, Any]:
|
|
58
|
+
return {
|
|
59
|
+
"id": self.id,
|
|
60
|
+
"from": self.sender,
|
|
61
|
+
"to": self.to,
|
|
62
|
+
"kind": self.kind,
|
|
63
|
+
"priority": self.priority,
|
|
64
|
+
"reply_to": self.reply_to,
|
|
65
|
+
"body": self.body,
|
|
66
|
+
"outcome": self.outcome,
|
|
67
|
+
"reason": self.reason,
|
|
68
|
+
"state": self.state,
|
|
69
|
+
"until": self.until,
|
|
70
|
+
"sent": self.sent,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def parse_msg_id(msg_id: str) -> str:
|
|
75
|
+
"""The ID itself; USAGE error if it is not ``msg_`` + ULID."""
|
|
76
|
+
if not (msg_id.startswith("msg_") and is_ulid(msg_id[4:])):
|
|
77
|
+
raise ForgeError(ExitCode.USAGE, "invalid_msg_id", f"{msg_id!r} is not a message ID")
|
|
78
|
+
return msg_id
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def fold_messages(events: Iterable[Mapping[str, Any]]) -> dict[str, Message]:
|
|
82
|
+
"""Every message and its current state, from the log."""
|
|
83
|
+
messages: dict[str, Message] = {}
|
|
84
|
+
for event in events:
|
|
85
|
+
data = event.get("data", {})
|
|
86
|
+
mid = data.get("msg_id")
|
|
87
|
+
if event["type"] == "msg" and isinstance(mid, str):
|
|
88
|
+
messages[mid] = Message(
|
|
89
|
+
id=mid,
|
|
90
|
+
sender=data.get("from", ""),
|
|
91
|
+
to=data.get("to", ""),
|
|
92
|
+
kind=data.get("kind", ""),
|
|
93
|
+
priority=data.get("priority", "normal"),
|
|
94
|
+
body=data.get("body", ""),
|
|
95
|
+
outcome=data.get("outcome", ""),
|
|
96
|
+
sent=event["ts"],
|
|
97
|
+
state="blocked" if data.get("outcome") == "blocked" else "sent",
|
|
98
|
+
reply_to=data.get("reply_to"),
|
|
99
|
+
reason=data.get("reason"),
|
|
100
|
+
)
|
|
101
|
+
elif event["type"] == "msg_state" and mid in messages:
|
|
102
|
+
messages[mid] = replace(
|
|
103
|
+
messages[mid], state=data.get("state", ""), until=data.get("until")
|
|
104
|
+
)
|
|
105
|
+
return messages
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def pair_allowed(
|
|
109
|
+
domain: Domain, sender: str, to: str, kind: str, removed: Iterable[str] = ()
|
|
110
|
+
) -> bool:
|
|
111
|
+
"""Whether the domain's rules let ``sender`` send ``kind`` to ``to``."""
|
|
112
|
+
if sender == to or sender not in domain.roles or to not in domain.roles:
|
|
113
|
+
return False
|
|
114
|
+
if f"{sender}>{to}" in set(removed):
|
|
115
|
+
return False
|
|
116
|
+
return any(rule.allows(sender, to, kind) for rule in domain.message_rules)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _until(text: str, now: datetime) -> str:
|
|
120
|
+
try:
|
|
121
|
+
when = datetime.fromisoformat(text)
|
|
122
|
+
except ValueError:
|
|
123
|
+
raise ForgeError(
|
|
124
|
+
ExitCode.USAGE, "invalid_until", f"--until {text!r} is not an ISO 8601 time"
|
|
125
|
+
) from None
|
|
126
|
+
if when.tzinfo is None:
|
|
127
|
+
raise ForgeError(
|
|
128
|
+
ExitCode.USAGE, "invalid_until", "--until needs a time zone, e.g. 2026-11-20T09:00Z"
|
|
129
|
+
)
|
|
130
|
+
if when <= now:
|
|
131
|
+
raise ForgeError(ExitCode.USAGE, "invalid_until", "--until must be in the future")
|
|
132
|
+
return when.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass
|
|
136
|
+
class Messages:
|
|
137
|
+
"""Relay messages and record their states as one pinned identity."""
|
|
138
|
+
|
|
139
|
+
layout: Layout
|
|
140
|
+
domain: Domain
|
|
141
|
+
identity: Identity | None = None
|
|
142
|
+
config: Mapping[str, Any] | None = None
|
|
143
|
+
|
|
144
|
+
def __post_init__(self) -> None:
|
|
145
|
+
self.store = EventStore(self.layout, self.domain)
|
|
146
|
+
|
|
147
|
+
def all(self) -> dict[str, Message]:
|
|
148
|
+
return fold_messages(self.store.events())
|
|
149
|
+
|
|
150
|
+
def _who(self) -> Identity:
|
|
151
|
+
if self.identity is None:
|
|
152
|
+
raise ForgeError(ExitCode.INTERNAL, "no_identity", "message writes need an identity")
|
|
153
|
+
return self.identity
|
|
154
|
+
|
|
155
|
+
def _removed(self) -> list[str]:
|
|
156
|
+
return list(((self.config or {}).get("messaging") or {}).get("pairs_remove") or [])
|
|
157
|
+
|
|
158
|
+
def send( # noqa: PLR0913 - the message's fields
|
|
159
|
+
self,
|
|
160
|
+
sender: str,
|
|
161
|
+
to: str,
|
|
162
|
+
kind: str,
|
|
163
|
+
body: str,
|
|
164
|
+
*,
|
|
165
|
+
priority: str = "normal",
|
|
166
|
+
reply_to: str | None = None,
|
|
167
|
+
) -> Message:
|
|
168
|
+
"""Write ``msg``. A denied pair is recorded as blocked and then refused (exit 2)."""
|
|
169
|
+
who = self._who()
|
|
170
|
+
if who.role != ORCHESTRATOR:
|
|
171
|
+
raise ForgeError(
|
|
172
|
+
ExitCode.REFUSED,
|
|
173
|
+
"orchestrator_only",
|
|
174
|
+
f"only the orchestrator relays messages; this call runs as {who.role}",
|
|
175
|
+
)
|
|
176
|
+
if sender not in self.domain.roles:
|
|
177
|
+
raise ForgeError(
|
|
178
|
+
ExitCode.USAGE,
|
|
179
|
+
"unknown_role",
|
|
180
|
+
f"--from {sender!r}: messages come from team roles "
|
|
181
|
+
f"({', '.join(self.domain.roles)})",
|
|
182
|
+
)
|
|
183
|
+
if to not in self.domain.all_roles:
|
|
184
|
+
raise ForgeError(ExitCode.USAGE, "unknown_role", f"--to {to!r} is not a role")
|
|
185
|
+
if kind not in KINDS or priority not in PRIORITIES:
|
|
186
|
+
raise ForgeError(
|
|
187
|
+
ExitCode.USAGE,
|
|
188
|
+
"invalid_message",
|
|
189
|
+
f"kind is one of {', '.join(KINDS)}; priority one of {', '.join(PRIORITIES)}",
|
|
190
|
+
)
|
|
191
|
+
text = body.strip()
|
|
192
|
+
if not text or len(text.encode("utf-8")) > MAX_BODY:
|
|
193
|
+
raise ForgeError(
|
|
194
|
+
ExitCode.USAGE,
|
|
195
|
+
"invalid_body",
|
|
196
|
+
f"a body is 1-{MAX_BODY} bytes; put larger content in a file and give its path",
|
|
197
|
+
)
|
|
198
|
+
if reply_to is not None:
|
|
199
|
+
parse_msg_id(reply_to)
|
|
200
|
+
with self.store.transaction() as tx:
|
|
201
|
+
events = list(tx.events())
|
|
202
|
+
if reply_to is not None:
|
|
203
|
+
original = fold_messages(events).get(reply_to)
|
|
204
|
+
if original is None:
|
|
205
|
+
raise ForgeError(ExitCode.NOT_FOUND, "msg_not_found", f"no message {reply_to}")
|
|
206
|
+
if kind == "answer" and (sender, to) != (original.to, original.sender):
|
|
207
|
+
raise ForgeError(
|
|
208
|
+
ExitCode.USAGE,
|
|
209
|
+
"reply_mismatch",
|
|
210
|
+
f"an answer to {original.label()} goes from {original.to} "
|
|
211
|
+
f"to {original.sender}",
|
|
212
|
+
)
|
|
213
|
+
allowed = pair_allowed(self.domain, sender, to, kind, self._removed())
|
|
214
|
+
msg_id = "msg_" + new_ulid()
|
|
215
|
+
data: dict[str, Any] = {
|
|
216
|
+
"msg_id": msg_id,
|
|
217
|
+
"from": sender,
|
|
218
|
+
"to": to,
|
|
219
|
+
"kind": kind,
|
|
220
|
+
"priority": priority,
|
|
221
|
+
"body": text,
|
|
222
|
+
}
|
|
223
|
+
if reply_to is not None:
|
|
224
|
+
data["reply_to"] = reply_to
|
|
225
|
+
if not allowed:
|
|
226
|
+
data["outcome"] = "blocked"
|
|
227
|
+
data["reason"] = "pair_denied"
|
|
228
|
+
elif kind == "answer" and reply_to is not None:
|
|
229
|
+
data["outcome"] = "answered"
|
|
230
|
+
else:
|
|
231
|
+
data["outcome"] = "relayed"
|
|
232
|
+
event = tx.append("msg", actor=who.role, session=who.session, data=data)
|
|
233
|
+
message = fold_messages([event])[msg_id]
|
|
234
|
+
if not allowed:
|
|
235
|
+
hint = " Use a gate, or ESC, to reach the operator." if to == "operator" else ""
|
|
236
|
+
raise ForgeError(
|
|
237
|
+
ExitCode.REFUSED,
|
|
238
|
+
"pair_denied",
|
|
239
|
+
f"{message.label()} is not an allowed pair; recorded as blocked.{hint}",
|
|
240
|
+
)
|
|
241
|
+
return message
|
|
242
|
+
|
|
243
|
+
def set_state(
|
|
244
|
+
self, msg_id: str, state: str, *, until: str | None = None, now: datetime | None = None
|
|
245
|
+
) -> Message:
|
|
246
|
+
"""Write ``msg_state`` (CONTRACT §8.2)."""
|
|
247
|
+
who = self._who()
|
|
248
|
+
parse_msg_id(msg_id)
|
|
249
|
+
if state not in STATES:
|
|
250
|
+
raise ForgeError(
|
|
251
|
+
ExitCode.USAGE, "invalid_state", f"state is one of {', '.join(STATES)}"
|
|
252
|
+
)
|
|
253
|
+
if (until is not None) != (state == "snoozed"):
|
|
254
|
+
raise ForgeError(
|
|
255
|
+
ExitCode.USAGE, "invalid_until", "--until goes with snoozed, and only with it"
|
|
256
|
+
)
|
|
257
|
+
moment = now or datetime.now(UTC)
|
|
258
|
+
with self.store.transaction() as tx:
|
|
259
|
+
message = fold_messages(tx.events()).get(msg_id)
|
|
260
|
+
if message is None:
|
|
261
|
+
raise ForgeError(ExitCode.NOT_FOUND, "msg_not_found", f"no message {msg_id}")
|
|
262
|
+
allowed = {
|
|
263
|
+
("sent", "delivered"): ORCHESTRATOR,
|
|
264
|
+
("snoozed", "delivered"): ORCHESTRATOR,
|
|
265
|
+
("delivered", "acked"): message.to,
|
|
266
|
+
("delivered", "snoozed"): message.to,
|
|
267
|
+
}
|
|
268
|
+
actor = allowed.get((message.state, state))
|
|
269
|
+
if actor is None:
|
|
270
|
+
raise ForgeError(
|
|
271
|
+
ExitCode.REFUSED,
|
|
272
|
+
"invalid_transition",
|
|
273
|
+
f"{message.label()} is {message.state}; it cannot become {state}",
|
|
274
|
+
)
|
|
275
|
+
if who.role != actor:
|
|
276
|
+
raise ForgeError(
|
|
277
|
+
ExitCode.REFUSED,
|
|
278
|
+
"wrong_role",
|
|
279
|
+
f"{message.label()}: {state} is recorded by {actor}, not {who.role}",
|
|
280
|
+
)
|
|
281
|
+
if message.state == "snoozed" and message.until is not None:
|
|
282
|
+
wake = datetime.fromisoformat(message.until)
|
|
283
|
+
if wake > moment:
|
|
284
|
+
raise ForgeError(
|
|
285
|
+
ExitCode.REFUSED,
|
|
286
|
+
"still_snoozed",
|
|
287
|
+
f"{message.label()} is snoozed until {message.until}",
|
|
288
|
+
)
|
|
289
|
+
data: dict[str, Any] = {"msg_id": msg_id, "state": state}
|
|
290
|
+
if until is not None:
|
|
291
|
+
data["until"] = _until(until, moment)
|
|
292
|
+
tx.append("msg_state", actor=who.role, session=who.session, data=data)
|
|
293
|
+
return replace(message, state=state, until=data.get("until"))
|