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.
- tortoise/__init__.py +45 -0
- tortoise/__main__.py +1865 -0
- tortoise/analyze.py +473 -0
- tortoise/api.py +303 -0
- tortoise/archived/search_legacy.py +31 -0
- tortoise/audit.py +236 -0
- tortoise/audit_events.py +284 -0
- tortoise/auth.py +107 -0
- tortoise/backup.py +155 -0
- tortoise/config.py +99 -0
- tortoise/connector_loader.py +74 -0
- tortoise/connectors/__init__.py +5 -0
- tortoise/connectors/github.py +432 -0
- tortoise/connectors/github_docs.py +146 -0
- tortoise/connectors/linear.py +199 -0
- tortoise/connectors/slack.py +222 -0
- tortoise/consistency.py +132 -0
- tortoise/crypto.py +52 -0
- tortoise/deployment.py +62 -0
- tortoise/domain_loader.py +142 -0
- tortoise/dream.py +153 -0
- tortoise/embedded_reaper.py +744 -0
- tortoise/embeddings.py +227 -0
- tortoise/ep.py +534 -0
- tortoise/exceptions.py +16 -0
- tortoise/extractor.py +945 -0
- tortoise/hosted_api.py +1982 -0
- tortoise/hosted_middleware.py +22 -0
- tortoise/idempotency.py +39 -0
- tortoise/ids.py +23 -0
- tortoise/indexer/github_indexer.py +129 -0
- tortoise/ingest.py +614 -0
- tortoise/log.py +29 -0
- tortoise/m0.py +50 -0
- tortoise/mcp_auth.py +337 -0
- tortoise/mcp_client.py +108 -0
- tortoise/mcp_server.py +1356 -0
- tortoise/memory_orchestrator.py +492 -0
- tortoise/memory_scope.py +15 -0
- tortoise/migrate_db.py +244 -0
- tortoise/migrate_kinds.py +141 -0
- tortoise/mining.py +338 -0
- tortoise/models.py +109 -0
- tortoise/monitoring.py +133 -0
- tortoise/navigation.py +216 -0
- tortoise/pack_registry.py +767 -0
- tortoise/pipeline_cli.py +197 -0
- tortoise/projection/__init__.py +913 -0
- tortoise/projection/edges.py +311 -0
- tortoise/projection/entities.py +521 -0
- tortoise/projection/grounding.py +95 -0
- tortoise/projection/propagation.py +114 -0
- tortoise/projection.py +37 -0
- tortoise/quadrature.py +90 -0
- tortoise/query_suggestions.py +194 -0
- tortoise/quota.py +163 -0
- tortoise/ranking.py +280 -0
- tortoise/render.py +108 -0
- tortoise/scripts/manifest.py +67 -0
- tortoise/sdk.py +4713 -0
- tortoise/search_engine.py +887 -0
- tortoise/security.py +268 -0
- tortoise/selfhost.py +157 -0
- tortoise/selfhost_api.py +201 -0
- tortoise/session_continuity.py +82 -0
- tortoise/session_indexer.py +569 -0
- tortoise/shared_state/__init__.py +20 -0
- tortoise/shared_state/concurrency.py +113 -0
- tortoise/shared_state/event_log.py +192 -0
- tortoise/shared_state/events.py +150 -0
- tortoise/shared_state/monitoring.py +87 -0
- tortoise/shared_state/recovery.py +126 -0
- tortoise/shared_state/tests/__init__.py +15 -0
- tortoise/shared_state/tests/test_concurrency.py +123 -0
- tortoise/shared_state/tests/test_events.py +145 -0
- tortoise/shared_state/tests/test_monitoring.py +54 -0
- tortoise/shared_state/tests/test_recovery.py +181 -0
- tortoise/source_credibility.py +306 -0
- tortoise/svbp.py +446 -0
- tortoise/taxonomy.py +71 -0
- tortoise/test_cross_ontology.py +180 -0
- tortoise/test_tortoise_client.py +206 -0
- tortoise/tool_registry.py +805 -0
- tortoise/tortoise_client.py +262 -0
- tortoise/verify_ontology.py +154 -0
- tortoise/version_vector.py +97 -0
- tortoise/weights.py +61 -0
- tortoise_graph-0.2.0.dist-info/METADATA +152 -0
- tortoise_graph-0.2.0.dist-info/RECORD +93 -0
- tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
- tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
- tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
- tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
tortoise/__main__.py
ADDED
|
@@ -0,0 +1,1865 @@
|
|
|
1
|
+
"""CLI entry point: python -m tortoise <command>"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
def _cmd_rebuild(args):
|
|
8
|
+
print(f"Rebuilding from {args.dir} → {args.db}")
|
|
9
|
+
try:
|
|
10
|
+
from tortoise.projection import FalkorProjection
|
|
11
|
+
# skip_health_check: `rebuild` IS the recovery tool — a broken DB must
|
|
12
|
+
# not block its own rebuild (ops safety #428).
|
|
13
|
+
proj = FalkorProjection(args.db, skip_health_check=True)
|
|
14
|
+
counts = proj.rebuild_all(args.dir)
|
|
15
|
+
print(f"Done: {counts['nodes']} nodes, {counts['edges']} edges from {counts['events']} events")
|
|
16
|
+
except ImportError as e:
|
|
17
|
+
print(f"FalkorDB unavailable ({e}). Use InMemory rebuild:", file=sys.stderr)
|
|
18
|
+
from tortoise.log import EventLog
|
|
19
|
+
from tortoise.projection import fold
|
|
20
|
+
import os
|
|
21
|
+
events = []
|
|
22
|
+
for f in sorted(os.listdir(args.dir)):
|
|
23
|
+
if f.endswith('.jsonl'):
|
|
24
|
+
events.extend(EventLog(os.path.join(args.dir, f)).read_all())
|
|
25
|
+
points = fold(events)
|
|
26
|
+
statements, ops = 0, 0
|
|
27
|
+
for p in points.values():
|
|
28
|
+
if p.get('operator'):
|
|
29
|
+
ops += 1
|
|
30
|
+
else:
|
|
31
|
+
statements += 1
|
|
32
|
+
print(f"Done: {len(points)} total ({statements} statements, {ops} operators) [in-memory, no DB]")
|
|
33
|
+
|
|
34
|
+
def _cmd_demo(args):
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from tempfile import NamedTemporaryFile
|
|
37
|
+
from tortoise.log import EventLog
|
|
38
|
+
from tortoise.api import EventAPI
|
|
39
|
+
from tortoise.extractor import MockExtractor
|
|
40
|
+
|
|
41
|
+
transcript = Path(__file__).parent.parent / "tests" / "sample_transcript.txt"
|
|
42
|
+
text = transcript.read_text(encoding="utf-8")
|
|
43
|
+
|
|
44
|
+
with NamedTemporaryFile(suffix=".jsonl", mode="w+", delete=False) as tmp:
|
|
45
|
+
tmp.close()
|
|
46
|
+
log = EventLog(tmp.name)
|
|
47
|
+
api = EventAPI(log, initiated_by="extractor", agent_id="mock@0")
|
|
48
|
+
MockExtractor().run(text, transcript.name, api)
|
|
49
|
+
events = log.read_all()
|
|
50
|
+
Path(tmp.name).unlink()
|
|
51
|
+
|
|
52
|
+
points, operators = {}, []
|
|
53
|
+
for ev in events:
|
|
54
|
+
if ev["type"] == "PointAdded":
|
|
55
|
+
p = ev["point"]
|
|
56
|
+
points[p["id"]] = p
|
|
57
|
+
elif ev["type"] == "OperatorAdded":
|
|
58
|
+
operators.append(ev["point"])
|
|
59
|
+
|
|
60
|
+
print(f"{'='*60}")
|
|
61
|
+
print(f"Tortoise Demo \u2014 {transcript.name}")
|
|
62
|
+
print(f"Extracted {len(points)} statements, {len(operators)} connections")
|
|
63
|
+
print(f"{'='*60}")
|
|
64
|
+
|
|
65
|
+
# Build ID -> label lookup
|
|
66
|
+
lookup = {}
|
|
67
|
+
for pid, p in points.items():
|
|
68
|
+
prov = p.get("provenance", {})
|
|
69
|
+
lookup[pid] = f"{prov.get('speaker','?')}: {prov.get('quote', p['content'])}"
|
|
70
|
+
|
|
71
|
+
# Print statements in order of utterance (by span start)
|
|
72
|
+
ordered = sorted(points.items(), key=lambda kv: kv[1]["provenance"]["span"][0])
|
|
73
|
+
for pid, p in ordered:
|
|
74
|
+
prov = p["provenance"]
|
|
75
|
+
print(f"\n [{prov['speaker']}] {prov['quote']}")
|
|
76
|
+
|
|
77
|
+
if operators:
|
|
78
|
+
_sep = '─'*40
|
|
79
|
+
print(f"\n{_sep}")
|
|
80
|
+
print("Connections:")
|
|
81
|
+
for op in operators:
|
|
82
|
+
op_data = op["operator"]
|
|
83
|
+
label = "supports" if op_data["op_type"] == "IMPL" else "contradicts"
|
|
84
|
+
src = lookup.get(op_data["inputs"][0], op_data["inputs"][0])
|
|
85
|
+
dst = lookup.get(op_data["inputs"][1], op_data["inputs"][1])
|
|
86
|
+
_ell = '\u2026'
|
|
87
|
+
print(f" {op_data['op_type']}: \u201c{src[:70]}{_ell if len(src)>70 else ''}\u201d")
|
|
88
|
+
print(f" {label} \u2192 \u201c{dst[:70]}{_ell if len(dst)>70 else ''}\u201d")
|
|
89
|
+
print()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _cmd_mine_conversation(args):
|
|
93
|
+
"""Mine conversation transcript → Events + Points (GAP-15 / #7003)."""
|
|
94
|
+
import json
|
|
95
|
+
from pathlib import Path
|
|
96
|
+
from tempfile import NamedTemporaryFile
|
|
97
|
+
|
|
98
|
+
from tortoise.api import EventAPI
|
|
99
|
+
from tortoise.log import EventLog
|
|
100
|
+
from tortoise.mining import ConversationMiner
|
|
101
|
+
from tortoise.projection import FalkorProjection
|
|
102
|
+
|
|
103
|
+
transcript_path = Path(args.transcript)
|
|
104
|
+
if not transcript_path.exists():
|
|
105
|
+
print(f"Transcript not found: {args.transcript}", file=sys.stderr)
|
|
106
|
+
return 1
|
|
107
|
+
|
|
108
|
+
source_id = args.source_id or transcript_path.stem
|
|
109
|
+
text = transcript_path.read_text(encoding="utf-8")
|
|
110
|
+
|
|
111
|
+
# Set up log + projection
|
|
112
|
+
proj = None
|
|
113
|
+
log_path = Path(f"mine-{source_id}.jsonl")
|
|
114
|
+
if args.db:
|
|
115
|
+
try:
|
|
116
|
+
proj = FalkorProjection.from_uri(args.db)
|
|
117
|
+
except Exception as e:
|
|
118
|
+
print(f"Warning: FalkorDB unavailable ({e}), using log-only mode")
|
|
119
|
+
|
|
120
|
+
log = EventLog(str(log_path))
|
|
121
|
+
api = EventAPI(log, initiated_by="extractor", agent_id="mining-pilot", projection=proj)
|
|
122
|
+
|
|
123
|
+
# Disable idempotency for mining (always process fresh)
|
|
124
|
+
api._ingest_cache = {}
|
|
125
|
+
|
|
126
|
+
miner = ConversationMiner()
|
|
127
|
+
result = miner.mine(text, source_id, api)
|
|
128
|
+
|
|
129
|
+
if proj:
|
|
130
|
+
proj.close()
|
|
131
|
+
|
|
132
|
+
events = log.read_all()
|
|
133
|
+
event_entries = [e for e in events if e["type"] == "EventRecorded"]
|
|
134
|
+
point_entries = [e for e in events if e["type"] == "PointAdded"]
|
|
135
|
+
op_entries = [e for e in events if e["type"] == "OperatorAdded"]
|
|
136
|
+
|
|
137
|
+
print(f"{'='*60}")
|
|
138
|
+
print(f"Conversation Mining — {source_id}")
|
|
139
|
+
print(f"{'='*60}")
|
|
140
|
+
print(f"Events: {len(event_entries)} (gate: >=3)")
|
|
141
|
+
print(f"Points: {len(point_entries)}")
|
|
142
|
+
print(f"Operators: {len(op_entries)}")
|
|
143
|
+
print(f"Log: {log_path}")
|
|
144
|
+
print()
|
|
145
|
+
|
|
146
|
+
if len(event_entries) < 3:
|
|
147
|
+
print(f"\u26a0\ufe0f GATE FAILED: {len(event_entries)} events < 3 minimum")
|
|
148
|
+
print(f" Per plan WF4: <3 events/session → permanently descoped.")
|
|
149
|
+
else:
|
|
150
|
+
print(f"\u2705 GATE PASSED: {len(event_entries)} events")
|
|
151
|
+
|
|
152
|
+
print()
|
|
153
|
+
for ev in event_entries:
|
|
154
|
+
e = ev.get("event", {})
|
|
155
|
+
kind = e.get("eventKind", "unknown")
|
|
156
|
+
obj = e.get("object", "")[:80]
|
|
157
|
+
print(f" [{kind}] {obj}..." if len(e.get("object","")) > 80 else f" [{kind}] {obj}")
|
|
158
|
+
print()
|
|
159
|
+
|
|
160
|
+
return result
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _cmd_reconcile(args):
|
|
164
|
+
"""Replay unprojected EventRecorded entries from JSONL into FalkorDB."""
|
|
165
|
+
import json, sys
|
|
166
|
+
from pathlib import Path
|
|
167
|
+
|
|
168
|
+
if not args.db.startswith("docker://"):
|
|
169
|
+
print("Error: reconcile requires docker:// URI (e.g. docker://:pass@localhost:6379)", file=sys.stderr)
|
|
170
|
+
return 1
|
|
171
|
+
|
|
172
|
+
log_path = Path(args.log)
|
|
173
|
+
if not log_path.exists():
|
|
174
|
+
print(f"No event log found at {args.log}. Nothing to reconcile.", file=sys.stderr)
|
|
175
|
+
return 1
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
from tortoise.log import EventLog
|
|
179
|
+
from tortoise.projection import FalkorProjection
|
|
180
|
+
except ImportError:
|
|
181
|
+
print("Tortoise not installed. Run: pip install -e negation-game-explorations/tortoise", file=sys.stderr)
|
|
182
|
+
return 1
|
|
183
|
+
|
|
184
|
+
events = EventLog(log_path).read_all()
|
|
185
|
+
|
|
186
|
+
proj = None
|
|
187
|
+
try:
|
|
188
|
+
proj = FalkorProjection.from_uri(args.db)
|
|
189
|
+
|
|
190
|
+
event_entries = [ev for ev in events if ev["type"] == "EventRecorded"]
|
|
191
|
+
all_ids = [ev["event"]["eventId"] for ev in event_entries]
|
|
192
|
+
existing: set[str] = set()
|
|
193
|
+
for i in range(0, len(all_ids), 500):
|
|
194
|
+
batch = all_ids[i:i+500]
|
|
195
|
+
rows = proj.g.query(
|
|
196
|
+
"UNWIND $ids AS eid MATCH (e:Event {eventId:eid}) RETURN e.eventId",
|
|
197
|
+
params={"ids": batch}
|
|
198
|
+
).result_set
|
|
199
|
+
existing.update(r[0] for r in rows if r)
|
|
200
|
+
|
|
201
|
+
applied = 0
|
|
202
|
+
for ev in event_entries:
|
|
203
|
+
if ev["event"]["eventId"] not in existing:
|
|
204
|
+
proj.apply(ev)
|
|
205
|
+
applied += 1
|
|
206
|
+
|
|
207
|
+
total = len(event_entries)
|
|
208
|
+
print(f"Reconciled {applied} events ({total - applied} already projected — {total} total)")
|
|
209
|
+
finally:
|
|
210
|
+
if proj:
|
|
211
|
+
proj.close()
|
|
212
|
+
return 0
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _cmd_init(args):
|
|
217
|
+
"""Auto-detect FalkorDB and create default graph — onboarding."""
|
|
218
|
+
import json as _json
|
|
219
|
+
import os, tempfile
|
|
220
|
+
from pathlib import Path
|
|
221
|
+
|
|
222
|
+
# ── Cloud mode (--api-key) ──────────────────────────────────
|
|
223
|
+
if getattr(args, 'api_key', None):
|
|
224
|
+
config_path = Path.cwd() / ".tortoise"
|
|
225
|
+
if config_path.exists():
|
|
226
|
+
existing = _json.loads(config_path.read_text())
|
|
227
|
+
if existing.get("api_key") == args.api_key:
|
|
228
|
+
print("Already connected to Tortoise Cloud with this API key.")
|
|
229
|
+
return 0
|
|
230
|
+
print(f"⚠️ Existing .tortoise config found — overwriting.")
|
|
231
|
+
config = {
|
|
232
|
+
"api_key": args.api_key,
|
|
233
|
+
"api_url": os.environ.get("TORTOISE_API_URL", "https://api.premiselabs.co"),
|
|
234
|
+
}
|
|
235
|
+
config_path.write_text(_json.dumps(config, indent=2) + "\n")
|
|
236
|
+
os.chmod(config_path, 0o600)
|
|
237
|
+
print("Connected to Tortoise Cloud (team will be resolved from API key)")
|
|
238
|
+
print(f"Config saved to {config_path}")
|
|
239
|
+
print("⚠️ .tortoise contains a plaintext API key — do NOT commit this file.")
|
|
240
|
+
print()
|
|
241
|
+
print("Next steps:")
|
|
242
|
+
print(" tortoise session capture --file transcript.txt # capture an agent session")
|
|
243
|
+
print(" tortoise session list # view your sessions")
|
|
244
|
+
print(" # Connect your agent via MCP (see welcome page)")
|
|
245
|
+
return 0
|
|
246
|
+
|
|
247
|
+
print("Tortoise init — auto-detecting FalkorDB…")
|
|
248
|
+
|
|
249
|
+
# 1. Try Docker FalkorDB
|
|
250
|
+
docker_host = os.environ.get("FALKORDB_HOST", "localhost")
|
|
251
|
+
docker_pass = os.environ.get("FALKORDB_PASSWORD", "")
|
|
252
|
+
|
|
253
|
+
try:
|
|
254
|
+
docker_port = int(os.environ.get("FALKORDB_PORT", "16379"))
|
|
255
|
+
except (ValueError, TypeError):
|
|
256
|
+
print(f" ❌ Invalid FALKORDB_PORT: {os.environ.get('FALKORDB_PORT')!r}. Must be an integer.")
|
|
257
|
+
return 1
|
|
258
|
+
|
|
259
|
+
graph_ready = False
|
|
260
|
+
docker_detected = False
|
|
261
|
+
|
|
262
|
+
try:
|
|
263
|
+
from falkordb import FalkorDB
|
|
264
|
+
db = FalkorDB(host=docker_host, port=docker_port,
|
|
265
|
+
password=docker_pass or None)
|
|
266
|
+
db.select_graph("tortoise").query("RETURN 1")
|
|
267
|
+
print(f" ✅ Docker FalkorDB detected at {docker_host}:{docker_port}")
|
|
268
|
+
graph_ready = True
|
|
269
|
+
docker_detected = True
|
|
270
|
+
except ImportError:
|
|
271
|
+
pass
|
|
272
|
+
except (ConnectionError, ConnectionRefusedError, OSError) as e:
|
|
273
|
+
print(f" ⚠️ Docker FalkorDB unreachable at {docker_host}:{docker_port}: {e}")
|
|
274
|
+
except Exception as e:
|
|
275
|
+
err = str(e).lower()
|
|
276
|
+
if "auth" in err or "password" in err:
|
|
277
|
+
print(f" ⚠️ Docker FalkorDB auth failed — check FALKORDB_PASSWORD env var")
|
|
278
|
+
else:
|
|
279
|
+
print(f" ⚠️ Docker FalkorDB unreachable ({e})")
|
|
280
|
+
|
|
281
|
+
# 2. Fallback: embedded mode (SQLite-backed)
|
|
282
|
+
if not graph_ready:
|
|
283
|
+
from tortoise.config import resolve_db_path
|
|
284
|
+
db_path = args.path or resolve_db_path()
|
|
285
|
+
try:
|
|
286
|
+
from tortoise.projection import FalkorProjection
|
|
287
|
+
_proj = FalkorProjection(db_path)
|
|
288
|
+
_proj.g.query("RETURN 1")
|
|
289
|
+
print(f" ✅ Embedded mode initialized at {db_path}")
|
|
290
|
+
graph_ready = True
|
|
291
|
+
except ImportError:
|
|
292
|
+
print(f" ❌ Neither falkordb nor redislite installed.")
|
|
293
|
+
print(f" pip install falkordb # for Docker mode (FalkorProjection)")
|
|
294
|
+
print(f" pip install redislite # for embedded mode (FalkorProjection)")
|
|
295
|
+
return 1
|
|
296
|
+
except Exception as e:
|
|
297
|
+
print(f" ❌ Embedded mode init failed: {e}")
|
|
298
|
+
return 1
|
|
299
|
+
|
|
300
|
+
if not graph_ready:
|
|
301
|
+
return 1
|
|
302
|
+
|
|
303
|
+
# Write welcome Point to the graph
|
|
304
|
+
try:
|
|
305
|
+
from tortoise.sdk import TortoiseSDK
|
|
306
|
+
if docker_detected:
|
|
307
|
+
os.environ.setdefault("TORTOISE_DB_URI",
|
|
308
|
+
f"docker://:{docker_pass}@{docker_host}:{docker_port}/tortoise")
|
|
309
|
+
sdk = TortoiseSDK()
|
|
310
|
+
else:
|
|
311
|
+
sdk = TortoiseSDK(db_path=db_path)
|
|
312
|
+
sdk.create_point(
|
|
313
|
+
kind="observation",
|
|
314
|
+
content="Tortoise graph initialized — file decisions and observations here so your agents remember across sessions.",
|
|
315
|
+
tags=["system", "welcome"],
|
|
316
|
+
)
|
|
317
|
+
status = sdk.status()
|
|
318
|
+
point_count = status.get("counts", {}).get("Point", 0)
|
|
319
|
+
except Exception:
|
|
320
|
+
point_count = "?"
|
|
321
|
+
|
|
322
|
+
print(f" Graph: tortoise | Points: {point_count}")
|
|
323
|
+
print()
|
|
324
|
+
print("Graph ready. The graph starts empty — it fills as you and your agents")
|
|
325
|
+
print("file decisions, observations, and findings.")
|
|
326
|
+
print()
|
|
327
|
+
print("Next steps:")
|
|
328
|
+
print(" tortoise setup — configure per-role memory (~2 min, optional)")
|
|
329
|
+
print(" tortoise doctor — verify everything is healthy")
|
|
330
|
+
print(" tortoise serve — start MCP server for agents")
|
|
331
|
+
|
|
332
|
+
# Onboarding: detect git repo and offer indexing
|
|
333
|
+
import subprocess as _sp
|
|
334
|
+
import sys as _sys
|
|
335
|
+
result = _sp.run(
|
|
336
|
+
["git", "rev-parse", "--show-toplevel"],
|
|
337
|
+
capture_output=True, text=True, timeout=5,
|
|
338
|
+
)
|
|
339
|
+
if result.returncode == 0:
|
|
340
|
+
repo_root = result.stdout.strip()
|
|
341
|
+
md_count = len(list(__import__("pathlib").Path(repo_root).rglob("*.md")))
|
|
342
|
+
auto_index = getattr(args, 'yes', False)
|
|
343
|
+
if md_count > 0:
|
|
344
|
+
if auto_index:
|
|
345
|
+
print(f"\nFound {md_count} markdown files in this repo. Auto-indexing…")
|
|
346
|
+
log_f = open(str(Path(tempfile.gettempdir()) / "tortoise-init-index.log"), 'w')
|
|
347
|
+
_sp.Popen(
|
|
348
|
+
[_sys.executable, "-m", "tortoise", "index", "github", repo_root],
|
|
349
|
+
stdout=log_f, stderr=_sp.STDOUT,
|
|
350
|
+
start_new_session=True,
|
|
351
|
+
)
|
|
352
|
+
print("Indexing in background. Tortoise is ready to use immediately.")
|
|
353
|
+
else:
|
|
354
|
+
print()
|
|
355
|
+
yn = input(f"Found {md_count} markdown files in this repo. Index them into Tortoise? [Y/n]: ").strip().lower()
|
|
356
|
+
if yn != "n":
|
|
357
|
+
print("Launching indexer in background…")
|
|
358
|
+
log_f = open(str(Path(tempfile.gettempdir()) / "tortoise-init-index.log"), 'a')
|
|
359
|
+
_sp.Popen(
|
|
360
|
+
[_sys.executable, "-m", "tortoise", "index", "github", repo_root],
|
|
361
|
+
stdout=log_f, stderr=_sp.STDOUT,
|
|
362
|
+
start_new_session=True,
|
|
363
|
+
)
|
|
364
|
+
print("Indexing in background. Tortoise is ready to use immediately.")
|
|
365
|
+
return 0
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _cmd_team_info(args) -> int:
|
|
369
|
+
"""Show team info from Tortoise Cloud API."""
|
|
370
|
+
import json, sys
|
|
371
|
+
from pathlib import Path
|
|
372
|
+
from urllib.request import Request, urlopen
|
|
373
|
+
from urllib.error import URLError, HTTPError
|
|
374
|
+
|
|
375
|
+
# Read config
|
|
376
|
+
config_path = Path.cwd() / ".tortoise"
|
|
377
|
+
if not config_path.exists():
|
|
378
|
+
print("No .tortoise config found. Run 'tortoise init --api-key <key>' first.", file=sys.stderr)
|
|
379
|
+
return 1
|
|
380
|
+
|
|
381
|
+
try:
|
|
382
|
+
config = json.loads(config_path.read_text())
|
|
383
|
+
except json.JSONDecodeError:
|
|
384
|
+
print(f"Invalid .tortoise config at {config_path}", file=sys.stderr)
|
|
385
|
+
return 1
|
|
386
|
+
|
|
387
|
+
api_key = config.get("api_key")
|
|
388
|
+
api_url = config.get("api_url") or os.environ.get("TORTOISE_API_URL", "https://api.premiselabs.co")
|
|
389
|
+
if not api_key:
|
|
390
|
+
print("No api_key in .tortoise config.", file=sys.stderr)
|
|
391
|
+
return 1
|
|
392
|
+
|
|
393
|
+
# Call API
|
|
394
|
+
try:
|
|
395
|
+
req = Request(
|
|
396
|
+
f"{api_url}/v1/team",
|
|
397
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
398
|
+
)
|
|
399
|
+
with urlopen(req, timeout=10) as resp:
|
|
400
|
+
data = json.loads(resp.read())
|
|
401
|
+
except (json.JSONDecodeError, ValueError) as e:
|
|
402
|
+
print(f"Invalid response from API: {e}", file=sys.stderr)
|
|
403
|
+
return 1
|
|
404
|
+
except HTTPError as e:
|
|
405
|
+
body = e.read().decode() if e.fp else ""
|
|
406
|
+
print(f"API error ({e.code}): {body}", file=sys.stderr)
|
|
407
|
+
return 1
|
|
408
|
+
except URLError as e:
|
|
409
|
+
print(f"Cannot reach API at {api_url}: {e.reason}", file=sys.stderr)
|
|
410
|
+
return 1
|
|
411
|
+
|
|
412
|
+
print(f"Team: {data.get('team_id', '?')}")
|
|
413
|
+
print(f"Tier: {data.get('tier', 'free')}")
|
|
414
|
+
print(f"Points: {data.get('point_count', 0)}")
|
|
415
|
+
print(f"Max users: {data.get('max_users', 1)}")
|
|
416
|
+
print(f"Max graphs: {data.get('max_graphs', 1)}")
|
|
417
|
+
return 0
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _cmd_create_point(args) -> int:
|
|
421
|
+
"""Create a Point via Tortoise Cloud API."""
|
|
422
|
+
import json as _json, os, sys as _sys
|
|
423
|
+
from pathlib import Path
|
|
424
|
+
from urllib.request import Request, urlopen
|
|
425
|
+
from urllib.error import URLError, HTTPError
|
|
426
|
+
|
|
427
|
+
# Read config
|
|
428
|
+
config_path = Path.cwd() / ".tortoise"
|
|
429
|
+
if not config_path.exists():
|
|
430
|
+
print("No .tortoise config found. Run 'tortoise init --api-key <key>' first.", file=_sys.stderr)
|
|
431
|
+
return 1
|
|
432
|
+
|
|
433
|
+
try:
|
|
434
|
+
config = _json.loads(config_path.read_text())
|
|
435
|
+
except _json.JSONDecodeError:
|
|
436
|
+
print(f"Invalid .tortoise config at {config_path}", file=_sys.stderr)
|
|
437
|
+
return 1
|
|
438
|
+
|
|
439
|
+
api_key = config.get("api_key")
|
|
440
|
+
api_url = config.get("api_url") or os.environ.get("TORTOISE_API_URL", "https://api.premiselabs.co")
|
|
441
|
+
if not api_key:
|
|
442
|
+
print("No api_key in .tortoise config.", file=_sys.stderr)
|
|
443
|
+
return 1
|
|
444
|
+
|
|
445
|
+
payload = {
|
|
446
|
+
"content": args.content,
|
|
447
|
+
"kind": args.kind or "statement",
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
try:
|
|
451
|
+
data = _json.dumps(payload).encode("utf-8")
|
|
452
|
+
req = Request(
|
|
453
|
+
f"{api_url}/v1/points",
|
|
454
|
+
data=data,
|
|
455
|
+
headers={
|
|
456
|
+
"Authorization": f"Bearer {api_key}",
|
|
457
|
+
"Content-Type": "application/json",
|
|
458
|
+
},
|
|
459
|
+
method="POST",
|
|
460
|
+
)
|
|
461
|
+
with urlopen(req, timeout=30) as resp:
|
|
462
|
+
result = _json.loads(resp.read())
|
|
463
|
+
except HTTPError as e:
|
|
464
|
+
body = e.read().decode() if e.fp else ""
|
|
465
|
+
print(f"API error ({e.code}): {body}", file=_sys.stderr)
|
|
466
|
+
return 1
|
|
467
|
+
except URLError as e:
|
|
468
|
+
print(f"Cannot reach API at {api_url}: {e.reason}", file=_sys.stderr)
|
|
469
|
+
return 1
|
|
470
|
+
|
|
471
|
+
point_id = result.get("id", result.get("point_id", "unknown"))
|
|
472
|
+
print(f"Created point: {point_id}")
|
|
473
|
+
print(f" Kind: {args.kind or 'statement'}")
|
|
474
|
+
content_preview = args.content[:100] + "..." if len(args.content) > 100 else args.content
|
|
475
|
+
print(f" Content: {content_preview}")
|
|
476
|
+
return 0
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _cmd_context(args) -> int:
|
|
480
|
+
"""Print a compact memory digest for agent session-start injection.
|
|
481
|
+
|
|
482
|
+
Used by the Claude Code SessionStart hook: stdout from this command is
|
|
483
|
+
injected into the session context automatically, so the agent starts
|
|
484
|
+
each session knowing what Tortoise already remembers.
|
|
485
|
+
|
|
486
|
+
Hosted mode (\".tortoise\" config): calls the hosted API.
|
|
487
|
+
Local mode (embedded/Docker): uses TortoiseSDK.session_context().
|
|
488
|
+
"""
|
|
489
|
+
import json as _json, os as _os, sys as _sys
|
|
490
|
+
from pathlib import Path
|
|
491
|
+
|
|
492
|
+
config_path = Path.cwd() / ".tortoise"
|
|
493
|
+
api_key = None
|
|
494
|
+
api_url = _os.environ.get("TORTOISE_API_URL", "https://api.premiselabs.co")
|
|
495
|
+
|
|
496
|
+
if config_path.exists():
|
|
497
|
+
try:
|
|
498
|
+
cfg = _json.loads(config_path.read_text())
|
|
499
|
+
api_key = cfg.get("api_key")
|
|
500
|
+
api_url = cfg.get("api_url") or api_url
|
|
501
|
+
except _json.JSONDecodeError:
|
|
502
|
+
pass
|
|
503
|
+
|
|
504
|
+
if api_key:
|
|
505
|
+
# ── Hosted: query the API ──
|
|
506
|
+
from urllib.request import Request, urlopen
|
|
507
|
+
from urllib.error import URLError, HTTPError
|
|
508
|
+
try:
|
|
509
|
+
req = Request(
|
|
510
|
+
f"{api_url}/v1/context",
|
|
511
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
512
|
+
)
|
|
513
|
+
with urlopen(req, timeout=15) as resp:
|
|
514
|
+
data = _json.loads(resp.read())
|
|
515
|
+
except HTTPError as e:
|
|
516
|
+
body = e.read().decode() if e.fp else ""
|
|
517
|
+
print(f"Cannot reach Tortoise API ({e.code}): {body}", file=_sys.stderr)
|
|
518
|
+
return 1
|
|
519
|
+
except (URLError, ValueError) as e:
|
|
520
|
+
print(f"Cannot reach Tortoise API: {e.reason if hasattr(e,'reason') else e}", file=_sys.stderr)
|
|
521
|
+
return 1
|
|
522
|
+
else:
|
|
523
|
+
# ── Local: SDK (embedded or TORTOISE_DB_URI) ──
|
|
524
|
+
try:
|
|
525
|
+
from tortoise.sdk import TortoiseSDK
|
|
526
|
+
if _os.environ.get("TORTOISE_DB_URI"):
|
|
527
|
+
sdk = TortoiseSDK()
|
|
528
|
+
else:
|
|
529
|
+
sdk = TortoiseSDK(db_path=_os.environ.get("TORTOISE_DB_PATH"))
|
|
530
|
+
data = sdk.session_context()
|
|
531
|
+
except Exception as e:
|
|
532
|
+
print(f"Tortoise unavailable: {e}", file=_sys.stderr)
|
|
533
|
+
return 1
|
|
534
|
+
|
|
535
|
+
if data.get("no_prior_sessions") or not (data.get("diary_entries") or data.get("recent_points") or data.get("recent_events")):
|
|
536
|
+
print("<Tortoise memory is empty — no prior sessions yet.>")
|
|
537
|
+
return 0
|
|
538
|
+
|
|
539
|
+
print("# Tortoise memory (from previous sessions)")
|
|
540
|
+
|
|
541
|
+
diary = data.get("diary_entries") or []
|
|
542
|
+
if diary:
|
|
543
|
+
print()
|
|
544
|
+
print("## Recent diary")
|
|
545
|
+
for p in diary[:5]:
|
|
546
|
+
ts = (p.get("createdAt") or "")[:10]
|
|
547
|
+
print(f"- [{ts}] {p.get('content','')[:160]}")
|
|
548
|
+
|
|
549
|
+
points = data.get("recent_points") or []
|
|
550
|
+
if points:
|
|
551
|
+
print()
|
|
552
|
+
print("## Recent points/decisions")
|
|
553
|
+
for p in points[:8]:
|
|
554
|
+
kind = p.get("pointKind", "point")
|
|
555
|
+
print(f"- ({kind}) {p.get('content','')[:160]}")
|
|
556
|
+
|
|
557
|
+
conf = data.get("confidence_changes") or []
|
|
558
|
+
if conf:
|
|
559
|
+
print()
|
|
560
|
+
print("## Confidence-tracked claims")
|
|
561
|
+
for c in conf[:5]:
|
|
562
|
+
print(f"- [{c.get('confidence',0):.2f}] {c.get('content','')[:120]}")
|
|
563
|
+
|
|
564
|
+
print()
|
|
565
|
+
print("Ask me about any of the above; file new decisions with tortoise_create_point.")
|
|
566
|
+
return 0
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _cmd_session(args) -> int:
|
|
570
|
+
"""Manage Tortoise Cloud sessions."""
|
|
571
|
+
import json, os, sys
|
|
572
|
+
from pathlib import Path
|
|
573
|
+
from urllib.request import Request, urlopen
|
|
574
|
+
from urllib.error import URLError, HTTPError
|
|
575
|
+
|
|
576
|
+
# Read config
|
|
577
|
+
config_path = Path.cwd() / ".tortoise"
|
|
578
|
+
if not config_path.exists():
|
|
579
|
+
print("No .tortoise config found. Run 'tortoise init --api-key <key>' first.", file=sys.stderr)
|
|
580
|
+
return 1
|
|
581
|
+
|
|
582
|
+
try:
|
|
583
|
+
config = json.loads(config_path.read_text())
|
|
584
|
+
except json.JSONDecodeError:
|
|
585
|
+
print(f"Invalid .tortoise config at {config_path}", file=sys.stderr)
|
|
586
|
+
return 1
|
|
587
|
+
|
|
588
|
+
api_key = config.get("api_key")
|
|
589
|
+
api_url = config.get("api_url") or os.environ.get("TORTOISE_API_URL", "https://api.premiselabs.co")
|
|
590
|
+
if not api_key:
|
|
591
|
+
print("No api_key in .tortoise config.", file=sys.stderr)
|
|
592
|
+
return 1
|
|
593
|
+
|
|
594
|
+
if args.session_cmd == "capture":
|
|
595
|
+
return _cmd_session_capture(args, api_key, api_url)
|
|
596
|
+
elif args.session_cmd == "list":
|
|
597
|
+
return _cmd_session_list(api_key, api_url)
|
|
598
|
+
elif args.session_cmd == "view":
|
|
599
|
+
return _cmd_session_view(args, api_key, api_url)
|
|
600
|
+
else:
|
|
601
|
+
print("Unknown session command. Try capture, list, or view.", file=sys.stderr)
|
|
602
|
+
return 1
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _parse_transcript(text: str) -> list:
|
|
606
|
+
"""Parse a transcript file into conversation turns.
|
|
607
|
+
|
|
608
|
+
Handles common speaker prefixes: User:, Human:, Me:, Assistant:, AI:, You:, System:
|
|
609
|
+
"""
|
|
610
|
+
turns = []
|
|
611
|
+
current_role = None
|
|
612
|
+
current_lines = []
|
|
613
|
+
|
|
614
|
+
for line in text.split('\n'):
|
|
615
|
+
stripped = line.strip()
|
|
616
|
+
lower = stripped.lower()
|
|
617
|
+
if any(lower.startswith(p) for p in ('user:', 'human:', 'me:')):
|
|
618
|
+
if current_role is not None and current_lines:
|
|
619
|
+
turns.append({"role": current_role, "content": '\n'.join(current_lines).strip()})
|
|
620
|
+
current_lines = []
|
|
621
|
+
colon = stripped.index(':')
|
|
622
|
+
current_role = 'user'
|
|
623
|
+
content = stripped[colon + 1:].strip()
|
|
624
|
+
if content:
|
|
625
|
+
current_lines.append(content)
|
|
626
|
+
elif any(lower.startswith(p) for p in ('assistant:', 'ai:', 'you:')):
|
|
627
|
+
if current_role is not None and current_lines:
|
|
628
|
+
turns.append({"role": current_role, "content": '\n'.join(current_lines).strip()})
|
|
629
|
+
current_lines = []
|
|
630
|
+
colon = stripped.index(':')
|
|
631
|
+
current_role = 'assistant'
|
|
632
|
+
content = stripped[colon + 1:].strip()
|
|
633
|
+
if content:
|
|
634
|
+
current_lines.append(content)
|
|
635
|
+
elif lower.startswith('system:'):
|
|
636
|
+
if current_role is not None and current_lines:
|
|
637
|
+
turns.append({"role": current_role, "content": '\n'.join(current_lines).strip()})
|
|
638
|
+
current_lines = []
|
|
639
|
+
colon = stripped.index(':')
|
|
640
|
+
current_role = 'system'
|
|
641
|
+
content = stripped[colon + 1:].strip()
|
|
642
|
+
if content:
|
|
643
|
+
current_lines.append(content)
|
|
644
|
+
elif stripped:
|
|
645
|
+
if current_role is not None:
|
|
646
|
+
current_lines.append(stripped)
|
|
647
|
+
|
|
648
|
+
if current_role is not None and current_lines:
|
|
649
|
+
turns.append({"role": current_role, "content": '\n'.join(current_lines).strip()})
|
|
650
|
+
|
|
651
|
+
return turns
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def _cmd_session_capture(args, api_key: str, api_url: str) -> int:
|
|
655
|
+
"""Read transcript, parse into turns, POST to /v1/sessions."""
|
|
656
|
+
import json as _json, sys as _sys
|
|
657
|
+
from pathlib import Path
|
|
658
|
+
from urllib.request import Request, urlopen
|
|
659
|
+
from urllib.error import URLError, HTTPError
|
|
660
|
+
|
|
661
|
+
transcript_path = Path(args.file)
|
|
662
|
+
if not transcript_path.exists():
|
|
663
|
+
print(f"Transcript file not found: {args.file}", file=_sys.stderr)
|
|
664
|
+
return 1
|
|
665
|
+
|
|
666
|
+
text = transcript_path.read_text(encoding="utf-8")
|
|
667
|
+
turns = _parse_transcript(text)
|
|
668
|
+
|
|
669
|
+
if not turns:
|
|
670
|
+
print("No conversation turns found in transcript.", file=_sys.stderr)
|
|
671
|
+
return 1
|
|
672
|
+
|
|
673
|
+
payload = {
|
|
674
|
+
"source": transcript_path.stem,
|
|
675
|
+
"conversation": turns,
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
try:
|
|
679
|
+
data = _json.dumps(payload).encode("utf-8")
|
|
680
|
+
req = Request(
|
|
681
|
+
f"{api_url}/v1/sessions",
|
|
682
|
+
data=data,
|
|
683
|
+
headers={
|
|
684
|
+
"Authorization": f"Bearer {api_key}",
|
|
685
|
+
"Content-Type": "application/json",
|
|
686
|
+
},
|
|
687
|
+
method="POST",
|
|
688
|
+
)
|
|
689
|
+
with urlopen(req, timeout=30) as resp:
|
|
690
|
+
result = _json.loads(resp.read())
|
|
691
|
+
except HTTPError as e:
|
|
692
|
+
body = e.read().decode() if e.fp else ""
|
|
693
|
+
print(f"API error ({e.code}): {body}", file=_sys.stderr)
|
|
694
|
+
return 1
|
|
695
|
+
except URLError as e:
|
|
696
|
+
print(f"Cannot reach API at {api_url}: {e.reason}", file=_sys.stderr)
|
|
697
|
+
return 1
|
|
698
|
+
|
|
699
|
+
session_id = result.get("session_id", result.get("id", "unknown"))
|
|
700
|
+
print(f"Captured session: {session_id}")
|
|
701
|
+
print(f" Turns: {len(turns)}")
|
|
702
|
+
print(f" Source: {transcript_path.stem}")
|
|
703
|
+
return 0
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _cmd_session_list(api_key: str, api_url: str) -> int:
|
|
707
|
+
"""GET /v1/sessions — list all sessions."""
|
|
708
|
+
import json as _json, sys as _sys
|
|
709
|
+
from urllib.request import Request, urlopen
|
|
710
|
+
from urllib.error import URLError, HTTPError
|
|
711
|
+
|
|
712
|
+
try:
|
|
713
|
+
req = Request(
|
|
714
|
+
f"{api_url}/v1/sessions",
|
|
715
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
716
|
+
)
|
|
717
|
+
with urlopen(req, timeout=10) as resp:
|
|
718
|
+
data = _json.loads(resp.read())
|
|
719
|
+
except HTTPError as e:
|
|
720
|
+
body = e.read().decode() if e.fp else ""
|
|
721
|
+
print(f"API error ({e.code}): {body}", file=_sys.stderr)
|
|
722
|
+
return 1
|
|
723
|
+
except URLError as e:
|
|
724
|
+
print(f"Cannot reach API at {api_url}: {e.reason}", file=_sys.stderr)
|
|
725
|
+
return 1
|
|
726
|
+
|
|
727
|
+
sessions = data if isinstance(data, list) else data.get("sessions", [])
|
|
728
|
+
if not sessions:
|
|
729
|
+
print("No sessions found.")
|
|
730
|
+
return 0
|
|
731
|
+
|
|
732
|
+
print(f"{'ID':<36} {'Turns':<6} {'Created'}")
|
|
733
|
+
print("-" * 60)
|
|
734
|
+
for s in sessions:
|
|
735
|
+
sid = s.get("id", s.get("session_id", "?"))
|
|
736
|
+
turns = s.get("turns", s.get("turn_count", "?"))
|
|
737
|
+
created = s.get("created_at", s.get("created", ""))[:19]
|
|
738
|
+
print(f"{sid:<36} {str(turns):<6} {created}")
|
|
739
|
+
return 0
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _cmd_session_view(args, api_key: str, api_url: str) -> int:
|
|
743
|
+
"""GET /v1/sessions/<id> — view session details."""
|
|
744
|
+
import json as _json, sys as _sys
|
|
745
|
+
from urllib.request import Request, urlopen
|
|
746
|
+
from urllib.error import URLError, HTTPError
|
|
747
|
+
|
|
748
|
+
session_id = args.id
|
|
749
|
+
try:
|
|
750
|
+
req = Request(
|
|
751
|
+
f"{api_url}/v1/sessions/{session_id}",
|
|
752
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
753
|
+
)
|
|
754
|
+
with urlopen(req, timeout=10) as resp:
|
|
755
|
+
data = _json.loads(resp.read())
|
|
756
|
+
except HTTPError as e:
|
|
757
|
+
body = e.read().decode() if e.fp else ""
|
|
758
|
+
print(f"API error ({e.code}): {body}", file=_sys.stderr)
|
|
759
|
+
return 1
|
|
760
|
+
except URLError as e:
|
|
761
|
+
print(f"Cannot reach API at {api_url}: {e.reason}", file=_sys.stderr)
|
|
762
|
+
return 1
|
|
763
|
+
|
|
764
|
+
print(f"Session: {session_id}")
|
|
765
|
+
print(f"Created: {data.get('created_at', data.get('created', '?'))}")
|
|
766
|
+
turns = data.get("turns", [])
|
|
767
|
+
print(f"Turns: {len(turns)}")
|
|
768
|
+
print()
|
|
769
|
+
for i, t in enumerate(turns):
|
|
770
|
+
role = t.get("role", "?").upper()
|
|
771
|
+
content = t.get("content", "")
|
|
772
|
+
if len(content) > 200:
|
|
773
|
+
content = content[:200] + "..."
|
|
774
|
+
print(f"[{i + 1}] {role}: {content}")
|
|
775
|
+
return 0
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def _cmd_onboard(args) -> int:
|
|
779
|
+
"""Guided onboarding: init → index → demo → doctor.
|
|
780
|
+
|
|
781
|
+
Chains existing commands into a cohesive flow.
|
|
782
|
+
Non-interactive — skips prompts, just runs.
|
|
783
|
+
Idempotent — re-running skips already-done steps.
|
|
784
|
+
"""
|
|
785
|
+
import os
|
|
786
|
+
import subprocess as _sp
|
|
787
|
+
import sys as _sys
|
|
788
|
+
from pathlib import Path
|
|
789
|
+
|
|
790
|
+
step = 0
|
|
791
|
+
total = 5
|
|
792
|
+
|
|
793
|
+
def banner(title: str):
|
|
794
|
+
nonlocal step
|
|
795
|
+
step += 1
|
|
796
|
+
print(f"\n{'─'*50}")
|
|
797
|
+
print(f"Step {step}/{total}: {title}")
|
|
798
|
+
print(f"{'─'*50}")
|
|
799
|
+
|
|
800
|
+
# Step 1: Ensure SDK installed
|
|
801
|
+
banner("Ensure Tortoise SDK is installed")
|
|
802
|
+
try:
|
|
803
|
+
import tortoise
|
|
804
|
+
print(f" ✅ Tortoise {tortoise.__version__ if hasattr(tortoise, '__version__') else 'installed'}")
|
|
805
|
+
except ImportError:
|
|
806
|
+
print(" ❌ Tortoise not installed. Run: pip install -e .")
|
|
807
|
+
return 1
|
|
808
|
+
|
|
809
|
+
# Step 2: Init — auto-detect FalkorDB, create graph
|
|
810
|
+
banner("Initialize graph")
|
|
811
|
+
rc = _cmd_init(argparse.Namespace(path=getattr(args, 'path', None), yes=True))
|
|
812
|
+
if rc != 0:
|
|
813
|
+
print(" ❌ Init failed")
|
|
814
|
+
return rc
|
|
815
|
+
|
|
816
|
+
# Step 3: Index current repo
|
|
817
|
+
banner("Index repository")
|
|
818
|
+
result = _sp.run(
|
|
819
|
+
["git", "rev-parse", "--show-toplevel"],
|
|
820
|
+
capture_output=True, text=True, timeout=5,
|
|
821
|
+
cwd=Path.cwd(),
|
|
822
|
+
)
|
|
823
|
+
if result.returncode == 0:
|
|
824
|
+
repo_root = result.stdout.strip()
|
|
825
|
+
md_count = len(list(Path(repo_root).rglob("*.md")))
|
|
826
|
+
if md_count > 0:
|
|
827
|
+
print(f" Found {md_count} markdown files. Indexing…")
|
|
828
|
+
idx_args = argparse.Namespace(
|
|
829
|
+
url=repo_root, background=False, branch="main",
|
|
830
|
+
index_cmd="github", cmd="index",
|
|
831
|
+
)
|
|
832
|
+
_cmd_index_github(idx_args)
|
|
833
|
+
else:
|
|
834
|
+
print(" ⊙ No markdown files found — skipping index.")
|
|
835
|
+
else:
|
|
836
|
+
print(" ⊙ Not a git repo — skipping index.")
|
|
837
|
+
|
|
838
|
+
# Step 4: First demo — create first memory
|
|
839
|
+
banner("First memory demo")
|
|
840
|
+
_cmd_demo(argparse.Namespace(cmd="demo"))
|
|
841
|
+
|
|
842
|
+
# Step 5: Doctor — health check (informational, don't fail on warnings)
|
|
843
|
+
banner("Health check")
|
|
844
|
+
_cmd_doctor(argparse.Namespace(cmd="doctor"))
|
|
845
|
+
|
|
846
|
+
print(f"\n{'='*50}")
|
|
847
|
+
print("Onboarding complete.")
|
|
848
|
+
print()
|
|
849
|
+
print("Tortoise is ready. Agents can now:")
|
|
850
|
+
print(" • Query the graph via tortoise_suggest_entry_points()")
|
|
851
|
+
print(" • File decisions with tortoise_create_point()")
|
|
852
|
+
print(" • Auto-capture via tortoise-context extension")
|
|
853
|
+
print()
|
|
854
|
+
print("Next: tortoise serve — start MCP server for agents")
|
|
855
|
+
print(" tortoise setup — configure per-role memory")
|
|
856
|
+
return 0
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def _cmd_verify(args):
|
|
860
|
+
"""Write, read, delete a test Point — health check."""
|
|
861
|
+
from .projection import FalkorProjection
|
|
862
|
+
proj = FalkorProjection.from_uri(args.db)
|
|
863
|
+
try:
|
|
864
|
+
proj.apply([{"type": "PointAdded", "point": {"id": "test-verify", "content": "verify", "pointKind": "observation", "createdAt": "2026-01-01T00:00:00Z"}}])
|
|
865
|
+
print("✓ write OK")
|
|
866
|
+
result = proj.db.query("MATCH (p:Point {id: 'test-verify'}) RETURN p")
|
|
867
|
+
print("✓ read OK" if result.result_set else "✗ read FAILED")
|
|
868
|
+
proj.db.query("MATCH (p:Point {id: 'test-verify'}) DELETE p")
|
|
869
|
+
print("✓ delete OK")
|
|
870
|
+
except Exception as e:
|
|
871
|
+
print(f"✗ {e}")
|
|
872
|
+
return 1
|
|
873
|
+
finally:
|
|
874
|
+
proj.close()
|
|
875
|
+
return 0
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def _cmd_backfill(args):
|
|
879
|
+
"""Backfill missing properties on existing Points."""
|
|
880
|
+
from .projection import FalkorProjection, _now_iso
|
|
881
|
+
proj = FalkorProjection(args.db)
|
|
882
|
+
try:
|
|
883
|
+
r = proj.g.query("MATCH (p:Point) WHERE p.status IS NULL SET p.status = 'live' RETURN count(p)").result_set
|
|
884
|
+
status_count = r[0][0] if r else 0
|
|
885
|
+
r = proj.g.query(
|
|
886
|
+
"MATCH (p:Point) WHERE p.createdAt IS NULL SET p.createdAt = $now RETURN count(p)",
|
|
887
|
+
params={"now": _now_iso()},
|
|
888
|
+
).result_set
|
|
889
|
+
created_count = r[0][0] if r else 0
|
|
890
|
+
print(f"Backfilled: {status_count} status + {created_count} createdAt")
|
|
891
|
+
finally:
|
|
892
|
+
proj.close()
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def _cmd_setup(args) -> int:
|
|
896
|
+
"""Interactive memory_filter configuration per role.
|
|
897
|
+
|
|
898
|
+
tortoise setup — interactive prompts
|
|
899
|
+
tortoise setup --role developer --team app — non-interactive, prints YAML
|
|
900
|
+
tortoise setup --role developer --team app --output config.yaml — saves to file
|
|
901
|
+
"""
|
|
902
|
+
try:
|
|
903
|
+
import yaml
|
|
904
|
+
except ImportError:
|
|
905
|
+
print("Error: PyYAML is required. Run: pip install PyYAML", file=sys.stderr)
|
|
906
|
+
return 1
|
|
907
|
+
|
|
908
|
+
if args.role:
|
|
909
|
+
# Non-interactive: generate default config for a role
|
|
910
|
+
if not args.team:
|
|
911
|
+
print("Error: --team is required with --role", file=sys.stderr)
|
|
912
|
+
return 1
|
|
913
|
+
config = _default_memory_filter(args.role)
|
|
914
|
+
output = {
|
|
915
|
+
"team": args.team,
|
|
916
|
+
"role": args.role,
|
|
917
|
+
"memory_filter": config,
|
|
918
|
+
}
|
|
919
|
+
yaml_text = yaml.dump(output, default_flow_style=False, sort_keys=False, allow_unicode=True)
|
|
920
|
+
if args.output:
|
|
921
|
+
try:
|
|
922
|
+
with open(args.output, "w") as f:
|
|
923
|
+
f.write("# Tortoise memory_filter config\n")
|
|
924
|
+
f.write(f"# Role: {args.role} Team: {args.team}\n")
|
|
925
|
+
f.write(yaml_text)
|
|
926
|
+
print(f"Saved to {args.output}")
|
|
927
|
+
except OSError as e:
|
|
928
|
+
print(f"Error writing {args.output}: {e}", file=sys.stderr)
|
|
929
|
+
return 1
|
|
930
|
+
else:
|
|
931
|
+
print(yaml_text)
|
|
932
|
+
return 0
|
|
933
|
+
|
|
934
|
+
# Interactive mode
|
|
935
|
+
from pathlib import Path
|
|
936
|
+
home = Path.home()
|
|
937
|
+
|
|
938
|
+
print("Tortoise Setup — Agent Memory Configuration")
|
|
939
|
+
print("=" * 50)
|
|
940
|
+
print()
|
|
941
|
+
|
|
942
|
+
# ── Harness detection ──────────────────────────────────────
|
|
943
|
+
detections: dict[str, bool] = {}
|
|
944
|
+
if (home / ".pi" / "agent" / "extensions" / "tortoise-context").exists():
|
|
945
|
+
detections["pi"] = True
|
|
946
|
+
if (home / ".claude").exists() or Path(".claude").exists():
|
|
947
|
+
detections["claude"] = True
|
|
948
|
+
if (home / ".codex").exists() or Path(".codex").exists():
|
|
949
|
+
detections["codex"] = True
|
|
950
|
+
if Path(".cursor").exists():
|
|
951
|
+
detections["cursor"] = True
|
|
952
|
+
|
|
953
|
+
print("Which agent harness are you using?")
|
|
954
|
+
opts = []
|
|
955
|
+
if detections.get("pi"):
|
|
956
|
+
opts.append("[1] Pi (detected)")
|
|
957
|
+
else:
|
|
958
|
+
opts.append("[1] Pi")
|
|
959
|
+
if detections.get("claude"):
|
|
960
|
+
opts.append("[2] Claude Code (detected)")
|
|
961
|
+
else:
|
|
962
|
+
opts.append("[2] Claude Code")
|
|
963
|
+
if detections.get("codex"):
|
|
964
|
+
opts.append("[3] Codex (detected)")
|
|
965
|
+
else:
|
|
966
|
+
opts.append("[3] Codex")
|
|
967
|
+
if detections.get("cursor"):
|
|
968
|
+
opts.append("[4] Cursor (detected)")
|
|
969
|
+
else:
|
|
970
|
+
opts.append("[4] Cursor")
|
|
971
|
+
opts.append("[5] Multiple — I use several")
|
|
972
|
+
opts.append("[6] Skip — just configure memory, no harness setup")
|
|
973
|
+
for o in opts:
|
|
974
|
+
print(f" {o}")
|
|
975
|
+
|
|
976
|
+
choice = input("\n> ").strip()
|
|
977
|
+
harness = None
|
|
978
|
+
harness_names = {"1": "pi", "2": "claude", "3": "codex", "4": "cursor"}
|
|
979
|
+
if choice in harness_names:
|
|
980
|
+
harness = harness_names[choice]
|
|
981
|
+
elif choice == "5":
|
|
982
|
+
harness = "multiple"
|
|
983
|
+
elif choice == "6":
|
|
984
|
+
harness = None
|
|
985
|
+
else:
|
|
986
|
+
harness = "pi" # default
|
|
987
|
+
|
|
988
|
+
print()
|
|
989
|
+
|
|
990
|
+
# ── Role config ─────────────────────────────────────────────
|
|
991
|
+
print("Configure what each role remembers from the graph.")
|
|
992
|
+
print("memory_filter is a FLOOR, not a CEILING — agents can always query more.")
|
|
993
|
+
print()
|
|
994
|
+
|
|
995
|
+
role_name = input("Role name (e.g., developer, researcher): ").strip()
|
|
996
|
+
if not role_name:
|
|
997
|
+
print("No role entered. Skipping.")
|
|
998
|
+
return 0
|
|
999
|
+
|
|
1000
|
+
team_name = input("Team name (e.g., app, org-design): ").strip() or role_name
|
|
1001
|
+
|
|
1002
|
+
config = {}
|
|
1003
|
+
|
|
1004
|
+
# Episodic
|
|
1005
|
+
print()
|
|
1006
|
+
print("─ Episodic Memory (session history, events) ─")
|
|
1007
|
+
yn = input(" Include last N sessions? [Y/n]: ").strip().lower()
|
|
1008
|
+
if yn != "n":
|
|
1009
|
+
n = input(" How many sessions? [3]: ").strip()
|
|
1010
|
+
try:
|
|
1011
|
+
n_val = int(n) if n else 3
|
|
1012
|
+
except ValueError:
|
|
1013
|
+
n_val = 3
|
|
1014
|
+
epic = input(" Filter by active epic? [Y/n]: ").strip().lower()
|
|
1015
|
+
config["episodic"] = {
|
|
1016
|
+
"last_n_sessions": n_val,
|
|
1017
|
+
"filter_by_epic": epic != "n",
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
# Epistemic
|
|
1021
|
+
print()
|
|
1022
|
+
print("─ Epistemic Memory (claims, evidence, confidence) ─")
|
|
1023
|
+
yn = input(" Include epistemic memory? [Y/n]: ").strip().lower()
|
|
1024
|
+
if yn != "n":
|
|
1025
|
+
conf = input(" Minimum confidence [0.5]: ").strip()
|
|
1026
|
+
try:
|
|
1027
|
+
conf_val = float(conf) if conf else 0.5
|
|
1028
|
+
except ValueError:
|
|
1029
|
+
conf_val = 0.5
|
|
1030
|
+
age = input(" Max age in days [30]: ").strip()
|
|
1031
|
+
try:
|
|
1032
|
+
age_val = int(age) if age else 30
|
|
1033
|
+
except ValueError:
|
|
1034
|
+
age_val = 30
|
|
1035
|
+
kinds = input(" Include kinds (comma-separated) [decision,observation,hypothesis]: ").strip()
|
|
1036
|
+
kind_list = [k.strip() for k in kinds.split(",") if k.strip()] if kinds else ["decision", "observation", "hypothesis"]
|
|
1037
|
+
config["epistemic"] = {
|
|
1038
|
+
"min_confidence": conf_val,
|
|
1039
|
+
"max_age_days": age_val,
|
|
1040
|
+
"include_kinds": kind_list,
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
# Semantic
|
|
1044
|
+
print()
|
|
1045
|
+
print("─ Semantic Memory (facts, decisions, plans) ─")
|
|
1046
|
+
yn = input(" Include decisions? [Y/n]: ").strip().lower()
|
|
1047
|
+
dec = yn != "n"
|
|
1048
|
+
yn = input(" Include plans? [y/N]: ").strip().lower()
|
|
1049
|
+
plans = yn == "y"
|
|
1050
|
+
if dec or plans:
|
|
1051
|
+
config["semantic"] = {
|
|
1052
|
+
"include_decisions": dec,
|
|
1053
|
+
"include_plans": plans,
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
# Procedural
|
|
1057
|
+
print()
|
|
1058
|
+
print("─ Procedural Memory (skills, workflows) ─")
|
|
1059
|
+
yn = input(" Include workflows? [Y/n]: ").strip().lower()
|
|
1060
|
+
if yn != "n":
|
|
1061
|
+
config["procedural"] = {"include_workflows": True}
|
|
1062
|
+
|
|
1063
|
+
# Working
|
|
1064
|
+
print()
|
|
1065
|
+
print("─ Working Memory (active context) ─")
|
|
1066
|
+
yn = input(" Include active epics? [Y/n]: ").strip().lower()
|
|
1067
|
+
if yn != "n":
|
|
1068
|
+
config["working"] = {"include_active_epics": True}
|
|
1069
|
+
|
|
1070
|
+
# Output
|
|
1071
|
+
print()
|
|
1072
|
+
print("=" * 50)
|
|
1073
|
+
output = {
|
|
1074
|
+
"team": team_name,
|
|
1075
|
+
"role": role_name,
|
|
1076
|
+
"memory_filter": config,
|
|
1077
|
+
}
|
|
1078
|
+
yaml_text = yaml.dump(output, default_flow_style=False, sort_keys=False, allow_unicode=True)
|
|
1079
|
+
print(yaml_text)
|
|
1080
|
+
|
|
1081
|
+
yn = input("Save to tortoise-setup.yaml? [Y/n]: ").strip().lower()
|
|
1082
|
+
if yn != "n":
|
|
1083
|
+
try:
|
|
1084
|
+
with open("tortoise-setup.yaml", "w") as f:
|
|
1085
|
+
f.write("# Tortoise memory_filter config\n")
|
|
1086
|
+
f.write(f"# Role: {role_name} Team: {team_name}\n")
|
|
1087
|
+
f.write(yaml_text)
|
|
1088
|
+
print("Saved to tortoise-setup.yaml")
|
|
1089
|
+
except OSError as e:
|
|
1090
|
+
print(f"Error saving: {e}", file=sys.stderr)
|
|
1091
|
+
|
|
1092
|
+
print()
|
|
1093
|
+
print("Add the memory_filter block to your agent manifest (.pi/agents/<name>.md)")
|
|
1094
|
+
print("under capabilities.memory_filter.")
|
|
1095
|
+
|
|
1096
|
+
# ── Harness-specific instructions ───────────────────────────
|
|
1097
|
+
if harness:
|
|
1098
|
+
print()
|
|
1099
|
+
print("─ Harness Setup ─")
|
|
1100
|
+
_print_harness_instructions(harness)
|
|
1101
|
+
|
|
1102
|
+
return 0
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def _print_harness_instructions(harness: str) -> None:
|
|
1106
|
+
"""Print harness-specific setup instructions."""
|
|
1107
|
+
if harness == "pi" or harness == "multiple":
|
|
1108
|
+
print()
|
|
1109
|
+
print("Pi:")
|
|
1110
|
+
print(" ✅ tortoise-context extension auto-injects context when you mention issues.")
|
|
1111
|
+
print(" Run /reload in Pi to activate.")
|
|
1112
|
+
print(" Or call tortoise_help() anytime.")
|
|
1113
|
+
if harness == "claude" or harness == "multiple":
|
|
1114
|
+
print()
|
|
1115
|
+
print("Claude Code:")
|
|
1116
|
+
print(" Add tortoise MCP to your .mcp.json:")
|
|
1117
|
+
print(' {"tortoise": {"command": "python3", "args": ["-m", "tortoise.mcp_server"]}}')
|
|
1118
|
+
print(" Claude Code will auto-discover MCP tools on restart.")
|
|
1119
|
+
print(" Optional: add .claude/hooks/session-start.sh for auto-injection.")
|
|
1120
|
+
print(" cp tortoise/claude-hooks/session-start.sh .claude/hooks/session-start.sh")
|
|
1121
|
+
if harness == "codex" or harness == "multiple":
|
|
1122
|
+
print()
|
|
1123
|
+
print("Codex:")
|
|
1124
|
+
print(" Add tortoise MCP to ~/.codex/config.toml:")
|
|
1125
|
+
print(" [mcp_servers.tortoise]")
|
|
1126
|
+
print(' command = "python3"')
|
|
1127
|
+
print(' args = ["-m", "tortoise.mcp_server"]')
|
|
1128
|
+
print(" AGENTS.md is auto-loaded by Codex — Tortoise instructions are already there.")
|
|
1129
|
+
print(" autoRecall will pick up Tortoise Points automatically.")
|
|
1130
|
+
if harness == "cursor" or harness == "multiple":
|
|
1131
|
+
print()
|
|
1132
|
+
print("Cursor:")
|
|
1133
|
+
print(" Add tortoise MCP to your .mcp.json (same format as Pi/Claude Code).")
|
|
1134
|
+
print(" Create .cursor/rules/tortoise.mdc with agent instructions:")
|
|
1135
|
+
print(" When working on issues, call mcp__tortoise__tortoise_suggest_entry_points()")
|
|
1136
|
+
print(" to find related context. File decisions with tortoise_create_point().")
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _default_memory_filter(role: str) -> dict:
|
|
1140
|
+
"""Return sensible defaults per role type."""
|
|
1141
|
+
defaults = {
|
|
1142
|
+
"developer": {
|
|
1143
|
+
"episodic": {"last_n_sessions": 3, "filter_by_epic": True},
|
|
1144
|
+
"epistemic": {"min_confidence": 0.5, "max_age_days": 30, "include_kinds": ["decision", "observation"]},
|
|
1145
|
+
"semantic": {"include_decisions": True, "include_plans": False},
|
|
1146
|
+
"working": {"include_active_epics": True},
|
|
1147
|
+
},
|
|
1148
|
+
"researcher": {
|
|
1149
|
+
"epistemic": {"min_confidence": 0.3, "max_age_days": 90, "include_kinds": ["hypothesis", "observation", "statement"]},
|
|
1150
|
+
"semantic": {"include_decisions": False, "include_plans": False},
|
|
1151
|
+
},
|
|
1152
|
+
"strategist": {
|
|
1153
|
+
"epistemic": {"min_confidence": 0.5, "max_age_days": 60, "include_kinds": ["decision", "hypothesis", "strategy", "vision"]},
|
|
1154
|
+
"semantic": {"include_decisions": True, "include_plans": True},
|
|
1155
|
+
"working": {"include_active_epics": True},
|
|
1156
|
+
},
|
|
1157
|
+
}
|
|
1158
|
+
return defaults.get(role, defaults["developer"])
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
def _cmd_index_github(args):
|
|
1162
|
+
"""Clone a GitHub repo, walk .md files, extract into FalkorDB.
|
|
1163
|
+
|
|
1164
|
+
tortoise index github <url> [--background]
|
|
1165
|
+
|
|
1166
|
+
Idempotent: re-running the same repo skips already-indexed files
|
|
1167
|
+
(keyed by content hash via idempotency.document_key).
|
|
1168
|
+
"""
|
|
1169
|
+
import atexit
|
|
1170
|
+
import os
|
|
1171
|
+
import subprocess
|
|
1172
|
+
import sys
|
|
1173
|
+
import tempfile
|
|
1174
|
+
from pathlib import Path
|
|
1175
|
+
|
|
1176
|
+
from tortoise.api import EventAPI
|
|
1177
|
+
from tortoise.extraction_pipeline import ExtractionPipeline
|
|
1178
|
+
from tortoise.log import EventLog
|
|
1179
|
+
from tortoise.projection import FalkorProjection
|
|
1180
|
+
|
|
1181
|
+
url = args.url
|
|
1182
|
+
branch = args.branch or "main"
|
|
1183
|
+
|
|
1184
|
+
# Background mode: detach and return immediately
|
|
1185
|
+
if args.background:
|
|
1186
|
+
cmd = [sys.executable, "-m", "tortoise", "index", "github", url]
|
|
1187
|
+
if branch != "main":
|
|
1188
|
+
cmd.extend(["--branch", branch])
|
|
1189
|
+
pid_file = Path(tempfile.gettempdir()) / f"tortoise-index-{Path(url).stem}.pid"
|
|
1190
|
+
log_file = pid_file.with_suffix('.log')
|
|
1191
|
+
with open(log_file, 'w') as lf:
|
|
1192
|
+
proc = subprocess.Popen(
|
|
1193
|
+
cmd, stdout=lf, stderr=subprocess.STDOUT,
|
|
1194
|
+
start_new_session=True,
|
|
1195
|
+
)
|
|
1196
|
+
pid_file.write_text(str(proc.pid))
|
|
1197
|
+
print(f"Indexing {url} in background (pid {proc.pid})")
|
|
1198
|
+
print(f" Progress: tail -f {pid_file.with_suffix('.log')}")
|
|
1199
|
+
return 0
|
|
1200
|
+
|
|
1201
|
+
# Determine if local path or remote URL
|
|
1202
|
+
url_path = Path(url).expanduser().resolve()
|
|
1203
|
+
is_local = url_path.is_dir()
|
|
1204
|
+
|
|
1205
|
+
if is_local:
|
|
1206
|
+
repo_path = url_path
|
|
1207
|
+
repo_name = repo_path.name
|
|
1208
|
+
tmpdir = None # no cleanup needed
|
|
1209
|
+
print(f"Indexing local repo: {repo_path}")
|
|
1210
|
+
else:
|
|
1211
|
+
# Clone repo
|
|
1212
|
+
tmpdir = tempfile.mkdtemp(prefix="tortoise-index-")
|
|
1213
|
+
atexit.register(lambda: __import__("shutil").rmtree(tmpdir, ignore_errors=True))
|
|
1214
|
+
|
|
1215
|
+
repo_name = url.rstrip("/").split("/")[-1].replace(".git", "")
|
|
1216
|
+
repo_path = Path(tmpdir) / repo_name
|
|
1217
|
+
|
|
1218
|
+
print(f"Cloning {url} (branch: {branch})…")
|
|
1219
|
+
result = subprocess.run(
|
|
1220
|
+
["git", "clone", "--depth", "1", "--branch", branch, url, str(repo_path)],
|
|
1221
|
+
capture_output=True, text=True, timeout=120,
|
|
1222
|
+
)
|
|
1223
|
+
if result.returncode != 0:
|
|
1224
|
+
print(f"Clone failed: {result.stderr}", file=sys.stderr)
|
|
1225
|
+
return 1
|
|
1226
|
+
|
|
1227
|
+
# Walk .md files
|
|
1228
|
+
md_files = sorted(repo_path.rglob("*.md"))
|
|
1229
|
+
# ponytail: skip node_modules, .git, venv
|
|
1230
|
+
md_files = [f for f in md_files if ".git/" not in str(f)
|
|
1231
|
+
and "node_modules/" not in str(f)
|
|
1232
|
+
and "venv/" not in str(f)
|
|
1233
|
+
and "__pycache__" not in str(f)]
|
|
1234
|
+
total = len(md_files)
|
|
1235
|
+
if total == 0:
|
|
1236
|
+
print("No markdown files found.")
|
|
1237
|
+
return 0
|
|
1238
|
+
|
|
1239
|
+
print(f"Found {total} markdown files. Indexing…")
|
|
1240
|
+
|
|
1241
|
+
# Set up projection + API (same detection as _cmd_init)
|
|
1242
|
+
proj = None
|
|
1243
|
+
# Try Docker FalkorDB first
|
|
1244
|
+
try:
|
|
1245
|
+
host = os.environ.get("FALKORDB_HOST", "localhost")
|
|
1246
|
+
port = int(os.environ.get("FALKORDB_PORT", "16379"))
|
|
1247
|
+
password = os.environ.get("FALKORDB_PASSWORD", "")
|
|
1248
|
+
from falkordb import FalkorDB as FDB
|
|
1249
|
+
db = FDB(host=host, port=port, password=password or None)
|
|
1250
|
+
db.select_graph("tortoise").query("RETURN 1")
|
|
1251
|
+
proj = FalkorProjection(host=host, port=port, password=password or None)
|
|
1252
|
+
except Exception:
|
|
1253
|
+
# Fallback: embedded mode (SQLite-backed) or docker:// URI
|
|
1254
|
+
try:
|
|
1255
|
+
if args.db.startswith("docker://"):
|
|
1256
|
+
proj = FalkorProjection.from_uri(args.db)
|
|
1257
|
+
else:
|
|
1258
|
+
proj = FalkorProjection(path=args.db)
|
|
1259
|
+
except Exception as e:
|
|
1260
|
+
print(f"tortoise index: Cannot connect to database: {e}", file=sys.stderr)
|
|
1261
|
+
print("Set --db to a Docker URI or ensure FalkorDB is running.", file=sys.stderr)
|
|
1262
|
+
return 1
|
|
1263
|
+
|
|
1264
|
+
log_path = Path(tempfile.gettempdir()) / f"tortoise-index-{repo_name}.jsonl"
|
|
1265
|
+
log = EventLog(str(log_path))
|
|
1266
|
+
api = EventAPI(log, initiated_by="extractor", agent_id="github-indexer", projection=proj)
|
|
1267
|
+
|
|
1268
|
+
# Idempotency: track content hashes to avoid re-indexing
|
|
1269
|
+
# ponytail: simple JSON file — no DB, no config. Add FalkorDB-backed
|
|
1270
|
+
# dedup if per-file tracking across repos becomes necessary.
|
|
1271
|
+
from tortoise.idempotency import document_key as doc_key_fn
|
|
1272
|
+
import json as _json
|
|
1273
|
+
hash_file = Path.home() / ".tortoise" / "indexed_hashes.json"
|
|
1274
|
+
hash_file.parent.mkdir(parents=True, exist_ok=True)
|
|
1275
|
+
indexed_hashes: set[str] = set()
|
|
1276
|
+
if hash_file.exists():
|
|
1277
|
+
try:
|
|
1278
|
+
indexed_hashes = set(_json.loads(hash_file.read_text()))
|
|
1279
|
+
except Exception:
|
|
1280
|
+
pass
|
|
1281
|
+
|
|
1282
|
+
pipeline = ExtractionPipeline(enrich=False)
|
|
1283
|
+
indexed, skipped, errors = 0, 0, 0
|
|
1284
|
+
|
|
1285
|
+
for i, fp in enumerate(md_files, 1):
|
|
1286
|
+
rel = fp.relative_to(repo_path)
|
|
1287
|
+
raw_text = fp.read_text(encoding="utf-8")
|
|
1288
|
+
# ponytail: strip frontmatter before hashing — pipeline may add
|
|
1289
|
+
# frontmatter, which would change the hash on the next run.
|
|
1290
|
+
text_for_hash = raw_text
|
|
1291
|
+
if raw_text.startswith('---'):
|
|
1292
|
+
end = raw_text.find('---', 3)
|
|
1293
|
+
if end > 0:
|
|
1294
|
+
text_for_hash = raw_text[end + 3:].lstrip('\n')
|
|
1295
|
+
content_hash = doc_key_fn(text_for_hash).value
|
|
1296
|
+
if content_hash in indexed_hashes:
|
|
1297
|
+
print(f" [{i}/{total}] {rel}… ⊙ (already indexed)")
|
|
1298
|
+
skipped += 1
|
|
1299
|
+
continue
|
|
1300
|
+
print(f" [{i}/{total}] {rel}…", end=" ", flush=True)
|
|
1301
|
+
try:
|
|
1302
|
+
stats = pipeline.process_file(fp, api)
|
|
1303
|
+
if stats.get("points", 0) > 0:
|
|
1304
|
+
indexed += 1
|
|
1305
|
+
indexed_hashes.add(content_hash)
|
|
1306
|
+
print(f"✓ ({stats['points']} pts, {stats['operators']} ops, kind={stats['documentKind']})")
|
|
1307
|
+
else:
|
|
1308
|
+
skipped += 1
|
|
1309
|
+
print("⊙ (skipped — no claims found)")
|
|
1310
|
+
except Exception as e:
|
|
1311
|
+
errors += 1
|
|
1312
|
+
print(f"✗ ({e})")
|
|
1313
|
+
|
|
1314
|
+
if proj:
|
|
1315
|
+
proj.close()
|
|
1316
|
+
|
|
1317
|
+
# Persist indexed hashes for cross-run idempotency
|
|
1318
|
+
try:
|
|
1319
|
+
hash_file.write_text(_json.dumps(sorted(indexed_hashes)))
|
|
1320
|
+
except Exception:
|
|
1321
|
+
pass
|
|
1322
|
+
|
|
1323
|
+
print()
|
|
1324
|
+
print(f"Done: {indexed} indexed, {skipped} skipped, {errors} errors")
|
|
1325
|
+
if indexed > 0:
|
|
1326
|
+
print(f" Log: {log_path}")
|
|
1327
|
+
print(f" Graph: query with tortoise_suggest_entry_points()")
|
|
1328
|
+
|
|
1329
|
+
# Cleanup (only if we cloned)
|
|
1330
|
+
if tmpdir:
|
|
1331
|
+
__import__("shutil").rmtree(tmpdir, ignore_errors=True)
|
|
1332
|
+
return 0 if errors == 0 else 1
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
def _cmd_doctor(args):
|
|
1336
|
+
"""Health check — verify Tortoise setup is healthy."""
|
|
1337
|
+
import importlib
|
|
1338
|
+
import os
|
|
1339
|
+
from pathlib import Path
|
|
1340
|
+
|
|
1341
|
+
print("Tortoise Doctor — Health Check")
|
|
1342
|
+
print("=" * 50)
|
|
1343
|
+
results: list[tuple[str, str, str]] = [] # (check, status, detail)
|
|
1344
|
+
|
|
1345
|
+
# 1. Python deps
|
|
1346
|
+
for dep, pkg in [("falkordb", "falkordb"), ("redislite.falkordb_client", "falkordblite"), ("yaml", "PyYAML")]:
|
|
1347
|
+
try:
|
|
1348
|
+
importlib.import_module(dep)
|
|
1349
|
+
results.append((f"Python: {pkg}", "✅", "installed"))
|
|
1350
|
+
except ImportError:
|
|
1351
|
+
results.append((f"Python: {pkg}", "⚠️", f"not installed — pip install {pkg}"))
|
|
1352
|
+
|
|
1353
|
+
# 2. Docker / FalkorDB
|
|
1354
|
+
docker_host = os.environ.get("FALKORDB_HOST", "localhost")
|
|
1355
|
+
try:
|
|
1356
|
+
docker_port = int(os.environ.get("FALKORDB_PORT", "16379"))
|
|
1357
|
+
except (ValueError, TypeError):
|
|
1358
|
+
results.append(("Graph: FalkorDB", "❌", f"Invalid FALKORDB_PORT: {os.environ.get('FALKORDB_PORT')!r}"))
|
|
1359
|
+
docker_port = 6379
|
|
1360
|
+
try:
|
|
1361
|
+
from falkordb import FalkorDB
|
|
1362
|
+
docker_pass = os.environ.get("FALKORDB_PASSWORD", "")
|
|
1363
|
+
db = FalkorDB(host=docker_host, port=docker_port,
|
|
1364
|
+
password=docker_pass or None)
|
|
1365
|
+
db.select_graph("tortoise").query("RETURN 1")
|
|
1366
|
+
results.append(("Graph: FalkorDB", "✅", f"connected at {docker_host}:{docker_port}"))
|
|
1367
|
+
except ImportError:
|
|
1368
|
+
results.append(("Graph: FalkorDB", "⚠️", "falkordb package not installed"))
|
|
1369
|
+
except Exception as e:
|
|
1370
|
+
results.append(("Graph: FalkorDB", "❌", str(e)[:60]))
|
|
1371
|
+
|
|
1372
|
+
# 3. Graph health
|
|
1373
|
+
try:
|
|
1374
|
+
from tortoise.sdk import TortoiseSDK
|
|
1375
|
+
sdk = TortoiseSDK(db_path=args.path)
|
|
1376
|
+
status = sdk.status()
|
|
1377
|
+
points = status.get("counts", {}).get("Point", 0)
|
|
1378
|
+
total = status.get("total_entities", 0)
|
|
1379
|
+
if points > 0:
|
|
1380
|
+
results.append(("Graph: health", "✅", f"{points} Points, {total} entities"))
|
|
1381
|
+
else:
|
|
1382
|
+
results.append(("Graph: health", "⚠️", "0 Points — graph is empty (expected for new setups)"))
|
|
1383
|
+
except Exception as e:
|
|
1384
|
+
results.append(("Graph: health", "❌", str(e)[:60]))
|
|
1385
|
+
|
|
1386
|
+
# 4. MCP server
|
|
1387
|
+
mcp_running = False
|
|
1388
|
+
try:
|
|
1389
|
+
import subprocess
|
|
1390
|
+
out = subprocess.run(
|
|
1391
|
+
["pgrep", "-f", "tortoise.mcp_server"],
|
|
1392
|
+
capture_output=True, timeout=2
|
|
1393
|
+
)
|
|
1394
|
+
mcp_running = out.returncode == 0
|
|
1395
|
+
except Exception:
|
|
1396
|
+
pass
|
|
1397
|
+
if mcp_running:
|
|
1398
|
+
results.append(("MCP server", "✅", "running"))
|
|
1399
|
+
else:
|
|
1400
|
+
results.append(("MCP server", "⚠️", "not running — tortoise serve"))
|
|
1401
|
+
|
|
1402
|
+
# 5. Harness detection
|
|
1403
|
+
home = Path.home()
|
|
1404
|
+
detections: list[str] = []
|
|
1405
|
+
if (home / ".pi" / "agent" / "extensions" / "tortoise-context").exists():
|
|
1406
|
+
detections.append("Pi (extension found)")
|
|
1407
|
+
if (home / ".claude").exists() or Path(".claude").exists():
|
|
1408
|
+
detections.append("Claude Code")
|
|
1409
|
+
if (home / ".codex").exists() or Path(".codex").exists():
|
|
1410
|
+
detections.append("Codex")
|
|
1411
|
+
if Path(".cursor").exists():
|
|
1412
|
+
detections.append("Cursor")
|
|
1413
|
+
if detections:
|
|
1414
|
+
results.append(("Harnesses", "✅", ", ".join(detections)))
|
|
1415
|
+
else:
|
|
1416
|
+
results.append(("Harnesses", "⚠️", "none detected — run tortoise setup to configure"))
|
|
1417
|
+
|
|
1418
|
+
# Print results
|
|
1419
|
+
for check, icon, detail in results:
|
|
1420
|
+
print(f" {icon} {check}: {detail}")
|
|
1421
|
+
|
|
1422
|
+
# Summary
|
|
1423
|
+
fails = sum(1 for _, icon, _ in results if icon == "❌")
|
|
1424
|
+
warns = sum(1 for _, icon, _ in results if icon == "⚠️")
|
|
1425
|
+
passes = sum(1 for _, icon, _ in results if icon == "✅")
|
|
1426
|
+
print()
|
|
1427
|
+
print(f"{passes} pass, {warns} warn, {fails} fail")
|
|
1428
|
+
if fails == 0 and warns == 0:
|
|
1429
|
+
print("✅ All checks passing!")
|
|
1430
|
+
elif fails == 0:
|
|
1431
|
+
print("⚠️ Some warnings — review above.")
|
|
1432
|
+
else:
|
|
1433
|
+
print("❌ Some checks failed — review above.")
|
|
1434
|
+
return 0 if fails == 0 else 1
|
|
1435
|
+
|
|
1436
|
+
|
|
1437
|
+
def _cmd_list_kinds(args) -> int:
|
|
1438
|
+
"""List all pointKinds present in the graph with counts."""
|
|
1439
|
+
import os as _os
|
|
1440
|
+
from tortoise.sdk import TortoiseSDK
|
|
1441
|
+
from tortoise.projection import FalkorProjection
|
|
1442
|
+
|
|
1443
|
+
uri = _os.environ.get("TORTOISE_DB_URI", "docker://:@localhost:16379/tortoise")
|
|
1444
|
+
sdk = TortoiseSDK()
|
|
1445
|
+
sdk._proj = FalkorProjection.from_uri(uri)
|
|
1446
|
+
|
|
1447
|
+
try:
|
|
1448
|
+
kinds = sdk.list_pointkinds()
|
|
1449
|
+
if not kinds:
|
|
1450
|
+
print("No pointKinds found.")
|
|
1451
|
+
return 0
|
|
1452
|
+
max_width = max(len(str(k["kind"])) for k in kinds)
|
|
1453
|
+
for k in kinds:
|
|
1454
|
+
pack_str = f" ({k['pack']})" if k["pack"] else ""
|
|
1455
|
+
print(f"{k['count']:>6} {k['kind']:<{max_width}}{pack_str}")
|
|
1456
|
+
print(f"\n{len(kinds)} kind(s) total")
|
|
1457
|
+
finally:
|
|
1458
|
+
if sdk._proj:
|
|
1459
|
+
sdk._proj.close()
|
|
1460
|
+
return 0
|
|
1461
|
+
|
|
1462
|
+
|
|
1463
|
+
def _cmd_list_sources(args) -> int:
|
|
1464
|
+
"""List all Sources with point counts."""
|
|
1465
|
+
import os as _os
|
|
1466
|
+
from tortoise.sdk import TortoiseSDK
|
|
1467
|
+
from tortoise.projection import FalkorProjection
|
|
1468
|
+
|
|
1469
|
+
uri = _os.environ.get("TORTOISE_DB_URI", "docker://:@localhost:16379/tortoise")
|
|
1470
|
+
sdk = TortoiseSDK()
|
|
1471
|
+
sdk._proj = FalkorProjection.from_uri(uri)
|
|
1472
|
+
|
|
1473
|
+
try:
|
|
1474
|
+
sources = sdk.list_sources()
|
|
1475
|
+
if not sources:
|
|
1476
|
+
print("No sources found.")
|
|
1477
|
+
return 0
|
|
1478
|
+
max_url_width = max(len(str(s["url"] or "")) for s in sources)
|
|
1479
|
+
max_sk_width = max(len(str(s["sourceKind"] or "")) for s in sources)
|
|
1480
|
+
for s in sources:
|
|
1481
|
+
url = str(s["url"] or "")
|
|
1482
|
+
sk = str(s["sourceKind"] or "")
|
|
1483
|
+
print(f"{s['points']:>6} {url:<{max_url_width}} {sk:<{max_sk_width}}")
|
|
1484
|
+
print(f"\n{len(sources)} source(s) total")
|
|
1485
|
+
finally:
|
|
1486
|
+
if sdk._proj:
|
|
1487
|
+
sdk._proj.close()
|
|
1488
|
+
return 0
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def _cmd_decide(args) -> int:
|
|
1492
|
+
"""Compare options via EP belief propagation.
|
|
1493
|
+
|
|
1494
|
+
Reads a JSON or YAML input file with:
|
|
1495
|
+
{context, options, criteria, findings, edges, truth_edges?, relevance_edges?}
|
|
1496
|
+
|
|
1497
|
+
Wires criteria+findings→options via IMPL/NAND, handles truth challenges
|
|
1498
|
+
(NAND on finding points) and relevance mitigations (mitigate on operators),
|
|
1499
|
+
then runs EP belief propagation and prints a ranked confidence table.
|
|
1500
|
+
|
|
1501
|
+
MITIGATION SEMANTICS (TRUTH vs RELEVANCE):
|
|
1502
|
+
- truth_edges: NAND directly on the target finding point (it's FALSE)
|
|
1503
|
+
- relevance_edges: mitigate the OPERATOR (it's TRUE but matters LESS)
|
|
1504
|
+
Uses mitigate_operator with strength in [0.10, 0.50] range.
|
|
1505
|
+
- Never NAND an option/criterion point for bad fit — express fit on the operator.
|
|
1506
|
+
"""
|
|
1507
|
+
import json as _json
|
|
1508
|
+
import sys as _sys
|
|
1509
|
+
from pathlib import Path
|
|
1510
|
+
from tortoise.sdk import TortoiseSDK
|
|
1511
|
+
from tortoise.projection import FalkorProjection
|
|
1512
|
+
|
|
1513
|
+
# Two modes: --input <file> or inline (--options/--criteria/--findings/--edges)
|
|
1514
|
+
if args.input:
|
|
1515
|
+
input_path = Path(args.input)
|
|
1516
|
+
if not input_path.exists():
|
|
1517
|
+
print(f"Input file not found: {args.input}", file=_sys.stderr)
|
|
1518
|
+
return 1
|
|
1519
|
+
raw = input_path.read_text(encoding="utf-8")
|
|
1520
|
+
# Parse JSON or YAML
|
|
1521
|
+
if input_path.suffix in (".yaml", ".yml"):
|
|
1522
|
+
try:
|
|
1523
|
+
import yaml
|
|
1524
|
+
except ImportError:
|
|
1525
|
+
print("Error: PyYAML is required for YAML input. Run: pip install PyYAML", file=_sys.stderr)
|
|
1526
|
+
return 1
|
|
1527
|
+
data = yaml.safe_load(raw)
|
|
1528
|
+
else:
|
|
1529
|
+
data = _json.loads(raw)
|
|
1530
|
+
else:
|
|
1531
|
+
# Inline mode
|
|
1532
|
+
data: dict = {}
|
|
1533
|
+
if args.options:
|
|
1534
|
+
data["options"] = _json.loads(args.options)
|
|
1535
|
+
if args.criteria:
|
|
1536
|
+
data["criteria"] = _json.loads(args.criteria)
|
|
1537
|
+
if args.findings:
|
|
1538
|
+
data["findings"] = _json.loads(args.findings)
|
|
1539
|
+
if args.edges:
|
|
1540
|
+
data["edges"] = _json.loads(args.edges)
|
|
1541
|
+
|
|
1542
|
+
options = data.get("options", {})
|
|
1543
|
+
criteria = data.get("criteria", {})
|
|
1544
|
+
findings = data.get("findings", {})
|
|
1545
|
+
edges = data.get("edges", [])
|
|
1546
|
+
truth_edges = data.get("truth_edges", [])
|
|
1547
|
+
relevance_edges = data.get("relevance_edges", [])
|
|
1548
|
+
|
|
1549
|
+
if not options:
|
|
1550
|
+
print("Error: at least one option required (--input file with 'options' or --options JSON)", file=_sys.stderr)
|
|
1551
|
+
return 1
|
|
1552
|
+
|
|
1553
|
+
import os as _os
|
|
1554
|
+
uri = getattr(args, "db", None) or _os.environ.get("TORTOISE_DB_URI", "docker://:@localhost:16379/tortoise")
|
|
1555
|
+
sdk = TortoiseSDK()
|
|
1556
|
+
sdk._proj = FalkorProjection.from_uri(uri)
|
|
1557
|
+
|
|
1558
|
+
# Track all operator IDs for explicit-factor mode
|
|
1559
|
+
all_operator_ids: list[str] = []
|
|
1560
|
+
|
|
1561
|
+
try:
|
|
1562
|
+
# ── Create all points ──
|
|
1563
|
+
all_points: dict[str, str] = {}
|
|
1564
|
+
for pid, content in {**options, **criteria, **findings}.items():
|
|
1565
|
+
kind = (
|
|
1566
|
+
"option" if pid.startswith(("opt:", "option:")) else
|
|
1567
|
+
"criterion" if pid.startswith(("crit:", "criterion:")) else
|
|
1568
|
+
"evidence"
|
|
1569
|
+
)
|
|
1570
|
+
try:
|
|
1571
|
+
p = sdk.create_point(kind, content, dedup=True)
|
|
1572
|
+
all_points[pid] = p["id"]
|
|
1573
|
+
print(f" ✓ {pid} → {p['id']}")
|
|
1574
|
+
except Exception as e:
|
|
1575
|
+
print(f" ⚠ {pid}: {e}")
|
|
1576
|
+
|
|
1577
|
+
# ── Resolve helper: name → point_id ──
|
|
1578
|
+
def _resolve(name: str) -> str:
|
|
1579
|
+
"""Resolve a key or point ID to a graph point ID."""
|
|
1580
|
+
if name in all_points:
|
|
1581
|
+
return all_points[name]
|
|
1582
|
+
# Try as a raw graph ID (pass-through)
|
|
1583
|
+
return name
|
|
1584
|
+
|
|
1585
|
+
# ── Create regular edges (IMPL/NAND) ──
|
|
1586
|
+
# Track created operators so relevance_edges can reuse them instead of
|
|
1587
|
+
# creating duplicates (same src/op_type/tgt in both sections).
|
|
1588
|
+
created_ops: dict[tuple[str, str, str], str] = {}
|
|
1589
|
+
for edge in edges:
|
|
1590
|
+
if isinstance(edge, list):
|
|
1591
|
+
# Tuple format: [source, op_type, target]
|
|
1592
|
+
src, op_type, tgt = edge[0], edge[1], edge[2]
|
|
1593
|
+
label = edge[3] if len(edge) > 3 else None
|
|
1594
|
+
elif isinstance(edge, dict):
|
|
1595
|
+
src = edge["source"]
|
|
1596
|
+
op_type = edge["op_type"]
|
|
1597
|
+
tgt = edge["target"]
|
|
1598
|
+
label = edge.get("label")
|
|
1599
|
+
else:
|
|
1600
|
+
print(f" ⚠ Unknown edge format: {edge}")
|
|
1601
|
+
continue
|
|
1602
|
+
|
|
1603
|
+
try:
|
|
1604
|
+
op = sdk.create_operator(op_type, _resolve(src), [_resolve(tgt)], label=label)
|
|
1605
|
+
created_ops[(src, op_type, tgt)] = op["id"]
|
|
1606
|
+
all_operator_ids.append(op["id"])
|
|
1607
|
+
print(f" ✓ {src} --{op_type}--> {tgt}")
|
|
1608
|
+
except Exception as e:
|
|
1609
|
+
print(f" ⚠ {src} --{op_type}--> {tgt}: {e}")
|
|
1610
|
+
|
|
1611
|
+
# ── Truth edges: NAND the target finding point (it's FALSE) ──
|
|
1612
|
+
for te in truth_edges:
|
|
1613
|
+
src = te["source"]
|
|
1614
|
+
op_type = te.get("op_type", "NAND")
|
|
1615
|
+
tgt = te["target"]
|
|
1616
|
+
try:
|
|
1617
|
+
top = sdk.create_operator(op_type, _resolve(src), [_resolve(tgt)])
|
|
1618
|
+
all_operator_ids.append(top["id"])
|
|
1619
|
+
print(f" ⚡ truth: {src} --{op_type}--> {tgt}")
|
|
1620
|
+
except Exception as e:
|
|
1621
|
+
print(f" ⚠ truth {src} --{op_type}--> {tgt}: {e}")
|
|
1622
|
+
|
|
1623
|
+
# ── Relevance edges: mitigate the OPERATOR (TRUE but matters LESS) ──
|
|
1624
|
+
for re in relevance_edges:
|
|
1625
|
+
src = re["source"]
|
|
1626
|
+
op_type = re.get("op_type", "NAND")
|
|
1627
|
+
tgt = re["target"]
|
|
1628
|
+
reason = re.get("reason", "Overstated relevance")
|
|
1629
|
+
strength = re.get("strength", 0.30)
|
|
1630
|
+
# Clamp to valid mitigation range
|
|
1631
|
+
strength = max(0.10, min(0.50, strength))
|
|
1632
|
+
try:
|
|
1633
|
+
# Reuse the operator if already created in `edges` (prevents
|
|
1634
|
+
# duplicate operators feeding EP twice).
|
|
1635
|
+
op_id = created_ops.get((src, op_type, tgt))
|
|
1636
|
+
if op_id is None:
|
|
1637
|
+
op = sdk.create_operator(op_type, _resolve(src), [_resolve(tgt)])
|
|
1638
|
+
op_id = op["id"]
|
|
1639
|
+
all_operator_ids.append(op_id)
|
|
1640
|
+
sdk.mitigate_operator(op_id, reason, strength)
|
|
1641
|
+
print(f" ⚖ relevance: {src} --{op_type}--> {tgt} (mitigated {strength:.2f}: {reason})")
|
|
1642
|
+
except Exception as e:
|
|
1643
|
+
print(f" ⚠ relevance {src} --{op_type}--> {tgt}: {e}")
|
|
1644
|
+
|
|
1645
|
+
# ── Compute confidence per option ──
|
|
1646
|
+
try:
|
|
1647
|
+
if all_operator_ids:
|
|
1648
|
+
print(f" (operator-factor mode: {len(all_operator_ids)} operator factors)")
|
|
1649
|
+
result = sdk.compute_confidence(factors=all_operator_ids)
|
|
1650
|
+
else:
|
|
1651
|
+
result = sdk.compute_confidence()
|
|
1652
|
+
print(f"\n✓ EP computed: {result['iterations']} iterations, converged={result['converged']}")
|
|
1653
|
+
confs = result.get("confidences", {})
|
|
1654
|
+
|
|
1655
|
+
opt_conf: dict[str, float] = {}
|
|
1656
|
+
for pid, cid in all_points.items():
|
|
1657
|
+
if pid.startswith(("opt:", "option:")):
|
|
1658
|
+
mean = confs.get(cid, {}).get("mean")
|
|
1659
|
+
if isinstance(mean, (int, float)):
|
|
1660
|
+
opt_conf[pid] = float(mean)
|
|
1661
|
+
|
|
1662
|
+
if opt_conf:
|
|
1663
|
+
print("\n=== OPTION CONFIDENCE (higher = more supported) ===")
|
|
1664
|
+
ranked = sorted(opt_conf.items(), key=lambda kv: kv[1], reverse=True)
|
|
1665
|
+
name_width = max(len(pid) for pid in opt_conf)
|
|
1666
|
+
for pid, c in ranked:
|
|
1667
|
+
bar = "█" * int(c * 20) + "░" * (20 - int(c * 20))
|
|
1668
|
+
print(f" {pid:<{name_width}} {c:.4f} {bar}")
|
|
1669
|
+
except Exception as e:
|
|
1670
|
+
print(f"\n⚠ compute_confidence: {e}")
|
|
1671
|
+
|
|
1672
|
+
finally:
|
|
1673
|
+
if sdk._proj:
|
|
1674
|
+
sdk._proj.close()
|
|
1675
|
+
|
|
1676
|
+
print(f"\nDone. Decision comparison filed.")
|
|
1677
|
+
return 0
|
|
1678
|
+
|
|
1679
|
+
|
|
1680
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1681
|
+
|
|
1682
|
+
p = argparse.ArgumentParser(prog="tortoise", exit_on_error=False)
|
|
1683
|
+
sp = p.add_subparsers(dest="cmd")
|
|
1684
|
+
rb = sp.add_parser("rebuild", help="Rebuild FalkorDB from all .jsonl files")
|
|
1685
|
+
rb.add_argument("--db", required=True)
|
|
1686
|
+
rb.add_argument("--dir", default=".")
|
|
1687
|
+
sp.add_parser("demo", help="Run mock extractor on sample transcript")
|
|
1688
|
+
sp.add_parser("backfill", help="Backfill missing Point properties (status, createdAt)").add_argument("--db", required=True, help="Docker URI or file path")
|
|
1689
|
+
vf = sp.add_parser("verify", help="Write/read/delete test Point — health check")
|
|
1690
|
+
vf.add_argument("--db", required=True, help="FalkorDB docker:// URI")
|
|
1691
|
+
cc = sp.add_parser("check-consistency", help="Verify event log matches graph state")
|
|
1692
|
+
cc.add_argument("--db", required=True, help="Docker URI or file path")
|
|
1693
|
+
cc.add_argument("--log", required=True, help="Path to events.jsonl")
|
|
1694
|
+
rc = sp.add_parser("reconcile", help="Replay unprojected EventRecorded entries from JSONL into FalkorDB")
|
|
1695
|
+
rc.add_argument("--db", required=True, help="FalkorDB docker:// URI")
|
|
1696
|
+
rc.add_argument("--log", required=True, help="Path to events.jsonl")
|
|
1697
|
+
bk = sp.add_parser("backup", help="Backup events.jsonl + FalkorDB to timestamped dir")
|
|
1698
|
+
bk.add_argument("--db", required=True, help="Path to database file")
|
|
1699
|
+
bk.add_argument("--events", default="events.jsonl", help="Path to event log")
|
|
1700
|
+
md = sp.add_parser("migrate-db", help="Migrate legacy embedded.db to canonical tortoise.db (data-safe)")
|
|
1701
|
+
md.add_argument("--force", action="store_true",
|
|
1702
|
+
help="Bypass marker / overwrite conflicting tortoise.db")
|
|
1703
|
+
rs = sp.add_parser("restore", help="Restore from backup directory")
|
|
1704
|
+
rs.add_argument("backup_dir", help="Path to backup directory")
|
|
1705
|
+
rs.add_argument("--db", required=True, help="Target database path")
|
|
1706
|
+
rs.add_argument("--events", default="events.jsonl", help="Target event log path")
|
|
1707
|
+
mc = sp.add_parser("mine-conversation", help="Mine conversation transcript → Events + Points (GAP-15)")
|
|
1708
|
+
mc.add_argument("transcript", help="Path to transcript file (Speaker: text format)")
|
|
1709
|
+
mc.add_argument("--source-id", default=None, help="Source identifier (default: basename of transcript)")
|
|
1710
|
+
mc.add_argument("--db", default=None, help="FalkorDB docker:// URI for projection")
|
|
1711
|
+
sr = sp.add_parser("serve", help="Start Tortoise MCP server (stdio)")
|
|
1712
|
+
init = sp.add_parser("init", help="Auto-detect FalkorDB and create default graph")
|
|
1713
|
+
init.add_argument("--path", default=None, help="Path for embedded mode (opt-in)")
|
|
1714
|
+
init.add_argument("--yes", "-y", action="store_true", help="Skip prompts, auto-index repo")
|
|
1715
|
+
init.add_argument("--api-key", dest="api_key", default=None, help="Connect to Tortoise Cloud instead of local Docker")
|
|
1716
|
+
setup = sp.add_parser("setup", help="Configure memory_filter per role (interactive)")
|
|
1717
|
+
setup.add_argument("--role", default=None, help="Role name (non-interactive, outputs YAML)")
|
|
1718
|
+
setup.add_argument("--team", default=None, help="Team name (used with --role)")
|
|
1719
|
+
setup.add_argument("--output", default=None, help="Save config to file instead of stdout")
|
|
1720
|
+
doctor = sp.add_parser("doctor", help="Health check — verify Tortoise setup")
|
|
1721
|
+
onboard = sp.add_parser("onboard", help="Guided onboarding: init → index → demo → doctor")
|
|
1722
|
+
onboard.add_argument("--path", default=None, help="Path for embedded mode")
|
|
1723
|
+
hs = sp.add_parser("health-server", help="Start standalone /health HTTP server")
|
|
1724
|
+
hs.add_argument("--port", type=int, default=9090, help="HTTP port (default: 9090)")
|
|
1725
|
+
hs.add_argument("--bind", default="127.0.0.1", help="Bind address (default: 127.0.0.1)")
|
|
1726
|
+
# tortoise team <subcommand>
|
|
1727
|
+
team = sp.add_parser("team", help="Team management (Tortoise Cloud)")
|
|
1728
|
+
team_sp = team.add_subparsers(dest="team_cmd")
|
|
1729
|
+
team_info_p = team_sp.add_parser("info", help="Show team info and usage")
|
|
1730
|
+
# tortoise index github <url>
|
|
1731
|
+
idx = sp.add_parser("index", help="Index content into the graph")
|
|
1732
|
+
idx_sp = idx.add_subparsers(dest="index_cmd")
|
|
1733
|
+
ig = idx_sp.add_parser("github", help="Index a GitHub repo's markdown files")
|
|
1734
|
+
ig.add_argument("url", help="GitHub repo URL (https://github.com/user/repo)")
|
|
1735
|
+
ig.add_argument("--db", required=True, help="Docker URI or file path for target database")
|
|
1736
|
+
ig.add_argument("--branch", default="main", help="Git branch to index")
|
|
1737
|
+
ig.add_argument("--background", action="store_true", help="Run in background")
|
|
1738
|
+
# tortoise create-point <content> --kind <kind>
|
|
1739
|
+
cp = sp.add_parser("create-point", help="Create a Point via Tortoise Cloud API")
|
|
1740
|
+
cp.add_argument("content", help="Point content (text)")
|
|
1741
|
+
cp.add_argument("--kind", default="statement", help="Point kind (default: statement)")
|
|
1742
|
+
# tortoise session <subcommand>
|
|
1743
|
+
session = sp.add_parser("session", help="Manage Tortoise Cloud sessions")
|
|
1744
|
+
session_sp = session.add_subparsers(dest="session_cmd")
|
|
1745
|
+
session_capture = session_sp.add_parser("capture", help="Capture a session from a transcript file")
|
|
1746
|
+
session_capture.add_argument("--file", required=True, help="Path to transcript file")
|
|
1747
|
+
session_list = session_sp.add_parser("list", help="List all sessions")
|
|
1748
|
+
session_view = session_sp.add_parser("view", help="View a specific session")
|
|
1749
|
+
session_view.add_argument("id", help="Session ID")
|
|
1750
|
+
# tortoise list-kinds
|
|
1751
|
+
lk = sp.add_parser("list-kinds", help="List all pointKinds present in the graph with counts")
|
|
1752
|
+
# tortoise context — memory digest for agent session-start hooks
|
|
1753
|
+
ctx = sp.add_parser("context", help="Print memory digest for agent session-start injection")
|
|
1754
|
+
# tortoise list-sources
|
|
1755
|
+
ls = sp.add_parser("list-sources", help="List all Sources with point counts")
|
|
1756
|
+
# tortoise decide --input <json|yaml>
|
|
1757
|
+
dc = sp.add_parser("decide", help="Compare options via EP belief propagation")
|
|
1758
|
+
dc.add_argument("--input", "-i", help="Path to JSON or YAML input file with options/criteria/findings/edges")
|
|
1759
|
+
dc.add_argument("--options", help="JSON dict of options, e.g. '{\"opt:a\": \"desc\"}'")
|
|
1760
|
+
dc.add_argument("--criteria", help="JSON dict of criteria")
|
|
1761
|
+
dc.add_argument("--findings", help="JSON dict of findings")
|
|
1762
|
+
dc.add_argument("--edges", help="JSON list of edges, e.g. '[\"crit:1\", \"IMPL\", \"opt:a\"]' or full edge dicts")
|
|
1763
|
+
dc.add_argument("--context-free", action="store_true",
|
|
1764
|
+
help="Deprecated no-op — context-free (explicit factors) is the only mode since #49 Phase 2",)
|
|
1765
|
+
dc.add_argument("--db", help="FalkorDB URI override (default: TORTOISE_DB_URI or docker://:@localhost:16379/tortoise)")
|
|
1766
|
+
try:
|
|
1767
|
+
args = p.parse_args(argv)
|
|
1768
|
+
except (argparse.ArgumentError, SystemExit) as e:
|
|
1769
|
+
if isinstance(e, SystemExit):
|
|
1770
|
+
raise
|
|
1771
|
+
p.print_usage()
|
|
1772
|
+
print(f"error: {e}", file=sys.stderr)
|
|
1773
|
+
return 2
|
|
1774
|
+
if args.cmd == "rebuild":
|
|
1775
|
+
_cmd_rebuild(args)
|
|
1776
|
+
return 0
|
|
1777
|
+
elif args.cmd == "demo":
|
|
1778
|
+
_cmd_demo(args)
|
|
1779
|
+
return 0
|
|
1780
|
+
elif args.cmd == "check-consistency":
|
|
1781
|
+
import sys as _sys
|
|
1782
|
+
try:
|
|
1783
|
+
from tortoise.consistency import check_consistency
|
|
1784
|
+
from tortoise.projection import FalkorProjection
|
|
1785
|
+
proj = FalkorProjection.from_uri(args.db)
|
|
1786
|
+
try:
|
|
1787
|
+
result = check_consistency(args.log, proj)
|
|
1788
|
+
finally:
|
|
1789
|
+
proj.close()
|
|
1790
|
+
except Exception as e:
|
|
1791
|
+
print(f"Error: {e}", file=_sys.stderr)
|
|
1792
|
+
return 1
|
|
1793
|
+
if result["ok"]:
|
|
1794
|
+
print(f"\u2713 Consistent: {result['log_points']} points in both log and graph")
|
|
1795
|
+
return 0
|
|
1796
|
+
else:
|
|
1797
|
+
print(f"\u2717 Inconsistent: {result['log_points']} in log, {result['db_points']} in graph (delta: {result['delta']})")
|
|
1798
|
+
return 1
|
|
1799
|
+
elif args.cmd == "reconcile":
|
|
1800
|
+
return _cmd_reconcile(args)
|
|
1801
|
+
elif args.cmd == "backfill":
|
|
1802
|
+
_cmd_backfill(args)
|
|
1803
|
+
return 0
|
|
1804
|
+
elif args.cmd == "verify":
|
|
1805
|
+
return _cmd_verify(args)
|
|
1806
|
+
elif args.cmd == "migrate-db":
|
|
1807
|
+
from tortoise.migrate_db import main as _migrate_main
|
|
1808
|
+
return _migrate_main(["--force"] if args.force else [])
|
|
1809
|
+
elif args.cmd == "backup":
|
|
1810
|
+
from tortoise.backup import backup
|
|
1811
|
+
target = backup(db_path=args.db, events_path=args.events)
|
|
1812
|
+
print(f"Backed up to {target}")
|
|
1813
|
+
return 0
|
|
1814
|
+
elif args.cmd == "restore":
|
|
1815
|
+
from tortoise.backup import restore
|
|
1816
|
+
result = restore(args.backup_dir, db_path=args.db, events_path=args.events)
|
|
1817
|
+
print(f"Restored {result['events']} events — {result['status']}")
|
|
1818
|
+
return 0
|
|
1819
|
+
elif args.cmd == "serve":
|
|
1820
|
+
from tortoise.mcp_server import main as serve_main
|
|
1821
|
+
serve_main()
|
|
1822
|
+
return 0
|
|
1823
|
+
elif args.cmd == "mine-conversation":
|
|
1824
|
+
return _cmd_mine_conversation(args)
|
|
1825
|
+
elif args.cmd == "init":
|
|
1826
|
+
return _cmd_init(args)
|
|
1827
|
+
elif args.cmd == "setup":
|
|
1828
|
+
return _cmd_setup(args)
|
|
1829
|
+
elif args.cmd == "doctor":
|
|
1830
|
+
return _cmd_doctor(args)
|
|
1831
|
+
elif args.cmd == "onboard":
|
|
1832
|
+
return _cmd_onboard(args)
|
|
1833
|
+
elif args.cmd == "health-server":
|
|
1834
|
+
from tortoise.monitoring import serve_health
|
|
1835
|
+
print(f"Health server on http://{args.bind}:{args.port}/health")
|
|
1836
|
+
serve_health(args.port, bind=args.bind)
|
|
1837
|
+
return 0
|
|
1838
|
+
elif args.cmd == "team":
|
|
1839
|
+
if args.team_cmd == "info":
|
|
1840
|
+
return _cmd_team_info(args)
|
|
1841
|
+
team.print_help()
|
|
1842
|
+
return 1
|
|
1843
|
+
elif args.cmd == "create-point":
|
|
1844
|
+
return _cmd_create_point(args)
|
|
1845
|
+
elif args.cmd == "session":
|
|
1846
|
+
return _cmd_session(args)
|
|
1847
|
+
elif args.cmd == "index":
|
|
1848
|
+
if args.index_cmd == "github":
|
|
1849
|
+
return _cmd_index_github(args)
|
|
1850
|
+
idx.print_help()
|
|
1851
|
+
return 1
|
|
1852
|
+
elif args.cmd == "list-kinds":
|
|
1853
|
+
return _cmd_list_kinds(args)
|
|
1854
|
+
elif args.cmd == "context":
|
|
1855
|
+
return _cmd_context(args)
|
|
1856
|
+
elif args.cmd == "list-sources":
|
|
1857
|
+
return _cmd_list_sources(args)
|
|
1858
|
+
elif args.cmd == "decide":
|
|
1859
|
+
return _cmd_decide(args)
|
|
1860
|
+
else:
|
|
1861
|
+
p.print_help()
|
|
1862
|
+
return 1
|
|
1863
|
+
|
|
1864
|
+
if __name__ == "__main__":
|
|
1865
|
+
raise SystemExit(main())
|