chunhualin1
2026-07-24 dfcc38b940873e2d5baa99b4c153e505388bf2ad
v20260724
43个文件已添加
2746 ■■■■■ 已修改文件
ai-agent-system-bootstrap/.codex-plugin/plugin.json 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/.gitignore 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/README.md 140 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/bundle.yaml 61 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/install-global-skills.ps1 96 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/contracts/bootstrap-run.md 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/contracts/project-snapshot.md 74 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/contracts/render-result.md 26 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/contracts/system-blueprint.md 58 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/contracts/validation-report.md 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/policies/agent-team-design.md 41 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/policies/default-minimal-system.md 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/policies/generated-team-runtime.md 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/policies/orchestration-scaling.md 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/policies/ownership-and-rebuild.md 70 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/policies/subagent-execution.md 44 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/schemas/agent-definition.md 36 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/schemas/agents-md.md 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/schemas/orchestration-definition.md 37 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/schemas/skill-definition.md 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/schemas/workflow-definition.md 35 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/scripts/validate-structure.py 705 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/AGENTS.md 68 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/agent.md 48 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/bootstrap-manifest.json 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/context-policy.md 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/execution-policy.md 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/merge-policy.md 41 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/skill.SKILL.md 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/subagent-contract.md 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/templates/workflow.md 72 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/shared/traceability/original-behavior-map.md 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-bootstrap/SKILL.md 84 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-bootstrap/agents/openai.yaml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-design/SKILL.md 61 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-design/agents/openai.yaml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-inspect/SKILL.md 66 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-inspect/agents/openai.yaml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-render/SKILL.md 68 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-render/agents/openai.yaml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-validate/SKILL.md 85 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/skills/ai-agent-system-validate/agents/openai.yaml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/tests/test_scripts.py 323 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ai-agent-system-bootstrap/.codex-plugin/plugin.json
New file
@@ -0,0 +1,18 @@
{
  "name": "ai-agent-system-suite",
  "version": "4.0.0",
  "description": "Initialize, rebuild, and validate repository-specific AI Agent Teams with multi-skill orchestration.",
  "author": {
    "name": "Local developer"
  },
  "skills": "./skills/",
  "interface": {
    "displayName": "AI Agent System Suite",
    "shortDescription": "Build repository Agent Teams through coordinated Skills.",
    "longDescription": "Inspect a repository, design its smallest complete Agent Team, scale orchestration to project needs, render directly in the project, and validate the generated output independently.",
    "developerName": "Local developer",
    "category": "Productivity",
    "capabilities": ["Read", "Write"],
    "defaultPrompt": "Use AI Agent System Suite to initialize or rebuild this repository's Agent Team."
  }
}
ai-agent-system-bootstrap/.gitignore
New file
@@ -0,0 +1,3 @@
__pycache__/
*.py[cod]
ai-agent-system-bootstrap/README.md
New file
@@ -0,0 +1,140 @@
# AI Agent System Suite
AI Agent System Suite 用于依据仓库中的真实代码、文档与运行约束,初始化、重建和校验项目级 AI Agent Team。它生成受管的 `.ai/` 目录,并只维护根目录 `AGENTS.md` 中的指定区块。
## 能力范围
套件包含一个编排 Skill 与四个阶段 Skill:
| Skill | 职责 | 是否写入目标仓库 |
| --- | --- | --- |
| `ai-agent-system-bootstrap` | 统一编排完整初始化或重建流程 | 是 |
| `ai-agent-system-inspect` | 读取项目证据并形成 `ProjectSnapshot` | 否 |
| `ai-agent-system-design` | 形成最小完整团队的 `SystemBlueprint` | 否 |
| `ai-agent-system-render` | 按蓝图生成受管文件 | 是 |
| `ai-agent-system-validate` | 独立校验结构、所有权与语义 | 否 |
完整流程如下:
```text
Inspect → Design → Render → Validate
```
每个阶段的输入和输出由 `bundle.yaml` 及 `shared/contracts/` 中的契约约束:
```text
BootstrapRun → ProjectSnapshot → SystemBlueprint → RenderResult → ValidationReport
```
## 生成边界与所有权
生成后的项目仅包含以下受管表面:
```text
<repository-root>/
├─ AGENTS.md                         # 仅维护标记区块
└─ .ai/                              # 整个目录由套件管理
   ├─ bootstrap-manifest.json
   ├─ agents/
   ├─ skills/
   ├─ workflows/
   └─ orchestration/                 # 仅在项目需要时生成
```
- `.ai/` 是完整受管目录;重建时根据当前仓库证据重新生成,不复用旧角色定义。
- `AGENTS.md` 中只有以下标记之间的内容由套件维护,其余内容保留为人工维护内容。
  ```text
  <!-- AI-AGENT-SYSTEM:START -->
  <!-- AI-AGENT-SYSTEM:END -->
  ```
- 目标仓库中已存在无法确认归属的 `.ai/` 目录、重复或不完整的标记时,流程会阻止写入,避免覆盖人工内容。
- 项目级 Skill 固定生成于 `.ai/skills/`,不会生成 `.agent` 或 `.agents` 目录。
## 使用方式
在目标仓库的 Codex 对话中显式调用入口 Skill:
```text
$ai-agent-system-bootstrap 为当前仓库初始化项目级 AI Agent Team。
```
重建已有的受管 Agent Team:
```text
$ai-agent-system-bootstrap 根据当前仓库证据重建项目级 AI Agent Team。
```
入口 Skill 会先确认仓库边界和现有 `.ai/` 的归属,再依次执行检查、设计、生成与校验。生成团队以实际职责、模块边界、风险和验证方式决定角色与本地 Skill;SubAgent 编排级别由项目复杂度决定,并保留顺序执行的回退路径。
若只需读取当前仓库的 Agent Team 结构,可调用:
```text
$ai-agent-system-inspect 检查当前仓库并输出 ProjectSnapshot。
$ai-agent-system-validate 校验当前仓库已安装的 AI Agent Team。
```
## 安装到全局 Skill 目录
在本仓库根目录执行 PowerShell 脚本:
```powershell
.\install-global-skills.ps1
```
脚本默认安装到 `%USERPROFILE%\.codex\skills`;也可指定 Codex 根目录:
```powershell
.\install-global-skills.ps1 -CodexHome 'D:\CodexHome'
```
安装会替换同名的五个全局 Skill 目录,并同步每个 Skill 所需的 `shared/` 契约、策略、模板及 `bundle.yaml`。安装完成后在新的 Codex 对话中即可使用 `$ai-agent-system-bootstrap`。
## 独立校验
校验指定目标仓库的受管结构:
```powershell
python .\shared\scripts\validate-structure.py --root 'D:\path\to\repository' --json
```
校验单个 manifest:
```powershell
python .\shared\scripts\validate-structure.py --manifest-only 'D:\path\to\repository\.ai\bootstrap-manifest.json' --json
```
校验器检查 UTF-8、路径安全性、manifest 清单、受管文件、Skill 前置元数据、工作流 DAG、执行模式、编排策略和所有权标记。发现结构错误时退出码为 `1`;命令异常时退出码为 `2`。
## 开发校验
运行套件的场景测试:
```powershell
python -m unittest discover -s tests -v
```
测试覆盖小型项目的内联编排、复杂项目的并行策略、项目 Skill 路径、人工 `AGENTS.md` 内容保留,以及受限目录的拒绝逻辑。
## 仓库结构
```text
.
├─ skills/                           # 五个可分发的 Codex Skills
├─ shared/
│  ├─ contracts/                     # 阶段输入输出契约
│  ├─ policies/                      # 所有权、编排与运行策略
│  ├─ schemas/                       # 生成物结构定义
│  ├─ scripts/                       # 独立结构校验器
│  ├─ templates/                     # Agent、Skill、工作流和策略模板
│  └─ traceability/                  # 原始能力保持映射
├─ tests/                            # 场景测试
├─ bundle.yaml                       # 套件成员和流水线定义
└─ install-global-skills.ps1         # 全局安装入口
```
## 版本与兼容性
当前套件版本为 `4`,分发清单位于 `.codex-plugin/plugin.json`。`bundle.yaml` 是运行时流水线和成员白名单的唯一来源;插件清单负责 Skill 发现。
ai-agent-system-bootstrap/bundle.yaml
New file
@@ -0,0 +1,61 @@
name: ai-agent-system-suite
version: 4
contract_version: 1
distribution_manifest: .codex-plugin/plugin.json
manifest_role: skill-discovery
bundle_role: pipeline-and-contracts
entry_skill: ai-agent-system-bootstrap
skills:
  - name: ai-agent-system-bootstrap
    role: orchestrator
    suite_entry_policy: public
    side_effects: repository-write
  - name: ai-agent-system-inspect
    role: inspect
    suite_entry_policy: public
    side_effects: none
  - name: ai-agent-system-design
    role: design
    suite_entry_policy: orchestrator-gated
    side_effects: none
  - name: ai-agent-system-render
    role: render
    suite_entry_policy: orchestrator-gated
    side_effects: repository-write
  - name: ai-agent-system-validate
    role: validate
    suite_entry_policy: public
    side_effects: none
pipeline:
  - skill: ai-agent-system-inspect
    input: BootstrapRun
    output: ProjectSnapshot
  - skill: ai-agent-system-design
    input: ProjectSnapshot
    output: SystemBlueprint
  - skill: ai-agent-system-render
    input: BootstrapRun and SystemBlueprint
    output: RenderResult
  - skill: ai-agent-system-validate
    input: BootstrapRun, ProjectSnapshot, SystemBlueprint, and RenderResult
    output: ValidationReport
rules:
  suite_entry_policy_enforcement: required-contract-inputs
  sibling_skill_calls: forbidden
  orchestrator_only_dispatch: true
  dynamic_skill_discovery: false
  maximum_skill_call_depth: 1
  render_target: repository-root
  generated_ai_directory_ownership: complete
  project_skill_location: .ai/skills
  orchestration_scaling: evidence-driven
  agent_team_size: smallest-complete-no-fixed-cap
  agents_md_ownership: managed-block-only
