@yandy-r/ycc-opencode 6.3.0 → 6.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,525 @@
1
+ #!/usr/bin/env python3
2
+ """Diff an app's capability inventory against a stored MCP parity manifest.
3
+
4
+ Deterministic core of the mcp-parity skill: the research phase writes a
5
+ capability inventory (JSON), the Linear manifest Document holds the previous
6
+ run's manifest, and this script decides what changed so a re-run only touches
7
+ the delta.
8
+
9
+ Subcommands:
10
+ init Print an empty manifest (create mode).
11
+ extract Print the manifest JSON embedded in a manifest Document body.
12
+ cover Set inventory mcpCovered flags from researcher coverage results.
13
+ diff Classify inventory capabilities against the manifest.
14
+ apply Merge the inventory and this run's recorded Linear results into the
15
+ next manifest, emitted as JSON or as a complete Document body.
16
+
17
+ Exit 0 on success, 1 on invalid input. Results go to stdout, errors to stderr.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import json
25
+ import re
26
+ import sys
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ SCHEMA = 1
31
+ KINDS = frozenset({"tool", "resource", "prompt"})
32
+ STATUSES = frozenset({"planned", "done", "covered", "removed", "declined"})
33
+ # Issue-map only: the tracked issue was deleted or archived; forget its key.
34
+ MAP_STATUSES = STATUSES | {"unlinked"}
35
+ ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,127}$")
36
+ # Visible heading, not an HTML comment: tracker markdown round-trips may drop comments.
37
+ MANIFEST_HEADING = "## Manifest data"
38
+ FENCE_RE = re.compile(r"```json[ \t]*\r?\n(.*?)\r?\n```", re.DOTALL)
39
+ # Fields whose change means the MCP contract must change. Summary, source
40
+ # location, area, and surface are presentation-only.
41
+ CONTRACT_FIELDS = ("kind", "operation", "inputs", "outputs", "mutating", "destructive", "auth")
42
+ ISSUE_FIELDS = frozenset({"issue", "milestone", "priority", "status", "applied"})
43
+
44
+
45
+ class InputError(ValueError):
46
+ """Raised for malformed inventory, manifest, or issue-map input."""
47
+
48
+
49
+ def _normalize(value: Any) -> Any:
50
+ if isinstance(value, str):
51
+ return " ".join(value.split())
52
+ if isinstance(value, dict):
53
+ return {str(k).strip(): _normalize(v) for k, v in sorted(value.items())}
54
+ if isinstance(value, list):
55
+ return [_normalize(v) for v in value]
56
+ return value
57
+
58
+
59
+ def contract(cap: dict[str, Any]) -> dict[str, Any]:
60
+ """Return the normalized contract fields of a capability."""
61
+ out = {k: _normalize(cap.get(k)) for k in CONTRACT_FIELDS}
62
+ out["mutating"] = bool(out["mutating"])
63
+ out["destructive"] = bool(out["destructive"])
64
+ out["auth"] = out["auth"] or "unspecified"
65
+ out["inputs"] = out["inputs"] if out["inputs"] is not None else {}
66
+ out["outputs"] = out["outputs"] if out["outputs"] is not None else ""
67
+ return out
68
+
69
+
70
+ def fingerprint(cap: dict[str, Any]) -> str:
71
+ """Return a stable 16-hex fingerprint of a capability's normalized contract."""
72
+ canonical = json.dumps(contract(cap), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
73
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
74
+
75
+
76
+ def _shape_key(cap: dict[str, Any]) -> str:
77
+ """Fingerprint without the operation, used to spot moved routes."""
78
+ return fingerprint({**contract(cap), "operation": "-"})
79
+
80
+
81
+ def empty_manifest(repo: str | None = None) -> dict[str, Any]:
82
+ manifest: dict[str, Any] = {"schema": SCHEMA, "foundation": {}, "capabilities": {}}
83
+ if repo:
84
+ manifest["repo"] = repo
85
+ return manifest
86
+
87
+
88
+ def validate_inventory(data: Any) -> list[dict[str, Any]]:
89
+ """Validate an inventory document and return its capability list."""
90
+ if not isinstance(data, dict) or not isinstance(data.get("capabilities"), list):
91
+ raise InputError("inventory must be an object with a 'capabilities' array")
92
+ seen: set[str] = set()
93
+ caps: list[dict[str, Any]] = []
94
+ for i, cap in enumerate(data["capabilities"]):
95
+ if not isinstance(cap, dict):
96
+ raise InputError(f"capability #{i} is not an object")
97
+ cid = cap.get("id")
98
+ if not isinstance(cid, str) or not ID_RE.match(cid):
99
+ raise InputError(f"capability #{i} has invalid id {cid!r} (want {ID_RE.pattern})")
100
+ if cid in seen:
101
+ raise InputError(f"duplicate capability id {cid!r}")
102
+ seen.add(cid)
103
+ if cap.get("kind") not in KINDS:
104
+ raise InputError(f"capability {cid!r} kind must be one of {sorted(KINDS)}")
105
+ if not isinstance(cap.get("operation"), str) or not cap["operation"].strip():
106
+ raise InputError(f"capability {cid!r} needs a non-empty 'operation'")
107
+ for flag in ("mutating", "destructive"):
108
+ if not isinstance(cap.get(flag), bool):
109
+ raise InputError(f"capability {cid!r} needs boolean {flag!r}")
110
+ caps.append(cap)
111
+ return caps
112
+
113
+
114
+ # `:name` only at a segment start, so custom verbs (`/things:cancel`) stay distinct.
115
+ PARAM_RE = re.compile(r"\{[^}/]*\}|(?<=/):[A-Za-z_][A-Za-z0-9_]*|<[^>/]*>|\[[^\]/]*\]")
116
+
117
+
118
+ def operation_key(operation: str) -> str:
119
+ """Normalize an operation for matching: method case, path-param syntax, trailing slash."""
120
+ parts = operation.split()
121
+ if len(parts) >= 2 and parts[0].isalpha():
122
+ method, path = parts[0].upper(), " ".join(parts[1:])
123
+ else:
124
+ method, path = "", " ".join(parts)
125
+ path = PARAM_RE.sub("{}", path)
126
+ if len(path) > 1:
127
+ path = path.rstrip("/")
128
+ return f"{method} {path}".strip()
129
+
130
+
131
+ def cover(caps: list[dict[str, Any]], covered: Any) -> tuple[list[dict[str, Any]], list[Any]]:
132
+ """Set mcpCovered from researcher 2's {operation, mcpName, inputsMatch} entries."""
133
+ if not isinstance(covered, list):
134
+ raise InputError("coverage must be a JSON array of {operation, mcpName, inputsMatch}")
135
+ by_key: dict[str, dict[str, Any]] = {}
136
+ unmapped: list[Any] = []
137
+ for entry in covered:
138
+ if not isinstance(entry, dict) or not isinstance(entry.get("operation"), str):
139
+ raise InputError(f"coverage entry {entry!r} needs a string 'operation'")
140
+ key = operation_key(entry["operation"])
141
+ if key.lower() in ("", "none", "n/a"):
142
+ unmapped.append(entry) # MCP-only tool with no app operation
143
+ continue
144
+ prior = by_key.get(key)
145
+ # Several tools on one operation: covered if any of them matches.
146
+ if prior is None or (entry.get("inputsMatch") is True and prior.get("inputsMatch") is not True):
147
+ by_key[key] = entry
148
+ used: set[str] = set()
149
+ out: list[dict[str, Any]] = []
150
+ for cap in caps:
151
+ key = operation_key(cap["operation"])
152
+ hit = by_key.get(key)
153
+ if hit:
154
+ used.add(key)
155
+ out.append({**cap, "mcpCovered": bool(hit and hit.get("inputsMatch") is True)})
156
+ mcp_only = unmapped + [e for k, e in by_key.items() if k not in used]
157
+ return out, mcp_only
158
+
159
+
160
+ def validate_manifest(data: Any) -> dict[str, Any]:
161
+ """Validate a manifest and return it with defaults filled in."""
162
+ if not isinstance(data, dict):
163
+ raise InputError("manifest must be a JSON object")
164
+ if data.get("schema") != SCHEMA:
165
+ raise InputError(f"unsupported manifest schema {data.get('schema')!r} (want {SCHEMA})")
166
+ caps = data.get("capabilities", {})
167
+ if not isinstance(caps, dict):
168
+ raise InputError("manifest 'capabilities' must be an object keyed by id")
169
+ for cid, entry in caps.items():
170
+ if not isinstance(entry, dict) or not isinstance(entry.get("fingerprint"), str):
171
+ raise InputError(f"manifest entry {cid!r} needs a string 'fingerprint'")
172
+ if entry.get("status") not in STATUSES:
173
+ raise InputError(f"manifest entry {cid!r} has invalid status {entry.get('status')!r}")
174
+ foundation = data.get("foundation", {})
175
+ if not isinstance(foundation, dict):
176
+ raise InputError("manifest 'foundation' must be an object")
177
+ return {**data, "capabilities": caps, "foundation": foundation}
178
+
179
+
180
+ def extract_manifest(body: str) -> dict[str, Any] | None:
181
+ """Return the manifest under the Manifest data heading of a Document body, if any."""
182
+ start = body.find(MANIFEST_HEADING)
183
+ if start < 0:
184
+ return None
185
+ match = FENCE_RE.search(body, start)
186
+ if match is None:
187
+ raise InputError(f"'{MANIFEST_HEADING}' has no ```json block after it")
188
+ try:
189
+ parsed = json.loads(match.group(1))
190
+ except json.JSONDecodeError as exc:
191
+ raise InputError(f"manifest JSON is invalid: {exc}") from exc
192
+ return validate_manifest(parsed)
193
+
194
+
195
+ def check_repo(manifest: dict[str, Any], repo: str | None) -> None:
196
+ """Refuse to diff a manifest that belongs to a different repository."""
197
+ stored = manifest.get("repo")
198
+ if repo and stored and str(stored).lower() != repo.lower():
199
+ raise InputError(f"manifest belongs to {stored!r}, not {repo!r}; wrong Project?")
200
+
201
+
202
+ def refreshed(manifest: dict[str, Any], issues: dict[str, Any] | None) -> dict[str, Any]:
203
+ """Return manifest capabilities with this run's State refresh statuses applied."""
204
+ known: dict[str, Any] = {k: dict(v) for k, v in manifest["capabilities"].items()}
205
+ for cid, update in (issues or {}).items():
206
+ if cid == "_foundation" or not isinstance(update, dict) or cid not in known:
207
+ continue
208
+ status = update.get("status")
209
+ if status == "unlinked":
210
+ known.pop(cid) # its issue is gone; plan it like a new capability
211
+ elif status in STATUSES:
212
+ known[cid]["status"] = status
213
+ return known
214
+
215
+
216
+ def diff(manifest: dict[str, Any], caps: list[dict[str, Any]], issues: dict[str, Any] | None = None) -> dict[str, Any]:
217
+ """Classify each inventory capability against the (refreshed) manifest."""
218
+ known = refreshed(manifest, issues)
219
+ result: dict[str, list[Any]] = {
220
+ "added": [],
221
+ "changed": [],
222
+ "removed": [],
223
+ "revived": [],
224
+ "unchanged": [],
225
+ "covered": [],
226
+ }
227
+ current: set[str] = set()
228
+ for cap in caps:
229
+ cid = cap["id"]
230
+ current.add(cid)
231
+ fp = fingerprint(cap)
232
+ entry = known.get(cid)
233
+ item: dict[str, Any] = {"id": cid, "fingerprint": fp, "capability": cap}
234
+ if entry is None:
235
+ result["covered" if cap.get("mcpCovered") is True else "added"].append(item)
236
+ elif entry["status"] == "covered" and cap.get("mcpCovered") is not True and not entry.get("issue"):
237
+ # A pre-existing MCP server no longer covers it.
238
+ result["added"].append(item)
239
+ elif entry["status"] == "removed":
240
+ result["revived"].append({**item, "issue": entry.get("issue")})
241
+ elif entry["fingerprint"] != fp:
242
+ result["changed"].append(
243
+ {
244
+ **item,
245
+ "issue": entry.get("issue"),
246
+ "status": entry["status"],
247
+ "oldFingerprint": entry["fingerprint"],
248
+ "oldContract": entry.get("contract"),
249
+ "newContract": contract(cap),
250
+ }
251
+ )
252
+ else:
253
+ result["unchanged"].append(cid)
254
+ for cid in sorted(known):
255
+ if cid not in current and known[cid]["status"] != "removed":
256
+ entry = known[cid]
257
+ result["removed"].append({"id": cid, "issue": entry.get("issue"), "status": entry["status"]})
258
+ for key in ("added", "changed", "revived", "covered"):
259
+ result[key].sort(key=lambda x: x["id"])
260
+ result["unchanged"].sort()
261
+ renames = _possible_renames(known, result["removed"], result["added"] + result["covered"])
262
+ counts = {k: len(v) for k, v in result.items()}
263
+ tracked = sum(1 for e in known.values() if e["status"] != "removed")
264
+ return {
265
+ "schema": SCHEMA,
266
+ "counts": counts,
267
+ "noop": not any(n for k, n in counts.items() if k != "unchanged"),
268
+ "removedRatio": round(counts["removed"] / tracked, 3) if tracked else 0.0,
269
+ "possibleRenames": renames,
270
+ **result,
271
+ }
272
+
273
+
274
+ def _possible_renames(
275
+ known: dict[str, Any], removed: list[dict[str, Any]], fresh: list[dict[str, Any]]
276
+ ) -> list[dict[str, str]]:
277
+ """Pair removed and new ids that look like the same capability."""
278
+ pairs: list[dict[str, str]] = []
279
+ for gone in removed:
280
+ old = known[gone["id"]].get("contract")
281
+ if not isinstance(old, dict):
282
+ continue
283
+ for new in fresh:
284
+ cap = new["capability"]
285
+ if _normalize(cap["operation"]) == old.get("operation"):
286
+ pairs.append({"from": gone["id"], "to": new["id"], "reason": "same operation"})
287
+ elif (old.get("inputs") or old.get("outputs")) and _shape_key(cap) == _shape_key(old):
288
+ pairs.append({"from": gone["id"], "to": new["id"], "reason": "same contract, new operation"})
289
+ return pairs
290
+
291
+
292
+ def apply(
293
+ manifest: dict[str, Any],
294
+ caps: list[dict[str, Any]],
295
+ issues: dict[str, Any],
296
+ meta: dict[str, Any],
297
+ partial: bool = False,
298
+ ) -> dict[str, Any]:
299
+ """Return the next manifest after this run's Linear writes.
300
+
301
+ Only work recorded in ``issues`` is committed: a changed contract keeps its
302
+ old fingerprint and a vanished capability keeps its status until the map
303
+ records it (``applied``, a new ``issue``, or a ``status``). With ``partial``,
304
+ new capabilities without an issue key are left out so they re-diff as added.
305
+ """
306
+ known: dict[str, Any] = manifest["capabilities"]
307
+ current = {cap["id"] for cap in caps}
308
+ for key, value in issues.items():
309
+ if key == "_foundation":
310
+ if not isinstance(value, dict):
311
+ raise InputError("issue map '_foundation' must be an object")
312
+ continue
313
+ if not isinstance(value, dict):
314
+ raise InputError(f"issue map entry {key!r} must be an object")
315
+ if key not in current and key not in known:
316
+ raise InputError(f"issue map entry {key!r} is not a known capability id")
317
+ unknown = set(value) - ISSUE_FIELDS
318
+ if unknown:
319
+ raise InputError(f"issue map entry {key!r} has unknown fields {sorted(unknown)}")
320
+ if "status" in value and value["status"] not in MAP_STATUSES:
321
+ raise InputError(f"issue map entry {key!r} has invalid status {value['status']!r}")
322
+
323
+ out_caps: dict[str, Any] = {}
324
+ for cap in caps:
325
+ cid = cap["id"]
326
+ prev: dict[str, Any] = dict(known.get(cid, {}))
327
+ update: dict[str, Any] = issues.get(cid, {})
328
+ if update.get("status") == "unlinked":
329
+ prev, update = {"history": _unlink(prev).get("history", [])}, _without_status(update)
330
+ recorded = _recorded(update)
331
+ entry = _merge_issue(prev, update)
332
+ if not prev.get("fingerprint"):
333
+ if cap.get("mcpCovered") is True and not entry.get("issue"):
334
+ entry.setdefault("status", "covered")
335
+ elif not entry.get("issue"):
336
+ if partial:
337
+ continue
338
+ raise InputError(f"new capability {cid!r} has no issue key in the issue map")
339
+ entry.setdefault("status", "planned")
340
+ elif prev["status"] in ("removed", "covered") and "status" not in update:
341
+ if prev["status"] == "covered" and cap.get("mcpCovered") is True and not update.get("issue"):
342
+ pass # still covered
343
+ elif update.get("issue"):
344
+ entry["status"] = "planned"
345
+ elif partial:
346
+ out_caps[cid] = prev # revived or uncovered, issue not created yet
347
+ continue
348
+ else:
349
+ raise InputError(f"capability {cid!r} needs a new issue key in the issue map")
350
+ fp = fingerprint(cap)
351
+ if not prev.get("fingerprint") or fp == prev.get("fingerprint") or recorded:
352
+ entry["fingerprint"] = fp
353
+ entry["contract"] = contract(cap)
354
+ entry["operation"] = cap["operation"]
355
+ if cap.get("area"):
356
+ entry["area"] = cap["area"]
357
+ out_caps[cid] = {k: entry[k] for k in sorted(entry) if entry[k] not in (None, [])}
358
+ for cid, prev in known.items():
359
+ if cid in current:
360
+ continue
361
+ update = issues.get(cid, {})
362
+ unlinked = update.get("status") == "unlinked"
363
+ if unlinked:
364
+ prev, update = _unlink(prev), _without_status(update)
365
+ entry = _merge_issue(dict(prev), update)
366
+ if unlinked or _recorded(update) or update.get("status") == "removed" or prev["status"] == "removed":
367
+ entry["status"] = "removed"
368
+ out_caps[cid] = {k: entry[k] for k in sorted(entry) if entry[k] not in (None, [])}
369
+
370
+ foundation = {**manifest.get("foundation", {}), **issues.get("_foundation", {})}
371
+ nxt: dict[str, Any] = {"schema": SCHEMA}
372
+ for key in ("project", "repo", "commit", "generatedAt"):
373
+ value = meta.get(key) if meta.get(key) is not None else manifest.get(key)
374
+ if value is not None:
375
+ nxt[key] = value
376
+ nxt["foundation"] = dict(sorted(foundation.items()))
377
+ nxt["capabilities"] = dict(sorted(out_caps.items()))
378
+ return nxt
379
+
380
+
381
+ def _unlink(prev: dict[str, Any]) -> dict[str, Any]:
382
+ """Drop a deleted/archived issue key, keeping it in history."""
383
+ entry = {k: v for k, v in prev.items() if k != "issue"}
384
+ if prev.get("issue"):
385
+ entry["history"] = [*prev.get("history", []), prev["issue"]]
386
+ return entry
387
+
388
+
389
+ def _without_status(update: dict[str, Any]) -> dict[str, Any]:
390
+ return {k: v for k, v in update.items() if k != "status"}
391
+
392
+
393
+ def _recorded(update: dict[str, Any]) -> bool:
394
+ """True when this run's Linear action for the id succeeded (status refreshes do not count)."""
395
+ return update.get("applied") is True or bool(update.get("issue"))
396
+
397
+
398
+ def _merge_issue(prev: dict[str, Any], update: dict[str, Any]) -> dict[str, Any]:
399
+ entry = dict(prev)
400
+ new_issue = update.get("issue")
401
+ if new_issue and prev.get("issue") and new_issue != prev["issue"]:
402
+ entry["history"] = [*prev.get("history", []), prev["issue"]]
403
+ for field in ("issue", "milestone", "priority", "status"):
404
+ if field in update:
405
+ entry[field] = update[field]
406
+ return entry
407
+
408
+
409
+ def render_document(manifest: dict[str, Any]) -> str:
410
+ """Render the manifest Document body: a readable table plus the JSON block."""
411
+ caps: dict[str, Any] = manifest["capabilities"]
412
+ live = {k: v for k, v in caps.items() if v.get("status") != "removed"}
413
+ exposed = sum(1 for v in live.values() if v.get("status") in ("covered", "done"))
414
+ lines = [
415
+ "# MCP parity manifest",
416
+ "",
417
+ "Maintained by the mcp-parity skill. Do not edit the JSON block by hand; re-run the skill instead.",
418
+ "",
419
+ f"- Repository: {manifest.get('repo', 'unknown')}",
420
+ f"- Commit: {manifest.get('commit', 'unknown')}",
421
+ f"- Generated: {manifest.get('generatedAt', 'unknown')}",
422
+ f"- Parity: {exposed}/{len(live)} capabilities exposed over MCP",
423
+ "",
424
+ "| Capability | Operation | Status | Issue |",
425
+ "| --- | --- | --- | --- |",
426
+ ]
427
+ for cid, entry in caps.items():
428
+ op = str(entry.get("operation", "")).replace("|", "\\|")
429
+ lines.append(f"| `{cid}` | {op} | {entry.get('status', '')} | {entry.get('issue', '')} |")
430
+ lines += ["", MANIFEST_HEADING, "", "```json", json.dumps(manifest, indent=2, ensure_ascii=False), "```", ""]
431
+ return "\n".join(lines)
432
+
433
+
434
+ def _load_json(path: str, what: str) -> Any:
435
+ try:
436
+ return json.loads(Path(path).read_text(encoding="utf-8"))
437
+ except FileNotFoundError as exc:
438
+ raise InputError(f"{what} file not found: {path}") from exc
439
+ except json.JSONDecodeError as exc:
440
+ raise InputError(f"{what} {path} is not valid JSON: {exc}") from exc
441
+
442
+
443
+ def _load_manifest(path: str) -> dict[str, Any]:
444
+ """Load a manifest from a .json file or a Document body (any other suffix)."""
445
+ p = Path(path)
446
+ if not p.is_file():
447
+ raise InputError(f"manifest file not found: {path}")
448
+ if p.suffix == ".json":
449
+ return validate_manifest(_load_json(path, "manifest"))
450
+ found = extract_manifest(p.read_text(encoding="utf-8"))
451
+ if found is None:
452
+ raise InputError(f"{path} has no '{MANIFEST_HEADING}' section")
453
+ return found
454
+
455
+
456
+ def _optional_object(path: str | None, what: str) -> dict[str, Any]:
457
+ if path is None or not Path(path).exists():
458
+ return {}
459
+ data = _load_json(path, what)
460
+ if not isinstance(data, dict):
461
+ raise InputError(f"{what} must be a JSON object")
462
+ return data
463
+
464
+
465
+ def main(argv: list[str] | None = None) -> int:
466
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
467
+ sub = parser.add_subparsers(dest="cmd", required=True)
468
+ p_init = sub.add_parser("init", help="print an empty manifest")
469
+ p_init.add_argument("--repo", help="owner/repo the manifest belongs to")
470
+ p_cover = sub.add_parser("cover", help="set mcpCovered on an inventory from coverage results")
471
+ p_cover.add_argument("--inventory", required=True, help="capability inventory JSON")
472
+ p_cover.add_argument("--covered", required=True, help="JSON array of {operation, mcpName, inputsMatch}")
473
+ p_extract = sub.add_parser("extract", help="print the manifest JSON from a Document body")
474
+ p_extract.add_argument("--doc", required=True, help="Document body (markdown) file")
475
+ for name in ("diff", "apply"):
476
+ p = sub.add_parser(name)
477
+ p.add_argument("--manifest", required=True, help="previous manifest: .json or a Document body")
478
+ p.add_argument("--inventory", required=True, help="current capability inventory JSON")
479
+ p.add_argument("--repo", help="owner/repo; refuses a manifest recorded for another repo")
480
+ p.add_argument("--adopt-repo", action="store_true", help="accept a renamed/transferred repo and re-key")
481
+ p.add_argument("--issues", help="JSON map of capability id (or _foundation) to recorded results")
482
+ if name == "apply":
483
+ p.add_argument("--meta", help="JSON object with project/repo/commit/generatedAt")
484
+ p.add_argument("--partial", action="store_true", help="leave unrecorded new capabilities out")
485
+ p.add_argument("--format", choices=("json", "markdown"), default="json")
486
+ args = parser.parse_args(argv)
487
+ try:
488
+ if args.cmd == "init":
489
+ print(json.dumps(empty_manifest(args.repo), indent=2))
490
+ return 0
491
+ if args.cmd == "cover":
492
+ data = _load_json(args.inventory, "inventory")
493
+ caps, mcp_only = cover(validate_inventory(data), _load_json(args.covered, "coverage"))
494
+ print(json.dumps({**data, "capabilities": caps, "mcpOnly": mcp_only}, indent=2))
495
+ return 0
496
+ if args.cmd == "extract":
497
+ doc = Path(args.doc)
498
+ if not doc.is_file():
499
+ raise InputError(f"file not found: {args.doc}")
500
+ found = extract_manifest(doc.read_text(encoding="utf-8"))
501
+ if found is None:
502
+ raise InputError(f"{args.doc} has no '{MANIFEST_HEADING}' section")
503
+ print(json.dumps(found, indent=2))
504
+ return 0
505
+ manifest = _load_manifest(args.manifest)
506
+ if not args.adopt_repo:
507
+ check_repo(manifest, args.repo)
508
+ caps = validate_inventory(_load_json(args.inventory, "inventory"))
509
+ issues = _optional_object(args.issues, "issue map")
510
+ if args.cmd == "diff":
511
+ print(json.dumps(diff(manifest, caps, issues), indent=2))
512
+ return 0
513
+ meta = _optional_object(args.meta, "meta")
514
+ if args.repo and (args.adopt_repo or meta.get("repo") is None):
515
+ meta["repo"] = args.repo
516
+ nxt = apply(manifest, caps, issues, meta, partial=args.partial)
517
+ print(render_document(nxt) if args.format == "markdown" else json.dumps(nxt, indent=2))
518
+ return 0
519
+ except InputError as exc:
520
+ print(f"capability_diff: {exc}", file=sys.stderr)
521
+ return 1
522
+
523
+
524
+ if __name__ == "__main__":
525
+ sys.exit(main())
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env bash
2
+ # detect-api-surface.sh — list the capability surfaces of a repository.
3
+ #
4
+ # Usage: detect-api-surface.sh [repo-root]
5
+ #
6
+ # Prints tab-separated `KIND<TAB>VALUE` lines on stdout, one per finding:
7
+ # LANG detected language/ecosystem (node, python, go, rust, java, ruby, php, dotnet)
8
+ # SPEC machine-readable contract file (openapi, graphql, proto, asyncapi)
9
+ # ROUTES source file that registers HTTP routes or RPC handlers
10
+ # CLI source file that defines CLI commands
11
+ # MCP source file that already uses an MCP server SDK
12
+ # MCP_CONFIG MCP config/manifest file
13
+ # Hints only: research agents must still read the code. Vendored, generated and
14
+ # dependency directories are skipped. Exit 0 on success (even with no findings),
15
+ # 1 on bad input.
16
+ set -euo pipefail
17
+
18
+ root="${1:-.}"
19
+ if [[ ! -d "$root" ]]; then
20
+ printf 'detect-api-surface: not a directory: %s\n' "$root" >&2
21
+ exit 1
22
+ fi
23
+ root="$(CDPATH='' cd -- "$root" >/dev/null && pwd -P)"
24
+
25
+ # A caller's GIT_DIR/GIT_WORK_TREE (git hooks export them) would point `git -C` at
26
+ # another repository; scan the target directory's own repository instead.
27
+ if command -v git >/dev/null 2>&1; then
28
+ while IFS= read -r git_var; do unset "$git_var"; done < <(git rev-parse --local-env-vars 2>/dev/null || true)
29
+ fi
30
+
31
+ MAX_HITS="${MCP_PARITY_MAX_HITS:-200}"
32
+ if [[ ! "$MAX_HITS" =~ ^[0-9]+$ ]] || ((MAX_HITS < 1)); then
33
+ printf 'detect-api-surface: MCP_PARITY_MAX_HITS must be a positive integer\n' >&2
34
+ exit 1
35
+ fi
36
+
37
+ # List candidate files relative to root. Prefer git (respects .gitignore).
38
+ list_files() {
39
+ if git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
40
+ git -C "$root" -c core.quotePath=false ls-files --cached --others --exclude-standard
41
+ else
42
+ (cd "$root" && find . -type f -not -path '*/.git/*' | sed 's|^\./||')
43
+ fi | grep -Ev '(^|/)(node_modules|vendor|dist|build|target|\.venv|venv|__pycache__|\.next|coverage|\.ycc|\.claude|\.codex|\.cursor|\.opencode|\.omp)/' || true
44
+ }
45
+
46
+ FILES="$(list_files)"
47
+
48
+ emit() { printf '%s\t%s\n' "$1" "$2"; }
49
+
50
+ # Language markers (root and up to two directories deep, for monorepos).
51
+ # A function, not an associative array: macOS ships Bash 3.2.
52
+ lang_for_base() {
53
+ case "$1" in
54
+ package.json) echo node ;;
55
+ pyproject.toml | requirements.txt | setup.py) echo python ;;
56
+ go.mod) echo go ;;
57
+ Cargo.toml) echo rust ;;
58
+ pom.xml | build.gradle | build.gradle.kts) echo java ;;
59
+ Gemfile) echo ruby ;;
60
+ composer.json) echo php ;;
61
+ *.csproj) echo dotnet ;;
62
+ esac
63
+ }
64
+ seen_langs=""
65
+ while IFS= read -r f; do
66
+ [[ -n "$f" ]] || continue
67
+ base="${f##*/}"
68
+ depth="${f//[^\/]/}"
69
+ ((${#depth} <= 2)) || continue
70
+ lang="$(lang_for_base "$base")"
71
+ if [[ -n "$lang" && " $seen_langs " != *" $lang "* ]]; then
72
+ seen_langs="$seen_langs $lang"
73
+ emit LANG "$lang"
74
+ fi
75
+ done <<<"$FILES"
76
+
77
+ # Contract specs by name/extension.
78
+ printf '%s\n' "$FILES" | grep -Ei '(^|/)(openapi|swagger)[^/]*\.(ya?ml|json)$|\.(graphql|gql|proto)$|(^|/)schema\.graphqls?$|(^|/)asyncapi[^/]*\.(ya?ml|json)$' \
79
+ | sed -n "1,${MAX_HITS}p" | while IFS= read -r f; do emit SPEC "$f"; done || true
80
+
81
+ SOURCE_RE='\.(ts|tsx|js|mjs|cjs|py|go|rs|java|kt|rb|php|cs)$'
82
+ sources="$(printf '%s\n' "$FILES" | grep -E "$SOURCE_RE" | grep -Ev '(^|/)(test|tests|__tests__|spec|testdata|fixtures)/|\.(test|spec)\.|_test\.(go|py)$|(^|/)test_[^/]*\.py$' || true)"
83
+
84
+ # Search file contents, printing each matching file once (bounded).
85
+ grep_files() {
86
+ local label=$1 pattern=$2 hits count
87
+ [[ -n "$sources" ]] || return 0
88
+ hits="$(printf '%s\n' "$sources" | (cd "$root" && tr '\n' '\0' | xargs -0 grep -lIE -- "$pattern" 2>/dev/null) || true)"
89
+ [[ -n "$hits" ]] || return 0
90
+ count="$(printf '%s\n' "$hits" | wc -l | tr -d ' ')"
91
+ if ((count > MAX_HITS)); then
92
+ printf 'detect-api-surface: %s: showing %s of %s files (raise MCP_PARITY_MAX_HITS)\n' "$label" "$MAX_HITS" "$count" >&2
93
+ fi
94
+ # sed, not head: head exits early and SIGPIPE would abort under pipefail.
95
+ printf '%s\n' "$hits" | sed -n "1,${MAX_HITS}p" | while IFS= read -r f; do emit "$label" "$f"; done
96
+ }
97
+
98
+ ROUTE_RE='\b(app|router|server|fastify|r|e|g|mux|http|api|bp|blueprint|group|v[0-9])\.(get|post|put|patch|delete|route|add_api_route|handle|Handle|HandleFunc|Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE)\(|^export (async )?function (GET|POST|PUT|PATCH|DELETE)\b|@(app|router|api|bp)\.(get|post|put|patch|delete|route)\(|@(Get|Post|Put|Patch|Delete|RequestMapping|GetMapping|PostMapping|PutMapping|DeleteMapping|Controller|RestController)\b|\b(createTRPCRouter|publicProcedure|protectedProcedure)\b|#\[(get|post|put|patch|delete)\(|\bRoute::(get|post|put|patch|delete)\(|\bresources? :[a-z_]+|\burlpatterns\b|\bRegister[A-Za-z]+Server\('
99
+ CLI_RE="(from|require\\()[[:space:]]*['\"](commander|yargs|cac|citty|@oclif/core)['\"]|\\bclick\\.(command|group)\\b|\\btyper\\.Typer\\b|\\bargparse\\.ArgumentParser\\b|github\\.com/spf13/cobra|github\\.com/urfave/cli|\\bclap::(Parser|Command)\\b|#\\[derive\\([^)]*Parser"
100
+ MCP_RE='@modelcontextprotocol/sdk|\bfrom mcp(\.server)?\b|\bimport mcp\b|\bFastMCP\b|mark3labs/mcp-go|modelcontextprotocol/go-sdk|\brmcp\b|McpServer|io\.modelcontextprotocol'
101
+
102
+ grep_files ROUTES "$ROUTE_RE"
103
+ grep_files CLI "$CLI_RE"
104
+ grep_files MCP "$MCP_RE"
105
+
106
+ printf '%s\n' "$FILES" | grep -Ei '(^|/)(\.mcp\.json|mcp\.json|server\.json|smithery\.ya?ml|mcp-server[^/]*\.(json|ya?ml))$' \
107
+ | sed -n "1,${MAX_HITS}p" | while IFS= read -r f; do emit MCP_CONFIG "$f"; done || true
108
+
109
+ exit 0