amark 0.1.0__py3-none-any.whl

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.
amark/__init__.py ADDED
@@ -0,0 +1,768 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from html.parser import HTMLParser
5
+ from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
6
+ import fnmatch
7
+ import json
8
+ import os
9
+ import re
10
+ import stat
11
+
12
+ try:
13
+ import yaml
14
+ from yaml.events import AliasEvent
15
+ except ImportError: # pragma: no cover
16
+ yaml = None
17
+ AliasEvent = None
18
+
19
+ # Files larger than this are skipped during discovery (spec Section 10, resource bounds).
20
+ # AMARK metadata lives in small front-matter blocks or a one-line marker; this only
21
+ # excludes pathologically large files.
22
+ MAX_FILE_BYTES = 5_000_000
23
+
24
+ # Version-control storage directories are never descended into (spec Section 8.1):
25
+ # they hold the repository's history, not the files the corpus is made of.
26
+ VCS_DIRS = frozenset({".git", ".hg", ".svn", "_darcs"})
27
+
28
+ # Comment syntax per host language (spec Section 6.4: the identity marker is only
29
+ # a declaration when it sits inside a comment *in the host language*). Entries are
30
+ # (extensions, line-comment leaders, block-comment delimiters). A "#" inside an
31
+ # HTML text node is not a comment, which is why this is keyed by extension rather
32
+ # than matched against one permissive set.
33
+ COMMENT_SYNTAX: Tuple[Tuple[frozenset, Tuple[str, ...], Tuple[Tuple[str, str], ...]], ...] = (
34
+ (frozenset({".html", ".htm", ".xml", ".svg", ".xhtml", ".vue", ".xsl"}),
35
+ (), (("<!--", "-->"),)),
36
+ # .yml/.yaml reach the marker binding only when the file carries no top-level
37
+ # amark- keys - the infrastructure case the spec calls out in Section 6.3.
38
+ (frozenset({".py", ".rb", ".sh", ".bash", ".zsh", ".ps1", ".pl", ".r", ".tf",
39
+ ".tfvars", ".toml", ".ini", ".cfg", ".mk", ".nix", ".ex", ".exs",
40
+ ".yml", ".yaml", ".dockerfile", ".gitconfig", ".conf", ".properties"}),
41
+ ("#",), ()),
42
+ (frozenset({".c", ".h", ".cpp", ".hpp", ".cc", ".cs", ".java", ".js", ".mjs",
43
+ ".cjs", ".ts", ".tsx", ".jsx", ".go", ".rs", ".swift", ".kt", ".kts",
44
+ ".scala", ".dart", ".bicep", ".proto", ".gradle", ".groovy", ".zig"}),
45
+ ("//",), (("/*", "*/"),)),
46
+ (frozenset({".css", ".scss", ".less"}), ("//",), (("/*", "*/"),)),
47
+ (frozenset({".php"}), ("//", "#"), (("/*", "*/"),)),
48
+ (frozenset({".sql", ".lua", ".hs", ".elm", ".adb", ".ads"}), ("--",), (("/*", "*/"),)),
49
+ (frozenset({".lisp", ".clj", ".cljs", ".el", ".scm", ".asm", ".s"}), (";",), ()),
50
+ (frozenset({".erl", ".tex", ".mat"}), ("%",), ()),
51
+ (frozenset({".vb", ".vbs", ".bas"}), ("'",), ()),
52
+ )
53
+
54
+ # For an extension with no entry above, accept the leaders shared by most
55
+ # languages rather than refusing the marker outright - an unknown extension
56
+ # should not silently lose an artifact.
57
+ DEFAULT_LINE_LEADERS: Tuple[str, ...] = ("#", "//", "--", ";")
58
+ DEFAULT_BLOCK_DELIMITERS: Tuple[Tuple[str, str], ...] = (("/*", "*/"), ("<!--", "-->"))
59
+
60
+ if yaml is not None:
61
+
62
+ class _SafeNoAliasLoader(yaml.SafeLoader):
63
+ """SafeLoader that also rejects YAML aliases.
64
+
65
+ `yaml.safe_load` prevents code execution, but still expands anchors/aliases,
66
+ which lets a tiny crafted file blow up exponentially in memory (the
67
+ "billion laughs" DoS). AMARK metadata never needs aliases, so we forbid them
68
+ when parsing untrusted repository content.
69
+ """
70
+
71
+ def compose_node(self, parent, index): # type: ignore[override]
72
+ if self.check_event(AliasEvent):
73
+ raise yaml.YAMLError("YAML aliases are not permitted in AMARK metadata")
74
+ return super().compose_node(parent, index)
75
+
76
+ def construct_yaml_int(self, node): # type: ignore[override]
77
+ # YAML 1.2: `017` is decimal and octal is written `0o17`.
78
+ value = self.construct_scalar(node)
79
+ if value[:2] in ("0o", "0x"):
80
+ return int(value[2:], 8 if value[1] == "o" else 16)
81
+ return int(value)
82
+
83
+ # PyYAML implements YAML 1.1, where `NO`, `on` and `2026-01-05` are not
84
+ # strings. The spec cites YAML 1.2 (Section 6.2), so plain scalars resolve
85
+ # by the 1.2 core schema instead; everything else stays a string.
86
+ _SafeNoAliasLoader.yaml_implicit_resolvers = {}
87
+ for _tag, _pattern, _first in (
88
+ ("bool", r"^(?:true|True|TRUE|false|False|FALSE)$", "tTfF"),
89
+ ("int", r"^(?:[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$", "-+0123456789"),
90
+ ("float", r"^(?:[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?"
91
+ r"|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$", "-+.0123456789"),
92
+ ("null", r"^(?:~|null|Null|NULL|)$", ["~", "n", "N", ""]),
93
+ ):
94
+ _SafeNoAliasLoader.add_implicit_resolver(
95
+ f"tag:yaml.org,2002:{_tag}", re.compile(_pattern), list(_first))
96
+ _SafeNoAliasLoader.add_constructor(
97
+ "tag:yaml.org,2002:int", _SafeNoAliasLoader.construct_yaml_int)
98
+ del _tag, _pattern, _first
99
+
100
+ def _load_yaml(text: str) -> Any:
101
+ return yaml.load(text, Loader=_SafeNoAliasLoader)
102
+
103
+ def _load_yaml_all(text: str) -> List[Any]:
104
+ """All documents of a multi-document YAML stream (same safe loader)."""
105
+ return list(yaml.load_all(text, Loader=_SafeNoAliasLoader))
106
+
107
+ else: # pragma: no cover
108
+
109
+ def _load_yaml(text: str) -> Any:
110
+ return None
111
+
112
+ def _load_yaml_all(text: str) -> List[Any]:
113
+ return []
114
+
115
+
116
+ # Spec Section 5.5: the separator is WSP (space/tab), never a line break, and the
117
+ # id is the grammar below - so a trailing "-->" is not swallowed into the id.
118
+ AMARK_ID_PATTERN = re.compile(
119
+ r"\bamark:id(?:[ \t]*=[ \t]*|[ \t]+)([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)(?![A-Za-z0-9_.-])",
120
+ re.IGNORECASE)
121
+
122
+ # Id grammar (spec section 5.2): US-ASCII alphanumeric segments joined by
123
+ # single hyphens; no leading/trailing/double hyphen.
124
+ ID_GRAMMAR = re.compile(r"^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$")
125
+
126
+ # Name grammar (spec Section 5.3), applied to the canonical (lower-cased) form. A
127
+ # registered name is `lc-start *( lc / DIGIT / "_" )`; a private name is the `x-`
128
+ # prefix or a reverse-DNS namespace followed by `1*( lc / DIGIT / "_" / "-" )`.
129
+ NAME_GRAMMAR = re.compile(r"^[a-z][a-z0-9_]*$")
130
+ PRIVATE_NAME_GRAMMAR = re.compile(
131
+ r"^(?:x-|[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*\.)[a-z0-9_-]+$"
132
+ )
133
+
134
+ # US-ASCII case folding only (spec section 7): never Unicode/locale case mapping.
135
+ _ASCII_UPPER = str.maketrans("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
136
+ _ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
137
+
138
+ # Registered value spaces (spec Appendix A and B). Custom values must be
139
+ # namespaced (spec section 9.3); these occupy the un-namespaced space.
140
+ REGISTERED_KINDS = {
141
+ # Software / runtime
142
+ "system", "component", "backend", "frontend", "api", "database", "storage",
143
+ "queue", "library", "pipeline", "test", "external", "resource",
144
+ # Documentation / logical / general architecture (tech-agnostic)
145
+ "document", "decision", "requirement", "capability", "event", "person",
146
+ }
147
+ REGISTERED_RELATIONSHIPS = {
148
+ "depends_on", "contains", "exposes", "consumes", "calls", "called_by",
149
+ "implements", "implemented_by", "persists_to", "reads_from", "writes_to",
150
+ "publishes_to", "subscribes_to", "reads_secrets_from", "integrates_with",
151
+ "documents",
152
+ }
153
+ # Registered lifecycle values (spec section 3.9). `production` is an alias of
154
+ # `active`, kept for Backstage compatibility.
155
+ REGISTERED_LIFECYCLES = {
156
+ "planned", "experimental", "active", "production", "deprecated", "retired",
157
+ }
158
+
159
+
160
+ def normalize_id(value: Any) -> str:
161
+ """Canonical form of an id: case-insensitive, stored upper-case (ASCII only).
162
+
163
+ Applied to every artifact id and every link target so that `be-orders`,
164
+ `BE-Orders` and `BE-ORDERS` are one and the same artifact everywhere.
165
+ """
166
+ if not value:
167
+ return ""
168
+ return str(value).strip().translate(_ASCII_UPPER)
169
+
170
+
171
+ def normalize_name(value: Any) -> str:
172
+ """Canonical form of a kind or relationship name: lower-case (ASCII only)."""
173
+ if not value:
174
+ return ""
175
+ return str(value).strip().translate(_ASCII_LOWER)
176
+
177
+
178
+ def is_namespaced_name(name: str) -> bool:
179
+ """True if a kind/relationship name is a well-formed private name (spec Section 5.3/Section 9.3):
180
+ the experimental `x-` prefix or a reverse-DNS namespace. Matched against the
181
+ canonical (lower-cased) form, so a malformed name (`foo.`, `.bar`, `9x.y`) is
182
+ not treated as namespaced and is surfaced as a producer-conformance warning."""
183
+ return bool(PRIVATE_NAME_GRAMMAR.match(name))
184
+
185
+
186
+ IGNORE_FILE = ".amarkignore"
187
+
188
+
189
+ def _resolves_inside(path: Path, root: Path) -> bool:
190
+ """True if `path`, with links and junctions resolved, lies inside `root`."""
191
+ try:
192
+ path.resolve().relative_to(root)
193
+ except (OSError, ValueError):
194
+ return False
195
+ return True
196
+
197
+
198
+ def load_ignore_patterns(root: Path) -> List[str]:
199
+ """Patterns from the scanned tree's ``.amarkignore`` (spec Section 8.1.1).
200
+
201
+ A repository may hold marked-up files that are not part of its own
202
+ architecture - fixtures, generated example repositories, vendored code,
203
+ documentation demonstrating the format. Excluding them is a property of the
204
+ scan, so the file is read from the scan root and nowhere else.
205
+ """
206
+ try:
207
+ path = root / IGNORE_FILE
208
+ if path.is_symlink():
209
+ raise ValueError(f"{path} must not be a symbolic link")
210
+ info = path.stat()
211
+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_FILE_BYTES:
212
+ raise ValueError(f"{path} must be a regular file smaller than {MAX_FILE_BYTES} bytes")
213
+ lines = path.read_text(encoding="utf-8-sig").splitlines()
214
+ except FileNotFoundError:
215
+ return []
216
+ return [
217
+ stripped
218
+ for stripped in (line.strip() for line in lines)
219
+ if stripped and not stripped.startswith("#")
220
+ ]
221
+
222
+
223
+ def is_ignored(relative_posix: str, patterns: Iterable[str]) -> bool:
224
+ """True if a root-relative POSIX path matches an exclusion pattern.
225
+
226
+ ``fnmatch``'s ``*`` spans separators, so ``samples/`` matching
227
+ ``samples/orders/README.md`` needs only the directory-contents form.
228
+ """
229
+ for pattern in patterns:
230
+ trimmed = pattern.rstrip("/").lstrip("/")
231
+ if not trimmed:
232
+ continue
233
+ if fnmatch.fnmatchcase(relative_posix, trimmed) or fnmatch.fnmatchcase(
234
+ relative_posix, trimmed + "/*"
235
+ ):
236
+ return True
237
+ return False
238
+
239
+
240
+ def parse_markdown_front_matter(text: str) -> Optional[Dict[str, Any]]:
241
+ """Return the YAML front-matter mapping, or None.
242
+
243
+ The block starts on the first line (a line that is exactly ``---``) and ends on
244
+ the next such line. The closing delimiter may be terminated by EOF rather than a
245
+ newline (spec section 6.2).
246
+ """
247
+ if yaml is None:
248
+ return None
249
+
250
+ lines = text.splitlines()
251
+ if not lines or lines[0] != "---":
252
+ return None
253
+
254
+ for index in range(1, len(lines)):
255
+ if lines[index] == "---":
256
+ block = "\n".join(lines[1:index])
257
+ try:
258
+ metadata = _load_yaml(block) or {}
259
+ except Exception:
260
+ return None # malformed YAML or a rejected alias -> no metadata
261
+ return metadata if isinstance(metadata, dict) else None
262
+
263
+ return None
264
+
265
+
266
+ # Core artifact keys; every other `amark-` key is a custom attribute (spec 3.6).
267
+ CORE_KEYS = {"amark-id", "amark-kind", "amark-links"}
268
+
269
+
270
+ def _leaders_for(suffix: str) -> Tuple[Tuple[str, ...], Tuple[Tuple[str, str], ...]]:
271
+ """Line-comment leaders and block-comment delimiters for a file extension."""
272
+ for extensions, line, block in COMMENT_SYNTAX:
273
+ if suffix in extensions:
274
+ return line, block
275
+ return DEFAULT_LINE_LEADERS, DEFAULT_BLOCK_DELIMITERS
276
+
277
+
278
+ def _comment_texts(text: str, suffix: str) -> Iterator[str]:
279
+ """Walk comments in order, skipping quoted strings across line boundaries.
280
+
281
+ This is a small lexer for the supported comment conventions, not a parser
282
+ for every language. Triple quotes and backticks prevent common multiline
283
+ examples from becoming false identity declarations.
284
+ """
285
+ leaders, blocks = _leaders_for(suffix)
286
+ if not leaders and blocks == (("<!--", "-->"),):
287
+ # Apostrophes in HTML text are not string delimiters. The standard
288
+ # tokenizer also keeps comment-looking text inside attributes inert.
289
+ class Comments(HTMLParser):
290
+ def handle_comment(self, data):
291
+ comments.append(data)
292
+ comments: List[str] = []
293
+ parser = Comments()
294
+ parser.feed(text)
295
+ parser.close()
296
+ yield from comments
297
+ return
298
+ index = 0
299
+ while index < len(text):
300
+ leader = next((value for value in leaders if text.startswith(value, index)), None)
301
+ if leader:
302
+ end = text.find("\n", index)
303
+ if end == -1:
304
+ end = len(text)
305
+ yield text[index + len(leader):end]
306
+ index = end
307
+ continue
308
+ block = next((pair for pair in blocks if text.startswith(pair[0], index)), None)
309
+ if block:
310
+ opener, closer = block
311
+ start = index + len(opener)
312
+ end = text.find(closer, start)
313
+ if end == -1:
314
+ end = len(text)
315
+ yield text[start:end]
316
+ index = end + len(closer)
317
+ continue
318
+ char = text[index]
319
+ if char in ("'", '"', "`"):
320
+ quote = char * 3 if text.startswith(char * 3, index) else char
321
+ # A single ' or " string ends at the line break: an apostrophe in
322
+ # prose (YAML `it's`), a Rust lifetime or a Lisp quote is not a
323
+ # string, and must not hide every later comment.
324
+ one_line = quote in ("'", '"')
325
+ index += len(quote)
326
+ while index < len(text):
327
+ if text[index] == "\\":
328
+ index += 2
329
+ elif text.startswith(quote, index):
330
+ index += len(quote)
331
+ break
332
+ elif one_line and text[index] == "\n":
333
+ break
334
+ else:
335
+ index += 1
336
+ continue
337
+ index += 1
338
+
339
+
340
+ def parse_source_identity(text: str, suffix: str = "") -> Optional[Dict[str, Any]]:
341
+ """Extract the first identity marker inside a host-language comment (6.4)."""
342
+ if "amark:id" not in text.lower():
343
+ return None
344
+ for comment in _comment_texts(text, suffix.lower()):
345
+ match = AMARK_ID_PATTERN.search(comment)
346
+ if match:
347
+ return {"id": match.group(1), "kind": "", "links": [], "attributes": {}}
348
+ return None
349
+
350
+
351
+ def amark_fields(mapping: Any) -> Optional[Dict[str, Any]]:
352
+ """Extract an AMARK artifact from a mapping's ``amark-`` prefixed keys.
353
+
354
+ The ``amark-`` prefix keeps AMARK metadata from colliding with a file's own
355
+ top-level keys (for example a static-site generator's ``id`` or a Kubernetes
356
+ ``kind:``). Every ``amark-`` key that is not `id`/`kind`/`links` is preserved as
357
+ a custom attribute (with the prefix stripped), so plugins and organizations can
358
+ extend AMARK without a spec change. Returns None if the mapping carries no AMARK
359
+ metadata.
360
+ """
361
+ if not isinstance(mapping, dict):
362
+ return None
363
+ if "amark-id" not in mapping and "amark-kind" not in mapping:
364
+ return None
365
+ attributes = {
366
+ key[len("amark-"):]: value
367
+ for key, value in mapping.items()
368
+ if isinstance(key, str) and key.startswith("amark-") and key not in CORE_KEYS
369
+ }
370
+ return {
371
+ "id": mapping.get("amark-id", ""),
372
+ "kind": mapping.get("amark-kind", ""),
373
+ "links": [] if mapping.get("amark-links") is None else mapping["amark-links"],
374
+ "attributes": attributes,
375
+ }
376
+
377
+
378
+ def parse_yaml_identity(text: str) -> Optional[Dict[str, Any]]:
379
+ """Read the AMARK artifact from a YAML document's top-level ``amark-`` keys."""
380
+ if yaml is None:
381
+ return None
382
+
383
+ try:
384
+ metadata = _load_yaml(text)
385
+ except Exception:
386
+ return None
387
+ return amark_fields(metadata)
388
+
389
+
390
+ def parse_json_identity(text: str) -> Optional[Dict[str, Any]]:
391
+ """Read the AMARK artifact from a JSON object's top-level ``amark-`` keys.
392
+
393
+ The JSON binding (spec section 6.5) mirrors the YAML one, for comment-less
394
+ host formats (CloudFormation/ARM JSON templates, package manifests). A file
395
+ that is not a JSON object, or carries no ``amark-`` keys, has no metadata;
396
+ there is no marker fallback because JSON has no comments.
397
+ """
398
+ try:
399
+ metadata = json.loads(text)
400
+ except (ValueError, RecursionError):
401
+ return None
402
+ return amark_fields(metadata)
403
+
404
+
405
+ def scan_repository(
406
+ root: Path | str,
407
+ diagnostics: Optional[List[str]] = None,
408
+ include_generated: bool = False,
409
+ ) -> List[Dict[str, Any]]:
410
+ """Scan a directory tree and return the artifacts it declares.
411
+
412
+ When ``diagnostics`` is a list, human-readable notes are appended for files
413
+ that were skipped (unreadable, oversized, not UTF-8) or that look like they
414
+ carry AMARK metadata but yielded no artifact (malformed front matter, a
415
+ malformed YAML/JSON document, an unparsable marker) - the silent-by-design
416
+ skips of spec section 8.6, surfaced for troubleshooting.
417
+ """
418
+ root_path = Path(root)
419
+ if not root_path.is_dir():
420
+ raise ValueError(f"not a directory: {root_path}")
421
+ artifacts: List[Dict[str, Any]] = []
422
+
423
+ def note(message: str) -> None:
424
+ if diagnostics is not None:
425
+ diagnostics.append(message)
426
+
427
+ # Discovery (spec section 8.1 / 10): do not descend into symlinked directories
428
+ # (os.walk followlinks=False) and skip symlinked files, so no scan escapes the
429
+ # repository root through a link.
430
+ ignore_patterns = load_ignore_patterns(root_path)
431
+
432
+ resolved_root = root_path.resolve()
433
+ file_paths: List[Path] = []
434
+ def walk_error(error: OSError) -> None:
435
+ raise error
436
+
437
+ for dirpath, dirnames, filenames in os.walk(root_path, followlinks=False, onerror=walk_error):
438
+ # A VCS store holds the repository's history, not its files (spec 8.1).
439
+ # Descending into it walks every loose object, emits one skip diagnostic
440
+ # per object, and would surface metadata from past states of the repo.
441
+ dirnames[:] = sorted(name for name in dirnames if name not in VCS_DIRS)
442
+ # A Windows junction is not a symlink to os.walk before Python 3.12, so
443
+ # prune every directory that resolves outside the root (spec 8.1).
444
+ dirnames[:] = [
445
+ name for name in dirnames
446
+ if _resolves_inside(Path(dirpath) / name, resolved_root)
447
+ ]
448
+ if ignore_patterns:
449
+ # Prune excluded directories (spec 8.1.1) rather than filtering their
450
+ # files afterwards, so an excluded tree is never walked at all.
451
+ kept = []
452
+ for name in dirnames:
453
+ relative = (Path(dirpath) / name).relative_to(root_path).as_posix()
454
+ if is_ignored(relative, ignore_patterns):
455
+ note(f"excluded by .amarkignore: {relative}/")
456
+ else:
457
+ kept.append(name)
458
+ dirnames[:] = kept
459
+ for name in filenames:
460
+ file_paths.append(Path(dirpath) / name)
461
+
462
+ for file_path in sorted(file_paths):
463
+ if file_path.is_dir() or file_path.is_symlink():
464
+ continue
465
+ rel = str(file_path.relative_to(root_path))
466
+
467
+ if ignore_patterns and is_ignored(file_path.relative_to(root_path).as_posix(),
468
+ ignore_patterns):
469
+ note(f"excluded by .amarkignore: {rel}")
470
+ continue
471
+
472
+ # Skip pathologically large files (spec Section 10, resource bounds).
473
+ try:
474
+ file_stat = file_path.stat()
475
+ if not stat.S_ISREG(file_stat.st_mode):
476
+ note(f"skipped (not a regular file): {rel}")
477
+ continue
478
+ if file_stat.st_size > MAX_FILE_BYTES:
479
+ note(f"skipped (larger than {MAX_FILE_BYTES} bytes): {rel}")
480
+ continue
481
+ except OSError as exc:
482
+ note(f"skipped (unreadable: {exc.__class__.__name__}): {rel}")
483
+ continue
484
+
485
+ # Skip files that are not valid UTF-8 rather than mangling bytes (spec 8.6).
486
+ # `utf-8-sig` transparently strips a leading BOM so it does not defeat the
487
+ # front-matter delimiter check; it is a no-op on BOM-less UTF-8.
488
+ try:
489
+ text = file_path.read_text(encoding="utf-8-sig")
490
+ except UnicodeDecodeError:
491
+ note(f"skipped (not valid UTF-8): {rel}")
492
+ continue
493
+ except OSError as exc:
494
+ note(f"skipped (unreadable: {exc.__class__.__name__}): {rel}")
495
+ continue
496
+ artifact: Optional[Dict[str, Any]] = None
497
+ suffix = file_path.suffix.lower()
498
+ if suffix in {".md", ".markdown"}:
499
+ artifact = amark_fields(parse_markdown_front_matter(text))
500
+ if artifact is None and text.startswith("---") and "amark-" in text:
501
+ note(
502
+ "front matter with amark- keys yielded no artifact "
503
+ f"(malformed YAML or unterminated block?): {rel}"
504
+ )
505
+ elif suffix in {".yml", ".yaml"}:
506
+ artifact = parse_yaml_identity(text)
507
+ if artifact is None:
508
+ # Infrastructure files may carry an identity-only comment marker.
509
+ artifact = parse_source_identity(text, suffix)
510
+ if artifact is None and "amark-" in text:
511
+ note(
512
+ "amark- keys present but no artifact extracted "
513
+ f"(malformed YAML or not a top-level mapping?): {rel}"
514
+ )
515
+ elif suffix == ".json":
516
+ artifact = parse_json_identity(text)
517
+ if artifact is None and "amark-" in text:
518
+ note(
519
+ "amark- keys present but no artifact extracted "
520
+ f"(malformed JSON or not an object?): {rel}"
521
+ )
522
+ else:
523
+ artifact = parse_source_identity(text, suffix)
524
+ if artifact is None and "amark:id" in text.lower():
525
+ note(
526
+ "amark:id text present but not a declaration "
527
+ f"(not inside a host-language comment, or bad characters in "
528
+ f"the id?): {rel}"
529
+ )
530
+
531
+ if artifact is None:
532
+ continue
533
+
534
+ if isinstance(artifact.get("id"), str):
535
+ artifact["id"] = normalize_id(artifact["id"])
536
+ if isinstance(artifact.get("kind"), str):
537
+ artifact["kind"] = normalize_name(artifact["kind"])
538
+ links = artifact.get("links")
539
+ if isinstance(links, list):
540
+ # Preserve malformed input for validation; canonicalize valid links
541
+ # and keep one of each (spec 3.4: duplicates are a single link).
542
+ canonical_links: List[Any] = []
543
+ seen_links = set()
544
+ for link in links:
545
+ pair = parse_link(link)
546
+ if pair is None:
547
+ canonical_links.append(link)
548
+ elif pair not in seen_links:
549
+ seen_links.add(pair)
550
+ canonical_links.append(f"{pair[0]}:{pair[1]}")
551
+ artifact["links"] = canonical_links
552
+ artifact["source"] = rel
553
+
554
+ # Machine-written declarations are excluded from discovery by default
555
+ # (spec Section 3.11). Without this a consumer reads back what it just
556
+ # wrote: generating an architecture document into a repository changes
557
+ # the artifact count of the next scan of that same repository, so the
558
+ # same command on unchanged sources gives two different answers.
559
+ generated_by = artifact.get("attributes", {}).get("generated-by")
560
+ if not include_generated and isinstance(generated_by, str) and generated_by.strip():
561
+ note(f"excluded (generated by "
562
+ f"{(artifact['attributes'])['generated-by']}): {rel}")
563
+ continue
564
+
565
+ artifacts.append(artifact)
566
+
567
+ return artifacts
568
+
569
+
570
+ def validate_artifacts(
571
+ artifacts: List[Dict[str, Any]], require_definitions: bool = True
572
+ ) -> List[str]:
573
+ """Return errors that make a corpus non-conforming (spec section 8.4).
574
+
575
+ Errors: an extracted artifact with no id; an id that violates the grammar;
576
+ an id that has no definition (no `kind` anywhere); and an id collision (two or
577
+ more definitions of the same canonical id). Identity declarations (source
578
+ markers with no kind) are not errors on their own - they are partial artifacts
579
+ merged with a definition of the same id (spec section 8.3).
580
+
581
+ A single repository is not a complete corpus: its marker's definition may live
582
+ in another repository. Pass `require_definitions=False` there and report
583
+ `find_undefined_ids()` as warnings instead.
584
+ """
585
+ errors: List[str] = []
586
+ definitions: Dict[str, List[str]] = {}
587
+ all_ids: Dict[str, str] = {}
588
+ grammar_checked: set = set()
589
+
590
+ for artifact in artifacts:
591
+ raw_id = artifact.get("id", "")
592
+ artifact_id = normalize_id(raw_id)
593
+ source = artifact.get("source", "unknown")
594
+ if not isinstance(raw_id, str):
595
+ errors.append(f"amark-id must be a string in {source}")
596
+ if not artifact_id:
597
+ errors.append(f"missing id in {source}")
598
+ continue
599
+ all_ids.setdefault(artifact_id, source)
600
+ if artifact_id not in grammar_checked:
601
+ grammar_checked.add(artifact_id)
602
+ if not ID_GRAMMAR.match(artifact_id):
603
+ errors.append(f"invalid id {raw_id!r} in {source}")
604
+ links = artifact.get("links")
605
+ if links is not None and not isinstance(links, list):
606
+ errors.append(f"amark-links must be a list in {source}")
607
+ elif isinstance(links, list):
608
+ for index, link in enumerate(links, 1):
609
+ pair = parse_link(link)
610
+ if pair is None:
611
+ errors.append(f"invalid link {index} in {source}: expected relation:TARGET "
612
+ "or a single-entry string mapping")
613
+ else:
614
+ relation, target = pair
615
+ if not (NAME_GRAMMAR.fullmatch(relation) or is_namespaced_name(relation)):
616
+ errors.append(f"invalid relationship {relation!r} in {source}")
617
+ if not ID_GRAMMAR.fullmatch(target):
618
+ errors.append(f"invalid link target {target!r} in {source}")
619
+ kind = artifact.get("kind", "")
620
+ if not isinstance(kind, str):
621
+ errors.append(f"amark-kind must be a string in {source}")
622
+ if normalize_name(kind):
623
+ definitions.setdefault(artifact_id, []).append(source)
624
+
625
+ for artifact_id in sorted(all_ids):
626
+ # Count distinct source files: one physical definition listed twice (e.g. an
627
+ # absent `source` defaulting to the same string) is not a collision.
628
+ sources = sorted(set(definitions.get(artifact_id, [])))
629
+ if not sources:
630
+ if require_definitions:
631
+ errors.append(f"missing kind for {artifact_id} in {all_ids[artifact_id]}")
632
+ elif len(sources) > 1:
633
+ errors.append(f"id collision: {artifact_id} defined in {', '.join(sources)}")
634
+
635
+ return errors
636
+
637
+
638
+ def find_undefined_ids(artifacts: List[Dict[str, Any]]) -> List[str]:
639
+ """Return one warning per id that no artifact gives a `kind` (spec section 8.4)."""
640
+ first_source: Dict[str, str] = {}
641
+ defined: set = set()
642
+ for artifact in artifacts:
643
+ artifact_id = normalize_id(artifact.get("id", ""))
644
+ if not artifact_id:
645
+ continue
646
+ first_source.setdefault(artifact_id, artifact.get("source", "unknown"))
647
+ kind = artifact.get("kind", "")
648
+ if isinstance(kind, str) and normalize_name(kind):
649
+ defined.add(artifact_id)
650
+ return [
651
+ f"missing kind for {artifact_id} in {first_source[artifact_id]} "
652
+ "(define it here or in another repository)"
653
+ for artifact_id in sorted(first_source)
654
+ if artifact_id not in defined
655
+ ]
656
+
657
+
658
+ def parse_link(link: Any) -> Optional[Tuple[str, str]]:
659
+ """Parse exactly one of the two link forms in spec Section 5.4."""
660
+ if isinstance(link, str) and ":" in link:
661
+ relation, target = link.split(":", 1)
662
+ elif isinstance(link, dict) and len(link) == 1:
663
+ relation, target = next(iter(link.items()))
664
+ if not isinstance(relation, str) or not isinstance(target, str):
665
+ return None
666
+ else:
667
+ return None
668
+ relation, target = normalize_name(relation), normalize_id(target)
669
+ return (relation, target) if relation and target else None
670
+
671
+
672
+ def iter_links(links: Any) -> Iterator[Tuple[str, str]]:
673
+ """Yield (relation, target) pairs from either link form.
674
+
675
+ A link is either the string ``relation:TARGET`` or the mapping
676
+ ``{relation: target}``. Relations are canonicalized lower-case, targets
677
+ canonicalized upper-case.
678
+ """
679
+ if not isinstance(links, list):
680
+ return
681
+ seen = set()
682
+ for link in links:
683
+ pair = parse_link(link)
684
+ if pair is not None and pair not in seen:
685
+ seen.add(pair)
686
+ yield pair
687
+
688
+
689
+ def find_name_warnings(artifacts: List[Dict[str, Any]]) -> List[str]:
690
+ """Return one warning per kind/relationship that is neither registered nor
691
+ namespaced (spec section 9.3). Consumers accept such names as opaque, so these
692
+ are producer-conformance warnings, not errors (promoted under strict mode)."""
693
+ warnings: List[str] = []
694
+ for artifact in artifacts:
695
+ artifact_id = normalize_id(artifact.get("id", "")) or "?"
696
+ source = artifact.get("source", "unknown")
697
+ kind = normalize_name(artifact.get("kind", ""))
698
+ if kind and kind not in REGISTERED_KINDS and not is_namespaced_name(kind):
699
+ warnings.append(
700
+ f"{artifact_id} uses unregistered, non-namespaced kind {kind!r} in {source}"
701
+ )
702
+ seen: set = set()
703
+ for relation, _target in iter_links(artifact.get("links", [])):
704
+ if relation in seen:
705
+ continue
706
+ seen.add(relation)
707
+ if relation not in REGISTERED_RELATIONSHIPS and not is_namespaced_name(relation):
708
+ warnings.append(
709
+ f"{artifact_id} uses unregistered, non-namespaced relationship "
710
+ f"{relation!r} in {source}"
711
+ )
712
+ return warnings
713
+
714
+
715
+ def find_attribute_warnings(artifacts: List[Dict[str, Any]]) -> List[str]:
716
+ """Producer-conformance warnings for the registered optional fields.
717
+
718
+ `amark-text`, `amark-owner`, and `amark-technology` must be strings (spec
719
+ 3.7/3.8/3.10); a present `amark-lifecycle` should carry a registered value
720
+ (spec 3.9) - unregistered values are accepted as opaque but warned about,
721
+ like unregistered names.
722
+ """
723
+ warnings: List[str] = []
724
+ for artifact in artifacts:
725
+ artifact_id = normalize_id(artifact.get("id", "")) or "?"
726
+ source = artifact.get("source", "unknown")
727
+ attributes = artifact.get("attributes") or {}
728
+ for field in ("text", "owner", "technology", "generated-by"):
729
+ value = attributes.get(field)
730
+ if field in attributes and not isinstance(value, str):
731
+ warnings.append(
732
+ f"{artifact_id} has non-string amark-{field} in {source}"
733
+ )
734
+ elif field == "owner" and isinstance(value, str) and not value.strip():
735
+ warnings.append(f"{artifact_id} has empty amark-owner in {source}")
736
+ lifecycle = attributes.get("lifecycle")
737
+ if "lifecycle" in attributes:
738
+ if not isinstance(lifecycle, str):
739
+ warnings.append(
740
+ f"{artifact_id} has non-string amark-lifecycle in {source}"
741
+ )
742
+ elif normalize_name(lifecycle) not in REGISTERED_LIFECYCLES:
743
+ warnings.append(
744
+ f"{artifact_id} uses unregistered lifecycle {lifecycle!r} in {source}"
745
+ )
746
+ return warnings
747
+
748
+
749
+ def find_dangling_links(artifacts: List[Dict[str, Any]]) -> List[str]:
750
+ """Return one message per link that targets an id no artifact defines.
751
+
752
+ Within a single repository this is expected for external/catalog ids defined
753
+ elsewhere, so callers treat these as warnings by default. Across a merged
754
+ global index every target should resolve, so they can be promoted to errors.
755
+ """
756
+ defined = {normalize_id(a.get("id", "")) for a in artifacts if a.get("id")}
757
+ warnings: List[str] = []
758
+ for artifact in artifacts:
759
+ artifact_id = normalize_id(artifact.get("id", ""))
760
+ source = artifact.get("source", "unknown")
761
+ seen = set()
762
+ for relation, target in iter_links(artifact.get("links", [])):
763
+ if target and target not in defined and target not in seen:
764
+ seen.add(target)
765
+ warnings.append(
766
+ f"{artifact_id or '?'} links to undefined id {target} ({relation}) in {source}"
767
+ )
768
+ return warnings