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,494 @@
|
|
|
1
|
+
"""Recipient-bound full handoffs. Preparation never sends content or transfers ownership."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import sqlite3
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, cast
|
|
10
|
+
|
|
11
|
+
from jsonschema import Draft202012Validator
|
|
12
|
+
|
|
13
|
+
from memoryking.adapters.local_store import RETRY_MS, uid
|
|
14
|
+
from memoryking.adapters.token_count import counter
|
|
15
|
+
from memoryking.adapters.working import Working
|
|
16
|
+
from memoryking.application.store_core import StoreCore
|
|
17
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash
|
|
18
|
+
from memoryking.domain.briefing import counted
|
|
19
|
+
from memoryking.domain.checkpoint import stream_name
|
|
20
|
+
from memoryking.domain.local import Decision, LocalError, Released
|
|
21
|
+
from memoryking.domain.selectors import bindings
|
|
22
|
+
|
|
23
|
+
VALIDATOR = Draft202012Validator(
|
|
24
|
+
json.loads(Path(__file__).with_name("handoff.schema.json").read_text())
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Handoff:
|
|
29
|
+
def __init__(self, store: StoreCore):
|
|
30
|
+
self.s, self.db = store, store.db
|
|
31
|
+
self.w = Working(store)
|
|
32
|
+
self.r = self.w.r
|
|
33
|
+
|
|
34
|
+
def _identity(
|
|
35
|
+
self, tenant: str, principal: str, project: str, at: int, capability: str = "read"
|
|
36
|
+
) -> dict[str, Any]:
|
|
37
|
+
return self.s._subject_auth(
|
|
38
|
+
self.s._token("credential", tenant=tenant, principal=principal), capability, project, at
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def _scope(row: sqlite3.Row) -> dict[str, Any]:
|
|
43
|
+
return {
|
|
44
|
+
"project": row["project"],
|
|
45
|
+
"task": row["task"],
|
|
46
|
+
"run": None if row["stream"] == "task" else row["stream"][4:],
|
|
47
|
+
"checkpoint": row["checkpoint"],
|
|
48
|
+
"bindings": json.loads(row["bindings"]),
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
def _row(self, who: dict[str, Any], project: str, identifier: str, action: str) -> sqlite3.Row:
|
|
52
|
+
role = "recipient" if action in {"materialize", "ack"} else "sender"
|
|
53
|
+
row = self.db.execute(
|
|
54
|
+
"SELECT * FROM handoffs WHERE tenant=? AND project=? AND id=?",
|
|
55
|
+
(who["tenant"], project, identifier),
|
|
56
|
+
).fetchone()
|
|
57
|
+
if row is None or row[role] != who["principal"]:
|
|
58
|
+
raise LocalError("handoff_unavailable")
|
|
59
|
+
if row["incarnation"] != self.s.incarnation:
|
|
60
|
+
raise LocalError("history_changed")
|
|
61
|
+
return cast(sqlite3.Row, row)
|
|
62
|
+
|
|
63
|
+
def _active(self, row: sqlite3.Row, at: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
64
|
+
if row["state"] not in {"prepared", "acknowledged"}:
|
|
65
|
+
raise LocalError("handoff_unavailable")
|
|
66
|
+
if at >= row["expires"]:
|
|
67
|
+
raise LocalError("handoff_expired")
|
|
68
|
+
try:
|
|
69
|
+
sender = self._identity(row["tenant"], row["sender"], row["project"], at, "handoff")
|
|
70
|
+
self._identity(row["tenant"], row["sender"], row["project"], at)
|
|
71
|
+
recipient = self._identity(row["tenant"], row["recipient"], row["project"], at)
|
|
72
|
+
args = self._scope(row)
|
|
73
|
+
self.w._checkpoint(sender, args, at)
|
|
74
|
+
self.w._checkpoint(recipient, args, at)
|
|
75
|
+
stream = self.w._stream(sender, args)
|
|
76
|
+
if (
|
|
77
|
+
stream is None
|
|
78
|
+
or stream["latest"] != row["checkpoint"]
|
|
79
|
+
or stream["revision"] != row["stream_revision"]
|
|
80
|
+
or stream["incarnation"] != self.s.incarnation
|
|
81
|
+
):
|
|
82
|
+
raise LocalError("handoff_superseded")
|
|
83
|
+
except LocalError as exc:
|
|
84
|
+
if exc.code == "handoff_superseded":
|
|
85
|
+
raise
|
|
86
|
+
raise LocalError("handoff_unavailable") from exc
|
|
87
|
+
return sender, recipient
|
|
88
|
+
|
|
89
|
+
def _prepare_check(self, who: dict[str, Any], args: dict[str, Any], at: int) -> sqlite3.Row:
|
|
90
|
+
bindings(args["bindings"])
|
|
91
|
+
try:
|
|
92
|
+
recipient = self._identity(who["tenant"], args["recipient"], args["project"], at)
|
|
93
|
+
self.w._checkpoint(who, args, at)
|
|
94
|
+
self.w._checkpoint(recipient, args, at)
|
|
95
|
+
stream = self.w._stream(who, args)
|
|
96
|
+
if (
|
|
97
|
+
stream is None
|
|
98
|
+
or stream["latest"] != args["checkpoint"]
|
|
99
|
+
or stream["incarnation"] != self.s.incarnation
|
|
100
|
+
):
|
|
101
|
+
raise LocalError("handoff_superseded")
|
|
102
|
+
except LocalError as exc:
|
|
103
|
+
if exc.code == "handoff_superseded":
|
|
104
|
+
raise
|
|
105
|
+
raise LocalError("handoff_unavailable") from exc
|
|
106
|
+
return stream
|
|
107
|
+
|
|
108
|
+
def _snapshot(
|
|
109
|
+
self, row: sqlite3.Row, recipient: dict[str, Any], at: int
|
|
110
|
+
) -> tuple[str, dict[str, Any], list[dict[str, str]]]:
|
|
111
|
+
args = self._scope(row)
|
|
112
|
+
policy = self.r.k.query(
|
|
113
|
+
recipient,
|
|
114
|
+
{k: args[k] for k in ("project", "task", "run", "bindings") if args[k] is not None},
|
|
115
|
+
at,
|
|
116
|
+
constraints=True,
|
|
117
|
+
)
|
|
118
|
+
# Do not bind to the wall clock or unrelated receipt/event positions.
|
|
119
|
+
policy = {k: v for k, v in policy.items() if k not in {"valid_ms", "recorded_position"}}
|
|
120
|
+
operations, deps = self.w._operations(recipient, args, at, include_all=True)
|
|
121
|
+
deps.extend(self.r._dependencies([self.r._claim(item) for item in policy["items"]]))
|
|
122
|
+
checkpoint = self.w._checkpoint(recipient, args, at)
|
|
123
|
+
available = []
|
|
124
|
+
for artifact in json.loads(checkpoint["body"])["repository"]["artifacts"]:
|
|
125
|
+
if artifact["availability"] == "stored":
|
|
126
|
+
source = self.db.execute(
|
|
127
|
+
"SELECT * FROM observations WHERE tenant=? AND id=?",
|
|
128
|
+
(row["tenant"], artifact["observation"]),
|
|
129
|
+
).fetchone()
|
|
130
|
+
try:
|
|
131
|
+
self.r._blob(source)
|
|
132
|
+
available.append(True)
|
|
133
|
+
except (LocalError, OSError):
|
|
134
|
+
available.append(False)
|
|
135
|
+
epoch = self.db.execute(
|
|
136
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (row["tenant"],)
|
|
137
|
+
).fetchone()
|
|
138
|
+
stamp = canonical_hash(
|
|
139
|
+
{
|
|
140
|
+
"compiler_revision": "handoff-v1",
|
|
141
|
+
"policy": policy,
|
|
142
|
+
"operations": operations,
|
|
143
|
+
"checkpoint_hash": checkpoint["body_hash"],
|
|
144
|
+
"stream_revision": row["stream_revision"],
|
|
145
|
+
"epochs": list(epoch),
|
|
146
|
+
"stored_artifacts_available": available,
|
|
147
|
+
}
|
|
148
|
+
)
|
|
149
|
+
return stamp, policy, deps
|
|
150
|
+
|
|
151
|
+
def _intersection(
|
|
152
|
+
self,
|
|
153
|
+
row: sqlite3.Row,
|
|
154
|
+
sender: dict[str, Any],
|
|
155
|
+
policy: dict[str, Any],
|
|
156
|
+
deps: list[dict[str, str]],
|
|
157
|
+
at: int,
|
|
158
|
+
) -> bool:
|
|
159
|
+
if policy["status"] != "complete":
|
|
160
|
+
return False
|
|
161
|
+
try:
|
|
162
|
+
self.w._operations(sender, self._scope(row), at, include_all=True)
|
|
163
|
+
for dep in deps:
|
|
164
|
+
self.w._dependency(sender, dep, at)
|
|
165
|
+
except LocalError:
|
|
166
|
+
return False
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
def verify_dependency(self, who: dict[str, Any], identifier: str, at: int) -> None:
|
|
170
|
+
view = self.db.execute(
|
|
171
|
+
"SELECT * FROM handoff_views WHERE tenant=? AND id=? AND actor=?",
|
|
172
|
+
(who["tenant"], identifier, who["principal"]),
|
|
173
|
+
).fetchone()
|
|
174
|
+
if view is None:
|
|
175
|
+
raise LocalError("handoff_unavailable")
|
|
176
|
+
target = self.db.execute(
|
|
177
|
+
"SELECT project FROM handoffs WHERE tenant=? AND id=?",
|
|
178
|
+
(who["tenant"], view["handoff"]),
|
|
179
|
+
).fetchone()
|
|
180
|
+
if target is None:
|
|
181
|
+
raise LocalError("handoff_unavailable")
|
|
182
|
+
row = self._row(
|
|
183
|
+
who,
|
|
184
|
+
target["project"],
|
|
185
|
+
view["handoff"],
|
|
186
|
+
view["mode"],
|
|
187
|
+
)
|
|
188
|
+
sender, recipient = self._active(row, at)
|
|
189
|
+
stamp, policy, deps = self._snapshot(row, recipient, at)
|
|
190
|
+
if view["stamp"] != stamp:
|
|
191
|
+
raise LocalError("handoff_view_stale")
|
|
192
|
+
if (
|
|
193
|
+
view["mode"] == "preview"
|
|
194
|
+
and view["status"] != "blocked"
|
|
195
|
+
and not self._intersection(row, sender, policy, deps, at)
|
|
196
|
+
):
|
|
197
|
+
raise LocalError("handoff_view_stale")
|
|
198
|
+
|
|
199
|
+
def execute(self, credential: str, command: dict[str, Any]) -> Released:
|
|
200
|
+
if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
|
|
201
|
+
raise LocalError("invalid_request")
|
|
202
|
+
if command["incarnation"] != self.s.incarnation:
|
|
203
|
+
raise LocalError("history_changed")
|
|
204
|
+
action, args = command["action"], command["args"]
|
|
205
|
+
receipt = uid("rcpt")
|
|
206
|
+
deps: list[dict[str, str]] = []
|
|
207
|
+
with self.s.transaction() as decision:
|
|
208
|
+
at = decision.evaluated_ms
|
|
209
|
+
who = self.s._auth(credential, "read", args["project"], at)
|
|
210
|
+
if action in {"prepare", "preview", "cancel"}:
|
|
211
|
+
self.s._auth(credential, "handoff", args["project"], at)
|
|
212
|
+
self.r._expire(at)
|
|
213
|
+
row = None
|
|
214
|
+
if action == "prepare":
|
|
215
|
+
stream = self._prepare_check(who, args, at)
|
|
216
|
+
else:
|
|
217
|
+
row = self._row(who, args["project"], args["handle"], action)
|
|
218
|
+
if action != "cancel":
|
|
219
|
+
self._active(row, at)
|
|
220
|
+
lookup = (
|
|
221
|
+
who["tenant"],
|
|
222
|
+
self.s.incarnation,
|
|
223
|
+
"handoff-v1",
|
|
224
|
+
who["principal"],
|
|
225
|
+
action,
|
|
226
|
+
command["key"],
|
|
227
|
+
)
|
|
228
|
+
old = self.db.execute(
|
|
229
|
+
"SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
230
|
+
lookup,
|
|
231
|
+
).fetchone()
|
|
232
|
+
if old is not None:
|
|
233
|
+
if old["hash"] != canonical_hash(command):
|
|
234
|
+
raise LocalError("idempotency_conflict")
|
|
235
|
+
if old["result"] is None or at >= old["expires"]:
|
|
236
|
+
raise LocalError("idempotency_result_expired")
|
|
237
|
+
result = json.loads(old["result"])
|
|
238
|
+
if action in {"materialize", "preview"}:
|
|
239
|
+
artifact = self.r._artifact(who, args["project"], result["materialization"], at)
|
|
240
|
+
raw = bytes(artifact["body"])
|
|
241
|
+
deps = json.loads(artifact["dependencies"])
|
|
242
|
+
elif action == "prepare":
|
|
243
|
+
self._active(self._row(who, args["project"], result["handle"], "prepare"), at)
|
|
244
|
+
elif action == "ack":
|
|
245
|
+
self._ack_check(who, cast(sqlite3.Row, row), args, at)
|
|
246
|
+
elif action == "prepare":
|
|
247
|
+
result = self._prepare(who, args, stream, at)
|
|
248
|
+
elif action in {"materialize", "preview"}:
|
|
249
|
+
raw, deps = self._render(
|
|
250
|
+
who, cast(sqlite3.Row, row), action, args, decision, receipt
|
|
251
|
+
)
|
|
252
|
+
result = {"materialization": receipt}
|
|
253
|
+
elif action == "ack":
|
|
254
|
+
self._ack_check(who, cast(sqlite3.Row, row), args, at)
|
|
255
|
+
self.db.execute(
|
|
256
|
+
"UPDATE handoffs SET state='acknowledged',ack_view=? WHERE tenant=? AND id=?",
|
|
257
|
+
(args["materialization"], who["tenant"], args["handle"]),
|
|
258
|
+
)
|
|
259
|
+
self._event(who, "handoff_acknowledged", args["handle"], at)
|
|
260
|
+
result = {
|
|
261
|
+
"handle": args["handle"],
|
|
262
|
+
"status": "acknowledged",
|
|
263
|
+
"materialization": args["materialization"],
|
|
264
|
+
"task_complete": False,
|
|
265
|
+
}
|
|
266
|
+
else:
|
|
267
|
+
self.db.execute(
|
|
268
|
+
"UPDATE handoffs SET state='cancelled' WHERE tenant=? AND id=?",
|
|
269
|
+
(who["tenant"], args["handle"]),
|
|
270
|
+
)
|
|
271
|
+
self._event(who, "handoff_cancelled", args["handle"], at)
|
|
272
|
+
result = {"handle": args["handle"], "status": "cancelled"}
|
|
273
|
+
if old is None:
|
|
274
|
+
self.db.execute(
|
|
275
|
+
"INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
276
|
+
(*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
|
|
277
|
+
)
|
|
278
|
+
if action not in {"materialize", "preview"}:
|
|
279
|
+
result.update(
|
|
280
|
+
receipt=receipt,
|
|
281
|
+
incarnation=self.s.incarnation,
|
|
282
|
+
evaluated_ms=at,
|
|
283
|
+
deadline_ms=decision.deadline_ms,
|
|
284
|
+
replayed=old is not None,
|
|
285
|
+
)
|
|
286
|
+
raw = canonical_bytes(result)
|
|
287
|
+
epoch = self.db.execute(
|
|
288
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
289
|
+
).fetchone()
|
|
290
|
+
self.db.execute(
|
|
291
|
+
"INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
292
|
+
(
|
|
293
|
+
who["tenant"],
|
|
294
|
+
receipt,
|
|
295
|
+
who["principal"],
|
|
296
|
+
self.s.incarnation,
|
|
297
|
+
at,
|
|
298
|
+
decision.deadline_ms,
|
|
299
|
+
*epoch,
|
|
300
|
+
hashlib.sha256(raw).hexdigest(),
|
|
301
|
+
json.dumps([d["id"] for d in deps if d["kind"] == "observation"]),
|
|
302
|
+
),
|
|
303
|
+
)
|
|
304
|
+
self.s.fault("after_validation")
|
|
305
|
+
self.s._expose()
|
|
306
|
+
return Released(raw, decision, self.s.clock, receipt)
|
|
307
|
+
|
|
308
|
+
def _event(self, who: dict[str, Any], kind: str, identifier: str, at: int) -> None:
|
|
309
|
+
position = self.s._event(who["tenant"], kind, identifier, at, who["principal"])
|
|
310
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
311
|
+
|
|
312
|
+
def _prepare(
|
|
313
|
+
self, who: dict[str, Any], args: dict[str, Any], stream: sqlite3.Row, at: int
|
|
314
|
+
) -> dict[str, Any]:
|
|
315
|
+
if (
|
|
316
|
+
self.db.execute(
|
|
317
|
+
"SELECT count(*) FROM handoffs WHERE tenant=?", (who["tenant"],)
|
|
318
|
+
).fetchone()[0]
|
|
319
|
+
>= 4096
|
|
320
|
+
):
|
|
321
|
+
raise LocalError("handoff_capacity")
|
|
322
|
+
identifier = uid("hnd")
|
|
323
|
+
scope = (
|
|
324
|
+
who["tenant"],
|
|
325
|
+
args["project"],
|
|
326
|
+
args["task"],
|
|
327
|
+
stream_name(args["run"]),
|
|
328
|
+
who["principal"],
|
|
329
|
+
args["recipient"],
|
|
330
|
+
)
|
|
331
|
+
self.db.execute(
|
|
332
|
+
"UPDATE handoffs SET state='superseded' WHERE tenant=? AND project=? AND task=? AND stream=? AND sender=? AND recipient=? AND state IN ('prepared','acknowledged')",
|
|
333
|
+
scope,
|
|
334
|
+
)
|
|
335
|
+
self.db.execute(
|
|
336
|
+
"INSERT INTO handoffs VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
337
|
+
(
|
|
338
|
+
who["tenant"],
|
|
339
|
+
identifier,
|
|
340
|
+
args["project"],
|
|
341
|
+
args["task"],
|
|
342
|
+
stream_name(args["run"]),
|
|
343
|
+
args["checkpoint"],
|
|
344
|
+
who["principal"],
|
|
345
|
+
args["recipient"],
|
|
346
|
+
args["role"],
|
|
347
|
+
args["stage"],
|
|
348
|
+
json.dumps(args["bindings"]),
|
|
349
|
+
self.s.incarnation,
|
|
350
|
+
at,
|
|
351
|
+
at + args["ttl_ms"],
|
|
352
|
+
"prepared",
|
|
353
|
+
stream["revision"],
|
|
354
|
+
None,
|
|
355
|
+
),
|
|
356
|
+
)
|
|
357
|
+
self._event(who, "handoff_prepared", identifier, at)
|
|
358
|
+
# A hand-off carries the sender's "where this left off" so the recipient reads
|
|
359
|
+
# three sentences before the full packet; the checkpoint remains the record.
|
|
360
|
+
from memoryking.adapters.working import Working
|
|
361
|
+
|
|
362
|
+
summary_receipt = uid("rcpt")
|
|
363
|
+
summary = Working(self.s)._summarize(
|
|
364
|
+
who,
|
|
365
|
+
{
|
|
366
|
+
"project": args["project"],
|
|
367
|
+
"task": args["task"],
|
|
368
|
+
"run": args["run"],
|
|
369
|
+
"checkpoint": args["checkpoint"],
|
|
370
|
+
"source": "extractive",
|
|
371
|
+
"text": None,
|
|
372
|
+
"permit": None,
|
|
373
|
+
"readers": None,
|
|
374
|
+
},
|
|
375
|
+
at,
|
|
376
|
+
summary_receipt,
|
|
377
|
+
)
|
|
378
|
+
return {
|
|
379
|
+
"handle": identifier,
|
|
380
|
+
"status": "prepared",
|
|
381
|
+
"expires_ms": at + args["ttl_ms"],
|
|
382
|
+
"summary": {
|
|
383
|
+
"receipt": summary_receipt,
|
|
384
|
+
"text": summary["summary"],
|
|
385
|
+
"method": summary["method"],
|
|
386
|
+
},
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
def _render(
|
|
390
|
+
self,
|
|
391
|
+
who: dict[str, Any],
|
|
392
|
+
row: sqlite3.Row,
|
|
393
|
+
mode: str,
|
|
394
|
+
args: dict[str, Any],
|
|
395
|
+
decision: Decision,
|
|
396
|
+
receipt: str,
|
|
397
|
+
) -> tuple[bytes, list[dict[str, str]]]:
|
|
398
|
+
at = decision.evaluated_ms
|
|
399
|
+
deps: list[dict[str, str]]
|
|
400
|
+
sender, recipient = self._active(row, at)
|
|
401
|
+
stamp, policy, view_deps = self._snapshot(row, recipient, at)
|
|
402
|
+
resume = {
|
|
403
|
+
**self._scope(row),
|
|
404
|
+
"max_output_tokens": args["max_output_tokens"],
|
|
405
|
+
"tokenizer": args["tokenizer"],
|
|
406
|
+
}
|
|
407
|
+
meta = {
|
|
408
|
+
"compiler_revision": "handoff-v1",
|
|
409
|
+
"handle": row["id"],
|
|
410
|
+
"sender": row["sender"],
|
|
411
|
+
"recipient": row["recipient"],
|
|
412
|
+
"role": row["role"],
|
|
413
|
+
"stage": row["stage"],
|
|
414
|
+
"mode": mode,
|
|
415
|
+
"materialization": receipt,
|
|
416
|
+
"expires_ms": row["expires"],
|
|
417
|
+
}
|
|
418
|
+
if mode == "preview" and not self._intersection(row, sender, policy, view_deps, at):
|
|
419
|
+
count, usage = counter(args["tokenizer"])
|
|
420
|
+
base = self.r._base(args, decision, receipt, usage)
|
|
421
|
+
base.update(
|
|
422
|
+
status="blocked",
|
|
423
|
+
reason="handoff_preview_incomplete",
|
|
424
|
+
checkpoint=None,
|
|
425
|
+
operations=[],
|
|
426
|
+
handoff=meta,
|
|
427
|
+
)
|
|
428
|
+
raw, used = counted(base, count)
|
|
429
|
+
if used > args["max_output_tokens"]:
|
|
430
|
+
base["usage"]["budget_compliant"] = False
|
|
431
|
+
raw, used = counted(base, count)
|
|
432
|
+
deps = []
|
|
433
|
+
else:
|
|
434
|
+
extras: dict[str, Any] = {"handoff": meta}
|
|
435
|
+
if mode == "preview":
|
|
436
|
+
extras["context_binding"] = {
|
|
437
|
+
"store": self.s.store_id,
|
|
438
|
+
"tenant": who["tenant"],
|
|
439
|
+
"principal": who["principal"],
|
|
440
|
+
"incarnation": self.s.incarnation,
|
|
441
|
+
"policy_epoch": self.db.execute(
|
|
442
|
+
"SELECT policy_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
443
|
+
).fetchone()[0],
|
|
444
|
+
}
|
|
445
|
+
raw, deps = self.w._resume(
|
|
446
|
+
recipient, resume, decision, receipt, extras=extras, retain=False
|
|
447
|
+
)
|
|
448
|
+
body = json.loads(raw)
|
|
449
|
+
if (
|
|
450
|
+
self.db.execute(
|
|
451
|
+
"SELECT count(*) FROM handoff_views WHERE tenant=?", (who["tenant"],)
|
|
452
|
+
).fetchone()[0]
|
|
453
|
+
>= 4096
|
|
454
|
+
):
|
|
455
|
+
raise LocalError("handoff_view_capacity")
|
|
456
|
+
self.db.execute(
|
|
457
|
+
"INSERT INTO handoff_views VALUES (?,?,?,?,?,?,?,?,?)",
|
|
458
|
+
(
|
|
459
|
+
who["tenant"],
|
|
460
|
+
receipt,
|
|
461
|
+
row["id"],
|
|
462
|
+
who["principal"],
|
|
463
|
+
mode,
|
|
464
|
+
stamp,
|
|
465
|
+
hashlib.sha256(raw).hexdigest(),
|
|
466
|
+
body["status"],
|
|
467
|
+
at,
|
|
468
|
+
),
|
|
469
|
+
)
|
|
470
|
+
deps.append({"kind": "handoff_view", "id": receipt})
|
|
471
|
+
diag = {
|
|
472
|
+
"kind": "handoff_" + mode,
|
|
473
|
+
"status": body["status"],
|
|
474
|
+
"usage": body["usage"],
|
|
475
|
+
"trace": [],
|
|
476
|
+
}
|
|
477
|
+
self.r._retain(who, args, receipt, raw, diag, deps, at)
|
|
478
|
+
self._event(who, "handoff_" + mode, row["id"], at)
|
|
479
|
+
return raw, deps
|
|
480
|
+
|
|
481
|
+
def _ack_check(
|
|
482
|
+
self, who: dict[str, Any], row: sqlite3.Row, args: dict[str, Any], at: int
|
|
483
|
+
) -> None:
|
|
484
|
+
view = self.db.execute(
|
|
485
|
+
"SELECT * FROM handoff_views WHERE tenant=? AND id=? AND handoff=? AND actor=? AND mode='materialize'",
|
|
486
|
+
(who["tenant"], args["materialization"], row["id"], who["principal"]),
|
|
487
|
+
).fetchone()
|
|
488
|
+
if (
|
|
489
|
+
view is None
|
|
490
|
+
or view["body_hash"] != args["rendered_hash"]
|
|
491
|
+
or view["status"] not in {"ready", "incomplete"}
|
|
492
|
+
):
|
|
493
|
+
raise LocalError("handoff_ack_invalid")
|
|
494
|
+
self.r._artifact(who, args["project"], view["id"], at)
|