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,330 @@
1
+ """Provider adapters: one bounded HTTPS call per dispatch, nothing else.
2
+
3
+ An adapter is constructed from the operator's egress policy and turns the frozen
4
+ canonical request bytes into one provider request. It cannot add, drop or reorder
5
+ messages: the mapping to the wire body is a fixed function per adapter, and the hash of
6
+ the exact wire body is returned so the daemon's audit record can hold it. One attempt,
7
+ a bounded timeout, a bounded reply, no streaming, no tool use, no retained state.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import http.client
14
+ import json
15
+ import socket
16
+ import ssl
17
+ import subprocess
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from memoryking.adapters.egress_policy import EgressPolicy, ProviderPolicy
23
+ from memoryking.adapters.local_files import private_file
24
+ from memoryking.contracts.canonical import canonical_bytes, load_strict
25
+ from memoryking.domain.local import LocalError
26
+
27
+ RESPONSE_LIMIT = 1048576
28
+ ANTHROPIC_VERSION = "2023-06-01"
29
+ VERTEX_ANTHROPIC_VERSION = "vertex-2023-10-16"
30
+
31
+
32
+ def digest(data: bytes) -> str:
33
+ return hashlib.sha256(data).hexdigest()
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ProviderResult:
38
+ content: str
39
+ request_hash: str
40
+ wire_hash: str
41
+ usage: dict[str, int | None]
42
+
43
+
44
+ class HttpAdapter:
45
+ """Shared transport and credential handling; subclasses define the wire mapping."""
46
+
47
+ stateful = False
48
+
49
+ def __init__(self, policy: EgressPolicy, entry: ProviderPolicy, model: str):
50
+ if not entry.allows(model):
51
+ raise LocalError("egress_provider_denied")
52
+ self.policy_revision = policy.binding
53
+ self.last_wire_hash: str | None = None # the body last handed to the transport
54
+ self.entry = entry
55
+ self.name = entry.name
56
+ self.model = model
57
+ self.host = entry.host
58
+
59
+ # Credentials are read by the host process at dispatch time and never logged.
60
+ def _secret(self, path: Path | None) -> str | None:
61
+ if path is None:
62
+ return None
63
+ try:
64
+ private_file(path)
65
+ value = path.read_text().strip()
66
+ except (OSError, LocalError) as exc:
67
+ raise LocalError("provider_credential_missing") from exc
68
+ if not value or len(value) > 8192 or any(c in value for c in "\r\n"):
69
+ raise LocalError("provider_credential_missing")
70
+ return value
71
+
72
+ def _token(self) -> str:
73
+ entry = self.entry
74
+ if entry.token_file is not None:
75
+ return self._secret(entry.token_file) or ""
76
+ if entry.token_command is not None:
77
+ try:
78
+ completed = subprocess.run(
79
+ list(entry.token_command),
80
+ capture_output=True,
81
+ text=True,
82
+ timeout=30,
83
+ check=False,
84
+ env={"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": str(Path.home())},
85
+ )
86
+ except (OSError, subprocess.SubprocessError) as exc:
87
+ raise LocalError("provider_credential_missing") from exc
88
+ token = completed.stdout.strip()
89
+ if completed.returncode or not token or len(token) > 8192:
90
+ raise LocalError("provider_credential_missing")
91
+ return token
92
+ raise LocalError("provider_credential_missing")
93
+
94
+ def _post(self, path: str, headers: dict[str, str], body: bytes) -> dict[str, Any]:
95
+ entry = self.entry
96
+ connection: http.client.HTTPConnection
97
+ if entry.insecure_http:
98
+ connection = http.client.HTTPConnection(entry.host, timeout=entry.timeout_s)
99
+ else:
100
+ connection = http.client.HTTPSConnection(
101
+ entry.host, timeout=entry.timeout_s, context=ssl.create_default_context()
102
+ )
103
+ try:
104
+ connection.request(
105
+ "POST",
106
+ path,
107
+ body,
108
+ {
109
+ "Content-Type": "application/json",
110
+ "Accept": "application/json",
111
+ "Content-Length": str(len(body)),
112
+ **entry.headers,
113
+ **headers,
114
+ },
115
+ )
116
+ response = connection.getresponse()
117
+ raw = response.read(RESPONSE_LIMIT + 1)
118
+ except (OSError, http.client.HTTPException, socket.timeout, ssl.SSLError) as exc:
119
+ raise LocalError("provider_unavailable") from exc
120
+ finally:
121
+ connection.close()
122
+ if response.status != 200:
123
+ raise LocalError("provider_unavailable")
124
+ if len(raw) > RESPONSE_LIMIT:
125
+ raise LocalError("provider_response_invalid")
126
+ try:
127
+ value = json.loads(raw)
128
+ except ValueError as exc:
129
+ raise LocalError("provider_response_invalid") from exc
130
+ if not isinstance(value, dict):
131
+ raise LocalError("provider_response_invalid")
132
+ return value
133
+
134
+ def dispatch(self, raw: bytes) -> ProviderResult:
135
+ self.last_wire_hash = None
136
+ request = load_strict(raw)
137
+ if (
138
+ not isinstance(request, dict)
139
+ or canonical_bytes(request) != raw
140
+ or request.get("provider") != self.name
141
+ or request.get("model") != self.model
142
+ or request.get("state_handles") != []
143
+ ):
144
+ raise LocalError("provider_request_invalid")
145
+ body = canonical_bytes(self.wire(request))
146
+ # Recorded before the transport so a failed delivery still audits the bytes
147
+ # that may have left.
148
+ self.last_wire_hash = digest(body)
149
+ reply = self._post(self.path(), self.headers(), body)
150
+ content, usage = self.parse(reply)
151
+ if not isinstance(content, str) or not content or len(content) > 65536:
152
+ raise LocalError("provider_response_invalid")
153
+ return ProviderResult(content, digest(raw), digest(body), usage)
154
+
155
+ def path(self) -> str:
156
+ raise NotImplementedError
157
+
158
+ def headers(self) -> dict[str, str]:
159
+ raise NotImplementedError
160
+
161
+ def wire(self, request: dict[str, Any]) -> dict[str, Any]:
162
+ raise NotImplementedError
163
+
164
+ def parse(self, reply: dict[str, Any]) -> tuple[str, dict[str, int | None]]:
165
+ raise NotImplementedError
166
+
167
+
168
+ def _count(value: Any) -> int | None:
169
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
170
+
171
+
172
+ def _anthropic_body(request: dict[str, Any], max_tokens: int) -> dict[str, Any]:
173
+ system = [m["content"] for m in request["messages"] if m["role"] == "system"]
174
+ messages = [
175
+ {"role": "assistant" if m["role"] == "assistant" else "user", "content": m["content"]}
176
+ for m in request["messages"]
177
+ if m["role"] != "system"
178
+ ]
179
+ body: dict[str, Any] = {"max_tokens": max_tokens, "messages": messages}
180
+ if system:
181
+ body["system"] = "\n\n".join(system)
182
+ return body
183
+
184
+
185
+ def _anthropic_parse(reply: dict[str, Any]) -> tuple[str, dict[str, int | None]]:
186
+ blocks = reply.get("content")
187
+ if not isinstance(blocks, list):
188
+ raise LocalError("provider_response_invalid")
189
+ text = "".join(
190
+ b["text"] for b in blocks if isinstance(b, dict) and isinstance(b.get("text"), str)
191
+ )
192
+ usage: dict[str, Any] = reply["usage"] if isinstance(reply.get("usage"), dict) else {}
193
+ return text, {
194
+ "input_tokens": _count(usage.get("input_tokens")),
195
+ "output_tokens": _count(usage.get("output_tokens")),
196
+ }
197
+
198
+
199
+ class AnthropicMessages(HttpAdapter):
200
+ def path(self) -> str:
201
+ return self.entry.path or "/v1/messages"
202
+
203
+ def headers(self) -> dict[str, str]:
204
+ key = self._secret(self.entry.key_file)
205
+ if key is None:
206
+ raise LocalError("provider_credential_missing")
207
+ return {"x-api-key": key, "anthropic-version": ANTHROPIC_VERSION}
208
+
209
+ def wire(self, request: dict[str, Any]) -> dict[str, Any]:
210
+ return {"model": self.model, **_anthropic_body(request, self.entry.max_output_tokens)}
211
+
212
+ def parse(self, reply: dict[str, Any]) -> tuple[str, dict[str, int | None]]:
213
+ return _anthropic_parse(reply)
214
+
215
+
216
+ class OpenAIChat(HttpAdapter):
217
+ """Chat completions: OpenAI, xAI Grok, and self-hosted servers at an explicit host."""
218
+
219
+ def path(self) -> str:
220
+ return self.entry.path or "/v1/chat/completions"
221
+
222
+ def headers(self) -> dict[str, str]:
223
+ key = self._secret(self.entry.key_file)
224
+ return {"Authorization": "Bearer " + key} if key else {}
225
+
226
+ def wire(self, request: dict[str, Any]) -> dict[str, Any]:
227
+ return {
228
+ "model": self.model,
229
+ "max_tokens": self.entry.max_output_tokens,
230
+ "messages": [
231
+ {"role": "user" if m["role"] == "tool" else m["role"], "content": m["content"]}
232
+ for m in request["messages"]
233
+ ],
234
+ "stream": False,
235
+ }
236
+
237
+ def parse(self, reply: dict[str, Any]) -> tuple[str, dict[str, int | None]]:
238
+ choices = reply.get("choices")
239
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
240
+ raise LocalError("provider_response_invalid")
241
+ message = choices[0].get("message")
242
+ content = message.get("content") if isinstance(message, dict) else None
243
+ usage: dict[str, Any] = reply["usage"] if isinstance(reply.get("usage"), dict) else {}
244
+ return content if isinstance(content, str) else "", {
245
+ "input_tokens": _count(usage.get("prompt_tokens")),
246
+ "output_tokens": _count(usage.get("completion_tokens")),
247
+ }
248
+
249
+
250
+ class VertexAI(HttpAdapter):
251
+ """Google Cloud Vertex AI: Gemini through generateContent, or Anthropic through rawPredict."""
252
+
253
+ def _base(self) -> str:
254
+ entry = self.entry
255
+ return (
256
+ f"/v1/projects/{entry.project}/locations/{entry.location}"
257
+ f"/publishers/{entry.publisher}/models/{self.model}"
258
+ )
259
+
260
+ def path(self) -> str:
261
+ if self.entry.path:
262
+ return self.entry.path
263
+ return self._base() + (
264
+ ":rawPredict" if self.entry.publisher == "anthropic" else ":generateContent"
265
+ )
266
+
267
+ def headers(self) -> dict[str, str]:
268
+ return {"Authorization": "Bearer " + self._token()}
269
+
270
+ def wire(self, request: dict[str, Any]) -> dict[str, Any]:
271
+ if self.entry.publisher == "anthropic":
272
+ return {
273
+ "anthropic_version": VERTEX_ANTHROPIC_VERSION,
274
+ **_anthropic_body(request, self.entry.max_output_tokens),
275
+ }
276
+ system = [m["content"] for m in request["messages"] if m["role"] == "system"]
277
+ body: dict[str, Any] = {
278
+ "contents": [
279
+ {
280
+ "role": "model" if m["role"] == "assistant" else "user",
281
+ "parts": [{"text": m["content"]}],
282
+ }
283
+ for m in request["messages"]
284
+ if m["role"] != "system"
285
+ ],
286
+ "generationConfig": {"maxOutputTokens": self.entry.max_output_tokens},
287
+ }
288
+ if system:
289
+ body["systemInstruction"] = {"parts": [{"text": "\n\n".join(system)}]}
290
+ return body
291
+
292
+ def parse(self, reply: dict[str, Any]) -> tuple[str, dict[str, int | None]]:
293
+ if self.entry.publisher == "anthropic":
294
+ return _anthropic_parse(reply)
295
+ candidates = reply.get("candidates")
296
+ if (
297
+ not isinstance(candidates, list)
298
+ or not candidates
299
+ or not isinstance(candidates[0], dict)
300
+ ):
301
+ raise LocalError("provider_response_invalid")
302
+ content = candidates[0].get("content")
303
+ parts = content.get("parts") if isinstance(content, dict) else None
304
+ text = "".join(
305
+ p["text"]
306
+ for p in (parts if isinstance(parts, list) else [])
307
+ if isinstance(p, dict) and isinstance(p.get("text"), str)
308
+ )
309
+ usage: dict[str, Any] = (
310
+ reply["usageMetadata"] if isinstance(reply.get("usageMetadata"), dict) else {}
311
+ )
312
+ return text, {
313
+ "input_tokens": _count(usage.get("promptTokenCount")),
314
+ "output_tokens": _count(usage.get("candidatesTokenCount")),
315
+ }
316
+
317
+
318
+ ADAPTERS: dict[str, type[HttpAdapter]] = {
319
+ "anthropic-messages": AnthropicMessages,
320
+ "openai-chat": OpenAIChat,
321
+ "vertex-ai": VertexAI,
322
+ }
323
+
324
+
325
+ def adapter(policy: EgressPolicy, name: str, model: str) -> HttpAdapter:
326
+ """The adapter the policy permits for a provider and model, or egress_provider_denied."""
327
+ entry = policy.provider(name)
328
+ if entry is None or name not in ADAPTERS:
329
+ raise LocalError("egress_provider_denied")
330
+ return ADAPTERS[name](policy, entry, model)
memoryking/py.typed ADDED
File without changes
@@ -0,0 +1,69 @@
1
+ """Record failing tests as observations: `pytest -p memoryking.pytest_plugin`.
2
+
3
+ Enable with `MEMORYKING_PROFILE` (or `MEMORYKING_SOCKET` and `MEMORYKING_CREDENTIAL`) and
4
+ `MEMORYKING_PROJECT` in the environment; without them the plugin stays silent. Each
5
+ failure captures the test id and the tail of its report under source `pytest`, with an
6
+ event id derived from the test id and message so a rerun replays rather than duplicates.
7
+ The plugin never fails the test run: capture errors are reported once to stderr.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from typing import Any
15
+
16
+ from memoryking import hooks
17
+ from memoryking.domain.local import LocalError
18
+
19
+ REPORT_TAIL = 4000
20
+ _state = {"announced": False, "captured": 0, "disabled": False}
21
+
22
+
23
+ def enabled() -> bool:
24
+ env = os.environ
25
+ return bool(env.get("MEMORYKING_PROJECT")) and bool(
26
+ env.get("MEMORYKING_PROFILE")
27
+ or (env.get("MEMORYKING_SOCKET") and env.get("MEMORYKING_CREDENTIAL"))
28
+ )
29
+
30
+
31
+ def summarize(report: Any) -> str:
32
+ """A bounded, readable failure text from a pytest report-like object."""
33
+ longrepr = getattr(report, "longreprtext", None) or str(getattr(report, "longrepr", "") or "")
34
+ tail = longrepr[-REPORT_TAIL:]
35
+ when = getattr(report, "when", "call")
36
+ return f"pytest {when} failed: {report.nodeid}\n{tail}".strip()
37
+
38
+
39
+ def record_failure(report: Any) -> dict[str, Any] | None:
40
+ """Capture one failed report; returns the capture result or None when disabled."""
41
+ if _state["disabled"] or not enabled() or not getattr(report, "failed", False):
42
+ return None
43
+ text = summarize(report)
44
+ try:
45
+ # The hook derives the key from the whole text (node id and traceback tail),
46
+ # the project and the day: a changed failure is recorded, an identical rerun
47
+ # replays.
48
+ result = hooks.capture(text, source="pytest")
49
+ except Exception as exc:
50
+ # Never fail the test run: any capture error disables capture for this run.
51
+ _state["disabled"] = True
52
+ if not _state["announced"]:
53
+ _state["announced"] = True
54
+ code = exc.code if isinstance(exc, LocalError) else type(exc).__name__
55
+ print(f"memoryking: capture disabled for this run ({code})", file=sys.stderr)
56
+ return None
57
+ _state["captured"] += 1
58
+ return result
59
+
60
+
61
+ def pytest_runtest_logreport(report: Any) -> None: # pytest hook
62
+ record_failure(report)
63
+
64
+
65
+ def pytest_terminal_summary(terminalreporter: Any) -> None: # pytest hook
66
+ if _state["captured"]:
67
+ terminalreporter.write_line(
68
+ f"memoryking: {_state['captured']} failing test(s) captured as observations"
69
+ )
@@ -0,0 +1,152 @@
1
+ """Explicit local reference-agent commands; no autonomous or network model execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from memoryking.contracts.canonical import ContractError, canonical_bytes, load_strict
11
+ from memoryking.domain.local import LocalError
12
+ from memoryking.harness import LocalFileTool, ReferenceHarness
13
+ from memoryking.harness_context import LocalRecordingProvider
14
+ from memoryking.sdk import LocalClient
15
+
16
+
17
+ def state_file(path: Path) -> dict[str, Any]:
18
+ with path.open("rb") as stream:
19
+ raw = stream.read(131073)
20
+ if len(raw) > 131072:
21
+ raise LocalError("checkpoint_input_limit")
22
+ value = load_strict(raw)
23
+ if not isinstance(value, dict):
24
+ raise LocalError("invalid_checkpoint")
25
+ return value
26
+
27
+
28
+ def main() -> None:
29
+ parser = argparse.ArgumentParser(description=__doc__)
30
+ for name in ("socket", "credential", "journal", "tool-root"):
31
+ parser.add_argument("--" + name, required=True, type=Path)
32
+ parser.add_argument("--project", required=True)
33
+ parser.add_argument("--task", required=True)
34
+ parser.add_argument("--run")
35
+ parser.add_argument(
36
+ "--reader", action="append", help="Additional checkpoint reader; start only"
37
+ )
38
+ commands = parser.add_subparsers(dest="action", required=True)
39
+ start = commands.add_parser("start", help="Durably register explicit task state")
40
+ start.add_argument("--state", required=True, type=Path)
41
+ for name in ("status", "resume", "reconcile", "close"):
42
+ commands.add_parser(name)
43
+ checkpoint = commands.add_parser("checkpoint")
44
+ checkpoint.add_argument("--reason", required=True)
45
+ update = commands.add_parser("update")
46
+ update.add_argument("--state", required=True, type=Path)
47
+ constraint = commands.add_parser("constraint")
48
+ constraint.add_argument("--text", required=True)
49
+ create = commands.add_parser("create-file")
50
+ create.add_argument("--operation", required=True)
51
+ create.add_argument("--name", required=True)
52
+ create.add_argument("--content", required=True, help="Explicit UTF-8 contents; exclude secrets")
53
+ artifact = commands.add_parser("store-artifact")
54
+ artifact.add_argument("--name", required=True)
55
+ snapshot = commands.add_parser(
56
+ "refresh-repository",
57
+ help="Capture an explicitly registered clone and declare the change scope",
58
+ )
59
+ snapshot.add_argument("--repository", required=True)
60
+ snapshot.add_argument("--clone", required=True)
61
+ snapshot.add_argument("--environment", required=True)
62
+ snapshot.add_argument("--path", action="append", required=True)
63
+ for command in (update, constraint, create, artifact, snapshot):
64
+ command.add_argument("--approve", action="store_true", help="Explicit host authorization")
65
+ model = commands.add_parser(
66
+ "model-turn", help="The local recorder by default; a policy adapter with --provider"
67
+ )
68
+ model.add_argument("--provider-root", type=Path, help="Local recorder directory")
69
+ model.add_argument("--egress-policy", type=Path, help="The daemon's egress policy file")
70
+ model.add_argument("--provider", help="An adapter named in the policy, e.g. openai-chat")
71
+ model.add_argument("--model", help="A model the policy allows for that provider")
72
+ handoff = commands.add_parser("prepare-handoff", help="Prepare only; does not send a message")
73
+ handoff.add_argument("--recipient", required=True)
74
+ handoff.add_argument("--stage", required=True)
75
+ handoff.add_argument("--role", required=True)
76
+ args = parser.parse_args()
77
+ harness = None
78
+ try:
79
+ if hasattr(args, "approve") and not args.approve:
80
+ raise LocalError("host_authorization_required")
81
+ if args.reader and args.action != "start":
82
+ raise LocalError("readers_only_at_start")
83
+ client = LocalClient(args.socket, args.credential, args.project)
84
+ readers = (
85
+ None
86
+ if not args.reader
87
+ else sorted(set([client.last_context["principal"], *args.reader]))
88
+ )
89
+ harness = ReferenceHarness(
90
+ client,
91
+ args.journal,
92
+ LocalFileTool(args.tool_root),
93
+ task=args.task,
94
+ run=args.run,
95
+ readers=readers,
96
+ state=state_file(args.state) if args.action == "start" else None,
97
+ )
98
+ result: Any
99
+ if args.action in {"start", "status"}:
100
+ result = harness.status()
101
+ elif args.action == "resume":
102
+ result = harness.resume()
103
+ elif args.action == "reconcile":
104
+ result = harness.reconcile()
105
+ elif args.action == "checkpoint":
106
+ result = harness.checkpoint(args.reason)
107
+ elif args.action == "update":
108
+ harness.update_state(state_file(args.state))
109
+ result = harness.status()
110
+ elif args.action == "constraint":
111
+ harness.accept_constraint(args.text, approved=True)
112
+ result = harness.status()
113
+ elif args.action == "create-file":
114
+ result = harness.create_file(args.operation, args.name, args.content, approved=True)
115
+ elif args.action == "store-artifact":
116
+ result = harness.store_artifact(args.name, approved=True)
117
+ elif args.action == "refresh-repository":
118
+ result = harness.refresh_repository(
119
+ args.repository, args.clone, args.environment, args.path, approved=True
120
+ )
121
+ elif args.action == "model-turn":
122
+ if args.provider:
123
+ from memoryking.adapters.egress_policy import EgressPolicy
124
+ from memoryking.providers import adapter
125
+
126
+ if not args.egress_policy or not args.model:
127
+ raise LocalError("egress_policy_invalid")
128
+ policy = EgressPolicy.load(args.egress_policy)
129
+ result = harness.model_turn(adapter(policy, args.provider, args.model))
130
+ else:
131
+ if args.provider_root is None:
132
+ raise LocalError("provider_handle_invalid")
133
+ result = harness.model_turn(LocalRecordingProvider(args.provider_root))
134
+ elif args.action == "prepare-handoff":
135
+ result = harness.prepare_handoff(args.recipient, args.role, args.stage)
136
+ else:
137
+ harness.close()
138
+ result = {"status": "closed", "checkpointed": True}
139
+ sys.stdout.buffer.write(canonical_bytes(result) + b"\n")
140
+ except (LocalError, ContractError, OSError, ValueError) as exc:
141
+ code = exc.code if isinstance(exc, LocalError) else "invalid_local_input"
142
+ sys.stderr.write(code + "\n")
143
+ raise SystemExit(2) from None
144
+ finally:
145
+ if harness is not None:
146
+ # Each mutating command captured its boundary already. Only explicit
147
+ # close adds shutdown; inspect/resume must not supersede a handoff.
148
+ harness.close(checkpoint=False)
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
@@ -0,0 +1,57 @@
1
+ """One bounded queued repository comparison through the authenticated local SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from memoryking.adapters.local_store import uid
10
+ from memoryking.contracts.canonical import ContractError, canonical_bytes
11
+ from memoryking.domain.local import LocalError
12
+ from memoryking.sdk import LocalClient
13
+
14
+
15
+ def run_once(client: LocalClient, repository: str) -> dict[str, object]:
16
+ def command(action: str, args: dict[str, object], key: str | None = None) -> dict[str, object]:
17
+ request = {
18
+ "version": 1,
19
+ "incarnation": client.binding[-1],
20
+ "action": action,
21
+ "args": {"project": client.project, "repository": repository, **args},
22
+ }
23
+ if key:
24
+ request["key"] = key
25
+ return client.repository(request)
26
+
27
+ jobs = command("pending", {})["jobs"]
28
+ if not isinstance(jobs, list) or not jobs:
29
+ return {"status": "idle", "checks_executed": False}
30
+ job = jobs[0]
31
+ return command(
32
+ "revalidate",
33
+ {"snapshot": job["snapshot"], "expected_generation": job["generation"]},
34
+ uid("revalidate"),
35
+ )
36
+
37
+
38
+ def main() -> None:
39
+ parser = argparse.ArgumentParser(description=__doc__)
40
+ parser.add_argument("--socket", type=Path, required=True)
41
+ parser.add_argument("--credential", type=Path, required=True)
42
+ parser.add_argument("--project", required=True)
43
+ parser.add_argument("--repository", required=True)
44
+ parser.add_argument("--once", action="store_true", required=True)
45
+ args = parser.parse_args()
46
+ try:
47
+ client = LocalClient(args.socket, args.credential, args.project)
48
+ sys.stdout.buffer.write(canonical_bytes(run_once(client, args.repository)) + b"\n")
49
+ except (LocalError, ContractError, OSError, ValueError) as exc:
50
+ sys.stderr.write(
51
+ (exc.code if isinstance(exc, LocalError) else "invalid_local_input") + "\n"
52
+ )
53
+ raise SystemExit(2) from None
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()