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.
Files changed (179) hide show
  1. memoryking/__init__.py +3 -0
  2. memoryking/__main__.py +1328 -0
  3. memoryking/adapters/__init__.py +1 -0
  4. memoryking/adapters/adapter_state.py +242 -0
  5. memoryking/adapters/anchor_schema.sql +7 -0
  6. memoryking/adapters/atlas.py +441 -0
  7. memoryking/adapters/browser_commands.py +125 -0
  8. memoryking/adapters/dashboard.py +510 -0
  9. memoryking/adapters/dense_search.py +86 -0
  10. memoryking/adapters/egress_policy.py +244 -0
  11. memoryking/adapters/egress_schema.sql +13 -0
  12. memoryking/adapters/embedding.schema.json +302 -0
  13. memoryking/adapters/embedding_store.py +469 -0
  14. memoryking/adapters/execution.py +369 -0
  15. memoryking/adapters/experience.py +423 -0
  16. memoryking/adapters/experience.schema.json +1508 -0
  17. memoryking/adapters/experience_records.py +239 -0
  18. memoryking/adapters/experience_schema.sql +23 -0
  19. memoryking/adapters/handoff.py +494 -0
  20. memoryking/adapters/handoff.schema.json +299 -0
  21. memoryking/adapters/handoff_schema.sql +17 -0
  22. memoryking/adapters/index_schema.sql +11 -0
  23. memoryking/adapters/inference.py +454 -0
  24. memoryking/adapters/inference.schema.json +541 -0
  25. memoryking/adapters/inspection.py +1128 -0
  26. memoryking/adapters/inspection.schema.json +568 -0
  27. memoryking/adapters/knowledge.schema.json +633 -0
  28. memoryking/adapters/knowledge_schema.sql +37 -0
  29. memoryking/adapters/knowledge_store.py +800 -0
  30. memoryking/adapters/legacy_snapshot.py +358 -0
  31. memoryking/adapters/legacy_tables.py +49 -0
  32. memoryking/adapters/local_contract.py +45 -0
  33. memoryking/adapters/local_embeddings.py +189 -0
  34. memoryking/adapters/local_files.py +242 -0
  35. memoryking/adapters/local_ipc.py +258 -0
  36. memoryking/adapters/local_schema.sql +44 -0
  37. memoryking/adapters/local_store.py +632 -0
  38. memoryking/adapters/local_wire.schema.json +7672 -0
  39. memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
  40. memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
  41. memoryking/adapters/optional_schema.sql +43 -0
  42. memoryking/adapters/plan_dashboard.py +51 -0
  43. memoryking/adapters/plans.py +253 -0
  44. memoryking/adapters/postgres_admin.py +300 -0
  45. memoryking/adapters/postgres_anchor_schema.sql +9 -0
  46. memoryking/adapters/postgres_counter.sql +14 -0
  47. memoryking/adapters/postgres_egress_schema.sql +15 -0
  48. memoryking/adapters/postgres_experience_schema.sql +39 -0
  49. memoryking/adapters/postgres_index_schema.sql +7 -0
  50. memoryking/adapters/postgres_optional_schema.sql +71 -0
  51. memoryking/adapters/postgres_pool.py +77 -0
  52. memoryking/adapters/postgres_recovery.py +525 -0
  53. memoryking/adapters/postgres_schema.sql +365 -0
  54. memoryking/adapters/postgres_sql.py +102 -0
  55. memoryking/adapters/postgres_store.py +428 -0
  56. memoryking/adapters/postgres_summary_schema.sql +12 -0
  57. memoryking/adapters/postgres_trust_schema.sql +20 -0
  58. memoryking/adapters/processing.schema.json +471 -0
  59. memoryking/adapters/processing_store.py +346 -0
  60. memoryking/adapters/projects.py +83 -0
  61. memoryking/adapters/proposals.py +238 -0
  62. memoryking/adapters/ranking.py +315 -0
  63. memoryking/adapters/repository.schema.json +664 -0
  64. memoryking/adapters/repository_git.py +264 -0
  65. memoryking/adapters/repository_schema.sql +25 -0
  66. memoryking/adapters/repository_store.py +960 -0
  67. memoryking/adapters/retrieval.py +1285 -0
  68. memoryking/adapters/retrieval.schema.json +553 -0
  69. memoryking/adapters/retrieval_schema.sql +10 -0
  70. memoryking/adapters/shared_control.py +40 -0
  71. memoryking/adapters/shared_dashboard.py +636 -0
  72. memoryking/adapters/shared_gateway.py +63 -0
  73. memoryking/adapters/shared_http.py +216 -0
  74. memoryking/adapters/shared_mcp.py +159 -0
  75. memoryking/adapters/shared_service.py +124 -0
  76. memoryking/adapters/stdio.py +193 -0
  77. memoryking/adapters/stdio.tools.json +6776 -0
  78. memoryking/adapters/summary_schema.sql +10 -0
  79. memoryking/adapters/team.py +253 -0
  80. memoryking/adapters/timeline.py +80 -0
  81. memoryking/adapters/token_count.py +55 -0
  82. memoryking/adapters/tokenizers/LICENSE +21 -0
  83. memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
  84. memoryking/adapters/trust.py +123 -0
  85. memoryking/adapters/trust_schema.sql +13 -0
  86. memoryking/adapters/web/app.css +1251 -0
  87. memoryking/adapters/web/app.js +907 -0
  88. memoryking/adapters/web/brand.js +44 -0
  89. memoryking/adapters/web/crown-mono.svg +1 -0
  90. memoryking/adapters/web/crown.svg +8 -0
  91. memoryking/adapters/web/elephant.png +0 -0
  92. memoryking/adapters/web/favicon.svg +8 -0
  93. memoryking/adapters/web/graph-layout.js +52 -0
  94. memoryking/adapters/web/graph-worker.js +10 -0
  95. memoryking/adapters/web/graph.js +570 -0
  96. memoryking/adapters/web/index.html +208 -0
  97. memoryking/adapters/web/observatory.js +1208 -0
  98. memoryking/adapters/web/team.js +151 -0
  99. memoryking/adapters/web/wordmark.svg +1 -0
  100. memoryking/adapters/working.py +971 -0
  101. memoryking/adapters/working.schema.json +1717 -0
  102. memoryking/adapters/working_schema.sql +24 -0
  103. memoryking/application/__init__.py +1 -0
  104. memoryking/application/conformance.py +50 -0
  105. memoryking/application/legacy_import.py +337 -0
  106. memoryking/application/local_port.py +9 -0
  107. memoryking/application/storage.py +117 -0
  108. memoryking/application/store_core.py +1292 -0
  109. memoryking/backups.py +131 -0
  110. memoryking/contracts/__init__.py +6 -0
  111. memoryking/contracts/__main__.py +20 -0
  112. memoryking/contracts/canonical.py +88 -0
  113. memoryking/contracts/embedding.schema.json +302 -0
  114. memoryking/contracts/embedding_generated.py +65 -0
  115. memoryking/contracts/experience.schema.json +1508 -0
  116. memoryking/contracts/experience_generated.py +239 -0
  117. memoryking/contracts/generated.py +122 -0
  118. memoryking/contracts/handoff.schema.json +299 -0
  119. memoryking/contracts/handoff_generated.py +69 -0
  120. memoryking/contracts/inference.schema.json +541 -0
  121. memoryking/contracts/inference_generated.py +106 -0
  122. memoryking/contracts/processing.schema.json +471 -0
  123. memoryking/contracts/processing_generated.py +82 -0
  124. memoryking/contracts/py.typed +0 -0
  125. memoryking/contracts/repository.schema.json +664 -0
  126. memoryking/contracts/repository_generated.py +144 -0
  127. memoryking/contracts/retrieval.schema.json +553 -0
  128. memoryking/contracts/retrieval_generated.py +110 -0
  129. memoryking/contracts/schema.json +696 -0
  130. memoryking/contracts/validation.py +92 -0
  131. memoryking/contracts/working.schema.json +1717 -0
  132. memoryking/contracts/working_generated.py +291 -0
  133. memoryking/domain/__init__.py +1 -0
  134. memoryking/domain/anchors.py +97 -0
  135. memoryking/domain/briefing.py +108 -0
  136. memoryking/domain/briefing_text.py +222 -0
  137. memoryking/domain/checkpoint.py +118 -0
  138. memoryking/domain/compression.py +64 -0
  139. memoryking/domain/delta.py +129 -0
  140. memoryking/domain/embeddings.py +90 -0
  141. memoryking/domain/hints.py +465 -0
  142. memoryking/domain/http_status.py +45 -0
  143. memoryking/domain/learning.py +62 -0
  144. memoryking/domain/local.py +65 -0
  145. memoryking/domain/plans.py +140 -0
  146. memoryking/domain/repository.py +118 -0
  147. memoryking/domain/selectors.py +356 -0
  148. memoryking/domain/summary.py +88 -0
  149. memoryking/domain/usage.py +163 -0
  150. memoryking/embedding_loop.py +98 -0
  151. memoryking/embedding_worker.py +131 -0
  152. memoryking/harness.py +882 -0
  153. memoryking/harness_context.py +376 -0
  154. memoryking/hooks.py +171 -0
  155. memoryking/host_hooks.py +454 -0
  156. memoryking/lean.py +352 -0
  157. memoryking/memory_tool.py +776 -0
  158. memoryking/migration.py +194 -0
  159. memoryking/model_install.py +78 -0
  160. memoryking/observability.py +101 -0
  161. memoryking/observability_metrics.py +100 -0
  162. memoryking/profiles.py +150 -0
  163. memoryking/providers.py +330 -0
  164. memoryking/py.typed +0 -0
  165. memoryking/pytest_plugin.py +69 -0
  166. memoryking/reference_agent.py +152 -0
  167. memoryking/repository_worker.py +57 -0
  168. memoryking/resume_adapter.py +154 -0
  169. memoryking/sdk.py +302 -0
  170. memoryking/shared.py +301 -0
  171. memoryking/shared_sdk.py +101 -0
  172. memoryking/vault.py +176 -0
  173. memoryking-0.1.0.dist-info/METADATA +157 -0
  174. memoryking-0.1.0.dist-info/RECORD +179 -0
  175. memoryking-0.1.0.dist-info/WHEEL +5 -0
  176. memoryking-0.1.0.dist-info/entry_points.txt +7 -0
  177. memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
  178. memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
  179. memoryking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,242 @@
