teaimforge 0.19.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- teaimforge/__init__.py +8 -0
- teaimforge/archive.py +370 -0
- teaimforge/backup.py +441 -0
- teaimforge/cli.py +823 -0
- teaimforge/config.py +207 -0
- teaimforge/domain.py +549 -0
- teaimforge/errors.py +36 -0
- teaimforge/events.py +381 -0
- teaimforge/findings.py +291 -0
- teaimforge/gates.py +395 -0
- teaimforge/identity.py +259 -0
- teaimforge/index.py +267 -0
- teaimforge/insights.py +142 -0
- teaimforge/items.py +554 -0
- teaimforge/ledger.py +196 -0
- teaimforge/messages.py +293 -0
- teaimforge/migrate.py +230 -0
- teaimforge/output.py +41 -0
- teaimforge/paths.py +101 -0
- teaimforge/py.typed +0 -0
- teaimforge/schema.py +113 -0
- teaimforge/ulid.py +36 -0
- teaimforge/upgrade.py +57 -0
- teaimforge/versions.py +28 -0
- teaimforge/views.py +71 -0
- teaimforge/walls.py +337 -0
- teaimforge/workflow.py +788 -0
- teaimforge-0.19.0.dist-info/METADATA +77 -0
- teaimforge-0.19.0.dist-info/RECORD +32 -0
- teaimforge-0.19.0.dist-info/WHEEL +4 -0
- teaimforge-0.19.0.dist-info/licenses/LICENSE +202 -0
- teaimforge-0.19.0.dist-info/licenses/NOTICE +7 -0
teaimforge/ledger.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
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. ``insights/INSIGHTS.md`` lists every insight 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 .insights import Insight, fold_insights
|
|
22
|
+
from .items import Item, _write_atomic
|
|
23
|
+
from .paths import Layout
|
|
24
|
+
from .workflow import ABANDONED, PARKED
|
|
25
|
+
|
|
26
|
+
LEDGER_FILE = "LEDGER.md"
|
|
27
|
+
INSIGHTS_FILE = "insights/INSIGHTS.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
|
+
INSIGHTS_FILE: self.layout.state / INSIGHTS_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
|
+
insights = list(fold_insights(log).values())
|
|
62
|
+
return {
|
|
63
|
+
LEDGER_FILE: self._ledger(items, gates),
|
|
64
|
+
INSIGHTS_FILE: self._insights(insights),
|
|
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
|
+
parent = self.domain.parent_title if self.domain.parent_fields else None
|
|
147
|
+
header = ("ID", "Title", "Type", "State", *((parent,) if parent else ()), "Assigned")
|
|
148
|
+
lines += _table(
|
|
149
|
+
header,
|
|
150
|
+
[
|
|
151
|
+
(
|
|
152
|
+
i.id,
|
|
153
|
+
i.title,
|
|
154
|
+
i.type,
|
|
155
|
+
i.state,
|
|
156
|
+
*((self.domain.parent_id(i.type, i.fields) or "",) if parent else ()),
|
|
157
|
+
i.assignee or "",
|
|
158
|
+
)
|
|
159
|
+
for i in rows
|
|
160
|
+
],
|
|
161
|
+
)
|
|
162
|
+
lines += ["", f"## Archived ({archived})", ""]
|
|
163
|
+
lines.append(
|
|
164
|
+
f"{archived} rolled up under `archive/`; `{self.domain.name} show <ID>` describes one."
|
|
165
|
+
if archived
|
|
166
|
+
else "None."
|
|
167
|
+
)
|
|
168
|
+
return "\n".join(lines) + "\n"
|
|
169
|
+
|
|
170
|
+
# ------------------------------------------------------------ INSIGHTS.md
|
|
171
|
+
|
|
172
|
+
def _insights(self, insights: Sequence[Insight]) -> str:
|
|
173
|
+
lines = [
|
|
174
|
+
f"# Insights \u2014 {self.project}",
|
|
175
|
+
"",
|
|
176
|
+
f"Generated from the event log by `{self.domain.name} ledger`. "
|
|
177
|
+
"Do not edit: record insights with `insight add`.",
|
|
178
|
+
"",
|
|
179
|
+
]
|
|
180
|
+
if not insights:
|
|
181
|
+
lines.append("No insights yet.")
|
|
182
|
+
return "\n".join(lines) + "\n"
|
|
183
|
+
lines += _table(
|
|
184
|
+
("ID", "Insight", "Tags", "From", "By"),
|
|
185
|
+
[
|
|
186
|
+
(x.id, x.summary, ", ".join(x.tags), x.from_item or "", x.actor)
|
|
187
|
+
for x in sorted(insights, key=lambda x: x.id)
|
|
188
|
+
],
|
|
189
|
+
)
|
|
190
|
+
tags = sorted({t for x in insights for t in x.tags})
|
|
191
|
+
if tags:
|
|
192
|
+
lines += ["", "## By tag", ""]
|
|
193
|
+
for tag in tags:
|
|
194
|
+
ids = ", ".join(x.id for x in sorted(insights, key=lambda x: x.id) if tag in x.tags)
|
|
195
|
+
lines.append(f"- **{tag}**: {ids}")
|
|
196
|
+
return "\n".join(lines) + "\n"
|
teaimforge/messages.py
ADDED
|
@@ -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"))
|