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,346 @@
1
+ """Optional source-backed proposals and conservative context compilation.
2
+
3
+ Generation is outside the release transaction and is never invoked here. Supplied
4
+ model provenance is an actor attestation, not evidence of dispatch or entitlement.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from jsonschema import Draft202012Validator
14
+
15
+ from memoryking.adapters.knowledge_store import Knowledge
16
+ from memoryking.adapters.local_store import RETRY_MS, USAGE_LIMIT, uid
17
+ from memoryking.adapters.token_count import counter
18
+ from memoryking.adapters.working import Working
19
+ from memoryking.application.store_core import StoreCore
20
+ from memoryking.contracts.canonical import canonical_bytes, canonical_hash
21
+ from memoryking.domain.briefing import counted
22
+ from memoryking.domain.compression import validate
23
+ from memoryking.domain.local import Decision, LocalError, Released
24
+ from memoryking.domain.usage import UsageRecord, summarize
25
+
26
+ VALIDATOR = Draft202012Validator(
27
+ json.loads(Path(__file__).with_name("processing.schema.json").read_text())
28
+ )
29
+
30
+
31
+ class Processing:
32
+ def __init__(self, store: StoreCore):
33
+ self.s, self.db = store, store.db
34
+ self.k, self.w = Knowledge(store), Working(store)
35
+ self.r = self.w.r
36
+
37
+ def execute(self, credential: str, command: dict[str, Any]) -> Released:
38
+ if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
39
+ raise LocalError("invalid_request")
40
+ if command["incarnation"] != self.s.incarnation:
41
+ raise LocalError("history_changed")
42
+ action, args, receipt = command["action"], command["args"], uid("rcpt")
43
+ with self.s.transaction() as decision:
44
+ at = decision.evaluated_ms
45
+ who = self.s._auth(credential, "read", args["project"], at)
46
+ deps: list[dict[str, str]] = []
47
+ if action == "extract":
48
+ self.s._auth(credential, "capture", args["project"], at)
49
+ result = self.extract(credential, who, command, at)
50
+ elif action == "compile":
51
+ if args["candidate"] is not None:
52
+ self.s._auth(credential, "inference", args["project"], at)
53
+ raw, deps = self.compile(who, args, decision, receipt)
54
+ result = json.loads(raw)
55
+ else:
56
+ self.s._auth(credential, "admin", args["project"], at)
57
+ result = self.usage(who, args)
58
+ if action != "compile":
59
+ result.update(
60
+ receipt=receipt,
61
+ evaluated_ms=at,
62
+ deadline_ms=decision.deadline_ms,
63
+ incarnation=self.s.incarnation,
64
+ )
65
+ raw = canonical_bytes(result)
66
+ epochs = self.db.execute(
67
+ "SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
68
+ ).fetchone()
69
+ self.db.execute(
70
+ "INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
71
+ (
72
+ who["tenant"],
73
+ receipt,
74
+ who["principal"],
75
+ self.s.incarnation,
76
+ at,
77
+ decision.deadline_ms,
78
+ *epochs,
79
+ canonical_hash(result),
80
+ json.dumps([d["id"] for d in deps if d["kind"] == "observation"]),
81
+ ),
82
+ )
83
+ self.s.fault("after_validation")
84
+ self.s._expose()
85
+ return Released(raw, decision, self.s.clock, receipt)
86
+
87
+ def attest_usage(
88
+ self,
89
+ who: dict[str, Any],
90
+ project: str,
91
+ attempt: str,
92
+ stage: str,
93
+ provenance: dict[str, Any],
94
+ at: int,
95
+ ) -> str:
96
+ identifier = canonical_hash([self.s.incarnation, who["principal"], project, stage, attempt])
97
+ request_hash = canonical_hash(provenance)
98
+ previous = self.db.execute(
99
+ "SELECT request_hash FROM processing_usage WHERE tenant=? AND id=?",
100
+ (who["tenant"], identifier),
101
+ ).fetchone()
102
+ if previous is not None:
103
+ if previous["request_hash"] != request_hash:
104
+ raise LocalError("usage_attempt_conflict")
105
+ return identifier
106
+ if (
107
+ self.db.execute(
108
+ "SELECT count(*) FROM processing_usage WHERE tenant=?", (who["tenant"],)
109
+ ).fetchone()[0]
110
+ >= USAGE_LIMIT
111
+ ):
112
+ # Only rows past their retention are released; recent attempts are never
113
+ # silently discarded to make room.
114
+ self.db.execute(
115
+ "DELETE FROM processing_usage WHERE tenant=? AND expires<=?", (who["tenant"], at)
116
+ )
117
+ if (
118
+ self.db.execute(
119
+ "SELECT count(*) FROM processing_usage WHERE tenant=?", (who["tenant"],)
120
+ ).fetchone()[0]
121
+ >= USAGE_LIMIT
122
+ ):
123
+ raise LocalError("usage_retention_limit")
124
+ self.db.execute(
125
+ "INSERT INTO processing_usage VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
126
+ (
127
+ who["tenant"],
128
+ identifier,
129
+ project,
130
+ who["principal"],
131
+ self.s.incarnation,
132
+ "attested:" + provenance["provider"],
133
+ provenance["configuration_hash"],
134
+ stage,
135
+ "unknown",
136
+ None,
137
+ None,
138
+ None,
139
+ None,
140
+ 0,
141
+ request_hash,
142
+ provenance["output_hash"],
143
+ "[]",
144
+ at,
145
+ at + RETRY_MS,
146
+ ),
147
+ )
148
+ return identifier
149
+
150
+ def extract(
151
+ self, credential: str, who: dict[str, Any], command: dict[str, Any], at: int
152
+ ) -> dict[str, Any]:
153
+ args = command["args"]
154
+ body, provenance = args["body"], args["provenance"]
155
+ self.k._support(who, body["evidence"], at)
156
+ # Blob identities plus exact byte ranges identify checked UTF-8 source bytes.
157
+ if provenance["input_hash"] != canonical_hash(body["evidence"]):
158
+ raise LocalError("source_manifest_mismatch")
159
+ if provenance["output_hash"] != canonical_hash(body):
160
+ raise LocalError("output_hash_mismatch")
161
+ lookup = (
162
+ who["tenant"],
163
+ self.s.incarnation,
164
+ "processing-v1",
165
+ who["principal"],
166
+ "extract",
167
+ command["key"],
168
+ )
169
+ previous = self.db.execute(
170
+ "SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
171
+ lookup,
172
+ ).fetchone()
173
+ if previous is not None:
174
+ if previous["hash"] != canonical_hash(command):
175
+ raise LocalError("idempotency_conflict")
176
+ if previous["result"] is None or at >= previous["expires"]:
177
+ raise LocalError("idempotency_result_expired")
178
+ return {**json.loads(previous["result"]), "replayed": True}
179
+ usage = self.attest_usage(
180
+ who, args["project"], command["key"], "capture_extraction", provenance, at
181
+ )
182
+ result = self.k.propose(
183
+ credential,
184
+ who,
185
+ {
186
+ **args,
187
+ "body": {
188
+ **body,
189
+ "provenance": {
190
+ **provenance,
191
+ "assurance": "actor_reported",
192
+ "usage_attempt": usage,
193
+ "validation": "source_bytes_and_output_hash_only",
194
+ "semantic_entailment": "unverified",
195
+ },
196
+ },
197
+ },
198
+ at,
199
+ )
200
+ result.update(usage_attempt=usage, assurance="actor_reported", automatic_acceptance=False)
201
+ self.db.execute(
202
+ "INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
203
+ (*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
204
+ )
205
+ return result
206
+
207
+ def sources(self, who: dict[str, Any], args: dict[str, Any], at: int) -> list[dict[str, Any]]:
208
+ units = []
209
+ for identifier in args["sources"]:
210
+ row = self.db.execute(
211
+ "SELECT * FROM observations WHERE tenant=? AND id=?", (who["tenant"], identifier)
212
+ ).fetchone()
213
+ if (
214
+ row is None
215
+ or row["project"] != args["project"]
216
+ or not self.s._visible(who, row, at)
217
+ ):
218
+ raise LocalError("optional_source_unavailable")
219
+ raw = self.r._blob(row)
220
+ if len(raw) > 8192:
221
+ raise LocalError("optional_source_limit")
222
+ try:
223
+ text = raw.decode("utf-8")
224
+ except UnicodeDecodeError as exc:
225
+ raise LocalError("optional_source_not_text") from exc
226
+ units.append(
227
+ {
228
+ "observation": identifier,
229
+ "content_hash": row["blob"],
230
+ "start_byte": 0,
231
+ "end_byte": len(raw),
232
+ "text": text,
233
+ }
234
+ )
235
+ return units
236
+
237
+ def claims(self, who: dict[str, Any], args: dict[str, Any], at: int) -> list[dict[str, str]]:
238
+ if not args["claims"]:
239
+ return []
240
+ query_args = {
241
+ key: args[key]
242
+ for key in ("project", "task", "run", "bindings")
243
+ if args[key] is not None
244
+ }
245
+ current = self.k.query(who, query_args, at, constraints=False)
246
+ if any(set(pair).intersection(args["claims"]) for pair in current.get("conflicts", [])):
247
+ raise LocalError("optional_claim_conflict")
248
+ eligible = {item["revision"]: item for item in current["items"]}
249
+ selected = []
250
+ for revision in args["claims"]:
251
+ item = eligible.get(revision)
252
+ if item is None or item["authority"] != "accepted_knowledge":
253
+ raise LocalError("optional_claim_unavailable")
254
+ claim = self.r._claim(item)
255
+ if not {span["observation"] for span in claim["evidence"]}.issubset(args["sources"]):
256
+ raise LocalError("optional_claim_sources_incomplete")
257
+ selected.append(claim)
258
+ return self.r._dependencies(selected)
259
+
260
+ def compile(
261
+ self, who: dict[str, Any], args: dict[str, Any], decision: Decision, receipt: str
262
+ ) -> tuple[bytes, list[dict[str, str]]]:
263
+ raw, deps = self.w._resume(who, args, decision, receipt, retain=False)
264
+ packet, at = json.loads(raw), decision.evaluated_ms
265
+ if packet["status"] in {"ready", "incomplete"}:
266
+ try:
267
+ units = self.sources(who, args, at)
268
+ claim_deps = self.claims(who, args, at)
269
+ summary = validate(units, packet, args["candidate"])
270
+ except LocalError as exc:
271
+ units, claim_deps = [], []
272
+ summary = {"mode": "omitted", "reason": exc.code, "quotes": []}
273
+ candidate = args["candidate"]
274
+ if candidate is not None:
275
+ summary["usage_attempt"] = self.attest_usage(
276
+ who,
277
+ args["project"],
278
+ candidate["attempt"],
279
+ "compression",
280
+ candidate["provenance"],
281
+ at,
282
+ )
283
+ summary["provenance"] = {**candidate["provenance"], "assurance": "actor_reported"}
284
+ # Candidates cannot set any checkpoint, policy, operation, or recovery field.
285
+ packet["optional_explanation"] = summary
286
+ count, _ = counter(args["tokenizer"])
287
+ candidate_raw, used = counted(packet, count)
288
+ if used > args["max_output_tokens"] or len(candidate_raw) > 262144:
289
+ packet["optional_explanation"] = {
290
+ "mode": "omitted",
291
+ "reason": "optional_budget",
292
+ "quotes": [],
293
+ }
294
+ candidate_raw, used = counted(packet, count)
295
+ units, claim_deps = [], []
296
+ if used <= args["max_output_tokens"] and len(candidate_raw) <= 262144:
297
+ raw = candidate_raw
298
+ deps.extend(claim_deps)
299
+ deps.extend({"kind": "observation", "id": unit["observation"]} for unit in units)
300
+ # If even the omission marker does not fit, retain the complete original.
301
+ result = json.loads(raw)
302
+ self.r._retain(
303
+ who,
304
+ {"project": args["project"], "action": "processing_compile"},
305
+ receipt,
306
+ raw,
307
+ {
308
+ "kind": "processing_compile",
309
+ "status": result["status"],
310
+ "trace": [],
311
+ "usage": result["usage"],
312
+ "optional": result.get("optional_explanation", {}).get("reason", "not_rendered"),
313
+ },
314
+ deps,
315
+ at,
316
+ )
317
+ return raw, deps
318
+
319
+ def usage(self, who: dict[str, Any], args: dict[str, Any]) -> dict[str, Any]:
320
+ rows = self.db.execute(
321
+ "SELECT * FROM processing_usage WHERE tenant=? AND project=? ORDER BY id LIMIT 100001",
322
+ (who["tenant"], args["project"]),
323
+ ).fetchall()
324
+ records = [
325
+ UsageRecord(
326
+ row["id"],
327
+ row["provider"],
328
+ row["fingerprint"],
329
+ row["stage"],
330
+ row["status"],
331
+ row["input_tokens"],
332
+ row["cached_input_tokens"],
333
+ row["output_tokens"],
334
+ row["cost_microusd"],
335
+ row["duration_ms"],
336
+ )
337
+ for row in rows
338
+ ]
339
+ return {
340
+ **summarize(records, args["successful_tasks"]),
341
+ "coverage": "retained_processing_records_only_not_complete_task_cost",
342
+ "task_outcomes": "caller_reported_not_validated",
343
+ "attested_duration": "not_observed_zero_placeholder",
344
+ "history_incarnations": sorted({row["incarnation"] for row in rows}),
345
+ "savings_qualification": "not_evaluated",
346
+ }
@@ -0,0 +1,83 @@
1
+ """Projects a principal may currently read, with counts, for dashboards and CLIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from memoryking.adapters.local_store import identifier
9
+ from memoryking.application.store_core import StoreCore
10
+ from memoryking.domain.local import temporal_valid
11
+
12
+
13
+ def visible_projects(store: StoreCore, credential: str, at: int) -> list[dict[str, Any]]:
14
+ """Projects the credential can read now, with observation, claim, task and receipt counts.
15
+
16
+ A tenant-wide grant lists every project that holds records; a scoped grant lists only
17
+ its own project, whether or not it holds records yet. Counts are tenant-wide per
18
+ project and describe presence, not what this principal may see of each record.
19
+ """
20
+ identity = store._decode(credential, "credential")
21
+ tenant, principal = identity["tenant"], identity["principal"]
22
+ db = store.db
23
+ readable: set[str] = set()
24
+ everything = False
25
+ for row in db.execute(
26
+ "SELECT project,capabilities,starts,expires FROM grants WHERE tenant=? AND principal=?",
27
+ (tenant, principal),
28
+ ).fetchall():
29
+ capabilities = row["capabilities"]
30
+ if isinstance(capabilities, str):
31
+ capabilities = json.loads(capabilities)
32
+ if "read" not in capabilities or not temporal_valid(at, row["starts"], row["expires"]):
33
+ continue
34
+ if row["project"] == "*":
35
+ everything = True
36
+ else:
37
+ readable.add(row["project"])
38
+ counts: dict[str, dict[str, int]] = {}
39
+
40
+ def tally(statement: str, field: str) -> None:
41
+ for row in db.execute(statement, (tenant,)).fetchall():
42
+ project = row[0]
43
+ if project is None or (not everything and project not in readable):
44
+ continue
45
+ counts.setdefault(project, {})[field] = int(row[1])
46
+
47
+ tally(
48
+ "SELECT project,count(*) FROM observations WHERE tenant=? AND deleted=0 GROUP BY project",
49
+ "observations",
50
+ )
51
+ tally(
52
+ "SELECT f.project,count(*) FROM revisions r JOIN families f ON r.tenant=f.tenant AND r.family=f.id WHERE r.tenant=? AND r.purged=0 GROUP BY f.project",
53
+ "claims",
54
+ )
55
+ tally(
56
+ "SELECT project,count(*) FROM checkpoint_streams WHERE tenant=? GROUP BY project",
57
+ "tasks",
58
+ )
59
+ tally(
60
+ "SELECT o.project,max(e.at_ms) FROM events e JOIN observations o ON o.tenant=e.tenant AND o.id=e.subject WHERE e.tenant=? GROUP BY o.project",
61
+ "last_activity_ms",
62
+ )
63
+ tally(
64
+ "SELECT project,count(*) FROM rendered_artifacts WHERE tenant=? AND state='retained' GROUP BY project",
65
+ "receipts",
66
+ )
67
+ for project in readable:
68
+ counts.setdefault(project, {})
69
+ items = []
70
+ for project in sorted(counts):
71
+ identifier(project)
72
+ entry = counts[project]
73
+ items.append(
74
+ {
75
+ "project": project,
76
+ "observations": entry.get("observations", 0),
77
+ "claims": entry.get("claims", 0),
78
+ "tasks": entry.get("tasks", 0),
79
+ "receipts": entry.get("receipts", 0),
80
+ "last_activity_ms": entry.get("last_activity_ms"),
81
+ }
82
+ )
83
+ return items
@@ -0,0 +1,238 @@
1
+ """Proposal drafts from repeated evidence: a review queue that is never empty.
2
+
3
+ Every other memory system lets a model extract facts on write. MemoryKing keeps the
4
+ review layer, so this engine only *drafts*: it looks for a name that several
5
+ independent observations share (an anchor such as a path, a ticket or a host, or
6
+ failing that a rare term), takes the most recent sentence that carries it, and files
7
+ an ordinary proposal with one evidence span per supporting observation. The draft is
8
+ a `knowledge` claim in state `proposed` with authority left to the reviewer; nothing
9
+ it writes can become a constraint or reach a briefing as accepted knowledge until a
10
+ person or an authorized reviewer accepts it. Deterministic, bounded, no model.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import re
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from memoryking.contracts.canonical import canonical_hash
20
+ from memoryking.domain.briefing import terms
21
+
22
+ if TYPE_CHECKING:
23
+ from memoryking.adapters.knowledge_store import Knowledge
24
+
25
+ WINDOW = 512 # newest observations considered
26
+ MIN_SUPPORT = 2 # distinct observations before a draft is filed
27
+ MAX_SUPPORT = 16 # the contract's evidence cap per revision
28
+ MAX_HOLDERS = 32 # an anchor held by more records than this is not a topic but a word
29
+ TERM_HOLDERS = 8 # a term shared by more than this many records is too common to anchor
30
+ SENTENCE_LIMIT = 512
31
+ METHOD = "repeated_evidence_v1"
32
+ # A sentence ends at ., ! or ? followed by whitespace or the end, or at a newline, so
33
+ # the dot inside `payments/retry.py` or `quartz.internal` never splits one.
34
+ _SENTENCE = re.compile(r"[^\n]+?(?:[.!?](?=\s|$)|(?=\n)|$)")
35
+
36
+
37
+ def _sentence_with(text: str, needle: str) -> tuple[int, int, str] | None:
38
+ """The first sentence containing `needle`: byte offsets and the bounded text."""
39
+ wanted = needle.casefold()
40
+ for match in _SENTENCE.finditer(text):
41
+ piece = match.group(0)
42
+ sentence = piece.strip()
43
+ if not sentence:
44
+ continue
45
+ if wanted not in sentence.casefold():
46
+ continue
47
+ start = match.start() + (len(piece) - len(piece.lstrip()))
48
+ sentence = sentence[:SENTENCE_LIMIT]
49
+ byte_start = len(text[:start].encode())
50
+ return byte_start, byte_start + len(sentence.encode()), sentence
51
+ return None
52
+
53
+
54
+ class Proposals:
55
+ def __init__(self, knowledge: Knowledge):
56
+ self.k, self.s, self.db = knowledge, knowledge.s, knowledge.db
57
+
58
+ def _window(self, who: dict[str, Any], project: str, at: int) -> list[dict[str, Any]]:
59
+ from memoryking.adapters.retrieval import Retrieval
60
+
61
+ retrieval = Retrieval(self.s)
62
+ rows = self.db.execute(
63
+ "SELECT * FROM observations WHERE tenant=? AND project=? AND deleted=0 ORDER BY position DESC,id DESC LIMIT ?",
64
+ (who["tenant"], project, WINDOW),
65
+ ).fetchall()
66
+ items = []
67
+ for row in rows:
68
+ if not self.s._visible(who, row, at):
69
+ continue
70
+ raw = retrieval._blob(row)
71
+ items.append(
72
+ {
73
+ "id": row["id"],
74
+ "blob": row["blob"],
75
+ "position": row["position"],
76
+ "source_event": row["source_event"],
77
+ "text": raw.decode("utf-8", "replace"),
78
+ }
79
+ )
80
+ return items
81
+
82
+ def _groups(self, who: dict[str, Any], items: list[dict[str, Any]]) -> list[dict[str, Any]]:
83
+ """Candidate topics: shared anchors first, then shared rare terms."""
84
+ by_id = {item["id"]: item for item in items}
85
+ groups: list[dict[str, Any]] = []
86
+ seen_members: set[frozenset[str]] = set()
87
+ if items:
88
+ ids = list(by_id)
89
+ holders: dict[str, list[str]] = {}
90
+ kinds: dict[str, str] = {}
91
+ for start in range(0, len(ids), 500):
92
+ chunk = ids[start : start + 500]
93
+ for row in self.db.execute(
94
+ "SELECT id,anchor,kind FROM anchors WHERE tenant=? AND id IN ("
95
+ + ",".join("?" for _ in chunk)
96
+ + ") ORDER BY anchor,id",
97
+ (who["tenant"], *chunk),
98
+ ).fetchall():
99
+ holders.setdefault(row["anchor"], []).append(row["id"])
100
+ kinds[row["anchor"]] = row["kind"]
101
+ for anchor, members in sorted(holders.items()):
102
+ unique = sorted(set(members))
103
+ if not MIN_SUPPORT <= len(unique) <= MAX_HOLDERS:
104
+ continue
105
+ key = frozenset(unique)
106
+ if key in seen_members:
107
+ continue
108
+ seen_members.add(key)
109
+ groups.append({"topic": anchor, "basis": kinds[anchor], "members": unique})
110
+ if items:
111
+ frequency: dict[str, list[str]] = {}
112
+ for item in items:
113
+ for term in set(terms(item["text"])):
114
+ if len(term) >= 5:
115
+ frequency.setdefault(term, []).append(item["id"])
116
+ for term, members in sorted(frequency.items()):
117
+ unique = sorted(set(members))
118
+ if not MIN_SUPPORT <= len(unique) <= TERM_HOLDERS:
119
+ continue
120
+ key = frozenset(unique)
121
+ if key in seen_members:
122
+ continue
123
+ seen_members.add(key)
124
+ groups.append({"topic": term, "basis": "term", "members": unique})
125
+ return groups
126
+
127
+ def draft(
128
+ self, credential: str, who: dict[str, Any], args: dict[str, Any], at: int
129
+ ) -> dict[str, Any]:
130
+ project = args["project"]
131
+ limit = args.get("limit", 16)
132
+ items = self._window(who, project, at)
133
+ by_id = {item["id"]: item for item in items}
134
+ drafted: list[dict[str, Any]] = []
135
+ skipped: dict[str, int] = {"already_proposed": 0, "single_source": 0, "no_sentence": 0}
136
+ for group in self._groups(who, items):
137
+ if len(drafted) >= limit:
138
+ skipped["limit"] = skipped.get("limit", 0) + 1
139
+ continue
140
+ members = [by_id[i] for i in group["members"]]
141
+ # Repetition means independent occurrences, not one event captured twice.
142
+ if len({m["source_event"] for m in members}) < MIN_SUPPORT:
143
+ skipped["single_source"] += 1
144
+ continue
145
+ spans = []
146
+ sentence = None
147
+ for member in sorted(members, key=lambda m: -m["position"])[:MAX_SUPPORT]:
148
+ found = _sentence_with(member["text"], group["topic"])
149
+ if found is None:
150
+ continue
151
+ start, end, text = found
152
+ if sentence is None:
153
+ sentence = text
154
+ spans.append(
155
+ {
156
+ "observation": member["id"],
157
+ "start_byte": start,
158
+ "end_byte": end,
159
+ "content_hash": member["blob"],
160
+ }
161
+ )
162
+ if sentence is None or len(spans) < MIN_SUPPORT:
163
+ skipped["no_sentence"] += 1
164
+ continue
165
+ logical_key = "draft-" + hashlib.sha256(group["topic"].encode()).hexdigest()[:40]
166
+ family = self.db.execute(
167
+ "SELECT id,version FROM families WHERE tenant=? AND project=? AND logical_key=?",
168
+ (who["tenant"], project, logical_key),
169
+ ).fetchone()
170
+ version = 0
171
+ if family is not None:
172
+ version = family["version"]
173
+ latest = self.db.execute(
174
+ "SELECT id,purged FROM revisions WHERE tenant=? AND family=? ORDER BY created DESC LIMIT 1",
175
+ (who["tenant"], family["id"]),
176
+ ).fetchone()
177
+ if latest is not None and not latest["purged"]:
178
+ existing = {
179
+ row["observation"]
180
+ for row in self.db.execute(
181
+ "SELECT observation FROM evidence_spans WHERE tenant=? AND revision=?",
182
+ (who["tenant"], latest["id"]),
183
+ ).fetchall()
184
+ }
185
+ if {s["observation"] for s in spans} <= existing:
186
+ skipped["already_proposed"] += 1
187
+ continue
188
+ body = {
189
+ "text": sentence,
190
+ "kind": "knowledge",
191
+ "selector": {"selector_version": "1", "any_of": [{"all_of": [{"op": "any"}]}]},
192
+ "valid_start": None,
193
+ "valid_end": None,
194
+ "task": None,
195
+ "run": None,
196
+ "readers": None,
197
+ "evidence": spans,
198
+ "authority": None,
199
+ "rule_key": None,
200
+ "effect": None,
201
+ "rule_value": None,
202
+ "provenance": {
203
+ "method": METHOD,
204
+ "topic": group["topic"],
205
+ "basis": group["basis"],
206
+ "support": len(spans),
207
+ "drafted_by": who["principal"],
208
+ },
209
+ }
210
+ result = self.k.propose(
211
+ credential,
212
+ who,
213
+ {
214
+ "project": project,
215
+ "logical_key": logical_key,
216
+ "expected_version": version,
217
+ "body": body,
218
+ },
219
+ at,
220
+ )
221
+ drafted.append(
222
+ {
223
+ "revision": result["revision"],
224
+ "family": result["family"],
225
+ "topic": group["topic"],
226
+ "basis": group["basis"],
227
+ "support": len(spans),
228
+ "text": sentence,
229
+ }
230
+ )
231
+ return {
232
+ "drafted": drafted,
233
+ "skipped": skipped,
234
+ "window": len(items),
235
+ "method": METHOD,
236
+ "coverage": f"newest_{WINDOW}_visible_observations; anchors_then_rare_terms; drafts_are_proposals_awaiting_review",
237
+ "digest": canonical_hash([d["revision"] for d in drafted]),
238
+ }