simple-skills 1.8.7 → 1.9.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.
- package/README.md +2 -1
- package/package.json +1 -1
- package/skills/engineering/knowledge-base/SKILL.md +122 -0
- package/skills/engineering/knowledge-base/references/consumption.md +171 -0
- package/skills/engineering/knowledge-base/references/format.md +565 -0
- package/skills/engineering/knowledge-base/scripts/knowledge.py +2175 -0
- package/skills/engineering/teach/DIAGRAM-TEACHING.md +133 -0
- package/skills/engineering/teach/SKILL.md +13 -1
- package/skills/engineering/teach/templates/diagram.css +104 -0
- package/skills/engineering/teach/templates/diagram.js +132 -0
|
@@ -0,0 +1,2175 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Knowledge bundle format v0.2 toolkit: create, validate, and consume knowledge bundles.
|
|
3
|
+
|
|
4
|
+
A bundle is a directory of markdown files with YAML frontmatter. This script is
|
|
5
|
+
the deterministic part of the `knowledge-base` skill: it never calls an LLM and never
|
|
6
|
+
invents content. It only reads, validates, indexes, and queries what is on disk.
|
|
7
|
+
|
|
8
|
+
Requires Python 3.9+ and PyYAML (`pip install pyyaml`).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Iterable
|
|
22
|
+
from urllib.parse import unquote
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
import yaml
|
|
26
|
+
except ImportError: # pragma: no cover - exercised only on a bad install
|
|
27
|
+
sys.stderr.write(
|
|
28
|
+
"knowledge.py requires PyYAML. Install it with: python3 -m pip install pyyaml\n"
|
|
29
|
+
)
|
|
30
|
+
raise SystemExit(2)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
FORMAT_VERSION = "0.2"
|
|
34
|
+
RESERVED_FILENAMES = {"index.md", "log.md"}
|
|
35
|
+
STATUS_VALUES = {"draft", "stable", "deprecated"}
|
|
36
|
+
TRUST_TIERS = {"unverified", "machine-confirmed", "human-reviewed"}
|
|
37
|
+
PROJECT_BUNDLE_REL = Path("docs") / "knowledge"
|
|
38
|
+
GLOBAL_BUNDLE_REL = Path(".agents") / "knowledge"
|
|
39
|
+
BUNDLE_HELP = "bundle directory; use '-' for the project/global default"
|
|
40
|
+
|
|
41
|
+
_ACTOR_RE = re.compile(
|
|
42
|
+
r"^(?:human:\S+|process:\S+|[A-Za-z0-9_.@-]+(?:/[A-Za-z0-9_.@+-]+)+)$"
|
|
43
|
+
)
|
|
44
|
+
_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
|
45
|
+
_LINK_RE = re.compile(
|
|
46
|
+
r"(?<!!)\[[^\]]*\]\(\s*(<[^>]+>|[^)\s]+)(?:\s+[\"'][^\"']*[\"'])?\s*\)"
|
|
47
|
+
)
|
|
48
|
+
_FOOTNOTE_USE_RE = re.compile(r"\[\^([^\]]+)\]")
|
|
49
|
+
_FOOTNOTE_DEF_RE = re.compile(r"^\[\^([^\]]+)\]:", re.M)
|
|
50
|
+
_FILE_EXT_RE = re.compile(
|
|
51
|
+
r"\.(?:md|sql|py|json|ya?ml|txt|csv|ts|js|toml|sh|ipynb|lookml)$", re.I
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class KnowledgeError(Exception):
|
|
56
|
+
"""A problem that makes a requested operation impossible."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------------------------------------------------------------------------
|
|
60
|
+
# YAML: keep timestamps as the author wrote them (string), not datetime objects.
|
|
61
|
+
# ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Loader(yaml.SafeLoader):
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
_Loader.yaml_implicit_resolvers = {
|
|
69
|
+
ch: [
|
|
70
|
+
(tag, regexp)
|
|
71
|
+
for tag, regexp in resolvers
|
|
72
|
+
if tag != "tag:yaml.org,2002:timestamp"
|
|
73
|
+
]
|
|
74
|
+
for ch, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------------------
|
|
79
|
+
# Small helpers
|
|
80
|
+
# ---------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def parse_timestamp(value: Any) -> datetime | None:
|
|
84
|
+
"""Parse a format timestamp: ISO 8601 with an explicit UTC offset.
|
|
85
|
+
|
|
86
|
+
Date-only values and values without a timezone return None. The format requires
|
|
87
|
+
the offset because a date-only instant is different in every timezone.
|
|
88
|
+
"""
|
|
89
|
+
if not isinstance(value, str) or "T" not in value:
|
|
90
|
+
return None
|
|
91
|
+
raw = value.strip()
|
|
92
|
+
if raw.endswith("Z"):
|
|
93
|
+
raw = raw[:-1] + "+00:00"
|
|
94
|
+
try:
|
|
95
|
+
parsed = datetime.fromisoformat(raw)
|
|
96
|
+
except ValueError:
|
|
97
|
+
return None
|
|
98
|
+
if parsed.tzinfo is None:
|
|
99
|
+
return None
|
|
100
|
+
return parsed
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def parse_now(value: str | None) -> datetime:
|
|
104
|
+
if value is None:
|
|
105
|
+
return datetime.now(timezone.utc)
|
|
106
|
+
raw = value.strip()
|
|
107
|
+
if "T" not in raw:
|
|
108
|
+
try:
|
|
109
|
+
return datetime.fromisoformat(raw).replace(tzinfo=timezone.utc)
|
|
110
|
+
except ValueError as exc:
|
|
111
|
+
raise KnowledgeError(f"--now is not an ISO date/datetime: {value!r}") from exc
|
|
112
|
+
if raw.endswith("Z"):
|
|
113
|
+
raw = raw[:-1] + "+00:00"
|
|
114
|
+
try:
|
|
115
|
+
parsed = datetime.fromisoformat(raw)
|
|
116
|
+
except ValueError as exc:
|
|
117
|
+
raise KnowledgeError(f"--now is not an ISO datetime: {value!r}") from exc
|
|
118
|
+
if parsed.tzinfo is None:
|
|
119
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
120
|
+
return parsed
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def one_line(text: Any) -> str:
|
|
124
|
+
return re.sub(r"\s+", " ", str(text or "")).strip()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def rel_posix(path: Path, bundle: Path) -> str:
|
|
128
|
+
return path.relative_to(bundle).as_posix()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def concept_id_from_rel(rel: str) -> str:
|
|
132
|
+
return rel[:-3] if rel.endswith(".md") else rel
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def is_hidden_rel(rel: Path) -> bool:
|
|
136
|
+
return any(part.startswith(".") for part in rel.parts)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def iter_markdown(bundle: Path) -> Iterable[Path]:
|
|
140
|
+
for path in sorted(bundle.rglob("*.md")):
|
|
141
|
+
rel = path.relative_to(bundle)
|
|
142
|
+
if is_hidden_rel(rel) or not path.is_file():
|
|
143
|
+
continue
|
|
144
|
+
yield path
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def strip_fenced(markdown_text: str) -> str:
|
|
148
|
+
"""Drop fenced code blocks so link detection ignores examples."""
|
|
149
|
+
out: list[str] = []
|
|
150
|
+
fence: str | None = None
|
|
151
|
+
for line in markdown_text.splitlines():
|
|
152
|
+
match = re.match(r"^\s*(`{3,}|~{3,})", line)
|
|
153
|
+
if match:
|
|
154
|
+
marker = match.group(1)
|
|
155
|
+
if fence is None:
|
|
156
|
+
fence = marker[0]
|
|
157
|
+
out.append("")
|
|
158
|
+
continue
|
|
159
|
+
if marker[0] == fence:
|
|
160
|
+
fence = None
|
|
161
|
+
out.append("")
|
|
162
|
+
continue
|
|
163
|
+
out.append("" if fence is not None else line)
|
|
164
|
+
return "\n".join(out)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def extract_links(markdown_text: str) -> list[str]:
|
|
168
|
+
text = strip_fenced(markdown_text)
|
|
169
|
+
return [match.group(1) for match in _LINK_RE.finditer(text)]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def resolve_link(bundle: Path, doc_path: Path, target: str) -> tuple[str | None, Path | None]:
|
|
173
|
+
"""Resolve a markdown link target.
|
|
174
|
+
|
|
175
|
+
Returns (status, resolved_path):
|
|
176
|
+
status is None for external/anchor links, "ok" when the target exists,
|
|
177
|
+
"broken" when it does not, and "outside" when it escapes the bundle.
|
|
178
|
+
"""
|
|
179
|
+
target = target.strip()
|
|
180
|
+
if target.startswith("<") and target.endswith(">"):
|
|
181
|
+
target = target[1:-1]
|
|
182
|
+
if not target or target.startswith("#") or target.startswith("//"):
|
|
183
|
+
return None, None
|
|
184
|
+
if _SCHEME_RE.match(target):
|
|
185
|
+
return None, None
|
|
186
|
+
target = unquote(target).split("#", 1)[0].split("?", 1)[0]
|
|
187
|
+
if not target:
|
|
188
|
+
return None, None
|
|
189
|
+
candidate = (
|
|
190
|
+
bundle / target.lstrip("/")
|
|
191
|
+
if target.startswith("/")
|
|
192
|
+
else doc_path.parent / target
|
|
193
|
+
)
|
|
194
|
+
try:
|
|
195
|
+
resolved_rel = candidate.resolve().relative_to(bundle.resolve())
|
|
196
|
+
except ValueError:
|
|
197
|
+
return "outside", candidate
|
|
198
|
+
if candidate.exists():
|
|
199
|
+
return "ok", resolved_rel
|
|
200
|
+
return "broken", resolved_rel
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def path_like(value: str) -> bool:
|
|
204
|
+
"""Whether a path-valued field should be checked for existence."""
|
|
205
|
+
value = value.strip()
|
|
206
|
+
if not value:
|
|
207
|
+
return False
|
|
208
|
+
if value.startswith(("/", "./", "../")):
|
|
209
|
+
return True
|
|
210
|
+
if _SCHEME_RE.match(value):
|
|
211
|
+
return False
|
|
212
|
+
return bool(_FILE_EXT_RE.search(value))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def resolve_field_candidates(
|
|
216
|
+
bundle: Path, doc_path: Path, value: str
|
|
217
|
+
) -> list[Path]:
|
|
218
|
+
raw = unquote(value.strip()).split("#", 1)[0].split("?", 1)[0]
|
|
219
|
+
if raw.startswith("/"):
|
|
220
|
+
return [bundle / raw.lstrip("/")]
|
|
221
|
+
# Sample bundles use bundle-root-relative values; specs also allow doc-relative.
|
|
222
|
+
return [bundle / raw, doc_path.parent / raw]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def normalize_verified(frontmatter: dict[str, Any]) -> list[dict[str, Any]]:
|
|
226
|
+
raw = frontmatter.get("verified")
|
|
227
|
+
if raw is None:
|
|
228
|
+
return []
|
|
229
|
+
if isinstance(raw, dict):
|
|
230
|
+
return [raw]
|
|
231
|
+
if isinstance(raw, list):
|
|
232
|
+
return [entry for entry in raw if isinstance(entry, dict)]
|
|
233
|
+
return []
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def trust_tier(frontmatter: dict[str, Any]) -> str:
|
|
237
|
+
events = normalize_verified(frontmatter)
|
|
238
|
+
if not events:
|
|
239
|
+
return "unverified"
|
|
240
|
+
if any(str(event.get("by") or "").startswith("human:") for event in events):
|
|
241
|
+
return "human-reviewed"
|
|
242
|
+
return "machine-confirmed"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def is_stale(frontmatter: dict[str, Any], now: datetime) -> bool:
|
|
246
|
+
stale_after = parse_timestamp(frontmatter.get("stale_after"))
|
|
247
|
+
if stale_after is None:
|
|
248
|
+
return False
|
|
249
|
+
return now >= stale_after
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def dump_frontmatter(frontmatter: dict[str, Any]) -> str:
|
|
253
|
+
text = yaml.safe_dump(
|
|
254
|
+
frontmatter, sort_keys=False, allow_unicode=True, default_flow_style=False
|
|
255
|
+
).rstrip()
|
|
256
|
+
return f"---\n{text}\n---\n\n"
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def slug_title(stem: str) -> str:
|
|
260
|
+
return re.sub(r"[-_]+", " ", stem).strip() or stem
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _find_repo_root(start: Path) -> Path | None:
|
|
264
|
+
current = start.resolve()
|
|
265
|
+
if current.is_file():
|
|
266
|
+
current = current.parent
|
|
267
|
+
for candidate in (current, *current.parents):
|
|
268
|
+
if (candidate / ".git").exists():
|
|
269
|
+
return candidate
|
|
270
|
+
return None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def default_bundle_paths(start: Path) -> tuple[Path | None, Path, Path | None]:
|
|
274
|
+
"""Return (project_path, global_path, repo_root).
|
|
275
|
+
|
|
276
|
+
Project bundles live at <repo>/docs/knowledge; global bundles at
|
|
277
|
+
~/.agents/knowledge. The project path is None outside a git repository.
|
|
278
|
+
"""
|
|
279
|
+
repo = _find_repo_root(start)
|
|
280
|
+
project = repo / PROJECT_BUNDLE_REL if repo is not None else None
|
|
281
|
+
global_path = Path.home() / GLOBAL_BUNDLE_REL
|
|
282
|
+
return project, global_path, repo
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def existing_default_bundle(start: Path) -> tuple[str, Path] | None:
|
|
286
|
+
"""First existing default bundle: project, then global. Never merges."""
|
|
287
|
+
project, global_path, _ = default_bundle_paths(start)
|
|
288
|
+
seen: set[Path] = set()
|
|
289
|
+
for scope, path in (("project", project), ("global", global_path)):
|
|
290
|
+
if path is None:
|
|
291
|
+
continue
|
|
292
|
+
resolved = path.resolve()
|
|
293
|
+
if resolved in seen:
|
|
294
|
+
continue
|
|
295
|
+
seen.add(resolved)
|
|
296
|
+
if path.is_dir():
|
|
297
|
+
return scope, path
|
|
298
|
+
return None
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def write_default_bundle(start: Path) -> tuple[str, Path]:
|
|
302
|
+
"""Project inside a git repo, global outside. Used by `init` and `where`."""
|
|
303
|
+
project, global_path, _ = default_bundle_paths(start)
|
|
304
|
+
if project is not None:
|
|
305
|
+
return "project", project
|
|
306
|
+
return "global", global_path
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _is_default_bundle_arg(value: Any) -> bool:
|
|
310
|
+
return value is None or str(value).strip() == "-"
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def resolve_cli_bundle(
|
|
314
|
+
value: Any, *, allow_missing: bool = False, start: Path | None = None
|
|
315
|
+
) -> Path:
|
|
316
|
+
"""Resolve an explicit BUNDLE, or '-'/None via project-then-global lookup."""
|
|
317
|
+
if not _is_default_bundle_arg(value):
|
|
318
|
+
return Path(value).resolve()
|
|
319
|
+
base = start or Path.cwd()
|
|
320
|
+
existing = existing_default_bundle(base)
|
|
321
|
+
if existing is not None:
|
|
322
|
+
return existing[1].resolve()
|
|
323
|
+
if allow_missing:
|
|
324
|
+
return write_default_bundle(base)[1].resolve()
|
|
325
|
+
project, global_path, _ = default_bundle_paths(base)
|
|
326
|
+
looked = ", ".join(
|
|
327
|
+
str(path) for path in (project, global_path) if path is not None
|
|
328
|
+
)
|
|
329
|
+
raise KnowledgeError(
|
|
330
|
+
f"no knowledge bundle found in default paths: {looked}. "
|
|
331
|
+
"Run `init` to create one, or pass an explicit BUNDLE."
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# ---------------------------------------------------------------------------
|
|
336
|
+
# Documents and concepts
|
|
337
|
+
# ---------------------------------------------------------------------------
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
@dataclass
|
|
341
|
+
class Document:
|
|
342
|
+
path: Path
|
|
343
|
+
rel: str
|
|
344
|
+
frontmatter: dict[str, Any]
|
|
345
|
+
body: str
|
|
346
|
+
has_frontmatter: bool
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def parse_document(path: Path, bundle: Path) -> Document:
|
|
350
|
+
rel = rel_posix(path, bundle)
|
|
351
|
+
try:
|
|
352
|
+
text = path.read_text(encoding="utf-8-sig")
|
|
353
|
+
except UnicodeDecodeError as exc:
|
|
354
|
+
raise KnowledgeError(f"{rel}: not valid UTF-8 ({exc})") from exc
|
|
355
|
+
lines = text.splitlines()
|
|
356
|
+
if not lines or lines[0].strip() != "---":
|
|
357
|
+
return Document(path, rel, {}, text, False)
|
|
358
|
+
end = next(
|
|
359
|
+
(i for i in range(1, len(lines)) if lines[i].strip() == "---"), None
|
|
360
|
+
)
|
|
361
|
+
if end is None:
|
|
362
|
+
raise KnowledgeError(f"{rel}: unterminated YAML frontmatter block")
|
|
363
|
+
try:
|
|
364
|
+
frontmatter = yaml.load("\n".join(lines[1:end]), Loader=_Loader) or {}
|
|
365
|
+
except yaml.YAMLError as exc:
|
|
366
|
+
raise KnowledgeError(f"{rel}: invalid YAML frontmatter: {exc}") from exc
|
|
367
|
+
if not isinstance(frontmatter, dict):
|
|
368
|
+
raise KnowledgeError(f"{rel}: frontmatter must be a YAML mapping")
|
|
369
|
+
body_lines = lines[end + 1 :]
|
|
370
|
+
if body_lines and body_lines[0] == "":
|
|
371
|
+
body_lines = body_lines[1:]
|
|
372
|
+
return Document(path, rel, frontmatter, "\n".join(body_lines), True)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@dataclass
|
|
376
|
+
class Concept:
|
|
377
|
+
path: Path
|
|
378
|
+
rel: str
|
|
379
|
+
frontmatter: dict[str, Any]
|
|
380
|
+
body: str
|
|
381
|
+
|
|
382
|
+
@property
|
|
383
|
+
def id(self) -> str:
|
|
384
|
+
return concept_id_from_rel(self.rel)
|
|
385
|
+
|
|
386
|
+
@property
|
|
387
|
+
def type(self) -> str:
|
|
388
|
+
value = self.frontmatter.get("type")
|
|
389
|
+
return value.strip() if isinstance(value, str) else ""
|
|
390
|
+
|
|
391
|
+
@property
|
|
392
|
+
def title(self) -> str:
|
|
393
|
+
value = self.frontmatter.get("title")
|
|
394
|
+
return value.strip() if isinstance(value, str) and value.strip() else self.path.stem
|
|
395
|
+
|
|
396
|
+
@property
|
|
397
|
+
def description(self) -> str:
|
|
398
|
+
value = self.frontmatter.get("description")
|
|
399
|
+
return one_line(value) if isinstance(value, str) else ""
|
|
400
|
+
|
|
401
|
+
@property
|
|
402
|
+
def tags(self) -> list[str]:
|
|
403
|
+
raw = self.frontmatter.get("tags")
|
|
404
|
+
if isinstance(raw, list):
|
|
405
|
+
return [str(tag).strip() for tag in raw if str(tag).strip()]
|
|
406
|
+
if isinstance(raw, str):
|
|
407
|
+
return [tag.strip() for tag in raw.split(",") if tag.strip()]
|
|
408
|
+
return []
|
|
409
|
+
|
|
410
|
+
@property
|
|
411
|
+
def status(self) -> str:
|
|
412
|
+
value = self.frontmatter.get("status")
|
|
413
|
+
return value if isinstance(value, str) and value else "stable"
|
|
414
|
+
|
|
415
|
+
@property
|
|
416
|
+
def generated_at(self) -> str | None:
|
|
417
|
+
generated = self.frontmatter.get("generated")
|
|
418
|
+
if isinstance(generated, dict) and isinstance(generated.get("at"), str):
|
|
419
|
+
return generated["at"]
|
|
420
|
+
return None
|
|
421
|
+
|
|
422
|
+
def summary(self, now: datetime) -> dict[str, Any]:
|
|
423
|
+
return {
|
|
424
|
+
"id": self.id,
|
|
425
|
+
"path": self.rel,
|
|
426
|
+
"type": self.type,
|
|
427
|
+
"title": self.title,
|
|
428
|
+
"description": self.description,
|
|
429
|
+
"tags": self.tags,
|
|
430
|
+
"status": self.status,
|
|
431
|
+
"trust": trust_tier(self.frontmatter),
|
|
432
|
+
"stale": is_stale(self.frontmatter, now),
|
|
433
|
+
"generated_at": self.generated_at,
|
|
434
|
+
"runtime": self.frontmatter.get("runtime"),
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def load_concepts(
|
|
439
|
+
bundle: Path, now: datetime
|
|
440
|
+
) -> tuple[list[Concept], list[dict[str, str]]]:
|
|
441
|
+
bundle = bundle.resolve()
|
|
442
|
+
if not bundle.is_dir():
|
|
443
|
+
raise KnowledgeError(f"bundle directory not found: {bundle}")
|
|
444
|
+
concepts: list[Concept] = []
|
|
445
|
+
skipped: list[dict[str, str]] = []
|
|
446
|
+
for path in iter_markdown(bundle):
|
|
447
|
+
if path.name in RESERVED_FILENAMES:
|
|
448
|
+
continue
|
|
449
|
+
try:
|
|
450
|
+
doc = parse_document(path, bundle)
|
|
451
|
+
except KnowledgeError as exc:
|
|
452
|
+
skipped.append({"path": rel_posix(path, bundle), "error": str(exc)})
|
|
453
|
+
continue
|
|
454
|
+
if not doc.has_frontmatter:
|
|
455
|
+
skipped.append(
|
|
456
|
+
{
|
|
457
|
+
"path": doc.rel,
|
|
458
|
+
"error": "missing YAML frontmatter (not a concept)",
|
|
459
|
+
}
|
|
460
|
+
)
|
|
461
|
+
continue
|
|
462
|
+
concepts.append(Concept(path, doc.rel, doc.frontmatter, doc.body))
|
|
463
|
+
return concepts, skipped
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
# ---------------------------------------------------------------------------
|
|
467
|
+
# Validation
|
|
468
|
+
# ---------------------------------------------------------------------------
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
@dataclass
|
|
472
|
+
class Finding:
|
|
473
|
+
path: str
|
|
474
|
+
level: str
|
|
475
|
+
code: str
|
|
476
|
+
message: str
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
@dataclass
|
|
480
|
+
class Report:
|
|
481
|
+
bundle: Path
|
|
482
|
+
now: datetime
|
|
483
|
+
findings: list[Finding] = field(default_factory=list)
|
|
484
|
+
concepts: list[Concept] = field(default_factory=list)
|
|
485
|
+
|
|
486
|
+
def add(self, path: str, level: str, code: str, message: str) -> None:
|
|
487
|
+
self.findings.append(Finding(path, level, code, message))
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _check_path_value(
|
|
491
|
+
report: Report, concept: Concept, value: Any, label: str
|
|
492
|
+
) -> None:
|
|
493
|
+
if not isinstance(value, str) or not value.strip():
|
|
494
|
+
report.add(
|
|
495
|
+
concept.rel,
|
|
496
|
+
"warning",
|
|
497
|
+
"W-PATH",
|
|
498
|
+
f"`{label}` must be a non-empty string",
|
|
499
|
+
)
|
|
500
|
+
return
|
|
501
|
+
if not path_like(value):
|
|
502
|
+
return
|
|
503
|
+
candidates = resolve_field_candidates(report.bundle, concept.path, value)
|
|
504
|
+
for candidate in candidates:
|
|
505
|
+
if not candidate.exists():
|
|
506
|
+
continue
|
|
507
|
+
try:
|
|
508
|
+
candidate.resolve().relative_to(report.bundle.resolve())
|
|
509
|
+
except ValueError:
|
|
510
|
+
report.add(
|
|
511
|
+
concept.rel,
|
|
512
|
+
"warning",
|
|
513
|
+
"W-PATH",
|
|
514
|
+
f"`{label}` points outside the bundle: {value!r}",
|
|
515
|
+
)
|
|
516
|
+
return
|
|
517
|
+
report.add(
|
|
518
|
+
concept.rel,
|
|
519
|
+
"warning",
|
|
520
|
+
"W-PATH",
|
|
521
|
+
f"`{label}` points to a missing file: {value!r}",
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _check_body_links(report: Report, concept: Concept) -> None:
|
|
526
|
+
for target in extract_links(concept.body):
|
|
527
|
+
status, resolved = resolve_link(report.bundle, concept.path, target)
|
|
528
|
+
if status == "broken":
|
|
529
|
+
report.add(
|
|
530
|
+
concept.rel,
|
|
531
|
+
"warning",
|
|
532
|
+
"W-LINK",
|
|
533
|
+
f"link target not found: {target!r}",
|
|
534
|
+
)
|
|
535
|
+
elif status == "outside":
|
|
536
|
+
report.add(
|
|
537
|
+
concept.rel,
|
|
538
|
+
"warning",
|
|
539
|
+
"W-LINK",
|
|
540
|
+
f"link escapes the bundle: {target!r}",
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _has_computation_block(body: str) -> bool:
|
|
545
|
+
in_section = False
|
|
546
|
+
for line in body.splitlines():
|
|
547
|
+
if re.match(r"^#\s+", line):
|
|
548
|
+
in_section = bool(re.match(r"^#\s+Computation\s*$", line, re.I))
|
|
549
|
+
continue
|
|
550
|
+
if not in_section:
|
|
551
|
+
continue
|
|
552
|
+
stripped = line.lstrip()
|
|
553
|
+
if stripped.startswith("```") or stripped.startswith("~~~"):
|
|
554
|
+
return True
|
|
555
|
+
if line.startswith(" ") and stripped:
|
|
556
|
+
return True
|
|
557
|
+
return False
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _validate_attested(report: Report, concept: Concept) -> None:
|
|
561
|
+
fm = concept.frontmatter
|
|
562
|
+
runtime = fm.get("runtime")
|
|
563
|
+
if not isinstance(runtime, str) or not runtime.strip():
|
|
564
|
+
report.add(
|
|
565
|
+
concept.rel,
|
|
566
|
+
"warning",
|
|
567
|
+
"W-AC-RUNTIME",
|
|
568
|
+
"Attested Computation requires a non-empty `runtime`",
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
parameters = fm.get("parameters")
|
|
572
|
+
if parameters is not None:
|
|
573
|
+
if not isinstance(parameters, list):
|
|
574
|
+
report.add(
|
|
575
|
+
concept.rel,
|
|
576
|
+
"warning",
|
|
577
|
+
"W-AC-PARAMETERS",
|
|
578
|
+
"`parameters` must be a list of {name, type, required} mappings",
|
|
579
|
+
)
|
|
580
|
+
else:
|
|
581
|
+
for index, param in enumerate(parameters):
|
|
582
|
+
label = f"parameters[{index}]"
|
|
583
|
+
if not isinstance(param, dict):
|
|
584
|
+
report.add(
|
|
585
|
+
concept.rel,
|
|
586
|
+
"warning",
|
|
587
|
+
"W-AC-PARAMETERS",
|
|
588
|
+
f"{label} must be a mapping",
|
|
589
|
+
)
|
|
590
|
+
continue
|
|
591
|
+
for key in ("name", "type"):
|
|
592
|
+
value = param.get(key)
|
|
593
|
+
if not isinstance(value, str) or not value.strip():
|
|
594
|
+
report.add(
|
|
595
|
+
concept.rel,
|
|
596
|
+
"warning",
|
|
597
|
+
"W-AC-PARAMETERS",
|
|
598
|
+
f"{label}.{key} must be a non-empty string",
|
|
599
|
+
)
|
|
600
|
+
if "required" in param and not isinstance(param["required"], bool):
|
|
601
|
+
report.add(
|
|
602
|
+
concept.rel,
|
|
603
|
+
"warning",
|
|
604
|
+
"W-AC-PARAMETERS",
|
|
605
|
+
f"{label}.required must be a boolean",
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
has_inline = _has_computation_block(concept.body)
|
|
609
|
+
computation = fm.get("computation")
|
|
610
|
+
if computation is not None:
|
|
611
|
+
if not isinstance(computation, str) or not computation.strip():
|
|
612
|
+
report.add(
|
|
613
|
+
concept.rel,
|
|
614
|
+
"warning",
|
|
615
|
+
"W-AC-COMPUTATION",
|
|
616
|
+
"`computation` must be a non-empty path",
|
|
617
|
+
)
|
|
618
|
+
if has_inline:
|
|
619
|
+
report.add(
|
|
620
|
+
concept.rel,
|
|
621
|
+
"warning",
|
|
622
|
+
"W-AC-COMPUTATION",
|
|
623
|
+
"computation is both inline and file-backed; use one form",
|
|
624
|
+
)
|
|
625
|
+
elif not has_inline:
|
|
626
|
+
report.add(
|
|
627
|
+
concept.rel,
|
|
628
|
+
"warning",
|
|
629
|
+
"W-AC-COMPUTATION",
|
|
630
|
+
"no computation found: add a `# Computation` code block or set `computation:`",
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
executor = fm.get("executor")
|
|
634
|
+
if executor is None:
|
|
635
|
+
report.add(
|
|
636
|
+
concept.rel,
|
|
637
|
+
"warning",
|
|
638
|
+
"W-AC-EXECUTOR",
|
|
639
|
+
"Attested Computation should declare `executor` (resource + receipt)",
|
|
640
|
+
)
|
|
641
|
+
elif not isinstance(executor, dict):
|
|
642
|
+
report.add(
|
|
643
|
+
concept.rel,
|
|
644
|
+
"warning",
|
|
645
|
+
"W-AC-EXECUTOR",
|
|
646
|
+
"`executor` must be a mapping",
|
|
647
|
+
)
|
|
648
|
+
else:
|
|
649
|
+
if not isinstance(executor.get("resource"), str) or not executor.get("resource"):
|
|
650
|
+
report.add(
|
|
651
|
+
concept.rel,
|
|
652
|
+
"warning",
|
|
653
|
+
"W-AC-EXECUTOR",
|
|
654
|
+
"`executor.resource` must name run instructions or code",
|
|
655
|
+
)
|
|
656
|
+
receipt = executor.get("receipt")
|
|
657
|
+
if receipt is None:
|
|
658
|
+
report.add(
|
|
659
|
+
concept.rel,
|
|
660
|
+
"warning",
|
|
661
|
+
"W-AC-RECEIPT",
|
|
662
|
+
"`executor.receipt` must declare the fields a run returns",
|
|
663
|
+
)
|
|
664
|
+
elif not isinstance(receipt, list) or any(
|
|
665
|
+
not isinstance(item, str) or not item.strip() for item in receipt
|
|
666
|
+
):
|
|
667
|
+
report.add(
|
|
668
|
+
concept.rel,
|
|
669
|
+
"warning",
|
|
670
|
+
"W-AC-RECEIPT",
|
|
671
|
+
"`executor.receipt` must be a list of field names",
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
attester = fm.get("attester")
|
|
675
|
+
if attester is None:
|
|
676
|
+
report.add(
|
|
677
|
+
concept.rel,
|
|
678
|
+
"warning",
|
|
679
|
+
"W-AC-ATTESTER",
|
|
680
|
+
"Attested Computation should declare `attester.resource`",
|
|
681
|
+
)
|
|
682
|
+
elif not isinstance(attester, dict):
|
|
683
|
+
report.add(
|
|
684
|
+
concept.rel,
|
|
685
|
+
"warning",
|
|
686
|
+
"W-AC-ATTESTER",
|
|
687
|
+
"`attester` must be a mapping",
|
|
688
|
+
)
|
|
689
|
+
elif not isinstance(attester.get("resource"), str) or not attester.get("resource"):
|
|
690
|
+
report.add(
|
|
691
|
+
concept.rel,
|
|
692
|
+
"warning",
|
|
693
|
+
"W-AC-ATTESTER",
|
|
694
|
+
"`attester.resource` must name deterministic check code",
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _validate_concept(report: Report, concept: Concept) -> None:
|
|
699
|
+
fm = concept.frontmatter
|
|
700
|
+
rel = concept.rel
|
|
701
|
+
|
|
702
|
+
type_value = fm.get("type")
|
|
703
|
+
if not isinstance(type_value, str) or not type_value.strip():
|
|
704
|
+
report.add(
|
|
705
|
+
rel,
|
|
706
|
+
"error",
|
|
707
|
+
"E-TYPE",
|
|
708
|
+
"frontmatter `type` must be a non-empty string",
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
for key in ("title", "description"):
|
|
712
|
+
value = fm.get(key)
|
|
713
|
+
if value is None:
|
|
714
|
+
report.add(
|
|
715
|
+
rel,
|
|
716
|
+
"warning",
|
|
717
|
+
"W-RECOMMENDED",
|
|
718
|
+
f"`{key}` is recommended; index.md and search use it",
|
|
719
|
+
)
|
|
720
|
+
elif not isinstance(value, str) or not value.strip():
|
|
721
|
+
report.add(
|
|
722
|
+
rel,
|
|
723
|
+
"warning",
|
|
724
|
+
"W-FIELD-SHAPE",
|
|
725
|
+
f"`{key}` must be a non-empty string when present",
|
|
726
|
+
)
|
|
727
|
+
|
|
728
|
+
if "resource" in fm and (
|
|
729
|
+
not isinstance(fm["resource"], str) or not fm["resource"].strip()
|
|
730
|
+
):
|
|
731
|
+
report.add(
|
|
732
|
+
rel,
|
|
733
|
+
"warning",
|
|
734
|
+
"W-FIELD-SHAPE",
|
|
735
|
+
"`resource` must be a non-empty string when present",
|
|
736
|
+
)
|
|
737
|
+
if "resource" in fm:
|
|
738
|
+
_check_path_value(report, concept, fm.get("resource"), "resource")
|
|
739
|
+
|
|
740
|
+
tags = fm.get("tags")
|
|
741
|
+
if tags is not None:
|
|
742
|
+
if not isinstance(tags, list):
|
|
743
|
+
report.add(
|
|
744
|
+
rel,
|
|
745
|
+
"warning",
|
|
746
|
+
"W-TAGS",
|
|
747
|
+
"`tags` should be a YAML list of short strings",
|
|
748
|
+
)
|
|
749
|
+
elif any(not isinstance(tag, str) or not tag.strip() for tag in tags):
|
|
750
|
+
report.add(
|
|
751
|
+
rel,
|
|
752
|
+
"warning",
|
|
753
|
+
"W-TAGS",
|
|
754
|
+
"`tags` entries must be non-empty strings",
|
|
755
|
+
)
|
|
756
|
+
|
|
757
|
+
status = fm.get("status")
|
|
758
|
+
if status is not None and (
|
|
759
|
+
not isinstance(status, str) or status not in STATUS_VALUES
|
|
760
|
+
):
|
|
761
|
+
report.add(
|
|
762
|
+
rel,
|
|
763
|
+
"warning",
|
|
764
|
+
"W-STATUS",
|
|
765
|
+
"`status` must be one of draft | stable | deprecated",
|
|
766
|
+
)
|
|
767
|
+
|
|
768
|
+
generated = fm.get("generated")
|
|
769
|
+
if generated is None:
|
|
770
|
+
if "timestamp" in fm:
|
|
771
|
+
report.add(
|
|
772
|
+
rel,
|
|
773
|
+
"warning",
|
|
774
|
+
"W-LEGACY",
|
|
775
|
+
"v0.1 `timestamp` found; use `generated: {by, at}`",
|
|
776
|
+
)
|
|
777
|
+
elif not isinstance(generated, dict):
|
|
778
|
+
report.add(
|
|
779
|
+
rel,
|
|
780
|
+
"warning",
|
|
781
|
+
"W-GENERATED",
|
|
782
|
+
"`generated` must be a {by, at} mapping",
|
|
783
|
+
)
|
|
784
|
+
else:
|
|
785
|
+
by = generated.get("by")
|
|
786
|
+
if not isinstance(by, str) or not by.strip():
|
|
787
|
+
report.add(
|
|
788
|
+
rel,
|
|
789
|
+
"warning",
|
|
790
|
+
"W-ACTOR",
|
|
791
|
+
"`generated.by` must be an actor "
|
|
792
|
+
"(<producer>/<version>, human:<id>, or process:<id>)",
|
|
793
|
+
)
|
|
794
|
+
elif not _ACTOR_RE.match(by.strip()):
|
|
795
|
+
report.add(
|
|
796
|
+
rel,
|
|
797
|
+
"warning",
|
|
798
|
+
"W-ACTOR",
|
|
799
|
+
f"`generated.by` does not follow the actor convention: {by!r}",
|
|
800
|
+
)
|
|
801
|
+
if "at" in generated and parse_timestamp(generated["at"]) is None:
|
|
802
|
+
report.add(
|
|
803
|
+
rel,
|
|
804
|
+
"warning",
|
|
805
|
+
"W-TIMESTAMP",
|
|
806
|
+
"`generated.at` must be ISO 8601 with an explicit UTC offset",
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
if "verified" in fm:
|
|
810
|
+
raw_verified = fm["verified"]
|
|
811
|
+
if not isinstance(raw_verified, (dict, list)):
|
|
812
|
+
report.add(
|
|
813
|
+
rel,
|
|
814
|
+
"warning",
|
|
815
|
+
"W-VERIFIED",
|
|
816
|
+
"`verified` must be a mapping or a list of {by, at} mappings",
|
|
817
|
+
)
|
|
818
|
+
elif isinstance(raw_verified, list) and not normalize_verified(fm):
|
|
819
|
+
report.add(
|
|
820
|
+
rel,
|
|
821
|
+
"warning",
|
|
822
|
+
"W-VERIFIED",
|
|
823
|
+
"`verified` list has no {by, at} mappings",
|
|
824
|
+
)
|
|
825
|
+
for index, event in enumerate(normalize_verified(fm)):
|
|
826
|
+
label = f"verified[{index}]"
|
|
827
|
+
by = event.get("by")
|
|
828
|
+
if not isinstance(by, str) or not by.strip():
|
|
829
|
+
report.add(
|
|
830
|
+
rel,
|
|
831
|
+
"warning",
|
|
832
|
+
"W-ACTOR",
|
|
833
|
+
f"`{label}.by` must be an actor",
|
|
834
|
+
)
|
|
835
|
+
elif not _ACTOR_RE.match(by.strip()):
|
|
836
|
+
report.add(
|
|
837
|
+
rel,
|
|
838
|
+
"warning",
|
|
839
|
+
"W-ACTOR",
|
|
840
|
+
f"`{label}.by` does not follow the actor convention: {by!r}",
|
|
841
|
+
)
|
|
842
|
+
if "at" in event and parse_timestamp(event["at"]) is None:
|
|
843
|
+
report.add(
|
|
844
|
+
rel,
|
|
845
|
+
"warning",
|
|
846
|
+
"W-TIMESTAMP",
|
|
847
|
+
f"`{label}.at` must be ISO 8601 with an explicit UTC offset",
|
|
848
|
+
)
|
|
849
|
+
|
|
850
|
+
if "stale_after" in fm and parse_timestamp(fm["stale_after"]) is None:
|
|
851
|
+
report.add(
|
|
852
|
+
rel,
|
|
853
|
+
"warning",
|
|
854
|
+
"W-TIMESTAMP",
|
|
855
|
+
"`stale_after` must be an absolute ISO 8601 instant with an offset",
|
|
856
|
+
)
|
|
857
|
+
|
|
858
|
+
source_ids: set[str] = set()
|
|
859
|
+
sources = fm.get("sources")
|
|
860
|
+
if sources is not None:
|
|
861
|
+
if isinstance(sources, list):
|
|
862
|
+
entries = sources
|
|
863
|
+
elif isinstance(sources, dict):
|
|
864
|
+
entries = [sources]
|
|
865
|
+
report.add(
|
|
866
|
+
rel,
|
|
867
|
+
"warning",
|
|
868
|
+
"W-SOURCES",
|
|
869
|
+
"`sources` should be a list of mappings",
|
|
870
|
+
)
|
|
871
|
+
else:
|
|
872
|
+
entries = []
|
|
873
|
+
report.add(
|
|
874
|
+
rel,
|
|
875
|
+
"warning",
|
|
876
|
+
"W-SOURCES",
|
|
877
|
+
"`sources` must be a list of mappings",
|
|
878
|
+
)
|
|
879
|
+
for index, entry in enumerate(entries):
|
|
880
|
+
label = f"sources[{index}]"
|
|
881
|
+
if not isinstance(entry, dict):
|
|
882
|
+
report.add(
|
|
883
|
+
rel, "warning", "W-SOURCES", f"`{label}` must be a mapping"
|
|
884
|
+
)
|
|
885
|
+
continue
|
|
886
|
+
source_id = entry.get("id")
|
|
887
|
+
if source_id is not None:
|
|
888
|
+
if not isinstance(source_id, str) or not source_id.strip():
|
|
889
|
+
report.add(
|
|
890
|
+
rel,
|
|
891
|
+
"warning",
|
|
892
|
+
"W-SOURCE-ID",
|
|
893
|
+
f"`{label}.id` must be a non-empty string",
|
|
894
|
+
)
|
|
895
|
+
elif source_id in source_ids:
|
|
896
|
+
report.add(
|
|
897
|
+
rel,
|
|
898
|
+
"warning",
|
|
899
|
+
"W-SOURCE-ID",
|
|
900
|
+
f"duplicate source id: {source_id!r}",
|
|
901
|
+
)
|
|
902
|
+
else:
|
|
903
|
+
source_ids.add(source_id)
|
|
904
|
+
if "resource" not in entry:
|
|
905
|
+
report.add(
|
|
906
|
+
rel,
|
|
907
|
+
"warning",
|
|
908
|
+
"W-SOURCE-RESOURCE",
|
|
909
|
+
f"`{label}.resource` is required",
|
|
910
|
+
)
|
|
911
|
+
else:
|
|
912
|
+
_check_path_value(
|
|
913
|
+
report, concept, entry.get("resource"), f"{label}.resource"
|
|
914
|
+
)
|
|
915
|
+
if "usage_count" in entry and not isinstance(
|
|
916
|
+
entry["usage_count"], (int, float)
|
|
917
|
+
):
|
|
918
|
+
report.add(
|
|
919
|
+
rel,
|
|
920
|
+
"warning",
|
|
921
|
+
"W-SOURCE-SIGNAL",
|
|
922
|
+
f"`{label}.usage_count` should be a number",
|
|
923
|
+
)
|
|
924
|
+
if "last_modified" in entry and parse_timestamp(
|
|
925
|
+
entry["last_modified"]
|
|
926
|
+
) is None:
|
|
927
|
+
report.add(
|
|
928
|
+
rel,
|
|
929
|
+
"warning",
|
|
930
|
+
"W-TIMESTAMP",
|
|
931
|
+
f"`{label}.last_modified` must be ISO 8601 with an offset",
|
|
932
|
+
)
|
|
933
|
+
if "author" in entry and not isinstance(entry["author"], str):
|
|
934
|
+
report.add(
|
|
935
|
+
rel,
|
|
936
|
+
"warning",
|
|
937
|
+
"W-SOURCE-SIGNAL",
|
|
938
|
+
f"`{label}.author` should be an actor string",
|
|
939
|
+
)
|
|
940
|
+
if "usage_window" in entry:
|
|
941
|
+
_validate_usage_window(
|
|
942
|
+
report, rel, entry["usage_window"], f"{label}.usage_window"
|
|
943
|
+
)
|
|
944
|
+
|
|
945
|
+
if "usage_window" in fm:
|
|
946
|
+
_validate_usage_window(
|
|
947
|
+
report, rel, fm["usage_window"], "usage_window"
|
|
948
|
+
)
|
|
949
|
+
|
|
950
|
+
footnote_body = strip_fenced(concept.body)
|
|
951
|
+
used_footnotes = set(_FOOTNOTE_USE_RE.findall(footnote_body)) - set(
|
|
952
|
+
_FOOTNOTE_DEF_RE.findall(footnote_body)
|
|
953
|
+
)
|
|
954
|
+
for label in sorted(used_footnotes):
|
|
955
|
+
if label not in source_ids:
|
|
956
|
+
report.add(
|
|
957
|
+
rel,
|
|
958
|
+
"warning",
|
|
959
|
+
"W-FOOTNOTE",
|
|
960
|
+
f"footnote [^{label}] has no matching sources[].id",
|
|
961
|
+
)
|
|
962
|
+
if "# Citations" in strip_fenced(concept.body):
|
|
963
|
+
report.add(
|
|
964
|
+
rel,
|
|
965
|
+
"warning",
|
|
966
|
+
"W-LEGACY",
|
|
967
|
+
"v0.1 `# Citations` section found; move provenance into `sources`",
|
|
968
|
+
)
|
|
969
|
+
|
|
970
|
+
_check_body_links(report, concept)
|
|
971
|
+
|
|
972
|
+
if "computation" in fm:
|
|
973
|
+
_check_path_value(report, concept, fm.get("computation"), "computation")
|
|
974
|
+
for key in ("executor", "attester"):
|
|
975
|
+
value = fm.get(key)
|
|
976
|
+
if isinstance(value, dict) and "resource" in value:
|
|
977
|
+
_check_path_value(
|
|
978
|
+
report, concept, value.get("resource"), f"{key}.resource"
|
|
979
|
+
)
|
|
980
|
+
|
|
981
|
+
if concept.type == "Attested Computation":
|
|
982
|
+
_validate_attested(report, concept)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def _validate_usage_window(
|
|
986
|
+
report: Report, rel: str, value: Any, label: str
|
|
987
|
+
) -> None:
|
|
988
|
+
if not isinstance(value, dict):
|
|
989
|
+
report.add(
|
|
990
|
+
rel, "warning", "W-USAGE-WINDOW", f"`{label}` must be a {{from, to}} mapping"
|
|
991
|
+
)
|
|
992
|
+
return
|
|
993
|
+
for key in ("from", "to"):
|
|
994
|
+
if key not in value:
|
|
995
|
+
report.add(
|
|
996
|
+
rel,
|
|
997
|
+
"warning",
|
|
998
|
+
"W-USAGE-WINDOW",
|
|
999
|
+
f"`{label}.{key}` is required",
|
|
1000
|
+
)
|
|
1001
|
+
elif parse_timestamp(value[key]) is None:
|
|
1002
|
+
report.add(
|
|
1003
|
+
rel,
|
|
1004
|
+
"warning",
|
|
1005
|
+
"W-TIMESTAMP",
|
|
1006
|
+
f"`{label}.{key}` must be ISO 8601 with an offset",
|
|
1007
|
+
)
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def _validate_index(report: Report, path: Path) -> None:
|
|
1011
|
+
bundle = report.bundle
|
|
1012
|
+
rel = rel_posix(path, bundle)
|
|
1013
|
+
try:
|
|
1014
|
+
doc = parse_document(path, bundle)
|
|
1015
|
+
except KnowledgeError as exc:
|
|
1016
|
+
report.add(rel, "error", "E-INDEX", str(exc))
|
|
1017
|
+
return
|
|
1018
|
+
|
|
1019
|
+
is_root = path.parent.resolve() == bundle.resolve()
|
|
1020
|
+
if doc.has_frontmatter:
|
|
1021
|
+
allowed = {"format_version"} if is_root else set()
|
|
1022
|
+
extra = [key for key in doc.frontmatter if key not in allowed]
|
|
1023
|
+
if extra or not is_root:
|
|
1024
|
+
report.add(
|
|
1025
|
+
rel,
|
|
1026
|
+
"warning",
|
|
1027
|
+
"W-INDEX-FRONTMATTER",
|
|
1028
|
+
"index.md has no frontmatter except an optional bundle-root `format_version`",
|
|
1029
|
+
)
|
|
1030
|
+
version = doc.frontmatter.get("format_version")
|
|
1031
|
+
if version is not None and not isinstance(version, str):
|
|
1032
|
+
report.add(
|
|
1033
|
+
rel,
|
|
1034
|
+
"warning",
|
|
1035
|
+
"W-INDEX-FRONTMATTER",
|
|
1036
|
+
"`format_version` must be a string",
|
|
1037
|
+
)
|
|
1038
|
+
|
|
1039
|
+
body = doc.body.strip()
|
|
1040
|
+
if not body:
|
|
1041
|
+
report.add(rel, "warning", "W-INDEX-SHAPE", "index.md is empty")
|
|
1042
|
+
else:
|
|
1043
|
+
if not re.search(r"^#\s+\S", body, re.M):
|
|
1044
|
+
report.add(
|
|
1045
|
+
rel,
|
|
1046
|
+
"warning",
|
|
1047
|
+
"W-INDEX-SHAPE",
|
|
1048
|
+
"index.md should group entries under `#` headings",
|
|
1049
|
+
)
|
|
1050
|
+
entry_re = re.compile(
|
|
1051
|
+
r"^\s*(?:[*-+]|\d+\.)\s+\[[^\]]+\]\([^)]+\)", re.M
|
|
1052
|
+
)
|
|
1053
|
+
if not entry_re.search(body):
|
|
1054
|
+
report.add(
|
|
1055
|
+
rel,
|
|
1056
|
+
"warning",
|
|
1057
|
+
"W-INDEX-SHAPE",
|
|
1058
|
+
"index.md should list concepts as markdown links",
|
|
1059
|
+
)
|
|
1060
|
+
for target in extract_links(body):
|
|
1061
|
+
status, _ = resolve_link(bundle, path, target)
|
|
1062
|
+
if status == "broken":
|
|
1063
|
+
report.add(
|
|
1064
|
+
rel, "warning", "W-LINK", f"link target not found: {target!r}"
|
|
1065
|
+
)
|
|
1066
|
+
elif status == "outside":
|
|
1067
|
+
report.add(
|
|
1068
|
+
rel, "warning", "W-LINK", f"link escapes the bundle: {target!r}"
|
|
1069
|
+
)
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _validate_log(report: Report, path: Path) -> None:
|
|
1073
|
+
bundle = report.bundle
|
|
1074
|
+
rel = rel_posix(path, bundle)
|
|
1075
|
+
try:
|
|
1076
|
+
doc = parse_document(path, bundle)
|
|
1077
|
+
except KnowledgeError as exc:
|
|
1078
|
+
report.add(rel, "error", "E-LOG", str(exc))
|
|
1079
|
+
return
|
|
1080
|
+
|
|
1081
|
+
headings = re.findall(r"^##\s+(.+?)\s*$", doc.body, re.M)
|
|
1082
|
+
if not headings:
|
|
1083
|
+
report.add(
|
|
1084
|
+
rel,
|
|
1085
|
+
"warning",
|
|
1086
|
+
"W-LOG-SHAPE",
|
|
1087
|
+
"log.md should group entries under ISO `YYYY-MM-DD` headings",
|
|
1088
|
+
)
|
|
1089
|
+
dates: list[str] = []
|
|
1090
|
+
for heading in headings:
|
|
1091
|
+
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", heading):
|
|
1092
|
+
report.add(
|
|
1093
|
+
rel,
|
|
1094
|
+
"warning",
|
|
1095
|
+
"W-LOG-DATE",
|
|
1096
|
+
f"log heading is not ISO YYYY-MM-DD: {heading!r}",
|
|
1097
|
+
)
|
|
1098
|
+
continue
|
|
1099
|
+
try:
|
|
1100
|
+
datetime.strptime(heading, "%Y-%m-%d")
|
|
1101
|
+
except ValueError:
|
|
1102
|
+
report.add(
|
|
1103
|
+
rel,
|
|
1104
|
+
"warning",
|
|
1105
|
+
"W-LOG-DATE",
|
|
1106
|
+
f"log heading is not a valid date: {heading!r}",
|
|
1107
|
+
)
|
|
1108
|
+
continue
|
|
1109
|
+
dates.append(heading)
|
|
1110
|
+
if dates != sorted(dates, reverse=True):
|
|
1111
|
+
report.add(
|
|
1112
|
+
rel,
|
|
1113
|
+
"warning",
|
|
1114
|
+
"W-LOG-ORDER",
|
|
1115
|
+
"log entries should be newest first",
|
|
1116
|
+
)
|
|
1117
|
+
|
|
1118
|
+
for target in extract_links(doc.body):
|
|
1119
|
+
status, _ = resolve_link(bundle, path, target)
|
|
1120
|
+
if status == "broken":
|
|
1121
|
+
report.add(
|
|
1122
|
+
rel, "warning", "W-LINK", f"link target not found: {target!r}"
|
|
1123
|
+
)
|
|
1124
|
+
elif status == "outside":
|
|
1125
|
+
report.add(
|
|
1126
|
+
rel, "warning", "W-LINK", f"link escapes the bundle: {target!r}"
|
|
1127
|
+
)
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def validate_bundle(
|
|
1131
|
+
bundle: Path, now: datetime, warn_missing_index: bool = False
|
|
1132
|
+
) -> Report:
|
|
1133
|
+
bundle = bundle.resolve()
|
|
1134
|
+
if not bundle.is_dir():
|
|
1135
|
+
raise KnowledgeError(f"bundle directory not found: {bundle}")
|
|
1136
|
+
report = Report(bundle, now)
|
|
1137
|
+
concept_dirs: set[Path] = set()
|
|
1138
|
+
|
|
1139
|
+
for path in iter_markdown(bundle):
|
|
1140
|
+
rel = rel_posix(path, bundle)
|
|
1141
|
+
if path.name == "index.md":
|
|
1142
|
+
_validate_index(report, path)
|
|
1143
|
+
continue
|
|
1144
|
+
if path.name == "log.md":
|
|
1145
|
+
_validate_log(report, path)
|
|
1146
|
+
continue
|
|
1147
|
+
concept_dirs.add(path.parent)
|
|
1148
|
+
try:
|
|
1149
|
+
doc = parse_document(path, bundle)
|
|
1150
|
+
except KnowledgeError as exc:
|
|
1151
|
+
report.add(rel, "error", "E-PARSE", str(exc))
|
|
1152
|
+
continue
|
|
1153
|
+
if not doc.has_frontmatter:
|
|
1154
|
+
report.add(
|
|
1155
|
+
rel,
|
|
1156
|
+
"error",
|
|
1157
|
+
"E-NO-FRONTMATTER",
|
|
1158
|
+
"concept document must start with a YAML frontmatter block",
|
|
1159
|
+
)
|
|
1160
|
+
continue
|
|
1161
|
+
concept = Concept(path, doc.rel, doc.frontmatter, doc.body)
|
|
1162
|
+
report.concepts.append(concept)
|
|
1163
|
+
_validate_concept(report, concept)
|
|
1164
|
+
|
|
1165
|
+
if warn_missing_index:
|
|
1166
|
+
for directory in sorted(concept_dirs):
|
|
1167
|
+
index_path = directory / "index.md"
|
|
1168
|
+
if not index_path.exists():
|
|
1169
|
+
report.add(
|
|
1170
|
+
rel_posix(index_path, bundle),
|
|
1171
|
+
"warning",
|
|
1172
|
+
"W-NO-INDEX",
|
|
1173
|
+
"directory has concepts but no index.md",
|
|
1174
|
+
)
|
|
1175
|
+
|
|
1176
|
+
return report
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
# ---------------------------------------------------------------------------
|
|
1180
|
+
# Index generation
|
|
1181
|
+
# ---------------------------------------------------------------------------
|
|
1182
|
+
|
|
1183
|
+
|
|
1184
|
+
def _index_target(name: str) -> str:
|
|
1185
|
+
if any(char in name for char in " ()<>"):
|
|
1186
|
+
return f"<{name}>"
|
|
1187
|
+
return name
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def _escape_link_text(text: str) -> str:
|
|
1191
|
+
return one_line(text).replace("]", "\\]")
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
def _render_index(
|
|
1195
|
+
bundle: Path,
|
|
1196
|
+
directory: Path,
|
|
1197
|
+
concepts_by_dir: dict[Path, list[Concept]],
|
|
1198
|
+
content_dirs: set[Path],
|
|
1199
|
+
frontmatter: dict[str, Any],
|
|
1200
|
+
) -> str:
|
|
1201
|
+
concepts = concepts_by_dir.get(directory, [])
|
|
1202
|
+
groups: dict[str, list[Concept]] = defaultdict(list)
|
|
1203
|
+
for concept in concepts:
|
|
1204
|
+
groups[concept.type or "Other"].append(concept)
|
|
1205
|
+
|
|
1206
|
+
sections: list[str] = []
|
|
1207
|
+
for group in sorted(groups):
|
|
1208
|
+
lines = [f"# {group}", ""]
|
|
1209
|
+
for concept in sorted(
|
|
1210
|
+
groups[group], key=lambda item: (item.title.casefold(), item.id)
|
|
1211
|
+
):
|
|
1212
|
+
description = (
|
|
1213
|
+
f" - {one_line(concept.description)}" if concept.description else ""
|
|
1214
|
+
)
|
|
1215
|
+
lines.append(
|
|
1216
|
+
f"* [{_escape_link_text(concept.title)}]"
|
|
1217
|
+
f"({_index_target(concept.path.name)}){description}"
|
|
1218
|
+
)
|
|
1219
|
+
sections.append("\n".join(lines))
|
|
1220
|
+
|
|
1221
|
+
subdirs = sorted(
|
|
1222
|
+
[
|
|
1223
|
+
child
|
|
1224
|
+
for child in directory.iterdir()
|
|
1225
|
+
if child.is_dir() and child in content_dirs
|
|
1226
|
+
],
|
|
1227
|
+
key=lambda item: item.name.casefold(),
|
|
1228
|
+
)
|
|
1229
|
+
if subdirs:
|
|
1230
|
+
lines = ["# Subdirectories", ""]
|
|
1231
|
+
for child in subdirs:
|
|
1232
|
+
child_concepts = concepts_by_dir.get(child, [])
|
|
1233
|
+
description = ""
|
|
1234
|
+
if len(child_concepts) == 1 and child_concepts[0].description:
|
|
1235
|
+
description = f" - {one_line(child_concepts[0].description)}"
|
|
1236
|
+
lines.append(
|
|
1237
|
+
f"* [{child.name}]({_index_target(child.name + '/index.md')})"
|
|
1238
|
+
f"{description}"
|
|
1239
|
+
)
|
|
1240
|
+
sections.append("\n".join(lines))
|
|
1241
|
+
|
|
1242
|
+
body = "\n\n".join(sections)
|
|
1243
|
+
if body:
|
|
1244
|
+
body += "\n"
|
|
1245
|
+
prefix = dump_frontmatter(frontmatter) if frontmatter else ""
|
|
1246
|
+
return prefix + body
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
def plan_indexes(
|
|
1250
|
+
bundle: Path, now: datetime
|
|
1251
|
+
) -> tuple[list[dict[str, Any]], list[str]]:
|
|
1252
|
+
bundle = bundle.resolve()
|
|
1253
|
+
if not bundle.is_dir():
|
|
1254
|
+
raise KnowledgeError(f"bundle directory not found: {bundle}")
|
|
1255
|
+
concepts, _ = load_concepts(bundle, now)
|
|
1256
|
+
concepts_by_dir: dict[Path, list[Concept]] = defaultdict(list)
|
|
1257
|
+
for concept in concepts:
|
|
1258
|
+
concepts_by_dir[concept.path.parent].append(concept)
|
|
1259
|
+
|
|
1260
|
+
content_dirs: set[Path] = set()
|
|
1261
|
+
for directory in concepts_by_dir:
|
|
1262
|
+
current = directory
|
|
1263
|
+
while True:
|
|
1264
|
+
content_dirs.add(current)
|
|
1265
|
+
if current == bundle:
|
|
1266
|
+
break
|
|
1267
|
+
current = current.parent
|
|
1268
|
+
|
|
1269
|
+
plan: list[dict[str, Any]] = []
|
|
1270
|
+
notes: list[str] = []
|
|
1271
|
+
for directory in sorted(content_dirs, key=lambda item: str(item)):
|
|
1272
|
+
index_path = directory / "index.md"
|
|
1273
|
+
frontmatter: dict[str, Any] = {}
|
|
1274
|
+
if index_path.exists():
|
|
1275
|
+
try:
|
|
1276
|
+
existing = parse_document(index_path, bundle)
|
|
1277
|
+
except KnowledgeError as exc:
|
|
1278
|
+
notes.append(f"{rel_posix(index_path, bundle)}: {exc}")
|
|
1279
|
+
existing = None
|
|
1280
|
+
if existing is not None and existing.has_frontmatter:
|
|
1281
|
+
if directory == bundle:
|
|
1282
|
+
frontmatter = dict(existing.frontmatter)
|
|
1283
|
+
else:
|
|
1284
|
+
notes.append(
|
|
1285
|
+
f"{rel_posix(index_path, bundle)}: dropped non-root "
|
|
1286
|
+
"index frontmatter (the format allows it only at the bundle root)"
|
|
1287
|
+
)
|
|
1288
|
+
rendered = _render_index(
|
|
1289
|
+
bundle, directory, concepts_by_dir, content_dirs, frontmatter
|
|
1290
|
+
)
|
|
1291
|
+
if not rendered.replace("\n", "").strip():
|
|
1292
|
+
continue
|
|
1293
|
+
current = index_path.read_text(encoding="utf-8") if index_path.exists() else ""
|
|
1294
|
+
plan.append(
|
|
1295
|
+
{
|
|
1296
|
+
"path": rel_posix(index_path, bundle),
|
|
1297
|
+
"changed": current != rendered,
|
|
1298
|
+
"text": rendered,
|
|
1299
|
+
"exists": index_path.exists(),
|
|
1300
|
+
}
|
|
1301
|
+
)
|
|
1302
|
+
return plan, notes
|
|
1303
|
+
|
|
1304
|
+
|
|
1305
|
+
# ---------------------------------------------------------------------------
|
|
1306
|
+
# Log updates
|
|
1307
|
+
# ---------------------------------------------------------------------------
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def _append_log_body(body: str, entry: str, date_str: str) -> str:
|
|
1311
|
+
heading_re = re.compile(r"^##\s+(\S+)\s*$", re.M)
|
|
1312
|
+
matches = list(heading_re.finditer(body))
|
|
1313
|
+
for index, match in enumerate(matches):
|
|
1314
|
+
if match.group(1) != date_str:
|
|
1315
|
+
continue
|
|
1316
|
+
start = match.end()
|
|
1317
|
+
end = matches[index + 1].start() if index + 1 < len(matches) else len(body)
|
|
1318
|
+
section = body[start:end].rstrip()
|
|
1319
|
+
replacement = section + ("\n\n" if section else "\n") + entry + "\n\n"
|
|
1320
|
+
return body[:start] + replacement + body[end:]
|
|
1321
|
+
|
|
1322
|
+
block = f"## {date_str}\n\n{entry}\n\n"
|
|
1323
|
+
if matches:
|
|
1324
|
+
insert_at = matches[0].start()
|
|
1325
|
+
return body[:insert_at] + block + body[insert_at:]
|
|
1326
|
+
body = body.rstrip()
|
|
1327
|
+
return (body + "\n\n" if body else "") + block
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def append_log(
|
|
1331
|
+
bundle: Path, rel_file: str, message: str, kind: str, date_str: str
|
|
1332
|
+
) -> Path:
|
|
1333
|
+
bundle = bundle.resolve()
|
|
1334
|
+
path = (bundle / rel_file).resolve()
|
|
1335
|
+
try:
|
|
1336
|
+
path.relative_to(bundle)
|
|
1337
|
+
except ValueError as exc:
|
|
1338
|
+
raise KnowledgeError(f"log path escapes the bundle: {rel_file}") from exc
|
|
1339
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1340
|
+
|
|
1341
|
+
if path.exists():
|
|
1342
|
+
doc = parse_document(path, bundle)
|
|
1343
|
+
frontmatter, body = dict(doc.frontmatter), doc.body
|
|
1344
|
+
else:
|
|
1345
|
+
frontmatter, body = {}, "# Update Log\n\n"
|
|
1346
|
+
|
|
1347
|
+
entry = f"* **{kind}**: {one_line(message)}"
|
|
1348
|
+
body = _append_log_body(body, entry, date_str)
|
|
1349
|
+
if frontmatter:
|
|
1350
|
+
path.write_text(dump_frontmatter(frontmatter) + body, encoding="utf-8")
|
|
1351
|
+
else:
|
|
1352
|
+
path.write_text(body, encoding="utf-8")
|
|
1353
|
+
return path
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
# ---------------------------------------------------------------------------
|
|
1357
|
+
# Commands
|
|
1358
|
+
# ---------------------------------------------------------------------------
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
def _summary_counts(concepts: list[Concept], now: datetime) -> dict[str, int]:
|
|
1362
|
+
return {
|
|
1363
|
+
"concepts": len(concepts),
|
|
1364
|
+
"stale": sum(1 for concept in concepts if is_stale(concept.frontmatter, now)),
|
|
1365
|
+
"unverified": sum(
|
|
1366
|
+
1 for concept in concepts if trust_tier(concept.frontmatter) == "unverified"
|
|
1367
|
+
),
|
|
1368
|
+
"deprecated": sum(
|
|
1369
|
+
1
|
|
1370
|
+
for concept in concepts
|
|
1371
|
+
if concept.frontmatter.get("status") == "deprecated"
|
|
1372
|
+
),
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
|
|
1376
|
+
def cmd_where(args: argparse.Namespace) -> int:
|
|
1377
|
+
start = Path(args.start).resolve() if args.start else Path.cwd()
|
|
1378
|
+
project, global_path, repo = default_bundle_paths(start)
|
|
1379
|
+
selected = existing_default_bundle(start)
|
|
1380
|
+
write_scope, write_path = write_default_bundle(start)
|
|
1381
|
+
project_exists = bool(project and project.is_dir())
|
|
1382
|
+
global_exists = global_path.is_dir()
|
|
1383
|
+
payload = {
|
|
1384
|
+
"repo": str(repo) if repo else None,
|
|
1385
|
+
"project": {
|
|
1386
|
+
"path": str(project) if project else None,
|
|
1387
|
+
"exists": project_exists,
|
|
1388
|
+
},
|
|
1389
|
+
"global": {"path": str(global_path), "exists": global_exists},
|
|
1390
|
+
"selected": (
|
|
1391
|
+
{"scope": selected[0], "path": str(selected[1])}
|
|
1392
|
+
if selected is not None
|
|
1393
|
+
else None
|
|
1394
|
+
),
|
|
1395
|
+
"write_default": {"scope": write_scope, "path": str(write_path)},
|
|
1396
|
+
}
|
|
1397
|
+
if args.json:
|
|
1398
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1399
|
+
else:
|
|
1400
|
+
print(f"repo {repo if repo else '-'}")
|
|
1401
|
+
print(
|
|
1402
|
+
f"project {project if project else '-'} "
|
|
1403
|
+
f"{'exists' if project_exists else 'missing'}"
|
|
1404
|
+
)
|
|
1405
|
+
print(
|
|
1406
|
+
f"global {global_path} "
|
|
1407
|
+
f"{'exists' if global_exists else 'missing'}"
|
|
1408
|
+
)
|
|
1409
|
+
if selected is not None:
|
|
1410
|
+
print(f"use {selected[1]} ({selected[0]})")
|
|
1411
|
+
else:
|
|
1412
|
+
print("use none")
|
|
1413
|
+
print(f"write {write_path} ({write_scope}; run `init` to create)")
|
|
1414
|
+
return 0 if selected is not None else 1
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
1418
|
+
using_default = _is_default_bundle_arg(args.bundle)
|
|
1419
|
+
bundle = resolve_cli_bundle(args.bundle, allow_missing=True)
|
|
1420
|
+
if using_default:
|
|
1421
|
+
print(f"using default bundle: {bundle}")
|
|
1422
|
+
bundle.mkdir(parents=True, exist_ok=True)
|
|
1423
|
+
index_path = bundle / "index.md"
|
|
1424
|
+
log_path = bundle / "log.md"
|
|
1425
|
+
name = args.name or bundle.name
|
|
1426
|
+
date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
1427
|
+
|
|
1428
|
+
if not index_path.exists() or args.force:
|
|
1429
|
+
index_path.write_text(
|
|
1430
|
+
dump_frontmatter({"format_version": FORMAT_VERSION})
|
|
1431
|
+
+ f"# {name}\n\nKnowledge bundle format v{FORMAT_VERSION}.\n",
|
|
1432
|
+
encoding="utf-8",
|
|
1433
|
+
)
|
|
1434
|
+
if not log_path.exists() or args.force:
|
|
1435
|
+
log_path.write_text(
|
|
1436
|
+
f"# Bundle Update Log\n\n## {date_str}\n\n"
|
|
1437
|
+
f"* **Initialization**: Created knowledge bundle `{name}`.\n",
|
|
1438
|
+
encoding="utf-8",
|
|
1439
|
+
)
|
|
1440
|
+
print(f"initialized knowledge bundle at {bundle}")
|
|
1441
|
+
return 0
|
|
1442
|
+
|
|
1443
|
+
|
|
1444
|
+
def _concept_path(bundle: Path, concept_id: str) -> Path:
|
|
1445
|
+
raw = concept_id.strip().lstrip("/")
|
|
1446
|
+
if raw.endswith(".md"):
|
|
1447
|
+
raw = raw[:-3]
|
|
1448
|
+
parts = [part for part in raw.split("/") if part]
|
|
1449
|
+
if not parts:
|
|
1450
|
+
raise KnowledgeError("concept id is empty")
|
|
1451
|
+
for part in parts:
|
|
1452
|
+
if part in (".", "..") or not re.fullmatch(
|
|
1453
|
+
r"[A-Za-z0-9_][A-Za-z0-9_.-]*", part
|
|
1454
|
+
):
|
|
1455
|
+
raise KnowledgeError(f"invalid concept id segment: {part!r}")
|
|
1456
|
+
if parts[-1] in ("index", "log"):
|
|
1457
|
+
raise KnowledgeError("index and log are reserved filenames, not concepts")
|
|
1458
|
+
return bundle.joinpath(*parts[:-1], parts[-1] + ".md")
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
def _fence_language(runtime: str) -> str:
|
|
1462
|
+
return {
|
|
1463
|
+
"bigquery": "sql",
|
|
1464
|
+
"postgres": "sql",
|
|
1465
|
+
"dbt": "sql",
|
|
1466
|
+
"duckdb": "sql",
|
|
1467
|
+
"python": "python",
|
|
1468
|
+
"looker": "lookml",
|
|
1469
|
+
}.get(runtime.casefold(), "")
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
def _parse_parameter(raw: str) -> dict[str, Any]:
|
|
1473
|
+
parts = raw.split(":", 2)
|
|
1474
|
+
if len(parts) < 2 or not parts[0].strip() or not parts[1].strip():
|
|
1475
|
+
raise KnowledgeError(
|
|
1476
|
+
f"--param expects name:type[:required], got {raw!r}"
|
|
1477
|
+
)
|
|
1478
|
+
required = True
|
|
1479
|
+
if len(parts) == 3:
|
|
1480
|
+
required = parts[2].strip().casefold() not in {
|
|
1481
|
+
"false",
|
|
1482
|
+
"no",
|
|
1483
|
+
"0",
|
|
1484
|
+
"optional",
|
|
1485
|
+
}
|
|
1486
|
+
return {
|
|
1487
|
+
"name": parts[0].strip(),
|
|
1488
|
+
"type": parts[1].strip(),
|
|
1489
|
+
"required": required,
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
|
|
1493
|
+
def cmd_new(args: argparse.Namespace) -> int:
|
|
1494
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1495
|
+
if not bundle.is_dir():
|
|
1496
|
+
raise KnowledgeError(f"bundle directory not found: {bundle} (run `init` first)")
|
|
1497
|
+
path = _concept_path(bundle, args.concept_id)
|
|
1498
|
+
rel = rel_posix(path, bundle)
|
|
1499
|
+
if path.exists() and not args.force:
|
|
1500
|
+
raise KnowledgeError(f"refusing to overwrite existing concept: {rel}")
|
|
1501
|
+
|
|
1502
|
+
concept_type = args.concept_type.strip()
|
|
1503
|
+
if not concept_type:
|
|
1504
|
+
raise KnowledgeError("--type must be non-empty")
|
|
1505
|
+
# `type: Attested Computation` implies the computation contract. Switching
|
|
1506
|
+
# automatically avoids silently ignoring --runtime/--executor/--attester.
|
|
1507
|
+
template = "computation" if concept_type == "Attested Computation" else args.template
|
|
1508
|
+
if template == "computation" and concept_type != "Attested Computation":
|
|
1509
|
+
raise KnowledgeError(
|
|
1510
|
+
"--template computation requires --type 'Attested Computation'"
|
|
1511
|
+
)
|
|
1512
|
+
if template == "basic" and any(
|
|
1513
|
+
[args.runtime, args.param, args.computation, args.executor, args.attester]
|
|
1514
|
+
):
|
|
1515
|
+
raise KnowledgeError(
|
|
1516
|
+
"--runtime/--param/--computation/--executor/--attester require "
|
|
1517
|
+
"--template computation"
|
|
1518
|
+
)
|
|
1519
|
+
|
|
1520
|
+
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
1521
|
+
frontmatter: dict[str, Any] = {
|
|
1522
|
+
"type": concept_type,
|
|
1523
|
+
"title": args.title or slug_title(path.stem),
|
|
1524
|
+
}
|
|
1525
|
+
if args.description:
|
|
1526
|
+
frontmatter["description"] = one_line(args.description)
|
|
1527
|
+
if args.resource:
|
|
1528
|
+
frontmatter["resource"] = args.resource
|
|
1529
|
+
tags = [tag.strip() for tag in args.tags.split(",") if tag.strip()]
|
|
1530
|
+
if tags:
|
|
1531
|
+
frontmatter["tags"] = tags
|
|
1532
|
+
if args.status:
|
|
1533
|
+
frontmatter["status"] = args.status
|
|
1534
|
+
frontmatter["generated"] = {"by": args.actor, "at": now}
|
|
1535
|
+
|
|
1536
|
+
if template == "computation":
|
|
1537
|
+
if not args.runtime:
|
|
1538
|
+
raise KnowledgeError("Attested Computation requires --runtime")
|
|
1539
|
+
frontmatter["runtime"] = args.runtime
|
|
1540
|
+
if args.param:
|
|
1541
|
+
frontmatter["parameters"] = [
|
|
1542
|
+
_parse_parameter(raw) for raw in args.param
|
|
1543
|
+
]
|
|
1544
|
+
if args.computation:
|
|
1545
|
+
frontmatter["computation"] = args.computation
|
|
1546
|
+
if args.executor:
|
|
1547
|
+
receipt = [
|
|
1548
|
+
item.strip() for item in args.receipt.split(",") if item.strip()
|
|
1549
|
+
]
|
|
1550
|
+
frontmatter["executor"] = {
|
|
1551
|
+
"resource": args.executor,
|
|
1552
|
+
"receipt": receipt or ["result"],
|
|
1553
|
+
}
|
|
1554
|
+
if args.attester:
|
|
1555
|
+
frontmatter["attester"] = {"resource": args.attester}
|
|
1556
|
+
|
|
1557
|
+
if args.body_file:
|
|
1558
|
+
try:
|
|
1559
|
+
body = args.body_file.read_text(encoding="utf-8")
|
|
1560
|
+
except OSError as exc:
|
|
1561
|
+
raise KnowledgeError(f"cannot read --body-file: {exc}") from exc
|
|
1562
|
+
elif args.computation:
|
|
1563
|
+
body = (
|
|
1564
|
+
"# Computation\n\n"
|
|
1565
|
+
f"The sanctioned computation lives in `{args.computation}`.\n"
|
|
1566
|
+
)
|
|
1567
|
+
else:
|
|
1568
|
+
language = _fence_language(args.runtime)
|
|
1569
|
+
comment = "#" if language == "python" else "--"
|
|
1570
|
+
body = (
|
|
1571
|
+
"# Computation\n\n"
|
|
1572
|
+
f"```{language}\n"
|
|
1573
|
+
f"{comment} Replace with the sanctioned computation. "
|
|
1574
|
+
"Only declared parameters may be bound.\n"
|
|
1575
|
+
"```\n"
|
|
1576
|
+
)
|
|
1577
|
+
elif args.body_file:
|
|
1578
|
+
try:
|
|
1579
|
+
body = args.body_file.read_text(encoding="utf-8")
|
|
1580
|
+
except OSError as exc:
|
|
1581
|
+
raise KnowledgeError(f"cannot read --body-file: {exc}") from exc
|
|
1582
|
+
else:
|
|
1583
|
+
body = (
|
|
1584
|
+
"# Overview\n\n"
|
|
1585
|
+
"Describe what this concept is, what it represents, and how it is used.\n"
|
|
1586
|
+
)
|
|
1587
|
+
|
|
1588
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1589
|
+
path.write_text(dump_frontmatter(frontmatter) + body, encoding="utf-8")
|
|
1590
|
+
print(f"created {rel}")
|
|
1591
|
+
|
|
1592
|
+
if args.index:
|
|
1593
|
+
plan, _ = plan_indexes(bundle, datetime.now(timezone.utc))
|
|
1594
|
+
changed = [item for item in plan if item["changed"]]
|
|
1595
|
+
for item in changed:
|
|
1596
|
+
(bundle / item["path"]).write_text(item["text"], encoding="utf-8")
|
|
1597
|
+
print(f"updated {len(changed)} index.md file(s)")
|
|
1598
|
+
if args.log:
|
|
1599
|
+
log_path = append_log(
|
|
1600
|
+
bundle,
|
|
1601
|
+
"log.md",
|
|
1602
|
+
f"Created [{frontmatter['title']}](/{rel}).",
|
|
1603
|
+
"Creation",
|
|
1604
|
+
datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
1605
|
+
)
|
|
1606
|
+
print(f"updated {rel_posix(log_path, bundle)}")
|
|
1607
|
+
return 0
|
|
1608
|
+
|
|
1609
|
+
|
|
1610
|
+
def cmd_validate(args: argparse.Namespace) -> int:
|
|
1611
|
+
now = parse_now(args.now)
|
|
1612
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1613
|
+
report = validate_bundle(
|
|
1614
|
+
bundle, now, warn_missing_index=args.warn_missing_index
|
|
1615
|
+
)
|
|
1616
|
+
errors = [item for item in report.findings if item.level == "error"]
|
|
1617
|
+
warnings = [item for item in report.findings if item.level == "warning"]
|
|
1618
|
+
counts = _summary_counts(report.concepts, now)
|
|
1619
|
+
|
|
1620
|
+
if args.json:
|
|
1621
|
+
payload = {
|
|
1622
|
+
"tool": "knowledge.py",
|
|
1623
|
+
"format_version": FORMAT_VERSION,
|
|
1624
|
+
"bundle": str(report.bundle),
|
|
1625
|
+
"now": now.isoformat(),
|
|
1626
|
+
"conformant": not errors,
|
|
1627
|
+
"summary": {
|
|
1628
|
+
**counts,
|
|
1629
|
+
"errors": len(errors),
|
|
1630
|
+
"warnings": len(warnings),
|
|
1631
|
+
},
|
|
1632
|
+
"diagnostics": [
|
|
1633
|
+
{
|
|
1634
|
+
"path": item.path,
|
|
1635
|
+
"level": item.level,
|
|
1636
|
+
"code": item.code,
|
|
1637
|
+
"message": item.message,
|
|
1638
|
+
}
|
|
1639
|
+
for item in report.findings
|
|
1640
|
+
],
|
|
1641
|
+
"concepts": [
|
|
1642
|
+
concept.summary(now) for concept in report.concepts
|
|
1643
|
+
],
|
|
1644
|
+
}
|
|
1645
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1646
|
+
else:
|
|
1647
|
+
grouped: dict[str, list[Finding]] = defaultdict(list)
|
|
1648
|
+
for item in report.findings:
|
|
1649
|
+
grouped[item.path].append(item)
|
|
1650
|
+
for path in sorted(grouped):
|
|
1651
|
+
print(path)
|
|
1652
|
+
for item in grouped[path]:
|
|
1653
|
+
print(f" {item.level:<7} {item.code}: {item.message}")
|
|
1654
|
+
if report.findings:
|
|
1655
|
+
print()
|
|
1656
|
+
print(
|
|
1657
|
+
f"Summary: {counts['concepts']} concept(s), {len(errors)} error(s), "
|
|
1658
|
+
f"{len(warnings)} warning(s) "
|
|
1659
|
+
f"({counts['stale']} stale, {counts['unverified']} unverified, "
|
|
1660
|
+
f"{counts['deprecated']} deprecated)"
|
|
1661
|
+
)
|
|
1662
|
+
if not errors:
|
|
1663
|
+
print("Conformant with format v0.2 (warnings are advisory).")
|
|
1664
|
+
|
|
1665
|
+
if errors:
|
|
1666
|
+
return 1
|
|
1667
|
+
if args.strict and warnings:
|
|
1668
|
+
return 1
|
|
1669
|
+
return 0
|
|
1670
|
+
|
|
1671
|
+
|
|
1672
|
+
def cmd_index(args: argparse.Namespace) -> int:
|
|
1673
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1674
|
+
plan, notes = plan_indexes(bundle, datetime.now(timezone.utc))
|
|
1675
|
+
changed = [item for item in plan if item["changed"]]
|
|
1676
|
+
unchanged = [item for item in plan if not item["changed"]]
|
|
1677
|
+
|
|
1678
|
+
if args.write:
|
|
1679
|
+
for item in changed:
|
|
1680
|
+
path = Path(bundle).resolve() / item["path"]
|
|
1681
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1682
|
+
path.write_text(item["text"], encoding="utf-8")
|
|
1683
|
+
|
|
1684
|
+
if args.json:
|
|
1685
|
+
payload = {
|
|
1686
|
+
"written": [item["path"] for item in changed] if args.write else [],
|
|
1687
|
+
"changed": [item["path"] for item in changed],
|
|
1688
|
+
"unchanged": [item["path"] for item in unchanged],
|
|
1689
|
+
"notes": notes,
|
|
1690
|
+
"checked": True,
|
|
1691
|
+
}
|
|
1692
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1693
|
+
else:
|
|
1694
|
+
for note in notes:
|
|
1695
|
+
print(f"note: {note}", file=sys.stderr)
|
|
1696
|
+
if changed:
|
|
1697
|
+
verb = "wrote" if args.write else "would write"
|
|
1698
|
+
print(f"{verb} {len(changed)} index.md file(s):")
|
|
1699
|
+
for item in changed:
|
|
1700
|
+
print(f" {item['path']}")
|
|
1701
|
+
else:
|
|
1702
|
+
print("index.md files are up to date")
|
|
1703
|
+
if unchanged and not changed:
|
|
1704
|
+
print(f" ({len(unchanged)} unchanged)")
|
|
1705
|
+
|
|
1706
|
+
if args.check and changed:
|
|
1707
|
+
return 1
|
|
1708
|
+
return 0
|
|
1709
|
+
|
|
1710
|
+
|
|
1711
|
+
def _filter_concepts(
|
|
1712
|
+
concepts: list[Concept], args: argparse.Namespace, now: datetime
|
|
1713
|
+
) -> list[Concept]:
|
|
1714
|
+
selected = concepts
|
|
1715
|
+
if args.concept_type:
|
|
1716
|
+
wanted = args.concept_type.casefold()
|
|
1717
|
+
selected = [
|
|
1718
|
+
concept for concept in selected if concept.type.casefold() == wanted
|
|
1719
|
+
]
|
|
1720
|
+
if args.tag:
|
|
1721
|
+
wanted = args.tag.casefold()
|
|
1722
|
+
selected = [
|
|
1723
|
+
concept
|
|
1724
|
+
for concept in selected
|
|
1725
|
+
if any(tag.casefold() == wanted for tag in concept.tags)
|
|
1726
|
+
]
|
|
1727
|
+
if args.status:
|
|
1728
|
+
selected = [
|
|
1729
|
+
concept for concept in selected if concept.status == args.status
|
|
1730
|
+
]
|
|
1731
|
+
if args.trust:
|
|
1732
|
+
selected = [
|
|
1733
|
+
concept
|
|
1734
|
+
for concept in selected
|
|
1735
|
+
if trust_tier(concept.frontmatter) == args.trust
|
|
1736
|
+
]
|
|
1737
|
+
if args.stale:
|
|
1738
|
+
selected = [
|
|
1739
|
+
concept
|
|
1740
|
+
for concept in selected
|
|
1741
|
+
if is_stale(concept.frontmatter, now)
|
|
1742
|
+
]
|
|
1743
|
+
return selected
|
|
1744
|
+
|
|
1745
|
+
|
|
1746
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
1747
|
+
now = parse_now(args.now)
|
|
1748
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1749
|
+
concepts, skipped = load_concepts(bundle, now)
|
|
1750
|
+
concepts = _filter_concepts(concepts, args, now)
|
|
1751
|
+
concepts.sort(key=lambda concept: concept.id)
|
|
1752
|
+
|
|
1753
|
+
rows = [concept.summary(now) for concept in concepts]
|
|
1754
|
+
if args.json:
|
|
1755
|
+
print(
|
|
1756
|
+
json.dumps(
|
|
1757
|
+
{"concepts": rows, "skipped": skipped},
|
|
1758
|
+
ensure_ascii=False,
|
|
1759
|
+
indent=2,
|
|
1760
|
+
)
|
|
1761
|
+
)
|
|
1762
|
+
return 0
|
|
1763
|
+
|
|
1764
|
+
if not args.no_header:
|
|
1765
|
+
print("ID\tTYPE\tTITLE\tSTATUS\tTRUST\tSTALE\tTAGS\tDESCRIPTION")
|
|
1766
|
+
for row in rows:
|
|
1767
|
+
print(
|
|
1768
|
+
"\t".join(
|
|
1769
|
+
[
|
|
1770
|
+
row["id"],
|
|
1771
|
+
row["type"],
|
|
1772
|
+
one_line(row["title"]),
|
|
1773
|
+
row["status"],
|
|
1774
|
+
row["trust"],
|
|
1775
|
+
"yes" if row["stale"] else "no",
|
|
1776
|
+
",".join(row["tags"]),
|
|
1777
|
+
row["description"],
|
|
1778
|
+
]
|
|
1779
|
+
)
|
|
1780
|
+
)
|
|
1781
|
+
for item in skipped:
|
|
1782
|
+
print(
|
|
1783
|
+
f"warning: skipped {item['path']}: {item['error']}",
|
|
1784
|
+
file=sys.stderr,
|
|
1785
|
+
)
|
|
1786
|
+
return 0
|
|
1787
|
+
|
|
1788
|
+
|
|
1789
|
+
def _links_for(
|
|
1790
|
+
bundle: Path, concept: Concept
|
|
1791
|
+
) -> list[dict[str, Any]]:
|
|
1792
|
+
links: list[dict[str, Any]] = []
|
|
1793
|
+
for target in extract_links(concept.body):
|
|
1794
|
+
status, resolved = resolve_link(bundle, concept.path, target)
|
|
1795
|
+
if status is None:
|
|
1796
|
+
continue
|
|
1797
|
+
target_id = None
|
|
1798
|
+
if (
|
|
1799
|
+
resolved is not None
|
|
1800
|
+
and resolved.suffix == ".md"
|
|
1801
|
+
and resolved.name not in RESERVED_FILENAMES
|
|
1802
|
+
):
|
|
1803
|
+
target_id = concept_id_from_rel(resolved.as_posix())
|
|
1804
|
+
links.append(
|
|
1805
|
+
{
|
|
1806
|
+
"target": target,
|
|
1807
|
+
"id": target_id,
|
|
1808
|
+
"resolved": status == "ok" and target_id is not None,
|
|
1809
|
+
}
|
|
1810
|
+
)
|
|
1811
|
+
return links
|
|
1812
|
+
|
|
1813
|
+
|
|
1814
|
+
def _show_payload(
|
|
1815
|
+
bundle: Path, concepts: list[Concept], concept: Concept, now: datetime
|
|
1816
|
+
) -> dict[str, Any]:
|
|
1817
|
+
backlinks = []
|
|
1818
|
+
for other in concepts:
|
|
1819
|
+
if other.id == concept.id:
|
|
1820
|
+
continue
|
|
1821
|
+
for link in _links_for(bundle, other):
|
|
1822
|
+
if link["id"] == concept.id:
|
|
1823
|
+
backlinks.append(other.id)
|
|
1824
|
+
break
|
|
1825
|
+
return {
|
|
1826
|
+
**concept.summary(now),
|
|
1827
|
+
"frontmatter": concept.frontmatter,
|
|
1828
|
+
"body": concept.body,
|
|
1829
|
+
"verified": normalize_verified(concept.frontmatter),
|
|
1830
|
+
"links": _links_for(bundle, concept),
|
|
1831
|
+
"backlinks": sorted(set(backlinks)),
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
|
|
1835
|
+
def cmd_show(args: argparse.Namespace) -> int:
|
|
1836
|
+
now = parse_now(args.now)
|
|
1837
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1838
|
+
concepts, skipped = load_concepts(bundle, now)
|
|
1839
|
+
wanted = args.concept_id.strip().lstrip("/")
|
|
1840
|
+
if wanted.endswith(".md"):
|
|
1841
|
+
wanted = wanted[:-3]
|
|
1842
|
+
concept = next((item for item in concepts if item.id == wanted), None)
|
|
1843
|
+
if concept is None:
|
|
1844
|
+
for item in skipped:
|
|
1845
|
+
if concept_id_from_rel(item["path"]) == wanted:
|
|
1846
|
+
raise KnowledgeError(f"{wanted}: {item['error']}")
|
|
1847
|
+
raise KnowledgeError(f"concept not found: {wanted}")
|
|
1848
|
+
|
|
1849
|
+
if args.json:
|
|
1850
|
+
print(
|
|
1851
|
+
json.dumps(
|
|
1852
|
+
_show_payload(bundle, concepts, concept, now),
|
|
1853
|
+
ensure_ascii=False,
|
|
1854
|
+
indent=2,
|
|
1855
|
+
)
|
|
1856
|
+
)
|
|
1857
|
+
else:
|
|
1858
|
+
print(concept.path.read_text(encoding="utf-8-sig"), end="")
|
|
1859
|
+
return 0
|
|
1860
|
+
|
|
1861
|
+
|
|
1862
|
+
def _snippet(text: str, query: str, width: int = 100) -> str:
|
|
1863
|
+
flat = one_line(text)
|
|
1864
|
+
position = flat.casefold().find(query.casefold())
|
|
1865
|
+
if position < 0:
|
|
1866
|
+
return flat[:width]
|
|
1867
|
+
start = max(0, position - width // 3)
|
|
1868
|
+
end = min(len(flat), position + len(query) + width // 2)
|
|
1869
|
+
prefix = "…" if start else ""
|
|
1870
|
+
suffix = "…" if end < len(flat) else ""
|
|
1871
|
+
return f"{prefix}{flat[start:end]}{suffix}"
|
|
1872
|
+
|
|
1873
|
+
|
|
1874
|
+
def cmd_search(args: argparse.Namespace) -> int:
|
|
1875
|
+
now = parse_now(args.now)
|
|
1876
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1877
|
+
concepts, skipped = load_concepts(bundle, now)
|
|
1878
|
+
query = args.query.casefold()
|
|
1879
|
+
scored: list[tuple[int, Concept, str]] = []
|
|
1880
|
+
for concept in concepts:
|
|
1881
|
+
fields = [
|
|
1882
|
+
(concept.title, 8),
|
|
1883
|
+
(concept.id, 5),
|
|
1884
|
+
(" ".join(concept.tags), 5),
|
|
1885
|
+
(concept.description, 4),
|
|
1886
|
+
(concept.body, 1),
|
|
1887
|
+
]
|
|
1888
|
+
score = 0
|
|
1889
|
+
first_match = ""
|
|
1890
|
+
for text, weight in fields:
|
|
1891
|
+
if not text:
|
|
1892
|
+
continue
|
|
1893
|
+
occurrences = text.casefold().count(query)
|
|
1894
|
+
if occurrences:
|
|
1895
|
+
score += occurrences * weight
|
|
1896
|
+
if not first_match:
|
|
1897
|
+
first_match = text
|
|
1898
|
+
if score:
|
|
1899
|
+
scored.append((score, concept, first_match))
|
|
1900
|
+
scored.sort(key=lambda item: (-item[0], item[1].id))
|
|
1901
|
+
scored = scored[: args.limit]
|
|
1902
|
+
|
|
1903
|
+
if args.json:
|
|
1904
|
+
print(
|
|
1905
|
+
json.dumps(
|
|
1906
|
+
{
|
|
1907
|
+
"query": args.query,
|
|
1908
|
+
"results": [
|
|
1909
|
+
{
|
|
1910
|
+
**concept.summary(now),
|
|
1911
|
+
"score": score,
|
|
1912
|
+
"snippet": _snippet(text, args.query),
|
|
1913
|
+
}
|
|
1914
|
+
for score, concept, text in scored
|
|
1915
|
+
],
|
|
1916
|
+
"skipped": skipped,
|
|
1917
|
+
},
|
|
1918
|
+
ensure_ascii=False,
|
|
1919
|
+
indent=2,
|
|
1920
|
+
)
|
|
1921
|
+
)
|
|
1922
|
+
return 0
|
|
1923
|
+
|
|
1924
|
+
print("SCORE\tID\tTITLE\tSNIPPET")
|
|
1925
|
+
for score, concept, text in scored:
|
|
1926
|
+
print(
|
|
1927
|
+
f"{score}\t{concept.id}\t{one_line(concept.title)}\t"
|
|
1928
|
+
f"{_snippet(text, args.query)}"
|
|
1929
|
+
)
|
|
1930
|
+
for item in skipped:
|
|
1931
|
+
print(
|
|
1932
|
+
f"warning: skipped {item['path']}: {item['error']}",
|
|
1933
|
+
file=sys.stderr,
|
|
1934
|
+
)
|
|
1935
|
+
return 0
|
|
1936
|
+
|
|
1937
|
+
|
|
1938
|
+
def _dot_escape(value: str) -> str:
|
|
1939
|
+
return value.replace("\\", "\\\\").replace('"', '\\"')
|
|
1940
|
+
|
|
1941
|
+
|
|
1942
|
+
def cmd_graph(args: argparse.Namespace) -> int:
|
|
1943
|
+
now = parse_now(args.now)
|
|
1944
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1945
|
+
concepts, skipped = load_concepts(bundle, now)
|
|
1946
|
+
nodes = [concept.summary(now) for concept in concepts]
|
|
1947
|
+
edges: list[dict[str, Any]] = []
|
|
1948
|
+
seen: set[tuple[str, str]] = set()
|
|
1949
|
+
for concept in concepts:
|
|
1950
|
+
for link in _links_for(bundle, concept):
|
|
1951
|
+
target = link["id"] or link["target"]
|
|
1952
|
+
key = (concept.id, str(target))
|
|
1953
|
+
if key in seen:
|
|
1954
|
+
continue
|
|
1955
|
+
seen.add(key)
|
|
1956
|
+
edges.append(
|
|
1957
|
+
{
|
|
1958
|
+
"source": concept.id,
|
|
1959
|
+
"target": target,
|
|
1960
|
+
"resolved": link["resolved"],
|
|
1961
|
+
}
|
|
1962
|
+
)
|
|
1963
|
+
|
|
1964
|
+
if args.format == "dot":
|
|
1965
|
+
print("digraph knowledge {")
|
|
1966
|
+
print(" rankdir=LR;")
|
|
1967
|
+
for node in nodes:
|
|
1968
|
+
print(
|
|
1969
|
+
f' "{_dot_escape(node["id"])}" '
|
|
1970
|
+
f'[label="{_dot_escape(node["title"])}", '
|
|
1971
|
+
f'shape=box, tooltip="{_dot_escape(node["type"])}"];'
|
|
1972
|
+
)
|
|
1973
|
+
for edge in edges:
|
|
1974
|
+
if edge["resolved"]:
|
|
1975
|
+
print(
|
|
1976
|
+
f' "{_dot_escape(edge["source"])}" -> '
|
|
1977
|
+
f'"{_dot_escape(str(edge["target"]))}";'
|
|
1978
|
+
)
|
|
1979
|
+
print("}")
|
|
1980
|
+
else:
|
|
1981
|
+
print(
|
|
1982
|
+
json.dumps(
|
|
1983
|
+
{"nodes": nodes, "edges": edges, "skipped": skipped},
|
|
1984
|
+
ensure_ascii=False,
|
|
1985
|
+
indent=2,
|
|
1986
|
+
)
|
|
1987
|
+
)
|
|
1988
|
+
return 0
|
|
1989
|
+
|
|
1990
|
+
|
|
1991
|
+
def cmd_log(args: argparse.Namespace) -> int:
|
|
1992
|
+
date_str = args.date or datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
1993
|
+
try:
|
|
1994
|
+
datetime.strptime(date_str, "%Y-%m-%d")
|
|
1995
|
+
except ValueError as exc:
|
|
1996
|
+
raise KnowledgeError(f"--date must be YYYY-MM-DD, got {date_str!r}") from exc
|
|
1997
|
+
bundle = resolve_cli_bundle(args.bundle)
|
|
1998
|
+
path = append_log(
|
|
1999
|
+
bundle, args.file, args.message, args.kind, date_str
|
|
2000
|
+
)
|
|
2001
|
+
print(f"updated {path}")
|
|
2002
|
+
return 0
|
|
2003
|
+
|
|
2004
|
+
|
|
2005
|
+
# ---------------------------------------------------------------------------
|
|
2006
|
+
# CLI
|
|
2007
|
+
# ---------------------------------------------------------------------------
|
|
2008
|
+
|
|
2009
|
+
|
|
2010
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
2011
|
+
parser = argparse.ArgumentParser(
|
|
2012
|
+
prog="knowledge.py",
|
|
2013
|
+
description=(
|
|
2014
|
+
"Create, validate, and consume knowledge bundles (format v0.2)."
|
|
2015
|
+
),
|
|
2016
|
+
)
|
|
2017
|
+
parser.add_argument(
|
|
2018
|
+
"--version", action="version", version=f"knowledge.py 1.0 (format v{FORMAT_VERSION})"
|
|
2019
|
+
)
|
|
2020
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
2021
|
+
|
|
2022
|
+
init_parser = subparsers.add_parser(
|
|
2023
|
+
"init", help="create a bundle skeleton (default: project/global path)"
|
|
2024
|
+
)
|
|
2025
|
+
init_parser.add_argument("bundle", nargs="?", type=Path, help=BUNDLE_HELP)
|
|
2026
|
+
init_parser.add_argument("--name", help="display name (default: directory name)")
|
|
2027
|
+
init_parser.add_argument(
|
|
2028
|
+
"--force", action="store_true", help="overwrite existing index.md/log.md"
|
|
2029
|
+
)
|
|
2030
|
+
init_parser.set_defaults(func=cmd_init)
|
|
2031
|
+
|
|
2032
|
+
where_parser = subparsers.add_parser(
|
|
2033
|
+
"where", help="resolve the default project/global bundle path"
|
|
2034
|
+
)
|
|
2035
|
+
where_parser.add_argument(
|
|
2036
|
+
"--start", help="directory to start repo discovery from (default: cwd)"
|
|
2037
|
+
)
|
|
2038
|
+
where_parser.add_argument("--json", action="store_true")
|
|
2039
|
+
where_parser.set_defaults(func=cmd_where)
|
|
2040
|
+
|
|
2041
|
+
new_parser = subparsers.add_parser("new", help="create one concept document")
|
|
2042
|
+
new_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2043
|
+
new_parser.add_argument("concept_id", help="e.g. tables/orders")
|
|
2044
|
+
new_parser.add_argument("--type", dest="concept_type", required=True)
|
|
2045
|
+
new_parser.add_argument("--title")
|
|
2046
|
+
new_parser.add_argument("--description", default="")
|
|
2047
|
+
new_parser.add_argument("--tags", default="", help="comma-separated")
|
|
2048
|
+
new_parser.add_argument("--resource")
|
|
2049
|
+
new_parser.add_argument(
|
|
2050
|
+
"--status", choices=["draft", "stable", "deprecated"]
|
|
2051
|
+
)
|
|
2052
|
+
new_parser.add_argument(
|
|
2053
|
+
"--actor",
|
|
2054
|
+
default="knowledge-skill/1.0",
|
|
2055
|
+
help="generated.by actor (default: knowledge-skill/1.0)",
|
|
2056
|
+
)
|
|
2057
|
+
new_parser.add_argument(
|
|
2058
|
+
"--template", choices=["basic", "computation"], default="basic"
|
|
2059
|
+
)
|
|
2060
|
+
new_parser.add_argument("--runtime", help="required for the computation template")
|
|
2061
|
+
new_parser.add_argument(
|
|
2062
|
+
"--param",
|
|
2063
|
+
action="append",
|
|
2064
|
+
default=[],
|
|
2065
|
+
help="name:type[:required] (repeatable)",
|
|
2066
|
+
)
|
|
2067
|
+
new_parser.add_argument("--computation", help="path to a computation file")
|
|
2068
|
+
new_parser.add_argument("--executor", help="path to run instructions/code")
|
|
2069
|
+
new_parser.add_argument("--attester", help="path to deterministic check code")
|
|
2070
|
+
new_parser.add_argument(
|
|
2071
|
+
"--receipt", default="result", help="comma-separated receipt fields"
|
|
2072
|
+
)
|
|
2073
|
+
new_parser.add_argument("--body-file", type=Path)
|
|
2074
|
+
new_parser.add_argument("--force", action="store_true")
|
|
2075
|
+
new_parser.add_argument(
|
|
2076
|
+
"--index", action="store_true", help="regenerate index.md files after writing"
|
|
2077
|
+
)
|
|
2078
|
+
new_parser.add_argument(
|
|
2079
|
+
"--log", action="store_true", help="append a Creation entry to log.md"
|
|
2080
|
+
)
|
|
2081
|
+
new_parser.set_defaults(func=cmd_new)
|
|
2082
|
+
|
|
2083
|
+
validate_parser = subparsers.add_parser(
|
|
2084
|
+
"validate", help="check format conformance and authoring quality"
|
|
2085
|
+
)
|
|
2086
|
+
validate_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2087
|
+
validate_parser.add_argument("--json", action="store_true")
|
|
2088
|
+
validate_parser.add_argument(
|
|
2089
|
+
"--strict", action="store_true", help="exit 1 when warnings are present"
|
|
2090
|
+
)
|
|
2091
|
+
validate_parser.add_argument(
|
|
2092
|
+
"--now", help="ISO instant used for stale_after checks"
|
|
2093
|
+
)
|
|
2094
|
+
validate_parser.add_argument("--warn-missing-index", action="store_true")
|
|
2095
|
+
validate_parser.set_defaults(func=cmd_validate)
|
|
2096
|
+
|
|
2097
|
+
index_parser = subparsers.add_parser(
|
|
2098
|
+
"index", help="generate or check index.md files"
|
|
2099
|
+
)
|
|
2100
|
+
index_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2101
|
+
index_parser.add_argument("--write", action="store_true")
|
|
2102
|
+
index_parser.add_argument(
|
|
2103
|
+
"--check", action="store_true", help="exit 1 when index.md files drift"
|
|
2104
|
+
)
|
|
2105
|
+
index_parser.add_argument("--json", action="store_true")
|
|
2106
|
+
index_parser.set_defaults(func=cmd_index)
|
|
2107
|
+
|
|
2108
|
+
list_parser = subparsers.add_parser(
|
|
2109
|
+
"list", help="list concepts with trust, freshness, and tags"
|
|
2110
|
+
)
|
|
2111
|
+
list_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2112
|
+
list_parser.add_argument("--type", dest="concept_type")
|
|
2113
|
+
list_parser.add_argument("--tag")
|
|
2114
|
+
list_parser.add_argument(
|
|
2115
|
+
"--status", choices=["draft", "stable", "deprecated"]
|
|
2116
|
+
)
|
|
2117
|
+
list_parser.add_argument(
|
|
2118
|
+
"--trust", choices=sorted(TRUST_TIERS)
|
|
2119
|
+
)
|
|
2120
|
+
list_parser.add_argument("--stale", action="store_true")
|
|
2121
|
+
list_parser.add_argument("--now")
|
|
2122
|
+
list_parser.add_argument("--json", action="store_true")
|
|
2123
|
+
list_parser.add_argument("--no-header", action="store_true")
|
|
2124
|
+
list_parser.set_defaults(func=cmd_list)
|
|
2125
|
+
|
|
2126
|
+
show_parser = subparsers.add_parser(
|
|
2127
|
+
"show", help="print one concept (raw by default, structured with --json)"
|
|
2128
|
+
)
|
|
2129
|
+
show_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2130
|
+
show_parser.add_argument("concept_id")
|
|
2131
|
+
show_parser.add_argument("--json", action="store_true")
|
|
2132
|
+
show_parser.add_argument("--now")
|
|
2133
|
+
show_parser.set_defaults(func=cmd_show)
|
|
2134
|
+
|
|
2135
|
+
search_parser = subparsers.add_parser(
|
|
2136
|
+
"search", help="search titles, tags, descriptions, and bodies"
|
|
2137
|
+
)
|
|
2138
|
+
search_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2139
|
+
search_parser.add_argument("query")
|
|
2140
|
+
search_parser.add_argument("-n", "--limit", type=int, default=10)
|
|
2141
|
+
search_parser.add_argument("--json", action="store_true")
|
|
2142
|
+
search_parser.add_argument("--now")
|
|
2143
|
+
search_parser.set_defaults(func=cmd_search)
|
|
2144
|
+
|
|
2145
|
+
graph_parser = subparsers.add_parser(
|
|
2146
|
+
"graph", help="export the concept link graph (JSON or DOT)"
|
|
2147
|
+
)
|
|
2148
|
+
graph_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2149
|
+
graph_parser.add_argument("--format", choices=["json", "dot"], default="json")
|
|
2150
|
+
graph_parser.add_argument("--now")
|
|
2151
|
+
graph_parser.set_defaults(func=cmd_graph)
|
|
2152
|
+
|
|
2153
|
+
log_parser = subparsers.add_parser("log", help="append an entry to log.md")
|
|
2154
|
+
log_parser.add_argument("bundle", type=Path, help=BUNDLE_HELP)
|
|
2155
|
+
log_parser.add_argument("--message", required=True)
|
|
2156
|
+
log_parser.add_argument("--kind", default="Update")
|
|
2157
|
+
log_parser.add_argument("--date", help="YYYY-MM-DD (default: today UTC)")
|
|
2158
|
+
log_parser.add_argument("--file", default="log.md")
|
|
2159
|
+
log_parser.set_defaults(func=cmd_log)
|
|
2160
|
+
|
|
2161
|
+
return parser
|
|
2162
|
+
|
|
2163
|
+
|
|
2164
|
+
def main(argv: list[str] | None = None) -> int:
|
|
2165
|
+
parser = build_parser()
|
|
2166
|
+
args = parser.parse_args(argv)
|
|
2167
|
+
try:
|
|
2168
|
+
return int(args.func(args))
|
|
2169
|
+
except KnowledgeError as exc:
|
|
2170
|
+
print(f"knowledge.py: {exc}", file=sys.stderr)
|
|
2171
|
+
return 2
|
|
2172
|
+
|
|
2173
|
+
|
|
2174
|
+
if __name__ == "__main__":
|
|
2175
|
+
raise SystemExit(main())
|