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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

structure-sentinel.py -- minimal structure sentinel for a nomad-skeleton team workspace.



WHAT THIS IS

    A single, dependency-free script that runs four checks over this team's

    folder and prints a plain-language report. It is a GUARDRAIL, not a gate:

    it never blocks or edits anything, it only tells you what drifted.



FOUR CHECKS

    1. Existence   -- every file a persona names as "must-read" (the agent-home

                      six-piece set + the core governance files) really exists.

    2. Orphan      -- files that exist on disk under a memory/ folder but are

                      not mentioned in that folder's README.md index.

    3. Frontmatter -- .md files under the three mandatory zones (00-index/,

                      02-shared-knowledge/, 01-agents/*/memory/) carry the

                      required 4-field YAML header (type/owner/created/status)

                      with controlled values.

    4. Broken link -- relative markdown links (`[text](path)`) inside .md

                      files resolve to a real file on disk.



USAGE

    python3 structure-sentinel.py [team_root]              # macOS / Linux

    py -3   structure-sentinel.py [team_root]              # Windows

    python3 structure-sentinel.py [team_root] --json report.json



    macOS 12.3 removed /usr/bin/python, so `python` alone is not portable;

    `python3` is the portable name on macOS/Linux and `py -3` on Windows.



    team_root defaults to the current working directory. Exit code is 0 when

    everything is clean, 1 when any violation was found -- so it is safe to

    wire into a CI-style check without parsing stdout.



DESIGN NOTE

    This is a deliberately minimal port of a design pattern used in the

    author's own production team workspace (structure sentinel + metadata

    schema), generalized and stripped of any private names/paths for this

    starter kit. It reads the team's own governance doc

    (`00-index/metadata-conventions.md`) for the controlled value tables --

    see TYPE_VALUES / STATUS_VALUES below, which mirror that doc's word list.

    If you rename files or fold in new agents, this script needs no changes:

    everything it scans is discovered by walking the disk, not hard-coded

    per-agent (only the six-piece file list and the three mandatory-zone

    directory names are fixed, because those are the team-skeleton contract

    itself, not per-deployment content).

"""
from __future__ import annotations

import argparse
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

# Runtime version gate (a guardrail, not a gate): warn — don't exit — below Python 3.8.
# Reaching here means parsing already succeeded (the hard floor is the
# `from __future__ import annotations` above, needing 3.7+); this only nudges lower
# versions. ASCII-only so it prints safely on mis-encoded old environments.
if sys.version_info < (3, 8):
    sys.stderr.write(
        "[sentinel] Python %d.%d detected; 3.8+ recommended. Older versions may hit "
        "obscure syntax errors; please upgrade (Windows: use 'py -3').\n"
        % (sys.version_info.major, sys.version_info.minor)
    )

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

# ---------------------------------------------------------------------------
# Controlled value tables (mirrors 00-index/metadata-conventions.md)
# ---------------------------------------------------------------------------

TYPE_VALUES = {"index", "rule", "state", "log", "knowledge", "calibration", "archive"}
STATUS_VALUES = {"active", "draft", "to-fix", "expired", "archived"}
REQUIRED_FIELDS = ["type", "owner", "created", "status"]

MANDATORY_ZONE_DIRS = ["00-index", "02-shared-knowledge"]  # + 01-agents/*/memory (discovered)

# Directories that are source material / not-yet-instantiated skeletons --
# excluded from frontmatter + orphan checks (they intentionally keep
# placeholders / upstream content untouched; see the metadata-conventions doc
# §7 for why "workspace / 98-archive / 99-recycle-bin / templates" are exempt).
EXEMPT_DIR_NAMES = {
    "templates", "workspace", "98-archive", "99-recycle-bin", "97-inbox-misc",
    ".agent-modpack", ".git", "__pycache__", "skills",
}
EMPLOYEE_TEMPLATE_DIRNAME_MARKER = "fill-in, not loaded"  # substring match, badge-agnostic

AGENT_HOME_SIX_PIECE = [
    "AGENTS.md", "CLAUDE.md", "workspace",
    "memory/README.md", "memory/inbox.md", "memory/worklog.md",
]
# The Nuwa agent does not land through the standard six-piece assembly path
# (it lands via kernel + template-library + two purpose-built memory files --
# see the installer's build_plan()). Checked against a different, smaller
# required-file set below instead of being fully exempted from existence
# checking -- it still has to pass frontmatter / broken-link / orphan checks
# like everyone else, only the six-piece shape does not apply to it.
NUWA_AGENT_NAMES = {"nuwa", "女娲"}
NUWA_HOME_REQUIRED = [
    "AGENTS.md", "CLAUDE.md",
    "memory/judgment-calibration-log.md", "memory/forging-ledger.md",
]

FRONTMATTER_RE = re.compile(r"\A?---[ \t]*\r?\n(.*?)\r?\n---[ \t]*\r?\n", re.DOTALL)
FIELD_LINE_RE = re.compile(r"^([A-Za-z_]+):[ \t]*(.*)$")
ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")

# Markdown inline link: [text](target) -- captures target, skips images'
# leading "!" naturally (the "!" just sits outside the match).
MD_LINK_RE = re.compile(r"\[[^\]]*\]\(([^)]+)\)")


def is_exempt_path(path: Path, root: Path) -> bool:
    rel_parts = path.relative_to(root).parts
    for part in rel_parts:
        if part in EXEMPT_DIR_NAMES:
            return True
        if EMPLOYEE_TEMPLATE_DIRNAME_MARKER in part:
            return True
    return False


def read_text(path: Path) -> str | None:
    try:
        text = path.read_text(encoding="utf-8")
    except Exception:
        return None
    if text.startswith(""):
        text = text[1:]
    return text


# ---------------------------------------------------------------------------
# Check 1: Existence
# ---------------------------------------------------------------------------

def check_existence(root: Path) -> list[dict]:
    violations: list[dict] = []
    if not (root / "team-config.json").exists():
        violations.append({
            "check": "existence", "severity": "high", "path": "team-config.json",
            "message": "team-config.json is missing -- the team's parameterized spine is gone.",
        })

    agents_root = root / "01-agents"
    if not agents_root.is_dir():
        violations.append({
            "check": "existence", "severity": "high", "path": "01-agents",
            "message": "01-agents/ directory is missing.",
        })
        return violations

    for agent_dir in sorted(p for p in agents_root.iterdir() if p.is_dir()):
        if EMPLOYEE_TEMPLATE_DIRNAME_MARKER in agent_dir.name:
            continue  # the fill-in template is checked structurally, not as a live agent
        required = NUWA_HOME_REQUIRED if agent_dir.name in NUWA_AGENT_NAMES else AGENT_HOME_SIX_PIECE
        for rel in required:
            if not (agent_dir / rel).exists():
                violations.append({
                    "check": "existence", "severity": "high",
                    "path": str((agent_dir / rel).relative_to(root)),
                    "message": f"agent home required file missing for '{agent_dir.name}'.",
                })
    return violations


# ---------------------------------------------------------------------------
# Check 2: Orphan (memory/ files not registered in memory/README.md)
# ---------------------------------------------------------------------------

def check_orphans(root: Path) -> list[dict]:
    violations: list[dict] = []
    agents_root = root / "01-agents"
    if not agents_root.is_dir():
        return violations
    for agent_dir in sorted(p for p in agents_root.iterdir() if p.is_dir()):
        if agent_dir.name in NUWA_AGENT_NAMES:
            continue  # Nuwa has no memory/README.md index by design -- see NUWA_HOME_REQUIRED
        mem_dir = agent_dir / "memory"
        if not mem_dir.is_dir():
            continue
        readme_path = mem_dir / "README.md"
        readme_text = read_text(readme_path)
        if readme_text is None:
            violations.append({
                "check": "orphan", "severity": "high",
                "path": str(readme_path.relative_to(root)),
                "message": "memory/README.md missing or unreadable -- orphan check skipped for this agent.",
            })
            continue
        for entry in sorted(mem_dir.iterdir()):
            if entry.is_dir():
                continue
            if entry.name == "README.md":
                continue
            if entry.name.startswith(".") or entry.name.endswith(".bak"):
                continue
            if entry.name not in readme_text:
                violations.append({
                    "check": "orphan", "severity": "medium",
                    "path": str(entry.relative_to(root)),
                    "message": f"'{entry.name}' exists on disk but is not mentioned in "
                               f"{readme_path.relative_to(root)} -- register it or delete it.",
                })
    return violations


# ---------------------------------------------------------------------------
# Check 3: Frontmatter schema
# ---------------------------------------------------------------------------

def parse_frontmatter(text: str) -> dict | None:
    m = FRONTMATTER_RE.match(text)
    if not m:
        return None
    fields: dict[str, str] = {}
    for line in m.group(1).splitlines():
        fm = FIELD_LINE_RE.match(line)
        if fm:
            fields[fm.group(1)] = fm.group(2).strip()
    return fields


def mandatory_zone_dirs(root: Path) -> list[Path]:
    dirs = [root / d for d in MANDATORY_ZONE_DIRS if (root / d).is_dir()]
    agents_root = root / "01-agents"
    if agents_root.is_dir():
        for agent_dir in sorted(p for p in agents_root.iterdir() if p.is_dir()):
            if EMPLOYEE_TEMPLATE_DIRNAME_MARKER in agent_dir.name:
                continue
            mem = agent_dir / "memory"
            if mem.is_dir():
                dirs.append(mem)
    return dirs


def check_frontmatter(root: Path) -> list[dict]:
    violations: list[dict] = []
    for zone in mandatory_zone_dirs(root):
        for md_path in sorted(zone.rglob("*.md")):
            if is_exempt_path(md_path, root):
                continue
            rel = md_path.relative_to(root)
            text = read_text(md_path)
            if text is None:
                violations.append({
                    "check": "frontmatter", "severity": "high", "path": str(rel),
                    "message": "file could not be read.",
                })
                continue
            fields = parse_frontmatter(text)
            if fields is None:
                violations.append({
                    "check": "frontmatter", "severity": "high", "path": str(rel),
                    "message": "missing YAML frontmatter (mandatory zone requires "
                               "type/owner/created/status).",
                })
                continue
            # Native-schema sniff (v0.4.0, mirrors the source team's sentinel
            # upgrade): all three team fields absent BUT a native field
            # (name/description/version/title) present = this file belongs to
            # another metadata system (SKILL.md, plugin manifests, ...) that
            # landed in a mandatory zone. Report it as "needs a human call"
            # instead of four misleading "required field missing" errors.
            if (not fields.get("type") and not fields.get("owner") and not fields.get("status")
                    and any(fields.get(k) for k in ("name", "description", "version", "title"))):
                violations.append({
                    "check": "frontmatter", "severity": "medium", "path": str(rel),
                    "message": "file carries another system's frontmatter schema "
                               "(name/description/version/title) inside a mandatory zone — "
                               "needs a human call: move it to where its system lives "
                               "(e.g. 90-methodology/skills/), or convert it to the team schema.",
                })
                continue
            for f in REQUIRED_FIELDS:
                if not fields.get(f):
                    violations.append({
                        "check": "frontmatter", "severity": "high", "path": str(rel),
                        "message": f"required field missing: {f}",
                    })
            if fields.get("type") and fields["type"] not in TYPE_VALUES:
                violations.append({
                    "check": "frontmatter", "severity": "high", "path": str(rel),
                    "message": f"type value '{fields['type']}' is not in the controlled "
                               f"7-value table: {sorted(TYPE_VALUES)}",
                })
            if fields.get("status") and fields["status"] not in STATUS_VALUES:
                violations.append({
                    "check": "frontmatter", "severity": "high", "path": str(rel),
                    "message": f"status value '{fields['status']}' is not in the controlled "
                               f"5-value table: {sorted(STATUS_VALUES)}",
                })
            created = fields.get("created")
            if created and not (ISO_DATE_RE.match(created) and _is_real_date(created)):
                violations.append({
                    "check": "frontmatter", "severity": "medium", "path": str(rel),
                    "message": f"created value '{created}' is not a valid YYYY-MM-DD date.",
                })
            # Archive-lingering hint (v0.4.0, mirrors the source team's sentinel
            # upgrade): a file marked archived/expired that still lives in a
            # mandatory (live) zone probably belongs in 98-archive/. Low
            # severity on purpose — sometimes an expired file is deliberately
            # kept in place as a tombstone; this is a nudge, not a violation.
            if fields.get("status") in ("archived", "expired"):
                violations.append({
                    "check": "frontmatter", "severity": "low", "path": str(rel),
                    "message": f"status is '{fields['status']}' but the file still lives in a "
                               "live mandatory zone — consider moving it to 98-archive/ "
                               "(or re-activate it if it is actually still in service).",
                })
    return violations


def _is_real_date(value: str) -> bool:
    try:
        datetime.strptime(value, "%Y-%m-%d")
        return True
    except ValueError:
        return False


# ---------------------------------------------------------------------------
# Check 4: Broken links (relative markdown links inside .md files)
# ---------------------------------------------------------------------------

def check_broken_links(root: Path) -> list[dict]:
    violations: list[dict] = []
    for md_path in sorted(root.rglob("*.md")):
        if is_exempt_path(md_path, root):
            continue
        text = read_text(md_path)
        if text is None:
            continue
        for m in MD_LINK_RE.finditer(text):
            target = m.group(1).strip()
            if not target:
                continue
            # Skip external / non-file targets.
            if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", target):  # http(s)://, mailto:, etc.
                continue
            if target.startswith("#"):
                continue
            if target.startswith("{{") and target.endswith("}}"):
                continue  # unresolved placeholder, not a real link yet
            # Strip a trailing anchor (#section) before resolving to a file.
            file_part = target.split("#", 1)[0].strip()
            if not file_part:
                continue
            if file_part.startswith("/"):
                candidate = root / file_part.lstrip("/")
            else:
                candidate = (md_path.parent / file_part).resolve()
            if not candidate.exists():
                violations.append({
                    "check": "broken-link", "severity": "medium",
                    "path": str(md_path.relative_to(root)),
                    "message": f"link target does not resolve to a file on disk: {target}",
                })
    return violations


# ---------------------------------------------------------------------------
# Report
# ---------------------------------------------------------------------------

def run_all(root: Path) -> dict:
    checks = {
        "existence": check_existence(root),
        "orphan": check_orphans(root),
        "frontmatter": check_frontmatter(root),
        "broken-link": check_broken_links(root),
    }
    all_violations = [v for vs in checks.values() for v in vs]
    return {
        "sentinelVersion": "0.1.0-min",
        "teamRoot": str(root),
        "ranAt": datetime.now(timezone.utc).isoformat(),
        "checkCounts": {name: len(vs) for name, vs in checks.items()},
        "totalViolations": len(all_violations),
        "overall": "CLEAN" if not all_violations else "DRIFT FOUND",
        "violations": all_violations,
    }


def render_report_text(report: dict) -> str:
    lines: list[str] = []
    lines.append(f"=== structure sentinel · {report['teamRoot']} ===")
    lines.append(f"ran at   : {report['ranAt']}")
    lines.append(f"overall  : {report['overall']}")
    lines.append(
        "checks   : existence={existence} orphan={orphan} frontmatter={frontmatter} "
        "broken-link={broken-link}".format(**report["checkCounts"])
    )
    lines.append("")
    if not report["violations"]:
        lines.append("Nothing to report -- structure looks clean.")
        return "\n".join(lines)
    by_check: dict[str, list[dict]] = {}
    for v in report["violations"]:
        by_check.setdefault(v["check"], []).append(v)
    for check_name, items in by_check.items():
        lines.append(f"-- {check_name} ({len(items)}) --")
        for v in items:
            lines.append(f"  [{v['severity']}] {v['path']}")
            lines.append(f"      {v['message']}")
        lines.append("")
    lines.append(
        f"TOTAL: {report['totalViolations']} issue(s). This is a guardrail, not a gate -- "
        f"nothing was changed. Fix what matters, re-run to confirm."
    )
    return "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser(description="Minimal structure sentinel for a nomad-skeleton team workspace.")
    parser.add_argument("team_root", nargs="?", default=".", help="Team root directory (default: cwd)")
    parser.add_argument("--json", dest="json_out", default=None, help="Also write a machine-readable JSON report to this path")
    args = parser.parse_args()

    root = Path(args.team_root).resolve()
    if not root.is_dir():
        print(f"ERROR: team_root does not exist or is not a directory: {root}")
        return 2

    report = run_all(root)
    print(render_report_text(report))

    if args.json_out:
        Path(args.json_out).write_text(
            json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n",
        )
        print(f"\nJSON report written: {args.json_out}")

    return 0 if report["overall"] == "CLEAN" else 1


if __name__ == "__main__":
    sys.exit(main())