ai-agent-system-bootstrap/install-global-skills.ps1
New file
@@ -0,0 +1,96 @@
[CmdletBinding()]
param(
    [Parameter()]
    [string]$CodexHome
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($CodexHome)) {
    $CodexHome = if ([string]::IsNullOrWhiteSpace($env:CODEX_HOME)) {
        Join-Path ([Environment]::GetFolderPath('UserProfile')) '.codex'
    }
    else {
        $env:CODEX_HOME
    }
}
$suiteRoot = [IO.Path]::GetFullPath($PSScriptRoot)
$sourceSkillsRoot = Join-Path $suiteRoot 'skills'
$sourceSharedRoot = Join-Path $suiteRoot 'shared'
$sourceBundle = Join-Path $suiteRoot 'bundle.yaml'
$targetCodexRoot = [IO.Path]::GetFullPath($CodexHome)
$targetSkillsRoot = [IO.Path]::GetFullPath((Join-Path $targetCodexRoot 'skills'))
$skillNames = @(
    'ai-agent-system-bootstrap'
    'ai-agent-system-inspect'
    'ai-agent-system-design'
    'ai-agent-system-render'
    'ai-agent-system-validate'
)
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
foreach ($requiredPath in @($sourceSkillsRoot, $sourceSharedRoot, $sourceBundle)) {
    if (-not (Test-Path -LiteralPath $requiredPath)) {
        throw "Required suite path is missing: $requiredPath"
    }
}
New-Item -ItemType Directory -Path $targetSkillsRoot -Force | Out-Null
$resolvedSkillsRoot = (Get-Item -LiteralPath $targetSkillsRoot).FullName.TrimEnd('\', '/')
foreach ($skillName in $skillNames) {
    $sourceSkill = Join-Path $sourceSkillsRoot $skillName
    $sourceSkillFile = Join-Path $sourceSkill 'SKILL.md'
    if (-not (Test-Path -LiteralPath $sourceSkillFile -PathType Leaf)) {
        throw "Skill source is incomplete: $sourceSkillFile"
    }
    $targetSkill = [IO.Path]::GetFullPath((Join-Path $resolvedSkillsRoot $skillName))
    if ([IO.Path]::GetDirectoryName($targetSkill).TrimEnd('\', '/') -ne $resolvedSkillsRoot) {
        throw "Refusing to install outside the global Skill directory: $targetSkill"
    }
    if (Test-Path -LiteralPath $targetSkill) {
        $existing = Get-Item -LiteralPath $targetSkill -Force
        if (-not $existing.PSIsContainer) {
            throw "Skill target exists and is not a directory: $targetSkill"
        }
        if (($existing.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
            throw "Skill target is a symlink or junction; remove it manually first: $targetSkill"
        }
        Remove-Item -LiteralPath $targetSkill -Recurse -Force
    }
    New-Item -ItemType Directory -Path $targetSkill | Out-Null
    Copy-Item -LiteralPath (Join-Path $sourceSkill 'SKILL.md') -Destination $targetSkill
    if (Test-Path -LiteralPath (Join-Path $sourceSkill 'agents')) {
        Copy-Item -LiteralPath (Join-Path $sourceSkill 'agents') -Destination $targetSkill -Recurse
    }
    Copy-Item -LiteralPath $sourceSharedRoot -Destination $targetSkill -Recurse
    Copy-Item -LiteralPath $sourceBundle -Destination (Join-Path $targetSkill 'bundle.yaml')
    $installedSkillFile = Join-Path $targetSkill 'SKILL.md'
    $skillText = [IO.File]::ReadAllText($installedSkillFile)
    $skillText = $skillText.Replace('../../shared/', 'shared/').Replace('../../bundle.yaml', 'bundle.yaml')
    [IO.File]::WriteAllText($installedSkillFile, $skillText, $utf8NoBom)
    if ($skillText -notmatch "(?m)^name:\s*$([regex]::Escape($skillName))\s*$") {
        throw "Installed Skill frontmatter name does not match its directory: $installedSkillFile"
    }
    $localLinks = [regex]::Matches($skillText, '\]\((?!https?://|#)([^)]+)\)')
    foreach ($match in $localLinks) {
        $relativePath = $match.Groups[1].Value.Replace('/', [IO.Path]::DirectorySeparatorChar)
        $linkedPath = [IO.Path]::GetFullPath((Join-Path $targetSkill $relativePath))
        if (-not (Test-Path -LiteralPath $linkedPath)) {
            throw "Installed Skill contains a broken local reference: $($match.Groups[1].Value)"
        }
    }
    Write-Host "Installed $skillName -> $targetSkill"
}
Write-Host "Installed $($skillNames.Count) Skills into $resolvedSkillsRoot"
Write-Host 'The updated Skills are available to new Codex turns.'
ai-agent-system-bootstrap/shared/contracts/bootstrap-run.md
New file
@@ -0,0 +1,30 @@
# BootstrapRun Contract
`BootstrapRun` is the orchestrator-owned state for one initialization or rebuild. Keep it immutable except for phase status, returned artifact identifiers, and the one-time `pending` mode resolution after Inspect.
```yaml
schema_version: 1
run_id: <lowercase identifier>
suite_version: 4
repository_root: <absolute path>
mode: pending | initialize | rebuild
user_request: <verbatim scoped request>
explicit_constraints: []
explicit_exclusions: []
allowed_warning_codes: []
current_phase: inspect | design | render | validate | complete
status: active | blocked | failed | complete
artifacts:
  project_snapshot_id: null
  system_blueprint_id: null
  render_result_id: null
  validation_report_id: null
```
Rules:
- Bind one run to one canonical repository root.
- Preserve the user request and explicit constraints unchanged across phases.
- Open with `mode: pending`; after an accepted ProjectSnapshot, resolve it exactly once to `initialize` or `rebuild` from the snapshot ownership classification.
- Treat an unknown warning code as blocking successful completion.
- Record phase outputs by identifier; do not let a later phase silently replace an earlier artifact.
ai-agent-system-bootstrap/shared/contracts/project-snapshot.md
New file
@@ -0,0 +1,74 @@
# ProjectSnapshot Contract
`ai-agent-system-inspect` returns this read-only evidence package.
```yaml
schema_version: 1
snapshot_id: <run-id plus digest>
run_id: <run id>
status: success | blocked
request:
  user_request: <verbatim scoped request>
  explicit_constraints: []
  explicit_exclusions: []
repository:
  root: <absolute path>
  purpose: <evidence-based summary>
  evidence_files: []
project:
  users: []
  goals: []
  technologies: []
  runtimes: []
  modules:
    - name: <module>
      paths: []
      responsibilities: []
      evidence: []
  ownership_boundaries: []
  recurring_work: []
data:
  stores: []
  migrations: []
integrations: []
quality:
  tests: []
  compatibility: []
  release: []
security:
  authentication: []
  authorization: []
  secrets: []
  privacy_or_compliance: []
delivery:
  build: []
  deployment: []
  documentation: []
agent_runtime:
  subagents: supported | unsupported | unknown
  shared_workspace: supported | unsupported | unknown
  worktrees: supported | unsupported | unknown
ownership:
  agents_md_marker: current | legacy | absent | conflict
  agents_md_human_content: present | absent
  ai_directory: absent | managed | legacy-agent-team | unrelated | mixed
  existing_managed_paths: []
  existing_generated_repo_skills: []
evidence: []
evidence_index:
  - path: <repository-relative path>
    supports: []
domain_assessment:
  - domain: product | architecture | frontend | backend | data | security | qa | devops | documentation | review | project-specific
    present: true | false | unknown
    independent_judgment: <evidence-based explanation>
    risks: []
    verification_methods: []
    module_ownership: []
    evidence: []
assumptions: []
unknowns: []
blockers: []
```
Each non-empty conclusion must cite an evidence path or appear under `assumptions`. Preserve raw evidence paths, module boundaries, project characteristics, and inference grounds; the snapshot is an evidence package, not a lossy summary. Preserve the BootstrapRun request and constraints verbatim in `request`. Old generated Agent roles, Skills, and workflows are ownership evidence only; they are not design inputs.
ai-agent-system-bootstrap/shared/contracts/render-result.md
New file
@@ -0,0 +1,26 @@
# RenderResult Contract
`ai-agent-system-render` returns this inventory after writing directly to the repository.
```yaml
schema_version: 1
render_result_id: <blueprint id plus digest>
run_id: <run id>
input_blueprint_id: <blueprint id>
status: success | failed
repository_root: <absolute path>
manifest_path: .ai/bootstrap-manifest.json
generated_files:
  - path: <repository-relative POSIX path>
    sha256: <hex digest>
counts:
  agents: 0
  project_skills: 0
  workflows: 0
  orchestration_policies: 0
  files: 0
warnings: []
errors: []
```
The inventory covers every render-owned file in the repository. Project-local Skills are counted from `.ai/skills`. Hash the managed block in `AGENTS.md` and every file under `.ai`, including the manifest.
ai-agent-system-bootstrap/shared/contracts/system-blueprint.md
New file
@@ -0,0 +1,58 @@
# SystemBlueprint Contract
`ai-agent-system-design` returns the only design source accepted by Render and Validate.
```yaml
schema_version: 1
blueprint_id: <snapshot id plus digest>
run_id: <run id>
input_snapshot_id: <snapshot id>
status: success | blocked
project_summary: <concise summary>
complexity:
  level: small | moderate | complex
  reasons: []
responsibility_coverage:
  - domain: <domain>
    disposition: dedicated-agent | combined-agent | workflow-owned | not-applicable
    owner: <agent or workflow or null>
    rationale: <evidence-based reason>
    evidence: []
agents:
  - name: <hyphen-case agent name>
    primary: true | false
    role_exists_because: <independent long-term responsibility>
    execution_default: inline | either | subagent-readonly
    source_evidence: []
    definition: {}
project_skills:
  - name: <project-prefixed skill name>
    source_evidence: []
    definition: {}
workflows:
  - name: <hyphen-case workflow name>
    source_evidence: []
    definition: {}
orchestration:
  level: inline | coordinated | isolated | parallel
  rationale: []
  rules_in_agents_md: []
  policies:
    - name: <policy filename>
      required_by: []
      definition: {}
agents_md:
  project_overview: <text>
  primary_agent: <agent name>
  routing: []
managed_output:
  ai_directory: .ai
  agents_md_start: "<!-- AI-AGENT-SYSTEM:START -->"
  agents_md_end: "<!-- AI-AGENT-SYSTEM:END -->"
traceability: []
assumptions: []
warnings: []
blockers: []
```
Exactly one Agent must have `primary: true`. Agent-role existence and SubAgent execution are separate fields: execution cost cannot justify deleting a durable role. Every rendered component must appear here and trace to snapshot evidence or an explicit assumption. Warning acceptance belongs only to `BootstrapRun.allowed_warning_codes`; Design cannot authorize a warning.
ai-agent-system-bootstrap/shared/contracts/validation-report.md
New file
@@ -0,0 +1,30 @@
# ValidationReport Contract
`ai-agent-system-validate` returns this read-only decision.
```yaml
schema_version: 1
validation_report_id: <scope-specific stable id>
scope: bootstrap-candidate | installed-standalone
run_id: <run id>
input_blueprint_id: <blueprint id or null for standalone>
input_render_result_id: <render result id or null for standalone>
candidate_digest: <tree digest>
validated_run_id: <manifest run id; bootstrap scope also matches BootstrapRun>
validated_blueprint_id: <manifest blueprint id; bootstrap scope also matches input blueprint>
status: passed | passed-with-warnings | blocked | failed
structural_errors: []
semantic_errors: []
warnings:
  - code: <stable code>
    path: <path or null>
    message: <finding>
cross_reference_errors: []
write_scope_conflicts: []
not_applicable_checks: []
final_decision: complete | reject | report-only
```
`complete` is valid only for `scope: bootstrap-candidate` with `passed`, or with `passed-with-warnings` when every warning code is explicitly allowed by the BootstrapRun. Unknown warnings default to `reject`. Validation must reject any run ID, blueprint ID, render result ID, or digest mismatch. Standalone scope always returns `report-only`.
Build `validation_report_id` from `input_render_result_id + candidate_digest` for bootstrap candidates. Build it from `validated_run_id + candidate_digest` for installed standalone reports.
ai-agent-system-bootstrap/shared/policies/agent-team-design.md
New file
@@ -0,0 +1,41 @@
# Agent Team Design Policy
Design the smallest complete Agent Team from current project responsibility boundaries. "Smallest" removes roles with no independent decision value; "complete" preserves every evidenced long-term responsibility with distinct judgment, risk, verification, or module ownership.
## Responsibility coverage
Evaluate every domain below and record one disposition in `SystemBlueprint.responsibility_coverage`:
- product and requirements
- architecture
- frontend and user interaction
- backend and integrations
- data, persistence, and migrations
- security, permissions, secrets, privacy, and safety
- QA, compatibility, and release confidence
- build, packaging, deployment, and operations
- documentation and onboarding
- final independent review
- project-specific business or technical domains
Use `not-applicable` only with repository evidence. Use `combined-agent` only when the combined responsibilities share the same decisions, artifacts, risks, verification methods, and module ownership. Use `dedicated-agent` when any of those differ materially. Use `workflow-owned` only for a bounded lifecycle concern with no durable role ownership.
## Role versus execution
Decide whether a role exists before choosing its execution mode. A role may remain a distinct Agent definition while normally running inline. SubAgent startup cost, thread count, and coordination cost control execution planning; they never erase a durable responsibility.
## Anti-collapse audit
Before completing Design:
1. Inspect every general Agent that owns more than two technical domains.
2. Split it when the domains have different technical judgments, risks, verification methods, or module ownership.
3. Confirm frontend, backend, data, security, DevOps, documentation, and project-specific domains were not omitted merely because they often execute inline.
4. Confirm no Agent exists solely to increase count, parallelism, or prompt specialization.
5. Confirm different repository evidence can produce materially different team sizes and structures.
Small repositories may close the lifecycle with one primary implementation Agent plus one verification role. Complex full-stack or multi-module repositories commonly require more than five Agents when their responsibility boundaries are independent. No numeric target or cap applies.
## Skills and workflows
Create project-local Skills for repeated executable procedures, not job titles. Create workflows for real project lifecycles and express dependencies, stable inputs, execution modes, scopes, synchronization, verification, and routing. Keep explicit Agent/Skill selection precedence and global-Skill opt-in in the generated runtime.
ai-agent-system-bootstrap/shared/policies/default-minimal-system.md
New file
@@ -0,0 +1,15 @@
# Default Minimal System Policy
Use this policy only when the repository is sparse yet the user explicitly requests initialization.
Build the smallest closed loop supported by evidence:
- one primary general implementation Agent
- one workflow covering routing, implementation, verification, and completion
- one independent review or QA Agent only when the repository has a verifiable software or document output
- project Skills only for repeated procedures established by repository commands or documentation
- no parallel writer by default
- evaluate every responsibility domain in `agent-team-design.md`; combine only domains that share decisions, artifacts, risks, verification, and ownership
- keep lightweight orchestration rules in `AGENTS.md` and the workflow; omit `.ai/orchestration` when no separate policy is needed
List every assumption. If a missing fact would change ownership, security, persistence, deployment, or write boundaries, return `blocked` instead of generating generic boilerplate.
ai-agent-system-bootstrap/shared/policies/generated-team-runtime.md
New file
@@ -0,0 +1,31 @@
# Generated Team Runtime Policy
This policy governs the Agent Team produced in a target repository. It does not govern execution of the Bootstrap plugin itself.
## Instruction priority
1. Preserve higher-priority system, safety, user, and human-authored repository instructions.
2. Apply an Agent or Skill explicitly named by the user exactly as scoped.
3. Run automatic Agent matching only when the user names neither an Agent nor a Skill, unless the user explicitly requests validation, replacement, supplementation, or automatic matching.
## Skill boundary
- Project Skills live under `.ai/skills` and may be used when explicitly named or referenced by the selected project Agent/workflow.
- Skills outside the repository are global Skills. Activate a global Skill only when the user explicitly names or authorizes it.
- A generated Agent, workflow, similarity match, missing local capability, or convenience does not authorize global Skill activation.
- Prefer a project Skill when a project and global Skill share a name, unless the user clearly identifies the global one.
## Automatic Agent routing
- Match task goal, affected modules, required output, stable inputs, and decision ownership to one primary Agent.
- Add supporting Agents only when their distinct output is required.
- Load only the selected definitions and referenced project Skills/workflows.
- Fall back to the general implementation or review Agent declared by the generated team.
## Orchestrator ownership
The main orchestrator or primary Agent owns task decomposition, dependency ordering, execution-mode selection, immutable handoffs, write ownership, conflict decisions, integration, final verification, and completion claims.
## Reporting
State routing and execution modes briefly when useful. Report partial results, rejected recommendations, unperformed verification, and remaining risks explicitly.
ai-agent-system-bootstrap/shared/policies/orchestration-scaling.md
New file
@@ -0,0 +1,21 @@
# Orchestration Scaling Policy
Preserve orchestration capability while scaling its files to the project.
## Inline level
Use for small, tightly coupled projects. Put execution-mode choice, bounded handoff fields, the unified return contract, single-writer ownership, sequential fallback, integration authority, and verification gates in root `AGENTS.md` and workflows. Do not create `.ai/orchestration` only to repeat those rules.
## Coordinated level
Add `.ai/orchestration/execution-policy.md` when multiple Agents require recurring execution-mode decisions, failure handling, or concurrency limits.
## Isolated level
Add `subagent-contract.md` and `context-policy.md` when independent review, security/QA isolation, context separation, versioned source-of-truth artifacts, or stale-work handling is material.
## Parallel level
Add `merge-policy.md` when independent writers can run concurrently, worktrees are used, several outputs require integration, or merge order and conflict decisions recur.
Every level keeps role selection separate from thread selection. Parallelism requires stable inputs, dependency-independent tasks, disjoint write scopes, synchronization gates, and one integration owner. When runtime isolation is unavailable, execute the same role and workflow boundaries sequentially inline.
ai-agent-system-bootstrap/shared/policies/ownership-and-rebuild.md
New file
@@ -0,0 +1,70 @@
# Ownership and Rebuild Policy
Treat the generated Agent Team as derived output. Rebuild managed components from current repository evidence; do not optimize or merge old Agent definitions.
## Managed surfaces
- The complete generated `.ai` directory is suite-owned after initialization, including `.ai/skills`.
- Durable run artifacts belong under `.ai/runs` only when the generated design includes them; a rebuild must explicitly preserve or regenerate them according to the blueprint.
- Only the root `AGENTS.md` block between current markers is suite-owned.
- Text outside the markers is human-owned.
Current markers:
```text
<!-- AI-AGENT-SYSTEM:START -->
<!-- AI-AGENT-SYSTEM:END -->
```
Recognize one legacy `AI-AGENT-ROUTING` block for migration. Block generation when marker halves are missing, markers repeat, or current and legacy blocks coexist.
## Ownership adoption
- `initialize`: `.ai` is absent and no managed block exists.
- `rebuild`: a strict current manifest whose declared inventory matches the installed managed tree, or an unambiguous legacy Agent Team, exists.
- `.ai` absent with a current or legacy managed marker is an orphan ownership conflict. Inspect returns `blocked`; Bootstrap leaves mode pending; Render refuses the target.
- Block an unrelated or mixed `.ai` directory. Do not assume ownership from its name alone.
- Use old generated paths only to identify rebuild scope. Do not carry old roles, prompts, or workflows into Design.
An unambiguous legacy Agent Team satisfies every condition below:
- `.ai` and every descendant are real directories/files with no symlink or junction.
- `.ai/agents` and `.ai/workflows` are directories.
- Top-level `.ai` entries are limited to `agents`, `skills`, `workflows`, `orchestration`, `runs`, and `bootstrap-manifest.yaml`.
- Root `AGENTS.md` contains exactly one ordered current marker pair or exactly one ordered legacy marker pair, never both.
Inspect and Render use this exact predicate. Any deviation is unrelated or mixed ownership and blocks adoption.
## Direct rebuild
1. Complete Inspect and Design before writing generated files.
2. Recreate the suite-owned `.ai` directory directly under the repository root.
3. Preserve human-owned root `AGENTS.md` text and update only its managed block.
4. Validate structure, semantics, inventory, hashes, run ID, blueprint ID, and ownership against the repository after Render completes.
5. Report any partial writes when Render or Validate fails.
## Target manifest
Write UTF-8 JSON to `.ai/bootstrap-manifest.json`:
```json
{
  "schema_version": 1,
  "generator": "ai-agent-system-bootstrap",
  "suite_version": 4,
  "run_id": "bootstrap-run-id",
  "blueprint_id": "system-blueprint-id",
  "generation_mode": "initialize",
  "generated_at": "ISO-8601 UTC",
  "managed_paths": [
    ".ai"
  ],
  "agents_md_managed_block": {
    "start": "<!-- AI-AGENT-SYSTEM:START -->",
    "end": "<!-- AI-AGENT-SYSTEM:END -->"
  },
  "generated_files": []
}
```
Use `generation_mode: "rebuild"` for rebuilds. The manifest field set, value types, markers, managed paths, and file inventory are strict; an arbitrary JSON file does not establish suite ownership.
ai-agent-system-bootstrap/shared/policies/subagent-execution.md
New file
@@ -0,0 +1,44 @@
# Selective SubAgent Execution Policy
Agent roles define responsibility. Execution plans decide threads.
## Concrete modes
- `inline`: execute in the main thread.
- `subagent-readonly`: isolate exploration, analysis, QA, security, architecture review, or final review with no writes.
- `subagent-shared`: use a SubAgent in the shared workspace only for serialized, non-overlapping writes.
- `subagent-worktree`: use an isolated worktree for independent parallel implementation with stable contracts.
Default to `inline`. Use a SubAgent only when the task is independently describable, inputs are stable, output is structured, scope is bounded, file overlap is low, and isolation or parallelism outweighs coordination cost.
## Concurrency gates
- Assign one writer to each file or module per phase.
- Run parallel writers only with disjoint write scopes.
- Keep dependency manifests, lockfiles, migrations, generated code, routing, and integration files under one owner.
- Serialize work when overlap emerges.
- Keep repository exploration, security, QA, and review read-only by default.
- Degrade to sequential `inline` execution when SubAgents or worktrees are unavailable.
## Handoff and return
Every delegated task carries an immutable objective, acceptance criteria, source of truth, inputs, read scope, write scope, required project Skills, prohibited actions, verification, escalation conditions, and required return format.
Use one return contract everywhere:
```text
status
summary
findings_or_changes
artifacts
files_inspected
files_changed
assumptions
risks
verification
unresolved_items
recommended_next_action
```
A SubAgent returns partial evidence when possible. The main orchestrator decides whether to retry, reject, serialize, or integrate it.
ai-agent-system-bootstrap/shared/schemas/agent-definition.md
New file
@@ -0,0 +1,36 @@
# Agent Definition Schema
Store each Agent at `.ai/agents/<agent-name>.md`, using lowercase hyphen-case.
Required headings:
```text
# <Agent Name>
## role
## input
## output
## decision
## execution
## return_contract
```
`execution` declares capability, not a thread already started:
```yaml
default_mode: inline
allowed_modes:
  - inline
  - subagent-readonly
  - subagent-shared
  - subagent-worktree
parallelizable: false
write_scope: []
requires: []
conflicts_with: []
failure_policy: return-partial | retry-once | escalate
```
Use only modes the role can safely perform. A read-only role has an empty `write_scope` and never declares a writable mode. The `return_contract` must use the unified fields from `subagent-execution.md`.
Make `role`, `input`, `output`, and `decision` specific enough for deterministic routing. Do not copy the root policy into Agent files.
ai-agent-system-bootstrap/shared/schemas/agents-md.md
New file
@@ -0,0 +1,18 @@
# Root AGENTS.md Schema
The generated artifact is one managed block, not a replacement for human repository instructions.
Required content:
1. current start and end markers, each exactly once
2. project overview
3. instruction priority and explicit Agent/Skill precedence
4. project versus global Skill boundary
5. automatic primary/supporting Agent routing
6. execution planning and selective SubAgent rules
7. task brief and unified return contract
8. single-writer, integration, verification, and completion ownership
9. links to every generated Agent, project Skill, workflow, and blueprint-selected orchestration policy
10. sequential fallback and concise reporting rules
Reference only files present in the blueprint. Keep role examples out of the rendered block unless those roles exist.
ai-agent-system-bootstrap/shared/schemas/orchestration-definition.md
New file
@@ -0,0 +1,37 @@
# Orchestration Definition Schema
Keep orchestration capability in every generated system. Put lightweight selection, handoff, single-writer, integration, and sequential-fallback rules directly in `AGENTS.md` and workflows. Create `.ai/orchestration` only when separate policies improve execution clarity.
Available policy files:
```text
.ai/orchestration/execution-policy.md
.ai/orchestration/subagent-contract.md
.ai/orchestration/context-policy.md
.ai/orchestration/merge-policy.md
```
Selection by project need:
- `inline`: no orchestration directory is required; keep the lightweight rules in `AGENTS.md` and the workflow.
- `coordinated`: create `execution-policy.md` when several Agents need non-trivial execution-mode selection.
- `isolated`: also create `subagent-contract.md` and `context-policy.md` when isolated review, context separation, or durable task briefs are used.
- `parallel`: also create `merge-policy.md` when parallel writers, worktrees, synchronization, or multi-output integration are used.
Generate only the files named in `SystemBlueprint.orchestration.policies`. Never emit an empty directory.
## Execution policy
Define concrete modes, default mode, SubAgent eligibility gates, runtime capabilities, concurrency limit, retry/partial-return behavior, and sequential fallback.
## SubAgent contract
Define the immutable Task Brief and the unified return fields from `subagent-execution.md`.
## Context policy
Define source-of-truth artifacts, minimum context, assumption recording, versioning, change propagation, stale-work cancellation/restart, and optional run artifacts.
## Merge policy
Define file/module ownership, isolation convention, merge order, conflict decisions, rejected recommendations, required integration checks, cleanup, and final completion authority.
ai-agent-system-bootstrap/shared/schemas/skill-definition.md
New file
@@ -0,0 +1,22 @@
# Project Skill Definition Schema
Store each generated project Skill at `.ai/skills/<skill-name>/SKILL.md`. Use project-specific names when needed to avoid collisions with common global Skills.
Required frontmatter contains only:
```yaml
---
name: "<lowercase-hyphen-case, max 64 characters>"
description: "<what it does plus the distinct repository task that triggers it>"
---
```
Required body:
```text
# <Skill Name>
## Steps
## Output
```
Keep both frontmatter values YAML strings; double-quote them and escape embedded quotes. Write imperative steps with explicit inputs, completion criteria, and validation gates. Put trigger conditions in frontmatter `description`; do not duplicate them in a `when_to_use` section. Create a Skill only for a repeated executable procedure, not a job title, schema fragment, or one-off instruction.
ai-agent-system-bootstrap/shared/schemas/workflow-definition.md
New file
@@ -0,0 +1,35 @@
# Workflow Definition Schema
Store each workflow at `.ai/workflows/<workflow-name>.md`.
Required headings:
```text
# <Workflow Name>
## goal
## flow
## execution_graph
## steps
## synchronization_gates
## routing_rules
## output_format
```
The `### <step-id>: <Step Name>` heading is the unique step identifier. Each step body declares:
```yaml
agent: <existing Agent>
skill: .ai/skills/<existing-skill>/SKILL.md | none
execution: inline | subagent-readonly | subagent-shared | subagent-worktree
depends_on: []
parallel_group: null
requires: []
read_scope: []
write_scope: []
input: []
output: []
verification: []
next: []
```
Dependencies must be acyclic. Parallel groups contain only dependency-independent steps. Read-only execution has no write scope. Synchronization gates prevent implementation before stable contracts, integration before required results, and completion before verification.
ai-agent-system-bootstrap/shared/scripts/validate-structure.py
New file
@@ -0,0 +1,705 @@
#!/usr/bin/env python3
"""Deterministically validate a repository Agent Team."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from datetime import datetime
from pathlib import Path, PurePosixPath
from typing import Iterable
START = "<!-- AI-AGENT-SYSTEM:START -->"
END = "<!-- AI-AGENT-SYSTEM:END -->"
LEGACY_START = "<!-- AI-AGENT-ROUTING:START -->"
LEGACY_END = "<!-- AI-AGENT-ROUTING:END -->"
NAME = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
RUN_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
ISO_UTC = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$")
PATH_REF = re.compile(
    r"(?<![A-Za-z0-9_])\.ai/(?:agents|skills|workflows|orchestration)/[A-Za-z0-9._/-]+"
)
EXECUTION_MODES = {"inline", "subagent-readonly", "subagent-shared", "subagent-worktree"}
AGENT_HEADINGS = ["## role", "## input", "## output", "## decision", "## execution", "## return_contract"]
SKILL_HEADINGS = ["## Steps", "## Output"]
WORKFLOW_HEADINGS = [
    "## goal",
    "## flow",
    "## execution_graph",
    "## steps",
    "## synchronization_gates",
    "## routing_rules",
    "## output_format",
]
WORKFLOW_STEP_FIELDS = {
    "agent",
    "skill",
    "execution",
    "depends_on",
    "parallel_group",
    "requires",
    "read_scope",
    "write_scope",
    "input",
    "output",
    "verification",
    "next",
}
ORCHESTRATION_FILES = {
    "execution-policy.md",
    "subagent-contract.md",
    "context-policy.md",
    "merge-policy.md",
}
MANIFEST_FIELDS = {
    "schema_version",
    "generator",
    "suite_version",
    "run_id",
    "blueprint_id",
    "generation_mode",
    "generated_at",
    "managed_paths",
    "agents_md_managed_block",
    "generated_files",
}
def configure_stdio() -> None:
    for stream in (sys.stdout, sys.stderr):
        if hasattr(stream, "reconfigure"):
            stream.reconfigure(encoding="utf-8", errors="strict")
def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--root")
    source.add_argument("--manifest-only")
    parser.add_argument("--json", action="store_true")
    return parser.parse_args()
def finding(path: str, message: str, code: str) -> dict:
    return {"code": code, "path": path, "message": message}
def is_reparse(path: Path) -> bool:
    return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())
def under(path: Path, root: Path) -> bool:
    try:
        path.relative_to(root)
        return True
    except ValueError:
        return False
def safe_repo_path(raw: str, *, allow_tree_glob: bool = False) -> str | None:
    """Return a canonical repository-relative POSIX path, or None when unsafe."""
    if not isinstance(raw, str) or not raw or raw != raw.strip():
        return None
    if "\\" in raw or ":" in raw or raw.startswith(("/", "./")) or "//" in raw:
        return None
    core = raw
    if allow_tree_glob and core.endswith("/**"):
        core = core[:-3]
    if not core or core == "." or any(character in core for character in "*?[]"):
        return None
    path = PurePosixPath(core)
    if any(part in {"", ".", ".."} for part in path.parts):
        return None
    if path.is_absolute() or path.as_posix() != core:
        return None
    return raw
def repository_path(root: Path, relative: str) -> Path:
    return root.joinpath(*PurePosixPath(relative).parts)
def check_path_chain(root: Path, relative: str, errors: list[dict]) -> Path | None:
    if safe_repo_path(relative) is None:
        errors.append(finding(relative, "path is not a safe repository-relative POSIX path", "unsafe-path"))
        return None
    resolved_root = root.resolve(strict=True)
    current = root
    for part in PurePosixPath(relative).parts:
        current /= part
        if (current.exists() or current.is_symlink()) and is_reparse(current):
            errors.append(finding(relative, f"path chain contains a symlink or junction: {current.name}", "reparse-point"))
            return None
        if not under(current.resolve(strict=False), resolved_root):
            errors.append(finding(relative, "resolved path escapes the repository", "unsafe-path"))
            return None
    return current
def walk_managed(root: Path, relative: str, errors: list[dict]) -> list[Path]:
    start = check_path_chain(root, relative, errors)
    if start is None or not start.exists():
        return []
    files: list[Path] = []
    pending = [start]
    while pending:
        current = pending.pop()
        if is_reparse(current):
            errors.append(finding(current.relative_to(root).as_posix(), "managed output contains a symlink or junction", "reparse-point"))
            continue
        if current.is_dir():
            pending.extend(current.iterdir())
        elif current.is_file():
            files.append(current)
    return files
def read_utf8(path: Path, root: Path, errors: list[dict], warnings: list[dict]) -> str | None:
    relative = path.relative_to(root).as_posix()
    try:
        data = path.read_bytes()
    except OSError as exc:
        errors.append(finding(relative, f"cannot read regular UTF-8 file: {exc}", "unreadable-file"))
        return None
    if data.startswith(b"\xef\xbb\xbf"):
        warnings.append(finding(relative, "UTF-8 BOM is unnecessary", "utf8-bom"))
    try:
        return data.decode("utf-8-sig")
    except UnicodeDecodeError as exc:
        errors.append(finding(relative, f"not valid UTF-8: {exc}", "invalid-utf8"))
        return None
def check_fences(text: str) -> bool:
    opened: tuple[str, int] | None = None
    for line in text.splitlines():
        match = re.match(r"^\s*(`{3,}|~{3,})", line)
        if not match:
            continue
        token = match.group(1)
        current = (token[0], len(token))
        if opened is None:
            opened = current
        elif current[0] == opened[0] and current[1] >= opened[1]:
            opened = None
    return opened is None
def require_headings(text: str, headings: Iterable[str], relative: str, errors: list[dict]) -> None:
    lines = set(text.splitlines())
    for heading in headings:
        if heading not in lines:
            errors.append(finding(relative, f"missing heading: {heading}", "missing-heading"))
def parse_frontmatter(text: str) -> dict[str, str] | None:
    lines = text.splitlines()
    if not lines or lines[0] != "---":
        return None
    try:
        end = lines.index("---", 1)
    except ValueError:
        return None
    values: dict[str, str] = {}
    for line in lines[1:end]:
        if not line.strip() or line.lstrip().startswith("#"):
            continue
        if line != line.lstrip() or ":" not in line:
            return None
        key, raw = line.split(":", 1)
        key, raw = key.strip(), raw.strip()
        if not re.fullmatch(r"[a-z][a-z0-9_-]*", key) or key in values or not raw or raw in {"|", ">"}:
            return None
        if raw.startswith('"'):
            try:
                value = json.loads(raw)
            except json.JSONDecodeError:
                return None
            if not isinstance(value, str):
                return None
        elif raw.startswith("'"):
            if len(raw) < 2 or not raw.endswith("'"):
                return None
            value = raw[1:-1].replace("''", "'")
        else:
            if raw.endswith(('"', "'")) or raw.startswith(("[", "{", "&", "*", "!")):
                return None
            lowered = raw.casefold()
            typed_scalar = (
                lowered in {"null", "~", "true", "false", "yes", "no", "on", "off", ".nan", ".inf", "+.inf", "-.inf"}
                or re.fullmatch(r"[-+]?(?:0|[1-9][0-9_]*)(?:\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?", raw) is not None
                or re.fullmatch(r"0[xX][0-9a-fA-F_]+|0[oO][0-7_]+", raw) is not None
                or re.fullmatch(r"\d{4}-\d{2}-\d{2}(?:[Tt ].*)?", raw) is not None
            )
            if typed_scalar:
                return None
            value = raw
        values[key] = value
    return values
def load_manifest(path: Path, errors: list[dict], display_path: str) -> dict:
    if not path.is_file() or is_reparse(path):
        errors.append(finding(display_path, "manifest is missing or is a reparse point", "missing-manifest"))
        return {}
    try:
        data = path.read_bytes()
        if data.startswith(b"\xef\xbb\xbf"):
            text = data.decode("utf-8-sig")
        else:
            text = data.decode("utf-8")
        value = json.loads(text)
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        errors.append(finding(display_path, f"manifest is not valid UTF-8 JSON: {exc}", "invalid-manifest"))
        return {}
    if not isinstance(value, dict):
        errors.append(finding(display_path, "manifest root must be an object", "invalid-manifest"))
        return {}
    return value
def validate_manifest(manifest: dict, errors: list[dict], display_path: str) -> list[str]:
    if set(manifest) != MANIFEST_FIELDS:
        missing = sorted(MANIFEST_FIELDS - set(manifest))
        extra = sorted(set(manifest) - MANIFEST_FIELDS)
        errors.append(finding(display_path, f"manifest fields mismatch; missing={missing}, extra={extra}", "invalid-manifest"))
    if type(manifest.get("schema_version")) is not int or manifest.get("schema_version") != 1:
        errors.append(finding(display_path, "schema_version must be integer 1", "invalid-manifest"))
    if manifest.get("generator") != "ai-agent-system-bootstrap":
        errors.append(finding(display_path, "generator must be ai-agent-system-bootstrap", "invalid-manifest"))
    if type(manifest.get("suite_version")) is not int or manifest.get("suite_version") != 4:
        errors.append(finding(display_path, "suite_version must be integer 4", "invalid-manifest"))
    run_id = manifest.get("run_id")
    if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id):
        errors.append(finding(display_path, "run_id is missing or invalid", "invalid-manifest"))
    blueprint_id = manifest.get("blueprint_id")
    if not isinstance(blueprint_id, str) or not RUN_ID.fullmatch(blueprint_id):
        errors.append(finding(display_path, "blueprint_id is missing or invalid", "invalid-manifest"))
    if manifest.get("generation_mode") not in {"initialize", "rebuild"}:
        errors.append(finding(display_path, "generation_mode must be initialize or rebuild", "invalid-manifest"))
    generated_at = manifest.get("generated_at")
    if not isinstance(generated_at, str) or not ISO_UTC.fullmatch(generated_at):
        errors.append(finding(display_path, "generated_at must be an ISO-8601 UTC timestamp ending in Z", "invalid-manifest"))
    else:
        try:
            datetime.fromisoformat(generated_at[:-1] + "+00:00")
        except ValueError:
            errors.append(finding(display_path, "generated_at is not a real UTC timestamp", "invalid-manifest"))
    if manifest.get("agents_md_managed_block") != {"start": START, "end": END}:
        errors.append(finding(display_path, "managed block markers do not match the current schema", "invalid-manifest"))
    managed = manifest.get("managed_paths")
    if not isinstance(managed, list) or any(not isinstance(value, str) for value in managed):
        errors.append(finding(display_path, "managed_paths must be a string array", "invalid-manifest"))
        managed = []
    if managed != [".ai"]:
        errors.append(finding(display_path, "managed_paths must contain only .ai", "invalid-manifest"))
    generated = manifest.get("generated_files")
    if not isinstance(generated, list) or any(not isinstance(value, str) for value in generated):
        errors.append(finding(display_path, "generated_files must be a string array", "invalid-manifest"))
        generated = []
    if len(generated) != len(set(generated)) or "AGENTS.md" not in generated or ".ai/bootstrap-manifest.json" not in generated:
        errors.append(finding(display_path, "generated_files must be unique and include AGENTS.md plus the manifest", "invalid-manifest"))
    for value in generated:
        if safe_repo_path(value) is None:
            errors.append(finding(display_path, f"unsafe generated file path: {value}", "invalid-generated-file"))
            continue
        owned = value == "AGENTS.md" or value.startswith(".ai/")
        if not owned:
            errors.append(finding(display_path, f"generated file is outside managed paths: {value}", "invalid-generated-file"))
    return []
def manifest_report(path: Path) -> dict:
    errors: list[dict] = []
    if is_reparse(path):
        errors.append(finding(str(path), "manifest must not be a symlink or junction", "reparse-point"))
        manifest = {}
    else:
        manifest = load_manifest(path, errors, str(path))
    skill_roots = validate_manifest(manifest, errors, str(path)) if manifest else []
    errors.sort(key=lambda item: (item["path"].casefold(), item["code"], item["message"]))
    return {
        "schema_version": 1,
        "status": "failed" if errors else "passed",
        "errors": errors,
        "warnings": [],
        "manifest": manifest if not errors else None,
        "managed_skill_paths": skill_roots if not errors else [],
    }
def extract_block(text: str, errors: list[dict], relative: str) -> str:
    if text.count(START) != 1 or text.count(END) != 1:
        errors.append(finding(relative, "current managed markers must each appear once", "invalid-markers"))
        return ""
    if text.count(LEGACY_START) or text.count(LEGACY_END):
        errors.append(finding(relative, "legacy markers remain in generated output", "legacy-markers"))
    start = text.find(START)
    end_start = text.find(END)
    if end_start < start:
        errors.append(finding(relative, "managed marker order is invalid", "invalid-markers"))
        return ""
    return text[start : end_start + len(END)].replace("\r\n", "\n")
def check_references(text: str, root: Path, relative: str, errors: list[dict]) -> None:
    for raw in PATH_REF.findall(text):
        reference = raw.rstrip("`'\".,;:)")
        if safe_repo_path(reference) is None:
            errors.append(finding(relative, f"unsafe referenced path: {reference}", "unsafe-reference"))
            continue
        target = check_path_chain(root, reference, errors)
        if target is not None and not target.is_file():
            errors.append(finding(relative, f"referenced path is missing or is not a regular file: {reference}", "missing-reference"))
def parse_list(block: str, key: str) -> list[str]:
    lines = block.splitlines()
    for index, line in enumerate(lines):
        match = re.match(rf"^-\s+{re.escape(key)}:\s*(.*)$", line)
        if not match:
            continue
        inline = match.group(1).strip().strip("`")
        if inline and inline not in {"none", "null", "[]"}:
            return [inline]
        values: list[str] = []
        for child in lines[index + 1 :]:
            child_match = re.match(r"^\s{2,}-\s+(.+)$", child)
            if child_match:
                value = child_match.group(1).strip().strip("`")
                if value not in {"none", "null"}:
                    values.append(value)
                continue
            if child.startswith("- ") or child.startswith("### "):
                break
        return values
    return []
def parse_scalar(block: str, key: str) -> str | None:
    match = re.search(rf"^-\s+{re.escape(key)}:\s*`?([^`\n]+)`?\s*$", block, re.MULTILINE)
    return match.group(1).strip() if match else None
def has_field(block: str, key: str) -> bool:
    return re.search(rf"^-\s+{re.escape(key)}:\s*", block, re.MULTILINE) is not None
def has_cycle(dependencies: dict[str, list[str]]) -> bool:
    visiting: set[str] = set()
    visited: set[str] = set()
    def visit(node: str) -> bool:
        if node in visiting:
            return True
        if node in visited:
            return False
        visiting.add(node)
        if any(visit(dependency) for dependency in dependencies.get(node, [])):
            return True
        visiting.remove(node)
        visited.add(node)
        return False
    return any(visit(node) for node in dependencies)
def depends_on(start: str, target: str, dependencies: dict[str, list[str]]) -> bool:
    pending = list(dependencies.get(start, []))
    seen: set[str] = set()
    while pending:
        current = pending.pop()
        if current == target:
            return True
        if current not in seen:
            seen.add(current)
            pending.extend(dependencies.get(current, []))
    return False
def scope_base(scope: str) -> str:
    return scope[:-3].rstrip("/") if scope.endswith("/**") else scope.rstrip("/")
def scopes_overlap(left: str, right: str) -> bool:
    a, b = scope_base(left).casefold(), scope_base(right).casefold()
    return a == b or a.startswith(b + "/") or b.startswith(a + "/")
def check_workflow(
    text: str,
    relative: str,
    agent_names: set[str],
    skill_references: set[str],
    errors: list[dict],
) -> None:
    blocks = re.findall(r"^###\s+([a-z0-9-]+):[^\n]*\n(.*?)(?=^###\s+|\Z)", text, re.MULTILINE | re.DOTALL)
    if not blocks:
        errors.append(finding(relative, "workflow has no parseable step headings", "missing-workflow-steps"))
        return
    step_ids = {step_id for step_id, _ in blocks}
    if len(step_ids) != len(blocks):
        errors.append(finding(relative, "workflow step ids must be unique", "duplicate-step"))
    dependencies: dict[str, list[str]] = {}
    metadata: dict[str, tuple[str | None, str | None, list[str]]] = {}
    for step_id, block in blocks:
        for field in WORKFLOW_STEP_FIELDS:
            if not has_field(block, field):
                errors.append(finding(relative, f"step {step_id} is missing field {field}", "missing-workflow-field"))
        deps = parse_list(block, "depends_on")
        dependencies[step_id] = deps
        for dependency in deps:
            if dependency not in step_ids:
                errors.append(finding(relative, f"step {step_id} depends on missing step {dependency}", "missing-dependency"))
        agent = parse_scalar(block, "agent")
        if not agent or agent in {"none", "null"} or agent not in agent_names:
            errors.append(finding(relative, f"step {step_id} references missing Agent {agent}", "missing-agent"))
        skill = parse_scalar(block, "skill")
        if skill not in {"none", "null"} and skill not in skill_references:
            errors.append(finding(relative, f"step {step_id} references missing or invalid project Skill {skill}", "missing-workflow-skill"))
        execution = parse_scalar(block, "execution")
        if execution not in EXECUTION_MODES:
            errors.append(finding(relative, f"step {step_id} has invalid execution mode {execution}", "invalid-execution"))
        group = parse_scalar(block, "parallel_group")
        if group in {"none", "null"}:
            group = None
        scopes: list[str] = []
        for key in ("read_scope", "write_scope"):
            for scope in parse_list(block, key):
                if safe_repo_path(scope, allow_tree_glob=True) is None:
                    errors.append(finding(relative, f"step {step_id} has unsafe {key} {scope}", "invalid-write-scope" if key == "write_scope" else "invalid-read-scope"))
                elif key == "write_scope":
                    scopes.append(scope)
        if execution == "subagent-readonly" and scopes:
            errors.append(finding(relative, f"read-only step {step_id} has a write scope", "readonly-write"))
        metadata[step_id] = (execution, group, scopes)
    if has_cycle(dependencies):
        errors.append(finding(relative, "workflow dependency graph contains a cycle", "workflow-cycle"))
    grouped: dict[str, list[str]] = {}
    for step_id, (_, group, _) in metadata.items():
        if group:
            grouped.setdefault(group, []).append(step_id)
    for group, members in grouped.items():
        for index, left in enumerate(members):
            for right in members[index + 1 :]:
                if depends_on(left, right, dependencies) or depends_on(right, left, dependencies):
                    errors.append(finding(relative, f"parallel group {group} contains dependent steps {left} and {right}", "invalid-parallel-group"))
                for left_scope in metadata[left][2]:
                    for right_scope in metadata[right][2]:
                        if scopes_overlap(left_scope, right_scope):
                            errors.append(finding(relative, f"parallel steps {left} and {right} overlap at {left_scope} / {right_scope}", "write-scope-overlap"))
def candidate_digest(root: Path, skill_roots: list[str], block: str, errors: list[dict]) -> str:
    digest = hashlib.sha256()
    digest.update(b"AGENTS.md\0")
    digest.update(block.encode("utf-8"))
    paths = walk_managed(root, ".ai", errors)
    for path in sorted(set(paths), key=lambda item: item.relative_to(root).as_posix().casefold()):
        relative = path.relative_to(root).as_posix()
        digest.update(relative.encode("utf-8") + b"\0" + path.read_bytes())
    return digest.hexdigest()
def validate(root: Path) -> dict:
    errors: list[dict] = []
    warnings: list[dict] = []
    agents_path = root / "AGENTS.md"
    manifest_path = root / ".ai" / "bootstrap-manifest.json"
    check_path_chain(root, agents_path.name, errors)
    check_path_chain(root, ".ai/bootstrap-manifest.json", errors)
    if not agents_path.is_file() or is_reparse(agents_path):
        errors.append(finding(agents_path.name, "managed AGENTS artifact is missing or is a reparse point", "missing-agents-md"))
        agents_text = ""
    else:
        agents_text = read_utf8(agents_path, root, errors, warnings) or ""
    block = extract_block(agents_text, errors, agents_path.name) if agents_text else ""
    if block:
        check_references(block, root, agents_path.name, errors)
    manifest = load_manifest(manifest_path, errors, ".ai/bootstrap-manifest.json")
    skill_roots = validate_manifest(manifest, errors, ".ai/bootstrap-manifest.json") if manifest else []
    for forbidden in (".agent", ".agents"):
        if (root / forbidden).exists() or (root / forbidden).is_symlink():
            errors.append(finding(forbidden, "generated output must not create .agent or .agents", "forbidden-agent-directory"))
    for relative in [".ai", ".ai/skills"]:
        check_path_chain(root, relative, errors)
    skills_parent = root / ".ai" / "skills"
    skill_dirs = sorted(skills_parent.iterdir()) if skills_parent.is_dir() and not is_reparse(skills_parent) else []
    for path in skill_dirs:
        if not path.is_dir() or is_reparse(path):
            errors.append(finding(path.relative_to(root).as_posix(), "expected a regular Skill directory", "invalid-managed-entry"))
    agent_root = root / ".ai" / "agents"
    workflow_root = root / ".ai" / "workflows"
    orchestration_root = root / ".ai" / "orchestration"
    agent_entries = sorted(agent_root.glob("*.md")) if agent_root.is_dir() and not is_reparse(agent_root) else []
    workflow_entries = sorted(workflow_root.glob("*.md")) if workflow_root.is_dir() and not is_reparse(workflow_root) else []
    agent_files = [path for path in agent_entries if path.is_file() and not is_reparse(path)]
    workflow_files = [path for path in workflow_entries if path.is_file() and not is_reparse(path)]
    for path in [*agent_entries, *workflow_entries]:
        if not path.is_file() or is_reparse(path):
            errors.append(finding(path.relative_to(root).as_posix(), "expected a regular Markdown file", "invalid-managed-entry"))
    if not agent_files:
        errors.append(finding(".ai/agents", "at least one generated Agent is required", "missing-agent"))
    if not workflow_files:
        errors.append(finding(".ai/workflows", "at least one generated workflow is required", "missing-workflow"))
    existing_orchestration = {path.name for path in orchestration_root.glob("*.md")} if orchestration_root.is_dir() and not is_reparse(orchestration_root) else set()
    for extra in existing_orchestration - ORCHESTRATION_FILES:
        errors.append(finding(f".ai/orchestration/{extra}", "unknown orchestration policy", "invalid-orchestration"))
    agent_names: set[str] = set()
    for path in agent_files:
        relative = path.relative_to(root).as_posix()
        if is_reparse(path):
            errors.append(finding(relative, "Agent must not be a symlink or junction", "reparse-point"))
            continue
        if not NAME.fullmatch(path.stem):
            errors.append(finding(relative, "Agent filename must use lowercase hyphen-case", "invalid-name"))
        agent_names.add(path.stem)
        text = read_utf8(path, root, errors, warnings)
        if text is not None:
            require_headings(text, AGENT_HEADINGS, relative, errors)
            if not check_fences(text):
                errors.append(finding(relative, "Markdown fence is not closed", "unclosed-fence"))
            check_references(text, root, relative, errors)
    skill_files: list[Path] = []
    skill_references = {f".ai/skills/{path.name}/SKILL.md" for path in skill_dirs if path.is_dir() and not is_reparse(path)}
    for skill_dir in skill_dirs:
        if not skill_dir.is_dir() or is_reparse(skill_dir):
            continue
        skill_file = skill_dir / "SKILL.md"
        skill_files.append(skill_file)
        relative = skill_file.relative_to(root).as_posix()
        if not skill_file.is_file() or is_reparse(skill_file):
            errors.append(finding(relative, "managed project Skill is missing or is a reparse point", "missing-skill"))
            continue
        text = read_utf8(skill_file, root, errors, warnings)
        if text is None:
            continue
        metadata = parse_frontmatter(text)
        if metadata is None:
            errors.append(finding(relative, "Skill frontmatter is missing or malformed", "invalid-frontmatter"))
        else:
            if set(metadata) != {"name", "description"}:
                errors.append(finding(relative, "Skill frontmatter must contain only name and description", "invalid-frontmatter"))
            expected = skill_file.parent.name
            if metadata.get("name") != expected or not NAME.fullmatch(expected) or len(expected) > 64:
                errors.append(finding(relative, "Skill name must match its lowercase hyphen-case directory", "invalid-name"))
            if not metadata.get("description"):
                errors.append(finding(relative, "Skill description is empty", "invalid-frontmatter"))
        require_headings(text, SKILL_HEADINGS, relative, errors)
        if not check_fences(text):
            errors.append(finding(relative, "Markdown fence is not closed", "unclosed-fence"))
        check_references(text, root, relative, errors)
    used_execution_modes: set[str] = set()
    has_parallel_group = False
    for path in workflow_files:
        relative = path.relative_to(root).as_posix()
        if is_reparse(path):
            errors.append(finding(relative, "workflow must not be a symlink or junction", "reparse-point"))
            continue
        if not NAME.fullmatch(path.stem):
            errors.append(finding(relative, "Workflow filename must use lowercase hyphen-case", "invalid-name"))
        text = read_utf8(path, root, errors, warnings)
        if text is not None:
            require_headings(text, WORKFLOW_HEADINGS, relative, errors)
            if not check_fences(text):
                errors.append(finding(relative, "Markdown fence is not closed", "unclosed-fence"))
            check_references(text, root, relative, errors)
            check_workflow(text, relative, agent_names, skill_references, errors)
            used_execution_modes.update(re.findall(r"^-\s+execution:\s*`?([a-z-]+)`?\s*$", text, re.MULTILINE))
            has_parallel_group = has_parallel_group or bool(
                re.search(r"^-\s+parallel_group:\s*`?(?!none|null)([a-z0-9-]+)`?\s*$", text, re.MULTILINE)
            )
    required_orchestration: set[str] = set()
    if used_execution_modes - {"inline"}:
        required_orchestration.update({"execution-policy.md", "subagent-contract.md", "context-policy.md"})
    if "subagent-worktree" in used_execution_modes or has_parallel_group:
        required_orchestration.add("merge-policy.md")
    for missing in required_orchestration - existing_orchestration:
        errors.append(finding(f".ai/orchestration/{missing}", "workflow execution requires this orchestration policy", "missing-orchestration"))
    if orchestration_root.exists() and not existing_orchestration:
        errors.append(finding(".ai/orchestration", "omit an empty orchestration directory", "empty-orchestration"))
    if orchestration_root.is_dir() and not is_reparse(orchestration_root):
        for path in sorted(orchestration_root.glob("*.md")):
            if not path.is_file() or is_reparse(path):
                errors.append(finding(path.relative_to(root).as_posix(), "expected a regular orchestration Markdown file", "invalid-managed-entry"))
                continue
            text = read_utf8(path, root, errors, warnings)
            if text is not None and not check_fences(text):
                errors.append(finding(path.relative_to(root).as_posix(), "Markdown fence is not closed", "unclosed-fence"))
    actual_files = {"AGENTS.md"}
    actual_files.update(path.relative_to(root).as_posix() for path in walk_managed(root, ".ai", errors))
    declared_files = set(manifest.get("generated_files", [])) if isinstance(manifest.get("generated_files"), list) else set()
    if declared_files != actual_files:
        missing = sorted(actual_files - declared_files, key=str.casefold)
        extra = sorted(declared_files - actual_files, key=str.casefold)
        errors.append(finding(".ai/bootstrap-manifest.json", f"generated_files mismatch; undeclared={missing}, absent={extra}", "file-inventory-mismatch"))
    digest = candidate_digest(root, skill_roots, block, errors)
    errors.sort(key=lambda item: ((item["path"] or "").casefold(), item["code"], item["message"]))
    warnings.sort(key=lambda item: ((item["path"] or "").casefold(), item["code"], item["message"]))
    return {
        "schema_version": 1,
        "status": "failed" if errors else ("passed-with-warnings" if warnings else "passed"),
        "candidate_digest": digest,
        "run_id": manifest.get("run_id") if isinstance(manifest, dict) else None,
        "blueprint_id": manifest.get("blueprint_id") if isinstance(manifest, dict) else None,
        "errors": errors,
        "warnings": warnings,
        "counts": {
            "agents": len(agent_files),
            "project_skills": len(skill_files),
            "workflows": len(workflow_files),
            "orchestration_policies": len(existing_orchestration),
            "files": len(actual_files),
        },
    }
def emit(report: dict, as_json: bool) -> None:
    if as_json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
        return
    print(f"{report['status']}: {len(report['errors'])} errors, {len(report['warnings'])} warnings")
    for item in report["errors"] + report["warnings"]:
        print(f"{item['code']} {item['path']}: {item['message']}")
def main() -> int:
    configure_stdio()
    args = parse_args()
    if args.manifest_only:
        path = Path(args.manifest_only).absolute()
        report = manifest_report(path)
    else:
        raw_root = Path(args.root).absolute()
        if is_reparse(raw_root):
            raise ValueError("root must not be a symlink or junction")
        root = raw_root.resolve(strict=True)
        report = validate(root)
    emit(report, args.json)
    return 0 if not report["errors"] else 1
if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        configure_stdio()
        print(json.dumps({"status": "failed", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
        raise SystemExit(2)
ai-agent-system-bootstrap/shared/templates/AGENTS.md
New file
@@ -0,0 +1,68 @@
<!-- AI-AGENT-SYSTEM:START -->
## AI Agent Routing and Orchestration
### Project
<Project-specific overview and generated-system scope.>
### Instruction priority
1. Follow higher-priority system, safety, user, and human-authored repository instructions.
2. Preserve an Agent or Skill explicitly named by the user.
3. Run automatic Agent matching only when the user names neither an Agent nor a Skill, unless automatic validation, regeneration, or supplementation was explicitly requested.
### Skill boundary
- Repository Skills under `.ai/skills` are project-local and may be used when requested or referenced by the selected project Agent or workflow.
- Skills outside this repository are global. Use one only when the user explicitly names or authorizes it.
- Agent definitions and workflows cannot grant permission to activate a global Skill.
- Prefer the project-local Skill when a local and global Skill share a name, unless the user clearly identifies the global one.
### Agent routing
When automatic matching is allowed:
1. Match the task goal, affected modules, required output, and stable inputs to one primary Agent.
2. Add a supporting Agent only when its distinct output is required.
3. Load only selected Agent definitions and their referenced project Skills/workflows.
4. Fall back to `<general-agent>` when no specialized Agent matches.
Primary Agent: `<primary-agent>`
| Task surface | Agent | Definition |
|---|---|---|
| <project-specific surface> | `<agent-name>` | `.ai/agents/<agent-name>.md` |
### Execution planning
1. Split work into bounded items and record their dependencies.
2. Assign `inline`, `subagent-readonly`, `subagent-shared`, or `subagent-worktree`; default to `inline`.
3. Start only the minimum SubAgents whose inputs are stable, outputs are structured, and isolation or parallelism has clear value.
4. Assign one writer per file/module per phase. Keep concurrent write scopes disjoint.
5. Keep exploration, QA, security, and review read-only by default.
6. Use sequential `inline` execution when SubAgents or worktrees are unavailable.
### SubAgent handoff and return
Every handoff includes objective, acceptance criteria, source of truth, inputs, read/write scope, required project Skills, prohibited actions, verification, escalation conditions, and return format.
Every result includes `status`, `summary`, `findings_or_changes`, `artifacts`, `files_inspected`, `files_changed`, `assumptions`, `risks`, `verification`, `unresolved_items`, and `recommended_next_action`.
### Project Skills
| Procedure | Skill |
|---|---|
| <project-specific procedure> | `.ai/skills/<skill-name>/SKILL.md` |
### Workflows and orchestration
- Workflow: `.ai/workflows/<workflow-name>.md`
- Orchestration level: `<inline | coordinated | isolated | parallel>`
- `<include only blueprint-defined .ai/orchestration policy links; omit this item when inline>`
For every delegated item, use an immutable objective and source of truth, propagate approved changes, and cancel or restart stale work. Serialize overlapping writes. Wait for required results before integration. The primary Agent records accepted and rejected findings and owns final verification.
### Integration and completion
The primary Agent or main orchestrator owns conflict decisions, integration, final verification, and completion claims. Report rejected recommendations, failed or unperformed checks, partial results, and remaining risks.
<!-- AI-AGENT-SYSTEM:END -->
ai-agent-system-bootstrap/shared/templates/agent.md
New file
@@ -0,0 +1,48 @@
# <Agent Name>
## role
<Distinct responsibility and project/module routing terms.>
## input
- <Stable required input>
## output
- <Owned result>
## decision
- When <condition>, route to `<other-agent>`.
- When <condition>, use `.ai/skills/<skill-name>/SKILL.md`.
- Follow root `AGENTS.md` for routing, execution, and global-Skill authorization.
## execution
- default_mode: `inline`
- allowed_modes:
  - `inline`
- parallelizable: `false`
- write_scope:
  - `<repository-relative path or none>`
- requires:
  - `<stable artifact or none>`
- conflicts_with:
  - `<agent/path or none>`
- failure_policy: `return-partial | retry-once | escalate`
## return_contract
- status
- summary
- findings_or_changes
- artifacts
- files_inspected
- files_changed
- assumptions
- risks
- verification
- unresolved_items
- recommended_next_action
ai-agent-system-bootstrap/shared/templates/bootstrap-manifest.json
New file
@@ -0,0 +1,17 @@
{
  "schema_version": 1,
  "generator": "ai-agent-system-bootstrap",
  "suite_version": 4,
  "run_id": "<bootstrap-run-id>",
  "blueprint_id": "<system-blueprint-id>",
  "generation_mode": "<initialize-or-rebuild>",
  "generated_at": "<ISO-8601 UTC>",
  "managed_paths": [
    ".ai"
  ],
  "agents_md_managed_block": {
    "start": "<!-- AI-AGENT-SYSTEM:START -->",
    "end": "<!-- AI-AGENT-SYSTEM:END -->"
  },
  "generated_files": []
}
ai-agent-system-bootstrap/shared/templates/context-policy.md
New file
@@ -0,0 +1,30 @@
# Context Policy
## Source of truth
- Create one immutable Task Brief for each delegated task.
- Reference versioned requirement and architecture artifacts when they exist.
- Share the minimum complete context needed for the assigned objective.
## Assumptions and changes
- Record every assumption in the result.
- Propagate approved requirement or architecture changes to future tasks.
- Cancel or restart active work whose source of truth became stale.
## Optional run artifacts
Create `.ai/runs/<run-id>/` only when the workflow needs durable traceability. The blueprint must state whether rebuild preserves or regenerates these suite-managed artifacts:
```text
task-brief.md
requirements.md
architecture-contract.md
execution-plan.md
agent-results/
integration-report.md
```
## Sensitive and irrelevant context
Exclude secrets, unrelated conversation history, and unneeded repository surfaces from handoffs.
ai-agent-system-bootstrap/shared/templates/execution-policy.md
New file
@@ -0,0 +1,32 @@
# Execution Policy
## Runtime capabilities
- SubAgents: `<supported | unsupported | unknown>`
- Shared workspace: `<supported | unsupported | unknown>`
- Isolated worktrees: `<supported | unsupported | unknown>`
- Maximum concurrent threads: `<project/runtime value>`
## Modes
- `inline`: main-thread execution and default mode.
- `subagent-readonly`: isolated read-only analysis or review.
- `subagent-shared`: serialized scoped write in the shared workspace.
- `subagent-worktree`: isolated parallel implementation with disjoint ownership.
## Selection gates
Use a SubAgent only for independently describable work with stable inputs, structured output, bounded scope, low file overlap, and positive isolation/parallel value. Start the minimum required threads.
## Concurrency and ownership
- One writer owns each file/module per phase.
- Parallel write scopes are disjoint.
- Shared manifests, lockfiles, migrations, routing, and integration files have one owner.
## Failure and fallback
- Return partial evidence when possible.
- `<retry/escalation policy>`
- Degrade to sequential `inline` execution when isolation is unavailable.
ai-agent-system-bootstrap/shared/templates/merge-policy.md
New file
@@ -0,0 +1,41 @@
# Merge Policy
## Ownership
- `<path/module>` → `<single writer>`
- Shared integration files → `<primary/integration agent>`
## Isolation and order
- Worktree/branch convention: `<project convention>`
- Merge order: `<dependency order>`
- Wait for all required parallel results before integration.
## Conflict decisions
The primary Agent compares assumptions and evidence, then records:
```markdown
## Agreed Findings
## Conflicting Findings
## Accepted Decisions
## Rejected Recommendations
## Missing Evidence
## Integration Actions
## Validation Result
## Remaining Risks
```
## Verification and cleanup
- Required integration checks: `<checks>`
- Cleanup: `<worktrees/branches/run artifacts>`
- Final completion authority: `<primary Agent or main orchestrator>`
ai-agent-system-bootstrap/shared/templates/skill.SKILL.md
New file
@@ -0,0 +1,29 @@
---
name: "<project-prefixed-skill-name>"
description: "<Action performed and the distinct repository task that triggers it.>"
---
# <Skill Name>
## Steps
1. Read <required project inputs>.
   Completion criterion: <checkable evidence that inputs are complete>.
2. Execute <project-specific procedure>.
   Completion criterion: <checkable owned result>.
3. Validate <result>.
   Completion criterion: <explicit pass/fail gate>.
## Output
```markdown
# <Output Title>
## Result
## Evidence
## Verification
## Remaining Risks
```
ai-agent-system-bootstrap/shared/templates/subagent-contract.md
New file
@@ -0,0 +1,57 @@
# SubAgent Contract
## Task Brief
### Identity
- run_id:
- task_id:
- agent:
- execution_mode:
### Objective
### Acceptance Criteria
### Source of Truth
### Inputs
### Read Scope
### Write Scope
### Required Project Skills
### Prohibited Actions
### Verification
### Escalation Conditions
### Required Return Format
## Result
### Status
### Summary
### Findings or Changes
### Artifacts
### Files Inspected
### Files Changed
### Assumptions
### Risks
### Verification
### Unresolved Items
### Recommended Next Action
ai-agent-system-bootstrap/shared/templates/workflow.md
New file
@@ -0,0 +1,72 @@
# <Workflow Name>
## goal
<Project-specific lifecycle result.>
## flow
<Routing → stable inputs → implementation → integration → verification → completion>
## execution_graph
```mermaid
flowchart TD
    A["<step-a>"] --> B["<step-b>"]
```
## steps
### <step-id>: <Step Name>
- agent: `<existing-agent>`
- skill: `.ai/skills/<existing-skill>/SKILL.md | none`
- execution: `inline | subagent-readonly | subagent-shared | subagent-worktree`
- depends_on:
  - `<step-id or none>`
- parallel_group: `<group or none>`
- requires:
  - `<stable artifact>`
- read_scope:
  - `<path/artifact>`
- write_scope:
  - `<repository-relative path or none>`
- input:
  - `<input>`
- output:
  - `<output>`
- verification:
  - `<check>`
- next:
  - `<routing/gate>`
## synchronization_gates
- <Gate protecting stable inputs.>
- <Gate protecting integration.>
- <Gate protecting completion.>
## routing_rules
- When <condition>, route to `<existing-agent>` with <evidence>.
- When outputs conflict, pause integration for the primary Agent's decision.
## output_format
```markdown
# Workflow Run: <task>
## Selection and Execution Plan
## Step Results
## Conflicts and Decisions
## Integration Result
## Verification
## Final Decision
## Remaining Risks
```
ai-agent-system-bootstrap/shared/traceability/original-behavior-map.md
New file
@@ -0,0 +1,19 @@
# Original Behavior Map
This map anchors the suite to the supplied `ai-agent-system-bootstrap.SKILL.md` (SHA-256 `620463275a2ea9018e71d6c5410e8383720f6c255af124307fda625b12b4b761`). Preserve the behavior in every row; phase separation changes ownership of the work, not its outcome.
| Original capability | Owning suite surface | Preservation gate |
|---|---|---|
| Understand project purpose, users, stack, modules, data, integrations, quality, delivery, security, runtime, and existing Agent Team | Inspect → `ProjectSnapshot` | Every conclusion carries evidence, assumption, unknown, or blocker; raw evidence and module boundaries remain available |
| Keep overall project understanding across the run | `BootstrapRun` + `ProjectSnapshot` + repository-readable Design + traceability | IDs and verbatim constraints remain bound; Design may expand repository evidence; later phases cannot silently replace facts |
| Generate the smallest useful yet complete team from actual responsibility boundaries | Design + `agent-team-design.md` | Every domain has a disposition; anti-collapse and count-only-role audits pass; no fixed count or cap |
| Treat Agent roles independently from SubAgent execution | Design + generated runtime + workflows | Role existence is decided first; execution mode is recorded separately |
| Preserve explicit Agent/Skill precedence | `generated-team-runtime.md`, root template, Validate | Automatic matching runs only when neither is named, except explicit override requests |
| Keep global Skills explicitly opt-in | `generated-team-runtime.md`, root template, Validate | Project Skills are `.ai/skills`; no Agent or workflow self-authorizes a global Skill |
| Generate project Agents with role, input, output, decisions, execution capability, and return contract | Agent schema/template + Render + Validate | Required headings, references, modes, and return fields validate |
| Generate reusable action-oriented project Skills | Skill schema/template + Render + Validate | Skills live only at `.ai/skills/<name>/SKILL.md` and pass frontmatter/body checks |
| Generate lifecycle workflows as dependency graphs | Workflow schema/template + Render + Validate | Steps declare routing, dependencies, modes, scopes, stable inputs, outputs, verification, and gates; DAG and parallel ownership validate |
| Preserve selective SubAgent orchestration, context isolation, concurrency, merging, and independent review | `subagent-execution.md` + `orchestration-scaling.md` + generated runtime | Essential rules always exist; separate policies scale from inline through parallel; sequential fallback remains |
| Preserve existing human root instructions and avoid duplicate generated blocks | Ownership policy + direct repository generation | Only the managed block is updated; marker conflicts block writes |
| Generate files only after complete design, then verify references and output integrity | Render → `RenderResult`; Validate → `ValidationReport` | Rendering writes managed repository paths; inventory, UTF-8, paths, references, counts, hashes, semantics, and warnings are checked in place |
| Report assumptions, partial failures, unresolved risks, and verification honestly | All contracts + Bootstrap failure/final output | Blocked/failed phases stop the run; structured results retain evidence and risks |
ai-agent-system-bootstrap/skills/ai-agent-system-bootstrap/SKILL.md
New file
@@ -0,0 +1,84 @@
---
name: ai-agent-system-bootstrap
description: Initialize or completely rebuild a repository-specific AI Agent Team, including root AGENTS.md routing, project-local Agents and Skills, workflow DAGs, and selective SubAgent orchestration. Use for explicit Agent Team bootstrap or regeneration; treat generated .ai content as replaceable output rather than incrementally optimizing the previous team.
---
# AI Agent System Bootstrap
Run the plugin suite as the sole orchestrator. Produce a new Agent Team from current repository evidence, write it directly into the repository, then validate the managed output in place.
## Required suite material
Read these files before dispatching a phase:
- [`../../bundle.yaml`](../../bundle.yaml) for the fixed member allowlist and pipeline. The plugin manifest discovers Skills; this file defines suite execution.
- [`../../shared/contracts/bootstrap-run.md`](../../shared/contracts/bootstrap-run.md) for run state.
- [`../../shared/policies/ownership-and-rebuild.md`](../../shared/policies/ownership-and-rebuild.md) for ownership, legacy adoption, and rebuild rules.
- [`../../shared/traceability/original-behavior-map.md`](../../shared/traceability/original-behavior-map.md) for the non-regression obligations inherited from the supplied original Skill.
Use only the four companion Skills declared in `bundle.yaml`. Keep dispatch centralized here; a phase Skill returns its result to this orchestrator and does not call a sibling.
Resolve `<suite-root>` from this `SKILL.md` location before running a suite script. Invoke the resolved absolute script path; do not resolve script paths from the target repository working directory.
The global-Skill restriction generated into a target repository governs that repository's future Agent Team. It does not constrain this explicitly invoked suite from dispatching its declared companion Skills.
## Pipeline
Skill selection and thread selection are separate decisions. Execute the phases strictly in pipeline order:
- For an inline phase, load and follow the named companion Skill in the current thread.
- For an isolated phase, start a SubAgent with the stable phase input and explicitly require the named companion Skill in its task brief.
- Run Inspect inline for small repositories or in a read-only SubAgent for broad discovery.
- Run Design inline by default; isolate it read-only only when context separation materially improves the design pass.
- Run Render as the single repository writer; never run it concurrently with another writer.
- Run Validate in an independent read-only SubAgent when the runtime supports it; otherwise run it inline after Render completes.
Using a companion Skill alone does not create a SubAgent. No phase may begin before its declared input artifact is complete.
### 1. Open the run
Create a `BootstrapRun` with an absolute repository root, `mode: pending`, suite version, unique run ID, explicit user constraints, and explicit exclusions. Inspect resolves ownership before the orchestrator sets the final mode.
Completion criterion: the run identifies one repository, the pending mode state, the exact user request, and no unresolved target-path ambiguity.
### 2. Inspect
Dispatch `ai-agent-system-inspect` with the run. Require a complete `ProjectSnapshot`; keep the user's scope immutable while allowing Design to expand or confirm repository evidence with explicit traceability.
Completion criterion: the snapshot covers every source category required by its contract and classifies existing `AGENTS.md` and `.ai` ownership. Resolve `BootstrapRun.mode` exactly once from that classification.
### 3. Design
Dispatch `ai-agent-system-design` with the immutable snapshot, whose request block carries the verbatim user request and constraints. Require one `SystemBlueprint` that is the sole design input for rendering and semantic validation.
Completion criterion: every responsibility domain, generated Agent, local Skill, workflow, adaptive orchestration rule/policy, managed path, and root routing rule appears in the blueprint with no unresolved writer overlap or overloaded general Agent.
### 4. Render in the repository
Dispatch `ai-agent-system-render` with the BootstrapRun and blueprint. Rendering writes the generated `.ai` tree and the managed block in root `AGENTS.md` directly under `BootstrapRun.repository_root`.
Completion criterion: `RenderResult` accounts for every generated file and reports no write outside the managed repository paths.
### 5. Validate
Dispatch `ai-agent-system-validate` with the BootstrapRun, immutable ProjectSnapshot, blueprint, and render result. Validate `BootstrapRun.repository_root`. Before accepting the report, require its run ID, input snapshot-derived blueprint ID, input render result ID, validated run ID, validated blueprint ID, and candidate digest to match the current run artifacts. Accept `passed`. Accept `passed-with-warnings` only when every warning code appears in `BootstrapRun.allowed_warning_codes`.
Completion criterion: structural and semantic validation both finish and the report contains a final decision.
## Failure handling
- Stop when a phase returns `blocked` or `failed`.
- Treat an existing unrelated `.ai` directory or malformed ownership marker as blocking evidence before Render starts.
- If Render or Validate fails after writes begin, report the exact files already changed and the failed gate. Do not claim initialization or rebuild succeeded.
- Report partial phase results and the exact failed gate. Do not claim initialization or rebuild succeeded.
## Final output
Return:
- run ID and mode
- generated Agent, Skill, workflow, and policy counts
- validation status and accepted warning codes
- generated managed paths
- preserved human-owned `AGENTS.md` status
- unresolved risks or blocking evidence
ai-agent-system-bootstrap/skills/ai-agent-system-bootstrap/agents/openai.yaml
New file
@@ -0,0 +1,7 @@
interface:
  display_name: "AI Agent System Bootstrap"
  short_description: "Initialize or rebuild a repository Agent Team"
  default_prompt: "Use $ai-agent-system-bootstrap to initialize or rebuild this repository Agent Team."
policy:
  allow_implicit_invocation: false
ai-agent-system-bootstrap/skills/ai-agent-system-design/SKILL.md
New file
@@ -0,0 +1,61 @@
---
name: ai-agent-system-design
description: Internal design phase for ai-agent-system-bootstrap that converts an evidence-rich ProjectSnapshot and current repository evidence into a complete SystemBlueprint for the smallest complete project Agent Team. Use only when a bootstrap run supplies the snapshot and requests Agent, local Skill, workflow DAG, and adaptive SubAgent orchestration design.
---
# AI Agent System Design
Convert one accepted `ProjectSnapshot`, including its immutable request block, into one complete `SystemBlueprint`. Remain read-only. Continue reading the target repository whenever the snapshot evidence needs expansion or confirmation; do not treat the snapshot as a ceiling on project understanding. Do not inspect the old generated Agent Team as a design source.
This phase is orchestrator-gated. If a complete accepted ProjectSnapshot with run ID, request, ownership classification, and evidence is not supplied, return `blocked` without reading unrelated repository state or writing files. Explicit direct invocation does not bypass this input gate.
## Required suite material
Read all of the following before designing:
- [`../../shared/contracts/project-snapshot.md`](../../shared/contracts/project-snapshot.md)
- [`../../shared/contracts/system-blueprint.md`](../../shared/contracts/system-blueprint.md)
- [`../../shared/policies/generated-team-runtime.md`](../../shared/policies/generated-team-runtime.md)
- [`../../shared/policies/agent-team-design.md`](../../shared/policies/agent-team-design.md)
- [`../../shared/policies/orchestration-scaling.md`](../../shared/policies/orchestration-scaling.md)
- [`../../shared/policies/subagent-execution.md`](../../shared/policies/subagent-execution.md)
- [`../../shared/policies/default-minimal-system.md`](../../shared/policies/default-minimal-system.md) only when repository evidence cannot support specialization
- [`../../shared/schemas/agents-md.md`](../../shared/schemas/agents-md.md)
- [`../../shared/schemas/agent-definition.md`](../../shared/schemas/agent-definition.md)
- [`../../shared/schemas/skill-definition.md`](../../shared/schemas/skill-definition.md)
- [`../../shared/schemas/workflow-definition.md`](../../shared/schemas/workflow-definition.md)
- [`../../shared/schemas/orchestration-definition.md`](../../shared/schemas/orchestration-definition.md)
## Design
### 1. Establish design facts
Accept only snapshot facts backed by evidence and snapshot assumptions explicitly carried forward. Block on unresolved ownership conflicts or missing facts that would materially change the generated system.
Completion criterion: every design input is classified as evidence, approved assumption, or blocker.
### 2. Define the smallest complete Agent and Skill set
Evaluate every responsibility domain in `agent-team-design.md`. Create an Agent when it owns a distinct recurring decision, risk, verification method, module boundary, or output. Combine roles only when all of those dimensions align. Create a project-local Skill only for a repeated executable procedure. Choose one default primary implementation Agent; identify supporting Agents before choosing whether any run inline or as SubAgents.
Completion criterion: every domain has an evidenced disposition, every Agent and Skill has a distinct responsibility and repository basis, and the anti-collapse audit finds neither an overloaded general Agent nor a count-only role.
### 3. Define workflows and execution
Express each lifecycle as a dependency DAG. For every step declare the Agent, local Skill or none, stable prerequisites, execution mode, read scope, write scope, output, verification, and next gate.
Apply the selective SubAgent policy. Default to `inline`; assign read-only isolation to independent exploration and review; assign worktree execution only to stable non-overlapping writers. Resolve every write-scope overlap before completing the blueprint.
Completion criterion: all workflow dependencies are acyclic, each parallel group is dependency-independent, and each writable path has one owner per phase.
### 4. Scale orchestration and define generated runtime
Choose `inline`, `coordinated`, `isolated`, or `parallel` from `orchestration-scaling.md`. Always place the essential execution, handoff, context, single-writer, integration, and fallback rules in the generated runtime. Add only the `.ai/orchestration` policy files justified by the selected level. Scope global-Skill opt-in rules to the generated repository Agent Team. Declare the complete `.ai` directory suite-owned and only the marked root `AGENTS.md` block suite-owned.
Completion criterion: the blueprint fully describes all rendered files, explains the orchestration level from project evidence, and contains no implicit ownership or routing rule.
### 5. Return the blueprint
Populate every `SystemBlueprint` field, including traceability from generated components to snapshot evidence and the complete managed path set. Do not add or alter warning acceptance; that authority remains in `BootstrapRun.allowed_warning_codes`.
Completion criterion: Render can proceed without a new design decision and Validate can independently compare the blueprint with the snapshot and repository evidence.
ai-agent-system-bootstrap/skills/ai-agent-system-design/agents/openai.yaml
New file
@@ -0,0 +1,7 @@
interface:
  display_name: "AI Agent System Design"
  short_description: "Design the smallest complete project Agent Team"
  default_prompt: "Use $ai-agent-system-design only as the orchestrator-gated design phase with a complete accepted ProjectSnapshot; otherwise return blocked."
policy:
  allow_implicit_invocation: false
ai-agent-system-bootstrap/skills/ai-agent-system-inspect/SKILL.md
New file
@@ -0,0 +1,66 @@
---
name: ai-agent-system-inspect
description: Inspect a repository and produce the ProjectSnapshot required to initialize or rebuild its AI Agent Team. Use for standalone Agent Team discovery or as the read-only inspection phase of ai-agent-system-bootstrap; classify existing generated ownership without optimizing old Agent definitions.
---
# AI Agent System Inspect
Inspect current repository truth and return one immutable `ProjectSnapshot`. Remain read-only.
## Required suite material
Read:
- [`../../shared/contracts/bootstrap-run.md`](../../shared/contracts/bootstrap-run.md)
- [`../../shared/contracts/project-snapshot.md`](../../shared/contracts/project-snapshot.md)
- [`../../shared/policies/ownership-and-rebuild.md`](../../shared/policies/ownership-and-rebuild.md)
## Inspection
### 1. Confirm the boundary
Resolve the repository root and copy the user request, explicit constraints, explicit exclusions, and available runtime capabilities into the snapshot. Reject a missing or ambiguous root.
Completion criterion: every inspected path is inside the resolved repository root.
### 2. Read repository evidence
Inspect the smallest set of real files that establishes:
- project and product purpose
- languages, frameworks, runtimes, and build tools
- modules and ownership boundaries
- persistence, migrations, and external integrations
- test, release, deployment, security, privacy, and compatibility constraints
- recurring development activities that justify project-local Skills
- runtime support for SubAgents, shared workspaces, and isolated worktrees
Record evidence paths beside conclusions. Mark absent evidence as an assumption rather than inventing detail.
Build the complete `domain_assessment` across product, architecture, frontend, backend, data, security, QA, DevOps, documentation, final review, and project-specific domains. Preserve module paths, raw evidence paths, risks, verification methods, and inference grounds.
Completion criterion: each populated snapshot field points to evidence or is explicitly marked assumed/unknown, and every responsibility domain has an explicit evidence-based assessment.
### 3. Classify existing Agent Team ownership
Read root `AGENTS.md`, `.ai/bootstrap-manifest.json`, and the structural shape of `.ai` when present. Recognize a legacy YAML manifest only as migration evidence.
- Treat text outside managed markers as human-owned.
- Recognize `AI-AGENT-SYSTEM` as the current marker and `AI-AGENT-ROUTING` as a legacy marker eligible for one-time migration.
- Treat `.ai` as suite-owned only when a strict current manifest and its declared inventory match the installed managed tree, or when it is an unambiguous legacy Agent Team containing the expected Agent/workflow structure.
- Report unrelated or mixed-ownership `.ai` content as a blocking ownership conflict.
- Inventory old generated paths only to determine rebuild scope. Do not use old Agent roles, workflows, or Skills as design requirements.
Completion criterion: `agents_md_marker`, `agents_md_human_content`, `ai_directory`, legacy status, and every conflict are explicit.
### 4. Return the snapshot
Populate every required field in `ProjectSnapshot`, including evidence, assumptions, unknowns, managed paths, and blockers. Set status to `blocked` when ownership or target boundary is unsafe; otherwise set `success`.
Completion criterion: the output conforms to the contract and contains no unclassified existing generated surface.
## Output
Return only the completed `ProjectSnapshot` plus a concise evidence summary. Do not write repository files.
For standalone invocation, accept an explicit repository root and user request, create an ephemeral read-only run ID, and populate the same snapshot request block. Standalone Inspect never selects a rebuild mode or writes a BootstrapRun.
ai-agent-system-bootstrap/skills/ai-agent-system-inspect/agents/openai.yaml
New file
@@ -0,0 +1,7 @@
interface:
  display_name: "AI Agent System Inspect"
  short_description: "Inspect a repository for Agent Team design"
  default_prompt: "Use $ai-agent-system-inspect to inspect this repository and produce a ProjectSnapshot."
policy:
  allow_implicit_invocation: true
ai-agent-system-bootstrap/skills/ai-agent-system-render/SKILL.md
New file
@@ -0,0 +1,68 @@
---
name: ai-agent-system-render
description: Internal render phase for ai-agent-system-bootstrap that materializes an accepted SystemBlueprint as the managed AGENTS.md block and a complete .ai tree directly in the target repository. Use only with a matching bootstrap run and blueprint.
---
# AI Agent System Render
Render the blueprint exactly into the target repository. Make no design decisions and write only the managed paths.
This phase is orchestrator-gated. Require a matching BootstrapRun and complete SystemBlueprint. Without both inputs, return `blocked` and write nothing. Explicit direct invocation does not bypass this input gate.
## Required suite material
Read:
- [`../../shared/contracts/system-blueprint.md`](../../shared/contracts/system-blueprint.md)
- [`../../shared/contracts/render-result.md`](../../shared/contracts/render-result.md)
- [`../../shared/policies/ownership-and-rebuild.md`](../../shared/policies/ownership-and-rebuild.md)
- [`../../shared/templates/AGENTS.md`](../../shared/templates/AGENTS.md)
- [`../../shared/templates/agent.md`](../../shared/templates/agent.md)
- [`../../shared/templates/skill.SKILL.md`](../../shared/templates/skill.SKILL.md)
- [`../../shared/templates/workflow.md`](../../shared/templates/workflow.md)
- [`../../shared/templates/execution-policy.md`](../../shared/templates/execution-policy.md)
- [`../../shared/templates/subagent-contract.md`](../../shared/templates/subagent-contract.md)
- [`../../shared/templates/context-policy.md`](../../shared/templates/context-policy.md)
- [`../../shared/templates/merge-policy.md`](../../shared/templates/merge-policy.md)
- [`../../shared/templates/bootstrap-manifest.json`](../../shared/templates/bootstrap-manifest.json)
## Rendering
### 1. Verify inputs
Confirm that the BootstrapRun has a resolved initialize/rebuild mode, the blueprint is complete, the repository root matches the inspected project, and the ownership classification allows direct generation. Use `BootstrapRun.mode` as the manifest `generation_mode`.
Completion criterion: all output paths resolve to `AGENTS.md` or `.ai` inside the repository and every blueprint component maps to one template/schema.
### 2. Materialize output
Create only:
```text
<repository-root>/
  AGENTS.md
  .ai/
    bootstrap-manifest.json
    agents/
    skills/
    workflows/
    orchestration/  # only when named by the blueprint
```
Render project-specific content; remove unused placeholders and example references. Write UTF-8 text. Preserve human-owned root `AGENTS.md` text outside the managed markers and replace only the single valid current or legacy managed block. Generate `.ai/orchestration` only when the blueprint names at least one policy. Generate a manifest that binds `run_id` and `blueprint_id`, declares only the complete `.ai` directory managed, then records every generated file path relative to the repository root.
Completion criterion: every blueprint component has exactly one generated file and no generated file lacks a blueprint source.
### 3. Return the result
Hash and list every generated file, record counts by component type, and return `RenderResult`. Report warnings without modifying the blueprint.
Completion criterion: the manifest, file list, counts, and hashes agree with the repository's managed output.
## Guardrails
- Keep the generated section of `AGENTS.md` limited to one managed block with current markers.
- Keep project-local Skills valid Codex Skills with YAML frontmatter.
- Never create `.agent`, `.agents`, or any project-Skill location outside `.ai/skills`.
- Use the unified execution modes and return contract defined by the schemas.
- Stop on missing blueprint data; do not fill gaps from the old Agent Team or generic boilerplate.
ai-agent-system-bootstrap/skills/ai-agent-system-render/agents/openai.yaml
New file
@@ -0,0 +1,7 @@
interface:
  display_name: "AI Agent System Render"
  short_description: "Render an Agent Team directly into a repository"
  default_prompt: "Use $ai-agent-system-render only as the orchestrator-gated repository writer with a matching BootstrapRun and SystemBlueprint; otherwise return blocked."
policy:
  allow_implicit_invocation: false
ai-agent-system-bootstrap/skills/ai-agent-system-validate/SKILL.md
New file
@@ -0,0 +1,85 @@
---
name: ai-agent-system-validate
description: Validate a repository Agent Team against the suite contracts, schemas, runtime policies, ownership rules, and project evidence. Use as the read-only validation phase of ai-agent-system-bootstrap or standalone to report structural and semantic defects without repairing files.
---
# AI Agent System Validate
Validate rendered output without changing it. Return evidence, not repairs.
## Required suite material
Read:
- [`../../shared/contracts/bootstrap-run.md`](../../shared/contracts/bootstrap-run.md) for bootstrap-candidate scope
- [`../../shared/contracts/project-snapshot.md`](../../shared/contracts/project-snapshot.md) for bootstrap-candidate scope
- [`../../shared/contracts/system-blueprint.md`](../../shared/contracts/system-blueprint.md) when a blueprint is available
- [`../../shared/contracts/render-result.md`](../../shared/contracts/render-result.md) for bootstrap validation
- [`../../shared/contracts/validation-report.md`](../../shared/contracts/validation-report.md)
- [`../../shared/policies/generated-team-runtime.md`](../../shared/policies/generated-team-runtime.md)
- [`../../shared/policies/agent-team-design.md`](../../shared/policies/agent-team-design.md)
- [`../../shared/policies/orchestration-scaling.md`](../../shared/policies/orchestration-scaling.md)
- [`../../shared/policies/ownership-and-rebuild.md`](../../shared/policies/ownership-and-rebuild.md)
- [`../../shared/policies/subagent-execution.md`](../../shared/policies/subagent-execution.md)
- [`../../shared/schemas/agents-md.md`](../../shared/schemas/agents-md.md)
- [`../../shared/schemas/agent-definition.md`](../../shared/schemas/agent-definition.md)
- [`../../shared/schemas/skill-definition.md`](../../shared/schemas/skill-definition.md)
- [`../../shared/schemas/workflow-definition.md`](../../shared/schemas/workflow-definition.md)
- [`../../shared/schemas/orchestration-definition.md`](../../shared/schemas/orchestration-definition.md)
- [`../../shared/traceability/original-behavior-map.md`](../../shared/traceability/original-behavior-map.md)
## Validation
Resolve `<suite-root>` from this `SKILL.md` location and invoke the resulting absolute script path. The target repository working directory is not the suite root.
For `bootstrap-candidate` scope, require the BootstrapRun, ProjectSnapshot, SystemBlueprint, and RenderResult with matching IDs. Validate `BootstrapRun.repository_root`. Return `blocked` when any input is absent or inconsistent.
### 1. Run structural validation
Run:
```text
python <suite-root>/shared/scripts/validate-structure.py --root <repository-root> --json
```
Account for every reported error and warning. Structural errors block successful completion.
Completion criterion: the script exits and its complete result is captured in the report.
### 2. Validate semantics
Check all of these surfaces:
- generated components trace to current `ProjectSnapshot` evidence or declared assumptions
- the Agent set is smallest complete: every responsibility domain has a justified disposition, responsibilities do not overlap, and no general Agent is overloaded across independently judged domains
- Agent-role existence was decided independently from inline/SubAgent execution cost
- exactly one primary Agent owns integration and completion
- role selection and execution-thread selection are separate decisions
- workflow graphs are acyclic and gates protect stable inputs, integration, and final review
- concurrent writers have disjoint scopes and shared files have one owner
- SubAgents are used only for bounded work with structured returns
- review, QA, security, and exploration Agents are read-only by default
- sequential inline fallback exists when SubAgents or worktrees are unavailable
- global-Skill opt-in language is scoped to the generated team runtime
- every project-local Skill is under `.ai/skills`, with no `.agent` or `.agents` output
- orchestration essentials exist at every level and separate policy files match the evidenced orchestration level
- the complete `.ai` ownership rule and managed `AGENTS.md` markers are consistent
- every RenderResult file and hash matches the managed repository output
- every applicable original capability in the behavior map has an implemented, traceable generated surface
Completion criterion: every semantic check has a pass, warning, or error with file/path evidence.
### 3. Decide status
Use only:
- `passed`: no errors or warnings
- `passed-with-warnings`: no errors and at least one warning
- `blocked`: required evidence or safe ownership is unavailable
- `failed`: structural or semantic requirements are violated
Return a `ValidationReport` with a final decision. Do not edit files, invoke Render, or silently waive warnings.
Completion criterion: the report accounts for every finding and identifies the exact gate that permits or blocks successful completion.
For standalone installed-team validation, set report scope to `installed-standalone`, allow absent input blueprint and render-result IDs, derive validated IDs from the strict installed manifest, and use `final_decision: report-only`. Skip only traceability checks that require unavailable bootstrap artifacts; mark each skipped check `not-applicable`.
ai-agent-system-bootstrap/skills/ai-agent-system-validate/agents/openai.yaml
New file
@@ -0,0 +1,7 @@
interface:
  display_name: "AI Agent System Validate"
  short_description: "Validate a generated repository Agent Team"
  default_prompt: "Use $ai-agent-system-validate to validate this repository Agent Team."
policy:
  allow_implicit_invocation: true
ai-agent-system-bootstrap/tests/test_scripts.py
New file
@@ -0,0 +1,323 @@
from __future__ import annotations
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SUITE = Path(__file__).resolve().parents[1]
SCRIPTS = SUITE / "shared" / "scripts"
def run_script(name: str, *args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [sys.executable, str(SCRIPTS / name), *args],
        capture_output=True,
        text=True,
        encoding="utf-8",
        check=False,
    )
def write(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8", newline="\n")
def agent_text(name: str, scope: str = "src/**", readonly: bool = False) -> str:
    mode = "subagent-readonly" if readonly else "inline"
    write_scope = "none" if readonly else scope
    return f"""# {name.replace('-', ' ').title()}
## role
Own the distinct {name} decisions, risks, artifacts, and verification.
## input
- Stable task and project evidence
## output
- Owned result with evidence
## decision
- Route cross-domain changes to the primary Agent.
## execution
- default_mode: `{mode}`
- allowed_modes:
  - `{mode}`
- parallelizable: `{'true' if readonly else 'false'}`
- write_scope:
  - `{write_scope}`
- requires:
  - `stable task`
- conflicts_with:
  - `none`
- failure_policy: `return-partial`
## return_contract
- status
- summary
- findings_or_changes
- artifacts
- files_inspected
- files_changed
- assumptions
- risks
- verification
- unresolved_items
- recommended_next_action
"""
def skill_text(name: str) -> str:
    return f"""---
name: {name}
description: Execute the {name} repository procedure when its owned lifecycle is requested.
---
# {name.replace('-', ' ').title()}
## Steps
1. Read the stable inputs.
2. Execute the repository procedure.
3. Validate the result.
## Output
Return the result, evidence, verification, and remaining risks.
"""
def workflow_text(agent: str, skill: str, execution: str, parallel: bool) -> str:
    group = "implementation" if parallel else "none"
    return f"""# Delivery Workflow
## goal
Deliver and verify a project change.
## flow
Route to stable implementation, integration, and verification.
## execution_graph
```mermaid
flowchart TD
    A["route"] --> B["deliver"]
```
## steps
### deliver: Deliver
- agent: `{agent}`
- skill: `.ai/skills/{skill}/SKILL.md`
- execution: `{execution}`
- depends_on:
  - `none`
- parallel_group: `{group}`
- requires:
  - `stable task`
- read_scope:
  - `src/**`
- write_scope:
  - `{'none' if execution == 'subagent-readonly' else 'src/**'}`
- input:
  - `task`
- output:
  - `verified result`
- verification:
  - `project check`
- next:
  - `primary integration`
## synchronization_gates
- Start after inputs are stable.
- Integrate after required results return.
- Complete after verification.
## routing_rules
- Route conflicts to `{agent}`.
## output_format
```markdown
# Workflow Result
```
"""
def build_candidate(repository: Path, *, complex_project: bool, run_id: str, mode: str = "initialize") -> None:
    agents = (
        ["dev-agent", "qa-agent"]
        if not complex_project
        else [
            "product-agent",
            "architect-agent",
            "frontend-agent",
            "backend-agent",
            "data-agent",
            "security-agent",
            "qa-agent",
            "devops-agent",
            "docs-agent",
            "review-agent",
        ]
    )
    skill = "demo-delivery"
    execution = "inline" if not complex_project else "subagent-worktree"
    policy_names = [] if not complex_project else [
        "execution-policy.md",
        "subagent-contract.md",
        "context-policy.md",
        "merge-policy.md",
    ]
    links = [f"- Agent: `.ai/agents/{name}.md`" for name in agents]
    links.extend([
        f"- Skill: `.ai/skills/{skill}/SKILL.md`",
        "- Workflow: `.ai/workflows/delivery-workflow.md`",
        f"- Orchestration level: {'parallel' if complex_project else 'inline'}",
        "- Explicitly named Agents and Skills take precedence over automatic matching.",
        "- Global Skills require explicit user authorization.",
        "- Role selection and SubAgent execution are separate decisions.",
        "- Use one writer per scope, immutable handoffs, structured returns, primary integration, and sequential fallback.",
    ])
    links.extend(f"- Policy: `.ai/orchestration/{name}`" for name in policy_names)
    managed_block = (
        "<!-- AI-AGENT-SYSTEM:START -->\n## AI Agent Routing and Orchestration\n\n"
        + "\n".join(links)
        + "\n<!-- AI-AGENT-SYSTEM:END -->\n"
    )
    agents_path = repository / "AGENTS.md"
    human_text = agents_path.read_text(encoding="utf-8").rstrip() if agents_path.is_file() else ""
    write(agents_path, f"{human_text}\n\n{managed_block}" if human_text else managed_block)
    for name in agents:
        write(repository / ".ai" / "agents" / f"{name}.md", agent_text(name, readonly=name in {"qa-agent", "security-agent", "review-agent"}))
    write(repository / ".ai" / "skills" / skill / "SKILL.md", skill_text(skill))
    write(
        repository / ".ai" / "workflows" / "delivery-workflow.md",
        workflow_text("dev-agent" if not complex_project else "backend-agent", skill, execution, complex_project),
    )
    for name in policy_names:
        write(repository / ".ai" / "orchestration" / name, f"# {name}\n\nProject-specific orchestration rules.\n")
    generated_files = ["AGENTS.md"]
    generated_files.extend(path.relative_to(repository).as_posix() for path in (repository / ".ai").rglob("*") if path.is_file())
    generated_files.append(".ai/bootstrap-manifest.json")
    manifest = {
        "schema_version": 1,
        "generator": "ai-agent-system-bootstrap",
        "suite_version": 4,
        "run_id": run_id,
        "blueprint_id": f"{run_id}-blueprint",
        "generation_mode": mode,
        "generated_at": "2026-07-16T00:00:00Z",
        "managed_paths": [".ai"],
        "agents_md_managed_block": {
            "start": "<!-- AI-AGENT-SYSTEM:START -->",
            "end": "<!-- AI-AGENT-SYSTEM:END -->",
        },
        "generated_files": sorted(set(generated_files)),
    }
    write(repository / ".ai" / "bootstrap-manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
def validate(repository: Path) -> subprocess.CompletedProcess[str]:
    return run_script("validate-structure.py", "--root", str(repository), "--json")
class SuiteScenarioTests(unittest.TestCase):
    def setUp(self) -> None:
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.repository = Path(self.temp.name) / "repo"
        self.repository.mkdir()
    def candidate(self, complex_project: bool, run_id: str = "scenario") -> Path:
        build_candidate(self.repository, complex_project=complex_project, run_id=run_id)
        return self.repository
    def test_small_project_uses_two_agents_and_inline_orchestration(self) -> None:
        result = validate(self.candidate(False, "small"))
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
        report = json.loads(result.stdout)
        self.assertEqual(report["counts"]["agents"], 2)
        self.assertEqual(report["counts"]["orchestration_policies"], 0)
    def test_complex_project_supports_more_than_five_distinct_agents(self) -> None:
        result = validate(self.candidate(True, "complex"))
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
        report = json.loads(result.stdout)
        self.assertEqual(report["counts"]["agents"], 10)
        self.assertEqual(report["counts"]["orchestration_policies"], 4)
    def test_project_skills_are_under_ai_skills(self) -> None:
        repository = self.candidate(False, "skill-path")
        self.assertTrue((repository / ".ai" / "skills" / "demo-delivery" / "SKILL.md").is_file())
        self.assertFalse((repository / ".agent").exists())
        self.assertFalse((repository / ".agents").exists())
    def test_forbidden_agent_directory_is_rejected_in_repository(self) -> None:
        repository = self.candidate(False, "forbidden")
        write(repository / ".agents" / "unexpected.md", "unexpected\n")
        result = validate(repository)
        self.assertNotEqual(result.returncode, 0)
        self.assertIn("forbidden-agent-directory", result.stdout)
    def test_parallel_workflow_requires_full_orchestration(self) -> None:
        repository = self.candidate(True, "missing-policy")
        (repository / ".ai" / "orchestration" / "merge-policy.md").unlink()
        result = validate(repository)
        self.assertNotEqual(result.returncode, 0)
        self.assertIn("missing-orchestration", result.stdout)
    def test_inline_workflow_does_not_require_orchestration_directory(self) -> None:
        repository = self.candidate(False, "inline")
        self.assertFalse((repository / ".ai" / "orchestration").exists())
        self.assertEqual(validate(repository).returncode, 0)
    def test_direct_generation_preserves_human_agents_text(self) -> None:
        write(self.repository / "AGENTS.md", "# Human rules\n\nKeep this.\n")
        repository = self.candidate(False, "direct")
        result = validate(repository)
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
        self.assertIn("Keep this.", (self.repository / "AGENTS.md").read_text(encoding="utf-8"))
        self.assertTrue((self.repository / ".ai" / "skills" / "demo-delivery" / "SKILL.md").is_file())
        self.assertFalse((self.repository / ".agent").exists())
        self.assertFalse((self.repository / ".agents").exists())
    def test_contracts_encode_complete_team_and_adaptive_orchestration(self) -> None:
        design = (SUITE / "shared" / "policies" / "agent-team-design.md").read_text(encoding="utf-8")
        scaling = (SUITE / "shared" / "policies" / "orchestration-scaling.md").read_text(encoding="utf-8")
        self.assertIn("frontend", design)
        self.assertIn("security", design)
        self.assertIn("documentation", design)
        self.assertIn("No numeric target or cap", design)
        self.assertIn("Inline level", scaling)
        self.assertIn("Parallel level", scaling)
    def test_suite_contains_no_generated_agents_skill_path(self) -> None:
        offenders = []
        forbidden = ".agents" + "/skills"
        for path in [*SUITE.rglob("*.md"), *SUITE.rglob("*.py"), *SUITE.rglob("*.json"), *SUITE.rglob("*.yaml")]:
            if path.is_file() and forbidden in path.read_text(encoding="utf-8"):
                offenders.append(path.relative_to(SUITE).as_posix())
        self.assertEqual(offenders, [])
if __name__ == "__main__":
    unittest.main()