@pipeworx/mcp-govinfo 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  interface McpToolDefinition {
2
2
  name: string;
3
3
  description: string;
4
+ /** Human-facing one-liner (fleet #1967). Optional; consumers fall back to
5
+ * description. Kept in step with shared/src/types.ts — scripts/lib/
6
+ * check-inlined-types.mjs reports drift at publish time. */
7
+ summary?: string;
4
8
  inputSchema: {
5
9
  type: 'object';
6
10
  properties: Record<string, unknown>;
7
11
  required?: string[];
12
+ anyOf?: Array<{ required: string[] }>;
13
+ oneOf?: Array<{ required: string[] }>;
14
+ allOf?: Array<{ required: string[] }>;
8
15
  };
16
+ outputSchema?: Record<string, unknown>;
9
17
  }
10
18
 
11
19
  interface McpToolExport {
@@ -16,6 +24,652 @@ interface McpToolExport {
16
24
  provider?: string;
17
25
  }
18
26
 
27
+ /**
28
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
29
+ *
30
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
31
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
32
+ * covered the majority and structurally could not cover the rest: the rest
33
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
34
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
35
+ *
36
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
37
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
38
+ *
39
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
40
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
41
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
42
+ * our own Supabase for fleet. There is no third party anywhere in either call.
43
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
44
+ * class that means "the source is unreachable and there is nothing for us to
45
+ * fix", which is why the problem-tools triage skips it.
46
+ *
47
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
48
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
49
+ * one site today, so it would work today. It would also rot the first time
50
+ * somebody rewords a label — silently, and in the direction of hiding our own
51
+ * outage, which is worse than the bug being fixed. Every prose rule in
52
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
53
+ * #584); that history is most of that file's comment budget.
54
+ *
55
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
56
+ * hostname is a fact about the call, not a guess about its prose. Two
57
+ * consequences that a pack-level flag could not give us, and the reason the
58
+ * flag was rejected:
59
+ *
60
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
61
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
62
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
63
+ * either pack would relabel a real third-party outage as ours — inventing
64
+ * work, which is the same class of error in the opposite direction.
65
+ * - It covers every future internal pack for free, instead of one declared
66
+ * slug at a time.
67
+ *
68
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
69
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
70
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
71
+ * this module — so changing the wording changes both sides in the same edit and
72
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
73
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
74
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
75
+ * from its own classifier three times and needed a CI gate to hold them
76
+ * together.
77
+ *
78
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
79
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
80
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
81
+ * availability failure" is decided from the actual status code, never re-derived
82
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
83
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
84
+ */
85
+
86
+ /**
87
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
88
+ *
89
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
90
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
91
+ * and different fixes. Here there is only one story to tell — an origin we run
92
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
93
+ * value is decoration; #724 is what happens when a class holds several
94
+ * situations, and inventing sub-values ahead of a reason to act on them
95
+ * differently is the same mistake with the sign flipped.
96
+ *
97
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
98
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
99
+ * hint paths, which only care whether retrying or a sibling tool might work —
100
+ * and it might. Nothing a caller sees or is charged changes here.
101
+ *
102
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
103
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
104
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
105
+ * worked on the write side and was invisible for weeks.
106
+ */
107
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
108
+
109
+ /**
110
+ * The token that carries "this origin is ours" from the call site to the
111
+ * classifier.
112
+ *
113
+ * Appended to the error message rather than attached to the Error object,
114
+ * because the object does not survive the trip: 275 packs return `{ error:
115
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
116
+ * and the fleet pack rebuilds its error from a captured status + body across a
117
+ * retry loop. A property on an Error would be dropped by every one of those
118
+ * paths and the class would work in tests and vanish in production.
119
+ *
120
+ * WORDING IS LOAD-BEARING, same rule as labelAge's note in authority.ts. This
121
+ * string is appended to a pack's thrown Error message (shared/src/http.ts),
122
+ * and a thrown Error's message is exactly what the gateway hands back to the
123
+ * caller as `content[0].text` when nothing rewrites it (workers/gateway/src
124
+ * catches the throw and sets `rawResult.message = stripClassPrefix(error)`,
125
+ * which does not touch this suffix) — so the original wording,
126
+ * " [pipeworx-hosted origin — our own service, not a third party]", was not a
127
+ * theoretical leak: it shipped live on pipeworx-catalog's 522s, 7 times in 6
128
+ * hours on 2026-09-02 (see tests/golden-internal-service.test.ts), verbatim
129
+ * naming Pipeworx as the host. check:hosting-claims never caught it because it
130
+ * did not scan shared/ at all (task #2009). Reworded to describe the
131
+ * OBSERVATION (the origin did not answer) without a claim about who runs it —
132
+ * the identical fix labelAge got: drop the possessive, keep the fact.
133
+ */
134
+ const INTERNAL_ORIGIN_MARKER = ' [origin did not respond — retry before concluding the named source is down]';
135
+
136
+ /**
137
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
138
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
139
+ *
140
+ * Matching the shape rather than listing the ref keeps this correct when we add
141
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
142
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
143
+ * own status page and emphatically not our database. Verified 2026-09-02 by
144
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
145
+ * only real project ref anywhere in the tree is ours, the rest are doc
146
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
147
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
148
+ * by construction.
149
+ */
150
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
151
+
152
+ /**
153
+ * Is this a host WE run?
154
+ *
155
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
156
+ * hosted on workers.dev, so the suffix says where something runs and not who
157
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
158
+ * hostname or to our Supabase project, both of which are ownership facts.
159
+ *
160
+ * `workers/gateway/src/provenance.ts`'s `OUR_HOSTS` answers the same
161
+ * question and DOES include `workers.dev` — a documented divergence
162
+ * (task #2051), not a bug to converge. That list decides what a response may
163
+ * cite as a data SOURCE, where a false negative (citing our own worker as an
164
+ * external source) is the hosting-disclosure leak this whole file exists to
165
+ * prevent, so it errs broad. This one decides who gets BLAMED for a 5xx in
166
+ * outage metrics read by on-call, where a false positive (crediting our own
167
+ * infra with a third party's outage) hides the real failure, so it errs
168
+ * narrow. Same suffix, opposite direction, because they are never called for
169
+ * the same reason.
170
+ *
171
+ * Returns false on anything unparseable rather than throwing — this runs inside
172
+ * an error path, and an error path that can itself throw turns a diagnosable
173
+ * failure into a mystery.
174
+ */
175
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
176
+ if (!url) return false;
177
+ let host: string;
178
+ try {
179
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
180
+ } catch {
181
+ return false;
182
+ }
183
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
184
+ return SUPABASE_PROJECT_HOST.test(host);
185
+ }
186
+
187
+ /**
188
+ * Append the marker when this failure was OUR origin failing to answer.
189
+ *
190
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
191
+ * where there is no response at all, and "the origin did not answer" is the
192
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
193
+ * registry for a slug that does not exist is the caller's argument, not our
194
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
195
+ *
196
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
197
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
198
+ */
199
+ function markInternalOrigin(
200
+ message: string,
201
+ url: string | URL | undefined | null,
202
+ status?: number,
203
+ ): string {
204
+ if (status !== undefined && status < 500) return message;
205
+ if (!isPipeworxOrigin(url)) return message;
206
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
207
+ return message + INTERNAL_ORIGIN_MARKER;
208
+ }
209
+
210
+ /**
211
+ * Which blob4 value a failure from our own web services books as, or undefined
212
+ * if this is not one.
213
+ *
214
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
215
+ * from our own Supabase is a strictly more specific statement about the same
216
+ * row (which of our services, and why), and the two cannot disagree about
217
+ * whether the failure is ours.
218
+ */
219
+ function internalHostMetricsClass(error: string): string | undefined {
220
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
221
+ }
222
+
223
+
224
+ /**
225
+ * One place to turn a failed `fetch` into an error a caller can act on.
226
+ *
227
+ * Nearly every pack was written the same way:
228
+ *
229
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
230
+ *
231
+ * which discards the response body — and the body is usually where the upstream
232
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
233
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
234
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
235
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
236
+ *
237
+ * It also hides bugs one level down. Two of the first three packs audited had a
238
+ * second defect that only existed because of this line: unsplash's rate-limit
239
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
240
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
241
+ * parsing dead code for every non-200.
242
+ *
243
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
244
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
245
+ * `error` tier is what the daily problem-tools list is built from — it means
246
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
247
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
248
+ * values into something TED rejected, and that bug was found only because it sat
249
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
250
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
251
+ * for the 481 that say nothing at all.
252
+ */
253
+
254
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
255
+ * short enough that an HTML page or a stack trace can't swamp the error. */
256
+
257
+ const MAX_DETAIL = 300;
258
+
259
+ /**
260
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
261
+ *
262
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
263
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
264
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
265
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
266
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
267
+ * fast, actionable error instead of holding the connection, and long enough
268
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
269
+ */
270
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
271
+
272
+ /**
273
+ * Read the body of a failed response and fold it into a throwable Error.
274
+ *
275
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
276
+ * change rather than a drop-in:
277
+ *
278
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
279
+ *
280
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
281
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
282
+ * something new from inside the error path.
283
+ */
284
+ async function httpError(res: Response, name: string): Promise<Error> {
285
+ return new Error(await httpErrorMessage(res, name));
286
+ }
287
+
288
+ /** The message text without constructing an Error — for packs that need to wrap
289
+ * it in their own envelope or add an explicit classification prefix. */
290
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
291
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
292
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
293
+ // about the call rather than a guess from the `name` the pack passed in —
294
+ // reword that label freely, the class does not move. See
295
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
296
+ // this touches 481 packs' error text and changes none of it.
297
+ return markInternalOrigin(
298
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
299
+ res.url,
300
+ res.status,
301
+ );
302
+ }
303
+
304
+ /**
305
+ * Just the upstream's own explanation — no name, no status.
306
+ *
307
+ * For a pack that has already said both in its own sentence. epo-ops reads
308
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
309
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
310
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
311
+ * actually said ("Not enough characters before truncation character") nowhere
312
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
313
+ * can fall back to its own wording.
314
+ */
315
+ async function upstreamDetail(res: Response): Promise<string> {
316
+ return readDetail(res);
317
+ }
318
+
319
+ /**
320
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
321
+ *
322
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
323
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
324
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
325
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
326
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
327
+ *
328
+ * That string is the problem. It names no upstream, carries no status, and
329
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
330
+ * means "we have a defect", and the caller is told nothing they can act on.
331
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
332
+ * status-code health check we own reported it green (7889a845). A zero-length
333
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
334
+ * uk-gazette (83% of external calls) and census.
335
+ *
336
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
337
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
338
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
339
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
340
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
341
+ * a statement of fact rather than a guess, and it keeps these out of the
342
+ * problem-tools list where they crowd out real defects.
343
+ *
344
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
345
+ *
346
+ * Call it only after the `!res.ok` check — on a failed response you want
347
+ * `httpError`, which mines the body for the upstream's own explanation.
348
+ */
349
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
350
+ let raw: string;
351
+ try {
352
+ raw = await res.text();
353
+ } catch {
354
+ throw new Error(
355
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
356
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
357
+ );
358
+ }
359
+
360
+ const type = res.headers.get('content-type') ?? 'no content-type';
361
+
362
+ if (!raw.trim()) {
363
+ throw new Error(
364
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
365
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
366
+ );
367
+ }
368
+
369
+ // Checked before parsing rather than in the catch, because knowing it is
370
+ // markup is what turns "we failed to parse something" into "they served a
371
+ // web page" — the second is diagnosable, the first is not.
372
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
373
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
374
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
375
+ // The summary, not the source. Pasting the first 120 characters of a web
376
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
377
+ // this branch exists to describe (fleet #712).
378
+ throw new Error(
379
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
380
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
381
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
382
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
383
+ );
384
+ }
385
+
386
+ try {
387
+ return JSON.parse(raw) as T;
388
+ } catch {
389
+ throw new Error(
390
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
391
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
392
+ );
393
+ }
394
+ }
395
+
396
+ /**
397
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
398
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
399
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
400
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
401
+ * existed — every unguarded call carries the same risk, just unconfirmed.
402
+ *
403
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
404
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
405
+ * an `upstream_down:` error that names the upstream and the bound rather than
406
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
407
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
408
+ * argument a caller passes can make an upstream hang, so it is always the
409
+ * upstream's fault, and marking it that way keeps a slow API off the
410
+ * problem-tools list where it would crowd out our own defects.
411
+ *
412
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
413
+ *
414
+ * const res = await fetchWithTimeout(url, init, 'Some API');
415
+ *
416
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
417
+ * with a known-slower upstream; the label should be the same short name you'd
418
+ * pass to `httpError`/`httpErrorMessage` for that call.
419
+ */
420
+ async function fetchWithTimeout(
421
+ url: string | URL,
422
+ init: RequestInit = {},
423
+ name: string,
424
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
425
+ ): Promise<Response> {
426
+ try {
427
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
428
+ } catch (err) {
429
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
430
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
431
+ // "appears to be degraded" is an inference about the vendor that we have
432
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
433
+ // a timeout from a Worker can equally mean OUR egress is blocked.
434
+ //
435
+ // Measured today (2026-09-01, fleet #1047): every call to
436
+ // mainnet.base.org failed from the x402 facilitator while the identical
437
+ // request from a laptop returned 200. Base was entirely healthy; the
438
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
439
+ // there it would have blamed Base by name, and the next person would have
440
+ // waited for a vendor outage to clear that did not exist.
441
+ // A timeout has no status to test — there is no response at all — so
442
+ // `markInternalOrigin` is called without one: an origin we run that never
443
+ // answered is an availability failure by definition. This is the half of
444
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
445
+ throw new Error(
446
+ markInternalOrigin(
447
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
448
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
449
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
450
+ `from elsewhere before concluding ${name} is down.`,
451
+ url,
452
+ ),
453
+ );
454
+ }
455
+ // Fleet #2382. Everything that isn't a timeout/abort here is a genuine
456
+ // NETWORK-LEVEL failure — DNS resolution, connection refused, TLS handshake,
457
+ // Cloudflare's own "Network connection lost." — meaning `fetch()` itself
458
+ // threw and no HTTP response of any kind was ever received. Until this fix
459
+ // that raw exception was rethrown VERBATIM: a bare `TypeError: fetch failed`
460
+ // (or the Workers-runtime equivalent) names no upstream, carries no class
461
+ // token, and reads exactly like a defect in OUR code — because it says
462
+ // nothing about the call at all. It landed in `error`, the tier that means
463
+ // "Pipeworx has a defect", for every one of the (at the time of writing)
464
+ // ~470 packs that call this helper directly with no wrapper of their own.
465
+ //
466
+ // `dexscreener` hit this independently (fleet #1579) and fixed it with a
467
+ // bespoke per-pack try/catch around `fetchWithTimeout`. That fix is correct
468
+ // but only covers one pack; every other caller of this shared helper still
469
+ // leaked the raw exception. Moving the same fix HERE — the one place that
470
+ // already carries the timeout case — covers every pack that uses
471
+ // `fetchWithTimeout` without a wrapper, for free, and without widening
472
+ // `classifyToolError`'s regex list: the fix is giving the message a proper
473
+ // `upstream_down:` token at the point the two facts (no response was ever
474
+ // received, and which host we were trying to reach) are actually in hand,
475
+ // not teaching the classifier to guess from prose after the fact.
476
+ //
477
+ // Safe on the same grounds as the timeout branch above: no argument a
478
+ // caller passes can make `fetch()` itself throw a connection-level error,
479
+ // so this is always an availability failure, never a caller mistake. Same
480
+ // `markInternalOrigin` treatment — an origin we run that never answered is
481
+ // still ours, not a third party's outage.
482
+ const raw = err instanceof Error ? err.message : String(err);
483
+ throw new Error(
484
+ markInternalOrigin(
485
+ `upstream_down: could not reach ${name} at all (${raw.slice(0, 160)}). ` +
486
+ `No request reached ${name}, so this says NOTHING about whether the arguments you passed ` +
487
+ 'are valid — do not re-check them on the strength of this error. Retry shortly.',
488
+ url,
489
+ ),
490
+ );
491
+ }
492
+ }
493
+
494
+ function detailSuffix(detail: string): string {
495
+ return detail ? ` — ${detail}` : '';
496
+ }
497
+
498
+ async function readDetail(res: Response): Promise<string> {
499
+ let raw: string;
500
+ try {
501
+ raw = await res.text();
502
+ } catch {
503
+ // Body already consumed, or the connection died mid-read. The status alone
504
+ // is still worth throwing — never let the error path throw its own error.
505
+ return '';
506
+ }
507
+ return summarizeErrorBody(raw);
508
+ }
509
+
510
+ /**
511
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
512
+ * that never contains markup.
513
+ *
514
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
515
+ * that markup crowds out the status. That was half right. Dropping it loses the
516
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
517
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
518
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
519
+ * verbatim, across 11 packs, and in every one of them the useful content —
520
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
521
+ * buried in markup the agent had to parse out of a string (fleet #712).
522
+ *
523
+ * So: extract the meaning, discard the markup. The output is passed through
524
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
525
+ * assert mechanically that no caller-facing message can contain `<?xml`,
526
+ * `<!DOCTYPE` or `<html`.
527
+ */
528
+ function summarizeErrorBody(raw: string): string {
529
+ if (!raw || !raw.trim()) return '';
530
+
531
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
532
+
533
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
534
+ // redirect) says what it is in its <title>, and almost nowhere else.
535
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
536
+ const title = htmlTitle(raw);
537
+ return title
538
+ ? `${title} (upstream returned an HTML error page, not an API response)`
539
+ : 'upstream returned an HTML error page, not an API response';
540
+ }
541
+
542
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
543
+ // human sentence sits in a child element whose tag name says what it is.
544
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
545
+ const fault = xmlFaultText(raw);
546
+ return fault
547
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
548
+ : 'upstream returned an XML error document with no readable message';
549
+ }
550
+
551
+ // Most JSON error bodies bury one human sentence among ids and echoed request
552
+ // params. Prefer that sentence; fall back to the whole body when the shape is
553
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
554
+ // guess wrong and show nothing.
555
+ const fromJson = messageFromJson(raw);
556
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
557
+ }
558
+
559
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
560
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
561
+ function htmlTitle(raw: string): string | null {
562
+ const head = raw.slice(0, 4000);
563
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
564
+ const m = re.exec(head);
565
+ const text = m ? stripMarkup(m[1]) : '';
566
+ if (text) return text.slice(0, 160);
567
+ }
568
+ return null;
569
+ }
570
+
571
+ /** Tag names that carry the explanation in an XML fault document, namespace
572
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
573
+ const XML_FAULT_TAG_RE =
574
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
575
+
576
+ function xmlFaultText(raw: string): string | null {
577
+ const head = raw.slice(0, 8000);
578
+ const tagged = XML_FAULT_TAG_RE.exec(head);
579
+ if (tagged && tagged[1].trim()) return tagged[1];
580
+
581
+ // Nothing conventionally named — take the longest text node instead. A fault
582
+ // document with one sentence in an oddly named element is still readable;
583
+ // returning nothing at all is not.
584
+ let best = '';
585
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
586
+ const text = m[1].trim();
587
+ if (text.length > best.length) best = text;
588
+ }
589
+ return best || null;
590
+ }
591
+
592
+ /**
593
+ * Remove every tag and stray angle bracket, then collapse whitespace.
594
+ *
595
+ * Applied to everything on the way out, including the JSON and plain-text
596
+ * paths, because an upstream is free to embed markup in a JSON string field —
597
+ * and a leak is a leak regardless of which branch produced it.
598
+ */
599
+ function stripMarkup(s: string): string {
600
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
601
+ }
602
+
603
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
604
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
605
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
606
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
607
+ function decodeEntities(s: string): string {
608
+ return s
609
+ .replace(/&(?:amp|#0*38);/gi, '&')
610
+ .replace(/&(?:lt|#0*60);/gi, '<')
611
+ .replace(/&(?:gt|#0*62);/gi, '>')
612
+ .replace(/&(?:quot|#0*34);/gi, '"')
613
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
614
+ .replace(/&nbsp;/gi, ' ');
615
+ }
616
+
617
+ /** The conventional "what went wrong" field, under any of the names upstreams
618
+ * actually use. Checked in order; first non-empty string wins. */
619
+ const MESSAGE_KEYS = [
620
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
621
+ 'description', 'error_description', 'reason', 'title', 'fault',
622
+ ];
623
+
624
+ function messageFromJson(raw: string): string | null {
625
+ let parsed: unknown;
626
+ try {
627
+ parsed = JSON.parse(raw);
628
+ } catch {
629
+ return null;
630
+ }
631
+ return pickMessage(parsed, 0);
632
+ }
633
+
634
+ function pickMessage(node: unknown, depth: number): string | null {
635
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
636
+ // shapes that account for nearly all of them, without walking a large payload.
637
+ if (depth > 2 || node == null) return null;
638
+
639
+ if (typeof node === 'string') return node.trim() || null;
640
+
641
+ if (Array.isArray(node)) {
642
+ for (const item of node) {
643
+ const found = pickMessage(item, depth + 1);
644
+ if (found) return found;
645
+ }
646
+ return null;
647
+ }
648
+
649
+ if (typeof node !== 'object') return null;
650
+ const obj = node as Record<string, unknown>;
651
+
652
+ for (const key of MESSAGE_KEYS) {
653
+ const v = obj[key];
654
+ if (typeof v === 'string' && v.trim()) return v.trim();
655
+ }
656
+ // `{error: …}` where error is itself an object or a string — the single most
657
+ // common wrapper, so it is worth descending into by name rather than scanning
658
+ // every key and risking picking up an echoed request parameter.
659
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
660
+ if (key in obj) {
661
+ const found = pickMessage(obj[key], depth + 1);
662
+ if (found) return found;
663
+ }
664
+ }
665
+ return null;
666
+ }
667
+
668
+ /** Errors are read in a single line of log output; newlines and runs of
669
+ * whitespace make a multi-line body unreadable there. */
670
+ function collapse(s: string): string {
671
+ return s.replace(/\s+/g, ' ').trim();
672
+ }
19
673
  /**
20
674
  * GovInfo.gov MCP — full text of US government publications
21
675
  *
@@ -35,10 +689,39 @@ interface McpToolExport {
35
689
  * - get_package: metadata for a package (e.g., one issue, one bill)
36
690
  * - list_granules: sub-units inside a package (sections of a CFR title)
37
691
  * - get_granule: single granule metadata
692
+ * - gao_red_book: topic -> the CURRENT chapter of GAO's appropriations-law treatise
693
+ * - gao_comptroller_decisions: topic -> Comptroller General decisions (B-numbers)
694
+ *
695
+ * TWO HOSTS, ON PURPOSE (fleet #1972). Everything above talks to
696
+ * api.govinfo.gov; `gao_red_book` talks to www.gao.gov, keylessly, because
697
+ * GovInfo does not carry the current Red Book. MEASURED 2026-09-14:
698
+ * `collection:(GAOREPORTS)` holds 16,569 packages but ZERO issued after
699
+ * 2010-01-01, and a full-text search for "Principles of Federal Appropriations
700
+ * Law" returns exactly ONE relevant package in its top 100 of 1,565 hits —
701
+ * GAOREPORTS-GAO-05-354SP, the *2004 Update of the Third Edition*. Serving that
702
+ * as current appropriations law is worse than serving nothing: GAO discontinued
703
+ * the Annual Update entirely and the live table of contents says the current
704
+ * Red Book is Chapters 1-3 of the FOURTH edition plus Chapters 5-15 of the
705
+ * third. So the edition composition is read from GAO's own page on every call
706
+ * rather than hardcoded here, and Chapter 4 will appear the day GAO posts it.
38
707
  */
39
708
 
40
709
 
710
+ // Bound every fetch() in this pack to a fixed timeout — an upstream that
711
+ // degrades without erroring would otherwise hold the Worker in `await fetch()`
712
+ // until its own execution budget kills the request (minutes, not seconds).
713
+ // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
714
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
715
+ return fetchWithTimeout(url, init ?? {}, 'GovInfo.gov');
716
+ }
717
+
41
718
  const BASE_URL = 'https://api.govinfo.gov';
719
+ const GAO_BASE = 'https://www.gao.gov';
720
+ const RED_BOOK_TOC_URL = `${GAO_BASE}/legal/appropriations-law/red-book`;
721
+ // The Workers runtime sends no User-Agent by default and gao.gov's bot filter
722
+ // answers 403 to an unidentified client, which reads as "GAO closed its site"
723
+ // rather than as a missing header (fleet #579).
724
+ const GAO_UA = 'pipeworx-mcp-govinfo/1.0 (+https://pipeworx.io)';
42
725
 
43
726
  const tools: McpToolExport['tools'] = [
44
727
  {
@@ -50,19 +733,21 @@ const tools: McpToolExport['tools'] = [
50
733
  {
51
734
  name: 'search_packages',
52
735
  description:
53
- 'Full-text + faceted search across GovInfo. Filter by collection codes (comma-separated), date range, congress, court (for USCOURTS), and free-text query. Returns package IDs and titles.',
736
+ 'Full-text + faceted search across GovInfo. Filter by one or more collection codes (BILLS, FR, CFR, USCODE, CHRG, CRPT, CREC, PLAW, USCOURTS...), date range, congress, and free-text query. Several codes search the union of those collections. Returns package IDs, titles, collection and issue dates.',
54
737
  inputSchema: {
55
738
  type: 'object',
56
739
  properties: {
57
740
  query: { type: 'string', description: 'Free-text search' },
58
741
  collections: {
59
742
  type: 'string',
60
- description: 'Comma-separated collection codes (e.g., "BILLS,FR")',
743
+ description:
744
+ 'Collection codes, comma- or space-separated (e.g. "CHRG" or "CHRG,CRPT"). Several codes return the union of those collections — "CHRG,CRPT" gives every package in either. Codes come from list_collections.',
61
745
  },
62
746
  congress: { type: 'number', description: 'Congress number (e.g., 118) — for BILLS/CHRG/CRPT' },
63
747
  date_from: { type: 'string', description: 'YYYY-MM-DD' },
64
748
  date_to: { type: 'string', description: 'YYYY-MM-DD' },
65
- page_size: { type: 'number', description: '1-100 (default 25)' },
749
+ page_size: { type: 'number', description: 'Results per page, 1-100 (default 25). `limit` works as an alias.' },
750
+ limit: { type: 'number', description: 'Alias for page_size, 1-100.' },
66
751
  offset_mark: { type: 'string', description: 'Pagination cursor from previous response' },
67
752
  },
68
753
  required: ['query'],
@@ -88,7 +773,8 @@ const tools: McpToolExport['tools'] = [
88
773
  type: 'object',
89
774
  properties: {
90
775
  package_id: { type: 'string', description: 'GovInfo packageId' },
91
- page_size: { type: 'number', description: '1-100 (default 100)' },
776
+ page_size: { type: 'number', description: 'Granules per page, 1-100 (default 100). `limit` works as an alias.' },
777
+ limit: { type: 'number', description: 'Alias for page_size, 1-100.' },
92
778
  offset_mark: { type: 'string', description: 'Pagination cursor' },
93
779
  },
94
780
  required: ['package_id'],
@@ -96,7 +782,7 @@ const tools: McpToolExport['tools'] = [
96
782
  },
97
783
  {
98
784
  name: 'get_granule',
99
- description: 'Granule metadata for a sub-unit within a package.',
785
+ description: 'Fetch summary metadata for a single granule (sub-unit) within a GovInfo package, given package_id and granule_id (both from list_granules). Returns title, class, and provenance fields from the GovInfo summary endpoint.',
100
786
  inputSchema: {
101
787
  type: 'object',
102
788
  properties: {
@@ -106,16 +792,65 @@ const tools: McpToolExport['tools'] = [
106
792
  required: ['package_id', 'granule_id'],
107
793
  },
108
794
  },
795
+ {
796
+ name: 'gao_red_book',
797
+ description:
798
+ 'Find the chapter of GAO\'s Principles of Federal Appropriations Law — the Red Book — that governs a federal appropriations, fiscal-law or government-funding question, described in plain words. Answers questions about what an appropriation may lawfully be spent on (the purpose statute and the necessary expense rule), how long it stays available (the bona fide needs rule, expired and cancelled accounts, no-year and multi-year money), how much may be obligated (the Antideficiency Act, augmentation, miscellaneous receipts, apportionment), recording valid obligations, continuing resolutions and funding lapses, accountable-officer liability and relief, grants and cooperative agreements, guaranteed and insured loans, acquisition, real property, and claims for and against the government. Returns the ranked chapters together with the full table of contents, each row naming which EDITION it comes from: GAO publishes the Red Book chapter by chapter, so the current treatise is a mix of Fourth and Third Edition chapters and this reads that composition live from GAO on every call. Every row carries the chapter PDF, its source_last_modified and age_days. This is official interpretation by the agency that decides federal appropriations law, not statute — pair it with uscode or cfr text for the underlying provision.',
799
+ inputSchema: {
800
+ type: 'object',
801
+ properties: {
802
+ topic: {
803
+ type: 'string',
804
+ description:
805
+ 'The fiscal-law topic or question in plain words, e.g. "can we pay for food at a conference", "bona fide needs rule", "Antideficiency Act violation", "obligating funds under a continuing resolution".',
806
+ },
807
+ chapter: { type: 'number', description: 'Return one specific Red Book chapter number (1-15) instead of ranking by topic.' },
808
+ include_scope_text: {
809
+ type: 'boolean',
810
+ description:
811
+ 'Fetch GAO\'s own scope summary for the Fourth Edition chapters from their product pages (3 extra parallel requests). Default true.',
812
+ },
813
+ },
814
+ required: [],
815
+ },
816
+ },
817
+ {
818
+ name: 'gao_comptroller_decisions',
819
+ description:
820
+ 'Search Comptroller General decisions and opinions — the B-numbered rulings in which GAO decides federal appropriations and fiscal-law disputes, the precedent the Red Book itself cites. Give a topic in plain words (purpose statute violation, augmentation of appropriations, gift acceptance authority, improper payment, interagency agreement) and get the decisions, each with its B-number, decision date and GovInfo package. Filters out GAO audit and performance reports so the result set is decisions only, and reports how many of the underlying hits were decisions. Complements gao_red_book (the treatise) and gao_protests_search (bid-protest decisions, a different GAO docket).',
821
+ inputSchema: {
822
+ type: 'object',
823
+ properties: {
824
+ query: { type: 'string', description: 'Free-text topic, e.g. "augmentation of appropriations" or "necessary expense".' },
825
+ date_from: { type: 'string', description: 'YYYY-MM-DD' },
826
+ date_to: { type: 'string', description: 'YYYY-MM-DD' },
827
+ include_reports: {
828
+ type: 'boolean',
829
+ description: 'Also return GAO audit/performance reports from the same search, flagged as reports. Default false.',
830
+ },
831
+ page_size: { type: 'number', description: 'Decisions to return, 1-100 (default 25).' },
832
+ limit: { type: 'number', description: 'Alias for page_size.' },
833
+ offset_mark: { type: 'string', description: 'Pagination cursor from a previous response.' },
834
+ },
835
+ required: ['query'],
836
+ },
837
+ },
109
838
  ];
110
839
 
111
840
  async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
841
+ // gao_red_book reads www.gao.gov, which is keyless. Demanding a data.gov key
842
+ // for it would refuse a call that works.
843
+ if (name === 'gao_red_book') return gaoRedBook(args);
844
+
112
845
  const apiKey = (args._apiKey as string | undefined)?.trim();
113
846
  if (!apiKey) {
114
847
  throw new Error(
115
- 'GovInfo requires a data.gov API key. Contact the operator about platform credentials (PLATFORM_DATAGOV_KEY), or BYO via ?_apiKey=<key> after registering at https://api.data.gov/signup.',
848
+ 'GovInfo requires a data.gov API key: pass your key as the _apiKey argument (free at https://api.data.gov/signup).',
116
849
  );
117
850
  }
118
851
  switch (name) {
852
+ case 'gao_comptroller_decisions':
853
+ return gaoComptrollerDecisions(apiKey, args);
119
854
  case 'list_collections':
120
855
  return listCollections(apiKey);
121
856
  case 'search_packages':
@@ -135,6 +870,16 @@ async function callTool(name: string, args: Record<string, unknown>): Promise<un
135
870
  }
136
871
  }
137
872
 
873
+ // Callers reach for `limit` — it is the near-universal name for this, and the
874
+ // repro that opened fleet #555 used it. An undeclared argument is dropped in
875
+ // silence, so `limit: 1` came back with 25 rows and a 200. Accept both.
876
+ function pageSize(args: Record<string, unknown>, fallback: number): number {
877
+ const raw = args.page_size ?? args.limit;
878
+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN;
879
+ if (!Number.isFinite(n)) return fallback;
880
+ return Math.min(100, Math.max(1, Math.floor(n)));
881
+ }
882
+
138
883
  function reqStr(args: Record<string, unknown>, key: string, example: string): string {
139
884
  const v = args[key];
140
885
  if (typeof v !== 'string' || !v.trim()) {
@@ -146,7 +891,7 @@ function reqStr(args: Record<string, unknown>, key: string, example: string): st
146
891
  async function giFetch<T>(apiKey: string, path: string, params: URLSearchParams): Promise<T> {
147
892
  params.set('api_key', apiKey);
148
893
  const url = `${BASE_URL}${path}?${params}`;
149
- const res = await fetch(url, { headers: { Accept: 'application/json' } });
894
+ const res = await pwFetch(url, { headers: { Accept: 'application/json' } });
150
895
  if (res.status === 401 || res.status === 403) throw new Error('GovInfo: unauthorized — check the data.gov key');
151
896
  if (res.status === 404) throw new Error('GovInfo: not found (HTTP 404)');
152
897
  if (res.status === 429) throw new Error('GovInfo: rate-limit (HTTP 429)');
@@ -159,7 +904,7 @@ async function giFetch<T>(apiKey: string, path: string, params: URLSearchParams)
159
904
 
160
905
  async function giPost<T>(apiKey: string, path: string, body: unknown): Promise<T> {
161
906
  const url = `${BASE_URL}${path}?api_key=${encodeURIComponent(apiKey)}`;
162
- const res = await fetch(url, {
907
+ const res = await pwFetch(url, {
163
908
  method: 'POST',
164
909
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
165
910
  body: JSON.stringify(body),
@@ -190,8 +935,25 @@ async function listCollections(apiKey: string) {
190
935
 
191
936
  async function searchPackages(apiKey: string, args: Record<string, unknown>) {
192
937
  // GovInfo search uses POST /search with a JSON body.
193
- const filters: string[] = [`query:"${String(args.query).replace(/"/g, '\\"')}"`];
194
- if (args.collections) filters.push(`collection:(${String(args.collections)})`);
938
+ //
939
+ // The free text goes in BARE. There is no `query:` field in GovInfo's query
940
+ // language, so wrapping it as `query:"Epstein"` made the API 500 — on every
941
+ // single call, for the life of this tool. Verified 2026-07-29:
942
+ // query:"Epstein" -> 500 "Oops, Something went wrong"
943
+ // Epstein -> 200, 19,910 results
944
+ // Epstein collection:(CHRG) -> 200, 510 results
945
+ // Field filters (collection:, congress:, publishdate:) ARE real and compose
946
+ // with the bare text via AND.
947
+ const filters: string[] = [];
948
+ const q = typeof args.query === 'string' ? args.query.trim() : '';
949
+ if (q) filters.push(q);
950
+ // Callers naturally write "CHRG,CRPT" (the arg is even plural), but a comma
951
+ // is not a separator in GovInfo's query grammar and the whole request 500s.
952
+ // Normalize any comma/whitespace-separated list to the OR form it wants.
953
+ if (args.collections) {
954
+ const codes = String(args.collections).split(/[,\s]+/).map((c) => c.trim()).filter(Boolean);
955
+ if (codes.length) filters.push(`collection:(${codes.join(' OR ')})`);
956
+ }
195
957
  if (args.congress) filters.push(`congress:${args.congress}`);
196
958
  if (args.date_from && args.date_to) {
197
959
  filters.push(`publishdate:range(${args.date_from},${args.date_to})`);
@@ -201,9 +963,16 @@ async function searchPackages(apiKey: string, args: Record<string, unknown>) {
201
963
  filters.push(`publishdate:range(,${args.date_to})`);
202
964
  }
203
965
 
966
+ if (!filters.length) {
967
+ throw new Error(
968
+ 'Provide either a free-text query or at least one filter (collections, congress, date_from/date_to). ' +
969
+ 'An empty search would ask GovInfo for every package it has.',
970
+ );
971
+ }
972
+
204
973
  const body = {
205
974
  query: filters.join(' AND '),
206
- pageSize: Math.min(100, Math.max(1, (args.page_size as number) ?? 25)),
975
+ pageSize: pageSize(args, 25),
207
976
  offsetMark: (args.offset_mark as string) ?? '*',
208
977
  sorts: [{ field: 'relevancy', sortOrder: 'DESC' }],
209
978
  };
@@ -248,7 +1017,7 @@ async function getPackage(apiKey: string, packageId: string) {
248
1017
  async function listGranules(apiKey: string, args: Record<string, unknown>) {
249
1018
  const packageId = reqStr(args, 'package_id', '"FR-2024-05-12"');
250
1019
  const params = new URLSearchParams({
251
- pageSize: String(Math.min(100, Math.max(1, (args.page_size as number) ?? 100))),
1020
+ pageSize: String(pageSize(args, 100)),
252
1021
  });
253
1022
  if (args.offset_mark) params.set('offsetMark', String(args.offset_mark));
254
1023
  else params.set('offsetMark', '*');
@@ -282,4 +1051,486 @@ async function getGranule(apiKey: string, packageId: string, granuleId: string)
282
1051
  return data;
283
1052
  }
284
1053
 
1054
+ // ─────────────────────────────────────────────────────────────────────────────
1055
+ // GAO Red Book — topic-level discovery over GAO's appropriations-law treatise
1056
+ // ─────────────────────────────────────────────────────────────────────────────
1057
+
1058
+ /**
1059
+ * A hand-maintained topic-to-chapter alias list for the Red Book.
1060
+ *
1061
+ * Read this as what it is: a hand-written alias list, NOT something derived from
1062
+ * the text. Chapter TITLES come off GAO's live page on every call and are
1063
+ * authoritative; these aliases are ours, so every matched row says which of the
1064
+ * two it matched on (`match_basis`) and a caller can discount accordingly. The
1065
+ * entries are deliberately restricted to terms that are the standard NAME of
1066
+ * the rule the chapter's own title states — "bona fide needs rule" for
1067
+ * *Availability of Appropriations: Time*, "Antideficiency Act" for *Amount* —
1068
+ * plus the US Code sections those rules live at. Nothing here is a guess at
1069
+ * what a chapter covers beyond its title, because a plausible wrong chapter is
1070
+ * a confident wrong answer and this tool cannot verify one: the chapters are
1071
+ * PDFs and GovInfo does not index them.
1072
+ *
1073
+ * Extending it: add a term only if you can point at the chapter title or the
1074
+ * statute it names. If a topic genuinely has no home here, leaving it out is
1075
+ * correct — the tool returns the whole table of contents with
1076
+ * match_confidence:"none" and lets the caller choose.
1077
+ */
1078
+ const RED_BOOK_TOPIC_ALIASES: Record<number, string[]> = {
1079
+ 1: ['power of the purse', 'constitutional', 'separation of powers', 'gao role', 'comptroller general authority', 'introduction'],
1080
+ 2: ['terminology', 'definitions', 'budget process', 'appropriations process', 'budget authority', 'types of appropriations', 'legal framework', 'authorization versus appropriation'],
1081
+ 3: ['purpose statute', 'necessary expense', 'necessary expense rule', '31 u.s.c. 1301', '1301(a)', 'available for its objects', 'permissible use of funds', 'what can appropriated funds be spent on',
1082
+ // The purpose chapter answers "may this appropriation be spent on X",
1083
+ // so the plain-English framings of that question route here. Kept to
1084
+ // verbs of spending, not to any particular X — we do not claim to know
1085
+ // which items the chapter discusses.
1086
+ 'pay for', 'spend', 'spent', 'spending', 'buy', 'purchase', 'permissible', 'allowable', 'improper purpose', 'use appropriated funds'],
1087
+ 4: [],
1088
+ 5: ['bona fide needs', 'bona fide needs rule', '31 u.s.c. 1502', '1502(a)', 'period of availability', 'fiscal year availability', 'expired appropriation', 'cancelled appropriation', 'no-year funds', 'multiple year funds', 'advance payment', 'severable services',
1089
+ // Plain-English framings of "for how long is this money available".
1090
+ 'expire', 'expired', 'expires', 'carry over', 'carryover', 'year end', 'end of the fiscal year', 'how long'],
1091
+ 6: ['antideficiency act', '31 u.s.c. 1341', '31 u.s.c. 1517', 'augmentation', 'augmentation of appropriations', 'miscellaneous receipts', '31 u.s.c. 3302', 'apportionment', 'over-obligation', 'deficiency', 'voluntary services', 'gift acceptance',
1092
+ // Plain-English framings of "how much may be obligated".
1093
+ 'exceed', 'overspend', 'more than appropriated', 'ran out of money', 'without an appropriation'],
1094
+ 7: ['recording statute', '31 u.s.c. 1501', 'valid obligation', 'recording obligations', 'deobligation', 'when is an obligation incurred'],
1095
+ 8: ['continuing resolution', 'cr', 'government shutdown', 'lapse in appropriations', 'stopgap funding', 'funding gap'],
1096
+ 9: ['accountable officer', 'certifying officer', 'disbursing officer', 'physical loss of funds', 'relief of liability', 'improper payment'],
1097
+ 10: ['grant', 'grants', 'cooperative agreement', 'federal assistance', 'subgrant', 'uniform guidance', '2 c.f.r. 200'],
1098
+ 11: ['loan guarantee', 'guaranteed loan', 'insured loan', 'credit reform', 'federal credit reform act'],
1099
+ 12: ['procurement', 'acquisition', 'government contract', 'far', 'competition', 'contract funding'],
1100
+ 13: ['real property', 'lease', 'leasing', 'land acquisition', 'building', 'construction'],
1101
+ 14: ['claim against the government', 'claims', 'setoff', 'debt collection', 'erroneous payment', 'waiver of indebtedness', 'tucker act'],
1102
+ 15: ['miscellaneous'],
1103
+ };
1104
+
1105
+ const STOPWORDS = new Set([
1106
+ 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'in', 'on', 'is', 'are', 'can', 'we', 'i', 'it', 'be', 'does',
1107
+ 'do', 'what', 'when', 'how', 'why', 'which', 'with', 'from', 'that', 'this', 'may', 'must', 'should', 'law',
1108
+ 'legal', 'rule', 'rules', 'federal', 'government', 'appropriation', 'appropriations', 'funds', 'fund', 'money',
1109
+ // Function words long enough to clear the length floor. Without these, the
1110
+ // single token "under" in "obligating funds under a continuing resolution"
1111
+ // matched a chapter's scope text and put the wrong chapter in the answer.
1112
+ 'under', 'over', 'into', 'their', 'there', 'them', 'they', 'its', 'our', 'will', 'would', 'could', 'any', 'all',
1113
+ 'not', 'was', 'were', 'has', 'have', 'had', 'been', 'but', 'than', 'then', 'also', 'such', 'about', 'after',
1114
+ 'before', 'during', 'within', 'between', 'each', 'other', 'some', 'one', 'two', 'agency', 'agencies',
1115
+ ]);
1116
+
1117
+ type RedBookChapter = {
1118
+ chapter: number;
1119
+ edition: string | null;
1120
+ edition_label: string | null;
1121
+ title: string | null;
1122
+ status: string;
1123
+ pdf_urls: string[];
1124
+ pdf_labels: string[];
1125
+ scope: string | null;
1126
+ source_last_modified: string | null;
1127
+ age_days: number | null;
1128
+ score: number;
1129
+ match_basis: string[];
1130
+ };
1131
+
1132
+ // GAO's product pages for the Fourth Edition chapters, which carry GAO's own
1133
+ // one-sentence scope summary. Verified live 2026-09-14 — each page's
1134
+ // <meta name="description"> opens "Chapter N of Principles of Federal
1135
+ // Appropriations Law…". Not load-bearing: an unknown or moved id just means the
1136
+ // chapter comes back with scope:null, never a wrong scope.
1137
+ const RED_BOOK_PRODUCT_PAGES: Record<number, string> = {
1138
+ 1: 'gao-16-463sp',
1139
+ 2: 'gao-16-464sp',
1140
+ 3: 'gao-17-797sp',
1141
+ };
1142
+
1143
+ type TocCache = { at: number; toc: RedBookChapter[]; composition: string | null; scope: Record<number, string> };
1144
+ let tocCache: TocCache | null = null;
1145
+ const TOC_TTL_MS = 6 * 60 * 60 * 1000; // GAO ships a chapter every year or two.
1146
+
1147
+ async function gaoFetchText(url: string): Promise<string> {
1148
+ const res = await pwFetch(url, {
1149
+ headers: { Accept: 'text/html,application/xhtml+xml', 'User-Agent': GAO_UA },
1150
+ });
1151
+ if (!res.ok) throw new Error(`GAO.gov: HTTP ${res.status} for ${url}`);
1152
+ return res.text();
1153
+ }
1154
+
1155
+ function unescapeHtml(s: string): string {
1156
+ return s
1157
+ .replace(/&nbsp;/g, ' ')
1158
+ .replace(/&amp;/g, '&')
1159
+ .replace(/&lt;/g, '<')
1160
+ .replace(/&gt;/g, '>')
1161
+ .replace(/&quot;/g, '"')
1162
+ .replace(/&#0?39;|&apos;|&rsquo;|&#8217;/g, "'")
1163
+ .replace(/&ldquo;|&rdquo;|&#8220;|&#8221;/g, '"')
1164
+ .replace(/&ndash;|&#8211;/g, '-')
1165
+ .replace(/&mdash;|&#8212;/g, '—')
1166
+ .replace(/&#(\d+);/g, (_m, d) => String.fromCharCode(Number(d)));
1167
+ }
1168
+
1169
+ function stripTags(html: string): string {
1170
+ return unescapeHtml(html.replace(/<[^>]*>/g, ' ')).replace(/\s+/g, ' ').trim();
1171
+ }
1172
+
1173
+ const ORDINALS: Record<string, string> = { '1': '1st', '2': '2nd', '3': '3rd', '4': '4th' };
1174
+
1175
+ /**
1176
+ * Parse GAO's Red Book table of contents.
1177
+ *
1178
+ * The links column is ROWSPANNED — one 3rd-edition volume PDF covers a run of
1179
+ * chapters, so chapters 7-11 arrive as two-cell rows and inherit the volume
1180
+ * cell opened at chapter 6. Carrying the last links cell forward is what makes
1181
+ * those chapters resolvable at all. The carry is reset by any 3-cell row,
1182
+ * including the empty one GAO uses for the not-yet-published chapter — without
1183
+ * that reset, Chapter 4 would inherit Chapter 3's PDF and we would hand a
1184
+ * caller the wrong chapter with a clean 200.
1185
+ */
1186
+ function parseRedBookToc(html: string): { toc: RedBookChapter[]; composition: string | null } {
1187
+ const tableMatch = html.match(/<table[\s\S]*?<\/table>/i);
1188
+ const toc: RedBookChapter[] = [];
1189
+ let carriedUrls: string[] = [];
1190
+ let carriedLabels: string[] = [];
1191
+
1192
+ if (tableMatch) {
1193
+ const rows = tableMatch[0].match(/<tr[\s\S]*?<\/tr>/gi) ?? [];
1194
+ for (const row of rows) {
1195
+ const cells = [...row.matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((m) => m[1]);
1196
+ if (cells.length < 2) continue;
1197
+ const chapMatch = stripTags(cells[0]).match(/(\d)(?:st|nd|rd|th)\s+Edition,?\s+Chapter\s+(\d+)/i);
1198
+ if (!chapMatch) continue;
1199
+ const editionDigit = chapMatch[1];
1200
+ const chapter = Number(chapMatch[2]);
1201
+ const title = stripTags(cells[1]);
1202
+
1203
+ if (cells.length >= 3) {
1204
+ const linkCell = cells[cells.length - 1];
1205
+ carriedUrls = [...linkCell.matchAll(/href="([^"]+)"/gi)].map((m) =>
1206
+ m[1].startsWith('http') ? m[1] : `${GAO_BASE}${m[1]}`,
1207
+ );
1208
+ carriedLabels = [...linkCell.matchAll(/<a[^>]*>([\s\S]*?)<\/a>/gi)].map((m) => stripTags(m[1]));
1209
+ }
1210
+
1211
+ // GAO writes "Coming soon!" in the title column for an announced chapter
1212
+ // that has no PDF yet. Reporting it as published-with-no-link would read
1213
+ // as a broken row; reporting it as absent hides that GAO has said it is
1214
+ // coming. It is neither, so it gets its own status.
1215
+ const announced = /coming soon/i.test(title);
1216
+ toc.push({
1217
+ chapter,
1218
+ edition: ORDINALS[editionDigit] ?? editionDigit,
1219
+ edition_label: `${ORDINALS[editionDigit] ?? editionDigit} Edition, Chapter ${chapter}`,
1220
+ title: announced ? null : title,
1221
+ status: announced ? 'announced_not_yet_published' : 'published',
1222
+ pdf_urls: announced ? [] : carriedUrls,
1223
+ pdf_labels: announced ? [] : carriedLabels,
1224
+ scope: null,
1225
+ source_last_modified: null,
1226
+ age_days: null,
1227
+ score: 0,
1228
+ match_basis: [],
1229
+ });
1230
+ }
1231
+ }
1232
+
1233
+ const text = stripTags(html.replace(/<(script|style)[\s\S]*?<\/\1>/gi, ''));
1234
+ const comp = text.match(/Our current Red Book consists of[^.]*\./i);
1235
+ return { toc, composition: comp ? comp[0] : null };
1236
+ }
1237
+
1238
+ async function fetchChapterScopes(): Promise<Record<number, string>> {
1239
+ const entries = await Promise.all(
1240
+ Object.entries(RED_BOOK_PRODUCT_PAGES).map(async ([chap, productId]) => {
1241
+ try {
1242
+ const html = await gaoFetchText(`${GAO_BASE}/products/${productId}`);
1243
+ const m = html.match(/<meta\s+name="description"\s+content="([^"]*)"/i);
1244
+ return [Number(chap), m ? unescapeHtml(m[1]) : ''] as const;
1245
+ } catch {
1246
+ return [Number(chap), ''] as const;
1247
+ }
1248
+ }),
1249
+ );
1250
+ const out: Record<number, string> = {};
1251
+ for (const [chap, scope] of entries) if (scope) out[chap] = scope;
1252
+ return out;
1253
+ }
1254
+
1255
+ async function loadRedBook(includeScope: boolean): Promise<TocCache> {
1256
+ if (tocCache && Date.now() - tocCache.at < TOC_TTL_MS && (!includeScope || Object.keys(tocCache.scope).length)) {
1257
+ return tocCache;
1258
+ }
1259
+ // Parallel, not sequential: Promise.all costs max() of the two legs, not the
1260
+ // sum, and the answer budget is shared with whatever the caller asked next.
1261
+ const [html, scope] = await Promise.all([
1262
+ gaoFetchText(RED_BOOK_TOC_URL),
1263
+ includeScope ? fetchChapterScopes() : Promise.resolve({} as Record<number, string>),
1264
+ ]);
1265
+ const { toc, composition } = parseRedBookToc(html);
1266
+ if (!toc.length) {
1267
+ throw new Error(
1268
+ 'GAO.gov returned the Red Book page but no chapter table could be read from it — the page layout has changed and gao_red_book needs its parser updated.',
1269
+ );
1270
+ }
1271
+ tocCache = { at: Date.now(), toc, composition, scope };
1272
+ return tocCache;
1273
+ }
1274
+
1275
+ function tokenize(s: string): string[] {
1276
+ return s
1277
+ .toLowerCase()
1278
+ .replace(/[^a-z0-9.()§ -]/g, ' ')
1279
+ .split(/[\s-]+/)
1280
+ .map((t) => t.trim())
1281
+ .filter((t) => t.length >= 3 && !STOPWORDS.has(t));
1282
+ }
1283
+
1284
+ function scoreChapter(chap: RedBookChapter, topic: string): { score: number; basis: string[] } {
1285
+ const low = topic.toLowerCase();
1286
+ const tokens = tokenize(topic);
1287
+ const basis: string[] = [];
1288
+ let score = 0;
1289
+
1290
+ // A chapter title is GAO's own text, fetched this call — the strongest signal
1291
+ // available and the only one that cannot be stale.
1292
+ const titleTokens = new Set(tokenize(chap.title ?? ''));
1293
+ const titleHits = [...new Set(tokens)].filter((t) => titleTokens.has(t));
1294
+ if (titleHits.length) {
1295
+ score += 5 * titleHits.length;
1296
+ basis.push(`title:${titleHits.join(',')}`);
1297
+ }
1298
+
1299
+ // The alias list below, maintained in this pack. A whole-phrase alias
1300
+ // inside the question is a strong,
1301
+ // low-ambiguity signal ("bona fide needs"); a single alias token is weak.
1302
+ for (const alias of RED_BOOK_TOPIC_ALIASES[chap.chapter] ?? []) {
1303
+ if (alias.includes(' ') || alias.includes('.')) {
1304
+ if (low.includes(alias)) {
1305
+ score += 6;
1306
+ basis.push(`alias:"${alias}"`);
1307
+ }
1308
+ } else if (tokens.includes(alias)) {
1309
+ score += 2;
1310
+ basis.push(`alias:${alias}`);
1311
+ }
1312
+ }
1313
+
1314
+ if (chap.scope) {
1315
+ const scopeTokens = new Set(tokenize(chap.scope));
1316
+ const scopeHits = [...new Set(tokens)].filter((t) => scopeTokens.has(t) && !titleTokens.has(t));
1317
+ if (scopeHits.length) {
1318
+ score += scopeHits.length;
1319
+ basis.push(`gao_scope:${scopeHits.join(',')}`);
1320
+ }
1321
+ }
1322
+
1323
+ return { score, basis };
1324
+ }
1325
+
1326
+ function ageDays(iso: string | null): number | null {
1327
+ if (!iso) return null;
1328
+ const t = Date.parse(iso);
1329
+ if (!Number.isFinite(t)) return null;
1330
+ return Math.floor((Date.now() - t) / 86400000);
1331
+ }
1332
+
1333
+ /**
1334
+ * The PDF's own Last-Modified is the only real content-freshness signal on
1335
+ * gao.gov. The TOC page's Last-Modified is a Drupal render timestamp — it reads
1336
+ * as "today" on every call (measured), so a caller shown that would conclude
1337
+ * a 2019 chapter was revised this morning.
1338
+ */
1339
+ async function pdfLastModified(url: string): Promise<string | null> {
1340
+ try {
1341
+ const res = await pwFetch(url, { method: 'HEAD', headers: { 'User-Agent': GAO_UA } });
1342
+ const lm = res.headers.get('last-modified');
1343
+ return lm ? new Date(lm).toISOString() : null;
1344
+ } catch {
1345
+ return null;
1346
+ }
1347
+ }
1348
+
1349
+ async function gaoRedBook(args: Record<string, unknown>) {
1350
+ const topic = typeof args.topic === 'string' ? args.topic.trim() : '';
1351
+ const wantChapter = typeof args.chapter === 'number' ? args.chapter : undefined;
1352
+ const includeScope = args.include_scope_text !== false;
1353
+
1354
+ const { toc, composition, scope } = await loadRedBook(includeScope);
1355
+ const retrievedAt = new Date().toISOString();
1356
+ for (const c of toc) c.scope = scope[c.chapter] ?? null;
1357
+
1358
+ let matched: RedBookChapter[];
1359
+ let confidence: string;
1360
+
1361
+ if (wantChapter !== undefined) {
1362
+ matched = toc.filter((c) => c.chapter === wantChapter);
1363
+ confidence = matched.length ? 'exact_chapter' : 'none';
1364
+ } else if (topic) {
1365
+ for (const c of toc) {
1366
+ const { score, basis } = scoreChapter(c, topic);
1367
+ c.score = score;
1368
+ c.match_basis = basis;
1369
+ }
1370
+ // Floor of 2: a single weak signal (one shared scope word, one bare alias
1371
+ // token) is noise, and a noisy row in `matched_chapters` reads as a
1372
+ // recommendation. Below the floor the caller gets the table of contents and
1373
+ // match_confidence:"none", which is the honest answer.
1374
+ const scored = toc.filter((c) => c.score >= 2).sort((a, b) => b.score - a.score);
1375
+ matched = scored.slice(0, 3);
1376
+ confidence = matched.length === 0 ? 'none' : matched[0].score >= 5 ? 'high' : 'low';
1377
+ } else {
1378
+ matched = [];
1379
+ confidence = 'no_topic_given';
1380
+ }
1381
+
1382
+ // Bounded: HEAD only the chapters we are actually recommending. Doing all 15
1383
+ // would be 15 requests to answer one question.
1384
+ await Promise.all(
1385
+ matched.map(async (c) => {
1386
+ if (!c.pdf_urls.length) return;
1387
+ c.source_last_modified = await pdfLastModified(c.pdf_urls[0]);
1388
+ c.age_days = ageDays(c.source_last_modified);
1389
+ }),
1390
+ );
1391
+
1392
+ const currentEditions = [...new Set(toc.filter((c) => c.status === 'published').map((c) => c.edition))];
1393
+
1394
+ return {
1395
+ found: matched.length > 0 || confidence === 'no_topic_given',
1396
+ source: 'GAO, Principles of Federal Appropriations Law (the "Red Book")',
1397
+ publisher: 'U.S. Government Accountability Office',
1398
+ // The Red Book is GAO's systematic treatise on appropriations law, so it is
1399
+ // `legal_treatise` (tier 3, practitioner_guidance) — NOT the same type as the
1400
+ // Comptroller General decisions it cites, which gao_comptroller_decisions
1401
+ // labels `agency_guidance` (tier 2). Same publisher, different instruments: a
1402
+ // single uniform authority_type for the GAO corpus is wrong whichever one you
1403
+ // pick. `official_interpretation` shipped here in #1972 and was wrong twice
1404
+ // over — it is a TIER, not a type, and it is not this document's tier anyway.
1405
+ authority_type: 'legal_treatise',
1406
+ authority_tier: 'practitioner_guidance',
1407
+ jurisdiction: 'us-federal',
1408
+ // Coded value ranks and filters; the sentence explains. Nothing ever parses
1409
+ // one into the other — see BINDING_STATUS_IS_CODED_PLUS_PROSE in
1410
+ // shared/src/authority.ts.
1411
+ binding_status: 'persuasive',
1412
+ binding_note:
1413
+ 'GAO\'s own view of federal appropriations law. Persuasive and followed in practice by agency counsel; not binding on courts.',
1414
+ table_of_contents_url: RED_BOOK_TOC_URL,
1415
+ // Straight from GAO's page, not from us: "Our current Red Book consists of
1416
+ // Chapters 1-3 (of the 4th Edition) and Chapters 5-15 (of the 3rd Edition)."
1417
+ current_edition_note: composition,
1418
+ editions_in_force: currentEditions,
1419
+ retrieved_at: retrievedAt,
1420
+ match_confidence: confidence,
1421
+ match_basis_legend:
1422
+ 'title = matched GAO\'s own chapter title, read live this call. alias = matched Pipeworx\'s topic index (see the pack README). gao_scope = matched GAO\'s product-page scope summary.',
1423
+ matched_chapters: matched.map(redBookRow),
1424
+ table_of_contents: toc.map(redBookRow),
1425
+ superseded: [
1426
+ {
1427
+ package_id: 'GAOREPORTS-GAO-05-354SP',
1428
+ title: 'Principles of Federal Appropriations Law: 2004 Update of the Third Edition',
1429
+ date_issued: '2005-03-01',
1430
+ why_not_current:
1431
+ 'The only Red Book package GovInfo carries, and it is a 2004 annual update to the Third Edition. GAO has discontinued the Annual Update entirely and does not list it in the current table of contents. It is legal history, not current appropriations law — a full-text GovInfo search returns it as the single relevant hit and it is the wrong answer.',
1432
+ },
1433
+ ],
1434
+ note:
1435
+ matched.length === 0 && topic
1436
+ ? 'No chapter matched that topic. The complete table of contents is returned above so you can pick one — every row is part of the current Red Book, with its edition named.'
1437
+ : null,
1438
+ };
1439
+ }
1440
+
1441
+ function redBookRow(c: RedBookChapter) {
1442
+ return {
1443
+ chapter: c.chapter,
1444
+ edition: c.edition,
1445
+ citation_label: c.edition_label,
1446
+ title: c.title,
1447
+ status: c.status,
1448
+ is_current: c.status === 'published',
1449
+ scope: c.scope,
1450
+ pdf_urls: c.pdf_urls,
1451
+ pdf_labels: c.pdf_labels,
1452
+ source_last_modified: c.source_last_modified,
1453
+ age_days: c.age_days,
1454
+ relevance_score: c.score,
1455
+ match_basis: c.match_basis,
1456
+ };
1457
+ }
1458
+
1459
+ // ─────────────────────────────────────────────────────────────────────────────
1460
+ // Comptroller General decisions
1461
+ // ─────────────────────────────────────────────────────────────────────────────
1462
+
1463
+ /**
1464
+ * GovInfo's GAOREPORTS collection mixes two very different things under one
1465
+ * code: GAO audit/performance reports and Comptroller General DECISIONS. Its
1466
+ * own name says so — "Government Accountability Office Reports and Comptroller
1467
+ * General Decisions" — and a relevance search over 16,569 packages interleaves
1468
+ * them, which is why a fiscal-law question comes back looking like noise. The
1469
+ * split is in the package id: a decision is GAOREPORTS-B-<number>.
1470
+ */
1471
+ function isDecision(packageId: string | null): boolean {
1472
+ return !!packageId && /^GAOREPORTS-B-/i.test(packageId);
1473
+ }
1474
+
1475
+ async function gaoComptrollerDecisions(apiKey: string, args: Record<string, unknown>) {
1476
+ const want = pageSize(args, 25);
1477
+ const includeReports = args.include_reports === true;
1478
+ // Over-fetch, because filtering happens here: asking for exactly `want` rows
1479
+ // upstream and then dropping the reports would return fewer decisions than
1480
+ // asked for and look like the collection was thin.
1481
+ const upstream = await searchPackages(apiKey, {
1482
+ query: reqStr(args, 'query', '"augmentation of appropriations"'),
1483
+ collections: 'GAOREPORTS',
1484
+ date_from: args.date_from,
1485
+ date_to: args.date_to,
1486
+ page_size: 100,
1487
+ offset_mark: args.offset_mark,
1488
+ });
1489
+
1490
+ const decisions = upstream.results.filter((r) => isDecision(r.package_id));
1491
+ const reports = upstream.results.filter((r) => !isDecision(r.package_id));
1492
+
1493
+ return {
1494
+ total_collection_hits: upstream.total,
1495
+ upstream_examined: upstream.returned,
1496
+ decisions_found: decisions.length,
1497
+ reports_filtered_out: includeReports ? 0 : reports.length,
1498
+ next_offset_mark: upstream.next_offset_mark,
1499
+ // A Comptroller General decision is the issuing body's own reading of the
1500
+ // appropriations statutes it administers — `agency_guidance`, tier 2
1501
+ // (official_interpretation). Contrast gao_red_book, which is the treatise
1502
+ // built ON these decisions and is therefore tier 3.
1503
+ authority_type: 'agency_guidance',
1504
+ authority_tier: 'official_interpretation',
1505
+ jurisdiction: 'us-federal',
1506
+ issuer: 'Comptroller General of the United States',
1507
+ // 'persuasive' rather than 'binding_on_issuer': these decisions direct
1508
+ // agencies that are not their issuer (GAO decides, the agency complies), so
1509
+ // the enum value reserved for an agency's own internal manual would be wrong.
1510
+ // The force they actually carry over those agencies is what binding_note is
1511
+ // for — the sentence is not a status and is never parsed into one.
1512
+ binding_status: 'persuasive',
1513
+ binding_note:
1514
+ 'A Comptroller General decision binds the agencies that must account to GAO and is the precedent the Red Book cites; it does not bind courts.',
1515
+ retrieved_at: new Date().toISOString(),
1516
+ decisions: decisions.map((r) => ({
1517
+ ...r,
1518
+ document_type: 'comptroller_general_decision',
1519
+ source_last_modified: r.last_modified,
1520
+ age_days: ageDays(r.last_modified),
1521
+ })),
1522
+ reports: includeReports
1523
+ ? reports.map((r) => ({
1524
+ ...r,
1525
+ document_type: 'gao_report',
1526
+ source_last_modified: r.last_modified,
1527
+ age_days: ageDays(r.last_modified),
1528
+ }))
1529
+ : undefined,
1530
+ note: decisions.length
1531
+ ? 'GovInfo carries Comptroller General decisions through the 2000s only — GAOREPORTS holds nothing issued after 2009 (measured). For the current appropriations-law treatise use gao_red_book; for recent bid protests use gao_protests_search.'
1532
+ : 'No Comptroller General decision in this collection matched. GAOREPORTS holds nothing issued after 2009 (measured), so a recent matter will not be here — try gao_red_book for the governing rule or gao_protests_search for bid protests.',
1533
+ };
1534
+ }
1535
+
285
1536
  export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;