-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
executable file
·508 lines (426 loc) · 17.3 KB
/
Copy pathinstall.py
File metadata and controls
executable file
·508 lines (426 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#!/usr/bin/env python3
"""
Installation script for temporal-reasoning skill.
Installs minigraf and mcp Python packages, syncs skill files, provides next steps.
Usage:
python install.py # Full install
python install.py --check # Just check dependencies
python install.py --force # Force reinstall even if recent
"""
import sys
import subprocess
import os
import importlib.util
from datetime import datetime, timezone
UPDATE_INTERVAL = 7 * 24 * 60 * 60 # 7 days in seconds
REPO_DIR = os.path.dirname(os.path.abspath(__file__))
LAST_UPDATE_FILE = os.path.join(REPO_DIR, ".last_update")
VENV_DIR = os.path.join(REPO_DIR, ".venv")
VENV_PYTHON = os.path.join(VENV_DIR, "bin", "python")
FILES_TO_SYNC = ["SKILL.md", "mcp_server.py", "skill.json"]
DIRS_TO_SYNC = ["tools", "hooks"]
SKILL_DIRS = [
os.path.join(".opencode", "skills", "temporal-reasoning"),
os.path.join("skills", "temporal-reasoning"),
]
def ensure_venv() -> bool:
"""Create the virtualenv at VENV_DIR if it doesn't already exist."""
if os.path.exists(VENV_PYTHON):
print(f"✓ Virtualenv found at {VENV_DIR}")
return True
print(f" Creating virtualenv at {VENV_DIR}...")
result = subprocess.run(
[sys.executable, "-m", "venv", VENV_DIR],
timeout=60,
)
if result.returncode == 0:
print(f"✓ Virtualenv created at {VENV_DIR}")
return True
print(f"✗ Could not create virtualenv — {result.returncode}")
return False
def check_python_version():
"""Check Python version is 3.9+."""
if sys.version_info < (3, 9):
print(f"ERROR: Python 3.9+ required, "
f"found {sys.version_info.major}.{sys.version_info.minor}")
return False
print(f"✓ Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
return True
def _venv_has(module: str) -> bool:
"""Return True if *module* is importable inside the venv."""
result = subprocess.run(
[VENV_PYTHON, "-c", f"import {module}"],
capture_output=True,
)
return result.returncode == 0
def _venv_pip_install(*specs: str, timeout: int = 300) -> bool:
"""Install one or more pip specs into the venv. Returns True on success."""
result = subprocess.run(
[VENV_PYTHON, "-m", "pip", "install"] + list(specs),
timeout=timeout,
)
return result.returncode == 0
def check_minigraf_package():
"""Verify minigraf Python package is installed in the venv."""
if _venv_has("minigraf"):
print("✓ minigraf Python package found")
return True
print("✗ minigraf not found — installing via pip...")
if _venv_pip_install("minigraf>=0.22.0", timeout=120):
print("✓ minigraf installed")
return True
print("✗ pip install minigraf failed")
return False
def check_mcp_package():
"""Verify mcp Python package is installed in the venv."""
if _venv_has("mcp"):
print("✓ mcp Python package found")
return True
print("✗ mcp not found — installing via pip...")
if _venv_pip_install("mcp>=1.27.0", timeout=120):
print("✓ mcp installed")
return True
print("✗ pip install mcp failed")
return False
def check_tree_sitter_languages_package():
"""Verify tree-sitter grammar support, installing packages if absent.
Required for git ingestion to extract code structure (functions, classes,
imports) from source files. Without it, ingestion runs silently but stores
no code entities.
Tries two options:
- tree-sitter-languages (bundled, Python <=3.12 only)
- Individual packages tree-sitter + tree-sitter-rust/python/javascript/...
(Python 3.13+ compatible, requires tree-sitter >=0.22)
"""
if _venv_has("tree_sitter_languages"):
print("✓ tree_sitter_languages package found")
return True
# Try installing tree-sitter-languages (works for Python <=3.12)
result = subprocess.run(
[VENV_PYTHON, "-m", "pip", "install", "tree-sitter-languages"],
timeout=300,
capture_output=True,
)
if result.returncode == 0:
print("✓ tree_sitter_languages installed")
return True
# Fallback: install individual language packages (Python 3.13+)
print(" tree-sitter-languages unavailable (Python 3.13+?) — installing individual packages...")
individual = [
"tree-sitter>=0.22.0",
"tree-sitter-rust", "tree-sitter-python", "tree-sitter-javascript",
"tree-sitter-typescript", "tree-sitter-go", "tree-sitter-java",
"tree-sitter-c", "tree-sitter-cpp",
]
if _venv_pip_install(*individual):
print("✓ Individual tree-sitter language packages installed")
return True
print("✗ Could not install tree-sitter grammar support — code ingestion will be disabled")
return False
def check_mcp_server_importable():
"""Verify mcp_server module can be imported inside the venv."""
result = subprocess.run(
[VENV_PYTHON, "-c", "import sys; sys.path.insert(0, ''); import mcp_server"],
capture_output=True,
cwd=REPO_DIR,
)
if result.returncode == 0:
print("✓ mcp_server module importable")
return True
stderr = result.stderr.decode(errors="replace").strip()
print(f"✗ Cannot import mcp_server: {stderr}")
return False
def should_update():
"""Check if update should run (no more than once a week)."""
if not os.path.exists(LAST_UPDATE_FILE):
return True
try:
with open(LAST_UPDATE_FILE, "r") as f:
content = f.read().strip()
if not content:
return True
last_update = datetime.fromisoformat(content)
except (ValueError, IOError):
return True
return (datetime.now(timezone.utc) - last_update).total_seconds() > UPDATE_INTERVAL
def _write_last_update() -> None:
with open(LAST_UPDATE_FILE, "w") as f:
f.write(datetime.now(timezone.utc).isoformat())
def _sync_files(target_dir: str) -> None:
import shutil
for rel_dir in SKILL_DIRS:
dest_dir = os.path.join(target_dir, rel_dir)
os.makedirs(dest_dir, exist_ok=True)
for fname in FILES_TO_SYNC:
src = os.path.join(REPO_DIR, fname)
if os.path.exists(src):
shutil.copy2(src, os.path.join(dest_dir, fname))
for dname in DIRS_TO_SYNC:
src_dir = os.path.join(REPO_DIR, dname)
if os.path.isdir(src_dir):
shutil.copytree(src_dir, os.path.join(dest_dir, dname), dirs_exist_ok=True)
synced = ", ".join(FILES_TO_SYNC + DIRS_TO_SYNC)
dirs = ", ".join(SKILL_DIRS)
print(f"✓ Synced [{synced}] → [{dirs}]")
def update_skill(target_dir: str) -> bool:
"""Pull from GitHub and sync skill files to target_dir."""
print("Checking for skill updates...")
try:
result = subprocess.run(
["git", "pull", "origin", "master"],
cwd=REPO_DIR,
capture_output=True,
text=True,
timeout=30,
check=True,
)
_write_last_update()
if result.stdout.strip() and "Already up to date" not in result.stdout:
print("Pulling latest from GitHub...")
_sync_files(target_dir)
print("✓ Skill up-to-date")
return True
except subprocess.CalledProcessError:
print("ERROR: git pull failed")
return False
except FileNotFoundError:
print("ERROR: git not found")
return False
except subprocess.TimeoutExpired:
print("ERROR: git pull timed out")
return False
def _get_target_dir() -> str:
if "--target" in sys.argv:
idx = sys.argv.index("--target")
if idx + 1 < len(sys.argv):
return os.path.abspath(sys.argv[idx + 1])
return os.getcwd()
_PLACEHOLDER_KEY = "your-api-key-here"
def setup_mcp_json(target_dir: str) -> bool:
"""Idempotently write the temporal-reasoning MCP server block into .mcp.json.
- Creates the file if absent.
- Merges into existing content if present (other servers are preserved).
- Always updates args and MINIGRAF_GRAPH_PATH to reflect current paths.
- Uses the venv python as the command so the MCP server runs in the venv.
- Only MINIGRAF_GRAPH_PATH is set here; ANTHROPIC_API_KEY and
VULCAN_EXTRACTION_STRATEGY belong in .claude/settings.local.json so
they are available to hook subprocesses as well as the MCP server.
"""
import json
mcp_json_path = os.path.join(target_dir, ".mcp.json")
server_script = os.path.join(REPO_DIR, "mcp_server.py")
graph_path = os.path.join(target_dir, "memory.graph")
existing: dict = {}
file_existed = os.path.exists(mcp_json_path)
if file_existed:
try:
with open(mcp_json_path) as f:
existing = json.load(f)
except (json.JSONDecodeError, IOError):
existing = {}
new_env = {
"MINIGRAF_GRAPH_PATH": graph_path,
}
existing.setdefault("mcpServers", {})["temporal-reasoning"] = {
"type": "stdio",
"command": VENV_PYTHON,
"args": [server_script],
"env": new_env,
}
try:
with open(mcp_json_path, "w") as f:
json.dump(existing, f, indent=2)
f.write("\n")
except IOError as e:
print(f"✗ Could not write .mcp.json: {e}")
return False
verb = "Updated" if file_existed else "Created"
print(f"✓ {verb} {mcp_json_path}")
print(f" command = {VENV_PYTHON}")
print(f" MINIGRAF_GRAPH_PATH = {graph_path}")
return True
def setup_claude_settings_json(target_dir: str) -> bool:
"""Idempotently write enabledPlugins, extraKnownMarketplaces, and
enabledMcpjsonServers into .claude/settings.json.
- Creates .claude/ and the file if absent.
- Merges into existing content (other keys are preserved).
- Always sets the marketplace path to the current REPO_DIR.
"""
import json
claude_dir = os.path.join(target_dir, ".claude")
settings_path = os.path.join(claude_dir, "settings.json")
existing: dict = {}
file_existed = os.path.exists(settings_path)
if file_existed:
try:
with open(settings_path) as f:
existing = json.load(f)
except (json.JSONDecodeError, IOError):
existing = {}
# enabledPlugins
plugins = existing.setdefault("enabledPlugins", {})
plugins["vulcan@temporal-reasoning-local"] = True
# extraKnownMarketplaces
marketplaces = existing.setdefault("extraKnownMarketplaces", {})
marketplaces["temporal-reasoning-local"] = {
"source": {
"source": "directory",
"path": REPO_DIR,
}
}
# enabledMcpjsonServers
mcp_servers = existing.setdefault("enabledMcpjsonServers", [])
if "temporal-reasoning" not in mcp_servers:
mcp_servers.append("temporal-reasoning")
# Hooks belong in settings.local.json, not here — remove any stale entry
existing.pop("hooks", None)
os.makedirs(claude_dir, exist_ok=True)
try:
with open(settings_path, "w") as f:
json.dump(existing, f, indent=4)
f.write("\n")
except IOError as e:
print(f"✗ Could not write {settings_path}: {e}")
return False
verb = "Updated" if file_existed else "Created"
print(f"✓ {verb} {settings_path}")
print(f" enabledPlugins.vulcan@temporal-reasoning-local = true")
print(f" extraKnownMarketplaces.temporal-reasoning-local → {REPO_DIR}")
print(f" enabledMcpjsonServers += temporal-reasoning")
return True
def setup_claude_settings(target_dir: str) -> bool:
"""Idempotently write hooks and env vars into .claude/settings.local.json.
- Creates .claude/ and the file if absent.
- Merges into existing content (permissions and other keys are preserved).
- For hooks: searches existing UserPromptSubmit/Stop arrays for an entry
that already references our hook scripts and updates the command path;
appends a new entry only if none is found.
- Preserves ANTHROPIC_API_KEY if already set to a real value.
- Sets VULCAN_EXTRACTION_STRATEGY=llm (default); preserves existing value.
- Hook commands use the venv python so they share the same environment.
- These env vars are written here (not in .mcp.json) so that hook
subprocesses inherit them from the Claude Code process environment.
"""
import json
prepare_cmd = f"{VENV_PYTHON} {os.path.join(REPO_DIR, 'hooks', 'prepare_hook.py')}"
finalize_cmd = f"{VENV_PYTHON} {os.path.join(REPO_DIR, 'hooks', 'finalize_hook.py')}"
claude_dir = os.path.join(target_dir, ".claude")
settings_path = os.path.join(claude_dir, "settings.local.json")
existing: dict = {}
file_existed = os.path.exists(settings_path)
if file_existed:
try:
with open(settings_path) as f:
existing = json.load(f)
except (json.JSONDecodeError, IOError):
existing = {}
# --- env block ---
env_block = existing.setdefault("env", {})
prev_key = env_block.get("ANTHROPIC_API_KEY", "")
key_is_real = bool(prev_key) and prev_key != _PLACEHOLDER_KEY
if not key_is_real:
env_block["ANTHROPIC_API_KEY"] = _PLACEHOLDER_KEY
if "VULCAN_EXTRACTION_STRATEGY" not in env_block:
env_block["VULCAN_EXTRACTION_STRATEGY"] = "heuristic"
# --- hooks ---
hooks_block = existing.setdefault("hooks", {})
def _upsert_hook(event: str, script_marker: str, command: str, timeout: int) -> str:
"""Insert or update a hook command for the given event. Returns 'added'/'updated'."""
entries = hooks_block.setdefault(event, [])
# Search for an existing entry whose hook command references our script
for entry in entries:
for hook in entry.get("hooks", []):
if script_marker in hook.get("command", ""):
old_cmd = hook["command"]
hook["command"] = command
hook["timeout"] = timeout
return "updated" if old_cmd != command else "unchanged"
# Not found — append a new matcher entry
entries.append({
"matcher": "",
"hooks": [{"type": "command", "command": command, "timeout": timeout}],
})
return "added"
prepare_status = _upsert_hook("UserPromptSubmit", "prepare_hook.py", prepare_cmd, 5000)
finalize_status = _upsert_hook("Stop", "finalize_hook.py", finalize_cmd, 10000)
os.makedirs(claude_dir, exist_ok=True)
try:
with open(settings_path, "w") as f:
json.dump(existing, f, indent=2)
f.write("\n")
except IOError as e:
print(f"✗ Could not write {settings_path}: {e}")
return False
verb = "Updated" if file_existed else "Created"
print(f"✓ {verb} {settings_path}")
print(f" UserPromptSubmit hook ({prepare_status}): {prepare_cmd}")
print(f" Stop hook ({finalize_status}): {finalize_cmd}")
print(f" env.VULCAN_EXTRACTION_STRATEGY = {env_block['VULCAN_EXTRACTION_STRATEGY']}")
if key_is_real:
print(" env.ANTHROPIC_API_KEY = (preserved)")
else:
print(f" env.ANTHROPIC_API_KEY = {_PLACEHOLDER_KEY} ← replace with your key")
return True
def main(target_dir: str = "") -> None:
print("=" * 50)
print("Temporal Reasoning Skill Setup")
print("=" * 50)
print()
if not target_dir:
target_dir = _get_target_dir()
print("Checking virtualenv...")
venv_ok = ensure_venv()
print()
if not venv_ok:
print("=" * 50)
print("✗ Setup incomplete — fix errors above")
print("=" * 50)
sys.exit(1)
checks = [
("Python version", check_python_version),
("minigraf package", check_minigraf_package),
("mcp package", check_mcp_package),
("tree_sitter_languages package", check_tree_sitter_languages_package),
("MCP server", check_mcp_server_importable),
]
results = []
for name, check_func in checks:
print(f"Checking {name}...")
results.append(check_func())
print()
print("Configuring .mcp.json...")
mcp_ok = setup_mcp_json(target_dir)
print()
print("Configuring .claude/settings.json...")
settings_json_ok = setup_claude_settings_json(target_dir)
print()
print("Configuring .claude/settings.local.json...")
settings_ok = setup_claude_settings(target_dir)
print()
if all(results) and mcp_ok and settings_json_ok and settings_ok:
print("=" * 50)
print("✓ Setup complete!")
print("=" * 50)
print()
print("Replace any 'your-api-key-here' placeholders in:")
print(" .claude/settings.local.json — hooks + Claude Code env (ANTHROPIC_API_KEY)")
print()
print("Other agents (manual config — see hooks/ for templates):")
print(" hooks/codex.toml — Codex CLI")
print(" hooks/hermes.yaml — Hermes")
print(" hooks/opencode.json — OpenCode")
else:
print("=" * 50)
print("✗ Setup incomplete — fix errors above")
print("=" * 50)
sys.exit(1)
if __name__ == "__main__":
target_dir = _get_target_dir()
force = "--force" in sys.argv
if target_dir != REPO_DIR:
print(f"Installing into: {target_dir}")
if force or should_update():
update_skill(target_dir)
else:
_sync_files(target_dir)
main(target_dir)