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,65 @@
1
+ """Backend-independent local service errors and bounded authorization decisions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass
7
+ from typing import Callable, Protocol
8
+
9
+
10
+ class LocalError(Exception):
11
+ """Stable non-disclosing error code; never embeds supplied content."""
12
+
13
+ def __init__(self, code: str, hint: str | None = None):
14
+ self.code = code
15
+ self.hint = hint
16
+ super().__init__(code)
17
+
18
+
19
+ class Clock(Protocol):
20
+ def utc_ms(self) -> int: ...
21
+ def monotonic_ms(self) -> int: ...
22
+
23
+
24
+ class SystemClock:
25
+ def utc_ms(self) -> int:
26
+ return time.time_ns() // 1_000_000
27
+
28
+ def monotonic_ms(self) -> int:
29
+ return time.monotonic_ns() // 1_000_000
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Decision:
34
+ evaluated_ms: int
35
+ monotonic_ms: int
36
+ deadline_ms: int
37
+
38
+ def check(self, clock: Clock) -> None:
39
+ utc, mono = clock.utc_ms(), clock.monotonic_ms()
40
+ elapsed = mono - self.monotonic_ms
41
+ if utc < self.evaluated_ms or elapsed < 0:
42
+ raise LocalError("clock_untrusted")
43
+ if utc >= self.deadline_ms or elapsed >= 5000:
44
+ raise LocalError("release_expired")
45
+ if abs((utc - self.evaluated_ms) - elapsed) > 1000:
46
+ raise LocalError("clock_untrusted")
47
+
48
+
49
+ def temporal_valid(at: int, start: int | None, end: int | None) -> bool:
50
+ """All grant, constraint and verification intervals use [start, end)."""
51
+ return (start is None or at >= start) and (end is None or at < end)
52
+
53
+
54
+ @dataclass
55
+ class Released:
56
+ """A committed receipt plus bounded bytes; check immediately before first byte."""
57
+
58
+ body: bytes
59
+ decision: Decision
60
+ clock: Clock
61
+ access_receipt: str | None = None
62
+
63
+ def emit(self, writer: Callable[[bytes], None]) -> None:
64
+ self.decision.check(self.clock)
65
+ writer(self.body)
@@ -0,0 +1,140 @@
1
+ """Pure structured-plan invariants and identical progress for every client/store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from typing import Any
7
+
8
+ from memoryking.contracts.canonical import canonical_hash
9
+ from memoryking.domain.local import LocalError
10
+
11
+ STATES = ("todo", "doing", "done", "blocked", "skipped", "unknown")
12
+
13
+
14
+ def validate(plan: dict[str, Any], previous: dict[str, Any] | None = None) -> None:
15
+ phases = {p["id"] for p in plan["phases"]}
16
+ steps = {s["id"]: s for s in plan["steps"]}
17
+ if len(phases) != len(plan["phases"]) or len(steps) != len(plan["steps"]):
18
+ raise LocalError("plan_duplicate_id")
19
+ for step in steps.values():
20
+ if step["phase"] not in phases or any(d not in steps for d in step["depends_on"]):
21
+ raise LocalError("plan_reference_invalid")
22
+ if step["status"] == "done" and not step["evidence"]:
23
+ raise LocalError("verification_evidence_required")
24
+ if step["status"] in {"blocked", "skipped"} and not step["notes"].strip():
25
+ raise LocalError("plan_reason_required")
26
+ if step["status"] == "skipped" and not step["decision"]:
27
+ raise LocalError("waiver_decision_required")
28
+ if step["status"] in {"doing", "done"} and any(
29
+ steps[d]["status"] not in {"done", "skipped"} for d in step["depends_on"]
30
+ ):
31
+ raise LocalError("plan_dependency_unresolved")
32
+ visiting: set[str] = set()
33
+ visited: set[str] = set()
34
+
35
+ def visit(key: str) -> None:
36
+ if key in visiting:
37
+ raise LocalError("plan_dependency_cycle")
38
+ if key in visited:
39
+ return
40
+ visiting.add(key)
41
+ for dep in steps[key]["depends_on"]:
42
+ visit(dep)
43
+ visiting.remove(key)
44
+ visited.add(key)
45
+
46
+ for key in steps:
47
+ visit(key)
48
+ if plan["status"] == "done" and (
49
+ not steps or any(s["status"] not in {"done", "skipped"} for s in steps.values())
50
+ ):
51
+ raise LocalError("plan_unresolved_steps")
52
+ if plan["status"] in {"done", "abandoned"} and (
53
+ not plan["lessons"] or not plan["closure_note"].strip()
54
+ ):
55
+ raise LocalError("plan_closure_evidence_required")
56
+ if previous is not None:
57
+ old = {s["id"]: s for s in previous["steps"]}
58
+ for key, step in steps.items():
59
+ if step["status"] != "done" or key not in old:
60
+ continue
61
+ definition_changed = definition(plan, key) != definition(previous, key)
62
+ if definition_changed and not (proof_refs(step) - proof_refs(old[key])):
63
+ raise LocalError("plan_reverification_required")
64
+
65
+
66
+ def proof_refs(step: dict[str, Any]) -> set[tuple[str, str]]:
67
+ return {(d["kind"], d["id"]) for d in step["evidence"]}
68
+
69
+
70
+ def definition(plan: dict[str, Any], key: str) -> str:
71
+ """Bind proof to the goal, step definition and transitive prerequisite states."""
72
+ steps = {s["id"]: s for s in plan["steps"]}
73
+ closure: set[str] = set()
74
+ pending = list(steps[key]["depends_on"])
75
+ while pending:
76
+ dep = pending.pop()
77
+ if dep in closure:
78
+ continue
79
+ closure.add(dep)
80
+ pending.extend(steps[dep]["depends_on"])
81
+ own = {k: steps[key][k] for k in ("description", "phase")}
82
+ own["depends_on"] = sorted(steps[key]["depends_on"])
83
+ return canonical_hash(
84
+ {
85
+ "objective": plan["objective"],
86
+ "step": own,
87
+ "dependencies": [
88
+ {
89
+ **{
90
+ k: steps[d][k] for k in ("id", "description", "phase", "status", "decision")
91
+ },
92
+ "depends_on": sorted(steps[d]["depends_on"]),
93
+ "evidence": [
94
+ {"kind": kind, "id": identifier}
95
+ for kind, identifier in sorted(proof_refs(steps[d]))
96
+ ],
97
+ }
98
+ for d in sorted(closure)
99
+ ],
100
+ }
101
+ )
102
+
103
+
104
+ def counts(steps: list[dict[str, Any]]) -> dict[str, Any]:
105
+ count = Counter(s["status"] for s in steps)
106
+ total = len(steps)
107
+ done, skipped = count["done"], count["skipped"]
108
+ return {
109
+ "total": total,
110
+ **{s: count[s] for s in STATES},
111
+ "completed": done,
112
+ "resolved": done + skipped,
113
+ "work_percent": None if not total else 100 * done // total,
114
+ "resolved_percent": None if not total else 100 * (done + skipped) // total,
115
+ }
116
+
117
+
118
+ def progress(plan: dict[str, Any]) -> dict[str, Any]:
119
+ phases = []
120
+ for phase in plan["phases"]:
121
+ value = counts([s for s in plan["steps"] if s["phase"] == phase["id"]])
122
+ state = (
123
+ "empty"
124
+ if not value["total"]
125
+ else (
126
+ "resolved"
127
+ if value["resolved"] == value["total"]
128
+ else "blocked"
129
+ if value["blocked"]
130
+ else "in_progress"
131
+ if value["doing"] or value["done"]
132
+ else "not_started"
133
+ )
134
+ )
135
+ phases.append({**phase, "state": state, "progress": value})
136
+ return {
137
+ **counts(plan["steps"]),
138
+ "phases": phases,
139
+ "current_phase": next((p["id"] for p in phases if p["state"] != "resolved"), None),
140
+ }
@@ -0,0 +1,118 @@
1
+ """Passive, bounded source projections. Never imports or executes inspected source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import hashlib
7
+ import json
8
+ import tomllib
9
+ from typing import Any
10
+
11
+ PARSER = "passive-python-ast-v1"
12
+ MAX_FILE_BYTES = 1024 * 1024
13
+ MAX_NODES = 20000
14
+ MAX_PROJECTIONS = 512
15
+
16
+
17
+ def project_source(path: str, raw: bytes) -> dict[str, Any]:
18
+ result: dict[str, Any] = {
19
+ "hash": hashlib.sha256(raw).hexdigest(),
20
+ "bytes": len(raw),
21
+ "parser": PARSER,
22
+ "coverage": "unsupported",
23
+ "symbols": [],
24
+ "imports": [],
25
+ "calls": [],
26
+ "tests": [],
27
+ "dependencies": [],
28
+ "dynamic_relationships": "unknown",
29
+ "truncated": False,
30
+ }
31
+ if len(raw) > MAX_FILE_BYTES:
32
+ result["coverage"] = "size_limit"
33
+ return result
34
+ try:
35
+ if path.endswith(".py"):
36
+ tree = ast.parse(raw, filename="<repository-data>")
37
+ nodes = []
38
+ for node in ast.walk(tree):
39
+ nodes.append(node)
40
+ if len(nodes) > MAX_NODES:
41
+ result["coverage"] = "node_limit"
42
+ return result
43
+ result["coverage"] = "python_syntax"
44
+ for node in nodes:
45
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
46
+ # Structural identity includes source location; moves are changes,
47
+ # never guessed symbol renames. Hash covers decorators and body.
48
+ ident = f"{path}:{node.name}:{node.lineno}"
49
+ result["symbols"].append(
50
+ {
51
+ "id": ident,
52
+ "name": node.name,
53
+ "line": node.lineno,
54
+ "kind": "class" if isinstance(node, ast.ClassDef) else "function",
55
+ "hash": hashlib.sha256(
56
+ ast.dump(node, include_attributes=False).encode()
57
+ ).hexdigest(),
58
+ }
59
+ )
60
+ if node.name.startswith("test_"):
61
+ result["tests"].append({"symbol": ident, "status": "discovered_not_run"})
62
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
63
+ names = (
64
+ [a.name for a in node.names]
65
+ if isinstance(node, ast.Import)
66
+ else ["." * node.level + (node.module or "")]
67
+ )
68
+ result["imports"].extend(
69
+ {"target": name, "line": node.lineno, "resolution": "syntactic_only"}
70
+ for name in names
71
+ )
72
+ elif isinstance(node, ast.Call):
73
+ name = ast.unparse(node.func)
74
+ result["calls"].append(
75
+ {"target": name[:256], "line": node.lineno, "resolution": "unresolved"}
76
+ )
77
+ elif path.rsplit("/", 1)[-1] == "package.json":
78
+ value = json.loads(raw)
79
+ if not isinstance(value, dict):
80
+ raise ValueError
81
+ for group in (
82
+ "dependencies",
83
+ "devDependencies",
84
+ "peerDependencies",
85
+ "optionalDependencies",
86
+ ):
87
+ deps = value.get(group, {})
88
+ if not isinstance(deps, dict):
89
+ raise ValueError
90
+ result["dependencies"].extend(
91
+ {
92
+ "name": str(k)[:256],
93
+ "declared": str(v)[:256],
94
+ "group": group,
95
+ "resolved": False,
96
+ }
97
+ for k, v in deps.items()
98
+ )
99
+ result["coverage"] = "manifest_declarations"
100
+ elif path.rsplit("/", 1)[-1] == "pyproject.toml":
101
+ value = tomllib.loads(raw.decode())
102
+ project = value.get("project", {})
103
+ if not isinstance(project, dict):
104
+ raise ValueError
105
+ deps = project.get("dependencies", [])
106
+ if not isinstance(deps, list) or not all(isinstance(d, str) for d in deps):
107
+ raise ValueError
108
+ result["dependencies"] = [{"declared": d[:512], "resolved": False} for d in deps]
109
+ result["coverage"] = "manifest_declarations"
110
+ except (SyntaxError, ValueError, TypeError, UnicodeError, RecursionError):
111
+ result.update(
112
+ coverage="parse_error", symbols=[], imports=[], calls=[], tests=[], dependencies=[]
113
+ )
114
+ for key in ("symbols", "imports", "calls", "tests", "dependencies"):
115
+ if len(result[key]) > MAX_PROJECTIONS:
116
+ result["truncated"] = True
117
+ result[key] = result[key][:MAX_PROJECTIONS]
118
+ return result
@@ -0,0 +1,356 @@
1
+ """Bounded selector v1. Three-valued evaluation and conservative region proofs.
2
+
3
+ No filesystem, database, regular-expression predicate or caller-supplied code executes.
4
+ Ancestry evidence is an internal port; request bindings cannot assert completeness.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from dataclasses import dataclass
12
+ from typing import Any, Callable, Literal
13
+
14
+ from memoryking.contracts.canonical import canonical_bytes
15
+ from memoryking.domain.local import LocalError
16
+
17
+ Truth = Literal["true", "false", "unknown"]
18
+ Relation = Literal["proven", "disproven", "indeterminate"]
19
+ FIELDS = {"repository_id", "component_id", "symbol_id", "environment", "task_stage", "role"}
20
+ Selector = dict[str, Any]
21
+ Atom = dict[str, Any]
22
+
23
+
24
+ @dataclass
25
+ class Work:
26
+ remaining: int = 4096
27
+
28
+ def take(self) -> None:
29
+ self.remaining -= 1
30
+ if self.remaining < 0:
31
+ raise LocalError("selector_limit_exceeded")
32
+
33
+
34
+ def path_valid(value: Any, *, root: bool = False) -> bool:
35
+ return isinstance(value, str) and (
36
+ (value == "" and root)
37
+ or (
38
+ 0 < len(value.encode()) <= 256
39
+ and len(value.split("/")) <= 32
40
+ and all(x not in {"", ".", ".."} for x in value.split("/"))
41
+ and not any(c in value for c in "\\\x00*?[]")
42
+ )
43
+ )
44
+
45
+
46
+ def triplet(value: Any) -> bool:
47
+ return (
48
+ isinstance(value, list)
49
+ and len(value) == 3
50
+ and all(type(x) is int and 0 <= x <= 2147483647 for x in value)
51
+ )
52
+
53
+
54
+ def _key(atom: Atom) -> tuple[str, str]:
55
+ return atom.get("field", "any"), atom.get("dependency", "")
56
+
57
+
58
+ def _under(path: str, prefix: str) -> bool:
59
+ return bool(path) if prefix == "" else path.startswith(prefix + "/")
60
+
61
+
62
+ def _atom(atom: Any) -> Atom:
63
+ if atom == {"op": "any"}:
64
+ return dict(atom)
65
+ if not isinstance(atom, dict) or not {"field", "op", "value"} <= atom.keys():
66
+ raise LocalError("selector_unsupported")
67
+ field, op, value = atom["field"], atom["op"], atom["value"]
68
+ if not isinstance(field, str) or not isinstance(op, str):
69
+ raise LocalError("selector_unsupported")
70
+ expected = {"field", "op", "value"}
71
+ if op == "version_in":
72
+ expected |= {"dependency", "scheme"}
73
+ if set(atom) != expected:
74
+ raise LocalError("selector_unsupported")
75
+ result = dict(atom)
76
+ if field in FIELDS and op in {"eq", "in"}:
77
+ values = [value] if op == "eq" else value
78
+ if (
79
+ not isinstance(values, list)
80
+ or not 1 <= len(values) <= 32
81
+ or not all(isinstance(v, str) and 0 < len(v.encode()) <= 256 for v in values)
82
+ ):
83
+ raise LocalError("selector_unsupported")
84
+ result.update(op="in", value=sorted(set(values)))
85
+ elif field == "path" and op in {"path_exact", "path_under"}:
86
+ if not path_valid(value, root=op == "path_under"):
87
+ raise LocalError("selector_unsupported")
88
+ elif field == "dependency_version" and op == "version_in":
89
+ if (
90
+ atom["scheme"] != "numeric_triplet_v1"
91
+ or not isinstance(atom["dependency"], str)
92
+ or not re.fullmatch(r"[A-Za-z0-9_.-]{1,96}", atom["dependency"])
93
+ or not isinstance(value, dict)
94
+ or set(value) != {"lower", "upper"}
95
+ or not triplet(value["lower"])
96
+ or (
97
+ value["upper"] is not None
98
+ and (not triplet(value["upper"]) or value["lower"] >= value["upper"])
99
+ )
100
+ ):
101
+ raise LocalError("selector_unsupported")
102
+ elif field == "commit" and op in {"commit_is", "descendant_of"}:
103
+ if not isinstance(value, str) or not re.fullmatch(r"(?:[a-f0-9]{40}|[a-f0-9]{64})", value):
104
+ raise LocalError("selector_unsupported")
105
+ else:
106
+ raise LocalError("selector_unsupported")
107
+ return result
108
+
109
+
110
+ def _subset(a: Atom, b: Atom, work: Work) -> Relation:
111
+ work.take()
112
+ if b["op"] == "any" or a == b:
113
+ return "proven"
114
+ if a["op"] == "any" or _key(a) != _key(b):
115
+ return "indeterminate"
116
+ av, bv = a["value"], b["value"]
117
+ if a["op"] == b["op"] == "in":
118
+ return "proven" if set(av) <= set(bv) else "disproven"
119
+ if a["op"] == b["op"] == "version_in":
120
+ inside = av["lower"] >= bv["lower"] and (
121
+ bv["upper"] is None or (av["upper"] is not None and av["upper"] <= bv["upper"])
122
+ )
123
+ return "proven" if inside else "disproven"
124
+ if a["field"] == "path":
125
+ if b["op"] == "path_exact":
126
+ return "proven" if a["op"] == "path_exact" and av == bv else "disproven"
127
+ inside = _under(av, bv) or (a["op"] == "path_under" and av == bv)
128
+ return "proven" if inside else "disproven"
129
+ if a["op"] == "commit_is":
130
+ if av == bv:
131
+ return "proven"
132
+ return "disproven" if b["op"] == "commit_is" else "indeterminate"
133
+ return "indeterminate"
134
+
135
+
136
+ def _merge(a: Atom, b: Atom, work: Work) -> list[Atom] | None:
137
+ work.take()
138
+ if a["op"] == "any":
139
+ return [b]
140
+ if b["op"] == "any" or a == b:
141
+ return [a]
142
+ if _key(a) != _key(b):
143
+ return [a, b]
144
+ av, bv = a["value"], b["value"]
145
+ if a["op"] == b["op"] == "in":
146
+ overlap = sorted(set(av) & set(bv))
147
+ return [{**a, "value": overlap}] if overlap else None
148
+ if a["op"] == b["op"] == "version_in":
149
+ lower = max(av["lower"], bv["lower"])
150
+ ends = [v for v in (av["upper"], bv["upper"]) if v is not None]
151
+ upper = min(ends) if ends else None
152
+ return (
153
+ [{**a, "value": {"lower": lower, "upper": upper}}]
154
+ if upper is None or lower < upper
155
+ else None
156
+ )
157
+ if a["field"] == "path":
158
+ if _subset(a, b, work) == "proven":
159
+ return [a]
160
+ if _subset(b, a, work) == "proven":
161
+ return [b]
162
+ return None
163
+ if a["op"] == b["op"] == "commit_is" and av != bv:
164
+ return None
165
+ if av == bv:
166
+ return [a if a["op"] == "commit_is" else b]
167
+ # A merge commit can descend from incomparable roots; retain both.
168
+ return [a, b]
169
+
170
+
171
+ def _clause(atoms: list[Atom], work: Work) -> list[Atom] | None:
172
+ result: list[Atom] = []
173
+ for atom in atoms:
174
+ keep = atom
175
+ others = []
176
+ for existing in result:
177
+ merged = _merge(existing, keep, work)
178
+ if merged is None:
179
+ return None
180
+ if len(merged) == 1:
181
+ keep = merged[0]
182
+ else:
183
+ others.append(existing)
184
+ result = others + [keep]
185
+ result.sort(key=lambda x: canonical_bytes(x))
186
+ if len(result) > 8:
187
+ raise LocalError("selector_limit_exceeded")
188
+ return result
189
+
190
+
191
+ def _output(clauses: list[list[Atom]]) -> Selector | None:
192
+ unique = {canonical_bytes(c): c for c in clauses}
193
+ if not unique:
194
+ return None
195
+ if len(unique) > 16:
196
+ raise LocalError("selector_limit_exceeded")
197
+ result = {"selector_version": "1", "any_of": [{"all_of": unique[k]} for k in sorted(unique)]}
198
+ if len(canonical_bytes(result)) > 16384:
199
+ raise LocalError("selector_limit_exceeded")
200
+ return result
201
+
202
+
203
+ def canonical(selector: Any, work: Work | None = None) -> Selector:
204
+ work = work or Work()
205
+ if (
206
+ not isinstance(selector, dict)
207
+ or set(selector) != {"selector_version", "any_of"}
208
+ or selector["selector_version"] != "1"
209
+ ):
210
+ raise LocalError("selector_unsupported")
211
+ if len(canonical_bytes(selector)) > 16384:
212
+ raise LocalError("selector_limit_exceeded")
213
+ clauses = selector["any_of"]
214
+ if not isinstance(clauses, list) or not 1 <= len(clauses) <= 16:
215
+ raise LocalError("selector_limit_exceeded")
216
+ output = []
217
+ for clause in clauses:
218
+ if not isinstance(clause, dict) or set(clause) != {"all_of"}:
219
+ raise LocalError("selector_unsupported")
220
+ atoms = clause["all_of"]
221
+ if not isinstance(atoms, list) or not 1 <= len(atoms) <= 8:
222
+ raise LocalError("selector_limit_exceeded")
223
+ parsed = [_atom(a) for a in atoms]
224
+ if any(a["op"] == "any" for a in parsed) and len(parsed) != 1:
225
+ raise LocalError("selector_unsupported")
226
+ if any(a.get("field") in {"path", "commit"} for a in parsed) and not any(
227
+ a.get("field") == "repository_id" and len(a["value"]) == 1 for a in parsed
228
+ ):
229
+ raise LocalError("selector_unsupported")
230
+ simplified = _clause(parsed, work)
231
+ if simplified is not None:
232
+ output.append(simplified)
233
+ normalized = _output(output)
234
+ if normalized is None:
235
+ raise LocalError("selector_empty")
236
+ return normalized
237
+
238
+
239
+ def intersection(left: Selector, right: Selector, work: Work | None = None) -> Selector | None:
240
+ work = work or Work()
241
+ a, b = canonical(left, work), canonical(right, work)
242
+ clauses = []
243
+ for ac in a["any_of"]:
244
+ for bc in b["any_of"]:
245
+ result = _clause(ac["all_of"] + bc["all_of"], work)
246
+ if result is not None:
247
+ clauses.append(result)
248
+ return _output(clauses)
249
+
250
+
251
+ def contains(region: Selector, container: Selector, work: Work | None = None) -> Relation:
252
+ """Prove region is contained in container; no arbitrary theorem proving."""
253
+ work = work or Work()
254
+ a, b = canonical(region, work), canonical(container, work)
255
+ unknown = False
256
+ for ac in a["any_of"]:
257
+ clause_proved = False
258
+ for bc in b["any_of"]:
259
+ if all(
260
+ any(_subset(x, y, work) == "proven" for x in ac["all_of"]) for y in bc["all_of"]
261
+ ):
262
+ clause_proved = True
263
+ break
264
+ if not clause_proved:
265
+ if len(b["any_of"]) == 1:
266
+ # Canonical single-dimension counterexamples are exact. Missing
267
+ # dimensions and ancestry remain indeterminate.
268
+ for y in b["any_of"][0]["all_of"]:
269
+ relevant = [x for x in ac["all_of"] if _key(x) == _key(y)]
270
+ if len(relevant) == 1 and _subset(relevant[0], y, work) == "disproven":
271
+ return "disproven"
272
+ unknown = True
273
+ return "indeterminate" if unknown else "proven"
274
+
275
+
276
+ def _truth(values: list[Truth], *, conjunction: bool) -> Truth:
277
+ decisive: Truth = "false" if conjunction else "true"
278
+ if decisive in values:
279
+ return decisive
280
+ if "unknown" in values:
281
+ return "unknown"
282
+ return "true" if conjunction else "false"
283
+
284
+
285
+ def evaluate(
286
+ selector: Selector,
287
+ binding: dict[str, Any],
288
+ ancestry: Callable[[str, str, str], Truth] | None = None,
289
+ ) -> Truth:
290
+ def atom(a: Atom) -> Truth:
291
+ op = a["op"]
292
+ if op == "any":
293
+ return "true"
294
+ field, value = a["field"], a["value"]
295
+ observed = binding.get(field)
296
+ if op == "version_in":
297
+ dependencies = binding.get("dependencies", {})
298
+ if not isinstance(dependencies, dict) or a["dependency"] not in dependencies:
299
+ return "unknown"
300
+ observed = dependencies[a["dependency"]]
301
+ if observed is None:
302
+ return "false"
303
+ if not triplet(observed):
304
+ return "unknown"
305
+ matches = observed >= value["lower"] and (
306
+ value["upper"] is None or observed < value["upper"]
307
+ )
308
+ elif not isinstance(observed, str):
309
+ return "unknown"
310
+ elif op == "in":
311
+ matches = observed in value
312
+ elif op in {"path_exact", "path_under"}:
313
+ if not path_valid(observed):
314
+ return "unknown"
315
+ matches = observed == value if op == "path_exact" else _under(observed, value)
316
+ elif op == "commit_is":
317
+ if not re.fullmatch(r"(?:[a-f0-9]{40}|[a-f0-9]{64})", observed):
318
+ return "unknown"
319
+ matches = observed == value
320
+ else:
321
+ if observed == value:
322
+ return "true"
323
+ repository = binding.get("repository_id")
324
+ return (
325
+ ancestry(repository, value, observed)
326
+ if ancestry and isinstance(repository, str)
327
+ else "unknown"
328
+ )
329
+ return "true" if matches else "false"
330
+
331
+ normalized = canonical(selector)
332
+ return _truth(
333
+ [_truth([atom(a) for a in c["all_of"]], conjunction=True) for c in normalized["any_of"]],
334
+ conjunction=False,
335
+ )
336
+
337
+
338
+ def bindings(value: Any) -> list[dict[str, Any]]:
339
+ allowed = FIELDS | {"path", "commit", "dependencies", "snapshot_id"}
340
+ if not isinstance(value, list) or not 1 <= len(value) <= 256:
341
+ raise LocalError("binding_coverage_incomplete")
342
+ if any(not isinstance(b, dict) or not set(b) <= allowed for b in value):
343
+ raise LocalError("invalid_binding")
344
+ if any(
345
+ any(
346
+ v is not None and (not isinstance(v, str) or len(v.encode()) > 256)
347
+ for k, v in b.items()
348
+ if k != "dependencies"
349
+ )
350
+ for b in value
351
+ ):
352
+ raise LocalError("invalid_binding")
353
+ # Copy prevents mutation during evaluation and enforces the canonical byte bound.
354
+ if len(canonical_bytes(value)) > 131072:
355
+ raise LocalError("binding_coverage_incomplete")
356
+ return json.loads(json.dumps(value)) # type: ignore[no-any-return]