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.
- memoryking/__init__.py +3 -0
- memoryking/__main__.py +1328 -0
- memoryking/adapters/__init__.py +1 -0
- memoryking/adapters/adapter_state.py +242 -0
- memoryking/adapters/anchor_schema.sql +7 -0
- memoryking/adapters/atlas.py +441 -0
- memoryking/adapters/browser_commands.py +125 -0
- memoryking/adapters/dashboard.py +510 -0
- memoryking/adapters/dense_search.py +86 -0
- memoryking/adapters/egress_policy.py +244 -0
- memoryking/adapters/egress_schema.sql +13 -0
- memoryking/adapters/embedding.schema.json +302 -0
- memoryking/adapters/embedding_store.py +469 -0
- memoryking/adapters/execution.py +369 -0
- memoryking/adapters/experience.py +423 -0
- memoryking/adapters/experience.schema.json +1508 -0
- memoryking/adapters/experience_records.py +239 -0
- memoryking/adapters/experience_schema.sql +23 -0
- memoryking/adapters/handoff.py +494 -0
- memoryking/adapters/handoff.schema.json +299 -0
- memoryking/adapters/handoff_schema.sql +17 -0
- memoryking/adapters/index_schema.sql +11 -0
- memoryking/adapters/inference.py +454 -0
- memoryking/adapters/inference.schema.json +541 -0
- memoryking/adapters/inspection.py +1128 -0
- memoryking/adapters/inspection.schema.json +568 -0
- memoryking/adapters/knowledge.schema.json +633 -0
- memoryking/adapters/knowledge_schema.sql +37 -0
- memoryking/adapters/knowledge_store.py +800 -0
- memoryking/adapters/legacy_snapshot.py +358 -0
- memoryking/adapters/legacy_tables.py +49 -0
- memoryking/adapters/local_contract.py +45 -0
- memoryking/adapters/local_embeddings.py +189 -0
- memoryking/adapters/local_files.py +242 -0
- memoryking/adapters/local_ipc.py +258 -0
- memoryking/adapters/local_schema.sql +44 -0
- memoryking/adapters/local_store.py +632 -0
- memoryking/adapters/local_wire.schema.json +7672 -0
- memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/optional_schema.sql +43 -0
- memoryking/adapters/plan_dashboard.py +51 -0
- memoryking/adapters/plans.py +253 -0
- memoryking/adapters/postgres_admin.py +300 -0
- memoryking/adapters/postgres_anchor_schema.sql +9 -0
- memoryking/adapters/postgres_counter.sql +14 -0
- memoryking/adapters/postgres_egress_schema.sql +15 -0
- memoryking/adapters/postgres_experience_schema.sql +39 -0
- memoryking/adapters/postgres_index_schema.sql +7 -0
- memoryking/adapters/postgres_optional_schema.sql +71 -0
- memoryking/adapters/postgres_pool.py +77 -0
- memoryking/adapters/postgres_recovery.py +525 -0
- memoryking/adapters/postgres_schema.sql +365 -0
- memoryking/adapters/postgres_sql.py +102 -0
- memoryking/adapters/postgres_store.py +428 -0
- memoryking/adapters/postgres_summary_schema.sql +12 -0
- memoryking/adapters/postgres_trust_schema.sql +20 -0
- memoryking/adapters/processing.schema.json +471 -0
- memoryking/adapters/processing_store.py +346 -0
- memoryking/adapters/projects.py +83 -0
- memoryking/adapters/proposals.py +238 -0
- memoryking/adapters/ranking.py +315 -0
- memoryking/adapters/repository.schema.json +664 -0
- memoryking/adapters/repository_git.py +264 -0
- memoryking/adapters/repository_schema.sql +25 -0
- memoryking/adapters/repository_store.py +960 -0
- memoryking/adapters/retrieval.py +1285 -0
- memoryking/adapters/retrieval.schema.json +553 -0
- memoryking/adapters/retrieval_schema.sql +10 -0
- memoryking/adapters/shared_control.py +40 -0
- memoryking/adapters/shared_dashboard.py +636 -0
- memoryking/adapters/shared_gateway.py +63 -0
- memoryking/adapters/shared_http.py +216 -0
- memoryking/adapters/shared_mcp.py +159 -0
- memoryking/adapters/shared_service.py +124 -0
- memoryking/adapters/stdio.py +193 -0
- memoryking/adapters/stdio.tools.json +6776 -0
- memoryking/adapters/summary_schema.sql +10 -0
- memoryking/adapters/team.py +253 -0
- memoryking/adapters/timeline.py +80 -0
- memoryking/adapters/token_count.py +55 -0
- memoryking/adapters/tokenizers/LICENSE +21 -0
- memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
- memoryking/adapters/trust.py +123 -0
- memoryking/adapters/trust_schema.sql +13 -0
- memoryking/adapters/web/app.css +1251 -0
- memoryking/adapters/web/app.js +907 -0
- memoryking/adapters/web/brand.js +44 -0
- memoryking/adapters/web/crown-mono.svg +1 -0
- memoryking/adapters/web/crown.svg +8 -0
- memoryking/adapters/web/elephant.png +0 -0
- memoryking/adapters/web/favicon.svg +8 -0
- memoryking/adapters/web/graph-layout.js +52 -0
- memoryking/adapters/web/graph-worker.js +10 -0
- memoryking/adapters/web/graph.js +570 -0
- memoryking/adapters/web/index.html +208 -0
- memoryking/adapters/web/observatory.js +1208 -0
- memoryking/adapters/web/team.js +151 -0
- memoryking/adapters/web/wordmark.svg +1 -0
- memoryking/adapters/working.py +971 -0
- memoryking/adapters/working.schema.json +1717 -0
- memoryking/adapters/working_schema.sql +24 -0
- memoryking/application/__init__.py +1 -0
- memoryking/application/conformance.py +50 -0
- memoryking/application/legacy_import.py +337 -0
- memoryking/application/local_port.py +9 -0
- memoryking/application/storage.py +117 -0
- memoryking/application/store_core.py +1292 -0
- memoryking/backups.py +131 -0
- memoryking/contracts/__init__.py +6 -0
- memoryking/contracts/__main__.py +20 -0
- memoryking/contracts/canonical.py +88 -0
- memoryking/contracts/embedding.schema.json +302 -0
- memoryking/contracts/embedding_generated.py +65 -0
- memoryking/contracts/experience.schema.json +1508 -0
- memoryking/contracts/experience_generated.py +239 -0
- memoryking/contracts/generated.py +122 -0
- memoryking/contracts/handoff.schema.json +299 -0
- memoryking/contracts/handoff_generated.py +69 -0
- memoryking/contracts/inference.schema.json +541 -0
- memoryking/contracts/inference_generated.py +106 -0
- memoryking/contracts/processing.schema.json +471 -0
- memoryking/contracts/processing_generated.py +82 -0
- memoryking/contracts/py.typed +0 -0
- memoryking/contracts/repository.schema.json +664 -0
- memoryking/contracts/repository_generated.py +144 -0
- memoryking/contracts/retrieval.schema.json +553 -0
- memoryking/contracts/retrieval_generated.py +110 -0
- memoryking/contracts/schema.json +696 -0
- memoryking/contracts/validation.py +92 -0
- memoryking/contracts/working.schema.json +1717 -0
- memoryking/contracts/working_generated.py +291 -0
- memoryking/domain/__init__.py +1 -0
- memoryking/domain/anchors.py +97 -0
- memoryking/domain/briefing.py +108 -0
- memoryking/domain/briefing_text.py +222 -0
- memoryking/domain/checkpoint.py +118 -0
- memoryking/domain/compression.py +64 -0
- memoryking/domain/delta.py +129 -0
- memoryking/domain/embeddings.py +90 -0
- memoryking/domain/hints.py +465 -0
- memoryking/domain/http_status.py +45 -0
- memoryking/domain/learning.py +62 -0
- memoryking/domain/local.py +65 -0
- memoryking/domain/plans.py +140 -0
- memoryking/domain/repository.py +118 -0
- memoryking/domain/selectors.py +356 -0
- memoryking/domain/summary.py +88 -0
- memoryking/domain/usage.py +163 -0
- memoryking/embedding_loop.py +98 -0
- memoryking/embedding_worker.py +131 -0
- memoryking/harness.py +882 -0
- memoryking/harness_context.py +376 -0
- memoryking/hooks.py +171 -0
- memoryking/host_hooks.py +454 -0
- memoryking/lean.py +352 -0
- memoryking/memory_tool.py +776 -0
- memoryking/migration.py +194 -0
- memoryking/model_install.py +78 -0
- memoryking/observability.py +101 -0
- memoryking/observability_metrics.py +100 -0
- memoryking/profiles.py +150 -0
- memoryking/providers.py +330 -0
- memoryking/py.typed +0 -0
- memoryking/pytest_plugin.py +69 -0
- memoryking/reference_agent.py +152 -0
- memoryking/repository_worker.py +57 -0
- memoryking/resume_adapter.py +154 -0
- memoryking/sdk.py +302 -0
- memoryking/shared.py +301 -0
- memoryking/shared_sdk.py +101 -0
- memoryking/vault.py +176 -0
- memoryking-0.1.0.dist-info/METADATA +157 -0
- memoryking-0.1.0.dist-info/RECORD +179 -0
- memoryking-0.1.0.dist-info/WHEEL +5 -0
- memoryking-0.1.0.dist-info/entry_points.txt +7 -0
- memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
- memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
- memoryking-0.1.0.dist-info/top_level.txt +1 -0
memoryking/shared.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""MemoryKing shared-profile operator commands. Secrets are private files, never stdout."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import ipaddress
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import psycopg
|
|
12
|
+
from psycopg import sql
|
|
13
|
+
|
|
14
|
+
from memoryking.adapters.local_files import atomic, private_dir, private_file
|
|
15
|
+
from memoryking.adapters.postgres_admin import (
|
|
16
|
+
Roles,
|
|
17
|
+
enable_vector,
|
|
18
|
+
initialize_tenant,
|
|
19
|
+
migrate,
|
|
20
|
+
provision_roles,
|
|
21
|
+
)
|
|
22
|
+
from memoryking.adapters.postgres_pool import create_pool
|
|
23
|
+
from memoryking.adapters.postgres_recovery import backup, end_maintenance, restore
|
|
24
|
+
from memoryking.adapters.postgres_store import PostgresStore
|
|
25
|
+
from memoryking.adapters.shared_http import create_app
|
|
26
|
+
from memoryking.adapters.shared_service import SharedService
|
|
27
|
+
from memoryking.contracts.canonical import canonical_bytes, load_strict
|
|
28
|
+
from memoryking.domain.local import LocalError
|
|
29
|
+
from memoryking.observability import LEVELS, configure
|
|
30
|
+
from memoryking.shared_sdk import SharedClient
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def secret(path: Path) -> str:
|
|
34
|
+
private_file(path)
|
|
35
|
+
with path.open("rb") as stream:
|
|
36
|
+
raw = stream.read(8193)
|
|
37
|
+
if not raw.strip() or len(raw) > 8192:
|
|
38
|
+
raise LocalError("invalid_secret_file")
|
|
39
|
+
return raw.decode().strip()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def dsn(path: Path) -> str:
|
|
43
|
+
value = secret(path)
|
|
44
|
+
options = psycopg.conninfo.conninfo_to_dict(value)
|
|
45
|
+
host = str(options.get("host") or "")
|
|
46
|
+
if not host.startswith("/") and options.get("sslmode") != "verify-full":
|
|
47
|
+
raise LocalError("database_tls_required")
|
|
48
|
+
return value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parser() -> argparse.ArgumentParser:
|
|
52
|
+
result = argparse.ArgumentParser(description=__doc__)
|
|
53
|
+
commands = result.add_subparsers(dest="command", required=True)
|
|
54
|
+
for name in (
|
|
55
|
+
"provision-roles",
|
|
56
|
+
"migrate",
|
|
57
|
+
"enable-vector",
|
|
58
|
+
"init-tenant",
|
|
59
|
+
"serve",
|
|
60
|
+
"worker-once",
|
|
61
|
+
"backup",
|
|
62
|
+
"restore",
|
|
63
|
+
"end-maintenance",
|
|
64
|
+
):
|
|
65
|
+
item = commands.add_parser(name)
|
|
66
|
+
item.add_argument("--dsn-file", type=Path, required=True)
|
|
67
|
+
if name == "provision-roles":
|
|
68
|
+
item.add_argument(
|
|
69
|
+
"--role-secrets",
|
|
70
|
+
type=Path,
|
|
71
|
+
required=True,
|
|
72
|
+
help="Private directory with mk_migration, mk_runtime, mk_worker, mk_backup password files",
|
|
73
|
+
)
|
|
74
|
+
if name in {"init-tenant", "serve", "worker-once", "backup", "restore"}:
|
|
75
|
+
item.add_argument("--content", type=Path, required=True)
|
|
76
|
+
item.add_argument("--control", type=Path, required=True)
|
|
77
|
+
item.add_argument("--audience", default="memoryking-shared")
|
|
78
|
+
if name in {"init-tenant", "worker-once", "backup", "restore", "end-maintenance"}:
|
|
79
|
+
item.add_argument("--tenant", required=True)
|
|
80
|
+
if name == "end-maintenance":
|
|
81
|
+
item.add_argument("--control", type=Path, required=True)
|
|
82
|
+
item.add_argument("--audience", default="memoryking-shared")
|
|
83
|
+
item.add_argument("--credential", type=Path, required=True)
|
|
84
|
+
item.add_argument(
|
|
85
|
+
"--operation", required=True, help="Operation id recorded by the dead backup"
|
|
86
|
+
)
|
|
87
|
+
if name == "init-tenant":
|
|
88
|
+
item.add_argument("--principal", default="owner")
|
|
89
|
+
if name in {"worker-once", "backup"}:
|
|
90
|
+
item.add_argument("--credential", type=Path, required=True)
|
|
91
|
+
if name == "worker-once":
|
|
92
|
+
item.add_argument("--project", required=True)
|
|
93
|
+
if name == "backup":
|
|
94
|
+
item.add_argument("--backup-dsn-file", type=Path, required=True)
|
|
95
|
+
if name in {"backup", "restore"}:
|
|
96
|
+
item.add_argument("--archive", type=Path, required=True)
|
|
97
|
+
if name == "restore":
|
|
98
|
+
item.add_argument("--lost-anchor-journal-head")
|
|
99
|
+
if name == "serve":
|
|
100
|
+
item.add_argument("--bind", default="127.0.0.1")
|
|
101
|
+
item.add_argument("--port", type=int, default=8765)
|
|
102
|
+
item.add_argument("--host", action="append", required=True)
|
|
103
|
+
item.add_argument("--origin", action="append", default=[])
|
|
104
|
+
item.add_argument("--tls-cert", type=Path)
|
|
105
|
+
item.add_argument("--tls-key", type=Path)
|
|
106
|
+
item.add_argument("--loopback-http", action="store_true")
|
|
107
|
+
item.add_argument("--pool-size", type=int, default=8)
|
|
108
|
+
item.add_argument("--dashboard-tenant")
|
|
109
|
+
item.add_argument("--log-level", default="warning", choices=LEVELS)
|
|
110
|
+
item.add_argument(
|
|
111
|
+
"--trace",
|
|
112
|
+
action="store_true",
|
|
113
|
+
help="Log one timing line per request; implies --log-level info",
|
|
114
|
+
)
|
|
115
|
+
item.add_argument(
|
|
116
|
+
"--egress-policy",
|
|
117
|
+
type=Path,
|
|
118
|
+
help="Private TOML policy naming the providers, models and hosts retained "
|
|
119
|
+
"context may reach; without it only the local recorder is accepted",
|
|
120
|
+
)
|
|
121
|
+
request = commands.add_parser("request")
|
|
122
|
+
request.add_argument("--url", required=True)
|
|
123
|
+
request.add_argument("--tenant", required=True)
|
|
124
|
+
request.add_argument("--project", required=True)
|
|
125
|
+
request.add_argument("--credential", type=Path, required=True)
|
|
126
|
+
request.add_argument("--credential-output", type=Path)
|
|
127
|
+
request.add_argument("--bootstrap-output", type=Path)
|
|
128
|
+
request.add_argument("--ca-file", type=Path)
|
|
129
|
+
request.add_argument("--loopback-http", action="store_true")
|
|
130
|
+
return result
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def run(args: Any) -> dict[str, Any]:
|
|
134
|
+
if args.command == "request":
|
|
135
|
+
raw = sys.stdin.buffer.read(262145)
|
|
136
|
+
value = load_strict(raw)
|
|
137
|
+
if (
|
|
138
|
+
len(raw) > 262144
|
|
139
|
+
or not isinstance(value, dict)
|
|
140
|
+
or set(value) != {"version", "operation", "args"}
|
|
141
|
+
or value["version"] != 1
|
|
142
|
+
):
|
|
143
|
+
raise LocalError("invalid_request")
|
|
144
|
+
if value["operation"] in {"grant", "delegate"}:
|
|
145
|
+
if args.credential_output is None or args.credential_output.exists():
|
|
146
|
+
raise LocalError("new_credential_output_required")
|
|
147
|
+
private_dir(args.credential_output.parent)
|
|
148
|
+
client = SharedClient(
|
|
149
|
+
args.url,
|
|
150
|
+
args.tenant,
|
|
151
|
+
args.credential,
|
|
152
|
+
args.project,
|
|
153
|
+
ca_file=args.ca_file,
|
|
154
|
+
loopback_http=args.loopback_http,
|
|
155
|
+
)
|
|
156
|
+
if value["operation"] == "dashboard_bootstrap":
|
|
157
|
+
if args.bootstrap_output is None or args.bootstrap_output.exists():
|
|
158
|
+
raise LocalError("new_bootstrap_output_required")
|
|
159
|
+
private_dir(args.bootstrap_output.parent)
|
|
160
|
+
output = client._request(client._credential(), value["operation"], value["args"])
|
|
161
|
+
if "credential" in output:
|
|
162
|
+
atomic(args.credential_output, output.pop("credential").encode())
|
|
163
|
+
output["credential_file"] = str(args.credential_output)
|
|
164
|
+
if "code" in output:
|
|
165
|
+
atomic(args.bootstrap_output, canonical_bytes(output))
|
|
166
|
+
return {"bootstrap_file": str(args.bootstrap_output), "url": output["url"]}
|
|
167
|
+
return output
|
|
168
|
+
connection_string = dsn(args.dsn_file)
|
|
169
|
+
if args.command in {
|
|
170
|
+
"provision-roles",
|
|
171
|
+
"migrate",
|
|
172
|
+
"enable-vector",
|
|
173
|
+
"init-tenant",
|
|
174
|
+
"restore",
|
|
175
|
+
"end-maintenance",
|
|
176
|
+
}:
|
|
177
|
+
with psycopg.connect(connection_string, autocommit=True) as connection:
|
|
178
|
+
if args.command == "provision-roles":
|
|
179
|
+
private_dir(args.role_secrets)
|
|
180
|
+
roles = Roles()
|
|
181
|
+
passwords = {
|
|
182
|
+
name: secret(args.role_secrets / name) for name in vars(roles).values()
|
|
183
|
+
}
|
|
184
|
+
with connection.transaction():
|
|
185
|
+
provision_roles(connection, roles)
|
|
186
|
+
for name, password in passwords.items():
|
|
187
|
+
connection.execute(
|
|
188
|
+
sql.SQL("ALTER ROLE {} PASSWORD {}").format(
|
|
189
|
+
sql.Identifier(name), sql.Literal(password)
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
elif args.command == "migrate":
|
|
193
|
+
migrate(connection)
|
|
194
|
+
elif args.command == "enable-vector":
|
|
195
|
+
enable_vector(connection)
|
|
196
|
+
elif args.command == "init-tenant":
|
|
197
|
+
path = initialize_tenant(
|
|
198
|
+
connection,
|
|
199
|
+
args.content,
|
|
200
|
+
args.control,
|
|
201
|
+
args.tenant,
|
|
202
|
+
args.principal,
|
|
203
|
+
args.audience,
|
|
204
|
+
)
|
|
205
|
+
return {"credential_file": str(path)}
|
|
206
|
+
elif args.command == "end-maintenance":
|
|
207
|
+
return end_maintenance(
|
|
208
|
+
connection,
|
|
209
|
+
args.control,
|
|
210
|
+
args.tenant,
|
|
211
|
+
args.operation,
|
|
212
|
+
secret(args.credential),
|
|
213
|
+
audience=args.audience,
|
|
214
|
+
)
|
|
215
|
+
else:
|
|
216
|
+
path = restore(
|
|
217
|
+
connection,
|
|
218
|
+
args.content,
|
|
219
|
+
args.control,
|
|
220
|
+
args.tenant,
|
|
221
|
+
args.archive,
|
|
222
|
+
audience=args.audience,
|
|
223
|
+
lost_anchor_journal_head=args.lost_anchor_journal_head,
|
|
224
|
+
)
|
|
225
|
+
return {"credential_file": str(path), "reconciliation_required": True}
|
|
226
|
+
return {"status": "complete", "operation": args.command}
|
|
227
|
+
pool = create_pool(connection_string, size=args.pool_size if args.command == "serve" else 2)
|
|
228
|
+
try:
|
|
229
|
+
if args.command == "serve":
|
|
230
|
+
import uvicorn
|
|
231
|
+
|
|
232
|
+
configure(args.log_level, trace=args.trace)
|
|
233
|
+
|
|
234
|
+
address = ipaddress.ip_address(args.bind)
|
|
235
|
+
if not 0 < args.port <= 65535:
|
|
236
|
+
raise LocalError("invalid_port")
|
|
237
|
+
if args.loopback_http:
|
|
238
|
+
if not address.is_loopback or args.tls_cert or args.tls_key:
|
|
239
|
+
raise LocalError("loopback_development_only")
|
|
240
|
+
elif not args.tls_cert or not args.tls_key:
|
|
241
|
+
raise LocalError("shared_tls_required")
|
|
242
|
+
if args.tls_key:
|
|
243
|
+
private_file(args.tls_key)
|
|
244
|
+
service = SharedService(pool, args.content, args.control, audience=args.audience)
|
|
245
|
+
if args.egress_policy is not None:
|
|
246
|
+
from memoryking.adapters.egress_policy import EgressPolicy
|
|
247
|
+
|
|
248
|
+
service.egress_policy = EgressPolicy.load(args.egress_policy)
|
|
249
|
+
app = create_app(
|
|
250
|
+
service,
|
|
251
|
+
hosts=args.host,
|
|
252
|
+
origins=args.origin,
|
|
253
|
+
loopback_http=args.loopback_http,
|
|
254
|
+
dashboard_tenant=args.dashboard_tenant,
|
|
255
|
+
)
|
|
256
|
+
uvicorn.run(
|
|
257
|
+
app,
|
|
258
|
+
host=args.bind,
|
|
259
|
+
port=args.port,
|
|
260
|
+
access_log=False,
|
|
261
|
+
log_level="warning",
|
|
262
|
+
proxy_headers=False,
|
|
263
|
+
ssl_certfile=str(args.tls_cert) if args.tls_cert else None,
|
|
264
|
+
ssl_keyfile=str(args.tls_key) if args.tls_key else None,
|
|
265
|
+
)
|
|
266
|
+
return {"status": "stopped"}
|
|
267
|
+
credential = secret(args.credential)
|
|
268
|
+
with PostgresStore(
|
|
269
|
+
pool, args.content, args.control, args.tenant, credential, audience=args.audience
|
|
270
|
+
) as store:
|
|
271
|
+
if args.command == "worker-once":
|
|
272
|
+
lease = store.claim(credential, args.project)
|
|
273
|
+
if lease is None:
|
|
274
|
+
return {"status": "idle", "provider_calls": 0}
|
|
275
|
+
store.finish(credential, args.project, lease["lease"], "complete")
|
|
276
|
+
return {"status": "complete", "provider_calls": 0, "projection": "audit_probe"}
|
|
277
|
+
with psycopg.connect(dsn(args.backup_dsn_file), autocommit=True) as connection:
|
|
278
|
+
manifest = backup(store, connection, args.archive)
|
|
279
|
+
return {
|
|
280
|
+
"status": "complete",
|
|
281
|
+
"archive": str(args.archive),
|
|
282
|
+
"archive_bytes": manifest["archive_bytes"],
|
|
283
|
+
}
|
|
284
|
+
finally:
|
|
285
|
+
pool.close()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def main() -> None:
|
|
289
|
+
try:
|
|
290
|
+
result = run(parser().parse_args())
|
|
291
|
+
sys.stdout.buffer.write(canonical_bytes(result) + b"\n")
|
|
292
|
+
except Exception as exc:
|
|
293
|
+
# Never render connection strings, passwords or driver exception detail.
|
|
294
|
+
sys.stderr.write(
|
|
295
|
+
(exc.code if isinstance(exc, LocalError) else "shared_operation_failed") + "\n"
|
|
296
|
+
)
|
|
297
|
+
raise SystemExit(2) from None
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
if __name__ == "__main__":
|
|
301
|
+
main()
|
memoryking/shared_sdk.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""HTTP variant of the project SDK; no automatic mutation retry or redirect following."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ssl
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from memoryking.adapters.local_store import identifier
|
|
13
|
+
from memoryking.contracts.canonical import canonical_bytes, load_strict
|
|
14
|
+
from memoryking.domain.local import LocalError
|
|
15
|
+
from memoryking.sdk import BINDING_FIELDS, LocalClient
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
19
|
+
def redirect_request(
|
|
20
|
+
self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str
|
|
21
|
+
) -> None:
|
|
22
|
+
raise LocalError("redirect_forbidden")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SharedClient(LocalClient):
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
url: str,
|
|
29
|
+
tenant: str,
|
|
30
|
+
credential_file: Path,
|
|
31
|
+
project: str,
|
|
32
|
+
*,
|
|
33
|
+
ca_file: Path | None = None,
|
|
34
|
+
loopback_http: bool = False,
|
|
35
|
+
namespace: str = "sdk",
|
|
36
|
+
):
|
|
37
|
+
self.namespace = namespace
|
|
38
|
+
parsed = urllib.parse.urlsplit(url)
|
|
39
|
+
if (
|
|
40
|
+
parsed.username
|
|
41
|
+
or parsed.password
|
|
42
|
+
or parsed.query
|
|
43
|
+
or parsed.fragment
|
|
44
|
+
or parsed.path not in {"", "/"}
|
|
45
|
+
or not parsed.hostname
|
|
46
|
+
):
|
|
47
|
+
raise LocalError("invalid_shared_url")
|
|
48
|
+
if parsed.scheme != "https" and not (
|
|
49
|
+
loopback_http
|
|
50
|
+
and parsed.scheme == "http"
|
|
51
|
+
and parsed.hostname in {"127.0.0.1", "::1", "localhost"}
|
|
52
|
+
):
|
|
53
|
+
raise LocalError("shared_tls_required")
|
|
54
|
+
self.url = url.rstrip("/") + "/v1/tenants/" + identifier(tenant) + "/operations"
|
|
55
|
+
self.credential_file, self.project = credential_file, identifier(project)
|
|
56
|
+
self.opener = urllib.request.build_opener(
|
|
57
|
+
urllib.request.ProxyHandler({}),
|
|
58
|
+
NoRedirect(),
|
|
59
|
+
urllib.request.HTTPSHandler(
|
|
60
|
+
context=ssl.create_default_context(cafile=str(ca_file) if ca_file else None)
|
|
61
|
+
),
|
|
62
|
+
)
|
|
63
|
+
self.last_context = self._request(self._credential(), "context", {"project": project})
|
|
64
|
+
self.binding = tuple(self.last_context[key] for key in BINDING_FIELDS)
|
|
65
|
+
self.delegation = self.last_context.get("delegation_chain", [])
|
|
66
|
+
|
|
67
|
+
def _current(self) -> tuple[str, dict[str, Any]]:
|
|
68
|
+
credential, context = super()._current()
|
|
69
|
+
if context.get("delegation_chain", []) != self.delegation:
|
|
70
|
+
raise LocalError("context_changed")
|
|
71
|
+
return credential, context
|
|
72
|
+
|
|
73
|
+
def _request(self, credential: str, operation: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
74
|
+
raw = canonical_bytes({"version": 1, "operation": operation, "args": args})
|
|
75
|
+
if len(raw) > 262144:
|
|
76
|
+
raise LocalError("invalid_request")
|
|
77
|
+
request = urllib.request.Request(
|
|
78
|
+
self.url,
|
|
79
|
+
raw,
|
|
80
|
+
headers={
|
|
81
|
+
"Authorization": "Bearer " + credential,
|
|
82
|
+
"Content-Type": "application/json",
|
|
83
|
+
"Accept": "application/json",
|
|
84
|
+
},
|
|
85
|
+
method="POST",
|
|
86
|
+
)
|
|
87
|
+
try:
|
|
88
|
+
with self.opener.open(request, timeout=10) as response:
|
|
89
|
+
body = response.read(1048577)
|
|
90
|
+
except urllib.error.HTTPError as exc:
|
|
91
|
+
body = exc.read(1048577)
|
|
92
|
+
except OSError as exc:
|
|
93
|
+
raise LocalError("transport_unavailable") from exc
|
|
94
|
+
if len(body) > 1048576:
|
|
95
|
+
raise LocalError("invalid_response")
|
|
96
|
+
value = load_strict(body)
|
|
97
|
+
if not isinstance(value, dict):
|
|
98
|
+
raise LocalError("invalid_response")
|
|
99
|
+
if "error" in value:
|
|
100
|
+
raise LocalError(value["error"])
|
|
101
|
+
return value
|
memoryking/vault.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""A Markdown vault: the project's memory as files on disk, for hand editing and portability.
|
|
2
|
+
|
|
3
|
+
`export` writes the same files the memory-tool adapter shows (`<project>/<source>/<name>.md`
|
|
4
|
+
for observations, `<project>/claims/<key>.md` for claims, each with a provenance block,
|
|
5
|
+
plus a README) into a private directory. `import_` reads such a directory back: a file
|
|
6
|
+
whose text differs from the stored newest version is captured as a new version, a new
|
|
7
|
+
file is a new observation, and a claim file is a proposal with the evidence its block
|
|
8
|
+
names. Nothing is deleted or overwritten in the store; the directory is the editable copy.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import secrets
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from memoryking.adapters.local_files import private_dir
|
|
20
|
+
from memoryking.domain.local import LocalError
|
|
21
|
+
from memoryking.memory_tool import (
|
|
22
|
+
CLAIMS,
|
|
23
|
+
IDENTIFIER,
|
|
24
|
+
README,
|
|
25
|
+
SUFFIX,
|
|
26
|
+
Files,
|
|
27
|
+
MemoryToolError,
|
|
28
|
+
render,
|
|
29
|
+
same,
|
|
30
|
+
split,
|
|
31
|
+
)
|
|
32
|
+
from memoryking.sdk import LocalClient
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def connect(*, socket: Path | None, credential: Path | None, project: str | None) -> LocalClient:
|
|
36
|
+
"""A client from explicit paths, else the environment (`MEMORYKING_*`)."""
|
|
37
|
+
socket = socket or (
|
|
38
|
+
Path(os.environ["MEMORYKING_SOCKET"]) if os.environ.get("MEMORYKING_SOCKET") else None
|
|
39
|
+
)
|
|
40
|
+
credential = credential or (
|
|
41
|
+
Path(os.environ["MEMORYKING_CREDENTIAL"])
|
|
42
|
+
if os.environ.get("MEMORYKING_CREDENTIAL")
|
|
43
|
+
else None
|
|
44
|
+
)
|
|
45
|
+
project = project or os.environ.get("MEMORYKING_PROJECT")
|
|
46
|
+
if socket is None:
|
|
47
|
+
raise LocalError("socket_required")
|
|
48
|
+
if credential is None:
|
|
49
|
+
raise LocalError("credential_required")
|
|
50
|
+
if not project:
|
|
51
|
+
raise LocalError("project_required")
|
|
52
|
+
return LocalClient(socket, credential, project, namespace="vault")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def write(path: Path, data: bytes) -> None:
|
|
56
|
+
"""Replace a vault file with a private one, whatever a hand editor left its mode at."""
|
|
57
|
+
temporary = path.with_name(".stage-" + secrets.token_hex(8))
|
|
58
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
59
|
+
try:
|
|
60
|
+
with os.fdopen(fd, "wb") as stream:
|
|
61
|
+
stream.write(data)
|
|
62
|
+
os.replace(temporary, path)
|
|
63
|
+
except BaseException:
|
|
64
|
+
temporary.unlink(missing_ok=True)
|
|
65
|
+
raise
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def export(directory: Path, client: LocalClient) -> dict[str, Any]:
|
|
69
|
+
"""Write every visible observation (newest version per file) and claim as Markdown."""
|
|
70
|
+
files = Files(client)
|
|
71
|
+
root = directory / client.project
|
|
72
|
+
private_dir(directory, create=True)
|
|
73
|
+
private_dir(root, create=True)
|
|
74
|
+
grouped = files.group(files.pages("observations", text=True))
|
|
75
|
+
written: list[str] = []
|
|
76
|
+
for (source, name), entry in sorted(grouped.items()):
|
|
77
|
+
folder = root / source
|
|
78
|
+
private_dir(folder, create=True)
|
|
79
|
+
path = folder / f"{name}{SUFFIX}"
|
|
80
|
+
write(path, render(entry, client.project).encode())
|
|
81
|
+
written.append(f"{source}/{name}{SUFFIX}")
|
|
82
|
+
claims = files.pages("claims", text=True)
|
|
83
|
+
if claims:
|
|
84
|
+
private_dir(root / CLAIMS, create=True)
|
|
85
|
+
for item in claims:
|
|
86
|
+
path = root / CLAIMS / f"{item['logical_key']}{SUFFIX}"
|
|
87
|
+
write(path, render({**item, "kind": "claim"}, client.project).encode())
|
|
88
|
+
written.append(f"{CLAIMS}/{item['logical_key']}{SUFFIX}")
|
|
89
|
+
total = sum(len(entry["versions"]) for entry in grouped.values())
|
|
90
|
+
readme = files.readme(grouped, total, len(claims)) + (
|
|
91
|
+
f"\nExported {datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')} by "
|
|
92
|
+
f"{files.principal}. Edit the text below a file's provenance block, add files, then\n"
|
|
93
|
+
f"run `memoryking vault import --project {client.project} --dir <this directory's parent>`:\n"
|
|
94
|
+
"changed and new files become new versions and observations, claim files become\n"
|
|
95
|
+
"proposals. The provenance block is ignored on import except for `evidence`.\n"
|
|
96
|
+
)
|
|
97
|
+
write(root / README, readme.encode())
|
|
98
|
+
return {
|
|
99
|
+
"directory": str(root),
|
|
100
|
+
"observations": len(grouped),
|
|
101
|
+
"versions": total,
|
|
102
|
+
"claims": len(claims),
|
|
103
|
+
"files": written,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def import_(directory: Path, client: LocalClient, *, dry_run: bool = False) -> dict[str, Any]:
|
|
108
|
+
"""Capture changed or new files as versions and claim files as proposals."""
|
|
109
|
+
files = Files(client)
|
|
110
|
+
root = directory / client.project
|
|
111
|
+
if not root.is_dir():
|
|
112
|
+
raise LocalError("vault_missing")
|
|
113
|
+
captured: list[dict[str, Any]] = []
|
|
114
|
+
proposed: list[dict[str, Any]] = []
|
|
115
|
+
errors: list[dict[str, str]] = []
|
|
116
|
+
unchanged = 0
|
|
117
|
+
folders = sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith("."))
|
|
118
|
+
# Notes first, so a claim file can cite a note that the same import adds.
|
|
119
|
+
for folder in sorted(folders, key=lambda p: p.name == CLAIMS):
|
|
120
|
+
source = folder.name
|
|
121
|
+
for path in sorted(p for p in folder.iterdir() if p.is_file() and p.suffix == SUFFIX):
|
|
122
|
+
relative = f"{source}/{path.name}"
|
|
123
|
+
name = path.name[: -len(SUFFIX)]
|
|
124
|
+
try:
|
|
125
|
+
if not IDENTIFIER.match(source) or not IDENTIFIER.match(name):
|
|
126
|
+
raise MemoryToolError(
|
|
127
|
+
"Error: directory and file names are identifiers (letters, digits, `_`, `-`)."
|
|
128
|
+
)
|
|
129
|
+
fields, body = split(path.read_text(encoding="utf-8"))
|
|
130
|
+
if source == CLAIMS:
|
|
131
|
+
existing = files.claim(name)
|
|
132
|
+
if existing is not None and same(existing["text"], body):
|
|
133
|
+
unchanged += 1
|
|
134
|
+
continue
|
|
135
|
+
evidence = (
|
|
136
|
+
fields.get("evidence") if isinstance(fields.get("evidence"), list) else []
|
|
137
|
+
)
|
|
138
|
+
if existing is not None and not evidence:
|
|
139
|
+
evidence = existing["evidence"]
|
|
140
|
+
record = {
|
|
141
|
+
"file": relative,
|
|
142
|
+
"key": name,
|
|
143
|
+
"version": (existing or {}).get("family_version", 0) + 1,
|
|
144
|
+
}
|
|
145
|
+
if not dry_run:
|
|
146
|
+
result = files.propose(name, body, evidence or [], existing)
|
|
147
|
+
record["revision"] = result["revision"]
|
|
148
|
+
else:
|
|
149
|
+
files.spans(evidence or []) # the evidence must still resolve
|
|
150
|
+
proposed.append(record)
|
|
151
|
+
else:
|
|
152
|
+
entry = files.observation(source, name)
|
|
153
|
+
if entry is not None and same(entry["text"], body):
|
|
154
|
+
unchanged += 1
|
|
155
|
+
continue
|
|
156
|
+
versions = entry["versions"] if entry else []
|
|
157
|
+
record = {"file": relative, "version": len(versions) + 1}
|
|
158
|
+
if not dry_run:
|
|
159
|
+
result = files.capture(source, name, body, versions)
|
|
160
|
+
record["observation"] = result["observation"]
|
|
161
|
+
captured.append(record)
|
|
162
|
+
except (MemoryToolError, LocalError, UnicodeDecodeError) as exc:
|
|
163
|
+
errors.append(
|
|
164
|
+
{
|
|
165
|
+
"file": relative,
|
|
166
|
+
"error": exc.message if isinstance(exc, MemoryToolError) else str(exc),
|
|
167
|
+
}
|
|
168
|
+
)
|
|
169
|
+
return {
|
|
170
|
+
"directory": str(root),
|
|
171
|
+
"dry_run": dry_run,
|
|
172
|
+
"captured": captured,
|
|
173
|
+
"proposed": proposed,
|
|
174
|
+
"unchanged": unchanged,
|
|
175
|
+
"errors": errors,
|
|
176
|
+
}
|