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,194 @@
1
+ """Operator-only snapshot planning/import; no source writes or live routing changes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shutil
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from memoryking.adapters.legacy_snapshot import MAX_DATABASE, digest_file, inspect
13
+ from memoryking.adapters.local_files import atomic, private_dir, private_file, sync_dir
14
+ from memoryking.application.legacy_import import apply_batch, make_plan, reconcile, summary
15
+ from memoryking.contracts.canonical import canonical_bytes, load_strict
16
+ from memoryking.domain.local import LocalError
17
+ from memoryking.sdk import LocalClient
18
+ from memoryking.shared_sdk import SharedClient
19
+
20
+
21
+ class Operator:
22
+ def __init__(self, client: LocalClient):
23
+ self.client = client
24
+
25
+ def context(self) -> dict[str, Any]:
26
+ return self.client.context()
27
+
28
+ def capture(self, key: str, observation: dict[str, Any]) -> dict[str, Any]:
29
+ return self.client.capture(key, observation)
30
+
31
+ def read_legacy(self, handle: str) -> dict[str, Any]:
32
+ credential, _ = self.client._current()
33
+ return self.client._request(
34
+ credential, "read", {"project": self.client.project, "observation": handle}
35
+ )
36
+
37
+ def knowledge(self, command: dict[str, Any]) -> dict[str, Any]:
38
+ credential, _ = self.client._current()
39
+ return self.client._request(credential, "knowledge", {"command": command})
40
+
41
+
42
+ def freeze(source: Path, directory: Path) -> Path:
43
+ if (
44
+ directory.exists()
45
+ or directory.is_symlink()
46
+ or not source.is_file()
47
+ or source.is_symlink()
48
+ or not 0 < source.stat().st_size <= MAX_DATABASE
49
+ ):
50
+ raise LocalError("legacy_snapshot_destination_or_source_invalid")
51
+ if any(Path(str(source) + suffix).exists() for suffix in ("-wal", "-shm", "-journal")):
52
+ raise LocalError("legacy_snapshot_not_detached")
53
+ before = digest_file(source)
54
+ private_dir(directory, create=True)
55
+ target = directory / "source.sqlite"
56
+ with source.open("rb") as incoming, target.open("xb") as outgoing:
57
+ os.chmod(target, 0o600)
58
+ shutil.copyfileobj(incoming, outgoing)
59
+ outgoing.flush()
60
+ os.fsync(outgoing.fileno())
61
+ sync_dir(directory)
62
+ if digest_file(target) != before or digest_file(source) != before:
63
+ raise LocalError("legacy_source_changed")
64
+ atomic(
65
+ directory / "snapshot.json",
66
+ canonical_bytes(
67
+ {
68
+ "sha256": before,
69
+ "bytes": target.stat().st_size,
70
+ "method": "detached_snapshot_copy_hash_checked",
71
+ "source_modified": False,
72
+ }
73
+ ),
74
+ )
75
+ return target
76
+
77
+
78
+ def main() -> None:
79
+ parser = argparse.ArgumentParser(description=__doc__)
80
+ sub = parser.add_subparsers(dest="action", required=True)
81
+ copy = sub.add_parser(
82
+ "snapshot", help="Copy a detached SQLite backup; rejects WAL/journal sidecars"
83
+ )
84
+ copy.add_argument("--source", type=Path, required=True)
85
+ copy.add_argument("--directory", type=Path, required=True)
86
+ for name in ("inspect", "plan", "apply", "reconcile"):
87
+ command = sub.add_parser(name)
88
+ command.add_argument("--directory", type=Path, required=True)
89
+ if name in {"inspect", "plan"}:
90
+ command.add_argument(
91
+ "--source-id",
92
+ required=True,
93
+ help="Stable identity of the legacy database across snapshots",
94
+ )
95
+ command.add_argument(
96
+ "--profile",
97
+ choices=["kingforge-v1", "standalone", "universal"],
98
+ action="append",
99
+ required=True,
100
+ help="Repeat for coexisting profiles; all detected profiles must be declared",
101
+ )
102
+ if name != "inspect":
103
+ transport = command.add_mutually_exclusive_group(required=True)
104
+ transport.add_argument("--socket", type=Path)
105
+ transport.add_argument("--url")
106
+ command.add_argument("--tenant")
107
+ command.add_argument("--ca-file", type=Path)
108
+ command.add_argument("--credential", type=Path, required=True)
109
+ command.add_argument("--project", required=True)
110
+ if name == "apply":
111
+ command.add_argument("--start", type=int, default=0)
112
+ command.add_argument("--limit", type=int, default=100)
113
+ args = parser.parse_args()
114
+ try:
115
+ if args.action == "snapshot":
116
+ freeze(args.source, args.directory)
117
+ result: dict[str, Any] = {"snapshot_created": True, "source_modified": False}
118
+ else:
119
+ private_dir(args.directory)
120
+ path = args.directory / "source.sqlite"
121
+ private_file(path)
122
+ snapshot_receipt = args.directory / "snapshot.json"
123
+ private_file(snapshot_receipt)
124
+ if load_strict(snapshot_receipt.read_bytes())["sha256"] != digest_file(path):
125
+ raise LocalError("legacy_snapshot_hash_mismatch")
126
+ if args.action == "inspect":
127
+ data = summary(inspect(path, args.source_id, expected_profiles=args.profile))
128
+ # Inspections can exceed canonical wire size. This is a private
129
+ # local report, not an API payload or authority token.
130
+ atomic(
131
+ args.directory / "inspection.json",
132
+ (
133
+ json.dumps(
134
+ data, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False
135
+ )
136
+ + "\n"
137
+ ).encode(),
138
+ )
139
+ result = {
140
+ "tables": data["tables"],
141
+ "rows": len(data["rows"]),
142
+ "unresolved_count": len(data["unresolved"]),
143
+ "writes": 0,
144
+ }
145
+ else:
146
+ if args.url:
147
+ if not args.tenant:
148
+ raise LocalError("legacy_shared_tenant_required")
149
+ client: LocalClient = SharedClient(
150
+ args.url, args.tenant, args.credential, args.project, ca_file=args.ca_file
151
+ )
152
+ else:
153
+ client = LocalClient(args.socket, args.credential, args.project)
154
+ operator = Operator(client)
155
+ plan_path = args.directory / "plan.json"
156
+ if args.action == "plan":
157
+ if plan_path.exists():
158
+ raise LocalError("legacy_plan_exists_use_new_snapshot_directory")
159
+ plan = make_plan(path, args.source_id, args.profile, operator)
160
+ atomic(plan_path, canonical_bytes(plan))
161
+ result = {
162
+ "planned_rows": plan["rows"],
163
+ "unresolved_count": len(plan["unresolved"]),
164
+ "writes": 0,
165
+ "authority": plan["authority"],
166
+ }
167
+ else:
168
+ private_file(plan_path)
169
+ plan = load_strict(plan_path.read_bytes())
170
+ journal = args.directory / "journal"
171
+ if args.action == "apply":
172
+ result = apply_batch(
173
+ path, plan, operator, journal, start=args.start, limit=args.limit
174
+ )
175
+ name = f"batch-{args.start}.json"
176
+ else:
177
+ result = reconcile(path, plan, operator, journal)
178
+ name = "reconciliation.json"
179
+ atomic(
180
+ args.directory / name,
181
+ (
182
+ json.dumps(result, sort_keys=True, indent=2, allow_nan=False) + "\n"
183
+ ).encode(),
184
+ )
185
+ result = {k: v for k, v in result.items() if k != "mapping"}
186
+ print(json.dumps(result, sort_keys=True))
187
+ except (LocalError, OSError, ValueError, KeyError) as exc:
188
+ code = exc.code if isinstance(exc, LocalError) else "legacy_input_or_transport_error"
189
+ print(json.dumps({"error": code, "automatic_retry": False}))
190
+ raise SystemExit(2) from None
191
+
192
+
193
+ if __name__ == "__main__":
194
+ main()
@@ -0,0 +1,78 @@
1
+ """Explicit download of the bundled public model manifest; never runs during inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import shutil
9
+ import tempfile
10
+ import time
11
+ import urllib.request
12
+ from pathlib import Path
13
+
14
+ from memoryking.adapters.local_embeddings import MODEL, RERANKER, model_files, model_manifest
15
+ from memoryking.domain.embeddings import fingerprint
16
+ from memoryking.domain.local import LocalError
17
+
18
+
19
+ class HTTPSOnly(urllib.request.HTTPRedirectHandler):
20
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
21
+ if not newurl.startswith("https://"):
22
+ raise LocalError("model_download_redirect_denied")
23
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
24
+
25
+
26
+ def install(destination: Path, model: str = MODEL) -> dict[str, str]:
27
+ manifest = model_manifest(model)
28
+ if destination.exists():
29
+ model_files(destination, manifest)
30
+ return {"status": "already_verified", "model": model, "fingerprint": fingerprint(manifest)}
31
+ destination.parent.mkdir(parents=True, exist_ok=True)
32
+ opener = urllib.request.build_opener(HTTPSOnly())
33
+ with tempfile.TemporaryDirectory(prefix=".model-download-", dir=destination.parent) as temp:
34
+ staging = Path(temp) / "model"
35
+ staging.mkdir(mode=0o700)
36
+ for file in manifest["files"]:
37
+ path = staging / file["path"]
38
+ path.parent.mkdir(parents=True, exist_ok=True)
39
+ digest, received = hashlib.sha256(), 0
40
+ started = time.monotonic()
41
+ with opener.open(file["url"], timeout=30) as response, path.open("xb") as output:
42
+ while chunk := response.read(65536):
43
+ received += len(chunk)
44
+ if received > file["bytes"] or time.monotonic() - started > 180:
45
+ raise LocalError("model_download_limit")
46
+ digest.update(chunk)
47
+ output.write(chunk)
48
+ if received != file["bytes"] or digest.hexdigest() != file["sha256"]:
49
+ raise LocalError("model_download_checksum_mismatch")
50
+ model_files(staging, manifest)
51
+ # All files are checked before the destination becomes available.
52
+ if destination.exists():
53
+ raise LocalError("model_destination_exists")
54
+ shutil.move(str(staging), destination)
55
+ return {"status": "installed_verified", "model": model, "fingerprint": fingerprint(manifest)}
56
+
57
+
58
+ def main() -> None:
59
+ parser = argparse.ArgumentParser(description=__doc__)
60
+ parser.add_argument("--destination", type=Path, required=True)
61
+ parser.add_argument(
62
+ "--model",
63
+ choices=["embedding", "reranker"],
64
+ default="embedding",
65
+ help="Which pinned manifest to install: the embedding model (default) or the reranker",
66
+ )
67
+ args = parser.parse_args()
68
+ try:
69
+ model = RERANKER if args.model == "reranker" else MODEL
70
+ print(json.dumps(install(args.destination.resolve(), model), sort_keys=True))
71
+ except Exception as exc:
72
+ raise SystemExit(
73
+ exc.code if isinstance(exc, LocalError) else "model_download_failed"
74
+ ) from None
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
@@ -0,0 +1,101 @@
1
+ """Redacted operator logging.
2
+
3
+ Log lines carry event names, request identifiers, error types and code locations.
4
+ They never carry SQL, file paths outside the package, caller content, credentials or
5
+ exception messages, which may embed any of those. Access logging stays off.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import secrets
12
+ import sys
13
+ import traceback
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ LOGGER = logging.getLogger("memoryking")
18
+ LEVELS = ("debug", "info", "warning", "error")
19
+
20
+
21
+ _TRACING = False
22
+
23
+
24
+ def configure(level: str = "warning", trace: bool = False) -> None:
25
+ """Send package logs to stderr at the requested level; idempotent.
26
+
27
+ With `trace`, one timing line per request is written at info level, so a level
28
+ above info is lowered to info; an explicit debug level is kept.
29
+ """
30
+ global _TRACING
31
+ if level not in LEVELS:
32
+ raise ValueError("log level must be one of " + ", ".join(LEVELS))
33
+ _TRACING = trace
34
+ if trace and LEVELS.index(level) > LEVELS.index("info"):
35
+ level = "info"
36
+ LOGGER.setLevel(getattr(logging, level.upper()))
37
+ if not any(getattr(h, "_memoryking", False) for h in LOGGER.handlers):
38
+ handler = logging.StreamHandler(sys.stderr)
39
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
40
+ handler._memoryking = True # type: ignore[attr-defined]
41
+ LOGGER.addHandler(handler)
42
+ LOGGER.propagate = False
43
+
44
+
45
+ def tracing() -> bool:
46
+ """Whether per-request timing lines are wanted; checked before any timing work."""
47
+ return _TRACING
48
+
49
+
50
+ def trace(component: str, **fields: Any) -> None:
51
+ """One timing line per request: operation names, outcome codes, durations and sizes.
52
+
53
+ Never the project, principal, request body, SQL or paths: identifiers that name
54
+ content stay out of the log exactly as for every other line.
55
+ """
56
+ if _TRACING:
57
+ LOGGER.info("component=%s event=trace%s", component, _fields(fields))
58
+
59
+
60
+ def timings(store: Any) -> list[dict[str, float]]:
61
+ """Start collecting this thread's transaction timings on a store; returns the list."""
62
+ items: list[dict[str, float]] = []
63
+ store.timings.items = items
64
+ return items
65
+
66
+
67
+ def summarize(elapsed_ms: float, spans: list[dict[str, float]]) -> dict[str, Any]:
68
+ """Fields for a trace line from a request's elapsed time and its transaction spans."""
69
+ return {
70
+ "elapsed_ms": round(elapsed_ms, 3),
71
+ "transactions": len(spans),
72
+ "lock_wait_ms": round(sum(span.get("lock_wait_ms", 0.0) for span in spans), 3),
73
+ "transaction_ms": round(sum(span.get("transaction_ms", 0.0) for span in spans), 3),
74
+ }
75
+
76
+
77
+ def event(component: str, name: str, **fields: Any) -> None:
78
+ """An informational line built only from identifiers and counts."""
79
+ LOGGER.info("component=%s event=%s%s", component, name, _fields(fields))
80
+
81
+
82
+ def failure(component: str, exc: BaseException, **fields: Any) -> str:
83
+ """Record an unexpected failure and return the request id handed to the caller."""
84
+ request_id = secrets.token_hex(8)
85
+ frames = " <- ".join(
86
+ f"{Path(frame.filename).name}:{frame.lineno}:{frame.name}"
87
+ for frame in traceback.extract_tb(exc.__traceback__)[-6:]
88
+ )
89
+ LOGGER.error(
90
+ "component=%s event=internal_error request_id=%s error=%s frames=%s%s",
91
+ component,
92
+ request_id,
93
+ type(exc).__name__,
94
+ frames or "none",
95
+ _fields(fields),
96
+ )
97
+ return request_id
98
+
99
+
100
+ def _fields(fields: dict[str, Any]) -> str:
101
+ return "".join(f" {key}={value}" for key, value in sorted(fields.items()))
@@ -0,0 +1,100 @@
1
+ """In-process request counters, rendered as Prometheus text for `/metrics`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from typing import Any
7
+
8
+ LATENCY_BUCKETS_MS = (5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000)
9
+
10
+
11
+ class Metrics:
12
+ """Counts and latencies per operation, errors per code; no content, no identities."""
13
+
14
+ def __init__(self) -> None:
15
+ self.lock = threading.Lock()
16
+ self.requests: dict[str, int] = {}
17
+ self.errors: dict[str, int] = {}
18
+ self.latency_sum_ms: dict[str, float] = {}
19
+ self.latency_buckets: dict[str, list[int]] = {}
20
+
21
+ def observe(self, operation: str, elapsed_ms: float, error: str | None) -> None:
22
+ with self.lock:
23
+ self.requests[operation] = self.requests.get(operation, 0) + 1
24
+ if error is not None:
25
+ self.errors[error] = self.errors.get(error, 0) + 1
26
+ self.latency_sum_ms[operation] = self.latency_sum_ms.get(operation, 0.0) + elapsed_ms
27
+ buckets = self.latency_buckets.setdefault(
28
+ operation, [0] * (len(LATENCY_BUCKETS_MS) + 1)
29
+ )
30
+ for index, bound in enumerate(LATENCY_BUCKETS_MS):
31
+ if elapsed_ms <= bound:
32
+ buckets[index] += 1
33
+ buckets[-1] += 1
34
+
35
+ def snapshot(self) -> dict[str, Any]:
36
+ with self.lock:
37
+ return {
38
+ "requests": dict(self.requests),
39
+ "errors": dict(self.errors),
40
+ "latency_sum_ms": dict(self.latency_sum_ms),
41
+ "latency_buckets": {k: list(v) for k, v in self.latency_buckets.items()},
42
+ }
43
+
44
+
45
+ def render(metrics: Metrics, status: dict[str, Any]) -> str:
46
+ """Prometheus exposition text from the counters and a status result."""
47
+ snap = metrics.snapshot()
48
+ lines = [
49
+ "# HELP memoryking_requests_total Requests handled, by operation.",
50
+ "# TYPE memoryking_requests_total counter",
51
+ ]
52
+ for op, n in sorted(snap["requests"].items()):
53
+ lines.append(f'memoryking_requests_total{{operation="{op}"}} {n}')
54
+ lines += [
55
+ "# HELP memoryking_errors_total Error replies, by code.",
56
+ "# TYPE memoryking_errors_total counter",
57
+ ]
58
+ for code, n in sorted(snap["errors"].items()):
59
+ lines.append(f'memoryking_errors_total{{code="{code}"}} {n}')
60
+ lines += [
61
+ "# HELP memoryking_request_duration_ms Request latency histogram, by operation.",
62
+ "# TYPE memoryking_request_duration_ms histogram",
63
+ ]
64
+ for op, buckets in sorted(snap["latency_buckets"].items()):
65
+ for bound, count in zip(LATENCY_BUCKETS_MS, buckets, strict=False):
66
+ lines.append(
67
+ f'memoryking_request_duration_ms_bucket{{operation="{op}",le="{bound}"}} {count}'
68
+ )
69
+ lines.append(
70
+ f'memoryking_request_duration_ms_bucket{{operation="{op}",le="+Inf"}} {buckets[-1]}'
71
+ )
72
+ lines.append(
73
+ f'memoryking_request_duration_ms_sum{{operation="{op}"}} {snap["latency_sum_ms"][op]:.3f}'
74
+ )
75
+ lines.append(f'memoryking_request_duration_ms_count{{operation="{op}"}} {buckets[-1]}')
76
+ lines += [
77
+ "# HELP memoryking_capacity_used Used amount of a bounded tenant resource.",
78
+ "# TYPE memoryking_capacity_used gauge",
79
+ "# HELP memoryking_capacity_limit Limit of a bounded tenant resource.",
80
+ "# TYPE memoryking_capacity_limit gauge",
81
+ ]
82
+ for name, value in sorted(status.get("capacity", {}).items()):
83
+ lines.append(f'memoryking_capacity_used{{resource="{name}"}} {value["used"]}')
84
+ lines.append(f'memoryking_capacity_limit{{resource="{name}"}} {value["limit"]}')
85
+ lines += [
86
+ "# HELP memoryking_jobs Jobs by state.",
87
+ "# TYPE memoryking_jobs gauge",
88
+ ]
89
+ for state, n in sorted(status.get("jobs", {}).items()):
90
+ lines.append(f'memoryking_jobs{{state="{state}"}} {n}')
91
+ projection = status.get("projection", {})
92
+ lines += [
93
+ "# HELP memoryking_position Latest event position.",
94
+ "# TYPE memoryking_position gauge",
95
+ f"memoryking_position {status.get('position', 0)}",
96
+ "# HELP memoryking_frontier Projection frontier.",
97
+ "# TYPE memoryking_frontier gauge",
98
+ f"memoryking_frontier {projection.get('frontier', 0)}",
99
+ ]
100
+ return "\n".join(lines) + "\n"
memoryking/profiles.py ADDED
@@ -0,0 +1,150 @@
1
+ """Named store profiles so commands take `--profile work` instead of four absolute paths.
2
+
3
+ The file is `~/.memoryking/config.toml` (override with `MEMORYKING_CONFIG`). It holds
4
+ paths only, never secrets: a credential entry is the path of a private credential file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import re
12
+ import tomllib
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from memoryking.adapters.local_files import atomic, private_dir, private_file
17
+ from memoryking.domain.local import LocalError
18
+
19
+ FIELDS = (
20
+ "store",
21
+ "control",
22
+ "socket",
23
+ "credential",
24
+ "dashboard_port",
25
+ "embedding_model",
26
+ "reranker_model",
27
+ "backup_dir",
28
+ "backup_every",
29
+ "backup_keep",
30
+ )
31
+ PATH_FIELDS = (
32
+ "store",
33
+ "control",
34
+ "socket",
35
+ "credential",
36
+ "embedding_model",
37
+ "reranker_model",
38
+ "backup_dir",
39
+ )
40
+
41
+
42
+ def config_path() -> Path:
43
+ return Path(os.environ.get("MEMORYKING_CONFIG") or Path.home() / ".memoryking" / "config.toml")
44
+
45
+
46
+ def load(path: Path | None = None) -> dict[str, dict[str, Any]]:
47
+ path = path or config_path()
48
+ if not path.exists():
49
+ return {}
50
+ private_file(path)
51
+ try:
52
+ data = tomllib.loads(path.read_text())
53
+ except (tomllib.TOMLDecodeError, UnicodeError) as exc:
54
+ raise LocalError("profile_config_invalid") from exc
55
+ profiles = data.get("profiles", {})
56
+ if not isinstance(profiles, dict):
57
+ raise LocalError("profile_config_invalid")
58
+ result: dict[str, dict[str, Any]] = {}
59
+ for name, values in profiles.items():
60
+ result[name] = validate(name, values)
61
+ return result
62
+
63
+
64
+ def validate(name: str, values: Any) -> dict[str, Any]:
65
+ if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", name) or not isinstance(values, dict):
66
+ raise LocalError("profile_config_invalid")
67
+ if set(values) - set(FIELDS) or not {"store", "control"} <= set(values):
68
+ raise LocalError("profile_config_invalid")
69
+ clean: dict[str, Any] = {}
70
+ for field in PATH_FIELDS:
71
+ if field in values:
72
+ if not isinstance(values[field], str) or not Path(values[field]).is_absolute():
73
+ raise LocalError("profile_config_invalid")
74
+ clean[field] = str(Path(values[field]))
75
+ if "dashboard_port" in values:
76
+ port = values["dashboard_port"]
77
+ if isinstance(port, bool) or not isinstance(port, int) or not 0 <= port <= 65535:
78
+ raise LocalError("profile_config_invalid")
79
+ clean["dashboard_port"] = port
80
+ if "backup_every" in values:
81
+ if not isinstance(values["backup_every"], str) or not re.fullmatch(
82
+ r"[1-9]\d*[mhd]", values["backup_every"]
83
+ ):
84
+ raise LocalError("profile_config_invalid")
85
+ clean["backup_every"] = values["backup_every"]
86
+ if "backup_keep" in values:
87
+ keep = values["backup_keep"]
88
+ if isinstance(keep, bool) or not isinstance(keep, int) or not 1 <= keep <= 1000:
89
+ raise LocalError("profile_config_invalid")
90
+ clean["backup_keep"] = keep
91
+ return clean
92
+
93
+
94
+ def resolve(name: str, path: Path | None = None) -> dict[str, Any]:
95
+ """A profile with its implied socket and credential paths filled in."""
96
+ profiles = load(path)
97
+ if name not in profiles:
98
+ raise LocalError("profile_unknown")
99
+ profile = dict(profiles[name])
100
+ profile.setdefault("socket", str(Path(profile["store"]) / "service.sock"))
101
+ profile.setdefault("credential", str(Path(profile["control"]) / "owner.credential"))
102
+ return profile
103
+
104
+
105
+ def apply(args: Any, name: str | None, path: Path | None = None) -> None:
106
+ """Fill omitted path arguments from the named profile; explicit flags always win."""
107
+ if name is None:
108
+ return
109
+ profile = resolve(name, path)
110
+ for field in FIELDS:
111
+ if hasattr(args, field) and getattr(args, field) is None and field in profile:
112
+ value = profile[field]
113
+ setattr(args, field, Path(value) if field in PATH_FIELDS else value)
114
+
115
+
116
+ def save(name: str, values: dict[str, Any], path: Path | None = None) -> Path:
117
+ """Add or replace one profile, keeping the file private."""
118
+ path = path or config_path()
119
+ profiles = load(path)
120
+ profiles[name] = validate(name, values)
121
+ private_dir(path.parent, create=True)
122
+ atomic(path, render(profiles).encode())
123
+ return path
124
+
125
+
126
+ def remove(name: str, path: Path | None = None) -> Path:
127
+ path = path or config_path()
128
+ profiles = load(path)
129
+ if name not in profiles:
130
+ raise LocalError("profile_unknown")
131
+ del profiles[name]
132
+ atomic(path, render(profiles).encode())
133
+ return path
134
+
135
+
136
+ def render(profiles: dict[str, dict[str, Any]]) -> str:
137
+ lines = ["# MemoryKing store profiles. Paths only; credential is the path of a private file."]
138
+ for name in sorted(profiles):
139
+ lines.append(f"\n[profiles.{name}]")
140
+ for field in FIELDS:
141
+ if field in profiles[name]:
142
+ value = profiles[name][field]
143
+ # JSON string escaping is valid TOML basic-string escaping: a path with a
144
+ # quote, backslash or control character reads back exactly.
145
+ lines.append(
146
+ f"{field} = {value}"
147
+ if isinstance(value, int)
148
+ else f"{field} = {json.dumps(str(value))}"
149
+ )
150
+ return "\n".join(lines) + "\n"