1
+ """Private files, process ownership, authenticated tokens and durable control state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import fcntl
7
+ import hashlib
8
+ import hmac
9
+ import os
10
+ import secrets
11
+ import stat
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from memoryking.contracts.canonical import canonical_bytes, load_strict
16
+ from memoryking.domain.local import LocalError
17
+
18
+ # Largest signed journal line accepted on write and read. It covers every journaled
19
+ # action (bindings are bounded at 128 KiB canonical, selectors at 16 KiB) with headroom.
20
+ JOURNAL_RECORD_LIMIT = 262144
21
+
22
+
23
+ def sync_dir(path: Path) -> None:
24
+ fd = os.open(path, os.O_RDONLY)
25
+ try:
26
+ os.fsync(fd)
27
+ finally:
28
+ os.close(fd)
29
+
30
+
31
+ def private_dir(path: Path, *, create: bool = False) -> None:
32
+ if create and not path.exists():
33
+ if not path.parent.exists():
34
+ private_dir(path.parent, create=True)
35
+ path.mkdir(mode=0o700)
36
+ sync_dir(path.parent)
37
+ info = path.lstat()
38
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
39
+ raise LocalError("unsafe_permissions")
40
+
41
+
42
+ def private_file(path: Path) -> None:
43
+ info = path.lstat()
44
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
45
+ raise LocalError("unsafe_permissions")
46
+
47
+
48
+ def atomic(path: Path, data: bytes) -> None:
49
+ if path.exists() or path.is_symlink():
50
+ private_file(path)
51
+ temporary = path.with_name(".stage-" + secrets.token_hex(12))
52
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
53
+ try:
54
+ with os.fdopen(fd, "wb") as stream:
55
+ stream.write(data)
56
+ stream.flush()
57
+ os.fsync(stream.fileno())
58
+ os.replace(temporary, path)
59
+ sync_dir(path.parent)
60
+ finally:
61
+ temporary.unlink(missing_ok=True)
62
+
63
+
64
+ class Ownership:
65
+ def __init__(self, directory: Path):
66
+ self.pid = os.getpid()
67
+ path = directory / "owner.lock"
68
+ self.fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
69
+ try:
70
+ private_file(path)
71
+ fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
72
+ except Exception as exc:
73
+ os.close(self.fd)
74
+ raise LocalError("owner_busy_or_unsafe") from exc
75
+
76
+ def check(self) -> None:
77
+ if self.pid != os.getpid():
78
+ raise LocalError("inherited_owner_forbidden")
79
+ if self.fd < 0:
80
+ raise LocalError("owner_closed")
81
+
82
+ def close(self) -> None:
83
+ if self.fd >= 0:
84
+ fd, self.fd = self.fd, -1
85
+ os.close(fd)
86
+
87
+
88
+ class Control:
89
+ """Not part of content backups. Same-UID filesystem compromise is out of scope."""
90
+
91
+ def __init__(self, path: Path):
92
+ self.path = path
93
+ private_file(path / "identity.json")
94
+ identity = load_strict((path / "identity.json").read_bytes())
95
+ self.store: str = identity["store"]
96
+ self.key = bytes.fromhex(identity["key"])
97
+ # Verified journal prefix: (byte length, running sha256, records, previous line hash).
98
+ self._verified: tuple[int, Any, list[dict[str, Any]], str] | None = None
99
+ # Byte offset of an unacknowledged torn final line, discarded on the next append.
100
+ self.torn_tail: int | None = None
101
+
102
+ def sign(self, body: dict[str, Any]) -> str:
103
+ raw = canonical_bytes(body)
104
+ return (
105
+ base64.urlsafe_b64encode(raw).decode().rstrip("=")
106
+ + "."
107
+ + hmac.new(self.key, raw, hashlib.sha256).hexdigest()
108
+ )
109
+
110
+ def verify(self, token: str) -> dict[str, Any]:
111
+ return self._verify(token, 8192)
112
+
113
+ def verify_document(self, path: Path) -> dict[str, Any]:
114
+ """Larger signed operator archives; never accepts an HTTP credential."""
115
+ private_file(path)
116
+ limit = 16 * 1024 * 1024
117
+ with path.open("rb") as stream:
118
+ raw = stream.read(limit + 1)
119
+ try:
120
+ return self._verify(raw.decode("utf-8"), limit)
121
+ except UnicodeError as exc:
122
+ raise LocalError("invalid_token") from exc
123
+
124
+ def _verify(self, token: str, limit: int) -> dict[str, Any]:
125
+ try:
126
+ if len(token) > limit:
127
+ raise ValueError
128
+ encoded, digest = token.split(".")
129
+ raw = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))
130
+ if not hmac.compare_digest(hmac.new(self.key, raw, hashlib.sha256).hexdigest(), digest):
131
+ raise ValueError
132
+ body = load_strict(raw)
133
+ if not isinstance(body, dict):
134
+ raise ValueError
135
+ return body
136
+ except Exception as exc:
137
+ raise LocalError("invalid_token") from exc
138
+
139
+ def read_anchor(self) -> dict[str, Any]:
140
+ try:
141
+ private_file(self.path / "anchor")
142
+ return self.verify((self.path / "anchor").read_text())
143
+ except Exception as exc:
144
+ raise LocalError("recovery_required") from exc
145
+
146
+ def anchor(self, value: dict[str, Any]) -> None:
147
+ atomic(self.path / "anchor", self.sign(value).encode())
148
+
149
+ def journal(self, anchor: dict[str, Any]) -> list[dict[str, Any]]:
150
+ """Verify the hash-chained journal; only an unanchored torn final line is tolerated."""
151
+ private_file(self.path / "journal")
152
+ data = (self.path / "journal").read_bytes()
153
+ records: list[dict[str, Any]] = []
154
+ previous = "0" * 64
155
+ position = 0
156
+ cached = self._verified
157
+ if (
158
+ cached is not None
159
+ and cached[0] <= len(data)
160
+ and hashlib.sha256(data[: cached[0]]).digest() == cached[1].digest()
161
+ ):
162
+ position, records, previous = cached[0], list(cached[2]), cached[3]
163
+ self.torn_tail = None
164
+ while position < len(data):
165
+ end = data.find(b"\n", position)
166
+ line = data[position : end if end >= 0 else len(data)]
167
+ record: dict[str, Any] | None = None
168
+ failure: LocalError | None = None
169
+ try:
170
+ record = self._verify(line.decode("ascii"), JOURNAL_RECORD_LIMIT)
171
+ if record["previous"] != previous or record["sequence"] != len(records) + 1:
172
+ raise LocalError("journal_invalid")
173
+ except UnicodeError:
174
+ failure = LocalError("invalid_token")
175
+ except LocalError as exc:
176
+ failure = exc
177
+ if failure is not None or end < 0:
178
+ # A crash while appending leaves a final line without its newline. It is
179
+ # discardable only when every anchored record before it verified; a
180
+ # complete line that fails, or damage anywhere else, stays fatal.
181
+ if end < 0 and len(records) >= anchor["journal_sequence"]:
182
+ self.torn_tail = position
183
+ break
184
+ raise failure or LocalError("journal_invalid")
185
+ assert record is not None
186
+ previous = hashlib.sha256(line).hexdigest()
187
+ records.append(record)
188
+ position = end + 1
189
+ verified_end = position if self.torn_tail is None else self.torn_tail
190
+ self._verified = (
191
+ verified_end,
192
+ hashlib.sha256(data[:verified_end]),
193
+ list(records),
194
+ previous,
195
+ )
196
+ index = anchor["journal_sequence"]
197
+ expected = (
198
+ "0" * 64
199
+ if index == 0
200
+ else (
201
+ hashlib.sha256(self.sign(records[index - 1]).encode()).hexdigest()
202
+ if index <= len(records)
203
+ else "missing"
204
+ )
205
+ )
206
+ if expected != anchor["journal_head"]:
207
+ raise LocalError("journal_rollback")
208
+ return list(records)
209
+
210
+ def append(self, anchor: dict[str, Any], action: dict[str, Any]) -> dict[str, Any]:
211
+ records = self.journal(anchor)
212
+ previous = (
213
+ "0" * 64 if not records else hashlib.sha256(self.sign(records[-1]).encode()).hexdigest()
214
+ )
215
+ record = {"sequence": len(records) + 1, "previous": previous, "action": action}
216
+ token = self.sign(record)
217
+ line = token.encode() + b"\n"
218
+ if len(token) > JOURNAL_RECORD_LIMIT:
219
+ # Refused before any byte is written, so the store stays healthy and readable.
220
+ raise LocalError("journal_record_limit")
221
+ verified = self._verified
222
+ assert verified is not None
223
+ with (self.path / "journal").open("r+b") as stream:
224
+ if self.torn_tail is not None:
225
+ stream.truncate(self.torn_tail)
226
+ self.torn_tail = None
227
+ stream.seek(0, os.SEEK_END)
228
+ stream.write(line)
229
+ stream.flush()
230
+ os.fsync(stream.fileno())
231
+ prefix = verified[1].copy()
232
+ prefix.update(line)
233
+ self._verified = (
234
+ verified[0] + len(line),
235
+ prefix,
236
+ [*verified[2], record],
237
+ hashlib.sha256(token.encode()).hexdigest(),
238
+ )
239
+ anchor["journal_sequence"] = record["sequence"]
240
+ anchor["journal_head"] = hashlib.sha256(token.encode()).hexdigest()
241
+ self.anchor(anchor)
242
+ return record
@@ -0,0 +1,258 @@
1
+ """Bounded Unix-socket transport. No HTTP, browser cookies or claimed role authority."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import socket
7
+ import socketserver
8
+ import stat
9
+ import threading
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, cast
13
+
14
+ from memoryking.adapters.embedding_store import Embeddings
15
+ from memoryking.adapters.experience import Experience
16
+ from memoryking.adapters.handoff import Handoff
17
+ from memoryking.adapters.inference import Inference
18
+ from memoryking.adapters.inspection import Inspection
19
+ from memoryking.adapters.knowledge_store import Knowledge
20
+ from memoryking.adapters.local_contract import OPERATIONS, VALIDATOR
21
+ from memoryking.adapters.processing_store import Processing
22
+ from memoryking.adapters.repository_store import Repository
23
+ from memoryking.adapters.retrieval import Retrieval
24
+ from memoryking.adapters.working import Working
25
+ from memoryking.application.local_port import LocalOperations
26
+ from memoryking.application.store_core import StoreCore
27
+ from memoryking.contracts.canonical import ContractError, canonical_bytes, load_strict
28
+ from memoryking.domain.hints import hint
29
+ from memoryking.domain.local import LocalError, Released
30
+ from memoryking.observability import failure, summarize, timings, trace, tracing
31
+
32
+ WIRE_LIMIT = 262144
33
+
34
+
35
+ class StoreOperations:
36
+ def __init__(self, store: StoreCore):
37
+ self.store = store
38
+
39
+ def execute(self, request: dict[str, Any]) -> dict[str, Any] | Released:
40
+ """Dispatch and record the operation's latency and outcome for `/metrics`.
41
+
42
+ With `serve --trace`, one redacted line per request also goes to the log:
43
+ operation, command action, outcome, elapsed time, lock wait, time inside
44
+ transactions and response size. Never the body, the project or the principal.
45
+ """
46
+ operation = request.get("operation") if isinstance(request, dict) else None
47
+ # Only a known operation name labels metrics and trace lines; caller text never does.
48
+ name = operation if isinstance(operation, str) and operation in OPERATIONS else "invalid"
49
+ started = time.monotonic()
50
+ error: str | None = None
51
+ spans = timings(self.store) if tracing() else None
52
+ response: dict[str, Any] | Released | None = None
53
+ try:
54
+ response = self._execute(request)
55
+ return response
56
+ except LocalError as exc:
57
+ error = exc.code
58
+ raise
59
+ except Exception:
60
+ error = "internal_error"
61
+ raise
62
+ finally:
63
+ elapsed = (time.monotonic() - started) * 1000
64
+ self.store.counters.observe(name, elapsed, error)
65
+ if spans is not None:
66
+ self.store.timings.items = None
67
+ trace(
68
+ "operations",
69
+ operation=name,
70
+ action=self._action(request),
71
+ outcome=error or "ok",
72
+ response_bytes=len(response.body)
73
+ if isinstance(response, Released)
74
+ else len(canonical_bytes(response))
75
+ if response is not None
76
+ else 0,
77
+ **summarize(elapsed, spans),
78
+ )
79
+
80
+ @staticmethod
81
+ def _action(request: Any) -> str:
82
+ """The command action (a fixed vocabulary such as brief), never free text."""
83
+ try:
84
+ action = request["args"]["command"]["action"]
85
+ except (KeyError, TypeError):
86
+ return "-"
87
+ return action if isinstance(action, str) and action.isidentifier() else "-"
88
+
89
+ def _execute(self, request: dict[str, Any]) -> dict[str, Any] | Released:
90
+ if not VALIDATOR.is_valid(request):
91
+ raise LocalError("invalid_request")
92
+ op, args, credential = request["operation"], request["args"], request["credential"]
93
+ store = self.store
94
+ if op == "experience":
95
+ return Experience(store).execute(credential, args["command"])
96
+ if op == "processing":
97
+ return Processing(store).execute(credential, args["command"])
98
+ if op == "embedding":
99
+ return Embeddings(store).execute(credential, args["command"])
100
+ if op == "repository":
101
+ return Repository(store).execute(credential, args["command"])
102
+ if op == "inference":
103
+ return Inference(store).execute(credential, args["command"])
104
+ if op == "handoff":
105
+ return Handoff(store).execute(credential, args["command"])
106
+ if op == "context":
107
+ return store.context(credential, args["project"])
108
+ if op == "working":
109
+ return Working(store).execute(credential, args["command"])
110
+ if op == "retrieval":
111
+ return Retrieval(store).execute(credential, args["command"])
112
+ if op == "knowledge":
113
+ return Knowledge(store).execute(credential, args["command"])
114
+ if op == "inspection":
115
+ return Inspection(store).execute(credential, args["command"])
116
+ if op == "dashboard_bootstrap":
117
+ dashboard = getattr(store, "dashboard", None)
118
+ if dashboard is None:
119
+ raise LocalError("dashboard_disabled")
120
+ return cast(dict[str, Any], dashboard.issue(credential))
121
+ if op == "namespace":
122
+ return {"namespace": store.namespace(credential, **args)}
123
+ if op == "capture":
124
+ return store.capture(credential, **args)
125
+ if op in {"read", "export"}:
126
+ return store.read(credential, **args, export=op == "export")
127
+ if op == "status":
128
+ return store.status(credential, **args)
129
+ if op == "grants":
130
+ return {"items": store.grants(credential)}
131
+ if op == "claim":
132
+ return {"job": store.claim(credential, **args)}
133
+ if op == "finish":
134
+ store.finish(credential, **args)
135
+ elif op == "grant":
136
+ return {"credential": store.grant(credential, **args)}
137
+ elif op == "revoke":
138
+ store.revoke(credential, **args)
139
+ elif op == "purge":
140
+ store.purge(credential, **args)
141
+ elif op == "reindex":
142
+ store.reindex(credential)
143
+ return {"ok": True}
144
+
145
+
146
+ class Handler(socketserver.StreamRequestHandler):
147
+ def handle(self) -> None:
148
+ self.request.settimeout(5)
149
+ try:
150
+ raw = self.rfile.readline(WIRE_LIMIT + 1)
151
+ if len(raw) > WIRE_LIMIT or not raw.endswith(b"\n"):
152
+ raise LocalError("invalid_request")
153
+ value = load_strict(raw)
154
+ if not isinstance(value, dict):
155
+ raise LocalError("invalid_request")
156
+ operations: LocalOperations = self.server.operations # type: ignore[attr-defined]
157
+ response = operations.execute(value)
158
+ if isinstance(response, Released):
159
+ response.emit(lambda data: self.request.sendall(data + b"\n"))
160
+ else:
161
+ self.request.sendall(canonical_bytes(response) + b"\n")
162
+ except (LocalError, ContractError) as exc:
163
+ code = exc.code if isinstance(exc, LocalError) else "invalid_request"
164
+ self.request.sendall(canonical_bytes({"error": code, "hint": hint(code)}) + b"\n")
165
+ except (TimeoutError, BrokenPipeError, ConnectionResetError):
166
+ return
167
+ except Exception as exc:
168
+ # Never serialize SQL, filenames, caller content or exception strings. The
169
+ # request id links the generic reply to the redacted operator log line.
170
+ request_id = failure("local_ipc", exc)
171
+ self.request.sendall(
172
+ canonical_bytes({"error": "internal_error", "request_id": request_id}) + b"\n"
173
+ )
174
+
175
+
176
+ class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
177
+ """Bounded concurrent requests: a slow client never blocks everyone else."""
178
+
179
+ request_queue_size = 16
180
+ daemon_threads = True
181
+ block_on_close = True
182
+ max_concurrent = 8
183
+
184
+ def __init__(self, store: StoreCore):
185
+ self.slots = threading.BoundedSemaphore(self.max_concurrent)
186
+ self.path = store.root / "service.sock"
187
+ if len(os.fsencode(self.path)) > 100:
188
+ raise LocalError("socket_path_too_long")
189
+ if self.path.exists():
190
+ info = self.path.lstat()
191
+ if not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.getuid():
192
+ raise LocalError("unsafe_socket")
193
+ self.path.unlink()
194
+ self.operations: LocalOperations = StoreOperations(store)
195
+ self.store = store
196
+ super().__init__(str(self.path), Handler)
197
+ os.chmod(self.path, 0o600)
198
+
199
+ def process_request(self, request: Any, client_address: Any) -> None:
200
+ if not self.slots.acquire(timeout=5):
201
+ try:
202
+ request.sendall(b'{"error":"service_busy"}\n')
203
+ except OSError:
204
+ pass
205
+ self.shutdown_request(request)
206
+ return
207
+ try:
208
+ super().process_request(request, client_address)
209
+ except BaseException:
210
+ self.slots.release()
211
+ raise
212
+
213
+ def process_request_thread(self, request: Any, client_address: Any) -> None:
214
+ try:
215
+ super().process_request_thread(request, client_address)
216
+ finally:
217
+ self.slots.release()
218
+
219
+ def service_actions(self) -> None:
220
+ """Between requests, complete trivial audit jobs so the queue never fills.
221
+
222
+ Draining and housekeeping are independent: a failure in one never skips the
223
+ other or escapes serve_forever. A fenced or unhealthy store reports its state
224
+ on the next request; anything else is logged.
225
+ """
226
+ for action in (self.store.drain, self.store.housekeeping):
227
+ try:
228
+ action()
229
+ except LocalError:
230
+ pass
231
+ except Exception as exc:
232
+ failure("local_ipc", exc, action=action.__name__)
233
+
234
+ def server_close(self) -> None:
235
+ super().server_close()
236
+ self.path.unlink(missing_ok=True)
237
+
238
+
239
+ def request(
240
+ socket_path: Path, credential: str, operation: str, args: dict[str, Any]
241
+ ) -> dict[str, Any]:
242
+ payload = canonical_bytes(
243
+ {"version": 1, "credential": credential, "operation": operation, "args": args}
244
+ )
245
+ if len(payload) + 1 > WIRE_LIMIT:
246
+ raise LocalError("invalid_request")
247
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as stream:
248
+ stream.settimeout(10)
249
+ stream.connect(str(socket_path))
250
+ stream.sendall(payload + b"\n")
251
+ with stream.makefile("rb") as response:
252
+ raw = response.readline(1048577)
253
+ value = load_strict(raw)
254
+ if not isinstance(value, dict):
255
+ raise LocalError("invalid_response")
256
+ if "error" in value:
257
+ raise LocalError(value["error"], value.get("hint"))
258
+ return value
@@ -0,0 +1,44 @@
1
+ CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
2
+ CREATE TABLE tenants (tenant TEXT PRIMARY KEY, position INTEGER NOT NULL DEFAULT 0,
3
+ policy_epoch INTEGER NOT NULL DEFAULT 0, purge_epoch INTEGER NOT NULL DEFAULT 0);
4
+ CREATE TABLE grants (tenant TEXT NOT NULL REFERENCES tenants, principal TEXT NOT NULL,
5
+ project TEXT NOT NULL, capabilities TEXT NOT NULL, starts INTEGER, expires INTEGER,
6
+ PRIMARY KEY(tenant,principal,project));
7
+ CREATE TABLE events (tenant TEXT NOT NULL REFERENCES tenants, position INTEGER NOT NULL,
8
+ event_id TEXT NOT NULL, kind TEXT NOT NULL, subject TEXT NOT NULL, origin TEXT NOT NULL,
9
+ at_ms INTEGER NOT NULL, actor TEXT NOT NULL, PRIMARY KEY(tenant,position), UNIQUE(tenant,event_id));
10
+ CREATE TABLE observations (tenant TEXT NOT NULL, id TEXT NOT NULL, project TEXT NOT NULL,
11
+ principal TEXT NOT NULL, source TEXT NOT NULL, source_event TEXT NOT NULL,
12
+ payload_hash TEXT NOT NULL, blob TEXT, readers TEXT, position INTEGER NOT NULL,
13
+ classification TEXT NOT NULL, observed_at_ms INTEGER NOT NULL,
14
+ origin TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1, deleted INTEGER NOT NULL DEFAULT 0,
15
+ PRIMARY KEY(tenant,id), UNIQUE(tenant,principal,source,source_event),
16
+ FOREIGN KEY(tenant,position) REFERENCES events(tenant,position));
17
+ CREATE VIRTUAL TABLE lexical USING fts5(tenant UNINDEXED, id UNINDEXED, text);
18
+ CREATE TABLE retries (tenant TEXT NOT NULL REFERENCES tenants, incarnation TEXT NOT NULL,
19
+ namespace TEXT NOT NULL, principal TEXT NOT NULL, operation TEXT NOT NULL,
20
+ key TEXT NOT NULL, hash TEXT NOT NULL, result TEXT, observation TEXT,
21
+ expires INTEGER NOT NULL, PRIMARY KEY(tenant,incarnation,namespace,principal,operation,key));
22
+ CREATE TABLE jobs (tenant TEXT NOT NULL, id TEXT NOT NULL, position INTEGER NOT NULL,
23
+ observation TEXT, incarnation TEXT NOT NULL, generation INTEGER NOT NULL,
24
+ state TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, fence INTEGER NOT NULL DEFAULT 0,
25
+ lease_until INTEGER NOT NULL DEFAULT 0, available INTEGER NOT NULL DEFAULT 0,
26
+ purge_epoch INTEGER NOT NULL, revision INTEGER NOT NULL, principal TEXT NOT NULL,
27
+ PRIMARY KEY(tenant,id), FOREIGN KEY(tenant,position) REFERENCES events(tenant,position),
28
+ FOREIGN KEY(tenant,observation) REFERENCES observations(tenant,id));
29
+ CREATE TABLE projections (tenant TEXT PRIMARY KEY REFERENCES tenants, incarnation TEXT NOT NULL,
30
+ channel TEXT NOT NULL, configuration TEXT NOT NULL, generation INTEGER NOT NULL,
31
+ frontier INTEGER NOT NULL DEFAULT 0);
32
+ CREATE TABLE projection_items (tenant TEXT NOT NULL, observation TEXT NOT NULL,
33
+ incarnation TEXT NOT NULL, generation INTEGER NOT NULL, source_revision INTEGER NOT NULL,
34
+ blob_hash TEXT NOT NULL, byte_count INTEGER NOT NULL, PRIMARY KEY(tenant,observation),
35
+ FOREIGN KEY(tenant,observation) REFERENCES observations(tenant,id));
36
+ CREATE TABLE receipts (tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL,
37
+ principal TEXT NOT NULL, incarnation TEXT NOT NULL, evaluated INTEGER NOT NULL,
38
+ deadline INTEGER NOT NULL, policy_epoch INTEGER NOT NULL, purge_epoch INTEGER NOT NULL,
39
+ response_hash TEXT NOT NULL, observation_ids TEXT NOT NULL,
40
+ PRIMARY KEY(tenant,id));
41
+ CREATE TABLE retired_sources (tenant TEXT NOT NULL REFERENCES tenants, principal TEXT NOT NULL,
42
+ source TEXT NOT NULL, source_event TEXT NOT NULL,
43
+ PRIMARY KEY(tenant,principal,source,source_event));
44
+ PRAGMA user_version=1;