@cliwant/mcp-sam-gov 0.2.1 → 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.
Files changed (228) hide show
  1. package/LICENSE +21 -21
  2. package/README.ja.md +48 -16
  3. package/README.ko.md +48 -16
  4. package/README.md +279 -67
  5. package/dist/attachments.d.ts +63 -0
  6. package/dist/attachments.d.ts.map +1 -0
  7. package/dist/attachments.js +576 -0
  8. package/dist/attachments.js.map +1 -0
  9. package/dist/bls.d.ts +267 -0
  10. package/dist/bls.d.ts.map +1 -0
  11. package/dist/bls.js +1549 -0
  12. package/dist/bls.js.map +1 -0
  13. package/dist/cache.d.ts +42 -0
  14. package/dist/cache.d.ts.map +1 -0
  15. package/dist/cache.js +64 -0
  16. package/dist/cache.js.map +1 -0
  17. package/dist/census.d.ts +182 -0
  18. package/dist/census.d.ts.map +1 -0
  19. package/dist/census.js +576 -0
  20. package/dist/census.js.map +1 -0
  21. package/dist/ckan.d.ts +141 -0
  22. package/dist/ckan.d.ts.map +1 -0
  23. package/dist/ckan.js +393 -0
  24. package/dist/ckan.js.map +1 -0
  25. package/dist/clinicaltrials.d.ts +180 -0
  26. package/dist/clinicaltrials.d.ts.map +1 -0
  27. package/dist/clinicaltrials.js +730 -0
  28. package/dist/clinicaltrials.js.map +1 -0
  29. package/dist/cms.d.ts +140 -0
  30. package/dist/cms.d.ts.map +1 -0
  31. package/dist/cms.js +482 -0
  32. package/dist/cms.js.map +1 -0
  33. package/dist/coerce.d.ts +32 -0
  34. package/dist/coerce.d.ts.map +1 -0
  35. package/dist/coerce.js +50 -0
  36. package/dist/coerce.js.map +1 -0
  37. package/dist/datagov-catalog.d.ts +84 -0
  38. package/dist/datagov-catalog.d.ts.map +1 -0
  39. package/dist/datagov-catalog.js +233 -0
  40. package/dist/datagov-catalog.js.map +1 -0
  41. package/dist/datagov.d.ts +146 -0
  42. package/dist/datagov.d.ts.map +1 -0
  43. package/dist/datagov.js +689 -0
  44. package/dist/datagov.js.map +1 -0
  45. package/dist/datagovKey.d.ts +36 -0
  46. package/dist/datagovKey.d.ts.map +1 -0
  47. package/dist/datagovKey.js +60 -0
  48. package/dist/datagovKey.js.map +1 -0
  49. package/dist/datasource.d.ts +313 -0
  50. package/dist/datasource.d.ts.map +1 -0
  51. package/dist/datasource.js +551 -0
  52. package/dist/datasource.js.map +1 -0
  53. package/dist/disclosure.d.ts +55 -0
  54. package/dist/disclosure.d.ts.map +1 -0
  55. package/dist/disclosure.js +57 -0
  56. package/dist/disclosure.js.map +1 -0
  57. package/dist/ecfr.d.ts +4 -2
  58. package/dist/ecfr.d.ts.map +1 -1
  59. package/dist/ecfr.js +92 -17
  60. package/dist/ecfr.js.map +1 -1
  61. package/dist/echo.d.ts +143 -0
  62. package/dist/echo.d.ts.map +1 -0
  63. package/dist/echo.js +424 -0
  64. package/dist/echo.js.map +1 -0
  65. package/dist/edgar.d.ts +377 -0
  66. package/dist/edgar.d.ts.map +1 -0
  67. package/dist/edgar.js +2418 -0
  68. package/dist/edgar.js.map +1 -0
  69. package/dist/errors.d.ts +102 -0
  70. package/dist/errors.d.ts.map +1 -0
  71. package/dist/errors.js +247 -0
  72. package/dist/errors.js.map +1 -0
  73. package/dist/fac.d.ts +180 -0
  74. package/dist/fac.d.ts.map +1 -0
  75. package/dist/fac.js +416 -0
  76. package/dist/fac.js.map +1 -0
  77. package/dist/far.d.ts +170 -0
  78. package/dist/far.d.ts.map +1 -0
  79. package/dist/far.js +804 -0
  80. package/dist/far.js.map +1 -0
  81. package/dist/fdic.d.ts +599 -0
  82. package/dist/fdic.d.ts.map +1 -0
  83. package/dist/fdic.js +1624 -0
  84. package/dist/fdic.js.map +1 -0
  85. package/dist/federal-register.d.ts +139 -2
  86. package/dist/federal-register.d.ts.map +1 -1
  87. package/dist/federal-register.js +432 -15
  88. package/dist/federal-register.js.map +1 -1
  89. package/dist/fema.d.ts +181 -0
  90. package/dist/fema.d.ts.map +1 -0
  91. package/dist/fema.js +436 -0
  92. package/dist/fema.js.map +1 -0
  93. package/dist/fpds.d.ts +108 -0
  94. package/dist/fpds.d.ts.map +1 -0
  95. package/dist/fpds.js +519 -0
  96. package/dist/fpds.js.map +1 -0
  97. package/dist/gao.d.ts +64 -0
  98. package/dist/gao.d.ts.map +1 -0
  99. package/dist/gao.js +640 -0
  100. package/dist/gao.js.map +1 -0
  101. package/dist/govinfo.d.ts +111 -0
  102. package/dist/govinfo.d.ts.map +1 -0
  103. package/dist/govinfo.js +422 -0
  104. package/dist/govinfo.js.map +1 -0
  105. package/dist/grants.d.ts +27 -4
  106. package/dist/grants.d.ts.map +1 -1
  107. package/dist/grants.js +114 -11
  108. package/dist/grants.js.map +1 -1
  109. package/dist/gsa-csv.d.ts +249 -0
  110. package/dist/gsa-csv.d.ts.map +1 -0
  111. package/dist/gsa-csv.js +784 -0
  112. package/dist/gsa-csv.js.map +1 -0
  113. package/dist/integrity.d.ts +212 -0
  114. package/dist/integrity.d.ts.map +1 -0
  115. package/dist/integrity.js +707 -0
  116. package/dist/integrity.js.map +1 -0
  117. package/dist/meta.d.ts +165 -0
  118. package/dist/meta.d.ts.map +1 -0
  119. package/dist/meta.js +162 -0
  120. package/dist/meta.js.map +1 -0
  121. package/dist/nih.d.ts +117 -0
  122. package/dist/nih.d.ts.map +1 -0
  123. package/dist/nih.js +291 -0
  124. package/dist/nih.js.map +1 -0
  125. package/dist/nppes.d.ts +157 -0
  126. package/dist/nppes.d.ts.map +1 -0
  127. package/dist/nppes.js +648 -0
  128. package/dist/nppes.js.map +1 -0
  129. package/dist/nsf.d.ts +176 -0
  130. package/dist/nsf.d.ts.map +1 -0
  131. package/dist/nsf.js +554 -0
  132. package/dist/nsf.js.map +1 -0
  133. package/dist/nvd.d.ts +176 -0
  134. package/dist/nvd.d.ts.map +1 -0
  135. package/dist/nvd.js +912 -0
  136. package/dist/nvd.js.map +1 -0
  137. package/dist/ofac.d.ts +205 -0
  138. package/dist/ofac.d.ts.map +1 -0
  139. package/dist/ofac.js +919 -0
  140. package/dist/ofac.js.map +1 -0
  141. package/dist/pricing.d.ts +110 -0
  142. package/dist/pricing.d.ts.map +1 -0
  143. package/dist/pricing.js +843 -0
  144. package/dist/pricing.js.map +1 -0
  145. package/dist/sam-gov/client.d.ts +60 -2
  146. package/dist/sam-gov/client.d.ts.map +1 -1
  147. package/dist/sam-gov/client.js +320 -54
  148. package/dist/sam-gov/client.js.map +1 -1
  149. package/dist/sam-gov/index.d.ts +1 -1
  150. package/dist/sam-gov/index.d.ts.map +1 -1
  151. package/dist/sam-gov/index.js +1 -1
  152. package/dist/sam-gov/index.js.map +1 -1
  153. package/dist/sam-gov/types.d.ts +24 -0
  154. package/dist/sam-gov/types.d.ts.map +1 -1
  155. package/dist/sba.d.ts +72 -0
  156. package/dist/sba.d.ts.map +1 -0
  157. package/dist/sba.js +281 -0
  158. package/dist/sba.js.map +1 -0
  159. package/dist/server.d.ts +14 -2
  160. package/dist/server.d.ts.map +1 -1
  161. package/dist/server.js +3897 -295
  162. package/dist/server.js.map +1 -1
  163. package/dist/snapshot.d.ts +98 -0
  164. package/dist/snapshot.d.ts.map +1 -0
  165. package/dist/snapshot.js +146 -0
  166. package/dist/snapshot.js.map +1 -0
  167. package/dist/socrata.d.ts +157 -0
  168. package/dist/socrata.d.ts.map +1 -0
  169. package/dist/socrata.js +448 -0
  170. package/dist/socrata.js.map +1 -0
  171. package/dist/treasury.d.ts +143 -0
  172. package/dist/treasury.d.ts.map +1 -0
  173. package/dist/treasury.js +436 -0
  174. package/dist/treasury.js.map +1 -0
  175. package/dist/usaspending.d.ts +260 -65
  176. package/dist/usaspending.d.ts.map +1 -1
  177. package/dist/usaspending.js +1664 -228
  178. package/dist/usaspending.js.map +1 -1
  179. package/dist/usitc.d.ts +142 -0
  180. package/dist/usitc.d.ts.map +1 -0
  181. package/dist/usitc.js +339 -0
  182. package/dist/usitc.js.map +1 -0
  183. package/package.json +24 -2
  184. package/src/attachments.ts +652 -0
  185. package/src/bls.ts +1943 -0
  186. package/src/cache.ts +73 -0
  187. package/src/census.ts +735 -0
  188. package/src/ckan.ts +495 -0
  189. package/src/clinicaltrials.ts +923 -0
  190. package/src/cms.ts +634 -0
  191. package/src/coerce.ts +47 -0
  192. package/src/datagov-catalog.ts +296 -0
  193. package/src/datagov.ts +907 -0
  194. package/src/datagovKey.ts +68 -0
  195. package/src/datasource.ts +721 -0
  196. package/src/disclosure.ts +61 -0
  197. package/src/ecfr.ts +231 -127
  198. package/src/echo.ts +496 -0
  199. package/src/edgar.ts +3014 -0
  200. package/src/errors.ts +303 -0
  201. package/src/fac.ts +529 -0
  202. package/src/far.ts +1007 -0
  203. package/src/fdic.ts +2052 -0
  204. package/src/federal-register.ts +706 -191
  205. package/src/fema.ts +541 -0
  206. package/src/fpds.ts +620 -0
  207. package/src/gao.ts +744 -0
  208. package/src/govinfo.ts +497 -0
  209. package/src/grants.ts +290 -155
  210. package/src/gsa-csv.ts +992 -0
  211. package/src/integrity.ts +928 -0
  212. package/src/meta.ts +292 -0
  213. package/src/nih.ts +375 -0
  214. package/src/nppes.ts +834 -0
  215. package/src/nsf.ts +706 -0
  216. package/src/nvd.ts +1124 -0
  217. package/src/ofac.ts +1166 -0
  218. package/src/pricing.ts +1075 -0
  219. package/src/sam-gov/client.ts +345 -63
  220. package/src/sam-gov/index.ts +5 -1
  221. package/src/sam-gov/types.ts +22 -0
  222. package/src/sba.ts +357 -0
  223. package/src/server.ts +4559 -327
  224. package/src/snapshot.ts +192 -0
  225. package/src/socrata.ts +532 -0
  226. package/src/treasury.ts +575 -0
  227. package/src/usaspending.ts +2680 -925
  228. package/src/usitc.ts +420 -0
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
+ }