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,337 @@
1
+ """The rule mirror (loop thread) and the literal-SQL helpers that take a ``Tx`` (writer thread).
2
+
3
+ All SQL here is a module-level constant; values go in as parameters (the store's SQL rule).
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import dataclasses
8
+ import sqlite3
9
+ from collections.abc import Iterable
10
+ from dataclasses import dataclass
11
+
12
+ from chimericmesh.store import Store, Tx
13
+ from chimericmesh.store.tx import format_id
14
+
15
+ from .errors import ApprovalsNotMigrated
16
+ from .models import Rule
17
+
18
+ # active < suspended < revoked = expired: a merge may only move up this ladder.
19
+ RANK = {"active": 0, "suspended": 1, "revoked": 2, "expired": 2}
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class Snapshot:
24
+ """What one reload read from the database."""
25
+ rules: tuple[Rule, ...]
26
+ paused: bool
27
+ paused_by: str
28
+ paused_at: float | None
29
+
30
+
31
+ class RuleBook:
32
+ """Mirror of the rules table plus the ordering state of "Rule state ordering" (review H2)."""
33
+
34
+ def __init__(self) -> None:
35
+ self._rules: dict[str, Rule] = {}
36
+ self._version: dict[str, int] = {}
37
+ self._changed_at: dict[str, int] = {}
38
+ self.epoch = 0
39
+ self.dirty: set[str] = set()
40
+ self.paused = False
41
+ self.paused_by = ""
42
+ self.paused_at: float | None = None
43
+ self.pause_version = 0
44
+ self._pause_changed_at = 0
45
+ self.paused_dirty = False
46
+
47
+ # ---- reads ----------------------------------------------------------------------------------
48
+ def rules(self, *, service_id: str | None = None, status: str | None = None) -> list[Rule]:
49
+ found = [r for r in self._rules.values()
50
+ if (service_id is None or r.service_id == service_id) and (status is None or r.status == status)]
51
+ return sorted(found, key=lambda r: r.seq)
52
+
53
+ def get(self, rule_id: str) -> Rule | None:
54
+ return self._rules.get(rule_id)
55
+
56
+ def version(self, rule_id: str) -> int:
57
+ return self._version.get(rule_id, 0)
58
+
59
+ def __len__(self) -> int:
60
+ return len(self._rules)
61
+
62
+ # ---- changes ---------------------------------------------------------------------------------
63
+ def load(self, rules: Iterable[Rule], *, paused: bool = False, paused_by: str = "",
64
+ paused_at: float | None = None) -> None:
65
+ self._rules = {r.id: r for r in sorted(rules, key=lambda r: r.seq)}
66
+ self._version = {rid: 1 for rid in self._rules}
67
+ self._changed_at = {rid: 0 for rid in self._rules}
68
+ self.paused, self.paused_by, self.paused_at = paused, paused_by, paused_at
69
+
70
+ def replace(self, rule: Rule) -> None:
71
+ """Swap a whole rule object. Bumps that rule's version and the epoch."""
72
+ self.epoch += 1
73
+ self._rules[rule.id] = rule
74
+ self._version[rule.id] = self._version.get(rule.id, 0) + 1
75
+ self._changed_at[rule.id] = self.epoch
76
+
77
+ def set_paused(self, paused: bool, by: str, at: float | None) -> None:
78
+ self.epoch += 1
79
+ self.paused, self.paused_by, self.paused_at = paused, by, at
80
+ self.pause_version += 1
81
+ self._pause_changed_at = self.epoch
82
+
83
+ def mark_dirty(self, rule_id: str) -> None:
84
+ self.dirty.add(rule_id)
85
+
86
+ def clear_dirty(self, rule_id: str) -> None:
87
+ self.dirty.discard(rule_id)
88
+
89
+ def mark_paused_dirty(self) -> None:
90
+ self.paused_dirty = True
91
+
92
+ def clear_paused_dirty(self) -> None:
93
+ self.paused_dirty = False
94
+
95
+ def merge(self, snapshot: Snapshot, started_epoch: int) -> list[str]:
96
+ """Tighten-only merge of a reload (rule 5). Returns the ids whose mirror entry changed.
97
+
98
+ ``started_epoch`` is the epoch recorded before the read began. A rule that is dirty, or changed in
99
+ the mirror after that, is kept whole; otherwise the stricter status of mirror and snapshot wins and
100
+ the other fields come from the snapshot. The pause flag can go false to true, never back.
101
+ """
102
+ changed: list[str] = []
103
+ for snap_rule in snapshot.rules:
104
+ mine = self._rules.get(snap_rule.id)
105
+ if mine is None:
106
+ self._rules[snap_rule.id] = snap_rule
107
+ self._version[snap_rule.id] = 1
108
+ self._changed_at[snap_rule.id] = 0
109
+ changed.append(snap_rule.id)
110
+ continue
111
+ if snap_rule.id in self.dirty or self._changed_at.get(snap_rule.id, 0) > started_epoch:
112
+ continue
113
+ if RANK[snap_rule.status] > RANK[mine.status] or snap_rule.status == mine.status:
114
+ merged = snap_rule
115
+ else:
116
+ merged = dataclasses.replace(snap_rule, status=mine.status, status_reason=mine.status_reason)
117
+ if merged != mine:
118
+ self._rules[mine.id] = merged
119
+ self._version[mine.id] = self._version.get(mine.id, 0) + 1
120
+ self.epoch += 1
121
+ self._changed_at[mine.id] = self.epoch
122
+ changed.append(mine.id)
123
+ if not (self.paused_dirty or self._pause_changed_at > started_epoch):
124
+ if snapshot.paused and not self.paused:
125
+ self.paused, self.paused_by, self.paused_at = True, snapshot.paused_by, snapshot.paused_at
126
+ self.pause_version += 1
127
+ self.epoch += 1
128
+ self._pause_changed_at = self.epoch
129
+ return changed
130
+
131
+
132
+ # ---- SQL helpers (writer or reader thread, ``tx`` only) --------------------------------------------------
133
+
134
+ _HAS_TABLE = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'approval_rules'"
135
+ _MAX_SEQ = "SELECT COALESCE(MAX(seq), 0) FROM approval_rules"
136
+ _COUNT_SERVICE = ("SELECT COUNT(*) FROM approval_rules WHERE service_id = ? AND status IN ('active', 'suspended')")
137
+ _COUNT_TOTAL = "SELECT COUNT(*) FROM approval_rules WHERE status IN ('active', 'suspended')"
138
+ _SELECT_RULES = (
139
+ "SELECT id, seq, service_id, match_type, match_value, most_urgent_severity, expires_at, max_per_hour, "
140
+ "max_per_incident, max_files, max_lines, status, status_reason, created_by, created_at, updated_at, "
141
+ "source_proposal_id, note, use_count, code_folder FROM approval_rules ORDER BY seq"
142
+ )
143
+ _SELECT_ONE_RULE = (
144
+ "SELECT id, seq, service_id, match_type, match_value, most_urgent_severity, expires_at, max_per_hour, "
145
+ "max_per_incident, max_files, max_lines, status, status_reason, created_by, created_at, updated_at, "
146
+ "source_proposal_id, note, use_count, code_folder FROM approval_rules WHERE id = ?"
147
+ )
148
+ _INSERT_RULE = (
149
+ "INSERT INTO approval_rules (id, seq, service_id, match_type, match_value, most_urgent_severity, expires_at, "
150
+ "max_per_hour, max_per_incident, max_files, max_lines, status, status_reason, created_by, created_at, "
151
+ "updated_at, source_proposal_id, note, use_count, code_folder) VALUES (:id, :seq, :service_id, :match_type, "
152
+ ":match_value, :most_urgent_severity, :expires_at, :max_per_hour, :max_per_incident, :max_files, :max_lines, "
153
+ ":status, :status_reason, :created_by, :created_at, :updated_at, :source_proposal_id, :note, :use_count, "
154
+ ":code_folder)"
155
+ )
156
+ _REVOKE = ("UPDATE approval_rules SET status = 'revoked', status_reason = ?, updated_at = ? "
157
+ "WHERE id = ? AND status IN ('active', 'suspended')")
158
+ _SUSPEND = ("UPDATE approval_rules SET status = 'suspended', status_reason = ?, updated_at = ? "
159
+ "WHERE id = ? AND status = 'active'")
160
+ _EXPIRE = ("UPDATE approval_rules SET status = 'expired', status_reason = 'expired', updated_at = ? "
161
+ "WHERE id = ? AND status IN ('active', 'suspended')")
162
+ _ENABLE = ("UPDATE approval_rules SET status = 'active', status_reason = '', updated_at = ? "
163
+ "WHERE id = ? AND status = 'suspended'")
164
+ _PATCH = (
165
+ "UPDATE approval_rules SET most_urgent_severity = ?, expires_at = ?, max_per_hour = ?, max_per_incident = ?, "
166
+ "max_files = ?, max_lines = ?, note = ?, updated_at = ? WHERE id = ? AND status IN ('active', 'suspended')"
167
+ )
168
+ _SELECT_ACTIVE_OF_SERVICE = "SELECT id FROM approval_rules WHERE service_id = ? AND status = 'active' ORDER BY seq"
169
+ _SELECT_LIVE_OF_SERVICE = (
170
+ "SELECT id, status FROM approval_rules WHERE service_id = ? AND status IN ('active', 'suspended') ORDER BY seq")
171
+ _SUSPEND_SERVICE = (
172
+ "UPDATE approval_rules SET status = 'suspended', status_reason = ?, updated_at = ? "
173
+ "WHERE service_id = ? AND status IN ('active', 'suspended')"
174
+ )
175
+ _SUSPEND_ACTIVE_OF_SERVICE = (
176
+ "UPDATE approval_rules SET status = 'suspended', status_reason = ?, updated_at = ? "
177
+ "WHERE service_id = ? AND status = 'active'"
178
+ )
179
+ _BUMP_USE = "UPDATE approval_rules SET use_count = use_count + 1 WHERE id = ?"
180
+ _SELECT_STATE = "SELECT key, value FROM approval_state"
181
+ _SET_STATE = "INSERT INTO approval_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
182
+ _PAUSE_STATE = "UPDATE approval_state SET value = ? WHERE key = 'paused' AND value = ?"
183
+ _INSERT_USE = (
184
+ "INSERT INTO rule_uses (rule_id, proposal_id, incident_id, opening, service_id, approved_at) "
185
+ "VALUES (?, ?, ?, ?, ?, ?)"
186
+ )
187
+ _COMPLETE_USE = "UPDATE rule_uses SET completed_at = ? WHERE proposal_id = ? AND completed_at IS NULL"
188
+ _SELECT_USES = ("SELECT rule_id, proposal_id, incident_id, opening, service_id, approved_at, completed_at "
189
+ "FROM rule_uses WHERE approved_at >= ? ORDER BY id")
190
+ _INSERT_OPENING = "INSERT OR IGNORE INTO incident_openings (incident_id, opening, first_seen_at) VALUES (?, ?, ?)"
191
+ _SELECT_OPENINGS = "SELECT incident_id, opening, first_seen_at FROM incident_openings WHERE first_seen_at >= ?"
192
+ _PRUNE_USES = "DELETE FROM rule_uses WHERE approved_at < ?"
193
+ _PRUNE_OPENINGS = "DELETE FROM incident_openings WHERE first_seen_at < ?"
194
+ _UNCOMPLETED_USES = ("SELECT u.proposal_id FROM rule_uses u JOIN proposals p ON p.id = u.proposal_id "
195
+ "WHERE u.completed_at IS NULL AND p.status = 'done'")
196
+
197
+
198
+ def ensure_migrated(store: Store) -> None:
199
+ """Raise ``ApprovalsNotMigrated`` when the store was opened without the approvals migrations."""
200
+ found = store.read_sync(lambda tx: tx.one(_HAS_TABLE), allow_blocking=True)
201
+ if found is None:
202
+ raise ApprovalsNotMigrated("open the store with approvals.register_migrations")
203
+
204
+
205
+ def row_to_rule(row: sqlite3.Row) -> Rule:
206
+ return Rule(
207
+ id=row["id"], seq=int(row["seq"]), service_id=row["service_id"], match_type=row["match_type"],
208
+ match_value=row["match_value"], most_urgent_severity=int(row["most_urgent_severity"]),
209
+ expires_at=float(row["expires_at"]), max_per_hour=int(row["max_per_hour"]),
210
+ max_per_incident=int(row["max_per_incident"]), max_files=int(row["max_files"]),
211
+ max_lines=int(row["max_lines"]), status=row["status"], status_reason=row["status_reason"],
212
+ created_by=row["created_by"], created_at=float(row["created_at"]), updated_at=float(row["updated_at"]),
213
+ source_proposal_id=row["source_proposal_id"], note=row["note"], use_count=int(row["use_count"]),
214
+ code_folder=row["code_folder"],
215
+ )
216
+
217
+
218
+ def max_rule_seq(tx: Tx) -> int:
219
+ return int(tx.one(_MAX_SEQ)[0])
220
+
221
+
222
+ def issue_rule_id(tx: Tx) -> tuple[int, str]:
223
+ """The next rule number and id, from the durable counter in this transaction (store R3.7)."""
224
+ seq = tx.counter_next("rule", floor=max_rule_seq(tx))
225
+ return seq, format_id("r", seq)
226
+
227
+
228
+ def count_live_rules(tx: Tx, service_id: str) -> tuple[int, int]:
229
+ """(rules of the service, rules in total) that are active or suspended."""
230
+ return int(tx.one(_COUNT_SERVICE, (service_id,))[0]), int(tx.one(_COUNT_TOTAL)[0])
231
+
232
+
233
+ def insert_rule(tx: Tx, rule: Rule) -> None:
234
+ tx.execute(_INSERT_RULE, dataclasses.asdict(rule))
235
+
236
+
237
+ def load_rules(tx: Tx) -> list[Rule]:
238
+ return [row_to_rule(r) for r in tx.all(_SELECT_RULES)]
239
+
240
+
241
+ def load_rule(tx: Tx, rule_id: str) -> Rule | None:
242
+ row = tx.one(_SELECT_ONE_RULE, (rule_id,))
243
+ return None if row is None else row_to_rule(row)
244
+
245
+
246
+ def load_state(tx: Tx) -> tuple[bool, str, float | None]:
247
+ state = {r["key"]: r["value"] for r in tx.all(_SELECT_STATE)}
248
+ try:
249
+ at = float(state["paused_at"]) if "paused_at" in state else None
250
+ except ValueError:
251
+ at = None
252
+ return state.get("paused") == "1", state.get("paused_by", ""), at
253
+
254
+
255
+ def revoke_row(tx: Tx, rule_id: str, reason: str, now: float) -> int:
256
+ return tx.execute(_REVOKE, (reason, now, rule_id)).rowcount
257
+
258
+
259
+ def suspend_row(tx: Tx, rule_id: str, reason: str, now: float) -> int:
260
+ return tx.execute(_SUSPEND, (reason, now, rule_id)).rowcount
261
+
262
+
263
+ def expire_row(tx: Tx, rule_id: str, now: float) -> int:
264
+ return tx.execute(_EXPIRE, (now, rule_id)).rowcount
265
+
266
+
267
+ def enable_row(tx: Tx, rule_id: str, now: float) -> int:
268
+ return tx.execute(_ENABLE, (now, rule_id)).rowcount
269
+
270
+
271
+ def patch_row(tx: Tx, rule: Rule, now: float) -> int:
272
+ return tx.execute(_PATCH, (rule.most_urgent_severity, rule.expires_at, rule.max_per_hour, rule.max_per_incident,
273
+ rule.max_files, rule.max_lines, rule.note, now, rule.id)).rowcount
274
+
275
+
276
+ def active_rule_ids(tx: Tx, service_id: str) -> list[str]:
277
+ return [r[0] for r in tx.all(_SELECT_ACTIVE_OF_SERVICE, (service_id,))]
278
+
279
+
280
+ def live_rule_ids(tx: Tx, service_id: str) -> list[tuple[str, str]]:
281
+ return [(r[0], r[1]) for r in tx.all(_SELECT_LIVE_OF_SERVICE, (service_id,))]
282
+
283
+
284
+ def suspend_service_rules(tx: Tx, service_id: str, reason: str, now: float, *, only_active: bool) -> int:
285
+ if only_active:
286
+ return tx.execute(_SUSPEND_ACTIVE_OF_SERVICE, (reason, now, service_id)).rowcount
287
+ return tx.execute(_SUSPEND_SERVICE, (reason, now, service_id)).rowcount
288
+
289
+
290
+ def bump_use_count(tx: Tx, rule_id: str) -> None:
291
+ tx.execute(_BUMP_USE, (rule_id,))
292
+
293
+
294
+ def set_state(tx: Tx, key: str, value: str) -> None:
295
+ tx.execute(_SET_STATE, (key, value))
296
+
297
+
298
+ def set_paused_row(tx: Tx, paused: bool, by: str, at: float) -> None:
299
+ set_state(tx, "paused", "1" if paused else "0")
300
+ set_state(tx, "paused_by", by[:100])
301
+ set_state(tx, "paused_at", repr(float(at)))
302
+
303
+
304
+ def resume_row(tx: Tx) -> int:
305
+ """Write ``paused = 0`` only when it is stored as ``1`` (conditional widen)."""
306
+ return tx.execute(_PAUSE_STATE, ("0", "1")).rowcount
307
+
308
+
309
+ def insert_use(tx: Tx, *, rule_id: str, proposal_id: str, incident_id: str, opening: int, service_id: str | None,
310
+ approved_at: float) -> None:
311
+ tx.execute(_INSERT_USE, (rule_id, proposal_id, incident_id, opening, service_id, approved_at))
312
+
313
+
314
+ def complete_use(tx: Tx, proposal_id: str, now: float) -> int:
315
+ return tx.execute(_COMPLETE_USE, (now, proposal_id)).rowcount
316
+
317
+
318
+ def load_uses(tx: Tx, since: float) -> list[sqlite3.Row]:
319
+ return tx.all(_SELECT_USES, (since,))
320
+
321
+
322
+ def load_openings(tx: Tx, since: float) -> list[sqlite3.Row]:
323
+ return tx.all(_SELECT_OPENINGS, (since,))
324
+
325
+
326
+ def insert_opening(tx: Tx, incident_id: str, opening: int, first_seen_at: float) -> None:
327
+ tx.execute(_INSERT_OPENING, (incident_id, opening, first_seen_at))
328
+
329
+
330
+ def prune_rows(tx: Tx, cutoff: float) -> None:
331
+ tx.execute(_PRUNE_USES, (cutoff,))
332
+ tx.execute(_PRUNE_OPENINGS, (cutoff,))
333
+
334
+
335
+ def done_without_completion(tx: Tx) -> list[str]:
336
+ return [r[0] for r in tx.all(_UNCOMPLETED_USES)]
337
+
@@ -0,0 +1,64 @@
1
+ """Migration ``approvals:0400-rules``: rules, their uses, first-seen openings and the pause flag."""
2
+ from __future__ import annotations
3
+
4
+ from chimericmesh.services.schema import services_registry
5
+ from chimericmesh.store.migrations import MigrationRegistry
6
+
7
+ APPROVALS_DDL: tuple[str, ...] = (
8
+ """CREATE TABLE approval_rules (
9
+ id TEXT PRIMARY KEY,
10
+ seq INTEGER NOT NULL UNIQUE,
11
+ service_id TEXT NOT NULL,
12
+ match_type TEXT NOT NULL CHECK (match_type IN ('signature','category')),
13
+ match_value TEXT NOT NULL CHECK (length(match_value) BETWEEN 1 AND 200),
14
+ most_urgent_severity INTEGER NOT NULL CHECK (most_urgent_severity IN (3,4)),
15
+ expires_at REAL NOT NULL,
16
+ max_per_hour INTEGER NOT NULL CHECK (max_per_hour BETWEEN 1 AND 10),
17
+ max_per_incident INTEGER NOT NULL CHECK (max_per_incident BETWEEN 1 AND 3),
18
+ max_files INTEGER NOT NULL CHECK (max_files BETWEEN 1 AND 20),
19
+ max_lines INTEGER NOT NULL CHECK (max_lines BETWEEN 1 AND 500),
20
+ status TEXT NOT NULL CHECK (status IN ('active','suspended','revoked','expired')),
21
+ status_reason TEXT NOT NULL DEFAULT '',
22
+ created_by TEXT NOT NULL,
23
+ created_at REAL NOT NULL,
24
+ updated_at REAL NOT NULL,
25
+ source_proposal_id TEXT,
26
+ note TEXT NOT NULL DEFAULT '' CHECK (length(note) <= 200),
27
+ use_count INTEGER NOT NULL DEFAULT 0,
28
+ code_folder TEXT NOT NULL
29
+ )""",
30
+ "CREATE INDEX idx_rules_service ON approval_rules (service_id, status)",
31
+ """CREATE TABLE rule_uses (
32
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
33
+ rule_id TEXT NOT NULL,
34
+ proposal_id TEXT NOT NULL UNIQUE,
35
+ incident_id TEXT NOT NULL,
36
+ opening INTEGER NOT NULL,
37
+ service_id TEXT,
38
+ approved_at REAL NOT NULL,
39
+ completed_at REAL
40
+ )""",
41
+ "CREATE INDEX idx_uses_rule ON rule_uses (rule_id, approved_at)",
42
+ "CREATE INDEX idx_uses_incident ON rule_uses (incident_id, opening)",
43
+ """CREATE TABLE incident_openings (
44
+ incident_id TEXT NOT NULL,
45
+ opening INTEGER NOT NULL,
46
+ first_seen_at REAL NOT NULL,
47
+ PRIMARY KEY (incident_id, opening)
48
+ )""",
49
+ """CREATE TABLE approval_state (
50
+ key TEXT PRIMARY KEY,
51
+ value TEXT NOT NULL
52
+ )""",
53
+ )
54
+
55
+
56
+ def register_migrations(registry: MigrationRegistry) -> None:
57
+ registry.register("approvals", 400, "approvals:0400-rules", APPROVALS_DDL)
58
+
59
+
60
+ def approvals_registry() -> MigrationRegistry:
61
+ """Core, services and approvals migrations (what the tests of this module open)."""
62
+ registry = services_registry()
63
+ register_migrations(registry)
64
+ return registry
@@ -0,0 +1,104 @@
1
+ """File scope of an auto-approved fix: inside the service's code folder, source files only (R5).
2
+
3
+ Pure and total: ``check_file`` and ``check_files`` never raise. The hub only checks what a proposal
4
+ *declares*; it does not stop the agent writing elsewhere (README states this limit, R5.4).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import re
10
+ from collections.abc import Callable, Sequence
11
+ from dataclasses import dataclass
12
+ from typing import Literal
13
+
14
+ from chimericmesh.diagnostics import CODE_SUFFIXES
15
+ from chimericmesh.services.paths import path_in_code_folder
16
+
17
+ from .format import safe_text
18
+
19
+ PROTECTED_PATTERNS = ("**/.git/**", "**/.kiro/**", "**/.github/**", "**/.env", "**/.env.*",
20
+ "**/*.pem", "**/*.key", "**/id_rsa*", "**/*.pfx")
21
+ SOURCE_SUFFIXES = CODE_SUFFIXES | frozenset({".php", ".pl", ".cs", ".cpp", ".cc", ".jsx", ".tsx"})
22
+ MAX_PATH = 300
23
+ _CONTROL = re.compile("[\\x00-\\x1f\\x7f-\\x9f\\ud800-\\udfff]")
24
+
25
+ ProblemCode = Literal["too_long", "control_char", "outside_folder", "protected", "extension"]
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class FileProblem:
30
+ file: str # the declared text, cleaned and cut to 80 characters
31
+ code: ProblemCode
32
+
33
+
34
+ def glob_to_regex(pattern: str) -> re.Pattern[str]:
35
+ """``**`` is any number of path components, ``*`` stays inside one component."""
36
+ parts = pattern.split("/")
37
+ out = ["^"]
38
+ for i, part in enumerate(parts):
39
+ last = i == len(parts) - 1
40
+ if part == "**":
41
+ out.append(".+" if last else "(?:[^/]+/)*")
42
+ continue
43
+ out.append("[^/]*".join(re.escape(piece) for piece in part.split("*")))
44
+ if not last:
45
+ out.append("/")
46
+ out.append("$")
47
+ return re.compile("".join(out))
48
+
49
+
50
+ _PROTECTED_RES = tuple(glob_to_regex(p) for p in PROTECTED_PATTERNS)
51
+
52
+
53
+ def _problem(file: str, code: ProblemCode) -> FileProblem:
54
+ return FileProblem(safe_text(file, 80), code)
55
+
56
+
57
+ def _inside(path: str, base: str) -> bool:
58
+ try:
59
+ return path != base and os.path.commonpath([path, base]) == base
60
+ except ValueError:
61
+ return False
62
+
63
+
64
+ def check_file(code_folder: str, file: str, *, protected_dirs: Sequence[str] = (),
65
+ realpath: Callable[[str], str] = os.path.realpath,
66
+ normcase: Callable[[str], str] = os.path.normcase) -> FileProblem | None:
67
+ """The first problem of one declared file, or None. Order: length, control, folder, protected, suffix."""
68
+ try:
69
+ if not isinstance(file, str):
70
+ return _problem(str(file), "control_char")
71
+ if len(file) > MAX_PATH:
72
+ return _problem(file, "too_long")
73
+ if _CONTROL.search(file):
74
+ return _problem(file, "control_char")
75
+ if not path_in_code_folder(code_folder, file, realpath=realpath, normcase=normcase):
76
+ return _problem(file, "outside_folder")
77
+ text = file.replace("\\", "/") if os.sep == "/" else file
78
+ joined = text if os.path.isabs(text) else os.path.join(code_folder, text)
79
+ real = normcase(realpath(joined))
80
+ base = normcase(realpath(code_folder))
81
+ rel = os.path.relpath(real, base).replace(os.sep, "/")
82
+ if any(rx.match(rel) for rx in _PROTECTED_RES):
83
+ return _problem(file, "protected")
84
+ for entry in protected_dirs:
85
+ if _inside(real, normcase(realpath(entry))):
86
+ return _problem(file, "protected")
87
+ if os.path.splitext(real)[1].lower() not in SOURCE_SUFFIXES:
88
+ return _problem(file, "extension")
89
+ return None
90
+ except Exception: # noqa: BLE001 - total by contract: any surprise is a refusal
91
+ return _problem(str(file)[:80], "outside_folder")
92
+
93
+
94
+ def check_files(code_folder: str, files: Sequence[str], *, protected_dirs: Sequence[str] = (),
95
+ realpath: Callable[[str], str] = os.path.realpath,
96
+ normcase: Callable[[str], str] = os.path.normcase) -> list[FileProblem]:
97
+ """Every problem, in the order of ``files``."""
98
+ found: list[FileProblem] = []
99
+ for file in files:
100
+ problem = check_file(code_folder, file, protected_dirs=protected_dirs, realpath=realpath,
101
+ normcase=normcase)
102
+ if problem is not None:
103
+ found.append(problem)
104
+ return found