-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-project.py
More file actions
executable file
·724 lines (621 loc) · 30.2 KB
/
setup-project.py
File metadata and controls
executable file
·724 lines (621 loc) · 30.2 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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
#!/usr/bin/env python3
"""
setup-project.py — Integrate session-knowledge + tentacle orchestration into a project.
Installs skills, instructions (enforcement), and optionally patches CLAUDE.md.
Single entry point for setting up all AI knowledge tools in any project.
Usage:
python setup-project.py # Auto-detect project root (git root)
python setup-project.py /path/to/project # Explicit project root
python setup-project.py --skill-only # Only install skills, skip patching
python setup-project.py --no-tentacle # Skip tentacle orchestration
python setup-project.py --dry-run # Show what would be done
"""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
from agent_adapters import detect_agents, expand_init_agents, get_adapter, unique_target_adapters
from host_manifest import HOST_INSTRUCTION_FILES as KNOWN_HOSTS_INSTRUCTION_FILES # noqa: E402
from host_manifest import HOST_SKILL_SUBPATHS # noqa: E402
SCRIPT_DIR = Path(__file__).resolve().parent
TEMPLATES_DIR = SCRIPT_DIR / "templates"
SKILLS_DIR = SCRIPT_DIR / "skills"
PRESETS_DIR = SCRIPT_DIR / "presets"
# ---------------------------------------------------------------------------
# Atomic write helper (P1-7)
# ---------------------------------------------------------------------------
def _atomic_write_text(path: Path, content: str, encoding: str = "utf-8") -> None:
"""Write content to path atomically via temp + os.replace. No CRLF translation."""
tmp = path.with_suffix(path.suffix + ".tmp")
try:
tmp.write_bytes(content.encode(encoding))
os.replace(str(tmp), str(path))
except Exception:
try:
tmp.unlink(missing_ok=True)
except Exception:
pass
raise
# Host metadata is centralised in host_manifest.py — import canonical constants.
# Do NOT add new hosts here; update host_manifest.py through the review process.
if os.name == "nt":
for _s in (sys.stdout, sys.stderr):
if hasattr(_s, "reconfigure"):
_s.reconfigure(encoding="utf-8", errors="replace")
# Vendored skills that explicitly support both Copilot CLI and Claude Code.
# These are deployed to BOTH host skill paths by install_skills().
# All other skills in INSTALL_ITEMS["skills"] are deployed to Copilot CLI only.
VENDORED_SKILLS: tuple[str, ...] = ("karpathy-guidelines",)
# What to install
INSTALL_ITEMS = {
# Skills (from tools/skills/ → .github/skills/)
"skills": [
{"src": "session-knowledge-creator", "label": "Session Knowledge Creator (meta-skill)"},
{"src": "tentacle-creator", "label": "Tentacle Creator (meta-skill)"},
{"src": "tentacle-orchestration", "label": "Tentacle Orchestration"},
{"src": "agent-creator", "label": "Agent Creator (generates .agent.md files)"},
{"src": "hook-creator", "label": "Hook Creator (quality enforcement hooks)"},
{"src": "workflow-creator", "label": "Workflow Creator (phased development lifecycle)"},
{"src": "skill-creator", "label": "Skill Creator (create, improve, and evaluate skills)"},
{"src": "find-skills", "label": "Find Skills (discover & install from skills.sh)"},
{"src": "agent-instructions-auditor", "label": "Instructions Auditor (token budget, cache safety, quality)"},
{"src": "forge-ecosystem", "label": "Forge Ecosystem (10 CLI tools for game & app dev)"},
{"src": "code-reviewer", "label": "Code Reviewer (skeptical, signal-over-noise code review)"},
{"src": "task-step-generator", "label": "Task Step Generator (structured step-file generation)"},
{"src": "conductor-creator", "label": "Conductor Creator (task-router generator)"},
{"src": "project-onboarding", "label": "Project Onboarding (full AI ecosystem setup guide)"},
{"src": "detective-investigation", "label": "Detective Investigation (evidence-board RCA workflow)"},
{"src": "karpathy-guidelines", "label": "Karpathy Guidelines (anti-overcomplication coding rules)"},
],
# Templates (from tools/templates/ → .github/skills/ or .github/instructions/)
"templates": [
{
"src": "SKILL.md",
"dst": ".github/skills/session-knowledge/SKILL.md",
"label": "Session Knowledge Skill",
},
{
"src": "session-knowledge.instructions.md",
"dst": ".github/instructions/session-knowledge.instructions.md",
"label": "Session Knowledge Instructions (enforcement)",
},
],
}
# Snippet to add to CLAUDE.md
CLAUDE_SNIPPET = """
## Pre-Task Briefing (BẮT BUỘC)
> **⚠️ MANDATORY**: Before starting a new task, run briefing to get context from past sessions.
> After fixing bugs or completing tasks, record learnings.
> Details: `.github/skills/session-knowledge/SKILL.md`
```bash
# Before starting a task — get context from past sessions
sk briefing --auto --compact
# Fallbacks: macOS/Linux `python3 ~/.copilot/tools/briefing.py --auto --compact`;
# Windows PowerShell `python "$env:USERPROFILE\\.copilot\\tools\\briefing.py" --auto --compact`
# After fixing a bug — record the mistake
sk learn --mistake "Title" "What happened and fix" --tags "relevant,tags"
# After completing work — record pattern/decision
sk learn --pattern "Title" "What works well" --tags "tags"
```
"""
SKILLS_TABLE_ROW = "| Pre-task briefing & record learnings | [session-knowledge](./skills/session-knowledge/) |"
# Registry of projects that have had skills deployed via setup-project.py.
# auto-update-tools.py reads this so vendored-skill updates propagate to every
# registered project even when auto-update runs from the tools repo or a
# non-project context (e.g. launchd / shell auto-start).
REGISTRY_PATH = Path.home() / ".copilot" / "session-state" / "tools-managed-projects.json"
def _load_project_registry() -> list[str]:
"""Return the list of registered project root paths (strings).
Handles both the legacy plain-string format and the richer dict format
written by project-registry.py (``{"name": ..., "path": ..., "created_at": ...}``).
Only the path string is extracted; callers receive a flat list of strings.
"""
try:
if REGISTRY_PATH.exists():
data = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
paths: list[str] = []
for entry in data.get("projects", []):
if isinstance(entry, str):
paths.append(entry)
elif isinstance(entry, dict):
p = entry.get("path", "")
if isinstance(p, str) and p:
paths.append(p)
return paths
except Exception:
pass
return []
def _register_project(project_root: Path) -> None:
"""Add *project_root* to the persistent registry (idempotent, silent on error).
Reads the full raw registry (which may contain richer dict entries written by
project-registry.py) and appends a plain string entry when the path is new.
Existing entries of either format are preserved unchanged.
"""
try:
key = str(project_root.resolve())
try:
raw: list = (
json.loads(REGISTRY_PATH.read_text(encoding="utf-8")).get("projects", [])
if REGISTRY_PATH.exists()
else []
)
except Exception:
raw = []
existing_paths: set[str] = set()
for entry in raw:
if isinstance(entry, str):
existing_paths.add(entry)
elif isinstance(entry, dict):
p = entry.get("path", "")
if p:
existing_paths.add(p)
if key not in existing_paths:
raw.append(key)
REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
# P1-7: atomic write prevents registry truncation on concurrent access
_atomic_write_text(REGISTRY_PATH, json.dumps({"projects": raw}, indent=2))
except Exception:
pass
# Snippet to add to AGENTS.md
AGENTS_SNIPPET = """
## Pre-Task Briefing (BẮT BUỘC)
> **⚠️ MANDATORY**: Before starting a new task, run briefing to get context from past sessions.
> After fixing bugs or completing tasks, record learnings with proper categorization.
> Details: `.github/skills/session-knowledge/SKILL.md`
```bash
# Before task — start minimal and escalate only when needed
sk briefing --auto --compact
# Fallbacks: macOS/Linux `python3 ~/.copilot/tools/briefing.py --auto --compact`;
# Windows PowerShell `python "$env:USERPROFILE\\.copilot\\tools\\briefing.py" --auto --compact`
# Before delegating via tentacle — preferred structured recall path
sk tentacle swarm <name> --briefing
# Manual compatibility for ad hoc sub-agent prompts
sk briefing "<sub-agent task>" --for-subagent
# During task — search for errors/topics
sk query "<error or topic>" --verbose
# After task — record with full metadata
sk learn --mistake "Title" "Description" --tags "t1,t2" --wing <wing> --room <room> --fact "key detail"
sk learn --pattern "Title" "Description" --tags "t1,t2" --wing <wing> --room <room>
sk learn --relate "#id1" "resolved_by" "#id2"
```
"""
def find_git_root() -> Path | None:
"""Find the git repository root from cwd."""
try:
result = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
return Path(result.stdout.strip())
except Exception:
pass
return None
def copy_if_changed(src: Path, dst: Path, dry_run: bool, label: str) -> bool:
"""Copy src to dst if content differs. Returns True if changed."""
if not src.exists():
print(f" ⚠ Source not found: {src}")
return False
if dst.exists():
src_hash = hashlib.md5(src.read_bytes()).hexdigest()
dst_hash = hashlib.md5(dst.read_bytes()).hexdigest()
if src_hash == dst_hash:
print(f" ⏭ {label} — already up to date")
return False
if dry_run:
print(f" [dry-run] Would update: {label}")
return True
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
print(f" ✓ Updated: {label}")
return True
if dry_run:
print(f" [dry-run] Would create: {label}")
return True
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
print(f" ✓ Installed: {label}")
return True
def should_copy_skill_asset(rel_path: Path) -> bool:
"""Return False for generated Python artifacts that should not deploy."""
return "__pycache__" not in rel_path.parts and rel_path.suffix != ".pyc"
def install_skills(project_root: Path, dry_run: bool) -> int:
"""Install creator skills from tools/skills/ → .github/skills/.
For each skill, copies SKILL.md and all files found in any asset
subdirectory (references/, templates/, evals/, …). The directory
structure under each subdirectory is preserved so that relative paths
inside SKILL.md (e.g. ``references/foo.md``, ``templates/bar.py``)
resolve correctly after deployment.
Vendored skills (listed in VENDORED_SKILLS) additionally support Claude Code
and are deployed to that host's skill path alongside the Copilot CLI path.
The Claude Code path is derived from HOST_SKILL_SUBPATHS to stay in sync with
host_manifest.py without duplicating path strings here.
"""
changes = 0
# Derive Claude Code skills base once from the manifest reference path.
# HOST_SKILL_SUBPATHS["Claude Code"] = ".claude/skills/session-knowledge/SKILL.md"
# → parent.parent = ".claude/skills"
_claude_ref = HOST_SKILL_SUBPATHS.get("Claude Code", "")
_claude_skills_base = Path(_claude_ref).parent.parent if _claude_ref else None
for item in INSTALL_ITEMS["skills"]:
skill_name = item["src"]
src = SKILLS_DIR / skill_name / "SKILL.md"
dst = project_root / ".github" / "skills" / skill_name / "SKILL.md"
if copy_if_changed(src, dst, dry_run, item["label"]):
changes += 1
# Vendored skills also deploy to Claude Code (both supported hosts).
if skill_name in VENDORED_SKILLS and _claude_skills_base:
dst_claude = project_root / _claude_skills_base / skill_name / "SKILL.md"
if copy_if_changed(src, dst_claude, dry_run, f"{item['label']} (Claude Code)"):
changes += 1
# Copy every asset subdirectory that lives alongside SKILL.md.
# This is intentionally generic so that new asset dirs (templates/,
# evals/, etc.) are picked up automatically without code changes.
# rglob("*") descends into nested subdirs; relative_to(skill_src_dir)
# preserves the full relative path at the destination.
# Vendored skills mirror asset subdirs to Claude Code alongside Copilot CLI.
skill_src_dir = SKILLS_DIR / skill_name
for subdir in sorted(skill_src_dir.iterdir()):
if not subdir.is_dir():
continue
for asset_file in subdir.rglob("*"):
if not asset_file.is_file():
continue
rel = asset_file.relative_to(skill_src_dir)
if not should_copy_skill_asset(rel):
continue
asset_dst = project_root / ".github" / "skills" / skill_name / rel
if copy_if_changed(asset_file, asset_dst, dry_run, f"{item['label']} → {rel}"):
changes += 1
if skill_name in VENDORED_SKILLS and _claude_skills_base:
asset_claude_dst = project_root / _claude_skills_base / skill_name / rel
if copy_if_changed(asset_file, asset_claude_dst, dry_run, f"{item['label']} (Claude Code) → {rel}"):
changes += 1
return changes
def install_templates(project_root: Path, dry_run: bool) -> int:
"""Install template files (SKILL.md, instructions) from tools/templates/."""
changes = 0
for item in INSTALL_ITEMS["templates"]:
src = TEMPLATES_DIR / item["src"]
dst = project_root / item["dst"]
if copy_if_changed(src, dst, dry_run, item["label"]):
changes += 1
return changes
def install_tentacle(project_root: Path, dry_run: bool) -> int:
"""Install tentacle orchestration: .gitignore entry."""
changes = 0
gitignore = project_root / ".gitignore"
if gitignore.exists():
content = gitignore.read_text(encoding="utf-8")
if ".octogent/" not in content:
if dry_run:
print(" [dry-run] Would add .octogent/ to .gitignore")
else:
with open(gitignore, "a") as f:
f.write("\n# Tentacle orchestration (local work contexts)\n.octogent/\n")
print(" ✓ Added .octogent/ to .gitignore")
changes += 1
else:
print(" ⏭ .octogent/ already in .gitignore")
else:
if dry_run:
print(" [dry-run] Would create .gitignore with .octogent/")
else:
gitignore.write_text("# Tentacle orchestration (local work contexts)\n.octogent/\n", encoding="utf-8")
print(" ✓ Created .gitignore with .octogent/")
changes += 1
return changes
def patch_claude_md(project_root: Path, dry_run: bool) -> bool:
"""Add Pre-Task Briefing section to CLAUDE.md if not present."""
claude_md = project_root / KNOWN_HOSTS_INSTRUCTION_FILES["Claude Code"]
if not claude_md.exists():
print(" ⏭ No CLAUDE.md found, skipping")
return False
content = claude_md.read_text(encoding="utf-8")
if "session-knowledge" in content or "briefing.py" in content:
print(" ⏭ CLAUDE.md already references session-knowledge")
return False
if dry_run:
print(" [dry-run] Would add Pre-Task Briefing section to CLAUDE.md")
return True
# Insert after "## Session Startup" section or at the top after first ##
lines = content.split("\n")
insert_idx = None
# Find end of Session Startup section (next ## heading)
in_startup = False
for i, line in enumerate(lines):
if "## Session Startup" in line:
in_startup = True
continue
if in_startup and line.startswith("## "):
insert_idx = i
break
if insert_idx is None:
# Find first ## heading and insert after it
for i, line in enumerate(lines):
if line.startswith("## ") and i > 0:
# Find the next ## after this one
for j in range(i + 1, len(lines)):
if lines[j].startswith("## "):
insert_idx = j
break
break
if insert_idx is None:
# Append at end
insert_idx = len(lines)
snippet_lines = CLAUDE_SNIPPET.strip().split("\n")
lines = lines[:insert_idx] + [""] + snippet_lines + [""] + lines[insert_idx:]
claude_md.write_text("\n".join(lines), encoding="utf-8")
print(" ✓ Added Pre-Task Briefing section to CLAUDE.md")
return True
def patch_copilot_instructions(project_root: Path, dry_run: bool) -> bool:
"""Add session-knowledge row to skills table in copilot-instructions.md."""
instructions = project_root / KNOWN_HOSTS_INSTRUCTION_FILES["Copilot CLI"]
if not instructions.exists():
print(" ⏭ No .github/copilot-instructions.md found, skipping")
return False
content = instructions.read_text(encoding="utf-8")
if "session-knowledge" in content:
print(" ⏭ copilot-instructions.md already references session-knowledge")
return False
if dry_run:
print(" [dry-run] Would add session-knowledge to copilot-instructions.md skills table")
return True
# Find the skills table header and insert after |------|-------|
lines = content.split("\n")
for i, line in enumerate(lines):
if "|------|-------|" in line or "|------|-" in line:
lines.insert(i + 1, SKILLS_TABLE_ROW)
instructions.write_text("\n".join(lines), encoding="utf-8")
print(" ✓ Added session-knowledge to copilot-instructions.md skills table")
return True
print(" ⏭ Could not find skills table in copilot-instructions.md")
return False
def patch_agents_md(project_root: Path, dry_run: bool) -> bool:
"""Add Pre-Task Briefing section to AGENTS.md if not present."""
agents_md = project_root / KNOWN_HOSTS_INSTRUCTION_FILES["All agents"]
if not agents_md.exists():
print(" ⏭ No AGENTS.md found, skipping")
return False
content = agents_md.read_text(encoding="utf-8")
if "session-knowledge" in content or "briefing.py" in content:
print(" ⏭ AGENTS.md already references session-knowledge")
return False
if dry_run:
print(" [dry-run] Would add Pre-Task Briefing section to AGENTS.md")
return True
# Insert before "## Code Navigation" or "## Commands" or at end
lines = content.split("\n")
insert_idx = None
for i, line in enumerate(lines):
if line.startswith("## Code Navigation") or line.startswith("## Commands"):
insert_idx = i
break
if insert_idx is None:
insert_idx = len(lines)
snippet_lines = AGENTS_SNIPPET.strip().split("\n")
lines = lines[:insert_idx] + [""] + snippet_lines + [""] + lines[insert_idx:]
agents_md.write_text("\n".join(lines), encoding="utf-8")
print(" ✓ Added Pre-Task Briefing section to AGENTS.md")
return True
def _select_init_adapters(
project_root: Path, requested_agents: list[str] | None, *, init_mode: bool
) -> tuple[list, list[str]]:
selected = list(requested_agents or [])
if not selected and init_mode:
selected = detect_agents(project_root)
if not selected:
selected = ["copilot"]
if not selected:
return [], []
adapters = [get_adapter(key) for key in expand_init_agents(selected)]
return unique_target_adapters(adapters), selected
def apply_init_adapters(project_root: Path, adapters: list, dry_run: bool) -> int:
changes = 0
for adapter in adapters:
rel = adapter.target_path(project_root).relative_to(project_root)
try:
status = adapter.upsert_context(project_root, dry_run=dry_run)
except ValueError as exc:
raise ValueError(f"{adapter.name} context at {rel} is invalid: {exc}") from exc
if status == "unchanged":
print(f" ⏭ {adapter.name} already up to date ({rel})")
continue
changes += 1
if dry_run:
print(f" [dry-run] Would {status}: {rel} ({adapter.name})")
else:
print(f" ✓ {status.capitalize()}: {rel} ({adapter.name})")
return changes
def main():
parser = argparse.ArgumentParser(
description="Integrate session-knowledge + tentacle orchestration into a project",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""\
Examples:
python setup-project.py # Full setup (auto-detect git root)
python setup-project.py /path/to/project # Explicit project root
python setup-project.py --skill-only # Skills only, no CLAUDE.md patching
python setup-project.py --no-tentacle # Skip tentacle orchestration
python setup-project.py --profile python # Install python hook bundle + WORKFLOW.md
python setup-project.py --profile mobile # Install mobile hook bundle + WORKFLOW.md
python setup-project.py --dry-run # Preview changes
Profiles (--profile):
default Minimal safe defaults (dangerous-blocker, secret-detector)
python Python project: TDD, test-reminder, build-reminder, commit-gate
typescript TypeScript/Node: coding-standards, test-reminder, build-reminder, commit-gate
mobile Android/iOS/KMP: architecture-guard, TDD, coding-standards, QA phase
fullstack Full-stack web: architecture-guard, coding-standards, session-banner
What gets installed:
.github/skills/session-knowledge/SKILL.md — Knowledge skill reference
.github/skills/session-knowledge-creator/SKILL.md — Meta-skill: customize for project
.github/skills/tentacle-creator/SKILL.md — Meta-skill: customize tentacle
.github/skills/tentacle-orchestration/SKILL.md — Tentacle workflow skill
.github/skills/skill-creator/SKILL.md — Meta-skill: create and improve skills
.github/skills/conductor-creator/SKILL.md — Meta-skill: generate task router
.github/skills/project-onboarding/SKILL.md — Meta-skill: full AI ecosystem setup
.github/instructions/session-knowledge.instructions.md — Enforcement (auto-inject)
.gitignore — Add .octogent/ entry
CLAUDE.md / copilot-instructions.md / AGENTS.md — Patched with references
.github/hooks/*.py — Hook bundle (when --profile used)
WORKFLOW.md — Starter workflow (when --profile used)
Note: If your project already has session-knowledge installed at the user/global level
(~/.github/instructions/session-knowledge.instructions.md), you can remove the project-level
copy to avoid duplicate always-loaded instructions and reduce context bloat.
""",
)
parser.add_argument(
"project_root", nargs="?", default=None, help="Project root directory (default: auto-detect git root)"
)
parser.add_argument(
"--skill-only", action="store_true", help="Only install skills and instructions, don't patch CLAUDE.md etc."
)
parser.add_argument("--no-tentacle", action="store_true", help="Skip tentacle orchestration setup")
parser.add_argument(
"--profile",
default=None,
metavar="PROFILE",
help="Workflow profile to install as a hook bundle + WORKFLOW.md "
"(default: none; choices: default, python, typescript, mobile, fullstack)",
)
parser.add_argument(
"--agent",
dest="agents",
action="append",
default=None,
metavar="AGENT",
help="Initialize adapter-specific context files; repeat to target multiple adapters",
)
parser.add_argument("--init-mode", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--dry-run", action="store_true", help="Show what would be done without making changes")
args = parser.parse_args()
# Find project root
if args.project_root:
project_root = Path(args.project_root).resolve()
else:
project_root = find_git_root()
if not project_root:
print("✗ Not in a git repository. Specify project root explicitly.")
sys.exit(1)
if not project_root.exists():
print(f"✗ Project root does not exist: {project_root}")
sys.exit(1)
project_name = project_root.name
print(f"🧠 Setting up AI knowledge tools for: {project_name}")
print(f" Path: {project_root}")
if args.dry_run:
print(" (dry-run mode)")
print()
try:
init_adapters, requested_init = _select_init_adapters(project_root, args.agents, init_mode=args.init_mode)
except ValueError as exc:
print(f"✗ {exc}")
sys.exit(1)
changes = 0
# 1. Install session-knowledge skill + instructions
print("📋 Session Knowledge:")
changes += install_templates(project_root, args.dry_run)
# 2. Install creator skills (meta-skills)
print("\n🔧 Creator Skills:")
changes += install_skills(project_root, args.dry_run)
# 3. Tentacle orchestration
if not args.no_tentacle:
print("\n🐙 Tentacle Orchestration:")
changes += install_tentacle(project_root, args.dry_run)
# 4. Patch config files
if not args.skill_only:
print("\n📝 Config Files:")
if init_adapters:
if args.agents:
requested_text = ", ".join(requested_init)
print(f" Initializing adapter contexts for: {requested_text}")
elif args.init_mode:
detected_text = ", ".join(requested_init)
print(f" Using detected adapters: {detected_text}")
try:
changes += apply_init_adapters(project_root, init_adapters, args.dry_run)
except ValueError as exc:
print(f"✗ {exc}")
sys.exit(1)
else:
if patch_claude_md(project_root, args.dry_run):
changes += 1
if patch_copilot_instructions(project_root, args.dry_run):
changes += 1
if patch_agents_md(project_root, args.dry_run):
changes += 1
# 5. Install workflow profile hook bundle (optional, only when --profile is given)
if args.profile:
import re as _re
print(f"\n🔩 Hook Bundle ({args.profile} profile):")
hook_installer = SCRIPT_DIR / "install-project-hooks.py"
cmd = [
sys.executable,
str(hook_installer),
"--profile",
args.profile,
"--project",
str(project_root),
"--workflow",
]
if args.dry_run:
cmd.append("--dry-run")
result = subprocess.run(cmd, capture_output=True, text=True)
# Print installer output so the user sees progress.
if result.stdout:
print(result.stdout, end="")
if result.returncode != 0:
if result.stderr:
print(result.stderr, end="")
print(f" ⚠ Hook bundle install exited with code {result.returncode}")
else:
# Parse the actual change count from installer output to avoid overcounting.
# The installer prints "N change(s) applied." (real run) or
# "Would make N change(s)." (dry-run); "No changes needed." → 0.
m = _re.search(r"(\d+)\s+change\(s\)", result.stdout)
if m:
changes += int(m.group(1))
# Summary
print()
if changes == 0:
print("✅ Already set up — no changes needed.")
elif args.dry_run:
print(f"Would make {changes} change(s). Run without --dry-run to apply.")
else:
print(f"✅ Done! {changes} change(s) applied.")
print()
print("Next steps:")
print(" 1. Run: sk index build --all")
print(" Fallbacks: macOS/Linux `python3 ~/.copilot/tools/build-session-index.py --all`;")
print(
' Windows PowerShell `python "$env:USERPROFILE\\.copilot\\tools\\build-session-index.py" --all`'
)
print(" 2. (Optional) Configure sync gateway URL: sk sync config --setup <https://gateway>")
print(" Default provider rollout recommendation: Neon (Postgres) + Railway (thin gateway host).")
print(
" 3. Trend Scout automation: keep trend-scout.py in scheduled/manual flow (trend-scout.yml), not preToolUse/postToolUse hooks."
)
print(" 4. Customize for your project:")
print(" /session-knowledge-creator — Generate project-specific knowledge skill")
print(" /skill-creator — Create or improve project-specific skills")
if not args.no_tentacle:
print(" /tentacle-creator — Generate project-specific tentacle skill")
if args.profile:
print(f" Edit .github/hooks/*.py — Customize installed {args.profile} hooks")
else:
print(" --profile python|typescript|mobile|fullstack — Install hook bundle")
print()
print("How it works:")
print(" 📋 .instructions.md → auto-injected into EVERY AI context (enforcement)")
print(" 🔧 Creator skills → run once to customize skills for your project")
print(" 🧠 briefing.py → AI runs before each task (past mistakes/patterns)")
print(" 📝 learn.py → AI records after each task (accumulate knowledge)")
if not args.no_tentacle:
print(" 🐙 tentacle.py → Multi-agent orchestration with scoped contexts")
# Register project for auto-update propagation (always, even if no changes this run).
# dry-run is excluded so the registry only contains projects with real deployments.
if not args.dry_run:
_register_project(project_root)
if __name__ == "__main__":
main()