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,960 @@
|
|
|
1
|
+
"""Authorized repository snapshots and dependency validation under the release gate."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from jsonschema import Draft202012Validator
|
|
11
|
+
|
|
12
|
+
from memoryking.adapters.local_files import private_file
|
|
13
|
+
from memoryking.adapters.local_store import RETRY_MS, uid
|
|
14
|
+
from memoryking.adapters.repository_git import GitSnapshot, canonical_remote
|
|
15
|
+
from memoryking.application.storage import upsert
|
|
16
|
+
from memoryking.application.store_core import StoreCore
|
|
17
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash
|
|
18
|
+
from memoryking.domain.local import LocalError, Released
|
|
19
|
+
from memoryking.domain.selectors import Truth, bindings, path_valid
|
|
20
|
+
|
|
21
|
+
VALIDATOR = Draft202012Validator(
|
|
22
|
+
json.loads(Path(__file__).with_name("repository.schema.json").read_text())
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Repository:
|
|
27
|
+
def __init__(self, store: StoreCore):
|
|
28
|
+
self.s, self.db = store, store.db
|
|
29
|
+
|
|
30
|
+
def execute(self, credential: str, command: dict[str, Any]) -> Released:
|
|
31
|
+
if not VALIDATOR.is_valid(command) or len(canonical_bytes(command)) > 131072:
|
|
32
|
+
raise LocalError("invalid_request")
|
|
33
|
+
if command["incarnation"] != self.s.incarnation:
|
|
34
|
+
raise LocalError("history_changed")
|
|
35
|
+
action, args = command["action"], command["args"]
|
|
36
|
+
mutation = action not in {"inspect", "impact", "coverage", "pending", "history"}
|
|
37
|
+
cap = {
|
|
38
|
+
"register": "admin",
|
|
39
|
+
"capture": "repository",
|
|
40
|
+
"bind": "review",
|
|
41
|
+
"verify": "attest",
|
|
42
|
+
"revalidate": "repository",
|
|
43
|
+
}.get(action, "read")
|
|
44
|
+
# Git runs before the write transaction so the store lock never waits on the
|
|
45
|
+
# repository; the commit below rechecks authorization and clone identity.
|
|
46
|
+
snapshot = self.snapshot_outside(credential, args) if action == "capture" else None
|
|
47
|
+
with self.s.transaction() as decision:
|
|
48
|
+
at = decision.evaluated_ms
|
|
49
|
+
who = self.s._auth(credential, cap, args["project"], at)
|
|
50
|
+
self.s._auth(credential, "read", args["project"], at)
|
|
51
|
+
if action == "bind":
|
|
52
|
+
from memoryking.adapters.knowledge_store import Knowledge
|
|
53
|
+
|
|
54
|
+
self.s._auth(credential, "attest", args["project"], at)
|
|
55
|
+
Knowledge(self.s)._authority(
|
|
56
|
+
credential, self._claim(who, args["revision"], args["project"], at), at
|
|
57
|
+
)
|
|
58
|
+
if "repository" in args:
|
|
59
|
+
self.visible(who, args["repository"], args["project"])
|
|
60
|
+
lookup = (
|
|
61
|
+
who["tenant"],
|
|
62
|
+
self.s.incarnation,
|
|
63
|
+
"repository-v1",
|
|
64
|
+
who["principal"],
|
|
65
|
+
action,
|
|
66
|
+
command.get("key"),
|
|
67
|
+
)
|
|
68
|
+
existing = (
|
|
69
|
+
self.db.execute(
|
|
70
|
+
"SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
71
|
+
lookup,
|
|
72
|
+
).fetchone()
|
|
73
|
+
if mutation
|
|
74
|
+
else None
|
|
75
|
+
)
|
|
76
|
+
if existing is not None:
|
|
77
|
+
if existing["hash"] != canonical_hash(command):
|
|
78
|
+
raise LocalError("idempotency_conflict")
|
|
79
|
+
if existing["result"] is None or at >= existing["expires"]:
|
|
80
|
+
raise LocalError("idempotency_result_expired")
|
|
81
|
+
# Present visibility still applies to retries of claim-dependent operations.
|
|
82
|
+
if "revision" in args:
|
|
83
|
+
self._claim(who, args["revision"], args["project"], at)
|
|
84
|
+
result = json.loads(existing["result"])
|
|
85
|
+
elif action == "register":
|
|
86
|
+
result = self.register(who, args, at)
|
|
87
|
+
elif action == "capture":
|
|
88
|
+
assert snapshot is not None
|
|
89
|
+
result = self.capture(who, args, at, snapshot)
|
|
90
|
+
elif action == "bind":
|
|
91
|
+
result = self.bind(who, args, at)
|
|
92
|
+
elif action == "verify":
|
|
93
|
+
result = self.verify(who, args, at)
|
|
94
|
+
elif action == "revalidate":
|
|
95
|
+
result = self.revalidate(who, args, at)
|
|
96
|
+
elif action == "pending":
|
|
97
|
+
result = {
|
|
98
|
+
"jobs": [
|
|
99
|
+
dict(row)
|
|
100
|
+
for row in self.db.execute(
|
|
101
|
+
"SELECT snapshot,generation,state FROM repository_jobs WHERE tenant=? AND incarnation=? AND repository=? AND state='pending' ORDER BY generation DESC LIMIT 1",
|
|
102
|
+
(who["tenant"], self.s.incarnation, args["repository"]),
|
|
103
|
+
)
|
|
104
|
+
]
|
|
105
|
+
}
|
|
106
|
+
elif action == "history":
|
|
107
|
+
result = self.history(who, args, at)
|
|
108
|
+
elif action == "impact":
|
|
109
|
+
result = self.impact(who, args, at)
|
|
110
|
+
elif action == "coverage":
|
|
111
|
+
result = self.coverage(who, args)
|
|
112
|
+
else:
|
|
113
|
+
snap = self.snapshot(who["tenant"], args["repository"], args["snapshot"])
|
|
114
|
+
body = json.loads(snap["body"])
|
|
115
|
+
files = sorted(body["files"].items())
|
|
116
|
+
# The full manifest is retained internally; output has an explicit bound.
|
|
117
|
+
result = {k: v for k, v in body.items() if k not in {"files", "ancestors"}}
|
|
118
|
+
result.update(
|
|
119
|
+
files=dict(files[:32]),
|
|
120
|
+
files_total=len(files),
|
|
121
|
+
truncated=len(files) > 32,
|
|
122
|
+
generation=snap["generation"],
|
|
123
|
+
ancestry_complete=body["ancestry_complete"],
|
|
124
|
+
)
|
|
125
|
+
if mutation and existing is None:
|
|
126
|
+
self.db.execute(
|
|
127
|
+
"INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
128
|
+
(*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
|
|
129
|
+
)
|
|
130
|
+
result.update(
|
|
131
|
+
incarnation=self.s.incarnation,
|
|
132
|
+
evaluated_ms=at,
|
|
133
|
+
deadline_ms=decision.deadline_ms,
|
|
134
|
+
receipt=uid("rcpt"),
|
|
135
|
+
)
|
|
136
|
+
if len(canonical_bytes(result)) > 262144:
|
|
137
|
+
result = {
|
|
138
|
+
"status": "blocked",
|
|
139
|
+
"reason": "response_limit_exceeded",
|
|
140
|
+
"receipt": result["receipt"],
|
|
141
|
+
"incarnation": self.s.incarnation,
|
|
142
|
+
}
|
|
143
|
+
epochs = self.db.execute(
|
|
144
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
145
|
+
).fetchone()
|
|
146
|
+
self.db.execute(
|
|
147
|
+
"INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
148
|
+
(
|
|
149
|
+
who["tenant"],
|
|
150
|
+
result["receipt"],
|
|
151
|
+
who["principal"],
|
|
152
|
+
self.s.incarnation,
|
|
153
|
+
at,
|
|
154
|
+
decision.deadline_ms,
|
|
155
|
+
*epochs,
|
|
156
|
+
canonical_hash(result),
|
|
157
|
+
"[]",
|
|
158
|
+
),
|
|
159
|
+
)
|
|
160
|
+
self.s.fault("after_validation")
|
|
161
|
+
self.s._expose()
|
|
162
|
+
return Released(canonical_bytes(result), decision, self.s.clock)
|
|
163
|
+
|
|
164
|
+
def visible(self, who: dict[str, Any], repository: str, project: str) -> sqlite3.Row:
|
|
165
|
+
row = self.db.execute(
|
|
166
|
+
"SELECT * FROM repositories WHERE tenant=? AND id=? AND project=?",
|
|
167
|
+
(who["tenant"], repository, project),
|
|
168
|
+
).fetchone()
|
|
169
|
+
if row is None or (
|
|
170
|
+
row["readers"] != "null" and who["principal"] not in json.loads(row["readers"])
|
|
171
|
+
):
|
|
172
|
+
raise LocalError("unavailable")
|
|
173
|
+
return cast(sqlite3.Row, row)
|
|
174
|
+
|
|
175
|
+
def snapshot(self, tenant: str, repository: str, snapshot: str) -> sqlite3.Row:
|
|
176
|
+
row = self.db.execute(
|
|
177
|
+
"SELECT * FROM repository_snapshots WHERE tenant=? AND incarnation=? AND repository=? AND id=?",
|
|
178
|
+
(tenant, self.s.incarnation, repository, snapshot),
|
|
179
|
+
).fetchone()
|
|
180
|
+
if row is None:
|
|
181
|
+
raise LocalError("snapshot_unchecked")
|
|
182
|
+
return cast(sqlite3.Row, row)
|
|
183
|
+
|
|
184
|
+
def register(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
185
|
+
remote = canonical_remote(args["remote"])
|
|
186
|
+
root = GitSnapshot(Path(args["path"])).root
|
|
187
|
+
if args["readers"] is not None and who["principal"] not in args["readers"]:
|
|
188
|
+
raise LocalError("repository_audience_invalid")
|
|
189
|
+
repo = self.db.execute(
|
|
190
|
+
"SELECT * FROM repositories WHERE tenant=? AND project=? AND remote=?",
|
|
191
|
+
(who["tenant"], args["project"], remote),
|
|
192
|
+
).fetchone()
|
|
193
|
+
if repo is None:
|
|
194
|
+
rid = uid("repo")
|
|
195
|
+
self.db.execute(
|
|
196
|
+
"INSERT INTO repositories(tenant,id,project,remote,readers) VALUES (?,?,?,?,?)",
|
|
197
|
+
(who["tenant"], rid, args["project"], remote, json.dumps(args["readers"])),
|
|
198
|
+
)
|
|
199
|
+
else:
|
|
200
|
+
rid = repo["id"]
|
|
201
|
+
if json.loads(repo["readers"]) != args["readers"]:
|
|
202
|
+
raise LocalError("repository_audience_conflict")
|
|
203
|
+
identity = root.stat()
|
|
204
|
+
existing = self.db.execute(
|
|
205
|
+
"SELECT * FROM repository_clones WHERE tenant=? AND (path=? OR (repository=? AND alias=?))",
|
|
206
|
+
(who["tenant"], str(root), rid, args["clone"]),
|
|
207
|
+
).fetchall()
|
|
208
|
+
if existing:
|
|
209
|
+
raise LocalError("clone_already_registered")
|
|
210
|
+
self.db.execute(
|
|
211
|
+
"INSERT INTO repository_clones VALUES (?,?,?,?,?,?)",
|
|
212
|
+
(who["tenant"], rid, args["clone"], str(root), identity.st_dev, identity.st_ino),
|
|
213
|
+
)
|
|
214
|
+
position = self.s._event(who["tenant"], "repository.registered", rid, at, who["principal"])
|
|
215
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
216
|
+
return {
|
|
217
|
+
"repository": rid,
|
|
218
|
+
"clone": args["clone"],
|
|
219
|
+
"canonical_remote": remote,
|
|
220
|
+
"position": position,
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
def _clone_root(self, who: dict[str, Any], args: dict[str, Any]) -> Path:
|
|
224
|
+
clone = self.db.execute(
|
|
225
|
+
"SELECT * FROM repository_clones WHERE tenant=? AND repository=? AND alias=?",
|
|
226
|
+
(who["tenant"], args["repository"], args["clone"]),
|
|
227
|
+
).fetchone()
|
|
228
|
+
if clone is None:
|
|
229
|
+
raise LocalError("unavailable")
|
|
230
|
+
root = Path(clone["path"])
|
|
231
|
+
identity = root.lstat()
|
|
232
|
+
if root.is_symlink() or (identity.st_dev, identity.st_ino) != (
|
|
233
|
+
clone["device"],
|
|
234
|
+
clone["inode"],
|
|
235
|
+
):
|
|
236
|
+
raise LocalError("repository_clone_changed")
|
|
237
|
+
return root
|
|
238
|
+
|
|
239
|
+
def snapshot_outside(self, credential: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
240
|
+
"""Authorize and locate the clone in a short transaction, then run Git unlocked."""
|
|
241
|
+
with self.s.transaction() as decision:
|
|
242
|
+
at = decision.evaluated_ms
|
|
243
|
+
who = self.s._auth(credential, "repository", args["project"], at)
|
|
244
|
+
self.s._auth(credential, "read", args["project"], at)
|
|
245
|
+
self.visible(who, args["repository"], args["project"])
|
|
246
|
+
root = self._clone_root(who, args)
|
|
247
|
+
return GitSnapshot(root).capture(args["repository"], args["environment"])
|
|
248
|
+
|
|
249
|
+
def capture(
|
|
250
|
+
self, who: dict[str, Any], args: dict[str, Any], at: int, body: dict[str, Any]
|
|
251
|
+
) -> dict[str, Any]:
|
|
252
|
+
self._clone_root(who, args) # The clone must still be the registered one at commit.
|
|
253
|
+
raw = canonical_bytes(body)
|
|
254
|
+
if len(raw) > 4 * 1024 * 1024:
|
|
255
|
+
raise LocalError("repository_projection_limit")
|
|
256
|
+
current = self.visible(who, args["repository"], args["project"])
|
|
257
|
+
if (
|
|
258
|
+
current["current_incarnation"] == self.s.incarnation
|
|
259
|
+
and current["current_snapshot"] == body["snapshot"]
|
|
260
|
+
):
|
|
261
|
+
existing = self.snapshot(who["tenant"], args["repository"], body["snapshot"])
|
|
262
|
+
return {
|
|
263
|
+
"snapshot": body["snapshot"],
|
|
264
|
+
"commit": body["commit"],
|
|
265
|
+
"dirty": body["dirty"],
|
|
266
|
+
"generation": current["generation"],
|
|
267
|
+
"position": existing["position"],
|
|
268
|
+
"status": "captured",
|
|
269
|
+
"validation": "per_claim",
|
|
270
|
+
"dirty_files": [
|
|
271
|
+
{
|
|
272
|
+
"path": p,
|
|
273
|
+
"hash": body["files"][p]["hash"],
|
|
274
|
+
"coverage": body["files"][p]["coverage"],
|
|
275
|
+
}
|
|
276
|
+
for p in body["dirty_paths"]
|
|
277
|
+
],
|
|
278
|
+
}
|
|
279
|
+
self.db.execute(
|
|
280
|
+
"UPDATE repositories SET current_incarnation=?,current_snapshot=? WHERE tenant=? AND id=?",
|
|
281
|
+
(self.s.incarnation, body["snapshot"], who["tenant"], args["repository"]),
|
|
282
|
+
)
|
|
283
|
+
self.db.execute(
|
|
284
|
+
"UPDATE repositories SET generation=generation+1 WHERE tenant=? AND id=?",
|
|
285
|
+
(who["tenant"], args["repository"]),
|
|
286
|
+
)
|
|
287
|
+
gen = self.visible(who, args["repository"], args["project"])["generation"]
|
|
288
|
+
position = self.s._event(
|
|
289
|
+
who["tenant"], "repository.barrier", args["repository"], at, who["principal"]
|
|
290
|
+
)
|
|
291
|
+
self.db.execute(
|
|
292
|
+
"INSERT INTO repository_snapshots VALUES (?,?,?,?,?,?,?) ON CONFLICT(tenant,incarnation,repository,id) DO UPDATE SET generation=excluded.generation,position=excluded.position",
|
|
293
|
+
(
|
|
294
|
+
who["tenant"],
|
|
295
|
+
self.s.incarnation,
|
|
296
|
+
args["repository"],
|
|
297
|
+
body["snapshot"],
|
|
298
|
+
gen,
|
|
299
|
+
position,
|
|
300
|
+
raw.decode(),
|
|
301
|
+
),
|
|
302
|
+
)
|
|
303
|
+
self.db.execute(
|
|
304
|
+
"UPDATE repository_jobs SET state='superseded' WHERE tenant=? AND incarnation=? AND repository=? AND state='pending'",
|
|
305
|
+
(who["tenant"], self.s.incarnation, args["repository"]),
|
|
306
|
+
)
|
|
307
|
+
self.db.execute(
|
|
308
|
+
"INSERT INTO repository_jobs VALUES (?,?,?,?,?,?)",
|
|
309
|
+
(
|
|
310
|
+
who["tenant"],
|
|
311
|
+
self.s.incarnation,
|
|
312
|
+
args["repository"],
|
|
313
|
+
body["snapshot"],
|
|
314
|
+
gen,
|
|
315
|
+
"pending",
|
|
316
|
+
),
|
|
317
|
+
)
|
|
318
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
319
|
+
return {
|
|
320
|
+
"snapshot": body["snapshot"],
|
|
321
|
+
"commit": body["commit"],
|
|
322
|
+
"dirty": body["dirty"],
|
|
323
|
+
"generation": gen,
|
|
324
|
+
"position": position,
|
|
325
|
+
"status": "captured",
|
|
326
|
+
"validation": "per_claim",
|
|
327
|
+
"dirty_files": [
|
|
328
|
+
{
|
|
329
|
+
"path": path,
|
|
330
|
+
"hash": body["files"][path]["hash"],
|
|
331
|
+
"coverage": body["files"][path]["coverage"],
|
|
332
|
+
}
|
|
333
|
+
for path in body["dirty_paths"]
|
|
334
|
+
],
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
def _claim(self, who: dict[str, Any], revision: str, project: str, at: int) -> sqlite3.Row:
|
|
338
|
+
from memoryking.adapters.knowledge_store import Knowledge
|
|
339
|
+
|
|
340
|
+
k = Knowledge(self.s)
|
|
341
|
+
row = k._revision(who["tenant"], revision, project)
|
|
342
|
+
state, quarantine = k._state(
|
|
343
|
+
who["tenant"],
|
|
344
|
+
revision,
|
|
345
|
+
self.db.execute(
|
|
346
|
+
"SELECT position FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
347
|
+
).fetchone()[0],
|
|
348
|
+
)
|
|
349
|
+
if state != "accepted" or quarantine or not k._available(who, row, at):
|
|
350
|
+
raise LocalError("unavailable")
|
|
351
|
+
return row
|
|
352
|
+
|
|
353
|
+
def _evidence(self, who: dict[str, Any], evidence: str, at: int) -> None:
|
|
354
|
+
from memoryking.adapters.knowledge_store import Knowledge
|
|
355
|
+
|
|
356
|
+
row = self.db.execute(
|
|
357
|
+
"SELECT * FROM observations WHERE tenant=? AND id=?", (who["tenant"], evidence)
|
|
358
|
+
).fetchone()
|
|
359
|
+
if row is None or not self.s._visible(who, row, at):
|
|
360
|
+
raise LocalError("evidence_unavailable")
|
|
361
|
+
path = self.s.root / "blobs" / who["tenant"] / row["blob"]
|
|
362
|
+
private_file(path)
|
|
363
|
+
with path.open("rb") as stream:
|
|
364
|
+
raw = stream.read(65537)
|
|
365
|
+
if len(raw) > 65536:
|
|
366
|
+
raise LocalError("evidence_unavailable")
|
|
367
|
+
Knowledge(self.s)._support(
|
|
368
|
+
who,
|
|
369
|
+
[
|
|
370
|
+
{
|
|
371
|
+
"observation": evidence,
|
|
372
|
+
"start_byte": 0,
|
|
373
|
+
"end_byte": len(raw),
|
|
374
|
+
"content_hash": row["blob"],
|
|
375
|
+
}
|
|
376
|
+
],
|
|
377
|
+
at,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
@staticmethod
|
|
381
|
+
def dependency_hash(body: dict[str, Any], dep: dict[str, Any]) -> str | None:
|
|
382
|
+
if dep["kind"] == "file":
|
|
383
|
+
return cast(str | None, body["files"].get(dep["target"], {}).get("hash"))
|
|
384
|
+
for file in body["files"].values():
|
|
385
|
+
if file.get("coverage") == "python_syntax" and not file.get("truncated"):
|
|
386
|
+
for symbol in file["symbols"]:
|
|
387
|
+
if symbol["id"] == dep["target"]:
|
|
388
|
+
return cast(str, symbol["hash"])
|
|
389
|
+
return None
|
|
390
|
+
|
|
391
|
+
def bind(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
392
|
+
row = self._claim(who, args["revision"], args["project"], at)
|
|
393
|
+
self._evidence(who, args["evidence"], at)
|
|
394
|
+
old = self.db.execute(
|
|
395
|
+
"SELECT * FROM code_policies WHERE tenant=? AND revision=?", (who["tenant"], row["id"])
|
|
396
|
+
).fetchone()
|
|
397
|
+
version = old["version"] if old else 0
|
|
398
|
+
if args["expected_policy"] != version:
|
|
399
|
+
raise LocalError("dependency_policy_conflict")
|
|
400
|
+
if not args["dependencies"] or len(
|
|
401
|
+
{(d["kind"], d["target"]) for d in args["dependencies"]}
|
|
402
|
+
) != len(args["dependencies"]):
|
|
403
|
+
raise LocalError("dependency_coverage_incomplete")
|
|
404
|
+
body = json.loads(
|
|
405
|
+
self.snapshot(who["tenant"], args["repository"], args["snapshot"])["body"]
|
|
406
|
+
)
|
|
407
|
+
dependencies = []
|
|
408
|
+
for dep in args["dependencies"]:
|
|
409
|
+
if dep["kind"] == "file" and not path_valid(dep["target"]):
|
|
410
|
+
raise LocalError("dependency_unsupported")
|
|
411
|
+
digest = self.dependency_hash(body, dep)
|
|
412
|
+
if digest is None:
|
|
413
|
+
raise LocalError("dependency_coverage_incomplete")
|
|
414
|
+
if dep["policy"] == "rank_penalty" and (
|
|
415
|
+
args["impact"] != "low" or row["kind"] == "constraint"
|
|
416
|
+
):
|
|
417
|
+
raise LocalError("dependency_policy_unsafe")
|
|
418
|
+
dependencies.append({**dep, "hash": digest})
|
|
419
|
+
impact = "high" if row["kind"] == "constraint" else args["impact"]
|
|
420
|
+
if old and old["impact"] == "high" and impact != "high":
|
|
421
|
+
raise LocalError("impact_downgrade_requires_new_revision")
|
|
422
|
+
self.db.execute(
|
|
423
|
+
upsert("code_policies"),
|
|
424
|
+
(
|
|
425
|
+
who["tenant"],
|
|
426
|
+
row["id"],
|
|
427
|
+
args["repository"],
|
|
428
|
+
args["snapshot"],
|
|
429
|
+
version + 1,
|
|
430
|
+
impact,
|
|
431
|
+
json.dumps(dependencies),
|
|
432
|
+
args["evidence"],
|
|
433
|
+
who["principal"],
|
|
434
|
+
),
|
|
435
|
+
)
|
|
436
|
+
position = self.s._event(
|
|
437
|
+
who["tenant"], "repository.dependency_policy", row["id"], at, who["principal"]
|
|
438
|
+
)
|
|
439
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
440
|
+
return {
|
|
441
|
+
"revision": row["id"],
|
|
442
|
+
"policy_version": version + 1,
|
|
443
|
+
"impact": impact,
|
|
444
|
+
"status": "unchecked",
|
|
445
|
+
"position": position,
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
def verify(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
449
|
+
row = self._claim(who, args["revision"], args["project"], at)
|
|
450
|
+
policy = self.db.execute(
|
|
451
|
+
"SELECT * FROM code_policies WHERE tenant=? AND revision=?", (who["tenant"], row["id"])
|
|
452
|
+
).fetchone()
|
|
453
|
+
if policy is None or policy["version"] != args["expected_policy"]:
|
|
454
|
+
raise LocalError("dependency_policy_conflict")
|
|
455
|
+
self.visible(who, policy["repository"], args["project"])
|
|
456
|
+
snap = self.snapshot(who["tenant"], policy["repository"], args["snapshot"])
|
|
457
|
+
body = json.loads(snap["body"])
|
|
458
|
+
self._evidence(who, args["evidence"], at)
|
|
459
|
+
if args["expires_ms"] <= at:
|
|
460
|
+
raise LocalError("verification_expired")
|
|
461
|
+
# A changed dependency needs a reviewed policy revision first. An attributed
|
|
462
|
+
# verification never silently rebases the dependency declaration.
|
|
463
|
+
if any(
|
|
464
|
+
self.dependency_hash(body, dep) != dep["hash"]
|
|
465
|
+
for dep in json.loads(policy["dependencies"])
|
|
466
|
+
):
|
|
467
|
+
raise LocalError("dependency_policy_stale")
|
|
468
|
+
state = "valid" if args["passed"] else "invalid"
|
|
469
|
+
self.db.execute(
|
|
470
|
+
upsert("code_validations"),
|
|
471
|
+
(
|
|
472
|
+
who["tenant"],
|
|
473
|
+
self.s.incarnation,
|
|
474
|
+
row["id"],
|
|
475
|
+
args["snapshot"],
|
|
476
|
+
policy["version"],
|
|
477
|
+
state,
|
|
478
|
+
args["evidence"],
|
|
479
|
+
args["expires_ms"],
|
|
480
|
+
"attributed_snapshot_verification",
|
|
481
|
+
snap["generation"],
|
|
482
|
+
),
|
|
483
|
+
)
|
|
484
|
+
position = self.s._event(
|
|
485
|
+
who["tenant"], "repository.verified", row["id"], at, who["principal"]
|
|
486
|
+
)
|
|
487
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
488
|
+
return {
|
|
489
|
+
"revision": row["id"],
|
|
490
|
+
"snapshot": args["snapshot"],
|
|
491
|
+
"state": state,
|
|
492
|
+
"environment": body["environment"],
|
|
493
|
+
"position": position,
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
def revalidate(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
497
|
+
repo = self.visible(who, args["repository"], args["project"])
|
|
498
|
+
snap = self.snapshot(who["tenant"], repo["id"], args["snapshot"])
|
|
499
|
+
if (
|
|
500
|
+
repo["generation"] != args["expected_generation"]
|
|
501
|
+
or snap["generation"] != args["expected_generation"]
|
|
502
|
+
):
|
|
503
|
+
raise LocalError("repository_generation_conflict")
|
|
504
|
+
body = json.loads(snap["body"])
|
|
505
|
+
policies = self.db.execute(
|
|
506
|
+
"SELECT * FROM code_policies WHERE tenant=? AND repository=? ORDER BY revision LIMIT 257",
|
|
507
|
+
(who["tenant"], repo["id"]),
|
|
508
|
+
).fetchall()
|
|
509
|
+
if len(policies) > 256:
|
|
510
|
+
raise LocalError("revalidation_limit")
|
|
511
|
+
results = []
|
|
512
|
+
for policy in policies:
|
|
513
|
+
try:
|
|
514
|
+
self._claim(who, policy["revision"], args["project"], at)
|
|
515
|
+
self._evidence(who, policy["evidence"], at)
|
|
516
|
+
except LocalError:
|
|
517
|
+
continue
|
|
518
|
+
current = self.db.execute(
|
|
519
|
+
"SELECT * FROM code_validations WHERE tenant=? AND incarnation=? AND revision=? AND snapshot=? AND policy=?",
|
|
520
|
+
(
|
|
521
|
+
who["tenant"],
|
|
522
|
+
self.s.incarnation,
|
|
523
|
+
policy["revision"],
|
|
524
|
+
snap["id"],
|
|
525
|
+
policy["version"],
|
|
526
|
+
),
|
|
527
|
+
).fetchone()
|
|
528
|
+
if current is not None and current["reason"] == "attributed_snapshot_verification":
|
|
529
|
+
# A failed explicit verification cannot be replaced by hash carry-forward.
|
|
530
|
+
results.append(
|
|
531
|
+
{
|
|
532
|
+
"revision": policy["revision"],
|
|
533
|
+
"state": "unchecked"
|
|
534
|
+
if current["state"] == "valid" and current["expires"] <= at
|
|
535
|
+
else current["state"],
|
|
536
|
+
"expires_ms": current["expires"],
|
|
537
|
+
}
|
|
538
|
+
)
|
|
539
|
+
continue
|
|
540
|
+
try:
|
|
541
|
+
origin = self.snapshot(who["tenant"], repo["id"], policy["origin"])
|
|
542
|
+
original = json.loads(origin["body"])
|
|
543
|
+
except LocalError:
|
|
544
|
+
original = None
|
|
545
|
+
prior = self.db.execute(
|
|
546
|
+
"SELECT * FROM code_validations WHERE tenant=? AND incarnation=? AND revision=? AND snapshot=? AND policy=?",
|
|
547
|
+
(
|
|
548
|
+
who["tenant"],
|
|
549
|
+
self.s.incarnation,
|
|
550
|
+
policy["revision"],
|
|
551
|
+
policy["origin"],
|
|
552
|
+
policy["version"],
|
|
553
|
+
),
|
|
554
|
+
).fetchone()
|
|
555
|
+
dependencies = json.loads(policy["dependencies"])
|
|
556
|
+
values = [(dep, self.dependency_hash(body, dep)) for dep in dependencies]
|
|
557
|
+
changed = [dep for dep, digest in values if digest != dep["hash"]]
|
|
558
|
+
reason, state = "verification_unavailable", "unchecked"
|
|
559
|
+
if any(digest is None for _, digest in values):
|
|
560
|
+
reason = "dependency_missing"
|
|
561
|
+
elif changed:
|
|
562
|
+
state = (
|
|
563
|
+
"invalid"
|
|
564
|
+
if any(dep["policy"] == "invalidate" for dep in changed)
|
|
565
|
+
else "unchecked"
|
|
566
|
+
)
|
|
567
|
+
reason = "dependency_changed"
|
|
568
|
+
elif original is None:
|
|
569
|
+
reason = "origin_snapshot_unavailable"
|
|
570
|
+
elif original["environment"] != body["environment"]:
|
|
571
|
+
reason = "environment_changed"
|
|
572
|
+
elif original["commit"] not in body["ancestors"]:
|
|
573
|
+
state = "invalid" if body["ancestry_complete"] else "unchecked"
|
|
574
|
+
reason = "lineage_mismatch" if state == "invalid" else "ancestry_unknown"
|
|
575
|
+
elif prior is not None and prior["state"] == "valid" and prior["expires"] > at:
|
|
576
|
+
try:
|
|
577
|
+
self._evidence(who, prior["evidence"], at)
|
|
578
|
+
reason, state = "trusted_dependency_comparison", "valid"
|
|
579
|
+
except (LocalError, OSError):
|
|
580
|
+
pass
|
|
581
|
+
evidence = prior["evidence"] if prior is not None else policy["evidence"]
|
|
582
|
+
expires = prior["expires"] if prior is not None else at
|
|
583
|
+
self.db.execute(
|
|
584
|
+
upsert("code_validations"),
|
|
585
|
+
(
|
|
586
|
+
who["tenant"],
|
|
587
|
+
self.s.incarnation,
|
|
588
|
+
policy["revision"],
|
|
589
|
+
snap["id"],
|
|
590
|
+
policy["version"],
|
|
591
|
+
state,
|
|
592
|
+
evidence,
|
|
593
|
+
expires,
|
|
594
|
+
reason,
|
|
595
|
+
snap["generation"],
|
|
596
|
+
),
|
|
597
|
+
)
|
|
598
|
+
results.append({"revision": policy["revision"], "state": state, "reason": reason})
|
|
599
|
+
self.db.execute(
|
|
600
|
+
"UPDATE repository_jobs SET state='evaluated' WHERE tenant=? AND incarnation=? AND repository=? AND snapshot=? AND generation=?",
|
|
601
|
+
(who["tenant"], self.s.incarnation, repo["id"], snap["id"], snap["generation"]),
|
|
602
|
+
)
|
|
603
|
+
position = self.s._event(
|
|
604
|
+
who["tenant"], "repository.revalidated", repo["id"], at, who["principal"]
|
|
605
|
+
)
|
|
606
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
607
|
+
return {
|
|
608
|
+
"snapshot": snap["id"],
|
|
609
|
+
"generation": snap["generation"],
|
|
610
|
+
"position": position,
|
|
611
|
+
"results": results,
|
|
612
|
+
"checks_executed": False,
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
def eligibility(
|
|
616
|
+
self, who: dict[str, Any], row: sqlite3.Row, binding: dict[str, Any], at: int
|
|
617
|
+
) -> Truth:
|
|
618
|
+
policy = self.db.execute(
|
|
619
|
+
"SELECT * FROM code_policies WHERE tenant=? AND revision=?", (who["tenant"], row["id"])
|
|
620
|
+
).fetchone()
|
|
621
|
+
if policy is None:
|
|
622
|
+
# A selector alone is not a claim of code verification. Existing
|
|
623
|
+
# repository-independent rules retain P03 applicability semantics.
|
|
624
|
+
return "true"
|
|
625
|
+
if (
|
|
626
|
+
binding.get("repository_id") is not None
|
|
627
|
+
and binding["repository_id"] != policy["repository"]
|
|
628
|
+
):
|
|
629
|
+
return "false"
|
|
630
|
+
if not all(
|
|
631
|
+
isinstance(binding.get(k), str) and binding[k]
|
|
632
|
+
for k in ("snapshot_id", "repository_id", "commit", "environment")
|
|
633
|
+
):
|
|
634
|
+
return "unknown"
|
|
635
|
+
try:
|
|
636
|
+
self.visible(who, policy["repository"], row["project"])
|
|
637
|
+
snap = self.snapshot(who["tenant"], policy["repository"], binding["snapshot_id"])
|
|
638
|
+
body = json.loads(snap["body"])
|
|
639
|
+
if (
|
|
640
|
+
binding.get("commit") != body["commit"]
|
|
641
|
+
or binding.get("environment") != body["environment"]
|
|
642
|
+
):
|
|
643
|
+
return "unknown"
|
|
644
|
+
self._evidence(who, policy["evidence"], at)
|
|
645
|
+
validation = self.db.execute(
|
|
646
|
+
"SELECT * FROM code_validations WHERE tenant=? AND incarnation=? AND revision=? AND snapshot=? AND policy=?",
|
|
647
|
+
(who["tenant"], self.s.incarnation, row["id"], snap["id"], policy["version"]),
|
|
648
|
+
).fetchone()
|
|
649
|
+
if validation is None or validation["state"] == "unchecked":
|
|
650
|
+
validation = self.carry_forward(who, policy, snap, body, at)
|
|
651
|
+
if validation is None:
|
|
652
|
+
return "unknown"
|
|
653
|
+
if validation["state"] == "invalid":
|
|
654
|
+
return "false"
|
|
655
|
+
if validation["expires"] <= at:
|
|
656
|
+
return "unknown"
|
|
657
|
+
self._evidence(who, validation["evidence"], at)
|
|
658
|
+
return "true"
|
|
659
|
+
except (LocalError, OSError):
|
|
660
|
+
return "unknown"
|
|
661
|
+
|
|
662
|
+
def carry_forward(
|
|
663
|
+
self,
|
|
664
|
+
who: dict[str, Any],
|
|
665
|
+
policy: sqlite3.Row,
|
|
666
|
+
snap: sqlite3.Row,
|
|
667
|
+
body: dict[str, Any],
|
|
668
|
+
at: int,
|
|
669
|
+
) -> sqlite3.Row | None:
|
|
670
|
+
"""Cheap foreground proof for unaffected guidance while workers are paused.
|
|
671
|
+
|
|
672
|
+
The snapshot and complete declared dependency hashes came from the trusted
|
|
673
|
+
adapter. No positive proof is inferred from ancestry alone or unseen data.
|
|
674
|
+
"""
|
|
675
|
+
try:
|
|
676
|
+
origin = json.loads(
|
|
677
|
+
self.snapshot(who["tenant"], policy["repository"], policy["origin"])["body"]
|
|
678
|
+
)
|
|
679
|
+
prior = self.db.execute(
|
|
680
|
+
"SELECT * FROM code_validations WHERE tenant=? AND incarnation=? AND revision=? AND snapshot=? AND policy=?",
|
|
681
|
+
(
|
|
682
|
+
who["tenant"],
|
|
683
|
+
self.s.incarnation,
|
|
684
|
+
policy["revision"],
|
|
685
|
+
policy["origin"],
|
|
686
|
+
policy["version"],
|
|
687
|
+
),
|
|
688
|
+
).fetchone()
|
|
689
|
+
if (
|
|
690
|
+
prior is None
|
|
691
|
+
or prior["state"] != "valid"
|
|
692
|
+
or prior["expires"] <= at
|
|
693
|
+
or origin["environment"] != body["environment"]
|
|
694
|
+
or origin["commit"] not in body["ancestors"]
|
|
695
|
+
):
|
|
696
|
+
return None
|
|
697
|
+
if any(
|
|
698
|
+
self.dependency_hash(body, dep) != dep["hash"]
|
|
699
|
+
for dep in json.loads(policy["dependencies"])
|
|
700
|
+
):
|
|
701
|
+
return None
|
|
702
|
+
self._evidence(who, prior["evidence"], at)
|
|
703
|
+
self.db.execute(
|
|
704
|
+
upsert("code_validations"),
|
|
705
|
+
(
|
|
706
|
+
who["tenant"],
|
|
707
|
+
self.s.incarnation,
|
|
708
|
+
policy["revision"],
|
|
709
|
+
snap["id"],
|
|
710
|
+
policy["version"],
|
|
711
|
+
"valid",
|
|
712
|
+
prior["evidence"],
|
|
713
|
+
prior["expires"],
|
|
714
|
+
"trusted_dependency_comparison",
|
|
715
|
+
snap["generation"],
|
|
716
|
+
),
|
|
717
|
+
)
|
|
718
|
+
return cast(
|
|
719
|
+
sqlite3.Row,
|
|
720
|
+
self.db.execute(
|
|
721
|
+
"SELECT * FROM code_validations WHERE tenant=? AND incarnation=? AND revision=? AND snapshot=? AND policy=?",
|
|
722
|
+
(
|
|
723
|
+
who["tenant"],
|
|
724
|
+
self.s.incarnation,
|
|
725
|
+
policy["revision"],
|
|
726
|
+
snap["id"],
|
|
727
|
+
policy["version"],
|
|
728
|
+
),
|
|
729
|
+
).fetchone(),
|
|
730
|
+
)
|
|
731
|
+
except (LocalError, OSError):
|
|
732
|
+
return None
|
|
733
|
+
|
|
734
|
+
def ancestry(
|
|
735
|
+
self,
|
|
736
|
+
who: dict[str, Any],
|
|
737
|
+
project: str,
|
|
738
|
+
repository: str,
|
|
739
|
+
ancestor: str,
|
|
740
|
+
commit: str,
|
|
741
|
+
snapshot_id: str | None = None,
|
|
742
|
+
) -> Truth:
|
|
743
|
+
try:
|
|
744
|
+
self.visible(who, repository, project)
|
|
745
|
+
except LocalError:
|
|
746
|
+
return "unknown"
|
|
747
|
+
if snapshot_id:
|
|
748
|
+
try:
|
|
749
|
+
body = json.loads(self.snapshot(who["tenant"], repository, snapshot_id)["body"])
|
|
750
|
+
if body["commit"] != commit:
|
|
751
|
+
return "unknown"
|
|
752
|
+
return (
|
|
753
|
+
"true"
|
|
754
|
+
if ancestor in body["ancestors"]
|
|
755
|
+
else "false"
|
|
756
|
+
if body["ancestry_complete"]
|
|
757
|
+
else "unknown"
|
|
758
|
+
)
|
|
759
|
+
except LocalError:
|
|
760
|
+
return "unknown"
|
|
761
|
+
# Evidence is bounded and captured by the trusted adapter. Request fields
|
|
762
|
+
# cannot inject a parent list or an assertion of graph completeness.
|
|
763
|
+
rows = self.db.execute(
|
|
764
|
+
"SELECT body FROM repository_snapshots WHERE tenant=? AND incarnation=? AND repository=? ORDER BY position DESC LIMIT 64",
|
|
765
|
+
(who["tenant"], self.s.incarnation, repository),
|
|
766
|
+
).fetchall()
|
|
767
|
+
complete = False
|
|
768
|
+
for row in rows:
|
|
769
|
+
body = json.loads(row["body"])
|
|
770
|
+
if body["commit"] != commit:
|
|
771
|
+
continue
|
|
772
|
+
if ancestor in body["ancestors"]:
|
|
773
|
+
return "true"
|
|
774
|
+
complete |= body["ancestry_complete"]
|
|
775
|
+
return "false" if complete else "unknown"
|
|
776
|
+
|
|
777
|
+
def impact(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
778
|
+
snap = self.snapshot(who["tenant"], args["repository"], args["snapshot"])
|
|
779
|
+
body = json.loads(snap["body"])
|
|
780
|
+
if any(not path_valid(p) for p in args["paths"]):
|
|
781
|
+
raise LocalError("invalid_binding")
|
|
782
|
+
nodes: list[dict[str, Any]] = []
|
|
783
|
+
edges: list[dict[str, Any]] = []
|
|
784
|
+
for path in args["paths"]:
|
|
785
|
+
file = body["files"].get(path)
|
|
786
|
+
nodes.append(
|
|
787
|
+
{
|
|
788
|
+
"id": path,
|
|
789
|
+
"kind": "file",
|
|
790
|
+
"coverage": file["coverage"] if file else "missing",
|
|
791
|
+
"hash": file["hash"] if file else None,
|
|
792
|
+
}
|
|
793
|
+
)
|
|
794
|
+
truncated = False
|
|
795
|
+
# Authorization filters all endpoints before counting or returning edges.
|
|
796
|
+
policies = self.db.execute(
|
|
797
|
+
"SELECT p.* FROM code_policies p JOIN revisions r ON r.tenant=p.tenant AND r.id=p.revision JOIN observations o ON o.tenant=p.tenant AND o.id=p.evidence WHERE p.tenant=? AND p.repository=? AND r.purged=0 AND r.body IS NOT NULL AND (json_type(r.body,'$.readers')='null' OR EXISTS(SELECT 1 FROM json_each(r.body,'$.readers') WHERE value=?)) AND o.deleted=0 AND (o.readers='null' OR EXISTS(SELECT 1 FROM json_each(o.readers) WHERE value=?)) ORDER BY p.revision LIMIT 4096",
|
|
798
|
+
(who["tenant"], args["repository"], who["principal"], who["principal"]),
|
|
799
|
+
).fetchall()
|
|
800
|
+
for policy in policies:
|
|
801
|
+
# Resolve complete current source authority before traversing declared
|
|
802
|
+
# relationships or contributing to any count/truncation indicator.
|
|
803
|
+
try:
|
|
804
|
+
self._claim(who, policy["revision"], args["project"], at)
|
|
805
|
+
self._evidence(who, policy["evidence"], at)
|
|
806
|
+
except (LocalError, OSError):
|
|
807
|
+
continue
|
|
808
|
+
deps = [
|
|
809
|
+
dep
|
|
810
|
+
for dep in json.loads(policy["dependencies"])
|
|
811
|
+
if any(
|
|
812
|
+
dep["target"] == p
|
|
813
|
+
or (dep["kind"] == "symbol" and dep["target"].startswith(p + ":"))
|
|
814
|
+
for p in args["paths"]
|
|
815
|
+
)
|
|
816
|
+
]
|
|
817
|
+
if not deps:
|
|
818
|
+
continue
|
|
819
|
+
target_nodes = [
|
|
820
|
+
{"id": dep["target"], "kind": dep["kind"]}
|
|
821
|
+
for dep in deps
|
|
822
|
+
if dep["target"] not in {n["id"] for n in nodes}
|
|
823
|
+
]
|
|
824
|
+
if (
|
|
825
|
+
len(nodes) + 1 + len(target_nodes) > args["limit"]
|
|
826
|
+
or len(edges) + len(deps) > args["limit"]
|
|
827
|
+
):
|
|
828
|
+
truncated = True
|
|
829
|
+
continue
|
|
830
|
+
nodes.extend(target_nodes)
|
|
831
|
+
nodes.append({"id": policy["revision"], "kind": "claim", "impact": policy["impact"]})
|
|
832
|
+
for dep in deps:
|
|
833
|
+
digest = self.dependency_hash(body, dep)
|
|
834
|
+
edges.append(
|
|
835
|
+
{
|
|
836
|
+
"source": policy["revision"],
|
|
837
|
+
"target": dep["target"],
|
|
838
|
+
"kind": "depends_on_" + dep["kind"],
|
|
839
|
+
"change_policy": dep["policy"],
|
|
840
|
+
"status": "missing"
|
|
841
|
+
if digest is None
|
|
842
|
+
else "known_affected"
|
|
843
|
+
if digest != dep["hash"]
|
|
844
|
+
else "unchanged",
|
|
845
|
+
"needs_revalidation": digest != dep["hash"],
|
|
846
|
+
}
|
|
847
|
+
)
|
|
848
|
+
return {
|
|
849
|
+
"status": "partial",
|
|
850
|
+
"snapshot": snap["id"],
|
|
851
|
+
"generation": snap["generation"],
|
|
852
|
+
"nodes": nodes[: args["limit"]],
|
|
853
|
+
"edges": edges,
|
|
854
|
+
"truncated": truncated or len(nodes) > args["limit"],
|
|
855
|
+
"missing_relationships": "dynamic_undeclared_or_bounded_scan_unknown",
|
|
856
|
+
"candidate_scan_limit": 4096,
|
|
857
|
+
"checks_executed": False,
|
|
858
|
+
"mutation": False,
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
def coverage(self, who: dict[str, Any], args: dict[str, Any]) -> dict[str, Any]:
|
|
862
|
+
snap = self.snapshot(who["tenant"], args["repository"], args["snapshot"])
|
|
863
|
+
body = json.loads(snap["body"])
|
|
864
|
+
points = bindings(args["bindings"])
|
|
865
|
+
if not args["paths"] or any(not path_valid(p) for p in args["paths"]):
|
|
866
|
+
raise LocalError("binding_coverage_incomplete")
|
|
867
|
+
covered = {
|
|
868
|
+
b.get("path")
|
|
869
|
+
for b in points
|
|
870
|
+
if b.get("repository_id") == args["repository"]
|
|
871
|
+
and b.get("snapshot_id") == snap["id"]
|
|
872
|
+
and b.get("commit") == body["commit"]
|
|
873
|
+
and b.get("environment") == body["environment"]
|
|
874
|
+
}
|
|
875
|
+
missing = sorted(set(args["paths"]) - covered)
|
|
876
|
+
return {
|
|
877
|
+
"status": "blocked" if missing else "complete",
|
|
878
|
+
"reason": "binding_coverage_incomplete" if missing else None,
|
|
879
|
+
"missing_paths": missing,
|
|
880
|
+
"snapshot": snap["id"],
|
|
881
|
+
"declared_scope_only": True,
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
def proof(
|
|
885
|
+
self, who: dict[str, Any], row: sqlite3.Row, binding: dict[str, Any], at: int
|
|
886
|
+
) -> dict[str, Any] | None:
|
|
887
|
+
policy = self.db.execute(
|
|
888
|
+
"SELECT * FROM code_policies WHERE tenant=? AND revision=?", (who["tenant"], row["id"])
|
|
889
|
+
).fetchone()
|
|
890
|
+
if policy is None or self.eligibility(who, row, binding, at) != "true":
|
|
891
|
+
return None
|
|
892
|
+
snap = self.snapshot(who["tenant"], policy["repository"], binding["snapshot_id"])
|
|
893
|
+
validation = self.db.execute(
|
|
894
|
+
"SELECT * FROM code_validations WHERE tenant=? AND incarnation=? AND revision=? AND snapshot=? AND policy=?",
|
|
895
|
+
(who["tenant"], self.s.incarnation, row["id"], snap["id"], policy["version"]),
|
|
896
|
+
).fetchone()
|
|
897
|
+
return {
|
|
898
|
+
"dependency": f"{row['id']}|{snap['id']}|{policy['version']}",
|
|
899
|
+
"repository": policy["repository"],
|
|
900
|
+
"snapshot": snap["id"],
|
|
901
|
+
"environment": binding["environment"],
|
|
902
|
+
"commit": binding["commit"],
|
|
903
|
+
"policy_version": policy["version"],
|
|
904
|
+
"generation": snap["generation"],
|
|
905
|
+
"method": validation["reason"],
|
|
906
|
+
"expires_ms": validation["expires"],
|
|
907
|
+
"evidence": sorted({policy["evidence"], validation["evidence"]}),
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
def verify_proof(self, who: dict[str, Any], dependency: str, at: int) -> None:
|
|
911
|
+
try:
|
|
912
|
+
revision, snapshot, version = dependency.split("|")
|
|
913
|
+
policy = self.db.execute(
|
|
914
|
+
"SELECT * FROM code_policies WHERE tenant=? AND revision=? AND version=?",
|
|
915
|
+
(who["tenant"], revision, int(version)),
|
|
916
|
+
).fetchone()
|
|
917
|
+
if policy is None:
|
|
918
|
+
raise LocalError("replay_denied")
|
|
919
|
+
from memoryking.adapters.knowledge_store import Knowledge
|
|
920
|
+
|
|
921
|
+
row = Knowledge(self.s)._revision(who["tenant"], revision)
|
|
922
|
+
body = json.loads(self.snapshot(who["tenant"], policy["repository"], snapshot)["body"])
|
|
923
|
+
binding = {
|
|
924
|
+
"repository_id": policy["repository"],
|
|
925
|
+
"snapshot_id": snapshot,
|
|
926
|
+
"commit": body["commit"],
|
|
927
|
+
"environment": body["environment"],
|
|
928
|
+
}
|
|
929
|
+
if self.eligibility(who, row, binding, at) != "true":
|
|
930
|
+
raise LocalError("replay_denied")
|
|
931
|
+
except (ValueError, OSError, LocalError) as exc:
|
|
932
|
+
raise LocalError("replay_denied") from exc
|
|
933
|
+
|
|
934
|
+
def history(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
935
|
+
row = self._claim(who, args["revision"], args["project"], at)
|
|
936
|
+
policy = self.db.execute(
|
|
937
|
+
"SELECT * FROM code_policies WHERE tenant=? AND revision=?", (who["tenant"], row["id"])
|
|
938
|
+
).fetchone()
|
|
939
|
+
if policy is None:
|
|
940
|
+
raise LocalError("dependency_policy_missing")
|
|
941
|
+
self.visible(who, policy["repository"], args["project"])
|
|
942
|
+
self._evidence(who, policy["evidence"], at)
|
|
943
|
+
origin = json.loads(
|
|
944
|
+
self.snapshot(who["tenant"], policy["repository"], policy["origin"])["body"]
|
|
945
|
+
)
|
|
946
|
+
target = json.loads(
|
|
947
|
+
self.snapshot(who["tenant"], policy["repository"], args["snapshot"])["body"]
|
|
948
|
+
)
|
|
949
|
+
return {
|
|
950
|
+
"status": "partial",
|
|
951
|
+
"authority": "historical_analogy_not_current_guidance",
|
|
952
|
+
"revision": row["id"],
|
|
953
|
+
"text": json.loads(row["body"])["text"],
|
|
954
|
+
"origin_snapshot": origin["snapshot"],
|
|
955
|
+
"origin_commit": origin["commit"],
|
|
956
|
+
"requested_snapshot": target["snapshot"],
|
|
957
|
+
"requested_commit": target["commit"],
|
|
958
|
+
"verified_current": False,
|
|
959
|
+
"checks_executed": False,
|
|
960
|
+
}
|