memoryking 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. memoryking/__init__.py +3 -0
  2. memoryking/__main__.py +1328 -0
  3. memoryking/adapters/__init__.py +1 -0
  4. memoryking/adapters/adapter_state.py +242 -0
  5. memoryking/adapters/anchor_schema.sql +7 -0
  6. memoryking/adapters/atlas.py +441 -0
  7. memoryking/adapters/browser_commands.py +125 -0
  8. memoryking/adapters/dashboard.py +510 -0
  9. memoryking/adapters/dense_search.py +86 -0
  10. memoryking/adapters/egress_policy.py +244 -0
  11. memoryking/adapters/egress_schema.sql +13 -0
  12. memoryking/adapters/embedding.schema.json +302 -0
  13. memoryking/adapters/embedding_store.py +469 -0
  14. memoryking/adapters/execution.py +369 -0
  15. memoryking/adapters/experience.py +423 -0
  16. memoryking/adapters/experience.schema.json +1508 -0
  17. memoryking/adapters/experience_records.py +239 -0
  18. memoryking/adapters/experience_schema.sql +23 -0
  19. memoryking/adapters/handoff.py +494 -0
  20. memoryking/adapters/handoff.schema.json +299 -0
  21. memoryking/adapters/handoff_schema.sql +17 -0
  22. memoryking/adapters/index_schema.sql +11 -0
  23. memoryking/adapters/inference.py +454 -0
  24. memoryking/adapters/inference.schema.json +541 -0
  25. memoryking/adapters/inspection.py +1128 -0
  26. memoryking/adapters/inspection.schema.json +568 -0
  27. memoryking/adapters/knowledge.schema.json +633 -0
  28. memoryking/adapters/knowledge_schema.sql +37 -0
  29. memoryking/adapters/knowledge_store.py +800 -0
  30. memoryking/adapters/legacy_snapshot.py +358 -0
  31. memoryking/adapters/legacy_tables.py +49 -0
  32. memoryking/adapters/local_contract.py +45 -0
  33. memoryking/adapters/local_embeddings.py +189 -0
  34. memoryking/adapters/local_files.py +242 -0
  35. memoryking/adapters/local_ipc.py +258 -0
  36. memoryking/adapters/local_schema.sql +44 -0
  37. memoryking/adapters/local_store.py +632 -0
  38. memoryking/adapters/local_wire.schema.json +7672 -0
  39. memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
  40. memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
  41. memoryking/adapters/optional_schema.sql +43 -0
  42. memoryking/adapters/plan_dashboard.py +51 -0
  43. memoryking/adapters/plans.py +253 -0
  44. memoryking/adapters/postgres_admin.py +300 -0
  45. memoryking/adapters/postgres_anchor_schema.sql +9 -0
  46. memoryking/adapters/postgres_counter.sql +14 -0
  47. memoryking/adapters/postgres_egress_schema.sql +15 -0
  48. memoryking/adapters/postgres_experience_schema.sql +39 -0
  49. memoryking/adapters/postgres_index_schema.sql +7 -0
  50. memoryking/adapters/postgres_optional_schema.sql +71 -0
  51. memoryking/adapters/postgres_pool.py +77 -0
  52. memoryking/adapters/postgres_recovery.py +525 -0
  53. memoryking/adapters/postgres_schema.sql +365 -0
  54. memoryking/adapters/postgres_sql.py +102 -0
  55. memoryking/adapters/postgres_store.py +428 -0
  56. memoryking/adapters/postgres_summary_schema.sql +12 -0
  57. memoryking/adapters/postgres_trust_schema.sql +20 -0
  58. memoryking/adapters/processing.schema.json +471 -0
  59. memoryking/adapters/processing_store.py +346 -0
  60. memoryking/adapters/projects.py +83 -0
  61. memoryking/adapters/proposals.py +238 -0
  62. memoryking/adapters/ranking.py +315 -0
  63. memoryking/adapters/repository.schema.json +664 -0
  64. memoryking/adapters/repository_git.py +264 -0
  65. memoryking/adapters/repository_schema.sql +25 -0
  66. memoryking/adapters/repository_store.py +960 -0
  67. memoryking/adapters/retrieval.py +1285 -0
  68. memoryking/adapters/retrieval.schema.json +553 -0
  69. memoryking/adapters/retrieval_schema.sql +10 -0
  70. memoryking/adapters/shared_control.py +40 -0
  71. memoryking/adapters/shared_dashboard.py +636 -0
  72. memoryking/adapters/shared_gateway.py +63 -0
  73. memoryking/adapters/shared_http.py +216 -0
  74. memoryking/adapters/shared_mcp.py +159 -0
  75. memoryking/adapters/shared_service.py +124 -0
  76. memoryking/adapters/stdio.py +193 -0
  77. memoryking/adapters/stdio.tools.json +6776 -0
  78. memoryking/adapters/summary_schema.sql +10 -0
  79. memoryking/adapters/team.py +253 -0
  80. memoryking/adapters/timeline.py +80 -0
  81. memoryking/adapters/token_count.py +55 -0
  82. memoryking/adapters/tokenizers/LICENSE +21 -0
  83. memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
  84. memoryking/adapters/trust.py +123 -0
  85. memoryking/adapters/trust_schema.sql +13 -0
  86. memoryking/adapters/web/app.css +1251 -0
  87. memoryking/adapters/web/app.js +907 -0
  88. memoryking/adapters/web/brand.js +44 -0
  89. memoryking/adapters/web/crown-mono.svg +1 -0
  90. memoryking/adapters/web/crown.svg +8 -0
  91. memoryking/adapters/web/elephant.png +0 -0
  92. memoryking/adapters/web/favicon.svg +8 -0
  93. memoryking/adapters/web/graph-layout.js +52 -0
  94. memoryking/adapters/web/graph-worker.js +10 -0
  95. memoryking/adapters/web/graph.js +570 -0
  96. memoryking/adapters/web/index.html +208 -0
  97. memoryking/adapters/web/observatory.js +1208 -0
  98. memoryking/adapters/web/team.js +151 -0
  99. memoryking/adapters/web/wordmark.svg +1 -0
  100. memoryking/adapters/working.py +971 -0
  101. memoryking/adapters/working.schema.json +1717 -0
  102. memoryking/adapters/working_schema.sql +24 -0
  103. memoryking/application/__init__.py +1 -0
  104. memoryking/application/conformance.py +50 -0
  105. memoryking/application/legacy_import.py +337 -0
  106. memoryking/application/local_port.py +9 -0
  107. memoryking/application/storage.py +117 -0
  108. memoryking/application/store_core.py +1292 -0
  109. memoryking/backups.py +131 -0
  110. memoryking/contracts/__init__.py +6 -0
  111. memoryking/contracts/__main__.py +20 -0
  112. memoryking/contracts/canonical.py +88 -0
  113. memoryking/contracts/embedding.schema.json +302 -0
  114. memoryking/contracts/embedding_generated.py +65 -0
  115. memoryking/contracts/experience.schema.json +1508 -0
  116. memoryking/contracts/experience_generated.py +239 -0
  117. memoryking/contracts/generated.py +122 -0
  118. memoryking/contracts/handoff.schema.json +299 -0
  119. memoryking/contracts/handoff_generated.py +69 -0
  120. memoryking/contracts/inference.schema.json +541 -0
  121. memoryking/contracts/inference_generated.py +106 -0
  122. memoryking/contracts/processing.schema.json +471 -0
  123. memoryking/contracts/processing_generated.py +82 -0
  124. memoryking/contracts/py.typed +0 -0
  125. memoryking/contracts/repository.schema.json +664 -0
  126. memoryking/contracts/repository_generated.py +144 -0
  127. memoryking/contracts/retrieval.schema.json +553 -0
  128. memoryking/contracts/retrieval_generated.py +110 -0
  129. memoryking/contracts/schema.json +696 -0
  130. memoryking/contracts/validation.py +92 -0
  131. memoryking/contracts/working.schema.json +1717 -0
  132. memoryking/contracts/working_generated.py +291 -0
  133. memoryking/domain/__init__.py +1 -0
  134. memoryking/domain/anchors.py +97 -0
  135. memoryking/domain/briefing.py +108 -0
  136. memoryking/domain/briefing_text.py +222 -0
  137. memoryking/domain/checkpoint.py +118 -0
  138. memoryking/domain/compression.py +64 -0
  139. memoryking/domain/delta.py +129 -0
  140. memoryking/domain/embeddings.py +90 -0
  141. memoryking/domain/hints.py +465 -0
  142. memoryking/domain/http_status.py +45 -0
  143. memoryking/domain/learning.py +62 -0
  144. memoryking/domain/local.py +65 -0
  145. memoryking/domain/plans.py +140 -0
  146. memoryking/domain/repository.py +118 -0
  147. memoryking/domain/selectors.py +356 -0
  148. memoryking/domain/summary.py +88 -0
  149. memoryking/domain/usage.py +163 -0
  150. memoryking/embedding_loop.py +98 -0
  151. memoryking/embedding_worker.py +131 -0
  152. memoryking/harness.py +882 -0
  153. memoryking/harness_context.py +376 -0
  154. memoryking/hooks.py +171 -0
  155. memoryking/host_hooks.py +454 -0
  156. memoryking/lean.py +352 -0
  157. memoryking/memory_tool.py +776 -0
  158. memoryking/migration.py +194 -0
  159. memoryking/model_install.py +78 -0
  160. memoryking/observability.py +101 -0
  161. memoryking/observability_metrics.py +100 -0
  162. memoryking/profiles.py +150 -0
  163. memoryking/providers.py +330 -0
  164. memoryking/py.typed +0 -0
  165. memoryking/pytest_plugin.py +69 -0
  166. memoryking/reference_agent.py +152 -0
  167. memoryking/repository_worker.py +57 -0
  168. memoryking/resume_adapter.py +154 -0
  169. memoryking/sdk.py +302 -0
  170. memoryking/shared.py +301 -0
  171. memoryking/shared_sdk.py +101 -0
  172. memoryking/vault.py +176 -0
  173. memoryking-0.1.0.dist-info/METADATA +157 -0
  174. memoryking-0.1.0.dist-info/RECORD +179 -0
  175. memoryking-0.1.0.dist-info/WHEEL +5 -0
  176. memoryking-0.1.0.dist-info/entry_points.txt +7 -0
  177. memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
  178. memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
  179. memoryking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,423 @@
