agent-concepts 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +771 -2
  3. package/concepts/bc-brainstorming/body/SKILL.md +43 -0
  4. package/concepts/bc-code-review/body/SKILL.md +120 -0
  5. package/concepts/bc-codebase-design/body/SKILL.md +54 -0
  6. package/concepts/bc-codebase-docs/body/SKILL.md +150 -0
  7. package/concepts/bc-council-audit-security/body/SKILL.md +72 -0
  8. package/concepts/bc-council-chain/body/SKILL.md +71 -0
  9. package/concepts/bc-council-challenge-plan/body/SKILL.md +78 -0
  10. package/concepts/bc-council-find-bugs/body/SKILL.md +70 -0
  11. package/concepts/bc-council-improve-architecture/body/SKILL.md +52 -0
  12. package/concepts/bc-council-mode/body/SKILL.md +56 -0
  13. package/concepts/bc-council-mode/body/examples/agents/README.md +11 -0
  14. package/concepts/bc-council-mode/body/examples/agents/council-change.md +14 -0
  15. package/concepts/bc-council-mode/body/examples/agents/council-compat.md +14 -0
  16. package/concepts/bc-council-mode/body/examples/agents/council-risk.md +14 -0
  17. package/concepts/bc-council-mode/body/references/pass-contracts.md +133 -0
  18. package/concepts/bc-delegate-investigation/body/SKILL.md +119 -0
  19. package/concepts/bc-delegate-investigation/body/examples/pi-settings-snippet.json +8 -0
  20. package/concepts/bc-delegate-investigation/body/pi.md +168 -0
  21. package/concepts/bc-design/body/SKILL.md +49 -0
  22. package/concepts/bc-design/body/design-framework.md +39 -0
  23. package/concepts/bc-design/body/existing-app.md +9 -0
  24. package/concepts/bc-design/body/new-work.md +22 -0
  25. package/concepts/bc-design/body/principles.md +34 -0
  26. package/concepts/bc-design/body/surfaces.md +13 -0
  27. package/concepts/bc-diagnosing-bugs/body/SKILL.md +83 -0
  28. package/concepts/bc-dispatching-parallel-agents/body/SKILL.md +63 -0
  29. package/concepts/bc-domain-modeling/body/SKILL.md +40 -0
  30. package/concepts/bc-executing-plans/body/SKILL.md +50 -0
  31. package/concepts/bc-explain-visually/body/SKILL.md +167 -0
  32. package/concepts/bc-find-bugs/body/SKILL.md +90 -0
  33. package/concepts/bc-finishing-development-branch/body/SKILL.md +73 -0
  34. package/concepts/bc-grilling/body/SKILL.md +22 -0
  35. package/concepts/bc-handoff/body/SKILL.md +104 -0
  36. package/concepts/bc-handoff/body/pickup.md +107 -0
  37. package/concepts/bc-handoff/body/writing.md +217 -0
  38. package/concepts/bc-improve-codebase-architecture/body/SKILL.md +101 -0
  39. package/concepts/bc-json-canvas/body/SKILL.md +40 -0
  40. package/concepts/bc-json-canvas/body/references/EXAMPLES.md +71 -0
  41. package/concepts/bc-json-canvas/body/references/SPEC.md +55 -0
  42. package/concepts/bc-json-canvas/body/references/VALIDATION.md +26 -0
  43. package/concepts/bc-minimal-solution-ladder/body/SKILL.md +120 -0
  44. package/concepts/bc-obsidian-bases/body/SKILL.md +59 -0
  45. package/concepts/bc-obsidian-bases/body/references/EXAMPLES.md +80 -0
  46. package/concepts/bc-obsidian-bases/body/references/FUNCTIONS.md +49 -0
  47. package/concepts/bc-obsidian-bases/body/references/SYNTAX.md +82 -0
  48. package/concepts/bc-obsidian-bases/body/references/TROUBLESHOOTING.md +41 -0
  49. package/concepts/bc-obsidian-markdown/body/SKILL.md +47 -0
  50. package/concepts/bc-obsidian-markdown/body/references/CALLOUTS.md +40 -0
  51. package/concepts/bc-obsidian-markdown/body/references/EMBEDS.md +35 -0
  52. package/concepts/bc-obsidian-markdown/body/references/PROPERTIES.md +37 -0
  53. package/concepts/bc-optimize-code/body/SKILL.md +41 -0
  54. package/concepts/bc-performance-guardrails/body/SKILL.md +53 -0
  55. package/concepts/bc-performance-guardrails/body/measuring.md +29 -0
  56. package/concepts/bc-performance-guardrails/body/targets.md +20 -0
  57. package/concepts/bc-pipeline-to-done/body/SKILL.md +205 -0
  58. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-auditor.md +19 -0
  59. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-reviewer.md +19 -0
  60. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-worker.md +19 -0
  61. package/concepts/bc-pipeline-to-done/body/execute-issue.md +71 -0
  62. package/concepts/bc-pipeline-to-done/body/recovery-bundle.md +79 -0
  63. package/concepts/bc-pipeline-to-done/body/review-contract.md +105 -0
  64. package/concepts/bc-pipeline-to-done/body/roles.md +13 -0
  65. package/concepts/bc-pipeline-to-done/body/scripts/publish-check.py +172 -0
  66. package/concepts/bc-pipeline-to-done/body/source-issues.md +86 -0
  67. package/concepts/bc-pipeline-to-done/body/source-work-items.md +76 -0
  68. package/concepts/bc-plain-language/body/SKILL.md +134 -0
  69. package/concepts/bc-plan-slicing/body/SKILL.md +56 -0
  70. package/concepts/bc-plan-to-pipeline/body/SKILL.md +89 -0
  71. package/concepts/bc-prd-drafting/body/SKILL.md +43 -0
  72. package/concepts/bc-prompting-agents/body/SKILL.md +278 -0
  73. package/concepts/bc-prototype/body/SKILL.md +40 -0
  74. package/concepts/bc-qmd/body/SKILL.md +64 -0
  75. package/concepts/bc-research/body/SKILL.md +26 -0
  76. package/concepts/bc-security-audit/body/AI-AND-LLM.md +25 -0
  77. package/concepts/bc-security-audit/body/ATTACK-CLASSES.md +35 -0
  78. package/concepts/bc-security-audit/body/DESKTOP-MOBILE-AND-LOCAL-IPC.md +28 -0
  79. package/concepts/bc-security-audit/body/RECONNAISSANCE.md +49 -0
  80. package/concepts/bc-security-audit/body/SKILL.md +117 -0
  81. package/concepts/bc-security-audit/body/SUPPLY-CHAIN-AND-RELEASE.md +28 -0
  82. package/concepts/bc-security-audit/body/VALIDATION-AND-REPORTING.md +124 -0
  83. package/concepts/bc-security-audit/body/WEB-PROTOCOL-AND-AUTH.md +27 -0
  84. package/concepts/bc-security-audit/body/validate_audit.py +151 -0
  85. package/concepts/bc-self-improve/body/SKILL.md +104 -0
  86. package/concepts/bc-seo/body/CITATIONS.md +23 -0
  87. package/concepts/bc-seo/body/IMAGE-SEO.md +350 -0
  88. package/concepts/bc-seo/body/SKILL.md +453 -0
  89. package/concepts/bc-setup-project/body/SKILL.md +252 -0
  90. package/concepts/bc-setup-project/body/scaffold.py +2751 -0
  91. package/concepts/bc-setup-project/body/starter-items.md +157 -0
  92. package/concepts/bc-setup-project/body/work-data.md +114 -0
  93. package/concepts/bc-setup-project/body/work_index.py +626 -0
  94. package/concepts/bc-setup-project/body/work_spent.py +220 -0
  95. package/concepts/bc-subagent-driven-development/body/SKILL.md +61 -0
  96. package/concepts/bc-tdd/body/SKILL.md +184 -0
  97. package/concepts/bc-tdd/body/formal.md +77 -0
  98. package/concepts/bc-tdd/body/mocking.md +49 -0
  99. package/concepts/bc-tdd/body/properties.md +59 -0
  100. package/concepts/bc-tdd/body/refactoring.md +12 -0
  101. package/concepts/bc-tdd/body/scripts/confirm-red.py +136 -0
  102. package/concepts/bc-tdd/body/tests.md +59 -0
  103. package/concepts/bc-teach/body/GLOSSARY-FORMAT.md +36 -0
  104. package/concepts/bc-teach/body/LEARNING-RECORD-FORMAT.md +60 -0
  105. package/concepts/bc-teach/body/MISSION-FORMAT.md +34 -0
  106. package/concepts/bc-teach/body/RESOURCES-FORMAT.md +53 -0
  107. package/concepts/bc-teach/body/REVIEW-FORMAT.md +48 -0
  108. package/concepts/bc-teach/body/SKILL.md +281 -0
  109. package/concepts/bc-teach/body/WIKI-FORMAT.md +58 -0
  110. package/concepts/bc-teach/body/scripts/due.py +65 -0
  111. package/concepts/bc-to-spec/body/SKILL.md +21 -0
  112. package/concepts/bc-to-tickets/body/SKILL.md +21 -0
  113. package/concepts/bc-triage/body/AGENT-BRIEF.md +38 -0
  114. package/concepts/bc-triage/body/OUT-OF-SCOPE.md +51 -0
  115. package/concepts/bc-triage/body/SKILL.md +81 -0
  116. package/concepts/bc-unslop/body/SKILL.md +269 -0
  117. package/concepts/bc-using-git-worktrees/body/SKILL.md +91 -0
  118. package/concepts/bc-wiki-maintain/body/SKILL.md +361 -0
  119. package/concepts/bc-wiki-maintain/body/runner/README.md +552 -0
  120. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-lint.service +24 -0
  121. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-lint.timer +15 -0
  122. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain-all.service +29 -0
  123. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain-all.timer +16 -0
  124. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain.service +28 -0
  125. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain.timer +12 -0
  126. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-notify@.service +15 -0
  127. package/concepts/bc-wiki-maintain/body/runner/notify-failure.sh +92 -0
  128. package/concepts/bc-wiki-maintain/body/runner/run-lint.sh +69 -0
  129. package/concepts/bc-wiki-maintain/body/runner/run-promotion-all.sh +103 -0
  130. package/concepts/bc-wiki-maintain/body/runner/run-promotion.sh +270 -0
  131. package/concepts/bc-wiki-maintain/body/wiki_lint.py +958 -0
  132. package/concepts/bc-wiki-maintain/body/wiki_search.py +206 -0
  133. package/concepts/bc-work-sync/body/PLAN.md +46 -0
  134. package/concepts/bc-work-sync/body/SKILL.md +71 -0
  135. package/concepts/bc-writing-plans/body/SKILL.md +79 -0
  136. package/package.json +130 -4
  137. package/packages/agent-kernel-pi/AGENT-KERNEL.md +109 -0
  138. package/packages/agent-kernel-pi/index.js +8 -0
  139. package/packages/agent-kernel-pi/package.json +12 -0
