pi-lean-host 0.2.0 → 0.3.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.
@@ -15,6 +15,7 @@ import type { Guide } from "./guide-loader.js";
15
15
  import { extractPathTokens } from "./path-template.js";
16
16
  import {
17
17
  GATHER_ALL_MAX_FALLBACK,
18
+ GUIDE_SCHEMA_VERSION,
18
19
  KNOWN_AUTH_KINDS,
19
20
  type ApiGuide,
20
21
  type DateParamFormat,
@@ -43,6 +44,42 @@ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
43
44
 
44
45
  export const TODAY = () => new Date().toISOString().slice(0, 10);
45
46
 
47
+ /**
48
+ * Line-level frontmatter stamp — replace (or insert) a single `key: value`
49
+ * line inside the isolated frontmatter block, preserving comments and key
50
+ * order (no YAML round-trip — a round-trip reformats and strips comments).
51
+ * Used by api-learn (schemaVersion save-stamp) and /api verify (verified
52
+ * stamp). Returns the document unchanged when it has no frontmatter block.
53
+ */
54
+ export function stampFrontmatterField(
55
+ raw: string,
56
+ key: string,
57
+ value: string,
58
+ ): string {
59
+ const match = raw.match(FRONTMATTER_RE);
60
+ if (!match) return raw;
61
+ const fm = match[1] ?? "";
62
+ const content = match[2] ?? "";
63
+ const nl = /^---(\r?\n)/.exec(raw)?.[1] ?? "\n";
64
+ const lines = fm.split(nl);
65
+ const keyRe = new RegExp(`^${key}:\\s*.+$`);
66
+ const idx = lines.findIndex((l) => keyRe.test(l));
67
+ const line = `${key}: ${value}`;
68
+ if (idx === -1) {
69
+ // Insert-only separation: a new key would land flush against the
70
+ // preceding line (e.g. under the last op's params block). Push a
71
+ // blank line first when the preceding line is non-empty. Replace
72
+ // must NOT do this — every /api verify re-stamp would drift the file.
73
+ if (lines.length > 0 && lines.at(-1)?.trim() !== "") {
74
+ lines.push("");
75
+ }
76
+ lines.push(line);
77
+ } else {
78
+ lines[idx] = line;
79
+ }
80
+ return `---${nl}${lines.join(nl)}${nl}---${nl}${content}`;
81
+ }
82
+
46
83
  const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
47
84
  // accept is a free-form string — any media type is valid (`json`/`xml`
48
85
  // shorthands are mapped by the helper).
@@ -61,6 +98,23 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
61
98
  "tokenBag",
62
99
  ]);
63
100
 
101
+ // Strict auth schema (gap 1): the only keys validateAuth reads. Any other key
102
+ // under `auth` is rejected at parse — the parser used to silently drop
103
+ // unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
104
+ // guide the executor then silently couldn't honor.
105
+ const KNOWN_AUTH_KEYS: ReadonlySet<string> = new Set([
106
+ "kind",
107
+ "headers",
108
+ "secretRefs",
109
+ "secretQueryRefs",
110
+ "requires",
111
+ "optional",
112
+ "headerPrefixes",
113
+ ]);
114
+ // Set insertion order — used to render the known-key list in error strings
115
+ // (expected + fallback fix) so they can't drift from the set.
116
+ const KNOWN_AUTH_KEYS_LIST = [...KNOWN_AUTH_KEYS].join(", ");
117
+
64
118
  // ═══════════════════════════════════════════════════════════════════
65
119
  // Error helper
66
120
  // ═══════════════════════════════════════════════════════════════════
