pi-lean-host 0.4.0 → 0.6.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.
@@ -9,10 +9,12 @@
9
9
  */
10
10
 
11
11
  import { parse as yamlParse } from "yaml";
12
- import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
13
- import { join } from "node:path";
14
- import type { Guide } from "./guide-loader.js";
15
- import { extractPathTokens, slug } from "./path-template.js";
12
+ import { fileURLToPath } from "node:url";
13
+ import {
14
+ extractPathTokens,
15
+ tokenizeJsonPath,
16
+ wireParamName,
17
+ } from "./path-template.js";
16
18
  import {
17
19
  GATHER_ALL_MAX_FALLBACK,
18
20
  GUIDE_SCHEMA_VERSION,
@@ -30,11 +32,21 @@ import {
30
32
  type ResponseCharset,
31
33
  type AuthConfig,
32
34
  type AuthKind,
35
+ type SecretRef,
36
+ type StaticKeyAuth,
37
+ type OAuth2Auth,
38
+ type OAuth2ParamStyle,
39
+ type OAuth2TokenEndpointAuthMethod,
40
+ isOAuth2Grant,
41
+ isOAuth2TokenEndpointAuthMethod,
42
+ isListStyle,
43
+ LIST_STYLES,
44
+ oauth2GrantIssue,
45
+ OAUTH2_GRANTS,
46
+ OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS,
33
47
  type ExecutorVia,
34
48
  type AcceptType,
35
49
  type QueryParamSpec,
36
- type LoadedApiGuides,
37
- type NotifyFn,
38
50
  } from "./api-guide-types.js";
39
51
 
40
52
  // ═══════════════════════════════════════════════════════════════════
@@ -63,8 +75,7 @@ export function stampFrontmatterField(
63
75
  const content = match[2] ?? "";
64
76
  const nl = /^---(\r?\n)/.exec(raw)?.[1] ?? "\n";
65
77
  const lines = fm.split(nl);
66
- const keyRe = new RegExp(`^${key}:\\s*.+$`);
67
- const idx = lines.findIndex((l) => keyRe.test(l));
78
+ const idx = lines.findIndex((l) => l.startsWith(`${key}:`));
68
79
  const line = `${key}: ${value}`;
69
80
  if (idx === -1) {
70
81
  // Insert-only separation: a new key would land flush against the
@@ -82,6 +93,17 @@ export function stampFrontmatterField(
82
93
  }
83
94
 
84
95
  const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
96
+ // Closed param-spec key allowlist — the unknown-key tripwire rejects
97
+ // anything else (typo'd `listStyl:` / `requried:` must not silently no-op).
98
+ // Exported for the allowlist↔parser tripwire in
99
+ // __tests__/parse-api-guide.test.ts (same two-direction shape as
100
+ // AUTH_ALLOWLISTS / PAGINATION_ALLOWLISTS).
101
+ export const PARAM_SPEC_KEYS: ReadonlySet<string> = new Set([
102
+ "required",
103
+ "default",
104
+ "description",
105
+ "listStyle",
106
+ ]);
85
107
  // accept is a free-form string — any media type is valid (`json`/`xml`
86
108
  // shorthands are mapped by the helper).
87
109
  const VALID_FORMAT: ReadonlySet<string> = new Set(["json", "xml", "text"]);
@@ -99,27 +121,169 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
99
121
  "tokenBag",
100
122
  ]);
101
123
 
102
- // Strict auth schema: the only keys validateAuth reads. Any other key
103
- // under `auth` is rejected at parse — the parser used to silently drop
104
- // unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
105
- // guide the executor then silently couldn't honor.
106
- const KNOWN_AUTH_KEYS: ReadonlySet<string> = new Set([
124
+ // Per-variant auth field allowlists — each kind rejects fields not legal for
125
+ // it (stricter than the old single global set: a `tokenUrl` on a static-key
126
+ // block or a `headerPrefixes` on an oauth2 block now fails at parse). The old
127
+ // `none`-kind field-presence check is subsumed by the NoneAuth allowlist.
128
+ // Exported for the allowlist↔parser tripwire in __tests__/parse-api-guide.test.ts
129
+ // (same two-direction shape as PAGINATION_ALLOWLISTS).
130
+ export const AUTH_ALLOWLISTS: Record<AuthKind, ReadonlySet<string>> = {
131
+ none: new Set(["kind", "headers"]),
132
+ "static-key": new Set([
133
+ "kind",
134
+ "headers",
135
+ "secretRefs",
136
+ "secretQueryRefs",
137
+ "secretPathRefs",
138
+ ]),
139
+ oauth2: new Set([
140
+ "kind",
141
+ "grant",
142
+ "tokenUrl",
143
+ "clientId",
144
+ "clientSecret",
145
+ "secretRefs",
146
+ "scopes",
147
+ "paramStyle",
148
+ "tokenEndpointAuthMethod",
149
+ "authorizeUrl",
150
+ "revokeUrl",
151
+ ]),
152
+ };
153
+
154
+ // Per-style pagination field allowlists — same pattern as AUTH_ALLOWLISTS:
155
+ // each style rejects keys not legal for it, so a typo (`itemPath:`) or a
156
+ // wrong-style key (`cursorPath:` on a nextLink block) fails at parse instead
157
+ // of silently single-paging at runtime.
158
+ // Post-landing note: any schema change touching pagination fields updates
159
+ // these allowlists in the same commit — every future optional pagination
160
+ // field must be added to its style's set here (the allowlist↔parser tripwire
161
+ // in __tests__/parse-api-guide.test.ts enforces the parser side mechanically).
162
+ export const PAGINATION_ALLOWLISTS: Record<
163
+ PaginationStyle,
164
+ ReadonlySet<string>
165
+ > = {
166
+ "offset-limit": new Set([
167
+ "style",
168
+ "itemsPath",
169
+ "pageParam",
170
+ "pageSizeParam",
171
+ "pageSize",
172
+ "base",
173
+ "totalCountPath",
174
+ "hasMorePath",
175
+ ]),
176
+ page: new Set([
177
+ "style",
178
+ "itemsPath",
179
+ "pageParam",
180
+ "pageSizeParam",
181
+ "pageSize",
182
+ "base",
183
+ "totalCountPath",
184
+ "hasMorePath",
185
+ ]),
186
+ nextLink: new Set([
187
+ "style",
188
+ "itemsPath",
189
+ "nextLinkPath",
190
+ "totalCountPath",
191
+ "hasMorePath",
192
+ ]),
193
+ cursor: new Set([
194
+ "style",
195
+ "itemsPath",
196
+ "cursorParam",
197
+ "cursorPath",
198
+ "pageSizeParam",
199
+ "pageSize",
200
+ "totalCountPath",
201
+ "hasMorePath",
202
+ ]),
203
+ resumptionToken: new Set([
204
+ "style",
205
+ "itemsPath",
206
+ "tokenParam",
207
+ "tokenPath",
208
+ "totalCountPath",
209
+ "hasMorePath",
210
+ ]),
211
+ tokenBag: new Set([
212
+ "style",
213
+ "itemsPath",
214
+ "continuationParams",
215
+ "totalCountPath",
216
+ "hasMorePath",
217
+ ]),
218
+ };
219
+
220
+ // Op-block key allowlist — the closed-schema pass's largest surface. An
221
+ // unknown op key (`errorPaths:` instead of `errorPath:`) used to parse clean
222
+ // and silently no-op the intended behavior — worst case, a typo'd error
223
+ // envelope never fires. Exported for the allowlist↔parser tripwire in
224
+ // __tests__/parse-api-guide.test.ts (same two-direction shape as
225
+ // PAGINATION_ALLOWLISTS). Not `pathParamDocs` — that's a parser-derived
226
+ // OUTPUT field built from params.<token>.description, never authored.
227
+ export const OP_ALLOWLIST: ReadonlySet<string> = new Set([
228
+ "name",
229
+ "via",
230
+ "path",
231
+ "accept",
232
+ "params",
233
+ "requiresAnyOf",
234
+ "dateParams",
235
+ "helper",
236
+ "transform",
237
+ "passthrough",
238
+ "parse",
239
+ "errorPath",
240
+ "pagination",
241
+ "gatherAllMax",
242
+ ]);
243
+
244
+ // responseShape block allowlist — same closed-schema pass, same philosophy:
245
+ // only `format` and `charset` are read; anything else is a typo.
246
+ // Exported for the allowlist↔parser tripwire in
247
+ // __tests__/parse-api-guide.test.ts.
248
+ export const RESPONSE_SHAPE_ALLOWLIST: ReadonlySet<string> = new Set([
249
+ "format",
250
+ "charset",
251
+ ]);
252
+
253
+ // Guide-frontmatter key allowlist — the closed-schema pass's third surface.
254
+ // Exactly the 16 keys parseApiGuide reads from the parsed YAML mapping: the
255
+ // 15 literal m["…"] sites plus `domains` (read via requireStringArray).
256
+ // Deliberately NOT Object.keys(const guide) — that would drag in derived
257
+ // non-authored fields (`content`, `category`, `source`). Exported for the
258
+ // allowlist↔parser tripwire in __tests__/parse-api-guide.test.ts.
259
+ export const GUIDE_ALLOWLIST: ReadonlySet<string> = new Set([
107
260
  "kind",
108
- "headers",
109
- "secretRefs",
110
- "secretQueryRefs",
111
- "requires",
112
- "optional",
113
- "headerPrefixes",
261
+ "domains",
262
+ "shortName",
263
+ "updated",
264
+ "icon",
265
+ "apiHost",
266
+ "verified",
267
+ "docs",
268
+ "organization",
269
+ "description",
270
+ "schemaVersion",
271
+ "gatherAllMax",
272
+ "auth",
273
+ "responseShape",
274
+ "operations",
275
+ "pagination",
114
276
  ]);
115
- // Set insertion order — used to render the known-key list in error strings
116
- // (expected + fallback fix) so they can't drift from the set.
117
- const KNOWN_AUTH_KEYS_LIST = [...KNOWN_AUTH_KEYS].join(", ");
118
277
 
119
278
  // ═══════════════════════════════════════════════════════════════════
120
279
  // Error helper
121
280
  // ═══════════════════════════════════════════════════════════════════
122
281
 
282
+ // The migration doc for the current schema bump, resolved from this module's
283
+ // own location so no hardcoded install path is ever rendered — the doc ships
284
+ // in the npm tarball (enforced by ship-manifest.test.ts).
285
+ const MIGRATION_DOC_NOTE = `See the migration guide for this schema bump: ${fileURLToPath(new URL("../docs/migration-v1.md", import.meta.url))}.`;
286
+
123
287
  function fail(
124
288
  file: string | undefined,
125
289
  field: string,
@@ -348,6 +512,21 @@ function validatePagination(
348
512
  }
349
513
  const style = styleRaw as PaginationStyle;
350
514
 
515
+ // Per-style allowlist — reject keys not legal for this style (a typo like
516
+ // `itemPath:` or a `cursorPath:` on a nextLink block fails here instead of
517
+ // silently single-paging at runtime). Format mirrors AUTH_ALLOWLISTS.
518
+ const allowlist = PAGINATION_ALLOWLISTS[style];
519
+ const unknownKeys = Object.keys(p).filter((k) => !allowlist.has(k));
520
+ if (unknownKeys.length > 0) {
521
+ const first = unknownKeys[0]!; // guarded by the length check above
522
+ return fail(
523
+ file,
524
+ `${fieldPrefix}.${first}`,
525
+ `a known pagination key for style: ${style} (${[...allowlist].join(", ")})`,
526
+ `unknown key(s): ${unknownKeys.join(", ")}`,
527
+ );
528
+ }
529
+
351
530
  const itemsPath = p["itemsPath"];
352
531
  if (typeof itemsPath !== "string" || itemsPath === "") {
353
532
  return fail(
@@ -422,6 +601,41 @@ function validatePagination(
422
601
  }
423
602
  Object.assign(cfg, { [req]: v });
424
603
  }
604
+ // Optional, validated-if-present (both were silently dropped before).
605
+ const cPsp = p["pageSizeParam"];
606
+ if (cPsp !== undefined) {
607
+ if (typeof cPsp !== "string" || cPsp === "") {
608
+ return fail(
609
+ file,
610
+ `${fieldPrefix}.pageSizeParam`,
611
+ "a string param name",
612
+ describeFound(cPsp),
613
+ );
614
+ }
615
+ cfg.pageSizeParam = cPsp;
616
+ }
617
+ const cPs = p["pageSize"];
618
+ if (cPs !== undefined) {
619
+ if (typeof cPs !== "number" || !Number.isFinite(cPs) || cPs <= 0) {
620
+ return fail(
621
+ file,
622
+ `${fieldPrefix}.pageSize`,
623
+ "a positive number",
624
+ describeFound(cPs),
625
+ );
626
+ }
627
+ cfg.pageSize = cPs;
628
+ }
629
+ // pageSize without pageSizeParam is inert (the executor seeds only
630
+ // when both are present) — reject rather than silently no-op.
631
+ if (cPs !== undefined && cPsp === undefined) {
632
+ return fail(
633
+ file,
634
+ `${fieldPrefix}.pageSize`,
635
+ "set alongside pageSizeParam (cursor: the seed only applies with both)",
636
+ describeFound(cPs),
637
+ );
638
+ }
425
639
  } else if (style === "resumptionToken") {
426
640
  for (const req of ["tokenParam", "tokenPath"] as const) {
427
641
  const v = p[req];
@@ -473,6 +687,21 @@ function validatePagination(
473
687
  cfg.totalCountPath = tcp;
474
688
  }
475
689
 
690
+ // optional hasMorePath (any style) — JSON path to a boolean/numeric
691
+ // "more pages" flag; a resolved falsy value stops the walk cleanly.
692
+ const hmp = p["hasMorePath"];
693
+ if (hmp !== undefined) {
694
+ if (typeof hmp !== "string" || hmp === "") {
695
+ return fail(
696
+ file,
697
+ `${fieldPrefix}.hasMorePath`,
698
+ "a non-empty string (JSON path to the has-more flag)",
699
+ describeFound(hmp),
700
+ );
701
+ }
702
+ cfg.hasMorePath = hmp;
703
+ }
704
+
476
705
  return cfg;
477
706
  }
478
707
 
@@ -495,6 +724,25 @@ function validateResponseShape(
495
724
  }
496
725
  const r = raw as Record<string, unknown>;
497
726
 
727
+ // responseShape allowlist — same closed-schema pass as OP_ALLOWLIST: only
728
+ // format/charset are read, so anything else is a typo that would
729
+ // silently no-op.
730
+ const unknownKeys = Object.keys(r).filter(
731
+ (k) => !RESPONSE_SHAPE_ALLOWLIST.has(k),
732
+ );
733
+ if (unknownKeys.length > 0) {
734
+ const first = unknownKeys[0]!; // guarded by the length check above
735
+ return fail(
736
+ file,
737
+ `${fieldPrefix}.${first}`,
738
+ `a known responseShape key (${[...RESPONSE_SHAPE_ALLOWLIST].join(", ")})`,
739
+ `unknown key(s): ${unknownKeys.join(", ")}`,
740
+ {
741
+ fix: `Remove ${fieldPrefix}.${first} — the responseShape schema is closed.`,
742
+ },
743
+ );
744
+ }
745
+
498
746
  const formatRaw = r["format"];
499
747
  let format: ResponseFormat = "json";
500
748
  if (formatRaw !== undefined) {
@@ -532,9 +780,8 @@ function validateResponseShape(
532
780
 
533
781
  /**
534
782
  * Validate a `Record<string, string>` auth sub-field (headers, secretRefs,
535
- * secretQueryRefs, headerPrefixes). Returns the parsed record, or a ParseError
536
- * when `raw` is absent/null/non-object/an array, or a value fails `valueOk`
537
- * (default: any string; `headerPrefixes` passes a non-empty check).
783
+ * secretQueryRefs). Returns the parsed record, or a ParseError when `raw` is
784
+ * absent/null/non-object/an array or any value is not a string.
538
785
  */
539
786
  function parseStringRecord(
540
787
  raw: unknown,
@@ -542,13 +789,12 @@ function parseStringRecord(
542
789
  fm: string,
543
790
  field: string,
544
791
  expect: string,
545
- valueOk: (v: unknown) => boolean = (v) => typeof v === "string",
546
792
  ): Record<string, string> | ParseApiGuideResult {
547
793
  if (
548
794
  raw === null ||
549
795
  typeof raw !== "object" ||
550
796
  Array.isArray(raw) ||
551
- Object.values(raw).some((v) => !valueOk(v))
797
+ Object.values(raw).some((v) => typeof v !== "string")
552
798
  ) {
553
799
  return fail(file, field, expect, describeFound(raw), {
554
800
  snippet: snippetFor(fm, "auth"),
@@ -590,7 +836,7 @@ function validateAuth(
590
836
  "a string",
591
837
  kindRaw === undefined ? "missing" : describeFound(kindRaw),
592
838
  {
593
- 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",
839
+ fix: "kind is one of: none | static-key | oauth2 — use `kind: none` (public), `kind: static-key` (keyed header), or `kind: oauth2`; or call api-learn({domain, new: true}) for a full skeleton",
594
840
  },
595
841
  );
596
842
  }
@@ -600,35 +846,175 @@ function validateAuth(
600
846
  "auth.kind",
601
847
  "one of: none | static-key | oauth2",
602
848
  kindRaw,
603
- { fix: "Use `kind: none` (public) or `kind: static-key` (keyed header)" },
849
+ {
850
+ fix: "Use `kind: none` (public), `kind: static-key` (keyed header), or `kind: oauth2`.",
851
+ },
604
852
  );
605
853
  }
606
- // oauth2 is a declared seam, not realized — reject at parse so a recipe
607
- // can't load an auth mode the transport can't honor.
608
- if (kindRaw === "oauth2") {
609
- return fail(file, "auth.kind", "one of: none | static-key", "oauth2", {
610
- fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
611
- });
612
- }
613
- // Strict auth schema — reject unknown keys. The parser used to
614
- // silently drop unknown keys (a wrong-but-plausible shape like
615
- // `name`/`secret` saved a guide the executor then silently couldn't
616
- // honor). Reject, don't infer: `expected` already lists the known keys
617
- // and `found` names the offenders — no separate fix needed.
618
- const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
854
+ const kind = kindRaw as AuthKind;
855
+ // Per-variant allowlist — reject keys not legal for this kind (a
856
+ // `tokenUrl` on a static-key block or a `headerPrefixes` on an oauth2
857
+ // block fails here, not silently downstream).
858
+ const allowlist = AUTH_ALLOWLISTS[kind];
859
+ const unknownKeys = Object.keys(a).filter((k) => !allowlist.has(k));
619
860
  if (unknownKeys.length > 0) {
620
861
  const first = unknownKeys[0]!;
621
862
  return fail(
622
863
  file,
623
864
  `auth.${first}`,
624
- `a known auth key (${KNOWN_AUTH_KEYS_LIST})`,
865
+ `a known auth key for kind: ${kind} (${[...allowlist].join(", ")})`,
625
866
  `unknown key(s): ${unknownKeys.join(", ")}`,
626
867
  {
627
868
  snippet: snippetFor(fm, "auth"),
628
869
  },
629
870
  );
630
871
  }
631
- // Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
872
+
873
+ switch (kind) {
874
+ case "none": {
875
+ let headers: Record<string, string> | undefined;
876
+ if (a["headers"] !== undefined) {
877
+ const hr = parseStringRecord(
878
+ a["headers"],
879
+ file,
880
+ fm,
881
+ "auth.headers",
882
+ "a YAML mapping of string → string",
883
+ );
884
+ if (isParseErr(hr)) return hr;
885
+ headers = hr;
886
+ }
887
+ return { kind: "none", ...(headers === undefined ? {} : { headers }) };
888
+ }
889
+ case "static-key": {
890
+ return validateStaticKeyAuth(a, file, fm);
891
+ }
892
+ case "oauth2": {
893
+ return validateOAuth2Auth(a, file, fm);
894
+ }
895
+ default: {
896
+ const never: never = kind;
897
+ throw new Error(`Unhandled auth kind: ${never}`);
898
+ }
899
+ }
900
+ }
901
+
902
+ /**
903
+ * Parse a nested `Record<string, SecretRef>` (header/form-field name → ref).
904
+ * Each ref is self-contained: `secret` (store name), optional `prefix`, and
905
+ * optional `optional`. The old three-field consistency checks (ref→declared,
906
+ * declared→ref, prefix→ref) are structurally impossible here — there is no
907
+ * `requires`/`optional` roster to diverge from, and `prefix` lives on the ref
908
+ * it applies to.
909
+ */
910
+ function parseSecretRefs(
911
+ raw: unknown,
912
+ file: string | undefined,
913
+ fm: string,
914
+ field: string,
915
+ ): Record<string, SecretRef> | ParseApiGuideResult {
916
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
917
+ return fail(
918
+ file,
919
+ field,
920
+ "a YAML mapping of name → { secret: <store name>, prefix?, optional? }",
921
+ describeFound(raw),
922
+ { snippet: snippetFor(fm, "auth") },
923
+ );
924
+ }
925
+ const out: Record<string, SecretRef> = {};
926
+ for (const [name, v] of Object.entries(raw)) {
927
+ const r = parseSecretRefValue(v, file, fm, `${field}.${name}`);
928
+ if (isParseErr(r)) return r;
929
+ out[name] = r;
930
+ }
931
+ return out;
932
+ }
933
+
934
+ /**
935
+ * Parse a single self-contained `SecretRef` value ({ secret, prefix?,
936
+ * optional? }). Used per-entry by `parseSecretRefs` and directly for the
937
+ * oauth2 named `clientId` / `clientSecret` fields.
938
+ */
939
+ function parseSecretRefValue(
940
+ raw: unknown,
941
+ file: string | undefined,
942
+ fm: string,
943
+ field: string,
944
+ ): SecretRef | ParseApiGuideResult {
945
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
946
+ return fail(
947
+ file,
948
+ field,
949
+ "a mapping with secret: <store name>",
950
+ describeFound(raw),
951
+ { snippet: snippetFor(fm, "auth") },
952
+ );
953
+ }
954
+ const ref = raw as Record<string, unknown>;
955
+ const unknownRefKeys = Object.keys(ref).filter(
956
+ (k) => !["secret", "prefix", "optional"].includes(k),
957
+ );
958
+ if (unknownRefKeys.length > 0) {
959
+ return fail(
960
+ file,
961
+ field,
962
+ "a mapping with only secret/prefix/optional keys",
963
+ `unknown key(s): ${unknownRefKeys.join(", ")}`,
964
+ { snippet: snippetFor(fm, "auth") },
965
+ );
966
+ }
967
+ const secret = ref["secret"];
968
+ if (typeof secret !== "string" || secret.length === 0) {
969
+ return fail(
970
+ file,
971
+ `${field}.secret`,
972
+ "a non-empty store name",
973
+ describeFound(secret),
974
+ { snippet: snippetFor(fm, "auth") },
975
+ );
976
+ }
977
+ let prefix: string | undefined;
978
+ if (ref["prefix"] !== undefined) {
979
+ if (
980
+ typeof ref["prefix"] !== "string" ||
981
+ /^\{[a-zA-Z0-9_]+\}$/.test(ref["prefix"])
982
+ ) {
983
+ return fail(
984
+ file,
985
+ `${field}.prefix`,
986
+ "a string prefix (empty allowed; not a bare {placeholder})",
987
+ describeFound(ref["prefix"]),
988
+ { snippet: snippetFor(fm, "auth") },
989
+ );
990
+ }
991
+ prefix = ref["prefix"];
992
+ }
993
+ let optional: boolean | undefined;
994
+ if (ref["optional"] !== undefined) {
995
+ if (typeof ref["optional"] !== "boolean") {
996
+ return fail(
997
+ file,
998
+ `${field}.optional`,
999
+ "a boolean",
1000
+ describeFound(ref["optional"]),
1001
+ { snippet: snippetFor(fm, "auth") },
1002
+ );
1003
+ }
1004
+ optional = ref["optional"];
1005
+ }
1006
+ return {
1007
+ secret,
1008
+ ...(prefix === undefined ? {} : { prefix }),
1009
+ ...(optional === undefined ? {} : { optional }),
1010
+ };
1011
+ }
1012
+
1013
+ function validateStaticKeyAuth(
1014
+ a: Record<string, unknown>,
1015
+ file: string | undefined,
1016
+ fm: string,
1017
+ ): StaticKeyAuth | ParseApiGuideResult {
632
1018
  let headers: Record<string, string> | undefined;
633
1019
  if (a["headers"] !== undefined) {
634
1020
  const hr = parseStringRecord(
@@ -641,202 +1027,314 @@ function validateAuth(
641
1027
  if (isParseErr(hr)) return hr;
642
1028
  headers = hr;
643
1029
  }
644
-
645
- // static-key reference fields (secretRefs/requires/optional).
646
- let secretRefs: Record<string, string> | undefined;
1030
+ let secretRefs: Record<string, SecretRef> | undefined;
647
1031
  if (a["secretRefs"] !== undefined) {
648
- const sr = parseStringRecord(
649
- a["secretRefs"],
650
- file,
651
- fm,
652
- "auth.secretRefs",
653
- "a YAML mapping of header name → secret name",
654
- );
1032
+ const sr = parseSecretRefs(a["secretRefs"], file, fm, "auth.secretRefs");
655
1033
  if (isParseErr(sr)) return sr;
656
1034
  secretRefs = sr;
657
1035
  }
658
-
659
- // Query-param secrets: maps query param name → secret store name.
660
- // Same shape + consistency rules as secretRefs; the collision-with-op-`params`
661
- // rule is enforced in parseApiGuide (auth is parsed before operations).
662
- let secretQueryRefs: Record<string, string> | undefined;
1036
+ let secretQueryRefs: Record<string, SecretRef> | undefined;
663
1037
  if (a["secretQueryRefs"] !== undefined) {
664
- const qr = parseStringRecord(
1038
+ const qr = parseSecretRefs(
665
1039
  a["secretQueryRefs"],
666
1040
  file,
667
1041
  fm,
668
1042
  "auth.secretQueryRefs",
669
- "a YAML mapping of query param name → secret name",
670
1043
  );
671
1044
  if (isParseErr(qr)) return qr;
672
1045
  secretQueryRefs = qr;
673
1046
  }
1047
+ let secretPathRefs: Record<string, SecretRef> | undefined;
1048
+ if (a["secretPathRefs"] !== undefined) {
1049
+ const pr = parseSecretRefs(
1050
+ a["secretPathRefs"],
1051
+ file,
1052
+ fm,
1053
+ "auth.secretPathRefs",
1054
+ );
1055
+ if (isParseErr(pr)) return pr;
1056
+ // Path-ref entry checks — fail loud, never silently ignore:
1057
+ // - `prefix` is rejected: path injection is the raw value (the store
1058
+ // value fills {name} verbatim).
1059
+ // - `optional` is rejected (presence, not just `true`): path refs are
1060
+ // required-only — an absent token fails closed in fillPathStrict
1061
+ // before any request, so an optional arm is an error-shaped
1062
+ // pseudostate, not a feature.
1063
+ // - a non-\w name is rejected: fillPathTemplate/extractPathTokens
1064
+ // only match {\w+}, so such a name could never fill — reject with
1065
+ // the grammar message instead of a confusing declared-but-unused
1066
+ // typo error downstream.
1067
+ for (const [name, ref] of Object.entries(pr)) {
1068
+ if (!/^\w+$/.test(name)) {
1069
+ return fail(
1070
+ file,
1071
+ `auth.secretPathRefs.${name}`,
1072
+ "a \\w+ path-token name (the {token} grammar matches \\w+ only)",
1073
+ `"${name}"`,
1074
+ {
1075
+ snippet: snippetFor(fm, "auth"),
1076
+ fix: `Rename the ref to an \\w+ name that matches a {token} in some operation's path — e.g. bot_token → {bot_token}.`,
1077
+ },
1078
+ );
1079
+ }
1080
+ if (ref.prefix !== undefined) {
1081
+ return fail(
1082
+ file,
1083
+ `auth.secretPathRefs.${name}.prefix`,
1084
+ "no prefix key — path injection is the raw secret value",
1085
+ `prefix: ${JSON.stringify(ref.prefix)}`,
1086
+ {
1087
+ snippet: snippetFor(fm, "auth"),
1088
+ fix: `Remove prefix from secretPathRefs.${name} — the value fills {${name}} in the path verbatim.`,
1089
+ },
1090
+ );
1091
+ }
1092
+ if (ref.optional !== undefined) {
1093
+ return fail(
1094
+ file,
1095
+ `auth.secretPathRefs.${name}.optional`,
1096
+ "no optional key — path refs are required-only (an absent path token fails closed before the request)",
1097
+ `optional: ${JSON.stringify(ref.optional)}`,
1098
+ {
1099
+ snippet: snippetFor(fm, "auth"),
1100
+ fix: `Remove optional from secretPathRefs.${name} — a path-keyed API has no unauthenticated state.`,
1101
+ },
1102
+ );
1103
+ }
1104
+ }
1105
+ secretPathRefs = pr;
1106
+ }
1107
+ const result: StaticKeyAuth = { kind: "static-key" };
1108
+ if (headers !== undefined) result.headers = headers;
1109
+ if (secretRefs !== undefined) result.secretRefs = secretRefs;
1110
+ if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
1111
+ if (secretPathRefs !== undefined) result.secretPathRefs = secretPathRefs;
1112
+ return result;
1113
+ }
674
1114
 
675
- let requires: string[] | undefined;
676
- const reqRaw = a["requires"];
677
- if (reqRaw !== undefined) {
678
- if (
679
- !Array.isArray(reqRaw) ||
680
- reqRaw.length === 0 ||
681
- reqRaw.some((v) => typeof v !== "string")
682
- ) {
1115
+ function validateOAuth2Auth(
1116
+ a: Record<string, unknown>,
1117
+ file: string | undefined,
1118
+ fm: string,
1119
+ ): OAuth2Auth | ParseApiGuideResult {
1120
+ const grant = a["grant"];
1121
+ if (!isOAuth2Grant(grant)) {
1122
+ return fail(
1123
+ file,
1124
+ "auth.grant",
1125
+ OAUTH2_GRANTS.join(" | "),
1126
+ describeFound(grant),
1127
+ {
1128
+ fix: "grant: client_credentials (server-to-server, no browser) or grant: authorization_code (interactive, PKCE).",
1129
+ },
1130
+ );
1131
+ }
1132
+ const tokenUrl = requireHttpUrl(a["tokenUrl"], "auth.tokenUrl", file, fm, {
1133
+ protocolFix: "Use https:// as the scheme",
1134
+ invalidFix: "Include the scheme, e.g. https://api.example.com/oauth/token",
1135
+ });
1136
+ if (typeof tokenUrl !== "string") return tokenUrl;
1137
+ if (a["clientId"] === undefined) {
1138
+ return fail(
1139
+ file,
1140
+ "auth.clientId",
1141
+ "a secret ref ({ secret: <store name> })",
1142
+ "missing",
1143
+ {
1144
+ snippet: snippetFor(fm, "auth"),
1145
+ fix: "Add clientId: { secret: client_id } — the store name provisioned via /api secrets <domain>. A shippable guide must not bake in one app's client id.",
1146
+ },
1147
+ );
1148
+ }
1149
+ const clientId = parseSecretRefValue(a["clientId"], file, fm, "auth.clientId");
1150
+ if (isParseErr(clientId)) return clientId;
1151
+ if (clientId.prefix !== undefined || clientId.optional !== undefined) {
1152
+ return fail(
1153
+ file,
1154
+ "auth.clientId",
1155
+ "a ref with only { secret } — prefix/optional are meaningless on the client id (it is always required and always used verbatim)",
1156
+ JSON.stringify(clientId),
1157
+ {
1158
+ snippet: snippetFor(fm, "auth"),
1159
+ fix: "Remove prefix/optional from clientId — keep clientId: { secret: <store name> }.",
1160
+ },
1161
+ );
1162
+ }
1163
+ let clientSecret: SecretRef | undefined;
1164
+ if (a["clientSecret"] !== undefined) {
1165
+ const cs = parseSecretRefValue(
1166
+ a["clientSecret"],
1167
+ file,
1168
+ fm,
1169
+ "auth.clientSecret",
1170
+ );
1171
+ if (isParseErr(cs)) return cs;
1172
+ if (cs.prefix !== undefined) {
683
1173
  return fail(
684
1174
  file,
685
- "auth.requires",
686
- "a non-empty list of secret names",
687
- describeFound(reqRaw),
688
- { snippet: snippetFor(fm, "auth") },
1175
+ "auth.clientSecret.prefix",
1176
+ "absent — the prefix would be silently ignored (the raw store value is sent as the client secret)",
1177
+ JSON.stringify(cs.prefix),
1178
+ {
1179
+ snippet: snippetFor(fm, "auth"),
1180
+ fix: "Remove prefix from clientSecret — keep clientSecret: { secret: <store name> }.",
1181
+ },
689
1182
  );
690
1183
  }
691
- requires = reqRaw as string[];
1184
+ if (cs.optional !== undefined && grant === "client_credentials") {
1185
+ return fail(
1186
+ file,
1187
+ "auth.clientSecret.optional",
1188
+ "absent for grant: client_credentials (clientSecret is parser-required there; optional can never fire)",
1189
+ "optional: true",
1190
+ {
1191
+ snippet: snippetFor(fm, "auth"),
1192
+ fix: "Remove optional from clientSecret — keep clientSecret: { secret: <store name> }.",
1193
+ },
1194
+ );
1195
+ }
1196
+ clientSecret = cs;
692
1197
  }
693
-
694
- let optional: string[] | undefined;
695
- const optRaw = a["optional"];
696
- if (optRaw !== undefined) {
1198
+ let secretRefs: Record<string, SecretRef> | undefined;
1199
+ if (a["secretRefs"] !== undefined) {
1200
+ const sr = parseSecretRefs(a["secretRefs"], file, fm, "auth.secretRefs");
1201
+ if (isParseErr(sr)) return sr;
1202
+ secretRefs = sr;
1203
+ }
1204
+ let scopes: string[] | undefined;
1205
+ if (a["scopes"] !== undefined) {
697
1206
  if (
698
- !Array.isArray(optRaw) ||
699
- optRaw.length === 0 ||
700
- optRaw.some((v) => typeof v !== "string")
1207
+ !Array.isArray(a["scopes"]) ||
1208
+ a["scopes"].some((s) => typeof s !== "string")
701
1209
  ) {
702
1210
  return fail(
703
1211
  file,
704
- "auth.optional",
705
- "a non-empty list of secret names",
706
- describeFound(optRaw),
1212
+ "auth.scopes",
1213
+ "a list of scope strings",
1214
+ describeFound(a["scopes"]),
707
1215
  { snippet: snippetFor(fm, "auth") },
708
1216
  );
709
1217
  }
710
- optional = optRaw as string[];
711
- }
712
-
713
- // static-key header prefixes: header name → prefix string prepended to the
714
- // resolved secret value (empty allowed — a bare-key header like CMC's
715
- // X-CMC_PRO_API_KEY has no scheme). Same mapping shape as secretRefs; every
716
- // key must also be a secretRefs header (a prefix for a non-secret header is
717
- // a mistake).
718
- let headerPrefixes: Record<string, string> | undefined;
719
- if (a["headerPrefixes"] !== undefined) {
720
- const hp = parseStringRecord(
721
- a["headerPrefixes"],
722
- file,
723
- fm,
724
- "auth.headerPrefixes",
725
- "a YAML mapping of header name → prefix string (empty allowed for bare-key headers)",
726
- (v) => typeof v === "string" && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
727
- );
728
- if (isParseErr(hp)) return hp;
729
- headerPrefixes = hp;
1218
+ scopes = a["scopes"] as string[];
730
1219
  }
731
-
732
- // Fail-closed consistency rules.
733
- if (
734
- kindRaw === "none" &&
735
- (secretRefs || secretQueryRefs || requires || optional || headerPrefixes)
736
- ) {
737
- return fail(
738
- file,
739
- "auth.secretRefs",
740
- "absent when auth.kind is none",
741
- "secretRefs/secretQueryRefs/requires/optional with kind: none",
742
- {
743
- fix: "Use auth.kind: static-key to reference stored secrets, or remove the auth fields for a public API.",
744
- },
745
- );
1220
+ let paramStyle: OAuth2ParamStyle | undefined;
1221
+ if (a["paramStyle"] !== undefined) {
1222
+ if (a["paramStyle"] !== "bearer-header" && a["paramStyle"] !== "query") {
1223
+ return fail(
1224
+ file,
1225
+ "auth.paramStyle",
1226
+ "bearer-header | query",
1227
+ describeFound(a["paramStyle"]),
1228
+ { snippet: snippetFor(fm, "auth") },
1229
+ );
1230
+ }
1231
+ paramStyle = a["paramStyle"];
746
1232
  }
747
- if (requires || optional || secretRefs || secretQueryRefs) {
748
- const declared = new Set([...(requires ?? []), ...(optional ?? [])]);
749
- const refNames = new Set([
750
- ...Object.values(secretRefs ?? {}),
751
- ...Object.values(secretQueryRefs ?? {}),
752
- ]);
753
- const checkRefs = (
754
- refs: Record<string, string>,
755
- field: string,
756
- ): ParseApiGuideResult | null => {
757
- for (const outName of Object.keys(refs)) {
758
- const secretName = refs[outName]!;
759
- if (!declared.has(secretName)) {
760
- return fail(
761
- file,
762
- `${field}.${outName}`,
763
- "a secret name declared in auth.requires or auth.optional",
764
- `"${secretName}" is not in requires/optional`,
765
- {
766
- fix: `Add "${secretName}" to auth.requires or auth.optional (or fix the reference).`,
767
- },
768
- );
769
- }
770
- }
771
- return null;
772
- };
773
- const r1 = checkRefs(secretRefs ?? {}, "auth.secretRefs");
774
- if (r1) return r1;
775
- const r2 = checkRefs(secretQueryRefs ?? {}, "auth.secretQueryRefs");
776
- if (r2) return r2;
777
- const both = (requires ?? []).filter((n) => (optional ?? []).includes(n));
778
- if (both.length > 0) {
1233
+ let tokenEndpointAuthMethod: OAuth2TokenEndpointAuthMethod | undefined;
1234
+ if (a["tokenEndpointAuthMethod"] !== undefined) {
1235
+ const m = a["tokenEndpointAuthMethod"];
1236
+ if (!isOAuth2TokenEndpointAuthMethod(m)) {
779
1237
  return fail(
780
1238
  file,
781
- "auth.requires",
782
- "secret names not duplicated across requires and optional",
783
- `in both: ${both.join(", ")}`,
784
- {
785
- fix: `Move "${both[0]}" to either requires or optional, not both.`,
786
- },
1239
+ "auth.tokenEndpointAuthMethod",
1240
+ OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS.join(" | "),
1241
+ describeFound(m),
1242
+ { snippet: snippetFor(fm, "auth") },
787
1243
  );
788
1244
  }
789
- const checkDeclared = (
790
- names: string[],
791
- field: string,
792
- ): ParseApiGuideResult | null => {
793
- for (const name of names) {
794
- if (!refNames.has(name)) {
795
- return fail(
796
- file,
797
- field,
798
- "a secret name referenced by auth.secretRefs or auth.secretQueryRefs",
799
- `"${name}" is declared here but not referenced by any header/query ref`,
800
- {
801
- fix: `Reference "${name}" from auth.secretRefs or auth.secretQueryRefs, or remove it from ${field}.`,
802
- },
803
- );
804
- }
805
- }
806
- return null;
807
- };
808
- const r3 = checkDeclared(requires ?? [], "auth.requires");
809
- if (r3) return r3;
810
- const r4 = checkDeclared(optional ?? [], "auth.optional");
811
- if (r4) return r4;
812
- }
813
- // Every headerPrefixes key must target a secret-injected header; a prefix
814
- // for a header that isn't in secretRefs is a mistake. Checked outside the
815
- // secretRefs/requires/optional block so a headerPrefixes-only guide fails
816
- // too (the prefix would otherwise be dead at fetch time silently).
817
- if (headerPrefixes) {
818
- for (const headerName of Object.keys(headerPrefixes)) {
819
- if (!secretRefs || !(headerName in secretRefs)) {
1245
+ tokenEndpointAuthMethod = m;
1246
+ }
1247
+ let authorizeUrl: string | undefined;
1248
+ if (a["authorizeUrl"] !== undefined) {
1249
+ const au = requireHttpUrl(a["authorizeUrl"], "auth.authorizeUrl", file, fm);
1250
+ if (typeof au !== "string") return au;
1251
+ authorizeUrl = au;
1252
+ }
1253
+ let revokeUrl: string | undefined;
1254
+ if (a["revokeUrl"] !== undefined) {
1255
+ const rv = requireHttpUrl(a["revokeUrl"], "auth.revokeUrl", file, fm);
1256
+ if (typeof rv !== "string") return rv;
1257
+ revokeUrl = rv;
1258
+ }
1259
+
1260
+ // Grant invariants — the single shared statement of OAuth2 grant
1261
+ // semantics (also enforced by buildSyntheticOAuth2Auth in core/auth.ts
1262
+ // for the bootstrap surfaces). Adding a grant or invariant: edit
1263
+ // oauth2GrantIssue, then extend both callers' message maps.
1264
+ const issue = oauth2GrantIssue({
1265
+ grant,
1266
+ hasClientSecret: clientSecret !== undefined,
1267
+ authorizeUrl,
1268
+ tokenEndpointAuthMethod,
1269
+ });
1270
+ if (issue) {
1271
+ switch (issue.code) {
1272
+ case "noneWithSecret":
1273
+ return fail(
1274
+ file,
1275
+ "auth.clientSecret",
1276
+ "absent when tokenEndpointAuthMethod: none",
1277
+ "present",
1278
+ {
1279
+ snippet: snippetFor(fm, "auth"),
1280
+ fix: "Remove clientSecret — tokenEndpointAuthMethod: none sends no client credentials (PKCE public clients have no secret).",
1281
+ },
1282
+ );
1283
+ case "ccRequiresSecret":
820
1284
  return fail(
821
1285
  file,
822
- `auth.headerPrefixes.${headerName}`,
823
- "a header name present in auth.secretRefs",
824
- `"${headerName}" is not a secret-injected header`,
1286
+ "auth.clientSecret",
1287
+ "a clientSecret ref for grant: client_credentials",
1288
+ "missing",
825
1289
  {
826
- fix: `Add "${headerName}" to auth.secretRefs (or remove the prefix).`,
1290
+ snippet: snippetFor(fm, "auth"),
1291
+ fix: "Add clientSecret: { secret: client_secret } — the store name provisioned via /api secrets <domain>.",
827
1292
  },
828
1293
  );
1294
+ case "ccRejectsAuthorizeUrl":
1295
+ return fail(
1296
+ file,
1297
+ "auth.authorizeUrl",
1298
+ "absent for grant: client_credentials",
1299
+ "authorizeUrl present",
1300
+ {
1301
+ fix: "Remove authorizeUrl — client_credentials is server-to-server with no browser flow.",
1302
+ },
1303
+ );
1304
+ case "acRequiresAuthorizeUrl":
1305
+ return fail(
1306
+ file,
1307
+ "auth.authorizeUrl",
1308
+ "a URL for grant: authorization_code",
1309
+ "missing",
1310
+ {
1311
+ fix: "Add authorizeUrl — the provider's authorization endpoint. The redirect URI is the runtime convention http://127.0.0.1/callback (RFC 8252 §7.3); register it on your OAuth app.",
1312
+ },
1313
+ );
1314
+ default: {
1315
+ // Compile-time exhaustiveness tripwire: a new OAuth2GrantIssue
1316
+ // code must extend this switch (the builder's message map is
1317
+ // already forced via its return type). Unreachable at runtime.
1318
+ const uncovered: never = issue.code;
1319
+ throw new Error(`unhandled OAuth2 grant invariant: ${String(uncovered)}`);
829
1320
  }
830
1321
  }
831
1322
  }
832
1323
 
833
- const result: AuthConfig = { kind: kindRaw as AuthKind };
834
- if (headers !== undefined) result.headers = headers;
1324
+ const result: OAuth2Auth = {
1325
+ kind: "oauth2",
1326
+ grant,
1327
+ tokenUrl,
1328
+ clientId,
1329
+ ...(clientSecret === undefined ? {} : { clientSecret }),
1330
+ };
835
1331
  if (secretRefs !== undefined) result.secretRefs = secretRefs;
836
- if (headerPrefixes !== undefined) result.headerPrefixes = headerPrefixes;
837
- if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
838
- if (requires !== undefined) result.requires = requires;
839
- if (optional !== undefined) result.optional = optional;
1332
+ if (scopes !== undefined) result.scopes = scopes;
1333
+ if (paramStyle !== undefined) result.paramStyle = paramStyle;
1334
+ if (tokenEndpointAuthMethod !== undefined)
1335
+ result.tokenEndpointAuthMethod = tokenEndpointAuthMethod;
1336
+ if (authorizeUrl !== undefined) result.authorizeUrl = authorizeUrl;
1337
+ if (revokeUrl !== undefined) result.revokeUrl = revokeUrl;
840
1338
  return result;
841
1339
  }
842
1340
 
@@ -849,6 +1347,9 @@ function validateOperation(
849
1347
  index: number,
850
1348
  file: string | undefined,
851
1349
  topPagination: PaginationConfig | undefined,
1350
+ guideResponseShape: ResponseShape,
1351
+ injectedQuerySecretNames: ReadonlySet<string>,
1352
+ authKind: string,
852
1353
  ): Operation | ParseApiGuideResult {
853
1354
  const fieldPath = (leaf: string) => `operations[${index}].${leaf}`;
854
1355
 
@@ -862,6 +1363,23 @@ function validateOperation(
862
1363
  }
863
1364
  const o = raw as Record<string, unknown>;
864
1365
 
1366
+ // Op-block allowlist — reject keys not legal for an op (a typo like
1367
+ // `errorPaths:` would silently no-op the intended behavior). Format
1368
+ // mirrors the pagination per-style allowlist check.
1369
+ const unknownKeys = Object.keys(o).filter((k) => !OP_ALLOWLIST.has(k));
1370
+ if (unknownKeys.length > 0) {
1371
+ const first = unknownKeys[0]!; // guarded by the length check above
1372
+ return fail(
1373
+ file,
1374
+ fieldPath(first),
1375
+ `a known op-block key (${[...OP_ALLOWLIST].join(", ")})`,
1376
+ `unknown key(s): ${unknownKeys.join(", ")}`,
1377
+ {
1378
+ fix: `Remove operations[${index}].${first} — the op-block schema is closed.`,
1379
+ },
1380
+ );
1381
+ }
1382
+
865
1383
  // name
866
1384
  const name = o["name"];
867
1385
  if (typeof name !== "string" || name === "") {
@@ -995,6 +1513,24 @@ function validateOperation(
995
1513
  );
996
1514
  }
997
1515
  const s = spec as Record<string, unknown>;
1516
+ // Unknown-key tripwire — the param-spec schema is closed
1517
+ // (required/default/description/listStyle). A typo'd key
1518
+ // (`listStyl:`, `requried:`) must not be silently dropped: that's
1519
+ // the silent-wrong-wire class. Same philosophy as the
1520
+ // pagination/auth allowlists.
1521
+ for (const k of Object.keys(s)) {
1522
+ if (!PARAM_SPEC_KEYS.has(k)) {
1523
+ return fail(
1524
+ file,
1525
+ fieldPath(`params.${key}.${k}`),
1526
+ `one of: ${[...PARAM_SPEC_KEYS].join(" | ")} (unknown param-spec key)`,
1527
+ `key "${k}"`,
1528
+ {
1529
+ fix: `Remove params.${key}.${k} — did you mean one of: ${[...PARAM_SPEC_KEYS].join(", ")}?`,
1530
+ },
1531
+ );
1532
+ }
1533
+ }
998
1534
  const paramSpec: QueryParamSpec = {};
999
1535
  if (s["required"] !== undefined) {
1000
1536
  if (typeof s["required"] !== "boolean") {
@@ -1021,6 +1557,93 @@ function validateOperation(
1021
1557
  }
1022
1558
  paramSpec.description = s["description"];
1023
1559
  }
1560
+ if (s["listStyle"] !== undefined) {
1561
+ if (!isListStyle(s["listStyle"])) {
1562
+ return fail(
1563
+ file,
1564
+ fieldPath(`params.${key}.listStyle`),
1565
+ `one of: ${LIST_STYLES.join(" | ")}`,
1566
+ describeFound(s["listStyle"]),
1567
+ );
1568
+ }
1569
+ paramSpec.listStyle = s["listStyle"];
1570
+ }
1571
+ // bracket double-dress — the style dresses the wire key with []
1572
+ // itself; a declared name already ending in [] would double-dress
1573
+ // (id[] + [] → id[][]=).
1574
+ if (s["listStyle"] === "bracket" && key.endsWith("[]")) {
1575
+ return fail(
1576
+ file,
1577
+ fieldPath(`params.${key}.listStyle`),
1578
+ "a param name that does not already end in [] (bracket adds the dress itself)",
1579
+ `"${key}" already ends in [] — the wire key would double-dress (id[][]=)`,
1580
+ {
1581
+ fix: `Declare the clean name (params.${key.slice(0, -2)}) with listStyle: bracket — the style appends [] to the wire key.`,
1582
+ },
1583
+ );
1584
+ }
1585
+ // Array default validation — both arms, same pass. An array default
1586
+ // on a non-listStyle param would throw on every call at runtime
1587
+ // (arrays are loud errors there once the serializer widening lands);
1588
+ // catch the authoring error at parse time. On a listStyle param the
1589
+ // elements are validated by the same rules the runtime serializer
1590
+ // enforces (scalars only; no comma-bearing element on comma — the
1591
+ // joined wire form can't distinguish it from a longer list).
1592
+ if (Array.isArray(paramSpec.default)) {
1593
+ if (paramSpec.listStyle === undefined) {
1594
+ return fail(
1595
+ file,
1596
+ fieldPath(`params.${key}.default`),
1597
+ "a scalar default (an array default requires listStyle)",
1598
+ "an array default on a param without listStyle",
1599
+ {
1600
+ fix: `Declare listStyle: ${LIST_STYLES.join(" | ")} on params.${key}, or use a scalar default — an array value on a non-listStyle param fails on every call.`,
1601
+ },
1602
+ );
1603
+ }
1604
+ // Empty array default — the same every-call-throw class as the
1605
+ // styleless case above: the runtime serializer rejects [] (the
1606
+ // param would be silently dropped), so a defaulted call with no
1607
+ // override always fails. Catch it at parse time.
1608
+ if (paramSpec.default.length === 0) {
1609
+ return fail(
1610
+ file,
1611
+ fieldPath(`params.${key}.default`),
1612
+ "a non-empty array default (an empty array default throws on every defaulted call — the param would be silently dropped)",
1613
+ "an empty array default ([])",
1614
+ {
1615
+ fix: `Omit params.${key}.default entirely, or default to a non-empty array — a caller-supplied [] on a listStyle param still fails per-call by design.`,
1616
+ },
1617
+ );
1618
+ }
1619
+ for (const el of paramSpec.default) {
1620
+ if (
1621
+ el === null ||
1622
+ (typeof el !== "string" &&
1623
+ typeof el !== "number" &&
1624
+ typeof el !== "boolean")
1625
+ ) {
1626
+ return fail(
1627
+ file,
1628
+ fieldPath(`params.${key}.default`),
1629
+ "an array of scalar (string | number | boolean) elements",
1630
+ `array contains ${describeFound(el)}`,
1631
+ );
1632
+ }
1633
+ if (
1634
+ paramSpec.listStyle === "comma" &&
1635
+ typeof el === "string" &&
1636
+ el.includes(",")
1637
+ ) {
1638
+ return fail(
1639
+ file,
1640
+ fieldPath(`params.${key}.default`),
1641
+ "comma-free elements (listStyle: comma joins with ',' — a comma-bearing element is indistinguishable from a longer list on the wire)",
1642
+ `element "${el}" contains a comma`,
1643
+ );
1644
+ }
1645
+ }
1646
+ }
1024
1647
  params[key] = paramSpec;
1025
1648
  }
1026
1649
  }
@@ -1031,7 +1654,9 @@ function validateOperation(
1031
1654
  // member-exists, path-param reject, no `required: true` overlap, no
1032
1655
  // `default` on a member. A group member that is `required` would defeat
1033
1656
  // the group at runtime; a `default` would fire alongside a caller-supplied
1034
- // sibling (the members are mutually exclusive peers).
1657
+ // sibling. Semantics are at-least-one-of with all supplied members sent
1658
+ // (members may combine freely); multi-group lands only as the reserved
1659
+ // `requiresAnyOfGroups` sibling key, never a union on this field.
1035
1660
  const requiresAnyOfRaw = o["requiresAnyOf"];
1036
1661
  let requiresAnyOf: string[] | undefined;
1037
1662
  if (requiresAnyOfRaw !== undefined) {
@@ -1076,7 +1701,7 @@ function validateOperation(
1076
1701
  "a param that is not also required: true",
1077
1702
  `"${member}" is required: true`,
1078
1703
  {
1079
- fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf group, not per-param required.`,
1704
+ fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf at-least-one-of group, not per-param required.`,
1080
1705
  },
1081
1706
  );
1082
1707
  }
@@ -1087,7 +1712,7 @@ function validateOperation(
1087
1712
  "a param that does not also declare a default",
1088
1713
  `"${member}" has a default`,
1089
1714
  {
1090
- fix: `Remove the default from params.${member} — requiresAnyOf members are mutually exclusive peers, so a default would fire alongside a caller-supplied sibling.`,
1715
+ fix: `Remove the default from params.${member} — requiresAnyOf members are at-least-one-of peers (all supplied members are sent), so a default would fire alongside a caller-supplied sibling.`,
1091
1716
  },
1092
1717
  );
1093
1718
  }
@@ -1122,6 +1747,20 @@ function validateOperation(
1122
1747
  describeFound(fmt),
1123
1748
  );
1124
1749
  }
1750
+ // Declared-but-dead: date normalization runs only in query assembly
1751
+ // (buildQueryParams), while fillPathTemplate fills path tokens raw —
1752
+ // a dateParams entry naming a path token can never fire.
1753
+ if (pathParams.includes(k)) {
1754
+ return fail(
1755
+ file,
1756
+ fieldPath(`dateParams.${k}`),
1757
+ "a query param name (not a path param)",
1758
+ `"${k}" is a path param — dateParams normalization runs only in query assembly, and path tokens are filled raw, so the declaration can never fire`,
1759
+ {
1760
+ fix: `Put the ISO date directly in the path (the real pattern: Polygon.io aggregates {from}/{to}, Frankfurter /{date}) — a future normalization for path tokens would be additive.`,
1761
+ },
1762
+ );
1763
+ }
1125
1764
  }
1126
1765
  dateParams = dateParamsRaw as Record<string, DateParamFormat>;
1127
1766
  }
@@ -1178,6 +1817,62 @@ function validateOperation(
1178
1817
  parseOverride = pr;
1179
1818
  }
1180
1819
 
1820
+ // errorPath — present-only-on-error envelope path. Guards (all parse-time,
1821
+ // fail-loud in front of the author):
1822
+ // - non-empty string (wrong type → ParseError)
1823
+ // - tokenizeable — a malformed path would resolve `undefined` at runtime,
1824
+ // i.e. declared-absent → success: the exact confidently-wrong failure
1825
+ // mode this field exists to kill. Parse is the only code that runs
1826
+ // exactly once, in front of the author who can fix it.
1827
+ // - non-empty tokenization — the root path ("$", ".") tokenizes to [] and
1828
+ // would resolve the entire parsed body, which is always defined
1829
+ // post-parseResponse — every call would fail.
1830
+ // - effective shape not text — parseResponse returns the raw body string
1831
+ // for text ops and resolveJsonPath against a string always resolves
1832
+ // undefined (declared-then-dead). Covers an op-level parse override AND
1833
+ // an op without one under a text guide-level responseShape.
1834
+ const errorPathRaw = o["errorPath"];
1835
+ let errorPath: string | undefined;
1836
+ if (errorPathRaw !== undefined) {
1837
+ if (typeof errorPathRaw !== "string" || errorPathRaw === "") {
1838
+ return fail(
1839
+ file,
1840
+ fieldPath("errorPath"),
1841
+ "a non-empty string JSON path",
1842
+ describeFound(errorPathRaw),
1843
+ );
1844
+ }
1845
+ const tokens = tokenizeJsonPath(errorPathRaw);
1846
+ if (tokens === null) {
1847
+ return fail(
1848
+ file,
1849
+ fieldPath("errorPath"),
1850
+ "a tokenizeable JSON path",
1851
+ `"${errorPathRaw}" is malformed (unterminated or non-numeric bracket)`,
1852
+ {
1853
+ fix: 'Fix the path syntax — e.g. "OAI-PMH.error" or "result[0].message".',
1854
+ },
1855
+ );
1856
+ }
1857
+ if (tokens.length === 0) {
1858
+ return fail(
1859
+ file,
1860
+ fieldPath("errorPath"),
1861
+ "a JSON path to an error element (not the document root)",
1862
+ `"${errorPathRaw}" resolves the entire parsed body — every call would fail`,
1863
+ );
1864
+ }
1865
+ if ((parseOverride ?? guideResponseShape).format === "text") {
1866
+ return fail(
1867
+ file,
1868
+ fieldPath("errorPath"),
1869
+ "an op whose effective response shape is not format: text",
1870
+ "errorPath can never fire on a text op — parseResponse yields the raw body string, not a resolvable shape",
1871
+ );
1872
+ }
1873
+ errorPath = errorPathRaw;
1874
+ }
1875
+
1181
1876
  // pagination (op-level override)
1182
1877
  const opPaginationRaw = o["pagination"];
1183
1878
  let opPagination: PaginationConfig | undefined;
@@ -1203,6 +1898,97 @@ function validateOperation(
1203
1898
  );
1204
1899
  }
1205
1900
 
1901
+ // listStyle collision guard — under keyed supersession, pagination /
1902
+ // tokenBag continuation writes REPLACE same-named base params, so a
1903
+ // listStyle param colliding with an effective pagination wire name is
1904
+ // dead (its listStyle could never reach the wire). Checked against the
1905
+ // EFFECTIVE config (op-level ?? guide-level) — a guide-level pageParam
1906
+ // collides too. Scoped to via: paginate — the supersession writes only
1907
+ // happen in the paginate executor loop, so a restGet op's params are
1908
+ // never replaced and no collision is possible there. tokenBag wire names
1909
+ // derive via the same wireParamName helper advancePagination uses at
1910
+ // runtime — one derivation, two consumers, no drift. Scope: listStyle
1911
+ // params only; scalar collisions stay legal (the seeded
1912
+ // `page: {default: 0}` + pageParam: page pattern).
1913
+ if (via === "paginate" && effectivePagination !== undefined) {
1914
+ const wireNames: string[] = [];
1915
+ if (effectivePagination.style === "tokenBag") {
1916
+ for (const key of effectivePagination.continuationParams ?? []) {
1917
+ wireNames.push(wireParamName(key));
1918
+ }
1919
+ } else {
1920
+ if (effectivePagination.pageParam)
1921
+ wireNames.push(effectivePagination.pageParam);
1922
+ if (effectivePagination.pageSizeParam)
1923
+ wireNames.push(effectivePagination.pageSizeParam);
1924
+ if (effectivePagination.cursorParam)
1925
+ wireNames.push(effectivePagination.cursorParam);
1926
+ if (effectivePagination.tokenParam)
1927
+ wireNames.push(effectivePagination.tokenParam);
1928
+ }
1929
+ for (const [key, spec] of Object.entries(params)) {
1930
+ if (spec.listStyle === undefined) continue;
1931
+ if (wireNames.includes(key)) {
1932
+ return fail(
1933
+ file,
1934
+ fieldPath(`params.${key}.listStyle`),
1935
+ "a param name not colliding with this operation's pagination wire params",
1936
+ `"${key}" is a pagination wire param (pagination.style: ${effectivePagination.style})`,
1937
+ {
1938
+ fix: `Rename params.${key} — pagination/tokenBag writes replace same-named base params, so the declared listStyle would never reach the wire.`,
1939
+ },
1940
+ );
1941
+ }
1942
+ }
1943
+ // Injected query-secret names vs pagination wire names — the paginate
1944
+ // URL is built as { ...pageParams, ...secretParams } (core/helpers.ts),
1945
+ // so the secret spreads last and overwrites the pagination value on
1946
+ // every page request: pagination silently never advances (valid-looking
1947
+ // 200s, page one forever). Injected names = static-key secretQueryRefs
1948
+ // key names plus oauth2 paramStyle: query's access_token — the same
1949
+ // secretQueryParams seam (core/auth.ts), merged last in the same spread.
1950
+ // Scoped to via: paginate like the listStyle guard — a restGet op never
1951
+ // builds pageParams, so a colliding name is legal there (the guide-level
1952
+ // secretQueryRefs-vs-params check must NOT extend to wire names).
1953
+ for (const secretName of injectedQuerySecretNames) {
1954
+ if (wireNames.includes(secretName)) {
1955
+ const isOAuth2 = authKind === "oauth2";
1956
+ return fail(
1957
+ file,
1958
+ isOAuth2 ? "auth.paramStyle" : `auth.secretQueryRefs.${secretName}`,
1959
+ "an injected query-secret name not colliding with this operation's pagination wire params",
1960
+ `"${secretName}" is a pagination wire param of operation "${name}" (pagination.style: ${effectivePagination.style}) — the injected secret overwrites the pagination value on every page request, so pagination never advances past page one`,
1961
+ {
1962
+ fix: isOAuth2
1963
+ ? `Set auth.paramStyle to bearer-header (or rename the wire param in operation "${name}"'s pagination block) — the query-injected access_token is merged after the pagination params and wins every page request.`
1964
+ : `Rename the secret ref in auth.secretQueryRefs (or the wire param in operation "${name}"'s pagination block) — the secret is merged after the pagination params and wins every page request.`,
1965
+ },
1966
+ );
1967
+ }
1968
+ }
1969
+ }
1970
+
1971
+ // listStyle × dateParams — mutually exclusive by design: date params are
1972
+ // single-valued (the runtime serializer throws before normalization on any
1973
+ // array), so a declared listStyle can never reach the wire. A defaulted
1974
+ // listStyle date param would additionally throw on every defaulted call —
1975
+ // the same every-call-throw class the array-default guard above exists for.
1976
+ if (dateParams !== undefined) {
1977
+ for (const key of Object.keys(dateParams)) {
1978
+ if (params[key]?.listStyle !== undefined) {
1979
+ return fail(
1980
+ file,
1981
+ fieldPath(`dateParams.${key}`),
1982
+ "a param not declaring listStyle (date params are single-valued — listStyle can never apply)",
1983
+ `"${key}" declares both listStyle: ${params[key]!.listStyle} and a dateParams entry`,
1984
+ {
1985
+ fix: `Drop one of the two — keep dateParams.${key} for date normalization, or remove it and declare listStyle on params.${key} if the API truly accepts multi-value dates.`,
1986
+ },
1987
+ );
1988
+ }
1989
+ }
1990
+ }
1991
+
1206
1992
  // gatherAllMax (op-level override)
1207
1993
  const opGatherAllMaxRaw = o["gatherAllMax"];
1208
1994
  let opGatherAllMax: number | undefined;
@@ -1236,6 +2022,7 @@ function validateOperation(
1236
2022
  ...(dateParams === undefined ? {} : { dateParams }),
1237
2023
  ...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
1238
2024
  ...(parseOverride ? { parse: parseOverride } : {}),
2025
+ ...(errorPath === undefined ? {} : { errorPath }),
1239
2026
  ...(opPagination ? { pagination: opPagination } : {}),
1240
2027
  ...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
1241
2028
  };
@@ -1354,6 +2141,24 @@ export function parseApiGuide(
1354
2141
  }
1355
2142
  const m = meta as Record<string, unknown>;
1356
2143
 
2144
+ // Frontmatter allowlist — reject keys parseApiGuide never reads (a typo'd
2145
+ // top-level key would be silently ignored today and hard-fail later once
2146
+ // the schema is published). Same closed-schema check as the op-block
2147
+ // allowlist; format mirrors the pagination per-style allowlist check.
2148
+ const unknownFmKeys = Object.keys(m).filter((k) => !GUIDE_ALLOWLIST.has(k));
2149
+ if (unknownFmKeys.length > 0) {
2150
+ const first = unknownFmKeys[0]!; // guarded by the length check above
2151
+ return fail(
2152
+ file,
2153
+ first,
2154
+ `a known frontmatter key (${[...GUIDE_ALLOWLIST].join(", ")})`,
2155
+ `unknown key(s): ${unknownFmKeys.join(", ")}`,
2156
+ {
2157
+ fix: `Remove ${first} from the frontmatter — the guide schema is closed.`,
2158
+ },
2159
+ );
2160
+ }
2161
+
1357
2162
  // ── projection slice ──────────────────────────────────────────
1358
2163
  const kindRaw = m["kind"];
1359
2164
  if (kindRaw !== undefined && kindRaw !== "api") {
@@ -1452,14 +2257,13 @@ export function parseApiGuide(
1452
2257
  description = descriptionRaw;
1453
2258
  }
1454
2259
 
1455
- // schemaVersion — breaking-change detection (design: "schemaVersion is
1456
- // detection, not enforcement"). Stamped on save by api-learn; absent-on-
1457
- // read defaults to 0 (the floor), so an unversioned guide flags as
1458
- // potentially stale after any schema bump rather than silently inheriting
1459
- // the new current. A valid-integer frontmatter value overrides the floor.
1460
- // A stale value (< current) warns non-blockingly in the api-guide catalog/
1461
- // detail and on api-fetch; never gates. A malformed (non-integer/negative)
1462
- // value falls back to 0 and never rejects a guide.
2260
+ // schemaVersion — breaking-change detection, enforced by the hard gate.
2261
+ // Stamped on save by api-learn; absent-on-read defaults to 0 (the floor),
2262
+ // so an unversioned guide is treated as pre-v1. A valid-integer frontmatter
2263
+ // value overrides the floor. A stale value (< current) fails to parse and
2264
+ // routes to malformed (the gate below). A malformed (non-integer/negative)
2265
+ // value also falls to the floor 0 and is caught by the same gate — one
2266
+ // code path, one message.
1463
2267
  let schemaVersion = 0;
1464
2268
  const schemaVersionRaw = m["schemaVersion"];
1465
2269
  if (
@@ -1469,6 +2273,20 @@ export function parseApiGuide(
1469
2273
  ) {
1470
2274
  schemaVersion = schemaVersionRaw;
1471
2275
  }
2276
+ if (isStaleSchema(schemaVersion, GUIDE_SCHEMA_VERSION)) {
2277
+ return fail(
2278
+ file,
2279
+ "schemaVersion",
2280
+ `>= ${GUIDE_SCHEMA_VERSION} (current)`,
2281
+ describeFound(schemaVersionRaw),
2282
+ {
2283
+ fix:
2284
+ `Guide ${file ?? "this guide"} was authored against schema ${schemaVersion}; the current schema is ${GUIDE_SCHEMA_VERSION}. ` +
2285
+ `Re-stamp its frontmatter to schemaVersion: ${GUIDE_SCHEMA_VERSION}, hand-fixing any breaking changes listed in the migration doc. ${MIGRATION_DOC_NOTE} ` +
2286
+ `Ask your agent to make this fix, then /reload.`,
2287
+ },
2288
+ );
2289
+ }
1472
2290
 
1473
2291
  let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
1474
2292
  const gatherAllMaxRaw = m["gatherAllMax"];
@@ -1528,10 +2346,30 @@ export function parseApiGuide(
1528
2346
  );
1529
2347
  }
1530
2348
  const operations: Operation[] = [];
2349
+ // Injected query-secret names (the secretQueryParams seam in core/auth.ts):
2350
+ // static-key secretQueryRefs key names, plus oauth2 paramStyle: query's
2351
+ // access_token. Derived once here (auth is validated above) and passed to
2352
+ // every validateOperation for the paginate wire-name collision check.
2353
+ const injectedQuerySecretNames: ReadonlySet<string> = new Set([
2354
+ ...(auth.kind === "static-key" && auth.secretQueryRefs
2355
+ ? Object.keys(auth.secretQueryRefs)
2356
+ : []),
2357
+ ...(auth.kind === "oauth2" && auth.paramStyle === "query"
2358
+ ? ["access_token"]
2359
+ : []),
2360
+ ]);
1531
2361
  for (let i = 0; i < opsRaw.length; i++) {
1532
2362
  const opRaw = opsRaw[i];
1533
2363
  if (opRaw === undefined) continue;
1534
- const opRes = validateOperation(opRaw, i, file, pagination);
2364
+ const opRes = validateOperation(
2365
+ opRaw,
2366
+ i,
2367
+ file,
2368
+ pagination,
2369
+ responseShape,
2370
+ injectedQuerySecretNames,
2371
+ auth.kind,
2372
+ );
1535
2373
  if (!("name" in opRes)) return opRes as ParseApiGuideResult;
1536
2374
  operations.push(opRes);
1537
2375
  }
@@ -1560,6 +2398,82 @@ export function parseApiGuide(
1560
2398
  }
1561
2399
  }
1562
2400
 
2401
+ // Cross-field (oauth2 arm of the same D1 class): on paramStyle: query the
2402
+ // injected access_token must not be a declared op param — it spreads last
2403
+ // in `{ ...query, ...secretParams }`, so the agent's value would be
2404
+ // silently overwritten. Scoped to paramStyle: query — with the default
2405
+ // bearer-header the token rides the Authorization header and a legit
2406
+ // access_token query param is legal. Paginate ops with access_token as a
2407
+ // wire name are already rejected earlier by the wire-name collision check.
2408
+ if (auth.kind === "oauth2" && auth.paramStyle === "query") {
2409
+ for (const dOp of operations) {
2410
+ if ("access_token" in dOp.params) {
2411
+ return fail(
2412
+ file,
2413
+ "auth.paramStyle",
2414
+ "an injected query-secret name not declared in any operation's params",
2415
+ `also a param of operation "${dOp.name}"`,
2416
+ {
2417
+ fix: `Remove access_token from operation "${dOp.name}"'s params map — it is code-injected from the token store on paramStyle: query and the agent must not be able to set it.`,
2418
+ },
2419
+ );
2420
+ }
2421
+ }
2422
+ }
2423
+
2424
+ // Cross-field: secretPathRefs rules. Every path-ref name is a
2425
+ // secret-owned path token — the agent must never be able to set it, and
2426
+ // it must be load-bearing. Checked after operations (the operative fact
2427
+ // is that this runs after BOTH parses):
2428
+ // - a name in any op's `params` map (agent-suppliable). Path-token-keyed
2429
+ // params entries never reach dOp.params (the parser routes them to
2430
+ // pathParamDocs, description-only), so `in dOp.params` is exactly
2431
+ // "agent-suppliable" — a docs-only params.<name>.description entry
2432
+ // stays legal.
2433
+ // - a name in NO op's path as {name} → declared-but-unused (typo).
2434
+ // - a name shared with secretQueryRefs — would inject one secret into
2435
+ // the path and another into the query under the same name.
2436
+ if (auth.kind === "static-key" && auth.secretPathRefs) {
2437
+ for (const paramName of Object.keys(auth.secretPathRefs)) {
2438
+ if (auth.secretQueryRefs && paramName in auth.secretQueryRefs) {
2439
+ return fail(
2440
+ file,
2441
+ `auth.secretPathRefs.${paramName}`,
2442
+ "a path-token name not shared with secretQueryRefs",
2443
+ `also a secretQueryRefs key`,
2444
+ {
2445
+ fix: `"${paramName}" is declared in both secretPathRefs and secretQueryRefs — one would fill it in the path and the other in the query under the same name. Rename one.`,
2446
+ },
2447
+ );
2448
+ }
2449
+ for (const dOp of operations) {
2450
+ if (paramName in dOp.params) {
2451
+ return fail(
2452
+ file,
2453
+ `auth.secretPathRefs.${paramName}`,
2454
+ "a path-token name not declared in any operation's params",
2455
+ `also a param of operation "${dOp.name}"`,
2456
+ {
2457
+ fix: `Remove "${paramName}" from operation "${dOp.name}"'s params map — it is code-injected from the secrets store and the agent must not be able to set it. (A docs-only params.${paramName}.description entry is fine.)`,
2458
+ },
2459
+ );
2460
+ }
2461
+ }
2462
+ const used = operations.some((dOp) => dOp.pathParams.includes(paramName));
2463
+ if (!used) {
2464
+ return fail(
2465
+ file,
2466
+ `auth.secretPathRefs.${paramName}`,
2467
+ `a path-token name used by at least one operation's path as {${paramName}}`,
2468
+ "no operation's path contains {" + paramName + "}",
2469
+ {
2470
+ fix: `Use {${paramName}} in at least one operation's path, or remove the secretPathRefs entry (declared-but-unused is usually a typo).`,
2471
+ },
2472
+ );
2473
+ }
2474
+ }
2475
+ }
2476
+
1563
2477
  const guide: ApiGuide = {
1564
2478
  content,
1565
2479
  updated,
@@ -1584,191 +2498,8 @@ export function parseApiGuide(
1584
2498
  return { ok: true, guide };
1585
2499
  }
1586
2500
 
1587
- // ═══════════════════════════════════════════════════════════════════
1588
- // projectToGuide — strips recipe fields, keeps presentation + kind
1589
- // ═══════════════════════════════════════════════════════════════════
1590
-
1591
- export function projectToGuide(guide: ApiGuide): Guide {
1592
- const projection: Guide = {
1593
- content: guide.content,
1594
- updated: guide.updated,
1595
- category: guide.category,
1596
- source: guide.source,
1597
- icon: guide.icon,
1598
- shortName: guide.shortName,
1599
- kind: guide.kind,
1600
- ...(guide.domains ? { domains: guide.domains } : {}),
1601
- };
1602
- return projection;
1603
- }
1604
-
1605
- // ═══════════════════════════════════════════════════════════════════
1606
- // Directory loader — one malformed guide doesn't block the store.
1607
- //
1608
- // Loads from per-guide subdirectories: <dir>/<slug(shortName)>/guide.md.
1609
- // The folder name must equal slug(shortName) — a divergent folder routes to
1610
- // malformed (enforced), so the active set holds at most one guide per
1611
- // shortName. Flat top-level .md files are not loaded.
1612
- // ═══════════════════════════════════════════════════════════════════
1613
-
1614
- /**
1615
- * Push a malformed guide and warn about it. One helper owns both the catalog
1616
- * entry and the load-time warn, so every malformed guide — parse
1617
- * failure, illegal shortName, divergent folder — surfaces the same signal
1618
- * (and its actionable `fix` when present) instead of being silently
1619
- * quarantined. Fires once per cached scan, same channel as the duplicate-
1620
- * shortName check.
1621
- */
1622
- function pushMalformed(
1623
- result: LoadedApiGuides,
1624
- file: string,
1625
- filename: string,
1626
- error: ParseError,
1627
- warn: (msg: string) => void,
1628
- ): void {
1629
- result.malformed.push({ file, filename, error });
1630
- warn(
1631
- `⚠ Malformed guide '${filename}': ${error.field} — expected ${error.expected}; found ${error.found}.` +
1632
- (error.fix ? ` ${error.fix}` : ""),
1633
- );
1634
- }
1635
-
1636
- export function loadApiGuidesFromDir(
1637
- dir: string,
1638
- notify?: NotifyFn,
1639
- ): LoadedApiGuides {
1640
- const result: LoadedApiGuides = { guides: {}, malformed: [] };
1641
- if (!existsSync(dir)) return result;
1642
- let entries: string[];
1643
- try {
1644
- entries = readdirSync(dir);
1645
- } catch {
1646
- return result;
1647
- }
1648
- // Scan-local duplicate-shortName tracker (migration-window check only).
1649
- // shortName → the first folder that declared it, so the duplicate warning
1650
- // can name both folders. Not a field on LoadedApiGuides.
1651
- const seenShortNames = new Map<string, string>();
1652
-
1653
- // Every load-time diagnostic routes through one channel: ctx.ui.notify
1654
- // when the caller has a UI context (renders via the Text component —
1655
- // wraps long lines, honors newlines), else console.warn. One fallback
1656
- // here, not one repeated per call site.
1657
- const warn = (msg: string) => {
1658
- if (notify) notify(msg, "warning");
1659
- else console.warn(msg);
1660
- };
1661
-
1662
- // TODO(0.5.0): remove — migration banner for the 0.4.0 folder-structure
1663
- // change only. The permanent divergence + illegal-shortName checks below
1664
- // stay; only this prelude and the duplicate-shortName check are 0.5.0
1665
- // deletions. Fires once, immediately before the first identity warning, so
1666
- // it prepends the wall of migration warnings with the agent instructions.
1667
- let bannerEmitted = false;
1668
- const emitMigrationBanner = () => {
1669
- if (bannerEmitted) return;
1670
- bannerEmitted = true;
1671
- const msg =
1672
- `\n⚠ pi-lean-host 0.4.0 changed the guide folder structure: each guide must now live ` +
1673
- `in a folder named slug(shortName). Pass the warnings below to the ` +
1674
- `agent to fix them (rename the folder or set a valid shortName), then /reload.\n`;
1675
- warn(msg);
1676
- };
1677
- for (const entry of entries) {
1678
- const entryPath = join(dir, entry);
1679
- try {
1680
- if (!statSync(entryPath).isDirectory()) continue;
1681
- } catch {
1682
- continue;
1683
- }
1684
- const guidePath = join(entryPath, "guide.md");
1685
- try {
1686
- if (!statSync(guidePath).isFile()) continue;
1687
- } catch {
1688
- continue;
1689
- }
1690
- const name = entry; // folder name = slug(shortName) in steady state
1691
- let raw: string;
1692
- try {
1693
- raw = readFileSync(guidePath, "utf-8");
1694
- } catch {
1695
- continue;
1696
- }
1697
- const parsed = parseApiGuide(raw, {
1698
- file: guidePath,
1699
- filename: name,
1700
- });
1701
- if (parsed.ok) {
1702
- const guide = parsed.guide;
1703
- // Illegal-shortName + divergence checks (permanent). One try/catch
1704
- // owns the slug() call: a throw (empty or all-symbol shortName) is
1705
- // routed to malformed, never escaped. This wrapping lives in the
1706
- // permanent checks so the loader stays safe after the 0.5.0
1707
- // duplicate-check deletion.
1708
- let slugged: string;
1709
- try {
1710
- slugged = slug(guide.shortName);
1711
- } catch {
1712
- emitMigrationBanner();
1713
- pushMalformed(
1714
- result,
1715
- guidePath,
1716
- name,
1717
- {
1718
- field: "shortName",
1719
- expected: "a shortName that slugs to a non-empty safe directory name",
1720
- found: `"${guide.shortName}"`,
1721
- fix: "Set a valid shortName (lowercase letters, digits, and '-') in the guide's frontmatter.",
1722
- },
1723
- warn,
1724
- );
1725
- continue;
1726
- }
1727
- // TODO(0.5.0): remove — save-time slug() makes duplicate shortNames
1728
- // unreachable once all folders are migrated. Tracked on guides that
1729
- // pass the slug (before divergence routing) so the migration window —
1730
- // two divergent folders sharing a valid shortName — still surfaces a
1731
- // clear "delete one" warning instead of two opaque malformed entries.
1732
- const first = seenShortNames.get(guide.shortName);
1733
- if (first === undefined) {
1734
- seenShortNames.set(guide.shortName, entry);
1735
- } else {
1736
- emitMigrationBanner();
1737
- const dupMsg =
1738
- `⚠ Duplicate shortName '${guide.shortName}' in folders '${first}' and '${entry}'. ` +
1739
- `Delete one: /api delete <one>`;
1740
- warn(dupMsg);
1741
- }
1742
- // Divergence check (permanent) — ENFORCED, not advisory: the folder
1743
- // name must equal slug(shortName); the coupling IS the identity. A
1744
- // divergent guide routes to malformed (never loads), so the active
1745
- // set structurally holds at most one guide per shortName.
1746
- if (entry !== slugged) {
1747
- emitMigrationBanner();
1748
- pushMalformed(
1749
- result,
1750
- guidePath,
1751
- name,
1752
- {
1753
- field: "shortName",
1754
- expected: `a folder named slug(shortName) ('${slugged}')`,
1755
- found: `folder '${entry}'`,
1756
- fix: `Rename the folder to '${slugged}': mv ${entryPath} ${join(dir, slugged)}`,
1757
- },
1758
- warn,
1759
- );
1760
- continue;
1761
- }
1762
- result.guides[entry] = guide;
1763
- } else {
1764
- pushMalformed(result, guidePath, name, parsed.error, warn);
1765
- }
1766
- }
1767
- return result;
1768
- }
1769
-
1770
2501
  // ════════════════════════════════════════════════════════════════════
1771
- // Schema-version staleness — detection, never a gate
2502
+ // Schema-version staleness — the hard gate's predicate
1772
2503
  // ════════════════════════════════════════════════════════════════════
1773
2504
 
1774
2505
  /**
@@ -1782,205 +2513,3 @@ export function isStaleSchema(
1782
2513
  ): boolean {
1783
2514
  return guideSchemaVersion < currentSchemaVersion;
1784
2515
  }
1785
-
1786
- /**
1787
- * Non-blocking stale-schema warning line for a guide, or undefined when the
1788
- * guide is current. Peer of the `⚠ malformed` catalog line — detection,
1789
- * never a gate (the guide still loads and runs). `current` defaults to
1790
- * GUIDE_SCHEMA_VERSION; tests pass a bumped value to force staleness.
1791
- */
1792
- export function staleSchemaLine(
1793
- guide: ApiGuide,
1794
- current: number = GUIDE_SCHEMA_VERSION,
1795
- ): string | undefined {
1796
- const v = guide.schemaVersion ?? 0;
1797
- if (!isStaleSchema(v, current)) return undefined;
1798
- return ` ⚠ schemaVersion ${v} < current ${current} — guide may need updating`;
1799
- }
1800
-
1801
- // ════════════════════════════════════════════════════════════════════
1802
- // Disambiguation helpers — shared by the api-guide menu and the
1803
- // api-fetch ambiguous-operation error. One rendering of the per-guide
1804
- // listing so the two surfaces stay visually consistent.
1805
- // ════════════════════════════════════════════════════════════════════
1806
-
1807
- /**
1808
- * Truncated op-name summary for disambiguation surfaces:
1809
- * "N ops: a, b, c, d, e, +K more" (first 5 names, then the remaining count).
1810
- * A 50-op guide must not dump 50 names into context — the menu exists to
1811
- * help pick a guide cheaply; the full op list is one api-guide call away.
1812
- */
1813
- function formatOpSummary(ops: { name: string }[]): string {
1814
- const names = ops.map((o) => o.name);
1815
- const count = names.length;
1816
- const head = names.slice(0, 5);
1817
- const remaining = count - head.length;
1818
- const tail = remaining > 0 ? `, +${remaining} more` : "";
1819
- return `${count} ops: ${head.join(", ")}${tail}`;
1820
- }
1821
-
1822
- /**
1823
- * Per-guide listing lines for a disambiguation surface (the api-guide
1824
- * multi-guide menu and the api-fetch ambiguous-op error). Each entry:
1825
- * `icon shortName` [+ ` — description` when present] then the truncated
1826
- * op-name list. When `description:` is absent the line falls back to
1827
- * shortName + op names only (the status-quo shape), so un-backfilled
1828
- * guides render consistently with those that have a one-line summary.
1829
- */
1830
- export function formatGuideListings(
1831
- entries: { guide: ApiGuide }[],
1832
- current: number = GUIDE_SCHEMA_VERSION,
1833
- ): string {
1834
- const lines: string[] = [];
1835
- for (const { guide } of entries) {
1836
- lines.push(
1837
- ` ${guide.icon} ${guide.shortName}` +
1838
- (guide.description ? ` — ${guide.description}` : ""),
1839
- );
1840
- lines.push(` ${formatOpSummary(guide.operations)}`);
1841
- const stale = staleSchemaLine(guide, current);
1842
- if (stale) lines.push(stale);
1843
- }
1844
- return lines.join("\n");
1845
- }
1846
-
1847
- /**
1848
- * Resolve a guide by shortName across a domain's matches (exact,
1849
- * case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
1850
- * /api verify — three call sites, one resolution rule (a drifted copy would
1851
- * ship a known second bug). Returns a structured outcome; each caller renders
1852
- * its own message (tool result vs command notify).
1853
- */
1854
- export function selectGuideByShortName(
1855
- matches: { guide: ApiGuide; dirName: string }[],
1856
- selector: string,
1857
- ):
1858
- | { ok: true; guide: ApiGuide; dirName: string }
1859
- | { ok: false; reason: "no_match"; valid: string[] }
1860
- | { ok: false; reason: "ambiguous"; directories: string[] } {
1861
- const lc = selector.toLowerCase();
1862
- const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
1863
- if (sel.length === 0) {
1864
- return {
1865
- ok: false,
1866
- reason: "no_match",
1867
- valid: matches.map((m) => m.guide.shortName),
1868
- };
1869
- }
1870
- if (sel.length > 1) {
1871
- return {
1872
- ok: false,
1873
- reason: "ambiguous",
1874
- directories: sel.map((s) => s.dirName),
1875
- };
1876
- }
1877
- return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
1878
- }
1879
-
1880
- /**
1881
- * Render the no-match / ambiguous error text for a failed
1882
- * `selectGuideByShortName` result. `callToAction` is the trailing
1883
- * "how to see the menu" sentence — it differs per surface (tool vs
1884
- * command), so callers pass their own.
1885
- */
1886
- export function shortNameErrorText(
1887
- sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
1888
- domain: string,
1889
- selector: string,
1890
- callToAction: string,
1891
- ): string {
1892
- if (sel.reason === "no_match") {
1893
- return (
1894
- `No guide named '${selector}' for '${domain}'. ` +
1895
- `Available guides: ${sel.valid.join(", ")}. ` +
1896
- callToAction
1897
- );
1898
- }
1899
- return (
1900
- `Ambiguous guide '${selector}' for '${domain}' — ` +
1901
- `${sel.directories.length} guides share shortName '${selector}' ` +
1902
- `(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
1903
- `disambiguate. ` +
1904
- callToAction
1905
- );
1906
- }
1907
-
1908
- // ════════════════════════════════════════════════════════════════════
1909
- // Catalog rendering — healthy + ⚠ malformed together
1910
- //
1911
- // Base catalog is collapsed by `organization:`: one line per org with its
1912
- // guide count and domain set. Guides without `organization:` fall back to
1913
- // the per-guide line, so the un-backfilled corpus renders unchanged (no
1914
- // forced migration). Op counts live on the per-domain disambiguation menu
1915
- // (api-guide {domain}), where they're useful for picking a guide — not
1916
- // here, where they'd bloat context for orgs with many guides.
1917
- // ════════════════════════════════════════════════════════════════════
1918
-
1919
- export function formatApiGuideCatalog(
1920
- loaded: LoadedApiGuides,
1921
- current: number = GUIDE_SCHEMA_VERSION,
1922
- ): string {
1923
- const lines: string[] = ["API guides:"];
1924
-
1925
- // Org-grouped rows preserve first-appearance order; guides without
1926
- // organization fall back to the per-guide line (no forced migration).
1927
- const orgRows: { org: string; guides: ApiGuide[] }[] = [];
1928
- const orgIndex = new Map<string, number>();
1929
- const orgless: { name: string; guide: ApiGuide }[] = [];
1930
- for (const [name, guide] of Object.entries(loaded.guides)) {
1931
- if (guide.organization) {
1932
- const idx = orgIndex.get(guide.organization);
1933
- if (idx === undefined) {
1934
- orgIndex.set(guide.organization, orgRows.length);
1935
- orgRows.push({ org: guide.organization, guides: [guide] });
1936
- } else {
1937
- orgRows[idx]!.guides.push(guide);
1938
- }
1939
- } else {
1940
- orgless.push({ name, guide });
1941
- }
1942
- }
1943
-
1944
- for (const row of orgRows) {
1945
- const domains = new Set<string>();
1946
- for (const g of row.guides) {
1947
- for (const d of g.domains ?? []) domains.add(d);
1948
- }
1949
- const domList = domains.size > 0 ? [...domains].join(", ") : "—";
1950
- const n = row.guides.length;
1951
- // Collapsed org row: a trailing ⚠ glyph when ANY guide in it is stale
1952
- // (hint only — the per-guide ⚠ line lives on the menu / detail view).
1953
- const stale = row.guides.some((g) =>
1954
- isStaleSchema(g.schemaVersion ?? 0, current),
1955
- );
1956
- lines.push(
1957
- ` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})${stale ? " ⚠" : ""}`,
1958
- );
1959
- }
1960
- for (const { name, guide } of orgless) {
1961
- const domains =
1962
- guide.domains && guide.domains.length > 0 ? guide.domains.join(", ") : name;
1963
- lines.push(
1964
- ` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
1965
- );
1966
- const stale = staleSchemaLine(guide, current);
1967
- if (stale) lines.push(stale);
1968
- }
1969
- for (const mal of loaded.malformed) {
1970
- lines.push(
1971
- ` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
1972
- );
1973
- // Actionable advice on its own line, matching api-fetch/api-learn's
1974
- // `Fix:` convention — multi-line fixes (e.g. the frontmatter template)
1975
- // render naturally instead of being inlined into the summary line.
1976
- if (mal.error.fix) lines.push(` fix: ${mal.error.fix}`);
1977
- }
1978
- if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
1979
- lines.push(" (no guides — call api-learn({domain, dir}) to author one)");
1980
- }
1981
- lines.push("");
1982
- lines.push(
1983
- 'Call api-guide({domain: "<name>"}) for detail. Multiple guides for a domain show a disambiguation menu.',
1984
- );
1985
- return lines.join("\n");
1986
- }