@cliwant/mcp-sam-gov 0.3.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.ja.md +48 -16
- package/README.ko.md +48 -16
- package/README.md +226 -64
- package/dist/attachments.d.ts +63 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +576 -0
- package/dist/attachments.js.map +1 -0
- package/dist/bls.d.ts +267 -0
- package/dist/bls.d.ts.map +1 -0
- package/dist/bls.js +1549 -0
- package/dist/bls.js.map +1 -0
- package/dist/cache.d.ts +2 -0
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +4 -0
- package/dist/cache.js.map +1 -1
- package/dist/census.d.ts +182 -0
- package/dist/census.d.ts.map +1 -0
- package/dist/census.js +576 -0
- package/dist/census.js.map +1 -0
- package/dist/ckan.d.ts +141 -0
- package/dist/ckan.d.ts.map +1 -0
- package/dist/ckan.js +393 -0
- package/dist/ckan.js.map +1 -0
- package/dist/clinicaltrials.d.ts +180 -0
- package/dist/clinicaltrials.d.ts.map +1 -0
- package/dist/clinicaltrials.js +730 -0
- package/dist/clinicaltrials.js.map +1 -0
- package/dist/cms.d.ts +140 -0
- package/dist/cms.d.ts.map +1 -0
- package/dist/cms.js +482 -0
- package/dist/cms.js.map +1 -0
- package/dist/coerce.d.ts +32 -0
- package/dist/coerce.d.ts.map +1 -0
- package/dist/coerce.js +50 -0
- package/dist/coerce.js.map +1 -0
- package/dist/datagov-catalog.d.ts +84 -0
- package/dist/datagov-catalog.d.ts.map +1 -0
- package/dist/datagov-catalog.js +233 -0
- package/dist/datagov-catalog.js.map +1 -0
- package/dist/datagov.d.ts +146 -0
- package/dist/datagov.d.ts.map +1 -0
- package/dist/datagov.js +689 -0
- package/dist/datagov.js.map +1 -0
- package/dist/datagovKey.d.ts +36 -0
- package/dist/datagovKey.d.ts.map +1 -0
- package/dist/datagovKey.js +60 -0
- package/dist/datagovKey.js.map +1 -0
- package/dist/datasource.d.ts +313 -0
- package/dist/datasource.d.ts.map +1 -0
- package/dist/datasource.js +551 -0
- package/dist/datasource.js.map +1 -0
- package/dist/disclosure.d.ts +55 -0
- package/dist/disclosure.d.ts.map +1 -0
- package/dist/disclosure.js +57 -0
- package/dist/disclosure.js.map +1 -0
- package/dist/ecfr.d.ts +4 -2
- package/dist/ecfr.d.ts.map +1 -1
- package/dist/ecfr.js +74 -1
- package/dist/ecfr.js.map +1 -1
- package/dist/echo.d.ts +143 -0
- package/dist/echo.d.ts.map +1 -0
- package/dist/echo.js +424 -0
- package/dist/echo.js.map +1 -0
- package/dist/edgar.d.ts +377 -0
- package/dist/edgar.d.ts.map +1 -0
- package/dist/edgar.js +2418 -0
- package/dist/edgar.js.map +1 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -1
- package/dist/errors.js.map +1 -1
- package/dist/fac.d.ts +180 -0
- package/dist/fac.d.ts.map +1 -0
- package/dist/fac.js +416 -0
- package/dist/fac.js.map +1 -0
- package/dist/far.d.ts +170 -0
- package/dist/far.d.ts.map +1 -0
- package/dist/far.js +804 -0
- package/dist/far.js.map +1 -0
- package/dist/fdic.d.ts +599 -0
- package/dist/fdic.d.ts.map +1 -0
- package/dist/fdic.js +1624 -0
- package/dist/fdic.js.map +1 -0
- package/dist/federal-register.d.ts +139 -2
- package/dist/federal-register.d.ts.map +1 -1
- package/dist/federal-register.js +419 -3
- package/dist/federal-register.js.map +1 -1
- package/dist/fema.d.ts +181 -0
- package/dist/fema.d.ts.map +1 -0
- package/dist/fema.js +436 -0
- package/dist/fema.js.map +1 -0
- package/dist/fpds.d.ts +108 -0
- package/dist/fpds.d.ts.map +1 -0
- package/dist/fpds.js +519 -0
- package/dist/fpds.js.map +1 -0
- package/dist/gao.d.ts +64 -0
- package/dist/gao.d.ts.map +1 -0
- package/dist/gao.js +640 -0
- package/dist/gao.js.map +1 -0
- package/dist/govinfo.d.ts +111 -0
- package/dist/govinfo.d.ts.map +1 -0
- package/dist/govinfo.js +422 -0
- package/dist/govinfo.js.map +1 -0
- package/dist/grants.d.ts +27 -4
- package/dist/grants.d.ts.map +1 -1
- package/dist/grants.js +111 -6
- package/dist/grants.js.map +1 -1
- package/dist/gsa-csv.d.ts +249 -0
- package/dist/gsa-csv.d.ts.map +1 -0
- package/dist/gsa-csv.js +784 -0
- package/dist/gsa-csv.js.map +1 -0
- package/dist/integrity.d.ts +212 -0
- package/dist/integrity.d.ts.map +1 -0
- package/dist/integrity.js +707 -0
- package/dist/integrity.js.map +1 -0
- package/dist/meta.d.ts +165 -0
- package/dist/meta.d.ts.map +1 -0
- package/dist/meta.js +162 -0
- package/dist/meta.js.map +1 -0
- package/dist/nih.d.ts +117 -0
- package/dist/nih.d.ts.map +1 -0
- package/dist/nih.js +291 -0
- package/dist/nih.js.map +1 -0
- package/dist/nppes.d.ts +157 -0
- package/dist/nppes.d.ts.map +1 -0
- package/dist/nppes.js +648 -0
- package/dist/nppes.js.map +1 -0
- package/dist/nsf.d.ts +176 -0
- package/dist/nsf.d.ts.map +1 -0
- package/dist/nsf.js +554 -0
- package/dist/nsf.js.map +1 -0
- package/dist/nvd.d.ts +176 -0
- package/dist/nvd.d.ts.map +1 -0
- package/dist/nvd.js +912 -0
- package/dist/nvd.js.map +1 -0
- package/dist/ofac.d.ts +205 -0
- package/dist/ofac.d.ts.map +1 -0
- package/dist/ofac.js +919 -0
- package/dist/ofac.js.map +1 -0
- package/dist/pricing.d.ts +110 -0
- package/dist/pricing.d.ts.map +1 -0
- package/dist/pricing.js +843 -0
- package/dist/pricing.js.map +1 -0
- package/dist/sam-gov/client.d.ts +60 -2
- package/dist/sam-gov/client.d.ts.map +1 -1
- package/dist/sam-gov/client.js +320 -54
- package/dist/sam-gov/client.js.map +1 -1
- package/dist/sam-gov/index.d.ts +1 -1
- package/dist/sam-gov/index.d.ts.map +1 -1
- package/dist/sam-gov/index.js +1 -1
- package/dist/sam-gov/index.js.map +1 -1
- package/dist/sam-gov/types.d.ts +24 -0
- package/dist/sam-gov/types.d.ts.map +1 -1
- package/dist/sba.d.ts +72 -0
- package/dist/sba.d.ts.map +1 -0
- package/dist/sba.js +281 -0
- package/dist/sba.js.map +1 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +3889 -296
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +98 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +146 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/socrata.d.ts +157 -0
- package/dist/socrata.d.ts.map +1 -0
- package/dist/socrata.js +448 -0
- package/dist/socrata.js.map +1 -0
- package/dist/treasury.d.ts +143 -0
- package/dist/treasury.d.ts.map +1 -0
- package/dist/treasury.js +436 -0
- package/dist/treasury.js.map +1 -0
- package/dist/usaspending.d.ts +260 -65
- package/dist/usaspending.d.ts.map +1 -1
- package/dist/usaspending.js +1629 -201
- package/dist/usaspending.js.map +1 -1
- package/dist/usitc.d.ts +142 -0
- package/dist/usitc.d.ts.map +1 -0
- package/dist/usitc.js +339 -0
- package/dist/usitc.js.map +1 -0
- package/package.json +24 -2
- package/src/attachments.ts +652 -0
- package/src/bls.ts +1943 -0
- package/src/cache.ts +5 -0
- package/src/census.ts +735 -0
- package/src/ckan.ts +495 -0
- package/src/clinicaltrials.ts +923 -0
- package/src/cms.ts +634 -0
- package/src/coerce.ts +47 -0
- package/src/datagov-catalog.ts +296 -0
- package/src/datagov.ts +907 -0
- package/src/datagovKey.ts +68 -0
- package/src/datasource.ts +721 -0
- package/src/disclosure.ts +61 -0
- package/src/ecfr.ts +98 -1
- package/src/echo.ts +496 -0
- package/src/edgar.ts +3014 -0
- package/src/errors.ts +84 -1
- package/src/fac.ts +529 -0
- package/src/far.ts +1007 -0
- package/src/fdic.ts +2052 -0
- package/src/federal-register.ts +512 -3
- package/src/fema.ts +541 -0
- package/src/fpds.ts +620 -0
- package/src/gao.ts +744 -0
- package/src/govinfo.ts +497 -0
- package/src/grants.ts +139 -7
- package/src/gsa-csv.ts +992 -0
- package/src/integrity.ts +928 -0
- package/src/meta.ts +292 -0
- package/src/nih.ts +375 -0
- package/src/nppes.ts +834 -0
- package/src/nsf.ts +706 -0
- package/src/nvd.ts +1124 -0
- package/src/ofac.ts +1166 -0
- package/src/pricing.ts +1075 -0
- package/src/sam-gov/client.ts +345 -63
- package/src/sam-gov/index.ts +5 -1
- package/src/sam-gov/types.ts +22 -0
- package/src/sba.ts +357 -0
- package/src/server.ts +4551 -328
- package/src/snapshot.ts +192 -0
- package/src/socrata.ts +532 -0
- package/src/treasury.ts +575 -0
- package/src/usaspending.ts +1946 -214
- package/src/usitc.ts +420 -0
package/src/errors.ts
CHANGED
|
@@ -18,6 +18,8 @@
|
|
|
18
18
|
* the error to the user with appropriate framing.
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
+
import { ZodError } from "zod";
|
|
22
|
+
|
|
21
23
|
export type ErrorKind =
|
|
22
24
|
/** HTTP 429. Retry after `retryAfterSeconds`. */
|
|
23
25
|
| "rate_limited"
|
|
@@ -43,6 +45,19 @@ export type ToolError = {
|
|
|
43
45
|
upstreamStatus?: number;
|
|
44
46
|
/** Endpoint that failed — for ops. */
|
|
45
47
|
upstreamEndpoint?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Set true when the upstream EXPLICITLY asked us to wait — i.e. a 429, or a
|
|
50
|
+
* 5xx that CARRIED a `Retry-After` header (ADR-0045 M2). The resilience layer
|
|
51
|
+
* (circuit breaker + path-chain) consults `isHonorRetryAfter(err)` and EXCLUDES
|
|
52
|
+
* such errors from the breaker failure count AND from fallback (B1-policy): we
|
|
53
|
+
* wait and fail honestly as `rate_limited`/`upstream_unavailable`, never route
|
|
54
|
+
* around a rate limit onto a mirror/snapshot. Absent (undefined) on a plain 5xx
|
|
55
|
+
* with no Retry-After header — that stays a HARD failure the breaker counts, so
|
|
56
|
+
* absence must NOT be read as `false`-meaning-"honor". The 429 path never sets
|
|
57
|
+
* this flag (it is detected by `kind==="rate_limited"`), keeping the 429 error
|
|
58
|
+
* envelope byte-identical to before this ADR.
|
|
59
|
+
*/
|
|
60
|
+
honorRetryAfter?: boolean;
|
|
46
61
|
};
|
|
47
62
|
|
|
48
63
|
export type ToolResult<T> =
|
|
@@ -91,7 +106,7 @@ export function errorFromResponse(
|
|
|
91
106
|
};
|
|
92
107
|
}
|
|
93
108
|
if (r.status >= 500) {
|
|
94
|
-
|
|
109
|
+
const err: ToolError = {
|
|
95
110
|
kind: "upstream_unavailable",
|
|
96
111
|
message: `Upstream server error (HTTP ${r.status}) at ${endpoint}. Try again later.`,
|
|
97
112
|
retryable: true,
|
|
@@ -99,6 +114,19 @@ export function errorFromResponse(
|
|
|
99
114
|
upstreamStatus,
|
|
100
115
|
upstreamEndpoint: endpoint,
|
|
101
116
|
};
|
|
117
|
+
// ADR-0045 M2 — a 5xx MAY carry Retry-After (e.g. a 503 maintenance window).
|
|
118
|
+
// Parse it ONLY when the header is PRESENT (so a plain 5xx is byte-identical
|
|
119
|
+
// to before: retryAfterSeconds:60, no honorRetryAfter key), preserving the
|
|
120
|
+
// `Math.min(...,60)` worst-case cap. The 429 branch above is UNTOUCHED (it
|
|
121
|
+
// already parses Retry-After; re-implementing it is forbidden). Flagging
|
|
122
|
+
// honorRetryAfter lets the resilience layer EXCLUDE this from the breaker /
|
|
123
|
+
// fallback (B1-policy: honor the explicit wait, never route around it).
|
|
124
|
+
const retryAfterHeader = r.headers.get("Retry-After");
|
|
125
|
+
if (retryAfterHeader !== null) {
|
|
126
|
+
err.retryAfterSeconds = Math.min(parseRetryAfter(retryAfterHeader), 60);
|
|
127
|
+
err.honorRetryAfter = true;
|
|
128
|
+
}
|
|
129
|
+
return err;
|
|
102
130
|
}
|
|
103
131
|
if (r.status >= 400) {
|
|
104
132
|
return {
|
|
@@ -118,6 +146,25 @@ export function errorFromResponse(
|
|
|
118
146
|
};
|
|
119
147
|
}
|
|
120
148
|
|
|
149
|
+
/**
|
|
150
|
+
* Does this thrown error carry an EXPLICIT "wait, then fail honestly" signal
|
|
151
|
+
* from the upstream — a 429 (`rate_limited`), or a 5xx that carried a
|
|
152
|
+
* `Retry-After` header (ADR-0045 M2, flagged `honorRetryAfter`)?
|
|
153
|
+
*
|
|
154
|
+
* The resilience layer (circuit breaker + path-chain, datasource.ts) consults
|
|
155
|
+
* this to EXCLUDE such errors from the breaker failure count AND from fallback
|
|
156
|
+
* (ADR-0045 B1-policy): a rate limit / honor-Retry-After outcome must NEVER
|
|
157
|
+
* count as a breaker "hard failure" nor trigger a mirror/snapshot fallback — we
|
|
158
|
+
* wait and fail honestly. This is a POLICY boundary, not a bypass: we honor the
|
|
159
|
+
* upstream's explicit throttle, we do not route around it.
|
|
160
|
+
*/
|
|
161
|
+
export function isHonorRetryAfter(err: unknown): boolean {
|
|
162
|
+
if (!(err instanceof ToolErrorCarrier)) return false;
|
|
163
|
+
const te = err.toolError;
|
|
164
|
+
if (te.kind === "rate_limited") return true;
|
|
165
|
+
return te.honorRetryAfter === true;
|
|
166
|
+
}
|
|
167
|
+
|
|
121
168
|
/**
|
|
122
169
|
* Wrap a fetch + json call in retry-with-backoff for transient errors.
|
|
123
170
|
*
|
|
@@ -147,6 +194,27 @@ export async function fetchWithRetry(
|
|
|
147
194
|
await new Promise((res) => setTimeout(res, wait * 1000));
|
|
148
195
|
} catch (e) {
|
|
149
196
|
if (e instanceof ToolErrorCarrier) throw e;
|
|
197
|
+
// A timeout/abort. The caller's AbortSignal.timeout fired (or an
|
|
198
|
+
// already-aborted signal is being reused across attempts). Retrying is
|
|
199
|
+
// futile within this call's budget: the same signal stays aborted, so
|
|
200
|
+
// attempts 2/3 reject immediately without ever reaching the endpoint,
|
|
201
|
+
// and a re-driven tool call just re-hits the same wall. Fail fast,
|
|
202
|
+
// honestly non-retryable. Keyed on the DOMException NAME only —
|
|
203
|
+
// AbortSignal.timeout → "TimeoutError", AbortController.abort() →
|
|
204
|
+
// "AbortError" — which is disjoint from a genuine network fault
|
|
205
|
+
// (TypeError, name "TypeError"), so a real "fetch failed" falls through
|
|
206
|
+
// to the generic retryable branch below UNCHANGED.
|
|
207
|
+
if (
|
|
208
|
+
e instanceof Error &&
|
|
209
|
+
(e.name === "TimeoutError" || e.name === "AbortError")
|
|
210
|
+
) {
|
|
211
|
+
throw new ToolErrorCarrier({
|
|
212
|
+
kind: "upstream_unavailable",
|
|
213
|
+
message: `Request to ${endpointLabel} timed out.`,
|
|
214
|
+
retryable: false,
|
|
215
|
+
upstreamEndpoint: endpointLabel,
|
|
216
|
+
});
|
|
217
|
+
}
|
|
150
218
|
// Network-level error
|
|
151
219
|
lastErr = {
|
|
152
220
|
kind: "upstream_unavailable",
|
|
@@ -192,6 +260,21 @@ function parseRetryAfter(value: string | null): number {
|
|
|
192
260
|
*/
|
|
193
261
|
export function toToolError(e: unknown, endpointLabel?: string): ToolError {
|
|
194
262
|
if (e instanceof ToolErrorCarrier) return e.toolError;
|
|
263
|
+
// A Zod input-validation failure is a CALLER error (e.g. limit above the max,
|
|
264
|
+
// a value outside an enum). Classify it as `invalid_input` with a readable
|
|
265
|
+
// field-level message — NEVER a generic `unknown` carrying Zod's raw JSON
|
|
266
|
+
// issue array (which an agent can't act on, and which mislabels a fixable
|
|
267
|
+
// input problem as a mysterious/possibly-transient failure).
|
|
268
|
+
if (e instanceof ZodError) {
|
|
269
|
+
return {
|
|
270
|
+
kind: "invalid_input",
|
|
271
|
+
message: `Invalid input${endpointLabel ? ` for ${endpointLabel}` : ""}: ${e.issues
|
|
272
|
+
.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`)
|
|
273
|
+
.join("; ")}`,
|
|
274
|
+
retryable: false,
|
|
275
|
+
upstreamEndpoint: endpointLabel,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
195
278
|
if (e instanceof Error) {
|
|
196
279
|
const msg = e.message;
|
|
197
280
|
// Common fetch timeout signature
|
package/src/fac.ts
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* fac.ts — CMS/GSA Federal Audit Clearinghouse (FAC) Single Audit vetting
|
|
3
|
+
* (ADR-0038). A NEW keyless PostgREST adapter over `api.fac.gov` (fronted by
|
|
4
|
+
* api.data.gov), housing TWO purpose-built audit-RISK vetting tools:
|
|
5
|
+
* - `fac_search_audits` — the `general` table (entity Single Audit summaries)
|
|
6
|
+
* - `fac_get_findings` — the `findings` table (the audit-RISK flags)
|
|
7
|
+
* The B2G unlock: before teaming with / subcontracting to a partner, vet their
|
|
8
|
+
* Single Audit RISK (material weaknesses, questioned costs, repeat findings,
|
|
9
|
+
* modified opinions) — joinable to SAM/USAspending/EDGAR by UEI/EIN. DISTINCT
|
|
10
|
+
* from `src/far.ts` (FAR clause compliance — no filename / gate-key collision).
|
|
11
|
+
*
|
|
12
|
+
* ★ KEYLESS-FIRST via the DEMO_KEY doctrine (the 3rd consumer of `datagovKey.ts`
|
|
13
|
+
* after datagov.ts + govinfo.ts). A bare api.fac.gov request → HTTP 403
|
|
14
|
+
* (API_KEY_MISSING); the SAME request + `X-Api-Key: DEMO_KEY` → 200/206 real
|
|
15
|
+
* data. `keyHeader()` places the secret in the `X-Api-Key` header ONLY (never the
|
|
16
|
+
* URL / label / _meta / a log); `resolvedKey()` falls back to the public literal
|
|
17
|
+
* "DEMO_KEY" when DATA_GOV_API_KEY is unset. `keylessMode:false` (honest — it
|
|
18
|
+
* genuinely sends a key, exactly like datagov.ts/govinfo.ts); `_meta.source`
|
|
19
|
+
* discloses the key-MODE only.
|
|
20
|
+
*
|
|
21
|
+
* R2 consumer — reuses the shared port: `getJsonWithHeaders` (ADR-0038 M1 — the
|
|
22
|
+
* header-exposing sibling of getJson; the EXACT total is a RESPONSE HEADER, not a
|
|
23
|
+
* body field), `driftError` / `throughGate` (datasource.ts), `num`·`str`
|
|
24
|
+
* (coerce.ts), `withMeta` (meta.ts). It writes ZERO bespoke fetch — a hand-rolled
|
|
25
|
+
* fetch inside fac.ts would re-open `redirect:"error"` (a 3xx off api.fac.gov
|
|
26
|
+
* carrying the X-Api-Key to a foreign host = key egress), the hostname/https
|
|
27
|
+
* assert, and `keyHeader()` placement, all of which the shared port keeps
|
|
28
|
+
* structurally present and ADR-0007-K-test-covered.
|
|
29
|
+
*
|
|
30
|
+
* ★ HONESTY (P1–P4; ADR §Q2 + the v2 review):
|
|
31
|
+
* (P1) The EXACT total is the `Content-Range` denominator (a RESPONSE HEADER
|
|
32
|
+
* under `Prefer: count=exact`; 206-on-subset). `parseTotal` takes the
|
|
33
|
+
* substring after the LAST `/`; a run of digits → num() EXACT; a `*`
|
|
34
|
+
* ("count not computed") / non-number / absent header → totalAvailable:null +
|
|
35
|
+
* a page-fullness `hasMore = returned >= limit` hedge + a disclosed note —
|
|
36
|
+
* NEVER 0 (the null-never-0 rule applied to a header).
|
|
37
|
+
* (P2) A genuine `[]` → honest empty (+ the M2 empty-findings note); a body
|
|
38
|
+
* that is not a JSON array → driftError. 400/403/5xx/timeout/off-host-redirect
|
|
39
|
+
* THROW via the port taxonomy (206 = success — `r.ok` covers 200-299). An
|
|
40
|
+
* HTML/non-JSON 200 (r.json() SyntaxError) → reclassified to schema_drift
|
|
41
|
+
* (S1) — never a fake empty.
|
|
42
|
+
* (P3) `total_amount_expended` is a JSON number → num() null-never-0. The `is_*`
|
|
43
|
+
* risk flags are STRINGS "Y"/"N" — surfaced verbatim (str → "Y"/"N"/null) AND
|
|
44
|
+
* mapped to a tri-state `riskFlags` object ("Y"→true / "N"→false / blank /
|
|
45
|
+
* absent / other → null=UNKNOWN). A null flag must NEVER read as false/"no
|
|
46
|
+
* material weakness" (the OFAC/sam_check_exclusions false-CLEAR class).
|
|
47
|
+
* (P4) Filters are server-side + self-policing: each caller filter maps to a
|
|
48
|
+
* KNOWN column + a FIXED operator, value-validated + URLSearchParams-encoded;
|
|
49
|
+
* a valid filter narrows the Content-Range total, a bad column → PostgREST 400
|
|
50
|
+
* → invalid_input. So `filtersDropped` is ALWAYS empty (no silent-drop path).
|
|
51
|
+
*
|
|
52
|
+
* ★ THE PII CRUX (load-bearing — §PII boundary, LIVE-confirmed SOUND): the
|
|
53
|
+
* `select=` is a HARDCODED MODULE CONSTANT allowlist that SURFACES only entity +
|
|
54
|
+
* audit-risk fields and EXCLUDES all 6 personal-contact columns (auditee_email,
|
|
55
|
+
* auditee_phone, auditee_certify_name, auditee_certify_title, auditee_contact_name,
|
|
56
|
+
* auditee_contact_title). PostgREST WILL project auditee_email the instant
|
|
57
|
+
* `select=` names it (live-verified), so the tools accept NO caller-supplied
|
|
58
|
+
* `select`/`order`/free-column param — the inputs are ONLY structured, validated
|
|
59
|
+
* filters. Purpose-built tools bake the allowlist in by construction (the reason
|
|
60
|
+
* v1 rejects a generic `fac_query{select}`). The mapper also picks ONLY the
|
|
61
|
+
* allowlist keys, so even a drifted server that returns an extra column cannot
|
|
62
|
+
* leak it into the output.
|
|
63
|
+
*
|
|
64
|
+
* ★ SSRF: fixed host `api.fac.gov` (single-entry FAC_HOSTS allowlist + a Set.has
|
|
65
|
+
* recheck); the table name is a FIXED per-tool path CONSTANT (`general`/`findings`
|
|
66
|
+
* — never caller free-text); filter values ride URLSearchParams as
|
|
67
|
+
* `col=eq.VALUE`; `redirect:"error"`; a post-construction hostname/https assert.
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
import { ToolErrorCarrier } from "./errors.js";
|
|
71
|
+
import { getJsonWithHeaders, driftError, throughGate } from "./datasource.js";
|
|
72
|
+
import { num, str } from "./coerce.js";
|
|
73
|
+
import { keyHeader, keyModeLabel, pushKeyNote } from "./datagovKey.js";
|
|
74
|
+
import { withMeta, type MetaBundle, type ResponseMeta } from "./meta.js";
|
|
75
|
+
|
|
76
|
+
// Re-export the shared honesty coercion (single audited copy in ./coerce.js) so
|
|
77
|
+
// the fault suite's num-parity guard resolves fac.num === coerce.num, exactly
|
|
78
|
+
// like fdic.num / cms.num / datagov.num.
|
|
79
|
+
export { num };
|
|
80
|
+
|
|
81
|
+
// ─── Constants (SSRF core) ─────────────────────────────────────────
|
|
82
|
+
const FAC_HOST = "api.fac.gov";
|
|
83
|
+
// Single-entry host allowlist (structured for a later host-add; the belt-and-
|
|
84
|
+
// suspenders Set.has recheck runs in getFac).
|
|
85
|
+
export const FAC_HOSTS: readonly string[] = [FAC_HOST];
|
|
86
|
+
const FAC_HOST_SET: ReadonlySet<string> = new Set(FAC_HOSTS);
|
|
87
|
+
// One host = one rate budget. A modest self-throttle — courtesy to a shared
|
|
88
|
+
// api.data.gov-fronted host, doubly warranted by the ~10 req/hr DEMO_KEY ceiling.
|
|
89
|
+
const FAC_MIN_INTERVAL_MS = 200;
|
|
90
|
+
export const FAC_LABEL = "fac:" + FAC_HOST; // → ToolError.upstreamEndpoint (host-only)
|
|
91
|
+
const GATE_KEY = "fac";
|
|
92
|
+
|
|
93
|
+
// Fixed table path constants — the TOOL chooses these; NO caller value on the
|
|
94
|
+
// path (SSRF core / no table-injection surface).
|
|
95
|
+
const TABLE_GENERAL = "general";
|
|
96
|
+
const TABLE_FINDINGS = "findings";
|
|
97
|
+
|
|
98
|
+
// ★ The HARDCODED positive select-allowlists (the PII crux). These are the ONLY
|
|
99
|
+
// columns ever named on the wire — every personal-contact column
|
|
100
|
+
// (auditee_email/phone/certify_name/certify_title/contact_name/contact_title) is
|
|
101
|
+
// STRUCTURALLY excluded. NO caller can supply a `select`/column param.
|
|
102
|
+
export const GENERAL_SELECT =
|
|
103
|
+
"report_id,auditee_uei,audit_year,auditee_name,auditee_ein,auditee_state,auditee_city,total_amount_expended,fac_accepted_date";
|
|
104
|
+
export const FINDINGS_SELECT =
|
|
105
|
+
"report_id,auditee_uei,audit_year,award_reference,reference_number,is_material_weakness,is_modified_opinion,is_questioned_costs,is_repeat_finding,is_significant_deficiency,is_other_findings,is_other_matters,type_requirement,prior_finding_ref_numbers";
|
|
106
|
+
|
|
107
|
+
// Fixed default orders (deterministic offset windows; never caller-derived).
|
|
108
|
+
const GENERAL_ORDER = "fac_accepted_date.desc";
|
|
109
|
+
const FINDINGS_ORDER = "report_id.asc,reference_number.asc";
|
|
110
|
+
|
|
111
|
+
// The 7 audit-RISK flags (STRING "Y"/"N"/blank live) mapped to the tri-state.
|
|
112
|
+
const RISK_FLAG_COLUMNS = [
|
|
113
|
+
"is_material_weakness",
|
|
114
|
+
"is_modified_opinion",
|
|
115
|
+
"is_questioned_costs",
|
|
116
|
+
"is_repeat_finding",
|
|
117
|
+
"is_significant_deficiency",
|
|
118
|
+
"is_other_findings",
|
|
119
|
+
"is_other_matters",
|
|
120
|
+
] as const;
|
|
121
|
+
|
|
122
|
+
// ─── Input grammars (belt-and-suspenders behind the server's Zod schemas — the
|
|
123
|
+
// fault suite calls these functions directly, bypassing Zod, so re-validation
|
|
124
|
+
// here is load-bearing for the SSRF/injection rejects). ────────────
|
|
125
|
+
const UEI_RE = /^[A-Z0-9]{12}$/;
|
|
126
|
+
const STATE_RE = /^[A-Z]{2}$/;
|
|
127
|
+
const REPORT_ID_RE = /^[0-9A-Za-z-]+$/;
|
|
128
|
+
const REPORT_ID_MAX = 64;
|
|
129
|
+
|
|
130
|
+
function invalidInput(message: string): ToolErrorCarrier {
|
|
131
|
+
return new ToolErrorCarrier({ kind: "invalid_input", message, retryable: false });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ─── Disclosure constants (honesty obligations — verbatim, fault-asserted) ──
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* ★ §PII(d) — the mandatory not-a-determination caveat carried on EVERY response
|
|
138
|
+
* (mirrors OFAC_NOT_DETERMINATION_NOTE / NPPES_NOT_DETERMINATION_NOTE). Kept
|
|
139
|
+
* verbatim so the fault suite can assert it.
|
|
140
|
+
*/
|
|
141
|
+
export const FAC_NOT_DETERMINATION_NOTE =
|
|
142
|
+
"Public Single Audit data (Federal Audit Clearinghouse; 2 CFR 200 Subpart F / Single Audit Act). Reports the independent auditor's findings, opinions, and questioned costs AS SUBMITTED — it is NOT a debarment, suspension, exclusion, or fitness determination, and an audit finding is the auditor's opinion, not proof of wrongdoing (many findings are routine and remediated). This tool DELIBERATELY EXCLUDES the auditee's personal-contact fields (email / phone / certifying-official name) — the vetting subject is the entity, not the individual. Cross-check SAM exclusions + OFAC and read the specific finding text before acting.";
|
|
143
|
+
|
|
144
|
+
/** ★ P3 — the risk-flag typing disclosure carried on EVERY fac_get_findings response. */
|
|
145
|
+
export const FAC_VALUE_TYPING_NOTE =
|
|
146
|
+
"Risk flags (is_material_weakness, is_modified_opinion, is_questioned_costs, is_repeat_finding, is_significant_deficiency, is_other_findings, is_other_matters) are surfaced VERBATIM as the auditor reported them (\"Y\"/\"N\") plus a typed riskFlags tri-state; a blank/absent flag is UNKNOWN (null), NOT a \"no\" — never read a null flag as 'no finding'.";
|
|
147
|
+
|
|
148
|
+
/** ★ M2 — the empty-findings ≠ clean-audit disclosure (any totalAvailable:0 / empty findings). */
|
|
149
|
+
export const FAC_EMPTY_FINDINGS_NOTE =
|
|
150
|
+
"An empty findings list means NO findings are ON RECORD for this UEI/report — it does NOT confirm a clean audit. The entity may not have filed a Single Audit (below the $750K threshold), the audit may predate FAC coverage, or the UEI may be wrong. Confirm the entity has an ACCEPTED audit via fac_search_audits before treating empty as clean.";
|
|
151
|
+
|
|
152
|
+
/** P1 — the Content-Range hedge disclosure (a `*`/absent/non-numeric denominator). */
|
|
153
|
+
const FAC_TOTAL_HEDGE_NOTE =
|
|
154
|
+
"FAC did not return an exact Content-Range total (the denominator was '*', absent, or non-numeric); totalAvailable is UNKNOWN (null) and hasMore is inferred from page-fullness — page via offset until a short page confirms the end (never read this as 0 results).";
|
|
155
|
+
|
|
156
|
+
function facSource(): string {
|
|
157
|
+
return `${FAC_HOST} via Federal Audit Clearinghouse API (${keyModeLabel()})`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ─── P1 — Content-Range EXACT-total parse (num-guarded, null-never-0) ──
|
|
161
|
+
/**
|
|
162
|
+
* Parse the EXACT total from `Content-Range: <start>-<end>/<TOTAL>` — take the
|
|
163
|
+
* substring after the LAST `/` and `num()` it. A run of digits → the EXACT total
|
|
164
|
+
* (`0` denominator → 0, a genuine-empty total); a `*` (PostgREST "count not
|
|
165
|
+
* computed") / non-number / absent header → null (NEVER 0 — the null-never-0 rule
|
|
166
|
+
* on a header). Exported for the Content-Range-matrix fault fixture.
|
|
167
|
+
*/
|
|
168
|
+
export function parseTotal(contentRange: string | null): number | null {
|
|
169
|
+
if (typeof contentRange !== "string") return null;
|
|
170
|
+
const slash = contentRange.lastIndexOf("/");
|
|
171
|
+
if (slash < 0) return null;
|
|
172
|
+
// num("*")→null, num("")→null, num("37144")→37144, num("0")→0 (genuine zero).
|
|
173
|
+
return num(contentRange.slice(slash + 1).trim());
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ─── P3 — risk-flag tri-state ("Y"→true / "N"→false / else → null=UNKNOWN) ──
|
|
177
|
+
/**
|
|
178
|
+
* Map an FAC risk flag to an HONEST tri-state: "Y" → true, "N" → false, and a
|
|
179
|
+
* null / blank / absent / any-other value → null (UNKNOWN — NEVER false). A null
|
|
180
|
+
* `is_material_weakness` silently read as "no material weakness" is the false-CLEAR
|
|
181
|
+
* class OFAC/sam_check_exclusions forbid. Exported for the flag-type fault fixture.
|
|
182
|
+
*/
|
|
183
|
+
export function flagTri(v: unknown): boolean | null {
|
|
184
|
+
const s = typeof v === "string" ? v.trim().toUpperCase() : v;
|
|
185
|
+
if (s === "Y") return true;
|
|
186
|
+
if (s === "N") return false;
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ─── SSRF-guarded fetch (fixed host + hostname assert + redirect) ──
|
|
191
|
+
/**
|
|
192
|
+
* GET one FAC PostgREST table through the shared header-exposing port. `table` is
|
|
193
|
+
* a FIXED per-tool constant (general/findings) — NO caller value on the path. The
|
|
194
|
+
* key rides `X-Api-Key` ONLY (keyHeader), `Prefer: count=exact` requests the
|
|
195
|
+
* EXACT total, `redirect:"error"` refuses an off-host 3xx (no key egress), and the
|
|
196
|
+
* CONSTRUCTED URL's hostname must equal api.fac.gov over https (+ a Set.has
|
|
197
|
+
* recheck). Returns `{ body, contentRange }`. A 200 non-JSON body (r.json()
|
|
198
|
+
* SyntaxError, e.g. an HTML maintenance page) is reclassified to schema_drift
|
|
199
|
+
* (S1); the structured 400/403/429/5xx/timeout taxonomy propagates unchanged.
|
|
200
|
+
*/
|
|
201
|
+
async function getFac(
|
|
202
|
+
table: string,
|
|
203
|
+
params: URLSearchParams,
|
|
204
|
+
): Promise<{ body: unknown; contentRange: string | null }> {
|
|
205
|
+
const url = `https://${FAC_HOST}/${table}?${params.toString()}`;
|
|
206
|
+
const built = new URL(url);
|
|
207
|
+
if (
|
|
208
|
+
built.hostname !== FAC_HOST ||
|
|
209
|
+
built.protocol !== "https:" ||
|
|
210
|
+
!FAC_HOST_SET.has(built.hostname)
|
|
211
|
+
) {
|
|
212
|
+
throw invalidInput(
|
|
213
|
+
`Constructed FAC URL host ${JSON.stringify(built.hostname)} (${built.protocol}) is not ${FAC_HOST} over https — refusing to fetch (SSRF safety).`,
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
return await throughGate(GATE_KEY, FAC_MIN_INTERVAL_MS, () =>
|
|
218
|
+
getJsonWithHeaders(url, {
|
|
219
|
+
label: FAC_LABEL,
|
|
220
|
+
headers: { ...keyHeader(), Prefer: "count=exact" },
|
|
221
|
+
redirect: "error",
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
224
|
+
} catch (e) {
|
|
225
|
+
// Preserve the structured taxonomy (400/403/429/5xx/timeout/off-host-redirect).
|
|
226
|
+
if (e instanceof ToolErrorCarrier) throw e;
|
|
227
|
+
// ★ S1 — a 200 non-JSON body makes getJsonWithHeaders' r.json() throw a
|
|
228
|
+
// SyntaxError → reclassify to schema_drift (an honest THROW, never a fake
|
|
229
|
+
// empty). The shared port stays byte-identical (reclassification is HERE).
|
|
230
|
+
if (e instanceof SyntaxError) {
|
|
231
|
+
throw driftError(
|
|
232
|
+
FAC_LABEL,
|
|
233
|
+
"FAC returned a non-JSON body at HTTP 2xx — treating as schema drift.",
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
throw e;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Assert the parsed body is a JSON array (P2 drift guard); else driftError. */
|
|
241
|
+
function asArray(body: unknown, table: string): unknown[] {
|
|
242
|
+
if (!Array.isArray(body)) {
|
|
243
|
+
throw driftError(
|
|
244
|
+
FAC_LABEL,
|
|
245
|
+
`FAC ${table} returned a non-array body — treating as schema drift (PostgREST returns a bare JSON array; never a fake empty).`,
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
return body;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ─── row mappers (pick ONLY the allowlist keys — a drifted extra column, incl.
|
|
252
|
+
// any personal-contact field, can NOT reach the output) ────────────
|
|
253
|
+
export type FacAudit = {
|
|
254
|
+
report_id: string | null;
|
|
255
|
+
auditee_uei: string | null;
|
|
256
|
+
audit_year: string | null;
|
|
257
|
+
auditee_name: string | null;
|
|
258
|
+
auditee_ein: string | null;
|
|
259
|
+
auditee_state: string | null;
|
|
260
|
+
auditee_city: string | null;
|
|
261
|
+
total_amount_expended: number | null;
|
|
262
|
+
fac_accepted_date: string | null;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
function mapAudit(rec: Record<string, unknown>): FacAudit {
|
|
266
|
+
return {
|
|
267
|
+
report_id: str(rec.report_id),
|
|
268
|
+
auditee_uei: str(rec.auditee_uei),
|
|
269
|
+
audit_year: str(rec.audit_year), // a STRING live ("2026")
|
|
270
|
+
auditee_name: str(rec.auditee_name),
|
|
271
|
+
auditee_ein: str(rec.auditee_ein), // a STRING live ("911767139")
|
|
272
|
+
auditee_state: str(rec.auditee_state),
|
|
273
|
+
auditee_city: str(rec.auditee_city),
|
|
274
|
+
total_amount_expended: num(rec.total_amount_expended), // JSON number, null-never-0
|
|
275
|
+
fac_accepted_date: str(rec.fac_accepted_date),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export type FacFinding = {
|
|
280
|
+
report_id: string | null;
|
|
281
|
+
auditee_uei: string | null;
|
|
282
|
+
audit_year: string | null;
|
|
283
|
+
award_reference: string | null;
|
|
284
|
+
reference_number: string | null;
|
|
285
|
+
is_material_weakness: string | null;
|
|
286
|
+
is_modified_opinion: string | null;
|
|
287
|
+
is_questioned_costs: string | null;
|
|
288
|
+
is_repeat_finding: string | null;
|
|
289
|
+
is_significant_deficiency: string | null;
|
|
290
|
+
is_other_findings: string | null;
|
|
291
|
+
is_other_matters: string | null;
|
|
292
|
+
type_requirement: string | null;
|
|
293
|
+
prior_finding_ref_numbers: string | null;
|
|
294
|
+
// ★ P3 — the typed tri-state convenience view ("Y"→true/"N"→false/UNKNOWN→null).
|
|
295
|
+
riskFlags: {
|
|
296
|
+
materialWeakness: boolean | null;
|
|
297
|
+
modifiedOpinion: boolean | null;
|
|
298
|
+
questionedCosts: boolean | null;
|
|
299
|
+
repeatFinding: boolean | null;
|
|
300
|
+
significantDeficiency: boolean | null;
|
|
301
|
+
otherFindings: boolean | null;
|
|
302
|
+
otherMatters: boolean | null;
|
|
303
|
+
};
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
function mapFinding(rec: Record<string, unknown>): FacFinding {
|
|
307
|
+
return {
|
|
308
|
+
report_id: str(rec.report_id),
|
|
309
|
+
auditee_uei: str(rec.auditee_uei),
|
|
310
|
+
audit_year: str(rec.audit_year),
|
|
311
|
+
award_reference: str(rec.award_reference),
|
|
312
|
+
reference_number: str(rec.reference_number),
|
|
313
|
+
// Flags surfaced VERBATIM ("Y"/"N"/null — str nulls ""/"null", so a blank
|
|
314
|
+
// flag is null=UNKNOWN, never "N").
|
|
315
|
+
is_material_weakness: str(rec.is_material_weakness),
|
|
316
|
+
is_modified_opinion: str(rec.is_modified_opinion),
|
|
317
|
+
is_questioned_costs: str(rec.is_questioned_costs),
|
|
318
|
+
is_repeat_finding: str(rec.is_repeat_finding),
|
|
319
|
+
is_significant_deficiency: str(rec.is_significant_deficiency),
|
|
320
|
+
is_other_findings: str(rec.is_other_findings),
|
|
321
|
+
is_other_matters: str(rec.is_other_matters),
|
|
322
|
+
type_requirement: str(rec.type_requirement),
|
|
323
|
+
prior_finding_ref_numbers: str(rec.prior_finding_ref_numbers),
|
|
324
|
+
riskFlags: {
|
|
325
|
+
materialWeakness: flagTri(rec.is_material_weakness),
|
|
326
|
+
modifiedOpinion: flagTri(rec.is_modified_opinion),
|
|
327
|
+
questionedCosts: flagTri(rec.is_questioned_costs),
|
|
328
|
+
repeatFinding: flagTri(rec.is_repeat_finding),
|
|
329
|
+
significantDeficiency: flagTri(rec.is_significant_deficiency),
|
|
330
|
+
otherFindings: flagTri(rec.is_other_findings),
|
|
331
|
+
otherMatters: flagTri(rec.is_other_matters),
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
void RISK_FLAG_COLUMNS; // documented flag inventory (mapper enumerates explicitly)
|
|
336
|
+
|
|
337
|
+
// ─── Tool 1: fac_search_audits (the `general` table) ───────────────
|
|
338
|
+
/**
|
|
339
|
+
* Search entity Single Audit summaries (`/general`). Structured filters (all
|
|
340
|
+
* optional, AND-combined): `auditeeUei` (^[A-Z0-9]{12}$), `auditeeState`
|
|
341
|
+
* (^[A-Z]{2}$), `auditYear` (int), `totalExpendedMin`/`totalExpendedMax` (finite
|
|
342
|
+
* → gte/lte on total_amount_expended). Plus `limit` (1..100, def 25) / `offset`.
|
|
343
|
+
* The `select=` is the HARDCODED GENERAL_SELECT allowlist (NO personal-contact
|
|
344
|
+
* columns; NO caller column param). Order is the fixed GENERAL_ORDER.
|
|
345
|
+
*
|
|
346
|
+
* HONESTY: totalAvailable is the EXACT Content-Range denominator (P1; a `*`/
|
|
347
|
+
* absent/non-numeric → null + a page-fullness hedge, never 0); a bad column ⇒
|
|
348
|
+
* PostgREST 400 ⇒ invalid_input (filtersDropped always empty, P4); a genuine `[]`
|
|
349
|
+
* ⇒ honest empty; 400/403/5xx/timeout/HTML(SyntaxError)/non-array THROW (P2, 206 =
|
|
350
|
+
* success). The FAC_NOT_DETERMINATION_NOTE rides every response.
|
|
351
|
+
*/
|
|
352
|
+
export async function searchAudits(args: {
|
|
353
|
+
auditeeUei?: string;
|
|
354
|
+
auditeeState?: string;
|
|
355
|
+
auditYear?: number;
|
|
356
|
+
totalExpendedMin?: number;
|
|
357
|
+
totalExpendedMax?: number;
|
|
358
|
+
limit?: number;
|
|
359
|
+
offset?: number;
|
|
360
|
+
}): Promise<MetaBundle> {
|
|
361
|
+
const limit = args.limit ?? 25;
|
|
362
|
+
const offset = args.offset ?? 0;
|
|
363
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
364
|
+
throw invalidInput("fac_search_audits: limit must be an integer in 1..100.");
|
|
365
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
366
|
+
throw invalidInput("fac_search_audits: offset must be an integer ≥ 0.");
|
|
367
|
+
|
|
368
|
+
const params = new URLSearchParams();
|
|
369
|
+
params.set("select", GENERAL_SELECT); // ★ hardcoded allowlist — never caller-derived
|
|
370
|
+
const filtersApplied: string[] = [];
|
|
371
|
+
|
|
372
|
+
if (args.auditeeUei !== undefined) {
|
|
373
|
+
if (!UEI_RE.test(args.auditeeUei))
|
|
374
|
+
throw invalidInput("fac_search_audits: auditeeUei must match ^[A-Z0-9]{12}$ (12-char UEI).");
|
|
375
|
+
params.append("auditee_uei", `eq.${args.auditeeUei}`);
|
|
376
|
+
filtersApplied.push("auditeeUei");
|
|
377
|
+
}
|
|
378
|
+
if (args.auditeeState !== undefined) {
|
|
379
|
+
if (!STATE_RE.test(args.auditeeState))
|
|
380
|
+
throw invalidInput("fac_search_audits: auditeeState must match ^[A-Z]{2}$ (2-letter state).");
|
|
381
|
+
params.append("auditee_state", `eq.${args.auditeeState}`);
|
|
382
|
+
filtersApplied.push("auditeeState");
|
|
383
|
+
}
|
|
384
|
+
if (args.auditYear !== undefined) {
|
|
385
|
+
if (!Number.isInteger(args.auditYear))
|
|
386
|
+
throw invalidInput("fac_search_audits: auditYear must be an integer.");
|
|
387
|
+
params.append("audit_year", `eq.${args.auditYear}`);
|
|
388
|
+
filtersApplied.push("auditYear");
|
|
389
|
+
}
|
|
390
|
+
if (args.totalExpendedMin !== undefined) {
|
|
391
|
+
if (!Number.isFinite(args.totalExpendedMin))
|
|
392
|
+
throw invalidInput("fac_search_audits: totalExpendedMin must be a finite number.");
|
|
393
|
+
params.append("total_amount_expended", `gte.${args.totalExpendedMin}`);
|
|
394
|
+
filtersApplied.push("totalExpendedMin");
|
|
395
|
+
}
|
|
396
|
+
if (args.totalExpendedMax !== undefined) {
|
|
397
|
+
if (!Number.isFinite(args.totalExpendedMax))
|
|
398
|
+
throw invalidInput("fac_search_audits: totalExpendedMax must be a finite number.");
|
|
399
|
+
params.append("total_amount_expended", `lte.${args.totalExpendedMax}`);
|
|
400
|
+
filtersApplied.push("totalExpendedMax");
|
|
401
|
+
}
|
|
402
|
+
params.set("order", GENERAL_ORDER);
|
|
403
|
+
params.set("limit", String(limit));
|
|
404
|
+
params.set("offset", String(offset));
|
|
405
|
+
|
|
406
|
+
const { body, contentRange } = await getFac(TABLE_GENERAL, params);
|
|
407
|
+
const rows = asArray(body, TABLE_GENERAL).map((r) =>
|
|
408
|
+
mapAudit((r ?? {}) as Record<string, unknown>),
|
|
409
|
+
);
|
|
410
|
+
const returned = rows.length;
|
|
411
|
+
const totalAvailable = parseTotal(contentRange); // EXACT or null
|
|
412
|
+
const exact = totalAvailable !== null;
|
|
413
|
+
const hasMore = exact ? offset + returned < totalAvailable : returned >= limit;
|
|
414
|
+
const nextOffset = hasMore ? offset + returned : null;
|
|
415
|
+
|
|
416
|
+
const notes: string[] = [];
|
|
417
|
+
pushKeyNote(notes);
|
|
418
|
+
if (!exact) notes.push(FAC_TOTAL_HEDGE_NOTE);
|
|
419
|
+
notes.push(FAC_NOT_DETERMINATION_NOTE);
|
|
420
|
+
|
|
421
|
+
return withMeta(
|
|
422
|
+
{ audits: rows },
|
|
423
|
+
{
|
|
424
|
+
source: facSource(),
|
|
425
|
+
keylessMode: false,
|
|
426
|
+
returned,
|
|
427
|
+
totalAvailable,
|
|
428
|
+
filtersApplied,
|
|
429
|
+
filtersDropped: [],
|
|
430
|
+
fieldsUnavailable: [],
|
|
431
|
+
pagination: { offset, limit, hasMore, nextOffset },
|
|
432
|
+
notes,
|
|
433
|
+
} satisfies Partial<ResponseMeta>,
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ─── Tool 2: fac_get_findings (the `findings` table) ───────────────
|
|
438
|
+
/**
|
|
439
|
+
* Drill into the audit-RISK findings (`/findings`) for a UEI and/or report. At
|
|
440
|
+
* least ONE of `auditeeUei` (^[A-Z0-9]{12}$) / `reportId` (^[0-9A-Za-z-]+$) is
|
|
441
|
+
* REQUIRED (empty → invalid_input, never a no-op full-table scan). Optional
|
|
442
|
+
* `auditYear` (int), `limit` (1..100, def 50), `offset`. The `select=` is the
|
|
443
|
+
* HARDCODED FINDINGS_SELECT allowlist (NO caller column param). Order is fixed.
|
|
444
|
+
*
|
|
445
|
+
* HONESTY: EXACT Content-Range total (P1); risk flags "Y"/"N" verbatim + the tri-
|
|
446
|
+
* state riskFlags (P3, null-is-UNKNOWN); a bad column ⇒ 400 ⇒ invalid_input (P4);
|
|
447
|
+
* 400/403/5xx/timeout/HTML/non-array THROW (P2); a genuine empty ⇒ honest empty +
|
|
448
|
+
* the ★M2 empty≠clean note. FAC_NOT_DETERMINATION_NOTE + FAC_VALUE_TYPING_NOTE
|
|
449
|
+
* ride every response.
|
|
450
|
+
*/
|
|
451
|
+
export async function getFindings(args: {
|
|
452
|
+
auditeeUei?: string;
|
|
453
|
+
reportId?: string;
|
|
454
|
+
auditYear?: number;
|
|
455
|
+
limit?: number;
|
|
456
|
+
offset?: number;
|
|
457
|
+
}): Promise<MetaBundle> {
|
|
458
|
+
const limit = args.limit ?? 50;
|
|
459
|
+
const offset = args.offset ?? 0;
|
|
460
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
461
|
+
throw invalidInput("fac_get_findings: limit must be an integer in 1..100.");
|
|
462
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
463
|
+
throw invalidInput("fac_get_findings: offset must be an integer ≥ 0.");
|
|
464
|
+
if (args.auditeeUei === undefined && args.reportId === undefined)
|
|
465
|
+
throw invalidInput(
|
|
466
|
+
"fac_get_findings: at least one of auditeeUei or reportId is REQUIRED (an empty query would scan the whole 670K-row findings table — refused).",
|
|
467
|
+
);
|
|
468
|
+
|
|
469
|
+
const params = new URLSearchParams();
|
|
470
|
+
params.set("select", FINDINGS_SELECT); // ★ hardcoded allowlist — never caller-derived
|
|
471
|
+
const filtersApplied: string[] = [];
|
|
472
|
+
|
|
473
|
+
if (args.auditeeUei !== undefined) {
|
|
474
|
+
if (!UEI_RE.test(args.auditeeUei))
|
|
475
|
+
throw invalidInput("fac_get_findings: auditeeUei must match ^[A-Z0-9]{12}$ (12-char UEI).");
|
|
476
|
+
params.append("auditee_uei", `eq.${args.auditeeUei}`);
|
|
477
|
+
filtersApplied.push("auditeeUei");
|
|
478
|
+
}
|
|
479
|
+
if (args.reportId !== undefined) {
|
|
480
|
+
if (!REPORT_ID_RE.test(args.reportId) || args.reportId.length > REPORT_ID_MAX)
|
|
481
|
+
throw invalidInput(
|
|
482
|
+
`fac_get_findings: reportId must match ^[0-9A-Za-z-]+$ (≤ ${REPORT_ID_MAX} chars).`,
|
|
483
|
+
);
|
|
484
|
+
params.append("report_id", `eq.${args.reportId}`);
|
|
485
|
+
filtersApplied.push("reportId");
|
|
486
|
+
}
|
|
487
|
+
if (args.auditYear !== undefined) {
|
|
488
|
+
if (!Number.isInteger(args.auditYear))
|
|
489
|
+
throw invalidInput("fac_get_findings: auditYear must be an integer.");
|
|
490
|
+
params.append("audit_year", `eq.${args.auditYear}`);
|
|
491
|
+
filtersApplied.push("auditYear");
|
|
492
|
+
}
|
|
493
|
+
params.set("order", FINDINGS_ORDER);
|
|
494
|
+
params.set("limit", String(limit));
|
|
495
|
+
params.set("offset", String(offset));
|
|
496
|
+
|
|
497
|
+
const { body, contentRange } = await getFac(TABLE_FINDINGS, params);
|
|
498
|
+
const rows = asArray(body, TABLE_FINDINGS).map((r) =>
|
|
499
|
+
mapFinding((r ?? {}) as Record<string, unknown>),
|
|
500
|
+
);
|
|
501
|
+
const returned = rows.length;
|
|
502
|
+
const totalAvailable = parseTotal(contentRange);
|
|
503
|
+
const exact = totalAvailable !== null;
|
|
504
|
+
const hasMore = exact ? offset + returned < totalAvailable : returned >= limit;
|
|
505
|
+
const nextOffset = hasMore ? offset + returned : null;
|
|
506
|
+
|
|
507
|
+
const notes: string[] = [];
|
|
508
|
+
pushKeyNote(notes);
|
|
509
|
+
if (!exact) notes.push(FAC_TOTAL_HEDGE_NOTE);
|
|
510
|
+
// ★ M2 — an empty findings result is an AMBIGUOUS false-CLEAR; disclose that
|
|
511
|
+
// empty ≠ clean audit (fires on any empty page / totalAvailable:0).
|
|
512
|
+
if (returned === 0 || totalAvailable === 0) notes.push(FAC_EMPTY_FINDINGS_NOTE);
|
|
513
|
+
notes.push(FAC_VALUE_TYPING_NOTE, FAC_NOT_DETERMINATION_NOTE);
|
|
514
|
+
|
|
515
|
+
return withMeta(
|
|
516
|
+
{ findings: rows },
|
|
517
|
+
{
|
|
518
|
+
source: facSource(),
|
|
519
|
+
keylessMode: false,
|
|
520
|
+
returned,
|
|
521
|
+
totalAvailable,
|
|
522
|
+
filtersApplied,
|
|
523
|
+
filtersDropped: [],
|
|
524
|
+
fieldsUnavailable: [],
|
|
525
|
+
pagination: { offset, limit, hasMore, nextOffset },
|
|
526
|
+
notes,
|
|
527
|
+
} satisfies Partial<ResponseMeta>,
|
|
528
|
+
);
|
|
529
|
+
}
|