@@ -156,10 +210,13 @@ function requireStringArray(
156
210
  key: string,
157
211
  file: string | undefined,
158
212
  fm: string,
213
+ opts?: { missingFix?: string },
159
214
  ): string[] | ParseApiGuideResult {
160
215
  const v = m[key];
161
216
  if (v === undefined) {
162
- return fail(file, key, "a list of strings", "missing");
217
+ return fail(file, key, "a list of strings", "missing", {
218
+ ...(opts?.missingFix ? { fix: opts.missingFix } : {}),
219
+ });
163
220
  }
164
221
  if (!Array.isArray(v) || v.length === 0) {
165
222
  return fail(file, key, "a non-empty list of strings", describeFound(v), {
@@ -250,6 +307,18 @@ function validatePagination(
250
307
  }
251
308
  cfg.pageSize = ps;
252
309
  }
310
+ const base = p["base"];
311
+ if (base !== undefined) {
312
+ if (typeof base !== "number" || !Number.isInteger(base)) {
313
+ return fail(
314
+ file,
315
+ `${fieldPrefix}.base`,
316
+ "a finite integer (the seed value for the page param)",
317
+ describeFound(base),
318
+ );
319
+ }
320
+ cfg.base = base;
321
+ }
253
322
  } else if (style === "nextLink") {
254
323
  const nlp = p["nextLinkPath"];
255
324
  if (typeof nlp !== "string" || nlp === "") {
@@ -382,6 +451,102 @@ function validateResponseShape(
382
451
  // Auth
383
452
  // ═══════════════════════════════════════════════════════════════════
384
453
 
454
+ /**
455
+ * Validate a `Record<string, string>` auth sub-field (headers, secretRefs,
456
+ * secretQueryRefs, headerPrefixes). Returns the parsed record, or a ParseError
457
+ * when `raw` is absent/null/non-object/an array, or a value fails `valueOk`
458
+ * (default: any string; `headerPrefixes` passes a non-empty check).
459
+ */
460
+ function parseStringRecord(
461
+ raw: unknown,
462
+ file: string | undefined,
463
+ fm: string,
464
+ field: string,
465
+ expect: string,
466
+ valueOk: (v: unknown) => boolean = (v) => typeof v === "string",
467
+ ): Record<string, string> | ParseApiGuideResult {
468
+ if (
469
+ raw === null ||
470
+ typeof raw !== "object" ||
471
+ Array.isArray(raw) ||
472
+ Object.values(raw).some((v) => !valueOk(v))
473
+ ) {
474
+ return fail(file, field, expect, describeFound(raw), {
475
+ snippet: snippetFor(fm, "auth"),
476
+ });
477
+ }
478
+ return raw as Record<string, string>;
479
+ }
480
+
481
+ /** `true` when a `parseStringRecord` / validator result is a ParseError. */
482
+ function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
483
+ return (
484
+ typeof v === "object" &&
485
+ v !== null &&
486
+ "ok" in v &&
487
+ (v as { ok: unknown }).ok === false
488
+ );
489
+ }
490
+
491
+ /** Levenshtein edit distance — spots near-miss auth keys (e.g. `requiers:` →
492
+ * `requires`) so the unknown-key error can say "did you mean X?" instead of a
493
+ * bare rejection. */
494
+ function editDistance(a: string, b: string): number {
495
+ const m = a.length;
496
+ const n = b.length;
497
+ if (m === 0) return n;
498
+ if (n === 0) return m;
499
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
500
+ for (let i = 1; i <= m; i++) {
501
+ const cur = new Array<number>(n + 1);
502
+ cur[0] = i;
503
+ for (let j = 1; j <= n; j++) {
504
+ cur[j] = Math.min(
505
+ prev[j]! + 1,
506
+ cur[j - 1]! + 1,
507
+ prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
508
+ );
509
+ }
510
+ prev = cur;
511
+ }
512
+ return prev[n]!;
513
+ }
514
+
515
+ /** Nearest known auth key within edit distance ≤ 2, or undefined. */
516
+ function nearestKnownKey(
517
+ key: string,
518
+ known: ReadonlySet<string>,
519
+ ): string | undefined {
520
+ let best: string | undefined;
521
+ let bestDist = Infinity;
522
+ for (const k of known) {
523
+ const d = editDistance(key, k);
524
+ if (d < bestDist) {
525
+ bestDist = d;
526
+ best = k;
527
+ }
528
+ }
529
+ return bestDist <= 2 ? best : undefined;
530
+ }
531
+
532
+ /**
533
+ * Adaptive fix for an unknown-auth-key rejection: near-miss → "did you mean
534
+ * X?"; the observed wrong shape (`name`/`secret` under static-key) → point at
535
+ * the real secretRefs/requires shape; anything else → list the known keys.
536
+ */
537
+ function authUnknownKeyFix(unknownKeys: string[]): string {
538
+ for (const key of unknownKeys) {
539
+ const known = nearestKnownKey(key, KNOWN_AUTH_KEYS);
540
+ if (known !== undefined) {
541
+ return `Unknown auth key "${key}" — did you mean "${known}"?`;
542
+ }
543
+ }
544
+ if (unknownKeys.includes("name") || unknownKeys.includes("secret")) {
545
+ return `The keyed-header shape is auth.secretRefs: { <header>: <secret-name> } with the secret declared in auth.requires (or auth.optional) — replace name/secret with secretRefs + requires.`;
546
+ }
547
+ return `Unknown auth key(s): ${unknownKeys.join(", ")} — known keys: ${KNOWN_AUTH_KEYS_LIST}.`;
548
+ }
549
+
385
550
  function validateAuth(
386
551
  raw: unknown,
387
552
  file: string | undefined,
@@ -404,6 +569,9 @@ function validateAuth(
404
569
  "auth.kind",
405
570
  "a string",
406
571
  kindRaw === undefined ? "missing" : describeFound(kindRaw),
572
+ {
573
+ fix: "kind is one of: none | static-key — use `kind: none` (public) or `kind: static-key` (keyed header); or call api-learn({domain, new: true}) for a full skeleton",
574
+ },
407
575
  );
408
576
  }
409
577
  if (!KNOWN_AUTH_KINDS.has(kindRaw)) {
@@ -422,68 +590,67 @@ function validateAuth(
422
590
  fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
423
591
  });
424
592
  }
593
+ // Strict auth schema — reject unknown keys (gap 1). The parser used to
594
+ // silently drop unknown keys (a wrong-but-plausible shape like
595
+ // `name`/`secret` saved a guide the executor then silently couldn't
596
+ // honor). Reject, don't infer: the fix is adaptive (near-miss → "did you
597
+ // mean X?", wrong shape → secretRefs/requires).
598
+ const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
599
+ if (unknownKeys.length > 0) {
600
+ const first = unknownKeys[0]!;
601
+ return fail(
602
+ file,
603
+ `auth.${first}`,
604
+ `a known auth key (${KNOWN_AUTH_KEYS_LIST})`,
605
+ `unknown key(s): ${unknownKeys.join(", ")}`,
606
+ {
607
+ snippet: snippetFor(fm, "auth"),
608
+ fix: authUnknownKeyFix(unknownKeys),
609
+ },
610
+ );
611
+ }
425
612
  // Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
426
613
  let headers: Record<string, string> | undefined;
427
- const headersRaw = a["headers"];
428
- if (headersRaw !== undefined) {
429
- if (
430
- headersRaw === null ||
431
- typeof headersRaw !== "object" ||
432
- Array.isArray(headersRaw) ||
433
- Object.values(headersRaw).some((v) => typeof v !== "string")
434
- ) {
435
- return fail(
436
- file,
437
- "auth.headers",
438
- "a YAML mapping of string → string",
439
- describeFound(headersRaw),
440
- );
441
- }
442
- headers = headersRaw as Record<string, string>;
614
+ if (a["headers"] !== undefined) {
615
+ const hr = parseStringRecord(
616
+ a["headers"],
617
+ file,
618
+ fm,
619
+ "auth.headers",
620
+ "a YAML mapping of string → string",
621
+ );
622
+ if (isParseErr(hr)) return hr;
623
+ headers = hr;
443
624
  }
444
625
 
445
626
  // static-key reference fields (secretRefs/requires/optional).
446
627
  let secretRefs: Record<string, string> | undefined;
447
- const refsRaw = a["secretRefs"];
448
- if (refsRaw !== undefined) {
449
- if (
450
- refsRaw === null ||
451
- typeof refsRaw !== "object" ||
452
- Array.isArray(refsRaw) ||
453
- Object.values(refsRaw).some((v) => typeof v !== "string")
454
- ) {
455
- return fail(
456
- file,
457
- "auth.secretRefs",
458
- "a YAML mapping of header name → secret name",
459
- describeFound(refsRaw),
460
- { snippet: snippetFor(fm, "auth") },
461
- );
462
- }
463
- secretRefs = refsRaw as Record<string, string>;
628
+ if (a["secretRefs"] !== undefined) {
629
+ const sr = parseStringRecord(
630
+ a["secretRefs"],
631
+ file,
632
+ fm,
633
+ "auth.secretRefs",
634
+ "a YAML mapping of header name → secret name",
635
+ );
636
+ if (isParseErr(sr)) return sr;
637
+ secretRefs = sr;
464
638
  }
465
639
 
466
640
  // Query-param secrets: maps query param name → secret store name.
467
641
  // Same shape + consistency rules as secretRefs; the collision-with-op-`params`
468
642
  // rule is enforced in parseApiGuide (auth is parsed before operations).
469
643
  let secretQueryRefs: Record<string, string> | undefined;
470
- const sqrRaw = a["secretQueryRefs"];
471
- if (sqrRaw !== undefined) {
472
- if (
473
- sqrRaw === null ||
474
- typeof sqrRaw !== "object" ||
475
- Array.isArray(sqrRaw) ||
476
- Object.values(sqrRaw).some((v) => typeof v !== "string")
477
- ) {
478
- return fail(
479
- file,
480
- "auth.secretQueryRefs",
481
- "a YAML mapping of query param name → secret name",
482
- describeFound(sqrRaw),
483
- { snippet: snippetFor(fm, "auth") },
484
- );
485
- }
486
- secretQueryRefs = sqrRaw as Record<string, string>;
644
+ if (a["secretQueryRefs"] !== undefined) {
645
+ const qr = parseStringRecord(
646
+ a["secretQueryRefs"],
647
+ file,
648
+ fm,
649
+ "auth.secretQueryRefs",
650
+ "a YAML mapping of query param name → secret name",
651
+ );
652
+ if (isParseErr(qr)) return qr;
653
+ secretQueryRefs = qr;
487
654
  }
488
655
 
489
656
  let requires: string[] | undefined;
@@ -524,10 +691,29 @@ function validateAuth(
524
691
  optional = optRaw as string[];
525
692
  }
526
693
 
694
+ // static-key header prefixes: header name → non-empty prefix string
695
+ // prepended to the resolved secret value. Same mapping shape as secretRefs;
696
+ // every key must also be a secretRefs header (a prefix for a non-secret
697
+ // header is a mistake).
698
+ let headerPrefixes: Record<string, string> | undefined;
699
+ if (a["headerPrefixes"] !== undefined) {
700
+ const hp = parseStringRecord(
701
+ a["headerPrefixes"],
702
+ file,
703
+ fm,
704
+ "auth.headerPrefixes",
705
+ "a YAML mapping of header name → non-empty prefix string",
706
+ (v) =>
707
+ typeof v === "string" && v.length > 0 && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
708
+ );
709
+ if (isParseErr(hp)) return hp;
710
+ headerPrefixes = hp;
711
+ }
712
+
527
713
  // Fail-closed consistency rules.
528
714
  if (
529
715
  kindRaw === "none" &&
530
- (secretRefs || secretQueryRefs || requires || optional)
716
+ (secretRefs || secretQueryRefs || requires || optional || headerPrefixes)
531
717
  ) {
532
718
  return fail(
533
719
  file,
@@ -605,10 +791,30 @@ function validateAuth(
605
791
  const r4 = checkDeclared(optional ?? [], "auth.optional");
606
792
  if (r4) return r4;
607
793
  }
794
+ // Every headerPrefixes key must target a secret-injected header; a prefix
795
+ // for a header that isn't in secretRefs is a mistake. Checked outside the
796
+ // secretRefs/requires/optional block so a headerPrefixes-only guide fails
797
+ // too (the prefix would otherwise be dead at fetch time silently).
798
+ if (headerPrefixes) {
799
+ for (const headerName of Object.keys(headerPrefixes)) {
800
+ if (!secretRefs || !(headerName in secretRefs)) {
801
+ return fail(
802
+ file,
803
+ `auth.headerPrefixes.${headerName}`,
804
+ "a header name present in auth.secretRefs",
805
+ `"${headerName}" is not a secret-injected header`,
806
+ {
807
+ fix: `Add "${headerName}" to auth.secretRefs (or remove the prefix).`,
808
+ },
809
+ );
810
+ }
811
+ }
812
+ }
608
813
 
609
814
  const result: AuthConfig = { kind: kindRaw as AuthKind };
610
815
  if (headers !== undefined) result.headers = headers;
611
816
  if (secretRefs !== undefined) result.secretRefs = secretRefs;
817
+ if (headerPrefixes !== undefined) result.headerPrefixes = headerPrefixes;
612
818
  if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
613
819
  if (requires !== undefined) result.requires = requires;
614
820
  if (optional !== undefined) result.optional = optional;
@@ -800,6 +1006,76 @@ function validateOperation(
800
1006
  }
801
1007
  }
802
1008
 
1009
+ // requiresAnyOf — at-least-one-of constraint (one group per op, v1).
1010
+ // Parser cross-field checks, same class as the secretQueryRefs collision
1011
+ // guard: empty-array reject (check #0, before member inspection),
1012
+ // member-exists, path-param reject, no `required: true` overlap, no
1013
+ // `default` on a member. A group member that is `required` would defeat
1014
+ // the group at runtime; a `default` would fire alongside a caller-supplied
1015
+ // sibling (the members are mutually exclusive peers).
1016
+ const requiresAnyOfRaw = o["requiresAnyOf"];
1017
+ let requiresAnyOf: string[] | undefined;
1018
+ if (requiresAnyOfRaw !== undefined) {
1019
+ if (!Array.isArray(requiresAnyOfRaw) || requiresAnyOfRaw.length === 0) {
1020
+ return fail(
1021
+ file,
1022
+ fieldPath("requiresAnyOf"),
1023
+ "a non-empty list of param names",
1024
+ describeFound(requiresAnyOfRaw),
1025
+ );
1026
+ }
1027
+ for (const member of requiresAnyOfRaw) {
1028
+ if (typeof member !== "string" || member === "") {
1029
+ return fail(
1030
+ file,
1031
+ fieldPath("requiresAnyOf"),
1032
+ "a non-empty list of param names",
1033
+ `contains ${describeFound(member)}`,
1034
+ );
1035
+ }
1036
+ if (pathParams.includes(member)) {
1037
+ return fail(
1038
+ file,
1039
+ fieldPath(`requiresAnyOf.${member}`),
1040
+ "a query param name (not a path param)",
1041
+ `"${member}" is a path param — path params are always required via {${member}} in path`,
1042
+ );
1043
+ }
1044
+ const spec = params[member];
1045
+ if (spec === undefined) {
1046
+ return fail(
1047
+ file,
1048
+ fieldPath(`requiresAnyOf.${member}`),
1049
+ "a param name declared in this operation's params",
1050
+ `"${member}" is not a declared param`,
1051
+ );
1052
+ }
1053
+ if (spec.required === true) {
1054
+ return fail(
1055
+ file,
1056
+ fieldPath(`requiresAnyOf.${member}`),
1057
+ "a param that is not also required: true",
1058
+ `"${member}" is required: true`,
1059
+ {
1060
+ fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf group, not per-param required.`,
1061
+ },
1062
+ );
1063
+ }
1064
+ if (spec.default !== undefined) {
1065
+ return fail(
1066
+ file,
1067
+ fieldPath(`requiresAnyOf.${member}`),
1068
+ "a param that does not also declare a default",
1069
+ `"${member}" has a default`,
1070
+ {
1071
+ fix: `Remove the default from params.${member} — requiresAnyOf members are mutually exclusive peers, so a default would fire alongside a caller-supplied sibling.`,
1072
+ },
1073
+ );
1074
+ }
1075
+ }
1076
+ requiresAnyOf = requiresAnyOfRaw as string[];
1077
+ }
1078
+
803
1079
  // dateParams — param name → date format normalization
804
1080
  const dateParamsRaw = o["dateParams"];
805
1081
  let dateParams: Record<string, DateParamFormat> | undefined;
@@ -939,6 +1215,7 @@ function validateOperation(
939
1215
  ...(transform === undefined ? {} : { transform }),
940
1216
  ...(passthrough === undefined ? {} : { passthrough }),
941
1217
  ...(dateParams === undefined ? {} : { dateParams }),
1218
+ ...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
942
1219
  ...(parseOverride ? { parse: parseOverride } : {}),
943
1220
  ...(opPagination ? { pagination: opPagination } : {}),
944
1221
  ...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
@@ -959,6 +1236,34 @@ export function parseApiGuide(
959
1236
 
960
1237
  const match = raw.match(FRONTMATTER_RE);
961
1238
  if (!match) {
1239
+ // Opening delimiter present → the failure is on the closing side, not
1240
+ // a missing frontmatter block. Detect the opener with /^---\r?\n/ (not
1241
+ // startsWith("---\n")) so a CRLF-prefixed file is routed here too.
1242
+ if (/^---\r?\n/.test(raw)) {
1243
+ // A `\n---` after the opener means a closer exists but FRONTMATTER_RE
1244
+ // still failed — the closer is malformed (e.g. no trailing newline
1245
+ // at EOF). Otherwise there is no closer at all.
1246
+ if (/\n---/.test(raw.replace(/^---\r?\n/, ""))) {
1247
+ return fail(
1248
+ file,
1249
+ "frontmatter",
1250
+ "a closing --- followed by a newline",
1251
+ "closing --- present but malformed (missing trailing newline after it)",
1252
+ {
1253
+ fix: "Ensure the closing --- is on its own line and followed by a newline before any prose.",
1254
+ },
1255
+ );
1256
+ }
1257
+ return fail(
1258
+ file,
1259
+ "frontmatter",
1260
+ "YAML frontmatter delimited by ---",
1261
+ "missing closing ---",
1262
+ {
1263
+ fix: "Close the frontmatter block with a --- line after the YAML.",
1264
+ },
1265
+ );
1266
+ }
962
1267
  return fail(
963
1268
  file,
964
1269
  "frontmatter",
@@ -1021,7 +1326,10 @@ export function parseApiGuide(
1021
1326
  }
1022
1327
  const kind = "api";
1023
1328
 
1024
- const domainsRes = requireStringArray(m, "domains", file, fm);
1329
+ const domainsRes = requireStringArray(m, "domains", file, fm, {
1330
+ missingFix:
1331
+ "Call api-learn({domain: '<domain>', new: true}) — it returns a template with `domains` pre-filled",
1332
+ });
1025
1333
  if (!Array.isArray(domainsRes)) return domainsRes;
1026
1334
  const domains = domainsRes;
1027
1335
 
@@ -1034,7 +1342,7 @@ export function parseApiGuide(
1034
1342
  // ── recipe slice ──────────────────────────────────────────────
1035
1343
  const apiHostRes = requireHttpUrl(m["apiHost"], "apiHost", file, fm, {
1036
1344
  protocolFix: "Use https:// as the scheme",
1037
- invalidFix: "Include the scheme, e.g. https://apidatos.boe.es/v1",
1345
+ invalidFix: "Include the scheme, e.g. https://api.example.com/v1",
1038
1346
  });
1039
1347
  if (typeof apiHostRes !== "string") return apiHostRes;
1040
1348
  const apiHost = apiHostRes;
@@ -1102,6 +1410,24 @@ export function parseApiGuide(
1102
1410
  description = descriptionRaw;
1103
1411
  }
1104
1412
 
1413
+ // schemaVersion — breaking-change detection (design: "schemaVersion is
1414
+ // detection, not enforcement"). Stamped on save by api-learn; absent-on-
1415
+ // read defaults to 0 (the floor), so an unversioned guide flags as
1416
+ // potentially stale after any schema bump rather than silently inheriting
1417
+ // the new current. A valid-integer frontmatter value overrides the floor.
1418
+ // A stale value (< current) warns non-blockingly in the api-guide catalog/
1419
+ // detail and on api-fetch; never gates. A malformed (non-integer/negative)
1420
+ // value falls back to 0 and never rejects a guide.
1421
+ let schemaVersion = 0;
1422
+ const schemaVersionRaw = m["schemaVersion"];
1423
+ if (
1424
+ typeof schemaVersionRaw === "number" &&
1425
+ Number.isInteger(schemaVersionRaw) &&
1426
+ schemaVersionRaw >= 0
1427
+ ) {
1428
+ schemaVersion = schemaVersionRaw;
1429
+ }
1430
+
1105
1431
  let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
1106
1432
  const gatherAllMaxRaw = m["gatherAllMax"];
1107
1433
  if (gatherAllMaxRaw !== undefined) {
@@ -1206,6 +1532,7 @@ export function parseApiGuide(
1206
1532
  ...(docs ? { docs } : {}),
1207
1533
  ...(organization ? { organization } : {}),
1208
1534
  ...(description ? { description } : {}),
1535
+ schemaVersion,
1209
1536
  gatherAllMax,
1210
1537
  auth,
1211
1538
  responseShape,
@@ -1287,6 +1614,37 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
1287
1614
  return result;
1288
1615
  }
1289
1616
 
1617
+ // ════════════════════════════════════════════════════════════════════
1618
+ // Schema-version staleness — detection, never a gate
1619
+ // ════════════════════════════════════════════════════════════════════
1620
+
1621
+ /**
1622
+ * Pure staleness predicate: a guide is stale when its schemaVersion predates
1623
+ * the current schema (a bump may have broken it). A forward-stamped guide
1624
+ * (authored against a newer schema than the running host) is NOT stale.
1625
+ */
1626
+ export function isStaleSchema(
1627
+ guideSchemaVersion: number,
1628
+ currentSchemaVersion: number,
1629
+ ): boolean {
1630
+ return guideSchemaVersion < currentSchemaVersion;
1631
+ }
1632
+
1633
+ /**
1634
+ * Non-blocking stale-schema warning line for a guide, or undefined when the
1635
+ * guide is current. Peer of the `⚠ malformed` catalog line — detection,
1636
+ * never a gate (the guide still loads and runs). `current` defaults to
1637
+ * GUIDE_SCHEMA_VERSION; tests pass a bumped value to force staleness.
1638
+ */
1639
+ export function staleSchemaLine(
1640
+ guide: ApiGuide,
1641
+ current: number = GUIDE_SCHEMA_VERSION,
1642
+ ): string | undefined {
1643
+ const v = guide.schemaVersion ?? 0;
1644
+ if (!isStaleSchema(v, current)) return undefined;
1645
+ return ` ⚠ schemaVersion ${v} < current ${current} — guide may need updating`;
1646
+ }
1647
+
1290
1648
  // ════════════════════════════════════════════════════════════════════
1291
1649
  // Disambiguation helpers — shared by the api-guide menu and the
1292
1650
  // api-fetch ambiguous-operation error. One rendering of the per-guide
@@ -1317,7 +1675,8 @@ function formatOpSummary(ops: { name: string }[]): string {
1317
1675
  * guides render consistently with those that have a one-line summary.
1318
1676
  */
1319
1677
  export function formatGuideListings(
1320
- entries: { guide: ApiGuide; dirName: string }[],
1678
+ entries: { guide: ApiGuide }[],
1679
+ current: number = GUIDE_SCHEMA_VERSION,
1321
1680
  ): string {
1322
1681
  const lines: string[] = [];
1323
1682
  for (const { guide } of entries) {
@@ -1326,10 +1685,73 @@ export function formatGuideListings(
1326
1685
  (guide.description ? ` — ${guide.description}` : ""),
1327
1686
  );
1328
1687
  lines.push(` ${formatOpSummary(guide.operations)}`);
1688
+ const stale = staleSchemaLine(guide, current);
1689
+ if (stale) lines.push(stale);
1329
1690
  }
1330
1691
  return lines.join("\n");
1331
1692
  }
1332
1693
 
1694
+ /**
1695
+ * Resolve a guide by shortName across a domain's matches (exact,
1696
+ * case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
1697
+ * /api verify — three call sites, one resolution rule (a drifted copy would
1698
+ * ship a known second bug). Returns a structured outcome; each caller renders
1699
+ * its own message (tool result vs command notify).
1700
+ */
1701
+ export function selectGuideByShortName(
1702
+ matches: { guide: ApiGuide; dirName: string }[],
1703
+ selector: string,
1704
+ ):
1705
+ | { ok: true; guide: ApiGuide; dirName: string }
1706
+ | { ok: false; reason: "no_match"; valid: string[] }
1707
+ | { ok: false; reason: "ambiguous"; directories: string[] } {
1708
+ const lc = selector.toLowerCase();
1709
+ const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
1710
+ if (sel.length === 0) {
1711
+ return {
1712
+ ok: false,
1713
+ reason: "no_match",
1714
+ valid: matches.map((m) => m.guide.shortName),
1715
+ };
1716
+ }
1717
+ if (sel.length > 1) {
1718
+ return {
1719
+ ok: false,
1720
+ reason: "ambiguous",
1721
+ directories: sel.map((s) => s.dirName),
1722
+ };
1723
+ }
1724
+ return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
1725
+ }
1726
+
1727
+ /**
1728
+ * Render the no-match / ambiguous error text for a failed
1729
+ * `selectGuideByShortName` result. `callToAction` is the trailing
1730
+ * "how to see the menu" sentence — it differs per surface (tool vs
1731
+ * command), so callers pass their own.
1732
+ */
1733
+ export function shortNameErrorText(
1734
+ sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
1735
+ domain: string,
1736
+ selector: string,
1737
+ callToAction: string,
1738
+ ): string {
1739
+ if (sel.reason === "no_match") {
1740
+ return (
1741
+ `No guide named '${selector}' for '${domain}'. ` +
1742
+ `Available guides: ${sel.valid.join(", ")}. ` +
1743
+ callToAction
1744
+ );
1745
+ }
1746
+ return (
1747
+ `Ambiguous guide '${selector}' for '${domain}' — ` +
1748
+ `${sel.directories.length} guides share shortName '${selector}' ` +
1749
+ `(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
1750
+ `disambiguate. ` +
1751
+ callToAction
1752
+ );
1753
+ }
1754
+
1333
1755
  // ════════════════════════════════════════════════════════════════════
1334
1756
  // Catalog rendering — healthy + ⚠ malformed together
1335
1757
  //
@@ -1341,7 +1763,10 @@ export function formatGuideListings(
1341
1763
  // here, where they'd bloat context for orgs with many guides.
1342
1764
  // ════════════════════════════════════════════════════════════════════
1343
1765
 
1344
- export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
1766
+ export function formatApiGuideCatalog(
1767
+ loaded: LoadedApiGuides,
1768
+ current: number = GUIDE_SCHEMA_VERSION,
1769
+ ): string {
1345
1770
  const lines: string[] = ["API guides:"];
1346
1771
 
1347
1772
  // Org-grouped rows preserve first-appearance order; guides without
@@ -1370,7 +1795,14 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
1370
1795
  }
1371
1796
  const domList = domains.size > 0 ? [...domains].join(", ") : "—";
1372
1797
  const n = row.guides.length;
1373
- lines.push(` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})`);
1798
+ // Collapsed org row: a trailing ⚠ glyph when ANY guide in it is stale
1799
+ // (hint only — the per-guide ⚠ line lives on the menu / detail view).
1800
+ const stale = row.guides.some((g) =>
1801
+ isStaleSchema(g.schemaVersion ?? 0, current),
1802
+ );
1803
+ lines.push(
1804
+ ` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})${stale ? " ⚠" : ""}`,
1805
+ );
1374
1806
  }
1375
1807
  for (const { name, guide } of orgless) {
1376
1808
  const domains =
@@ -1378,6 +1810,8 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
1378
1810
  lines.push(
1379
1811
  ` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
1380
1812
  );
1813
+ const stale = staleSchemaLine(guide, current);
1814
+ if (stale) lines.push(stale);
1381
1815
  }
1382
1816
  for (const mal of loaded.malformed) {
1383
1817
  lines.push(