1
+ """Reviewed procedures under the shared transaction, evidence and release boundary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from jsonschema import Draft202012Validator
10
+
11
+ from memoryking.adapters.knowledge_store import Knowledge
12
+ from memoryking.adapters.local_store import RETRY_MS, uid
13
+ from memoryking.adapters.repository_store import Repository
14
+ from memoryking.application.store_core import StoreCore
15
+ from memoryking.contracts.canonical import canonical_bytes, canonical_hash
16
+ from memoryking.domain import selectors
17
+ from memoryking.domain.local import LocalError, Released, temporal_valid
18
+
19
+ VALIDATOR = Draft202012Validator(
20
+ json.loads(Path(__file__).with_name("experience.schema.json").read_text())
21
+ )
22
+ POLICY = "reviewed-procedure-v1"
23
+ LIMIT = 256
24
+
25
+
26
+ class Experience:
27
+ def __init__(self, store: StoreCore):
28
+ self.s, self.db, self.k = store, store.db, Knowledge(store)
29
+
30
+ def revision(self, who: dict[str, Any], args: dict[str, Any], at: int) -> Any:
31
+ row = self.k._revision(who["tenant"], args["revision"], args["project"])
32
+ if row["kind"] != "procedure" or not self.k._available(who, row, at):
33
+ raise LocalError("procedure_unavailable")
34
+ return row
35
+
36
+ def execute(self, credential: str, command: dict[str, Any]) -> Released:
37
+ if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
38
+ raise LocalError("invalid_request")
39
+ if command["incarnation"] != self.s.incarnation:
40
+ raise LocalError("history_changed")
41
+ action, args, receipt = command["action"], command["args"], uid("rcpt")
42
+ mutation = action not in {"query", "records", "record", "ranking_inspect"}
43
+ with self.s.transaction() as decision:
44
+ at = decision.evaluated_ms
45
+ who = self.s._auth(credential, "read", args["project"], at)
46
+ cap = "capture" if action in {"propose", "outcome", "feedback"} else "review"
47
+ if mutation or args.get("diagnostic", False):
48
+ self.s._auth(credential, cap, args["project"], at)
49
+ if action.startswith("ranking_"):
50
+ self.s._auth(credential, "review", args["project"], at)
51
+ self.s._auth(credential, "admin", args["project"], at)
52
+ if action == "propose":
53
+ self.proposal(who, args, at)
54
+ elif action in {"review", "activate", "suspend"}:
55
+ self.revision(who, args, at)
56
+ lookup = (
57
+ who["tenant"],
58
+ self.s.incarnation,
59
+ "experience-v1",
60
+ who["principal"],
61
+ action,
62
+ command.get("key"),
63
+ )
64
+ previous = (
65
+ self.db.execute(
66
+ "SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
67
+ lookup,
68
+ ).fetchone()
69
+ if mutation
70
+ else None
71
+ )
72
+ if previous is not None:
73
+ if previous["hash"] != canonical_hash(command):
74
+ raise LocalError("idempotency_conflict")
75
+ if previous["result"] is None or at >= previous["expires"]:
76
+ raise LocalError("idempotency_result_expired")
77
+ result = json.loads(previous["result"])
78
+ result["replayed"] = True
79
+ elif action.startswith("ranking_"):
80
+ from memoryking.adapters.ranking import Ranking
81
+
82
+ ranking = Ranking(self.s)
83
+ if action == "ranking_propose":
84
+ result = ranking.propose(who, args, at)
85
+ elif action == "ranking_evaluate":
86
+ result = ranking.evaluate(who, args, decision)
87
+ elif action == "ranking_inspect":
88
+ result = ranking.inspect(who, args, at)
89
+ else:
90
+ result = ranking.transition(who, args, action.removeprefix("ranking_"), at)
91
+ elif action in {"outcome", "feedback", "records", "record"}:
92
+ from memoryking.adapters.experience_records import ExperienceRecords
93
+
94
+ result = getattr(ExperienceRecords(self.s), action)(who, args, at)
95
+ elif action == "propose":
96
+ result = self.k.propose(credential, who, args, at)
97
+ elif action == "review":
98
+ result = self.k.review(credential, who, args, at, procedure=True)
99
+ elif action in {"activate", "suspend"}:
100
+ result = self.transition(who, args, action, at)
101
+ else:
102
+ result = self.query(who, args, at)
103
+ if mutation and previous is None:
104
+ self.db.execute(
105
+ "INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
106
+ (*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
107
+ )
108
+ result.update(
109
+ incarnation=self.s.incarnation,
110
+ evaluated_ms=at,
111
+ deadline_ms=decision.deadline_ms,
112
+ receipt=receipt,
113
+ )
114
+ raw = canonical_bytes(result)
115
+ if len(raw) > 262144:
116
+ raise LocalError("experience_response_limit")
117
+ epochs = self.db.execute(
118
+ "SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
119
+ ).fetchone()
120
+ self.db.execute(
121
+ "INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
122
+ (
123
+ who["tenant"],
124
+ receipt,
125
+ who["principal"],
126
+ self.s.incarnation,
127
+ at,
128
+ decision.deadline_ms,
129
+ *epochs,
130
+ canonical_hash(result),
131
+ "[]",
132
+ ),
133
+ )
134
+ self.s.fault("after_validation")
135
+ self.s._expose()
136
+ return Released(raw, decision, self.s.clock, receipt)
137
+
138
+ def proposal(self, who: dict[str, Any], args: dict[str, Any], at: int) -> None:
139
+ body = args["body"]
140
+ procedure = body["procedure"]
141
+ evidence = {span["observation"] for span in body["evidence"]}
142
+ if not set(procedure["success_evidence"] + procedure["failure_evidence"]) <= evidence:
143
+ raise LocalError("procedure_support_required")
144
+ if set(procedure["success_evidence"]) & set(procedure["failure_evidence"]):
145
+ raise LocalError("procedure_case_ambiguous")
146
+ self.k._support(who, body["evidence"], at)
147
+ selectors.canonical(body["selector"])
148
+ # A knowledge family cannot turn into a procedure/constraint under a new name.
149
+ previous = self.db.execute(
150
+ "SELECT r.kind FROM revisions r JOIN families f ON r.tenant=f.tenant AND r.family=f.id WHERE r.tenant=? AND f.project=? AND f.logical_key=? LIMIT 1",
151
+ (who["tenant"], args["project"], args["logical_key"]),
152
+ ).fetchone()
153
+ if previous is not None and previous[0] != "procedure":
154
+ raise LocalError("family_kind_mismatch")
155
+
156
+ def activation(self, tenant: str, revision: str, position: int) -> dict[str, Any] | None:
157
+ row = self.db.execute(
158
+ "SELECT action,detail,position FROM lifecycle WHERE tenant=? AND revision=? AND action IN ('activate','suspend') AND position<=? ORDER BY position DESC LIMIT 1",
159
+ (tenant, revision, position),
160
+ ).fetchone()
161
+ if row is None:
162
+ return None
163
+ return {"action": row["action"], "position": row["position"], **json.loads(row["detail"])}
164
+
165
+ def matches(
166
+ self, who: dict[str, Any], row: Any, points: list[dict[str, Any]], at: int, position: int
167
+ ) -> list[str]:
168
+ body = json.loads(row["body"])
169
+ if (
170
+ body["procedure"]["dependency_mode"] == "required"
171
+ and self.db.execute(
172
+ "SELECT 1 FROM code_policies WHERE tenant=? AND revision=?",
173
+ (who["tenant"], row["id"]),
174
+ ).fetchone()
175
+ is None
176
+ ):
177
+ return ["unknown"] * len(points)
178
+ return [self.k._eligible(row, body, point, at, position, who, at) for point in points]
179
+
180
+ def transition(
181
+ self, who: dict[str, Any], args: dict[str, Any], action: str, at: int
182
+ ) -> dict[str, Any]:
183
+ if (
184
+ action == "activate"
185
+ and self.db.execute(
186
+ "SELECT recovery_gap FROM knowledge_state WHERE tenant=?", (who["tenant"],)
187
+ ).fetchone()[0]
188
+ ):
189
+ raise LocalError("knowledge_reconciliation_required")
190
+ row = self.revision(who, args, at)
191
+ if row["family_version"] != args["expected_version"]:
192
+ raise LocalError("family_version_conflict")
193
+ position = self.db.execute(
194
+ "SELECT position FROM tenants WHERE tenant=?", (who["tenant"],)
195
+ ).fetchone()[0]
196
+ state, quarantine = self.k._state(who["tenant"], row["id"], position)
197
+ if state != "accepted" or quarantine:
198
+ raise LocalError("procedure_review_required")
199
+ body = json.loads(row["body"])
200
+ if action == "activate":
201
+ points = selectors.bindings(args["bindings"])
202
+ if any(m != "true" for m in self.matches(who, row, points, at, position)):
203
+ raise LocalError("procedure_validation_required")
204
+ elif self.activation(who["tenant"], row["id"], position) is None:
205
+ raise LocalError("invalid_transition")
206
+ detail = {
207
+ "incarnation": self.s.incarnation,
208
+ "policy": POLICY,
209
+ "audience_hash": canonical_hash(body["readers"]),
210
+ "reason": args["reason"],
211
+ "actor": who["principal"],
212
+ "validated_bindings": args.get("bindings", []),
213
+ "execution_privileges": False,
214
+ }
215
+ self.s._apply(
216
+ self.s._journal(
217
+ {
218
+ "kind": "procedure",
219
+ "tenant": who["tenant"],
220
+ "actor": who["principal"],
221
+ "revision": row["id"],
222
+ "expected_hash": row["body_hash"],
223
+ "decision": action,
224
+ "detail": detail,
225
+ }
226
+ ),
227
+ at,
228
+ )
229
+ return {
230
+ "revision": row["id"],
231
+ "family": row["family"],
232
+ "family_version": row["family_version"] + 1,
233
+ "state": "active" if action == "activate" else "suspended",
234
+ "policy": POLICY,
235
+ "execution_privileges": False,
236
+ }
237
+
238
+ def apply_policy(self, action: dict[str, Any], at: int) -> None:
239
+ tenant = action["tenant"]
240
+ row = self.db.execute(
241
+ "SELECT * FROM revisions WHERE tenant=? AND id=?", (tenant, action["revision"])
242
+ ).fetchone()
243
+ if row is None or row["body_hash"] != action["expected_hash"]:
244
+ self.db.execute(
245
+ "UPDATE knowledge_state SET recovery_gap=1,generation=generation+1 WHERE tenant=?",
246
+ (tenant,),
247
+ )
248
+ return
249
+ position = self.s._event(
250
+ tenant, "procedure_" + action["decision"], row["id"], at, action["actor"]
251
+ )
252
+ self.db.execute(
253
+ "INSERT INTO lifecycle VALUES (?,?,?,?,?)",
254
+ (tenant, row["id"], position, action["decision"], json.dumps(action["detail"])),
255
+ )
256
+ self.db.execute(
257
+ "UPDATE families SET version=version+1 WHERE tenant=? AND id=?", (tenant, row["family"])
258
+ )
259
+ self.db.execute(
260
+ "UPDATE knowledge_state SET generation=generation+1 WHERE tenant=?", (tenant,)
261
+ )
262
+ self.s._enqueue(tenant, position, None, action["actor"])
263
+
264
+ def query(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
265
+ tenant, points = who["tenant"], selectors.bindings(args["bindings"])
266
+ state = self.db.execute(
267
+ "SELECT recovery_gap FROM knowledge_state WHERE tenant=?", (tenant,)
268
+ ).fetchone()
269
+ if state[0]:
270
+ return {"status": "blocked", "reason": "knowledge_reconciliation_required", "items": []}
271
+ position = self.db.execute(
272
+ "SELECT position FROM tenants WHERE tenant=?", (tenant,)
273
+ ).fetchone()[0]
274
+ rows = self.db.execute(
275
+ "SELECT r.*,f.project,f.version AS family_version FROM revisions r JOIN families f ON r.tenant=f.tenant AND r.family=f.id WHERE r.tenant=? AND f.project=? AND r.kind='procedure' ORDER BY r.created LIMIT 257",
276
+ (tenant, args["project"]),
277
+ ).fetchall()
278
+ if len(rows) > LIMIT or len(points) > 32:
279
+ return {"status": "blocked", "reason": "procedure_resolution_incomplete", "items": []}
280
+ values: list[
281
+ tuple[Any, dict[str, Any], str, bool, dict[str, Any] | None, bool, list[str]]
282
+ ] = []
283
+ work = 0
284
+ for row in rows:
285
+ if row["body"] is None:
286
+ lifecycle, quarantine = self.k._state(tenant, row["id"], position)
287
+ activation = self.activation(tenant, row["id"], position)
288
+ values.append(
289
+ (row, {}, lifecycle, quarantine, activation, False, ["unknown"] * len(points))
290
+ )
291
+ continue
292
+ body = json.loads(row["body"])
293
+ if any(body[k] is not None and body[k] != args.get(k) for k in ("task", "run")):
294
+ continue
295
+ lifecycle, quarantine = self.k._state(tenant, row["id"], position)
296
+ activation = self.activation(tenant, row["id"], position)
297
+ available = self.k._available(who, row, at)
298
+ masks = self.db.execute(
299
+ "SELECT selector FROM replacements WHERE tenant=? AND predecessor=? AND position<=?",
300
+ (tenant, row["id"], position),
301
+ ).fetchall()
302
+ work += len(points) * sum(
303
+ len(clause["all_of"])
304
+ for selector in [body["selector"], *[json.loads(m[0]) for m in masks]]
305
+ for clause in selector["any_of"]
306
+ )
307
+ if work > 65536:
308
+ return {
309
+ "status": "blocked",
310
+ "reason": "procedure_resolution_incomplete",
311
+ "items": [],
312
+ }
313
+ matches = self.matches(who, row, points, at, position)
314
+ values.append((row, body, lifecycle, quarantine, activation, available, matches))
315
+ items, blockers = [], []
316
+ for row, body, lifecycle, quarantine, activation, available, matches in values:
317
+ if not available:
318
+ continue
319
+ reason = None
320
+ if lifecycle != "accepted":
321
+ reason = "review_required" if lifecycle == "proposed" else lifecycle
322
+ elif quarantine:
323
+ reason = "quarantined"
324
+ elif activation is None:
325
+ reason = "activation_required"
326
+ elif activation["action"] != "activate":
327
+ reason = "suspended_by_review"
328
+ elif activation["incarnation"] != self.s.incarnation:
329
+ reason = "history_reconciliation_required"
330
+ elif activation["policy"] != POLICY or activation["audience_hash"] != canonical_hash(
331
+ body["readers"]
332
+ ):
333
+ reason = "activation_context_changed"
334
+ elif any(m != "true" for m in matches):
335
+ reason = "applicability_or_validation_unavailable"
336
+ if reason is None:
337
+ for other, _obody, ostate, _oq, oa, _, om in values:
338
+ if other["id"] == row["id"] or other["family"] != row["family"]:
339
+ continue
340
+ # Hidden/quarantined disagreement never becomes a clean active procedure.
341
+ if (
342
+ ostate == "accepted"
343
+ and oa
344
+ and oa["action"] == "activate"
345
+ and oa["incarnation"] == self.s.incarnation
346
+ and any(m != "false" for m in om)
347
+ and other["body_hash"] != row["body_hash"]
348
+ ):
349
+ reason = "unresolved_procedure_conflict"
350
+ break
351
+ effective = (
352
+ "active"
353
+ if reason is None
354
+ else "suspended"
355
+ if lifecycle == "accepted" and activation
356
+ else lifecycle
357
+ )
358
+ if reason is not None:
359
+ blockers.append(
360
+ {"revision": row["id"], "reason": reason, "effective_state": effective}
361
+ )
362
+ if reason is not None and not args.get("diagnostic", False):
363
+ continue
364
+ proofs = [
365
+ p
366
+ for point in points
367
+ if (p := Repository(self.s).proof(who, row, point, at)) is not None
368
+ ]
369
+ items.append(
370
+ {
371
+ "revision": row["id"],
372
+ "family": row["family"],
373
+ "family_version": row["family_version"],
374
+ "body_hash": row["body_hash"],
375
+ "created_position": row["created"],
376
+ "origin": row["origin"],
377
+ "attestations": [],
378
+ "body": body,
379
+ "state": lifecycle,
380
+ "effective_state": effective,
381
+ "reason": reason,
382
+ "activation": activation,
383
+ "applicability": matches,
384
+ "code_validation": proofs,
385
+ "authority": "active_procedure" if reason is None else "procedure_inspection",
386
+ "execution_privileges": False,
387
+ }
388
+ )
389
+ return {
390
+ "status": "partial" if blockers else "complete",
391
+ "items": items,
392
+ "blockers": blockers,
393
+ "recorded_position": position,
394
+ "valid_ms": at,
395
+ "policy": POLICY,
396
+ "execution_privileges": False,
397
+ }
398
+
399
+ def verify_dependency(self, who: dict[str, Any], reference: str, at: int) -> None:
400
+ try:
401
+ revision, position, family_version = reference.split("|")
402
+ row = self.k._revision(who["tenant"], revision)
403
+ activation = self.activation(who["tenant"], revision, 9007199254740991)
404
+ lifecycle, quarantine = self.k._state(who["tenant"], revision, 9007199254740991)
405
+ if not self.k._available(who, row, at):
406
+ raise LocalError("replay_denied")
407
+ body = json.loads(row["body"])
408
+ if (
409
+ lifecycle != "accepted"
410
+ or row["family_version"] != int(family_version)
411
+ or quarantine
412
+ or activation is None
413
+ or activation["action"] != "activate"
414
+ or activation["position"] != int(position)
415
+ or activation["incarnation"] != self.s.incarnation
416
+ or not temporal_valid(at, body["valid_start"], body["valid_end"])
417
+ or self.db.execute(
418
+ "SELECT recovery_gap FROM knowledge_state WHERE tenant=?", (who["tenant"],)
419
+ ).fetchone()[0]
420
+ ):
421
+ raise LocalError("replay_denied")
422
+ except (ValueError, TypeError, LocalError) as exc:
423
+ raise LocalError("replay_denied") from exc