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.
- memoryking/__init__.py +3 -0
- memoryking/__main__.py +1328 -0
- memoryking/adapters/__init__.py +1 -0
- memoryking/adapters/adapter_state.py +242 -0
- memoryking/adapters/anchor_schema.sql +7 -0
- memoryking/adapters/atlas.py +441 -0
- memoryking/adapters/browser_commands.py +125 -0
- memoryking/adapters/dashboard.py +510 -0
- memoryking/adapters/dense_search.py +86 -0
- memoryking/adapters/egress_policy.py +244 -0
- memoryking/adapters/egress_schema.sql +13 -0
- memoryking/adapters/embedding.schema.json +302 -0
- memoryking/adapters/embedding_store.py +469 -0
- memoryking/adapters/execution.py +369 -0
- memoryking/adapters/experience.py +423 -0
- memoryking/adapters/experience.schema.json +1508 -0
- memoryking/adapters/experience_records.py +239 -0
- memoryking/adapters/experience_schema.sql +23 -0
- memoryking/adapters/handoff.py +494 -0
- memoryking/adapters/handoff.schema.json +299 -0
- memoryking/adapters/handoff_schema.sql +17 -0
- memoryking/adapters/index_schema.sql +11 -0
- memoryking/adapters/inference.py +454 -0
- memoryking/adapters/inference.schema.json +541 -0
- memoryking/adapters/inspection.py +1128 -0
- memoryking/adapters/inspection.schema.json +568 -0
- memoryking/adapters/knowledge.schema.json +633 -0
- memoryking/adapters/knowledge_schema.sql +37 -0
- memoryking/adapters/knowledge_store.py +800 -0
- memoryking/adapters/legacy_snapshot.py +358 -0
- memoryking/adapters/legacy_tables.py +49 -0
- memoryking/adapters/local_contract.py +45 -0
- memoryking/adapters/local_embeddings.py +189 -0
- memoryking/adapters/local_files.py +242 -0
- memoryking/adapters/local_ipc.py +258 -0
- memoryking/adapters/local_schema.sql +44 -0
- memoryking/adapters/local_store.py +632 -0
- memoryking/adapters/local_wire.schema.json +7672 -0
- memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/optional_schema.sql +43 -0
- memoryking/adapters/plan_dashboard.py +51 -0
- memoryking/adapters/plans.py +253 -0
- memoryking/adapters/postgres_admin.py +300 -0
- memoryking/adapters/postgres_anchor_schema.sql +9 -0
- memoryking/adapters/postgres_counter.sql +14 -0
- memoryking/adapters/postgres_egress_schema.sql +15 -0
- memoryking/adapters/postgres_experience_schema.sql +39 -0
- memoryking/adapters/postgres_index_schema.sql +7 -0
- memoryking/adapters/postgres_optional_schema.sql +71 -0
- memoryking/adapters/postgres_pool.py +77 -0
- memoryking/adapters/postgres_recovery.py +525 -0
- memoryking/adapters/postgres_schema.sql +365 -0
- memoryking/adapters/postgres_sql.py +102 -0
- memoryking/adapters/postgres_store.py +428 -0
- memoryking/adapters/postgres_summary_schema.sql +12 -0
- memoryking/adapters/postgres_trust_schema.sql +20 -0
- memoryking/adapters/processing.schema.json +471 -0
- memoryking/adapters/processing_store.py +346 -0
- memoryking/adapters/projects.py +83 -0
- memoryking/adapters/proposals.py +238 -0
- memoryking/adapters/ranking.py +315 -0
- memoryking/adapters/repository.schema.json +664 -0
- memoryking/adapters/repository_git.py +264 -0
- memoryking/adapters/repository_schema.sql +25 -0
- memoryking/adapters/repository_store.py +960 -0
- memoryking/adapters/retrieval.py +1285 -0
- memoryking/adapters/retrieval.schema.json +553 -0
- memoryking/adapters/retrieval_schema.sql +10 -0
- memoryking/adapters/shared_control.py +40 -0
- memoryking/adapters/shared_dashboard.py +636 -0
- memoryking/adapters/shared_gateway.py +63 -0
- memoryking/adapters/shared_http.py +216 -0
- memoryking/adapters/shared_mcp.py +159 -0
- memoryking/adapters/shared_service.py +124 -0
- memoryking/adapters/stdio.py +193 -0
- memoryking/adapters/stdio.tools.json +6776 -0
- memoryking/adapters/summary_schema.sql +10 -0
- memoryking/adapters/team.py +253 -0
- memoryking/adapters/timeline.py +80 -0
- memoryking/adapters/token_count.py +55 -0
- memoryking/adapters/tokenizers/LICENSE +21 -0
- memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
- memoryking/adapters/trust.py +123 -0
- memoryking/adapters/trust_schema.sql +13 -0
- memoryking/adapters/web/app.css +1251 -0
- memoryking/adapters/web/app.js +907 -0
- memoryking/adapters/web/brand.js +44 -0
- memoryking/adapters/web/crown-mono.svg +1 -0
- memoryking/adapters/web/crown.svg +8 -0
- memoryking/adapters/web/elephant.png +0 -0
- memoryking/adapters/web/favicon.svg +8 -0
- memoryking/adapters/web/graph-layout.js +52 -0
- memoryking/adapters/web/graph-worker.js +10 -0
- memoryking/adapters/web/graph.js +570 -0
- memoryking/adapters/web/index.html +208 -0
- memoryking/adapters/web/observatory.js +1208 -0
- memoryking/adapters/web/team.js +151 -0
- memoryking/adapters/web/wordmark.svg +1 -0
- memoryking/adapters/working.py +971 -0
- memoryking/adapters/working.schema.json +1717 -0
- memoryking/adapters/working_schema.sql +24 -0
- memoryking/application/__init__.py +1 -0
- memoryking/application/conformance.py +50 -0
- memoryking/application/legacy_import.py +337 -0
- memoryking/application/local_port.py +9 -0
- memoryking/application/storage.py +117 -0
- memoryking/application/store_core.py +1292 -0
- memoryking/backups.py +131 -0
- memoryking/contracts/__init__.py +6 -0
- memoryking/contracts/__main__.py +20 -0
- memoryking/contracts/canonical.py +88 -0
- memoryking/contracts/embedding.schema.json +302 -0
- memoryking/contracts/embedding_generated.py +65 -0
- memoryking/contracts/experience.schema.json +1508 -0
- memoryking/contracts/experience_generated.py +239 -0
- memoryking/contracts/generated.py +122 -0
- memoryking/contracts/handoff.schema.json +299 -0
- memoryking/contracts/handoff_generated.py +69 -0
- memoryking/contracts/inference.schema.json +541 -0
- memoryking/contracts/inference_generated.py +106 -0
- memoryking/contracts/processing.schema.json +471 -0
- memoryking/contracts/processing_generated.py +82 -0
- memoryking/contracts/py.typed +0 -0
- memoryking/contracts/repository.schema.json +664 -0
- memoryking/contracts/repository_generated.py +144 -0
- memoryking/contracts/retrieval.schema.json +553 -0
- memoryking/contracts/retrieval_generated.py +110 -0
- memoryking/contracts/schema.json +696 -0
- memoryking/contracts/validation.py +92 -0
- memoryking/contracts/working.schema.json +1717 -0
- memoryking/contracts/working_generated.py +291 -0
- memoryking/domain/__init__.py +1 -0
- memoryking/domain/anchors.py +97 -0
- memoryking/domain/briefing.py +108 -0
- memoryking/domain/briefing_text.py +222 -0
- memoryking/domain/checkpoint.py +118 -0
- memoryking/domain/compression.py +64 -0
- memoryking/domain/delta.py +129 -0
- memoryking/domain/embeddings.py +90 -0
- memoryking/domain/hints.py +465 -0
- memoryking/domain/http_status.py +45 -0
- memoryking/domain/learning.py +62 -0
- memoryking/domain/local.py +65 -0
- memoryking/domain/plans.py +140 -0
- memoryking/domain/repository.py +118 -0
- memoryking/domain/selectors.py +356 -0
- memoryking/domain/summary.py +88 -0
- memoryking/domain/usage.py +163 -0
- memoryking/embedding_loop.py +98 -0
- memoryking/embedding_worker.py +131 -0
- memoryking/harness.py +882 -0
- memoryking/harness_context.py +376 -0
- memoryking/hooks.py +171 -0
- memoryking/host_hooks.py +454 -0
- memoryking/lean.py +352 -0
- memoryking/memory_tool.py +776 -0
- memoryking/migration.py +194 -0
- memoryking/model_install.py +78 -0
- memoryking/observability.py +101 -0
- memoryking/observability_metrics.py +100 -0
- memoryking/profiles.py +150 -0
- memoryking/providers.py +330 -0
- memoryking/py.typed +0 -0
- memoryking/pytest_plugin.py +69 -0
- memoryking/reference_agent.py +152 -0
- memoryking/repository_worker.py +57 -0
- memoryking/resume_adapter.py +154 -0
- memoryking/sdk.py +302 -0
- memoryking/shared.py +301 -0
- memoryking/shared_sdk.py +101 -0
- memoryking/vault.py +176 -0
- memoryking-0.1.0.dist-info/METADATA +157 -0
- memoryking-0.1.0.dist-info/RECORD +179 -0
- memoryking-0.1.0.dist-info/WHEEL +5 -0
- memoryking-0.1.0.dist-info/entry_points.txt +7 -0
- memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
- memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
- memoryking-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,800 @@
|
|
|
1
|
+
"""SQLite evidence-backed claims and complete policy registry, under the local gate."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import sqlite3
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, cast
|
|
10
|
+
|
|
11
|
+
from jsonschema import Draft202012Validator
|
|
12
|
+
|
|
13
|
+
from memoryking.adapters.local_files import private_file
|
|
14
|
+
from memoryking.adapters.local_store import RETRY_MS, uid
|
|
15
|
+
from memoryking.application.storage import insert_ignore
|
|
16
|
+
from memoryking.application.store_core import StoreCore
|
|
17
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash
|
|
18
|
+
from memoryking.domain import selectors
|
|
19
|
+
from memoryking.domain.local import LocalError, Released, temporal_valid
|
|
20
|
+
|
|
21
|
+
REGISTRY_LIMIT = 256
|
|
22
|
+
VALIDATOR = Draft202012Validator(
|
|
23
|
+
json.loads(Path(__file__).with_name("knowledge.schema.json").read_text())
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Knowledge:
|
|
28
|
+
def __init__(self, store: StoreCore):
|
|
29
|
+
self.s = store
|
|
30
|
+
self.db = store.db
|
|
31
|
+
|
|
32
|
+
def execute(self, credential: str, command: dict[str, Any]) -> Released:
|
|
33
|
+
canonical_bytes(command)
|
|
34
|
+
if not VALIDATOR.is_valid(command):
|
|
35
|
+
raise LocalError("invalid_request")
|
|
36
|
+
if command["incarnation"] != self.s.incarnation:
|
|
37
|
+
raise LocalError("history_changed")
|
|
38
|
+
action, args = command["action"], command["args"]
|
|
39
|
+
cap = {
|
|
40
|
+
"propose": "capture",
|
|
41
|
+
"draft": "capture",
|
|
42
|
+
"review": "review",
|
|
43
|
+
"attest": "attest",
|
|
44
|
+
"promote": "review",
|
|
45
|
+
}.get(action, "read")
|
|
46
|
+
with self.s.transaction() as decision:
|
|
47
|
+
who = self.s._auth(credential, cap, args["project"], decision.evaluated_ms)
|
|
48
|
+
at = decision.evaluated_ms
|
|
49
|
+
if args.get("diagnostic", False):
|
|
50
|
+
self.s._auth(credential, "review", args["project"], at)
|
|
51
|
+
# Required operation capabilities apply equally to fresh calls and retries.
|
|
52
|
+
if action == "propose" and args["body"]["kind"] == "constraint":
|
|
53
|
+
self.s._auth(
|
|
54
|
+
credential,
|
|
55
|
+
"task_constraint" if args["body"]["authority"] == "task" else "policy",
|
|
56
|
+
args["project"],
|
|
57
|
+
at,
|
|
58
|
+
)
|
|
59
|
+
if action == "promote":
|
|
60
|
+
self.s._auth(credential, "capture", args["project"], at)
|
|
61
|
+
source = self._revision(who["tenant"], args["revision"])
|
|
62
|
+
self.s._auth(credential, "review", source["project"], at)
|
|
63
|
+
self.s._auth(credential, "export", source["project"], at)
|
|
64
|
+
mutation = action in {"propose", "draft", "review", "attest", "promote"}
|
|
65
|
+
key = command.get("key")
|
|
66
|
+
if mutation and not key:
|
|
67
|
+
raise LocalError("request_key_required")
|
|
68
|
+
existing = None
|
|
69
|
+
lookup = (
|
|
70
|
+
who["tenant"],
|
|
71
|
+
self.s.incarnation,
|
|
72
|
+
"knowledge-v1",
|
|
73
|
+
who["principal"],
|
|
74
|
+
action,
|
|
75
|
+
key,
|
|
76
|
+
)
|
|
77
|
+
if mutation:
|
|
78
|
+
existing = self.db.execute(
|
|
79
|
+
"SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
80
|
+
lookup,
|
|
81
|
+
).fetchone()
|
|
82
|
+
if existing is not None:
|
|
83
|
+
if existing["hash"] != canonical_hash(command):
|
|
84
|
+
raise LocalError("idempotency_conflict")
|
|
85
|
+
if existing["result"] is None or at >= existing["expires"]:
|
|
86
|
+
raise LocalError("idempotency_result_expired")
|
|
87
|
+
result = json.loads(existing["result"])
|
|
88
|
+
# Replay contains IDs only, but the operation's present authority is required.
|
|
89
|
+
if action == "review":
|
|
90
|
+
self._authority(
|
|
91
|
+
credential,
|
|
92
|
+
self._revision(who["tenant"], args["revision"], args["project"]),
|
|
93
|
+
at,
|
|
94
|
+
)
|
|
95
|
+
elif action == "propose":
|
|
96
|
+
result = self.propose(credential, who, args, at)
|
|
97
|
+
elif action == "draft":
|
|
98
|
+
from memoryking.adapters.proposals import Proposals
|
|
99
|
+
|
|
100
|
+
result = Proposals(self).draft(credential, who, args, at)
|
|
101
|
+
elif action == "promote":
|
|
102
|
+
result = self.promote(credential, who, args, at)
|
|
103
|
+
elif action == "review":
|
|
104
|
+
result = self.review(credential, who, args, at)
|
|
105
|
+
elif action == "attest":
|
|
106
|
+
result = self.attest(who, args, at)
|
|
107
|
+
else:
|
|
108
|
+
result = self.query(who, args, at, constraints=action == "constraints")
|
|
109
|
+
if mutation and existing is None:
|
|
110
|
+
self.db.execute(
|
|
111
|
+
"INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
112
|
+
(*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
|
|
113
|
+
)
|
|
114
|
+
if len(json.dumps(result).encode()) > 524288:
|
|
115
|
+
result = {"status": "blocked", "reason": "response_limit_exceeded", "items": []}
|
|
116
|
+
result = {
|
|
117
|
+
**result,
|
|
118
|
+
"incarnation": self.s.incarnation,
|
|
119
|
+
"evaluated_ms": at,
|
|
120
|
+
"deadline_ms": decision.deadline_ms,
|
|
121
|
+
"receipt": uid("rcpt"),
|
|
122
|
+
}
|
|
123
|
+
epochs = self.db.execute(
|
|
124
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
125
|
+
).fetchone()
|
|
126
|
+
self.db.execute(
|
|
127
|
+
"INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
128
|
+
(
|
|
129
|
+
who["tenant"],
|
|
130
|
+
result["receipt"],
|
|
131
|
+
who["principal"],
|
|
132
|
+
self.s.incarnation,
|
|
133
|
+
at,
|
|
134
|
+
decision.deadline_ms,
|
|
135
|
+
*epochs,
|
|
136
|
+
canonical_hash(result),
|
|
137
|
+
"[]",
|
|
138
|
+
),
|
|
139
|
+
)
|
|
140
|
+
self.s.fault("after_validation")
|
|
141
|
+
self.s._expose()
|
|
142
|
+
return Released(canonical_bytes(result), decision, self.s.clock)
|
|
143
|
+
|
|
144
|
+
def _revision(self, tenant: str, revision: str, project: str | None = None) -> sqlite3.Row:
|
|
145
|
+
row = self.db.execute(
|
|
146
|
+
"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 r.id=?",
|
|
147
|
+
(tenant, revision),
|
|
148
|
+
).fetchone()
|
|
149
|
+
if row is None or (project is not None and row["project"] != project):
|
|
150
|
+
raise LocalError("unavailable")
|
|
151
|
+
return cast(sqlite3.Row, row)
|
|
152
|
+
|
|
153
|
+
def _support(self, who: dict[str, Any], evidence: list[dict[str, Any]], at: int) -> None:
|
|
154
|
+
for span in evidence:
|
|
155
|
+
row = self.db.execute(
|
|
156
|
+
"SELECT * FROM observations WHERE tenant=? AND id=?",
|
|
157
|
+
(who["tenant"], span["observation"]),
|
|
158
|
+
).fetchone()
|
|
159
|
+
if row is None or not self.s._visible(who, row, at):
|
|
160
|
+
raise LocalError("evidence_unavailable")
|
|
161
|
+
path = self.s.root / "blobs" / who["tenant"] / row["blob"]
|
|
162
|
+
private_file(path)
|
|
163
|
+
raw = path.read_bytes()
|
|
164
|
+
if (
|
|
165
|
+
hashlib.sha256(raw).hexdigest() != row["blob"]
|
|
166
|
+
or span["content_hash"] != row["blob"]
|
|
167
|
+
):
|
|
168
|
+
raise LocalError("evidence_changed")
|
|
169
|
+
start, end = span["start_byte"], span["end_byte"]
|
|
170
|
+
if not 0 <= start < end <= len(raw):
|
|
171
|
+
raise LocalError("invalid_evidence_span")
|
|
172
|
+
try:
|
|
173
|
+
raw[:start].decode()
|
|
174
|
+
raw[start:end].decode()
|
|
175
|
+
except UnicodeDecodeError as exc:
|
|
176
|
+
raise LocalError("invalid_evidence_span") from exc
|
|
177
|
+
|
|
178
|
+
def _evidence(self, tenant: str, revision: str) -> list[dict[str, Any]]:
|
|
179
|
+
return [
|
|
180
|
+
dict(row)
|
|
181
|
+
for row in self.db.execute(
|
|
182
|
+
"SELECT observation,start_byte,end_byte,content_hash FROM evidence_spans WHERE tenant=? AND revision=?",
|
|
183
|
+
(tenant, revision),
|
|
184
|
+
)
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
def _available(self, who: dict[str, Any], row: sqlite3.Row, at: int) -> bool:
|
|
188
|
+
if row["purged"] or row["body"] is None:
|
|
189
|
+
return False
|
|
190
|
+
body = json.loads(row["body"])
|
|
191
|
+
if body["readers"] is not None and who["principal"] not in body["readers"]:
|
|
192
|
+
return False
|
|
193
|
+
try:
|
|
194
|
+
self.s._subject_auth(
|
|
195
|
+
self.s._token("credential", tenant=who["tenant"], principal=who["principal"]),
|
|
196
|
+
"read",
|
|
197
|
+
row["project"],
|
|
198
|
+
at,
|
|
199
|
+
)
|
|
200
|
+
self._support(who, self._evidence(who["tenant"], row["id"]), at)
|
|
201
|
+
except LocalError:
|
|
202
|
+
return False
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
def _authority(self, credential: str, row: sqlite3.Row, at: int) -> None:
|
|
206
|
+
if row["body"] is None:
|
|
207
|
+
self.s._auth(
|
|
208
|
+
credential,
|
|
209
|
+
"policy" if row["kind"] == "constraint" else "review",
|
|
210
|
+
row["project"],
|
|
211
|
+
at,
|
|
212
|
+
)
|
|
213
|
+
return
|
|
214
|
+
body = json.loads(row["body"])
|
|
215
|
+
if row["kind"] == "constraint":
|
|
216
|
+
cap = "task_constraint" if body["authority"] == "task" else "policy"
|
|
217
|
+
who = self.s._auth(credential, cap, row["project"], at)
|
|
218
|
+
if cap == "task_constraint" and who["principal"] != row["issuer"]:
|
|
219
|
+
self.s._auth(credential, "policy", row["project"], at)
|
|
220
|
+
|
|
221
|
+
def propose(
|
|
222
|
+
self, credential: str, who: dict[str, Any], args: dict[str, Any], at: int
|
|
223
|
+
) -> dict[str, Any]:
|
|
224
|
+
tenant, body = who["tenant"], dict(args["body"])
|
|
225
|
+
if (
|
|
226
|
+
body["valid_start"] is not None
|
|
227
|
+
and body["valid_end"] is not None
|
|
228
|
+
and body["valid_start"] >= body["valid_end"]
|
|
229
|
+
):
|
|
230
|
+
raise LocalError("invalid_interval")
|
|
231
|
+
if body["run"] and not body["task"]:
|
|
232
|
+
raise LocalError("invalid_scope")
|
|
233
|
+
if args["project"] in {"_tenant", "_workspace"}:
|
|
234
|
+
self.s._auth(credential, "admin", "*", at)
|
|
235
|
+
if body["kind"] != "constraint" or body["task"] or body["run"]:
|
|
236
|
+
raise LocalError("invalid_scope")
|
|
237
|
+
if body["kind"] == "constraint":
|
|
238
|
+
if body["authority"] not in {"project", "task"}:
|
|
239
|
+
raise LocalError("invalid_constraint")
|
|
240
|
+
self.s._auth(
|
|
241
|
+
credential,
|
|
242
|
+
"task_constraint" if body["authority"] == "task" else "policy",
|
|
243
|
+
args["project"],
|
|
244
|
+
at,
|
|
245
|
+
)
|
|
246
|
+
if body["authority"] == "task" and not body["task"]:
|
|
247
|
+
raise LocalError("invalid_scope")
|
|
248
|
+
if body["rule_key"] is None or body["effect"] is None or body["rule_value"] is None:
|
|
249
|
+
raise LocalError("invalid_constraint")
|
|
250
|
+
elif any(body[k] is not None for k in ("authority", "rule_key", "effect", "rule_value")):
|
|
251
|
+
raise LocalError("invalid_constraint")
|
|
252
|
+
try:
|
|
253
|
+
body["selector"] = selectors.canonical(body["selector"])
|
|
254
|
+
executable = True
|
|
255
|
+
except LocalError as exc:
|
|
256
|
+
if exc.code not in {"selector_unsupported", "selector_empty"} or not args.get(
|
|
257
|
+
"preserve_legacy", False
|
|
258
|
+
):
|
|
259
|
+
raise
|
|
260
|
+
executable = False
|
|
261
|
+
self._support(who, body["evidence"], at)
|
|
262
|
+
row = self.db.execute(
|
|
263
|
+
"SELECT * FROM families WHERE tenant=? AND project=? AND logical_key=?",
|
|
264
|
+
(tenant, args["project"], args["logical_key"]),
|
|
265
|
+
).fetchone()
|
|
266
|
+
if row is not None:
|
|
267
|
+
prior = self.db.execute(
|
|
268
|
+
"SELECT kind FROM revisions WHERE tenant=? AND family=? LIMIT 1",
|
|
269
|
+
(tenant, row["id"]),
|
|
270
|
+
).fetchone()
|
|
271
|
+
if prior is not None and prior[0] != body["kind"]:
|
|
272
|
+
raise LocalError("family_kind_mismatch")
|
|
273
|
+
version = row["version"] if row else 0
|
|
274
|
+
if args["expected_version"] != version:
|
|
275
|
+
raise LocalError("family_version_conflict")
|
|
276
|
+
family = row["id"] if row else uid("family")
|
|
277
|
+
if row is None:
|
|
278
|
+
self.db.execute(
|
|
279
|
+
"INSERT INTO families VALUES (?,?,?,?,0)",
|
|
280
|
+
(tenant, family, args["project"], args["logical_key"]),
|
|
281
|
+
)
|
|
282
|
+
revision = uid("rev")
|
|
283
|
+
position = self.s._event(tenant, "propose", revision, at, who["principal"])
|
|
284
|
+
body["executable"] = executable
|
|
285
|
+
self.db.execute(
|
|
286
|
+
"INSERT INTO revisions VALUES (?,?,?,?,?,?,?,?,?,0)",
|
|
287
|
+
(
|
|
288
|
+
tenant,
|
|
289
|
+
revision,
|
|
290
|
+
family,
|
|
291
|
+
json.dumps(body),
|
|
292
|
+
canonical_hash(body),
|
|
293
|
+
body["kind"],
|
|
294
|
+
who["principal"],
|
|
295
|
+
position,
|
|
296
|
+
self.s.incarnation,
|
|
297
|
+
),
|
|
298
|
+
)
|
|
299
|
+
for span in body["evidence"]:
|
|
300
|
+
self.db.execute(
|
|
301
|
+
"INSERT INTO evidence_spans VALUES (?,?,?,?,?,?)",
|
|
302
|
+
(
|
|
303
|
+
tenant,
|
|
304
|
+
revision,
|
|
305
|
+
span["observation"],
|
|
306
|
+
span["start_byte"],
|
|
307
|
+
span["end_byte"],
|
|
308
|
+
span["content_hash"],
|
|
309
|
+
),
|
|
310
|
+
)
|
|
311
|
+
self.db.execute(
|
|
312
|
+
"UPDATE families SET version=version+1 WHERE tenant=? AND id=?", (tenant, family)
|
|
313
|
+
)
|
|
314
|
+
self.s._enqueue(tenant, position, None, who["principal"])
|
|
315
|
+
return {
|
|
316
|
+
"revision": revision,
|
|
317
|
+
"family": family,
|
|
318
|
+
"family_version": version + 1,
|
|
319
|
+
"position": position,
|
|
320
|
+
"state": "proposed",
|
|
321
|
+
"executable": executable,
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
def _state(self, tenant: str, revision: str, position: int) -> tuple[str, bool]:
|
|
325
|
+
state, quarantine = "proposed", False
|
|
326
|
+
for row in self.db.execute(
|
|
327
|
+
"SELECT action FROM lifecycle WHERE tenant=? AND revision=? AND position<=? ORDER BY position",
|
|
328
|
+
(tenant, revision, position),
|
|
329
|
+
):
|
|
330
|
+
if row[0] == "quarantine":
|
|
331
|
+
quarantine = True
|
|
332
|
+
elif row[0] == "release_quarantine":
|
|
333
|
+
quarantine = False
|
|
334
|
+
else:
|
|
335
|
+
state = {"accept": "accepted", "reject": "rejected", "deprecate": "deprecated"}.get(
|
|
336
|
+
row[0], state
|
|
337
|
+
)
|
|
338
|
+
return state, quarantine
|
|
339
|
+
|
|
340
|
+
def review(
|
|
341
|
+
self,
|
|
342
|
+
credential: str,
|
|
343
|
+
who: dict[str, Any],
|
|
344
|
+
args: dict[str, Any],
|
|
345
|
+
at: int,
|
|
346
|
+
*,
|
|
347
|
+
procedure: bool = False,
|
|
348
|
+
) -> dict[str, Any]:
|
|
349
|
+
tenant = who["tenant"]
|
|
350
|
+
row = self._revision(tenant, args["revision"], args["project"])
|
|
351
|
+
if (row["kind"] == "procedure") != procedure:
|
|
352
|
+
raise LocalError("procedure_review_required")
|
|
353
|
+
if row["family_version"] != args["expected_version"]:
|
|
354
|
+
raise LocalError("family_version_conflict")
|
|
355
|
+
self._authority(credential, row, at)
|
|
356
|
+
if not self._available(who, row, at) and not (
|
|
357
|
+
row["purged"] and args["decision"] == "deprecate"
|
|
358
|
+
):
|
|
359
|
+
raise LocalError("evidence_unavailable")
|
|
360
|
+
action, body = args["decision"], json.loads(row["body"]) if row["body"] else {}
|
|
361
|
+
state, quarantine = self._state(tenant, row["id"], 9_007_199_254_740_991)
|
|
362
|
+
if action in {"accept", "release_quarantine"}:
|
|
363
|
+
if not body["executable"]:
|
|
364
|
+
raise LocalError("selector_unsupported")
|
|
365
|
+
selectors.canonical(body["selector"])
|
|
366
|
+
if not args["breadth_reviewed"]:
|
|
367
|
+
raise LocalError("breadth_review_required")
|
|
368
|
+
if (
|
|
369
|
+
(action in {"accept", "reject"} and state != "proposed")
|
|
370
|
+
or (action == "accept" and quarantine)
|
|
371
|
+
or (action == "deprecate" and state != "accepted")
|
|
372
|
+
or (action == "release_quarantine" and not quarantine)
|
|
373
|
+
):
|
|
374
|
+
raise LocalError("invalid_transition")
|
|
375
|
+
replacement = args.get("replacement")
|
|
376
|
+
if replacement and action != "accept":
|
|
377
|
+
raise LocalError("invalid_transition")
|
|
378
|
+
if replacement:
|
|
379
|
+
predecessor = self._revision(tenant, replacement["predecessor"], args["project"])
|
|
380
|
+
if predecessor["family"] != row["family"] or predecessor["id"] == row["id"]:
|
|
381
|
+
raise LocalError("unrelated_replacement")
|
|
382
|
+
if self._state(tenant, predecessor["id"], 9_007_199_254_740_991)[0] != "accepted":
|
|
383
|
+
raise LocalError("invalid_transition")
|
|
384
|
+
if not self._available(who, predecessor, at):
|
|
385
|
+
raise LocalError("evidence_unavailable")
|
|
386
|
+
previous = json.loads(predecessor["body"])
|
|
387
|
+
self._authority(credential, predecessor, at)
|
|
388
|
+
if any(previous[k] != body[k] for k in ("kind", "authority", "task", "run")):
|
|
389
|
+
raise LocalError("unrelated_replacement")
|
|
390
|
+
replacement = dict(replacement)
|
|
391
|
+
replacement["selector"] = selectors.canonical(replacement["selector"])
|
|
392
|
+
for candidate in (body, previous):
|
|
393
|
+
proof = selectors.contains(replacement["selector"], candidate["selector"])
|
|
394
|
+
if proof != "proven":
|
|
395
|
+
raise LocalError(
|
|
396
|
+
"replacement_out_of_range"
|
|
397
|
+
if proof == "disproven"
|
|
398
|
+
else "selector_relation_indeterminate"
|
|
399
|
+
)
|
|
400
|
+
start, end = replacement["valid_start"], replacement["valid_end"]
|
|
401
|
+
if (
|
|
402
|
+
(start is not None and end is not None and start >= end)
|
|
403
|
+
or (
|
|
404
|
+
candidate["valid_start"] is not None
|
|
405
|
+
and (start is None or start < candidate["valid_start"])
|
|
406
|
+
)
|
|
407
|
+
or (
|
|
408
|
+
candidate["valid_end"] is not None
|
|
409
|
+
and (end is None or end > candidate["valid_end"])
|
|
410
|
+
)
|
|
411
|
+
):
|
|
412
|
+
raise LocalError("replacement_out_of_range")
|
|
413
|
+
# Accepting only proposed successors makes replacement edges acyclic.
|
|
414
|
+
journal = {
|
|
415
|
+
"kind": "knowledge",
|
|
416
|
+
"tenant": tenant,
|
|
417
|
+
"actor": who["principal"],
|
|
418
|
+
"revision": row["id"],
|
|
419
|
+
"decision": action,
|
|
420
|
+
"reason": args["reason"],
|
|
421
|
+
"replacement": replacement,
|
|
422
|
+
"expected_hash": row["body_hash"],
|
|
423
|
+
}
|
|
424
|
+
self.s._apply(self.s._journal(journal), at)
|
|
425
|
+
return {
|
|
426
|
+
"revision": row["id"],
|
|
427
|
+
"family": row["family"],
|
|
428
|
+
"family_version": row["family_version"] + 1,
|
|
429
|
+
"state": action,
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
def apply_policy(self, action: dict[str, Any], at: int) -> None:
|
|
433
|
+
tenant = action["tenant"]
|
|
434
|
+
row = self.db.execute(
|
|
435
|
+
"SELECT * FROM revisions WHERE tenant=? AND id=?", (tenant, action["revision"])
|
|
436
|
+
).fetchone()
|
|
437
|
+
replacement = action["replacement"]
|
|
438
|
+
missing_previous = (
|
|
439
|
+
replacement
|
|
440
|
+
and self.db.execute(
|
|
441
|
+
"SELECT 1 FROM revisions WHERE tenant=? AND id=?",
|
|
442
|
+
(tenant, replacement["predecessor"]),
|
|
443
|
+
).fetchone()
|
|
444
|
+
is None
|
|
445
|
+
)
|
|
446
|
+
if row is None or row["body_hash"] != action["expected_hash"] or missing_previous:
|
|
447
|
+
# Never erase current policy or revive a predecessor when its decision
|
|
448
|
+
# cannot be reconstructed from the restored content snapshot.
|
|
449
|
+
self.db.execute(
|
|
450
|
+
"UPDATE knowledge_state SET recovery_gap=1,generation=generation+1 WHERE tenant=?",
|
|
451
|
+
(tenant,),
|
|
452
|
+
)
|
|
453
|
+
return
|
|
454
|
+
position = self.s._event(tenant, "review", row["id"], at, action["actor"])
|
|
455
|
+
self.db.execute(
|
|
456
|
+
"INSERT INTO lifecycle VALUES (?,?,?,?,?)",
|
|
457
|
+
(
|
|
458
|
+
tenant,
|
|
459
|
+
row["id"],
|
|
460
|
+
position,
|
|
461
|
+
action["decision"],
|
|
462
|
+
json.dumps({"reason": action["reason"], "actor": action["actor"]}),
|
|
463
|
+
),
|
|
464
|
+
)
|
|
465
|
+
if replacement:
|
|
466
|
+
self.db.execute(
|
|
467
|
+
"INSERT INTO replacements VALUES (?,?,?,?,?,?,?)",
|
|
468
|
+
(
|
|
469
|
+
tenant,
|
|
470
|
+
replacement["predecessor"],
|
|
471
|
+
row["id"],
|
|
472
|
+
position,
|
|
473
|
+
json.dumps(replacement["selector"]),
|
|
474
|
+
replacement["valid_start"],
|
|
475
|
+
replacement["valid_end"],
|
|
476
|
+
),
|
|
477
|
+
)
|
|
478
|
+
if action["decision"] == "accept":
|
|
479
|
+
for other in self.db.execute(
|
|
480
|
+
"SELECT * FROM revisions WHERE tenant=? AND family=? AND id!=?",
|
|
481
|
+
(tenant, row["family"], row["id"]),
|
|
482
|
+
).fetchall():
|
|
483
|
+
if self._state(tenant, other["id"], position)[0] == "accepted":
|
|
484
|
+
self.db.execute(
|
|
485
|
+
insert_ignore("conflicts", 4),
|
|
486
|
+
(tenant, other["id"], row["id"], position),
|
|
487
|
+
)
|
|
488
|
+
self.db.execute(
|
|
489
|
+
"UPDATE families SET version=version+1 WHERE tenant=? AND id=?", (tenant, row["family"])
|
|
490
|
+
)
|
|
491
|
+
self.db.execute(
|
|
492
|
+
"UPDATE knowledge_state SET generation=generation+1 WHERE tenant=?", (tenant,)
|
|
493
|
+
)
|
|
494
|
+
self.s._enqueue(tenant, position, None, action["actor"])
|
|
495
|
+
|
|
496
|
+
def purge_dependencies(self, tenant: str, observation: str) -> None:
|
|
497
|
+
ids = [
|
|
498
|
+
r[0]
|
|
499
|
+
for r in self.db.execute(
|
|
500
|
+
"SELECT revision FROM evidence_spans WHERE tenant=? AND observation=?",
|
|
501
|
+
(tenant, observation),
|
|
502
|
+
)
|
|
503
|
+
]
|
|
504
|
+
for revision in ids:
|
|
505
|
+
self.db.execute(
|
|
506
|
+
"UPDATE revisions SET body=NULL,purged=1 WHERE tenant=? AND id=?",
|
|
507
|
+
(tenant, revision),
|
|
508
|
+
)
|
|
509
|
+
self.db.execute(
|
|
510
|
+
"UPDATE attestations SET statement=NULL WHERE tenant=? AND revision=?",
|
|
511
|
+
(tenant, revision),
|
|
512
|
+
)
|
|
513
|
+
self.db.execute(
|
|
514
|
+
"UPDATE knowledge_state SET generation=generation+1 WHERE tenant=?", (tenant,)
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
def attest(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
518
|
+
row = self._revision(who["tenant"], args["revision"], args["project"])
|
|
519
|
+
if not self._available(who, row, at) or args["expires_ms"] <= at:
|
|
520
|
+
raise LocalError("evidence_unavailable")
|
|
521
|
+
position = self.s._event(who["tenant"], "attest", row["id"], at, who["principal"])
|
|
522
|
+
ident = uid("att")
|
|
523
|
+
self.db.execute(
|
|
524
|
+
"INSERT INTO attestations VALUES (?,?,?,?,?,?,?)",
|
|
525
|
+
(
|
|
526
|
+
who["tenant"],
|
|
527
|
+
ident,
|
|
528
|
+
row["id"],
|
|
529
|
+
who["principal"],
|
|
530
|
+
position,
|
|
531
|
+
args["expires_ms"],
|
|
532
|
+
args["statement"],
|
|
533
|
+
),
|
|
534
|
+
)
|
|
535
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
536
|
+
return {"attestation": ident, "position": position}
|
|
537
|
+
|
|
538
|
+
def promote(
|
|
539
|
+
self, credential: str, who: dict[str, Any], args: dict[str, Any], at: int
|
|
540
|
+
) -> dict[str, Any]:
|
|
541
|
+
source = self._revision(who["tenant"], args["revision"])
|
|
542
|
+
self.s._auth(credential, "review", source["project"], at)
|
|
543
|
+
self.s._auth(credential, "export", source["project"], at)
|
|
544
|
+
if not self._available(who, source, at):
|
|
545
|
+
raise LocalError("evidence_unavailable")
|
|
546
|
+
if source["kind"] == "procedure":
|
|
547
|
+
raise LocalError("procedure_review_required")
|
|
548
|
+
body = json.loads(source["body"])
|
|
549
|
+
body.pop("executable")
|
|
550
|
+
body["provenance"] = {"promoted_from": source["id"], "source_hash": source["body_hash"]}
|
|
551
|
+
# Original evidence dependencies remain; promotion cannot silently widen their audience.
|
|
552
|
+
return self.propose(
|
|
553
|
+
credential,
|
|
554
|
+
who,
|
|
555
|
+
{
|
|
556
|
+
"project": args["project"],
|
|
557
|
+
"logical_key": args["logical_key"],
|
|
558
|
+
"expected_version": args["expected_version"],
|
|
559
|
+
"body": body,
|
|
560
|
+
},
|
|
561
|
+
at,
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
def _eligible(
|
|
565
|
+
self,
|
|
566
|
+
row: sqlite3.Row,
|
|
567
|
+
body: dict[str, Any],
|
|
568
|
+
binding: dict[str, Any],
|
|
569
|
+
valid: int,
|
|
570
|
+
recorded: int,
|
|
571
|
+
who: dict[str, Any] | None = None,
|
|
572
|
+
at: int | None = None,
|
|
573
|
+
) -> selectors.Truth:
|
|
574
|
+
if not temporal_valid(valid, body["valid_start"], body["valid_end"]):
|
|
575
|
+
return "false"
|
|
576
|
+
from memoryking.adapters.repository_store import Repository
|
|
577
|
+
|
|
578
|
+
repo = Repository(self.s)
|
|
579
|
+
ancestry = (
|
|
580
|
+
(
|
|
581
|
+
lambda r, a, c: repo.ancestry(
|
|
582
|
+
who, row["project"], r, a, c, binding.get("snapshot_id")
|
|
583
|
+
)
|
|
584
|
+
)
|
|
585
|
+
if who is not None
|
|
586
|
+
else None
|
|
587
|
+
)
|
|
588
|
+
match = selectors.evaluate(body["selector"], binding, ancestry)
|
|
589
|
+
if match != "false" and who is not None and at is not None:
|
|
590
|
+
code = repo.eligibility(who, row, binding, at)
|
|
591
|
+
if code == "false":
|
|
592
|
+
return "false"
|
|
593
|
+
if code == "unknown":
|
|
594
|
+
match = "unknown"
|
|
595
|
+
if match == "false":
|
|
596
|
+
return match
|
|
597
|
+
for edge in self.db.execute(
|
|
598
|
+
"SELECT * FROM replacements WHERE tenant=? AND predecessor=? AND position<=?",
|
|
599
|
+
(row["tenant"], row["id"], recorded),
|
|
600
|
+
):
|
|
601
|
+
if temporal_valid(valid, edge["valid_start"], edge["valid_end"]):
|
|
602
|
+
mask = selectors.evaluate(json.loads(edge["selector"]), binding, ancestry)
|
|
603
|
+
if mask == "true":
|
|
604
|
+
return "false"
|
|
605
|
+
if mask == "unknown":
|
|
606
|
+
match = "unknown"
|
|
607
|
+
return match
|
|
608
|
+
|
|
609
|
+
def query(
|
|
610
|
+
self,
|
|
611
|
+
who: dict[str, Any],
|
|
612
|
+
args: dict[str, Any],
|
|
613
|
+
at: int,
|
|
614
|
+
*,
|
|
615
|
+
constraints: bool,
|
|
616
|
+
attestation_limit: int = 256,
|
|
617
|
+
) -> dict[str, Any]:
|
|
618
|
+
tenant = who["tenant"]
|
|
619
|
+
state = self.db.execute(
|
|
620
|
+
"SELECT * FROM knowledge_state WHERE tenant=?", (tenant,)
|
|
621
|
+
).fetchone()
|
|
622
|
+
generation = state["generation"]
|
|
623
|
+
if state["recovery_gap"]:
|
|
624
|
+
return {"status": "blocked", "reason": "knowledge_reconciliation_required", "items": []}
|
|
625
|
+
points = selectors.bindings(args["bindings"])
|
|
626
|
+
frontier = self.db.execute(
|
|
627
|
+
"SELECT position FROM tenants WHERE tenant=?", (tenant,)
|
|
628
|
+
).fetchone()[0]
|
|
629
|
+
recorded = args.get("recorded_position", frontier)
|
|
630
|
+
if recorded > frontier:
|
|
631
|
+
raise LocalError("invalid_recorded_position")
|
|
632
|
+
# Mandatory current policy cannot be waived by a historical query.
|
|
633
|
+
if constraints:
|
|
634
|
+
recorded, valid = frontier, at
|
|
635
|
+
else:
|
|
636
|
+
valid = args.get("valid_ms", at)
|
|
637
|
+
rows = self.db.execute(
|
|
638
|
+
"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 IN (?,?,?) AND r.created<=? AND r.kind=? ORDER BY r.created LIMIT ?",
|
|
639
|
+
(
|
|
640
|
+
tenant,
|
|
641
|
+
args["project"],
|
|
642
|
+
"_tenant" if constraints else args["project"],
|
|
643
|
+
"_workspace" if constraints else args["project"],
|
|
644
|
+
recorded,
|
|
645
|
+
"constraint" if constraints else "knowledge",
|
|
646
|
+
REGISTRY_LIMIT + 1,
|
|
647
|
+
),
|
|
648
|
+
).fetchall()
|
|
649
|
+
if len(rows) > REGISTRY_LIMIT:
|
|
650
|
+
return {
|
|
651
|
+
"status": "blocked",
|
|
652
|
+
"reason": "constraint_resolution_incomplete"
|
|
653
|
+
if constraints
|
|
654
|
+
else "knowledge_resolution_incomplete",
|
|
655
|
+
"items": [],
|
|
656
|
+
}
|
|
657
|
+
items: list[dict[str, Any]] = []
|
|
658
|
+
unknown, unavailable = False, False
|
|
659
|
+
matches_by_binding: list[list[dict[str, Any]]] = [[] for _ in points]
|
|
660
|
+
evaluation_work = 0
|
|
661
|
+
for row in rows:
|
|
662
|
+
lifecycle, quarantine_then = self._state(tenant, row["id"], recorded)
|
|
663
|
+
if lifecycle != "accepted" and not (args.get("diagnostic", False) and not constraints):
|
|
664
|
+
continue
|
|
665
|
+
if row["body"] is None:
|
|
666
|
+
# Purged essential policy retains a blocking tombstone; no content leaks.
|
|
667
|
+
if lifecycle == "accepted":
|
|
668
|
+
unavailable = True
|
|
669
|
+
continue
|
|
670
|
+
body = json.loads(row["body"])
|
|
671
|
+
if any(body[k] is not None and body[k] != args.get(k) for k in ("task", "run")):
|
|
672
|
+
# Missing scope can hide required task constraints, so block if unknown.
|
|
673
|
+
if constraints and any(
|
|
674
|
+
body[k] is not None and args.get(k) is None for k in ("task", "run")
|
|
675
|
+
):
|
|
676
|
+
unknown = True
|
|
677
|
+
continue
|
|
678
|
+
if not body["executable"]:
|
|
679
|
+
if args.get("diagnostic", False) and self._available(who, row, at):
|
|
680
|
+
items.append(
|
|
681
|
+
{
|
|
682
|
+
"revision": row["id"],
|
|
683
|
+
"state": lifecycle,
|
|
684
|
+
"authority": "proposed_interpretation",
|
|
685
|
+
"body": body,
|
|
686
|
+
"selector_status": "unsupported",
|
|
687
|
+
}
|
|
688
|
+
)
|
|
689
|
+
continue
|
|
690
|
+
mask_selectors = [
|
|
691
|
+
json.loads(e[0])
|
|
692
|
+
for e in self.db.execute(
|
|
693
|
+
"SELECT selector FROM replacements WHERE tenant=? AND predecessor=? AND position<=?",
|
|
694
|
+
(tenant, row["id"], recorded),
|
|
695
|
+
)
|
|
696
|
+
]
|
|
697
|
+
evaluation_work += len(points) * sum(
|
|
698
|
+
len(c["all_of"])
|
|
699
|
+
for selector in [body["selector"], *mask_selectors]
|
|
700
|
+
for c in selector["any_of"]
|
|
701
|
+
)
|
|
702
|
+
if evaluation_work > 65536:
|
|
703
|
+
return {"status": "blocked", "reason": "selector_limit_exceeded", "items": []}
|
|
704
|
+
matches = [self._eligible(row, body, b, valid, recorded, who, at) for b in points]
|
|
705
|
+
if all(m == "false" for m in matches):
|
|
706
|
+
continue
|
|
707
|
+
if "unknown" in matches:
|
|
708
|
+
unknown = True
|
|
709
|
+
# Never emit a partially validated code claim as current guidance
|
|
710
|
+
# over a declared multi-path/snapshot scope.
|
|
711
|
+
if (
|
|
712
|
+
not args.get("diagnostic", False)
|
|
713
|
+
and self.db.execute(
|
|
714
|
+
"SELECT 1 FROM code_policies WHERE tenant=? AND revision=?",
|
|
715
|
+
(tenant, row["id"]),
|
|
716
|
+
).fetchone()
|
|
717
|
+
):
|
|
718
|
+
continue
|
|
719
|
+
if not self._available(who, row, at):
|
|
720
|
+
unavailable = unavailable or constraints
|
|
721
|
+
continue
|
|
722
|
+
_, quarantined_now = self._state(tenant, row["id"], frontier)
|
|
723
|
+
if (quarantined_now or quarantine_then) and not args.get("diagnostic", False):
|
|
724
|
+
unavailable = True
|
|
725
|
+
continue
|
|
726
|
+
if "true" not in matches and not args.get("diagnostic", False):
|
|
727
|
+
continue
|
|
728
|
+
attestations = [
|
|
729
|
+
dict(a)
|
|
730
|
+
for a in self.db.execute(
|
|
731
|
+
"SELECT actor,position,expires,statement FROM attestations WHERE tenant=? AND revision=? AND position<=? AND expires>? ORDER BY position LIMIT ?",
|
|
732
|
+
(tenant, row["id"], recorded, at, attestation_limit),
|
|
733
|
+
)
|
|
734
|
+
]
|
|
735
|
+
item = {
|
|
736
|
+
"revision": row["id"],
|
|
737
|
+
"family": row["family"],
|
|
738
|
+
"family_version": row["family_version"],
|
|
739
|
+
"body_hash": row["body_hash"],
|
|
740
|
+
"created_position": row["created"],
|
|
741
|
+
"origin": row["origin"],
|
|
742
|
+
"state": lifecycle,
|
|
743
|
+
"quarantined": quarantined_now or quarantine_then,
|
|
744
|
+
"authority": "mandatory_constraint"
|
|
745
|
+
if constraints
|
|
746
|
+
else (
|
|
747
|
+
"accepted_knowledge" if lifecycle == "accepted" else "proposed_interpretation"
|
|
748
|
+
),
|
|
749
|
+
"body": body,
|
|
750
|
+
"applicability": matches,
|
|
751
|
+
"attestations": attestations,
|
|
752
|
+
}
|
|
753
|
+
from memoryking.adapters.repository_store import Repository
|
|
754
|
+
|
|
755
|
+
item["code_validation"] = [
|
|
756
|
+
proof
|
|
757
|
+
for b, match in zip(points, matches, strict=True)
|
|
758
|
+
if match == "true"
|
|
759
|
+
and (proof := Repository(self.s).proof(who, row, b, at)) is not None
|
|
760
|
+
]
|
|
761
|
+
items.append(item)
|
|
762
|
+
if lifecycle == "accepted":
|
|
763
|
+
for i, match in enumerate(matches):
|
|
764
|
+
if match == "true":
|
|
765
|
+
matches_by_binding[i].append(item)
|
|
766
|
+
# A restricted essential dependency must not disclose any hidden IDs/counts.
|
|
767
|
+
if constraints and unavailable:
|
|
768
|
+
return {"status": "blocked", "reason": "essential_policy_unavailable", "items": []}
|
|
769
|
+
conflict_pairs: set[tuple[str, str]] = set()
|
|
770
|
+
for applicable in matches_by_binding:
|
|
771
|
+
for i, left in enumerate(applicable):
|
|
772
|
+
for right in applicable[i + 1 :]:
|
|
773
|
+
lb, rb = left["body"], right["body"]
|
|
774
|
+
conflict = left["family"] == right["family"] and lb["text"] != rb["text"]
|
|
775
|
+
if constraints and lb["rule_key"] == rb["rule_key"]:
|
|
776
|
+
conflict |= (
|
|
777
|
+
lb["effect"] != rb["effect"] or lb["rule_value"] != rb["rule_value"]
|
|
778
|
+
)
|
|
779
|
+
if conflict:
|
|
780
|
+
conflict_pairs.add(tuple(sorted((left["revision"], right["revision"]))))
|
|
781
|
+
reason = (
|
|
782
|
+
"applicability_unknown"
|
|
783
|
+
if unknown
|
|
784
|
+
else "guidance_unavailable"
|
|
785
|
+
if unavailable
|
|
786
|
+
else "unresolved_conflict"
|
|
787
|
+
if conflict_pairs
|
|
788
|
+
else None
|
|
789
|
+
)
|
|
790
|
+
return {
|
|
791
|
+
"status": "blocked" if reason else "complete",
|
|
792
|
+
"reason": reason,
|
|
793
|
+
"items": items,
|
|
794
|
+
"conflicts": [list(pair) for pair in sorted(conflict_pairs)],
|
|
795
|
+
"constraint_generation": generation if constraints else None,
|
|
796
|
+
"recorded_position": recorded,
|
|
797
|
+
"valid_ms": valid,
|
|
798
|
+
"binding_count": len(points),
|
|
799
|
+
"authority": "complete_registry" if constraints else "knowledge_inspection",
|
|
800
|
+
}
|