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,113 @@
1
+ """Single-machine concurrency: fcntl.flock for JSONL, atomic os.rename for cards.
2
+
3
+ Zero dependencies. Pessimistic locking (research brief §5: abort costs for AI
4
+ agents are minutes/dollars, not microseconds).
5
+ """
6
+
7
+ import fcntl
8
+ import json
9
+ import os
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def locked_append(path: Path, record: dict[str, Any],
16
+ timeout_ms: float = 5000.0,
17
+ dedup_key: str | None = None) -> bool:
18
+ """Append a JSON line to a file under an advisory flock.
19
+
20
+ Blocks up to timeout_ms. Returns True on success, False if timeout.
21
+ If dedup_key is provided, the file is scanned under lock — if any
22
+ existing record contains that key:value, the write is skipped (returns True).
23
+
24
+ Per research brief §5: pessimistic locking is correct for AI agents
25
+ whose abort costs are measured in minutes and dollars.
26
+ """
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ deadline = time.monotonic() + timeout_ms / 1000.0
29
+ fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND, 0o600)
30
+ try:
31
+ while True:
32
+ try:
33
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
34
+ break
35
+ except BlockingIOError:
36
+ if time.monotonic() >= deadline:
37
+ return False
38
+ time.sleep(0.005) # ponytail: 5ms spin — good enough for ≤10 agents
39
+
40
+ # Dedup check under lock (no TOCTOU)
41
+ if dedup_key:
42
+ os.lseek(fd, 0, os.SEEK_SET)
43
+ raw = os.read(fd, 4096 * 1024).decode('utf-8', errors='replace')
44
+ for line in raw.split('\n'):
45
+ line = line.strip()
46
+ if not line:
47
+ continue
48
+ try:
49
+ ev = json.loads(line)
50
+ if ev.get('event_id') == dedup_key:
51
+ return True # already exists, skip
52
+ except json.JSONDecodeError:
53
+ continue
54
+
55
+ line = json.dumps(record, ensure_ascii=False, default=str) + "\n"
56
+ os.write(fd, line.encode())
57
+ return True
58
+ finally:
59
+ fcntl.flock(fd, fcntl.LOCK_UN)
60
+ os.close(fd)
61
+
62
+
63
+ def atomic_claim(card_dir: Path, card_id: str, claim_data: dict[str, Any],
64
+ suffix: str = ".card") -> Optional[Path]:
65
+ """Atomically claim a card using O_EXCL (no TOCTOU window).
66
+
67
+ Uses open(target, 'x') for atomic create-or-fail. If the target already
68
+ exists, another agent claimed it first — returns None.
69
+
70
+ Returns the Path of the claimed card file, or None if already claimed.
71
+ """
72
+ card_dir.mkdir(parents=True, exist_ok=True)
73
+ target = card_dir / f"{card_id}{suffix}"
74
+ try:
75
+ # O_CREAT | O_EXCL — atomic, fails if exists (no TOCTOU)
76
+ fd = os.open(str(target), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
77
+ try:
78
+ os.write(fd, json.dumps(claim_data, ensure_ascii=False, default=str).encode())
79
+ finally:
80
+ os.close(fd)
81
+ return target
82
+ except FileExistsError:
83
+ return None
84
+
85
+
86
+ # --- self-check ---
87
+ if __name__ == "__main__":
88
+ import tempfile
89
+ d = Path(tempfile.mkdtemp())
90
+
91
+ # locked_append
92
+ log = d / "test.jsonl"
93
+ ok = locked_append(log, {"event": "test", "n": 1})
94
+ assert ok
95
+ assert log.exists()
96
+ lines = log.read_text().strip().split("\n")
97
+ assert len(lines) == 1
98
+ assert json.loads(lines[0])["event"] == "test"
99
+
100
+ # atomic_claim — first claim succeeds
101
+ cards = d / "cards"
102
+ claimed = atomic_claim(cards, "card-001", {"owner": "agent-1"})
103
+ assert claimed is not None
104
+ assert claimed.exists()
105
+ data = json.loads(claimed.read_text())
106
+ assert data["owner"] == "agent-1"
107
+
108
+ # atomic_claim — second claim on same ID returns None
109
+ claimed2 = atomic_claim(cards, "card-001", {"owner": "agent-2"})
110
+ assert claimed2 is None
111
+
112
+ print("✅ concurrency")
113
+ import shutil; shutil.rmtree(d)
@@ -0,0 +1,192 @@
1
+ """JSONL event log — append, replay, integrity verification.
2
+
3
+
4
+ Composes with concurrency.locked_append and events.EventCodec.
5
+ Event types: cardCreated, stepStarted, stepCompleted, gatePassed, gateBlocked.
6
+ Registered via PM domain extension (packs/project-management/manifest.yaml).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from .concurrency import locked_append
16
+
17
+
18
+ # ── Append ────────────────────────────────────────────────────
19
+
20
+ def append_event(
21
+ log_path: Path,
22
+ event_type: str,
23
+ data: dict[str, Any],
24
+ *,
25
+ event_id: str | None = None,
26
+ ) -> bool:
27
+ """Append an event to the JSONL log under flock.
28
+
29
+ Dedup by event_id: if an event with the same ID already exists,
30
+ returns True without writing (idempotent). Returns False on lock timeout.
31
+ """
32
+ from .events import EventCodec
33
+
34
+ if event_id and _event_id_exists(log_path, event_id):
35
+ return True # ponytail: idempotent — already recorded, nothing to do
36
+
37
+ record = EventCodec.encode(event_type, data, event_id=event_id)
38
+ return locked_append(log_path, record)
39
+
40
+
41
+ def _event_id_exists(log_path: Path, event_id: str) -> bool:
42
+ """Check if an event_id already exists in the log."""
43
+ if not log_path.exists():
44
+ return False
45
+ with open(log_path) as f:
46
+ for line in f:
47
+ line = line.strip()
48
+ if not line:
49
+ continue
50
+ try:
51
+ ev = json.loads(line)
52
+ if ev.get("event_id") == event_id:
53
+ return True
54
+ except json.JSONDecodeError:
55
+ continue
56
+ return False
57
+
58
+
59
+ # ── Replay ────────────────────────────────────────────────────
60
+
61
+ def replay_events(log_path: Path) -> list[dict[str, Any]]:
62
+ """Read and decode all events from the log. Returns parsed event dicts."""
63
+ from .events import EventCodec
64
+ return EventCodec.read_all(str(log_path))
65
+
66
+
67
+ # ── Integrity ─────────────────────────────────────────────────
68
+
69
+ def verify_hash(
70
+ log_path: Path, expected_sha256: str | None = None
71
+ ) -> tuple[bool, str]:
72
+ """Verify SHA-256 integrity of the event log.
73
+
74
+ Sorts events by (timestamp, event_id) before hashing for determinism.
75
+ Returns (valid, computed_hash).
76
+ """
77
+ h = hashlib.sha256()
78
+ if log_path.exists():
79
+ events = replay_events(log_path)
80
+ events.sort(key=lambda e: (
81
+ e.get("timestamp", 0),
82
+ e.get("event_id", ""),
83
+ ))
84
+ for ev in events:
85
+ h.update(json.dumps(ev, sort_keys=True, default=str).encode())
86
+ computed = h.hexdigest()
87
+ if expected_sha256 is not None:
88
+ return (computed == expected_sha256, computed)
89
+ return (True, computed)
90
+
91
+
92
+ # ── Crash Recovery ────────────────────────────────────────────
93
+
94
+ def scan_incomplete(
95
+ log_path: Path,
96
+ expected_cards: set[str],
97
+ ) -> list[str]:
98
+ """Find cards with no completion event (cardCompleted or cardFailed).
99
+
100
+ Returns list of card IDs that have been created but not completed.
101
+ """
102
+ completed: set[str] = set()
103
+ if log_path.exists():
104
+ for ev in replay_events(log_path):
105
+ card_id = ev.get("card_id", "")
106
+ if card_id and ev.get("type", "") in ("cardCompleted", "cardFailed"):
107
+ completed.add(card_id)
108
+ return sorted(expected_cards - completed)
109
+
110
+
111
+ def recover(
112
+ log_path: Path,
113
+ card_id: str,
114
+ retry_fn,
115
+ ) -> dict[str, Any]:
116
+ """Replay log up to card, identify last completed step, and retry.
117
+
118
+ retry_fn(card_id, last_step_id | None) is called to resume execution.
119
+ Returns the result of retry_fn.
120
+ """
121
+ events = replay_events(log_path) if log_path.exists() else []
122
+
123
+ # Find this card's events, scan for last completed step
124
+ last_step: str | None = None
125
+ for ev in reversed(events):
126
+ if ev.get("card_id") != card_id:
127
+ continue
128
+ if ev.get("type", "") == "stepCompleted":
129
+ last_step = ev.get("step_id")
130
+ break
131
+
132
+ return retry_fn(card_id, last_step)
133
+
134
+
135
+ # ── self-check ────────────────────────────────────────────────
136
+
137
+ if __name__ == "__main__":
138
+ import sys, tempfile, os, shutil
139
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
140
+ from .events import register_event_type
141
+
142
+ register_event_type("cardCreated")
143
+ register_event_type("stepStarted")
144
+ register_event_type("stepCompleted")
145
+ register_event_type("gatePassed")
146
+ register_event_type("gateBlocked")
147
+ register_event_type("cardCompleted")
148
+ register_event_type("cardFailed")
149
+
150
+ d = Path(tempfile.mkdtemp())
151
+ log = d / "events.jsonl"
152
+
153
+ # Append + dedup
154
+ assert append_event(log, "cardCreated", {"card_id": "c1"}, event_id="ev-1")
155
+ assert append_event(log, "cardCreated", {"card_id": "c1"}, event_id="ev-1") # idempotent
156
+ assert append_event(log, "stepStarted", {"card_id": "c1", "step_id": "s1"}, event_id="ev-2")
157
+ assert append_event(log, "stepCompleted", {"card_id": "c1", "step_id": "s1"}, event_id="ev-3")
158
+ assert append_event(log, "cardCompleted", {"card_id": "c1"}, event_id="ev-4")
159
+ # Incomplete card
160
+ assert append_event(log, "cardCreated", {"card_id": "c2"}, event_id="ev-5")
161
+
162
+ # Replay — 5 unique events (ev-1 dedup'd on second append)
163
+ events = replay_events(log)
164
+ assert len(events) == 5, f"expected 5, got {len(events)}"
165
+ assert events[0]["card_id"] == "c1"
166
+
167
+ # Hash
168
+ ok, h = verify_hash(log)
169
+ assert ok
170
+ ok2, h2 = verify_hash(log, expected_sha256=h)
171
+ assert ok2
172
+ # Wrong hash fails
173
+ ok3, _ = verify_hash(log, expected_sha256="deadbeef")
174
+ assert not ok3
175
+
176
+ # Scan incomplete
177
+ incomplete = scan_incomplete(log, {"c1", "c2"})
178
+ assert incomplete == ["c2"], f"expected ['c2'], got {incomplete}"
179
+
180
+ # Recover
181
+ def fake_retry(cid: str, last_step_id: str | None) -> dict[str, Any]:
182
+ return {"card_id": cid, "last_step": last_step_id}
183
+
184
+ result = recover(log, "c2", fake_retry)
185
+ assert result["card_id"] == "c2"
186
+ assert result["last_step"] is None # no steps completed for c2
187
+
188
+ result2 = recover(log, "c1", fake_retry)
189
+ assert result2["last_step"] == "s1"
190
+
191
+ print("✅ event_log")
192
+ shutil.rmtree(d)
@@ -0,0 +1,150 @@
1
+ """Type-based event versioning — each event type carries its own version.
2
+
3
+ No global schemaVersion. Each type evolves independently with its own upcaster
4
+ chain. Per research brief: upcasters deployed BEFORE new event versions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import threading
11
+ from typing import Any, Callable, Optional
12
+
13
+ Upcaster = Callable[[dict[str, Any]], dict[str, Any]]
14
+ """An upcaster transforms an event dict from version N to N+1."""
15
+
16
+
17
+ _event_types: dict[str, list[Upcaster]] = {}
18
+ _event_types_lock = threading.Lock()
19
+ """Registered event types and their upcaster chains.
20
+
21
+ Structure: {type_name: [v1→v2, v2→v3, ...]}
22
+ The current version = len(upcasters) + 1.
23
+ """
24
+
25
+
26
+ def event_types() -> dict[str, int]:
27
+ """Return {type_name: current_version} for all registered types."""
28
+ return {name: len(chain) + 1 for name, chain in _event_types.items()}
29
+
30
+
31
+ def register_event_type(name: str, upcasters: Optional[list[Upcaster]] = None
32
+ ) -> None:
33
+ """Register an event type with its upcaster chain.
34
+
35
+ Upcasters must be ordered oldest-first: [v1→v2, v2→v3, ...].
36
+ This must be called before any events of this type are written.
37
+ Thread-safe.
38
+ """
39
+ with _event_types_lock:
40
+ if name in _event_types:
41
+ raise ValueError(f"Event type {name!r} already registered")
42
+ _event_types[name] = list(upcasters or [])
43
+
44
+
45
+ class EventCodec:
46
+ """Encode/decode events with type-based versioning."""
47
+
48
+ @staticmethod
49
+ def encode(type_name: str, payload: dict[str, Any],
50
+ *,
51
+ timestamp: Optional[float] = None,
52
+ event_id: Optional[str] = None,
53
+ **extra_fields) -> dict[str, Any]:
54
+ """Build an event dict for writing.
55
+
56
+ Injects type, version, and timestamp. Each event type carries its own
57
+ current version from the registry.
58
+ """
59
+ import time as _time
60
+ if type_name not in _event_types:
61
+ raise KeyError(f"Unknown event type: {type_name!r}. Register it first.")
62
+ version = len(_event_types[type_name]) + 1
63
+ event: dict[str, Any] = {
64
+ "type": type_name,
65
+ "version": version,
66
+ "timestamp": timestamp if timestamp is not None else _time.time(),
67
+ **extra_fields,
68
+ **payload,
69
+ }
70
+ if event_id is not None:
71
+ event["event_id"] = event_id
72
+ return event
73
+
74
+ @staticmethod
75
+ def decode(raw: dict[str, Any]) -> dict[str, Any]:
76
+ """Decode a raw event dict, applying upcasters if needed.
77
+
78
+ If the event's version is older than the current registered version,
79
+ runs the upcaster chain to bring it current.
80
+ """
81
+ type_name = raw.get("type")
82
+ if not type_name or type_name not in _event_types:
83
+ return raw # unknown type — pass through
84
+ version = raw.get("version", 1)
85
+ chain = _event_types[type_name]
86
+ current = len(chain) + 1
87
+ if version >= current:
88
+ return raw
89
+ # Run upcasters from version-1 to current-1
90
+ event = dict(raw)
91
+ for i in range(version - 1, current - 1):
92
+ event = chain[i](event)
93
+ event["version"] = i + 2
94
+ return event
95
+
96
+ @staticmethod
97
+ def read_all(log_path: str) -> list[dict[str, Any]]:
98
+ """Read and decode all events from a JSONL file."""
99
+ events: list[dict] = []
100
+ with open(log_path) as f:
101
+ for line in f:
102
+ line = line.strip()
103
+ if not line:
104
+ continue
105
+ raw = json.loads(line)
106
+ events.append(EventCodec.decode(raw))
107
+ return events
108
+
109
+
110
+ # --- self-check ---
111
+ if __name__ == "__main__":
112
+ import tempfile, os, time
113
+
114
+ # Register a type
115
+ register_event_type("card_started")
116
+ def _v1_to_v2(e):
117
+ e = dict(e)
118
+ e["duration_ms"] = e.pop("dur", 0)
119
+ return e
120
+ register_event_type("card_completed", upcasters=[_v1_to_v2])
121
+
122
+ assert event_types() == {"card_started": 1, "card_completed": 2}
123
+
124
+ # Encode
125
+ ev = EventCodec.encode("card_started", {"card_id": "c1"}, event_id="ev-1")
126
+ assert ev["type"] == "card_started"
127
+ assert ev["version"] == 1
128
+ assert ev["event_id"] == "ev-1"
129
+ assert "timestamp" in ev
130
+ assert ev["card_id"] == "c1"
131
+
132
+ # Decode old version through upcaster
133
+ old = {"type": "card_completed", "version": 1, "card_id": "c2", "dur": 42}
134
+ decoded = EventCodec.decode(old)
135
+ assert decoded["version"] == 2
136
+ assert decoded["duration_ms"] == 42
137
+ assert "dur" not in decoded # upcaster renamed it
138
+
139
+ # Round-trip through JSONL
140
+ import pathlib
141
+ tmp = pathlib.Path(tempfile.mkdtemp()) / "events.jsonl"
142
+ with open(tmp, "w") as f:
143
+ f.write(json.dumps(EventCodec.encode("card_started", {"card_id": "c1"}, event_id="ev-1")) + "\n")
144
+ events = EventCodec.read_all(str(tmp))
145
+ assert len(events) == 1
146
+ assert events[0]["type"] == "card_started"
147
+
148
+ print("✅ events")
149
+ os.unlink(tmp)
150
+ os.rmdir(tmp.parent)
@@ -0,0 +1,87 @@
1
+ """4 golden signals — latency P99, throughput, error rate, saturation.
2
+
3
+ Self-contained stdlib module.
4
+ No external dependencies. Composes with event_log for crash recovery.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from collections import deque
11
+ from typing import Any
12
+
13
+
14
+ class GoldenSignals:
15
+ """Track the 4 golden signals for a component."""
16
+
17
+ def __init__(self, max_samples: int = 1000):
18
+ self.max_samples = max_samples
19
+ self._latencies: deque[float] = deque(maxlen=max_samples)
20
+ self._errors: deque[bool] = deque(maxlen=max_samples)
21
+ self._start_time = time.monotonic()
22
+ self._request_count = 0
23
+
24
+ def record(self, latency_ms: float, is_error: bool = False) -> None:
25
+ self._latencies.append(latency_ms)
26
+ self._errors.append(is_error)
27
+ self._request_count += 1
28
+
29
+ @property
30
+ def latency_p99(self) -> float:
31
+ if not self._latencies:
32
+ return 0.0
33
+ sorted_lat = sorted(self._latencies)
34
+ idx = int(len(sorted_lat) * 0.99)
35
+ return sorted_lat[min(idx, len(sorted_lat) - 1)]
36
+
37
+ @property
38
+ def throughput(self) -> float:
39
+ elapsed = time.monotonic() - self._start_time
40
+ if elapsed == 0:
41
+ return 0.0
42
+ return self._request_count / elapsed
43
+
44
+ @property
45
+ def error_rate(self) -> float:
46
+ if not self._errors:
47
+ return 0.0
48
+ return sum(self._errors) / len(self._errors)
49
+
50
+ @property
51
+ def saturation(self) -> float:
52
+ return len(self._latencies) / self.max_samples
53
+
54
+ def snapshot(self) -> dict[str, Any]:
55
+ return {
56
+ "latency_p99": self.latency_p99,
57
+ "throughput": self.throughput,
58
+ "error_rate": self.error_rate,
59
+ "saturation": self.saturation,
60
+ "sample_count": len(self._latencies),
61
+ }
62
+
63
+
64
+ def collect_signals(component_name: str) -> dict[str, Any]:
65
+ """Placeholder — real implementation reads from event log.
66
+
67
+ ponytail: stub returns zeros. Wire when signal collection is needed.
68
+ """
69
+ return {
70
+ "component": component_name,
71
+ "latency_p99": 0.0,
72
+ "throughput": 0.0,
73
+ "error_rate": 0.0,
74
+ "saturation": 0.0,
75
+ }
76
+
77
+
78
+ # --- self-check ---
79
+ if __name__ == "__main__":
80
+ gs = GoldenSignals(max_samples=100)
81
+ for i in range(100):
82
+ gs.record(latency_ms=float(i), is_error=(i < 5))
83
+ snap = gs.snapshot()
84
+ assert snap["sample_count"] == 100
85
+ assert 0.0 <= snap["error_rate"] <= 1.0
86
+ assert snap["throughput"] > 0
87
+ print("✅ monitoring")
@@ -0,0 +1,126 @@
1
+ """Crash recovery: scan incomplete cards on startup, event ID dedup.
2
+
3
+ At-least-once semantics. Recovery finds cards with no completion event and
4
+ re-plays from the last gatePassed checkpoint. Event ID dedup prevents
5
+ double-processing on replay.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Optional
13
+
14
+
15
+ def scan_incomplete_cards(card_dir: Path, suffix: str = ".card"
16
+ ) -> list[dict]:
17
+ """Find cards that were claimed but never completed.
18
+
19
+ Returns list of card data dicts for recovery processing.
20
+ Does NOT modify files — caller decides what to do.
21
+
22
+ A card is "incomplete" if it exists but has no matching
23
+ `card_completed` event in the event log referenced by the card dir.
24
+ """
25
+ if not card_dir.exists():
26
+ return []
27
+ incomplete: list[dict] = []
28
+ for cf in sorted(card_dir.glob(f"*{suffix}")):
29
+ # Skip temp files (from partial atomic_claim)
30
+ if cf.name.startswith("."):
31
+ continue
32
+ try:
33
+ data = json.loads(cf.read_text())
34
+ except (json.JSONDecodeError, OSError):
35
+ continue
36
+ # ponytail: incomplete = no 'completed_at' field. Caller
37
+ # may add richer detection (check event log for matching completion).
38
+ if "completed_at" not in data:
39
+ incomplete.append(data)
40
+ return incomplete
41
+
42
+
43
+ def dedup_events(events: list[dict]) -> list[dict]:
44
+ """Remove duplicate events by event_id, keeping first occurrence.
45
+
46
+ For at-least-once replay: if the same event_id appears multiple times
47
+ (e.g., after crash recovery + re-emit), only keep the first.
48
+ Events without an event_id are always included.
49
+ """
50
+ seen: set[str] = set()
51
+ out: list[dict] = []
52
+ for ev in events:
53
+ eid = ev.get("event_id")
54
+ if eid is None:
55
+ out.append(ev)
56
+ elif eid not in seen:
57
+ seen.add(eid)
58
+ out.append(ev)
59
+ return out
60
+
61
+
62
+ def find_last_checkpoint(log_path: Path
63
+ ) -> Optional[dict]:
64
+ """Find the last gatePassed event in the event log.
65
+
66
+ This is the recovery point: replay from here after a crash.
67
+ Per research brief §Tension 2: gate events ARE checkpoints.
68
+ """
69
+ if not log_path.exists():
70
+ return None
71
+ last: Optional[dict] = None
72
+ with open(log_path) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if not line:
76
+ continue
77
+ try:
78
+ ev = json.loads(line)
79
+ except json.JSONDecodeError:
80
+ continue
81
+ if ev.get("type") == "gatePassed":
82
+ last = ev
83
+ return last
84
+
85
+
86
+ # --- self-check ---
87
+ if __name__ == "__main__":
88
+ import tempfile, os
89
+
90
+ d = Path(tempfile.mkdtemp())
91
+ cards = d / "cards"
92
+ cards.mkdir()
93
+
94
+ # Incomplete: card exists with no completed_at
95
+ (cards / "c1.card").write_text(json.dumps({"card_id": "c1", "owner": "a1"}))
96
+ # Complete: has completed_at
97
+ (cards / "c2.card").write_text(json.dumps({"card_id": "c2", "completed_at": 123}))
98
+
99
+ incomplete = scan_incomplete_cards(cards)
100
+ assert len(incomplete) == 1
101
+ assert incomplete[0]["card_id"] == "c1"
102
+
103
+ # Dedup
104
+ events = [
105
+ {"event_id": "ev-1", "x": 1},
106
+ {"event_id": "ev-1", "x": 2}, # dup
107
+ {"event_id": "ev-2", "x": 3},
108
+ {"x": 4}, # no event_id — always included
109
+ ]
110
+ deduped = dedup_events(events)
111
+ assert len(deduped) == 3 # ev-1 once, ev-2, and the no-id event
112
+ assert deduped[0]["x"] == 1 # first occurrence kept
113
+
114
+ # find_last_checkpoint
115
+ log = d / "events.jsonl"
116
+ log.write_text('\n'.join([
117
+ json.dumps({"type": "cardStarted", "id": "ev-1"}),
118
+ json.dumps({"type": "gatePassed", "gate": "review"}),
119
+ json.dumps({"type": "cardCompleted", "id": "ev-2"}),
120
+ ]))
121
+ cp = find_last_checkpoint(log)
122
+ assert cp is not None
123
+ assert cp["gate"] == "review"
124
+
125
+ print("✅ recovery")
126
+ import shutil; shutil.rmtree(d)
@@ -0,0 +1,15 @@
1
+ """Tests for shared_state package import."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def test_shared_state_imports():
6
+ import shared_state
7
+ assert hasattr(shared_state, "locked_append")
8
+ assert hasattr(shared_state, "atomic_claim")
9
+ assert hasattr(shared_state, "EventCodec")
10
+ assert hasattr(shared_state, "register_event_type")
11
+ assert hasattr(shared_state, "scan_incomplete_cards")
12
+ assert hasattr(shared_state, "dedup_events")
13
+ assert hasattr(shared_state, "find_last_checkpoint")
14
+ assert hasattr(shared_state, "GoldenSignals")
15
+ assert hasattr(shared_state, "collect_signals")