Files
gcp_solution_architecture_a…/app/agent_skills.py
Jonathan Boniface f040493583 feat: run role files on the ADK runtime with scoped Skills
Increment 5 of .scratch/solution-architect-agent/spec.md, test-first.

- agents/*.md: provider-neutral role files for the Orchestrator, nine
  Specialists and the pillar advisor, with a shared Specialist protocol.
- app/agents/roles.py: load and validate role files; Skills, MCP
  servers and models come from the provider bundle.
- app/agents/adk_runtime.py: AgentRuntime on google-adk 2.9 with a
  per-run LlmAgent, role-scoped SkillToolset (no run_skill_script),
  step budgets, early stop on turn-ending tools, LiteLLM models.
- app/execution/pillars.py + toolkit.py: design advisor fans out to one
  advisor per WAF pillar in parallel.
- Specialists receive every earlier-Phase Deliverable as input.
- Bundle gains role_skills, pillar_skills and -latest Gemini aliases;
  pin google-adk[extensions]==2.9.0.
- 37 new tests; full suite 158 passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 09:51:02 +01:00

143 lines
4.7 KiB
Python

"""Agent Skills discovery and frontmatter validation.
A Skill is a directory holding a SKILL.md whose YAML frontmatter follows the
Agent Skills specification (https://agentskills.io/specification).
"""
from __future__ import annotations
import re
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
import yaml
SKILL_FILE = "SKILL.md"
_NAME_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
_FRONTMATTER_PATTERN = re.compile(
r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL
)
_ALLOWED_FIELDS = {
"name",
"description",
"license",
"compatibility",
"metadata",
"allowed-tools",
}
class SkillFormatError(ValueError):
"""A SKILL.md does not conform to the Agent Skills specification."""
@dataclass(frozen=True)
class SkillMeta:
"""The level-1 metadata of a Skill, plus where it lives."""
name: str
description: str
path: Path
def split_frontmatter(text: str, source: Path) -> tuple[dict, str]:
"""Split a markdown document into its YAML frontmatter mapping and body."""
match = _FRONTMATTER_PATTERN.match(text)
if not match:
raise SkillFormatError(f"{source}: missing YAML frontmatter delimited by '---'")
try:
frontmatter = yaml.safe_load(match.group(1))
except yaml.YAMLError as exc:
raise SkillFormatError(
f"{source}: frontmatter is not valid YAML: {exc}"
) from exc
if not isinstance(frontmatter, dict):
raise SkillFormatError(f"{source}: frontmatter must be a mapping")
return frontmatter, text[match.end() :]
def read_skill(skill_dir: Path) -> SkillMeta:
"""Parse and validate the SKILL.md in `skill_dir`."""
skill_file = skill_dir / SKILL_FILE
frontmatter, _ = split_frontmatter(
skill_file.read_text(encoding="utf-8"), skill_file
)
unknown = set(frontmatter) - _ALLOWED_FIELDS
if unknown:
raise SkillFormatError(
f"{skill_file}: unsupported frontmatter fields: {', '.join(sorted(unknown))}"
)
name = frontmatter.get("name")
if not isinstance(name, str) or not name:
raise SkillFormatError(f"{skill_file}: 'name' is required")
if len(name) > 64:
raise SkillFormatError(f"{skill_file}: 'name' must be at most 64 characters")
if not _NAME_PATTERN.match(name):
raise SkillFormatError(
f"{skill_file}: 'name' must use lowercase letters, digits and single hyphens, "
"without leading or trailing hyphens"
)
if name != skill_dir.name:
raise SkillFormatError(
f"{skill_file}: 'name' {name!r} must match its directory {skill_dir.name!r}"
)
description = frontmatter.get("description")
if not isinstance(description, str) or not description.strip():
raise SkillFormatError(
f"{skill_file}: 'description' is required and must be non-empty"
)
if len(description) > 1024:
raise SkillFormatError(
f"{skill_file}: 'description' must be at most 1024 characters"
)
compatibility = frontmatter.get("compatibility")
if compatibility is not None and (
not isinstance(compatibility, str) or not 1 <= len(compatibility) <= 500
):
raise SkillFormatError(
f"{skill_file}: 'compatibility' must be 1-500 characters"
)
metadata = frontmatter.get("metadata")
if metadata is not None and (
not isinstance(metadata, dict)
or not all(
isinstance(key, str) and isinstance(value, str)
for key, value in metadata.items()
)
):
raise SkillFormatError(
f"{skill_file}: 'metadata' must map string keys to string values"
)
for field in ("license", "allowed-tools"):
if field in frontmatter and not isinstance(frontmatter[field], str):
raise SkillFormatError(f"{skill_file}: '{field}' must be a string")
return SkillMeta(name=name, description=description, path=skill_dir)
def discover_skills(directories: Iterable[Path]) -> dict[str, SkillMeta]:
"""Index every Skill that is an immediate child of one of `directories`.
Raises SkillFormatError on an invalid Skill or a name defined twice.
"""
skills: dict[str, SkillMeta] = {}
for directory in directories:
for child in sorted(directory.iterdir()):
if not (child / SKILL_FILE).is_file():
continue
skill = read_skill(child)
if skill.name in skills:
raise SkillFormatError(
f"Skill {skill.name!r} is defined in both {skills[skill.name].path} and {skill.path}"
)
skills[skill.name] = skill
return skills