chimericmesh 0.2.2__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.
Files changed (147) hide show
  1. chimericmesh/__init__.py +3 -0
  2. chimericmesh/__main__.py +119 -0
  3. chimericmesh/agent/__init__.py +21 -0
  4. chimericmesh/agent/codesearch.py +131 -0
  5. chimericmesh/agent/digest.py +131 -0
  6. chimericmesh/agent/errors.py +38 -0
  7. chimericmesh/agent/feed.py +47 -0
  8. chimericmesh/agent/limits.py +98 -0
  9. chimericmesh/agent/ports.py +32 -0
  10. chimericmesh/agent/routes.py +92 -0
  11. chimericmesh/agent/service.py +116 -0
  12. chimericmesh/agent/snippet.py +135 -0
  13. chimericmesh/agent/verify.py +215 -0
  14. chimericmesh/agent/watch.py +156 -0
  15. chimericmesh/api.py +626 -0
  16. chimericmesh/approvals/__init__.py +25 -0
  17. chimericmesh/approvals/errors.py +72 -0
  18. chimericmesh/approvals/format.py +76 -0
  19. chimericmesh/approvals/irc.py +54 -0
  20. chimericmesh/approvals/ledger.py +149 -0
  21. chimericmesh/approvals/limits.py +87 -0
  22. chimericmesh/approvals/manager.py +935 -0
  23. chimericmesh/approvals/matching.py +107 -0
  24. chimericmesh/approvals/models.py +251 -0
  25. chimericmesh/approvals/ports.py +36 -0
  26. chimericmesh/approvals/routes.py +220 -0
  27. chimericmesh/approvals/rulebook.py +337 -0
  28. chimericmesh/approvals/schema.py +64 -0
  29. chimericmesh/approvals/scope.py +104 -0
  30. chimericmesh/approvals/validate.py +215 -0
  31. chimericmesh/catalog/demo_apps.json +41 -0
  32. chimericmesh/catalog/legacy_apps.json +612 -0
  33. chimericmesh/commands.py +223 -0
  34. chimericmesh/connectors/__init__.py +1 -0
  35. chimericmesh/connectors/config.py +55 -0
  36. chimericmesh/connectors/framing.py +132 -0
  37. chimericmesh/connectors/limiter.py +42 -0
  38. chimericmesh/connectors/manager.py +252 -0
  39. chimericmesh/connectors/offsets.py +157 -0
  40. chimericmesh/connectors/schema.py +31 -0
  41. chimericmesh/connectors/submit.py +26 -0
  42. chimericmesh/connectors/syslog_tcp.py +141 -0
  43. chimericmesh/connectors/tailer.py +236 -0
  44. chimericmesh/connectors/tailread.py +288 -0
  45. chimericmesh/demo/__init__.py +1 -0
  46. chimericmesh/demo/agent.py +32 -0
  47. chimericmesh/demo/apps/__init__.py +1 -0
  48. chimericmesh/demo/apps/__main__.py +83 -0
  49. chimericmesh/demo/apps/common.py +163 -0
  50. chimericmesh/demo/apps/mail_bridge.py +48 -0
  51. chimericmesh/demo/apps/orders_api.py +31 -0
  52. chimericmesh/demo/apps/spooler.py +28 -0
  53. chimericmesh/demo/config.py +38 -0
  54. chimericmesh/demo/engine.py +68 -0
  55. chimericmesh/demo/env.py +46 -0
  56. chimericmesh/demo/hub.py +172 -0
  57. chimericmesh/demo/launcher.py +165 -0
  58. chimericmesh/demo/ports.py +44 -0
  59. chimericmesh/demo/routes.py +81 -0
  60. chimericmesh/demo/samples.py +32 -0
  61. chimericmesh/demo/scenario.py +95 -0
  62. chimericmesh/demo/supervisor.py +267 -0
  63. chimericmesh/demo/watch.py +46 -0
  64. chimericmesh/diagnostics.py +253 -0
  65. chimericmesh/discovery/__init__.py +17 -0
  66. chimericmesh/discovery/accept.py +131 -0
  67. chimericmesh/discovery/catalog.py +313 -0
  68. chimericmesh/discovery/collect.py +131 -0
  69. chimericmesh/discovery/dismissals.py +46 -0
  70. chimericmesh/discovery/engine.py +41 -0
  71. chimericmesh/discovery/errors.py +34 -0
  72. chimericmesh/discovery/expand.py +151 -0
  73. chimericmesh/discovery/manager.py +220 -0
  74. chimericmesh/discovery/match.py +177 -0
  75. chimericmesh/discovery/models.py +174 -0
  76. chimericmesh/discovery/parse.py +166 -0
  77. chimericmesh/discovery/probe.py +69 -0
  78. chimericmesh/discovery/routes.py +129 -0
  79. chimericmesh/discovery/runner.py +147 -0
  80. chimericmesh/discovery/schema.py +25 -0
  81. chimericmesh/discovery/text.py +53 -0
  82. chimericmesh/events.py +74 -0
  83. chimericmesh/fsperms.py +72 -0
  84. chimericmesh/hub.py +757 -0
  85. chimericmesh/listeners.py +162 -0
  86. chimericmesh/mcp_server.py +199 -0
  87. chimericmesh/mute/__init__.py +10 -0
  88. chimericmesh/mute/models.py +14 -0
  89. chimericmesh/mute/mutelist.py +51 -0
  90. chimericmesh/mute/routes.py +49 -0
  91. chimericmesh/mute/schema.py +29 -0
  92. chimericmesh/mute/store.py +94 -0
  93. chimericmesh/notify.py +47 -0
  94. chimericmesh/parsers/__init__.py +12 -0
  95. chimericmesh/parsers/formats.py +23 -0
  96. chimericmesh/parsers/irc.py +91 -0
  97. chimericmesh/parsers/logctx.py +143 -0
  98. chimericmesh/parsers/ncsa.py +57 -0
  99. chimericmesh/parsers/plain.py +17 -0
  100. chimericmesh/parsers/syslog.py +82 -0
  101. chimericmesh/parsers/syslogtext.py +62 -0
  102. chimericmesh/parsers/telnet.py +56 -0
  103. chimericmesh/parsers/w3c.py +58 -0
  104. chimericmesh/parsers/xferlog.py +31 -0
  105. chimericmesh/replay.py +108 -0
  106. chimericmesh/replay_irc.py +202 -0
  107. chimericmesh/services/__init__.py +39 -0
  108. chimericmesh/services/access.py +224 -0
  109. chimericmesh/services/asgi.py +107 -0
  110. chimericmesh/services/deps.py +42 -0
  111. chimericmesh/services/errors.py +49 -0
  112. chimericmesh/services/limiter.py +130 -0
  113. chimericmesh/services/models.py +160 -0
  114. chimericmesh/services/paths.py +139 -0
  115. chimericmesh/services/registry.py +638 -0
  116. chimericmesh/services/routes.py +161 -0
  117. chimericmesh/services/schema.py +48 -0
  118. chimericmesh/services/status.py +239 -0
  119. chimericmesh/services/tagging.py +63 -0
  120. chimericmesh/services/token.py +129 -0
  121. chimericmesh/services/validate.py +184 -0
  122. chimericmesh/store/__init__.py +43 -0
  123. chimericmesh/store/audit.py +89 -0
  124. chimericmesh/store/config.py +88 -0
  125. chimericmesh/store/connection.py +98 -0
  126. chimericmesh/store/errors.py +65 -0
  127. chimericmesh/store/events.py +430 -0
  128. chimericmesh/store/incidents.py +292 -0
  129. chimericmesh/store/migrations.py +109 -0
  130. chimericmesh/store/models.py +49 -0
  131. chimericmesh/store/ports.py +61 -0
  132. chimericmesh/store/proposals.py +215 -0
  133. chimericmesh/store/schema.py +102 -0
  134. chimericmesh/store/store.py +173 -0
  135. chimericmesh/store/tx.py +143 -0
  136. chimericmesh/store/writer.py +315 -0
  137. chimericmesh/web/__init__.py +1 -0
  138. chimericmesh/web/feed.py +212 -0
  139. chimericmesh/web/index.html +3775 -0
  140. chimericmesh/web/sse.py +74 -0
  141. chimericmesh/web/stream.py +64 -0
  142. chimericmesh-0.2.2.dist-info/METADATA +537 -0
  143. chimericmesh-0.2.2.dist-info/RECORD +147 -0
  144. chimericmesh-0.2.2.dist-info/WHEEL +5 -0
  145. chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
  146. chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
  147. chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,935 @@
