@rvdbreemen/adr-kit-opencode 0.52.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/.claude-plugin/plugin.json +29 -0
- package/LICENSE +21 -0
- package/README.md +850 -0
- package/bin/adr +1552 -0
- package/bin/adr-audit +454 -0
- package/bin/adr-context +584 -0
- package/bin/adr-discover +546 -0
- package/bin/adr-doctor +166 -0
- package/bin/adr-generate-scripts +421 -0
- package/bin/adr-grill-signal +131 -0
- package/bin/adr-guardian +1263 -0
- package/bin/adr-index +199 -0
- package/bin/adr-judge +2832 -0
- package/bin/adr-judge-precommit +87 -0
- package/bin/adr-lint +2087 -0
- package/bin/adr-mcp +1093 -0
- package/bin/adr-migrate +644 -0
- package/bin/adr-quality +275 -0
- package/bin/adr-readiness +211 -0
- package/bin/adr-readiness-ci +111 -0
- package/bin/adr-related +401 -0
- package/bin/adr-renumber +254 -0
- package/bin/adr-retire +467 -0
- package/bin/adr-settings +399 -0
- package/bin/adr-status +797 -0
- package/bin/adr-suggest +803 -0
- package/bin/adr-watch +674 -0
- package/bin/adr_catalog.py +536 -0
- package/bin/adr_config.py +280 -0
- package/bin/adr_doctor_checks.py +407 -0
- package/bin/adr_doctor_core.py +342 -0
- package/bin/adr_doctor_models.py +186 -0
- package/bin/adr_doctor_probes.py +216 -0
- package/bin/adr_format.py +786 -0
- package/bin/adr_grill_signal.py +123 -0
- package/bin/adr_guardian_queue.py +218 -0
- package/bin/adr_history_scan.py +278 -0
- package/bin/adr_index_core.py +443 -0
- package/bin/adr_llm.py +333 -0
- package/bin/adr_llm_judge_migration.py +314 -0
- package/bin/adr_quality_core.py +674 -0
- package/bin/adr_query.py +678 -0
- package/bin/adr_readiness.py +442 -0
- package/bin/adr_readiness_ci.py +123 -0
- package/bin/adr_regex.py +165 -0
- package/bin/adr_regex_worker.py +30 -0
- package/bin/adr_retrieval_health.py +385 -0
- package/bin/adr_schema.py +448 -0
- package/bin/adr_state.py +172 -0
- package/bin/bump-version +71 -0
- package/clients/workflows.json +229 -0
- package/hooks/__init__.py +1 -0
- package/hooks/adapters/__init__.py +13 -0
- package/hooks/adapters/claude.py +27 -0
- package/hooks/adapters/codex.py +26 -0
- package/hooks/adapters/copilot.py +11 -0
- package/hooks/adr-hook.py +128 -0
- package/hooks/adr_hook_core.py +843 -0
- package/hooks/adr_pr_guard.py +367 -0
- package/instructions/ADR-guide.md +48 -0
- package/instructions/adr.coding.md +82 -0
- package/instructions/adr.review.md +182 -0
- package/opencode/plugin.ts +451 -0
- package/package.json +41 -0
- package/schemas/adr-context-probes.schema.json +56 -0
- package/schemas/adr-enforcement.schema.json +57 -0
- package/schemas/adr-frontmatter.schema.json +144 -0
- package/schemas/adr-index.schema.json +276 -0
- package/schemas/adr-kit-config.schema.json +371 -0
- package/schemas/adr-readiness.schema.json +41 -0
- package/schemas/client-capabilities.schema.json +503 -0
- package/schemas/client-certification.schema.json +101 -0
- package/schemas/doctor-output.schema.json +92 -0
- package/schemas/marketplace.json.schema.json +70 -0
- package/schemas/plugin.json.schema.json +67 -0
- package/scripts/adr_settings.py +239 -0
- package/scripts/benchmark-adr-grilling.py +323 -0
- package/scripts/benchmark-client-generation.py +178 -0
- package/scripts/build-client-adapters.py +139 -0
- package/scripts/bump-version.py +304 -0
- package/scripts/check-branch-sync.py +243 -0
- package/scripts/check-release-version.py +81 -0
- package/scripts/client_certification.py +153 -0
- package/scripts/client_evidence.py +280 -0
- package/scripts/client_generation.py +288 -0
- package/scripts/client_generation_artifacts.py +351 -0
- package/scripts/client_generation_model.py +173 -0
- package/scripts/client_generation_state.py +260 -0
- package/scripts/client_support_matrix.py +360 -0
- package/scripts/install-agent-envs.py +300 -0
- package/scripts/probe-client-events.py +183 -0
- package/scripts/project_setup.py +379 -0
- package/scripts/refresh-otgw-corpus.py +219 -0
- package/scripts/settings.py +81 -0
- package/scripts/setup-project.py +205 -0
- package/scripts/sync-agent-plugins.py +17 -0
- package/scripts/version_sites.py +377 -0
- package/skills/adr/SKILL.md +780 -0
- package/skills/audit/SKILL.md +103 -0
- package/skills/context/SKILL.md +77 -0
- package/skills/grill/SKILL.md +84 -0
- package/skills/grill/agents/openai.yaml +4 -0
- package/skills/guardian/SKILL.md +316 -0
- package/skills/init/SKILL.md +499 -0
- package/skills/install-hooks/SKILL.md +154 -0
- package/skills/judge/SKILL.md +168 -0
- package/skills/lint/SKILL.md +321 -0
- package/skills/migrate/SKILL.md +313 -0
- package/skills/related/SKILL.md +62 -0
- package/skills/retire/SKILL.md +41 -0
- package/skills/review/SKILL.md +167 -0
- package/skills/settings/SKILL.md +73 -0
- package/skills/setup/SKILL.md +128 -0
- package/skills/supersede/SKILL.md +136 -0
- package/skills/upgrade/SKILL.md +273 -0
- package/templates/adr-kit-guide.md +354 -0
- package/templates/adr-template.canonical.md +115 -0
- package/templates/adr-template.madr.md +131 -0
- package/templates/adr-template.md +131 -0
- package/templates/adr-template.nygard.md +111 -0
- package/templates/cc-settings/guardian-hook-entry.json +9 -0
- package/templates/githooks/pre-commit +337 -0
- package/templates/github-workflows/adr-audit.yml +58 -0
- package/templates/github-workflows/adr-guardian-audit.yml +133 -0
- package/templates/github-workflows/adr-index-check.yml +30 -0
- package/templates/github-workflows/adr-judge.yml +31 -0
- package/templates/github-workflows/adr-readiness.yml +18 -0
- package/templates/validate_adr_template.py +38 -0
- package/templates/validate_adr_template.sh +74 -0
package/bin/adr_query.py
ADDED
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
"""Deterministic index-first ADR retrieval.
|
|
2
|
+
|
|
3
|
+
``index-first-retrieval`` is the named verification gate for ADR-014.
|
|
4
|
+
Markdown ADRs remain authoritative; this module queries their generated graph
|
|
5
|
+
projection and uses the semantic Markdown loader only as a visible fallback.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fnmatch
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
|
15
|
+
|
|
16
|
+
INDEX_FIRST_RETRIEVAL_GATE = "index-first-retrieval"
|
|
17
|
+
SUPPORTED_SCHEMA_VERSIONS = {1, 2}
|
|
18
|
+
SUPPORTED_STATUSES = {
|
|
19
|
+
"Accepted",
|
|
20
|
+
"Proposed",
|
|
21
|
+
"Superseded",
|
|
22
|
+
"Rejected",
|
|
23
|
+
"Deprecated",
|
|
24
|
+
"Amended",
|
|
25
|
+
"Unknown",
|
|
26
|
+
}
|
|
27
|
+
SUPPORTED_AUTHORITIES = {"governing", "advisory", "historical"}
|
|
28
|
+
HISTORICAL_STATUSES = {
|
|
29
|
+
"Superseded",
|
|
30
|
+
"Rejected",
|
|
31
|
+
"Deprecated",
|
|
32
|
+
"Amended",
|
|
33
|
+
"Unknown",
|
|
34
|
+
}
|
|
35
|
+
FIELD_WEIGHTS = {
|
|
36
|
+
"path": 1.0,
|
|
37
|
+
"symbols": 0.95,
|
|
38
|
+
"components": 0.90,
|
|
39
|
+
"topics": 0.75,
|
|
40
|
+
"aliases": 0.70,
|
|
41
|
+
"title": 0.60,
|
|
42
|
+
"decision_contract": 0.50,
|
|
43
|
+
"decision_summary": 0.40,
|
|
44
|
+
}
|
|
45
|
+
MAX_SUPPORTING_RESULTS = 2
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class IndexQueryError(RuntimeError):
|
|
49
|
+
"""Raised when strict index retrieval cannot use the generated graph."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def extract_keywords(value: str) -> List[str]:
|
|
53
|
+
return sorted(
|
|
54
|
+
{
|
|
55
|
+
token
|
|
56
|
+
for token in re.split(r"[^a-z0-9_.:/-]+", value.casefold())
|
|
57
|
+
if len(token) >= 3
|
|
58
|
+
}
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _normalized_text(value: object) -> str:
|
|
63
|
+
return re.sub(r"\s+", " ", str(value or "")).strip().casefold()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _string_list(value: object) -> List[str]:
|
|
67
|
+
if not isinstance(value, list):
|
|
68
|
+
return []
|
|
69
|
+
return [item for item in value if isinstance(item, str) and item.strip()]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _empty_contract() -> Dict[str, List[str]]:
|
|
73
|
+
return {
|
|
74
|
+
"must": [],
|
|
75
|
+
"must_not": [],
|
|
76
|
+
"exceptions": [],
|
|
77
|
+
"verification": [],
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _normalize_contract(value: object) -> Dict[str, List[str]]:
|
|
82
|
+
contract = _empty_contract()
|
|
83
|
+
if not isinstance(value, dict):
|
|
84
|
+
return contract
|
|
85
|
+
for key in contract:
|
|
86
|
+
contract[key] = _string_list(value.get(key))[:20]
|
|
87
|
+
return contract
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _validate_node(node: object, version: int) -> Dict:
|
|
91
|
+
if not isinstance(node, dict):
|
|
92
|
+
raise IndexQueryError("ADR graph contains a non-object ADR record")
|
|
93
|
+
required = {
|
|
94
|
+
"id",
|
|
95
|
+
"title",
|
|
96
|
+
"path",
|
|
97
|
+
"format",
|
|
98
|
+
"status",
|
|
99
|
+
"date",
|
|
100
|
+
"decision_summary",
|
|
101
|
+
"scope",
|
|
102
|
+
"metadata",
|
|
103
|
+
}
|
|
104
|
+
missing = sorted(required - set(node))
|
|
105
|
+
if missing:
|
|
106
|
+
raise IndexQueryError(
|
|
107
|
+
"ADR graph record is missing required field(s): " + ", ".join(missing)
|
|
108
|
+
)
|
|
109
|
+
adr_id = node.get("id")
|
|
110
|
+
if not isinstance(adr_id, str) or not re.fullmatch(r"ADR-\d{3,4}", adr_id):
|
|
111
|
+
raise IndexQueryError(f"ADR graph record has invalid id: {adr_id!r}")
|
|
112
|
+
if not isinstance(node.get("title"), str) or not isinstance(node.get("path"), str):
|
|
113
|
+
raise IndexQueryError(f"{adr_id} title/path must be strings")
|
|
114
|
+
if not isinstance(node.get("scope"), dict) or not isinstance(
|
|
115
|
+
node["scope"].get("path_globs"), list
|
|
116
|
+
):
|
|
117
|
+
raise IndexQueryError(f"{adr_id} scope.path_globs must be a list")
|
|
118
|
+
if not isinstance(node.get("metadata"), dict):
|
|
119
|
+
raise IndexQueryError(f"{adr_id} metadata must be an object")
|
|
120
|
+
|
|
121
|
+
normalized = dict(node)
|
|
122
|
+
if version == 2:
|
|
123
|
+
retrieval_required = {
|
|
124
|
+
"topics",
|
|
125
|
+
"aliases",
|
|
126
|
+
"components",
|
|
127
|
+
"symbols",
|
|
128
|
+
"context_scope",
|
|
129
|
+
"decision_contract",
|
|
130
|
+
}
|
|
131
|
+
missing_retrieval = sorted(retrieval_required - set(node))
|
|
132
|
+
if missing_retrieval:
|
|
133
|
+
raise IndexQueryError(
|
|
134
|
+
f"{adr_id} schema-v2 retrieval field(s) missing: "
|
|
135
|
+
+ ", ".join(missing_retrieval)
|
|
136
|
+
)
|
|
137
|
+
for field in ("topics", "aliases", "components", "symbols"):
|
|
138
|
+
value = node.get(field, [])
|
|
139
|
+
if version == 2 and (
|
|
140
|
+
not isinstance(value, list)
|
|
141
|
+
or not all(isinstance(item, str) and item for item in value)
|
|
142
|
+
):
|
|
143
|
+
raise IndexQueryError(f"{adr_id} {field} must be a list")
|
|
144
|
+
normalized[field] = _string_list(value)
|
|
145
|
+
context_scope = node.get("context_scope", "selective")
|
|
146
|
+
if version == 2 and context_scope not in {"global", "selective"}:
|
|
147
|
+
raise IndexQueryError(f"{adr_id} context_scope is invalid")
|
|
148
|
+
normalized["context_scope"] = (
|
|
149
|
+
context_scope if context_scope in {"global", "selective"} else "selective"
|
|
150
|
+
)
|
|
151
|
+
contract = node.get("decision_contract")
|
|
152
|
+
if version == 2:
|
|
153
|
+
contract_keys = {"must", "must_not", "exceptions", "verification"}
|
|
154
|
+
if (
|
|
155
|
+
not isinstance(contract, dict)
|
|
156
|
+
or set(contract) != contract_keys
|
|
157
|
+
or any(
|
|
158
|
+
not isinstance(contract.get(key), list)
|
|
159
|
+
or not all(
|
|
160
|
+
isinstance(item, str) and item
|
|
161
|
+
for item in contract.get(key, [])
|
|
162
|
+
)
|
|
163
|
+
for key in contract_keys
|
|
164
|
+
)
|
|
165
|
+
):
|
|
166
|
+
raise IndexQueryError(f"{adr_id} decision_contract is invalid")
|
|
167
|
+
normalized["decision_contract"] = _normalize_contract(contract)
|
|
168
|
+
return normalized
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _validate_relationship(value: object) -> Dict:
|
|
172
|
+
if not isinstance(value, dict):
|
|
173
|
+
raise IndexQueryError("ADR graph contains a non-object relationship")
|
|
174
|
+
required = {"source", "target", "type", "resolved"}
|
|
175
|
+
if not required <= set(value):
|
|
176
|
+
raise IndexQueryError("ADR graph relationship is incomplete")
|
|
177
|
+
if not all(isinstance(value.get(key), str) for key in ("source", "target", "type")):
|
|
178
|
+
raise IndexQueryError("ADR graph relationship identifiers must be strings")
|
|
179
|
+
if not isinstance(value.get("resolved"), bool):
|
|
180
|
+
raise IndexQueryError("ADR graph relationship resolved must be boolean")
|
|
181
|
+
return dict(value)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _index_path(adr_dir: Path) -> Path:
|
|
185
|
+
return adr_dir / "ADR-INDEX.json"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _is_stale(index_path: Path, adr_dir: Path) -> bool:
|
|
189
|
+
try:
|
|
190
|
+
index_mtime = index_path.stat().st_mtime_ns
|
|
191
|
+
source_mtimes = (
|
|
192
|
+
path.stat().st_mtime_ns
|
|
193
|
+
for path in adr_dir.glob("ADR-*.md")
|
|
194
|
+
if re.match(r"ADR-\d{1,4}-.*\.md$", path.name, re.IGNORECASE)
|
|
195
|
+
)
|
|
196
|
+
return any(mtime > index_mtime for mtime in source_mtimes)
|
|
197
|
+
except OSError as exc:
|
|
198
|
+
raise IndexQueryError(f"cannot inspect ADR graph freshness: {exc}") from exc
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def load_index_graph(adr_dir: Path) -> Tuple[List[Dict], List[Dict], int]:
|
|
202
|
+
path = _index_path(adr_dir)
|
|
203
|
+
if not path.is_file():
|
|
204
|
+
raise IndexQueryError(f"generated ADR graph is missing: {path}")
|
|
205
|
+
if _is_stale(path, adr_dir):
|
|
206
|
+
raise IndexQueryError(f"generated ADR graph is stale: {path}")
|
|
207
|
+
try:
|
|
208
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
209
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
210
|
+
raise IndexQueryError(f"generated ADR graph is invalid: {exc}") from exc
|
|
211
|
+
if not isinstance(payload, dict):
|
|
212
|
+
raise IndexQueryError("generated ADR graph root must be an object")
|
|
213
|
+
version = payload.get("schema_version")
|
|
214
|
+
if version not in SUPPORTED_SCHEMA_VERSIONS:
|
|
215
|
+
raise IndexQueryError(
|
|
216
|
+
f"unsupported ADR graph schema_version {version!r}; "
|
|
217
|
+
"supported versions are 1 and 2"
|
|
218
|
+
)
|
|
219
|
+
adrs = payload.get("adrs")
|
|
220
|
+
relationships = payload.get("relationships")
|
|
221
|
+
if not isinstance(adrs, list) or not isinstance(relationships, list):
|
|
222
|
+
raise IndexQueryError("generated ADR graph requires adrs and relationships arrays")
|
|
223
|
+
records = [_validate_node(node, version) for node in adrs]
|
|
224
|
+
ids = [record["id"] for record in records]
|
|
225
|
+
if len(ids) != len(set(ids)):
|
|
226
|
+
raise IndexQueryError("generated ADR graph contains duplicate ADR ids")
|
|
227
|
+
edges = [_validate_relationship(edge) for edge in relationships]
|
|
228
|
+
return records, edges, version
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _markdown_graph(adr_dir: Path) -> Tuple[List[Dict], List[Dict]]:
|
|
232
|
+
# Keep the semantic Markdown stack off the healthy index hot path. Its
|
|
233
|
+
# format/frontmatter imports are paid only for an explicit fallback.
|
|
234
|
+
from adr_catalog import build_relationships, load_adr_records, public_adr_node
|
|
235
|
+
|
|
236
|
+
records = load_adr_records(adr_dir)
|
|
237
|
+
return (
|
|
238
|
+
[public_adr_node(record) for record in records],
|
|
239
|
+
build_relationships(records),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _contract_values(record: Dict) -> List[str]:
|
|
244
|
+
contract = record.get("decision_contract", {})
|
|
245
|
+
if not isinstance(contract, dict):
|
|
246
|
+
return []
|
|
247
|
+
return [
|
|
248
|
+
item
|
|
249
|
+
for key in ("must", "must_not", "exceptions", "verification")
|
|
250
|
+
for item in _string_list(contract.get(key))
|
|
251
|
+
]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _explicit_matches(values: Iterable[str], explicit: Sequence[str]) -> List[str]:
|
|
255
|
+
requested = {_normalized_text(value) for value in explicit if str(value).strip()}
|
|
256
|
+
return sorted(
|
|
257
|
+
{
|
|
258
|
+
value
|
|
259
|
+
for value in values
|
|
260
|
+
if _normalized_text(value) in requested
|
|
261
|
+
},
|
|
262
|
+
key=lambda item: (item.casefold(), item),
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _lexical_matches(
|
|
267
|
+
values: Iterable[str],
|
|
268
|
+
normalized_query: str,
|
|
269
|
+
query_keywords: Sequence[str],
|
|
270
|
+
) -> Tuple[List[str], int]:
|
|
271
|
+
query_set = set(query_keywords)
|
|
272
|
+
matched_values: List[str] = []
|
|
273
|
+
matched_tokens = set()
|
|
274
|
+
for value in values:
|
|
275
|
+
normalized = _normalized_text(value)
|
|
276
|
+
direct = bool(
|
|
277
|
+
normalized
|
|
278
|
+
and normalized_query
|
|
279
|
+
and (
|
|
280
|
+
normalized in normalized_query
|
|
281
|
+
or normalized_query in normalized
|
|
282
|
+
)
|
|
283
|
+
)
|
|
284
|
+
overlap = set() if direct else query_set & set(extract_keywords(normalized))
|
|
285
|
+
if direct or overlap:
|
|
286
|
+
matched_values.append(value)
|
|
287
|
+
matched_tokens.update(query_set if direct else overlap)
|
|
288
|
+
return (
|
|
289
|
+
sorted(set(matched_values), key=lambda item: (item.casefold(), item)),
|
|
290
|
+
len(matched_tokens),
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _path_matches(globs: Iterable[str], paths: Sequence[str]) -> List[str]:
|
|
295
|
+
matches = set()
|
|
296
|
+
for raw_path in paths:
|
|
297
|
+
normalized_path = str(raw_path).replace("\\", "/")
|
|
298
|
+
for glob in globs:
|
|
299
|
+
normalized_glob = str(glob).replace("\\", "/")
|
|
300
|
+
if fnmatch.fnmatchcase(normalized_path.casefold(), normalized_glob.casefold()):
|
|
301
|
+
matches.add(str(glob))
|
|
302
|
+
return sorted(matches, key=lambda item: (item.casefold(), item))
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def score_record(
|
|
306
|
+
record: Dict,
|
|
307
|
+
query: str,
|
|
308
|
+
*,
|
|
309
|
+
paths: Sequence[str] = (),
|
|
310
|
+
symbols: Sequence[str] = (),
|
|
311
|
+
components: Sequence[str] = (),
|
|
312
|
+
topics: Sequence[str] = (),
|
|
313
|
+
_query_keywords: Optional[Sequence[str]] = None,
|
|
314
|
+
_normalized_query_value: Optional[str] = None,
|
|
315
|
+
) -> Dict:
|
|
316
|
+
"""Score one graph node from positive field evidence only."""
|
|
317
|
+
query_keywords = list(_query_keywords or extract_keywords(query))
|
|
318
|
+
normalized_query = (
|
|
319
|
+
_normalized_query_value
|
|
320
|
+
if _normalized_query_value is not None
|
|
321
|
+
else _normalized_text(query)
|
|
322
|
+
)
|
|
323
|
+
denominator = max(1, len(query_keywords))
|
|
324
|
+
signals: Dict[str, float] = {}
|
|
325
|
+
matches: List[Dict[str, object]] = []
|
|
326
|
+
|
|
327
|
+
path_hits = _path_matches(
|
|
328
|
+
record.get("scope", {}).get("path_globs", []),
|
|
329
|
+
paths,
|
|
330
|
+
)
|
|
331
|
+
if path_hits:
|
|
332
|
+
signals["path"] = FIELD_WEIGHTS["path"]
|
|
333
|
+
matches.append({"field": "path", "values": path_hits})
|
|
334
|
+
|
|
335
|
+
fields = (
|
|
336
|
+
("symbols", _string_list(record.get("symbols")), symbols),
|
|
337
|
+
("components", _string_list(record.get("components")), components),
|
|
338
|
+
("topics", _string_list(record.get("topics")), topics),
|
|
339
|
+
("aliases", _string_list(record.get("aliases")), ()),
|
|
340
|
+
("title", [str(record.get("title", ""))], ()),
|
|
341
|
+
("decision_contract", _contract_values(record), ()),
|
|
342
|
+
("decision_summary", [str(record.get("decision_summary", ""))], ()),
|
|
343
|
+
)
|
|
344
|
+
for field, values, explicit in fields:
|
|
345
|
+
explicit_hits = _explicit_matches(values, explicit)
|
|
346
|
+
lexical_hits, matched_token_count = _lexical_matches(
|
|
347
|
+
values, normalized_query, query_keywords
|
|
348
|
+
)
|
|
349
|
+
hits = sorted(
|
|
350
|
+
set(explicit_hits + lexical_hits),
|
|
351
|
+
key=lambda item: (item.casefold(), item),
|
|
352
|
+
)
|
|
353
|
+
if not hits:
|
|
354
|
+
continue
|
|
355
|
+
coverage = 1.0 if explicit_hits else matched_token_count / denominator
|
|
356
|
+
if coverage <= 0:
|
|
357
|
+
coverage = 1.0
|
|
358
|
+
signals[field] = round(FIELD_WEIGHTS[field] * min(1.0, coverage), 4)
|
|
359
|
+
matches.append({"field": field, "values": hits})
|
|
360
|
+
if (
|
|
361
|
+
not paths
|
|
362
|
+
and not symbols
|
|
363
|
+
and not components
|
|
364
|
+
and not topics
|
|
365
|
+
and sum(signals.values()) >= 1.0
|
|
366
|
+
):
|
|
367
|
+
break
|
|
368
|
+
|
|
369
|
+
total = round(min(1.0, sum(signals.values())), 4)
|
|
370
|
+
return {"total": total, "signals": signals, "matches": matches}
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _authority(status: str) -> str:
|
|
374
|
+
if status == "Accepted":
|
|
375
|
+
return "governing"
|
|
376
|
+
if status == "Proposed":
|
|
377
|
+
return "advisory"
|
|
378
|
+
return "historical"
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _adr_sort_key(adr_id: str) -> Tuple[int, str]:
|
|
382
|
+
match = re.search(r"\d+", adr_id)
|
|
383
|
+
return (int(match.group(0)) if match else 0, adr_id)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _related_ids(record_id: str, relationships: Sequence[Dict]) -> List[str]:
|
|
387
|
+
related = set()
|
|
388
|
+
for edge in relationships:
|
|
389
|
+
if edge.get("type") != "related" or edge.get("resolved") is not True:
|
|
390
|
+
continue
|
|
391
|
+
if edge.get("source") == record_id:
|
|
392
|
+
related.add(str(edge.get("target")))
|
|
393
|
+
elif edge.get("target") == record_id:
|
|
394
|
+
related.add(str(edge.get("source")))
|
|
395
|
+
return sorted(related, key=_adr_sort_key)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _successor_id(record: Dict, relationships: Sequence[Dict]) -> Optional[str]:
|
|
399
|
+
successor = record.get("metadata", {}).get("superseded_by")
|
|
400
|
+
if isinstance(successor, str) and successor:
|
|
401
|
+
return successor
|
|
402
|
+
for edge in relationships:
|
|
403
|
+
if (
|
|
404
|
+
edge.get("source") == record.get("id")
|
|
405
|
+
and edge.get("type") == "superseded-by"
|
|
406
|
+
and edge.get("resolved") is True
|
|
407
|
+
):
|
|
408
|
+
return str(edge.get("target"))
|
|
409
|
+
return None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _public_result(
|
|
413
|
+
record: Dict,
|
|
414
|
+
score: Dict,
|
|
415
|
+
adr_dir: Path,
|
|
416
|
+
*,
|
|
417
|
+
source: str,
|
|
418
|
+
schema_version: int,
|
|
419
|
+
role: str = "primary",
|
|
420
|
+
redirected_from: Optional[str] = None,
|
|
421
|
+
related_ids: Sequence[str] = (),
|
|
422
|
+
) -> Dict:
|
|
423
|
+
raw_path = Path(str(record["path"]))
|
|
424
|
+
path = raw_path if raw_path.is_absolute() else adr_dir / raw_path
|
|
425
|
+
metadata = dict(record.get("metadata", {}))
|
|
426
|
+
engine = "index-first" if source.startswith("index-") else "markdown-fallback"
|
|
427
|
+
return {
|
|
428
|
+
"adr_id": record["id"],
|
|
429
|
+
"title": record["title"],
|
|
430
|
+
"path": path.as_posix(),
|
|
431
|
+
"status": record["status"],
|
|
432
|
+
"is_accepted": record["status"] == "Accepted",
|
|
433
|
+
"authority": _authority(record["status"]),
|
|
434
|
+
"role": role,
|
|
435
|
+
"format": record["format"],
|
|
436
|
+
"decision_summary": record["decision_summary"],
|
|
437
|
+
"scope": record.get("scope", {}).get("path_globs", []),
|
|
438
|
+
"related_ids": list(related_ids),
|
|
439
|
+
"metadata": metadata,
|
|
440
|
+
"topics": _string_list(record.get("topics")),
|
|
441
|
+
"aliases": _string_list(record.get("aliases")),
|
|
442
|
+
"components": _string_list(record.get("components")),
|
|
443
|
+
"symbols": _string_list(record.get("symbols")),
|
|
444
|
+
"context_scope": record.get("context_scope", "selective"),
|
|
445
|
+
"decision_contract": _normalize_contract(record.get("decision_contract")),
|
|
446
|
+
"score": score["total"],
|
|
447
|
+
"signals": score["signals"],
|
|
448
|
+
"matches": score["matches"],
|
|
449
|
+
"source": source,
|
|
450
|
+
"engine": engine,
|
|
451
|
+
"schema_version": schema_version,
|
|
452
|
+
"redirected_from": redirected_from,
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def query_records(
|
|
457
|
+
records: Sequence[Dict],
|
|
458
|
+
relationships: Sequence[Dict],
|
|
459
|
+
query: str,
|
|
460
|
+
adr_dir: Path,
|
|
461
|
+
*,
|
|
462
|
+
limit: int = 5,
|
|
463
|
+
min_score: float = 0.1,
|
|
464
|
+
include_history: bool = False,
|
|
465
|
+
statuses: Sequence[str] = (),
|
|
466
|
+
authorities: Sequence[str] = (),
|
|
467
|
+
paths: Sequence[str] = (),
|
|
468
|
+
symbols: Sequence[str] = (),
|
|
469
|
+
components: Sequence[str] = (),
|
|
470
|
+
topics: Sequence[str] = (),
|
|
471
|
+
source: str = "index-v2",
|
|
472
|
+
schema_version: int = 2,
|
|
473
|
+
) -> List[Dict]:
|
|
474
|
+
by_id = {record["id"]: record for record in records}
|
|
475
|
+
candidates: Dict[str, Dict] = {}
|
|
476
|
+
redirected: Dict[str, str] = {}
|
|
477
|
+
query_keywords = extract_keywords(query)
|
|
478
|
+
normalized_query = _normalized_text(query)
|
|
479
|
+
status_filter = set(statuses)
|
|
480
|
+
authority_filter = set(authorities)
|
|
481
|
+
|
|
482
|
+
def selected(record: Dict) -> bool:
|
|
483
|
+
status = str(record.get("status"))
|
|
484
|
+
return (
|
|
485
|
+
(not status_filter or status in status_filter)
|
|
486
|
+
and (not authority_filter or _authority(status) in authority_filter)
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
for record in records:
|
|
490
|
+
if not selected(record):
|
|
491
|
+
continue
|
|
492
|
+
score = score_record(
|
|
493
|
+
record,
|
|
494
|
+
query,
|
|
495
|
+
paths=paths,
|
|
496
|
+
symbols=symbols,
|
|
497
|
+
components=components,
|
|
498
|
+
topics=topics,
|
|
499
|
+
_query_keywords=query_keywords,
|
|
500
|
+
_normalized_query_value=normalized_query,
|
|
501
|
+
)
|
|
502
|
+
if score["total"] < min_score:
|
|
503
|
+
continue
|
|
504
|
+
status = str(record.get("status"))
|
|
505
|
+
if status == "Superseded" and not include_history:
|
|
506
|
+
successor_id = _successor_id(record, relationships)
|
|
507
|
+
successor = by_id.get(successor_id or "")
|
|
508
|
+
if successor and successor.get("status") in {"Accepted", "Proposed"}:
|
|
509
|
+
redirected_score = {
|
|
510
|
+
"total": score["total"],
|
|
511
|
+
"signals": dict(score["signals"]),
|
|
512
|
+
"matches": list(score["matches"])
|
|
513
|
+
+ [
|
|
514
|
+
{
|
|
515
|
+
"field": "successor_redirect",
|
|
516
|
+
"values": [record["id"]],
|
|
517
|
+
}
|
|
518
|
+
],
|
|
519
|
+
}
|
|
520
|
+
existing = candidates.get(successor["id"])
|
|
521
|
+
if existing is None or score["total"] > existing["total"]:
|
|
522
|
+
candidates[successor["id"]] = redirected_score
|
|
523
|
+
redirected[successor["id"]] = record["id"]
|
|
524
|
+
continue
|
|
525
|
+
if status in HISTORICAL_STATUSES and not include_history:
|
|
526
|
+
continue
|
|
527
|
+
existing = candidates.get(record["id"])
|
|
528
|
+
if existing is None or score["total"] > existing["total"]:
|
|
529
|
+
candidates[record["id"]] = score
|
|
530
|
+
|
|
531
|
+
ordered = sorted(
|
|
532
|
+
candidates,
|
|
533
|
+
key=lambda adr_id: (-candidates[adr_id]["total"], _adr_sort_key(adr_id)),
|
|
534
|
+
)
|
|
535
|
+
primary_ids = ordered[: max(0, limit)]
|
|
536
|
+
results = [
|
|
537
|
+
_public_result(
|
|
538
|
+
by_id[adr_id],
|
|
539
|
+
candidates[adr_id],
|
|
540
|
+
adr_dir,
|
|
541
|
+
source=source,
|
|
542
|
+
schema_version=schema_version,
|
|
543
|
+
redirected_from=redirected.get(adr_id),
|
|
544
|
+
related_ids=_related_ids(adr_id, relationships),
|
|
545
|
+
)
|
|
546
|
+
for adr_id in primary_ids
|
|
547
|
+
]
|
|
548
|
+
|
|
549
|
+
supporting_ids: List[str] = []
|
|
550
|
+
for primary_id in primary_ids:
|
|
551
|
+
for related_id in _related_ids(primary_id, relationships):
|
|
552
|
+
if related_id in primary_ids or related_id in supporting_ids:
|
|
553
|
+
continue
|
|
554
|
+
related = by_id.get(related_id)
|
|
555
|
+
if related is None:
|
|
556
|
+
continue
|
|
557
|
+
if not selected(related):
|
|
558
|
+
continue
|
|
559
|
+
if related.get("status") in HISTORICAL_STATUSES and not include_history:
|
|
560
|
+
continue
|
|
561
|
+
supporting_ids.append(related_id)
|
|
562
|
+
if len(supporting_ids) >= MAX_SUPPORTING_RESULTS:
|
|
563
|
+
break
|
|
564
|
+
if len(supporting_ids) >= MAX_SUPPORTING_RESULTS:
|
|
565
|
+
break
|
|
566
|
+
|
|
567
|
+
for supporting_id in supporting_ids:
|
|
568
|
+
if len(results) >= limit:
|
|
569
|
+
break
|
|
570
|
+
results.append(
|
|
571
|
+
_public_result(
|
|
572
|
+
by_id[supporting_id],
|
|
573
|
+
{
|
|
574
|
+
"total": 0.0,
|
|
575
|
+
"signals": {},
|
|
576
|
+
"matches": [
|
|
577
|
+
{
|
|
578
|
+
"field": "relationship",
|
|
579
|
+
"values": ["one-hop supporting ADR"],
|
|
580
|
+
}
|
|
581
|
+
],
|
|
582
|
+
},
|
|
583
|
+
adr_dir,
|
|
584
|
+
source=source,
|
|
585
|
+
schema_version=schema_version,
|
|
586
|
+
role="supporting",
|
|
587
|
+
related_ids=_related_ids(supporting_id, relationships),
|
|
588
|
+
)
|
|
589
|
+
)
|
|
590
|
+
return results
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def query_adr_context(
|
|
594
|
+
query: str,
|
|
595
|
+
adr_dir: Path,
|
|
596
|
+
*,
|
|
597
|
+
limit: int = 5,
|
|
598
|
+
min_score: float = 0.1,
|
|
599
|
+
strict_index: bool = False,
|
|
600
|
+
include_history: bool = False,
|
|
601
|
+
statuses: Sequence[str] = (),
|
|
602
|
+
authorities: Sequence[str] = (),
|
|
603
|
+
paths: Sequence[str] = (),
|
|
604
|
+
symbols: Sequence[str] = (),
|
|
605
|
+
components: Sequence[str] = (),
|
|
606
|
+
topics: Sequence[str] = (),
|
|
607
|
+
) -> Dict:
|
|
608
|
+
if not isinstance(query, str) or not query.strip():
|
|
609
|
+
raise ValueError("query must be a non-empty string")
|
|
610
|
+
if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 100:
|
|
611
|
+
raise ValueError("limit must be an integer between 1 and 100")
|
|
612
|
+
if (
|
|
613
|
+
not isinstance(min_score, (int, float))
|
|
614
|
+
or isinstance(min_score, bool)
|
|
615
|
+
or not 0 <= float(min_score) <= 1
|
|
616
|
+
):
|
|
617
|
+
raise ValueError("min_score must be a number between 0 and 1")
|
|
618
|
+
invalid_statuses = sorted(set(statuses) - SUPPORTED_STATUSES)
|
|
619
|
+
if invalid_statuses:
|
|
620
|
+
raise ValueError("unsupported status filter(s): " + ", ".join(invalid_statuses))
|
|
621
|
+
invalid_authorities = sorted(set(authorities) - SUPPORTED_AUTHORITIES)
|
|
622
|
+
if invalid_authorities:
|
|
623
|
+
raise ValueError(
|
|
624
|
+
"unsupported authority filter(s): " + ", ".join(invalid_authorities)
|
|
625
|
+
)
|
|
626
|
+
for name, values in (
|
|
627
|
+
("paths", paths),
|
|
628
|
+
("symbols", symbols),
|
|
629
|
+
("components", components),
|
|
630
|
+
("topics", topics),
|
|
631
|
+
):
|
|
632
|
+
if len(values) > 32 or any(
|
|
633
|
+
not isinstance(value, str) or not value.strip() or len(value) > 240
|
|
634
|
+
for value in values
|
|
635
|
+
):
|
|
636
|
+
raise ValueError(
|
|
637
|
+
f"{name} must contain at most 32 non-empty strings of 240 characters"
|
|
638
|
+
)
|
|
639
|
+
warnings: List[str] = []
|
|
640
|
+
try:
|
|
641
|
+
records, relationships, version = load_index_graph(adr_dir)
|
|
642
|
+
source = f"index-v{version}"
|
|
643
|
+
except IndexQueryError as exc:
|
|
644
|
+
if strict_index:
|
|
645
|
+
raise
|
|
646
|
+
warning = f"[adr-context] WARN: {exc}; using Markdown compatibility fallback"
|
|
647
|
+
warnings.append(warning)
|
|
648
|
+
records, relationships = _markdown_graph(adr_dir)
|
|
649
|
+
version = 2
|
|
650
|
+
source = "markdown-fallback"
|
|
651
|
+
results = query_records(
|
|
652
|
+
records,
|
|
653
|
+
relationships,
|
|
654
|
+
query,
|
|
655
|
+
adr_dir,
|
|
656
|
+
limit=limit,
|
|
657
|
+
min_score=min_score,
|
|
658
|
+
include_history=include_history,
|
|
659
|
+
statuses=statuses,
|
|
660
|
+
authorities=authorities,
|
|
661
|
+
paths=paths,
|
|
662
|
+
symbols=symbols,
|
|
663
|
+
components=components,
|
|
664
|
+
topics=topics,
|
|
665
|
+
source=source,
|
|
666
|
+
schema_version=version,
|
|
667
|
+
)
|
|
668
|
+
return {
|
|
669
|
+
"results": results,
|
|
670
|
+
"warnings": warnings,
|
|
671
|
+
"source": source,
|
|
672
|
+
"engine": (
|
|
673
|
+
"index-first" if source.startswith("index-") else "markdown-fallback"
|
|
674
|
+
),
|
|
675
|
+
"schema_version": version,
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
|