@@ -0,0 +1,958 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only Markdown wiki lint (stdlib only); qmd paths use a narrow YAML line parser."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ from collections import Counter
6
+ import datetime as dt
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ from urllib.parse import unquote
14
+ WIKI_LINK_RE = re.compile(r"\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?\]\]")
15
+ MD_LINK_RE = re.compile(r"(?<!!)\[[^\]]*\]\(\s*(?:<([^>\n]+)>|([^\s)\n]+))(?:\s+(?:\"[^\"]*\"|'[^']*'|\([^)]*\)))?\s*\)")
16
+ INLINE_CODE_RE = re.compile(r"(`+)([^`\n]*?)\1")
17
+ FENCE_RE = re.compile(r"^[ \t]{0,3}(`{3,}|~{3,})")
18
+ LOG_HEADING_RE = re.compile(r"^## (.+?)\s*$")
19
+ LOG_DATED_HEADING_RE = re.compile(r"^## \[(\d{4}-\d{2}-\d{2})\](?:\s|$)")
20
+
21
+
22
+ def without_code(value: str) -> str:
23
+ """Mask fenced blocks and inline code while preserving line structure."""
24
+ visible: list[str] = []
25
+ fence_char: str | None = None
26
+ fence_length = 0
27
+ for line in value.splitlines(keepends=True):
28
+ match = FENCE_RE.match(line)
29
+ if fence_char is not None:
30
+ if match and match.group(1)[0] == fence_char and len(match.group(1)) >= fence_length:
31
+ fence_char = None
32
+ fence_length = 0
33
+ visible.append("\n" if line.endswith("\n") else "")
34
+ continue
35
+ if match:
36
+ fence_char = match.group(1)[0]
37
+ fence_length = len(match.group(1))
38
+ visible.append("\n" if line.endswith("\n") else "")
39
+ continue
40
+ visible.append(INLINE_CODE_RE.sub(lambda match: "".join("\n" if char == "\n" else " " for char in match.group(0)), line))
41
+ return "".join(visible)
42
+
43
+
44
+ def log_headings(value: str) -> list[tuple[str, str | None]]:
45
+ headings = []
46
+ for line in without_code(value).splitlines():
47
+ line = line.rstrip()
48
+ if not LOG_HEADING_RE.match(line):
49
+ continue
50
+ dated = LOG_DATED_HEADING_RE.match(line)
51
+ date = None
52
+ if dated:
53
+ try:
54
+ dt.date.fromisoformat(dated.group(1))
55
+ except ValueError:
56
+ pass
57
+ else:
58
+ date = dated.group(1)
59
+ headings.append((line, date))
60
+ return headings
61
+
62
+ def rel(path: Path, vault: Path) -> str:
63
+ return path.relative_to(vault).as_posix()
64
+
65
+ def text(path: Path) -> str:
66
+ try:
67
+ return path.read_text(encoding="utf-8", errors="ignore")
68
+ except OSError:
69
+ return ""
70
+
71
+ def links(value: str):
72
+ value = without_code(value)
73
+ for match in WIKI_LINK_RE.finditer(value):
74
+ target = match.group(1).strip()
75
+ yield target, f"[[{target}]]"
76
+ for match in MD_LINK_RE.finditer(value):
77
+ target = (match.group(1) or match.group(2)).strip()
78
+ yield target, match.group(0)
79
+
80
+ def skip_link(target: str) -> bool:
81
+ value = target.strip().lower()
82
+ return (not value or value.startswith(("#", "http://", "https://", "mailto:", "//")) or re.match(r"^[a-z][a-z0-9+.-]*:", value) is not None or any(char in target for char in "$`<>{"))
83
+
84
+ def key(path: Path) -> str:
85
+ return path.with_suffix("").as_posix() if path.suffix.lower() == ".md" else path.as_posix()
86
+
87
+ def resolve_link(source: Path, target: str, vault: Path, pages: dict[str, Path], stems: dict[str, list[Path]]):
88
+ """Return (page candidates, existing-local-target) or None for skipped links."""
89
+ if skip_link(target):
90
+ return None
91
+ target = unquote(target.strip().split("#", 1)[0].split("?", 1)[0]).strip()
92
+ raw = Path(target)
93
+ variants = [raw] if raw.is_absolute() else [source.parent / raw, vault / raw]
94
+ if target.startswith("wiki/"):
95
+ variants.append(vault / target[5:])
96
+ seen: set[Path] = set()
97
+ local = False
98
+ for candidate in variants:
99
+ candidate = candidate.resolve()
100
+ if candidate in seen:
101
+ continue
102
+ seen.add(candidate)
103
+ found = pages.get(key(candidate.relative_to(vault))) if candidate.is_relative_to(vault) else None
104
+ if found is not None:
105
+ return [found], False
106
+ local |= candidate.exists()
107
+ target_key = key(Path(target.lstrip("/").removeprefix("wiki/")))
108
+ if target_key in pages:
109
+ return [pages[target_key]], False
110
+ if local:
111
+ return [], True
112
+ return stems.get(Path(target_key).name, []), False
113
+
114
+ def git(repo: Path, *args: str):
115
+ try:
116
+ return subprocess.run(["git", "-C", str(repo), *args], capture_output=True, text=True, check=False)
117
+ except OSError:
118
+ return None
119
+
120
+ def git_root(vault: Path) -> Path | None:
121
+ result = git(vault, "rev-parse", "--show-toplevel")
122
+ return Path(result.stdout.strip()).resolve() if result and result.returncode == 0 and result.stdout.strip() else None
123
+
124
+ def git_path(repo: Path, path: Path) -> str | None:
125
+ try:
126
+ return path.resolve().relative_to(repo).as_posix()
127
+ except ValueError:
128
+ return None
129
+
130
+ def git_date(repo: Path | None, path: Path) -> tuple[str | None, str]:
131
+ if repo is None:
132
+ return None, "not a git repository"
133
+ relative = git_path(repo, path)
134
+ if relative is None:
135
+ return None, "outside git repository"
136
+ result = git(repo, "log", "-1", "--format=%cs", "--", relative)
137
+ value = result.stdout.strip() if result else ""
138
+ return (value, "") if result and result.returncode == 0 and value else (None, "untracked or has no commit")
139
+
140
+ def promotion_status(vault: Path, repo: Path | None) -> dict:
141
+ log_path = vault / "log.md"
142
+ current_headings = log_headings(text(log_path))
143
+ result = {
144
+ "count": None,
145
+ "range": None,
146
+ "last_promotion": None,
147
+ "note": None,
148
+ "headings": [],
149
+ "undatable_headings": [],
150
+ }
151
+ if repo is None:
152
+ result["note"] = "unknown: not a git repository"
153
+ return result
154
+ relative = git_path(repo, log_path)
155
+ if relative is None:
156
+ result["note"] = "unknown: log.md is outside the git repository"
157
+ return result
158
+ listed = git(repo, "ls-files", "--error-unmatch", "--", relative)
159
+ if not listed or listed.returncode != 0:
160
+ result["note"] = "unknown: log.md is untracked"
161
+ return result
162
+
163
+ # Promotion commits do not touch log.md, so scope the subject search by the
164
+ # vault directory instead of using a path-limited git log.
165
+ promotion_log = git(repo, "log", "--format=%H%x00%cs%x00%s", "--grep=^wiki: promote")
166
+ promotion_record = None
167
+ vault_prefix = str(Path(relative).parent)
168
+ if promotion_log and promotion_log.returncode == 0:
169
+ for record in promotion_log.stdout.splitlines():
170
+ fields = record.split("\x00", 2)
171
+ if len(fields) != 3:
172
+ continue
173
+ commit, date, subject = fields
174
+ touched = git(repo, "diff-tree", "--no-commit-id", "--name-only", "-r", commit, "--", vault_prefix)
175
+ if touched and touched.returncode == 0 and touched.stdout.strip():
176
+ promotion_record = (commit, date, subject)
177
+ break
178
+
179
+ if promotion_record is None:
180
+ unpromoted = current_headings
181
+ result["count"] = len(unpromoted)
182
+ result["note"] = "no wiki: promote log entries commit found; all current log entries are unpromoted"
183
+ else:
184
+ commit, date, subject = promotion_record
185
+ result["last_promotion"] = {"commit": commit, "date": date, "subject": subject}
186
+ previous = git(repo, "show", f"{commit}:{relative}")
187
+ if not previous or previous.returncode != 0:
188
+ result["note"] = "unknown: could not compare log.md with last promotion commit"
189
+ unpromoted = []
190
+ else:
191
+ previous_headings = log_headings(previous.stdout)
192
+ unpromoted = [
193
+ heading
194
+ for heading, remaining in Counter(current_headings).items()
195
+ for _ in range(max(0, remaining - Counter(previous_headings)[heading]))
196
+ ]
197
+ result["count"] = len(unpromoted)
198
+ result["headings"] = [heading for heading, _date in unpromoted]
199
+ result["undatable_headings"] = [heading for heading, date in unpromoted if date is None]
200
+ if result["count"] is not None and result["count"] > 0:
201
+ dates = [date for _heading, date in unpromoted if date is not None]
202
+ if dates:
203
+ result["range"] = f"{min(dates)}..{max(dates)}"
204
+ return result
205
+
206
+ def qmd_paths(registry: Path) -> list[Path]:
207
+ path_re = re.compile(r"^\s+path:\s*(?:\"([^\"]+)\"|'([^']+)'|(\S.*?))\s*$")
208
+ paths = []
209
+ for line in text(registry).splitlines():
210
+ match = path_re.match(line)
211
+ if not match:
212
+ continue
213
+ value = next(group for group in match.groups() if group is not None)
214
+ paths.append(Path(os.path.expandvars(value).strip()).expanduser().resolve())
215
+ return paths
216
+
217
+
218
+ def qmd_collections(registry: Path) -> list[dict]:
219
+ """Collections of a qmd collections file as {name, path, pattern}; narrow line parser."""
220
+ name_re = re.compile(r"^ ([^\s#][^:]*):\s*$")
221
+ field_re = re.compile(r"^ (path|pattern):\s*(?:\"([^\"]+)\"|'([^']+)'|(\S.*?))\s*$")
222
+ found: list[dict] = []
223
+ for line in text(registry).splitlines():
224
+ name = name_re.match(line)
225
+ if name:
226
+ found.append({"name": name.group(1).strip().strip("\"'"), "path": None, "pattern": "**/*.md"})
227
+ continue
228
+ field = field_re.match(line)
229
+ if field and found:
230
+ value = next(group for group in field.groups()[1:] if group is not None)
231
+ if field.group(1) == "path":
232
+ found[-1]["path"] = Path(os.path.expandvars(value).strip()).expanduser().resolve()
233
+ else:
234
+ found[-1]["pattern"] = value.strip()
235
+ return [collection for collection in found if collection["path"] is not None]
236
+
237
+
238
+ def qmd_covering_path(vault: Path, paths: list[Path]) -> Path | None:
239
+ for registered in paths:
240
+ try:
241
+ vault.relative_to(registered)
242
+ except ValueError:
243
+ continue
244
+ return registered
245
+ return None
246
+
247
+
248
+ def qmd_status(
249
+ vault: Path,
250
+ registry: Path | None = None,
251
+ machine_index: Path | None = None,
252
+ ) -> dict:
253
+ registry = registry or Path.home() / "Sync" / "Scripts" / "config" / "qmd-collections.yml"
254
+ machine_index = machine_index or Path.home() / ".config" / "qmd" / "index.yml"
255
+ result = {
256
+ "registered": False,
257
+ "unindexed": False,
258
+ "intentional_exclusion": False,
259
+ "registry": str(registry),
260
+ "machine_index": str(machine_index),
261
+ "canonical_path": None,
262
+ "machine_path": None,
263
+ "reason": None,
264
+ }
265
+ if not registry.exists():
266
+ result["reason"] = "registry file is missing; skipped"
267
+ return result
268
+
269
+ canonical_path = qmd_covering_path(vault, qmd_paths(registry))
270
+ result["canonical_path"] = str(canonical_path) if canonical_path else None
271
+ if canonical_path is None:
272
+ for line in text(vault / "project" / "overview.md").splitlines():
273
+ if "excluded from the global qmd index" in line.lower():
274
+ result.update(intentional_exclusion=True, reason=line.strip())
275
+ return result
276
+ if machine_index.exists():
277
+ machine_path = qmd_covering_path(vault, qmd_paths(machine_index))
278
+ result["machine_path"] = str(machine_path) if machine_path else None
279
+ result["reason"] = (
280
+ f"vault path is absent from canonical qmd registry; machine index covers {machine_path}"
281
+ if machine_path
282
+ else "vault path is absent from qmd registry"
283
+ )
284
+ else:
285
+ result["reason"] = (
286
+ "vault path is absent from qmd registry; "
287
+ f"machine index unavailable at {machine_index}"
288
+ )
289
+ return result
290
+
291
+ if not machine_index.exists():
292
+ result["registered"] = True
293
+ result["reason"] = (
294
+ f"covered by canonical path {canonical_path}; machine index unavailable at {machine_index}; "
295
+ "reporting canonical-only coverage"
296
+ )
297
+ return result
298
+
299
+ machine_path = qmd_covering_path(vault, qmd_paths(machine_index))
300
+ result["machine_path"] = str(machine_path) if machine_path else None
301
+ if machine_path:
302
+ result["registered"] = True
303
+ result["reason"] = f"covered by canonical path {canonical_path} and machine index path {machine_path}"
304
+ else:
305
+ result["unindexed"] = True
306
+ result["reason"] = (
307
+ f"covered by canonical path {canonical_path}; machine index lacks a covering path at {machine_index}"
308
+ )
309
+ return result
310
+
311
+ QMD_EXCLUSION_TEXT = "excluded from the global qmd index"
312
+
313
+
314
+ def visible_qmd_status(vault: Path, table: dict[str, str], registry: Path, machine_index: Path) -> dict:
315
+ """Registration of a visible-layout project: the two collections `--qmd-entry` prints.
316
+
317
+ qmd skips every hidden path part, so one collection rooted at the repository cannot
318
+ index `.bc-agent/`; the mechanics need their own collection rooted there.
319
+ """
320
+ project, pattern = vault.parent, knowledge_pattern(table)
321
+ result = {
322
+ "registered": False, "unindexed": False, "intentional_exclusion": False,
323
+ "registry": str(registry), "machine_index": str(machine_index),
324
+ "canonical_path": None, "machine_path": None, "reason": None,
325
+ "knowledge_pattern": pattern,
326
+ }
327
+ if not registry.exists():
328
+ result["reason"] = "registry file is missing; skipped"
329
+ return result
330
+
331
+ def missing(collections: list[dict]) -> list[str]:
332
+ problems = []
333
+ rooted = [collection for collection in collections if collection["path"] == project]
334
+ if not any(collection["pattern"] == pattern for collection in rooted):
335
+ problems.append(
336
+ f"collection {rooted[0]['name']} at {project} has pattern {rooted[0]['pattern']}; "
337
+ f"the table expects {pattern}" if rooted else
338
+ f"no collection rooted at {project} with pattern {pattern}")
339
+ if not any(collection["path"] == vault for collection in collections):
340
+ problems.append(f"no collection rooted at {vault}")
341
+ return problems
342
+
343
+ canonical = missing(qmd_collections(registry))
344
+ if canonical:
345
+ for line in text(vault / "AGENTS.md").splitlines():
346
+ if QMD_EXCLUSION_TEXT in line.lower():
347
+ result.update(intentional_exclusion=True, reason=line.strip())
348
+ return result
349
+ result["reason"] = ("; ".join(canonical) + "; print the entry with "
350
+ "`wiki_lint.py <vault-root> --qmd-entry <slug>`")
351
+ return result
352
+ result["canonical_path"] = str(project)
353
+ if not machine_index.exists():
354
+ result["registered"] = True
355
+ result["reason"] = (f"both collections are in the canonical registry; machine index unavailable at "
356
+ f"{machine_index}; reporting canonical-only coverage")
357
+ return result
358
+ machine = missing(qmd_collections(machine_index))
359
+ if machine:
360
+ result["unindexed"] = True
361
+ result["reason"] = "both collections are in the canonical registry; machine index: " + "; ".join(machine)
362
+ else:
363
+ result["registered"] = True
364
+ result["machine_path"] = str(project)
365
+ result["reason"] = f"knowledge collection at {project} and mechanics collection at {vault} in both registries"
366
+ return result
367
+
368
+
369
+ # --- visible layout ------------------------------------------------------------
370
+ # Copied verbatim from concepts/bc-setup-project/body/scaffold.py, which owns the
371
+ # "Where things go" table contract. Copied rather than imported because a skill
372
+ # body can be deployed as a copy without its sibling concept;
373
+ # tests/test_visible_layout_lint.py fails when the two copies differ.
374
+ WHERE_THINGS_GO_HEADING = "## Where things go"
375
+ _WHERE_THINGS_GO_LINE = re.compile(r"^" + re.escape(WHERE_THINGS_GO_HEADING) + r"[ \t]*\r?$", re.M)
376
+ _UNDECIDED_PATH_CELLS = {"", "—", "-"}
377
+
378
+
379
+ def parse_where_things_go(text: str) -> dict[str, str]:
380
+ """Map each role key of a "Where things go" table to its path.
381
+
382
+ Paths are relative to the project root. A backticked path is unwrapped; a plain
383
+ path is returned stripped; only `—`, `-` or an empty cell means "no decided path"
384
+ and maps to an empty string. Raises ValueError when the heading line is missing,
385
+ when the section has no table rows, or when a role appears twice.
386
+ """
387
+ match = _WHERE_THINGS_GO_LINE.search(text)
388
+ if not match:
389
+ raise ValueError(f"no {WHERE_THINGS_GO_HEADING!r} section")
390
+ section = re.split(r"^## ", text[match.end():], maxsplit=1, flags=re.M)[0]
391
+ result: dict[str, str] = {}
392
+ for line in section.splitlines():
393
+ line = line.strip()
394
+ if not line.startswith("|"):
395
+ continue
396
+ cells = [cell.strip() for cell in line.strip("|").split("|")]
397
+ if len(cells) < 2 or cells[0] == "Role" or set(cells[0]) <= {"-", ":", " "}:
398
+ continue
399
+ role, path = cells[0], cells[1]
400
+ if role in result:
401
+ raise ValueError(f"role {role!r} appears twice in {WHERE_THINGS_GO_HEADING!r}")
402
+ if path.count("`") >= 2:
403
+ path = path.split("`")[1].strip()
404
+ result[role] = "" if path in _UNDECIDED_PATH_CELLS else path
405
+ if not result:
406
+ raise ValueError(f"{WHERE_THINGS_GO_HEADING!r} section has no table rows")
407
+ return result
408
+
409
+
410
+ def layout_table(vault: Path) -> dict[str, str] | None:
411
+ """Return the role table when VAULT is the `.bc-agent/` of a visible-layout project."""
412
+ # Locate the heading outside code fences, so a vault AGENTS.md that quotes the
413
+ # visible protocol in a fence stays a vault. The copied parser itself stays
414
+ # verbatim (the drift test compares it), so it is handed the text from that line.
415
+ raw = text(vault / "AGENTS.md").splitlines(keepends=True)
416
+ masked = without_code("".join(raw)).splitlines(keepends=True)
417
+ start = next((index for index, line in enumerate(masked) if _WHERE_THINGS_GO_LINE.match(line)), None)
418
+ if start is None:
419
+ return None
420
+ try:
421
+ return parse_where_things_go("".join(raw[start:]))
422
+ except ValueError:
423
+ return None
424
+
425
+
426
+ WORK_STAGE_ROLES = ("work-planned", "work-active", "work-done", "work-dropped")
427
+ # Roles whose paths the project's search collection indexes, in pattern order, with the
428
+ # authority context a search hit carries for a folder role (None: a single file).
429
+ SEARCH_ROLE_CONTEXTS = (
430
+ ("glossary", None),
431
+ ("decisions", "Decision records — binding unless superseded"),
432
+ ("research", "Dated investigations and architecture reviews — evidence, not authoritative"),
433
+ ("requirements", None),
434
+ ("architecture", None),
435
+ ("components", "Verified state of real systems, dated"),
436
+ ("ideas", None),
437
+ ("work-planned", "Work items agreed but not started; the folder is the status"),
438
+ ("work-active", "Work items in progress"),
439
+ ("work-done", "Finished work items by month, each with its Outcome"),
440
+ ("work-dropped", "Dropped work and rejected requests with the reason — check before proposing similar work"),
441
+ )
442
+
443
+
444
+ def search_paths(table: dict[str, str]) -> list[tuple[str, str, str | None]]:
445
+ """(glob, role path, context) for each searchable role with a visible path."""
446
+ found: list[tuple[str, str, str | None]] = []
447
+ for role, context in SEARCH_ROLE_CONTEXTS:
448
+ path = table.get(role, "").strip().removeprefix("./")
449
+ if not path or path.startswith("."):
450
+ continue # undecided, or hidden: qmd skips hidden paths, and `.bc-agent/` has its own collection
451
+ folder = path.endswith("/") or not Path(path).suffix
452
+ glob = path.rstrip("/") + "/**/*.md" if folder else path
453
+ if glob not in (item[0] for item in found):
454
+ found.append((glob, path.rstrip("/"), context if folder else None))
455
+ return found
456
+
457
+
458
+ def knowledge_pattern(table: dict[str, str]) -> str:
459
+ """The qmd pattern of the project's knowledge collection, built from the table."""
460
+ globs = [glob for glob, _path, _context in search_paths(table)]
461
+ return "{" + ",".join(globs) + "}" if len(globs) > 1 else (globs[0] if globs else "")
462
+
463
+
464
+ def registry_path(path: Path) -> str:
465
+ """A path as the synced collections file writes it: `~/` under the home folder."""
466
+ try:
467
+ return "~/" + path.relative_to(Path.home().resolve()).as_posix()
468
+ except ValueError:
469
+ return path.as_posix()
470
+
471
+
472
+ def qmd_entry(vault: Path, table: dict[str, str], slug: str) -> str:
473
+ """Collections-file entries for a visible-layout project: knowledge, then mechanics."""
474
+ project = vault.parent
475
+ mechanics = [
476
+ f" {slug}:", f" path: {registry_path(vault)}", ' pattern: "**/*.md"', " ignore: []", " contexts:",
477
+ f' "/": "Agent mechanics for {slug}: session protocol and Where things go table, map, journal log"',
478
+ ' "/conventions": "Validation, git, layout and workflow norms — follow these"',
479
+ ' "/references": "Recurring commands, paths, gotchas"',
480
+ ]
481
+ knowledge = [
482
+ f" {slug}-project:", f" path: {registry_path(project)}", f' pattern: "{knowledge_pattern(table)}"',
483
+ " ignore: []", " contexts:",
484
+ f' "/": "Project knowledge for {slug}: glossary, work items (the folder is the status), decisions, research"',
485
+ ]
486
+ knowledge += [f' "/{path}": "{context}"' for _glob, path, context in search_paths(table) if context]
487
+ return "\n".join(mechanics + [""] + knowledge) + "\n"
488
+ # Three or more digits, never all zeros: numbering starts at 001 and continues past 999.
489
+ WORK_ITEM_NAME_RE = re.compile(r"^(?!0+-)(\d{3,})-[A-Za-z0-9][A-Za-z0-9._-]*$")
490
+ MONTH_FOLDER_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
491
+ STATUS_LINE_RE = re.compile(r"^[ \t]*(?:[-*][ \t]+)?\**Status\**[ \t]*:", re.M | re.I)
492
+
493
+
494
+ def finding(severity: str, check: str, path: Path, project: Path, problem: str, fix: str) -> dict:
495
+ return {"severity": severity, "check": check, "path": rel(path, project), "problem": problem, "fix": fix}
496
+
497
+
498
+ def folder_entries(folder: Path, project: Path, found: list[dict]) -> list[Path]:
499
+ """Candidate items directly in a stage or month folder.
500
+
501
+ `README.md` documents the folder and is not an item. Any other non-Markdown file is
502
+ reported as a warning and not scanned, since it can be neither an item nor read as one.
503
+ """
504
+ entries: list[Path] = []
505
+ for entry in sorted(folder.iterdir()):
506
+ if entry.name.startswith(".") or entry.name == "README.md":
507
+ continue
508
+ if entry.is_file() and entry.suffix != ".md":
509
+ found.append(finding("warning", "non-markdown", entry, project,
510
+ "non-Markdown file sits directly in a work stage folder.",
511
+ "move it into the folder item it belongs to, or out of the work folders"))
512
+ continue
513
+ entries.append(entry)
514
+ return entries
515
+
516
+
517
+ def stage_items(stage: Path, done: bool, project: Path, found: list[dict]) -> list[Path]:
518
+ """Items in one stage folder; in the done folder, items sit inside month folders."""
519
+ entries = folder_entries(stage, project, found) if stage.is_dir() else []
520
+ if not done:
521
+ return entries
522
+ items: list[Path] = []
523
+ for entry in entries:
524
+ if entry.is_dir() and MONTH_FOLDER_RE.match(entry.name):
525
+ items.extend(folder_entries(entry, project, found))
526
+ elif entry.is_dir() and not WORK_ITEM_NAME_RE.match(entry.name):
527
+ found.append(finding("error", "done-month-folder", entry, project,
528
+ "month folder name is not YYYY-MM.", "rename it to the item's finishing month, e.g. 2026-03"))
529
+ items.extend(folder_entries(entry, project, found))
530
+ else:
531
+ found.append(finding("error", "done-month-folder", entry, project,
532
+ "item sits directly in the done folder.", "git mv it into a <year>-<month>/ folder"))
533
+ items.append(entry)
534
+ return items
535
+
536
+
537
+ def role_notes(agents_text: str, role: str) -> str:
538
+ """Notes cell of ROLE's table row; the shared parser returns paths only."""
539
+ match = re.search(r"^\|\s*" + re.escape(role) + r"\s*\|[^|\n]*\|(.*)$", agents_text, re.M)
540
+ return match.group(1) if match else ""
541
+
542
+
543
+ def outcome_filled(content: str) -> bool:
544
+ """True when `## Outcome` has text other than comments or the template's `<...>` placeholder."""
545
+ match = re.search(r"^## Outcome[ \t]*$", content, re.M)
546
+ if not match:
547
+ return False
548
+ section = re.split(r"^#{1,2} ", content[match.end():], maxsplit=1, flags=re.M)[0]
549
+ section = re.sub(r"<!--.*?-->", "", section, flags=re.S)
550
+ return any(line.strip() and not re.fullmatch(r"<[^>]*>", line.strip()) for line in section.splitlines())
551
+
552
+
553
+ def item_name_number(item: Path) -> int | None:
554
+ name = item.name if item.is_dir() else item.stem if item.suffix == ".md" else ""
555
+ match = WORK_ITEM_NAME_RE.match(name)
556
+ return int(match.group(1)) if match else None
557
+
558
+
559
+ def work_findings(project: Path, table: dict[str, str], agents_text: str) -> list[dict]:
560
+ """Check the work folders named by the table; errors break the layout's rules."""
561
+ found: list[dict] = []
562
+ numbered: dict[int, list[Path]] = {}
563
+ seen_stages: set[Path] = set()
564
+ for role in WORK_STAGE_ROLES:
565
+ if not table.get(role):
566
+ continue
567
+ stage = (project / table[role]).resolve()
568
+ if stage in seen_stages:
569
+ continue # two roles hand-edited to one path: count its items once
570
+ seen_stages.add(stage)
571
+ for item in stage_items(project / table[role], role == "work-done", project, found):
572
+ number = item_name_number(item)
573
+ if number is not None:
574
+ numbered.setdefault(number, []).append(item)
575
+ if number is None:
576
+ found.append(finding("warning", "item-name", item, project,
577
+ "item name is not <number of three or more digits, from 001>-<slug>.",
578
+ "git mv it to NNN-slug.md (or NNN-slug/) using the next free number"))
579
+ body = item / "plan.md" if item.is_dir() else item
580
+ if item.is_dir() and not body.is_file():
581
+ found.append(finding("warning", "missing-plan", item, project,
582
+ "folder item has no plan.md.",
583
+ "add plan.md from the work-item template"))
584
+ content = without_code(text(body)) if body.is_file() else ""
585
+ for page in sorted(item.rglob("*.md")) if item.is_dir() else [item]:
586
+ if STATUS_LINE_RE.search(without_code(text(page))):
587
+ found.append(finding("error", "status-line", page, project,
588
+ "item has a Status: line; the folder is the status.",
589
+ "delete the Status: line"))
590
+ if role in {"work-done", "work-dropped"} and not outcome_filled(content):
591
+ found.append(finding("error", "missing-outcome", body, project,
592
+ "finished or dropped item has no filled ## Outcome section.",
593
+ "write what happened, or why it was dropped, under ## Outcome"))
594
+ for role, path in table.items():
595
+ if role == AGENT_EXTRAS_ROLE:
596
+ continue # a list of `.bc-agent/` entries, checked by agent_mechanics_findings
597
+ if not path or (project / path).exists() or "created on first need" in role_notes(agents_text, role).lower():
598
+ continue
599
+ found.append(finding("warning", "role-path", project / path, project,
600
+ f"the {role} path in the Where things go table does not exist.",
601
+ "create it, or correct the path in .bc-agent/AGENTS.md"))
602
+ found.extend(agent_mechanics_findings(project, table, agents_text))
603
+ for number, items in sorted(numbered.items()):
604
+ if len(items) > 1:
605
+ for item in items:
606
+ found.append(finding("error", "duplicate-number", item, project,
607
+ f"number {number:03d} is used by {len(items)} items.",
608
+ "renumber the later item to the highest number in any stage plus one"))
609
+ return found
610
+
611
+
612
+ # `.bc-agent/` holds agent mechanics only (owner decision 2026-11-12, after `bc-prototype`
613
+ # kept writing to a scratch folder the user named). Every other direct entry is an error.
614
+ AGENT_MECHANICS_ENTRIES = {"AGENTS.md", "map.md", "log.md", "conventions", "references", "templates", "scripts"}
615
+ # Folders a hosted teach workspace owns under `.bc-agent/` (bc-setup-project's
616
+ # teach-workspace row); its index.md catalogs these and nothing else.
617
+ TEACH_OWNED_DIRS = {"learning", "sources", "concepts", "sessions", "questions"}
618
+ # What bc-setup-project's scaffold writes under `.bc-agent/` for the hosted teach workspace of
619
+ # a hybrid project; tests/test_visible_layout_lint.py fails when the scaffold differs.
620
+ HYBRID_TEACH_ENTRIES = TEACH_OWNED_DIRS | {"index.md"}
621
+ AGENT_EXTRAS_ROLE = "agent-extras"
622
+ TEACH_WORKSPACE_ROLE = "teach-workspace"
623
+
624
+
625
+ def agent_extras(agents_text: str) -> set[str]:
626
+ """Entry names a project declares in its optional agent-extras row.
627
+
628
+ Read from the raw Path cell, because the shared parser keeps only the first
629
+ backticked path and this cell lists several, comma-separated.
630
+ """
631
+ match = re.search(r"^\|\s*" + re.escape(AGENT_EXTRAS_ROLE) + r"\s*\|([^|\n]*)\|", agents_text, re.M)
632
+ if not match:
633
+ return set()
634
+ names = set()
635
+ for item in match.group(1).split(","):
636
+ item = item.strip().strip("`").strip().removeprefix("./").removeprefix(".bc-agent/").strip("/")
637
+ if item:
638
+ names.add(item.split("/", 1)[0])
639
+ return names
640
+
641
+
642
+ def agent_mechanics_findings(project: Path, table: dict[str, str], agents_text: str) -> list[dict]:
643
+ """Errors for entries directly under `.bc-agent/` that are not agent mechanics.
644
+
645
+ Hidden entries are skipped (`.gitkeep`, `.DS_Store`), except `.obsidian/`: the
646
+ Obsidian settings are retired in this layout, so a leftover one is reported.
647
+ """
648
+ vault = project / ".bc-agent"
649
+ allowed = AGENT_MECHANICS_ENTRIES | agent_extras(agents_text)
650
+ if table.get(TEACH_WORKSPACE_ROLE):
651
+ allowed |= HYBRID_TEACH_ENTRIES
652
+ found = []
653
+ for entry in sorted(vault.iterdir()) if vault.is_dir() else []:
654
+ if entry.name in allowed or (entry.name.startswith(".") and entry.name != ".obsidian"):
655
+ continue
656
+ found.append(finding("error", "agent-mechanics", entry, project,
657
+ "not agent mechanics: project knowledge lives at the table's role paths; "
658
+ "`.bc-agent/` holds agent mechanics only.",
659
+ "move it to the role path in the Where things go table (for example the research "
660
+ "folder), delete it, or list it in an agent-extras row if a tool reads it there"))
661
+ return found
662
+
663
+
664
+ SKIP_DIR_NAMES = {".git", ".obsidian", "scratch", "temp", "node_modules", "vendor"}
665
+
666
+ def maintenance_report(path: Path, vault: Path) -> bool:
667
+ item = path.relative_to(vault)
668
+ return len(item.parts) >= 2 and item.parts[0] == "_meta" and item.name.startswith(("lint-", "health-check-", "semantic-consolidation-"))
669
+
670
+ def ignored_path(path: Path, vault: Path) -> bool:
671
+ return any(part in SKIP_DIR_NAMES for part in path.relative_to(vault).parts)
672
+
673
+ def lint(
674
+ vault: Path,
675
+ stale_days: int,
676
+ *,
677
+ qmd_registry: Path | None = None,
678
+ qmd_machine_index: Path | None = None,
679
+ ) -> dict:
680
+ pages_list = sorted(
681
+ path
682
+ for path in (item.resolve() for item in vault.rglob("*.md"))
683
+ if path.is_relative_to(vault) and not ignored_path(path, vault)
684
+ )
685
+ pages = {key(path.relative_to(vault)): path for path in pages_list}
686
+ stems: dict[str, list[Path]] = {}
687
+ for path in pages_list:
688
+ stems.setdefault(path.stem, []).append(path)
689
+ incoming, broken, ambiguous = dict.fromkeys(pages_list, 0), [], []
690
+ for path in pages_list:
691
+ # log.md is append-only evidence, not a graph source; its links may be historical or cross-vault.
692
+ if path.name == "log.md":
693
+ continue
694
+ # Templates hold example links on purpose; do not fail the vault on them.
695
+ if "templates" in path.relative_to(vault).parts:
696
+ continue
697
+ for target, display in links(text(path)):
698
+ resolution = resolve_link(path, target, vault, pages, stems)
699
+ if resolution is None:
700
+ continue
701
+ candidates, local = resolution
702
+ if len(candidates) == 1:
703
+ incoming[candidates[0]] += 1
704
+ elif len(candidates) > 1:
705
+ ambiguous.append({"page": rel(path, vault), "link": display, "candidates": [rel(item, vault) for item in candidates]})
706
+ elif not local:
707
+ broken.append({"page": rel(path, vault), "link": display})
708
+ table = layout_table(vault)
709
+ index_text, index_path = text(vault / "index.md"), (vault / "index.md").resolve()
710
+ # A visible-layout project has no vault catalog; only a hosted teach workspace
711
+ # keeps an index.md, and it catalogs teach's own folders, not agent mechanics.
712
+ index_scope = [
713
+ path for path in pages_list
714
+ if table is None or (index_path.exists() and path.relative_to(vault).parts[0] in TEACH_OWNED_DIRS)
715
+ ]
716
+ missing = [rel(path, vault) for path in index_scope if path != index_path and not maintenance_report(path, vault) and rel(path, vault) not in index_text and path.stem not in index_text]
717
+ orphans = [rel(path, vault) for path, count in incoming.items() if count == 0 and path.name not in {"index.md", "log.md"} and "templates" not in path.parts and not maintenance_report(path, vault)]
718
+
719
+ stale, unknown, active, repo = [], [], vault / "tasks" / "active.md", git_root(vault)
720
+ if table is None and active.exists():
721
+ referenced = set()
722
+ for target, _display in links(text(active)):
723
+ resolution = resolve_link(active.resolve(), target, vault, pages, stems)
724
+ if resolution and len(resolution[0]) == 1:
725
+ referenced.add(resolution[0][0])
726
+ today = dt.date.today()
727
+ for path in sorted(referenced):
728
+ committed, reason = git_date(repo, path)
729
+ if committed is None:
730
+ unknown.append({"page": rel(path, vault), "reason": reason})
731
+ continue
732
+ age = (today - dt.date.fromisoformat(committed)).days
733
+ if age > stale_days:
734
+ stale.append({"page": rel(path, vault), "last_modified": committed, "age_days": age})
735
+ return {"vault": str(vault), "layout": "vault" if table is None else "visible",
736
+ "work_findings": [] if table is None else work_findings(vault.parent, table, text(vault / "AGENTS.md")),
737
+ "pages": len(pages_list), "broken_links": broken, "ambiguous_links": ambiguous,
738
+ "orphans": orphans, "missing_index": missing, "stale_active_references": stale,
739
+ "unknown_active_references": unknown, "stale_days": stale_days,
740
+ # Promotion moved log entries into vault pages; in the visible layout agents write to
741
+ # the role folders directly and log.md is a plain journal, so there is nothing to promote.
742
+ "unpromoted_log": promotion_status(vault, repo) if table is None else None,
743
+ "qmd": qmd_status(vault, registry=qmd_registry, machine_index=qmd_machine_index) if table is None
744
+ else visible_qmd_status(vault, table,
745
+ qmd_registry or Path.home() / "Sync" / "Scripts" / "config" / "qmd-collections.yml",
746
+ qmd_machine_index or Path.home() / ".config" / "qmd" / "index.yml"),
747
+ }
748
+
749
+ CLASSIFY_VERDICTS = {"promote", "skip", "conflict"}
750
+
751
+
752
+ def verify_classification(path: Path, promotion: dict) -> tuple[list[str], list[dict]]:
753
+ """Return errors and rows for FILE against every unpromoted heading, exactly once."""
754
+ if promotion["count"] is None:
755
+ note = promotion["note"] or "the unpromoted heading list could not be computed"
756
+ return ([f"cannot verify classification: {note}"], [])
757
+ headings = promotion["headings"]
758
+ if not path.is_file():
759
+ return ([f"classification file does not exist: {path}"], [])
760
+ errors: list[str] = []
761
+ seen: list[str] = []
762
+ rows: list[dict] = []
763
+ try:
764
+ raw = path.read_text(encoding="utf-8")
765
+ except OSError as exc:
766
+ return ([f"could not read classification file: {exc}"], [])
767
+ for lineno, line in enumerate(raw.splitlines(), 1):
768
+ line = line.strip()
769
+ if not line:
770
+ continue
771
+ try:
772
+ row = json.loads(line)
773
+ except json.JSONDecodeError as exc:
774
+ errors.append(f"line {lineno}: invalid JSON ({exc})")
775
+ continue
776
+ if not isinstance(row, dict):
777
+ errors.append(f"line {lineno}: expected a JSON object")
778
+ continue
779
+ heading = row.get("heading")
780
+ verdict = row.get("verdict")
781
+ reason = row.get("reason")
782
+ page = row.get("page")
783
+ if not isinstance(heading, str) or not heading.strip():
784
+ errors.append(f"line {lineno}: heading must be a non-empty string")
785
+ heading = None
786
+ if verdict not in CLASSIFY_VERDICTS:
787
+ errors.append(f"line {lineno}: verdict must be promote, skip, or conflict")
788
+ if not isinstance(reason, str) or not reason.strip():
789
+ errors.append(f"line {lineno}: reason must be a non-empty string")
790
+ if verdict in {"promote", "conflict"} and (not isinstance(page, str) or not page.strip()):
791
+ errors.append(f"line {lineno}: page is required for {verdict}")
792
+ if heading is not None:
793
+ seen.append(heading)
794
+ rows.append({"heading": heading, "verdict": verdict, "reason": reason, "page": page})
795
+ expected = Counter(headings)
796
+ found = Counter(seen)
797
+ if expected != found:
798
+ missing = list((expected - found).elements())
799
+ extra = list((found - expected).elements())
800
+ if missing:
801
+ errors.append("missing headings:")
802
+ errors.extend(f"- {item}" for item in missing)
803
+ if extra:
804
+ errors.append("unexpected headings:")
805
+ errors.extend(f"- {item}" for item in extra)
806
+ return errors, rows
807
+
808
+
809
+ def classification_summary(rows: list[dict]) -> str:
810
+ """Render verdicts for the promotion commit body, so skip reasons outlive the temp file."""
811
+ counts = Counter(row["verdict"] for row in rows)
812
+ header = "Classification: " + ", ".join(
813
+ f"{counts[verdict]} {verdict}" for verdict in sorted(CLASSIFY_VERDICTS)
814
+ )
815
+ lines = [header, ""]
816
+ for row in rows:
817
+ flat = {key: " ".join(str(value).split()) for key, value in row.items() if value is not None}
818
+ target = f" -> {flat['page']}" if flat.get("page") else ""
819
+ lines.append(f"{flat['verdict']} {flat['heading']}{target}: {flat['reason']}")
820
+ return "\n".join(lines)
821
+
822
+
823
+ def print_report(report: dict) -> None:
824
+ print("# Wiki lint report")
825
+ visible = report["layout"] == "visible"
826
+ print(f"Vault: {report['vault']}\nLayout: {report['layout']}\nPages: {report['pages']}")
827
+ checks = [("broken_links", "Broken links"), ("ambiguous_links", "Ambiguous links"), ("orphans", "Orphan pages")]
828
+ if not visible or (Path(report["vault"]) / "index.md").exists():
829
+ checks.append(("missing_index", "Possibly missing from index" if not visible else "Teach pages possibly missing from index"))
830
+ for name, label in checks:
831
+ entries = report[name]
832
+ print(f"{label}: {len(entries)}")
833
+ for entry in entries:
834
+ if isinstance(entry, str):
835
+ print(f"- {entry}")
836
+ elif name == "ambiguous_links":
837
+ print(f"- {entry['page']} -> {entry['link']} could be {', '.join(entry['candidates'])}")
838
+ else:
839
+ print(f"- {entry['page']} -> {entry['link']}")
840
+ if visible:
841
+ for severity, label in (("error", "Work-folder errors"), ("warning", "Work-folder warnings")):
842
+ entries = [entry for entry in report["work_findings"] if entry["severity"] == severity]
843
+ print(f"{label}: {len(entries)}")
844
+ for entry in entries:
845
+ print(f"- {entry['path']} — {entry['problem']} Fix: {entry['fix']}")
846
+ else:
847
+ stale = report["stale_active_references"]
848
+ print(f"Stale pages referenced from tasks/active.md (>{report['stale_days']} days): {len(stale)}")
849
+ for entry in stale:
850
+ print(f"- {entry['page']} — {entry['last_modified']} ({entry['age_days']} days)")
851
+ unknown = report["unknown_active_references"]
852
+ print(f"Unknown active references: {len(unknown)}")
853
+ for entry in unknown:
854
+ print(f"- {entry['page']} — {entry['reason']}")
855
+ promotion = report["unpromoted_log"]
856
+ if promotion is None:
857
+ print(f"Promotion: {PROMOTION_NOT_APPLICABLE}")
858
+ else:
859
+ print_promotion(promotion)
860
+ qmd = report["qmd"]
861
+ status = (
862
+ "registered"
863
+ if qmd["registered"]
864
+ else "unindexed"
865
+ if qmd["unindexed"]
866
+ else "intentional exclusion"
867
+ if qmd["intentional_exclusion"]
868
+ else "unregistered"
869
+ )
870
+ print(f"qmd registration: {status}")
871
+ if qmd["reason"]:
872
+ print(f"- {qmd['reason']}")
873
+ if promotion is None:
874
+ return
875
+ # Machine-readable contract consumed by runner/run-promotion.sh. Fails closed:
876
+ # an unknown count means git could not answer, so do not license an unattended write.
877
+ required = 1 if promotion["count"] is None or promotion["count"] > 0 else 0
878
+ promotion_range = promotion["range"] if promotion["range"] else "invalid" if required else "none"
879
+ print(f"PROMOTION_REQUIRED={required}")
880
+ print(f"PROMOTION_RANGE={promotion_range}")
881
+ for heading in promotion.get("headings") or []:
882
+ print(f"PROMOTION_HEADING\t{heading}")
883
+
884
+
885
+ PROMOTION_NOT_APPLICABLE = (
886
+ "not applicable (visible layout: agents write decisions and research to the table's role "
887
+ "folders, and log.md is a plain journal)"
888
+ )
889
+
890
+
891
+ def print_promotion(promotion: dict) -> None:
892
+ print(f"Unpromoted log entries: {promotion['count'] if promotion['count'] is not None else 'unknown'}")
893
+ if promotion["last_promotion"]:
894
+ print(f"- Last promotion: {promotion['last_promotion']['date']} {promotion['last_promotion']['subject']}")
895
+ if promotion["note"]:
896
+ print(f"- {promotion['note']}")
897
+ for heading in promotion.get("headings") or []:
898
+ print(f"- {heading}")
899
+ undatable = promotion.get("undatable_headings") or []
900
+ if undatable:
901
+ print(f"Warning: undatable unpromoted log headings: {len(undatable)}")
902
+ for heading in undatable:
903
+ print(f"- {heading}")
904
+
905
+ def main() -> int:
906
+ parser = argparse.ArgumentParser(description="Read-only Markdown wiki lint")
907
+ parser.add_argument("vault_root", help="wiki/vault directory to inspect")
908
+ parser.add_argument("--stale-days", type=int, default=90, help="staleness threshold (default: 90)")
909
+ mode = parser.add_mutually_exclusive_group()
910
+ mode.add_argument("--json", action="store_true", help="emit machine-readable JSON")
911
+ mode.add_argument(
912
+ "--verify-classify",
913
+ metavar="FILE",
914
+ help="require FILE to classify every unpromoted heading (JSONL); print the verdict"
915
+ " summary on success, or errors and exit 1 on mismatch",
916
+ )
917
+ mode.add_argument(
918
+ "--qmd-entry",
919
+ metavar="SLUG",
920
+ help="print the qmd collections-file entries for a visible-layout project named SLUG",
921
+ )
922
+ args = parser.parse_args()
923
+ if args.stale_days < 0:
924
+ parser.error("--stale-days must be non-negative")
925
+ vault = Path(args.vault_root).expanduser().resolve()
926
+ if not vault.is_dir():
927
+ parser.error(f"vault root is not a directory: {vault}")
928
+ report = lint(vault, args.stale_days)
929
+ promotion = report["unpromoted_log"]
930
+ report["promotion_required"] = promotion is not None and (promotion["count"] is None or bool(promotion["count"]))
931
+ if args.qmd_entry:
932
+ table = layout_table(vault)
933
+ if table is None:
934
+ parser.error("--qmd-entry applies to a visible-layout project (a .bc-agent/ with a Where things go table)")
935
+ print(qmd_entry(vault, table, args.qmd_entry), end="")
936
+ return 0
937
+ if args.verify_classify and promotion is None:
938
+ print(f"bc-wiki-maintain: promotion is {PROMOTION_NOT_APPLICABLE}", file=sys.stderr)
939
+ return 1
940
+ if args.verify_classify:
941
+ errors, rows = verify_classification(Path(args.verify_classify).expanduser(), report["unpromoted_log"])
942
+ if errors:
943
+ print("bc-wiki-maintain: classification does not cover every unpromoted heading", file=sys.stderr)
944
+ for error in errors:
945
+ print(error, file=sys.stderr)
946
+ return 1
947
+ print(classification_summary(rows))
948
+ return 0
949
+ if args.json:
950
+ print(json.dumps(report, indent=2, sort_keys=True))
951
+ else:
952
+ print_report(report)
953
+ invalid_required_range = report["promotion_required"] and not promotion["range"]
954
+ work_errors = any(entry["severity"] == "error" for entry in report["work_findings"])
955
+ return 1 if report["broken_links"] or report["ambiguous_links"] or invalid_required_range or work_errors else 0
956
+
957
+ if __name__ == "__main__":
958
+ sys.exit(main())