-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
3573 lines (3069 loc) · 133 KB
/
install.py
File metadata and controls
3573 lines (3069 loc) · 133 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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
install.py — Smart installer for session knowledge tools
Usage:
python install.py # Auto-detect and show status
python install.py --install-sk # Install/refresh sk launcher in ~/.copilot/bin/
python install.py --uninstall-launcher # Remove only the managed sk launcher
python install.py --deploy-skill # Deploy SKILL.md to current project
python install.py --deploy-global-skills # Deploy all skills to ~/.copilot/skills/
python install.py --deploy-hooks # Deploy hooks.json to ~/.copilot/hooks/
python install.py --deploy-instructions # Deploy global instructions to ~/.github/
python install.py --inject-global # Add session-knowledge to global copilot-instructions
python install.py --install-git-hooks # Install pre-commit/pre-push into current repo's .git/hooks/
python install.py --lock-hooks # Lock hooks with OS immutable flags (tamper protection)
python install.py --repair-hooks # Clear hooks-tampered marker (no sudo required)
python install.py --unlock-hooks # Unlock hooks for updates
python install.py --doctor [--manifest] # Verify install health / manifest drift
python install.py --test # Run self-test
python install.py --uninstall # Remove installed files
python install.py --help # Show this help
Windows Task Scheduler (WBS-006):
python install.py --setup-watch-task # Register sk watch ONLOGON scheduled task
python install.py --setup-watch-task --dry-run # Preview without registering
python install.py --remove-watch-task # Remove the scheduled task
sk Launcher (managed cross-platform):
--install-sk creates ~/.copilot/bin/sk (POSIX) or ~/.copilot/bin/sk.cmd (Windows)
and idempotently adds ~/.copilot/bin to your shell profile PATH.
After install: open a new shell (or 'source ~/.zshrc') then type 'sk --help'.
auto-update-tools.py calls --install-sk --quiet whenever sk.py or install.py changes.
Tamper Protection:
--lock-hooks sets OS-level immutable flags on all hook scripts + hooks.json:
macOS: chflags uchg (user immutable, no sudo needed)
Linux: chattr +i (requires sudo)
Windows: attrib +R (read-only, weaker)
Also generates SHA256 manifest checked by verify-integrity.py at session start.
"""
import hashlib
import importlib.util
import json
import os
import platform
import re
import shutil
import sqlite3
import subprocess
import sys
import textwrap
from datetime import datetime, timezone
from importlib import metadata
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import url2pathname
# ---------------------------------------------------------------------------
# Windows console encoding fix (same pattern as other tools)
# ---------------------------------------------------------------------------
if os.name == "nt":
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# ---------------------------------------------------------------------------
# Atomic write helper (P1-5, 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
def _atomic_write_bytes(path: Path, content: bytes) -> None:
"""Write bytes to path atomically via temp + os.replace."""
tmp = path.with_suffix(path.suffix + ".tmp")
try:
tmp.write_bytes(content)
os.replace(str(tmp), str(path))
except Exception:
try:
tmp.unlink(missing_ok=True)
except Exception:
pass
raise
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
HOME = Path.home()
def _real_home():
"""Get real user home, even under sudo (where Path.home() returns /root)."""
sudo_user = os.environ.get("SUDO_USER")
if sudo_user and os.name != "nt":
import pwd
try:
return Path(pwd.getpwnam(sudo_user).pw_dir)
except KeyError:
pass
return HOME
# 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.
from host_manifest import ( # noqa: E402
CLAUDE_DIR,
COPILOT_DIR,
HOST_INSTRUCTION_FILES,
HOST_SKILL_SUBPATHS,
)
from host_manifest import (
HOST_DIRS as KNOWN_HOSTS,
)
TOOLS_DIR = COPILOT_DIR / "tools"
SESSION_STATE = COPILOT_DIR / "session-state"
DB_PATH = SESSION_STATE / "knowledge.db"
SKILLS_SRC = COPILOT_DIR / "skills" / "session-knowledge" / "SKILL.md"
GLOBAL_INSTRUCTIONS = HOME / ".github" / "copilot-instructions.md"
LOCK_FILE = SESSION_STATE / ".watcher.lock"
# Registry of projects that have received a skill deployment via install.py
# --deploy-skill or 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).
REGISTRY_PATH = 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
# Resolve the repo's templates/ directory (works when run from repo or ~/.copilot/tools/)
_SCRIPT_DIR = Path(__file__).resolve().parent
_REPO_SKILL_MD = _SCRIPT_DIR / "templates" / "SKILL.md"
TOOL_FILES = [
"build-session-index.py",
"extract-knowledge.py",
"query-session.py",
"briefing.py",
"clarify.py",
"constitution.py",
"specify.py",
"task.py",
"watch-sessions.py",
"learn.py",
"embed.py",
"sync_enqueue.py",
"agent_adapters.py",
"aider-adapter.py",
"windsurf-adapter.py",
"claude-adapter.py",
"context-blocks.py",
"cron-tasks.py",
"sync-knowledge.py",
"sync-config.py",
"sync-daemon.py",
"sync-status.py",
"sync-gateway.py",
"generate-summary.py",
"events.py",
"sk.py",
"skill-catalog.py",
"preset-manager.py",
"install.py",
"statusline.py",
"harness-init.py",
"doctor.py",
"code-search.py",
"code-index.py",
"code-embed.py",
"cost-analytics.py",
"session-compare.py",
"session-compact.py",
"repo-map.py",
"coverage.py",
"entity-extract.py",
"trace.py",
"knowledge-broadcast.py",
"curate.py",
"knowledge-import.py",
"tui.py",
]
SUPPORT_FILES = [
"README.md",
"KNOWLEDGE.md",
"embedding-config.json",
"pyproject.toml",
]
SUPPORT_DIRS = [
"skills",
]
# Managed sk launcher directory (cross-platform: ~/.copilot/bin/)
SK_LAUNCHER_DIR = HOME / ".copilot" / "bin"
_SK_PATH_MARKER_START = "# >>> session-knowledge sk launcher >>>"
_SK_PATH_MARKER_END = "# <<< session-knowledge sk launcher <<<"
_CONTEXT_START_RE = re.compile(r"^\s*<!--\s*(?P<block>[^\r\n<>]+?)\s+SK START\s*-->\s*$")
# ---------------------------------------------------------------------------
# Markers
# ---------------------------------------------------------------------------
OK = "\u2713" # ✓
FAIL = "\u2717" # ✗
INFO = "\u2139" # ℹ
WARN = "\u26a0" # ⚠
# ===================================================================
# Helpers
# ===================================================================
def _tilde(p: Path) -> str:
"""Show path relative to ~ for readability."""
try:
return "~/" + p.relative_to(HOME).as_posix()
except ValueError:
return p.as_posix()
def _count_scripts(d: Path) -> int:
"""Count .py files in a directory."""
if not d.is_dir():
return 0
return sum(1 for f in d.iterdir() if f.suffix == ".py")
def _support_dir_files(base_dir: Path) -> list[Path]:
"""Return managed files under support directories."""
files: list[Path] = []
for rel_dir in SUPPORT_DIRS:
root = base_dir / rel_dir
if not root.is_dir():
continue
files.extend(sorted(p for p in root.rglob("*") if p.is_file()))
return files
def _is_deployable_skill_asset(rel_path: Path) -> bool:
"""Return False for generated artifacts that should not deploy with skills."""
return "__pycache__" not in rel_path.parts and rel_path.suffix != ".pyc"
def _sync_skill_file(src: Path, dst: Path) -> bool:
"""Copy a skill file atomically when content differs."""
content = src.read_bytes()
if dst.is_file() and dst.read_bytes() == content:
return False
dst.parent.mkdir(parents=True, exist_ok=True)
_atomic_write_bytes(dst, content)
return True
def _prune_empty_dir(root: Path) -> None:
"""Remove an empty directory tree from the bottom up."""
if not root.is_dir():
return
for child in sorted((p for p in root.rglob("*") if p.is_dir()), key=lambda p: len(p.parts), reverse=True):
try:
child.rmdir()
except OSError:
pass
try:
root.rmdir()
except OSError:
pass
def _replace_support_dir(src_dir: Path, dst_dir: Path) -> None:
"""Refresh a bundled support directory via staged same-volume renames."""
staging_dir = dst_dir.with_name(dst_dir.name + ".new")
backup_dir = dst_dir.with_name(dst_dir.name + ".old")
shutil.rmtree(staging_dir, ignore_errors=True)
shutil.rmtree(backup_dir, ignore_errors=True)
shutil.copytree(str(src_dir), str(staging_dir))
try:
if dst_dir.exists():
os.replace(str(dst_dir), str(backup_dir))
os.replace(str(staging_dir), str(dst_dir))
except Exception:
shutil.rmtree(staging_dir, ignore_errors=True)
if backup_dir.exists() and not dst_dir.exists():
os.replace(str(backup_dir), str(dst_dir))
raise
shutil.rmtree(backup_dir, ignore_errors=True)
MANAGED_MANIFEST_VERSION = "1.0.0"
def _managed_manifest_path() -> Path:
"""Return the general installer manifest path (~/.copilot/manifest.json)."""
return HOME / ".copilot" / "manifest.json"
def _manifest_root() -> Path:
"""Return the root directory all manifest entries are relative to."""
return HOME.resolve()
def _manifest_timestamp() -> str:
"""Return the current UTC timestamp for manifest metadata."""
return datetime.now(timezone.utc).isoformat()
def _empty_managed_manifest() -> dict:
"""Return the canonical empty installer-manifest payload."""
return {
"files": {},
"version": MANAGED_MANIFEST_VERSION,
"installed_at": _manifest_timestamp(),
}
def _load_managed_manifest() -> dict | None:
"""Load ~/.copilot/manifest.json or return None when absent/invalid."""
manifest_path = _managed_manifest_path()
if not manifest_path.is_file():
return None
try:
data = json.loads(manifest_path.read_text(encoding="utf-8"))
except Exception:
return None
if not isinstance(data, dict):
return None
raw_files = data.get("files")
if not isinstance(raw_files, dict):
return None
files = {key: value for key, value in raw_files.items() if isinstance(key, str) and isinstance(value, str)}
version = data.get("version") if isinstance(data.get("version"), str) else MANAGED_MANIFEST_VERSION
installed_at = data.get("installed_at") if isinstance(data.get("installed_at"), str) else _manifest_timestamp()
return {
"files": files,
"version": version,
"installed_at": installed_at,
}
def _path_has_symlink(path: Path, root: Path) -> bool:
"""Return True when any existing component between root and path is a symlink."""
try:
rel = path.relative_to(root)
except ValueError:
return True
probe = root
for part in rel.parts:
probe = probe / part
if probe.exists() and probe.is_symlink():
return True
return False
def _manifest_key_to_path(key: str) -> Path | None:
"""Resolve a manifest key to a concrete path under HOME, rejecting unsafe keys."""
if not isinstance(key, str) or not key.strip():
return None
rel = Path(key)
if rel.is_absolute():
return None
if not rel.parts or any(part in ("", ".", "..") for part in rel.parts):
return None
root = _manifest_root()
candidate = root / rel
if _path_has_symlink(candidate, root):
return None
return candidate
def _path_to_manifest_key(path: Path) -> str | None:
"""Convert an on-disk file path into a safe manifest key relative to HOME."""
expanded = path.expanduser()
if expanded.exists() and expanded.is_symlink():
return None
try:
candidate = expanded.resolve(strict=False)
except OSError:
candidate = expanded.absolute()
root = _manifest_root()
try:
rel = candidate.relative_to(root)
except ValueError:
return None
if not rel.parts or any(part in ("", ".", "..") for part in rel.parts):
return None
if _path_has_symlink(candidate, root):
return None
return rel.as_posix()
def _sha256_file(path: Path) -> str:
"""Return the SHA-256 digest for a file."""
digest = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _write_managed_manifest(manifest: dict) -> None:
"""Persist the installer manifest atomically, deleting it when empty."""
manifest_path = _managed_manifest_path()
files = manifest.get("files", {})
if not files:
manifest_path.unlink(missing_ok=True)
return
manifest_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"files": dict(sorted(files.items())),
"version": MANAGED_MANIFEST_VERSION,
"installed_at": _manifest_timestamp(),
}
_atomic_write_text(manifest_path, json.dumps(payload, indent=2, sort_keys=True))
def _record_managed_paths(paths: list[Path], *, quiet: bool = False) -> int:
"""Record manifest entries for files managed by install.py."""
manifest = _load_managed_manifest() or _empty_managed_manifest()
recorded = 0
for path in paths:
if not path.is_file():
continue
key = _path_to_manifest_key(path)
if key is None:
if not quiet:
print(f" {WARN} Manifest skip (unsafe or outside HOME): {_tilde(path)}")
continue
manifest["files"][key] = _sha256_file(path)
recorded += 1
if recorded:
_write_managed_manifest(manifest)
return recorded
def _forget_managed_paths(paths: list[Path]) -> None:
"""Remove manifest entries for paths no longer managed."""
manifest = _load_managed_manifest()
if not manifest:
return
changed = False
for path in paths:
key = _path_to_manifest_key(path)
if key and key in manifest["files"]:
manifest["files"].pop(key, None)
changed = True
if changed:
_write_managed_manifest(manifest)
def _manifest_drift_report() -> tuple[list[str], list[str], list[str], int]:
"""Return (missing, modified, unsafe, tracked_count) for the installer manifest."""
manifest = _load_managed_manifest()
if not manifest:
return [], [], [], 0
missing: list[str] = []
modified: list[str] = []
unsafe: list[str] = []
for key, expected_hash in manifest.get("files", {}).items():
path = _manifest_key_to_path(key)
if path is None:
unsafe.append(key)
continue
if not path.exists():
missing.append(key)
continue
if path.is_symlink() or not path.is_file():
unsafe.append(key)
continue
actual_hash = _sha256_file(path)
if actual_hash != expected_hash:
modified.append(key)
tracked = len(manifest.get("files", {}))
return missing, modified, unsafe, tracked
def _partition_manifest_removals(paths: list[Path]) -> tuple[list[Path], list[Path], list[Path]]:
"""Split paths into (safe_to_remove, modified, untracked_or_unsafe)."""
manifest = _load_managed_manifest()
tracked = manifest.get("files", {}) if manifest else {}
removable: list[Path] = []
modified: list[Path] = []
untracked: list[Path] = []
for path in paths:
if not path.is_file():
continue
key = _path_to_manifest_key(path)
expected = tracked.get(key, "") if key else ""
if not expected:
untracked.append(path)
continue
try:
actual = _sha256_file(path)
except OSError:
untracked.append(path)
continue
if actual == expected:
removable.append(path)
else:
modified.append(path)
return removable, modified, untracked
def _remove_managed_context_blocks_from_text(text: str) -> tuple[str, int]:
"""Remove all managed `<!-- ... SK START -->` blocks from text."""
lines = text.splitlines(keepends=True)
if not lines:
return text, 0
output: list[str] = []
removed = 0
idx = 0
while idx < len(lines):
match = _CONTEXT_START_RE.match(lines[idx].rstrip("\r\n"))
if not match:
output.append(lines[idx])
idx += 1
continue
block_id = match.group("block")
end_marker = f"<!-- {block_id} SK END -->"
end_idx = None
for probe in range(idx + 1, len(lines)):
if lines[probe].rstrip("\r\n") == end_marker:
end_idx = probe
break
if end_idx is None:
output.append(lines[idx])
idx += 1
continue
removed += 1
idx = end_idx + 1
if output and idx < len(lines) and not output[-1].strip() and not lines[idx].strip():
idx += 1
if not output:
while idx < len(lines) and not lines[idx].strip():
idx += 1
if removed and output and all(not line.strip() for line in output):
output = []
return "".join(output), removed
def _remove_managed_context_blocks_from_file(path: Path, *, quiet: bool = False) -> bool:
"""Strip all managed context blocks from a single instruction file."""
if not path.is_file():
return False
original = path.read_text(encoding="utf-8")
updated, removed = _remove_managed_context_blocks_from_text(original)
if removed <= 0 or updated == original:
return False
_atomic_write_text(path, updated)
if not quiet:
print(f" {OK} Removed {removed} managed context block(s) from {_tilde(path)}")
return True
def _managed_context_targets(project_root: Path) -> list[Path]:
"""Return unique project instruction-file targets that may hold managed blocks."""
targets: list[Path] = []
seen: set[str] = set()
for rel in HOST_INSTRUCTION_FILES.values():
key = str(rel)
if key in seen:
continue
seen.add(key)
targets.append(project_root / rel)
return targets
def _remove_registered_project_context_blocks(*, quiet: bool = False) -> int:
"""Remove managed context blocks from every registered project instruction file."""
changed = 0
for raw_root in _load_project_registry():
project_root = Path(raw_root).expanduser()
if not project_root.is_dir():
continue
for target in _managed_context_targets(project_root):
if _remove_managed_context_blocks_from_file(target, quiet=quiet):
changed += 1
return changed
def _file_url_to_path(url: str) -> Path | None:
"""Convert a file:// URL from direct_url.json to a local path."""
if not url:
return None
parsed = urlparse(url)
if parsed.scheme != "file":
return None
path_str = url2pathname(parsed.path)
if parsed.netloc and parsed.netloc not in ("", "localhost"):
path_str = f"//{parsed.netloc}{path_str}"
if not path_str:
return None
return Path(path_str).expanduser().resolve()
def _matching_editable_install_source_dir(target_dir: Path | None = None) -> Path | None:
"""Return the editable-install source dir when it matches this checkout."""
target = (target_dir or TOOLS_DIR).resolve()
try:
distributions = metadata.distributions()
except Exception:
return None
for dist in distributions:
dist_name = (dist.metadata.get("Name") or "").strip().lower().replace("_", "-")
if dist_name != "copilot-session-knowledge":
continue
direct_url_text = dist.read_text("direct_url.json")
if not direct_url_text:
continue
try:
direct_url = json.loads(direct_url_text)
except Exception:
continue
if not direct_url.get("dir_info", {}).get("editable"):
continue
source_dir = _file_url_to_path(direct_url.get("url", ""))
if source_dir == target:
return source_dir
return None
def _pip_uninstall_command() -> str:
"""Command that removes the editable `sk` console entrypoint cleanly."""
return f"{sys.executable} -m pip uninstall copilot-session-knowledge"
def _git_hook_install_text(src_text: str) -> str:
"""Adjust Python git-hook shebangs for the host's launcher naming."""
if os.name == "nt" and src_text.startswith("#!/usr/bin/env python3\n"):
return "#!/usr/bin/env python\n" + src_text.split("\n", 1)[1]
return src_text
def _db_counts() -> dict:
"""Read document / knowledge-entry / relation counts from the DB."""
result = {"documents": 0, "entries": 0, "relations": 0, "sessions": 0}
if not DB_PATH.is_file():
return result
try:
db = sqlite3.connect(str(DB_PATH))
_ALLOWED_TABLES = {"documents", "knowledge_entries", "knowledge_relations", "sessions"}
for table, key in [
("documents", "documents"),
("knowledge_entries", "entries"),
("knowledge_relations", "relations"),
("sessions", "sessions"),
]:
assert table in _ALLOWED_TABLES, f"Unexpected table: {table}"
try:
result[key] = db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
except sqlite3.OperationalError:
pass
db.close()
except Exception:
pass
return result
def _watcher_running() -> bool:
"""Check if the session watcher is currently running."""
if not LOCK_FILE.is_file():
return False
try:
raw = LOCK_FILE.read_text(encoding="utf-8").strip()
# Handle both formats: bare PID ("9119") and JSON ({"pid": 9119})
try:
data = json.loads(raw)
except (json.JSONDecodeError, ValueError):
return False
if isinstance(data, int):
pid = data
elif isinstance(data, dict):
pid = data.get("pid")
else:
return False
if pid is None:
return False
if os.name == "nt":
import ctypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(0x100000, False, int(pid))
if handle:
kernel32.CloseHandle(handle)
return True
return False
else:
os.kill(int(pid), 0)
return True
except (OSError, ValueError, PermissionError, TypeError):
return False
def _git_root() -> "Path | None":
"""Find the git root from cwd."""
try:
r = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
timeout=5,
)
if r.returncode == 0:
return Path(r.stdout.strip())
except Exception:
pass
return None
def _fts_working() -> bool:
"""Quick FTS5 probe."""
if not DB_PATH.is_file():
return False
try:
db = sqlite3.connect(str(DB_PATH))
rows = db.execute("SELECT COUNT(*) FROM knowledge_fts WHERE knowledge_fts MATCH 'test OR error'").fetchone()
db.close()
return rows[0] >= 0
except Exception:
return False
# ===================================================================
# SK Launcher: managed cross-platform sk command
# ===================================================================
def _sk_launcher_script_paths() -> "list[Path]":
"""Return platform-appropriate launcher file paths under SK_LAUNCHER_DIR."""
if os.name == "nt":
return [SK_LAUNCHER_DIR / "sk.cmd"]
return [SK_LAUNCHER_DIR / "sk"]
def _launcher_backup_path(script: Path) -> Path:
"""Return the rollback copy path for a replaced launcher."""
return script.with_name(script.name + ".backup")
def _sk_launcher_managed_paths() -> "list[Path]":
"""Return existing managed launcher files, including rollback backups."""
paths: list[Path] = []
for script in _sk_launcher_script_paths():
for candidate in (script, _launcher_backup_path(script)):
if candidate.is_file():
paths.append(candidate)
return paths
def _sk_launcher_content() -> str:
"""Return the launcher script body for the current platform.
WBS-004: prefer py -3, fallback to python3/python on Windows.
WBS-005: honor SK_TOOLS_DIR env var on both platforms.
"""
if os.name == "nt":
# WBS-005: honor SK_TOOLS_DIR; WBS-004: prefer py -3, fallback to python3/python
python_exe = str(Path(sys.executable))
return (
"@echo off\r\n"
"setlocal\r\n"
'set "TOOLS_DIR=%USERPROFILE%\\.copilot\\tools"\r\n'
'if defined SK_TOOLS_DIR set "TOOLS_DIR=%SK_TOOLS_DIR%"\r\n'
f'set "PYTHON_EXE={python_exe}"\r\n'
'if exist "%PYTHON_EXE%" (\r\n'
' "%PYTHON_EXE%" "%TOOLS_DIR%\\sk.py" %*\r\n'
" exit /b\r\n"
")\r\n"
"where py >nul 2>&1\r\n"
"if not errorlevel 1 (\r\n"
' py -3 "%TOOLS_DIR%\\sk.py" %*\r\n'
" exit /b\r\n"
")\r\n"
"where python3 >nul 2>&1\r\n"
"if not errorlevel 1 (\r\n"
' python3 "%TOOLS_DIR%\\sk.py" %*\r\n'
" exit /b\r\n"
")\r\n"
"where python >nul 2>&1\r\n"
"if not errorlevel 1 (\r\n"
' python "%TOOLS_DIR%\\sk.py" %*\r\n'
" exit /b\r\n"
")\r\n"
"echo sk launcher could not find py, python3, or python on PATH. 1>&2\r\n"
"exit /b 1\r\n"
)
# POSIX: WBS-005: honor SK_TOOLS_DIR, fallback to $HOME/.copilot/tools
return '#!/bin/sh\nTOOLS_DIR="${SK_TOOLS_DIR:-$HOME/.copilot/tools}"\nexec python3 "$TOOLS_DIR/sk.py" "$@"\n'
def _shell_profiles() -> "list[Path]":
"""Return candidate POSIX shell profile files for PATH injection."""
return [
HOME / ".bash_profile",
HOME / ".bashrc",
HOME / ".zprofile",
HOME / ".zshrc",
HOME / ".profile",
]
def _preferred_shell_profile() -> Path:
"""Pick the best profile file to create when none already exist."""
shell_name = Path(os.environ.get("SHELL", "")).name.lower()
if "zsh" in shell_name:
return HOME / ".zshrc"
if "bash" in shell_name:
return HOME / ".bash_profile"
return HOME / ".profile"
def _build_sk_path_block() -> str:
"""Return the expected sk launcher PATH export block for the current launcher dir.
WBS-010: single source-of-truth for the managed block content so both
_inject_launcher_path and tests can compare against it precisely.
"""
bin_str = str(SK_LAUNCHER_DIR)
return f'{_SK_PATH_MARKER_START}\nexport PATH="{bin_str}:$PATH"\n{_SK_PATH_MARKER_END}\n'
def _inject_launcher_path(quiet: bool = False) -> None:
"""Idempotently add ~/.copilot/bin to existing shell profiles (POSIX only).
WBS-010: atomic write + precise idempotency — never duplicates the block,
never corrupts the profile on write failure (uses _atomic_write_text).
Updates an existing block when the launcher dir has changed.
"""
bin_str = str(SK_LAUNCHER_DIR)
expected_block = _build_sk_path_block()
profiles = [profile for profile in _shell_profiles() if profile.exists()]
if not profiles:
profiles = [_preferred_shell_profile()]
for profile in profiles:
if not profile.parent.exists():
profile.parent.mkdir(parents=True, exist_ok=True)
content = profile.read_text(encoding="utf-8") if profile.exists() else ""
if _SK_PATH_MARKER_START in content:
# Marker found: check whether the block content is already correct.
if expected_block in content:
if not quiet:
print(f" {INFO} sk PATH already in {_tilde(profile)}")
else:
# Block is stale (launcher dir changed): replace it atomically.
cleaned, _ = _remove_launcher_path_block_from_text(content)
base = cleaned.rstrip("\n")
new_content = (base + "\n\n" + expected_block) if base.strip() else expected_block
_atomic_write_text(profile, new_content)
if not quiet:
print(f" {OK} Updated sk launcher PATH in {_tilde(profile)}")
continue
if bin_str in content:
# User has manually added the path without our managed markers — leave it alone.
if not quiet:
print(f" {INFO} sk PATH already in {_tilde(profile)} (without managed markers)")
continue
# Path not present at all: append the managed block atomically.
new_content = expected_block if not content else content.rstrip("\n") + "\n\n" + expected_block
_atomic_write_text(profile, new_content)
if not quiet:
print(f" {OK} Added sk launcher PATH to {_tilde(profile)}")
def _remove_launcher_path_block_from_text(text: str) -> tuple[str, int]:
"""Remove the managed sk launcher PATH block without leaving an injected blank line."""
block_re = re.escape(_SK_PATH_MARKER_START) + r".*?" + re.escape(_SK_PATH_MARKER_END) + r"\n?"
updated, removed = re.subn(r"\n" + block_re, "", text, flags=re.DOTALL)
if removed:
return updated, removed
return re.subn(block_re, "", text, flags=re.DOTALL)
def _inject_launcher_path_windows(quiet: bool = False) -> bool:
"""Try adding ~/.copilot/bin to user PATH in Windows Registry.
WBS-007: uses canonical 'Path' key and minimal KEY_READ | KEY_SET_VALUE access.
WBS-001: sends WM_SETTINGCHANGE after actual mutation; no broadcast on no-op.
"""
bin_str = str(SK_LAUNCHER_DIR)
try:
import winreg
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
"Environment",
0,
winreg.KEY_READ | winreg.KEY_SET_VALUE, # WBS-007: minimal rights
)
try:
cur_path, _ = winreg.QueryValueEx(key, "Path") # WBS-007: canonical "Path"
except FileNotFoundError:
cur_path = ""
entries = [entry for entry in cur_path.split(";") if entry.strip()]
launcher_key = _windows_path_entry_key(bin_str)
if not any(_windows_path_entry_key(entry) == launcher_key for entry in entries):
new_path = f"{bin_str};{cur_path}" if cur_path else bin_str
winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path) # WBS-007
if not quiet:
print(f" {OK} Added sk launcher dir to Windows user PATH")
winreg.CloseKey(key)
_broadcast_windows_path_change(quiet=quiet) # WBS-001
return True
else:
if not quiet:
print(f" {INFO} sk launcher dir already in Windows user PATH")
winreg.CloseKey(key)
except Exception as exc:
if not quiet:
print(f" {WARN} Could not update Windows PATH: {exc}")
print(f" Add manually: {bin_str}")
return False
def _remove_launcher_path_windows(quiet: bool = False) -> bool:
"""Try removing ~/.copilot/bin from the Windows user PATH.
WBS-007: uses canonical 'Path' key and minimal KEY_READ | KEY_SET_VALUE access.
"""
bin_str = str(SK_LAUNCHER_DIR)
try:
import winreg