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,358 @@
|
|
|
1
|
+
"""Read a detached legacy SQLite snapshot without executing its schema or code.
|
|
2
|
+
|
|
3
|
+
The snapshot is evidence, never authority. A plan must account for every ordinary
|
|
4
|
+
table. Virtual/shadow search tables are inventoried but rebuilt rather than copied.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import math
|
|
11
|
+
import sqlite3
|
|
12
|
+
import stat
|
|
13
|
+
from collections import deque
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from memoryking.adapters.legacy_tables import TABLES
|
|
18
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash
|
|
19
|
+
from memoryking.domain.local import LocalError
|
|
20
|
+
|
|
21
|
+
MAX_DATABASE = 512 * 1024 * 1024
|
|
22
|
+
MAX_ROWS = 10_000
|
|
23
|
+
MAX_ROW = 60 * 1024
|
|
24
|
+
MAX_TOTAL = 64 * 1024 * 1024
|
|
25
|
+
SHAPES = {
|
|
26
|
+
"kingforge-v1": {
|
|
27
|
+
"plans": {
|
|
28
|
+
"id",
|
|
29
|
+
"title",
|
|
30
|
+
"objective",
|
|
31
|
+
"context",
|
|
32
|
+
"author",
|
|
33
|
+
"status",
|
|
34
|
+
"created_at",
|
|
35
|
+
"updated_at",
|
|
36
|
+
},
|
|
37
|
+
"steps": {"id", "plan_id", "seq", "description", "status", "notes", "updated_at"},
|
|
38
|
+
"lessons": {
|
|
39
|
+
"id",
|
|
40
|
+
"plan_id",
|
|
41
|
+
"title",
|
|
42
|
+
"situation",
|
|
43
|
+
"lesson",
|
|
44
|
+
"kind",
|
|
45
|
+
"tags",
|
|
46
|
+
"author",
|
|
47
|
+
"created_at",
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
"standalone": {
|
|
51
|
+
"documents": {
|
|
52
|
+
"id",
|
|
53
|
+
"kind",
|
|
54
|
+
"feature",
|
|
55
|
+
"title",
|
|
56
|
+
"content",
|
|
57
|
+
"status",
|
|
58
|
+
"content_hash",
|
|
59
|
+
"created_at",
|
|
60
|
+
"updated_at",
|
|
61
|
+
},
|
|
62
|
+
"lessons": {
|
|
63
|
+
"id",
|
|
64
|
+
"category",
|
|
65
|
+
"title",
|
|
66
|
+
"body",
|
|
67
|
+
"source_feature",
|
|
68
|
+
"created_at",
|
|
69
|
+
"updated_at",
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
"universal": {
|
|
73
|
+
"lw_schema_migrations": {"version", "name", "applied_at"},
|
|
74
|
+
"lw_scopes": {"id", "parent_scope_id", "kind", "external_key", "lifecycle"},
|
|
75
|
+
"lw_evidence": {"id", "scope_id", "content", "content_hash"},
|
|
76
|
+
"lw_memories": {
|
|
77
|
+
"id",
|
|
78
|
+
"scope_id",
|
|
79
|
+
"memory_key",
|
|
80
|
+
"revision",
|
|
81
|
+
"type",
|
|
82
|
+
"title",
|
|
83
|
+
"body",
|
|
84
|
+
"lifecycle",
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def digest_file(path: Path) -> str:
|
|
91
|
+
with path.open("rb") as stream:
|
|
92
|
+
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def quote(name: str) -> str:
|
|
96
|
+
return '"' + name.replace('"', '""') + '"'
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def cell(value: Any) -> dict[str, Any]:
|
|
100
|
+
"""Preserve SQLite storage type; vectors remain opaque source metadata."""
|
|
101
|
+
if value is None:
|
|
102
|
+
return {"type": "null"}
|
|
103
|
+
if isinstance(value, bytes):
|
|
104
|
+
return {"type": "blob", "sha256": hashlib.sha256(value).hexdigest(), "bytes": len(value)}
|
|
105
|
+
if isinstance(value, str):
|
|
106
|
+
return {"type": "text", "value": value}
|
|
107
|
+
if isinstance(value, int):
|
|
108
|
+
return {"type": "integer", "value": str(value)}
|
|
109
|
+
if isinstance(value, float) and math.isfinite(value):
|
|
110
|
+
return {"type": "real", "hex": value.hex()}
|
|
111
|
+
raise LocalError("legacy_value_unsupported")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def inspect(path: Path, source: str, *, expected_profiles: list[str]) -> dict[str, Any]:
|
|
115
|
+
"""Inspect a closed snapshot. Callers supply a stable source-system identity.
|
|
116
|
+
|
|
117
|
+
Refuse WAL/journal sidecars instead of treating an active database as a backup.
|
|
118
|
+
Only a detached copy is opened by SQLite, using immutable read-only mode.
|
|
119
|
+
The caller may not use this function to take a live backup.
|
|
120
|
+
"""
|
|
121
|
+
from memoryking.adapters.local_store import identifier
|
|
122
|
+
|
|
123
|
+
identifier(source)
|
|
124
|
+
info = path.lstat()
|
|
125
|
+
if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= MAX_DATABASE:
|
|
126
|
+
raise LocalError("legacy_snapshot_invalid")
|
|
127
|
+
if any(Path(str(path) + suffix).exists() for suffix in ("-wal", "-shm", "-journal")):
|
|
128
|
+
raise LocalError("legacy_snapshot_not_detached")
|
|
129
|
+
before = digest_file(path)
|
|
130
|
+
db = sqlite3.connect(path.resolve().as_uri() + "?mode=ro&immutable=1", uri=True)
|
|
131
|
+
db.row_factory = sqlite3.Row
|
|
132
|
+
try:
|
|
133
|
+
db.execute("PRAGMA query_only=ON")
|
|
134
|
+
db.execute("PRAGMA trusted_schema=OFF")
|
|
135
|
+
# Bound malicious/accidentally huge queries as well as returned bytes.
|
|
136
|
+
steps = 0
|
|
137
|
+
|
|
138
|
+
def deadline() -> int:
|
|
139
|
+
nonlocal steps
|
|
140
|
+
steps += 1
|
|
141
|
+
return int(steps > 100_000)
|
|
142
|
+
|
|
143
|
+
db.set_progress_handler(deadline, 1000)
|
|
144
|
+
if db.execute("PRAGMA quick_check").fetchone()[0] != "ok":
|
|
145
|
+
raise LocalError("legacy_integrity_failed")
|
|
146
|
+
table_list = list(db.execute("PRAGMA table_list"))
|
|
147
|
+
tables = sorted(
|
|
148
|
+
r["name"]
|
|
149
|
+
for r in table_list
|
|
150
|
+
if r["schema"] == "main"
|
|
151
|
+
and r["type"] == "table"
|
|
152
|
+
and not r["name"].startswith("sqlite_")
|
|
153
|
+
)
|
|
154
|
+
derived = sorted(
|
|
155
|
+
r["name"]
|
|
156
|
+
for r in table_list
|
|
157
|
+
if r["schema"] == "main" and r["type"] in {"virtual", "shadow"}
|
|
158
|
+
)
|
|
159
|
+
if len(tables) > 128:
|
|
160
|
+
raise LocalError("legacy_table_limit")
|
|
161
|
+
schema = {
|
|
162
|
+
t: [dict(r) for r in db.execute("PRAGMA table_info(" + quote(t) + ")")] for t in tables
|
|
163
|
+
}
|
|
164
|
+
columns = {t: {c["name"] for c in schema[t]} for t in tables}
|
|
165
|
+
profiles = sorted(
|
|
166
|
+
p
|
|
167
|
+
for p, requirements in SHAPES.items()
|
|
168
|
+
if all(required <= columns.get(t, set()) for t, required in requirements.items())
|
|
169
|
+
)
|
|
170
|
+
unresolved: list[dict[str, Any]] = []
|
|
171
|
+
if not profiles or profiles != sorted(expected_profiles):
|
|
172
|
+
unresolved.append({"code": "profile_mismatch", "detected": profiles})
|
|
173
|
+
rows: list[dict[str, Any]] = []
|
|
174
|
+
raw_rows: dict[str, list[dict[str, Any]]] = {}
|
|
175
|
+
counts: dict[str, int] = {}
|
|
176
|
+
total_bytes = 0
|
|
177
|
+
for table in tables:
|
|
178
|
+
key = [c["name"] for c in sorted(schema[table], key=lambda c: c["pk"]) if c["pk"]]
|
|
179
|
+
counts[table] = db.execute("SELECT count(*) FROM " + quote(table)).fetchone()[0]
|
|
180
|
+
if sum(counts.values()) > MAX_ROWS:
|
|
181
|
+
raise LocalError("legacy_row_limit")
|
|
182
|
+
if table not in TABLES:
|
|
183
|
+
unresolved.append({"code": "unsupported_table", "table": table})
|
|
184
|
+
continue
|
|
185
|
+
if not key:
|
|
186
|
+
unresolved.append({"code": "missing_stable_key", "table": table})
|
|
187
|
+
continue
|
|
188
|
+
sql = "SELECT * FROM " + quote(table) + " ORDER BY " + ",".join(map(quote, key))
|
|
189
|
+
raw_rows[table] = []
|
|
190
|
+
for row in db.execute(sql):
|
|
191
|
+
raw = dict(row)
|
|
192
|
+
raw_rows[table].append(raw)
|
|
193
|
+
identity = {k: cell(raw[k]) for k in key}
|
|
194
|
+
if any(raw[k] is None for k in key):
|
|
195
|
+
unresolved.append({"code": "null_stable_key", "table": table})
|
|
196
|
+
row_key = canonical_hash({"table": table, "key": identity})
|
|
197
|
+
values = {k: cell(v) for k, v in raw.items()}
|
|
198
|
+
body = {
|
|
199
|
+
"format": "memoryking-legacy-row-v1",
|
|
200
|
+
"source": source,
|
|
201
|
+
"table": table,
|
|
202
|
+
"key": identity,
|
|
203
|
+
"values": values,
|
|
204
|
+
"authority": "untrusted_historical_evidence",
|
|
205
|
+
"time_semantics": "original_values_only_not_current_validity",
|
|
206
|
+
"embedding_semantics": "opaque_hash_not_an_index",
|
|
207
|
+
}
|
|
208
|
+
encoded = canonical_bytes(body)
|
|
209
|
+
total_bytes += len(encoded)
|
|
210
|
+
if total_bytes > MAX_TOTAL:
|
|
211
|
+
raise LocalError("legacy_total_limit")
|
|
212
|
+
blocked = len(encoded) > MAX_ROW
|
|
213
|
+
if blocked:
|
|
214
|
+
unresolved.append({"code": "record_too_large", "table": table, "key": row_key})
|
|
215
|
+
if table in {"documents", "lw_evidence"} and isinstance(raw.get("content"), str):
|
|
216
|
+
expected = hashlib.sha256(raw["content"].encode()).hexdigest()
|
|
217
|
+
if str(raw.get("content_hash", "")).lower() != expected:
|
|
218
|
+
unresolved.append(
|
|
219
|
+
{"code": "content_hash_mismatch", "table": table, "key": row_key}
|
|
220
|
+
)
|
|
221
|
+
retired = any(
|
|
222
|
+
str(raw.get(k, "")).lower() in {"deleted", "purged", "revoked"}
|
|
223
|
+
for k in ("status", "lifecycle")
|
|
224
|
+
)
|
|
225
|
+
rows.append(
|
|
226
|
+
{
|
|
227
|
+
"table": table,
|
|
228
|
+
"key": row_key,
|
|
229
|
+
"identity": identity,
|
|
230
|
+
"sha256": hashlib.sha256(encoded).hexdigest(),
|
|
231
|
+
"body": body,
|
|
232
|
+
"retired": retired,
|
|
233
|
+
"references": [],
|
|
234
|
+
}
|
|
235
|
+
)
|
|
236
|
+
lookup = {
|
|
237
|
+
(r["table"], tuple((k, canonical_bytes(v)) for k, v in r["identity"].items())): r["key"]
|
|
238
|
+
for r in rows
|
|
239
|
+
}
|
|
240
|
+
row_map = {r["key"]: r for r in rows}
|
|
241
|
+
# KingForge projections intentionally omit SQL FKs to compatibility
|
|
242
|
+
# tables in the legacy schema; resolve those source links explicitly.
|
|
243
|
+
projection_sources = {
|
|
244
|
+
"lw_kingforge_v1_plan_projections": ("plan_id", "plans"),
|
|
245
|
+
"lw_kingforge_v1_lesson_projections": ("lesson_id", "lessons"),
|
|
246
|
+
}
|
|
247
|
+
for table, (column, target) in projection_sources.items():
|
|
248
|
+
for row, raw in zip(
|
|
249
|
+
[r for r in rows if r["table"] == table], raw_rows.get(table, []), strict=True
|
|
250
|
+
):
|
|
251
|
+
ref = lookup.get((target, (("id", canonical_bytes(cell(raw.get(column)))),)))
|
|
252
|
+
if ref is None:
|
|
253
|
+
unresolved.append(
|
|
254
|
+
{"code": "unresolved_projection_source", "table": table, "key": row["key"]}
|
|
255
|
+
)
|
|
256
|
+
else:
|
|
257
|
+
row["references"].append(ref)
|
|
258
|
+
# Resolve every declared foreign key, including composite keys. Partial
|
|
259
|
+
# NULL keys have SQLite's non-reference semantics and remain in raw data.
|
|
260
|
+
for table, originals in raw_rows.items():
|
|
261
|
+
foreign: dict[int, list[dict[str, Any]]] = {}
|
|
262
|
+
for fk in db.execute("PRAGMA foreign_key_list(" + quote(table) + ")"):
|
|
263
|
+
foreign.setdefault(fk["id"], []).append(dict(fk))
|
|
264
|
+
by_table = [r for r in rows if r["table"] == table]
|
|
265
|
+
for raw, row in zip(originals, by_table, strict=True):
|
|
266
|
+
for group in foreign.values():
|
|
267
|
+
group.sort(key=lambda f: f["seq"])
|
|
268
|
+
if any(raw[f["from"]] is None for f in group):
|
|
269
|
+
continue
|
|
270
|
+
target = group[0]["table"]
|
|
271
|
+
target_pk = [
|
|
272
|
+
c["name"]
|
|
273
|
+
for c in sorted(schema.get(target, []), key=lambda c: c["pk"])
|
|
274
|
+
if c["pk"]
|
|
275
|
+
]
|
|
276
|
+
names = [
|
|
277
|
+
f["to"] or (target_pk[i] if i < len(target_pk) else "")
|
|
278
|
+
for i, f in enumerate(group)
|
|
279
|
+
]
|
|
280
|
+
values = {
|
|
281
|
+
name: cell(raw[f["from"]]) for name, f in zip(names, group, strict=True)
|
|
282
|
+
}
|
|
283
|
+
ref = (
|
|
284
|
+
lookup.get(
|
|
285
|
+
(
|
|
286
|
+
target,
|
|
287
|
+
tuple(
|
|
288
|
+
(k, canonical_bytes(values[k]))
|
|
289
|
+
for k in target_pk
|
|
290
|
+
if k in values
|
|
291
|
+
),
|
|
292
|
+
)
|
|
293
|
+
)
|
|
294
|
+
if set(values) == set(target_pk)
|
|
295
|
+
else None
|
|
296
|
+
)
|
|
297
|
+
if ref is None:
|
|
298
|
+
unresolved.append(
|
|
299
|
+
{
|
|
300
|
+
"code": "unresolved_reference",
|
|
301
|
+
"table": table,
|
|
302
|
+
"key": row["key"],
|
|
303
|
+
"target_table": target,
|
|
304
|
+
}
|
|
305
|
+
)
|
|
306
|
+
else:
|
|
307
|
+
row["references"].append(ref)
|
|
308
|
+
# Polymorphic universal provenance is not a foreign key. Never quietly
|
|
309
|
+
# count it reconciled without resolving both typed ends.
|
|
310
|
+
types = {
|
|
311
|
+
"scope": "lw_scopes",
|
|
312
|
+
"evidence": "lw_evidence",
|
|
313
|
+
"memory": "lw_memories",
|
|
314
|
+
"procedure": "lw_procedures",
|
|
315
|
+
}
|
|
316
|
+
for row, raw in zip(
|
|
317
|
+
[r for r in rows if r["table"] == "lw_links"], raw_rows.get("lw_links", []), strict=True
|
|
318
|
+
):
|
|
319
|
+
for end in ("subject", "object"):
|
|
320
|
+
target = types.get(str(raw.get(end + "_type", "")), "")
|
|
321
|
+
ref = lookup.get((target, (("id", canonical_bytes(cell(raw.get(end + "_id")))),)))
|
|
322
|
+
if ref is None:
|
|
323
|
+
unresolved.append(
|
|
324
|
+
{"code": "unresolved_typed_link", "key": row["key"], "end": end}
|
|
325
|
+
)
|
|
326
|
+
else:
|
|
327
|
+
row["references"].append(ref)
|
|
328
|
+
# A dependent cannot resurrect retired content from its copied body.
|
|
329
|
+
dependents: dict[str, list[str]] = {}
|
|
330
|
+
for row in rows:
|
|
331
|
+
for ref in row["references"]:
|
|
332
|
+
dependents.setdefault(ref, []).append(row["key"])
|
|
333
|
+
retired_queue = deque(row["key"] for row in rows if row["retired"])
|
|
334
|
+
while retired_queue:
|
|
335
|
+
for dependent_key in dependents.get(retired_queue.popleft(), []):
|
|
336
|
+
if not row_map[dependent_key]["retired"]:
|
|
337
|
+
row_map[dependent_key]["retired"] = True
|
|
338
|
+
retired_queue.append(dependent_key)
|
|
339
|
+
if len({r["key"] for r in rows}) != len(rows):
|
|
340
|
+
unresolved.append({"code": "duplicate_stable_key"})
|
|
341
|
+
return {
|
|
342
|
+
"version": 1,
|
|
343
|
+
"source": source,
|
|
344
|
+
"snapshot_sha256": before,
|
|
345
|
+
"snapshot_bytes": info.st_size,
|
|
346
|
+
"profiles": profiles,
|
|
347
|
+
"schema_sha256": canonical_hash(schema),
|
|
348
|
+
"tables": counts,
|
|
349
|
+
"derived_tables_not_imported": derived,
|
|
350
|
+
"rows": rows,
|
|
351
|
+
"unresolved": unresolved,
|
|
352
|
+
}
|
|
353
|
+
except sqlite3.Error as exc:
|
|
354
|
+
raise LocalError("legacy_sqlite_inspection_failed") from exc
|
|
355
|
+
finally:
|
|
356
|
+
db.close()
|
|
357
|
+
if digest_file(path) != before:
|
|
358
|
+
raise LocalError("legacy_source_changed")
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Ordinary table names inspected at Loreweaver d7e5a7b; unknown tables block import."""
|
|
2
|
+
|
|
3
|
+
TABLES = frozenset(
|
|
4
|
+
[
|
|
5
|
+
"plans",
|
|
6
|
+
"steps",
|
|
7
|
+
"lessons",
|
|
8
|
+
"documents",
|
|
9
|
+
"chunks",
|
|
10
|
+
"lw_schema_migrations",
|
|
11
|
+
"lw_scopes",
|
|
12
|
+
"lw_evidence",
|
|
13
|
+
"lw_memories",
|
|
14
|
+
"lw_memory_evidence",
|
|
15
|
+
"lw_links",
|
|
16
|
+
"lw_retrieval_receipts",
|
|
17
|
+
"lw_retrieval_receipt_items",
|
|
18
|
+
"lw_audit_events",
|
|
19
|
+
"lw_procedures",
|
|
20
|
+
"lw_procedure_evidence",
|
|
21
|
+
"lw_procedure_compilations",
|
|
22
|
+
"lw_procedure_compilation_items",
|
|
23
|
+
"lw_memory_proposals",
|
|
24
|
+
"lw_proposal_evidence",
|
|
25
|
+
"lw_memory_curation_cases",
|
|
26
|
+
"lw_memory_curation_members",
|
|
27
|
+
"lw_database_maintenance_runs",
|
|
28
|
+
"lw_embedding_jobs",
|
|
29
|
+
"lw_memory_embeddings",
|
|
30
|
+
"lw_run_outcomes",
|
|
31
|
+
"lw_outcome_evidence",
|
|
32
|
+
"lw_retrieval_evaluations",
|
|
33
|
+
"lw_retrieval_feedback",
|
|
34
|
+
"lw_kingforge_v1_plan_projections",
|
|
35
|
+
"lw_kingforge_v1_lesson_projections",
|
|
36
|
+
"lw_kingforge_v1_projection_runs",
|
|
37
|
+
"lw_plan_traces",
|
|
38
|
+
"lw_plan_trace_steps",
|
|
39
|
+
"lw_procedure_evaluations",
|
|
40
|
+
"lw_procedure_feedback",
|
|
41
|
+
"lw_plan_genome_suggestions",
|
|
42
|
+
"lw_plan_genome_suggestion_traces",
|
|
43
|
+
"lw_plan_genome_motifs",
|
|
44
|
+
"lw_plan_genome_motif_evidence",
|
|
45
|
+
"lw_project_closeouts",
|
|
46
|
+
"lw_generalizations",
|
|
47
|
+
"lw_project_prune_receipts",
|
|
48
|
+
]
|
|
49
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""One closed JSON Schema for P02 socket requests and capture payloads."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from jsonschema import Draft202012Validator
|
|
8
|
+
|
|
9
|
+
from memoryking.contracts.canonical import canonical_bytes
|
|
10
|
+
from memoryking.domain.local import LocalError
|
|
11
|
+
|
|
12
|
+
SCHEMA = json.loads(Path(__file__).with_name("local_wire.schema.json").read_text())
|
|
13
|
+
VALIDATOR = Draft202012Validator(SCHEMA)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _operations(node: Any) -> set[str]:
|
|
17
|
+
found: set[str] = set()
|
|
18
|
+
if isinstance(node, dict):
|
|
19
|
+
operation = (
|
|
20
|
+
node.get("properties", {}).get("operation")
|
|
21
|
+
if isinstance(node.get("properties"), dict)
|
|
22
|
+
else None
|
|
23
|
+
)
|
|
24
|
+
if isinstance(operation, dict):
|
|
25
|
+
found.update(
|
|
26
|
+
[operation["const"]] if "const" in operation else operation.get("enum", [])
|
|
27
|
+
)
|
|
28
|
+
for value in node.values():
|
|
29
|
+
found |= _operations(value)
|
|
30
|
+
elif isinstance(node, list):
|
|
31
|
+
for value in node:
|
|
32
|
+
found |= _operations(value)
|
|
33
|
+
return found
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# The closed operation vocabulary of the wire schema: the only names metrics and trace
|
|
37
|
+
# lines may carry.
|
|
38
|
+
OPERATIONS = frozenset(_operations(SCHEMA))
|
|
39
|
+
CAPTURE = Draft202012Validator(SCHEMA["$defs"]["Capture"])
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def validate_capture(value: dict[str, Any]) -> None:
|
|
43
|
+
canonical_bytes(value)
|
|
44
|
+
if not CAPTURE.is_valid(value) or len(value["text"].encode()) > 65536:
|
|
45
|
+
raise LocalError("invalid_request")
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Explicitly installed, hash-pinned ONNX CPU inference; no downloads or remote code."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import importlib
|
|
7
|
+
import importlib.metadata
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
import threading
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from memoryking.contracts.canonical import canonical_hash
|
|
16
|
+
from memoryking.domain.embeddings import EmbeddingBatch, fingerprint, quantize, validate_inputs
|
|
17
|
+
from memoryking.domain.local import LocalError
|
|
18
|
+
|
|
19
|
+
MODEL = "minilm-l6-v2-onnx"
|
|
20
|
+
RERANKER = "ms-marco-minilm-l6-v2-onnx"
|
|
21
|
+
RERANK_PAIRS = 16 # query/text pairs scored per call
|
|
22
|
+
RERANK_TEXT_BYTES = 16384
|
|
23
|
+
RERANK_TOKENS = 256 # per pair; the text is cut, never the query
|
|
24
|
+
RERANK_THREADS = 4 # the reranker may use up to this many CPU threads
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def model_manifest(name: str = MODEL) -> dict[str, Any]:
|
|
28
|
+
value: dict[str, Any] = json.loads(
|
|
29
|
+
Path(__file__).with_name("models").joinpath(name + ".json").read_text()
|
|
30
|
+
)
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def model_files(directory: Path, manifest: dict[str, Any] | None = None) -> dict[str, bytes]:
|
|
35
|
+
manifest = manifest or model_manifest()
|
|
36
|
+
prefix = (
|
|
37
|
+
"reranker_model" if manifest.get("schema") == "reranker-model-v1" else "embedding_model"
|
|
38
|
+
)
|
|
39
|
+
result = {}
|
|
40
|
+
for file in manifest["files"]:
|
|
41
|
+
path = directory / file["path"]
|
|
42
|
+
if path.is_symlink() or not path.is_file() or path.stat().st_size != file["bytes"]:
|
|
43
|
+
raise LocalError(prefix + "_not_installed")
|
|
44
|
+
raw = path.read_bytes()
|
|
45
|
+
if hashlib.sha256(raw).hexdigest() != file["sha256"]:
|
|
46
|
+
raise LocalError(prefix + "_checksum_mismatch")
|
|
47
|
+
result[file["path"]] = raw
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _runtime(configuration: dict[str, Any]) -> tuple[Any, Any, Any]:
|
|
52
|
+
"""The pinned ONNX runtime, tokenizers and numpy, or the one error that names them."""
|
|
53
|
+
try:
|
|
54
|
+
for name, version in configuration["runtime"].items():
|
|
55
|
+
if importlib.metadata.version(name) != version:
|
|
56
|
+
raise LocalError("embedding_runtime_mismatch")
|
|
57
|
+
ort = importlib.import_module("onnxruntime")
|
|
58
|
+
tokenizers = importlib.import_module("tokenizers")
|
|
59
|
+
np = importlib.import_module("numpy")
|
|
60
|
+
except (ImportError, importlib.metadata.PackageNotFoundError) as exc:
|
|
61
|
+
raise LocalError("embedding_runtime_unavailable") from exc
|
|
62
|
+
return ort, tokenizers, np
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _session(ort: Any, data: bytes, threads: int = 1) -> Any:
|
|
66
|
+
options = ort.SessionOptions()
|
|
67
|
+
options.intra_op_num_threads = threads
|
|
68
|
+
options.inter_op_num_threads = 1
|
|
69
|
+
options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
|
70
|
+
options.log_severity_level = 3
|
|
71
|
+
# Load the exact checked bytes, not a path that can change after hashing.
|
|
72
|
+
return ort.InferenceSession(data, sess_options=options, providers=["CPUExecutionProvider"])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class LocalOnnxEmbedding:
|
|
76
|
+
"""One CPU thread, sequential inference, max 16 texts and 256 tokens each."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, directory: Path):
|
|
79
|
+
self.configuration = model_manifest()
|
|
80
|
+
self.fingerprint = fingerprint(self.configuration)
|
|
81
|
+
self.dimensions = self.configuration["dimensions"]
|
|
82
|
+
data = model_files(directory)
|
|
83
|
+
ort, tokenizers, self.np = _runtime(self.configuration)
|
|
84
|
+
self.lock = threading.Lock()
|
|
85
|
+
try:
|
|
86
|
+
self.session = _session(ort, data["onnx/model.onnx"])
|
|
87
|
+
self.tokenizer = tokenizers.Tokenizer.from_str(data["tokenizer.json"].decode())
|
|
88
|
+
self.tokenizer.enable_padding(pad_id=0, pad_token="[PAD]")
|
|
89
|
+
except Exception as exc:
|
|
90
|
+
raise LocalError("embedding_model_invalid") from exc
|
|
91
|
+
|
|
92
|
+
def embed(self, texts: list[str]) -> EmbeddingBatch:
|
|
93
|
+
validate_inputs(texts)
|
|
94
|
+
with self.lock:
|
|
95
|
+
try:
|
|
96
|
+
self.tokenizer.no_truncation()
|
|
97
|
+
full = self.tokenizer.encode_batch(texts)
|
|
98
|
+
lengths = [sum(item.attention_mask) for item in full]
|
|
99
|
+
self.tokenizer.enable_truncation(max_length=256)
|
|
100
|
+
tokens = self.tokenizer.encode_batch(texts)
|
|
101
|
+
values = {
|
|
102
|
+
"input_ids": [item.ids for item in tokens],
|
|
103
|
+
"attention_mask": [item.attention_mask for item in tokens],
|
|
104
|
+
"token_type_ids": [item.type_ids for item in tokens],
|
|
105
|
+
}
|
|
106
|
+
inputs = {
|
|
107
|
+
name: self.np.asarray(value, dtype=self.np.int64)
|
|
108
|
+
for name, value in values.items()
|
|
109
|
+
}
|
|
110
|
+
output = self.session.run(None, inputs)[0]
|
|
111
|
+
mask = inputs["attention_mask"][..., None]
|
|
112
|
+
pooled = (output * mask).sum(axis=1) / mask.sum(axis=1).clip(min=1)
|
|
113
|
+
batch = EmbeddingBatch(
|
|
114
|
+
self.fingerprint,
|
|
115
|
+
self.dimensions,
|
|
116
|
+
[quantize(vector.tolist(), self.dimensions) for vector in pooled],
|
|
117
|
+
[canonical_hash(text) for text in texts],
|
|
118
|
+
sum(sum(item.attention_mask) for item in tokens),
|
|
119
|
+
[length > 256 for length in lengths],
|
|
120
|
+
)
|
|
121
|
+
batch.validate(self.fingerprint, self.dimensions, texts)
|
|
122
|
+
return batch
|
|
123
|
+
except LocalError:
|
|
124
|
+
raise
|
|
125
|
+
except Exception as exc:
|
|
126
|
+
raise LocalError("embedding_provider_failure") from exc
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class LocalOnnxReranker:
|
|
130
|
+
"""A cross-encoder that scores a query against each candidate text on the CPU.
|
|
131
|
+
|
|
132
|
+
At most 16 pairs per call and 256 tokens per pair (the text is what gets cut, never
|
|
133
|
+
the query), on up to four threads, so a call stays well inside the five-second
|
|
134
|
+
release deadline of a request. The score is the model's relevance logit through a
|
|
135
|
+
sigmoid, rounded to millionths, so it is comparable across calls and replayable."""
|
|
136
|
+
|
|
137
|
+
def __init__(self, directory: Path):
|
|
138
|
+
self.configuration = model_manifest(RERANKER)
|
|
139
|
+
self.fingerprint = fingerprint(self.configuration)
|
|
140
|
+
data = model_files(directory, self.configuration)
|
|
141
|
+
ort, tokenizers, self.np = _runtime(self.configuration)
|
|
142
|
+
self.lock = threading.Lock()
|
|
143
|
+
try:
|
|
144
|
+
self.session = _session(
|
|
145
|
+
ort, data["onnx/model.onnx"], min(RERANK_THREADS, os.cpu_count() or 1)
|
|
146
|
+
)
|
|
147
|
+
self.inputs = {item.name for item in self.session.get_inputs()}
|
|
148
|
+
self.tokenizer = tokenizers.Tokenizer.from_str(data["tokenizer.json"].decode())
|
|
149
|
+
self.tokenizer.enable_padding(pad_id=0, pad_token="[PAD]")
|
|
150
|
+
self.tokenizer.enable_truncation(max_length=RERANK_TOKENS, strategy="only_second")
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
raise LocalError("reranker_model_invalid") from exc
|
|
153
|
+
|
|
154
|
+
def score(self, query: str, texts: list[str]) -> list[int]:
|
|
155
|
+
"""Relevance of each text to the query, in millionths, in the texts' order."""
|
|
156
|
+
if (
|
|
157
|
+
not isinstance(query, str)
|
|
158
|
+
or not query
|
|
159
|
+
or len(query.encode()) > RERANK_TEXT_BYTES
|
|
160
|
+
or not isinstance(texts, list)
|
|
161
|
+
or not 1 <= len(texts) <= RERANK_PAIRS
|
|
162
|
+
or any(
|
|
163
|
+
not isinstance(text, str) or not text or len(text.encode()) > RERANK_TEXT_BYTES
|
|
164
|
+
for text in texts
|
|
165
|
+
)
|
|
166
|
+
):
|
|
167
|
+
raise LocalError("reranker_input_limit")
|
|
168
|
+
with self.lock:
|
|
169
|
+
try:
|
|
170
|
+
encoded = self.tokenizer.encode_batch([(query, text) for text in texts])
|
|
171
|
+
values = {
|
|
172
|
+
"input_ids": [item.ids for item in encoded],
|
|
173
|
+
"attention_mask": [item.attention_mask for item in encoded],
|
|
174
|
+
"token_type_ids": [item.type_ids for item in encoded],
|
|
175
|
+
}
|
|
176
|
+
inputs = {
|
|
177
|
+
name: self.np.asarray(value, dtype=self.np.int64)
|
|
178
|
+
for name, value in values.items()
|
|
179
|
+
if name in self.inputs
|
|
180
|
+
}
|
|
181
|
+
logits = self.session.run(None, inputs)[0]
|
|
182
|
+
return [
|
|
183
|
+
int(round(1_000_000 / (1 + math.exp(-float(row[0] if len(row) else row)))))
|
|
184
|
+
for row in logits.reshape(len(texts), -1)
|
|
185
|
+
]
|
|
186
|
+
except LocalError:
|
|
187
|
+
raise
|
|
188
|
+
except Exception as exc:
|
|
189
|
+
raise LocalError("reranker_failure") from exc
|