1
+ """``ApprovalManager``: the one facade of auto-approval.
2
+
3
+ Threads: everything here runs on the loop thread except ``ApprovalPlan.write_in_tx`` and the registry
4
+ callbacks, which run on the ``store-writer`` thread and use only their ``tx``.
5
+
6
+ Authorization is the caller's business: the widen operations (create, patch, enable, resume) are called
7
+ after ``require_admin`` passed; the reduce operations (revoke, pause, withdraw) take no token and are
8
+ never refused (R2.3). There is no method that the agent can reach.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import dataclasses
14
+ import logging
15
+ import time
16
+ import weakref
17
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
18
+ from typing import Any
19
+
20
+ from chimericmesh.services.models import ServiceChange
21
+ from chimericmesh.services.registry import ServiceRegistry
22
+ from chimericmesh.store import Store, StoreError, Tx
23
+ from chimericmesh.store.errors import InvalidTransition, NotFound
24
+ from chimericmesh.store.models import Proposal
25
+ from chimericmesh.store.ports import ProposalWriter, StateView
26
+
27
+ from . import rulebook as rb
28
+ from .errors import (
29
+ ActiveProposalExists, ProposalExpired, ProposalInvalid, RuleConflict, RuleInvalid, RuleLimitReached,
30
+ RuleNotApplicable, RuleNotFound,
31
+ )
32
+ from .format import auto_approved_line, cooldown_note, rule_line, safe_text
33
+ from .ledger import OpeningRow, UsageLedger, UsageRow
34
+ from .limits import ProposalLimits
35
+ from .matching import MatchContext, first_match
36
+ from .models import (
37
+ BOUNDS, MAX_EXPIRY_SECONDS, MAX_RULES_PER_SERVICE, MAX_RULES_TOTAL, ApprovalPlan, ApprovalSettings,
38
+ ApprovalStatus, CreateContext, Rule, RuleCheck, RuleDefaults, RuleFields, RulePatch,
39
+ )
40
+ from .rulebook import RuleBook, Snapshot
41
+ from .scope import check_files
42
+ from .validate import clean_note, validate_completion, validate_new_proposal
43
+
44
+ log = logging.getLogger("chimericmesh.approvals")
45
+
46
+ AnnounceFn = Callable[[str], Awaitable[None]]
47
+ RETENTION_SECONDS = 31 * 86400.0
48
+ HOUR = 3600.0
49
+ EXPIRE_DUE_TIMEOUT = 1.0
50
+ SWEEP_STEPS = ("_step_persist_dirty", "_step_expire", "_step_deny_stale", "_step_ttl", "_step_repair",
51
+ "_step_reload", "_step_openings", "_step_prune")
52
+
53
+
54
+ def _retrieve(task: "asyncio.Future[Any]") -> None:
55
+ """Mark the exception of a shielded unit as retrieved so a cancelled caller logs nothing."""
56
+ if not task.cancelled():
57
+ task.exception()
58
+
59
+
60
+ class ApprovalManager:
61
+ def __init__(self, store: Store, *, state: StateView, writer: ProposalWriter, registry: ServiceRegistry,
62
+ limiter: Any, announce: AnnounceFn, protected: Sequence[str] = (),
63
+ settings: ApprovalSettings | None = None, now: Callable[[], float] | None = None,
64
+ expire_timeout: float = EXPIRE_DUE_TIMEOUT) -> None:
65
+ # Weak, like the registry's: a strong reference would keep a private ``:memory:`` store (and its writer
66
+ # thread) alive after the app that owns it is dropped.
67
+ self._store_ref = weakref.ref(store)
68
+ self._state = state
69
+ self._writer = writer
70
+ self._registry = registry
71
+ self._limiter = limiter
72
+ self._announce = announce
73
+ self._protected = tuple(protected)
74
+ self._settings = settings or ApprovalSettings()
75
+ self._now: Callable[[], float] = now or state.now
76
+ self._expire_timeout = expire_timeout
77
+ self._book = RuleBook()
78
+ self._ledger = UsageLedger()
79
+ self._limits = ProposalLimits()
80
+ self._rules_lock = asyncio.Lock() # serializes widen operations against each other only
81
+ self._sweep_lock = asyncio.Lock()
82
+ self._sweep_task: asyncio.Task | None = None
83
+ self._tasks: set[asyncio.Task] = set()
84
+ self._warned_at = float("-inf")
85
+ self._closed = False
86
+ self._unsaved_openings: dict[tuple[str, int], float] = {} # first sightings not yet in the database
87
+
88
+ # ---- construction ----------------------------------------------------------------------------------
89
+ @classmethod
90
+ def load(cls, store: Store, *, state: StateView, writer: ProposalWriter, registry: ServiceRegistry,
91
+ limiter: Any, announce: AnnounceFn, protected: Sequence[str] = (),
92
+ settings: ApprovalSettings | None = None, now: Callable[[], float] | None = None,
93
+ expire_timeout: float = EXPIRE_DUE_TIMEOUT) -> "ApprovalManager":
94
+ rb.ensure_migrated(store)
95
+ self = cls(store, state=state, writer=writer, registry=registry, limiter=limiter, announce=announce,
96
+ protected=protected, settings=settings, now=now, expire_timeout=expire_timeout)
97
+ since = self._now() - RETENTION_SECONDS
98
+
99
+ def read(tx: Tx):
100
+ paused, by, at = rb.load_state(tx)
101
+ return (rb.load_rules(tx), paused, by, at,
102
+ [UsageRow(r["rule_id"], r["proposal_id"], r["incident_id"], int(r["opening"]), r["service_id"],
103
+ float(r["approved_at"]),
104
+ None if r["completed_at"] is None else float(r["completed_at"]))
105
+ for r in rb.load_uses(tx, since)],
106
+ [OpeningRow(r["incident_id"], int(r["opening"]), float(r["first_seen_at"]))
107
+ for r in rb.load_openings(tx, since)])
108
+
109
+ rules, paused, by, at, uses, openings = store.read_sync(read, allow_blocking=True)
110
+ self._book.load(rules, paused=paused, paused_by=by, paused_at=at)
111
+ self._ledger.seed(uses, openings)
112
+ self._seed_limits()
113
+ # The registry outlives the app when a caller keeps the hub (hub.tagger is registry.tag), so it holds the
114
+ # manager weakly: bound methods here would keep the manager and everything it references alive.
115
+ me = weakref.ref(self)
116
+
117
+ def on_code_folder_changed(tx: Tx, change: ServiceChange) -> None:
118
+ manager = me()
119
+ if manager is not None:
120
+ manager._on_code_folder_changed(tx, change)
121
+
122
+ def on_service_deleted(tx: Tx, change: ServiceChange) -> None:
123
+ manager = me()
124
+ if manager is not None:
125
+ manager._on_service_deleted(tx, change)
126
+
127
+ async def after_commit(change: ServiceChange) -> None:
128
+ manager = me()
129
+ if manager is not None:
130
+ await manager._on_after_commit(change)
131
+
132
+ registry.subscribe(on_code_folder_changed=on_code_folder_changed, on_service_deleted=on_service_deleted,
133
+ after_commit=after_commit, name="approvals")
134
+ return self
135
+
136
+ def _seed_limits(self) -> None:
137
+ now = self._now()
138
+ by_service: dict[str, list[float]] = {}
139
+ for prop in self._state.list_proposals():
140
+ if now - prop.created < HOUR:
141
+ by_service.setdefault(prop.service_id or "unassigned", []).append(prop.created)
142
+ self._limits.seed(by_service, now)
143
+
144
+ @property
145
+ def _store(self) -> Store:
146
+ store = self._store_ref()
147
+ if store is None:
148
+ raise RuntimeError("the approval manager was used after its store was dropped")
149
+ return store
150
+
151
+ # ---- small helpers -----------------------------------------------------------------------------------
152
+ def _warn_once_a_minute(self, text: str, *args: object) -> None:
153
+ mono = time.monotonic()
154
+ if mono - self._warned_at >= 60.0:
155
+ self._warned_at = mono
156
+ log.warning(text, *args)
157
+
158
+ async def _say(self, text: str) -> None:
159
+ try:
160
+ await self._announce(text)
161
+ except Exception: # noqa: BLE001 - an announcement problem never undoes a decision
162
+ log.exception("could not announce an approvals event")
163
+
164
+ def _unit(self, coro: Awaitable[Any]) -> "asyncio.Future[Any]":
165
+ """Run ``coro`` as a task that a cancelled caller cannot interrupt (store T6)."""
166
+ task = asyncio.ensure_future(coro)
167
+ self._tasks.add(task)
168
+ task.add_done_callback(self._tasks.discard)
169
+ task.add_done_callback(_retrieve)
170
+ return asyncio.shield(task)
171
+
172
+ def _audit(self, tx: Tx, actor: str, action: str, subject: str, detail: str = "", *,
173
+ service_id: str | None = None, rule_id: str | None = None, proposal_id: str | None = None) -> int:
174
+ return self._store.audit.append_tx(tx, actor, action, subject, detail, service_id=service_id,
175
+ rule_id=rule_id, proposal_id=proposal_id)
176
+
177
+ # ---- reads (loop thread, no I/O) ---------------------------------------------------------------------
178
+ def rules(self, *, service_id: str | None = None, status: str | None = None) -> list[Rule]:
179
+ return self._book.rules(service_id=service_id, status=status)
180
+
181
+ def rule(self, rule_id: str) -> Rule | None:
182
+ return self._book.get(rule_id)
183
+
184
+ def rule_dict(self, rule: Rule) -> dict[str, Any]:
185
+ now = self._now()
186
+ uses = self._ledger.usage(rule.id, "", 0, now).hour
187
+ return rule.to_dict(now=now, uses_last_hour=uses)
188
+
189
+ @property
190
+ def paused(self) -> bool:
191
+ return self._book.paused
192
+
193
+ def now(self) -> float:
194
+ return self._now()
195
+
196
+ @property
197
+ def audit_log(self):
198
+ """The audit log the manager writes to (read by ``GET /api/audit``)."""
199
+ return self._store.audit
200
+
201
+ def status(self) -> ApprovalStatus:
202
+ return ApprovalStatus(
203
+ paused=self._book.paused, paused_by=self._book.paused_by, paused_at=self._book.paused_at,
204
+ active_rules=len(self._book.rules(status="active")),
205
+ suspended_rules=len(self._book.rules(status="suspended")),
206
+ cooldown_seconds=self._settings.autofix_cooldown,
207
+ proposal_ttl_hours=self._settings.proposal_ttl / 3600.0, bounds=BOUNDS)
208
+
209
+ def _expired_by_clock(self, rule: Rule) -> bool:
210
+ return rule.status in ("active", "suspended") and self._now() >= rule.expires_at
211
+
212
+ # ---- widen operations (the caller has passed require_admin) -----------------------------------------
213
+ async def create_rule(self, fields: RuleFields, *, actor: str, source_proposal_id: str | None = None) -> Rule:
214
+ async with self._rules_lock:
215
+ return await self._unit(self._create(fields, actor, source_proposal_id))
216
+
217
+ async def _create(self, fields: RuleFields, actor: str, source_proposal_id: str | None) -> Rule:
218
+ service = self._registry.get(fields.service_id)
219
+ if service is None:
220
+ raise RuleInvalid("service_id", "unknown service")
221
+ if not service.code_folder:
222
+ raise RuleInvalid("service_id", "service has no code folder")
223
+ folder = service.code_folder
224
+ now = self._now()
225
+ who = safe_text(actor, 100)
226
+ expires = fields.expires_at if fields.expires_at is not None else now + 7 * 86400.0
227
+ if expires > now + MAX_EXPIRY_SECONDS:
228
+ raise RuleInvalid("expires_at", "may be at most 30 days after the rule was created")
229
+
230
+ def write(tx: Tx) -> Rule:
231
+ per_service, total = rb.count_live_rules(tx, fields.service_id)
232
+ if per_service >= MAX_RULES_PER_SERVICE or total >= MAX_RULES_TOTAL:
233
+ raise RuleLimitReached(f"at most {MAX_RULES_PER_SERVICE} rules per service and "
234
+ f"{MAX_RULES_TOTAL} in total")
235
+ seq, rid = rb.issue_rule_id(tx)
236
+ rule = Rule(
237
+ id=rid, seq=seq, service_id=fields.service_id, match_type=fields.match_type,
238
+ match_value=fields.match_value, most_urgent_severity=fields.most_urgent_severity,
239
+ expires_at=float(expires), max_per_hour=fields.max_per_hour, max_per_incident=fields.max_per_incident,
240
+ max_files=fields.max_files, max_lines=fields.max_lines, status="active", status_reason="",
241
+ created_by=who, created_at=now, updated_at=now, source_proposal_id=source_proposal_id,
242
+ note=clean_note(fields.note), use_count=0, code_folder=folder)
243
+ rb.insert_rule(tx, rule)
244
+ detail = f"from proposal {source_proposal_id}" if source_proposal_id else "created directly"
245
+ self._audit(tx, who, "rule_created", rid, detail, service_id=rule.service_id, rule_id=rid,
246
+ proposal_id=source_proposal_id)
247
+ return rule
248
+
249
+ rule = await self._store.transact(write)
250
+ self._book.replace(rule) # no await between the commit result and the mirror
251
+ await self._say(rule_line("created", rule.id, rule.service_id, who))
252
+ return rule
253
+
254
+ async def patch_rule(self, rule_id: str, patch: RulePatch, *, actor: str) -> Rule:
255
+ async with self._rules_lock:
256
+ return await self._unit(self._patch(rule_id, patch, actor))
257
+
258
+ async def _patch(self, rule_id: str, patch: RulePatch, actor: str) -> Rule:
259
+ rule = self._book.get(rule_id)
260
+ if rule is None:
261
+ raise RuleNotFound(rule_id)
262
+ if rule.status in ("revoked", "expired") or self._expired_by_clock(rule):
263
+ raise RuleConflict(f"rule {rule_id} is {rule.status if rule.status != 'active' else 'expired'}")
264
+ changes = {k: v for k, v in dataclasses.asdict(patch).items() if v is not None}
265
+ if "expires_at" in changes and not self._now() < changes["expires_at"] <= rule.created_at + MAX_EXPIRY_SECONDS:
266
+ raise RuleInvalid("expires_at", "must be in the future and at most 30 days after the rule was created")
267
+ if "note" in changes:
268
+ changes["note"] = clean_note(changes["note"])
269
+ for name, low, high in (("most_urgent_severity", 3, 4), ("max_per_hour", 1, BOUNDS["max_per_hour"]["max"]),
270
+ ("max_per_incident", 1, 3), ("max_files", 1, 20), ("max_lines", 1, 500)):
271
+ if name in changes and not low <= changes[name] <= high:
272
+ raise RuleInvalid(name, f"must be from {low} to {high}")
273
+ changes = {k: v for k, v in changes.items() if getattr(rule, k) != v}
274
+ if not changes:
275
+ return rule
276
+ version = self._book.version(rule_id)
277
+ now = self._now()
278
+ new = dataclasses.replace(rule, updated_at=now, **changes)
279
+ who = safe_text(actor, 100)
280
+ detail = "; ".join(f"{k}: {getattr(rule, k)} -> {v}" if k != "note" else "note changed"
281
+ for k, v in changes.items())
282
+
283
+ def write(tx: Tx) -> None:
284
+ if rb.patch_row(tx, new, now) == 0:
285
+ raise RuleConflict(f"rule {rule_id} changed while updating")
286
+ self._audit(tx, who, "rule_updated", rule_id, detail, service_id=rule.service_id, rule_id=rule_id)
287
+
288
+ await self._store.transact(write)
289
+ current = self._book.get(rule_id)
290
+ if current is None or self._book.version(rule_id) != version:
291
+ self._book.mark_dirty(rule_id)
292
+ raise RuleConflict(f"rule {rule_id} changed while updating")
293
+ self._book.replace(new)
294
+ return new
295
+
296
+ async def enable_rule(self, rule_id: str, *, actor: str) -> Rule:
297
+ async with self._rules_lock:
298
+ return await self._unit(self._enable(rule_id, actor))
299
+
300
+ async def _enable(self, rule_id: str, actor: str) -> Rule:
301
+ rule = self._book.get(rule_id)
302
+ if rule is None:
303
+ raise RuleNotFound(rule_id)
304
+ if rule.status != "suspended":
305
+ raise RuleConflict(f"rule {rule_id} is {rule.status}, only a suspended rule can be re-enabled")
306
+ if self._expired_by_clock(rule):
307
+ await self._expire_rules([rule])
308
+ raise RuleConflict(f"rule {rule_id} has expired")
309
+ service = self._registry.get(rule.service_id)
310
+ if service is None:
311
+ raise RuleConflict("the service of this rule is gone")
312
+ if service.code_folder != rule.code_folder:
313
+ raise RuleConflict("the code folder of the service changed; create a new rule")
314
+ version = self._book.version(rule_id)
315
+ now = self._now()
316
+ who = safe_text(actor, 100)
317
+
318
+ def write(tx: Tx) -> None:
319
+ if rb.enable_row(tx, rule_id, now) == 0:
320
+ raise RuleConflict(f"rule {rule_id} changed while enabling")
321
+ self._audit(tx, who, "rule_enabled", rule_id, "", service_id=rule.service_id, rule_id=rule_id)
322
+
323
+ await self._store.transact(write)
324
+ if self._book.version(rule_id) != version:
325
+ self._book.mark_dirty(rule_id) # the database may now hold a looser state than the mirror
326
+ raise RuleConflict(f"rule {rule_id} changed while enabling")
327
+ new = dataclasses.replace(rule, status="active", status_reason="", updated_at=now)
328
+ self._book.replace(new)
329
+ await self._say(rule_line("enabled", rule_id, rule.service_id, who))
330
+ return new
331
+
332
+ async def resume(self, *, actor: str) -> ApprovalStatus:
333
+ async with self._rules_lock:
334
+ return await self._unit(self._resume(actor))
335
+
336
+ async def _resume(self, actor: str) -> ApprovalStatus:
337
+ if not self._book.paused:
338
+ return self.status()
339
+ version = self._book.pause_version
340
+ who = safe_text(actor, 100)
341
+
342
+ def write(tx: Tx) -> None:
343
+ rb.resume_row(tx)
344
+ self._audit(tx, who, "rules_resumed", "all")
345
+
346
+ await self._store.transact(write)
347
+ if self._book.pause_version != version:
348
+ self._book.mark_paused_dirty()
349
+ raise RuleConflict("auto-approval was paused again while resuming")
350
+ self._book.set_paused(False, "", None)
351
+ await self._say(rule_line("resumed", "", "", who))
352
+ return self.status()
353
+
354
+ # ---- reduce operations (token-free, always executed, mirror first) ------------------------------------
355
+ async def _gate(self, key: str, **row: Any) -> bool:
356
+ """The limiter decides whether this call gets its own audit row and announcement. Never raises."""
357
+ try:
358
+ return bool(await self._limiter.record(key, **row))
359
+ except Exception: # noqa: BLE001 - the action goes ahead; at worst it is announced
360
+ log.exception("the reduce-operations limiter failed")
361
+ return True
362
+
363
+ async def revoke_rule(self, rule_id: str, *, actor: str, key: str) -> Rule:
364
+ rule = self._book.get(rule_id)
365
+ if rule is None:
366
+ raise RuleNotFound(rule_id)
367
+ if rule.status in ("revoked", "expired"):
368
+ return rule # already final: nothing to write or announce
369
+ who = safe_text(actor, 100)
370
+ now = self._now()
371
+ revoked = dataclasses.replace(rule, status="revoked", status_reason=f"revoked by {who}"[:100], updated_at=now)
372
+ self._book.replace(revoked) # before any await: the next prepare already refuses
373
+ self._book.mark_dirty(rule_id)
374
+ speak = await self._gate(key, actor=who, action="rule_revoked", subject=rule_id, detail="",
375
+ service_id=rule.service_id, rule_id=rule_id)
376
+ await self._persist_rule(rule_id, lambda tx: rb.revoke_row(tx, rule_id, revoked.status_reason, now))
377
+ await self._deny_open_proposals(rule_id, f"rule-revoked:{rule_id}")
378
+ if speak:
379
+ await self._say(rule_line("revoked", rule_id, rule.service_id, who))
380
+ return revoked
381
+
382
+ async def pause_rule(self, rule_id: str, *, actor: str, key: str) -> Rule:
383
+ rule = self._book.get(rule_id)
384
+ if rule is None:
385
+ raise RuleNotFound(rule_id)
386
+ if rule.status != "active":
387
+ return rule
388
+ who = safe_text(actor, 100)
389
+ now = self._now()
390
+ paused = dataclasses.replace(rule, status="suspended", status_reason=f"paused by {who}"[:100], updated_at=now)
391
+ self._book.replace(paused)
392
+ self._book.mark_dirty(rule_id)
393
+ speak = await self._gate(key, actor=who, action="rule_paused", subject=rule_id, detail="",
394
+ service_id=rule.service_id, rule_id=rule_id)
395
+ await self._persist_rule(rule_id, lambda tx: rb.suspend_row(tx, rule_id, paused.status_reason, now))
396
+ await self._deny_open_proposals(rule_id, f"rule-suspended:{rule_id}")
397
+ if speak:
398
+ await self._say(rule_line("rule_paused", rule_id, rule.service_id, who))
399
+ return paused
400
+
401
+ async def pause(self, *, actor: str, key: str) -> ApprovalStatus:
402
+ if self._book.paused:
403
+ return self.status()
404
+ who = safe_text(actor, 100)
405
+ now = self._now()
406
+ self._book.set_paused(True, who, now)
407
+ self._book.mark_paused_dirty()
408
+ speak = await self._gate(key, actor=who, action="rules_paused", subject="all", detail="")
409
+ try:
410
+ await self._store.transact(lambda tx: rb.set_paused_row(tx, True, who, now))
411
+ if self._book.paused:
412
+ self._book.clear_paused_dirty()
413
+ except StoreError:
414
+ self._warn_once_a_minute("could not persist the pause flag; the sweep will retry")
415
+ if speak:
416
+ await self._say(rule_line("paused", "", "", who))
417
+ return self.status()
418
+
419
+ async def _persist_rule(self, rule_id: str, fn: Callable[[Tx], int]) -> None:
420
+ """Write a reduce to the database. A failure leaves the rule dirty for the sweep (design O5)."""
421
+ try:
422
+ await self._store.transact(fn)
423
+ except StoreError:
424
+ self._warn_once_a_minute("could not persist a rule change; the sweep will retry")
425
+ return
426
+ self._book.clear_dirty(rule_id)
427
+
428
+ async def withdraw(self, proposal_id: str, *, actor: str, key: str) -> Proposal:
429
+ prop = self._state.get_proposal(proposal_id)
430
+ if prop is None:
431
+ raise NotFound(f"proposal {proposal_id} not found")
432
+ if prop.status != "pending":
433
+ return prop
434
+ who = safe_text(actor, 40)
435
+ speak = await self._gate(key, actor=who, action="proposal_withdrawn", subject=proposal_id, detail="",
436
+ service_id=prop.service_id, proposal_id=proposal_id)
437
+ try:
438
+ moved = await self._writer.hub_transition(proposal_id, "denied", decided_by=f"withdrawn:{who}"[:60])
439
+ except InvalidTransition:
440
+ moved = None
441
+ if moved is None:
442
+ return self._state.get_proposal(proposal_id) or prop
443
+ if speak:
444
+ await self._say(rule_line("withdrawn", proposal_id, prop.service_id or "", who))
445
+ return moved
446
+
447
+ async def _deny_open_proposals(self, rule_id: str, decided_by: str) -> None:
448
+ """Deny every ``approved`` proposal of the rule. Each is its own commit; a failure is left to the sweep."""
449
+ for prop in self._state.list_proposals("approved"):
450
+ if prop.approved_by_rule != rule_id:
451
+ continue
452
+ try:
453
+ await self._writer.hub_transition(prop.id, "denied", decided_by=decided_by)
454
+ except (InvalidTransition, NotFound):
455
+ continue
456
+ except StoreError:
457
+ self._warn_once_a_minute("could not deny proposals of rule %s; the sweep will retry", rule_id)
458
+ return
459
+
460
+ # ---- rules from a proposal (R3) ------------------------------------------------------------------------
461
+ def rule_defaults(self, proposal_id: str, *, now: float | None = None) -> RuleDefaults:
462
+ prop = self._state.get_proposal(proposal_id)
463
+ if prop is None:
464
+ raise NotFound(f"proposal {proposal_id} not found")
465
+ if prop.approved_by_rule:
466
+ raise RuleNotApplicable("this proposal was approved by a rule, not by a person")
467
+ if prop.status == "pending":
468
+ raise RuleNotApplicable("the proposal is still pending")
469
+ if prop.status == "denied":
470
+ raise RuleNotApplicable("the proposal was denied")
471
+ if prop.status == "done" and prop.verification_result != "passed":
472
+ raise RuleNotApplicable("the fix was not verified as passed")
473
+ inc = self._state.get_incident(prop.incident_id)
474
+ if inc is None:
475
+ raise RuleInvalid("incident_id", "the incident of this proposal is no longer known")
476
+ if not inc.service_id:
477
+ raise RuleInvalid("service_id", "the incident is not tagged to a service")
478
+ service = self._registry.get(inc.service_id)
479
+ if service is None or not service.code_folder:
480
+ raise RuleInvalid("service_id", "the service has no code folder")
481
+ at = self._now() if now is None else now
482
+ return RuleDefaults(
483
+ service_id=inc.service_id, match_type="signature", match_value=inc.signature[:200],
484
+ most_urgent_severity=min(4, max(3, int(inc.severity))), expires_at=at + 7 * 86400.0,
485
+ max_per_hour=BOUNDS["max_per_hour"]["default"], max_per_incident=BOUNDS["max_per_incident"]["default"],
486
+ max_files=BOUNDS["max_files"]["default"], max_lines=BOUNDS["max_lines"]["default"],
487
+ note=f"from {proposal_id}", source_proposal_id=proposal_id)
488
+
489
+ async def create_rule_from_proposal(self, proposal_id: str, overrides: Mapping[str, object], *,
490
+ actor: str) -> Rule:
491
+ from .validate import validate_rule_fields
492
+
493
+ defaults = self.rule_defaults(proposal_id)
494
+ raw: dict[str, object] = {k: v for k, v in defaults.to_dict().items() if k != "source_proposal_id"}
495
+ for key, value in overrides.items():
496
+ if key in ("service_id", "source_proposal_id"):
497
+ raise RuleInvalid(key, "cannot be changed when a rule is made from a proposal")
498
+ raw[key] = value
499
+ fields = validate_rule_fields(raw, now=self._now())
500
+ return await self.create_rule(fields, actor=actor, source_proposal_id=proposal_id)
501
+
502
+ # ---- rule expiry and denial helpers -----------------------------------------------------------------------
503
+ @staticmethod
504
+ def _denial_for(rule: Rule) -> str:
505
+ word = {"suspended": "suspended", "revoked": "revoked", "expired": "expired"}.get(rule.status, "suspended")
506
+ return f"rule-{word}:{rule.id}"
507
+
508
+ async def _expire_rules(self, rules: Sequence[Rule]) -> None:
509
+ for rule in rules:
510
+ current = self._book.get(rule.id)
511
+ if current is None or current.status not in ("active", "suspended"):
512
+ continue
513
+ now = self._now()
514
+ self._book.replace(dataclasses.replace(current, status="expired", status_reason="expired", updated_at=now))
515
+ self._book.mark_dirty(rule.id)
516
+
517
+ def write(tx: Tx, rid: str = rule.id, sid: str = rule.service_id) -> int:
518
+ changed = rb.expire_row(tx, rid, now)
519
+ if changed:
520
+ self._audit(tx, "hub", "rule_expired", rid, "", service_id=sid, rule_id=rid)
521
+ return changed
522
+
523
+ await self._persist_rule(rule.id, write)
524
+ await self._deny_open_proposals(rule.id, f"rule-expired:{rule.id}")
525
+ await self._say(rule_line("expired", rule.id, rule.service_id, "hub"))
526
+
527
+ # ---- registry subscriptions (R6.9) ------------------------------------------------------------------------
528
+ def _suspend_in_tx(self, tx: Tx, service_id: str, reason: str, *, only_active: bool) -> None:
529
+ """Writer thread, inside the registry's transaction: uses only ``tx`` and the immutable arguments."""
530
+ ids = rb.active_rule_ids(tx, service_id) if only_active else [rid for rid, _ in rb.live_rule_ids(tx, service_id)]
531
+ if not ids:
532
+ return
533
+ rb.suspend_service_rules(tx, service_id, reason, self._store.now(), only_active=only_active)
534
+ for rid in ids:
535
+ self._audit(tx, "hub", "rule_suspended", rid, reason, service_id=service_id, rule_id=rid)
536
+
537
+ def _on_code_folder_changed(self, tx: Tx, change: ServiceChange) -> None:
538
+ self._suspend_in_tx(tx, change.service_id, "code_folder_changed", only_active=True)
539
+
540
+ def _on_service_deleted(self, tx: Tx, change: ServiceChange) -> None:
541
+ self._suspend_in_tx(tx, change.service_id, "service_deleted", only_active=False)
542
+
543
+ async def _on_after_commit(self, change: ServiceChange) -> None:
544
+ if change.kind == "service_deleted" or (change.kind == "service_updated" and change.code_folder_changed):
545
+ await self._reload(announce=True)
546
+
547
+ async def _reload(self, *, announce: bool = False) -> list[str]:
548
+ """Re-read the rules and merge tighten-only (rule 5). Returns the ids that changed."""
549
+ started = self._book.epoch
550
+
551
+ def read(tx: Tx) -> Snapshot:
552
+ paused, by, at = rb.load_state(tx)
553
+ return Snapshot(tuple(rb.load_rules(tx)), paused, by, at)
554
+
555
+ snapshot = await self._store.read(read)
556
+ before = {r.id: r.status for r in self._book.rules()}
557
+ changed = self._book.merge(snapshot, started)
558
+ for rid in changed:
559
+ rule = self._book.get(rid)
560
+ if rule is None or rule.status == "active":
561
+ continue
562
+ if before.get(rid, "active") == "active":
563
+ await self._deny_open_proposals(rid, self._denial_for(rule))
564
+ if announce:
565
+ await self._say(rule_line("suspended", rid, rule.service_id, "hub", rule.status_reason))
566
+ return changed
567
+
568
+ # ---- sweep and expiry on read (R6.4, R6.8, R9.8) --------------------------------------------------------------
569
+ async def start(self) -> None:
570
+ if self._sweep_task is None and not self._closed:
571
+ self._sweep_task = asyncio.get_running_loop().create_task(self._sweep_loop())
572
+
573
+ async def aclose(self, timeout: float = 1.0) -> None:
574
+ """Stop the sweep, then let in-flight store units finish (bounded) so none outlives the store."""
575
+ self._closed = True
576
+ task, self._sweep_task = self._sweep_task, None
577
+ if task is not None:
578
+ task.cancel()
579
+ await asyncio.gather(task, return_exceptions=True)
580
+ pending = [t for t in self._tasks if not t.done()]
581
+ if pending:
582
+ # Units are never cancelled (a decision and its audit row commit together); wait for them instead.
583
+ _, late = await asyncio.wait(pending, timeout=max(0.0, timeout))
584
+ if late:
585
+ log.error("%d approvals store unit(s) still running at shutdown", len(late))
586
+
587
+ async def _sweep_loop(self) -> None:
588
+ while True:
589
+ await asyncio.sleep(self._settings.sweep_interval)
590
+ try:
591
+ await self.sweep_once()
592
+ except asyncio.CancelledError:
593
+ raise
594
+ except Exception: # noqa: BLE001
595
+ log.exception("approvals sweep failed")
596
+
597
+ async def sweep_once(self) -> None:
598
+ async with self._sweep_lock:
599
+ for name in SWEEP_STEPS:
600
+ try:
601
+ await getattr(self, name)()
602
+ except asyncio.CancelledError:
603
+ raise
604
+ except Exception: # noqa: BLE001 - one failing step never stops the others
605
+ self._warn_once_a_minute("approvals sweep step %s failed", name)
606
+
607
+ async def expire_due(self) -> None:
608
+ """Steps 2 to 4 on read. Bounded, never raises, returns at once while the sweep runs (review M5)."""
609
+ if self._sweep_lock.locked():
610
+ return
611
+ task = asyncio.ensure_future(self._expire_work())
612
+ self._tasks.add(task)
613
+ task.add_done_callback(self._tasks.discard)
614
+ task.add_done_callback(_retrieve)
615
+ try:
616
+ await asyncio.wait_for(asyncio.shield(task), self._expire_timeout)
617
+ except asyncio.TimeoutError:
618
+ return # the work keeps running; the caller goes on
619
+ except asyncio.CancelledError:
620
+ raise
621
+ except Exception: # noqa: BLE001 - includes StoreError: reads stay 200
622
+ self._warn_once_a_minute("expire_due failed; reads continue without it")
623
+
624
+ async def _expire_work(self) -> None:
625
+ async with self._sweep_lock:
626
+ for name in ("_step_expire", "_step_deny_stale", "_step_ttl"):
627
+ try:
628
+ await getattr(self, name)()
629
+ except asyncio.CancelledError:
630
+ raise
631
+ except Exception: # noqa: BLE001
632
+ self._warn_once_a_minute("approvals step %s failed", name)
633
+
634
+ async def _step_persist_dirty(self) -> None:
635
+ now = self._now()
636
+ for rid in list(self._book.dirty):
637
+ rule = self._book.get(rid)
638
+ if rule is None or rule.status == "active":
639
+ self._book.clear_dirty(rid)
640
+ continue
641
+ version = self._book.version(rid)
642
+
643
+ def write(tx: Tx, rule: Rule = rule) -> int:
644
+ if rule.status == "revoked":
645
+ return rb.revoke_row(tx, rule.id, rule.status_reason, now)
646
+ if rule.status == "expired":
647
+ return rb.expire_row(tx, rule.id, now)
648
+ return rb.suspend_row(tx, rule.id, rule.status_reason, now)
649
+
650
+ await self._store.transact(write)
651
+ if self._book.version(rid) == version:
652
+ self._book.clear_dirty(rid)
653
+ if self._book.paused_dirty:
654
+ if self._book.paused:
655
+ await self._store.transact(lambda tx: rb.set_paused_row(tx, True, self._book.paused_by,
656
+ self._book.paused_at or now))
657
+ self._book.clear_paused_dirty()
658
+
659
+ async def _step_expire(self) -> None:
660
+ due = [r for r in self._book.rules() if self._expired_by_clock(r)]
661
+ if due:
662
+ await self._expire_rules(due)
663
+
664
+ def _approved_age_start(self, prop: Proposal) -> float | None:
665
+ at = self._ledger.approved_at(prop.id)
666
+ return at if at is not None else prop.decided_at
667
+
668
+ async def _step_deny_stale(self) -> None:
669
+ now = self._now()
670
+ for prop in self._state.list_proposals("approved"):
671
+ if not prop.approved_by_rule:
672
+ continue
673
+ started = self._approved_age_start(prop)
674
+ if started is not None and now - started > self._settings.rule_approval_ttl:
675
+ try:
676
+ await self._writer.hub_transition(prop.id, "denied", decided_by=f"rule-expired:{prop.approved_by_rule}")
677
+ except (InvalidTransition, NotFound):
678
+ continue
679
+
680
+ async def _step_ttl(self) -> None:
681
+ now = self._now()
682
+ for prop in self._state.list_proposals("pending"):
683
+ if now - prop.created > self._settings.proposal_ttl:
684
+ try:
685
+ await self._writer.hub_transition(prop.id, "denied", decided_by="expired:ttl")
686
+ except (InvalidTransition, NotFound):
687
+ continue
688
+
689
+ async def _step_repair(self) -> None:
690
+ for rule in self._book.rules():
691
+ if rule.status != "active":
692
+ await self._deny_open_proposals(rule.id, self._denial_for(rule))
693
+ now = self._now()
694
+ for pid in self._ledger.incomplete_proposals():
695
+ prop = self._state.get_proposal(pid)
696
+ if prop is not None and prop.status == "done":
697
+ await self._store.transact(lambda tx, pid=pid: rb.complete_use(tx, pid, now))
698
+ self._ledger.completed(pid, now)
699
+
700
+ async def _step_reload(self) -> None:
701
+ await self._reload(announce=True)
702
+
703
+ async def _step_openings(self) -> None:
704
+ now = self._now()
705
+ for (incident_id, opening), seen in list(self._unsaved_openings.items()):
706
+ await self._store.transact(lambda tx, i=incident_id, o=opening, s=seen: rb.insert_opening(tx, i, o, s))
707
+ self._unsaved_openings.pop((incident_id, opening), None)
708
+ for incident_id, opening, _pid in self._ledger.completed_uses():
709
+ inc = self._state.get_incident(incident_id)
710
+ if inc is None or inc.opening <= opening:
711
+ continue
712
+ if self._ledger.note_opening(incident_id, inc.opening, now):
713
+ await self._store.transact(lambda tx, i=incident_id, o=inc.opening: rb.insert_opening(tx, i, o, now))
714
+
715
+ async def _step_prune(self) -> None:
716
+ now = self._now()
717
+ self._ledger.prune(now)
718
+ await self._store.transact(lambda tx: rb.prune_rows(tx, now - RETENTION_SECONDS))
719
+
720
+ # ---- views (R4.6, R7.5) --------------------------------------------------------------------------------------
721
+ def approval_of(self, prop: Proposal) -> dict[str, Any] | None:
722
+ """Who approved ``prop``. ``by`` and ``rule_id`` follow the ``approved_by_rule`` column only."""
723
+ rule_id = prop.approved_by_rule
724
+ if rule_id:
725
+ rule = self._book.get(rule_id)
726
+ now = self._now()
727
+ status_now: str | None = None
728
+ if rule is not None:
729
+ status_now = "expired" if self._expired_by_clock(rule) else rule.status
730
+ started = self._ledger.approved_at(prop.id)
731
+ expired = False
732
+ if prop.status == "approved":
733
+ begun = started if started is not None else prop.decided_at
734
+ too_old = begun is None or now - begun > self._settings.rule_approval_ttl
735
+ expired = too_old or status_now != "active"
736
+ return {"by": "rule", "rule_id": rule_id, "rule_status_now": status_now, "approved_at": started,
737
+ "expired": expired}
738
+ if prop.status in ("approved", "done"):
739
+ return {"by": "user", "rule_id": None, "rule_status_now": None, "approved_at": prop.decided_at,
740
+ "expired": False}
741
+ return None
742
+
743
+ def proposal_view(self, prop: Proposal) -> dict[str, Any]:
744
+ view = prop.to_full_dict()
745
+ view["approval"] = self.approval_of(prop)
746
+ return view
747
+
748
+ # ---- the hub seam (ProposalApprover) -----------------------------------------------------------------------
749
+ def shares_store(self, store: Store | None) -> bool:
750
+ return store is not None and store is self._store
751
+
752
+ def _active_of(self, incident_id: str) -> str | None:
753
+ for status in ("pending", "approved"):
754
+ for prop in self._state.list_proposals(status):
755
+ if prop.incident_id == incident_id:
756
+ return prop.id
757
+ return None
758
+
759
+ def prepare(self, ctx: CreateContext) -> ApprovalPlan:
760
+ """Validate, enforce limits, evaluate the rules, reserve quota. Synchronous and await-free."""
761
+ now = self._now()
762
+ service = self._registry.get(ctx.service_id) if ctx.service_id else None
763
+ live_folder = service.code_folder if service is not None else None
764
+ extra = validate_new_proposal(ctx.extra, code_folder=live_folder) # raises before anything is reserved
765
+ limit_token = self._limits.reserve(ctx.incident_id, ctx.service_id or "unassigned", now,
766
+ enforce=ctx.enforce_limits, active_of=self._active_of)
767
+ try:
768
+ return self._decide_plan(ctx, extra, now, live_folder, limit_token)
769
+ except BaseException:
770
+ self._limits.release(limit_token)
771
+ raise
772
+
773
+ def _decide_plan(self, ctx: CreateContext, extra: dict[str, object], now: float, live_folder: str | None,
774
+ limit_token: int) -> ApprovalPlan:
775
+ files = tuple(str(f) for f in (extra.get("files") or ()))
776
+ # The first sighting of a reopened opening is recorded whether or not any rule exists (O2, H1).
777
+ first_seen: float | None = None
778
+ prior: str | None = None
779
+ if ctx.opening > 1 and any(u.opening < ctx.opening for u in self._ledger.uses_of(ctx.incident_id)):
780
+ if self._ledger.note_opening(ctx.incident_id, ctx.opening, now):
781
+ first_seen = now
782
+ self._unsaved_openings[(ctx.incident_id, ctx.opening)] = now
783
+ prior = self._ledger.cooldown_for(ctx.incident_id, ctx.opening, self._settings.autofix_cooldown)
784
+ live = [r for r in self._book.rules(service_id=ctx.service_id) if r.status == "active"] if ctx.service_id else []
785
+ kind: str = "pending"
786
+ checks: tuple[RuleCheck, ...] = ()
787
+ rule_id: str | None = None
788
+ token = 0
789
+ remaining_hour = remaining_incident = None
790
+ paused_skip = False
791
+ if self._book.paused:
792
+ paused_skip = bool(live)
793
+ elif live:
794
+ try:
795
+ problem: str | None = None
796
+ if files and live_folder:
797
+ found = check_files(live_folder, files, protected_dirs=self._protected)
798
+ problem = found[0].code if found else None
799
+ mctx = MatchContext(
800
+ now=now, paused=False, kind=extra.get("kind") if isinstance(extra.get("kind"), str) else None,
801
+ service_id=ctx.service_id, signature=ctx.signature, category=ctx.category, severity=ctx.severity,
802
+ files=files or None, estimated_lines=extra.get("estimated_lines"), # type: ignore[arg-type]
803
+ verification=extra.get("verification"), # type: ignore[arg-type]
804
+ file_problem=problem, live_code_folder=live_folder, cooldown_active=prior is not None)
805
+ rule, checks = first_match(live, mctx,
806
+ lambda rid: self._ledger.usage(rid, ctx.incident_id, ctx.opening, now))
807
+ if rule is not None:
808
+ usage = self._ledger.usage(rule.id, ctx.incident_id, ctx.opening, now)
809
+ token = self._ledger.reserve(rule.id, ctx.incident_id, ctx.opening, now)
810
+ kind, rule_id = "auto", rule.id
811
+ remaining_hour = max(0, rule.max_per_hour - usage.hour - 1)
812
+ remaining_incident = max(0, rule.max_per_incident - usage.incident_opening - 1)
813
+ elif prior is not None and any(c.failed == "cooldown" for c in checks):
814
+ kind = "cooldown"
815
+ rule_id = next(c.rule_id for c in checks if c.failed == "cooldown")
816
+ except Exception: # noqa: BLE001 - a failure in matching is a refusal, never an approval
817
+ log.exception("rule matching failed; the proposal stays pending")
818
+ kind, rule_id, token = "pending", None, 0
819
+ checks = (RuleCheck(live[0].id, "error"),)
820
+ return ApprovalPlan(
821
+ kind=kind, extra=dict(extra), rule_id=rule_id, checks=checks, incident_id=ctx.incident_id, # type: ignore[arg-type]
822
+ service_id=ctx.service_id, opening=ctx.opening, files=files, remaining_hour=remaining_hour,
823
+ remaining_incident=remaining_incident, prior_proposal_id=prior, reserved_at=now,
824
+ opening_first_seen=first_seen, token=token, limit_token=limit_token, paused_skip=paused_skip,
825
+ audit_append=self._store.audit.append_tx)
826
+
827
+ def confirm(self, plan: ApprovalPlan, prop: Proposal) -> str | None:
828
+ """After the commit and the mirror update: bind the reservation, re-read the rule (review M1)."""
829
+ self._limits.commit(plan.limit_token)
830
+ if plan.opening_first_seen is not None:
831
+ self._unsaved_openings.pop((plan.incident_id, plan.opening), None)
832
+ if plan.kind != "auto" or plan.rule_id is None:
833
+ return None
834
+ self._ledger.bind(plan.token, prop.id)
835
+ rule = self._book.get(plan.rule_id)
836
+ if rule is None:
837
+ return f"rule-suspended:{plan.rule_id}"
838
+ if self._expired_by_clock(rule):
839
+ return f"rule-expired:{plan.rule_id}"
840
+ if rule.status != "active":
841
+ return self._denial_for(rule)
842
+ return None
843
+
844
+ def abort(self, plan: ApprovalPlan) -> None:
845
+ self._limits.release(plan.limit_token)
846
+ if plan.token:
847
+ self._ledger.release(plan.token)
848
+
849
+ async def persist(self, plan: ApprovalPlan, prop: Proposal) -> None:
850
+ """Bare hub: the plan's rows in the manager's own transaction. Never raises."""
851
+ try:
852
+ await self._store.transact(lambda tx: plan.write_in_tx(tx, prop))
853
+ self._unsaved_openings.pop((plan.incident_id, plan.opening), None)
854
+ except Exception: # noqa: BLE001
855
+ self._warn_once_a_minute("could not persist the auto-approval record of %s; it stays in memory", prop.id)
856
+
857
+ def line_for(self, plan: ApprovalPlan, base_line: str, prop: Proposal) -> str:
858
+ if plan.kind == "auto" and plan.rule_id is not None:
859
+ if prop.status == "denied":
860
+ reason = {"rule-revoked": "was revoked", "rule-suspended": "is suspended",
861
+ "rule-expired": "has expired"}.get(prop.decided_by.split(":", 1)[0], "is no longer active")
862
+ return rule_line("denied", prop.id, plan.rule_id, "hub", reason)
863
+ return auto_approved_line(prop.id, plan.rule_id, plan.service_id or "", prop.action)
864
+ if plan.kind == "cooldown" and plan.prior_proposal_id:
865
+ return base_line + cooldown_note(plan.prior_proposal_id, plan.rule_id or "")
866
+ return base_line
867
+
868
+ async def before_complete(self, pid: str) -> None:
869
+ await self.expire_due()
870
+
871
+ def validate_completion(self, pid: str, extra: Mapping[str, object] | None) -> Mapping[str, object]:
872
+ clean = validate_completion(extra)
873
+ prop = self._state.get_proposal(pid)
874
+ if prop is not None and prop.approved_by_rule and prop.status == "approved":
875
+ started = self._approved_age_start(prop)
876
+ if started is not None and self._now() - started > self._settings.rule_approval_ttl:
877
+ raise ProposalExpired(f"the approval of {pid} expired; propose the fix again")
878
+ return clean
879
+
880
+ async def after_complete(self, prop: Proposal, extra: Mapping[str, object]) -> None:
881
+ """R6.5 and R6.6: check what was changed against the rule. Never raises."""
882
+ try:
883
+ await self._after_complete(prop, extra)
884
+ except asyncio.CancelledError:
885
+ raise
886
+ except Exception: # noqa: BLE001
887
+ log.exception("completion check of %s failed", prop.id)
888
+
889
+ async def _after_complete(self, prop: Proposal, extra: Mapping[str, object]) -> None:
890
+ rule_id = prop.approved_by_rule
891
+ if not rule_id:
892
+ return # a user approval is not checked
893
+ now = self._now()
894
+ self._ledger.completed(prop.id, now)
895
+ rule = self._book.get(rule_id)
896
+ files = list(extra.get("files_changed") or prop.files_changed or [])
897
+ lines = extra.get("lines_changed", prop.lines_changed)
898
+ result = extra.get("verification_result", prop.verification_result)
899
+ reason: str | None = None
900
+ if rule is not None:
901
+ if files and check_files(rule.code_folder, files, protected_dirs=self._protected):
902
+ reason = "completion_out_of_scope"
903
+ elif len(files) > rule.max_files:
904
+ reason = "files_over_limit"
905
+ elif isinstance(lines, int) and lines > rule.max_lines:
906
+ reason = "lines_over_limit"
907
+ elif result == "failed":
908
+ reason = "verification_failed"
909
+ unverified = not files and lines is None and result is None
910
+ action = "completion_unverified" if unverified else "completion_checked"
911
+ sid = prop.service_id
912
+ # Only an active rule is suspended; a rule already suspended, revoked or expired keeps its state and
913
+ # gets no second rule_suspended row or announcement.
914
+ suspend = reason is not None and rule is not None and rule.status == "active" and not self._expired_by_clock(rule)
915
+
916
+ def write(tx: Tx) -> None:
917
+ rb.complete_use(tx, prop.id, now)
918
+ self._audit(tx, "hub", action if reason is None else "completion_checked", prop.id,
919
+ "" if reason is None else f"violation={reason}", service_id=sid, rule_id=rule_id,
920
+ proposal_id=prop.id)
921
+ if suspend and rb.suspend_row(tx, rule_id, reason, now):
922
+ self._audit(tx, "hub", "rule_suspended", rule_id, reason, service_id=sid, rule_id=rule_id)
923
+
924
+ if suspend:
925
+ self._book.replace(dataclasses.replace(rule, status="suspended", status_reason=reason, updated_at=now))
926
+ self._book.mark_dirty(rule_id)
927
+ try:
928
+ await self._store.transact(write)
929
+ if suspend:
930
+ self._book.clear_dirty(rule_id)
931
+ except StoreError:
932
+ self._warn_once_a_minute("could not record the completion check of %s", prop.id)
933
+ if suspend:
934
+ await self._deny_open_proposals(rule_id, f"rule-suspended:{rule_id}")
935
+ await self._say(rule_line("suspended", rule_id, rule.service_id, "hub", reason))