chunhualin1
2026-07-24 dfcc38b940873e2d5baa99b4c153e505388bf2ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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()