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,300 @@
1
+ """Explicit PostgreSQL provisioning boundary; never imported by domain code.
2
+
3
+ Role creation is a privileged deployment operation. Runtime pools cannot migrate,
4
+ create tenants, or read credentials from this module.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import secrets
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from psycopg import sql
16
+
17
+ from memoryking.adapters.local_files import Control, atomic, private_dir, sync_dir
18
+ from memoryking.adapters.local_store import CAPABILITIES, identifier, paths, uid
19
+ from memoryking.contracts.canonical import canonical_bytes
20
+ from memoryking.domain.local import LocalError
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Roles:
25
+ migration: str = "mk_migration"
26
+ runtime: str = "mk_runtime"
27
+ worker: str = "mk_worker"
28
+ backup: str = "mk_backup"
29
+
30
+ def __post_init__(self) -> None:
31
+ values = (self.migration, self.runtime, self.worker, self.backup)
32
+ if len(set(values)) != 4:
33
+ raise ValueError("Database roles must be distinct")
34
+ for value in values:
35
+ identifier(value)
36
+
37
+
38
+ def provision_roles(admin: Any, roles: Roles | None = None) -> None:
39
+ """Create fresh least-privileged roles, with no password or membership inheritance.
40
+
41
+ Deployment must separately configure SCRAM secrets or certificate authentication.
42
+ Private Unix-socket test fixtures authenticate these names only inside their fixture.
43
+ Existing roles are rejected rather than silently trusting their privileges.
44
+ """
45
+ roles = roles or Roles()
46
+ with admin.transaction():
47
+ for role in (roles.migration, roles.runtime, roles.worker, roles.backup):
48
+ admin.execute(
49
+ sql.SQL(
50
+ "CREATE ROLE {} LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE "
51
+ "NOREPLICATION NOBYPASSRLS"
52
+ ).format(sql.Identifier(role))
53
+ )
54
+ admin.execute(
55
+ sql.SQL("CREATE SCHEMA memoryking AUTHORIZATION {}").format(
56
+ sql.Identifier(roles.migration)
57
+ )
58
+ )
59
+ admin.execute("REVOKE ALL ON SCHEMA public FROM PUBLIC")
60
+ admin.execute("REVOKE ALL ON SCHEMA memoryking FROM PUBLIC")
61
+
62
+
63
+ def enable_vector(admin: Any, roles: Roles | None = None) -> None:
64
+ """Explicit operator action after installing pgvector 0.8.7; never automatic."""
65
+ roles = roles or Roles()
66
+ with admin.transaction():
67
+ if not admin.execute("SELECT rolsuper FROM pg_roles WHERE rolname=current_user").fetchone()[
68
+ 0
69
+ ]:
70
+ raise LocalError("extension_administrator_required")
71
+ existing = admin.execute(
72
+ "SELECT e.extversion,n.nspname FROM pg_extension e JOIN pg_namespace n ON e.extnamespace=n.oid WHERE e.extname='vector'"
73
+ ).fetchone()
74
+ if existing is not None and tuple(existing) != ("0.8.7", "memoryking_vector"):
75
+ raise LocalError("vector_extension_mismatch")
76
+ if existing is None:
77
+ # Refuse a pre-existing schema; its ownership/functions are unknown.
78
+ admin.execute("CREATE SCHEMA memoryking_vector")
79
+ admin.execute("CREATE EXTENSION vector WITH SCHEMA memoryking_vector VERSION '0.8.7'")
80
+ admin.execute("REVOKE ALL ON SCHEMA memoryking_vector FROM PUBLIC")
81
+ admin.execute("REVOKE ALL ON ALL FUNCTIONS IN SCHEMA memoryking_vector FROM PUBLIC")
82
+ for role in (roles.runtime, roles.worker):
83
+ admin.execute(
84
+ sql.SQL("GRANT USAGE ON SCHEMA memoryking_vector TO {}").format(
85
+ sql.Identifier(role)
86
+ )
87
+ )
88
+ admin.execute(
89
+ sql.SQL("GRANT USAGE ON TYPE memoryking_vector.vector TO {}").format(
90
+ sql.Identifier(role)
91
+ )
92
+ )
93
+ admin.execute(
94
+ sql.SQL("GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA memoryking_vector TO {}").format(
95
+ sql.Identifier(role)
96
+ )
97
+ )
98
+
99
+
100
+ def migrate(connection: Any, roles: Roles | None = None) -> None:
101
+ """Apply supported migrations transactionally as the separate owner, offline."""
102
+ roles = roles or Roles()
103
+ with connection.transaction():
104
+ role = connection.execute("SELECT current_user").fetchone()[0]
105
+ if role != roles.migration:
106
+ raise LocalError("migration_role_required")
107
+ connection.execute("SET LOCAL search_path=memoryking,pg_catalog")
108
+ connection.execute("SELECT pg_advisory_xact_lock(71102308)")
109
+ if connection.execute("SELECT to_regclass('memoryking.shared_meta')").fetchone()[0] is None:
110
+ connection.execute(Path(__file__).with_name("postgres_schema.sql").read_text())
111
+ connection.execute("INSERT INTO shared_meta VALUES ('schema','1')")
112
+ version = connection.execute("SELECT value FROM shared_meta WHERE key='schema'").fetchone()
113
+ if version is None or version[0] not in {"1", "2", "3", "4", "5", "6", "7", "8"}:
114
+ raise LocalError("schema_unsupported")
115
+ if version[0] == "1":
116
+ connection.execute(Path(__file__).with_name("postgres_optional_schema.sql").read_text())
117
+ connection.execute("UPDATE shared_meta SET value='2' WHERE key='schema'")
118
+ if version[0] in {"1", "2"}:
119
+ connection.execute(
120
+ Path(__file__).with_name("postgres_experience_schema.sql").read_text()
121
+ )
122
+ connection.execute("UPDATE shared_meta SET value='3' WHERE key='schema'")
123
+ if version[0] in {"1", "2", "3"}:
124
+ connection.execute(Path(__file__).with_name("postgres_counter.sql").read_text())
125
+ connection.execute(Path(__file__).with_name("postgres_index_schema.sql").read_text())
126
+ connection.execute("UPDATE shared_meta SET value='4' WHERE key='schema'")
127
+ if version[0] in {"1", "2", "3", "4"}:
128
+ connection.execute(Path(__file__).with_name("postgres_egress_schema.sql").read_text())
129
+ connection.execute("UPDATE shared_meta SET value='5' WHERE key='schema'")
130
+ if version[0] in {"1", "2", "3", "4", "5"}:
131
+ connection.execute(Path(__file__).with_name("postgres_summary_schema.sql").read_text())
132
+ connection.execute("UPDATE shared_meta SET value='6' WHERE key='schema'")
133
+ if version[0] in {"1", "2", "3", "4", "5", "6"}:
134
+ connection.execute(Path(__file__).with_name("postgres_trust_schema.sql").read_text())
135
+ connection.execute("UPDATE shared_meta SET value='7' WHERE key='schema'")
136
+ if version[0] in {"1", "2", "3", "4", "5", "6", "7"}:
137
+ connection.execute(Path(__file__).with_name("postgres_anchor_schema.sql").read_text())
138
+ connection.execute("UPDATE shared_meta SET value='8' WHERE key='schema'")
139
+ connection.execute("REVOKE ALL ON ALL TABLES IN SCHEMA memoryking FROM PUBLIC")
140
+ connection.execute("REVOKE ALL ON ALL FUNCTIONS IN SCHEMA memoryking FROM PUBLIC")
141
+ tables = [
142
+ r[0]
143
+ for r in connection.execute(
144
+ "SELECT tablename FROM pg_tables WHERE schemaname='memoryking' "
145
+ "AND tablename!='shared_meta' ORDER BY tablename"
146
+ )
147
+ ]
148
+ for role in (roles.runtime, roles.worker, roles.backup):
149
+ connection.execute(
150
+ sql.SQL("GRANT USAGE ON SCHEMA memoryking TO {}").format(sql.Identifier(role))
151
+ )
152
+ connection.execute(
153
+ sql.SQL("GRANT SELECT ON ALL TABLES IN SCHEMA memoryking TO {}").format(
154
+ sql.Identifier(role)
155
+ )
156
+ )
157
+ connection.execute(
158
+ sql.SQL("GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA memoryking TO {}").format(
159
+ sql.Identifier(role)
160
+ )
161
+ )
162
+ for table in [*tables, "meta"]:
163
+ connection.execute(
164
+ sql.SQL("GRANT INSERT,UPDATE,DELETE ON {} TO {}").format(
165
+ sql.Identifier(table), sql.Identifier(roles.runtime)
166
+ )
167
+ )
168
+ # Workers can materialize projections and record their bounded release receipts;
169
+ # they cannot create policy, content, checkpoint or handoff records, rewrite or
170
+ # delete receipts, or touch tenant counters except through the owner-run function.
171
+ for table in (
172
+ "jobs",
173
+ "projections",
174
+ "projection_items",
175
+ "repository_jobs",
176
+ "embedding_jobs",
177
+ "embedding_items",
178
+ "processing_usage",
179
+ "code_validations",
180
+ "meta",
181
+ ):
182
+ connection.execute(
183
+ sql.SQL("GRANT INSERT,UPDATE,DELETE ON {} TO {}").format(
184
+ sql.Identifier(table), sql.Identifier(roles.worker)
185
+ )
186
+ )
187
+ for table in ("receipts", "tenant_meta"):
188
+ connection.execute(
189
+ sql.SQL("REVOKE INSERT,UPDATE,DELETE ON {} FROM {}").format(
190
+ sql.Identifier(table), sql.Identifier(roles.worker)
191
+ )
192
+ )
193
+ connection.execute(
194
+ sql.SQL("GRANT INSERT ON receipts TO {}").format(sql.Identifier(roles.worker))
195
+ )
196
+ connection.execute(
197
+ sql.SQL("REVOKE EXECUTE ON FUNCTION next_commit_serial(text,bigint) FROM {}").format(
198
+ sql.Identifier(roles.backup)
199
+ )
200
+ )
201
+ # SELECT FOR UPDATE/SHARE requires UPDATE permission even on the lock-only row.
202
+ connection.execute(
203
+ sql.SQL("GRANT UPDATE ON tenant_gates TO {}").format(sql.Identifier(roles.worker))
204
+ )
205
+ connection.execute(
206
+ sql.SQL("GRANT UPDATE(scheduled,frontier) ON embedding_partitions TO {}").format(
207
+ sql.Identifier(roles.worker)
208
+ )
209
+ )
210
+ for table in tables:
211
+ if connection.execute(
212
+ "SELECT 1 FROM pg_policies WHERE schemaname='memoryking' AND tablename=%s AND policyname='backup_read'",
213
+ (table,),
214
+ ).fetchone():
215
+ continue
216
+ connection.execute(
217
+ sql.SQL("CREATE POLICY backup_read ON {} FOR SELECT TO {} USING (true)").format(
218
+ sql.Identifier(table), sql.Identifier(roles.backup)
219
+ )
220
+ )
221
+
222
+
223
+ def initialize_tenant(
224
+ connection: Any,
225
+ root: Path,
226
+ control: Path,
227
+ tenant: str,
228
+ principal: str = "owner",
229
+ audience: str = "memoryking-shared",
230
+ ) -> Path:
231
+ """Create a fresh tenant plus independent private identity/control volume.
232
+
233
+ Run offline as migration owner. Incomplete provisioning is fail closed and must
234
+ be reconciled explicitly; existing directories and tenant identifiers are refused.
235
+ """
236
+ identifier(tenant)
237
+ identifier(principal)
238
+ identifier(audience)
239
+ paths(root, control)
240
+ private_dir(root, create=True)
241
+ private_dir(root / "blobs", create=True)
242
+ private_dir(control, create=True)
243
+ tenant_control = control / tenant
244
+ if tenant_control.exists():
245
+ raise LocalError("initialization_requires_new_directories")
246
+ private_dir(tenant_control, create=True)
247
+ store, incarnation = uid("store"), uid("hist")
248
+ atomic(
249
+ tenant_control / "identity.json",
250
+ canonical_bytes({"store": store, "key": secrets.token_hex(32)}),
251
+ )
252
+ atomic(tenant_control / "journal", b"")
253
+ controller = Control(tenant_control)
254
+ anchor = {
255
+ "store": store,
256
+ "incarnation": incarnation,
257
+ "state": "provisioning",
258
+ "frontiers": {},
259
+ "journal_sequence": 0,
260
+ "journal_head": "0" * 64,
261
+ "last_utc": 0,
262
+ "commit_serial": 0,
263
+ }
264
+ controller.anchor(anchor)
265
+ with connection.transaction():
266
+ connection.execute("SET LOCAL search_path=memoryking,pg_catalog")
267
+ connection.execute("SELECT set_config('memoryking.tenant',%s,true)", (tenant,))
268
+ connection.execute("INSERT INTO tenants(tenant) VALUES (%s)", (tenant,))
269
+ connection.execute("INSERT INTO tenant_gates VALUES (%s)", (tenant,))
270
+ for key, value in (
271
+ ("store", store),
272
+ ("incarnation", incarnation),
273
+ ("journal", "0"),
274
+ ("commit_serial", "0"),
275
+ ):
276
+ connection.execute("INSERT INTO tenant_meta VALUES (%s,%s,%s)", (tenant, key, value))
277
+ connection.execute(
278
+ "INSERT INTO grants VALUES (%s,%s,'*',%s,NULL,NULL)",
279
+ (tenant, principal, json.dumps(sorted(CAPABILITIES))),
280
+ )
281
+ connection.execute(
282
+ "INSERT INTO projections VALUES (%s,%s,'audit_probe','v1',1,0)", (tenant, incarnation)
283
+ )
284
+ connection.execute("INSERT INTO knowledge_state(tenant) VALUES (%s)", (tenant,))
285
+ anchor["state"] = "active"
286
+ controller.anchor(anchor)
287
+ token = controller.sign(
288
+ {
289
+ "kind": "credential",
290
+ "store": store,
291
+ "incarnation": incarnation,
292
+ "tenant": tenant,
293
+ "principal": principal,
294
+ "audience": audience,
295
+ }
296
+ )
297
+ credential = tenant_control / "owner.credential"
298
+ atomic(credential, token.encode())
299
+ sync_dir(control)
300
+ return credential
@@ -0,0 +1,9 @@
1
+ CREATE TABLE IF NOT EXISTS anchors (
2
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, anchor TEXT NOT NULL, kind TEXT NOT NULL,
3
+ PRIMARY KEY(tenant,id,anchor));
4
+ CREATE INDEX IF NOT EXISTS anchors_lookup ON anchors(tenant,anchor,id);
5
+ ALTER TABLE anchors ENABLE ROW LEVEL SECURITY;
6
+ ALTER TABLE anchors FORCE ROW LEVEL SECURITY;
7
+ CREATE POLICY tenant_isolation ON anchors
8
+ USING (tenant = current_setting('memoryking.tenant',true))
9
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
@@ -0,0 +1,14 @@
1
+ -- Commit serial advancement runs as the table owner so worker and runtime roles need no
2
+ -- UPDATE right on tenant_meta. The function honors the session tenant like row security.
3
+ CREATE OR REPLACE FUNCTION memoryking.next_commit_serial(target text, maximum bigint)
4
+ RETURNS bigint
5
+ LANGUAGE sql
6
+ SECURITY DEFINER
7
+ SET search_path = memoryking, pg_catalog
8
+ AS $$
9
+ UPDATE memoryking.tenant_meta SET value=(value::bigint+1)::text
10
+ WHERE tenant=target AND key='commit_serial' AND value::bigint<maximum
11
+ AND tenant=current_setting('memoryking.tenant', true)
12
+ RETURNING value::bigint
13
+ $$;
14
+ REVOKE ALL ON FUNCTION memoryking.next_commit_serial(text, bigint) FROM PUBLIC;
@@ -0,0 +1,15 @@
1
+ CREATE TABLE IF NOT EXISTS egress_audit (
2
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, principal TEXT NOT NULL,
3
+ project TEXT NOT NULL, incarnation TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL,
4
+ host TEXT NOT NULL, policy_revision TEXT NOT NULL, request_hash TEXT NOT NULL,
5
+ manifest_hash TEXT NOT NULL, manifest TEXT NOT NULL, classification TEXT NOT NULL,
6
+ request_bytes BIGINT NOT NULL, evaluated BIGINT NOT NULL, deadline BIGINT NOT NULL,
7
+ status TEXT NOT NULL, wire_hash TEXT, response_hash TEXT, input_tokens BIGINT,
8
+ output_tokens BIGINT, reported BIGINT, expires BIGINT NOT NULL,
9
+ PRIMARY KEY(tenant,id));
10
+ CREATE INDEX IF NOT EXISTS egress_audit_project ON egress_audit(tenant,project,evaluated);
11
+ ALTER TABLE egress_audit ENABLE ROW LEVEL SECURITY;
12
+ ALTER TABLE egress_audit FORCE ROW LEVEL SECURITY;
13
+ CREATE POLICY tenant_isolation ON egress_audit
14
+ USING (tenant = current_setting('memoryking.tenant',true))
15
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
@@ -0,0 +1,39 @@
1
+ -- Native migration 2 -> 3: reviewed experience and frozen ranking decisions.
2
+ CREATE TABLE experience_records (
3
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, project TEXT NOT NULL,
4
+ principal TEXT NOT NULL, incarnation TEXT NOT NULL, kind TEXT NOT NULL,
5
+ logical_key TEXT NOT NULL, revision BIGINT NOT NULL, body TEXT,
6
+ body_hash TEXT NOT NULL, dependencies TEXT NOT NULL, readers TEXT,
7
+ position BIGINT NOT NULL,
8
+ PRIMARY KEY(tenant,id), UNIQUE(tenant,project,principal,incarnation,kind,logical_key,revision),
9
+ FOREIGN KEY(tenant,position) REFERENCES events(tenant,position));
10
+ CREATE INDEX experience_lookup ON experience_records(tenant,project,kind,position);
11
+ CREATE TABLE ranking_state (
12
+ tenant TEXT NOT NULL REFERENCES tenants, project TEXT NOT NULL, version BIGINT NOT NULL,
13
+ configuration TEXT, reconciliation BIGINT NOT NULL DEFAULT 0,
14
+ PRIMARY KEY(tenant,project),
15
+ FOREIGN KEY(tenant,configuration) REFERENCES experience_records(tenant,id));
16
+ CREATE TABLE ranking_history (
17
+ tenant TEXT NOT NULL, project TEXT NOT NULL, position BIGINT NOT NULL,
18
+ configuration TEXT, detail TEXT NOT NULL,
19
+ PRIMARY KEY(tenant,project,position),
20
+ FOREIGN KEY(tenant,configuration) REFERENCES experience_records(tenant,id),
21
+ FOREIGN KEY(tenant,position) REFERENCES events(tenant,position));
22
+
23
+ ALTER TABLE experience_records ENABLE ROW LEVEL SECURITY;
24
+ ALTER TABLE experience_records FORCE ROW LEVEL SECURITY;
25
+ CREATE POLICY tenant_isolation ON experience_records
26
+ USING (tenant = current_setting('memoryking.tenant',true))
27
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
28
+
29
+ ALTER TABLE ranking_state ENABLE ROW LEVEL SECURITY;
30
+ ALTER TABLE ranking_state FORCE ROW LEVEL SECURITY;
31
+ CREATE POLICY tenant_isolation ON ranking_state
32
+ USING (tenant = current_setting('memoryking.tenant',true))
33
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
34
+
35
+ ALTER TABLE ranking_history ENABLE ROW LEVEL SECURITY;
36
+ ALTER TABLE ranking_history FORCE ROW LEVEL SECURITY;
37
+ CREATE POLICY tenant_isolation ON ranking_history
38
+ USING (tenant = current_setting('memoryking.tenant',true))
39
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
@@ -0,0 +1,7 @@
1
+ -- Hot-path indexes for tables that only grow; applied with shared schema 4.
2
+ CREATE INDEX IF NOT EXISTS jobs_queue ON jobs(tenant,state,available,position);
3
+ CREATE INDEX IF NOT EXISTS jobs_observation ON jobs(tenant,observation);
4
+ CREATE INDEX IF NOT EXISTS observations_scope ON observations(tenant,project,position);
5
+ CREATE INDEX IF NOT EXISTS retries_observation ON retries(tenant,observation);
6
+ CREATE INDEX IF NOT EXISTS embedding_items_observation ON embedding_items(tenant,observation);
7
+ CREATE INDEX IF NOT EXISTS receipts_evaluated ON receipts(tenant,evaluated);
@@ -0,0 +1,71 @@
1
+ -- Native PostgreSQL shared migration 1 -> 2; no pgvector dependency.
2
+ CREATE TABLE embedding_partitions (
3
+ tenant TEXT NOT NULL REFERENCES tenants, project TEXT NOT NULL, fingerprint TEXT NOT NULL,
4
+ incarnation TEXT NOT NULL, generation BIGINT NOT NULL, dimensions BIGINT NOT NULL CHECK(dimensions BETWEEN 1 AND 4096),
5
+ configuration TEXT NOT NULL, state TEXT NOT NULL, scheduled BIGINT NOT NULL DEFAULT 0,
6
+ frontier BIGINT NOT NULL DEFAULT 0, created BIGINT NOT NULL,
7
+ PRIMARY KEY(tenant,project,fingerprint));
8
+ CREATE TABLE embedding_jobs (
9
+ tenant TEXT NOT NULL, project TEXT NOT NULL, fingerprint TEXT NOT NULL, generation BIGINT NOT NULL,
10
+ position BIGINT NOT NULL, observation TEXT, source_revision BIGINT NOT NULL, blob_hash TEXT,
11
+ incarnation TEXT NOT NULL, state TEXT NOT NULL, attempts BIGINT NOT NULL DEFAULT 0,
12
+ fence BIGINT NOT NULL DEFAULT 0, lease_until BIGINT NOT NULL DEFAULT 0,
13
+ available BIGINT NOT NULL DEFAULT 0, principal TEXT, purge_epoch BIGINT NOT NULL,
14
+ PRIMARY KEY(tenant,project,fingerprint,generation,position),
15
+ FOREIGN KEY(tenant,project,fingerprint) REFERENCES embedding_partitions(tenant,project,fingerprint),
16
+ FOREIGN KEY(tenant,position) REFERENCES events(tenant,position),
17
+ FOREIGN KEY(tenant,observation) REFERENCES observations(tenant,id));
18
+ CREATE INDEX embedding_queue ON embedding_jobs(tenant,project,fingerprint,state,position);
19
+ CREATE TABLE embedding_items (
20
+ tenant TEXT NOT NULL, project TEXT NOT NULL, fingerprint TEXT NOT NULL, generation BIGINT NOT NULL,
21
+ observation TEXT NOT NULL, incarnation TEXT NOT NULL, source_revision BIGINT NOT NULL,
22
+ blob_hash TEXT NOT NULL, input_hash TEXT NOT NULL, vector_json TEXT NOT NULL,
23
+ start_byte BIGINT NOT NULL, end_byte BIGINT NOT NULL, input_tokens BIGINT,
24
+ truncated BIGINT NOT NULL, position BIGINT NOT NULL,
25
+ PRIMARY KEY(tenant,project,fingerprint,generation,observation),
26
+ FOREIGN KEY(tenant,project,fingerprint) REFERENCES embedding_partitions(tenant,project,fingerprint),
27
+ FOREIGN KEY(tenant,observation) REFERENCES observations(tenant,id));
28
+ CREATE TABLE processing_usage (
29
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, project TEXT NOT NULL,
30
+ principal TEXT NOT NULL, incarnation TEXT NOT NULL, provider TEXT NOT NULL,
31
+ fingerprint TEXT NOT NULL, stage TEXT NOT NULL, status TEXT NOT NULL,
32
+ input_tokens BIGINT, cached_input_tokens BIGINT, output_tokens BIGINT,
33
+ cost_microusd BIGINT, duration_ms BIGINT NOT NULL, request_hash TEXT NOT NULL,
34
+ output_hash TEXT, dependencies TEXT NOT NULL, created BIGINT NOT NULL, expires BIGINT NOT NULL,
35
+ PRIMARY KEY(tenant,id));
36
+ CREATE TABLE adapter_bases (
37
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, project TEXT NOT NULL,
38
+ principal TEXT NOT NULL, incarnation TEXT NOT NULL, binding TEXT NOT NULL,
39
+ body BYTEA NOT NULL, body_hash TEXT NOT NULL, dependencies TEXT NOT NULL,
40
+ created BIGINT NOT NULL, expires BIGINT NOT NULL,
41
+ PRIMARY KEY(tenant,id));
42
+
43
+ ALTER TABLE embedding_partitions ENABLE ROW LEVEL SECURITY;
44
+ ALTER TABLE embedding_partitions FORCE ROW LEVEL SECURITY;
45
+ CREATE POLICY tenant_isolation ON embedding_partitions
46
+ USING (tenant = current_setting('memoryking.tenant',true))
47
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
48
+
49
+ ALTER TABLE embedding_jobs ENABLE ROW LEVEL SECURITY;
50
+ ALTER TABLE embedding_jobs FORCE ROW LEVEL SECURITY;
51
+ CREATE POLICY tenant_isolation ON embedding_jobs
52
+ USING (tenant = current_setting('memoryking.tenant',true))
53
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
54
+
55
+ ALTER TABLE embedding_items ENABLE ROW LEVEL SECURITY;
56
+ ALTER TABLE embedding_items FORCE ROW LEVEL SECURITY;
57
+ CREATE POLICY tenant_isolation ON embedding_items
58
+ USING (tenant = current_setting('memoryking.tenant',true))
59
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
60
+
61
+ ALTER TABLE processing_usage ENABLE ROW LEVEL SECURITY;
62
+ ALTER TABLE processing_usage FORCE ROW LEVEL SECURITY;
63
+ CREATE POLICY tenant_isolation ON processing_usage
64
+ USING (tenant = current_setting('memoryking.tenant',true))
65
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
66
+
67
+ ALTER TABLE adapter_bases ENABLE ROW LEVEL SECURITY;
68
+ ALTER TABLE adapter_bases FORCE ROW LEVEL SECURITY;
69
+ CREATE POLICY tenant_isolation ON adapter_bases
70
+ USING (tenant = current_setting('memoryking.tenant',true))
71
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
@@ -0,0 +1,77 @@
1
+ """Bounded primary-only PostgreSQL pool with explicit session sanitation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from psycopg.pq import TransactionStatus
8
+ from psycopg_pool import ConnectionPool, PoolClosed, PoolTimeout, TooManyRequests
9
+
10
+ from memoryking.adapters.postgres_sql import record_factory
11
+ from memoryking.domain.local import LocalError
12
+
13
+
14
+ def acquire(pool: Any, timeout: float | None = None) -> Any:
15
+ """Admission fails before a connection, transaction or mutation exists.
16
+
17
+ A request deadline can only shorten the wait for a free connection; the pool's
18
+ own limit is the most any caller waits."""
19
+ limit = getattr(pool, "timeout", None)
20
+ if timeout is not None:
21
+ limit = timeout if limit is None else min(limit, timeout)
22
+ try:
23
+ return pool.getconn() if limit is None else pool.getconn(timeout=max(0.0, limit))
24
+ except (PoolTimeout, TooManyRequests):
25
+ raise LocalError("service_busy") from None
26
+ except PoolClosed:
27
+ raise LocalError("service_unavailable") from None
28
+
29
+
30
+ def reset(connection: Any) -> None:
31
+ if connection.info.transaction_status != TransactionStatus.IDLE:
32
+ connection.rollback()
33
+ connection.execute("RESET ALL")
34
+ connection.execute("UNLISTEN *")
35
+ connection.execute("SELECT pg_advisory_unlock_all()")
36
+ if connection.info.transaction_status != TransactionStatus.IDLE:
37
+ raise LocalError("pool_reset_failed")
38
+
39
+
40
+ def check(connection: Any) -> None:
41
+ row = connection.execute(
42
+ "SELECT pg_is_in_recovery(),rolsuper,rolbypassrls,rolcreaterole,rolcreatedb,rolreplication "
43
+ "FROM pg_roles WHERE rolname=current_user"
44
+ ).fetchone()
45
+ if row is None or any(row):
46
+ raise LocalError("primary_nonprivileged_runtime_required")
47
+ owner = connection.execute(
48
+ "SELECT 1 FROM pg_tables WHERE schemaname='memoryking' AND tableowner=current_user LIMIT 1"
49
+ ).fetchone()
50
+ if owner:
51
+ raise LocalError("runtime_table_owner_forbidden")
52
+ for setting in ("fsync", "synchronous_commit", "full_page_writes"):
53
+ if connection.execute(f"SHOW {setting}").fetchone()[0] != "on":
54
+ raise LocalError("database_durability_required")
55
+
56
+
57
+ def create_pool(dsn: str, *, size: int = 8, timeout: float = 5) -> Any:
58
+ if not 1 <= size <= 64 or not 0 < timeout <= 30:
59
+ raise LocalError("invalid_pool_configuration")
60
+ pool = ConnectionPool(
61
+ dsn,
62
+ min_size=1,
63
+ max_size=size,
64
+ max_waiting=64,
65
+ timeout=timeout,
66
+ kwargs={
67
+ "autocommit": True,
68
+ "row_factory": record_factory,
69
+ "prepare_threshold": None,
70
+ "application_name": "memoryking",
71
+ },
72
+ reset=reset,
73
+ check=check,
74
+ open=False,
75
+ )
76
+ pool.open(wait=True, timeout=timeout)
77
+ return pool