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,107 @@
1
+ """Rule matching. Pure: no clock, store or registry is read here.
2
+
3
+ The requirement lists conditions (a) to (m); they are numbered 4.2.1 to 4.2.13 in the order below
4
+ (design L8). The first failing condition is the one returned.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Callable, Sequence
9
+ from dataclasses import dataclass
10
+ from enum import Enum
11
+
12
+ from .models import Rule, RuleCheck
13
+
14
+
15
+ class Condition(str, Enum):
16
+ PAUSED = "paused" # 4.2.1 (a)
17
+ INACTIVE = "inactive" # 4.2.2 (b) status active and now < expires_at
18
+ KIND = "kind" # 4.2.3 (c)
19
+ SERVICE = "service" # 4.2.4 (d)
20
+ MATCH = "match" # 4.2.5 (e)
21
+ SEVERITY = "severity" # 4.2.6 (f)
22
+ HOUR_QUOTA = "hour_quota" # 4.2.7 (g)
23
+ INCIDENT_QUOTA = "incident_quota" # 4.2.8 (h)
24
+ FILES = "files" # 4.2.9 (i)
25
+ LINES = "lines" # 4.2.10 (j)
26
+ VERIFICATION = "verification" # 4.2.11 (k)
27
+ CODE_FOLDER = "code_folder" # 4.2.12 (l)
28
+ COOLDOWN = "cooldown" # 4.2.13 (m)
29
+
30
+
31
+ RULE_CONDITIONS = tuple(Condition)
32
+ ERROR = "error"
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class RuleUsage:
37
+ hour: int
38
+ incident_opening: int
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class MatchContext:
43
+ now: float
44
+ paused: bool
45
+ kind: str | None
46
+ service_id: str | None
47
+ signature: str
48
+ category: str
49
+ severity: int
50
+ files: tuple[str, ...] | None
51
+ estimated_lines: int | None
52
+ verification: str | None
53
+ file_problem: str | None # first FileProblem code for ``files``, computed once per proposal
54
+ live_code_folder: str | None # the service's code folder right now
55
+ cooldown_active: bool
56
+
57
+
58
+ def match_rule(rule: Rule, ctx: MatchContext, usage: RuleUsage) -> str | None:
59
+ """None when the rule covers the proposal, else the code of the first failing condition. Never raises."""
60
+ try:
61
+ return _match(rule, ctx, usage)
62
+ except Exception: # noqa: BLE001 - total: a surprise means "no match"
63
+ return ERROR
64
+
65
+
66
+ def _match(rule: Rule, ctx: MatchContext, usage: RuleUsage) -> str | None:
67
+ if ctx.paused:
68
+ return Condition.PAUSED.value
69
+ if rule.status != "active" or ctx.now >= rule.expires_at:
70
+ return Condition.INACTIVE.value
71
+ if ctx.kind != "code_change":
72
+ return Condition.KIND.value
73
+ if ctx.service_id is None or ctx.service_id != rule.service_id:
74
+ return Condition.SERVICE.value
75
+ wanted = ctx.signature if rule.match_type == "signature" else ctx.category
76
+ if rule.match_type not in ("signature", "category") or wanted != rule.match_value:
77
+ return Condition.MATCH.value
78
+ if ctx.severity < max(3, rule.most_urgent_severity):
79
+ return Condition.SEVERITY.value
80
+ if usage.hour >= rule.max_per_hour:
81
+ return Condition.HOUR_QUOTA.value
82
+ if usage.incident_opening >= rule.max_per_incident:
83
+ return Condition.INCIDENT_QUOTA.value
84
+ if (not ctx.files or len(ctx.files) > rule.max_files or ctx.file_problem is not None
85
+ or not all(isinstance(f, str) for f in ctx.files)):
86
+ return Condition.FILES.value
87
+ if ctx.estimated_lines is None or ctx.estimated_lines > rule.max_lines:
88
+ return Condition.LINES.value
89
+ if not (ctx.verification or "").strip():
90
+ return Condition.VERIFICATION.value
91
+ if ctx.live_code_folder is None or ctx.live_code_folder != rule.code_folder:
92
+ return Condition.CODE_FOLDER.value
93
+ if ctx.cooldown_active:
94
+ return Condition.COOLDOWN.value
95
+ return None
96
+
97
+
98
+ def first_match(rules: Sequence[Rule], ctx: MatchContext,
99
+ usage_of: Callable[[str], RuleUsage]) -> tuple[Rule | None, tuple[RuleCheck, ...]]:
100
+ """Walk the rules by ``seq``; stop at the first that matches. ``checks`` lists every rule examined."""
101
+ checks: list[RuleCheck] = []
102
+ for rule in sorted(rules, key=lambda r: r.seq):
103
+ failed = match_rule(rule, ctx, usage_of(rule.id))
104
+ checks.append(RuleCheck(rule.id, failed))
105
+ if failed is None:
106
+ return rule, tuple(checks)
107
+ return None, tuple(checks)
@@ -0,0 +1,251 @@
1
+ """Rule, request and plan models plus the constants every other file shares."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import math
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Literal
9
+
10
+ from chimericmesh.store.models import Proposal
11
+ from chimericmesh.store.tx import Tx
12
+
13
+ from .limits import MAX_PROPOSALS_PER_SERVICE_HOUR
14
+
15
+ log = logging.getLogger("chimericmesh.approvals")
16
+
17
+ # A test pins this set against the categories diagnostics can emit.
18
+ CATEGORIES = ("memory", "disk", "network", "security", "crash", "unknown")
19
+ MATCH_TYPES = ("signature", "category")
20
+ RULE_STATUSES = ("active", "suspended", "revoked", "expired")
21
+ VERIFICATION_RESULTS = ("passed", "failed", "not_run")
22
+ MAX_RULES_PER_SERVICE, MAX_RULES_TOTAL = 20, 100
23
+
24
+ DAY = 86400.0
25
+ DEFAULT_EXPIRY_SECONDS = 7 * DAY
26
+ MAX_EXPIRY_SECONDS = 30 * DAY
27
+ RULE_APPROVAL_TTL = 1800.0 # a rule approval stays usable this long (R6.4)
28
+ HOUR = 3600.0
29
+
30
+ BOUNDS: dict[str, dict[str, int]] = {
31
+ "most_urgent_severity": {"min": 3, "max": 4, "default": 3},
32
+ "max_per_hour": {"min": 1, "max": MAX_PROPOSALS_PER_SERVICE_HOUR, "default": 3},
33
+ "max_per_incident": {"min": 1, "max": 3, "default": 1},
34
+ "max_files": {"min": 1, "max": 20, "default": 5},
35
+ "max_lines": {"min": 1, "max": 500, "default": 100},
36
+ "expires_days": {"min": 0, "max": 30, "default": 7},
37
+ }
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class Rule:
42
+ id: str
43
+ seq: int
44
+ service_id: str
45
+ match_type: str
46
+ match_value: str
47
+ most_urgent_severity: int
48
+ expires_at: float
49
+ max_per_hour: int
50
+ max_per_incident: int
51
+ max_files: int
52
+ max_lines: int
53
+ status: str
54
+ status_reason: str
55
+ created_by: str
56
+ created_at: float
57
+ updated_at: float
58
+ source_proposal_id: str | None
59
+ note: str
60
+ use_count: int
61
+ code_folder: str
62
+
63
+ def to_dict(self, *, now: float, uses_last_hour: int) -> dict[str, Any]:
64
+ status = self.status
65
+ if status in ("active", "suspended") and now >= self.expires_at:
66
+ status = "expired" # computed on read, before the sweep has run
67
+ return {
68
+ "id": self.id, "service_id": self.service_id, "match_type": self.match_type,
69
+ "match_value": self.match_value, "most_urgent_severity": self.most_urgent_severity,
70
+ "expires_at": self.expires_at, "max_per_hour": self.max_per_hour,
71
+ "max_per_incident": self.max_per_incident, "max_files": self.max_files,
72
+ "max_lines": self.max_lines, "status": status, "status_reason": self.status_reason,
73
+ "created_by": self.created_by, "created_at": self.created_at, "updated_at": self.updated_at,
74
+ "source_proposal_id": self.source_proposal_id, "note": self.note, "use_count": self.use_count,
75
+ "code_folder": self.code_folder, "uses_last_hour": uses_last_hour,
76
+ "remaining_this_hour": max(0, self.max_per_hour - uses_last_hour),
77
+ }
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class RuleFields:
82
+ """Create input, already validated."""
83
+ service_id: str
84
+ match_type: str
85
+ match_value: str
86
+ most_urgent_severity: int = 3
87
+ expires_at: float | None = None
88
+ max_per_hour: int = 3
89
+ max_per_incident: int = 1
90
+ max_files: int = 5
91
+ max_lines: int = 100
92
+ note: str = ""
93
+
94
+
95
+ @dataclass(frozen=True, slots=True)
96
+ class RulePatch:
97
+ """None means unchanged."""
98
+ most_urgent_severity: int | None = None
99
+ expires_at: float | None = None
100
+ max_per_hour: int | None = None
101
+ max_per_incident: int | None = None
102
+ max_files: int | None = None
103
+ max_lines: int | None = None
104
+ note: str | None = None
105
+
106
+
107
+ @dataclass(frozen=True, slots=True)
108
+ class RuleDefaults:
109
+ service_id: str
110
+ match_type: str
111
+ match_value: str
112
+ most_urgent_severity: int
113
+ expires_at: float
114
+ max_per_hour: int
115
+ max_per_incident: int
116
+ max_files: int
117
+ max_lines: int
118
+ note: str
119
+ source_proposal_id: str
120
+
121
+ def to_dict(self) -> dict[str, Any]:
122
+ return {name: getattr(self, name) for name in self.__slots__}
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class CreateContext:
127
+ """Built by ``Hub.create_proposal`` on the loop thread."""
128
+ incident_id: str
129
+ service_id: str | None
130
+ signature: str
131
+ category: str
132
+ severity: int
133
+ opening: int
134
+ action: str
135
+ details: str
136
+ extra: Mapping[str, object]
137
+ enforce_limits: bool
138
+
139
+
140
+ @dataclass(frozen=True, slots=True)
141
+ class RuleCheck:
142
+ rule_id: str
143
+ failed: str | None # a condition code, or None for the rule that matched
144
+
145
+
146
+ AuditAppend = Callable[..., int]
147
+
148
+
149
+ @dataclass(frozen=True, slots=True)
150
+ class ApprovalPlan:
151
+ """Immutable; crosses to the writer thread."""
152
+ kind: Literal["pending", "auto", "cooldown"]
153
+ extra: Mapping[str, object]
154
+ rule_id: str | None
155
+ checks: tuple[RuleCheck, ...]
156
+ incident_id: str
157
+ service_id: str | None
158
+ opening: int
159
+ files: tuple[str, ...]
160
+ remaining_hour: int | None
161
+ remaining_incident: int | None
162
+ prior_proposal_id: str | None
163
+ reserved_at: float
164
+ opening_first_seen: float | None
165
+ token: int
166
+ limit_token: int = 0
167
+ paused_skip: bool = False
168
+ audit_append: AuditAppend | None = field(default=None, compare=False, repr=False)
169
+
170
+ def write_in_tx(self, tx: Tx, prop: Proposal) -> None:
171
+ """Store-backed commit work, on the writer thread, using only ``tx`` and this plan."""
172
+ from .rulebook import insert_opening, insert_use, bump_use_count # local: keeps models import-light
173
+
174
+ audit = self.audit_append
175
+ if self.opening_first_seen is not None:
176
+ insert_opening(tx, self.incident_id, self.opening, self.opening_first_seen)
177
+ if self.kind == "auto" and self.rule_id is not None:
178
+ insert_use(tx, rule_id=self.rule_id, proposal_id=prop.id, incident_id=self.incident_id,
179
+ opening=self.opening, service_id=self.service_id, approved_at=self.reserved_at)
180
+ bump_use_count(tx, self.rule_id)
181
+ if audit is None:
182
+ return
183
+ sid = self.service_id
184
+ if self.kind == "auto" and self.rule_id is not None:
185
+ files = ",".join(self.files)
186
+ audit(tx, f"rule:{self.rule_id}", "proposal_auto_approved", prop.id,
187
+ f"incident={self.incident_id} files={files} remaining_hour={self.remaining_hour} "
188
+ f"remaining_incident={self.remaining_incident}",
189
+ service_id=sid, rule_id=self.rule_id, proposal_id=prop.id)
190
+ elif self.kind == "cooldown":
191
+ rule = self.rule_id
192
+ audit(tx, "hub", "autofix_cooldown", prop.id,
193
+ f"earlier={self.prior_proposal_id} rule={rule} reopened_at={self.opening_first_seen}",
194
+ service_id=sid, rule_id=rule, proposal_id=prop.id)
195
+ else:
196
+ if self.paused_skip:
197
+ audit(tx, "hub", "auto_approval_skipped", prop.id, "condition=paused",
198
+ service_id=sid, proposal_id=prop.id)
199
+ for check in self.checks:
200
+ if check.failed is not None:
201
+ audit(tx, "hub", "auto_approval_skipped", prop.id, f"condition={check.failed}",
202
+ service_id=sid, rule_id=check.rule_id, proposal_id=prop.id)
203
+
204
+
205
+ @dataclass(frozen=True, slots=True)
206
+ class ApprovalStatus:
207
+ paused: bool
208
+ paused_by: str
209
+ paused_at: float | None
210
+ active_rules: int
211
+ suspended_rules: int
212
+ cooldown_seconds: float
213
+ proposal_ttl_hours: float
214
+ bounds: Mapping[str, Mapping[str, int]] = field(default_factory=lambda: BOUNDS)
215
+
216
+ def to_dict(self) -> dict[str, Any]:
217
+ return {
218
+ "paused": self.paused, "paused_by": self.paused_by, "paused_at": self.paused_at,
219
+ "active_rules": self.active_rules, "suspended_rules": self.suspended_rules,
220
+ "cooldown_seconds": self.cooldown_seconds, "proposal_ttl_hours": self.proposal_ttl_hours,
221
+ "bounds": {k: dict(v) for k, v in self.bounds.items()},
222
+ }
223
+
224
+
225
+ @dataclass(frozen=True, slots=True)
226
+ class ApprovalSettings:
227
+ autofix_cooldown: float = 86400.0
228
+ proposal_ttl: float = 24 * 3600.0
229
+ rule_approval_ttl: float = RULE_APPROVAL_TTL
230
+ sweep_interval: float = 60.0
231
+
232
+ @classmethod
233
+ def from_env(cls, environ: Mapping[str, str]) -> "ApprovalSettings":
234
+ cooldown = _env_number(environ, "CHIMERICMESH_AUTOFIX_COOLDOWN_SECONDS", 86400.0, 0.0, 2_592_000.0)
235
+ ttl_hours = _env_number(environ, "CHIMERICMESH_PROPOSAL_TTL_HOURS", 24.0, 1.0, 720.0)
236
+ return cls(autofix_cooldown=cooldown, proposal_ttl=ttl_hours * 3600.0)
237
+
238
+
239
+ def _env_number(environ: Mapping[str, str], name: str, default: float, low: float, high: float) -> float:
240
+ raw = environ.get(name)
241
+ if raw is None or not str(raw).strip():
242
+ return default
243
+ try:
244
+ value = float(str(raw).strip())
245
+ except ValueError:
246
+ log.warning("%s is not a number; using %s", name, default)
247
+ return default
248
+ if not math.isfinite(value) or not low <= value <= high:
249
+ log.warning("%s is outside %s to %s; using %s", name, low, high, default)
250
+ return default
251
+ return value
@@ -0,0 +1,36 @@
1
+ """The seam the hub uses: ``Hub`` knows this protocol, never the manager (M2)."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Awaitable, Callable, Mapping
5
+ from typing import Protocol
6
+
7
+ from chimericmesh.store import Store
8
+ from chimericmesh.store.models import Proposal
9
+
10
+ from .models import ApprovalPlan, CreateContext
11
+
12
+ AnnounceFn = Callable[[str], Awaitable[None]]
13
+ ClockFn = Callable[[], float]
14
+
15
+
16
+ class ProposalApprover(Protocol):
17
+ def prepare(self, ctx: CreateContext) -> ApprovalPlan:
18
+ """Synchronous and await-free. Raises ProposalInvalid, ActiveProposalExists, ProposalRateLimited."""
19
+
20
+ def shares_store(self, store: Store | None) -> bool: ...
21
+
22
+ async def persist(self, plan: ApprovalPlan, prop: Proposal) -> None:
23
+ """Bare hub: own transaction. Never raises."""
24
+
25
+ def confirm(self, plan: ApprovalPlan, prop: Proposal) -> str | None:
26
+ """Bind the reservation, then re-read the rule. A ``decided_by`` denial text, or None."""
27
+
28
+ def abort(self, plan: ApprovalPlan) -> None: ...
29
+
30
+ async def before_complete(self, pid: str) -> None: ...
31
+
32
+ def validate_completion(self, pid: str, extra: Mapping[str, object] | None) -> Mapping[str, object]: ...
33
+
34
+ async def after_complete(self, prop: Proposal, extra: Mapping[str, object]) -> None: ...
35
+
36
+ def line_for(self, plan: ApprovalPlan, base_line: str, prop: Proposal) -> str: ...
@@ -0,0 +1,220 @@
1
+ """REST routes of auto-approval. One of two files of this module that may import the web stack.
2
+
3
+ Widening operations (create, patch, enable, resume, rule from a proposal) depend on ``require_admin``.
4
+ Reduce operations (revoke, pause, withdraw) take no token and are never refused (R2.3). Nothing here, and
5
+ nothing in ``mcp_server.py``, lets the agent create or widen a rule.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Awaitable, Callable
10
+ from typing import Any, Literal
11
+
12
+ from fastapi import APIRouter, Depends, FastAPI, HTTPException, Query, Request
13
+ from fastapi.responses import JSONResponse
14
+ from pydantic import BaseModel, ConfigDict
15
+
16
+ from chimericmesh.services.deps import client_address, route_template
17
+ from chimericmesh.services.limiter import reduce_key
18
+ from chimericmesh.store.errors import InvalidTransition, NotFound
19
+
20
+ from .errors import (
21
+ ActiveProposalExists, ApprovalsError, ProposalExpired, ProposalInvalid, ProposalRateLimited, RuleConflict,
22
+ RuleInvalid, RuleLimitReached, RuleNotApplicable, RuleNotFound,
23
+ )
24
+ from .manager import ApprovalManager
25
+ from .validate import validate_rule_fields, validate_rule_patch
26
+
27
+ SERVICE_ID_MAX = 64
28
+
29
+
30
+ class _Strict(BaseModel):
31
+ model_config = ConfigDict(extra="forbid")
32
+
33
+
34
+ class RuleBody(_Strict):
35
+ service_id: str
36
+ match_type: str
37
+ match_value: str
38
+ most_urgent_severity: Any = None
39
+ expires_at: Any = None
40
+ max_per_hour: Any = None
41
+ max_per_incident: Any = None
42
+ max_files: Any = None
43
+ max_lines: Any = None
44
+ note: Any = None
45
+
46
+
47
+ class RulePatchBody(_Strict):
48
+ most_urgent_severity: Any = None
49
+ expires_at: Any = None
50
+ max_per_hour: Any = None
51
+ max_per_incident: Any = None
52
+ max_files: Any = None
53
+ max_lines: Any = None
54
+ note: Any = None
55
+
56
+
57
+ class RuleFromProposalBody(_Strict):
58
+ match_type: str | None = None
59
+ match_value: str | None = None
60
+ most_urgent_severity: Any = None
61
+ expires_at: Any = None
62
+ max_per_hour: Any = None
63
+ max_per_incident: Any = None
64
+ max_files: Any = None
65
+ max_lines: Any = None
66
+ note: Any = None
67
+
68
+
69
+ def _given(body: BaseModel) -> dict[str, Any]:
70
+ """Only the fields the caller sent (a null is treated as not sent)."""
71
+ return {k: v for k, v in body.model_dump().items() if v is not None}
72
+
73
+
74
+ def actor_of(request: Request) -> str:
75
+ return f"rest:{client_address(request)}"
76
+
77
+
78
+ def register_error_handlers(app: FastAPI) -> None:
79
+ """Map the module's errors to the status codes of the design's REST table."""
80
+
81
+ @app.exception_handler(ApprovalsError)
82
+ async def approvals_error(request: Request, exc: ApprovalsError):
83
+ if isinstance(exc, (RuleInvalid, ProposalInvalid)):
84
+ return JSONResponse({"detail": exc.reason, "field": exc.field}, status_code=422)
85
+ if isinstance(exc, ActiveProposalExists):
86
+ return JSONResponse({"detail": str(exc), "proposal_id": exc.proposal_id}, status_code=409)
87
+ if isinstance(exc, ProposalRateLimited):
88
+ return JSONResponse({"detail": str(exc)}, status_code=429,
89
+ headers={"Retry-After": str(exc.retry_after)})
90
+ if isinstance(exc, RuleNotFound):
91
+ return JSONResponse({"detail": "rule not found"}, status_code=404)
92
+ if isinstance(exc, (RuleConflict, RuleNotApplicable)):
93
+ return JSONResponse({"detail": exc.reason}, status_code=409)
94
+ if isinstance(exc, ProposalExpired):
95
+ return JSONResponse({"detail": "the approval expired"}, status_code=409)
96
+ if isinstance(exc, RuleLimitReached):
97
+ return JSONResponse({"detail": str(exc) or "too many rules"}, status_code=409)
98
+ return JSONResponse({"detail": "request refused"}, status_code=400)
99
+
100
+ @app.exception_handler(NotFound)
101
+ async def not_found(request: Request, exc: NotFound):
102
+ return JSONResponse({"detail": "not found"}, status_code=404)
103
+
104
+
105
+ def build_router(manager: ApprovalManager, access: Any, require_admin: Callable[[Request], Awaitable[None]],
106
+ *, state: Any = None) -> APIRouter:
107
+ """The rule routes. ``state`` (the hub) is only used to read proposals for the view."""
108
+ router = APIRouter()
109
+
110
+ async def admin(request: Request) -> None:
111
+ """``require_admin`` plus a ``rule_auth_failed`` row on 401 (R2.1, R2.5). Nothing is written on 429."""
112
+ try:
113
+ await require_admin(request)
114
+ except HTTPException as exc:
115
+ if exc.status_code == 401:
116
+ try:
117
+ await manager.audit_log.append(
118
+ f"client:{client_address(request)}", "rule_auth_failed", route_template(request), "",
119
+ rule_id=request.path_params.get("rule_id"))
120
+ except Exception: # noqa: BLE001 - the 401 matters more than its audit row
121
+ pass
122
+ raise
123
+
124
+ admin_dep = [Depends(admin)]
125
+
126
+ def rule_or_404(rule_id: str):
127
+ rule = manager.rule(rule_id)
128
+ if rule is None:
129
+ raise RuleNotFound(rule_id)
130
+ return rule
131
+
132
+ def view(rule) -> dict[str, Any]:
133
+ return manager.rule_dict(rule)
134
+
135
+ def proposal_view(prop) -> dict[str, Any]:
136
+ return manager.proposal_view(prop)
137
+
138
+ # ---- reads (no token) ------------------------------------------------------------------------------------
139
+ @router.get("/api/rules")
140
+ async def list_rules(service_id: str | None = Query(None, max_length=SERVICE_ID_MAX),
141
+ status: Literal["active", "suspended", "revoked", "expired"] | None = None):
142
+ await manager.expire_due()
143
+ return [view(r) for r in manager.rules(service_id=service_id, status=status)]
144
+
145
+ @router.get("/api/rules/{rule_id}")
146
+ async def get_rule(rule_id: str):
147
+ await manager.expire_due()
148
+ return view(rule_or_404(rule_id))
149
+
150
+ @router.get("/api/approvals/status")
151
+ async def approvals_status():
152
+ return manager.status().to_dict()
153
+
154
+ @router.get("/api/audit")
155
+ async def audit(service_id: str | None = Query(None, max_length=SERVICE_ID_MAX),
156
+ rule_id: str | None = Query(None, max_length=100),
157
+ proposal_id: str | None = Query(None, max_length=100),
158
+ limit: int = Query(100, ge=1, le=500), before: int | None = Query(None, ge=0)):
159
+ return await manager.audit_log.read(limit, before, service_id=service_id, rule_id=rule_id,
160
+ proposal_id=proposal_id)
161
+
162
+ @router.get("/api/proposals/{pid}/rule-defaults")
163
+ async def rule_defaults(pid: str):
164
+ await manager.expire_due()
165
+ return manager.rule_defaults(pid).to_dict()
166
+
167
+ # ---- widening operations (token) -------------------------------------------------------------------------
168
+ @router.post("/api/rules", status_code=201, dependencies=admin_dep)
169
+ async def create_rule(body: RuleBody, request: Request):
170
+ fields = validate_rule_fields(_given(body), now=manager.now())
171
+ return view(await manager.create_rule(fields, actor=actor_of(request)))
172
+
173
+ @router.patch("/api/rules/{rule_id}", dependencies=admin_dep)
174
+ async def patch_rule(rule_id: str, body: RulePatchBody, request: Request):
175
+ rule = rule_or_404(rule_id)
176
+ patch = validate_rule_patch(_given(body), now=manager.now(), created_at=rule.created_at)
177
+ return view(await manager.patch_rule(rule_id, patch, actor=actor_of(request)))
178
+
179
+ @router.post("/api/rules/{rule_id}/enable", dependencies=admin_dep)
180
+ async def enable_rule(rule_id: str, request: Request):
181
+ rule_or_404(rule_id)
182
+ return view(await manager.enable_rule(rule_id, actor=actor_of(request)))
183
+
184
+ @router.post("/api/rules/resume", dependencies=admin_dep)
185
+ async def resume(request: Request):
186
+ return (await manager.resume(actor=actor_of(request))).to_dict()
187
+
188
+ @router.post("/api/proposals/{pid}/rule", status_code=201, dependencies=admin_dep)
189
+ async def rule_from_proposal(pid: str, request: Request, body: RuleFromProposalBody | None = None):
190
+ overrides = _given(body) if body is not None else {}
191
+ return view(await manager.create_rule_from_proposal(pid, overrides, actor=actor_of(request)))
192
+
193
+ # ---- reduce operations (no token, never refused) ---------------------------------------------------------
194
+ @router.post("/api/rules/pause")
195
+ async def pause_all(request: Request):
196
+ who = client_address(request)
197
+ return (await manager.pause(actor=actor_of(request), key=reduce_key("rest", who))).to_dict()
198
+
199
+ @router.post("/api/rules/{rule_id}/revoke")
200
+ async def revoke(rule_id: str, request: Request):
201
+ rule_or_404(rule_id)
202
+ who = client_address(request)
203
+ return view(await manager.revoke_rule(rule_id, actor=actor_of(request), key=reduce_key("rest", who)))
204
+
205
+ @router.post("/api/rules/{rule_id}/pause")
206
+ async def pause_rule(rule_id: str, request: Request):
207
+ rule_or_404(rule_id)
208
+ who = client_address(request)
209
+ return view(await manager.pause_rule(rule_id, actor=actor_of(request), key=reduce_key("rest", who)))
210
+
211
+ @router.post("/api/proposals/{pid}/withdraw")
212
+ async def withdraw(pid: str, request: Request):
213
+ who = client_address(request)
214
+ try:
215
+ prop = await manager.withdraw(pid, actor=actor_of(request), key=reduce_key("rest", who))
216
+ except InvalidTransition:
217
+ raise HTTPException(409, "proposal cannot be withdrawn") from None
218
+ return proposal_view(prop)
219
+
220
+ return router