Repository navigation
Expand file tree
/
Copy pathpackage_internal_plugin.py
More file actions
executable file
·1641 lines (1442 loc) · 66 KB
/
Copy pathpackage_internal_plugin.py
File metadata and controls
executable file
·1641 lines (1442 loc) · 66 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
"""Build a company-branded appsec-advisor plugin artifact.
This script keeps internal packaging logic in the upstream plugin instead of
copying fragile rsync/sed/json snippets into every company's CI repository.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import io
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
from datetime import datetime, timezone
from pathlib import Path
UPSTREAM_NAMESPACE = "appsec-advisor"
# Namespace rewriting + leak detection must reach the script surfaces too:
# scripts/run-headless.sh and many .py helpers hardcode `<namespace>:<skill>`
# command references (e.g. the `claude -p` prompt, `/…:fix-run-issues` hints).
# Excluding .sh/.py left a repackaged plugin dispatching the upstream namespace
# — a broken headless wrapper that check_namespace_leaks never saw.
TEXT_SUFFIXES = {".json", ".md", ".txt", ".yaml", ".yml", ".sh", ".py"}
TOP_LEVEL_EXCLUDES = {
".agents",
".cache",
".claude",
".codex",
".env",
".git",
".github",
".gitlab-ci.yml",
".gitignore",
".pytest_cache",
".ruff_cache",
".mypy_cache",
".venv",
".venv-tests",
"AGENTS.md",
"CHANGELOG.md",
"CLAUDE.md",
"CONTRIBUTING.md",
"LICENSE",
"Makefile",
"README.md",
"SECURITY.md",
"build",
"dist",
"examples",
"htmlcov",
"node_modules",
"pyproject.toml",
"tests",
}
ANY_LEVEL_EXCLUDES = {
".appsec-cache",
".cache",
".coverage-data",
".mypy_cache",
".pytest_cache",
".ruff_cache",
".venv",
".venv-tests",
"__pycache__",
"build",
"dist",
"htmlcov",
"node_modules",
}
ANY_LEVEL_FILE_EXCLUDES = {
".agent-run.log",
".appsec-checkpoint",
".appsec-lock",
".appsec-progress.json",
".hook-events.log",
".render-integrity.json",
".run-issues.json",
".scan-start-epoch",
".scan-wall-seconds",
".section-integrity.json",
".skill-config.json",
}
PATH_EXCLUDES = {
("data", "appsec-requirements-fallback.yaml"),
("docs", "analysis"),
("docs", "internal"),
("docs", "proposals"),
("docs", "security"),
("scripts", "docs"),
("skills", "appsec-analyzer", "docs"),
("tests", "fixtures", "e2e", "_last-run"),
}
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
SURFACE_MANIFEST = ".claude-plugin/package-surface.json"
MCP_CONFIG = ".mcp.json"
HOOK_SCRIPT_IDS = {
"agent_logger.py": "agent-logger",
"security_steering.py": "security-coach",
}
INTERNAL_REQUIRED_SKILLS = {"internal-threat-analysis-kernel"}
def _die(message: str, code: int = 2) -> None:
print(f"ERROR: {message}", file=sys.stderr)
raise SystemExit(code)
def _validate_package_name(name: str) -> None:
if not NAME_RE.match(name):
_die(
"plugin name must start with a lowercase letter or digit and contain "
"only lowercase letters, digits, '.', '_' and '-'"
)
def _validate_version(version: str) -> None:
if not version:
_die("version must not be empty")
if "/" in version:
_die("VERSION must not contain '/' because it is used in artifact paths")
def _require_plugin_root(source: Path) -> None:
required = [
".claude-plugin/plugin.json",
"config.json",
"agents",
"skills",
"scripts",
"schemas",
]
missing = [rel for rel in required if not (source / rel).exists()]
if missing:
_die(f"{source} is not an appsec-advisor plugin root; missing {missing}")
def _copy_ignore(source_root: Path):
source_root = source_root.resolve()
def ignore(current: str, names: list[str]) -> set[str]:
current_path = Path(current).resolve()
try:
rel = current_path.relative_to(source_root)
except ValueError:
rel = Path(".")
ignored: set[str] = set()
for name in names:
child = current_path / name
rel_child = tuple((rel / name).parts)
if rel == Path(".") and name in TOP_LEVEL_EXCLUDES:
ignored.add(name)
elif rel_child in PATH_EXCLUDES:
ignored.add(name)
elif child.is_dir() and name in ANY_LEVEL_EXCLUDES:
ignored.add(name)
elif child.is_file() and name in ANY_LEVEL_FILE_EXCLUDES:
ignored.add(name)
return ignored
return ignore
def copy_source(source: Path, build: Path) -> None:
if build.exists():
shutil.rmtree(build)
build.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source, build, ignore=_copy_ignore(source))
def overlay_org_profile(org_profile: Path, build: Path) -> None:
if not (org_profile / "org-profile.yaml").is_file():
_die(f"{org_profile} must contain org-profile.yaml")
target = build / "org-profile"
if target.exists():
shutil.rmtree(target)
shutil.copytree(org_profile, target)
def _git(source: Path, *cmd: str) -> str:
"""Read-only git output from the source checkout, or empty when unavailable."""
try:
result = subprocess.run(["git", *cmd], capture_output=True, text=True, timeout=10, cwd=source, check=False)
except (OSError, subprocess.SubprocessError):
return ""
return result.stdout.strip() if result.returncode == 0 else ""
def core_provenance(source: Path, version: str) -> dict:
"""Which upstream revision this package was built from.
The build tree carries no ``.git``, so a packaged install can no longer read
its own origin: without these fields ``status`` shows the organization's
version number and nothing about the appsec-advisor underneath it. Every
field is best-effort — a source tree that is not a git checkout records the
core version alone rather than failing the build.
"""
provenance = {"appsec_advisor_core_version": version}
ref = _git(source, "rev-parse", "--abbrev-ref", "HEAD")
if ref == "HEAD": # detached: name the tag when one points here
ref = _git(source, "describe", "--tags", "--exact-match") or "detached"
commit = _git(source, "rev-parse", "HEAD")
committed_at = _git(source, "log", "-1", "--format=%cI")
if ref:
provenance["appsec_advisor_core_ref"] = ref
if commit:
provenance["appsec_advisor_core_commit"] = commit
if committed_at:
provenance["appsec_advisor_core_committed_at"] = committed_at
if _git(source, "status", "--porcelain"):
provenance["appsec_advisor_core_dirty"] = True
provenance["appsec_advisor_packaged_at"] = (
datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
)
return provenance
def upstream_url_from_git(source: Path) -> str | None:
"""The source checkout's origin remote as an https URL, when it has one.
Used when the caller passed no ``--upstream-url``: the packaged build is the
only place a reader can still see where the code came from, and an origin
remote answers that as well as the flag does. An SSH remote is rewritten to
its https form; anything else is dropped rather than guessed at.
"""
remote = _git(source, "remote", "get-url", "origin")
if not remote:
return None
match = re.match(r"^(?:git\+)?ssh://git@([^/]+)/(.+?)(?:\.git)?/?$", remote) or re.match(
r"^git@([^:]+):(.+?)(?:\.git)?/?$", remote
)
if match:
return f"https://{match.group(1)}/{match.group(2)}"
if remote.startswith("https://"):
return remote.removesuffix(".git")
return None
def patch_plugin_json(
build: Path, name: str, version: str, description: str | None, source: Path, *, provenance: dict | None = None
) -> None:
plugin_path = build / ".claude-plugin" / "plugin.json"
data = json.loads(plugin_path.read_text(encoding="utf-8"))
core_version = data.get("version", "")
data["name"] = name
data["version"] = version
data["description"] = (
description if description is not None else f"Internal packaged build of appsec-advisor for {name}."
)
data.update(core_provenance(source, core_version) if provenance is None else provenance)
plugin_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
def _org_profile_banner(build: Path) -> dict:
"""Session-banner overrides declared in the packaged org profile.
The banner runs as a SessionStart hook and must stay free of a YAML
dependency, so the profile is resolved into config.json here at build time.
"""
profile_path = build / "org-profile" / "org-profile.yaml"
if not profile_path.is_file():
return {}
banner = _load_yaml_or_json(profile_path).get("banner")
if not isinstance(banner, dict):
return {}
return {key: value for key, value in banner.items() if key in ("enabled", "headline", "url")}
def _org_profile_baseline(build: Path) -> dict:
"""The organization's own secure-coding baseline, resolved into config.json.
Like the banner, this is read at build time so the SessionStart hook stays
free of a YAML dependency. Declaring any source *replaces* the plugin's
default baseline rather than merging with it: the upstream source and the
upstream bundled copy both carry the upstream id, which the organization's
own id check would refuse anyway, so keeping them would only produce a
confusing failure. ``file`` is rewritten to the packaged profile path,
because the profile directory is where it lands in the build.
"""
profile_path = build / "org-profile" / "org-profile.yaml"
if not profile_path.is_file():
return {}
baseline = _load_yaml_or_json(profile_path).get("baseline")
if not isinstance(baseline, dict):
return {}
resolved = {
key: value for key, value in baseline.items() if key in ("enabled", "enforce", "id", "name", "install_filename")
}
if baseline.get("url"):
resolved["url"] = baseline["url"]
if isinstance(baseline.get("git"), dict):
resolved["git"] = baseline["git"]
if baseline.get("file"):
resolved["fallback_file"] = f"org-profile/{str(baseline['file']).lstrip('/')}"
if any(key in resolved for key in ("id", "url", "git", "fallback_file")):
# An organization that names its own baseline owns the whole chain; a
# leftover upstream source would be fetched, fail the id check, and
# report a puzzling error. The display name goes the same way: inherited,
# it would head the banner and both skills with the upstream product
# name over the organization's own rules. Cleared, the generic default
# applies until the profile sets one.
for key in ("url", "git", "release", "fallback_file", "name", "bundle_dir"):
resolved.setdefault(key, None)
resolved["mode"] = "complete"
return resolved
def _org_profile_skill_toggles(build: Path) -> dict:
"""The profile's skill policy, resolved into config.json at build time.
Without this the policy only exists in ``.org-profile-effective.json``,
which a run writes into its output directory — so a skill invoked before
any scan has ever happened found no policy and ran. Resolving it here gives
every session the same answer from the first command onwards, the way the
banner and baseline blocks already work.
Normalised to the ``{enabled, reason}`` shape so consumers see one form,
matching ``resolve_org_profile.normalize_skill_toggles``.
"""
profile_path = build / "org-profile" / "org-profile.yaml"
if not profile_path.is_file():
return {}
toggles = _load_yaml_or_json(profile_path).get("skill_toggles")
if not isinstance(toggles, dict):
return {}
out: dict[str, dict] = {}
for name, value in toggles.items():
if isinstance(value, bool):
out[str(name)] = {"enabled": value, "reason": None}
elif isinstance(value, dict):
out[str(name)] = {"enabled": bool(value.get("enabled", True)), "reason": value.get("reason")}
return out
def _prune_unused_baselines(build: Path, baseline: dict) -> None:
"""Drop the upstream bundled baseline when the build does not use it.
An organization that ships its own baseline never reads the copy in
``data/baselines/`` — its id would not match, so an install would refuse it.
Leaving it in place ships a third-party document, under its own licence,
that the build's configuration never touches: dead weight in an internal
package and a puzzle for whoever audits it.
"""
bundled_dir = build / "data" / "baselines"
if not bundled_dir.is_dir():
return
fallback = baseline.get("fallback_file")
if isinstance(fallback, str) and fallback.startswith("data/baselines/"):
return
shutil.rmtree(bundled_dir, ignore_errors=True)
def patch_config(build: Path, info_url: str | None = None) -> None:
config_path = build / "config.json"
data = json.loads(config_path.read_text(encoding="utf-8"))
data["organization_profile"] = {
"enabled": True,
"path": "org-profile/org-profile.yaml",
}
baseline = dict(data.get("baseline") or {})
baseline.update(_org_profile_baseline(build))
if baseline:
data["baseline"] = baseline
_prune_unused_baselines(build, baseline)
toggles = _org_profile_skill_toggles(build)
if toggles:
data["skill_toggles"] = toggles
banner = dict(data.get("banner") or {})
banner.update(_org_profile_banner(build))
if info_url is not None:
# The flag wins over the profile. An empty value drops the "more
# information" line; the upstream URL is wrong for an internal build
# either way.
banner["url"] = info_url or None
if banner:
data["banner"] = banner
config_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
def _load_yaml_or_json(path: Path) -> dict:
try:
text = path.read_text(encoding="utf-8")
except OSError as exc:
_die(f"cannot read package policy {path}: {exc}")
if path.suffix.lower() == ".json":
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
_die(f"invalid JSON package policy {path}: {exc}")
else:
try:
import yaml
except ImportError:
_die("package policy YAML requires PyYAML; install pyyaml or use a .json policy file")
try:
data = yaml.safe_load(text)
except yaml.YAMLError as exc:
_die(f"invalid YAML package policy {path}: {exc}")
if data is None:
return {}
if not isinstance(data, dict):
_die(f"package policy {path} must contain a mapping/object at the root")
return data
def load_package_policy(org_profile: Path, explicit_path: str | None) -> tuple[dict, Path | None]:
if explicit_path:
path = Path(explicit_path).resolve()
if not path.is_file():
_die(f"package policy not found at {path}")
return _load_yaml_or_json(path), path
for name in ("package-policy.yaml", "package-policy.yml", "package-policy.json"):
candidate = org_profile / name
if candidate.is_file():
return _load_yaml_or_json(candidate), candidate.resolve()
return {}, None
def _policy_surface(policy: dict) -> dict:
surface = policy.get("plugin_surface", policy)
if not isinstance(surface, dict):
_die("package policy 'plugin_surface' must be a mapping/object")
unknown = set(surface) - {"skills", "hooks", "mcp_servers"}
if unknown:
_die(f"package policy has unknown plugin_surface keys: {sorted(unknown)}")
return surface
def _read_name_list(block: dict, key: str, surface: str) -> set[str] | None:
if key not in block:
return None
value = block[key]
if value is None:
return set()
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
_die(f"package policy plugin_surface.{surface}.{key} must be a list of strings")
seen: set[str] = set()
duplicates: set[str] = set()
for item in value:
name = item.strip()
if not name:
_die(f"package policy plugin_surface.{surface}.{key} contains an empty name")
if name in seen:
duplicates.add(name)
seen.add(name)
if duplicates:
_die(f"package policy plugin_surface.{surface}.{key} contains duplicates: {sorted(duplicates)}")
return seen
def _resolve_keep_set(
block: object,
available: set[str],
surface: str,
*,
required: set[str] | None = None,
) -> set[str]:
required = required or set()
if block is None:
return set(available)
if not isinstance(block, dict):
_die(f"package policy plugin_surface.{surface} must be a mapping/object")
unknown_keys = set(block) - {"include", "exclude"}
if unknown_keys:
_die(f"package policy plugin_surface.{surface} has unknown keys: {sorted(unknown_keys)}")
include = _read_name_list(block, "include", surface)
exclude = _read_name_list(block, "exclude", surface)
if include is not None and exclude is not None:
_die(f"package policy plugin_surface.{surface} cannot set both include and exclude")
selected = include if include is not None else exclude
if selected is None:
return set(available)
unknown = selected - available
if unknown:
_die(
f"package policy plugin_surface.{surface} references unknown names: "
f"{sorted(unknown)} (available: {sorted(available)})"
)
keep = set(selected) if include is not None else (available - selected)
missing_required = required - keep
if missing_required:
_die(f"package policy plugin_surface.{surface} must keep required names: {sorted(missing_required)}")
return keep
def _available_skills(build: Path) -> set[str]:
skills_dir = build / "skills"
if not skills_dir.is_dir():
return set()
return {path.parent.name for path in skills_dir.glob("*/SKILL.md") if path.is_file()}
def _required_internal_skills(build: Path) -> set[str]:
"""Internal skills referenced by agent frontmatter in this packaged source."""
agents_dir = build / "agents"
if not agents_dir.is_dir():
return set()
required: set[str] = set()
for path in agents_dir.glob("*.md"):
try:
text = path.read_text(encoding="utf-8")
except OSError:
continue
frontmatter = text.split("---", 2)[1] if text.startswith("---") and text.count("---") >= 2 else ""
for skill in INTERNAL_REQUIRED_SKILLS:
if re.search(rf"(?m)^\s*-\s+{re.escape(skill)}\s*$", frontmatter):
required.add(skill)
return required
def _hook_id(command: str) -> str | None:
if "/scripts/" not in command and "\\scripts\\" not in command:
return None
script_name = command.replace("\\", "/").split("/scripts/", 1)[1].split()[0]
script_name = Path(script_name).name
return HOOK_SCRIPT_IDS.get(script_name, Path(script_name).stem.replace("_", "-"))
def _load_hooks(build: Path) -> tuple[Path, dict]:
hooks_path = build / "hooks" / "hooks.json"
if not hooks_path.is_file():
return hooks_path, {"hooks": {}}
try:
data = json.loads(hooks_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
_die(f"invalid hooks.json in packaged copy: {exc}")
if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
_die("hooks/hooks.json must contain a top-level 'hooks' object")
return hooks_path, data
def _available_hook_ids(build: Path) -> set[str]:
_, data = _load_hooks(build)
ids: set[str] = set()
for entries in data.get("hooks", {}).values():
if not isinstance(entries, list):
continue
for outer in entries:
if not isinstance(outer, dict):
continue
for hook in outer.get("hooks") or []:
if not isinstance(hook, dict):
continue
command = hook.get("command")
if isinstance(command, str):
hook_id = _hook_id(command)
if hook_id:
ids.add(hook_id)
return ids
def apply_skill_policy(build: Path, surface: dict, *, required: set[str] | None = None) -> dict:
available = _available_skills(build)
required_internal = _required_internal_skills(build)
missing_internal = required_internal - available
if missing_internal:
_die(f"packaged source is missing internal required skills: {sorted(missing_internal)}")
keep = _resolve_keep_set(
surface.get("skills"),
available,
"skills",
required={"appsec-analyzer"} if required is None else required,
)
keep.update(required_internal)
removed = sorted(available - keep)
for skill in removed:
shutil.rmtree(build / "skills" / skill)
return {"included": sorted(keep), "removed": removed}
# Where an org profile keeps the skills it adds, unless it says otherwise.
ORG_SKILLS_GLOB = "skills/*/SKILL.md"
def overlay_org_skills(build: Path) -> list[str]:
"""Copy the skills the org profile adds into the plugin's skills directory.
Claude Code discovers skills by convention — every ``skills/<name>/SKILL.md``
under the plugin root — so adding one is a directory copy. It has to happen
before the package policy runs, or ``plugin_surface.skills`` could not name
an added skill and would reject it as unknown.
Two refusals rather than a silent result:
* A name that collides with an upstream skill aborts the build. Overwriting
``appsec-analyzer`` with an organization's own file would replace the
pipeline's entry point without anyone deciding to.
* Frontmatter that would not pass for an upstream skill aborts too. The
description is the only text the model sees when choosing a skill, so a
malformed one degrades routing quietly instead of failing.
"""
profile_dir = build / "org-profile"
profile_path = profile_dir / "org-profile.yaml"
if not profile_path.is_file():
return []
block = _load_yaml_or_json(profile_path).get("skills")
if not isinstance(block, dict):
return []
pattern = str(block.get("add") or ORG_SKILLS_GLOB)
upstream = _available_skills(build)
added: list[str] = []
for skill_md in sorted(profile_dir.glob(pattern)):
source = skill_md.parent
name = source.name
_require_inside(profile_dir, skill_md, "skills.add")
_validate_org_skill(skill_md, name)
if name in upstream:
_die(
f"org profile adds skill '{name}', which the plugin already ships. "
f"Rename it — replacing an upstream skill would change what its command does."
)
if name in added:
_die(f"org profile adds skill '{name}' more than once")
shutil.copytree(source, build / "skills" / name)
added.append(name)
return added
def _require_inside(root: Path, path: Path, label: str) -> None:
"""Abort when ``path`` escapes ``root`` — a glob must not reach outside."""
try:
path.resolve().relative_to(root.resolve())
except ValueError:
_die(f"package policy {label}: '{path}' resolves outside the profile directory")
def _validate_org_skill(skill_md: Path, directory: str) -> None:
"""Hold an added skill to the same frontmatter rules as an upstream one."""
lines = skill_md.read_text(encoding="utf-8").splitlines()
if not lines or lines[0].strip() != "---":
_die(f"org skill '{directory}': SKILL.md does not start with a '---' frontmatter delimiter")
try:
end = lines.index("---", 1)
except ValueError:
_die(f"org skill '{directory}': frontmatter is not terminated by a closing '---'")
try:
import yaml
front = yaml.safe_load("\n".join(lines[1:end]))
except Exception as exc: # noqa: BLE001
_die(f"org skill '{directory}': frontmatter is not valid YAML: {exc}")
if not isinstance(front, dict):
_die(f"org skill '{directory}': frontmatter must be a mapping")
unknown = set(front) - {"name", "description"}
if unknown:
_die(f"org skill '{directory}': unsupported frontmatter keys {sorted(unknown)}")
name, description = front.get("name"), front.get("description")
if name != directory:
_die(f"org skill '{directory}': frontmatter name '{name}' must match the directory name")
if not isinstance(description, str) or not description.strip():
_die(f"org skill '{directory}': a non-empty description is required")
if len(description) > 1024:
_die(f"org skill '{directory}': description is {len(description)} characters; the limit is 1024")
def _org_profile_hooks(build: Path) -> dict:
"""Hook definitions declared in the packaged org profile (top-level `hooks`).
Returns a {id: {event, command, matcher?}} mapping, or {} when the profile
has none. The org profile is already overlaid into build/org-profile here."""
profile_path = build / "org-profile" / "org-profile.yaml"
if not profile_path.is_file():
return {}
data = _load_yaml_or_json(profile_path)
hooks = data.get("hooks")
return hooks if isinstance(hooks, dict) else {}
def apply_hook_policy(build: Path, surface: dict) -> dict:
org_hooks = _org_profile_hooks(build)
# Org hook ids join the upstream ids in the keep-set resolution, so
# plugin_surface.hooks (include/exclude) gates org hooks too. Declared org
# hooks are included by default.
upstream_available = _available_hook_ids(build)
available = upstream_available | set(org_hooks)
keep = _resolve_keep_set(surface.get("hooks"), available, "hooks")
removed = sorted(available - keep)
hooks_path, data = _load_hooks(build)
filtered_events: dict[str, list[dict]] = {}
for event, entries in data.get("hooks", {}).items():
if not isinstance(entries, list):
continue
kept_entries: list[dict] = []
for outer in entries:
if not isinstance(outer, dict):
continue
hooks = outer.get("hooks") or []
kept_hooks = []
for hook in hooks:
if not isinstance(hook, dict):
continue
command = hook.get("command")
hook_id = _hook_id(command) if isinstance(command, str) else None
if hook_id is None or hook_id in keep:
kept_hooks.append(hook)
if kept_hooks:
new_outer = dict(outer)
new_outer["hooks"] = kept_hooks
kept_entries.append(new_outer)
if kept_entries:
filtered_events[event] = kept_entries
# Merge kept org hooks into the built hooks.json under their declared event.
org_kept: list[dict] = []
for hook_id in sorted(keep):
cfg = org_hooks.get(hook_id)
if not isinstance(cfg, dict):
continue
event = cfg.get("event")
command = cfg.get("command")
if not event or not command:
continue
outer: dict = {"hooks": [{"type": "command", "command": command}]}
if cfg.get("matcher"):
outer["matcher"] = cfg["matcher"]
filtered_events.setdefault(event, []).append(outer)
org_kept.append({"id": hook_id, "event": event, "command": command})
if hooks_path.parent.exists():
hooks_path.write_text(
json.dumps({"hooks": filtered_events}, indent=2) + "\n",
encoding="utf-8",
)
if "security-coach" in removed:
keywords_path = build / "hooks" / "steering_keywords.json"
if keywords_path.exists():
keywords_path.unlink()
return {
# Upstream hooks only — org hooks are tracked separately under "org"
# (they are not discoverable via the /scripts/ id derivation).
"included": sorted(upstream_available & keep),
"removed": removed,
"events": sorted(filtered_events),
"org": org_kept,
}
def _org_profile_mcp_servers(build: Path) -> dict:
"""MCP server definitions declared in the packaged org profile (mcp.servers).
Returns a {name: server_config} mapping, or {} when the profile has no mcp
block. The org profile has already been overlaid into build/org-profile at
this point.
"""
profile_path = build / "org-profile" / "org-profile.yaml"
if not profile_path.is_file():
return {}
data = _load_yaml_or_json(profile_path)
servers = (data.get("mcp") or {}).get("servers")
return servers if isinstance(servers, dict) else {}
def apply_mcp_policy(build: Path, surface: dict) -> dict:
"""Emit build/.mcp.json from the org profile's mcp.servers, gated by the
package-policy allowlist (plugin_surface.mcp_servers). Declared servers are
included by default; an include/exclude list narrows them. Writes no file
when nothing is kept."""
servers = _org_profile_mcp_servers(build)
available = set(servers)
keep = _resolve_keep_set(surface.get("mcp_servers"), available, "mcp_servers")
removed = sorted(available - keep)
mcp_path = build / MCP_CONFIG
if keep:
payload = {"mcpServers": {name: servers[name] for name in sorted(keep)}}
mcp_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
elif mcp_path.exists():
mcp_path.unlink()
return {"included": sorted(keep), "removed": removed}
def write_surface_manifest(
build: Path,
policy_path: Path | None,
skills: dict,
hooks: dict,
upstream_url: str | None = None,
mcp_servers: dict | None = None,
) -> None:
if policy_path is None:
policy_ref = None
elif (build / "org-profile" / policy_path.name).is_file():
policy_ref = f"org-profile/{policy_path.name}"
else:
try:
policy_ref = str(policy_path.relative_to(build))
except ValueError:
policy_ref = policy_path.name
manifest = {
"version": 1,
"policy": policy_ref,
"skills": skills,
"hooks": hooks,
}
if mcp_servers is not None:
manifest["mcp_servers"] = mcp_servers
if upstream_url:
manifest["upstream_url"] = upstream_url
manifest["based_on"] = upstream_url.removesuffix(".git")
manifest_path = build / SURFACE_MANIFEST
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
def apply_package_surface_policy(
build: Path,
policy: dict,
policy_path: Path | None,
upstream_url: str | None = None,
*,
required_skills: set[str] | None = None,
) -> None:
surface = _policy_surface(policy)
# Added first, so the package policy can name an org skill like any other
# and so the manifest counts it among what this build ships.
org_added = overlay_org_skills(build)
skills = apply_skill_policy(build, surface, required=required_skills)
if org_added:
# Recorded separately, the way org hooks are: the artifact surface has
# to say which parts are the organization's own.
skills["org_added"] = sorted(org_added)
hooks = apply_hook_policy(build, surface)
mcp_servers = apply_mcp_policy(build, surface)
write_surface_manifest(build, policy_path, skills, hooks, upstream_url, mcp_servers)
def _has_shebang(path: Path) -> bool:
try:
with path.open("rb") as fh:
return fh.read(2) == b"#!"
except OSError:
return False
def _text_files(root: Path):
for path in root.rglob("*"):
if not path.is_file():
continue
if path.suffix.lower() in TEXT_SUFFIXES:
yield path
elif not path.suffix and _has_shebang(path):
# Extensionless executables (CLI shims like scripts/appsec-reviewer-cli)
# hardcode `<namespace>:<skill>` command references too, but match no
# suffix. Detect them by shebang so the namespace rewrite and the leak
# check reach them — without hardcoding shim names.
yield path
def rewrite_namespace(build: Path, name: str, *, protected: set[str] | None = None) -> None:
old = f"{UPSTREAM_NAMESPACE}:"
new = f"{name}:"
for path in _text_files(build):
if protected and path.relative_to(build).as_posix() in protected:
continue
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
continue
if old in text:
path.write_text(text.replace(old, new), encoding="utf-8")
def check_namespace_leaks(build: Path, *, protected: set[str] | None = None) -> None:
needle = f"{UPSTREAM_NAMESPACE}:"
leaks: list[str] = []
for root_name in ("skills", "agents", "scripts"):
root = build / root_name
if not root.exists():
continue
for path in _text_files(root):
if protected and path.relative_to(build).as_posix() in protected:
continue
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
continue
if needle in text:
leaks.append(str(path.relative_to(build)))
if leaks:
shown = "\n - ".join(leaks[:20])
_die(f"upstream namespace {needle!r} still present in packaged copy:\n - {shown}", 1)
def run_validation(build: Path) -> None:
subprocess.run(
[sys.executable, str(build / "scripts" / "validators/validate_config.py"), str(build)],
check=True,
)
subprocess.run(
[
sys.executable,
str(build / "scripts" / "validators/validate_org_profile.py"),
str(build / "org-profile" / "org-profile.yaml"),
],
check=True,
)
def write_archive(
build: Path, name: str, version: str, dist_dir: Path, *, deterministic: bool = False
) -> tuple[Path, Path]:
dist_dir.mkdir(parents=True, exist_ok=True)
tar_path = dist_dir / f"{name}-{version}.tgz"
sha_path = dist_dir / f"{name}-{version}.tgz.sha256"
if deterministic:
with (
tar_path.open("wb") as stream,
gzip.GzipFile(filename="", fileobj=stream, mode="wb", mtime=0) as compressed,
):
with tarfile.open(fileobj=compressed, mode="w") as archive:
for relative, data in sorted(_staging_tree(build).items()):
entry = tarfile.TarInfo(f"{name}/{relative}")
entry.size = len(data)
entry.mode = 0o644
archive.addfile(entry, io.BytesIO(data))
else:
with tarfile.open(tar_path, "w:gz") as archive:
archive.add(build, arcname=name)
digest = hashlib.sha256(tar_path.read_bytes()).hexdigest()
sha_path.write_text(f"{digest} {tar_path.name}\n", encoding="utf-8")
return tar_path, sha_path
def remove_stale_archive(name: str, version: str, dist_dir: Path) -> None:
for path in (
dist_dir / f"{name}-{version}.tgz",
dist_dir / f"{name}-{version}.tgz.sha256",
):
if path.exists():
path.unlink()
HOOK_DESCRIPTIONS = {
"agent-logger": "Logs all tool calls and agent actions for audit and debugging.",
"security-coach": "Intercepts tool calls and provides real-time security guidance.",
"session-banner": "Opens each session with the repository's threat-model and baseline status.",
"skill-policy-gate": "Blocks skills this organization disabled, on both the typed and the model-invoked path.",
}
# Skills with their own detailed section in the README
MAIN_SKILLS = ["appsec-analyzer", "audit-security-requirements", "verify-requirements"]
INTERNAL_SKILLS = INTERNAL_REQUIRED_SKILLS
# Skills grouped into a single utility section
UTILITY_SKILLS = [
"help",
"security-assessment-health",
"check-permissions",
"status",
"fix-run-issues",
"diagnose-run",
"clean-run-state",
]
def _skill_description(build: Path, skill: str) -> str:
"""First sentence of a skill's description, for the packaged README table.
The frontmatter is parsed as YAML rather than scanned line by line. Several
skills write the description as a block scalar::
description: >-
Install the secure-coding baseline into ...
where the value is on the following lines — a line scan returned the literal
``>-`` and the README table shipped that as the skill's description.
"""
skill_md = build / "skills" / skill / "SKILL.md"
if not skill_md.exists():
return ""
lines = skill_md.read_text(encoding="utf-8").splitlines()
if not lines or lines[0].strip() != "---":
return ""
try:
end = lines.index("---", 1)
except ValueError:
return ""
try:
import yaml
front = yaml.safe_load("\n".join(lines[1:end]))
except Exception: # noqa: BLE001 — a malformed skill must not fail the build