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,510 @@
|
|
|
1
|
+
"""Opt-in owner dashboard; inspection and explicit domain review, never a scheduler."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import secrets
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from http.cookies import SimpleCookie
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from memoryking.adapters.local_store import uid
|
|
16
|
+
from memoryking.application.store_core import StoreCore
|
|
17
|
+
from memoryking.contracts.canonical import canonical_bytes, load_strict
|
|
18
|
+
from memoryking.domain.hints import hint
|
|
19
|
+
from memoryking.domain.http_status import http_status
|
|
20
|
+
from memoryking.domain.local import LocalError, Released
|
|
21
|
+
from memoryking.observability import failure, summarize, timings, trace, tracing
|
|
22
|
+
|
|
23
|
+
STATIC = Path(__file__).with_name("web")
|
|
24
|
+
ASSETS = {
|
|
25
|
+
"/": ("index.html", "text/html; charset=utf-8"),
|
|
26
|
+
"/app.css": ("app.css", "text/css"),
|
|
27
|
+
"/elephant.png": ("elephant.png", "image/png"),
|
|
28
|
+
**{
|
|
29
|
+
f"/{name}.js": (f"{name}.js", "text/javascript")
|
|
30
|
+
for name in ("app", "observatory", "graph", "graph-layout", "graph-worker", "brand", "team")
|
|
31
|
+
},
|
|
32
|
+
**{
|
|
33
|
+
f"/{name}.svg": (f"{name}.svg", "image/svg+xml")
|
|
34
|
+
for name in ("crown", "favicon", "wordmark", "crown-mono")
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
SAFE_HEADERS = {
|
|
38
|
+
"Content-Security-Policy": "default-src 'none'; script-src 'self'; worker-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
|
|
39
|
+
"X-Content-Type-Options": "nosniff",
|
|
40
|
+
"X-Frame-Options": "DENY",
|
|
41
|
+
"Referrer-Policy": "no-referrer",
|
|
42
|
+
"Cache-Control": "no-store",
|
|
43
|
+
"Cross-Origin-Resource-Policy": "same-origin",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def workspace_snapshot(at: int) -> dict[str, Any]:
|
|
48
|
+
"""The session's view of the store itself; every project view is loaded on demand."""
|
|
49
|
+
return {"schema_version": 1, "observed_ms": at, "fresh_until_ms": at + 15000}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Dashboard(ThreadingHTTPServer):
|
|
53
|
+
request_queue_size = 8
|
|
54
|
+
daemon_threads = True
|
|
55
|
+
|
|
56
|
+
def __init__(self, store: StoreCore, port: int = 0):
|
|
57
|
+
self.store = store
|
|
58
|
+
self.codes: dict[str, dict[str, Any]] = {}
|
|
59
|
+
self.sessions: dict[str, dict[str, Any]] = {}
|
|
60
|
+
super().__init__(("127.0.0.1", port), DashboardHandler)
|
|
61
|
+
self.origin = f"http://127.0.0.1:{self.server_port}"
|
|
62
|
+
self.host = f"127.0.0.1:{self.server_port}"
|
|
63
|
+
self.thread: threading.Thread | None = None
|
|
64
|
+
|
|
65
|
+
def issue(self, credential: str) -> dict[str, Any]:
|
|
66
|
+
with self.store.transaction() as decision:
|
|
67
|
+
who = self.store._auth(credential, "admin", "*", decision.evaluated_ms)
|
|
68
|
+
self.codes = {
|
|
69
|
+
k: v for k, v in self.codes.items() if v["expires"] > decision.evaluated_ms
|
|
70
|
+
}
|
|
71
|
+
if len(self.codes) >= 32:
|
|
72
|
+
raise LocalError("bootstrap_limit")
|
|
73
|
+
code = secrets.token_urlsafe(32)
|
|
74
|
+
self.codes[hashlib.sha256(code.encode()).hexdigest()] = {
|
|
75
|
+
"credential": credential,
|
|
76
|
+
"tenant": who["tenant"],
|
|
77
|
+
"expires": decision.evaluated_ms + 60000,
|
|
78
|
+
"epoch": self.epoch(who["tenant"]),
|
|
79
|
+
}
|
|
80
|
+
self.store._expose()
|
|
81
|
+
return {"url": self.origin, "code": code, "expires_ms": decision.evaluated_ms + 60000}
|
|
82
|
+
|
|
83
|
+
def epoch(self, tenant: str) -> int:
|
|
84
|
+
return int(
|
|
85
|
+
self.store.db.execute(
|
|
86
|
+
"SELECT policy_epoch FROM tenants WHERE tenant=?", (tenant,)
|
|
87
|
+
).fetchone()[0]
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def current(self, session: str, at: int) -> dict[str, Any]:
|
|
91
|
+
value = self.sessions.get(session)
|
|
92
|
+
if value is None or value["expires"] <= at:
|
|
93
|
+
raise LocalError("session_expired")
|
|
94
|
+
who = self.store._auth(value["credential"], "admin", "*", at)
|
|
95
|
+
if (
|
|
96
|
+
value["epoch"] != self.epoch(who["tenant"])
|
|
97
|
+
or value["incarnation"] != self.store.incarnation
|
|
98
|
+
):
|
|
99
|
+
self.sessions.pop(session, None)
|
|
100
|
+
raise LocalError("session_changed")
|
|
101
|
+
return value
|
|
102
|
+
|
|
103
|
+
def start(self) -> None:
|
|
104
|
+
self.thread = threading.Thread(target=self.serve_forever, daemon=True)
|
|
105
|
+
self.thread.start()
|
|
106
|
+
|
|
107
|
+
def stop(self) -> None:
|
|
108
|
+
if self.thread:
|
|
109
|
+
self.shutdown()
|
|
110
|
+
self.thread.join(timeout=5)
|
|
111
|
+
self.server_close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class DashboardHandler(BaseHTTPRequestHandler):
|
|
115
|
+
server: Dashboard
|
|
116
|
+
server_version = "MemoryKing"
|
|
117
|
+
|
|
118
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
119
|
+
pass # Never log bootstrap codes, cookies, paths or source content.
|
|
120
|
+
|
|
121
|
+
def setup(self) -> None:
|
|
122
|
+
super().setup()
|
|
123
|
+
self.connection.settimeout(5)
|
|
124
|
+
|
|
125
|
+
def send(
|
|
126
|
+
self,
|
|
127
|
+
status: int,
|
|
128
|
+
raw: bytes,
|
|
129
|
+
content_type: str = "application/json",
|
|
130
|
+
cookie: str | None = None,
|
|
131
|
+
access_receipt: str | None = None,
|
|
132
|
+
) -> None:
|
|
133
|
+
self.trace_status = status
|
|
134
|
+
self.send_response(status)
|
|
135
|
+
for name, value in SAFE_HEADERS.items():
|
|
136
|
+
self.send_header(name, value)
|
|
137
|
+
self.send_header("Content-Type", content_type)
|
|
138
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
139
|
+
if cookie:
|
|
140
|
+
self.send_header("Set-Cookie", cookie)
|
|
141
|
+
if access_receipt:
|
|
142
|
+
self.send_header("X-MemoryKing-Access-Receipt", access_receipt)
|
|
143
|
+
self.end_headers()
|
|
144
|
+
if self.command != "HEAD":
|
|
145
|
+
self.wfile.write(raw)
|
|
146
|
+
|
|
147
|
+
def guard(self) -> None:
|
|
148
|
+
if self.headers.get_all("Host", []) != [self.server.host]:
|
|
149
|
+
raise LocalError("host_rejected")
|
|
150
|
+
origins = self.headers.get_all("Origin", [])
|
|
151
|
+
if origins and origins != [self.server.origin]:
|
|
152
|
+
raise LocalError("origin_rejected")
|
|
153
|
+
public_asset = self.command in {"GET", "HEAD"} and self.path in ASSETS
|
|
154
|
+
if not public_asset and self.headers.get("Sec-Fetch-Site") not in {
|
|
155
|
+
None,
|
|
156
|
+
"same-origin",
|
|
157
|
+
"none",
|
|
158
|
+
}:
|
|
159
|
+
raise LocalError("origin_rejected")
|
|
160
|
+
agent_endpoint = self.path == "/api/v1/retrieval" and self.command == "POST"
|
|
161
|
+
if (
|
|
162
|
+
self.command not in {"GET", "HEAD"}
|
|
163
|
+
and not agent_endpoint
|
|
164
|
+
and origins != [self.server.origin]
|
|
165
|
+
):
|
|
166
|
+
raise LocalError("origin_required")
|
|
167
|
+
|
|
168
|
+
def session(self) -> str:
|
|
169
|
+
if len(self.headers.get_all("Cookie", [])) != 1:
|
|
170
|
+
raise LocalError("session_required")
|
|
171
|
+
cookie = SimpleCookie()
|
|
172
|
+
cookie.load(self.headers["Cookie"])
|
|
173
|
+
if "mk_session" not in cookie:
|
|
174
|
+
raise LocalError("session_required")
|
|
175
|
+
return cookie["mk_session"].value
|
|
176
|
+
|
|
177
|
+
def body(self, limit: int = 4096) -> dict[str, Any]:
|
|
178
|
+
if self.headers.get_all("Content-Type", []) != ["application/json"] or self.headers.get(
|
|
179
|
+
"Transfer-Encoding"
|
|
180
|
+
):
|
|
181
|
+
raise LocalError("invalid_request")
|
|
182
|
+
lengths = self.headers.get_all("Content-Length", [])
|
|
183
|
+
if len(lengths) != 1 or not lengths[0].isdigit() or not 1 <= int(lengths[0]) <= limit:
|
|
184
|
+
raise LocalError("invalid_request")
|
|
185
|
+
value = load_strict(self.rfile.read(int(lengths[0])))
|
|
186
|
+
if not isinstance(value, dict):
|
|
187
|
+
raise LocalError("invalid_request")
|
|
188
|
+
return value
|
|
189
|
+
|
|
190
|
+
def route(self) -> None:
|
|
191
|
+
self.guard()
|
|
192
|
+
dashboard, store = self.server, self.server.store
|
|
193
|
+
if self.path == "/metrics" and self.command == "GET":
|
|
194
|
+
from memoryking.observability_metrics import render
|
|
195
|
+
|
|
196
|
+
authorization = self.headers.get_all("Authorization", [])
|
|
197
|
+
if len(authorization) != 1 or not authorization[0].startswith("Bearer "):
|
|
198
|
+
raise LocalError("bearer_required")
|
|
199
|
+
if self.headers.get("Cookie"):
|
|
200
|
+
raise LocalError("mixed_authentication")
|
|
201
|
+
status = store.status(authorization[0][7:], "metrics")
|
|
202
|
+
self.send(200, render(store.counters, status).encode(), "text/plain; version=0.0.4")
|
|
203
|
+
return
|
|
204
|
+
if self.path == "/api/v1/retrieval" and self.command == "POST":
|
|
205
|
+
from memoryking.adapters.retrieval import Retrieval
|
|
206
|
+
|
|
207
|
+
authorization = self.headers.get_all("Authorization", [])
|
|
208
|
+
if len(authorization) != 1 or not authorization[0].startswith("Bearer "):
|
|
209
|
+
raise LocalError("bearer_required")
|
|
210
|
+
# Cookies never authorize agent endpoints; reject mixed contexts.
|
|
211
|
+
if self.headers.get_all("Cookie", []):
|
|
212
|
+
raise LocalError("mixed_authentication")
|
|
213
|
+
response = Retrieval(store).execute(authorization[0][7:], self.body(131072))
|
|
214
|
+
response.emit(lambda b: self.send(200, b, access_receipt=response.access_receipt))
|
|
215
|
+
return
|
|
216
|
+
if self.command in {"GET", "HEAD"} and self.path in ASSETS:
|
|
217
|
+
name, kind = ASSETS[self.path]
|
|
218
|
+
self.send(200, (STATIC / name).read_bytes(), kind)
|
|
219
|
+
return
|
|
220
|
+
if self.command == "OPTIONS":
|
|
221
|
+
if self.headers.get("Access-Control-Request-Method") not in {
|
|
222
|
+
"GET",
|
|
223
|
+
"HEAD",
|
|
224
|
+
"POST",
|
|
225
|
+
} or self.headers.get("Access-Control-Request-Headers", "").lower() not in {
|
|
226
|
+
"",
|
|
227
|
+
"content-type",
|
|
228
|
+
}:
|
|
229
|
+
raise LocalError("preflight_rejected")
|
|
230
|
+
self.send(204, b"")
|
|
231
|
+
return
|
|
232
|
+
if self.command == "POST" and self.path == "/api/bootstrap":
|
|
233
|
+
data = self.body()
|
|
234
|
+
if set(data) != {"code"} or not isinstance(data["code"], str):
|
|
235
|
+
raise LocalError("invalid_request")
|
|
236
|
+
with store.transaction() as decision:
|
|
237
|
+
code = dashboard.codes.pop(hashlib.sha256(data["code"].encode()).hexdigest(), None)
|
|
238
|
+
if code is None or code["expires"] <= decision.evaluated_ms:
|
|
239
|
+
raise LocalError("bootstrap_invalid")
|
|
240
|
+
who = store._auth(code["credential"], "admin", "*", decision.evaluated_ms)
|
|
241
|
+
if code["epoch"] != dashboard.epoch(who["tenant"]):
|
|
242
|
+
raise LocalError("bootstrap_invalid")
|
|
243
|
+
dashboard.sessions = {
|
|
244
|
+
k: v
|
|
245
|
+
for k, v in dashboard.sessions.items()
|
|
246
|
+
if v["expires"] > decision.evaluated_ms
|
|
247
|
+
}
|
|
248
|
+
if len(dashboard.sessions) >= 16:
|
|
249
|
+
raise LocalError("session_limit")
|
|
250
|
+
session = secrets.token_urlsafe(32)
|
|
251
|
+
dashboard.sessions[session] = {
|
|
252
|
+
**code,
|
|
253
|
+
"expires": decision.evaluated_ms + 900000,
|
|
254
|
+
"csrf": secrets.token_urlsafe(32),
|
|
255
|
+
"incarnation": store.incarnation,
|
|
256
|
+
}
|
|
257
|
+
raw = canonical_bytes({"ok": True})
|
|
258
|
+
store._expose()
|
|
259
|
+
Released(raw, decision, store.clock).emit(
|
|
260
|
+
lambda b: self.send(
|
|
261
|
+
200,
|
|
262
|
+
b,
|
|
263
|
+
cookie=f"mk_session={session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=900",
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
return
|
|
267
|
+
session = self.session()
|
|
268
|
+
if self.command == "POST" and self.path == "/api/admin/revoke":
|
|
269
|
+
from memoryking.adapters.local_store import identifier
|
|
270
|
+
|
|
271
|
+
data = self.body()
|
|
272
|
+
# The same expiry, policy-epoch and incarnation checks as every other route:
|
|
273
|
+
# a session made stale by an earlier revoke cannot keep revoking.
|
|
274
|
+
with store.transaction() as decision:
|
|
275
|
+
value = dashboard.current(session, decision.evaluated_ms)
|
|
276
|
+
if (
|
|
277
|
+
set(data) != {"csrf", "principal", "project"}
|
|
278
|
+
or not isinstance(data["csrf"], str)
|
|
279
|
+
or not secrets.compare_digest(data["csrf"], value["csrf"])
|
|
280
|
+
):
|
|
281
|
+
raise LocalError("csrf_rejected")
|
|
282
|
+
principal, project = identifier(data["principal"]), identifier(data["project"])
|
|
283
|
+
# A policy change advances the epoch, so every browser session, including this
|
|
284
|
+
# one, must sign in again afterwards; the reply says so.
|
|
285
|
+
store.revoke(value["credential"], principal, project)
|
|
286
|
+
self.send(
|
|
287
|
+
200,
|
|
288
|
+
canonical_bytes(
|
|
289
|
+
{"revoked": principal, "project": project, "sign_in_required": True}
|
|
290
|
+
),
|
|
291
|
+
)
|
|
292
|
+
return
|
|
293
|
+
if self.command == "POST" and self.path == "/api/command":
|
|
294
|
+
from memoryking.adapters.browser_commands import execute
|
|
295
|
+
|
|
296
|
+
if self.headers.get_all("Authorization", []):
|
|
297
|
+
raise LocalError("mixed_authentication")
|
|
298
|
+
|
|
299
|
+
def current_session() -> dict[str, Any]:
|
|
300
|
+
value = dashboard.sessions.get(session)
|
|
301
|
+
if value is None:
|
|
302
|
+
raise LocalError("session_expired")
|
|
303
|
+
return value
|
|
304
|
+
|
|
305
|
+
response = execute(store, current_session(), self.body(131072), current_session)
|
|
306
|
+
response.emit(lambda b: self.send(200, b, access_receipt=response.access_receipt))
|
|
307
|
+
return
|
|
308
|
+
with store.transaction() as decision:
|
|
309
|
+
value = dashboard.current(session, decision.evaluated_ms)
|
|
310
|
+
cookie = None
|
|
311
|
+
content_type = "application/json"
|
|
312
|
+
if self.command == "POST" and self.path == "/api/logout":
|
|
313
|
+
data = self.body()
|
|
314
|
+
if (
|
|
315
|
+
set(data) != {"csrf"}
|
|
316
|
+
or not isinstance(data["csrf"], str)
|
|
317
|
+
or not secrets.compare_digest(data["csrf"], value["csrf"])
|
|
318
|
+
):
|
|
319
|
+
raise LocalError("csrf_rejected")
|
|
320
|
+
dashboard.sessions.pop(session, None)
|
|
321
|
+
raw = b'{"ok":true}'
|
|
322
|
+
cookie = "mk_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0"
|
|
323
|
+
elif self.command in {"GET", "HEAD"} and self.path == "/api/snapshot":
|
|
324
|
+
result = workspace_snapshot(decision.evaluated_ms)
|
|
325
|
+
result.update(
|
|
326
|
+
csrf=value["csrf"],
|
|
327
|
+
incarnation=store.incarnation,
|
|
328
|
+
principal=store._decode(value["credential"], "credential")["principal"],
|
|
329
|
+
tenant=value["tenant"],
|
|
330
|
+
authorization_epoch=dashboard.epoch(value["tenant"]),
|
|
331
|
+
capacity=store._capacity(value["tenant"]),
|
|
332
|
+
)
|
|
333
|
+
raw = canonical_bytes(result)
|
|
334
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith("/api/timeline/"):
|
|
335
|
+
from memoryking.adapters.local_store import identifier
|
|
336
|
+
from memoryking.adapters.timeline import timeline
|
|
337
|
+
|
|
338
|
+
parts = self.path.split("/")
|
|
339
|
+
if len(parts) not in {4, 5}:
|
|
340
|
+
raise LocalError("invalid_request")
|
|
341
|
+
project = identifier(parts[3])
|
|
342
|
+
before = None
|
|
343
|
+
if len(parts) == 5:
|
|
344
|
+
if not parts[4].isdigit():
|
|
345
|
+
raise LocalError("invalid_request")
|
|
346
|
+
before = int(parts[4])
|
|
347
|
+
who = store._auth(value["credential"], "read", project, decision.evaluated_ms)
|
|
348
|
+
raw = canonical_bytes(timeline(store, who, project, before=before))
|
|
349
|
+
elif self.command in {"GET", "HEAD"} and self.path == "/api/projects":
|
|
350
|
+
from memoryking.adapters.projects import visible_projects
|
|
351
|
+
|
|
352
|
+
raw = canonical_bytes(
|
|
353
|
+
{"items": visible_projects(store, value["credential"], decision.evaluated_ms)}
|
|
354
|
+
)
|
|
355
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith("/api/plans/"):
|
|
356
|
+
from memoryking.adapters.plan_dashboard import read as read_plans
|
|
357
|
+
|
|
358
|
+
raw = canonical_bytes(
|
|
359
|
+
read_plans(store, value["credential"], self.path, decision.evaluated_ms)
|
|
360
|
+
)
|
|
361
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith("/api/execution/"):
|
|
362
|
+
from memoryking.adapters.execution import Execution
|
|
363
|
+
from memoryking.adapters.local_store import identifier
|
|
364
|
+
|
|
365
|
+
project = self.path.removeprefix("/api/execution/")
|
|
366
|
+
identifier(project)
|
|
367
|
+
who = store._auth(value["credential"], "read", project, decision.evaluated_ms)
|
|
368
|
+
raw = canonical_bytes(
|
|
369
|
+
Execution(store).snapshot(who, project, decision.evaluated_ms)
|
|
370
|
+
)
|
|
371
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith(
|
|
372
|
+
("/api/receipts/", "/api/receipt/")
|
|
373
|
+
):
|
|
374
|
+
from memoryking.adapters.local_store import identifier
|
|
375
|
+
from memoryking.adapters.retrieval import Retrieval
|
|
376
|
+
|
|
377
|
+
parts = self.path.split("/")
|
|
378
|
+
if len(parts) not in {4, 5}:
|
|
379
|
+
raise LocalError("invalid_request")
|
|
380
|
+
project = parts[3]
|
|
381
|
+
identifier(project)
|
|
382
|
+
who = store._auth(value["credential"], "read", project, decision.evaluated_ms)
|
|
383
|
+
retrieval = Retrieval(store)
|
|
384
|
+
if parts[2] == "receipts" and len(parts) == 4:
|
|
385
|
+
raw = canonical_bytes(
|
|
386
|
+
{"items": retrieval.list_receipts(who, project, decision.evaluated_ms)}
|
|
387
|
+
)
|
|
388
|
+
elif parts[2] == "receipt" and len(parts) == 5:
|
|
389
|
+
identifier(parts[4])
|
|
390
|
+
row = retrieval._artifact(who, project, parts[4], decision.evaluated_ms)
|
|
391
|
+
raw = canonical_bytes(
|
|
392
|
+
{
|
|
393
|
+
"receipt": row["id"],
|
|
394
|
+
"rendered_hash": row["body_hash"],
|
|
395
|
+
"expires_ms": row["expires"],
|
|
396
|
+
"diagnostics": json.loads(row["diagnostics"]),
|
|
397
|
+
}
|
|
398
|
+
)
|
|
399
|
+
else:
|
|
400
|
+
raise LocalError("route_unavailable")
|
|
401
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith("/api/activity/"):
|
|
402
|
+
from memoryking.adapters.local_store import identifier
|
|
403
|
+
from memoryking.adapters.team import activity
|
|
404
|
+
|
|
405
|
+
parts = self.path.split("/")
|
|
406
|
+
if len(parts) not in {4, 5} or (len(parts) == 5 and not parts[4].isdigit()):
|
|
407
|
+
raise LocalError("invalid_request")
|
|
408
|
+
project = identifier(parts[3])
|
|
409
|
+
who = store._auth(value["credential"], "read", project, decision.evaluated_ms)
|
|
410
|
+
raw = canonical_bytes(
|
|
411
|
+
activity(
|
|
412
|
+
store,
|
|
413
|
+
who,
|
|
414
|
+
project,
|
|
415
|
+
decision.evaluated_ms,
|
|
416
|
+
days=int(parts[4]) if len(parts) == 5 else 30,
|
|
417
|
+
)
|
|
418
|
+
)
|
|
419
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith("/api/export/"):
|
|
420
|
+
from memoryking.adapters.local_store import identifier
|
|
421
|
+
from memoryking.adapters.team import export
|
|
422
|
+
|
|
423
|
+
project = identifier(self.path.removeprefix("/api/export/"))
|
|
424
|
+
who = store._auth(value["credential"], "admin", "*", decision.evaluated_ms)
|
|
425
|
+
store._auth(value["credential"], "read", project, decision.evaluated_ms)
|
|
426
|
+
raw = canonical_bytes(export(store, who, project, decision.evaluated_ms))
|
|
427
|
+
elif self.command in {"GET", "HEAD"} and self.path.startswith("/api/citations/"):
|
|
428
|
+
from urllib.parse import unquote
|
|
429
|
+
|
|
430
|
+
from memoryking.adapters.local_store import identifier
|
|
431
|
+
from memoryking.adapters.retrieval import Retrieval
|
|
432
|
+
|
|
433
|
+
parts = self.path.split("/")
|
|
434
|
+
if len(parts) != 5:
|
|
435
|
+
raise LocalError("invalid_request")
|
|
436
|
+
project = identifier(parts[3])
|
|
437
|
+
who = store._auth(value["credential"], "read", project, decision.evaluated_ms)
|
|
438
|
+
raw = canonical_bytes(
|
|
439
|
+
{
|
|
440
|
+
"node": unquote(parts[4]),
|
|
441
|
+
"items": Retrieval(store).list_citations(
|
|
442
|
+
who, project, unquote(parts[4]), decision.evaluated_ms
|
|
443
|
+
),
|
|
444
|
+
}
|
|
445
|
+
)
|
|
446
|
+
else:
|
|
447
|
+
raise LocalError("route_unavailable")
|
|
448
|
+
who = store._decode(value["credential"], "credential")
|
|
449
|
+
epochs = store.db.execute(
|
|
450
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
451
|
+
).fetchone()
|
|
452
|
+
store.db.execute(
|
|
453
|
+
"INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
454
|
+
(
|
|
455
|
+
who["tenant"],
|
|
456
|
+
uid("rcpt"),
|
|
457
|
+
who["principal"],
|
|
458
|
+
store.incarnation,
|
|
459
|
+
decision.evaluated_ms,
|
|
460
|
+
decision.deadline_ms,
|
|
461
|
+
*epochs,
|
|
462
|
+
hashlib.sha256(raw).hexdigest(),
|
|
463
|
+
"[]",
|
|
464
|
+
),
|
|
465
|
+
)
|
|
466
|
+
store.fault("after_validation")
|
|
467
|
+
store._expose()
|
|
468
|
+
Released(raw, decision, store.clock).emit(lambda b: self.send(200, b, content_type, cookie))
|
|
469
|
+
|
|
470
|
+
def do_GET(self) -> None:
|
|
471
|
+
if not tracing():
|
|
472
|
+
self._serve()
|
|
473
|
+
return
|
|
474
|
+
started = time.monotonic()
|
|
475
|
+
self.trace_status = 0
|
|
476
|
+
spans = timings(self.server.store)
|
|
477
|
+
try:
|
|
478
|
+
self._serve()
|
|
479
|
+
finally:
|
|
480
|
+
self.server.store.timings.items = None
|
|
481
|
+
trace(
|
|
482
|
+
"dashboard",
|
|
483
|
+
method=self.command,
|
|
484
|
+
route="/".join(self.path.split("?")[0].split("/")[:3]),
|
|
485
|
+
status=self.trace_status,
|
|
486
|
+
**summarize((time.monotonic() - started) * 1000, spans),
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
def _serve(self) -> None:
|
|
490
|
+
try:
|
|
491
|
+
self.route()
|
|
492
|
+
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
|
493
|
+
return
|
|
494
|
+
except LocalError as exc:
|
|
495
|
+
self.send(
|
|
496
|
+
http_status(exc.code, 403),
|
|
497
|
+
canonical_bytes({"error": exc.code, "hint": hint(exc.code)}),
|
|
498
|
+
)
|
|
499
|
+
except Exception as exc:
|
|
500
|
+
request_id = failure("dashboard", exc)
|
|
501
|
+
self.send(
|
|
502
|
+
503, canonical_bytes({"error": "dashboard_unavailable", "request_id": request_id})
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
do_HEAD = do_GET
|
|
506
|
+
do_POST = do_GET
|
|
507
|
+
do_OPTIONS = do_GET
|
|
508
|
+
do_PUT = do_GET
|
|
509
|
+
do_DELETE = do_GET
|
|
510
|
+
do_PATCH = do_GET
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Exact search only after current tenant/project/audience/source eligibility."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from memoryking.application.store_core import StoreCore
|
|
9
|
+
from memoryking.contracts.canonical import canonical_hash
|
|
10
|
+
from memoryking.domain.embeddings import cosine_ppm, validate_vector
|
|
11
|
+
from memoryking.domain.local import LocalError
|
|
12
|
+
|
|
13
|
+
SCAN_LIMIT = 10000
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def search(
|
|
17
|
+
store: StoreCore, who: dict[str, Any], args: dict[str, Any], recorded: int, target: int
|
|
18
|
+
) -> dict[str, Any]:
|
|
19
|
+
request = args.get("dense")
|
|
20
|
+
result: dict[str, Any] = {
|
|
21
|
+
"availability": "unavailable",
|
|
22
|
+
"position": None,
|
|
23
|
+
"scores": {},
|
|
24
|
+
"method": "authorized_exact_cosine_v1",
|
|
25
|
+
"candidate_limit_reached": False,
|
|
26
|
+
}
|
|
27
|
+
if request is None:
|
|
28
|
+
return result
|
|
29
|
+
if request["query_hash"] != canonical_hash(args["query"]):
|
|
30
|
+
raise LocalError("embedding_query_mismatch")
|
|
31
|
+
row = store.db.execute(
|
|
32
|
+
"SELECT * FROM embedding_partitions WHERE tenant=? AND project=? AND fingerprint=?",
|
|
33
|
+
(who["tenant"], args["project"], request["fingerprint"]),
|
|
34
|
+
).fetchone()
|
|
35
|
+
if row is None or row["state"] != "experimental" or row["incarnation"] != store.incarnation:
|
|
36
|
+
return result
|
|
37
|
+
validate_vector(request["vector"], row["dimensions"])
|
|
38
|
+
result.update(
|
|
39
|
+
position=row["frontier"],
|
|
40
|
+
fingerprint=row["fingerprint"],
|
|
41
|
+
generation=row["generation"],
|
|
42
|
+
availability="ready" if row["frontier"] >= target else "indexing",
|
|
43
|
+
query_embedding_origin="caller_supplied",
|
|
44
|
+
indexed_kind="observation_prefix",
|
|
45
|
+
input_byte_limit=16384,
|
|
46
|
+
input_token_limit=256,
|
|
47
|
+
)
|
|
48
|
+
if args.get("freshness", "any") == "attested":
|
|
49
|
+
result["availability"] = "unsupported_freshness"
|
|
50
|
+
return result
|
|
51
|
+
# Eligibility is inside the storage query, before the scan or candidate cap.
|
|
52
|
+
# An old or purged revision cannot be resurrected by an index entry.
|
|
53
|
+
statement = "SELECT i.observation,i.vector_json FROM embedding_items i JOIN observations o ON i.tenant=o.tenant AND i.observation=o.id AND i.project=o.project AND i.source_revision=o.revision AND i.blob_hash=o.blob WHERE i.tenant=? AND i.project=? AND i.fingerprint=? AND i.generation=? AND i.incarnation=? AND o.deleted=0 AND o.position<=? AND (o.readers='null' OR EXISTS(SELECT 1 FROM json_each(o.readers) WHERE value=?)) ORDER BY i.observation LIMIT ?"
|
|
54
|
+
parameters = (
|
|
55
|
+
who["tenant"],
|
|
56
|
+
args["project"],
|
|
57
|
+
row["fingerprint"],
|
|
58
|
+
row["generation"],
|
|
59
|
+
store.incarnation,
|
|
60
|
+
recorded,
|
|
61
|
+
who["principal"],
|
|
62
|
+
SCAN_LIMIT + 1,
|
|
63
|
+
)
|
|
64
|
+
if request.get("engine", "python_exact") == "pgvector_exact":
|
|
65
|
+
native = getattr(store, "dense_exact", None)
|
|
66
|
+
scored = native(statement, parameters, request, SCAN_LIMIT) if native else None
|
|
67
|
+
result["method"] = "pgvector_0_8_7_exact_cosine_v1"
|
|
68
|
+
if scored is None:
|
|
69
|
+
result["availability"] = "engine_unavailable"
|
|
70
|
+
else:
|
|
71
|
+
result.update(scored)
|
|
72
|
+
return result
|
|
73
|
+
rows = store.db.execute(statement, parameters).fetchall()
|
|
74
|
+
if len(rows) > SCAN_LIMIT:
|
|
75
|
+
result.update(availability="scan_limit", candidate_limit_reached=True)
|
|
76
|
+
return result
|
|
77
|
+
ranked = []
|
|
78
|
+
for item in rows:
|
|
79
|
+
score = cosine_ppm(request["vector"], json.loads(item["vector_json"]))
|
|
80
|
+
if score >= request.get("minimum_similarity_ppm", 200000):
|
|
81
|
+
ranked.append((score, item["observation"]))
|
|
82
|
+
ranked.sort(key=lambda item: (-item[0], item[1]))
|
|
83
|
+
result["scores"] = {reference: score for score, reference in ranked[:256]}
|
|
84
|
+
result["candidate_limit_reached"] = len(ranked) > 256
|
|
85
|
+
result["eligible_vectors"] = len(rows)
|
|
86
|
+
return result
|