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,1128 @@
|
|
|
1
|
+
"""Bounded human inspection and preview-bound retention using current authority."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from jsonschema import Draft202012Validator
|
|
12
|
+
|
|
13
|
+
from memoryking.adapters.execution import Execution
|
|
14
|
+
from memoryking.adapters.experience_records import ExperienceRecords
|
|
15
|
+
from memoryking.adapters.handoff import Handoff
|
|
16
|
+
from memoryking.adapters.local_store import RETRY_MS, uid
|
|
17
|
+
from memoryking.adapters.retrieval import Retrieval
|
|
18
|
+
from memoryking.application.store_core import StoreCore
|
|
19
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash
|
|
20
|
+
from memoryking.domain.local import LocalError, Released
|
|
21
|
+
from memoryking.domain.usage import UsageRecord, summarize
|
|
22
|
+
|
|
23
|
+
CATALOG_TEXT_BYTES = 196608 # text per catalog page, under the inspection reply limit
|
|
24
|
+
DAY_MS = 86_400_000
|
|
25
|
+
BACKLOG_ITEMS = 16 # oldest waiting proposals listed by the health report
|
|
26
|
+
HEALTH_MIN_SAMPLE = 5 # votes or briefings before a ratio becomes a signal
|
|
27
|
+
BACKLOG_ATTENTION_MS = 7 * DAY_MS # a proposal waiting longer than this needs a reviewer
|
|
28
|
+
VALIDATOR = Draft202012Validator(
|
|
29
|
+
json.loads(Path(__file__).with_name("inspection.schema.json").read_text())
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Inspection:
|
|
34
|
+
def __init__(self, store: StoreCore):
|
|
35
|
+
self.s, self.db = store, store.db
|
|
36
|
+
self.r = Retrieval(store)
|
|
37
|
+
|
|
38
|
+
def execute(self, credential: str, command: dict[str, Any]) -> Released:
|
|
39
|
+
if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
|
|
40
|
+
raise LocalError("invalid_request")
|
|
41
|
+
if command["incarnation"] != self.s.incarnation:
|
|
42
|
+
raise LocalError("history_changed")
|
|
43
|
+
action, args = command["action"], command["args"]
|
|
44
|
+
with self.s.transaction() as decision:
|
|
45
|
+
at = decision.evaluated_ms
|
|
46
|
+
who = self.s._auth(credential, "read", args["project"], at)
|
|
47
|
+
if action in {
|
|
48
|
+
"operations",
|
|
49
|
+
"purge",
|
|
50
|
+
"retention_preview",
|
|
51
|
+
"influence",
|
|
52
|
+
"trust",
|
|
53
|
+
"trust_list",
|
|
54
|
+
"held",
|
|
55
|
+
"release",
|
|
56
|
+
"health",
|
|
57
|
+
}:
|
|
58
|
+
self.s._auth(credential, "admin", "*", at)
|
|
59
|
+
if action == "history":
|
|
60
|
+
result = self.history(who, args, at)
|
|
61
|
+
elif action == "operations":
|
|
62
|
+
result = self.operations(who, args, at)
|
|
63
|
+
elif action == "cost":
|
|
64
|
+
result = self.cost(who, args, at)
|
|
65
|
+
elif action == "handoffs":
|
|
66
|
+
result = self.handoffs(who, args, at)
|
|
67
|
+
elif action == "retention_preview":
|
|
68
|
+
result = self.retention(who, args, at)
|
|
69
|
+
elif action == "influence":
|
|
70
|
+
result = self.influence(who, args, at)
|
|
71
|
+
elif action == "trust_list":
|
|
72
|
+
result = self.trust_list(who, args, at)
|
|
73
|
+
elif action == "held":
|
|
74
|
+
result = self.held(who, args, at)
|
|
75
|
+
elif action == "catalog":
|
|
76
|
+
result = self.catalog(who, args, at)
|
|
77
|
+
elif action == "health":
|
|
78
|
+
result = self.health(who, args, at)
|
|
79
|
+
elif action in {"trust", "release"}:
|
|
80
|
+
result = self.policy(who, command, at)
|
|
81
|
+
else:
|
|
82
|
+
result = self.purge(who, command, at)
|
|
83
|
+
result.update(
|
|
84
|
+
incarnation=self.s.incarnation,
|
|
85
|
+
tenant=who["tenant"],
|
|
86
|
+
principal=who["principal"],
|
|
87
|
+
project=args["project"],
|
|
88
|
+
evaluated_ms=at,
|
|
89
|
+
fresh_until_ms=at + 15000,
|
|
90
|
+
authorization="current",
|
|
91
|
+
receipt=uid("rcpt"),
|
|
92
|
+
)
|
|
93
|
+
raw = canonical_bytes(result)
|
|
94
|
+
if len(raw) > 524288:
|
|
95
|
+
raise LocalError("inspection_response_limit")
|
|
96
|
+
epochs = self.db.execute(
|
|
97
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
98
|
+
).fetchone()
|
|
99
|
+
self.db.execute(
|
|
100
|
+
"INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
101
|
+
(
|
|
102
|
+
who["tenant"],
|
|
103
|
+
result["receipt"],
|
|
104
|
+
who["principal"],
|
|
105
|
+
self.s.incarnation,
|
|
106
|
+
at,
|
|
107
|
+
decision.deadline_ms,
|
|
108
|
+
*epochs,
|
|
109
|
+
hashlib.sha256(raw).hexdigest(),
|
|
110
|
+
"[]",
|
|
111
|
+
),
|
|
112
|
+
)
|
|
113
|
+
self.s.fault("after_validation")
|
|
114
|
+
self.s._expose()
|
|
115
|
+
if action == "purge":
|
|
116
|
+
self.s.gc()
|
|
117
|
+
return Released(raw, decision, self.s.clock, result["receipt"])
|
|
118
|
+
|
|
119
|
+
def history(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
120
|
+
projection = Execution(self.s).snapshot(
|
|
121
|
+
who, args["project"], at, args.get("recorded_position")
|
|
122
|
+
)
|
|
123
|
+
rows = self.db.execute(
|
|
124
|
+
"SELECT * FROM checkpoints WHERE tenant=? AND project=? AND incarnation=? AND (readers='null' OR EXISTS(SELECT 1 FROM json_each(readers) WHERE value=?)) ORDER BY position DESC LIMIT 65",
|
|
125
|
+
(who["tenant"], args["project"], self.s.incarnation, who["principal"]),
|
|
126
|
+
).fetchall()
|
|
127
|
+
frames = []
|
|
128
|
+
for row in rows[:64]:
|
|
129
|
+
scope = {
|
|
130
|
+
"project": args["project"],
|
|
131
|
+
"task": row["task"],
|
|
132
|
+
"run": None if row["stream"] == "task" else row["stream"][4:],
|
|
133
|
+
"checkpoint": row["id"],
|
|
134
|
+
}
|
|
135
|
+
try:
|
|
136
|
+
Execution(self.s).w._checkpoint(who, scope, at)
|
|
137
|
+
except LocalError:
|
|
138
|
+
continue
|
|
139
|
+
frames.append(
|
|
140
|
+
{
|
|
141
|
+
"position": row["position"],
|
|
142
|
+
"recorded_ms": row["created"],
|
|
143
|
+
"checkpoint": row["id"],
|
|
144
|
+
"task": row["task"],
|
|
145
|
+
"run": scope["run"],
|
|
146
|
+
"revision": row["revision"],
|
|
147
|
+
}
|
|
148
|
+
)
|
|
149
|
+
return {
|
|
150
|
+
"projection": projection,
|
|
151
|
+
"frames": list(reversed(frames)),
|
|
152
|
+
"coverage": "latest_64_audience_candidates_current_permission; missing_history_not_interpolated",
|
|
153
|
+
"window_full": len(frames) >= 64,
|
|
154
|
+
"external_actions": 0,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
def operations(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
158
|
+
# Aggregate only jobs whose observation and dependency are currently visible.
|
|
159
|
+
rows = self.db.execute(
|
|
160
|
+
"SELECT j.*,e.at_ms FROM jobs j JOIN observations o ON j.tenant=o.tenant AND j.observation=o.id JOIN events e ON e.tenant=j.tenant AND e.position=j.position WHERE j.tenant=? AND o.project=? AND j.incarnation=? ORDER BY j.position DESC LIMIT 513",
|
|
161
|
+
(who["tenant"], args["project"], self.s.incarnation),
|
|
162
|
+
).fetchall()
|
|
163
|
+
items = []
|
|
164
|
+
for row in rows[:512]:
|
|
165
|
+
try:
|
|
166
|
+
self.r._dependency(who, {"kind": "observation", "id": row["observation"]}, at)
|
|
167
|
+
except LocalError:
|
|
168
|
+
continue
|
|
169
|
+
items.append(
|
|
170
|
+
{
|
|
171
|
+
key: row[key]
|
|
172
|
+
for key in (
|
|
173
|
+
"id",
|
|
174
|
+
"position",
|
|
175
|
+
"state",
|
|
176
|
+
"attempts",
|
|
177
|
+
"fence",
|
|
178
|
+
"lease_until",
|
|
179
|
+
"available",
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
items[-1]["age_ms"] = max(0, at - row["at_ms"])
|
|
184
|
+
# Tenant frontiers are opaque ordering tokens, never hidden-item counts.
|
|
185
|
+
state = self.db.execute("SELECT * FROM tenants WHERE tenant=?", (who["tenant"],)).fetchone()
|
|
186
|
+
projection = self.db.execute(
|
|
187
|
+
"SELECT * FROM projections WHERE tenant=?", (who["tenant"],)
|
|
188
|
+
).fetchone()
|
|
189
|
+
return {
|
|
190
|
+
"jobs": items,
|
|
191
|
+
"counts": {
|
|
192
|
+
status: sum(i["state"] == status for i in items)
|
|
193
|
+
for status in sorted({i["state"] for i in items})
|
|
194
|
+
},
|
|
195
|
+
"coverage": "up_to_512_recent_jobs_with_current_visible_observation; non_observation_jobs_not_included",
|
|
196
|
+
"frontier": {
|
|
197
|
+
"source": state["position"],
|
|
198
|
+
"projection": projection["frontier"],
|
|
199
|
+
"generation": projection["generation"],
|
|
200
|
+
},
|
|
201
|
+
"authorization_epoch": state["policy_epoch"],
|
|
202
|
+
"purge_epoch": state["purge_epoch"],
|
|
203
|
+
"health": "request_authorized_primary_available",
|
|
204
|
+
"lock_wait_ms": None,
|
|
205
|
+
"cache_churn": None,
|
|
206
|
+
"recovery_qualified": False,
|
|
207
|
+
"controls": {
|
|
208
|
+
"retry": "unsupported",
|
|
209
|
+
"cancel": "unsupported",
|
|
210
|
+
"schedule": "unsupported",
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
def cost(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
215
|
+
rows = self.db.execute(
|
|
216
|
+
"SELECT * FROM processing_usage WHERE tenant=? AND project=? AND principal=? AND incarnation=? AND expires>? ORDER BY created DESC,id LIMIT 513",
|
|
217
|
+
(who["tenant"], args["project"], who["principal"], self.s.incarnation, at),
|
|
218
|
+
).fetchall()
|
|
219
|
+
attempts = []
|
|
220
|
+
for row in rows[:512]:
|
|
221
|
+
try:
|
|
222
|
+
for dep in json.loads(row["dependencies"]):
|
|
223
|
+
self.r._dependency(who, dep, at)
|
|
224
|
+
except LocalError:
|
|
225
|
+
continue
|
|
226
|
+
attempts.append(
|
|
227
|
+
UsageRecord(
|
|
228
|
+
*(
|
|
229
|
+
row[k]
|
|
230
|
+
for k in (
|
|
231
|
+
"id",
|
|
232
|
+
"provider",
|
|
233
|
+
"fingerprint",
|
|
234
|
+
"stage",
|
|
235
|
+
"status",
|
|
236
|
+
"input_tokens",
|
|
237
|
+
"cached_input_tokens",
|
|
238
|
+
"output_tokens",
|
|
239
|
+
"cost_microusd",
|
|
240
|
+
"duration_ms",
|
|
241
|
+
)
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
)
|
|
245
|
+
summary = summarize(attempts, 0)
|
|
246
|
+
summary.update(successful_tasks=None, tokens_per_successful_task=None)
|
|
247
|
+
outcomes = ExperienceRecords(self.s).records(who, {**args, "kind": "outcome"}, at)
|
|
248
|
+
return {
|
|
249
|
+
"processing": summary,
|
|
250
|
+
"attempts": [record.document() for record in attempts],
|
|
251
|
+
"outcomes": outcomes,
|
|
252
|
+
"coverage": "up_to_512_retained_own_current_authorized_processing_attempts; outcomes_are_separate_actor_reports_not_added_to_usage",
|
|
253
|
+
"assurance": "provider_or_actor_reported_not_independent_metering",
|
|
254
|
+
"full_task_cost": None,
|
|
255
|
+
"human_effort": None,
|
|
256
|
+
"unrecorded_attempts": "unknown",
|
|
257
|
+
"savings": "not_evaluated",
|
|
258
|
+
"estimated_usage": None,
|
|
259
|
+
"duration_note": "attested_usage_duration_zero_is_unobserved_placeholder",
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
def handoffs(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
263
|
+
h = Handoff(self.s)
|
|
264
|
+
rows = self.db.execute(
|
|
265
|
+
"SELECT * FROM handoffs WHERE tenant=? AND project=? AND incarnation=? AND (sender=? OR recipient=?) ORDER BY created DESC,id LIMIT 65",
|
|
266
|
+
(
|
|
267
|
+
who["tenant"],
|
|
268
|
+
args["project"],
|
|
269
|
+
self.s.incarnation,
|
|
270
|
+
who["principal"],
|
|
271
|
+
who["principal"],
|
|
272
|
+
),
|
|
273
|
+
).fetchall()
|
|
274
|
+
items = []
|
|
275
|
+
for row in rows[:64]:
|
|
276
|
+
try:
|
|
277
|
+
h.w._checkpoint(who, h._scope(row), at)
|
|
278
|
+
except LocalError:
|
|
279
|
+
continue
|
|
280
|
+
effective = row["state"]
|
|
281
|
+
try:
|
|
282
|
+
h._active(row, at)
|
|
283
|
+
except LocalError as exc:
|
|
284
|
+
effective = exc.code
|
|
285
|
+
items.append(
|
|
286
|
+
{
|
|
287
|
+
**{
|
|
288
|
+
key: row[key]
|
|
289
|
+
for key in (
|
|
290
|
+
"id",
|
|
291
|
+
"task",
|
|
292
|
+
"stream",
|
|
293
|
+
"checkpoint",
|
|
294
|
+
"sender",
|
|
295
|
+
"recipient",
|
|
296
|
+
"state",
|
|
297
|
+
"created",
|
|
298
|
+
"expires",
|
|
299
|
+
"stream_revision",
|
|
300
|
+
)
|
|
301
|
+
},
|
|
302
|
+
"effective": effective,
|
|
303
|
+
"role_label_is_authority": False,
|
|
304
|
+
}
|
|
305
|
+
)
|
|
306
|
+
return {
|
|
307
|
+
"items": items,
|
|
308
|
+
"coverage": "up_to_64_own_handoffs_with_current_checkpoint_access",
|
|
309
|
+
"external_actions": 0,
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
def retention(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
313
|
+
row = self.db.execute(
|
|
314
|
+
"SELECT * FROM observations WHERE tenant=? AND project=? AND id=?",
|
|
315
|
+
(who["tenant"], args["project"], args["observation"]),
|
|
316
|
+
).fetchone()
|
|
317
|
+
if row is None or not self.s._visible(who, row, at):
|
|
318
|
+
raise LocalError("unavailable")
|
|
319
|
+
self.r._blob(row)
|
|
320
|
+
rows = self.db.execute(
|
|
321
|
+
"SELECT DISTINCT revision FROM evidence_spans WHERE tenant=? AND observation=? ORDER BY revision LIMIT 257",
|
|
322
|
+
(who["tenant"], row["id"]),
|
|
323
|
+
).fetchall()
|
|
324
|
+
affected = []
|
|
325
|
+
for ref in rows[:256]:
|
|
326
|
+
claim = self.r.k._revision(who["tenant"], ref["revision"])
|
|
327
|
+
if self.r.k._available(who, claim, at):
|
|
328
|
+
affected.append(
|
|
329
|
+
{
|
|
330
|
+
"revision": claim["id"],
|
|
331
|
+
"family": claim["family"],
|
|
332
|
+
"effect": "purged_with_source",
|
|
333
|
+
}
|
|
334
|
+
)
|
|
335
|
+
state = dict(
|
|
336
|
+
self.db.execute("SELECT * FROM tenants WHERE tenant=?", (who["tenant"],)).fetchone()
|
|
337
|
+
)
|
|
338
|
+
preview = {
|
|
339
|
+
"observation": row["id"],
|
|
340
|
+
"content_hash": row["blob"],
|
|
341
|
+
"affected": affected,
|
|
342
|
+
"coverage": "up_to_256_direct_authorized_claims; dependent artifacts, checkpoints, handoffs and experience records are selected by recorded dependencies and not enumerated",
|
|
343
|
+
"effects": [
|
|
344
|
+
"Delete source and dependent claim bodies",
|
|
345
|
+
"Retire rendered artifacts, checkpoints and handoffs that recorded a dependency on the source or its claims",
|
|
346
|
+
"Delete access receipts that list the source; the purge epoch retires other retained views",
|
|
347
|
+
"Retire ALL tenant replay results for working, handoff and experience operations (no dependency index)",
|
|
348
|
+
"Retire experience records that recorded a dependency and disable ranking when any was retired",
|
|
349
|
+
"Prior delivered copies and backups are not erased",
|
|
350
|
+
],
|
|
351
|
+
"irreversible": True,
|
|
352
|
+
"source_position": state["position"],
|
|
353
|
+
}
|
|
354
|
+
preview["preview"] = self.s._token(
|
|
355
|
+
"retention_preview",
|
|
356
|
+
tenant=who["tenant"],
|
|
357
|
+
principal=who["principal"],
|
|
358
|
+
project=args["project"],
|
|
359
|
+
observation=row["id"],
|
|
360
|
+
state=canonical_hash(state),
|
|
361
|
+
digest=canonical_hash(preview),
|
|
362
|
+
expires=at + 15000,
|
|
363
|
+
)
|
|
364
|
+
return preview
|
|
365
|
+
|
|
366
|
+
def influence(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
367
|
+
"""Where one observation went: every record built from it and who received it.
|
|
368
|
+
|
|
369
|
+
The same recorded dependencies a purge would follow, read without changing
|
|
370
|
+
anything: the claims that cite the observation, the checkpoints, handoffs,
|
|
371
|
+
summaries, experience records and retained deliveries (briefings, fetches,
|
|
372
|
+
reruns, graph pages) that recorded a dependency on it or on anything derived
|
|
373
|
+
from it, and the principals those reached. Bounded per list; truncation is
|
|
374
|
+
explicit. Prior exports, provider deliveries and backups leave no record here."""
|
|
375
|
+
tenant = who["tenant"]
|
|
376
|
+
row = self.db.execute(
|
|
377
|
+
"SELECT * FROM observations WHERE tenant=? AND id=? AND project=?",
|
|
378
|
+
(tenant, args["observation"], args["project"]),
|
|
379
|
+
).fetchone()
|
|
380
|
+
if row is None or row["deleted"]:
|
|
381
|
+
raise LocalError("unavailable")
|
|
382
|
+
self.r._blob(row)
|
|
383
|
+
limit = 256
|
|
384
|
+
truncation: set[str] = set()
|
|
385
|
+
derived = {row["id"]}
|
|
386
|
+
claims: list[dict[str, Any]] = []
|
|
387
|
+
for ref in self.db.execute(
|
|
388
|
+
"SELECT DISTINCT revision FROM evidence_spans WHERE tenant=? AND observation=? ORDER BY revision LIMIT 257",
|
|
389
|
+
(tenant, row["id"]),
|
|
390
|
+
).fetchall()[: limit + 1]:
|
|
391
|
+
if len(claims) >= limit:
|
|
392
|
+
truncation.add("claims")
|
|
393
|
+
break
|
|
394
|
+
claim = self.r.k._revision(tenant, ref["revision"])
|
|
395
|
+
derived.add(claim["id"])
|
|
396
|
+
claims.append(
|
|
397
|
+
{
|
|
398
|
+
"revision": claim["id"],
|
|
399
|
+
"family": claim["family"],
|
|
400
|
+
"kind": claim["kind"],
|
|
401
|
+
"issuer": claim["issuer"],
|
|
402
|
+
"readable_now": self.r.k._available(who, claim, at),
|
|
403
|
+
}
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
def depends(raw: Any) -> bool:
|
|
407
|
+
try:
|
|
408
|
+
deps = json.loads(raw) if isinstance(raw, str) else raw
|
|
409
|
+
except ValueError:
|
|
410
|
+
return False
|
|
411
|
+
return isinstance(deps, list) and any(
|
|
412
|
+
isinstance(d, dict) and d.get("id") in derived for d in deps
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
checkpoints: dict[str, dict[str, Any]] = {}
|
|
416
|
+
experience: dict[str, dict[str, Any]] = {}
|
|
417
|
+
deliveries: dict[str, dict[str, Any]] = {}
|
|
418
|
+
changed = True
|
|
419
|
+
while changed:
|
|
420
|
+
changed = False
|
|
421
|
+
for item in self.db.execute(
|
|
422
|
+
"SELECT id,task,stream,revision,writer,readers,created,state,dependencies FROM checkpoints WHERE tenant=? AND project=? AND state!='purged' ORDER BY created,id",
|
|
423
|
+
(tenant, args["project"]),
|
|
424
|
+
).fetchall():
|
|
425
|
+
if item["id"] in checkpoints or not depends(item["dependencies"]):
|
|
426
|
+
continue
|
|
427
|
+
if len(checkpoints) >= limit:
|
|
428
|
+
truncation.add("checkpoints")
|
|
429
|
+
continue
|
|
430
|
+
checkpoints[item["id"]] = {
|
|
431
|
+
"checkpoint": item["id"],
|
|
432
|
+
"task": item["task"],
|
|
433
|
+
"stream": item["stream"],
|
|
434
|
+
"revision": item["revision"],
|
|
435
|
+
"writer": item["writer"],
|
|
436
|
+
"readers": json.loads(item["readers"]),
|
|
437
|
+
"created_ms": item["created"],
|
|
438
|
+
"state": item["state"],
|
|
439
|
+
}
|
|
440
|
+
derived.add(item["id"])
|
|
441
|
+
changed = True
|
|
442
|
+
for item in self.db.execute(
|
|
443
|
+
"SELECT id,dependencies FROM experience_records WHERE tenant=? AND body IS NOT NULL ORDER BY id",
|
|
444
|
+
(tenant,),
|
|
445
|
+
).fetchall():
|
|
446
|
+
if item["id"] in experience or not depends(item["dependencies"]):
|
|
447
|
+
continue
|
|
448
|
+
if len(experience) >= limit:
|
|
449
|
+
truncation.add("experience")
|
|
450
|
+
continue
|
|
451
|
+
experience[item["id"]] = {"record": item["id"]}
|
|
452
|
+
derived.add(item["id"])
|
|
453
|
+
changed = True
|
|
454
|
+
for item in self.db.execute(
|
|
455
|
+
"SELECT id,principal,created,state,diagnostics,dependencies FROM rendered_artifacts WHERE tenant=? AND project=? AND state='retained' ORDER BY created,id",
|
|
456
|
+
(tenant, args["project"]),
|
|
457
|
+
).fetchall():
|
|
458
|
+
if item["id"] in deliveries or not depends(item["dependencies"]):
|
|
459
|
+
continue
|
|
460
|
+
if len(deliveries) >= limit:
|
|
461
|
+
truncation.add("deliveries")
|
|
462
|
+
continue
|
|
463
|
+
diag = json.loads(item["diagnostics"] or "{}")
|
|
464
|
+
deliveries[item["id"]] = {
|
|
465
|
+
"receipt": item["id"],
|
|
466
|
+
"kind": diag.get("kind", "brief"),
|
|
467
|
+
"principal": item["principal"],
|
|
468
|
+
"created_ms": item["created"],
|
|
469
|
+
"status": diag.get("status"),
|
|
470
|
+
}
|
|
471
|
+
derived.add(item["id"])
|
|
472
|
+
changed = True
|
|
473
|
+
handoffs: list[dict[str, Any]] = []
|
|
474
|
+
summaries: list[dict[str, Any]] = []
|
|
475
|
+
for identifier in checkpoints:
|
|
476
|
+
for item in self.db.execute(
|
|
477
|
+
"SELECT id,sender,recipient,role,stage,state,created FROM handoffs WHERE tenant=? AND checkpoint=? ORDER BY created,id",
|
|
478
|
+
(tenant, identifier),
|
|
479
|
+
).fetchall():
|
|
480
|
+
if len(handoffs) >= limit:
|
|
481
|
+
truncation.add("handoffs")
|
|
482
|
+
break
|
|
483
|
+
handoffs.append(
|
|
484
|
+
{
|
|
485
|
+
"handoff": item["id"],
|
|
486
|
+
"checkpoint": identifier,
|
|
487
|
+
"sender": item["sender"],
|
|
488
|
+
"recipient": item["recipient"],
|
|
489
|
+
"role": item["role"],
|
|
490
|
+
"stage": item["stage"],
|
|
491
|
+
"state": item["state"],
|
|
492
|
+
"created_ms": item["created"],
|
|
493
|
+
}
|
|
494
|
+
)
|
|
495
|
+
for item in self.db.execute(
|
|
496
|
+
"SELECT id,checkpoint,principal,method,readers,created FROM session_summaries WHERE tenant=? AND project=? ORDER BY created,id",
|
|
497
|
+
(tenant, args["project"]),
|
|
498
|
+
).fetchall():
|
|
499
|
+
if item["checkpoint"] not in checkpoints and item["id"] not in deliveries:
|
|
500
|
+
continue
|
|
501
|
+
if len(summaries) >= limit:
|
|
502
|
+
truncation.add("summaries")
|
|
503
|
+
break
|
|
504
|
+
summaries.append(
|
|
505
|
+
{
|
|
506
|
+
"summary": item["id"],
|
|
507
|
+
"checkpoint": item["checkpoint"],
|
|
508
|
+
"principal": item["principal"],
|
|
509
|
+
"method": item["method"],
|
|
510
|
+
"readers": json.loads(item["readers"]),
|
|
511
|
+
"created_ms": item["created"],
|
|
512
|
+
}
|
|
513
|
+
)
|
|
514
|
+
principals: set[str] = {d["principal"] for d in deliveries.values()}
|
|
515
|
+
for value in checkpoints.values():
|
|
516
|
+
principals.update(value["readers"])
|
|
517
|
+
for value in handoffs:
|
|
518
|
+
principals.update((value["sender"], value["recipient"]))
|
|
519
|
+
for value in summaries:
|
|
520
|
+
principals.update(value["readers"])
|
|
521
|
+
state = self.db.execute("SELECT position FROM tenants WHERE tenant=?", (tenant,)).fetchone()
|
|
522
|
+
return {
|
|
523
|
+
"observation": row["id"],
|
|
524
|
+
"source": row["source"],
|
|
525
|
+
"captured_by": row["principal"],
|
|
526
|
+
"position": row["position"],
|
|
527
|
+
"content_hash": row["blob"],
|
|
528
|
+
"claims": claims,
|
|
529
|
+
"checkpoints": list(checkpoints.values()),
|
|
530
|
+
"handoffs": handoffs,
|
|
531
|
+
"summaries": summaries,
|
|
532
|
+
"experience": list(experience.values()),
|
|
533
|
+
"deliveries": list(deliveries.values()),
|
|
534
|
+
"principals": sorted(principals),
|
|
535
|
+
"counts": {
|
|
536
|
+
"claims": len(claims),
|
|
537
|
+
"checkpoints": len(checkpoints),
|
|
538
|
+
"handoffs": len(handoffs),
|
|
539
|
+
"summaries": len(summaries),
|
|
540
|
+
"experience": len(experience),
|
|
541
|
+
"deliveries": len(deliveries),
|
|
542
|
+
"principals": len(principals),
|
|
543
|
+
},
|
|
544
|
+
"truncation": sorted(truncation),
|
|
545
|
+
"coverage": "recorded_dependencies_in_this_project; retained_deliveries_only; prior_exports_provider_deliveries_and_backups_not_tracked",
|
|
546
|
+
"source_position": state["position"],
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
def health(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
550
|
+
"""Whether memory is paying for itself, from records the store already keeps.
|
|
551
|
+
|
|
552
|
+
Counts over one project and a trailing window: helpful feedback against every
|
|
553
|
+
rated vote, briefings that found no relevant memory, observations no retained
|
|
554
|
+
delivery ever included, claims retired because their evidence was purged or
|
|
555
|
+
replaced by a successor, and how long the oldest proposal has waited. Every
|
|
556
|
+
figure is a count or a ratio of counts; no text and no principal is named, so
|
|
557
|
+
the report reveals usage, not content. Admin only, because it aggregates every
|
|
558
|
+
principal's feedback and deliveries in the project. Each signal says what the
|
|
559
|
+
numbers suggest and the thresholds are fixed and documented, not learned."""
|
|
560
|
+
tenant, project = who["tenant"], args["project"]
|
|
561
|
+
days = args.get("days", 30)
|
|
562
|
+
since = at - days * DAY_MS
|
|
563
|
+
frontier = self.db.execute(
|
|
564
|
+
"SELECT position FROM tenants WHERE tenant=?", (tenant,)
|
|
565
|
+
).fetchone()[0]
|
|
566
|
+
|
|
567
|
+
def count(sql: str, *values: Any) -> int:
|
|
568
|
+
return int(self.db.execute(sql, (tenant, project, *values)).fetchone()[0])
|
|
569
|
+
|
|
570
|
+
observations: dict[str, Any] = {
|
|
571
|
+
"total": count(
|
|
572
|
+
"SELECT count(*) FROM observations WHERE tenant=? AND project=? AND deleted=0"
|
|
573
|
+
),
|
|
574
|
+
"recent": count(
|
|
575
|
+
"SELECT count(*) FROM observations o JOIN events e ON e.tenant=o.tenant AND e.position=o.position WHERE o.tenant=? AND o.project=? AND o.deleted=0 AND e.at_ms>=?",
|
|
576
|
+
since,
|
|
577
|
+
),
|
|
578
|
+
"held": count(
|
|
579
|
+
"SELECT count(*) FROM observation_holds h JOIN observations o ON o.tenant=h.tenant AND o.id=h.id WHERE h.tenant=? AND h.project=? AND h.state='held' AND o.deleted=0"
|
|
580
|
+
),
|
|
581
|
+
"purged": count(
|
|
582
|
+
"SELECT count(*) FROM observations WHERE tenant=? AND project=? AND deleted=1"
|
|
583
|
+
),
|
|
584
|
+
}
|
|
585
|
+
# Retained deliveries in the window: briefings (and reruns) by status, every kind
|
|
586
|
+
# by count, and the observations any of them carried.
|
|
587
|
+
by_kind: dict[str, int] = {}
|
|
588
|
+
by_status: dict[str, int] = {}
|
|
589
|
+
carried: set[str] = set()
|
|
590
|
+
for row in self.db.execute(
|
|
591
|
+
"SELECT diagnostics,dependencies FROM rendered_artifacts WHERE tenant=? AND project=? AND state='retained' AND created>=?",
|
|
592
|
+
(tenant, project, since),
|
|
593
|
+
).fetchall():
|
|
594
|
+
diag = json.loads(row["diagnostics"] or "{}")
|
|
595
|
+
kind = str(diag.get("kind") or diag.get("operation") or "brief")
|
|
596
|
+
by_kind[kind] = by_kind.get(kind, 0) + 1
|
|
597
|
+
if kind == "brief":
|
|
598
|
+
status = str(diag.get("status", "unknown"))
|
|
599
|
+
by_status[status] = by_status.get(status, 0) + 1
|
|
600
|
+
for dep in json.loads(row["dependencies"] or "[]"):
|
|
601
|
+
if (
|
|
602
|
+
isinstance(dep, dict)
|
|
603
|
+
and dep.get("kind") == "observation"
|
|
604
|
+
and isinstance(dep.get("id"), str)
|
|
605
|
+
):
|
|
606
|
+
carried.add(dep["id"])
|
|
607
|
+
delivered = 0
|
|
608
|
+
ids = sorted(carried)
|
|
609
|
+
for start in range(0, len(ids), 500):
|
|
610
|
+
chunk = ids[start : start + 500]
|
|
611
|
+
delivered += count(
|
|
612
|
+
"SELECT count(*) FROM observations WHERE tenant=? AND project=? AND deleted=0 AND id IN ("
|
|
613
|
+
+ ",".join("?" for _ in chunk)
|
|
614
|
+
+ ")",
|
|
615
|
+
*chunk,
|
|
616
|
+
)
|
|
617
|
+
observations["delivered"] = delivered
|
|
618
|
+
observations["never_delivered"] = observations["total"] - delivered
|
|
619
|
+
observations["never_delivered_ppm"] = (
|
|
620
|
+
observations["never_delivered"] * 1_000_000 // observations["total"]
|
|
621
|
+
if observations["total"]
|
|
622
|
+
else None
|
|
623
|
+
)
|
|
624
|
+
briefings_total = sum(by_status.values())
|
|
625
|
+
empty = by_status.get("no_relevant_memory", 0)
|
|
626
|
+
briefings = {
|
|
627
|
+
"total": briefings_total,
|
|
628
|
+
"by_status": dict(sorted(by_status.items())),
|
|
629
|
+
"no_relevant_memory": empty,
|
|
630
|
+
"no_relevant_memory_ppm": (
|
|
631
|
+
empty * 1_000_000 // briefings_total if briefings_total else None
|
|
632
|
+
),
|
|
633
|
+
"deliveries": sum(by_kind.values()),
|
|
634
|
+
"deliveries_by_kind": dict(sorted(by_kind.items())),
|
|
635
|
+
}
|
|
636
|
+
# Feedback: the latest revision of each vote, counted once, in the window.
|
|
637
|
+
latest: dict[tuple[str, str, str], tuple[int, int, dict[str, Any]]] = {}
|
|
638
|
+
for row in self.db.execute(
|
|
639
|
+
"SELECT e.principal,e.incarnation,e.logical_key,e.revision,e.body,ev.at_ms FROM experience_records e JOIN events ev ON ev.tenant=e.tenant AND ev.position=e.position WHERE e.tenant=? AND e.project=? AND e.kind='feedback' AND e.body IS NOT NULL",
|
|
640
|
+
(tenant, project),
|
|
641
|
+
).fetchall():
|
|
642
|
+
key = (row["principal"], row["incarnation"], row["logical_key"])
|
|
643
|
+
if key not in latest or latest[key][0] < row["revision"]:
|
|
644
|
+
latest[key] = (row["revision"], row["at_ms"], json.loads(row["body"]))
|
|
645
|
+
by_usefulness: dict[str, int] = {}
|
|
646
|
+
by_use: dict[str, int] = {}
|
|
647
|
+
for _, at_ms, body in latest.values():
|
|
648
|
+
if at_ms < since:
|
|
649
|
+
continue
|
|
650
|
+
usefulness = str(body.get("usefulness", "unknown"))
|
|
651
|
+
by_usefulness[usefulness] = by_usefulness.get(usefulness, 0) + 1
|
|
652
|
+
use = str(body.get("use", "unknown"))
|
|
653
|
+
by_use[use] = by_use.get(use, 0) + 1
|
|
654
|
+
votes = sum(by_usefulness.values())
|
|
655
|
+
rated = votes - by_usefulness.get("unknown", 0)
|
|
656
|
+
helpful = by_usefulness.get("helpful", 0)
|
|
657
|
+
feedback = {
|
|
658
|
+
"votes": votes,
|
|
659
|
+
"rated": rated,
|
|
660
|
+
"helpful": helpful,
|
|
661
|
+
"helpful_ppm": helpful * 1_000_000 // rated if rated else None,
|
|
662
|
+
"by_usefulness": dict(sorted(by_usefulness.items())),
|
|
663
|
+
"by_use": dict(sorted(by_use.items())),
|
|
664
|
+
}
|
|
665
|
+
# Claims: the latest revision of every non-procedure family, purged ones included,
|
|
666
|
+
# so a family retired because its evidence was purged still counts.
|
|
667
|
+
by_state: dict[str, int] = {}
|
|
668
|
+
quarantined = 0
|
|
669
|
+
evidence_purged = 0
|
|
670
|
+
families = 0
|
|
671
|
+
waiting: list[dict[str, Any]] = []
|
|
672
|
+
for row in self.db.execute(
|
|
673
|
+
"SELECT r.id,r.family,r.kind,r.issuer,r.purged,f.logical_key,ev.at_ms FROM revisions r JOIN families f ON f.tenant=r.tenant AND f.id=r.family JOIN events ev ON ev.tenant=r.tenant AND ev.position=r.created WHERE r.tenant=? AND f.project=? AND r.kind!='procedure' AND r.created=(SELECT max(r2.created) FROM revisions r2 WHERE r2.tenant=r.tenant AND r2.family=r.family) ORDER BY r.created,r.id",
|
|
674
|
+
(tenant, project),
|
|
675
|
+
).fetchall():
|
|
676
|
+
families += 1
|
|
677
|
+
if row["purged"]:
|
|
678
|
+
evidence_purged += 1
|
|
679
|
+
continue
|
|
680
|
+
state, quarantine = self.r.k._state(tenant, row["id"], frontier)
|
|
681
|
+
by_state[state] = by_state.get(state, 0) + 1
|
|
682
|
+
if quarantine:
|
|
683
|
+
quarantined += 1
|
|
684
|
+
if state == "proposed":
|
|
685
|
+
waiting.append(
|
|
686
|
+
{
|
|
687
|
+
"revision": row["id"],
|
|
688
|
+
"family": row["family"],
|
|
689
|
+
"logical_key": row["logical_key"],
|
|
690
|
+
"kind": row["kind"],
|
|
691
|
+
"issuer": row["issuer"],
|
|
692
|
+
"quarantined": quarantine,
|
|
693
|
+
"age_ms": max(0, at - row["at_ms"]),
|
|
694
|
+
}
|
|
695
|
+
)
|
|
696
|
+
superseded = count(
|
|
697
|
+
"SELECT count(DISTINCT rp.predecessor) FROM replacements rp JOIN revisions r ON r.tenant=rp.tenant AND r.id=rp.predecessor JOIN families f ON f.tenant=r.tenant AND f.id=r.family WHERE rp.tenant=? AND f.project=?"
|
|
698
|
+
)
|
|
699
|
+
claims = {
|
|
700
|
+
"families": families,
|
|
701
|
+
"by_state": dict(sorted(by_state.items())),
|
|
702
|
+
"quarantined": quarantined,
|
|
703
|
+
"evidence_purged": evidence_purged,
|
|
704
|
+
"superseded": superseded,
|
|
705
|
+
}
|
|
706
|
+
waiting.sort(key=lambda item: (-item["age_ms"], item["revision"]))
|
|
707
|
+
backlog = {
|
|
708
|
+
"proposed": len(waiting),
|
|
709
|
+
"oldest_age_ms": waiting[0]["age_ms"] if waiting else None,
|
|
710
|
+
"items": waiting[:BACKLOG_ITEMS],
|
|
711
|
+
"truncated": len(waiting) > BACKLOG_ITEMS,
|
|
712
|
+
}
|
|
713
|
+
signals: list[dict[str, str]] = []
|
|
714
|
+
|
|
715
|
+
def signal(name: str, level: str, text: str) -> None:
|
|
716
|
+
signals.append({"name": name, "level": level, "text": text})
|
|
717
|
+
|
|
718
|
+
if rated < HEALTH_MIN_SAMPLE:
|
|
719
|
+
signal(
|
|
720
|
+
"feedback",
|
|
721
|
+
"unknown",
|
|
722
|
+
f"{rated} rated vote(s) in {days} day(s); at least {HEALTH_MIN_SAMPLE} are needed before the helpful ratio means anything.",
|
|
723
|
+
)
|
|
724
|
+
elif by_usefulness.get("harmful", 0) or by_usefulness.get("misleading", 0):
|
|
725
|
+
signal(
|
|
726
|
+
"feedback",
|
|
727
|
+
"attention",
|
|
728
|
+
f"{by_usefulness.get('harmful', 0)} harmful and {by_usefulness.get('misleading', 0)} misleading vote(s): look at what was delivered and consider quarantine.",
|
|
729
|
+
)
|
|
730
|
+
elif helpful * 2 < rated:
|
|
731
|
+
signal(
|
|
732
|
+
"feedback",
|
|
733
|
+
"watch",
|
|
734
|
+
f"{helpful} of {rated} rated votes were helpful: under half of what memory delivered was worth reading.",
|
|
735
|
+
)
|
|
736
|
+
else:
|
|
737
|
+
signal("feedback", "ok", f"{helpful} of {rated} rated votes were helpful.")
|
|
738
|
+
if briefings_total < HEALTH_MIN_SAMPLE:
|
|
739
|
+
signal(
|
|
740
|
+
"briefings",
|
|
741
|
+
"unknown",
|
|
742
|
+
f"{briefings_total} retained briefing(s) in {days} day(s); at least {HEALTH_MIN_SAMPLE} are needed before the empty share means anything.",
|
|
743
|
+
)
|
|
744
|
+
elif empty * 2 > briefings_total:
|
|
745
|
+
signal(
|
|
746
|
+
"briefings",
|
|
747
|
+
"watch",
|
|
748
|
+
f"{empty} of {briefings_total} briefings found no relevant memory: agents ask about things nothing was captured for.",
|
|
749
|
+
)
|
|
750
|
+
elif by_status.get("budget_insufficient", 0) * 4 > briefings_total:
|
|
751
|
+
signal(
|
|
752
|
+
"briefings",
|
|
753
|
+
"watch",
|
|
754
|
+
f"{by_status.get('budget_insufficient', 0)} of {briefings_total} briefings ran out of output budget: raise max_output_tokens or ask narrower questions.",
|
|
755
|
+
)
|
|
756
|
+
else:
|
|
757
|
+
signal(
|
|
758
|
+
"briefings",
|
|
759
|
+
"ok",
|
|
760
|
+
f"{briefings_total - empty} of {briefings_total} briefings carried relevant memory.",
|
|
761
|
+
)
|
|
762
|
+
if not waiting:
|
|
763
|
+
signal("backlog", "ok", "No proposal is waiting for review.")
|
|
764
|
+
elif waiting[0]["age_ms"] > BACKLOG_ATTENTION_MS:
|
|
765
|
+
signal(
|
|
766
|
+
"backlog",
|
|
767
|
+
"attention",
|
|
768
|
+
f"{len(waiting)} proposal(s) waiting; the oldest for {waiting[0]['age_ms'] // DAY_MS} day(s). Reviewed knowledge is not growing.",
|
|
769
|
+
)
|
|
770
|
+
else:
|
|
771
|
+
signal("backlog", "watch", f"{len(waiting)} proposal(s) waiting for review.")
|
|
772
|
+
if quarantined:
|
|
773
|
+
signal(
|
|
774
|
+
"evidence",
|
|
775
|
+
"attention",
|
|
776
|
+
f"{quarantined} claim(s) quarantined; {evidence_purged} retired because evidence was purged; {superseded} replaced.",
|
|
777
|
+
)
|
|
778
|
+
elif evidence_purged:
|
|
779
|
+
signal(
|
|
780
|
+
"evidence",
|
|
781
|
+
"watch",
|
|
782
|
+
f"{evidence_purged} claim(s) retired because their evidence was purged; propose again from evidence that remains. {superseded} replaced.",
|
|
783
|
+
)
|
|
784
|
+
else:
|
|
785
|
+
signal(
|
|
786
|
+
"evidence",
|
|
787
|
+
"ok",
|
|
788
|
+
f"No claim lost its evidence; {superseded} replaced by a successor.",
|
|
789
|
+
)
|
|
790
|
+
if observations["total"] < 4 * HEALTH_MIN_SAMPLE:
|
|
791
|
+
signal(
|
|
792
|
+
"reach",
|
|
793
|
+
"unknown",
|
|
794
|
+
f"{observations['total']} observation(s); too few to judge how much of memory is read.",
|
|
795
|
+
)
|
|
796
|
+
elif observations["never_delivered"] * 10 > observations["total"] * 9:
|
|
797
|
+
signal(
|
|
798
|
+
"reach",
|
|
799
|
+
"watch",
|
|
800
|
+
f"{observations['never_delivered']} of {observations['total']} observations were in no retained delivery in {days} day(s): memory is written far more than it is read.",
|
|
801
|
+
)
|
|
802
|
+
else:
|
|
803
|
+
signal(
|
|
804
|
+
"reach",
|
|
805
|
+
"ok",
|
|
806
|
+
f"{delivered} of {observations['total']} observations reached a retained delivery in {days} day(s).",
|
|
807
|
+
)
|
|
808
|
+
return {
|
|
809
|
+
"window": {"days": days, "since_ms": since},
|
|
810
|
+
"observations": observations,
|
|
811
|
+
"briefings": briefings,
|
|
812
|
+
"feedback": feedback,
|
|
813
|
+
"claims": claims,
|
|
814
|
+
"backlog": backlog,
|
|
815
|
+
"signals": signals,
|
|
816
|
+
"coverage": "counts_only_no_text_no_principals; retained_deliveries_in_window_only; latest_vote_per_actor_and_item; latest_revision_per_family; thresholds_fixed_not_learned",
|
|
817
|
+
"source_position": frontier,
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
def trust_list(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
821
|
+
from memoryking.adapters.trust import Trust
|
|
822
|
+
|
|
823
|
+
return {"rules": Trust(self.s).rules(who["tenant"], args["project"])}
|
|
824
|
+
|
|
825
|
+
def catalog(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
826
|
+
"""The project's records as a catalog, newest first, paged by position.
|
|
827
|
+
|
|
828
|
+
`observations` lists every visible capture (optionally one source, one file
|
|
829
|
+
name with its versions, or one id); `claims` lists the latest unpurged
|
|
830
|
+
`knowledge` revision of every family, accepted ones for every reader and the
|
|
831
|
+
rest only for a reviewer. Text is included unless `text` is false, within a
|
|
832
|
+
page budget, so the memory-tool adapter and the vault export can read a whole
|
|
833
|
+
project without a model and without a briefing. Reads here leave no delivery
|
|
834
|
+
record; `fetch` is the receipted way to open one record."""
|
|
835
|
+
if args.get("kind", "observations") == "claims":
|
|
836
|
+
return self._claim_catalog(who, args, at)
|
|
837
|
+
return self._observation_catalog(who, args, at)
|
|
838
|
+
|
|
839
|
+
def _observation_catalog(
|
|
840
|
+
self, who: dict[str, Any], args: dict[str, Any], at: int
|
|
841
|
+
) -> dict[str, Any]:
|
|
842
|
+
where = ["o.tenant=?", "o.project=?", "o.deleted=0"]
|
|
843
|
+
values: list[Any] = [who["tenant"], args["project"]]
|
|
844
|
+
if "source" in args:
|
|
845
|
+
where.append("o.source=?")
|
|
846
|
+
values.append(args["source"])
|
|
847
|
+
if "name" in args:
|
|
848
|
+
# A file's versions share its name: `name`, then `name__v2`, `name__v3`, ...
|
|
849
|
+
where.append("(o.source_event=? OR o.source_event LIKE ? ESCAPE '!')")
|
|
850
|
+
values.extend(
|
|
851
|
+
[args["name"], args["name"].replace("!", "!!").replace("_", "!_") + "!_!_v%"]
|
|
852
|
+
)
|
|
853
|
+
if "id" in args:
|
|
854
|
+
where.append("o.id=?")
|
|
855
|
+
values.append(args["id"])
|
|
856
|
+
total = self.db.execute(
|
|
857
|
+
"SELECT count(*) FROM observations o WHERE " + " AND ".join(where), values
|
|
858
|
+
).fetchone()[0]
|
|
859
|
+
if "after" in args:
|
|
860
|
+
where.append("o.position<?")
|
|
861
|
+
values.append(args["after"])
|
|
862
|
+
limit = args.get("limit", 256)
|
|
863
|
+
rows = self.db.execute(
|
|
864
|
+
"SELECT o.*,e.at_ms AS recorded_ms FROM observations o JOIN events e ON e.tenant=o.tenant AND e.position=o.position WHERE "
|
|
865
|
+
+ " AND ".join(where)
|
|
866
|
+
+ " ORDER BY o.position DESC,o.id DESC LIMIT ?",
|
|
867
|
+
(*values, limit + 1),
|
|
868
|
+
).fetchall()
|
|
869
|
+
version = re.compile(r"^(.+?)__v[0-9]+$")
|
|
870
|
+
items: list[dict[str, Any]] = []
|
|
871
|
+
used = 0
|
|
872
|
+
next_after: int | None = None
|
|
873
|
+
for index, row in enumerate(rows):
|
|
874
|
+
if index >= limit:
|
|
875
|
+
next_after = rows[index - 1]["position"]
|
|
876
|
+
break
|
|
877
|
+
if not self.s._visible(who, row, at):
|
|
878
|
+
continue
|
|
879
|
+
if "name" in args:
|
|
880
|
+
match = version.match(row["source_event"])
|
|
881
|
+
if (match.group(1) if match else row["source_event"]) != args["name"]:
|
|
882
|
+
continue
|
|
883
|
+
raw = self.r._blob(row)
|
|
884
|
+
if items and args.get("text", True) and used + len(raw) > CATALOG_TEXT_BYTES:
|
|
885
|
+
next_after = row["position"] + 1
|
|
886
|
+
break
|
|
887
|
+
used += len(raw)
|
|
888
|
+
item = {
|
|
889
|
+
"id": row["id"],
|
|
890
|
+
"source": row["source"],
|
|
891
|
+
"source_event": row["source_event"],
|
|
892
|
+
"principal": row["principal"],
|
|
893
|
+
"position": row["position"],
|
|
894
|
+
"recorded_ms": row["recorded_ms"],
|
|
895
|
+
"observed_at_ms": row["observed_at_ms"],
|
|
896
|
+
"classification": row["classification"],
|
|
897
|
+
"readers": json.loads(row["readers"]),
|
|
898
|
+
"bytes": len(raw),
|
|
899
|
+
"hash": row["blob"],
|
|
900
|
+
}
|
|
901
|
+
if args.get("text", True):
|
|
902
|
+
item["text"] = raw.decode("utf-8", "replace")
|
|
903
|
+
items.append(item)
|
|
904
|
+
return {
|
|
905
|
+
"kind": "observations",
|
|
906
|
+
"items": items,
|
|
907
|
+
"total": total,
|
|
908
|
+
"next_after": next_after,
|
|
909
|
+
"coverage": "visible_observations_newest_first; one_page_per_call; text_within_page_budget",
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
def _claim_catalog(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
913
|
+
tenant = who["tenant"]
|
|
914
|
+
try:
|
|
915
|
+
self.s._subject_auth(
|
|
916
|
+
self.s._token("credential", tenant=tenant, principal=who["principal"]),
|
|
917
|
+
"review",
|
|
918
|
+
args["project"],
|
|
919
|
+
at,
|
|
920
|
+
)
|
|
921
|
+
reviewer = True
|
|
922
|
+
except LocalError:
|
|
923
|
+
reviewer = False
|
|
924
|
+
frontier = self.db.execute(
|
|
925
|
+
"SELECT position FROM tenants WHERE tenant=?", (tenant,)
|
|
926
|
+
).fetchone()[0]
|
|
927
|
+
where = [
|
|
928
|
+
"r.tenant=?",
|
|
929
|
+
"f.project=?",
|
|
930
|
+
"r.kind='knowledge'",
|
|
931
|
+
"r.purged=0",
|
|
932
|
+
"r.created=(SELECT max(r2.created) FROM revisions r2 WHERE r2.tenant=r.tenant AND r2.family=r.family AND r2.purged=0)",
|
|
933
|
+
]
|
|
934
|
+
values: list[Any] = [tenant, args["project"]]
|
|
935
|
+
if "name" in args:
|
|
936
|
+
where.append("f.logical_key=?")
|
|
937
|
+
values.append(args["name"])
|
|
938
|
+
if "id" in args:
|
|
939
|
+
where.append("r.id=?")
|
|
940
|
+
values.append(args["id"])
|
|
941
|
+
total = self.db.execute(
|
|
942
|
+
"SELECT count(*) FROM revisions r JOIN families f ON r.tenant=f.tenant AND r.family=f.id WHERE "
|
|
943
|
+
+ " AND ".join(where),
|
|
944
|
+
values,
|
|
945
|
+
).fetchone()[0]
|
|
946
|
+
if "after" in args:
|
|
947
|
+
where.append("r.created<?")
|
|
948
|
+
values.append(args["after"])
|
|
949
|
+
limit = args.get("limit", 256)
|
|
950
|
+
rows = self.db.execute(
|
|
951
|
+
"SELECT r.*,f.project,f.logical_key,f.version AS family_version FROM revisions r JOIN families f ON r.tenant=f.tenant AND r.family=f.id WHERE "
|
|
952
|
+
+ " AND ".join(where)
|
|
953
|
+
+ " ORDER BY r.created DESC LIMIT ?",
|
|
954
|
+
(*values, limit + 1),
|
|
955
|
+
).fetchall()
|
|
956
|
+
items: list[dict[str, Any]] = []
|
|
957
|
+
used = 0
|
|
958
|
+
next_after: int | None = None
|
|
959
|
+
for index, row in enumerate(rows):
|
|
960
|
+
if index >= limit:
|
|
961
|
+
next_after = rows[index - 1]["created"]
|
|
962
|
+
break
|
|
963
|
+
state, quarantined = self.r.k._state(tenant, row["id"], frontier)
|
|
964
|
+
if (state != "accepted" or quarantined) and not reviewer:
|
|
965
|
+
continue
|
|
966
|
+
if not self.r.k._available(who, row, at):
|
|
967
|
+
continue
|
|
968
|
+
body = json.loads(row["body"])
|
|
969
|
+
size = len(body["text"].encode())
|
|
970
|
+
if items and args.get("text", True) and used + size > CATALOG_TEXT_BYTES:
|
|
971
|
+
next_after = row["created"] + 1
|
|
972
|
+
break
|
|
973
|
+
used += size
|
|
974
|
+
item = {
|
|
975
|
+
"revision": row["id"],
|
|
976
|
+
"family": row["family"],
|
|
977
|
+
"logical_key": row["logical_key"],
|
|
978
|
+
"family_version": row["family_version"],
|
|
979
|
+
"state": state,
|
|
980
|
+
"quarantined": quarantined,
|
|
981
|
+
"kind": row["kind"],
|
|
982
|
+
"created": row["created"],
|
|
983
|
+
"issuer": row["issuer"],
|
|
984
|
+
"bytes": size,
|
|
985
|
+
"hash": hashlib.sha256(body["text"].encode()).hexdigest(),
|
|
986
|
+
"valid_start": body["valid_start"],
|
|
987
|
+
"valid_end": body["valid_end"],
|
|
988
|
+
"readers": body["readers"],
|
|
989
|
+
"evidence": sorted(
|
|
990
|
+
{
|
|
991
|
+
span["observation"]
|
|
992
|
+
for span in self.db.execute(
|
|
993
|
+
"SELECT observation FROM evidence_spans WHERE tenant=? AND revision=?",
|
|
994
|
+
(tenant, row["id"]),
|
|
995
|
+
).fetchall()
|
|
996
|
+
}
|
|
997
|
+
),
|
|
998
|
+
"provenance": body.get("provenance", {}),
|
|
999
|
+
}
|
|
1000
|
+
if args.get("text", True):
|
|
1001
|
+
item["text"] = body["text"]
|
|
1002
|
+
items.append(item)
|
|
1003
|
+
return {
|
|
1004
|
+
"kind": "claims",
|
|
1005
|
+
"items": items,
|
|
1006
|
+
"total": total,
|
|
1007
|
+
"next_after": next_after,
|
|
1008
|
+
"reviewer": reviewer,
|
|
1009
|
+
"coverage": "latest_unpurged_knowledge_revision_per_family_newest_first; accepted_for_readers; every_state_for_reviewers",
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
def held(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
|
|
1013
|
+
from memoryking.adapters.trust import Trust
|
|
1014
|
+
|
|
1015
|
+
items = Trust(self.s).listing(who, args["project"])
|
|
1016
|
+
return {
|
|
1017
|
+
"held": items,
|
|
1018
|
+
"coverage": "oldest_64_held_captures_in_this_project; preview_is_the_first_256_bytes",
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
def policy(self, who: dict[str, Any], command: dict[str, Any], at: int) -> dict[str, Any]:
|
|
1022
|
+
"""A trust rule or a release is a journaled policy decision with a retry key."""
|
|
1023
|
+
action, args = command["action"], command["args"]
|
|
1024
|
+
lookup = (
|
|
1025
|
+
who["tenant"],
|
|
1026
|
+
self.s.incarnation,
|
|
1027
|
+
"dashboard-trust-v1",
|
|
1028
|
+
who["principal"],
|
|
1029
|
+
action,
|
|
1030
|
+
command["key"],
|
|
1031
|
+
)
|
|
1032
|
+
old = self.db.execute(
|
|
1033
|
+
"SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
1034
|
+
lookup,
|
|
1035
|
+
).fetchone()
|
|
1036
|
+
if old is not None:
|
|
1037
|
+
if old["hash"] != canonical_hash(command):
|
|
1038
|
+
raise LocalError("idempotency_conflict")
|
|
1039
|
+
if old["result"] is None or at >= old["expires"]:
|
|
1040
|
+
raise LocalError("idempotency_result_expired")
|
|
1041
|
+
return {**json.loads(old["result"]), "replayed": True}
|
|
1042
|
+
record: dict[str, Any] = {"tenant": who["tenant"], "actor": who["principal"]}
|
|
1043
|
+
if action == "trust":
|
|
1044
|
+
record.update(
|
|
1045
|
+
kind="trust",
|
|
1046
|
+
project=args["project"],
|
|
1047
|
+
source=args["source"],
|
|
1048
|
+
level=args["level"],
|
|
1049
|
+
explicit=args.get("explicit", True),
|
|
1050
|
+
)
|
|
1051
|
+
result = {
|
|
1052
|
+
"project": args["project"],
|
|
1053
|
+
"source": args["source"],
|
|
1054
|
+
"level": args["level"],
|
|
1055
|
+
"status": "recorded",
|
|
1056
|
+
"replayed": False,
|
|
1057
|
+
}
|
|
1058
|
+
else:
|
|
1059
|
+
row = self.db.execute(
|
|
1060
|
+
"SELECT 1 FROM observation_holds WHERE tenant=? AND id=? AND project=? AND state='held'",
|
|
1061
|
+
(who["tenant"], args["observation"], args["project"]),
|
|
1062
|
+
).fetchone()
|
|
1063
|
+
if row is None:
|
|
1064
|
+
raise LocalError("hold_unavailable")
|
|
1065
|
+
record.update(kind="hold", observation=args["observation"])
|
|
1066
|
+
result = {"observation": args["observation"], "status": "released", "replayed": False}
|
|
1067
|
+
self.s._apply(self.s._journal(record), at)
|
|
1068
|
+
self.db.execute(
|
|
1069
|
+
"INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
1070
|
+
(*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
|
|
1071
|
+
)
|
|
1072
|
+
return result
|
|
1073
|
+
|
|
1074
|
+
def purge(self, who: dict[str, Any], command: dict[str, Any], at: int) -> dict[str, Any]:
|
|
1075
|
+
args = command["args"]
|
|
1076
|
+
lookup = (
|
|
1077
|
+
who["tenant"],
|
|
1078
|
+
self.s.incarnation,
|
|
1079
|
+
"dashboard-retention-v1",
|
|
1080
|
+
who["principal"],
|
|
1081
|
+
"purge",
|
|
1082
|
+
command["key"],
|
|
1083
|
+
)
|
|
1084
|
+
old = self.db.execute(
|
|
1085
|
+
"SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
1086
|
+
lookup,
|
|
1087
|
+
).fetchone()
|
|
1088
|
+
if old is not None:
|
|
1089
|
+
if old["hash"] != canonical_hash(command):
|
|
1090
|
+
raise LocalError("idempotency_conflict")
|
|
1091
|
+
if old["result"] is None or at >= old["expires"]:
|
|
1092
|
+
raise LocalError("idempotency_result_expired")
|
|
1093
|
+
return {**json.loads(old["result"]), "replayed": True}
|
|
1094
|
+
token = self.s._decode(args["preview"], "retention_preview")
|
|
1095
|
+
state = dict(
|
|
1096
|
+
self.db.execute("SELECT * FROM tenants WHERE tenant=?", (who["tenant"],)).fetchone()
|
|
1097
|
+
)
|
|
1098
|
+
if (
|
|
1099
|
+
token.get("tenant") != who["tenant"]
|
|
1100
|
+
or token.get("principal") != who["principal"]
|
|
1101
|
+
or token.get("project") != args["project"]
|
|
1102
|
+
or token.get("observation") != args["observation"]
|
|
1103
|
+
or args["confirm"] != args["observation"]
|
|
1104
|
+
or at >= token.get("expires", 0)
|
|
1105
|
+
or token.get("state") != canonical_hash(state)
|
|
1106
|
+
):
|
|
1107
|
+
raise LocalError("retention_preview_stale")
|
|
1108
|
+
current = self.retention(who, args, at)
|
|
1109
|
+
current.pop("preview")
|
|
1110
|
+
if token.get("digest") != canonical_hash(current):
|
|
1111
|
+
raise LocalError("retention_preview_stale")
|
|
1112
|
+
self.s._apply(
|
|
1113
|
+
self.s._journal(
|
|
1114
|
+
{
|
|
1115
|
+
"kind": "purge",
|
|
1116
|
+
"tenant": who["tenant"],
|
|
1117
|
+
"actor": who["principal"],
|
|
1118
|
+
"observation": args["observation"],
|
|
1119
|
+
}
|
|
1120
|
+
),
|
|
1121
|
+
at,
|
|
1122
|
+
)
|
|
1123
|
+
result = {"observation": args["observation"], "status": "purged", "replayed": False}
|
|
1124
|
+
self.db.execute(
|
|
1125
|
+
"INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
1126
|
+
(*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
|
|
1127
|
+
)
|
|
1128
|
+
return result
|