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,24 @@
|
|
|
1
|
+
BEGIN IMMEDIATE;
|
|
2
|
+
CREATE TABLE IF NOT EXISTS checkpoint_streams (
|
|
3
|
+
tenant TEXT NOT NULL REFERENCES tenants, project TEXT NOT NULL, task TEXT NOT NULL,
|
|
4
|
+
stream TEXT NOT NULL, writer TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
5
|
+
incarnation TEXT NOT NULL, latest TEXT,
|
|
6
|
+
PRIMARY KEY(tenant,project,task,stream));
|
|
7
|
+
CREATE TABLE IF NOT EXISTS checkpoints (
|
|
8
|
+
tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, project TEXT NOT NULL,
|
|
9
|
+
task TEXT NOT NULL, stream TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
10
|
+
writer TEXT NOT NULL, incarnation TEXT NOT NULL, created INTEGER NOT NULL,
|
|
11
|
+
body TEXT, body_hash TEXT NOT NULL, readers TEXT NOT NULL, dependencies TEXT NOT NULL,
|
|
12
|
+
state TEXT NOT NULL, position INTEGER NOT NULL,
|
|
13
|
+
PRIMARY KEY(tenant,id), UNIQUE(tenant,project,task,stream,revision));
|
|
14
|
+
CREATE TABLE IF NOT EXISTS operation_intents (
|
|
15
|
+
tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, principal TEXT NOT NULL,
|
|
16
|
+
project TEXT NOT NULL, task TEXT NOT NULL, stream TEXT NOT NULL,
|
|
17
|
+
incarnation TEXT NOT NULL, target_hash TEXT NOT NULL, parameters_hash TEXT NOT NULL,
|
|
18
|
+
method TEXT NOT NULL, provider_key TEXT, state TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
19
|
+
result_hash TEXT, evidence TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL,
|
|
20
|
+
reconciled_incarnation TEXT,
|
|
21
|
+
PRIMARY KEY(tenant,id));
|
|
22
|
+
CREATE INDEX IF NOT EXISTS operations_scope ON operation_intents(tenant,project,task,stream);
|
|
23
|
+
PRAGMA user_version=4;
|
|
24
|
+
COMMIT;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Application orchestration ports; authoritative transactions arrive in P02."""
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Backend-neutral scenario harness. Missing adapters are never passing evidence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ScenarioAdapter(Protocol):
|
|
10
|
+
"""Adapters must reset isolated state and execute real operations before asserting."""
|
|
11
|
+
|
|
12
|
+
name: str
|
|
13
|
+
supported_scenarios: frozenset[str]
|
|
14
|
+
|
|
15
|
+
def reset(self, seed: dict[str, Any]) -> None: ...
|
|
16
|
+
|
|
17
|
+
def execute(self, operation: str, arguments: dict[str, Any]) -> dict[str, Any]: ...
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ScenarioResult:
|
|
22
|
+
scenario_id: str
|
|
23
|
+
backend: str
|
|
24
|
+
status: str
|
|
25
|
+
assertions: int
|
|
26
|
+
reason: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run_scenario(case: dict[str, Any], adapter: ScenarioAdapter | None) -> ScenarioResult:
|
|
30
|
+
identifier = str(case["id"])
|
|
31
|
+
backend = adapter.name if adapter else "none"
|
|
32
|
+
if adapter is None or identifier not in adapter.supported_scenarios:
|
|
33
|
+
return ScenarioResult(identifier, backend, "not_evaluated", 0, "adapter_not_implemented")
|
|
34
|
+
checks = 0
|
|
35
|
+
try:
|
|
36
|
+
adapter.reset(case["seed"])
|
|
37
|
+
for step in case["steps"]:
|
|
38
|
+
observed = adapter.execute(step["operation"], step["arguments"])
|
|
39
|
+
for key, expected in step["expect"].items():
|
|
40
|
+
checks += 1
|
|
41
|
+
if key not in observed or observed[key] != expected:
|
|
42
|
+
return ScenarioResult(
|
|
43
|
+
identifier, backend, "failed", checks, "assertion_mismatch"
|
|
44
|
+
)
|
|
45
|
+
if checks == 0:
|
|
46
|
+
return ScenarioResult(identifier, backend, "failed", 0, "no_assertions")
|
|
47
|
+
return ScenarioResult(identifier, backend, "passed", checks, "observed")
|
|
48
|
+
except Exception:
|
|
49
|
+
# Evidence logs must be explicitly sanitized; exception text may contain source content.
|
|
50
|
+
return ScenarioResult(identifier, backend, "failed", checks, "adapter_error")
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Bounded legacy import through the existing authorized capture contract.
|
|
2
|
+
|
|
3
|
+
The source row maps to one private historical observation. Lessons additionally
|
|
4
|
+
become unaccepted proposals. No grant, verification, constraint, checkpoint or
|
|
5
|
+
active procedure is created by import.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Protocol
|
|
13
|
+
|
|
14
|
+
from memoryking.adapters.legacy_snapshot import inspect
|
|
15
|
+
from memoryking.adapters.local_files import Ownership, atomic, private_dir, private_file
|
|
16
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash, load_strict
|
|
17
|
+
from memoryking.domain.local import LocalError
|
|
18
|
+
from memoryking.sdk import BINDING_FIELDS
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ImportClient(Protocol):
|
|
22
|
+
def context(self) -> dict[str, Any]: ...
|
|
23
|
+
def capture(self, key: str, observation: dict[str, Any]) -> dict[str, Any]: ...
|
|
24
|
+
def read_legacy(self, handle: str) -> dict[str, Any]: ...
|
|
25
|
+
def knowledge(self, command: dict[str, Any]) -> dict[str, Any]: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def binding(client: ImportClient) -> dict[str, Any]:
|
|
29
|
+
context = client.context()
|
|
30
|
+
if not {"read", "capture", "admin"} <= set(context["capabilities"]):
|
|
31
|
+
raise LocalError("legacy_operator_required")
|
|
32
|
+
return {key: context[key] for key in BINDING_FIELDS}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def summary(snapshot: dict[str, Any]) -> dict[str, Any]:
|
|
36
|
+
return {
|
|
37
|
+
**{key: value for key, value in snapshot.items() if key != "rows"},
|
|
38
|
+
"rows": [
|
|
39
|
+
{key: value for key, value in row.items() if key != "body"} for row in snapshot["rows"]
|
|
40
|
+
],
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def make_plan(path: Path, source: str, profiles: list[str], client: ImportClient) -> dict[str, Any]:
|
|
45
|
+
snapshot = inspect(path, source, expected_profiles=profiles)
|
|
46
|
+
target = binding(client)
|
|
47
|
+
for row in snapshot["rows"]:
|
|
48
|
+
try:
|
|
49
|
+
lesson_text(row)
|
|
50
|
+
except LocalError as exc:
|
|
51
|
+
snapshot["unresolved"].append({"code": exc.code, "key": row["key"]})
|
|
52
|
+
# The plan is small even when the source contains thousands of records.
|
|
53
|
+
# Detailed row mappings live in the independently hashed inspection report.
|
|
54
|
+
return {
|
|
55
|
+
"version": 1,
|
|
56
|
+
"snapshot_sha256": snapshot["snapshot_sha256"],
|
|
57
|
+
"source": source,
|
|
58
|
+
"profiles": profiles,
|
|
59
|
+
"binding": target,
|
|
60
|
+
"rows": len(snapshot["rows"]),
|
|
61
|
+
"tables": snapshot["tables"],
|
|
62
|
+
"unresolved": snapshot["unresolved"],
|
|
63
|
+
"row_set_sha256": hashlib.sha256(
|
|
64
|
+
b"".join(
|
|
65
|
+
canonical_bytes({k: v for k, v in row.items() if k != "body"}) + b"\n"
|
|
66
|
+
for row in snapshot["rows"]
|
|
67
|
+
)
|
|
68
|
+
).hexdigest(),
|
|
69
|
+
"policy": "private_historical_evidence_and_lesson_proposals_v1",
|
|
70
|
+
"authority": "no_imported_approval_or_activation",
|
|
71
|
+
"retired_policy": "hash_only_tombstone_or_source_conflict",
|
|
72
|
+
"blob_policy": "preserve_in_snapshot_hash_only_in_target",
|
|
73
|
+
"time_policy": "preserve_legacy_values_observed_time_unknown",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def lesson_text(row: dict[str, Any]) -> str | None:
|
|
78
|
+
if row["table"] != "lessons" or row["retired"]:
|
|
79
|
+
return None
|
|
80
|
+
values = row["body"]["values"]
|
|
81
|
+
value = values.get("lesson", values.get("body", {}))
|
|
82
|
+
text = value.get("value") if value.get("type") == "text" else None
|
|
83
|
+
if not isinstance(text, str) or not 1 <= len(text) <= 8192:
|
|
84
|
+
raise LocalError("legacy_lesson_proposal_limit")
|
|
85
|
+
return text
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def propose_lesson(
|
|
89
|
+
row: dict[str, Any],
|
|
90
|
+
plan: dict[str, Any],
|
|
91
|
+
request: dict[str, Any],
|
|
92
|
+
receipt: dict[str, Any],
|
|
93
|
+
client: ImportClient,
|
|
94
|
+
) -> dict[str, Any] | None:
|
|
95
|
+
text = lesson_text(row)
|
|
96
|
+
if text is None:
|
|
97
|
+
return None
|
|
98
|
+
raw = request["text"].encode()
|
|
99
|
+
key = "legacy_" + canonical_hash(
|
|
100
|
+
{"source": plan["source"], "row": row["key"], "project": plan["binding"]["project"]}
|
|
101
|
+
)
|
|
102
|
+
return client.knowledge(
|
|
103
|
+
{
|
|
104
|
+
"version": 1,
|
|
105
|
+
"incarnation": plan["binding"]["incarnation"],
|
|
106
|
+
"action": "propose",
|
|
107
|
+
"key": key,
|
|
108
|
+
"args": {
|
|
109
|
+
"project": plan["binding"]["project"],
|
|
110
|
+
"logical_key": key,
|
|
111
|
+
"expected_version": 0,
|
|
112
|
+
"preserve_legacy": True,
|
|
113
|
+
"body": {
|
|
114
|
+
"text": text,
|
|
115
|
+
"kind": "knowledge",
|
|
116
|
+
"selector": {"legacy_applicability": "requires_current_review"},
|
|
117
|
+
"valid_start": None,
|
|
118
|
+
"valid_end": None,
|
|
119
|
+
"task": None,
|
|
120
|
+
"run": None,
|
|
121
|
+
"readers": request["readers"],
|
|
122
|
+
"evidence": [
|
|
123
|
+
{
|
|
124
|
+
"observation": receipt["observation"],
|
|
125
|
+
"start_byte": 0,
|
|
126
|
+
"end_byte": len(raw),
|
|
127
|
+
"content_hash": hashlib.sha256(raw).hexdigest(),
|
|
128
|
+
}
|
|
129
|
+
],
|
|
130
|
+
"authority": None,
|
|
131
|
+
"rule_key": None,
|
|
132
|
+
"effect": None,
|
|
133
|
+
"rule_value": None,
|
|
134
|
+
"provenance": {
|
|
135
|
+
"migration": "legacy_proposal_requires_current_review",
|
|
136
|
+
"source": plan["source"],
|
|
137
|
+
"row_sha256": row["sha256"],
|
|
138
|
+
"legacy_review_is_not_authority": True,
|
|
139
|
+
"original_times_not_converted_to_current_validity": True,
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def request_for(row: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:
|
|
148
|
+
body = row["body"]
|
|
149
|
+
if row["retired"]:
|
|
150
|
+
body = {
|
|
151
|
+
"format": "memoryking-legacy-tombstone-v1",
|
|
152
|
+
"source": plan["source"],
|
|
153
|
+
"table": row["table"],
|
|
154
|
+
"key": row["identity"],
|
|
155
|
+
"source_row_sha256": row["sha256"],
|
|
156
|
+
"authority": "retired_source_content_unavailable",
|
|
157
|
+
}
|
|
158
|
+
else:
|
|
159
|
+
body = {**body, "legacy_reference_keys": row["references"]}
|
|
160
|
+
text = canonical_bytes(body).decode()
|
|
161
|
+
if len(text.encode()) > 65536:
|
|
162
|
+
raise LocalError("legacy_record_too_large")
|
|
163
|
+
return {
|
|
164
|
+
"version": 1,
|
|
165
|
+
"project": plan["binding"]["project"],
|
|
166
|
+
"source": "legacy_" + hashlib.sha256(plan["source"].encode()).hexdigest(),
|
|
167
|
+
"source_event": "row_" + row["key"],
|
|
168
|
+
"text": text,
|
|
169
|
+
"readers": [plan["binding"]["principal"]],
|
|
170
|
+
"classification": "restricted",
|
|
171
|
+
"observed_at_ms": 0,
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def apply_batch(
|
|
176
|
+
path: Path,
|
|
177
|
+
plan: dict[str, Any],
|
|
178
|
+
client: ImportClient,
|
|
179
|
+
journal: Path,
|
|
180
|
+
*,
|
|
181
|
+
start: int = 0,
|
|
182
|
+
limit: int = 100,
|
|
183
|
+
) -> dict[str, Any]:
|
|
184
|
+
if not 1 <= limit <= 500 or start < 0:
|
|
185
|
+
raise LocalError("legacy_batch_limit")
|
|
186
|
+
if plan != make_plan(path, plan["source"], plan["profiles"], client):
|
|
187
|
+
raise LocalError("legacy_plan_changed")
|
|
188
|
+
if plan["unresolved"]:
|
|
189
|
+
raise LocalError("legacy_reconciliation_required")
|
|
190
|
+
snapshot = inspect(path, plan["source"], expected_profiles=plan["profiles"])
|
|
191
|
+
if snapshot["snapshot_sha256"] != plan["snapshot_sha256"]:
|
|
192
|
+
raise LocalError("legacy_plan_changed")
|
|
193
|
+
requests = [request_for(row, plan) for row in snapshot["rows"]]
|
|
194
|
+
for row in snapshot["rows"]:
|
|
195
|
+
lesson_text(row)
|
|
196
|
+
if start > len(requests):
|
|
197
|
+
raise LocalError("legacy_batch_start")
|
|
198
|
+
private_dir(journal, create=True)
|
|
199
|
+
owner = Ownership(journal)
|
|
200
|
+
try:
|
|
201
|
+
identity = journal / "plan.json"
|
|
202
|
+
if identity.exists():
|
|
203
|
+
private_file(identity)
|
|
204
|
+
if load_strict(identity.read_bytes()) != plan:
|
|
205
|
+
raise LocalError("legacy_journal_plan_mismatch")
|
|
206
|
+
else:
|
|
207
|
+
atomic(identity, canonical_bytes(plan))
|
|
208
|
+
completed = 0
|
|
209
|
+
wrote = 0
|
|
210
|
+
mapping: list[dict[str, Any]] = []
|
|
211
|
+
for index, (row, request) in enumerate(zip(snapshot["rows"], requests, strict=True)):
|
|
212
|
+
if index < start:
|
|
213
|
+
continue
|
|
214
|
+
result_path = journal / (row["key"] + ".json")
|
|
215
|
+
if result_path.exists():
|
|
216
|
+
private_file(result_path)
|
|
217
|
+
result = load_strict(result_path.read_bytes())
|
|
218
|
+
if result["request_sha256"] != canonical_hash(request) or result[
|
|
219
|
+
"plan_sha256"
|
|
220
|
+
] != canonical_hash(plan):
|
|
221
|
+
raise LocalError("legacy_journal_corrupt")
|
|
222
|
+
# Repeated import goes through current authorization and stable
|
|
223
|
+
# source identity again. A prior local journal is not authority.
|
|
224
|
+
if wrote == limit:
|
|
225
|
+
break
|
|
226
|
+
if binding(client) != plan["binding"]:
|
|
227
|
+
raise LocalError("legacy_context_changed")
|
|
228
|
+
try:
|
|
229
|
+
receipt = client.capture("import_" + row["key"], request)
|
|
230
|
+
proposal = propose_lesson(row, plan, request, receipt, client)
|
|
231
|
+
except LocalError as exc:
|
|
232
|
+
atomic(
|
|
233
|
+
journal / "last-failure.json",
|
|
234
|
+
canonical_bytes(
|
|
235
|
+
{
|
|
236
|
+
"row": row["key"],
|
|
237
|
+
"index": index,
|
|
238
|
+
"code": exc.code,
|
|
239
|
+
"automatic_retry": False,
|
|
240
|
+
}
|
|
241
|
+
),
|
|
242
|
+
)
|
|
243
|
+
raise
|
|
244
|
+
result = {
|
|
245
|
+
"row": row["key"],
|
|
246
|
+
"table": row["table"],
|
|
247
|
+
"request_sha256": canonical_hash(request),
|
|
248
|
+
"plan_sha256": canonical_hash(plan),
|
|
249
|
+
"target": receipt["observation"],
|
|
250
|
+
"handle": receipt["handle"],
|
|
251
|
+
"incarnation": receipt["incarnation"],
|
|
252
|
+
"retired": row["retired"],
|
|
253
|
+
"legacy_references": row["references"],
|
|
254
|
+
"proposal": proposal,
|
|
255
|
+
}
|
|
256
|
+
if result["incarnation"] != plan["binding"]["incarnation"]:
|
|
257
|
+
raise LocalError("legacy_context_changed")
|
|
258
|
+
atomic(result_path, canonical_bytes(result))
|
|
259
|
+
mapping.append(result)
|
|
260
|
+
wrote += 1
|
|
261
|
+
completed += 1
|
|
262
|
+
return {
|
|
263
|
+
"version": 1,
|
|
264
|
+
"plan_sha256": canonical_hash(plan),
|
|
265
|
+
"submitted_this_batch": completed,
|
|
266
|
+
"start": start,
|
|
267
|
+
"next_start": start + completed,
|
|
268
|
+
"total_rows": len(requests),
|
|
269
|
+
"end_reached": start + completed == len(requests),
|
|
270
|
+
"mapping": mapping,
|
|
271
|
+
"authority_created": False,
|
|
272
|
+
"live_cutover": False,
|
|
273
|
+
"reconciliation_required": True,
|
|
274
|
+
}
|
|
275
|
+
finally:
|
|
276
|
+
owner.close()
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def reconcile(
|
|
280
|
+
path: Path, plan: dict[str, Any], client: ImportClient, journal: Path
|
|
281
|
+
) -> dict[str, Any]:
|
|
282
|
+
"""Verify every mapped row through current authorized reads, without writes."""
|
|
283
|
+
if plan != make_plan(path, plan["source"], plan["profiles"], client) or plan["unresolved"]:
|
|
284
|
+
raise LocalError("legacy_plan_changed")
|
|
285
|
+
private_dir(journal)
|
|
286
|
+
snapshot = inspect(path, plan["source"], expected_profiles=plan["profiles"])
|
|
287
|
+
if snapshot["snapshot_sha256"] != plan["snapshot_sha256"]:
|
|
288
|
+
raise LocalError("legacy_plan_changed")
|
|
289
|
+
mapping: dict[str, str] = {}
|
|
290
|
+
references = 0
|
|
291
|
+
for row in snapshot["rows"]:
|
|
292
|
+
if binding(client) != plan["binding"]:
|
|
293
|
+
raise LocalError("legacy_context_changed")
|
|
294
|
+
result_path = journal / (row["key"] + ".json")
|
|
295
|
+
if not result_path.exists():
|
|
296
|
+
raise LocalError("legacy_incomplete")
|
|
297
|
+
private_file(result_path)
|
|
298
|
+
result = load_strict(result_path.read_bytes())
|
|
299
|
+
request = request_for(row, plan)
|
|
300
|
+
if (
|
|
301
|
+
result["plan_sha256"] != canonical_hash(plan)
|
|
302
|
+
or result["request_sha256"] != canonical_hash(request)
|
|
303
|
+
or result["incarnation"] != plan["binding"]["incarnation"]
|
|
304
|
+
):
|
|
305
|
+
raise LocalError("legacy_journal_corrupt")
|
|
306
|
+
items = client.read_legacy(result["handle"])["items"]
|
|
307
|
+
if (
|
|
308
|
+
len(items) != 1
|
|
309
|
+
or any(
|
|
310
|
+
items[0][key] != request[key]
|
|
311
|
+
for key in (
|
|
312
|
+
"text",
|
|
313
|
+
"source",
|
|
314
|
+
"source_event",
|
|
315
|
+
"project",
|
|
316
|
+
"classification",
|
|
317
|
+
"observed_at_ms",
|
|
318
|
+
)
|
|
319
|
+
)
|
|
320
|
+
or items[0]["id"] != result["target"]
|
|
321
|
+
):
|
|
322
|
+
raise LocalError("legacy_target_mismatch")
|
|
323
|
+
mapping[row["key"]] = result["target"]
|
|
324
|
+
references += len(row["references"])
|
|
325
|
+
if any(ref not in mapping for row in snapshot["rows"] for ref in row["references"]):
|
|
326
|
+
raise LocalError("legacy_reference_missing")
|
|
327
|
+
return {
|
|
328
|
+
"version": 1,
|
|
329
|
+
"plan_sha256": canonical_hash(plan),
|
|
330
|
+
"verified_rows": len(mapping),
|
|
331
|
+
"verified_references": references,
|
|
332
|
+
"mapping": mapping,
|
|
333
|
+
"current_reads_verified": True,
|
|
334
|
+
"point_in_time_read_checks_not_a_global_snapshot": True,
|
|
335
|
+
"authority_created": False,
|
|
336
|
+
"live_cutover": False,
|
|
337
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Wire dispatch port; transports do not own policy or database transactions."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Protocol
|
|
4
|
+
|
|
5
|
+
from memoryking.domain.local import Released
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LocalOperations(Protocol):
|
|
9
|
+
def execute(self, request: dict[str, Any]) -> dict[str, Any] | Released: ...
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""The storage port's dialect: the few expressions SQLite and PostgreSQL spell differently.
|
|
2
|
+
|
|
3
|
+
Everything else the store and its adapters write is portable SQL: `?` placeholders
|
|
4
|
+
(the PostgreSQL facade binds them), `ON CONFLICT` upserts, and the JSON table function
|
|
5
|
+
`json_each`, which the PostgreSQL schema defines. A backend hands its dialect to the
|
|
6
|
+
store, and no adapter may emit engine-specific syntax: the PostgreSQL facade refuses it
|
|
7
|
+
rather than translating it, so a new divergence is a test failure, not a regex.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
# Upsert targets: the full column list and the conflict key for each table that is
|
|
15
|
+
# written with "insert or replace" semantics. Both engines accept the generated SQL.
|
|
16
|
+
UPSERTS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
|
|
17
|
+
"grants": (
|
|
18
|
+
("tenant", "principal", "project", "capabilities", "starts", "expires"),
|
|
19
|
+
("tenant", "principal", "project"),
|
|
20
|
+
),
|
|
21
|
+
"projection_items": (
|
|
22
|
+
(
|
|
23
|
+
"tenant",
|
|
24
|
+
"observation",
|
|
25
|
+
"incarnation",
|
|
26
|
+
"generation",
|
|
27
|
+
"source_revision",
|
|
28
|
+
"blob_hash",
|
|
29
|
+
"byte_count",
|
|
30
|
+
),
|
|
31
|
+
("tenant", "observation"),
|
|
32
|
+
),
|
|
33
|
+
"code_policies": (
|
|
34
|
+
(
|
|
35
|
+
"tenant",
|
|
36
|
+
"revision",
|
|
37
|
+
"repository",
|
|
38
|
+
"origin",
|
|
39
|
+
"version",
|
|
40
|
+
"impact",
|
|
41
|
+
"dependencies",
|
|
42
|
+
"evidence",
|
|
43
|
+
"actor",
|
|
44
|
+
),
|
|
45
|
+
("tenant", "revision"),
|
|
46
|
+
),
|
|
47
|
+
"source_trust": (
|
|
48
|
+
("tenant", "project", "source", "level", "decided_by", "decided"),
|
|
49
|
+
("tenant", "project", "source"),
|
|
50
|
+
),
|
|
51
|
+
"code_validations": (
|
|
52
|
+
(
|
|
53
|
+
"tenant",
|
|
54
|
+
"incarnation",
|
|
55
|
+
"revision",
|
|
56
|
+
"snapshot",
|
|
57
|
+
"policy",
|
|
58
|
+
"state",
|
|
59
|
+
"evidence",
|
|
60
|
+
"expires",
|
|
61
|
+
"reason",
|
|
62
|
+
"generation",
|
|
63
|
+
),
|
|
64
|
+
("tenant", "incarnation", "revision", "snapshot", "policy"),
|
|
65
|
+
),
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def upsert(table: str) -> str:
|
|
70
|
+
"""INSERT ... ON CONFLICT (keys) DO UPDATE for a registered table; portable SQL."""
|
|
71
|
+
columns, keys = UPSERTS[table]
|
|
72
|
+
assignments = ",".join(f"{c}=EXCLUDED.{c}" for c in columns if c not in keys)
|
|
73
|
+
placeholders = ",".join("?" for _ in columns)
|
|
74
|
+
return (
|
|
75
|
+
f"INSERT INTO {table} ({','.join(columns)}) VALUES ({placeholders}) "
|
|
76
|
+
f"ON CONFLICT ({','.join(keys)}) DO UPDATE SET {assignments}"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def insert_ignore(table: str, count: int) -> str:
|
|
81
|
+
"""INSERT ... ON CONFLICT DO NOTHING; portable SQL."""
|
|
82
|
+
placeholders = ",".join("?" for _ in range(count))
|
|
83
|
+
return f"INSERT INTO {table} VALUES ({placeholders}) ON CONFLICT DO NOTHING"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Dialect(Protocol):
|
|
87
|
+
name: str
|
|
88
|
+
|
|
89
|
+
def lexical_match(self) -> str:
|
|
90
|
+
"""A predicate over the `lexical` table with one `?` bound to the query string."""
|
|
91
|
+
...
|
|
92
|
+
|
|
93
|
+
def byte_length(self, expression: str) -> str:
|
|
94
|
+
"""The byte length of a text column."""
|
|
95
|
+
...
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class SQLiteDialect:
|
|
99
|
+
name = "sqlite"
|
|
100
|
+
|
|
101
|
+
def lexical_match(self) -> str:
|
|
102
|
+
return "lexical MATCH ?"
|
|
103
|
+
|
|
104
|
+
def byte_length(self, expression: str) -> str:
|
|
105
|
+
return f"length(CAST({expression} AS BLOB))"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class PostgresDialect:
|
|
109
|
+
name = "postgresql"
|
|
110
|
+
|
|
111
|
+
def lexical_match(self) -> str:
|
|
112
|
+
# Retrieval sends quoted terms joined by OR; websearch_to_tsquery keeps that
|
|
113
|
+
# meaning (any term matches) where phraseto_tsquery would demand the phrase.
|
|
114
|
+
return "to_tsvector('simple',text) @@ websearch_to_tsquery('simple',?)"
|
|
115
|
+
|
|
116
|
+
def byte_length(self, expression: str) -> str:
|
|
117
|
+
return f"octet_length({expression})"
|