chunhualin1
2026-07-15 1a1ec5d071834d7720039ca94fc0c357d05d67c9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
#!/usr/bin/env python3
"""Deterministically validate a staged or installed 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 -->"
STAGING_MARKER = ".bootstrap-staging.json"
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|workflows|orchestration)/[A-Za-z0-9._/-]+|"
    r"\.agents/skills/[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") != 3:
        errors.append(finding(display_path, "suite_version must be integer 3", "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")
    skill_roots: list[str] = []
    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 len(managed) != len(set(managed)) or managed.count(".ai") != 1:
        errors.append(finding(display_path, "managed_paths must be unique and contain .ai exactly once", "invalid-manifest"))
    for value in managed:
        if value == ".ai":
            continue
        if safe_repo_path(value) is None or not re.fullmatch(r"\.agents/skills/[a-z0-9]+(?:-[a-z0-9]+)*", value):
            errors.append(finding(display_path, f"invalid managed path: {value}", "invalid-managed-path"))
        else:
            skill_roots.append(value)
 
    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/") or any(
            value.startswith(root + "/") for root in skill_roots
        )
        if not owned:
            errors.append(finding(display_path, f"generated file is outside managed paths: {value}", "invalid-generated-file"))
    return sorted(set(skill_roots), key=str.casefold)
 
 
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 relative in skill_roots:
        paths.extend(walk_managed(root, relative, 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] = []
    staged = (root / STAGING_MARKER).is_file()
    agents_path = root / ("AGENTS.generated.md" if staged else "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 relative in [".ai", ".agents", ".agents/skills", *skill_roots]:
        check_path_chain(root, relative, errors)
 
    expected_skill_names = {PurePosixPath(path).name for path in skill_roots}
    skills_parent = root / ".agents" / "skills"
    if staged and skills_parent.exists() and not is_reparse(skills_parent):
        actual_names = {path.name for path in skills_parent.iterdir() if path.is_dir() and not is_reparse(path)}
        unexpected_entries = {path.name for path in skills_parent.iterdir() if not path.is_dir() or is_reparse(path)}
        if actual_names != expected_skill_names or unexpected_entries:
            errors.append(finding(".agents/skills", f"staged Skill inventory mismatch; expected={sorted(expected_skill_names)}, actual={sorted(actual_names)}, other={sorted(unexpected_entries)}", "unlisted-staged-skill"))
 
    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 missing in ORCHESTRATION_FILES - existing_orchestration:
        errors.append(finding(f".ai/orchestration/{missing}", "required orchestration policy is missing", "missing-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"{relative_root}/SKILL.md" for relative_root in skill_roots}
    for relative_root in skill_roots:
        skill_file = repository_path(root, relative_root) / "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)
 
    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)
 
    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))
    for relative_root in skill_roots:
        actual_files.update(path.relative_to(root).as_posix() for path in walk_managed(root, relative_root, 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)