Repository navigation
Expand file tree
/
Copy pathbootstrap.py
More file actions
3381 lines (2915 loc) · 123 KB
/
Copy pathbootstrap.py
File metadata and controls
3381 lines (2915 loc) · 123 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
"""Pegasus bootstrap v33.3 — cross-platform, checksum-guarded, backup-first.
Writes tooling, hooks, skills, adapters, contracts and the capability scaffold;
consolidates the version; reconciles the Makefile; prunes or regenerates unwired
root files; wires hooksPath; provisions pyyaml; runs the sequence and verifies it.
v33.3 removes the possibility of the two cap lints disagreeing quietly:
* scripts/capreg.py is the single AST-based parser; both lints import it
* modules_lint now fails on an orphan cap, the same condition caps_matrix fails on
* modules_lint sweeps the whole enum, so an unreferenced orphan is caught too
* modules_lint also fails on a phantom `provides` entry (a typo in the registry)
* caps-consistency asserts the two lints return the same verdict, and is a gate
* build/caps_orphans.allow waives an orphan deliberately, with a reason
* build/caps_baseline.json records provider counts; an edge drop is reported
* the matrix is emitted as JSON as well as markdown, so CI need not scrape prose
Self-check before touching anything (64 assertions, 16 of them negative):
python bootstrap.py --self-test
Usage:
python bootstrap.py # normal
python bootstrap.py --force # overwrite locally modified tooling
python bootstrap.py --no-prune # leave root files in place
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
STATE = Path(".bootstrap-state")
TOOLING = [
"scripts/handoff.py", "scripts/require.py", "scripts/emit_agents.py",
"scripts/bootstrap-check.py", "scripts/verify.py", "scripts/openapi_snapshot.py",
"scripts/module_new.py", "scripts/parity.py", "scripts/version_check.py",
"scripts/modules_lint.py", "scripts/audit_derive.py", "scripts/caps_matrix.py",
"scripts/risk_lint.py", "scripts/no_platform_branch.py", "scripts/capability_check.py",
"scripts/capreg.py", "scripts/caps_consistency.py",
"pegasus/tests/contract/test_agents.py",
".githooks/pre-commit", ".githooks/pre-push", ".githooks/commit-msg",
]
GATES = {f"G{i}" for i in range(1, 25)}
MANAGED_BEGIN = "# >>> pegasus bootstrap managed targets (regenerated) >>>"
MANAGED_END = "# <<< pegasus bootstrap managed targets <<<"
PYRESOURCES = ("version.txt", "version-web.txt")
RESOURCE_DEST = Path("packaging/pyinstaller")
VERSION_FILE = Path("pegasus/VERSION")
SEMVER = re.compile(r"(?:filevers|prodvers)\s*=\s*\(\s*(\d+),\s*(\d+),\s*(\d+)")
STRVER = re.compile(r"StringStruct\('(?:FileVersion|ProductVersion)',\s*'([0-9][0-9.]*)'\)")
TRIPLE = re.compile(r"^\d+\.\d+\.\d+$")
PRUNE: list[tuple[str, str, str]] = [
("oracle.py", "DELETE", "dist leg is print('PASS'); superseded by pcap_engine"),
("phase_engine.py", "DELETE", "can_enter compares a serial to the literal '*'"),
("blast_radius_estimator.py", "DELETE", "superseded by harness blast classes"),
("snapshot_before_mutate.py", "DELETE", "superseded by harness quarantine"),
("shadow_deploy.py", "DELETE", "superseded by harness dry-run"),
("idempotent_wrapper.py", "DELETE", "superseded by control/undo"),
("promotion.py", "DELETE", "no caller; superseded by gate G13"),
("mutation.py", "DELETE", "superseded by harness mutators"),
("self_healing.py", "DELETE", "no caller; superseded by control/rollback"),
("observability_trace.py", "DELETE", "superseded by audit log"),
("test_all.py", "DELETE", "superseded by pegasus/tests tiers"),
("smoke_manual.py", "DELETE", "superseded by make preflight"),
("count_repos.py", "DELETE", "one-shot; superseded by make map"),
("find_repos.py", "DELETE", "one-shot; superseded by make map"),
("feature_inventory.py", "DELETE", "one-shot; superseded by make parity"),
("build_final.log", "DELETE", "build transcript; read by no target"),
(".openfable-skills", "REGENERATE", "re-emitted as a generated adapter"),
(".zfable-skills", "REGENERATE", "re-emitted as a generated adapter"),
("pegasus_web.py", "ARCHIVE", "moves to pegasus/ui/api/app.py in P3b"),
("verify_blob.py", "ARCHIVE", "merges into scripts/verify.py in P3c"),
("verify_integration.py", "ARCHIVE", "merges into scripts/verify.py in P3c"),
("setup_init.py", "ARCHIVE", "merges into pegasus/core in P5"),
("setup_wizard_first_run.py", "ARCHIVE", "merges into pegasus/core in P5"),
("knowledge_db.py", "ARCHIVE", "merges into pegasus/modules/memory in P4"),
("target_manifest.schema.json", "ARCHIVE", "moves to pegasus/modules/journal in P4"),
("create_release.sh", "ARCHIVE", "moves to scripts/ in P7"),
("release_v3_notes.md", "ARCHIVE", "moves to docs/releases/ in P8"),
("release_v3_1_notes.md", "ARCHIVE", "moves to docs/releases/ in P8"),
("README_BUNDLE.md", "ARCHIVE", "merges into README.md in P8"),
("Pegasus-Web.spec", "ARCHIVE", "moves to packaging/pyinstaller/web.spec in P7"),
("fix_inits.py", "MOVE", "belongs in scripts/"),
("benchmark_multi.py", "MOVE", "belongs in scripts/"),
("cloud_deploy.py", "MOVE", "belongs in scripts/"),
("pegasus.icns", "MOVE", "belongs in assets/icons/"),
("pegasus.ico", "MOVE", "belongs in assets/icons/"),
]
MOVE_DEST = {
"fix_inits.py": "scripts/fix_inits.py",
"benchmark_multi.py": "scripts/benchmark_multi.py",
"cloud_deploy.py": "scripts/cloud_deploy.py",
"pegasus.icns": "assets/icons/pegasus.icns",
"pegasus.ico": "assets/icons/pegasus.ico",
}
def say(msg: str) -> None:
print(f"\033[1;36m{msg}\033[0m" if os.name != "nt" else msg)
def die(msg: str, code: int = 1) -> None:
print(f"ERROR: {msg}", file=sys.stderr)
sys.exit(code)
def have(exe: str) -> bool:
return shutil.which(exe) is not None
def is_admin() -> bool:
if os.name == "nt":
try:
import ctypes
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
return hasattr(os, "geteuid") and os.geteuid() == 0
def privileged(cmd: list[str]) -> list[str]:
if is_admin() or os.name == "nt":
return cmd
if have("sudo"):
return ["sudo"] + cmd
return cmd
def run(cmd: list[str], check: bool = False) -> tuple[int, str]:
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
except (OSError, subprocess.TimeoutExpired) as exc:
return 1, str(exc)
out = (proc.stdout or "") + (proc.stderr or "")
if check and proc.returncode != 0:
die(f"{' '.join(cmd)} failed:\n{out}")
return proc.returncode, out
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def write(rel: str, body: str, executable: bool = False) -> None:
path = Path(rel)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8", newline="\n")
if executable:
try:
os.chmod(path, 0o755)
except OSError:
pass
def stamp() -> str:
return subprocess.run(["git", "rev-parse", "--short", "HEAD"],
capture_output=True, text=True).stdout.strip() or "noh"
def tracked(rel: str) -> bool:
return run(["git", "ls-files", "--error-unmatch", "--", rel])[0] == 0
def git_remove(rel: str) -> None:
if tracked(rel):
run(["git", "rm", "-r", "-q", "-f", "--ignore-unmatch", "--", rel])
# --------------------------------------------------------------------- pyyaml
def pyyaml_available() -> bool:
try:
import yaml # noqa: F401
return True
except ImportError:
return False
def pyyaml_install() -> bool:
system = platform.system()
attempts: list[tuple[str, list[str]]] = [
("pip --user", [sys.executable, "-m", "pip", "install", "--user", "pyyaml"]),
("pip --user --break-system-packages",
[sys.executable, "-m", "pip", "install", "--user",
"--break-system-packages", "pyyaml"]),
]
if system == "Darwin":
if have("brew"):
attempts.append(("brew", ["brew", "install", "pyyaml"]))
elif system == "Linux":
if have("apt-get"):
attempts.append(("apt-get", privileged(["apt-get", "install", "-y", "python3-yaml"])))
if have("dnf"):
attempts.append(("dnf", privileged(["dnf", "install", "-y", "python3-pyyaml"])))
if have("zypper"):
attempts.append(("zypper", privileged(["zypper", "install", "-y", "python3-PyYAML"])))
if have("pacman"):
attempts.append(("pacman", privileged(["pacman", "-S", "--noconfirm", "python-yaml"])))
if have("apk"):
attempts.append(("apk", privileged(["apk", "add", "py3-yaml"])))
elif system == "Windows":
if have("py"):
attempts.append(("py -m pip", ["py", "-m", "pip", "install", "--user", "pyyaml"]))
if have("winget"):
attempts.append(("winget", ["winget", "install", "--id",
"Python.Python.3.12", "-e", "--silent"]))
for label, cmd in attempts:
say(f" trying {label}")
code, out = run(cmd)
if pyyaml_available():
say(f" pyyaml installed via {label}")
return True
if code != 0 and "already satisfied" not in out.lower():
print(f" {label} failed: {out.strip().splitlines()[-1:] or ''}")
return pyyaml_available()
def ensure_pyyaml() -> None:
say("0a/21 checking pyyaml")
if pyyaml_available():
say(" present")
return
say(f" missing — provisioning for {platform.system()}")
if not pyyaml_install():
die(
"could not install pyyaml automatically.\n"
" Debian/Ubuntu: sudo apt-get install -y python3-yaml\n"
" Fedora: sudo dnf install -y python3-pyyaml\n"
" Arch: sudo pacman -S python-yaml\n"
" Alpine: sudo apk add py3-yaml\n"
" macOS: brew install pyyaml\n"
" Windows: py -m pip install --user pyyaml\n"
" anywhere: python -m pip install --user pyyaml"
)
# ------------------------------------------------------------------- payloads
CAPREG_PY = '''#!/usr/bin/env python3
"""Single source of truth for the cap enum and the transport provider map.
Both modules_lint and caps_matrix import this. Neither parses core/caps.py
itself, so they cannot disagree about what a cap is — the shared module is the
agreement, not a convention.
AST, not regex: a docstring edit, a reformat, or a second enum cannot silently
change the parsed set. Parsing also proves the file is valid Python.
Exit conventions the lints share: 0 clean, 2 violation, 3 precondition.
"""
from __future__ import annotations
import ast
import json
from pathlib import Path
CAPS = Path("core/caps.py")
REGISTRY = Path("transports/registry.yaml")
ALLOW = Path("build/caps_orphans.allow")
BASELINE = Path("build/caps_baseline.json")
ENUM = "Cap"
class Precondition(Exception):
"""The tree is not shaped as expected; exit 3, not 2."""
def cap_values(caps: Path = CAPS) -> list[str]:
"""Every Cap member value, in declaration order."""
if not caps.exists():
raise Precondition(f"{caps} missing")
tree = ast.parse(caps.read_text(encoding="utf-8"), filename=str(caps))
for node in tree.body:
if isinstance(node, ast.ClassDef) and node.name == ENUM:
out = []
for stmt in node.body:
if (isinstance(stmt, ast.Assign)
and isinstance(stmt.value, ast.Constant)
and isinstance(stmt.value.value, str)):
out.append(stmt.value.value)
if not out:
raise Precondition(f"{ENUM} in {caps} has no string members")
return out
raise Precondition(f"no class {ENUM} in {caps}")
def providers(registry: Path = REGISTRY) -> dict[str, list[str]]:
"""cap value -> transport names advertising it."""
if not registry.exists():
raise Precondition(f"{registry} missing")
import yaml
rows = yaml.safe_load(registry.read_text(encoding="utf-8")) or []
if not isinstance(rows, list) or not rows:
raise Precondition(f"{registry} has no transports")
out: dict[str, list[str]] = {}
for row in rows:
if not isinstance(row, dict):
raise Precondition(f"{registry} has a non-mapping row")
name = row.get("name", "?")
for cap in row.get("provides") or []:
out.setdefault(cap, []).append(name)
return out
def allowlist(path: Path = ALLOW) -> dict[str, str]:
"""cap value -> reason. Blank lines and # comments ignored."""
if not path.exists():
return {}
out = {}
for line in path.read_text(encoding="utf-8").splitlines():
head, _, tail = line.partition("#")
cap = head.strip()
if cap:
out[cap] = tail.strip()
return out
def split_orphans(values, provided, allowed):
"""(blocking, waived). Waiving an absent cap is itself reported."""
orphans = [c for c in values if c not in provided]
waived = [c for c in orphans if c in allowed]
blocking = [c for c in orphans if c not in allowed]
stale = sorted(c for c in allowed if c not in orphans)
return blocking, waived, stale
def phantom_provides(values, provided) -> list[str]:
"""Caps a transport advertises but the enum does not define — a typo."""
known = set(values)
return sorted(c for c in provided if c not in known)
def load_baseline(path: Path = BASELINE) -> dict[str, int]:
if not path.exists():
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return {}
return data if isinstance(data, dict) else {}
def save_baseline(provided, path: Path = BASELINE) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps({k: len(v) for k, v in sorted(provided.items())}, indent=2) + "\\n",
encoding="utf-8")
def dropped_edges(baseline, provided) -> list[str]:
"""Caps whose provider count fell since the baseline was taken."""
return sorted(c for c, n in baseline.items() if len(provided.get(c, [])) < n)
'''
CAPS_CONSISTENCY_PY = '''#!/usr/bin/env python3
"""Assert modules_lint and caps_matrix reach the same verdict.
They share scripts/capreg.py, so a disagreement means one of them is not using
it. Exit 0 both pass, 2 both fail (agreement, red gate), 3 they disagree or the
tree is unshaped. A disagreement is always reported, never averaged.
"""
import subprocess
import sys
from pathlib import Path
LINT = Path("scripts/modules_lint.py")
MATRIX = Path("scripts/caps_matrix.py")
def verdict(script: Path) -> tuple[int, str]:
if not script.exists():
return 3, f"{script} missing"
proc = subprocess.run([sys.executable, str(script)],
capture_output=True, text=True)
return proc.returncode, (proc.stdout + proc.stderr).strip()
def main() -> int:
a, a_out = verdict(LINT)
b, b_out = verdict(MATRIX)
if a != b:
print("LINT DISAGREEMENT — the two parsers are not the same parser")
print(f" modules_lint -> {a}")
print(f" caps_matrix -> {b}")
for out in (a_out, b_out):
for line in out.splitlines()[-6:]:
print(f" {line}")
return 3
if a == 0:
print("both lints agree: clean")
return 0
print(f"both lints agree: violation (exit {a})")
for line in b_out.splitlines()[-8:]:
print(f" {line}")
return 2
if __name__ == "__main__":
sys.exit(main())
'''
HANDOFF_PY = '''#!/usr/bin/env python3
"""Extract the handoff section of docs/PLAN.md into docs/HANDOFF.md."""
import os, re, sys
from pathlib import Path
PLAN = Path("docs/PLAN.md")
OUT = Path("docs/HANDOFF.md")
HEAD = re.compile(r"^## " + os.environ.get("HANDOFF_SECTION", r"60\\."), re.M)
def extract() -> str:
text = PLAN.read_text(encoding="utf-8")
m = HEAD.search(text)
if not m:
sys.exit("PRECONDITION: handoff section not found in docs/PLAN.md")
body = text[m.start():].rstrip() + "\\n"
if len(body) < 200:
sys.exit("PRECONDITION: handoff section suspiciously short")
return body
def main() -> int:
body = extract()
if "--check" in sys.argv:
if not OUT.exists():
print("PRECONDITION: docs/HANDOFF.md missing", file=sys.stderr)
return 3
if OUT.read_text(encoding="utf-8") != body:
print("PRECONDITION: HANDOFF drifted from PLAN", file=sys.stderr)
return 3
print("handoff in sync")
return 0
OUT.write_text(body, encoding="utf-8")
print(f"wrote {OUT} ({len(body)} bytes)")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
REQUIRE_PY = '''#!/usr/bin/env python3
"""Phase precondition checker. Exit 3 on absence or drift. --lint validates."""
import hashlib, sys
from pathlib import Path
import yaml
PHASES = Path("build/phases.yaml")
REQUIRED = {"id", "gate", "revert"}
GATES = {f"G{i}" for i in range(1, 25)}
def die(msg, code=3):
print(f"PRECONDITION: {msg}", file=sys.stderr)
sys.exit(code)
def load():
if not PHASES.exists():
die(f"{PHASES} missing")
data = yaml.safe_load(PHASES.read_text(encoding="utf-8")) or {}
phases = data.get("phases")
if not isinstance(phases, list) or not phases:
die("phases.yaml has no phases list")
return phases
def lint(phases):
ids = [p.get("id") for p in phases]
if len(ids) != len(set(ids)):
die("duplicate phase id")
for p in phases:
missing = REQUIRED - set(p)
if missing:
die(f"{p.get('id', '?')}: missing {sorted(missing)}")
if p["gate"] not in GATES:
die(f"{p['id']}: unknown gate {p['gate']}")
produces = {x if isinstance(x, str) else x["path"] for x in p.get("produces", [])}
requires = {x["path"] for x in p.get("requires", [])}
if produces & requires:
die(f"{p['id']}: requires what it produces")
if p["id"] != "P0" and "docs/HANDOFF.md" not in requires:
die(f"{p['id']}: must require docs/HANDOFF.md")
order = {pid: i for i, pid in enumerate(ids)}
if "P8" not in order:
die("P8 missing")
for pid in ids:
if pid.startswith("R") and order[pid] < order["P8"]:
die(f"{pid}: R-phase before P8")
print(f"phases.yaml valid ({len(ids)} phases)")
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def check(phase_id):
phases = {p["id"]: p for p in load()}
if phase_id not in phases:
die(f"unknown phase {phase_id}")
ph = phases[phase_id]
for req in ph.get("requires", []):
path = Path(req["path"])
if not path.exists():
die(f"{phase_id} requires {path}")
if req.get("sha256") and sha(path) != req["sha256"]:
die(f"{path} drifted since {phase_id} was planned")
for entry in ph.get("requires_empty", []):
p = Path(entry)
if p.is_file() and p.stat().st_size:
die(f"{entry} must be empty before {phase_id}")
if p.is_dir() and any(p.iterdir()):
die(f"{entry} must be empty before {phase_id}")
print(f"{phase_id}: preconditions satisfied")
if __name__ == "__main__":
if "--lint" in sys.argv:
lint(load())
elif len(sys.argv) > 1:
check(sys.argv[1])
else:
die("usage: require.py <phase> | --lint")
'''
BOOTSTRAP_CHECK_PY = '''#!/usr/bin/env python3
"""Verify generated tooling matches .bootstrap-state. Exit 1 on tamper."""
import hashlib, sys
from pathlib import Path
STATE = Path(".bootstrap-state")
if not STATE.exists():
sys.exit("PRECONDITION: .bootstrap-state missing — run bootstrap")
bad = 0
for line in STATE.read_text().splitlines():
if not line.strip():
continue
want, path = line.split(None, 1)
p = Path(path)
if not p.exists():
print(f"missing: {path}")
bad = 1
continue
if hashlib.sha256(p.read_bytes()).hexdigest() != want:
print(f"modified: {path}")
bad = 1
sys.exit(1 if bad else 0)
'''
OPENAPI_SNAPSHOT_PY = '''#!/usr/bin/env python3
"""Freeze the Flask URL map before dashboard_server.py is split into blueprints."""
import hashlib, json, sys
from pathlib import Path
SPEC = Path("docs/api/openapi.yaml")
ROUTES = Path("build/openapi.routes.json")
SHA = Path("build/openapi.sha256")
CANDIDATES = (
("pegasus.ui.web.server", "app"), ("pegasus.ui.web.server", "create_app"),
("pegasus.ui.api.app", "app"), ("pegasus.ui.api.app", "create_app"),
("dashboard_server", "app"),
)
def load_app():
last = "no candidate module imported"
for mod, attr in CANDIDATES:
try:
m = __import__(mod, fromlist=[attr])
except Exception as exc:
last = f"{mod}: {exc}"
continue
obj = getattr(m, attr, None)
if obj is None:
last = f"{mod}.{attr} missing"
continue
try:
return obj() if attr == "create_app" else obj
except Exception as exc:
last = f"{mod}.{attr}() raised {exc}"
sys.exit(f"PRECONDITION: cannot import app — {last}")
def collect(app):
out = []
for rule in app.url_map.iter_rules():
methods = sorted(rule.methods - {"HEAD", "OPTIONS"})
if not methods:
continue
out.append({"rule": str(rule), "methods": methods,
"endpoint": rule.endpoint, "args": sorted(rule.arguments)})
out.sort(key=lambda r: (r["rule"], r["methods"]))
return out
def main() -> int:
routes = collect(load_app())
if not routes:
sys.exit("PRECONDITION: url_map is empty")
ROUTES.parent.mkdir(parents=True, exist_ok=True)
ROUTES.write_text(json.dumps(routes, indent=2) + "\\n", encoding="utf-8")
lines = ["openapi: 3.0.3", "info:", " title: Pegasus", " version: snapshot", "paths:"]
for r in routes:
lines.append(f" {r['rule']}:")
for m in r["methods"]:
lines += [f" {m.lower()}:", f" operationId: {r['endpoint']}",
" responses:", " '200': {description: ok}"]
SPEC.parent.mkdir(parents=True, exist_ok=True)
SPEC.write_text("\\n".join(lines) + "\\n", encoding="utf-8")
digest = hashlib.sha256()
for p in (SPEC, ROUTES):
digest.update(p.read_bytes())
SHA.write_text(digest.hexdigest() + " openapi\\n", encoding="utf-8")
print(f"{len(routes)} routes frozen")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
MODULE_NEW_PY = '''#!/usr/bin/env python3
"""Scaffold a module: manifest, method, schema, fixture, contract test.
Replaces the absent pegasus.modules.postex.scaffold. Exit 3 on bad input.
"""
import json, re, sys
from pathlib import Path
ROOT = Path("pegasus/modules")
BLASTS = ("readonly", "stateful", "destructive", "irreversible")
COSTS = ("cheap", "moderate", "expensive")
ID_RE = re.compile(r"^[a-z][a-z0-9_]{1,39}$")
MODULE_PY = \'\'\'"""{mid} module."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
BLAST = "{blast}"
COST = "{cost}"
REQUIRES_CAPS: set[str] = set()
SCHEMA = Path(__file__).with_name("schema.json")
def schema() -> dict[str, Any]:
return json.loads(SCHEMA.read_text(encoding="utf-8"))
def run(ctx: Any, target: str, **kw: Any) -> dict[str, Any]:
"""Return the envelope. Device-side failure is ok=False, never an exception."""
return {{
"ok": True, "module": "{mid}", "target": target,
"started": None, "finished": None, "requires_root": False,
"steps": [], "artifacts": [], "findings": {{}}, "errors": [],
}}
\'\'\'
PLUGIN_PY = \'\'\'"""{mid} plugin registration."""
from __future__ import annotations
from typing import Any
from .module import BLAST, COST, run
NAME = "{mid}"
def register(registry: Any) -> None:
registry.register(NAME, run, blast=BLAST, cost=COST)
\'\'\'
def schema_for(mid: str) -> dict:
return {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": f"{mid} result envelope", "type": "object",
"required": ["ok", "module", "target", "steps", "artifacts", "findings", "errors"],
"properties": {
"ok": {"type": "boolean"}, "module": {"const": mid},
"target": {"type": "string"}, "requires_root": {"type": "boolean"},
"steps": {"type": "array"}, "artifacts": {"type": "array"},
"findings": {"type": "object"},
"errors": {"type": "array", "items": {"type": "string"}},
},
"additionalProperties": True,
}
def main() -> int:
args = [a for a in sys.argv[1:] if not a.startswith("--")]
flags = {a.split("=", 1)[0]: a.split("=", 1)[1]
for a in sys.argv[1:] if a.startswith("--") and "=" in a}
if not args:
sys.exit("PRECONDITION: usage: module_new.py <id> [--blast=B] [--cost=C]")
mid = args[0]
if not ID_RE.match(mid):
sys.exit(f"PRECONDITION: bad id {mid!r}")
blast, cost = flags.get("--blast", "readonly"), flags.get("--cost", "cheap")
if blast not in BLASTS or cost not in COSTS:
sys.exit("PRECONDITION: bad blast or cost")
dest = ROOT / mid
if dest.exists():
sys.exit(f"PRECONDITION: {dest} exists")
dest.mkdir(parents=True)
(dest / "__init__.py").write_text("", encoding="utf-8")
(dest / "module.py").write_text(
MODULE_PY.format(mid=mid, blast=blast, cost=cost), encoding="utf-8")
(dest / "plugin.py").write_text(PLUGIN_PY.format(mid=mid), encoding="utf-8")
(dest / "schema.json").write_text(
json.dumps(schema_for(mid), indent=2) + "\\n", encoding="utf-8")
print(f"created {dest} (blast={blast} cost={cost})")
print(f"map row to add: {dest}/ | KEEP | new module")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
PARITY_PY = '''#!/usr/bin/env python3
"""Diff capability names declared in registries against those in README."""
import re, sys
from pathlib import Path
REGISTRIES = ("pegasus/core/plugin/modules/base.py", "pegasus/modules/base.py",
"weapons/registry.py", "exploits/registry.py", "c2/registry.py",
"rat/commands.py")
README, OUT = Path("README.md"), Path("build/parity.diff")
REG_RE = re.compile(r"""register\\(\\s*["']([a-z][a-z0-9_]*)["']""")
CAP_RE = re.compile(r"(?m)^CAPABILITIES\\s*[:=].*$")
NAME_RE = re.compile(r"""["']([a-z][a-z0-9_]{2,})["']""")
DOC_RE = re.compile(r"`([a-z][a-z0-9_]{2,})`")
def declared() -> set[str]:
names: set[str] = set()
for rel in REGISTRIES:
p = Path(rel)
if not p.exists():
continue
text = p.read_text(encoding="utf-8", errors="replace")
names |= set(REG_RE.findall(text))
for line in CAP_RE.findall(text):
names |= set(NAME_RE.findall(line))
return names
def main() -> int:
found = [r for r in REGISTRIES if Path(r).exists()]
if not found:
sys.exit("PRECONDITION: no registry file found")
if not README.exists():
sys.exit("PRECONDITION: README.md missing")
names = declared()
if not names:
sys.exit("PRECONDITION: no capability names parsed")
documented = set(DOC_RE.findall(README.read_text(encoding="utf-8", errors="replace")))
undoc, orphan = sorted(names - documented), sorted(documented - names)
lines = ["# registry vs README", "", "registries: " + ", ".join(found), "",
"## declared, not documented"]
lines += [f"- {n}" for n in undoc] or ["- none"]
lines += ["", "## documented, not declared (informational)"]
lines += [f"- {n}" for n in orphan[:200]] or ["- none"]
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text("\\n".join(lines) + "\\n", encoding="utf-8")
print(f"{len(names)} declared, {len(undoc)} undocumented")
if undoc:
return 2
print("parity clean")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
VERSION_CHECK_PY = '''#!/usr/bin/env python3
"""Assert one version everywhere. Exit 1 on drift, 3 on a missing source."""
import json, re, sys
from pathlib import Path
VERSION = Path("pegasus/VERSION")
PYPROJECTS = (Path("pyproject.toml"), Path("pegasus/pyproject.toml"))
PACKAGE = Path("pegasus/ui/web/package.json")
RESOURCES = (Path("packaging/pyinstaller/version.txt"),
Path("packaging/pyinstaller/version-web.txt"))
NUMS = re.compile(r"\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*\\d+\\s*\\)")
STRV = re.compile(r"StringStruct\\('(?:FileVersion|ProductVersion)',\\s*'([0-9][0-9.]*)'\\)")
def main() -> int:
if not VERSION.exists():
sys.exit("PRECONDITION: pegasus/VERSION missing")
want = VERSION.read_text(encoding="utf-8").strip()
if not re.fullmatch(r"\\d+\\.\\d+\\.\\d+", want):
sys.exit(f"PRECONDITION: bad version {want!r}")
bad = 0
for p in PYPROJECTS:
if not p.exists():
continue
m = re.search(r'(?m)^version\\s*=\\s*"([^"]+)"', p.read_text(encoding="utf-8"))
if not m:
print(f" warn {p}: no version field")
elif m.group(1) != want:
print(f" FAIL {p}: {m.group(1)} != {want}")
bad = 1
else:
print(f" ok {p}")
if PACKAGE.exists():
got = json.loads(PACKAGE.read_text(encoding="utf-8")).get("version")
if got != want:
print(f" FAIL {PACKAGE}: {got} != {want}")
bad = 1
else:
print(f" ok {PACKAGE}")
for p in RESOURCES:
if not p.exists():
continue
text = p.read_text(encoding="utf-8")
seen = {".".join(n) for n in NUMS.findall(text)} | set(STRV.findall(text))
if seen != {want}:
print(f" FAIL {p}: {sorted(seen)} != {want}")
bad = 1
else:
print(f" ok {p}")
return 1 if bad else 0
if __name__ == "__main__":
sys.exit(main())
'''
NO_PLATFORM_BRANCH_PY = '''#!/usr/bin/env python3
"""Fail if a module body branches on platform instead of capabilities.
Plan section 113. platform_hint is grouping only; the gate is requires_caps.
Exit 3 if no module file exists, 2 on any branch found.
"""
import re, sys
from pathlib import Path
ROOT = Path("pegasus/modules")
PATTERNS = [
(re.compile(r"\\bif\\s+[\\w.]*platform\\s*[=!]="), "platform equality"),
(re.compile(r"\\bis_android\\b|\\bis_ios\\b|\\bis_windows\\b"), "is_<os> helper"),
(re.compile(r"\\bos\\.name\\s*[=!]="), "os.name comparison"),
(re.compile(r"\\bsys\\.platform\\b"), "sys.platform"),
]
ALLOW = Path("build/noplatform.allow")
def main() -> int:
files = sorted(ROOT.rglob("module.py")) if ROOT.exists() else []
if not files:
sys.exit(f"PRECONDITION: no module.py under {ROOT}")
allow = set()
if ALLOW.exists():
allow = {ln.split("#")[0].strip() for ln in ALLOW.read_text().splitlines()
if ln.strip() and not ln.startswith("#")}
hits = []
for f in files:
rel = f.as_posix()
if rel in allow:
continue
for i, line in enumerate(f.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
code = line.split("#")[0]
for pat, label in PATTERNS:
if pat.search(code):
hits.append(f"{rel}:{i}: {label}: {code.strip()[:70]}")
break
if hits:
print("\\n".join(hits))
print(f"\\n{len(hits)} platform branch(es) across {len(files)} module(s)")
print("move the decision into requires_caps, or add the file to build/noplatform.allow")
return 2
print(f"no platform branches in {len(files)} module(s)")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
CAPABILITY_CHECK_PY = '''#!/usr/bin/env python3
"""Dashboard is renamed Capability. Exit 3 if the web tree is absent, 2 on drift."""
import sys
from pathlib import Path
WEB = Path("pegasus/ui/web/src")
OLD, NEW = "Dashboard", "Capability"
SKIP = {"node_modules", "dist", ".vite"}
def files():
if not WEB.exists():
return []
return [p for p in WEB.rglob("*")
if p.suffix in {".tsx", ".ts", ".jsx", ".js"}
and not SKIP & set(p.parts)]
def main() -> int:
fs = files()
if not fs:
sys.exit(f"PRECONDITION: no source under {WEB}")
stale, renamed = [], []
for p in fs:
text = p.read_text(encoding="utf-8", errors="replace")
if OLD in text:
stale.append(p.as_posix())
if NEW in text:
renamed.append(p.as_posix())
if stale:
print(f"{len(stale)} file(s) still say {OLD}:")
for s in stale:
print(f" {s}")
print(f"rename to {NEW} before P6")
return 2
if not renamed:
print(f"{NEW} label not found anywhere")
return 2
print(f"{NEW} label present, {OLD} gone")
return 0
if __name__ == "__main__":
sys.exit(main())
'''
MODULES_LINT_PY = '''#!/usr/bin/env python3
"""Lint module manifests: ids, caps, tiers, deps, cycles, orphans.
Plan sections 115-116. Every cap comparison goes through scripts/capreg.py, the
same module caps_matrix uses, so the two lints cannot disagree about what a cap
is or whether a transport provides it. An orphan cap fails here as well as
there — a green modules_lint with a red matrix is not reachable.
Exit 3 on a malformed tree, 2 on any violation.
"""
import re, sys
from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent))
import capreg
MANIFESTS = Path("post_exploitation/manifests")
ID_RE = re.compile(r"^[a-z][a-z0-9_]{2,23}$")
REQUIRED = {"id", "title", "category", "tier"}
def load():
if not MANIFESTS.exists():
return None, []
specs, errs = {}, []
for f in sorted(MANIFESTS.glob("*.yaml")):
raw = yaml.safe_load(f.read_text(encoding="utf-8")) or []
if not isinstance(raw, list):
errs.append(f"{f.name}: not a list")
continue
for e in raw:
if not isinstance(e, dict):
errs.append(f"{f.name}: entry is not a mapping")
continue
e["_file"] = f.name
specs[e.get("id", "?")] = e
return specs, errs
def main() -> int:
try:
known = set(capreg.cap_values())
provided = capreg.providers()
except capreg.Precondition as exc:
sys.exit(f"PRECONDITION: {exc}")
allowed = capreg.allowlist()
specs, errs = load()
if specs is None:
sys.exit(f"PRECONDITION: {MANIFESTS} missing")