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
memoryking/harness.py
ADDED
|
@@ -0,0 +1,882 @@
|
|
|
1
|
+
"""Durable host-driven reference task harness with a readback-capable local file tool.
|
|
2
|
+
|
|
3
|
+
No model output selects tools or grants authority. Every mutation is an explicit host
|
|
4
|
+
call; the only provider is the local recorder. The journal is private recovery state.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import hashlib
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Callable
|
|
18
|
+
|
|
19
|
+
from memoryking.adapters.local_files import Ownership, atomic, private_dir, private_file, sync_dir
|
|
20
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash, load_strict
|
|
21
|
+
from memoryking.contracts.validation import validate_working
|
|
22
|
+
from memoryking.domain.local import LocalError
|
|
23
|
+
from memoryking.harness_context import AuthorizedConversation, LocalRecordingProvider
|
|
24
|
+
from memoryking.providers import HttpAdapter
|
|
25
|
+
from memoryking.sdk import BINDING_FIELDS, LocalClient
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class LocalFileTool:
|
|
29
|
+
"""Create one bounded private file exclusively; readback never repeats the effect."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, root: Path):
|
|
32
|
+
private_dir(root, create=True)
|
|
33
|
+
self.root = root.resolve()
|
|
34
|
+
|
|
35
|
+
def target(self, name: str) -> Path:
|
|
36
|
+
private_dir(self.root)
|
|
37
|
+
if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", name) is None or name in {".", ".."}:
|
|
38
|
+
raise LocalError("tool_path_invalid")
|
|
39
|
+
return self.root / name
|
|
40
|
+
|
|
41
|
+
def payload(self, operation: str, content: str) -> bytes:
|
|
42
|
+
if len(content.encode()) > 16384:
|
|
43
|
+
raise LocalError("tool_input_limit")
|
|
44
|
+
return canonical_bytes({"operation": operation, "content": content})
|
|
45
|
+
|
|
46
|
+
def create(self, name: str, data: bytes) -> None:
|
|
47
|
+
target = self.target(name)
|
|
48
|
+
try:
|
|
49
|
+
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
50
|
+
except FileExistsError as exc:
|
|
51
|
+
raise LocalError("tool_target_exists") from exc
|
|
52
|
+
with os.fdopen(fd, "wb") as stream:
|
|
53
|
+
stream.write(data)
|
|
54
|
+
stream.flush()
|
|
55
|
+
os.fsync(stream.fileno())
|
|
56
|
+
sync_dir(self.root)
|
|
57
|
+
|
|
58
|
+
def inspect(self, name: str, expected_hash: str) -> dict[str, Any]:
|
|
59
|
+
path = self.target(name)
|
|
60
|
+
if not path.exists() and not path.is_symlink():
|
|
61
|
+
return {"state": "failed", "reason": "absent_at_readback", "path": name, "hash": None}
|
|
62
|
+
try:
|
|
63
|
+
private_file(path)
|
|
64
|
+
with path.open("rb") as stream:
|
|
65
|
+
raw = stream.read(32769)
|
|
66
|
+
hashed = hashlib.sha256(raw).hexdigest()
|
|
67
|
+
if len(raw) > 32768 or hashed != expected_hash:
|
|
68
|
+
raise LocalError("tool_readback_mismatch")
|
|
69
|
+
return {"state": "succeeded", "reason": "exact_readback", "path": name, "hash": hashed}
|
|
70
|
+
except (LocalError, OSError):
|
|
71
|
+
return {
|
|
72
|
+
"state": "unknown",
|
|
73
|
+
"reason": "readback_unavailable_or_mismatched",
|
|
74
|
+
"path": name,
|
|
75
|
+
"hash": None,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ReferenceHarness:
|
|
80
|
+
"""All accepted changes are journaled; each boundary persists a full checkpoint.
|
|
81
|
+
|
|
82
|
+
Staged state is flushed within flush_seconds (at most 60) while the harness runs.
|
|
83
|
+
Capture failure prevents later mutations. Resumption never redispatches a tool.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
client: LocalClient,
|
|
89
|
+
directory: Path,
|
|
90
|
+
tool: LocalFileTool,
|
|
91
|
+
*,
|
|
92
|
+
task: str,
|
|
93
|
+
run: str | None = None,
|
|
94
|
+
state: dict[str, Any] | None = None,
|
|
95
|
+
readers: list[str] | None = None,
|
|
96
|
+
bindings: list[dict[str, Any]] | None = None,
|
|
97
|
+
flush_seconds: float = 30,
|
|
98
|
+
fault: Callable[[str], None] | None = None,
|
|
99
|
+
):
|
|
100
|
+
if type(tool) is not LocalFileTool or not 0.05 <= flush_seconds <= 60:
|
|
101
|
+
raise LocalError("harness_configuration_invalid")
|
|
102
|
+
private_dir(directory, create=True)
|
|
103
|
+
self.client, self.directory, self.tool = client, directory, tool
|
|
104
|
+
self.path = directory / "task.json"
|
|
105
|
+
self.lock = threading.RLock()
|
|
106
|
+
self.owner = Ownership(directory)
|
|
107
|
+
self.stop = threading.Event()
|
|
108
|
+
self.fault = fault or (lambda name: None)
|
|
109
|
+
self.closed = False
|
|
110
|
+
self.error: str | None = None
|
|
111
|
+
self.flush_seconds = flush_seconds
|
|
112
|
+
try:
|
|
113
|
+
context = client.context()
|
|
114
|
+
binding = {key: context[key] for key in BINDING_FIELDS}
|
|
115
|
+
if self.path.exists():
|
|
116
|
+
if state is not None:
|
|
117
|
+
raise LocalError("harness_already_exists")
|
|
118
|
+
private_file(self.path)
|
|
119
|
+
with self.path.open("rb") as stream:
|
|
120
|
+
raw = stream.read(262145)
|
|
121
|
+
if len(raw) > 262144:
|
|
122
|
+
raise LocalError("harness_journal_limit")
|
|
123
|
+
document = load_strict(raw)
|
|
124
|
+
if (
|
|
125
|
+
not isinstance(document, dict)
|
|
126
|
+
or set(document) != {"format", "sha256", "payload"}
|
|
127
|
+
or document["format"] != "reference-harness-v1"
|
|
128
|
+
or canonical_hash(document["payload"]) != document["sha256"]
|
|
129
|
+
):
|
|
130
|
+
raise LocalError("harness_journal_integrity")
|
|
131
|
+
self.data = document["payload"]
|
|
132
|
+
required = {
|
|
133
|
+
"version",
|
|
134
|
+
"binding",
|
|
135
|
+
"task",
|
|
136
|
+
"run",
|
|
137
|
+
"readers",
|
|
138
|
+
"bindings",
|
|
139
|
+
"tool_root",
|
|
140
|
+
"state",
|
|
141
|
+
"revision",
|
|
142
|
+
"checkpoint",
|
|
143
|
+
"sequence",
|
|
144
|
+
"pending",
|
|
145
|
+
"operation",
|
|
146
|
+
"staged",
|
|
147
|
+
"activity",
|
|
148
|
+
"handoff_checkpoint",
|
|
149
|
+
}
|
|
150
|
+
if (
|
|
151
|
+
not isinstance(self.data, dict)
|
|
152
|
+
or set(self.data) != required
|
|
153
|
+
or self.data["version"] != 1
|
|
154
|
+
):
|
|
155
|
+
raise LocalError("harness_journal_invalid")
|
|
156
|
+
if self.data["binding"] != binding or (
|
|
157
|
+
self.data["task"],
|
|
158
|
+
self.data["run"],
|
|
159
|
+
self.data["tool_root"],
|
|
160
|
+
) != (task, run, str(tool.root)):
|
|
161
|
+
raise LocalError("harness_binding_changed")
|
|
162
|
+
self._validate(self.data["state"])
|
|
163
|
+
self._flush_pending()
|
|
164
|
+
if self.data["checkpoint"] is None:
|
|
165
|
+
self._record("task_started_recovered", {})
|
|
166
|
+
self._guard(ready=False)
|
|
167
|
+
self._recover_operation()
|
|
168
|
+
if (
|
|
169
|
+
self.data["activity"] is not None
|
|
170
|
+
and self.data["activity"]["outcome"] == "pending"
|
|
171
|
+
):
|
|
172
|
+
state = self.state()
|
|
173
|
+
state["findings"].append(
|
|
174
|
+
{
|
|
175
|
+
"kind": "hypothesis",
|
|
176
|
+
"text": "Interrupted model turn: its unobserved result was not restored or reused.",
|
|
177
|
+
"evidence": [],
|
|
178
|
+
}
|
|
179
|
+
)
|
|
180
|
+
self._record(
|
|
181
|
+
"model_interrupted",
|
|
182
|
+
{"activity": self.data["activity"], "result": "unobserved"},
|
|
183
|
+
state,
|
|
184
|
+
)
|
|
185
|
+
self.data["activity"] = None
|
|
186
|
+
self._persist()
|
|
187
|
+
if self.data["staged"] is not None:
|
|
188
|
+
self._record("recovered_staged_state", {})
|
|
189
|
+
else:
|
|
190
|
+
if state is None:
|
|
191
|
+
raise LocalError("harness_state_required")
|
|
192
|
+
self.data = {
|
|
193
|
+
"version": 1,
|
|
194
|
+
"binding": binding,
|
|
195
|
+
"task": task,
|
|
196
|
+
"run": run,
|
|
197
|
+
"readers": readers if readers is not None else [binding["principal"]],
|
|
198
|
+
"bindings": bindings if bindings is not None else [{}],
|
|
199
|
+
"tool_root": str(tool.root),
|
|
200
|
+
"state": copy.deepcopy(state),
|
|
201
|
+
"revision": 0,
|
|
202
|
+
"checkpoint": None,
|
|
203
|
+
"sequence": 0,
|
|
204
|
+
"pending": None,
|
|
205
|
+
"operation": None,
|
|
206
|
+
"staged": None,
|
|
207
|
+
"activity": None,
|
|
208
|
+
"handoff_checkpoint": None,
|
|
209
|
+
}
|
|
210
|
+
self._validate(state)
|
|
211
|
+
self._persist()
|
|
212
|
+
self._record("task_started", {})
|
|
213
|
+
except BaseException:
|
|
214
|
+
self.owner.close()
|
|
215
|
+
self.closed = True
|
|
216
|
+
raise
|
|
217
|
+
self.worker = threading.Thread(
|
|
218
|
+
target=self._periodic, name="memoryking-capture", daemon=True
|
|
219
|
+
)
|
|
220
|
+
self.worker.start()
|
|
221
|
+
|
|
222
|
+
def _scope(self) -> dict[str, Any]:
|
|
223
|
+
return {"project": self.client.project, "task": self.data["task"], "run": self.data["run"]}
|
|
224
|
+
|
|
225
|
+
def _command(self, action: str, args: dict[str, Any], key: str | None = None) -> dict[str, Any]:
|
|
226
|
+
return {
|
|
227
|
+
"version": 1,
|
|
228
|
+
"incarnation": self.data["binding"]["incarnation"],
|
|
229
|
+
"action": action,
|
|
230
|
+
"args": args,
|
|
231
|
+
**({"key": key} if key is not None else {}),
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
def _validate(self, state: dict[str, Any]) -> None:
|
|
235
|
+
validate_working(
|
|
236
|
+
self._command(
|
|
237
|
+
"save",
|
|
238
|
+
{
|
|
239
|
+
**self._scope(),
|
|
240
|
+
"expected_revision": self.data["revision"],
|
|
241
|
+
"readers": self.data["readers"],
|
|
242
|
+
"checkpoint": state,
|
|
243
|
+
},
|
|
244
|
+
"journal-validation",
|
|
245
|
+
)
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def _persist(self) -> None:
|
|
249
|
+
raw = canonical_bytes(
|
|
250
|
+
{
|
|
251
|
+
"format": "reference-harness-v1",
|
|
252
|
+
"sha256": canonical_hash(self.data),
|
|
253
|
+
"payload": self.data,
|
|
254
|
+
}
|
|
255
|
+
)
|
|
256
|
+
if len(raw) > 262144:
|
|
257
|
+
raise LocalError("harness_journal_limit")
|
|
258
|
+
atomic(self.path, raw)
|
|
259
|
+
|
|
260
|
+
def _available(self) -> None:
|
|
261
|
+
if self.closed:
|
|
262
|
+
raise LocalError("harness_closed")
|
|
263
|
+
self.owner.check()
|
|
264
|
+
if self.error:
|
|
265
|
+
raise LocalError("harness_capture_degraded")
|
|
266
|
+
|
|
267
|
+
def _periodic(self) -> None:
|
|
268
|
+
while not self.stop.wait(self.flush_seconds):
|
|
269
|
+
with self.lock:
|
|
270
|
+
if not self.error:
|
|
271
|
+
try:
|
|
272
|
+
if self.data["staged"] is not None:
|
|
273
|
+
self._record("periodic_state", {})
|
|
274
|
+
self.heartbeat()
|
|
275
|
+
except Exception as exc:
|
|
276
|
+
self.error = exc.code if isinstance(exc, LocalError) else "capture_failed"
|
|
277
|
+
|
|
278
|
+
def heartbeat(self) -> dict[str, Any]:
|
|
279
|
+
"""An observed signal, not a checkpoint, progress increment or claim of completion."""
|
|
280
|
+
with self.lock:
|
|
281
|
+
self._available()
|
|
282
|
+
event = "heartbeat_" + uuid.uuid4().hex
|
|
283
|
+
observed = time.time_ns() // 1_000_000
|
|
284
|
+
payload = {
|
|
285
|
+
"version": 1,
|
|
286
|
+
"id": event,
|
|
287
|
+
**self._scope(),
|
|
288
|
+
"checkpoint": self.data["checkpoint"],
|
|
289
|
+
"revision": self.data["revision"],
|
|
290
|
+
"activity": "model"
|
|
291
|
+
if self.data["activity"]
|
|
292
|
+
else "tool"
|
|
293
|
+
if self.data["operation"]
|
|
294
|
+
else "idle",
|
|
295
|
+
"observed_ms": observed,
|
|
296
|
+
}
|
|
297
|
+
return self.client.capture(
|
|
298
|
+
event,
|
|
299
|
+
{
|
|
300
|
+
"version": 1,
|
|
301
|
+
"project": self.client.project,
|
|
302
|
+
"source": "reference-heartbeat-v1",
|
|
303
|
+
"source_event": event,
|
|
304
|
+
"text": canonical_bytes(payload).decode(),
|
|
305
|
+
"classification": "restricted",
|
|
306
|
+
"readers": self.data["readers"],
|
|
307
|
+
"observed_at_ms": observed,
|
|
308
|
+
},
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
def _flush_pending(self) -> dict[str, Any] | None:
|
|
312
|
+
pending = self.data["pending"]
|
|
313
|
+
if pending is None:
|
|
314
|
+
return None
|
|
315
|
+
try:
|
|
316
|
+
captured = self.client.capture(pending["id"], pending["observation"])
|
|
317
|
+
body = copy.deepcopy(pending["state"])
|
|
318
|
+
reference = {"kind": "observation", "id": captured["observation"]}
|
|
319
|
+
body["references"].append(reference)
|
|
320
|
+
body["capture"].update(
|
|
321
|
+
last_event=pending["id"], observed_ms=pending["observation"]["observed_at_ms"]
|
|
322
|
+
)
|
|
323
|
+
result = self.client.working(
|
|
324
|
+
self._command(
|
|
325
|
+
"save",
|
|
326
|
+
{
|
|
327
|
+
**self._scope(),
|
|
328
|
+
"expected_revision": pending["expected_revision"],
|
|
329
|
+
"readers": self.data["readers"],
|
|
330
|
+
"checkpoint": body,
|
|
331
|
+
},
|
|
332
|
+
pending["id"],
|
|
333
|
+
)
|
|
334
|
+
)
|
|
335
|
+
self.fault("after_checkpoint_ack")
|
|
336
|
+
self.data.update(
|
|
337
|
+
state=body,
|
|
338
|
+
revision=result["revision"],
|
|
339
|
+
checkpoint=result["checkpoint"],
|
|
340
|
+
pending=None,
|
|
341
|
+
staged=None,
|
|
342
|
+
)
|
|
343
|
+
self._persist()
|
|
344
|
+
self.error = None
|
|
345
|
+
return reference
|
|
346
|
+
except Exception as exc:
|
|
347
|
+
self.error = exc.code if isinstance(exc, LocalError) else "capture_failed"
|
|
348
|
+
raise
|
|
349
|
+
|
|
350
|
+
def _record(
|
|
351
|
+
self, kind: str, details: dict[str, Any], state: dict[str, Any] | None = None
|
|
352
|
+
) -> dict[str, Any]:
|
|
353
|
+
self._flush_pending()
|
|
354
|
+
body = copy.deepcopy(
|
|
355
|
+
state if state is not None else (self.data["staged"] or self.data["state"])
|
|
356
|
+
)
|
|
357
|
+
self._validate(body)
|
|
358
|
+
if len(body["references"]) >= 120:
|
|
359
|
+
raise LocalError("harness_evidence_capacity")
|
|
360
|
+
event = "event_" + uuid.uuid4().hex
|
|
361
|
+
observed = time.time_ns() // 1_000_000
|
|
362
|
+
self.data["sequence"] += 1
|
|
363
|
+
payload = {
|
|
364
|
+
"version": 1,
|
|
365
|
+
"kind": kind,
|
|
366
|
+
"id": event,
|
|
367
|
+
"sequence": self.data["sequence"],
|
|
368
|
+
**self._scope(),
|
|
369
|
+
"observed_ms": observed,
|
|
370
|
+
"previous_checkpoint": self.data["checkpoint"],
|
|
371
|
+
"previous_revision": self.data["revision"],
|
|
372
|
+
"details": details,
|
|
373
|
+
}
|
|
374
|
+
observation = {
|
|
375
|
+
"version": 1,
|
|
376
|
+
"project": self.client.project,
|
|
377
|
+
"source": "reference-harness-v1",
|
|
378
|
+
"source_event": event,
|
|
379
|
+
"text": canonical_bytes(payload).decode(),
|
|
380
|
+
"classification": "restricted",
|
|
381
|
+
"readers": self.data["readers"],
|
|
382
|
+
"observed_at_ms": observed,
|
|
383
|
+
}
|
|
384
|
+
self.data["pending"] = {
|
|
385
|
+
"id": event,
|
|
386
|
+
"observation": observation,
|
|
387
|
+
"state": body,
|
|
388
|
+
"expected_revision": self.data["revision"],
|
|
389
|
+
}
|
|
390
|
+
self._persist()
|
|
391
|
+
self.fault("after_event_journal")
|
|
392
|
+
result = self._flush_pending()
|
|
393
|
+
assert result is not None
|
|
394
|
+
return result
|
|
395
|
+
|
|
396
|
+
def _guard(self, *, ready: bool = True) -> dict[str, Any]:
|
|
397
|
+
self._available()
|
|
398
|
+
self._flush_pending()
|
|
399
|
+
if self.data["staged"] is not None:
|
|
400
|
+
self._record("before_action_state", {})
|
|
401
|
+
packet = self.client.working(
|
|
402
|
+
self._command(
|
|
403
|
+
"resume",
|
|
404
|
+
{
|
|
405
|
+
**self._scope(),
|
|
406
|
+
"checkpoint": None,
|
|
407
|
+
"bindings": self.data["bindings"],
|
|
408
|
+
"max_output_tokens": 16000,
|
|
409
|
+
"tokenizer": "cl100k_base",
|
|
410
|
+
},
|
|
411
|
+
)
|
|
412
|
+
)
|
|
413
|
+
if packet.get("checkpoint") is None:
|
|
414
|
+
raise LocalError("essential_context_unavailable")
|
|
415
|
+
if (
|
|
416
|
+
packet["checkpoint"]["id"] != self.data["checkpoint"]
|
|
417
|
+
or packet["checkpoint"]["revision"] != self.data["revision"]
|
|
418
|
+
):
|
|
419
|
+
raise LocalError("harness_checkpoint_changed")
|
|
420
|
+
if canonical_hash(self.data["state"]) != packet["checkpoint"]["body_hash"]:
|
|
421
|
+
raise LocalError("harness_journal_diverged")
|
|
422
|
+
repository = self.data["state"]["repository"]
|
|
423
|
+
if ready and repository.get("snapshot_id"):
|
|
424
|
+
if not repository.get("clone"):
|
|
425
|
+
raise LocalError("repository_capture_configuration_missing")
|
|
426
|
+
current = self.client.repository(
|
|
427
|
+
{
|
|
428
|
+
"version": 1,
|
|
429
|
+
"incarnation": self.client.binding[-1],
|
|
430
|
+
"action": "capture",
|
|
431
|
+
"key": "preaction_" + uuid.uuid4().hex,
|
|
432
|
+
"args": {
|
|
433
|
+
"project": self.client.project,
|
|
434
|
+
"repository": repository["repository"],
|
|
435
|
+
"clone": repository["clone"],
|
|
436
|
+
"environment": repository["environment"],
|
|
437
|
+
},
|
|
438
|
+
}
|
|
439
|
+
)
|
|
440
|
+
if current["snapshot"] != repository["snapshot_id"]:
|
|
441
|
+
raise LocalError("repository_snapshot_changed")
|
|
442
|
+
if ready and packet["status"] != "ready":
|
|
443
|
+
raise LocalError("harness_recovery_incomplete")
|
|
444
|
+
return packet
|
|
445
|
+
|
|
446
|
+
def state(self) -> dict[str, Any]:
|
|
447
|
+
with self.lock:
|
|
448
|
+
return copy.deepcopy(self.data["staged"] or self.data["state"])
|
|
449
|
+
|
|
450
|
+
def status(self) -> dict[str, Any]:
|
|
451
|
+
with self.lock:
|
|
452
|
+
return {
|
|
453
|
+
"checkpoint": self.data["checkpoint"],
|
|
454
|
+
"revision": self.data["revision"],
|
|
455
|
+
"capture": "degraded" if self.error or self.data["pending"] else "current",
|
|
456
|
+
"reason": self.error,
|
|
457
|
+
"staged": self.data["staged"] is not None,
|
|
458
|
+
"pending_operation": None
|
|
459
|
+
if self.data["operation"] is None
|
|
460
|
+
else self.data["operation"]["id"],
|
|
461
|
+
"activity": copy.deepcopy(self.data["activity"]),
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
def accept_constraint(self, text: str, *, approved: bool) -> None:
|
|
465
|
+
with self.lock:
|
|
466
|
+
self._guard(ready=False)
|
|
467
|
+
if approved is not True:
|
|
468
|
+
raise LocalError("host_authorization_required")
|
|
469
|
+
state = self.state()
|
|
470
|
+
if text not in state["hard_constraints"]:
|
|
471
|
+
state["hard_constraints"].append(text)
|
|
472
|
+
self._record("accepted_constraint", {"text": text}, state)
|
|
473
|
+
|
|
474
|
+
def update_state(self, state: dict[str, Any], *, defer: bool = False) -> None:
|
|
475
|
+
with self.lock:
|
|
476
|
+
self._guard(ready=False)
|
|
477
|
+
self._validate(state)
|
|
478
|
+
# A host update must not erase the captured source lineage.
|
|
479
|
+
if not set(map(canonical_hash, self.data["state"]["references"])) <= set(
|
|
480
|
+
map(canonical_hash, state["references"])
|
|
481
|
+
):
|
|
482
|
+
raise LocalError("harness_provenance_removed")
|
|
483
|
+
self.data["staged"] = copy.deepcopy(state)
|
|
484
|
+
self._persist()
|
|
485
|
+
if not defer:
|
|
486
|
+
self._record("structured_state_changed", {})
|
|
487
|
+
|
|
488
|
+
def refresh_repository(
|
|
489
|
+
self, repository: str, clone: str, environment: str, paths: list[str], *, approved: bool
|
|
490
|
+
) -> dict[str, Any]:
|
|
491
|
+
"""Capture registered source data and checkpoint the exact declared change scope."""
|
|
492
|
+
with self.lock:
|
|
493
|
+
if approved is not True:
|
|
494
|
+
raise LocalError("host_authorization_required")
|
|
495
|
+
self._available()
|
|
496
|
+
self._flush_pending()
|
|
497
|
+
# Checkpointing new bindings remains possible while old essential
|
|
498
|
+
# guidance is blocked. No model or external tool executes here.
|
|
499
|
+
result = self.client.repository(
|
|
500
|
+
{
|
|
501
|
+
"version": 1,
|
|
502
|
+
"incarnation": self.client.binding[-1],
|
|
503
|
+
"action": "capture",
|
|
504
|
+
"key": "snapshot_" + uuid.uuid4().hex,
|
|
505
|
+
"args": {
|
|
506
|
+
"project": self.client.project,
|
|
507
|
+
"repository": repository,
|
|
508
|
+
"clone": clone,
|
|
509
|
+
"environment": environment,
|
|
510
|
+
},
|
|
511
|
+
}
|
|
512
|
+
)
|
|
513
|
+
points = [
|
|
514
|
+
{
|
|
515
|
+
"repository_id": repository,
|
|
516
|
+
"snapshot_id": result["snapshot"],
|
|
517
|
+
"commit": result["commit"],
|
|
518
|
+
"environment": environment,
|
|
519
|
+
"path": path,
|
|
520
|
+
}
|
|
521
|
+
for path in paths
|
|
522
|
+
]
|
|
523
|
+
coverage = self.client.repository(
|
|
524
|
+
{
|
|
525
|
+
"version": 1,
|
|
526
|
+
"incarnation": self.client.binding[-1],
|
|
527
|
+
"action": "coverage",
|
|
528
|
+
"args": {
|
|
529
|
+
"project": self.client.project,
|
|
530
|
+
"repository": repository,
|
|
531
|
+
"snapshot": result["snapshot"],
|
|
532
|
+
"paths": paths,
|
|
533
|
+
"bindings": points,
|
|
534
|
+
},
|
|
535
|
+
}
|
|
536
|
+
)
|
|
537
|
+
if coverage["status"] != "complete":
|
|
538
|
+
raise LocalError("binding_coverage_incomplete")
|
|
539
|
+
state = self.state()
|
|
540
|
+
state["repository"].update(
|
|
541
|
+
repository=repository,
|
|
542
|
+
clone=clone,
|
|
543
|
+
current_commit=result["commit"],
|
|
544
|
+
snapshot_id=result["snapshot"],
|
|
545
|
+
environment=environment,
|
|
546
|
+
change_scope=paths,
|
|
547
|
+
dirty=result["dirty"],
|
|
548
|
+
)
|
|
549
|
+
if state["repository"]["base_commit"] is None:
|
|
550
|
+
state["repository"]["base_commit"] = result["commit"]
|
|
551
|
+
dirty = result["dirty_files"]
|
|
552
|
+
old = {artifact["path"]: artifact for artifact in state["repository"]["artifacts"]}
|
|
553
|
+
artifacts = []
|
|
554
|
+
deleted = []
|
|
555
|
+
for item in dirty:
|
|
556
|
+
if item["coverage"] == "missing":
|
|
557
|
+
deleted.append(item["path"])
|
|
558
|
+
continue
|
|
559
|
+
previous = old.get(item["path"])
|
|
560
|
+
if (
|
|
561
|
+
previous
|
|
562
|
+
and previous["content_hash"] == item["hash"]
|
|
563
|
+
and previous["availability"] == "stored"
|
|
564
|
+
):
|
|
565
|
+
artifacts.append(previous)
|
|
566
|
+
else:
|
|
567
|
+
artifacts.append(
|
|
568
|
+
{
|
|
569
|
+
"path": item["path"],
|
|
570
|
+
"availability": "missing",
|
|
571
|
+
"observation": None,
|
|
572
|
+
"content_hash": None,
|
|
573
|
+
"required": True,
|
|
574
|
+
}
|
|
575
|
+
)
|
|
576
|
+
state["repository"].update(artifacts=artifacts, deleted_paths=deleted)
|
|
577
|
+
self._validate(state)
|
|
578
|
+
self.data["bindings"] = points
|
|
579
|
+
self.data["staged"] = state
|
|
580
|
+
self._persist()
|
|
581
|
+
self._record(
|
|
582
|
+
"repository_snapshot",
|
|
583
|
+
{
|
|
584
|
+
"snapshot": result["snapshot"],
|
|
585
|
+
"generation": result["generation"],
|
|
586
|
+
"change_scope": paths,
|
|
587
|
+
},
|
|
588
|
+
state,
|
|
589
|
+
)
|
|
590
|
+
return result
|
|
591
|
+
|
|
592
|
+
def resume(self) -> dict[str, Any]:
|
|
593
|
+
with self.lock:
|
|
594
|
+
return self._guard(ready=False)
|
|
595
|
+
|
|
596
|
+
def checkpoint(self, reason: str) -> dict[str, Any]:
|
|
597
|
+
with self.lock:
|
|
598
|
+
self._guard(ready=False)
|
|
599
|
+
return self._record("checkpoint", {"reason": reason})
|
|
600
|
+
|
|
601
|
+
def reset_context(self) -> dict[str, Any]:
|
|
602
|
+
with self.lock:
|
|
603
|
+
self.checkpoint("before_context_reset")
|
|
604
|
+
# Each model turn starts from a new full resume; no provider state is restored.
|
|
605
|
+
return self._guard(ready=False)
|
|
606
|
+
|
|
607
|
+
def _operations(self) -> list[dict[str, Any]]:
|
|
608
|
+
return self.client.working(self._command("operations", self._scope()))["operations"] # type: ignore[no-any-return]
|
|
609
|
+
|
|
610
|
+
def _transition(
|
|
611
|
+
self,
|
|
612
|
+
row: dict[str, Any],
|
|
613
|
+
state: str,
|
|
614
|
+
*,
|
|
615
|
+
reconciled: bool = False,
|
|
616
|
+
evidence: list[dict[str, Any]] | None = None,
|
|
617
|
+
result_hash: str | None = None,
|
|
618
|
+
) -> dict[str, Any]:
|
|
619
|
+
return self.client.working(
|
|
620
|
+
self._command(
|
|
621
|
+
"operation_transition",
|
|
622
|
+
{
|
|
623
|
+
"project": self.client.project,
|
|
624
|
+
"operation": row["id"],
|
|
625
|
+
"expected_revision": row["revision"],
|
|
626
|
+
"state": state,
|
|
627
|
+
"reconciled": reconciled,
|
|
628
|
+
"evidence": evidence or [],
|
|
629
|
+
"result_hash": result_hash,
|
|
630
|
+
},
|
|
631
|
+
row["id"] + "_" + state + "_" + str(row["revision"]),
|
|
632
|
+
)
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
def create_file(
|
|
636
|
+
self, operation: str, name: str, content: str, *, approved: bool
|
|
637
|
+
) -> dict[str, Any]:
|
|
638
|
+
with self.lock:
|
|
639
|
+
self._guard()
|
|
640
|
+
if approved is not True:
|
|
641
|
+
raise LocalError("host_authorization_required")
|
|
642
|
+
repository = self.data["state"]["repository"]
|
|
643
|
+
if repository.get("snapshot_id") and name not in repository.get("change_scope", []):
|
|
644
|
+
raise LocalError("tool_outside_declared_scope")
|
|
645
|
+
if self.data["operation"] is not None:
|
|
646
|
+
raise LocalError("operation_reconciliation_required")
|
|
647
|
+
if re.fullmatch(r"[A-Za-z0-9_-]{1,64}", operation) is None:
|
|
648
|
+
raise LocalError("invalid_operation_id")
|
|
649
|
+
if any(item["id"] == operation for item in self._operations()):
|
|
650
|
+
raise LocalError("operation_already_recorded")
|
|
651
|
+
raw = self.tool.payload(operation, content)
|
|
652
|
+
target = self.tool.target(name)
|
|
653
|
+
self.data["operation"] = {
|
|
654
|
+
"id": operation,
|
|
655
|
+
"path": name,
|
|
656
|
+
"expected_hash": hashlib.sha256(raw).hexdigest(),
|
|
657
|
+
}
|
|
658
|
+
self._persist()
|
|
659
|
+
intent = self.client.working(
|
|
660
|
+
self._command(
|
|
661
|
+
"operation_intent",
|
|
662
|
+
{
|
|
663
|
+
**self._scope(),
|
|
664
|
+
"operation": operation,
|
|
665
|
+
"target_hash": hashlib.sha256(str(target).encode()).hexdigest(),
|
|
666
|
+
"parameters_hash": hashlib.sha256(raw).hexdigest(),
|
|
667
|
+
"method": "readback",
|
|
668
|
+
"provider_key": None,
|
|
669
|
+
},
|
|
670
|
+
operation + "_intent",
|
|
671
|
+
)
|
|
672
|
+
)
|
|
673
|
+
state = self.state()
|
|
674
|
+
state["operation_ids"].append(operation)
|
|
675
|
+
self._record(
|
|
676
|
+
"tool_started",
|
|
677
|
+
{
|
|
678
|
+
"operation": operation,
|
|
679
|
+
"tool": "local-file-create-v1",
|
|
680
|
+
"path": name,
|
|
681
|
+
"parameters_hash": hashlib.sha256(raw).hexdigest(),
|
|
682
|
+
},
|
|
683
|
+
state,
|
|
684
|
+
)
|
|
685
|
+
started = time.monotonic_ns()
|
|
686
|
+
self._transition({"id": operation, "revision": intent["revision"]}, "dispatching")
|
|
687
|
+
self.fault("before_external_effect")
|
|
688
|
+
elapsed = time.monotonic_ns() - started
|
|
689
|
+
if elapsed < 0 or elapsed >= 5_000_000_000:
|
|
690
|
+
raise LocalError("release_expired")
|
|
691
|
+
try:
|
|
692
|
+
self.tool.create(name, raw)
|
|
693
|
+
except Exception as exc:
|
|
694
|
+
code = exc.code if isinstance(exc, LocalError) else "tool_outcome_unknown"
|
|
695
|
+
evidence = self._record(
|
|
696
|
+
"tool_returned_error", {"operation": operation, "code": code}
|
|
697
|
+
)
|
|
698
|
+
row = next(item for item in self._operations() if item["id"] == operation)
|
|
699
|
+
if code == "tool_target_exists":
|
|
700
|
+
self._transition(
|
|
701
|
+
row,
|
|
702
|
+
"failed",
|
|
703
|
+
evidence=[evidence],
|
|
704
|
+
result_hash=canonical_hash({"code": code}),
|
|
705
|
+
)
|
|
706
|
+
self._recover_operation()
|
|
707
|
+
else:
|
|
708
|
+
self._transition(row, "unknown")
|
|
709
|
+
raise LocalError(code) from exc
|
|
710
|
+
self.fault("after_external_effect")
|
|
711
|
+
return self._recover_operation()
|
|
712
|
+
|
|
713
|
+
def _recover_operation(self) -> dict[str, Any]:
|
|
714
|
+
pending = self.data["operation"]
|
|
715
|
+
if pending is None:
|
|
716
|
+
return {"state": "none"}
|
|
717
|
+
rows = [item for item in self._operations() if item["id"] == pending["id"]]
|
|
718
|
+
if not rows or rows[0]["state"] == "intent_recorded":
|
|
719
|
+
self.data["operation"] = None
|
|
720
|
+
self._persist()
|
|
721
|
+
self._record("tool_not_dispatched", {"operation": pending["id"]})
|
|
722
|
+
return {"state": "not_dispatched"}
|
|
723
|
+
row = rows[0]
|
|
724
|
+
if row["state"] in {"succeeded", "failed"} and not row["reconciliation_required"]:
|
|
725
|
+
result = {"state": row["state"], "reason": "durable_result_already_recorded"}
|
|
726
|
+
else:
|
|
727
|
+
if row["state"] == "dispatching":
|
|
728
|
+
transition = self._transition(row, "unknown")
|
|
729
|
+
row = {**row, "state": "unknown", "revision": transition["revision"]}
|
|
730
|
+
result = self.tool.inspect(pending["path"], pending["expected_hash"])
|
|
731
|
+
if result["state"] == "unknown":
|
|
732
|
+
return result
|
|
733
|
+
evidence = self._record("tool_readback", {"operation": pending["id"], "result": result})
|
|
734
|
+
self._transition(
|
|
735
|
+
row,
|
|
736
|
+
result["state"],
|
|
737
|
+
reconciled=True,
|
|
738
|
+
evidence=[evidence],
|
|
739
|
+
result_hash=canonical_hash(result),
|
|
740
|
+
)
|
|
741
|
+
self._record("tool_completed", {"operation": pending["id"], "result": result})
|
|
742
|
+
self.data["operation"] = None
|
|
743
|
+
self._persist()
|
|
744
|
+
return result
|
|
745
|
+
|
|
746
|
+
def reconcile(self) -> dict[str, Any]:
|
|
747
|
+
with self.lock:
|
|
748
|
+
# An explicit retry of capture/readback is safe; it never invokes create.
|
|
749
|
+
self.error = None
|
|
750
|
+
self._flush_pending()
|
|
751
|
+
self._guard(ready=False)
|
|
752
|
+
return self._recover_operation()
|
|
753
|
+
|
|
754
|
+
def model_turn(self, provider: LocalRecordingProvider | HttpAdapter) -> dict[str, str]:
|
|
755
|
+
with self.lock:
|
|
756
|
+
self._guard()
|
|
757
|
+
self.data["activity"] = {
|
|
758
|
+
"kind": "model",
|
|
759
|
+
"id": "model_" + uuid.uuid4().hex,
|
|
760
|
+
"outcome": "pending",
|
|
761
|
+
}
|
|
762
|
+
self._persist()
|
|
763
|
+
name, model = "local-recording", "echo-v1"
|
|
764
|
+
if isinstance(provider, HttpAdapter):
|
|
765
|
+
name, model = provider.name, provider.model
|
|
766
|
+
self._record("model_started", {"provider": name, "model": model})
|
|
767
|
+
try:
|
|
768
|
+
context = AuthorizedConversation(self.client, provider)
|
|
769
|
+
context.add_memory(self._guard())
|
|
770
|
+
result = context.dispatch()
|
|
771
|
+
except Exception as exc:
|
|
772
|
+
self.data["activity"]["outcome"] = "failed"
|
|
773
|
+
self._record(
|
|
774
|
+
"model_failed",
|
|
775
|
+
{"code": exc.code if isinstance(exc, LocalError) else "provider_failure"},
|
|
776
|
+
)
|
|
777
|
+
self.data["activity"] = None
|
|
778
|
+
self._persist()
|
|
779
|
+
raise
|
|
780
|
+
self.data["activity"]["outcome"] = "completed"
|
|
781
|
+
# Persist observable result identity, not a free-standing copy of derived
|
|
782
|
+
# restricted text that could outlive the original source permissions.
|
|
783
|
+
self._record(
|
|
784
|
+
"model_completed",
|
|
785
|
+
{
|
|
786
|
+
"request_hash": result["request_hash"],
|
|
787
|
+
"response_hash": hashlib.sha256(result["content"].encode()).hexdigest(),
|
|
788
|
+
"permit_receipt": result["permit_receipt"],
|
|
789
|
+
"provider": name,
|
|
790
|
+
"model": model,
|
|
791
|
+
},
|
|
792
|
+
)
|
|
793
|
+
self.data["activity"] = None
|
|
794
|
+
self._persist()
|
|
795
|
+
return result
|
|
796
|
+
|
|
797
|
+
def store_artifact(self, name: str, *, approved: bool) -> dict[str, Any]:
|
|
798
|
+
with self.lock:
|
|
799
|
+
self._guard(ready=False)
|
|
800
|
+
if approved is not True:
|
|
801
|
+
raise LocalError("host_authorization_required")
|
|
802
|
+
path = self.tool.target(name)
|
|
803
|
+
private_file(path)
|
|
804
|
+
with path.open("rb") as stream:
|
|
805
|
+
raw = stream.read(16385)
|
|
806
|
+
if len(raw) > 16384:
|
|
807
|
+
raise LocalError("artifact_input_limit")
|
|
808
|
+
try:
|
|
809
|
+
text = raw.decode("utf-8")
|
|
810
|
+
except UnicodeError as exc:
|
|
811
|
+
raise LocalError("artifact_not_utf8") from exc
|
|
812
|
+
event = "artifact_" + uuid.uuid4().hex
|
|
813
|
+
captured = self.client.capture(
|
|
814
|
+
event,
|
|
815
|
+
{
|
|
816
|
+
"version": 1,
|
|
817
|
+
"project": self.client.project,
|
|
818
|
+
"source": "reference-artifact-v1",
|
|
819
|
+
"source_event": event,
|
|
820
|
+
"text": text,
|
|
821
|
+
"classification": "restricted",
|
|
822
|
+
"readers": self.data["readers"],
|
|
823
|
+
"observed_at_ms": time.time_ns() // 1_000_000,
|
|
824
|
+
},
|
|
825
|
+
)
|
|
826
|
+
artifact = {
|
|
827
|
+
"path": name,
|
|
828
|
+
"availability": "stored",
|
|
829
|
+
"observation": captured["observation"],
|
|
830
|
+
"content_hash": hashlib.sha256(raw).hexdigest(),
|
|
831
|
+
"required": True,
|
|
832
|
+
}
|
|
833
|
+
state = self.state()
|
|
834
|
+
old = [item for item in state["repository"]["artifacts"] if item["path"] != name]
|
|
835
|
+
state["repository"].update(dirty=True, artifacts=[*old, artifact])
|
|
836
|
+
self._record(
|
|
837
|
+
"artifact_stored", {"path": name, "content_hash": artifact["content_hash"]}, state
|
|
838
|
+
)
|
|
839
|
+
return artifact
|
|
840
|
+
|
|
841
|
+
def prepare_handoff(
|
|
842
|
+
self, recipient: str, role: str, stage: str, *, ttl_ms: int = 60000
|
|
843
|
+
) -> dict[str, Any]:
|
|
844
|
+
with self.lock:
|
|
845
|
+
self._guard()
|
|
846
|
+
self.checkpoint("before_handoff")
|
|
847
|
+
result = self.client.handoff(
|
|
848
|
+
self._command(
|
|
849
|
+
"prepare",
|
|
850
|
+
{
|
|
851
|
+
**self._scope(),
|
|
852
|
+
"checkpoint": self.data["checkpoint"],
|
|
853
|
+
"recipient": recipient,
|
|
854
|
+
"role": role,
|
|
855
|
+
"stage": stage,
|
|
856
|
+
"bindings": self.data["bindings"],
|
|
857
|
+
"ttl_ms": ttl_ms,
|
|
858
|
+
},
|
|
859
|
+
"handoff_" + uuid.uuid4().hex,
|
|
860
|
+
)
|
|
861
|
+
)
|
|
862
|
+
self.data["handoff_checkpoint"] = self.data["checkpoint"]
|
|
863
|
+
self._persist()
|
|
864
|
+
return result
|
|
865
|
+
|
|
866
|
+
def close(self, *, checkpoint: bool = True) -> None:
|
|
867
|
+
self.stop.set()
|
|
868
|
+
if hasattr(self, "worker"):
|
|
869
|
+
self.worker.join()
|
|
870
|
+
with self.lock:
|
|
871
|
+
if self.closed:
|
|
872
|
+
return
|
|
873
|
+
try:
|
|
874
|
+
if checkpoint:
|
|
875
|
+
self._guard(ready=False)
|
|
876
|
+
# The unchanged pre-handoff snapshot is also the durable shutdown
|
|
877
|
+
# snapshot. An audit-only new revision would retire that handoff.
|
|
878
|
+
if self.data["handoff_checkpoint"] != self.data["checkpoint"]:
|
|
879
|
+
self._record("shutdown", {})
|
|
880
|
+
finally:
|
|
881
|
+
self.closed = True
|
|
882
|
+
self.owner.close()
|