tortoise-graph 0.2.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 (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,262 @@
1
+ #!/usr/bin/env python3
2
+ """Tortoise client for skill wiring (S9).
3
+
4
+ Thin CLI + Python API wrapping TortoiseSDK for the §6.3 skill wiring contracts.
5
+ Skills call this module to read/write epistemic graph Points.
6
+
7
+ Usage:
8
+ # Query prior research for a domain
9
+ python3 operations/memory/tortoise_client.py query-prior-research --domain "competitor-analysis"
10
+
11
+ # Query existing strategy Points
12
+ python3 operations/memory/tortoise_client.py query-strategies
13
+
14
+ # Query existing vision Points
15
+ python3 operations/memory/tortoise_client.py query-visions --context "product"
16
+
17
+ # Write strategy Points
18
+ python3 operations/memory/tortoise_client.py write-points --kind strategy --points-json '[{"content":"..."}]'
19
+
20
+ # Write a single claim Point
21
+ python3 operations/memory/tortoise_client.py write-claim --content "X is Y" --context "competitor-analysis" --authored-by "research-skill"
22
+
23
+ # Check if the memory system is available
24
+ python3 operations/memory/tortoise_client.py status
25
+
26
+ Design (ponytail):
27
+ - One file, no dependencies outside stdlib + TortoiseSDK
28
+ - CLI via argparse subcommands, one function per §6.3 contract
29
+ - JSON in/out for agent tool consumption
30
+ - Graceful degradation when Tortoise not installed: prints "tortoise unavailable" + exits 0
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import os
37
+ import sys
38
+ from pathlib import Path
39
+
40
+ # Ensure premise-labs is on path (sibling project)
41
+ _TORTOISE_ROOT = Path(__file__).resolve().parent
42
+ if str(_TORTOISE_ROOT) not in sys.path:
43
+ sys.path.insert(0, str(_TORTOISE_ROOT))
44
+
45
+
46
+ def _get_sdk() -> "TortoiseSDK":
47
+ """Lazy-import TortoiseSDK. Returns None if unavailable."""
48
+ try:
49
+ from tortoise.sdk import TortoiseSDK
50
+ return TortoiseSDK() # uses TORTOISE_DB_URI from env
51
+ except ImportError:
52
+ return None
53
+
54
+
55
+ def _check_available() -> bool:
56
+ return _get_sdk() is not None
57
+
58
+
59
+ # ── §6.3 Contract: queryPriorResearch ───────────────────
60
+
61
+ def query_prior_research(domain: str) -> list[dict]:
62
+ """Query epistemic graph for existing claims about a domain.
63
+
64
+ Searches Points by kind (fuzzy match). Returns list of dicts:
65
+ {id, content, pointKind, confidence, status}.
66
+ """
67
+ sdk = _get_sdk()
68
+ if sdk is None:
69
+ return []
70
+
71
+ # Query by kind — domain is used as a keyword search in content
72
+ return sdk.query(kind=domain)
73
+
74
+
75
+ # ── §6.3 Contract: writeStrategyPoints ──────────────────
76
+
77
+ def write_strategy_points(points: list[dict], kind: str = "strategy") -> list[dict]:
78
+ """Write Points to the epistemic graph.
79
+
80
+ Each point dict: {content (required), context (optional), authoredBy (optional), confidence (float optional)}.
81
+ kind: pointKind to use (default "strategy", use "vision" for vision Points).
82
+ Returns list of created point dicts.
83
+ """
84
+ sdk = _get_sdk()
85
+ if sdk is None:
86
+ _log_unavailable()
87
+ return []
88
+
89
+ created: list[dict] = []
90
+ for p in points:
91
+ content = p["content"]
92
+ props = {}
93
+ if p.get("authoredBy"):
94
+ props["authoredBy"] = p["authoredBy"]
95
+ if p.get("confidence") is not None:
96
+ props["confidence"] = float(p["confidence"])
97
+ pt = _create_with_retry(sdk, kind, content, **props)
98
+ created.append(pt)
99
+ return created
100
+
101
+
102
+ # ── §6.3 Contract: queryExistingStrategies ──────────────
103
+
104
+ def query_existing_strategies() -> list[dict]:
105
+ """Query epistemic graph for current strategy Points."""
106
+ sdk = _get_sdk()
107
+ if sdk is None:
108
+ return []
109
+ return sdk.query(kind="strategy")
110
+
111
+
112
+ # ── Vision queries (from E2E-10 pattern) ───────────────
113
+
114
+ def query_existing_visions(point_kind: str | None = None) -> list[dict]:
115
+ """Query epistemic graph for existing vision Points."""
116
+ sdk = _get_sdk()
117
+ if sdk is None:
118
+ return []
119
+ if point_kind:
120
+ return sdk.query(kind=point_kind)
121
+ return sdk.query(kind="vision")
122
+
123
+
124
+ # ── Generic claim writing ──────────────────────────────
125
+
126
+ def write_claim(content: str, kind: str = "statement", *,
127
+ authored_by: str = "",
128
+ confidence: float | None = None) -> dict:
129
+ """Write a single claim Point to the epistemic graph."""
130
+ sdk = _get_sdk()
131
+ if sdk is None:
132
+ return {"error": "tortoise_unavailable", "id": "", "written": False}
133
+ props: dict = {}
134
+ if authored_by:
135
+ props["authoredBy"] = authored_by
136
+ if confidence is not None:
137
+ props["confidence"] = float(confidence)
138
+ return sdk.create_point(kind, content, **props)
139
+
140
+
141
+ # ── Status ──────────────────────────────────────────────
142
+
143
+ def status() -> dict:
144
+ """Report whether Tortoise is available and basic graph stats."""
145
+ sdk = _get_sdk()
146
+ if sdk is None:
147
+ return {"available": False, "message": "Tortoise SDK not installed. PYTHONPATH missing premise-labs/tortoise."}
148
+ try:
149
+ chain = sdk.summarize_structure()
150
+ except Exception:
151
+ chain = {"error": "query failed"}
152
+ return {
153
+ "available": True,
154
+ "db_uri": os.environ.get("TORTOISE_DB_URI") or os.environ.get("TORTOISE_DB_PATH", "not set"),
155
+ "chain_status": chain,
156
+ }
157
+
158
+
159
+ # ── Helpers ─────────────────────────────────────────────
160
+
161
+ def _create_with_retry(sdk, kind: str, content: str, **props) -> dict:
162
+ """Create point with retry for concurrent-write lock contention."""
163
+ # ponytail: 3 attempts with 100ms/200ms/400ms backoff.
164
+ # FalkorDBLite uses SQLite — file lock under concurrent processes.
165
+ import time
166
+ for attempt in range(3):
167
+ try:
168
+ return sdk.create_point(kind, content, **props)
169
+ except Exception as e:
170
+ if "locked" in str(e).lower() and attempt < 2:
171
+ time.sleep(0.1 * (2 ** attempt))
172
+ else:
173
+ raise
174
+ raise RuntimeError("unreachable")
175
+
176
+
177
+ def _log_unavailable() -> None:
178
+ print(json.dumps({"warning": "tortoise unavailable — write skipped", "status": "noop"}), file=sys.stderr)
179
+
180
+
181
+ def _to_json(data) -> str:
182
+ """Serialize to JSON for agent consumption."""
183
+ return json.dumps(data, indent=2, default=str)
184
+
185
+
186
+ # ── CLI ─────────────────────────────────────────────────
187
+
188
+ def _build_parser() -> argparse.ArgumentParser:
189
+ parser = argparse.ArgumentParser(description="Tortoise client for skill wiring")
190
+ sub = parser.add_subparsers(dest="command")
191
+
192
+ # query-prior-research
193
+ qpr = sub.add_parser("query-prior-research", help="Query epistemic graph for prior claims about a domain")
194
+ qpr.add_argument("--domain", required=True, help="Domain to query (e.g. 'competitor-analysis')")
195
+
196
+ # query-strategies
197
+ sub.add_parser("query-strategies", help="Query existing strategy Points")
198
+
199
+ # query-visions
200
+ qv = sub.add_parser("query-visions", help="Query existing vision Points")
201
+ qv.add_argument("--point-kind", default=None, help="Optional pointKind filter")
202
+
203
+ # write-points
204
+ wp = sub.add_parser("write-points", help="Write Points to epistemic graph")
205
+ wp.add_argument("--kind", required=True, help="Point kind (strategy, vision, statement, etc.)")
206
+ wp.add_argument("--points-json", required=True, help="JSON array of point dicts with 'content' key")
207
+
208
+ # write-claim
209
+ wc = sub.add_parser("write-claim", help="Write a single claim Point")
210
+ wc.add_argument("--content", required=True, help="Claim content")
211
+ wc.add_argument("--kind", default="statement", help="Point kind")
212
+ wc.add_argument("--authored-by", default="", help="Who authored this claim")
213
+ wc.add_argument("--confidence", type=float, default=None, help="Confidence 0.0-1.0")
214
+
215
+ # status
216
+ sub.add_parser("status", help="Check Tortoise availability and graph stats")
217
+
218
+ return parser
219
+
220
+
221
+ def main():
222
+ parser = _build_parser()
223
+ args = parser.parse_args()
224
+
225
+ if args.command == "query-prior-research":
226
+ results = query_prior_research(args.domain)
227
+ print(_to_json({"domain": args.domain, "count": len(results), "results": results}))
228
+
229
+ elif args.command == "query-strategies":
230
+ results = query_existing_strategies()
231
+ print(_to_json({"count": len(results), "results": results}))
232
+
233
+ elif args.command == "query-visions":
234
+ results = query_existing_visions(point_kind=args.point_kind)
235
+ print(_to_json({"count": len(results), "results": results}))
236
+
237
+ elif args.command == "write-points":
238
+ try:
239
+ points = json.loads(args.points_json)
240
+ except json.JSONDecodeError as e:
241
+ print(_to_json({"error": "invalid-json", "detail": str(e)}), file=sys.stderr)
242
+ sys.exit(1)
243
+ results = write_strategy_points(points, kind=args.kind)
244
+ print(_to_json({"written": len(results), "results": results}))
245
+
246
+ elif args.command == "write-claim":
247
+ result = write_claim(
248
+ args.content, kind=args.kind,
249
+ authored_by=args.authored_by, confidence=args.confidence,
250
+ )
251
+ print(_to_json(result))
252
+
253
+ elif args.command == "status":
254
+ print(_to_json(status()))
255
+
256
+ else:
257
+ parser.print_help()
258
+ sys.exit(1)
259
+
260
+
261
+ if __name__ == "__main__":
262
+ main()
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env python3
2
+ """Pre-flight ontology validator — catch Schema B drift before batch LLM operations.
3
+
4
+ Validates that _template.md matches AGENTS.md frontmatter contract before
5
+ expensive operations like enrich_frontmatter.py batch mode.
6
+
7
+ Usage:
8
+ python3 premise-labs/tortoise/verify_ontology.py # exit 0 = good
9
+ python3 premise-labs/tortoise/verify_ontology.py --quiet # only exit code
10
+ python3 premise-labs/tortoise/verify_ontology.py --sample 10 # check 10 docs
11
+ python3 premise-labs/tortoise/verify_ontology.py --sample 0 # skip doc check
12
+
13
+ Exit codes: 0 = pass, 1 = contract mismatch, 2 = missing infrastructure, 3 = doc failures
14
+ """
15
+ from __future__ import annotations
16
+ import argparse, re, sys
17
+ from pathlib import Path
18
+
19
+ REPO = Path(__file__).resolve().parent.parent.parent
20
+ TEMPLATE = REPO / "docs" / "_template.md"
21
+ AGENTS = REPO / "AGENTS.md"
22
+ VOCAB = REPO / "docs" / "teams" / "organisation-design-team" / "data" / "controlled_vocabulary.md"
23
+ TEAMS_DIR = REPO / "docs" / "teams"
24
+
25
+ FRONTMATTER_RE = re.compile(r'^---\s*\n(.*?)\n---', re.DOTALL)
26
+ FIELD_LINE = re.compile(r'^(\S+):')
27
+
28
+
29
+ def parse_frontmatter_fields(text: str) -> set[str]:
30
+ m = FRONTMATTER_RE.match(text)
31
+ if not m:
32
+ return set()
33
+ fields = set()
34
+ for line in m.group(1).split("\n"):
35
+ fl = FIELD_LINE.match(line.strip())
36
+ if fl:
37
+ fields.add(fl.group(1))
38
+ return fields
39
+
40
+
41
+ def extract_agents_contract() -> set[str]:
42
+ """Extract required fields from AGENTS.md §Frontmatter Population."""
43
+ text = AGENTS.read_text(encoding="utf-8")
44
+
45
+ section = False
46
+ fields = set()
47
+ for line in text.split("\n"):
48
+ if "## Frontmatter Population" in line:
49
+ section = True
50
+ continue
51
+ if section:
52
+ if line.startswith("## ") and "Frontmatter" not in line:
53
+ break
54
+ m = re.match(r'^- `([^`]+)`', line.strip())
55
+ if m:
56
+ fields.add(m.group(1))
57
+ return fields
58
+
59
+
60
+ def verify_contract(schema_b_fields: set[str], agents_fields: set[str]) -> list[str]:
61
+ """Check all AGENTS.md-mandated fields exist in _template.md Schema B."""
62
+ failures = []
63
+ for field in agents_fields:
64
+ if field not in schema_b_fields:
65
+ failures.append(
66
+ f"MISMATCH: AGENTS.md requires '{field}' but _template.md Schema B is missing it"
67
+ )
68
+ return failures
69
+
70
+
71
+ def sample_docs(sample_n: int = 5) -> list[str]:
72
+ """Sample docs for contract-required field presence."""
73
+ if not TEAMS_DIR.exists():
74
+ return ["FAIL: docs/teams/ directory not found"]
75
+
76
+ docs = sorted(
77
+ f for f in TEAMS_DIR.rglob("*.md")
78
+ if "_templates" not in str(f) and ".git" not in str(f)
79
+ )
80
+ if not docs:
81
+ return []
82
+
83
+ import random
84
+ random.seed(42)
85
+ sample = random.sample(docs, min(sample_n, len(docs)))
86
+
87
+ agents_fields = extract_agents_contract()
88
+ failures = []
89
+ for fp in sample:
90
+ text = fp.read_text(encoding="utf-8")
91
+ if len(text) < 50:
92
+ continue
93
+ fields = parse_frontmatter_fields(text)
94
+ for field in agents_fields:
95
+ if field not in fields:
96
+ try:
97
+ rel = fp.relative_to(TEAMS_DIR)
98
+ except ValueError:
99
+ rel = fp
100
+ failures.append(f"DOC_MISSING: {rel} missing '{field}'")
101
+ return failures
102
+
103
+
104
+ def main():
105
+ p = argparse.ArgumentParser(
106
+ description="Pre-flight ontology validator — catch Schema B drift before batch LLM ops"
107
+ )
108
+ p.add_argument("--quiet", action="store_true")
109
+ p.add_argument("--sample", type=int, default=5, metavar="N")
110
+ args = p.parse_args()
111
+
112
+ # 1. Check infrastructure files exist
113
+ for path, label in [(TEMPLATE, "_template.md"), (AGENTS, "AGENTS.md"),
114
+ (VOCAB, "controlled_vocabulary.md")]:
115
+ if not path.exists():
116
+ print(f"MISSING: {label} ({path})", file=sys.stderr)
117
+ sys.exit(2)
118
+
119
+ # 2. Parse Schema B fields from _template.md
120
+ template_text = TEMPLATE.read_text(encoding="utf-8")
121
+ schema_b_fields = parse_frontmatter_fields(template_text)
122
+
123
+ # 3. Parse AGENTS.md contract
124
+ agents_fields = extract_agents_contract()
125
+ if not agents_fields:
126
+ print("FAIL: could not parse AGENTS.md §Frontmatter Population", file=sys.stderr)
127
+ sys.exit(1)
128
+
129
+ # 4. Check _template.md has required AGENTS.md fields
130
+ failures = verify_contract(schema_b_fields, agents_fields)
131
+
132
+ # 5. Check controlled_vocabulary has team + domain sections
133
+ vocab_text = VOCAB.read_text(encoding="utf-8")
134
+ if "## Teams" not in vocab_text:
135
+ failures.append("FAIL: controlled_vocabulary.md missing ## Teams section")
136
+ if "## Domains" not in vocab_text:
137
+ failures.append("FAIL: controlled_vocabulary.md missing ## Domains section")
138
+
139
+ # 6. Sample docs
140
+ if args.sample > 0:
141
+ failures += sample_docs(args.sample)
142
+
143
+ if failures:
144
+ for f in failures:
145
+ print(f" {f}", file=sys.stderr)
146
+ code = 3 if any(f.startswith("DOC_MISSING") for f in failures) else 1
147
+ sys.exit(code)
148
+
149
+ if not args.quiet:
150
+ print("ontology verified — Schema B matches AGENTS.md contract")
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
@@ -0,0 +1,97 @@
1
+ """Version vectors — Lamport clocks + cross-machine causality tracking.
2
+
3
+ REQ-EVT-005. ~30 LOC. Per-machine Lamport clock + vector clock for
4
+ distributed agent coordination. Composes with coordination.py for
5
+ Card lifecycle ordering.
6
+ """
7
+ from __future__ import annotations
8
+
9
+
10
+ class VersionVector:
11
+ """Per-machine Lamport clock + cross-machine vector clock."""
12
+
13
+ def __init__(self, machine_id: str):
14
+ self.machine_id = machine_id
15
+ self._clock: dict[str, int] = {machine_id: 0}
16
+
17
+ def increment(self, machine_id: str | None = None) -> int:
18
+ """Increment the clock for a machine. Returns new value."""
19
+ mid = machine_id or self.machine_id
20
+ self._clock[mid] = self._clock.get(mid, 0) + 1
21
+ return self._clock[mid]
22
+
23
+ def get(self, machine_id: str) -> int:
24
+ """Read clock value for a machine (0 if unseen)."""
25
+ return self._clock.get(machine_id, 0)
26
+
27
+ def merge(self, other: VersionVector) -> None:
28
+ """Merge another vector clock into this one (max per dimension)."""
29
+ for mid, count in other._clock.items():
30
+ self._clock[mid] = max(self._clock.get(mid, 0), count)
31
+
32
+ def happens_before(self, other: VersionVector) -> bool:
33
+ """True if self strictly happens-before other.
34
+
35
+ Self ≤ other on all machines AND strictly less on at least one.
36
+ """
37
+ all_keys = set(self._clock) | set(other._clock)
38
+ any_less = False
39
+ for k in all_keys:
40
+ s = self._clock.get(k, 0)
41
+ o = other._clock.get(k, 0)
42
+ if s > o:
43
+ return False
44
+ if s < o:
45
+ any_less = True
46
+ return any_less
47
+
48
+ def to_dict(self) -> dict[str, int]:
49
+ return dict(self._clock)
50
+
51
+ @classmethod
52
+ def from_dict(cls, machine_id: str, data: dict[str, int]) -> VersionVector:
53
+ vv = cls(machine_id)
54
+ vv._clock = dict(data)
55
+ if machine_id not in vv._clock:
56
+ vv._clock[machine_id] = 0
57
+ return vv
58
+
59
+
60
+ # ── self-check ────────────────────────────────────────────────
61
+
62
+ if __name__ == "__main__":
63
+ a = VersionVector("A")
64
+ b = VersionVector("B")
65
+
66
+ a.increment("A") # A:1
67
+ assert a.get("A") == 1
68
+ assert a.get("B") == 0
69
+
70
+ b.increment("B") # B:1
71
+ b.increment("B") # B:2
72
+
73
+ # Concurrent — neither happens-before the other
74
+ assert not a.happens_before(b)
75
+ assert not b.happens_before(a)
76
+
77
+ # After merge, A sees B's clock (A:1, B:2)
78
+ a.merge(b)
79
+ assert a.get("B") == 2
80
+
81
+ # B updated again: B:3. a and b are concurrent (a ahead on A, b ahead on B)
82
+ b.increment("B") # B:3
83
+ assert not a.happens_before(b) # a is ahead on A
84
+ assert not b.happens_before(a) # b is ahead on B
85
+
86
+ # Fresh vector C that only sees B:1 — should happen-before b
87
+ c = VersionVector("C")
88
+ c.increment("B") # C sees B at 1
89
+ assert c.happens_before(b) # C < b on B (1 < 3)
90
+
91
+ # Roundtrip
92
+ d = b.to_dict()
93
+ b2 = VersionVector.from_dict("B", d)
94
+ assert b2.get("B") == 3
95
+ assert b2.happens_before(b) is False # equal
96
+
97
+ print("✅ version_vector")
tortoise/weights.py ADDED
@@ -0,0 +1,61 @@
1
+ """Operator weight computation for EP factors (#6742).
2
+
3
+ Derives w from graph structure: mitigation status, edge density,
4
+ context tags, and optionally post-convergence message strengths.
5
+ """
6
+ import math
7
+
8
+
9
+ def compute_operator_weight(proj, op_id: str, use_dynamic: bool = False) -> float:
10
+ """Compute EP factor weight w in [0.1, 10.0] from graph structure."""
11
+ g = proj.g
12
+ rows = g.query(
13
+ "MATCH (o:Point {id:$id}) "
14
+ "RETURN o.op_type, "
15
+ "coalesce(o.annotator_bias, 0.0) AS bias, "
16
+ "coalesce(o.annotator_precision, 1.0) AS precision, "
17
+ "coalesce(o.annotator_consistency, 1.0) AS consistency, "
18
+ "coalesce(o.annotator_directness, 1.0) AS directness",
19
+ params={"id": op_id},
20
+ ).result_set
21
+ if not rows:
22
+ return 1.0
23
+ op_type, bias, precision, consistency, directness = rows[0]
24
+ w = 1.0
25
+
26
+ # Mitigation: operator targets another operator
27
+ input_ops = g.query(
28
+ "MATCH (o:Point {id:$id})-[r:IMPL|NAND]->(p:Point) "
29
+ "WHERE p.is_operator = true RETURN count(p)",
30
+ params={"id": op_id},
31
+ ).result_set[0][0]
32
+ if input_ops > 0:
33
+ w *= 2.0
34
+
35
+ # Edge density penalty removed — unnecessary with directional IMPL.
36
+ # Directional messages eliminate bidirectional amplification loops,
37
+ # so hub nodes no longer need manual dampening.
38
+ w *= 1.0 # no-op, preserved for reference
39
+
40
+ # Context tag multipliers removed (#49 Phase 2 — n.context is deprecated).
41
+ # Re-key to pointKind-based weighting when needed.
42
+
43
+ # Annotation dimensions (ARCHIVED — no active effect)
44
+ # Restore to (1.0 - bias * 0.5) * precision * consistency * directness when reactivated.
45
+ annotation_factor = 1.0
46
+ w *= annotation_factor
47
+
48
+ # Dynamic: post-convergence message strength
49
+ if use_dynamic:
50
+ for rel in ("IMPL", "NAND"):
51
+ rows = g.query(
52
+ f"MATCH (o:Point {{id:$id}})-[r:{rel}]->(:Point) "
53
+ "RETURN abs(coalesce(r.msg_alpha,0.0)) + abs(coalesce(r.msg_beta,0.0))",
54
+ params={"id": op_id},
55
+ ).result_set
56
+ if rows:
57
+ strength = float(rows[0][0])
58
+ dyn = max(min(strength / 10.0, 3.0), 0.5)
59
+ w *= dyn
60
+
61
+ return max(min(w, 10.0), 0.1)