infra(validator): phase 2 — precise line numbers in all diagnostics
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
Add _line_of(content, pos) helper that computes the 1-indexed line number
from a character position in any content string. Thread it through every
document check:
check_frontmatter
- Missing frontmatter → line 1
- Malformed frontmatter → line 1
- Missing type field → line 1
- Invalid type → exact line of the 'type:' field in the frontmatter block
check_links
- Broken relative link → exact line of the [text](url) span
check_code_fences
- Unclosed fence → line number of the last unpaired backtick delimiter
- Switch from counting fence strings to enumerating (line_no, line) pairs
check_mermaid
- Pair every raw block line with its file-level line number via
fence_line + 1 + i so each issue can report an exact location
- Structural issues (unbalanced subgraph, sequenceDiagram blocks)
anchor to the diagram header line
- Edge-label issues anchor to the exact line where the label appears
- Empty diagram block anchors to the first line after the fence
Update report() to render 'path:line message' prefixes via _location();
fall back to 'path message' when line is None, or bare message for
tool-level issues where path is also None.
Clean redundant path embedding from all error message strings — the
location is now structural data in Issue, not prose.
Smoke-tested: all six assertion cases pass with exact line numbers.
This commit is contained in:
1 parent
fd4bdb1c80
commit
70188228a0
1 file changed
+80
-39
+80
-39
@@ -81,7 +81,7 @@ class Document(NamedTuple):
|
|||||||
class Issue(NamedTuple):
|
class Issue(NamedTuple):
|
||||||
severity: Severity
|
severity: Severity
|
||||||
path: pathlib.Path | None
|
path: pathlib.Path | None
|
||||||
line: int | None # reserved for Phase 2 — always None in Phase 1
|
line: int | None
|
||||||
message: str
|
message: str
|
||||||
|
|
||||||
|
|
||||||
@@ -107,6 +107,13 @@ def discover_documents(root: pathlib.Path) -> list[Document]:
|
|||||||
return documents
|
return documents
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _line_of(content: str, pos: int) -> int:
|
||||||
|
"""Return the 1-indexed line number of character position `pos` in `content`."""
|
||||||
|
return content[:pos].count('\n') + 1
|
||||||
|
|
||||||
|
|
||||||
# ── Repository checks ──────────────────────────────────────────────────────────
|
# ── Repository checks ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def check_deprecated_dirs(root: pathlib.Path) -> list[Issue]:
|
def check_deprecated_dirs(root: pathlib.Path) -> list[Issue]:
|
||||||
@@ -132,21 +139,25 @@ def check_frontmatter(doc: Document) -> list[Issue]:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
content = doc.content
|
content = doc.content
|
||||||
|
|
||||||
if not content.startswith("---"):
|
if not content.startswith("---"):
|
||||||
return [Issue("error", doc.rel, None, f"Missing frontmatter: {doc.rel}")]
|
return [Issue("error", doc.rel, 1, "Missing frontmatter")]
|
||||||
|
|
||||||
end = content.find("\n---", 3)
|
end = content.find("\n---", 3)
|
||||||
if end == -1:
|
if end == -1:
|
||||||
return [Issue("error", doc.rel, None, f"Malformed frontmatter (no closing ---): {doc.rel}")]
|
return [Issue("error", doc.rel, 1, "Malformed frontmatter: no closing ---")]
|
||||||
|
|
||||||
fm_block = content[3:end]
|
fm_block = content[3:end]
|
||||||
type_match = re.search(r'^type:\s*(\S+)', fm_block, re.MULTILINE)
|
type_match = re.search(r'^type:\s*(\S+)', fm_block, re.MULTILINE)
|
||||||
if not type_match:
|
if not type_match:
|
||||||
return [Issue("error", doc.rel, None, f"Frontmatter missing 'type' field: {doc.rel}")]
|
return [Issue("error", doc.rel, 1, "Frontmatter missing 'type' field")]
|
||||||
|
|
||||||
|
# Position of 'type:' in the original content is 3 (the opening ---) + match start.
|
||||||
|
# _line_of gives us the exact line in the file.
|
||||||
|
type_line = _line_of(content, 3 + type_match.start())
|
||||||
doc_type = type_match.group(1)
|
doc_type = type_match.group(1)
|
||||||
if doc_type not in VALID_TYPES:
|
if doc_type not in VALID_TYPES:
|
||||||
return [Issue("error", doc.rel, None, f"Invalid type '{doc_type}': {doc.rel}")]
|
return [Issue("error", doc.rel, type_line, f"Invalid type '{doc_type}'")]
|
||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
@@ -162,66 +173,84 @@ def check_links(doc: Document) -> list[Issue]:
|
|||||||
continue
|
continue
|
||||||
resolved = (doc.path.parent / target).resolve()
|
resolved = (doc.path.parent / target).resolve()
|
||||||
if not resolved.exists():
|
if not resolved.exists():
|
||||||
issues.append(Issue("error", doc.rel, None, f"Broken link in {doc.rel}: {target}"))
|
issues.append(Issue(
|
||||||
|
"error", doc.rel, _line_of(doc.content, m.start()),
|
||||||
|
f"Broken relative link: {target}",
|
||||||
|
))
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
|
|
||||||
def check_code_fences(doc: Document) -> list[Issue]:
|
def check_code_fences(doc: Document) -> list[Issue]:
|
||||||
fences = [line for line in doc.content.splitlines() if line.strip().startswith("```")]
|
# Track (line_number, fence_text) pairs so we can report the last unpaired fence.
|
||||||
if len(fences) % 2 != 0:
|
fence_lines: list[int] = [
|
||||||
|
i
|
||||||
|
for i, line in enumerate(doc.content.splitlines(), 1)
|
||||||
|
if line.strip().startswith("```")
|
||||||
|
]
|
||||||
|
if len(fence_lines) % 2 != 0:
|
||||||
return [Issue(
|
return [Issue(
|
||||||
"error", doc.rel, None,
|
"error", doc.rel, fence_lines[-1],
|
||||||
f"Unclosed code fence in {doc.rel} (found {len(fences)} fence delimiters)",
|
f"Unclosed code fence (found {len(fence_lines)} fence delimiters)",
|
||||||
)]
|
)]
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
def check_mermaid(doc: Document) -> list[Issue]:
|
def check_mermaid(doc: Document) -> list[Issue]:
|
||||||
issues: list[Issue] = []
|
issues: list[Issue] = []
|
||||||
|
|
||||||
for m in re.finditer(r'```mermaid\s*\n(.*?)\n```', doc.content, re.DOTALL):
|
for m in re.finditer(r'```mermaid\s*\n(.*?)\n```', doc.content, re.DOTALL):
|
||||||
block = m.group(1).strip()
|
# Line of the opening ```mermaid fence in the file.
|
||||||
if not block:
|
fence_line = _line_of(doc.content, m.start())
|
||||||
issues.append(Issue("error", doc.rel, None, f"Empty Mermaid diagram block in {doc.rel}"))
|
|
||||||
continue
|
|
||||||
|
|
||||||
lines = [
|
# Pair each raw line with its file-level line number.
|
||||||
line.strip() for line in block.splitlines()
|
# m.group(1) starts on the line immediately after ```mermaid,
|
||||||
if line.strip() and not line.strip().startswith("%%")
|
# so raw_lines[i] lives at fence_line + 1 + i.
|
||||||
|
raw_lines = m.group(1).splitlines()
|
||||||
|
numbered: list[tuple[int, str]] = [
|
||||||
|
(fence_line + 1 + i, raw_line.strip())
|
||||||
|
for i, raw_line in enumerate(raw_lines)
|
||||||
|
if raw_line.strip() and not raw_line.strip().startswith("%%")
|
||||||
]
|
]
|
||||||
if not lines:
|
|
||||||
|
if not numbered:
|
||||||
|
issues.append(Issue("error", doc.rel, fence_line + 1, "Empty Mermaid diagram block"))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
header = lines[0].split()[0].lower()
|
first_line_no, first_line = numbered[0]
|
||||||
|
header = first_line.split()[0].lower()
|
||||||
|
|
||||||
if header not in MERMAID_TYPES:
|
if header not in MERMAID_TYPES:
|
||||||
issues.append(Issue(
|
issues.append(Issue(
|
||||||
"error", doc.rel, None,
|
"error", doc.rel, first_line_no,
|
||||||
f"Invalid Mermaid diagram type '{header}' in {doc.rel}",
|
f"Unknown Mermaid diagram type: '{header}'",
|
||||||
))
|
))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
content_lines = [line for _, line in numbered]
|
||||||
|
|
||||||
|
# Structural balance checks — anchored to the diagram header line.
|
||||||
if header in ("flowchart", "graph"):
|
if header in ("flowchart", "graph"):
|
||||||
subgraphs = sum(1 for line in lines if line.startswith("subgraph"))
|
subgraphs = sum(1 for line in content_lines if line.startswith("subgraph"))
|
||||||
ends = sum(1 for line in lines if line == "end" or line.startswith("end "))
|
ends = sum(1 for line in content_lines if line == "end" or line.startswith("end "))
|
||||||
if subgraphs != ends:
|
if subgraphs != ends:
|
||||||
issues.append(Issue(
|
issues.append(Issue(
|
||||||
"error", doc.rel, None,
|
"error", doc.rel, first_line_no,
|
||||||
f"Unbalanced subgraph in Mermaid diagram in {doc.rel} "
|
f"Unbalanced subgraph: {subgraphs} subgraph vs {ends} end",
|
||||||
f"({subgraphs} subgraph vs {ends} end)",
|
|
||||||
))
|
))
|
||||||
elif header == "sequencediagram":
|
elif header == "sequencediagram":
|
||||||
block_openers = sum(
|
block_openers = sum(
|
||||||
1 for line in lines
|
1 for line in content_lines
|
||||||
if re.match(r'^(alt|opt|loop|par|critical|break|rect)\b', line)
|
if re.match(r'^(alt|opt|loop|par|critical|break|rect)\b', line)
|
||||||
)
|
)
|
||||||
ends = sum(1 for line in lines if re.match(r'^end\b', line))
|
ends = sum(1 for line in content_lines if re.match(r'^end\b', line))
|
||||||
if block_openers != ends:
|
if block_openers != ends:
|
||||||
issues.append(Issue(
|
issues.append(Issue(
|
||||||
"error", doc.rel, None,
|
"error", doc.rel, first_line_no,
|
||||||
f"Unbalanced control blocks in Mermaid sequenceDiagram in {doc.rel} "
|
f"Unbalanced sequenceDiagram blocks: {block_openers} openers vs {ends} end",
|
||||||
f"({block_openers} block openers vs {ends} end)",
|
|
||||||
))
|
))
|
||||||
|
|
||||||
for line in lines:
|
# Edge-label syntax check — each issue anchored to its exact line.
|
||||||
|
for line_no, line in numbered:
|
||||||
for label_match in re.finditer(r'[-.=~<>]*\|([^|]+)\|', line):
|
for label_match in re.finditer(r'[-.=~<>]*\|([^|]+)\|', line):
|
||||||
label = label_match.group(1).strip()
|
label = label_match.group(1).strip()
|
||||||
if (
|
if (
|
||||||
@@ -229,10 +258,10 @@ def check_mermaid(doc: Document) -> list[Issue]:
|
|||||||
and not (label.startswith('"') and label.endswith('"'))
|
and not (label.startswith('"') and label.endswith('"'))
|
||||||
):
|
):
|
||||||
issues.append(Issue(
|
issues.append(Issue(
|
||||||
"error", doc.rel, None,
|
"error", doc.rel, line_no,
|
||||||
f"Unquoted special character in Mermaid edge label "
|
f"Unquoted special character in edge label '|{label}|' — wrap in \"...\"",
|
||||||
f"'|{label}|' in {doc.rel} (wrap in \"...\")",
|
|
||||||
))
|
))
|
||||||
|
|
||||||
return issues
|
return issues
|
||||||
|
|
||||||
|
|
||||||
@@ -263,11 +292,21 @@ def run_pyright(root: pathlib.Path) -> list[Issue]:
|
|||||||
|
|
||||||
# ── Reporting ──────────────────────────────────────────────────────────────────
|
# ── Reporting ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _location(issue: Issue) -> str:
|
||||||
|
"""Format a path:line location prefix for an issue."""
|
||||||
|
if issue.path is None:
|
||||||
|
return ""
|
||||||
|
loc = str(issue.path)
|
||||||
|
if issue.line is not None:
|
||||||
|
loc = f"{loc}:{issue.line}"
|
||||||
|
return loc
|
||||||
|
|
||||||
|
|
||||||
def report(issues: list[Issue]) -> None:
|
def report(issues: list[Issue]) -> None:
|
||||||
"""Render collected issues to stdout.
|
"""Render collected issues to stdout.
|
||||||
|
|
||||||
The renderer is deliberately separated from the checks so that the output
|
The renderer is separated from validation logic so the output format
|
||||||
format can evolve (e.g. --format json) without touching validation logic.
|
can evolve (e.g. --format json) without touching any check function.
|
||||||
"""
|
"""
|
||||||
errors = [i for i in issues if i.severity == "error"]
|
errors = [i for i in issues if i.severity == "error"]
|
||||||
warnings = [i for i in issues if i.severity == "warning"]
|
warnings = [i for i in issues if i.severity == "warning"]
|
||||||
@@ -275,12 +314,14 @@ def report(issues: list[Issue]) -> None:
|
|||||||
if warnings:
|
if warnings:
|
||||||
print(f"\n⚠️ {len(warnings)} warning(s):\n")
|
print(f"\n⚠️ {len(warnings)} warning(s):\n")
|
||||||
for issue in warnings:
|
for issue in warnings:
|
||||||
print(f" ⚠ {issue.message}")
|
loc = _location(issue)
|
||||||
|
print(f" ⚠ {loc + ' ' if loc else ''}{issue.message}")
|
||||||
|
|
||||||
if errors:
|
if errors:
|
||||||
print(f"\n❌ Validation failed — {len(errors)} error(s):\n")
|
print(f"\n❌ Validation failed — {len(errors)} error(s):\n")
|
||||||
for issue in errors:
|
for issue in errors:
|
||||||
print(f" ✗ {issue.message}")
|
loc = _location(issue)
|
||||||
|
print(f" ✗ {loc + ' ' if loc else ''}{issue.message}")
|
||||||
else:
|
else:
|
||||||
print("\n✅ All checks passed. Brain structure is valid.")
|
print("\n✅ All checks passed. Brain structure is valid.")
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user