secondforeman-mcp 0.0.0-stage → 1.8.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.
@@ -0,0 +1,2970 @@
1
+ #!/usr/bin/env node
2
+ // ContextGuard CLI & Model Context Protocol (MCP) Server (bin/contextguard.mjs)
3
+ // Built and operated by an AI agent (Google Gemini) with Paul Edward Lewis Jr. human sign-off, guaranteed by Second Foreman LLC.
4
+ //
5
+ // Zero external dependencies. Supports:
6
+ // npx github:oneandroid-max/contextguard-mcp audit [dir] [--max-boot-tokens N] [--json]
7
+ // npx github:oneandroid-max/contextguard-mcp slim [dir] [--write]
8
+ // npx github:oneandroid-max/contextguard-mcp clip <file> [--budget 3000]
9
+ // npx github:oneandroid-max/contextguard-mcp bids [--category web_redesign|ada_pdf|it_software]
10
+ // npx github:oneandroid-max/contextguard-mcp --mcp
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import readline from 'node:readline';
15
+ import zlib from 'node:zlib';
16
+ import {
17
+ auditContextBundle,
18
+ compileSlimArtifacts,
19
+ compressWebDocument,
20
+ } from '../src/core.mjs';
21
+ import { verifyContextGuardLicense } from '../src/licensing.mjs';
22
+
23
+ const TARGET_PATTERNS = [
24
+ 'CLAUDE.md',
25
+ 'AGENTS.md',
26
+ 'GEMINI.md',
27
+ 'START.md',
28
+ '.cursorrules',
29
+ '.windsurfrules',
30
+ '.clinerules',
31
+ 'README.md',
32
+ '.github/copilot-instructions.md',
33
+ 'docs/FAILURES.md',
34
+ 'docs/LESSONS.md',
35
+ ];
36
+
37
+ function collectWorkspaceEntries(rootDir) {
38
+ const absRoot = path.resolve(rootDir || '.');
39
+ const entries = [];
40
+ const seen = new Set();
41
+
42
+ const tryAdd = (relPath) => {
43
+ if (seen.has(relPath)) return;
44
+ const full = path.join(absRoot, relPath);
45
+ if (!fs.existsSync(full)) return;
46
+ const stat = fs.statSync(full);
47
+ if (!stat.isFile() || stat.size > 2_500_000) return;
48
+ seen.add(relPath);
49
+ entries.push({
50
+ path: relPath,
51
+ content: fs.readFileSync(full, 'utf8'),
52
+ bytes: stat.size,
53
+ });
54
+ };
55
+
56
+ for (const rel of TARGET_PATTERNS) tryAdd(rel);
57
+
58
+ const plansDir = path.join(absRoot, 'docs', 'plans');
59
+ if (fs.existsSync(plansDir) && fs.statSync(plansDir).isDirectory()) {
60
+ for (const fn of fs.readdirSync(plansDir)) {
61
+ if (fn.endsWith('.md')) tryAdd(path.posix.join('docs/plans', fn));
62
+ }
63
+ }
64
+
65
+ // Flag lockfiles if not ignored in .claudeignore
66
+ const ignoreFile = path.join(absRoot, '.claudeignore');
67
+ const ignoreText = fs.existsSync(ignoreFile) ? fs.readFileSync(ignoreFile, 'utf8') : '';
68
+ for (const lock of ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock']) {
69
+ if (!ignoreText.includes(lock)) {
70
+ const full = path.join(absRoot, lock);
71
+ if (fs.existsSync(full) && fs.statSync(full).size <= 1_500_000) {
72
+ tryAdd(lock);
73
+ }
74
+ }
75
+ }
76
+
77
+ return entries;
78
+ }
79
+
80
+ async function resolveProStatus() {
81
+ const code = process.env.SECOND_FOREMAN_PRO_KEY || process.env.CONTEXTGUARD_PRO_KEY || '';
82
+ if (!code) return { isPro: false };
83
+ const check = await verifyContextGuardLicense(code);
84
+ return { isPro: Boolean(check.valid), detail: check };
85
+ }
86
+
87
+ function estimateAdaPdfRemediation(args = {}) {
88
+ const tier = ['pop_50k_plus', 'pop_under_50k', 'special_district', 'commercial_508'].includes(args.entityTier)
89
+ ? args.entityTier
90
+ : 'pop_50k_plus';
91
+ const pdfCount = Math.max(1, Math.min(100000, Math.round(Number(args.pdfCount) || 50)));
92
+ const avgPages = Math.max(1, Math.min(2000, Math.round(Number(args.avgPagesPerPdf) || 6)));
93
+ const scannedPct = Math.max(0, Math.min(100, Number(args.scannedSharePct ?? 20)));
94
+ const acroFormCount = Math.max(0, Math.min(10000, Math.round(Number(args.acroFormCount) || 0)));
95
+ const webTemplateCount = Math.max(0, Math.min(500, Math.round(Number(args.webTemplateCount) || 0)));
96
+
97
+ const totalPages = pdfCount * avgPages;
98
+ const scannedPages = Math.round(totalPages * (scannedPct / 100));
99
+ const bornDigitalPages = Math.max(0, totalPages - scannedPages);
100
+ const automatedHybridUsd = Math.round(
101
+ bornDigitalPages * 1.5 + scannedPages * 3.0 + acroFormCount * 45 + webTemplateCount * 350
102
+ );
103
+ const legacyManualLowUsd = Math.round(
104
+ bornDigitalPages * 5.0 + scannedPages * 9.0 + acroFormCount * 120 + webTemplateCount * 850
105
+ );
106
+ const legacyManualHighUsd = Math.round(
107
+ bornDigitalPages * 12.0 + scannedPages * 18.0 + acroFormCount * 240 + webTemplateCount * 1500
108
+ );
109
+ const deadlineLabel =
110
+ tier === 'pop_50k_plus'
111
+ ? 'April 26, 2027 (28 CFR Part 35 Subpart H / 91 FR 20902 — State & Local >= 50,000 pop.; general Title II duties active now)'
112
+ : tier === 'pop_under_50k' || tier === 'special_district'
113
+ ? 'April 26, 2028 (28 CFR Part 35 Subpart H / 91 FR 20902 — Under 50,000 pop. & Special Districts; general Title II duties active now)'
114
+ : 'Immediate (Revised Section 508 / WCAG 2.1 AA Procurement & Vendor Gate)';
115
+
116
+ return {
117
+ entityTier: tier,
118
+ deadlineLabel,
119
+ totalPages,
120
+ bornDigitalPages,
121
+ scannedPages,
122
+ acroFormCount,
123
+ webTemplateCount,
124
+ automatedHybridUsd,
125
+ legacyManualLowUsd,
126
+ legacyManualHighUsd,
127
+ estimatedSavingsUsd: Math.max(0, legacyManualHighUsd - automatedHybridUsd),
128
+ fitsFederalGpc15k: automatedHybridUsd <= 15000,
129
+ fitsOklahomaStatePCard25k: automatedHybridUsd <= 25000,
130
+ freePage1ProofUrl: 'https://secondforeman.com/pdf-remediation/',
131
+ calculatorUrl: 'https://secondforeman.com/bidradar/ada-title-ii-pdf-estimator/',
132
+ exceptionsWorkbenchUrl: 'https://secondforeman.com/bidradar/ada-title-ii-exceptions-undue-burden-worksheet/',
133
+ stateProcurementWorkbenchUrl: 'https://secondforeman.com/bidradar/state-procurement-pdaa-vadsir-scorer/',
134
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
135
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
136
+ };
137
+ }
138
+
139
+ function sanitizeMdInline(val) {
140
+ return String(val ?? '')
141
+ .replace(/[\r\n\t]+/g, ' ')
142
+ .replace(/\|/g, '\\|')
143
+ .trim();
144
+ }
145
+
146
+ function sanitizeCsvCell(val) {
147
+ const raw = String(val ?? '').replace(/[\r\n]+/g, ' ').trim();
148
+ const safe = /^[=+\-@\t\r]/.test(raw) ? `'${raw}` : raw;
149
+ return `"${safe.replace(/"/g, '""')}"`;
150
+ }
151
+
152
+ function triageAda28Cfr35Exceptions(args = {}, { isPro = false } = {}) {
153
+ for (const strKey of ['entityName', 'entityTier', 'contentCategory', 'proKey']) {
154
+ if (args[strKey] !== undefined && typeof args[strKey] !== 'string') {
155
+ throw new Error(`Invalid params: "${strKey}" must be a string.`);
156
+ }
157
+ }
158
+ for (const numKey of ['docCount', 'avgPagesPerDoc', 'scannedSharePct', 'acroFormCount']) {
159
+ if (args[numKey] !== undefined && (typeof args[numKey] !== 'number' || !Number.isFinite(args[numKey]) || args[numKey] < 0)) {
160
+ throw new Error(`Invalid params: "${numKey}" must be a non-negative finite number.`);
161
+ }
162
+ }
163
+ if (args.scannedSharePct !== undefined && args.scannedSharePct > 100) {
164
+ throw new Error('Invalid params: "scannedSharePct" must be between 0 and 100.');
165
+ }
166
+ const boolKeys = [
167
+ 'createdBeforeComplianceDate',
168
+ 'usedForActiveServiceOrProgram',
169
+ 'retainedExclusivelyForReference',
170
+ 'unalteredSinceArchiving',
171
+ 'storedInClearlyIdentifiedArchive',
172
+ 'underContractualOrLicensingArrangement',
173
+ 'individualizedToSpecificPersonOrAccount',
174
+ 'passwordProtectedOrSecured',
175
+ 'evaluate35204UndueBurden',
176
+ 'allProgramResourcesConsidered',
177
+ 'headOfEntityOrDesigneeNamed',
178
+ 'writtenStatementOfReasonsPrepared',
179
+ 'maximumExtentAlternativeActionDefined',
180
+ 'evaluate35205MinimalImpact',
181
+ 'timelinessEquivalent',
182
+ 'privacyEquivalent',
183
+ 'independenceEquivalent',
184
+ 'easeOfUseEquivalent',
185
+ ];
186
+ for (const bKey of boolKeys) {
187
+ if (args[bKey] !== undefined && typeof args[bKey] !== 'boolean') {
188
+ throw new Error(`Invalid params: "${bKey}" must be a boolean.`);
189
+ }
190
+ }
191
+
192
+ const validTiers = ['pop_50k_plus', 'pop_under_50k', 'special_district'];
193
+ const entityTier = args.entityTier ? args.entityTier.trim() : 'pop_50k_plus';
194
+ if (!validTiers.includes(entityTier)) {
195
+ throw new Error(`Invalid params: "entityTier" must be one of ${validTiers.join(', ')}.`);
196
+ }
197
+
198
+ const validCategories = [
199
+ 'archived_web_content',
200
+ 'conventional_doc',
201
+ 'third_party_content',
202
+ 'individualized_secured_doc',
203
+ 'preexisting_social_post',
204
+ 'active_web_or_doc',
205
+ ];
206
+ const contentCategory = args.contentCategory ? args.contentCategory.trim() : 'conventional_doc';
207
+ if (!validCategories.includes(contentCategory)) {
208
+ throw new Error(`Invalid params: "contentCategory" must be one of ${validCategories.join(', ')}.`);
209
+ }
210
+
211
+ const entityName = String(args.entityName || 'Public Entity').replace(/[\r\n\t]+/g, ' ').trim().slice(0, 160) || 'Public Entity';
212
+ const complianceDateLabel =
213
+ entityTier === 'pop_50k_plus'
214
+ ? 'April 26, 2027 (28 CFR § 35.200(b)(1) as amended by 91 FR 20902 — >= 50,000 pop.)'
215
+ : 'April 26, 2028 (28 CFR § 35.200(b)(2) as amended by 91 FR 20902 — < 50,000 pop. & Special Districts)';
216
+
217
+ const createdBeforeComplianceDate = Boolean(args.createdBeforeComplianceDate ?? false);
218
+ const usedForActiveServiceOrProgram = Boolean(args.usedForActiveServiceOrProgram ?? true);
219
+ const retainedExclusivelyForReference = Boolean(args.retainedExclusivelyForReference ?? false);
220
+ const unalteredSinceArchiving = Boolean(args.unalteredSinceArchiving ?? false);
221
+ const storedInClearlyIdentifiedArchive = Boolean(args.storedInClearlyIdentifiedArchive ?? false);
222
+ const underContractualOrLicensingArrangement = Boolean(args.underContractualOrLicensingArrangement ?? true);
223
+ const individualizedToSpecificPersonOrAccount = Boolean(args.individualizedToSpecificPersonOrAccount ?? false);
224
+ const passwordProtectedOrSecured = Boolean(args.passwordProtectedOrSecured ?? false);
225
+
226
+ let qualifiesFor35201Exception = false;
227
+ let matchedExceptionCode = 'NONE';
228
+ let matchedExceptionCitation = 'None — Full WCAG 2.1 Level AA / PDF/UA-1 conformance required under 28 CFR § 35.200';
229
+ const disqualifyingReasons = [];
230
+ const checkRows = [];
231
+
232
+ if (contentCategory === 'archived_web_content') {
233
+ const c1 = createdBeforeComplianceDate;
234
+ const c2 = retainedExclusivelyForReference && !usedForActiveServiceOrProgram;
235
+ const c3 = storedInClearlyIdentifiedArchive;
236
+ const c4 = unalteredSinceArchiving;
237
+ checkRows.push(
238
+ { rule: '28 CFR § 35.104(1) Pre-Compliance Creation / Physical Reproduction', status: c1 ? 'MET' : 'FAILED', detail: c1 ? 'Created before Subpart H compliance date (or reproduces pre-compliance physical media).' : 'Content created on or after compliance date fails § 35.104(1).' },
239
+ { rule: '28 CFR § 35.104(2) Retained Exclusively for Reference/Research/Recordkeeping', status: c2 ? 'MET' : 'FAILED', detail: c2 ? 'Not used to apply for, access, or participate in active public programs.' : 'Active program/service documents never qualify as archived web content even if placed in /archive/.' },
240
+ { rule: '28 CFR § 35.104(3) Stored in Dedicated, Clearly Identified Archive Area', status: c3 ? 'MET' : 'FAILED', detail: c3 ? 'Kept in a special area clearly labeled as archived content.' : 'Mixed into live navigation/pages without dedicated archive segregation.' },
241
+ { rule: '28 CFR § 35.104(4) Unaltered & Unupdated Since Archiving', status: c4 ? 'MET' : 'FAILED', detail: c4 ? 'Zero edits since archiving.' : 'Post-archive edits forfeit the § 35.201(a) archived web content exception.' }
242
+ );
243
+ if (!c1) disqualifyingReasons.push('Fails § 35.104(1): not created before applicable Subpart H compliance date.');
244
+ if (!c2) disqualifyingReasons.push('Fails § 35.104(2): used for an active service/program or not retained solely for reference/research/recordkeeping.');
245
+ if (!c3) disqualifyingReasons.push('Fails § 35.104(3): not stored in a dedicated, clearly identified archive area.');
246
+ if (!c4) disqualifyingReasons.push('Fails § 35.104(4): altered or updated after archiving.');
247
+ if (c1 && c2 && c3 && c4) {
248
+ qualifiesFor35201Exception = true;
249
+ matchedExceptionCode = '28_CFR_35_201_A_ARCHIVED_WEB_CONTENT';
250
+ matchedExceptionCitation = '28 CFR § 35.201(a) & § 35.104 — Archived Web Content (all 4 statutory conditions met)';
251
+ }
252
+ } else if (contentCategory === 'conventional_doc') {
253
+ const c1 = createdBeforeComplianceDate;
254
+ const c2 = !usedForActiveServiceOrProgram;
255
+ checkRows.push(
256
+ { rule: '28 CFR § 35.201(b) Preexisting Conventional Electronic Document (PDF/Word/Excel/PPT)', status: c1 ? 'MET' : 'FAILED', detail: c1 ? 'Available on web/mobile before Subpart H compliance date.' : 'Posted on or after compliance date — must meet WCAG 2.1 AA.' },
257
+ { rule: '28 CFR § 35.201(b) Active Program / Service Carve-Out', status: c2 ? 'MET' : 'FAILED', detail: c2 ? 'Not currently used to apply for, gain access to, or participate in any public program/service.' : 'Currently used to apply for, access, or participate in services/programs — exception barred.' }
258
+ );
259
+ if (!c1) disqualifyingReasons.push('Fails § 35.201(b): document was not posted prior to the Subpart H compliance date.');
260
+ if (!c2) disqualifyingReasons.push('Fails § 35.201(b): document is currently used to apply for, gain access to, or participate in public services/programs.');
261
+ if (c1 && c2) {
262
+ qualifiesFor35201Exception = true;
263
+ matchedExceptionCode = '28_CFR_35_201_B_PREEXISTING_CONVENTIONAL_DOC';
264
+ matchedExceptionCitation = '28 CFR § 35.201(b) — Preexisting Conventional Electronic Documents';
265
+ }
266
+ } else if (contentCategory === 'third_party_content') {
267
+ const c1 = !underContractualOrLicensingArrangement;
268
+ checkRows.push({
269
+ rule: '28 CFR § 35.201(c) Independent Third-Party Posting (No Contract/License)',
270
+ status: c1 ? 'MET' : 'FAILED',
271
+ detail: c1 ? 'Posted independently by an external third party without contractual, licensing, or other arrangement.' : 'Vendor/contractor/SaaS content posted under contract or license is NOT exempt under § 35.201(c).',
272
+ });
273
+ if (!c1) disqualifyingReasons.push('Fails § 35.201(c): content posted under a contractual, licensing, or vendor arrangement with the public entity is never exempt.');
274
+ if (c1) {
275
+ qualifiesFor35201Exception = true;
276
+ matchedExceptionCode = '28_CFR_35_201_C_THIRD_PARTY_CONTENT';
277
+ matchedExceptionCitation = '28 CFR § 35.201(c) — Content Posted by an Independent Third Party';
278
+ }
279
+ } else if (contentCategory === 'individualized_secured_doc') {
280
+ const c1 = individualizedToSpecificPersonOrAccount;
281
+ const c2 = passwordProtectedOrSecured;
282
+ checkRows.push(
283
+ { rule: '28 CFR § 35.201(d) Individualized to Specific Person, Property, or Account', status: c1 ? 'MET' : 'FAILED', detail: c1 ? 'Conventional document pertains to a specific individual, property, or account (e.g., utility bill, tax notice).' : 'General-audience or blank form PDF is not individualized.' },
284
+ { rule: '28 CFR § 35.201(d) Password-Protected or Otherwise Secured', status: c2 ? 'MET' : 'FAILED', detail: c2 ? 'Delivered behind authenticated/password-protected portal.' : 'Publicly downloadable URL fails § 35.201(d) security requirement.' }
285
+ );
286
+ if (!c1) disqualifyingReasons.push('Fails § 35.201(d): document is not individualized to a specific person, property, or account.');
287
+ if (!c2) disqualifyingReasons.push('Fails § 35.201(d): document is not password-protected or otherwise secured.');
288
+ if (c1 && c2) {
289
+ qualifiesFor35201Exception = true;
290
+ matchedExceptionCode = '28_CFR_35_201_D_INDIVIDUALIZED_SECURED_DOC';
291
+ matchedExceptionCitation = '28 CFR § 35.201(d) — Individualized, Password-Protected Conventional Electronic Documents';
292
+ }
293
+ } else if (contentCategory === 'preexisting_social_post') {
294
+ const c1 = createdBeforeComplianceDate;
295
+ checkRows.push({
296
+ rule: '28 CFR § 35.201(e) Preexisting Social Media Post',
297
+ status: c1 ? 'MET' : 'FAILED',
298
+ detail: c1 ? 'Social media post published prior to Subpart H compliance date.' : 'Social media posts published on or after compliance date require captions/alt text.',
299
+ });
300
+ if (!c1) disqualifyingReasons.push('Fails § 35.201(e): social media post was published on or after the Subpart H compliance date.');
301
+ if (c1) {
302
+ qualifiesFor35201Exception = true;
303
+ matchedExceptionCode = '28_CFR_35_201_E_PREEXISTING_SOCIAL_POST';
304
+ matchedExceptionCitation = '28 CFR § 35.201(e) — Preexisting Social Media Posts';
305
+ }
306
+ } else {
307
+ checkRows.push({
308
+ rule: '28 CFR § 35.200 Active Web Content & Public Program Documents',
309
+ status: 'FAILED',
310
+ detail: 'Active web pages, online forms, and current program PDFs require full WCAG 2.1 Level AA conformance.',
311
+ });
312
+ disqualifyingReasons.push('Active web content and active public-service documents are outside 28 CFR § 35.201(a)–(e) exceptions.');
313
+ }
314
+
315
+ const evaluate35204UndueBurden = Boolean(args.evaluate35204UndueBurden ?? false);
316
+ const allProgramResourcesConsidered = Boolean(args.allProgramResourcesConsidered ?? false);
317
+ const headOfEntityOrDesigneeNamed = Boolean(args.headOfEntityOrDesigneeNamed ?? false);
318
+ const writtenStatementOfReasonsPrepared = Boolean(args.writtenStatementOfReasonsPrepared ?? false);
319
+ const maximumExtentAlternativeActionDefined = Boolean(args.maximumExtentAlternativeActionDefined ?? false);
320
+ const undueBurden35204ProceduralComplete =
321
+ evaluate35204UndueBurden &&
322
+ allProgramResourcesConsidered &&
323
+ headOfEntityOrDesigneeNamed &&
324
+ writtenStatementOfReasonsPrepared &&
325
+ maximumExtentAlternativeActionDefined;
326
+
327
+ if (evaluate35204UndueBurden) {
328
+ checkRows.push(
329
+ { rule: '28 CFR § 35.204 All Program/Service Funding & Operational Resources Considered', status: allProgramResourcesConsidered ? 'MET' : 'FAILED', detail: allProgramResourcesConsidered ? 'Evaluated against all resources available to fund and operate the program/service (not just IT discretionary line).' : 'Must evaluate all resources available to the service, program, or activity — not an isolated IT budget.' },
330
+ { rule: '28 CFR § 35.204 Determination by Head of Public Entity or Designee', status: headOfEntityOrDesigneeNamed ? 'MET' : 'FAILED', detail: headOfEntityOrDesigneeNamed ? 'Authorized head of public entity or formal designee identified.' : 'Missing authorized head-of-entity or designee decision-maker.' },
331
+ { rule: '28 CFR § 35.204 Formal Written Statement of Reasons Prepared', status: writtenStatementOfReasonsPrepared ? 'MET' : 'FAILED', detail: writtenStatementOfReasonsPrepared ? 'Written statement of factual/financial reasons drafted for record.' : '§ 35.204 requires a written statement of the reasons for reaching the conclusion.' },
332
+ { rule: '28 CFR § 35.204 Maximum-Extent Alternative Accessibility Action Defined', status: maximumExtentAlternativeActionDefined ? 'MET' : 'FAILED', detail: maximumExtentAlternativeActionDefined ? 'Alternative action ensuring disability access to maximum non-burdensome extent documented.' : 'Must document alternative action providing program benefits to the maximum extent possible.' }
333
+ );
334
+ }
335
+
336
+ const evaluate35205MinimalImpact = Boolean(args.evaluate35205MinimalImpact ?? false);
337
+ const timelinessEquivalent = Boolean(args.timelinessEquivalent ?? false);
338
+ const privacyEquivalent = Boolean(args.privacyEquivalent ?? false);
339
+ const independenceEquivalent = Boolean(args.independenceEquivalent ?? false);
340
+ const easeOfUseEquivalent = Boolean(args.easeOfUseEquivalent ?? false);
341
+ const minimalImpact35205AllFourMet =
342
+ evaluate35205MinimalImpact &&
343
+ timelinessEquivalent &&
344
+ privacyEquivalent &&
345
+ independenceEquivalent &&
346
+ easeOfUseEquivalent;
347
+
348
+ if (evaluate35205MinimalImpact) {
349
+ checkRows.push({
350
+ rule: '28 CFR § 35.205 Minimal-Impact 4-Factor Equivalence (Timeliness, Privacy, Independence, Ease of Use)',
351
+ status: minimalImpact35205AllFourMet ? 'MET' : 'FAILED',
352
+ detail: `Timeliness: ${timelinessEquivalent ? 'Yes' : 'No'}, Privacy: ${privacyEquivalent ? 'Yes' : 'No'}, Independence: ${independenceEquivalent ? 'Yes' : 'No'}, Ease of Use: ${easeOfUseEquivalent ? 'Yes' : 'No'}.`,
353
+ });
354
+ }
355
+
356
+ const docCount = Math.max(0, Math.min(100000, Math.round(Number(args.docCount ?? 25))));
357
+ const avgPagesPerDoc = Math.max(1, Math.min(2000, Math.round(Number(args.avgPagesPerDoc ?? 5))));
358
+ const scannedSharePct = Math.max(0, Math.min(100, Number(args.scannedSharePct ?? 20)));
359
+ const acroFormCount = Math.max(0, Math.min(docCount, Math.round(Number(args.acroFormCount ?? 0))));
360
+
361
+ const exemptQualifyingDocs = qualifiesFor35201Exception ? docCount : 0;
362
+ const mustRemediateNowDocs = docCount - exemptQualifyingDocs;
363
+ const mustRemediatePages = mustRemediateNowDocs * avgPagesPerDoc;
364
+ const scannedPages = Math.round(mustRemediatePages * (scannedSharePct / 100));
365
+ const bornDigitalPages = Math.max(0, mustRemediatePages - scannedPages);
366
+ const activeFormDocs = qualifiesFor35201Exception ? 0 : acroFormCount;
367
+ const estimatedRemediationUsd =
368
+ mustRemediateNowDocs === 0
369
+ ? 0
370
+ : Math.max(25, Math.round((bornDigitalPages * 1.5 + scannedPages * 3.0 + activeFormDocs * 40) * 100) / 100);
371
+
372
+ const scopeDisclaimer =
373
+ 'Operational technical triage worksheet — Not legal advice. Determinations under 28 CFR §§ 35.201, 35.204, and 35.205 require review by the public entity’s legal counsel, and any § 35.204 undue burden or fundamental alteration determination requires a formal written statement by the head of the public entity or their designee.';
374
+ const individualRequestDutyNote =
375
+ 'Even when a 28 CFR § 35.201(a)–(e) Subpart H exception applies, 28 CFR § 35.160 (Effective Communication) and § 35.130 still require providing an accessible format promptly and free of charge upon an individual request.';
376
+
377
+ const mdHeader = [
378
+ `# DOJ ADA Title II (28 CFR Part 35 Subpart H / 91 FR 20902) — Operational Exceptions & § 35.204 Triage Record Draft`,
379
+ `- **Public Entity:** ${sanitizeMdInline(entityName)}`,
380
+ `- **Subpart H Compliance Tier:** ${complianceDateLabel}`,
381
+ `- **Content Category Evaluated:** \`${contentCategory}\` (${docCount} document(s), ~${avgPagesPerDoc} pages/doc)`,
382
+ `- **28 CFR § 35.201 Exception Result:** **${qualifiesFor35201Exception ? `QUALIFIES (${matchedExceptionCode})` : 'DOES NOT QUALIFY — REMEDIATE TO WCAG 2.1 AA / PDF/UA-1'}**`,
383
+ `- **Active Remediation Scope:** ${mustRemediateNowDocs} document(s) (${mustRemediatePages} pages; Est. Second Foreman PDF/UA-1 remediation: $${estimatedRemediationUsd})`,
384
+ `- **28 CFR § 35.204 Undue Burden Procedural Check:** ${evaluate35204UndueBurden ? (undueBurden35204ProceduralComplete ? 'All 4 procedural elements documented (counsel & head-of-entity sign-off required)' : 'INCOMPLETE — missing mandatory § 35.204 procedural elements') : 'Not invoked'}`,
385
+ `- **28 CFR § 35.205 Minimal-Impact 4-Factor Check:** ${evaluate35205MinimalImpact ? (minimalImpact35205AllFourMet ? 'All 4 equivalence factors marked met' : 'DOES NOT MEET all 4 equivalence factors') : 'Not invoked'}`,
386
+ `- **Effective Communication Reminder:** ${individualRequestDutyNote}`,
387
+ `- **Scope & Non-Legal-Advice Notice:** ${scopeDisclaimer}`,
388
+ ``,
389
+ `## Statutory Condition Matrix`,
390
+ `| Regulatory Requirement | Automated Triage Status | Operational Observation |`,
391
+ `| :--- | :--- | :--- |`,
392
+ ];
393
+ const fmtCheckRows = (rows) =>
394
+ rows.map((r) => `| ${sanitizeMdInline(r.rule)} | **${r.status}** | ${sanitizeMdInline(r.detail)} |`);
395
+
396
+ const previewWorksheetMarkdown = [
397
+ ...mdHeader,
398
+ ...fmtCheckRows(checkRows.slice(0, 2)),
399
+ `| ... *(Full 28 CFR §§ 35.201 / 35.204 Head-of-Entity Written Statement Draft & § 35.205 Matrix)* | *Pro Unlock* | *Unlock downloadable .md record & .csv inventory log with Second Foreman Pro ($29/mo or $149/yr).* |`,
400
+ ].join('\n');
401
+
402
+ const fullWorksheetMarkdown = isPro
403
+ ? [
404
+ ...mdHeader,
405
+ ...fmtCheckRows(checkRows),
406
+ ``,
407
+ `## Draft 28 CFR § 35.204 Head-of-Entity / Designee Written Statement Structure (For Legal Counsel Review)`,
408
+ `1. **Service, Program, or Activity:** [Insert department/program name at ${sanitizeMdInline(entityName)}]`,
409
+ `2. **All Available Program Resources Considered (§ 35.204):** [${allProgramResourcesConsidered ? 'Documented' : 'REQUIRED — insert total program funding & operational resources evaluated'}]`,
410
+ `3. **Factual Reasons Fundamental Alteration or Undue Financial/Administrative Burden Would Result:** [Insert specific technical/financial basis reviewed with counsel]`,
411
+ `4. **Maximum-Extent Accessible Alternative Action (§ 35.204 & § 35.160):** [Insert immediate accessible-format fulfillment workflow, contact email/phone, and turnaround SLA]`,
412
+ `5. **Authorized Decision-Maker (Head of Public Entity or Designee):** [Name & Title — Natural-Person Signature & Date Required]`,
413
+ ].join('\n')
414
+ : null;
415
+
416
+ const fullTriageCsv = isPro
417
+ ? [
418
+ 'entity_name,entity_tier,compliance_date,content_category,qualifies_35_201,matched_exception_code,doc_count,exempt_docs,must_remediate_docs,estimated_remediation_usd,undue_burden_35_204_procedural_complete,minimal_impact_35_205_all_four_met',
419
+ [
420
+ sanitizeCsvCell(entityName),
421
+ sanitizeCsvCell(entityTier),
422
+ sanitizeCsvCell(complianceDateLabel),
423
+ sanitizeCsvCell(contentCategory),
424
+ sanitizeCsvCell(qualifiesFor35201Exception),
425
+ sanitizeCsvCell(matchedExceptionCode),
426
+ sanitizeCsvCell(docCount),
427
+ sanitizeCsvCell(exemptQualifyingDocs),
428
+ sanitizeCsvCell(mustRemediateNowDocs),
429
+ sanitizeCsvCell(estimatedRemediationUsd),
430
+ sanitizeCsvCell(undueBurden35204ProceduralComplete),
431
+ sanitizeCsvCell(minimalImpact35205AllFourMet),
432
+ ].join(','),
433
+ ].join('\n')
434
+ : null;
435
+
436
+ return {
437
+ entityName,
438
+ entityTier,
439
+ complianceDateLabel,
440
+ contentCategory,
441
+ isPro,
442
+ qualifiesFor35201Exception,
443
+ matchedExceptionCode,
444
+ matchedExceptionCitation,
445
+ disqualifyingReasons,
446
+ docCount,
447
+ avgPagesPerDoc,
448
+ exemptQualifyingDocs,
449
+ mustRemediateNowDocs,
450
+ mustRemediatePages,
451
+ estimatedRemediationUsd,
452
+ fitsFederalGpc15k: estimatedRemediationUsd <= 15000,
453
+ fitsOklahomaStatePCard25k: estimatedRemediationUsd <= 25000,
454
+ evaluate35204UndueBurden,
455
+ undueBurden35204ProceduralComplete,
456
+ evaluate35205MinimalImpact,
457
+ minimalImpact35205AllFourMet,
458
+ checks: isPro ? checkRows : checkRows.slice(0, 2),
459
+ individualRequestDutyNote,
460
+ scopeDisclaimer,
461
+ previewWorksheetMarkdown,
462
+ fullWorksheetMarkdown,
463
+ fullTriageCsv,
464
+ workbenchUrl: 'https://secondforeman.com/bidradar/ada-title-ii-exceptions-undue-burden-worksheet/',
465
+ estimatorUrl: 'https://secondforeman.com/bidradar/ada-title-ii-pdf-estimator/',
466
+ freePage1ProofUrl: 'https://secondforeman.com/pdf-remediation/',
467
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
468
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
469
+ };
470
+ }
471
+
472
+ function scoreStateProcurementPdaa(args = {}, { isPro = false } = {}) {
473
+ const validStates = ['TX_DIR', 'WA_USER_01', 'VA_HB2541', 'CO_HB21_1110', 'MULTI_STATE'];
474
+ if (typeof args.targetState !== 'string' || !validStates.includes(args.targetState)) {
475
+ throw new Error(`Invalid params: "targetState" must be one of ${validStates.join(', ')}.`);
476
+ }
477
+ const validWcag = ['wcag22_aa', 'wcag21_aa', 'untested'];
478
+ if (
479
+ args.wcagTargetTested !== undefined &&
480
+ (typeof args.wcagTargetTested !== 'string' || !validWcag.includes(args.wcagTargetTested))
481
+ ) {
482
+ throw new Error(`Invalid params: "wcagTargetTested" must be one of ${validWcag.join(', ')}.`);
483
+ }
484
+ if (args.vendorName !== undefined && typeof args.vendorName !== 'string') {
485
+ throw new Error('Invalid params: "vendorName" must be a string.');
486
+ }
487
+ if (args.proKey !== undefined && typeof args.proKey !== 'string') {
488
+ throw new Error('Invalid params: "proKey" must be a string.');
489
+ }
490
+ for (const pk of [
491
+ 'pdaaPolicy',
492
+ 'pdaaOrgStructure',
493
+ 'pdaaSdlcIntegration',
494
+ 'pdaaCorrectiveProcess',
495
+ 'pdaaStaffSkills',
496
+ 'pdaaPublicInfo',
497
+ ]) {
498
+ if (
499
+ args[pk] !== undefined &&
500
+ (typeof args[pk] !== 'number' || !Number.isFinite(args[pk]) || args[pk] < 0 || args[pk] > 3)
501
+ ) {
502
+ throw new Error(`Invalid params: "${pk}" must be a number between 0 and 3.`);
503
+ }
504
+ }
505
+ for (const nk of ['contractValueUsd', 'untaggedPdfCount', 'avgPagesPerPdf']) {
506
+ if (args[nk] !== undefined && (typeof args[nk] !== 'number' || !Number.isFinite(args[nk]) || args[nk] < 0)) {
507
+ throw new Error(`Invalid params: "${nk}" must be a non-negative finite number.`);
508
+ }
509
+ }
510
+ for (const bk of [
511
+ 'includesDevServices',
512
+ 'includesCotsOrSaas',
513
+ 'hasVpat25',
514
+ 'vadsirPrepared',
515
+ 'thirdPartyTestingPlanned',
516
+ ]) {
517
+ if (args[bk] !== undefined && typeof args[bk] !== 'boolean') {
518
+ throw new Error(`Invalid params: "${bk}" must be a boolean.`);
519
+ }
520
+ }
521
+
522
+ const targetState = args.targetState;
523
+ const vendorName =
524
+ String(args.vendorName || 'Vendor Organization')
525
+ .replace(/[\r\n\t]+/g, ' ')
526
+ .trim()
527
+ .slice(0, 120) || 'Vendor Organization';
528
+
529
+ const clampStep = (v, fallback = 1) => Math.max(0, Math.min(3, Math.round(Number(v ?? fallback))));
530
+ const pdaaPolicy = clampStep(args.pdaaPolicy, 1);
531
+ const pdaaOrgStructure = clampStep(args.pdaaOrgStructure, 1);
532
+ const pdaaSdlcIntegration = clampStep(args.pdaaSdlcIntegration, 1);
533
+ const pdaaCorrectiveProcess = clampStep(args.pdaaCorrectiveProcess, 1);
534
+ const pdaaStaffSkills = clampStep(args.pdaaStaffSkills, 1);
535
+ const pdaaPublicInfo = clampStep(args.pdaaPublicInfo, 1);
536
+
537
+ const contractValueUsd = Math.max(0, Math.min(500000000, Math.round(Number(args.contractValueUsd ?? 150000) || 0)));
538
+ const includesDevServices = Boolean(args.includesDevServices ?? true);
539
+ const includesCotsOrSaas = Boolean(args.includesCotsOrSaas ?? true);
540
+ const hasVpat25 = Boolean(args.hasVpat25 ?? false);
541
+ const vadsirPrepared = Boolean(args.vadsirPrepared ?? false);
542
+ const thirdPartyTestingPlanned = Boolean(args.thirdPartyTestingPlanned ?? false);
543
+ const wcagTargetTested = args.wcagTargetTested || 'wcag21_aa';
544
+
545
+ const untaggedPdfCount = Math.max(0, Math.min(250000, Math.round(Number(args.untaggedPdfCount ?? 0) || 0)));
546
+ const avgPagesPerPdf = Math.max(1, Math.min(2000, Number(args.avgPagesPerPdf ?? 5) || 1));
547
+ const totalPdfPages = Math.round(untaggedPdfCount * avgPagesPerPdf);
548
+ const estimatedPdfRemediationUsd = untaggedPdfCount === 0 ? 0 : Math.max(25, Math.round(totalPdfPages * 1.5));
549
+
550
+ const regimeMeta = {
551
+ TX_DIR: {
552
+ short: 'Texas DIR (1 TAC Ch. 206 & 213)',
553
+ citation: 'Texas Gov’t Code Ch. 2054 Subch. M & 1 TAC Chapters 206 & 213 (DIR PDAA + VADSIR + VPAT)',
554
+ wcag22Required: false,
555
+ },
556
+ WA_USER_01: {
557
+ short: 'Washington WaTech USER-01 (WCAG 2.2 AA)',
558
+ citation: 'Washington WaTech Policy USER-01 & Standard USER-01-01-S (WCAG 2.2 Level AA effective July 1, 2026)',
559
+ wcag22Required: true,
560
+ },
561
+ VA_HB2541: {
562
+ short: 'Virginia IT Access Act (HB2541)',
563
+ citation: 'Virginia Information Technology Access Act (Va. Code §§ 2.2-3500 et seq., as amended by 2025 HB2541 Ch. 571)',
564
+ wcag22Required: false,
565
+ },
566
+ CO_HB21_1110: {
567
+ short: 'Colorado HB21-1110 & 8 CCR 1501-11',
568
+ citation: 'Colorado HB21-1110 (C.R.S. § 24-85-101 et seq.) & OIT 8 CCR 1501-11 Digital Accessibility Rules',
569
+ wcag22Required: false,
570
+ },
571
+ MULTI_STATE: {
572
+ short: 'Multi-State (TX + WA + VA + CO)',
573
+ citation: 'Multi-State ICT Procurement Baseline (TX 1 TAC 213 PDAA/VADSIR, WA USER-01 WCAG 2.2 AA, VA HB2541, CO 8 CCR 1501-11)',
574
+ wcag22Required: true,
575
+ },
576
+ }[targetState];
577
+
578
+ const pdaaRawPoints =
579
+ pdaaPolicy + pdaaOrgStructure + pdaaSdlcIntegration + pdaaCorrectiveProcess + pdaaStaffSkills + pdaaPublicInfo;
580
+ const pdaaScore100 = Math.round((pdaaRawPoints / 18) * 100);
581
+ const zeroCriteriaCount = [
582
+ pdaaPolicy,
583
+ pdaaOrgStructure,
584
+ pdaaSdlcIntegration,
585
+ pdaaCorrectiveProcess,
586
+ pdaaStaffSkills,
587
+ pdaaPublicInfo,
588
+ ].filter((x) => x === 0).length;
589
+
590
+ let maturityStage = 'STAGE_1_LAUNCH';
591
+ let maturityStageLabel = 'Stage 1 — Launch';
592
+ if (pdaaRawPoints === 0 || zeroCriteriaCount >= 3) {
593
+ maturityStage = 'NON_RESPONSIVE_RISK';
594
+ maturityStageLabel = 'Unscored / Non-Responsive Risk';
595
+ } else if (pdaaScore100 >= 83) {
596
+ maturityStage = 'STAGE_3_OPTIMIZE';
597
+ maturityStageLabel = 'Stage 3 — Optimize';
598
+ } else if (pdaaScore100 >= 50) {
599
+ maturityStage = 'STAGE_2_INTEGRATE';
600
+ maturityStageLabel = 'Stage 2 — Integrate';
601
+ }
602
+
603
+ const txInScope = targetState === 'TX_DIR' || targetState === 'MULTI_STATE';
604
+ const vadsirRequired = includesDevServices && txInScope;
605
+ const thirdPartyTestingRequiredTx500k = txInScope && contractValueUsd > 500000;
606
+ const wcag22RequiredByState = regimeMeta.wcag22Required;
607
+ const wcag22GapWarning =
608
+ (wcag22RequiredByState && wcagTargetTested !== 'wcag22_aa') || wcagTargetTested === 'untested';
609
+
610
+ const blockingGaps = [];
611
+ if (txInScope && pdaaRawPoints === 0) {
612
+ blockingGaps.push('Texas DIR RFO Attachment C (PDAA) is 0/18 — leaving PDAA blank risks non-responsive disqualification.');
613
+ } else if (zeroCriteriaCount > 0) {
614
+ blockingGaps.push(`${zeroCriteriaCount} of 6 PDAA criteria are scored 0 (Missing).`);
615
+ }
616
+ if (includesCotsOrSaas && !hasVpat25) {
617
+ blockingGaps.push('COTS/SaaS product in scope lacks a current ITI VPAT 2.4+ / 2.5 ACR.');
618
+ }
619
+ if (vadsirRequired && !vadsirPrepared) {
620
+ blockingGaps.push('Web/mobile/UI development services in Texas DIR scope require a 6-section VADSIR (Attachment E).');
621
+ }
622
+ if (thirdPartyTestingRequiredTx500k && !thirdPartyTestingPlanned) {
623
+ blockingGaps.push('Texas EIR procurement > $500,000 requires documented accessibility test criteria AND third-party accessibility testing (1 TAC Ch. 213).');
624
+ }
625
+ if (wcagTargetTested === 'untested') {
626
+ blockingGaps.push('Deliverables have no WCAG 2.1 AA / 2.2 AA conformance testing baseline.');
627
+ } else if (wcag22RequiredByState && wcagTargetTested !== 'wcag22_aa') {
628
+ blockingGaps.push('Washington WaTech USER-01-01-S requires WCAG 2.2 Level AA (effective July 1, 2026).');
629
+ }
630
+ if (untaggedPdfCount > 0) {
631
+ blockingGaps.push(`${untaggedPdfCount} untagged PDF(s) (~${totalPdfPages} pages) require ISO 14289-1 (PDF/UA-1) remediation.`);
632
+ }
633
+
634
+ const bidResponsiveReady = blockingGaps.length === 0;
635
+ const submittals = ['PDAA Self-Assessment'];
636
+ if (vadsirRequired || includesDevServices) submittals.push('6-Section VADSIR');
637
+ if (includesCotsOrSaas) submittals.push('VPAT 2.5 ACR');
638
+ if (thirdPartyTestingRequiredTx500k) submittals.push('3rd-Party EIR Test Plan');
639
+ if (targetState === 'VA_HB2541' || targetState === 'CO_HB21_1110' || targetState === 'WA_USER_01' || targetState === 'MULTI_STATE') {
640
+ submittals.push('Remediation Roadmap');
641
+ }
642
+ const requiredSubmittalsLabel = submittals.join(' + ');
643
+
644
+ const stepName = (n) => (n === 3 ? '3 - Optimize' : n === 2 ? '2 - Integrate' : n === 1 ? '1 - Launch' : '0 - Missing');
645
+ const checkRows = [
646
+ { gate: 'PDAA Criterion 1 — ICT Accessibility Policy', status: stepName(pdaaPolicy), detail: pdaaPolicy >= 2 ? 'Formal policy adopted' : 'Adopt written ICT accessibility policy' },
647
+ { gate: 'PDAA Criterion 2 — Governance & Accountability', status: stepName(pdaaOrgStructure), detail: pdaaOrgStructure >= 2 ? 'Coordinator & release gate assigned' : 'Assign accessibility release-gate owner' },
648
+ { gate: 'PDAA Criterion 3 — SDLC & Procurement Integration', status: stepName(pdaaSdlcIntegration), detail: pdaaSdlcIntegration >= 2 ? 'Design + CI + QA gates active' : 'Embed axe-core + veraPDF PDF/UA-1 CI checks' },
649
+ { gate: 'PDAA Criterion 4 — Corrective Action & Alternate Access', status: stepName(pdaaCorrectiveProcess), detail: pdaaCorrectiveProcess >= 2 ? 'Defect SLAs & alternate access defined' : 'Document defect remediation SLAs & alternate access' },
650
+ { gate: 'PDAA Criterion 5 — Staff Accessibility Skills & Training', status: stepName(pdaaStaffSkills), detail: pdaaStaffSkills >= 2 ? 'Role-based training active' : 'Document developer/QA accessibility training' },
651
+ { gate: 'PDAA Criterion 6 — Customer-Facing Policy & ACRs', status: stepName(pdaaPublicInfo), detail: pdaaPublicInfo >= 2 ? 'Public statement & ACR channel live' : 'Publish accessibility statement & ACR contact' },
652
+ { gate: 'COTS / SaaS Product VPAT 2.4+ / 2.5 ACR Gate', status: !includesCotsOrSaas ? 'N/A' : hasVpat25 ? 'MET' : 'BLOCKING GAP', detail: !includesCotsOrSaas ? 'No COTS/SaaS in scope' : hasVpat25 ? 'VPAT 2.5 ACR ready' : 'Complete VPAT 2.5 ACR' },
653
+ { gate: 'Development Services VADSIR (6 Sections)', status: !includesDevServices ? 'N/A' : vadsirPrepared ? 'MET' : vadsirRequired ? 'BLOCKING GAP' : 'RECOMMENDED', detail: !includesDevServices ? 'No dev services in scope' : vadsirPrepared ? '6-section VADSIR prepared' : 'Prepare 6-section VADSIR narrative' },
654
+ { gate: 'Texas EIR > $500,000 Third-Party Testing Gate (1 TAC Ch. 213)', status: !thirdPartyTestingRequiredTx500k ? 'N/A' : thirdPartyTestingPlanned ? 'MET' : 'BLOCKING GAP', detail: !thirdPartyTestingRequiredTx500k ? '<= $500k or non-TX scope' : thirdPartyTestingPlanned ? '3rd-party EIR test planned' : 'Budget independent third-party EIR testing' },
655
+ { gate: `WCAG Conformance (${wcag22RequiredByState ? 'WCAG 2.2 AA Required' : 'WCAG 2.1/2.2 AA'})`, status: wcag22GapWarning ? 'GAP' : 'MET', detail: wcagTargetTested === 'wcag22_aa' ? 'WCAG 2.2 AA verified' : 'Upgrade testing matrix to WCAG 2.2 AA' },
656
+ ];
657
+
658
+ const scopeDisclaimer =
659
+ 'Operational Vendor Bid-Readiness & Self-Assessment Draft ONLY — Not legal advice, not an official state-issued form, not a signed VPAT/ACR, and not third-party human assistive-technology testing.';
660
+
661
+ const fmtMd = (rows) => rows.map((r) => `| ${r.gate} | **${r.status}** | ${sanitizeMdInline(r.detail)} |`);
662
+ const mdHeader = [
663
+ `# State IT Procurement Accessibility Packet — ${sanitizeMdInline(vendorName)}`,
664
+ `- **Target Procurement Regime:** ${regimeMeta.citation}`,
665
+ `- **Estimated Contract Value:** $${contractValueUsd.toLocaleString()} USD`,
666
+ `- **PDAA Organizational Maturity Score:** **${pdaaScore100}/100** (${pdaaRawPoints}/18 raw points · ${maturityStageLabel})`,
667
+ `- **Bid-Gate Readiness:** ${bidResponsiveReady ? 'PASS' : `ACTION REQUIRED (${blockingGaps.length} Gap(s))`}`,
668
+ `- **Required Bid Attachments:** ${requiredSubmittalsLabel}`,
669
+ `- **Notice:** ${scopeDisclaimer}`,
670
+ ``,
671
+ `| Evaluation Criterion / Bid Gate | Status | Vendor Action / Evidence |`,
672
+ `| --- | --- | --- |`,
673
+ ];
674
+
675
+ const previewPacketMarkdown = [
676
+ ...mdHeader,
677
+ ...fmtMd(checkRows.slice(0, 3)),
678
+ `| ... *(Full 10-Row PDAA & State Bid-Gate Matrix + 6-Section VADSIR Template + State Roadmap)* | *Pro Unlock* | *Unlock downloadable .md packet & .csv scoring sheet with Second Foreman Pro ($29/mo or $149/yr).* |`,
679
+ ].join('\n');
680
+
681
+ const fullPacketMarkdown = isPro
682
+ ? [
683
+ ...mdHeader,
684
+ ...fmtMd(checkRows),
685
+ ``,
686
+ `## Draft 6-Section VADSIR (Vendor Accessibility Development Services Information Request) Response Structure`,
687
+ `1. **Business & SDLC Processes Integrating Accessibility:** [${sanitizeMdInline(vendorName)} integrates WCAG 2.2 Level AA & ISO 14289-1 (PDF/UA-1) gates across design, CI, and release QA.]`,
688
+ `2. **Developer & Authoring Accessibility Skills / Training:** [Role-based accessibility engineering, QA, and PDF/UA-1 training records.]`,
689
+ `3. **Accessibility Development & Testing Tools Used:** [axe-core, Lighthouse, veraPDF 106-rule PDF/UA-1 validator, AcroForm /TU & /Tabs /S inspector, keyboard & reflow checks.]`,
690
+ `4. **Corrective-Action Process for Accessibility Defects:** [Severity-tiered defect remediation SLAs and regression gates.]`,
691
+ `5. **Alternate Methods / Support When Full Compliance Is Pending:** [Designated accessibility support Desk and zero-surcharge accessible-format SLA.]`,
692
+ `6. **Examples / Links to Prior Accessible Deliverables:** [Attach WCAG AA URLs, 100/100 veraPDF PDF/UA-1 specimens, and VPAT 2.5 ACRs.]`,
693
+ ``,
694
+ `## Multi-State Statutory Alignment (1 TAC Ch. 206 & 213 · WA USER-01 · VA HB2541 · CO HB21-1110)`,
695
+ `- **Texas DIR (1 TAC Ch. 206 & 213):** Submit RFO Attachment C (PDAA), Attachment E (VADSIR), VPAT 2.4+/2.5, and >$500k third-party testing evidence.`,
696
+ `- **Washington (WaTech USER-01-01-S):** Verify WCAG 2.2 Level AA conformance (effective July 1, 2026).`,
697
+ `- **Virginia (HB2541 / Va. Code §§ 2.2-3500):** Provide comprehensive all-disability VPAT/ACR and contractual remediation roadmap.`,
698
+ `- **Colorado (HB21-1110 / 8 CCR 1501-11):** Provide testing evidence, accessibility statement, and defect remediation plan.`,
699
+ ].join('\n')
700
+ : null;
701
+
702
+ const fullMatrixCsv = isPro
703
+ ? [
704
+ 'vendor_name,target_state,contract_value_usd,pdaa_raw_points,pdaa_score_100,maturity_stage,bid_responsive_ready,vadsir_required,tx_500k_third_party_test_required,wcag22_gap_warning,estimated_pdf_remediation_usd,blocking_gap_count',
705
+ [
706
+ sanitizeCsvCell(vendorName),
707
+ sanitizeCsvCell(targetState),
708
+ sanitizeCsvCell(contractValueUsd),
709
+ sanitizeCsvCell(pdaaRawPoints),
710
+ sanitizeCsvCell(pdaaScore100),
711
+ sanitizeCsvCell(maturityStage),
712
+ sanitizeCsvCell(bidResponsiveReady),
713
+ sanitizeCsvCell(vadsirRequired),
714
+ sanitizeCsvCell(thirdPartyTestingRequiredTx500k),
715
+ sanitizeCsvCell(wcag22GapWarning),
716
+ sanitizeCsvCell(estimatedPdfRemediationUsd),
717
+ sanitizeCsvCell(blockingGaps.length),
718
+ ].join(','),
719
+ ].join('\n')
720
+ : null;
721
+
722
+ return {
723
+ vendorName,
724
+ targetState,
725
+ regimeShortLabel: regimeMeta.short,
726
+ regimeCitation: regimeMeta.citation,
727
+ contractValueUsd,
728
+ includesDevServices,
729
+ includesCotsOrSaas,
730
+ hasVpat25,
731
+ vadsirPrepared,
732
+ thirdPartyTestingPlanned,
733
+ wcagTargetTested,
734
+ isPro,
735
+ pdaaRawPoints,
736
+ pdaaScore100,
737
+ zeroCriteriaCount,
738
+ maturityStage,
739
+ maturityStageLabel,
740
+ vadsirRequired,
741
+ thirdPartyTestingRequiredTx500k,
742
+ wcag22RequiredByState,
743
+ wcag22GapWarning,
744
+ bidResponsiveReady,
745
+ blockingGaps,
746
+ requiredSubmittalsLabel,
747
+ untaggedPdfCount,
748
+ totalPdfPages,
749
+ estimatedPdfRemediationUsd,
750
+ checks: isPro ? checkRows : checkRows.slice(0, 3),
751
+ scopeDisclaimer,
752
+ previewPacketMarkdown,
753
+ fullPacketMarkdown,
754
+ fullMatrixCsv,
755
+ workbenchUrl: 'https://secondforeman.com/bidradar/state-procurement-pdaa-vadsir-scorer/',
756
+ vpatAuditorUrl: 'https://secondforeman.com/bidradar/vpat-acroform-auditor/',
757
+ freePage1ProofUrl: 'https://secondforeman.com/pdf-remediation/',
758
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
759
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
760
+ };
761
+ }
762
+
763
+ function calculateEpa608LeakRate(args = {}) {
764
+ const REFRIGERANT_GWP = {
765
+ 'R-410A': 2088, 'R-454B': 466, 'R-32': 675, 'R-404A': 3922,
766
+ 'R-407C': 1774, 'R-134a': 1430, 'R-448A': 1387, 'R-22': 1810,
767
+ 'R-1234yf': 4, 'R-744': 1,
768
+ };
769
+ const cat = ['comfort_cooling', 'commercial_refrig', 'industrial_process'].includes(args.category)
770
+ ? args.category
771
+ : 'comfort_cooling';
772
+ const ref = Object.hasOwn(REFRIGERANT_GWP, args.refrigerant) ? args.refrigerant : 'R-454B';
773
+ const gwp = REFRIGERANT_GWP[ref];
774
+ const chargeLbs = Math.max(0.1, Number(args.chargeLbs) || 20);
775
+ const addedNowLbs = Math.max(0, Number(args.addedNowLbs) || 0);
776
+ const daysSinceLastAdd = Math.max(1, Math.min(365, Number(args.daysSinceLastAdd) || 365));
777
+ const addedRolling365Lbs = Math.max(addedNowLbs, Number(args.addedRolling365Lbs ?? addedNowLbs));
778
+ const shutdownRequired = Boolean(args.shutdownRequired);
779
+
780
+ const triggerPct = cat === 'comfort_cooling' ? 10 : cat === 'commercial_refrig' ? 20 : 30;
781
+ const minRegulatedLbs = ref === 'R-22' ? 50 : gwp > 53 ? 15 : Infinity;
782
+ const isRegulatedCharge = chargeLbs >= minRegulatedLbs;
783
+ const annualizingPct = Number(((addedNowLbs / chargeLbs) * (365 / daysSinceLastAdd) * 100).toFixed(2));
784
+ const rollingPct = Number(((addedRolling365Lbs / chargeLbs) * 100).toFixed(2));
785
+ const exceedsAnnualizing = isRegulatedCharge && annualizingPct > triggerPct;
786
+ const exceedsRolling = isRegulatedCharge && rollingPct > triggerPct;
787
+ const repairWindowDays = shutdownRequired ? 120 : 30;
788
+
789
+ return {
790
+ category: cat,
791
+ refrigerant: ref,
792
+ gwp,
793
+ chargeLbs,
794
+ isRegulatedCharge,
795
+ triggerPct,
796
+ annualizingPct,
797
+ rollingPct,
798
+ exceedsAnnualizing,
799
+ exceedsRolling,
800
+ repairRequired: exceedsAnnualizing || exceedsRolling,
801
+ repairWindowDays: isRegulatedCharge ? repairWindowDays : null,
802
+ aldRequired: (cat === 'commercial_refrig' || cat === 'industrial_process') && gwp > 53 && chargeLbs >= 1500,
803
+ chronicLeakReportRequired: isRegulatedCharge && rollingPct >= 125,
804
+ calculatorUrl: 'https://secondforeman.com/epa-608-practice-test/leak-rate-calculator/',
805
+ simulatorUrl: 'https://secondforeman.com/epa-608-practice-test/',
806
+ };
807
+ }
808
+
809
+ function calculateA2lRoomChargeLimit(args = {}, { isPro = false } = {}) {
810
+ const a2lSpecs = {
811
+ 'R-454B': {
812
+ label: 'R-454B (68.9% R-32 / 31.1% R-1234yf · Class A2L · GWP 466)',
813
+ lflKgM3: 0.296,
814
+ lflLb1000Ft3: 18.5,
815
+ rclLb1000Ft3: 3.1,
816
+ gwp: 466,
817
+ },
818
+ 'R-32': {
819
+ label: 'R-32 (Single-Component HFC · Class A2L · GWP 675)',
820
+ lflKgM3: 0.307,
821
+ lflLb1000Ft3: 19.2,
822
+ rclLb1000Ft3: 4.8,
823
+ gwp: 675,
824
+ },
825
+ 'R-454A': {
826
+ label: 'R-454A (35% R-32 / 65% R-1234yf · Class A2L · GWP 239)',
827
+ lflKgM3: 0.279,
828
+ lflLb1000Ft3: 17.4,
829
+ rclLb1000Ft3: 2.8,
830
+ gwp: 239,
831
+ },
832
+ 'R-454C': {
833
+ label: 'R-454C (21.5% R-32 / 78.5% R-1234yf · Class A2L · GWP 148)',
834
+ lflKgM3: 0.291,
835
+ lflLb1000Ft3: 18.2,
836
+ rclLb1000Ft3: 2.9,
837
+ gwp: 148,
838
+ },
839
+ 'R-1234yf': {
840
+ label: 'R-1234yf (HFO · Class A2L · GWP < 1)',
841
+ lflKgM3: 0.289,
842
+ lflLb1000Ft3: 18.0,
843
+ rclLb1000Ft3: 2.9,
844
+ gwp: 1,
845
+ },
846
+ 'R-1234ze(E)': {
847
+ label: 'R-1234ze(E) (Chiller HFO · Class A2L · GWP < 1)',
848
+ lflKgM3: 0.303,
849
+ lflLb1000Ft3: 18.9,
850
+ rclLb1000Ft3: 3.8,
851
+ gwp: 1,
852
+ },
853
+ };
854
+
855
+ if (typeof args.refrigerant !== 'string' || !Object.hasOwn(a2lSpecs, args.refrigerant)) {
856
+ throw new Error(`Invalid params: "refrigerant" is required and must be one of ${Object.keys(a2lSpecs).join(', ')}.`);
857
+ }
858
+ if (args.systemType !== undefined && (typeof args.systemType !== 'string' || !['ducted', 'non_ducted'].includes(args.systemType))) {
859
+ throw new Error('Invalid params: "systemType" must be "ducted" or "non_ducted".');
860
+ }
861
+ const releaseHeightMap = { floor: 0.6, window: 1.0, wall: 1.8, ceiling: 2.2 };
862
+ if (args.releaseHeightPreset !== undefined && (typeof args.releaseHeightPreset !== 'string' || !Object.hasOwn(releaseHeightMap, args.releaseHeightPreset))) {
863
+ throw new Error('Invalid params: "releaseHeightPreset" must be one of floor, window, wall, ceiling.');
864
+ }
865
+ if (args.projectOrSiteName !== undefined && typeof args.projectOrSiteName !== 'string') {
866
+ throw new Error('Invalid params: "projectOrSiteName" must be a string.');
867
+ }
868
+ if (args.proKey !== undefined && typeof args.proKey !== 'string') {
869
+ throw new Error('Invalid params: "proKey" must be a string.');
870
+ }
871
+ for (const posKey of ['factoryChargeLb', 'conditionedAreaFt2', 'smallestZoneAreaFt2']) {
872
+ if (args[posKey] !== undefined && (typeof args[posKey] !== 'number' || !Number.isFinite(args[posKey]) || args[posKey] <= 0)) {
873
+ throw new Error(`Invalid params: "${posKey}" must be a positive finite number (> 0).`);
874
+ }
875
+ }
876
+ for (const nonNegKey of ['totalLineSetFt', 'factoryPrechargeFt', 'extraOzPerFt', 'elevationFt', 'actualMitigationCfm']) {
877
+ if (args[nonNegKey] !== undefined && (typeof args[nonNegKey] !== 'number' || !Number.isFinite(args[nonNegKey]) || args[nonNegKey] < 0)) {
878
+ throw new Error(`Invalid params: "${nonNegKey}" must be a non-negative finite number (>= 0).`);
879
+ }
880
+ }
881
+ for (const boolKey of ['hasRdsInstalled', 'hasZoneDampers', 'rdsOpensAllZoneDampers', 'hasLowDuctOpeningUnder5_9Ft', 'hasFalseCeilingReturnPlenum']) {
882
+ if (args[boolKey] !== undefined && typeof args[boolKey] !== 'boolean') {
883
+ throw new Error(`Invalid params: "${boolKey}" must be a boolean.`);
884
+ }
885
+ }
886
+
887
+ const cleanMd = (v) => String(v ?? '').replace(/[\r\n\t]+/g, ' ').replace(/\|/g, '\\|').trim();
888
+ const cleanCsv = (v) => {
889
+ const raw = String(v ?? '').replace(/[\r\n]+/g, ' ').trim();
890
+ const safe = /^[=+\-@\t\r]/.test(raw) ? `'${raw}` : raw;
891
+ return `"${safe.replace(/"/g, '""')}"`;
892
+ };
893
+
894
+ const LB_TO_KG = 0.45359237;
895
+ const KG_TO_LB = 2.20462262;
896
+ const FT_TO_M = 0.3048;
897
+ const M2_TO_FT2 = 10.7639104;
898
+ const M3H_TO_CFM = 0.58857778;
899
+
900
+ const projectOrSiteName =
901
+ String(args.projectOrSiteName || 'Jobsite Split System')
902
+ .replace(/[\r\n\t]+/g, ' ')
903
+ .trim()
904
+ .slice(0, 120) || 'Jobsite Split System';
905
+ const refrigerant = args.refrigerant;
906
+ const spec = a2lSpecs[refrigerant];
907
+ const systemType = args.systemType === 'non_ducted' ? 'non_ducted' : 'ducted';
908
+ const releaseHeightPreset = args.releaseHeightPreset || 'wall';
909
+ const releaseHeightM = releaseHeightMap[releaseHeightPreset];
910
+
911
+ const clampNum = (v, min, max, fb) => {
912
+ const n = Number(v ?? fb);
913
+ if (!Number.isFinite(n)) return fb;
914
+ return Math.max(min, Math.min(max, n));
915
+ };
916
+
917
+ const factoryChargeLb = clampNum(args.factoryChargeLb, 0.1, 1000, 10.0);
918
+ const totalLineSetFt = clampNum(args.totalLineSetFt, 0, 1000, 15);
919
+ const factoryPrechargeFt = clampNum(args.factoryPrechargeFt, 0, 500, 15);
920
+ const extraOzPerFt = clampNum(args.extraOzPerFt, 0, 20, 0.6);
921
+ const elevationFt = clampNum(args.elevationFt, 0, 16000, 0);
922
+ const conditionedAreaFt2 = clampNum(args.conditionedAreaFt2, 10, 500000, 1200);
923
+ const smallestZoneAreaFt2 = clampNum(args.smallestZoneAreaFt2, 10, 500000, conditionedAreaFt2);
924
+ const actualMitigationCfm = clampNum(args.actualMitigationCfm, 0, 200000, systemType === 'ducted' ? 400 : 0);
925
+
926
+ const hasRdsInstalled = Boolean(args.hasRdsInstalled ?? (systemType === 'ducted'));
927
+ const hasZoneDampers = Boolean(args.hasZoneDampers ?? false);
928
+ const rdsOpensAllZoneDampers = Boolean(args.rdsOpensAllZoneDampers ?? false);
929
+ const hasLowDuctOpeningUnder5_9Ft = Boolean(args.hasLowDuctOpeningUnder5_9Ft ?? false);
930
+ const hasFalseCeilingReturnPlenum = Boolean(args.hasFalseCeilingReturnPlenum ?? false);
931
+
932
+ const extraLineSetFt = Math.max(0, Number((totalLineSetFt - factoryPrechargeFt).toFixed(2)));
933
+ const addedLineSetChargeOz = Number((extraLineSetFt * extraOzPerFt).toFixed(2));
934
+ const addedLineSetChargeLb = Number((addedLineSetChargeOz / 16).toFixed(2));
935
+ const totalSystemChargeLb = Number((factoryChargeLb + addedLineSetChargeOz / 16).toFixed(2));
936
+ const totalSystemChargeKg = Number((totalSystemChargeLb * LB_TO_KG).toFixed(4));
937
+
938
+ const m1Kg = Number((6 * spec.lflKgM3).toFixed(4));
939
+ const m2Kg = Number((52 * spec.lflKgM3).toFixed(4));
940
+ const m3Kg = Number((260 * spec.lflKgM3).toFixed(4));
941
+ const m1Lb = Number((m1Kg * KG_TO_LB).toFixed(2));
942
+ const m2Lb = Number((m2Kg * KG_TO_LB).toFixed(2));
943
+ const m3Lb = Number((m3Kg * KG_TO_LB).toFixed(2));
944
+
945
+ const altKnots = [
946
+ [0, 1.0], [600, 1.0], [800, 1.02], [1000, 1.05], [1200, 1.07], [1400, 1.1],
947
+ [1600, 1.12], [1800, 1.15], [2000, 1.18], [2200, 1.21], [2400, 1.25], [2600, 1.28],
948
+ [2800, 1.32], [3000, 1.36], [3200, 1.4], [3600, 1.5], [4000, 1.61], [4600, 1.8],
949
+ ];
950
+ const elevationM = elevationFt * FT_TO_M;
951
+ let interpAf = altKnots[altKnots.length - 1][1];
952
+ if (elevationM <= altKnots[0][0]) {
953
+ interpAf = altKnots[0][1];
954
+ } else {
955
+ for (let i = 0; i < altKnots.length - 1; i++) {
956
+ const [m0, af0] = altKnots[i];
957
+ const [m1, af1] = altKnots[i + 1];
958
+ if (elevationM >= m0 && elevationM <= m1) {
959
+ const t = m1 === m0 ? 0 : (elevationM - m0) / (m1 - m0);
960
+ interpAf = af0 + t * (af1 - af0);
961
+ break;
962
+ }
963
+ }
964
+ }
965
+ const altitudeAdjustmentFactor = Number(interpAf.toFixed(2));
966
+ const exceedsUl3200mAltitudeRating = elevationM > 3205;
967
+
968
+ const unmitigatedExempt = totalSystemChargeKg <= m1Kg + 1e-6;
969
+ const exceedsM2UnmitigatedCap = totalSystemChargeKg > m2Kg + 1e-6;
970
+ const exceedsM3SingleCircuitCap = totalSystemChargeKg > m3Kg + 1e-6;
971
+ const poeOilNoteRequired = totalSystemChargeLb > 20;
972
+ const recommendedExtraPoeOilFlOz = poeOilNoteRequired ? Math.ceil((totalSystemChargeLb - 20) / 5) : 0;
973
+
974
+ const evaluatedAreaFt2 =
975
+ systemType === 'ducted' && hasZoneDampers && !rdsOpensAllZoneDampers
976
+ ? Math.min(conditionedAreaFt2, smallestZoneAreaFt2)
977
+ : conditionedAreaFt2;
978
+ const evaluatedAreaM2 = evaluatedAreaFt2 / M2_TO_FT2;
979
+
980
+ const calcUnmitigatedAminM2 = (h0) => {
981
+ const eq1 = Math.pow(totalSystemChargeKg / (2.5 * Math.pow(spec.lflKgM3, 1.25) * h0), 2);
982
+ const eq2 = totalSystemChargeKg / (0.5 * spec.lflKgM3 * h0);
983
+ return Math.min(eq1, eq2) * altitudeAdjustmentFactor;
984
+ };
985
+
986
+ const rdsTriggerReasons = [];
987
+ if (!unmitigatedExempt) {
988
+ if (exceedsM2UnmitigatedCap) {
989
+ rdsTriggerReasons.push(`circuit charge (${totalSystemChargeLb} lb) exceeds unmitigated m2 cap (${m2Lb} lb = 52 × LFL)`);
990
+ }
991
+ if (systemType === 'ducted') {
992
+ if (hasLowDuctOpeningUnder5_9Ft) rdsTriggerReasons.push('duct opening < 5.9 ft (1.8 m) above floor (ASHRAE 15-2022 §7.6.2.3)');
993
+ if (hasFalseCeilingReturnPlenum) rdsTriggerReasons.push('false-ceiling unducted return plenum (ASHRAE 15-2022 §7.6.2.3)');
994
+ if (hasZoneDampers) rdsTriggerReasons.push('multi-zone motorized dampers installed');
995
+ const unmitDuctH0 = hasLowDuctOpeningUnder5_9Ft ? 0.6 : 1.8;
996
+ const unmitDuctAminFt2 = calcUnmitigatedAminM2(unmitDuctH0) * M2_TO_FT2;
997
+ if (evaluatedAreaFt2 < unmitDuctAminFt2) {
998
+ rdsTriggerReasons.push(`space area (${evaluatedAreaFt2} sq ft) is below unmitigated Amin (${unmitDuctAminFt2.toFixed(1)} sq ft)`);
999
+ }
1000
+ }
1001
+ }
1002
+ const rdsRequired = rdsTriggerReasons.length > 0;
1003
+
1004
+ let requiredAreaM2 = 0;
1005
+ let requiredAreaFt2 = 0;
1006
+ let requiredQminM3h = 0;
1007
+ let requiredQminCfm = 0;
1008
+ let areaFormulaUsed = 'EXEMPT_MC_LE_M1';
1009
+
1010
+ if (!unmitigatedExempt) {
1011
+ if (systemType === 'ducted' && hasRdsInstalled) {
1012
+ const rawTaMinM2 = (totalSystemChargeKg / (0.5 * spec.lflKgM3 * 2.2)) * altitudeAdjustmentFactor;
1013
+ requiredAreaM2 = Number(rawTaMinM2.toFixed(2));
1014
+ requiredAreaFt2 = Number((rawTaMinM2 * M2_TO_FT2).toFixed(2));
1015
+ const rawQminM3h = (30 * totalSystemChargeKg) / spec.lflKgM3;
1016
+ requiredQminM3h = Number(rawQminM3h.toFixed(1));
1017
+ requiredQminCfm = Math.round(rawQminM3h * M3H_TO_CFM);
1018
+ areaFormulaUsed = 'UL_60335_2_40_ANNEX_GG_TAMIN_DUCTED_MITIGATED';
1019
+ } else {
1020
+ const h0 = systemType === 'ducted' ? (hasLowDuctOpeningUnder5_9Ft ? 0.6 : 1.8) : releaseHeightM;
1021
+ const rawAminM2 = calcUnmitigatedAminM2(h0);
1022
+ requiredAreaM2 = Number(rawAminM2.toFixed(2));
1023
+ requiredAreaFt2 = Number((rawAminM2 * M2_TO_FT2).toFixed(2));
1024
+ if (hasRdsInstalled) {
1025
+ const rawQminM3h = (30 * totalSystemChargeKg) / spec.lflKgM3;
1026
+ requiredQminM3h = Number(rawQminM3h.toFixed(1));
1027
+ requiredQminCfm = Math.round(rawQminM3h * M3H_TO_CFM);
1028
+ }
1029
+ areaFormulaUsed = 'UL_60335_2_40_ANNEX_GG_AMIN_UNMITIGATED';
1030
+ }
1031
+ }
1032
+
1033
+ const effectiveZoneDampers = systemType === 'ducted' && hasZoneDampers;
1034
+ let mMaxKg;
1035
+ if (systemType === 'ducted' && hasRdsInstalled) {
1036
+ mMaxKg = Math.min(m3Kg, Math.max(m1Kg, (evaluatedAreaM2 / altitudeAdjustmentFactor) * 0.5 * spec.lflKgM3 * 2.2));
1037
+ } else {
1038
+ const h0 = systemType === 'ducted' ? (hasLowDuctOpeningUnder5_9Ft ? 0.6 : 1.8) : releaseHeightM;
1039
+ const baseAreaM2 = evaluatedAreaM2 / altitudeAdjustmentFactor;
1040
+ const mEq1 = 2.5 * Math.pow(spec.lflKgM3, 1.25) * h0 * Math.sqrt(baseAreaM2);
1041
+ const mEq2 = 0.5 * spec.lflKgM3 * h0 * baseAreaM2;
1042
+ mMaxKg = Math.min(hasRdsInstalled ? m3Kg : m2Kg, Math.max(m1Kg, Math.max(mEq1, mEq2)));
1043
+ }
1044
+ const maxAllowableChargeLb = Number((mMaxKg * KG_TO_LB).toFixed(2));
1045
+
1046
+ const blockingFailures = [];
1047
+ if (exceedsM3SingleCircuitCap) {
1048
+ blockingFailures.push(`Total circuit charge (${totalSystemChargeLb} lb) exceeds UL 60335-2-40 single-circuit m3 cap (${m3Lb} lb = 260 × LFL).`);
1049
+ }
1050
+ if (!unmitigatedExempt && systemType === 'non_ducted' && exceedsM2UnmitigatedCap && !hasRdsInstalled) {
1051
+ blockingFailures.push(`Non-ducted charge (${totalSystemChargeLb} lb) exceeds unmitigated m2 limit (${m2Lb} lb); active UL-listed RDS mitigation is mandatory.`);
1052
+ }
1053
+ if (rdsRequired && !hasRdsInstalled) {
1054
+ blockingFailures.push(`Integral UL 60335-2-40 Annex LL RDS is required (${rdsTriggerReasons.join('; ')}) but not marked installed.`);
1055
+ }
1056
+ if (!unmitigatedExempt && evaluatedAreaFt2 + 1e-6 < requiredAreaFt2) {
1057
+ if (effectiveZoneDampers && !rdsOpensAllZoneDampers && conditionedAreaFt2 >= requiredAreaFt2) {
1058
+ blockingFailures.push(`ZONING DAMPER TRAP: Total floor area (${conditionedAreaFt2} sq ft) clears TAmin (${requiredAreaFt2} sq ft), but isolated smallest zone (${smallestZoneAreaFt2} sq ft) fails because zone dampers do not open on RDS alarm.`);
1059
+ } else {
1060
+ blockingFailures.push(`Evaluated conditioned area (${evaluatedAreaFt2} sq ft) is below minimum required ${systemType === 'ducted' && hasRdsInstalled ? 'TAmin' : 'Amin'} (${requiredAreaFt2} sq ft @ AF ${altitudeAdjustmentFactor.toFixed(2)}).`);
1061
+ }
1062
+ }
1063
+ if (requiredQminCfm > 0 && actualMitigationCfm < requiredQminCfm) {
1064
+ blockingFailures.push(`Configured RDS mitigation airflow (${actualMitigationCfm} CFM) is below minimum required Qmin (${requiredQminCfm} CFM).`);
1065
+ }
1066
+
1067
+ const fieldWarnings = [];
1068
+ if (exceedsUl3200mAltitudeRating) {
1069
+ fieldWarnings.push(`Site elevation (${elevationFt.toLocaleString()} ft) exceeds standard UL 60335-2-40 3,200 m (10,500 ft) appliance rating table.`);
1070
+ }
1071
+ if (poeOilNoteRequired) {
1072
+ fieldWarnings.push(`Total charge (${totalSystemChargeLb} lb) exceeds 20 lb — verify OEM compressor POE oil supplement (~${recommendedExtraPoeOilFlOz} fl oz).`);
1073
+ }
1074
+ if (totalSystemChargeLb >= 15 && spec.gwp > 53) {
1075
+ fieldWarnings.push(`Total charge (${totalSystemChargeLb} lb, GWP ${spec.gwp}) >= 15 lb: subject to 2026 EPA AIM Act 40 CFR § 84.106 leak-repair thresholds.`);
1076
+ }
1077
+
1078
+ const complianceStatus = blockingFailures.length === 0 ? 'PASS' : 'FAIL';
1079
+ const scopeDisclaimer =
1080
+ 'Field Engineering & Pre-Installation Sizing Aid ONLY — Not a PE-stamped mechanical design, not a substitute for the specific OEM Installation & Operation Manual (IOM) nameplate tables, and not Authority Having Jurisdiction (AHJ) code approval (IMC / UMC / ASHRAE 15 / ASHRAE 15.2 / UL 60335-2-40).';
1081
+
1082
+ const checkRows = [
1083
+ { gate: '1. Class A2L Refrigerant & UL 60335-2-40 Thresholds', status: exceedsM3SingleCircuitCap ? 'FAIL (> m3)' : unmitigatedExempt ? 'EXEMPT (<= m1)' : 'ACTIVE (> m1)', detail: `${refrigerant} (LFL ${spec.lflKgM3} kg/m³ · GWP ${spec.gwp}) — m1 = ${m1Lb} lb · m2 = ${m2Lb} lb · m3 = ${m3Lb} lb` },
1084
+ { gate: '2. Total Single-Circuit Charge (Factory + Line Set)', status: exceedsM3SingleCircuitCap ? 'FAIL' : 'CALCULATED', detail: `${totalSystemChargeLb} lb (${totalSystemChargeKg.toFixed(2)} kg) = ${factoryChargeLb} lb factory + ${addedLineSetChargeOz} oz` },
1085
+ { gate: '3. Elevation & UL Altitude Adjustment Factor (AF)', status: exceedsUl3200mAltitudeRating ? 'VERIFY >3,200m' : 'PASS', detail: `${elevationFt.toLocaleString()} ft -> AF = ${altitudeAdjustmentFactor.toFixed(2)}` },
1086
+ { gate: `4. Minimum Conditioned Floor Area (${systemType === 'ducted' && hasRdsInstalled ? 'TAmin Eq. GG.15DV' : 'Amin Annex GG.2'})`, status: unmitigatedExempt || evaluatedAreaFt2 + 1e-6 >= requiredAreaFt2 ? 'PASS' : 'FAIL', detail: unmitigatedExempt ? `Exempt (<= ${m1Lb} lb)` : `Evaluated ${evaluatedAreaFt2} sq ft vs Required ${requiredAreaFt2.toFixed(2)} sq ft · Max charge = ${maxAllowableChargeLb} lb` },
1087
+ { gate: '5. Mitigation Circulation Airflow (Qmin Eq. GG.17DV)', status: requiredQminCfm === 0 ? 'EXEMPT' : actualMitigationCfm >= requiredQminCfm ? 'PASS' : 'FAIL', detail: requiredQminCfm === 0 ? '0 CFM required' : `Configured ${actualMitigationCfm} CFM vs Required ${requiredQminCfm} CFM (${requiredQminM3h} m³/h)` },
1088
+ { gate: '6. Motorized Zoning Damper Isolation Check', status: !effectiveZoneDampers || rdsOpensAllZoneDampers || evaluatedAreaFt2 + 1e-6 >= requiredAreaFt2 ? 'PASS' : 'FAIL (ISOLATED ZONE)', detail: systemType !== 'ducted' ? 'N/A — Non-ducted appliance' : !effectiveZoneDampers ? 'Single-zone distribution' : rdsOpensAllZoneDampers ? `All dampers drive open on RDS alarm (${conditionedAreaFt2} sq ft)` : `Smallest isolated zone (${smallestZoneAreaFt2} sq ft) governs` },
1089
+ { gate: '7. ASHRAE 15-2022 §7.6.2.3 & Annex LL RDS Gate', status: !rdsRequired ? 'EXEMPT' : hasRdsInstalled ? 'PASS' : 'FAIL', detail: !rdsRequired ? 'No mandatory RDS trigger above m1' : hasRdsInstalled ? 'Integral Annex LL RDS installed' : `RDS missing (${rdsTriggerReasons.join('; ')})` },
1090
+ { gate: '8. Ignition Sources, Indoor Joints & EPA 40 CFR § 84.106', status: totalSystemChargeLb >= 15 && spec.gwp > 53 ? '15-LB AIM LOG' : 'CHECKLIST', detail: `Brazed or UL 207 / ISO 14903 press-fit indoor joints <=5 g/yr; CGA 164 left-hand adapter${totalSystemChargeLb >= 15 && spec.gwp > 53 ? '; >=15 lb AIM Act leak log' : ''}.` },
1091
+ ];
1092
+
1093
+ const fmtMd = (rows) => rows.map((r) => `| ${cleanMd(r.gate)} | **${r.status}** | ${cleanMd(r.detail)} |`);
1094
+ const mdHeader = [
1095
+ `# Class A2L Room Area, Charge Limit & RDS Airflow Sheet — ${cleanMd(projectOrSiteName)}`,
1096
+ `- **Applicable Standards:** UL 60335-2-40 (4th Ed. Annex GG & LL) · ASHRAE 15-2022 §7.6.2.3 · ASHRAE 15.2-2022`,
1097
+ `- **Refrigerant & Distribution:** ${spec.label} · ${systemType === 'ducted' ? 'Ducted System' : `Non-Ducted (${releaseHeightPreset} h0 = ${releaseHeightM} m)`}`,
1098
+ `- **Total Circuit Charge (mc):** **${totalSystemChargeLb} lb** (${totalSystemChargeKg.toFixed(2)} kg) · m1 = ${m1Lb} lb · m2 = ${m2Lb} lb · m3 = ${m3Lb} lb`,
1099
+ `- **Minimum Required Area / Airflow:** **${requiredAreaFt2.toFixed(1)} sq ft** (${requiredAreaM2} m² @ AF ${altitudeAdjustmentFactor.toFixed(2)}) · **Qmin = ${requiredQminCfm} CFM**`,
1100
+ `- **Compliance Verdict:** **${complianceStatus}**`,
1101
+ `- **Notice:** ${scopeDisclaimer}`,
1102
+ ``,
1103
+ `| Commissioning / Code Gate | Status | Calculated Field Requirement |`,
1104
+ `| --- | --- | --- |`,
1105
+ ];
1106
+
1107
+ const previewChecklistMarkdown = [
1108
+ ...mdHeader,
1109
+ ...fmtMd(checkRows.slice(0, 3)),
1110
+ `| ... *(Full 8-Gate UL 60335-2-40 & ASHRAE 15.2 Commissioning Matrix + Field Sign-Off Block)* | *Pro Unlock* | *Unlock downloadable .md permit sheet & .csv room schedule with Second Foreman Pro ($29/mo or $149/yr).* |`,
1111
+ ].join('\n');
1112
+
1113
+ const fullChecklistMarkdown = isPro
1114
+ ? [
1115
+ ...mdHeader,
1116
+ ...fmtMd(checkRows),
1117
+ ...(fieldWarnings.length ? [``, `## Field Engineering & Code Notes`, ...fieldWarnings.map((w) => `- ${cleanMd(w)}`)] : []),
1118
+ ``,
1119
+ `## Technician A2L Startup & AHJ Inspection Sign-Off Block`,
1120
+ `- [ ] **Cylinder & Liquid Charging Verified:** Charged from PMS 185 red-band cylinder via left-hand CGA 164 (<50 lb) / CGA 670 adapter in liquid phase.`,
1121
+ `- [ ] **Permanent Charge Label Completed:** Marked factory charge (${factoryChargeLb} lb), extra line set (${extraLineSetFt} ft), added trim (${addedLineSetChargeOz} oz), and total charge (${totalSystemChargeLb} lb).`,
1122
+ `- [ ] **Indoor Field Joints Leak-Tested:** Brazed or UL 207 / ISO 14903 listed press-fit indoor joints verified <= 5 g/yr (0.2 oz/yr).`,
1123
+ `- [ ] **Annex LL RDS Alarm & Airflow Proof Tested:** Confirmed compressor lockout, electric-heat cutout, and >= ${requiredQminCfm} CFM blower response within 15–30 seconds.`,
1124
+ ].join('\n')
1125
+ : null;
1126
+
1127
+ const fullScheduleCsv = isPro
1128
+ ? [
1129
+ 'project_or_site_name,refrigerant,system_type,factory_charge_lb,extra_lineset_ft,added_lineset_oz,total_charge_lb,elevation_ft,altitude_af,evaluated_area_ft2,required_area_ft2,required_qmin_cfm,actual_mitigation_cfm,rds_required,has_rds_installed,compliance_status',
1130
+ [
1131
+ cleanCsv(projectOrSiteName),
1132
+ cleanCsv(refrigerant),
1133
+ cleanCsv(systemType),
1134
+ cleanCsv(factoryChargeLb),
1135
+ cleanCsv(extraLineSetFt),
1136
+ cleanCsv(addedLineSetChargeOz),
1137
+ cleanCsv(totalSystemChargeLb),
1138
+ cleanCsv(elevationFt),
1139
+ cleanCsv(altitudeAdjustmentFactor),
1140
+ cleanCsv(evaluatedAreaFt2),
1141
+ cleanCsv(requiredAreaFt2),
1142
+ cleanCsv(requiredQminCfm),
1143
+ cleanCsv(actualMitigationCfm),
1144
+ cleanCsv(rdsRequired),
1145
+ cleanCsv(hasRdsInstalled),
1146
+ cleanCsv(complianceStatus),
1147
+ ].join(','),
1148
+ ].join('\n')
1149
+ : null;
1150
+
1151
+ return {
1152
+ projectOrSiteName,
1153
+ refrigerant,
1154
+ refrigerantLabel: spec.label,
1155
+ lflKgM3: spec.lflKgM3,
1156
+ lflLb1000Ft3: spec.lflLb1000Ft3,
1157
+ rclLb1000Ft3: spec.rclLb1000Ft3,
1158
+ gwp: spec.gwp,
1159
+ systemType,
1160
+ releaseHeightPreset,
1161
+ releaseHeightM,
1162
+ factoryChargeLb,
1163
+ totalLineSetFt,
1164
+ factoryPrechargeFt,
1165
+ extraOzPerFt,
1166
+ extraLineSetFt,
1167
+ addedLineSetChargeOz,
1168
+ addedLineSetChargeLb,
1169
+ totalSystemChargeLb,
1170
+ totalSystemChargeKg,
1171
+ m1Lb,
1172
+ m2Lb,
1173
+ m3Lb,
1174
+ elevationFt,
1175
+ altitudeAdjustmentFactor,
1176
+ exceedsUl3200mAltitudeRating,
1177
+ conditionedAreaFt2,
1178
+ smallestZoneAreaFt2,
1179
+ evaluatedAreaFt2,
1180
+ requiredAreaM2,
1181
+ requiredAreaFt2,
1182
+ areaFormulaUsed,
1183
+ requiredQminM3h,
1184
+ requiredQminCfm,
1185
+ actualMitigationCfm,
1186
+ maxAllowableChargeLb,
1187
+ unmitigatedExempt,
1188
+ exceedsM2UnmitigatedCap,
1189
+ exceedsM3SingleCircuitCap,
1190
+ poeOilNoteRequired,
1191
+ recommendedExtraPoeOilFlOz,
1192
+ rdsRequired,
1193
+ rdsTriggerReasons,
1194
+ hasRdsInstalled,
1195
+ hasZoneDampers,
1196
+ rdsOpensAllZoneDampers,
1197
+ hasLowDuctOpeningUnder5_9Ft,
1198
+ hasFalseCeilingReturnPlenum,
1199
+ complianceStatus,
1200
+ blockingFailures,
1201
+ fieldWarnings,
1202
+ isPro,
1203
+ checks: isPro ? checkRows : checkRows.slice(0, 3),
1204
+ scopeDisclaimer,
1205
+ previewChecklistMarkdown,
1206
+ fullChecklistMarkdown,
1207
+ fullScheduleCsv,
1208
+ workbenchUrl: 'https://secondforeman.com/epa-608-practice-test/a2l-charge-limit-calculator/',
1209
+ superheatCalculatorUrl: 'https://secondforeman.com/epa-608-practice-test/superheat-subcooling-calculator/',
1210
+ leakRateCalculatorUrl: 'https://secondforeman.com/epa-608-practice-test/leak-rate-calculator/',
1211
+ simulatorUrl: 'https://secondforeman.com/epa-608-practice-test/',
1212
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
1213
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
1214
+ };
1215
+ }
1216
+
1217
+ function validateSafePublicHttpsUrl(rawUrl) {
1218
+ let parsed;
1219
+ try {
1220
+ parsed = new URL(String(rawUrl || '').trim());
1221
+ } catch {
1222
+ throw new Error('Provide a valid https:// URL.');
1223
+ }
1224
+ if (parsed.protocol !== 'https:') throw new Error('Only public https:// URLs are permitted.');
1225
+ if (parsed.username || parsed.password) throw new Error('URLs with embedded credentials are not permitted.');
1226
+ if (parsed.port && parsed.port !== '443') throw new Error('Only standard port 443 https:// URLs are permitted.');
1227
+ const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
1228
+ if (
1229
+ !host || !host.includes('.') || host.includes(':') ||
1230
+ host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') ||
1231
+ host.endsWith('.internal') || host.endsWith('.arpa') || host.endsWith('.nip.io') ||
1232
+ host.endsWith('.sslip.io') || host.endsWith('.xip.io') || host.endsWith('.lvh.me') ||
1233
+ host.endsWith('.localtest.me') || host.endsWith('.traefik.me') ||
1234
+ /^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || /^0x[0-9a-f]+$/i.test(host) || /^\d+$/.test(host)
1235
+ ) {
1236
+ throw new Error('Private, loopback, IP-literal, and internal hostnames are blocked.');
1237
+ }
1238
+ return parsed;
1239
+ }
1240
+
1241
+ async function readStreamCappedUtf8(resp, maxBytes = 524288) {
1242
+ if (!resp.body || typeof resp.body.getReader !== 'function') {
1243
+ const buf = await resp.arrayBuffer();
1244
+ return new TextDecoder('utf-8', { fatal: false }).decode(buf.byteLength > maxBytes ? buf.slice(0, maxBytes) : buf);
1245
+ }
1246
+ const reader = resp.body.getReader();
1247
+ const chunks = [];
1248
+ let total = 0;
1249
+ try {
1250
+ while (total < maxBytes) {
1251
+ const { done, value } = await reader.read();
1252
+ if (done || !value) break;
1253
+ const take = value.byteLength > maxBytes - total ? value.subarray(0, maxBytes - total) : value;
1254
+ chunks.push(take);
1255
+ total += take.byteLength;
1256
+ if (total >= maxBytes) {
1257
+ await reader.cancel().catch(() => {});
1258
+ break;
1259
+ }
1260
+ }
1261
+ } finally {
1262
+ reader.releaseLock();
1263
+ }
1264
+ const merged = new Uint8Array(total);
1265
+ let offset = 0;
1266
+ for (const c of chunks) {
1267
+ merged.set(c, offset);
1268
+ offset += c.byteLength;
1269
+ }
1270
+ return new TextDecoder('utf-8', { fatal: false }).decode(merged);
1271
+ }
1272
+
1273
+ async function auditPublicWebpageWcagPdf(rawUrl, fetchImpl = globalThis.fetch) {
1274
+ let currentUrl = validateSafePublicHttpsUrl(rawUrl);
1275
+ const controller = new AbortController();
1276
+ const timer = setTimeout(() => controller.abort(), 6000);
1277
+ let resp;
1278
+ try {
1279
+ for (let hop = 0; hop <= 3; hop++) {
1280
+ resp = await fetchImpl(currentUrl.toString(), {
1281
+ method: 'GET',
1282
+ redirect: 'manual',
1283
+ headers: {
1284
+ accept: 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5',
1285
+ 'user-agent': 'SecondForeman-ADA-QuickAudit/1.1 (+https://secondforeman.com/pdf-remediation/)',
1286
+ },
1287
+ signal: controller.signal,
1288
+ });
1289
+ if (resp.status >= 300 && resp.status < 400) {
1290
+ const loc = resp.headers.get('location');
1291
+ if (!loc || hop === 3) throw new Error('Too many or invalid redirects.');
1292
+ currentUrl = validateSafePublicHttpsUrl(new URL(loc, currentUrl).toString());
1293
+ continue;
1294
+ }
1295
+ break;
1296
+ }
1297
+ const ctype = (resp.headers.get('content-type') || '').toLowerCase();
1298
+ if (ctype && !ctype.includes('html') && !ctype.includes('xml') && !ctype.includes('text/plain')) {
1299
+ throw new Error(`Unsupported content-type "${ctype}" (expected HTML webpage).`);
1300
+ }
1301
+ const html = await readStreamCappedUtf8(resp, 524288);
1302
+ const hasHtmlLang = /<html\b[^<>]{0,2048}\blang\s*=\s*["']?[a-zA-Z-]{2,}/i.test(html);
1303
+ const tOpen = html.search(/<title\b[^<>]{0,512}>/i);
1304
+ const titleMatch = tOpen >= 0 ? html.slice(tOpen, tOpen + 4096).match(/^<title\b[^<>]{0,512}>([\s\S]{0,2048}?)<\/title>/i) : null;
1305
+ const hasTitle = Boolean(titleMatch && titleMatch[1].trim());
1306
+ const h1Count = (html.match(/<h1[\s>]/gi) || []).length;
1307
+ const imgTags = html.match(/<img\b[^<>]{0,2048}>/gi) || [];
1308
+ let imagesMissingAlt = 0;
1309
+ for (const tag of imgTags) if (!/\balt\s*=/i.test(tag)) imagesMissingAlt++;
1310
+ const iframeTags = html.match(/<iframe\b[^<>]{0,2048}>/gi) || [];
1311
+ let untitledIframes = 0;
1312
+ for (const tag of iframeTags) if (!/\b(?:title|aria-label)\s*=\s*["'][^"']+["']/i.test(tag)) untitledIframes++;
1313
+ const pdfSet = new Set();
1314
+ for (const m of html.matchAll(/\bhref\s*=\s*["']([^"'#?]+\.pdf(?:\?[^"'#]*)?)["']/gi)) {
1315
+ try { pdfSet.add(new URL(m[1], currentUrl).toString()); } catch {}
1316
+ }
1317
+ const linkedPdfs = [...pdfSet];
1318
+ return {
1319
+ auditedUrl: currentUrl.toString(),
1320
+ httpStatus: resp.status,
1321
+ hasHtmlLang,
1322
+ hasTitle,
1323
+ h1Count,
1324
+ totalImages: imgTags.length,
1325
+ imagesMissingAlt,
1326
+ totalIframes: iframeTags.length,
1327
+ untitledIframes,
1328
+ linkedPdfCount: linkedPdfs.length,
1329
+ linkedPdfSamples: linkedPdfs.slice(0, 10),
1330
+ estimatedPdfRemediationUsd: Math.round(linkedPdfs.length * 6 * 1.5),
1331
+ freePage1ProofUrl: 'https://secondforeman.com/pdf-remediation/',
1332
+ costEstimatorUrl: 'https://secondforeman.com/bidradar/ada-title-ii-pdf-estimator/',
1333
+ };
1334
+ } finally {
1335
+ clearTimeout(timer);
1336
+ }
1337
+ }
1338
+
1339
+ function inflatePdfBufferFlate(bytes, raw) {
1340
+ if (!raw.includes('/FlateDecode')) return '';
1341
+ const flateRe = />>\s*stream(?:\r\n|\n)/g;
1342
+ let fm;
1343
+ let fCount = 0;
1344
+ let fBytes = 0;
1345
+ let inflated = '';
1346
+ while ((fm = flateRe.exec(raw)) && fCount < 64 && fBytes < 1572864) {
1347
+ const dictWin = raw.slice(Math.max(0, fm.index - 600), fm.index);
1348
+ let depth = 1;
1349
+ let pos = dictWin.length - 1;
1350
+ while (pos > 0 && depth > 0) {
1351
+ if (dictWin[pos] === '>' && dictWin[pos - 1] === '>') {
1352
+ depth++;
1353
+ pos -= 2;
1354
+ continue;
1355
+ }
1356
+ if (dictWin[pos] === '<' && dictWin[pos - 1] === '<') {
1357
+ depth--;
1358
+ pos -= 2;
1359
+ continue;
1360
+ }
1361
+ pos--;
1362
+ }
1363
+ const dictBody = depth === 0 ? dictWin.slice(pos + 1) : dictWin;
1364
+ if (!/\/FlateDecode\b/.test(dictBody)) continue;
1365
+ const sStart = flateRe.lastIndex;
1366
+ const sEnd = raw.indexOf('endstream', sStart);
1367
+ if (sEnd < 0 || sEnd - sStart > 1048576) continue;
1368
+ let slice = bytes.subarray(sStart, sEnd);
1369
+ if (slice.length >= 2 && slice[slice.length - 2] === 13 && slice[slice.length - 1] === 10) {
1370
+ slice = slice.subarray(0, slice.length - 2);
1371
+ } else if (slice.length >= 1 && (slice[slice.length - 1] === 10 || slice[slice.length - 1] === 13)) {
1372
+ slice = slice.subarray(0, slice.length - 1);
1373
+ }
1374
+ if (!slice.length) continue;
1375
+ fCount++;
1376
+ try {
1377
+ const outBuf = zlib.inflateSync(slice, { maxOutputLength: 262144 });
1378
+ if (fBytes + outBuf.byteLength > 1572864) break;
1379
+ fBytes += outBuf.byteLength;
1380
+ inflated += '\n' + outBuf.toString('latin1');
1381
+ } catch {
1382
+ /* ignore malformed or non-zlib stream */
1383
+ }
1384
+ }
1385
+ return inflated;
1386
+ }
1387
+
1388
+ const READ_ONLY_LOCAL = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
1389
+ const READ_ONLY_WEB = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
1390
+
1391
+ export async function handleMcpRequest(req, options = {}) {
1392
+ if (!req || typeof req !== 'object') return null;
1393
+ const { id, method, params } = req;
1394
+
1395
+ // Notifications have no id and expect no response
1396
+ if (id === undefined || id === null) return null;
1397
+
1398
+ if (method === 'initialize') {
1399
+ return {
1400
+ jsonrpc: '2.0',
1401
+ id,
1402
+ result: {
1403
+ protocolVersion: '2024-11-05',
1404
+ capabilities: { tools: {} },
1405
+ serverInfo: {
1406
+ name: 'contextguard-mcp',
1407
+ version: '1.8.0',
1408
+ },
1409
+ },
1410
+ };
1411
+ }
1412
+
1413
+ if (method === 'ping') {
1414
+ return { jsonrpc: '2.0', id, result: {} };
1415
+ }
1416
+
1417
+ if (method === 'tools/list') {
1418
+ return {
1419
+ jsonrpc: '2.0',
1420
+ id,
1421
+ result: {
1422
+ tools: [
1423
+ {
1424
+ name: 'contextguard_audit_workspace',
1425
+ description: 'Audits CLAUDE.md, AGENTS.md, .cursorrules, plans, and lockfiles in a directory for AI-coding token burn and context-compaction loop traps.',
1426
+ annotations: { title: 'Audit Workspace Token Burn', ...READ_ONLY_LOCAL },
1427
+ inputSchema: {
1428
+ type: 'object',
1429
+ properties: {
1430
+ directory: { type: 'string', description: 'Workspace directory path (defaults to current working directory).' },
1431
+ },
1432
+ },
1433
+ },
1434
+ {
1435
+ name: 'contextguard_slim_boot_card',
1436
+ description: 'Compiles oversized workspace instruction files into a deterministic <5 KB START.md boot card and .claudeignore.',
1437
+ annotations: { title: 'Compile <5 KB START.md Boot Card', ...READ_ONLY_LOCAL },
1438
+ inputSchema: {
1439
+ type: 'object',
1440
+ properties: {
1441
+ directory: { type: 'string', description: 'Workspace directory path.' },
1442
+ },
1443
+ },
1444
+ },
1445
+ {
1446
+ name: 'contextguard_compress_web_doc',
1447
+ description: 'Strips HTML/DOM boilerplate and compresses PR diffs, docs, or logs into a strict token budget.',
1448
+ annotations: { title: 'Compress HTML/DOM to Token Budget', ...READ_ONLY_LOCAL },
1449
+ inputSchema: {
1450
+ type: 'object',
1451
+ properties: {
1452
+ html_or_text: { type: 'string', description: 'Raw HTML or log text to compress.' },
1453
+ budget_tokens: { type: 'number', description: 'Target token cap (default 3000).' },
1454
+ },
1455
+ required: ['html_or_text'],
1456
+ },
1457
+ },
1458
+ {
1459
+ name: 'bidradar_search_public_bids',
1460
+ description: 'Queries Second Foreman BidRadar (https://secondforeman.com/bidradar/) for open written/async government & institutional RFPs, sub-threshold P-Card quotes, and ADA Title II remediation opportunities.',
1461
+ annotations: { title: 'Search Async Public RFPs & Micro-Purchases', ...READ_ONLY_WEB },
1462
+ inputSchema: {
1463
+ type: 'object',
1464
+ properties: {
1465
+ category: { type: 'string', description: 'Optional category: web_redesign, ada_pdf, it_software, or data_editorial.' },
1466
+ query: { type: 'string', description: 'Optional keyword or state filter.' },
1467
+ },
1468
+ },
1469
+ },
1470
+ {
1471
+ name: 'ada_estimate_pdf_ua_remediation',
1472
+ description: 'Estimates DOJ 28 CFR Part 35 Subpart H (91 FR 20902) ADA Title II PDF/UA-1 & WCAG 2.1 AA remediation cost, timeline, and $15k Federal GPC / $25k State P-Card eligibility.',
1473
+ annotations: { title: 'Estimate ADA Title II PDF/UA-1 Budget', ...READ_ONLY_LOCAL },
1474
+ inputSchema: {
1475
+ type: 'object',
1476
+ properties: {
1477
+ entityTier: { type: 'string', enum: ['pop_50k_plus', 'pop_under_50k', 'special_district', 'commercial_508'] },
1478
+ pdfCount: { type: 'number', description: 'Number of PDFs to remediate.' },
1479
+ avgPagesPerPdf: { type: 'number', description: 'Average pages per PDF (default 6).' },
1480
+ scannedSharePct: { type: 'number', description: 'Percentage of image-only scanned pages (0-100).' },
1481
+ acroFormCount: { type: 'number', description: 'Interactive fillable PDF forms count.' },
1482
+ webTemplateCount: { type: 'number', description: 'HTML web templates count.' },
1483
+ },
1484
+ required: ['pdfCount'],
1485
+ },
1486
+ },
1487
+ {
1488
+ name: 'ada_audit_public_webpage',
1489
+ description: 'Performs a read-only WCAG 2.2 AA & linked-PDF quick audit on a public https:// webpage (<html lang>, <title>, <h1>, missing alt, untitled iframes, and linked PDFs).',
1490
+ annotations: { title: 'Audit Public Webpage WCAG 2.2 & PDFs', ...READ_ONLY_WEB },
1491
+ inputSchema: {
1492
+ type: 'object',
1493
+ properties: {
1494
+ url: { type: 'string', description: 'Public https:// URL to audit.' },
1495
+ },
1496
+ required: ['url'],
1497
+ },
1498
+ },
1499
+ {
1500
+ name: 'epa608_calculate_leak_rate',
1501
+ description: 'Calculates 2026 EPA Section 608 & AIM Act 40 CFR 84.106 (>= 15 lb HFC/A2L GWP > 53) annualizing and rolling 12-month refrigerant leak rates and repair deadlines.',
1502
+ annotations: { title: 'Calculate 2026 EPA 608 / AIM Act Leak Rate', ...READ_ONLY_LOCAL },
1503
+ inputSchema: {
1504
+ type: 'object',
1505
+ properties: {
1506
+ category: { type: 'string', enum: ['comfort_cooling', 'commercial_refrig', 'industrial_process'] },
1507
+ refrigerant: { type: 'string', description: 'Refrigerant (e.g. R-454B, R-32, R-410A, R-404A, R-22).' },
1508
+ chargeLbs: { type: 'number', description: 'Full system charge in lbs.' },
1509
+ addedNowLbs: { type: 'number', description: 'Refrigerant added today in lbs.' },
1510
+ daysSinceLastAdd: { type: 'number', description: 'Days since previous refrigerant addition (default 365).' },
1511
+ addedRolling365Lbs: { type: 'number', description: 'Total lbs added over rolling 365 days.' },
1512
+ shutdownRequired: { type: 'boolean', description: 'Whether industrial process shutdown is required.' },
1513
+ },
1514
+ required: ['chargeLbs', 'addedNowLbs'],
1515
+ },
1516
+ },
1517
+ {
1518
+ name: 'govcon_calculate_gpc_unison_margin',
1519
+ description: 'Calculates Unison Marketplace (<= 3.93% GSA GS-35F-131GA fee) and Federal Government Purchase Card (FAR 13.2 $15,000 micro-purchase + Stripe 2.9% + $0.30 on gross award) net profit, FOB Destination margin, and floor-safe seller bid.',
1520
+ annotations: { title: 'Calculate Unison & Federal $15k GPC Bid Margin', ...READ_ONLY_LOCAL },
1521
+ inputSchema: {
1522
+ type: 'object',
1523
+ properties: {
1524
+ sellerBidUsd: { type: 'number', description: 'Seller bid in USD before Unison fee.' },
1525
+ supplierCogsUsd: { type: 'number', description: 'Wholesale distributor COGS in USD.' },
1526
+ shippingFobDestUsd: { type: 'number', description: 'FOB Destination freight in USD (default 0).' },
1527
+ unisonFeePct: { type: 'number', description: 'Unison fee % 0 to 3.93 (default 3.0).' },
1528
+ paymentMethod: { type: 'string', enum: ['GPC_CARD', 'ACH_EFT', 'OK_PCARD_DVBE'] },
1529
+ targetMarginPct: { type: 'number', description: 'Target minimum net margin % (default 20).' },
1530
+ minProfitUsd: { type: 'number', description: 'Minimum net profit floor in USD (default 1500).' },
1531
+ },
1532
+ required: ['sellerBidUsd', 'supplierCogsUsd'],
1533
+ },
1534
+ },
1535
+ {
1536
+ name: 'ada_inspect_public_pdf_ua',
1537
+ description: 'Inspects a public https:// PDF (and /FlateDecode object streams) against ISO 14289-1 (PDF/UA-1), WCAG 2.1 AA, and 28 CFR Part 35 (/Marked true, /StructTreeRoot, pdfuaid:part=1, /Lang, /DisplayDocTitle, scanned OCR vs digital fonts).',
1538
+ annotations: { title: 'Inspect Public PDF for ISO 14289-1 (PDF/UA-1)', ...READ_ONLY_WEB },
1539
+ inputSchema: {
1540
+ type: 'object',
1541
+ properties: {
1542
+ url: { type: 'string', description: 'Public https:// PDF URL.' },
1543
+ },
1544
+ required: ['url'],
1545
+ },
1546
+ },
1547
+ {
1548
+ name: 'contextguard_scan_public_repo',
1549
+ description: 'Scans a public GitHub owner/repo for CLAUDE.md, AGENTS.md, .cursorrules, and copilot-instructions.md token burn and hidden bidi Unicode prompt-injection risks.',
1550
+ annotations: { title: 'Scan Public GitHub Repo for Token Burn & Unicode', ...READ_ONLY_WEB },
1551
+ inputSchema: {
1552
+ type: 'object',
1553
+ properties: {
1554
+ repo: { type: 'string', description: 'Public GitHub owner/repo slug.' },
1555
+ },
1556
+ required: ['repo'],
1557
+ },
1558
+ },
1559
+ {
1560
+ name: 'ada_inspect_acroform_and_vpat',
1561
+ description: 'Inspects a public https:// fillable PDF form (/AcroForm widgets, non-empty /TU tooltips, /Tabs /S keyboard order, /XFA lockout) and generates a 14-criterion ITI VPAT 2.5 Automated Technical Self-Assessment Draft for Revised Section 508, HHS Section 504 (91 FR 25496), DOJ ADA Title II, and Colorado HB21-1110.',
1562
+ annotations: { title: 'Inspect Fillable PDF AcroForm & Generate VPAT 2.5 Draft', ...READ_ONLY_WEB },
1563
+ inputSchema: {
1564
+ type: 'object',
1565
+ properties: {
1566
+ url: { type: 'string', description: 'Public https:// PDF URL to inspect.' },
1567
+ productName: { type: 'string', description: 'Optional document or product name for the VPAT 2.5 header.' },
1568
+ proKey: { type: 'string', description: 'Optional Second Foreman SC1. Pro key to unlock all 14 criteria (.md + .csv).' },
1569
+ },
1570
+ required: ['url'],
1571
+ },
1572
+ },
1573
+ {
1574
+ name: 'ada_audit_eaa_en301549',
1575
+ description: 'Audits a public https:// webpage (EN 301 549 Clause 9 WCAG 2.2 AA + linked PDFs) or https:// PDF document (Clause 10 Non-Web Documents + ISO 14289-1) against the European Accessibility Act (Directive (EU) 2019/882) and EN 301 549 (v3.2.1 OJEU & v4.1.1 Sept 2026), generating a 16-clause Annex V Automated Technical Self-Assessment Draft.',
1576
+ annotations: { title: 'Audit EU EAA & EN 301 549 (v3.2.1 & v4.1.1) Web + PDF', ...READ_ONLY_WEB },
1577
+ inputSchema: {
1578
+ type: 'object',
1579
+ properties: {
1580
+ url: { type: 'string', description: 'Public https:// webpage or PDF URL to audit.' },
1581
+ orgName: { type: 'string', description: 'Optional service provider / organization name for Annex V draft.' },
1582
+ contactEmail: { type: 'string', description: 'Optional accessibility feedback contact email for Annex V draft.' },
1583
+ proKey: { type: 'string', description: 'Optional Second Foreman SC1. Pro key to unlock all 16 clauses (.md + .csv).' },
1584
+ },
1585
+ required: ['url'],
1586
+ },
1587
+ },
1588
+ {
1589
+ name: 'epa608_calculate_superheat_subcooling',
1590
+ description: 'Calculates NIST REFPROP 10 / Chemours R-454B, R-32, R-410A, and R-22 vapor dew-point superheat, liquid bubble-point subcooling, zeotropic glide, ACCA fixed-orifice target superheat, US Standard Atmosphere elevation correction, and HVAC charge diagnosis.',
1591
+ annotations: { title: 'Calculate R-454B / R-32 Superheat, Subcooling & Glide', ...READ_ONLY_LOCAL },
1592
+ inputSchema: {
1593
+ type: 'object',
1594
+ properties: {
1595
+ refrigerant: { type: 'string', enum: ['R-454B', 'R-32', 'R-410A', 'R-22'] },
1596
+ meteringDevice: { type: 'string', enum: ['txv', 'fixed_orifice'] },
1597
+ suctionPsig: { type: 'number', description: 'Measured vapor/suction gauge pressure in psig.' },
1598
+ suctionLineTempF: { type: 'number', description: 'Measured suction line temperature in °F.' },
1599
+ liquidPsig: { type: 'number', description: 'Measured liquid/head gauge pressure in psig.' },
1600
+ liquidLineTempF: { type: 'number', description: 'Measured liquid line temperature in °F.' },
1601
+ indoorWetBulbF: { type: 'number', description: 'Return air indoor wet-bulb °F (default 63, for fixed orifice).' },
1602
+ outdoorDryBulbF: { type: 'number', description: 'Condenser entering air outdoor dry-bulb °F (default 85).' },
1603
+ targetSubcoolingF: { type: 'number', description: 'OEM nameplate target subcooling °F for TXV/EEV (default 10).' },
1604
+ elevationFt: { type: 'number', description: 'Jobsite elevation above sea level in feet (default 0).' },
1605
+ proKey: { type: 'string', description: 'Optional Second Foreman SC1. Pro key for downloadable commissioning CSV.' },
1606
+ },
1607
+ required: ['suctionPsig', 'suctionLineTempF', 'liquidPsig', 'liquidLineTempF'],
1608
+ },
1609
+ },
1610
+ {
1611
+ name: 'ada_triage_28cfr35_exceptions',
1612
+ description: 'Evaluates DOJ ADA Title II Subpart H (28 CFR §§ 35.104, 35.201(a)-(e), 35.204, 35.205 & 91 FR 20902) 5 content exceptions (4-condition archived web content, preexisting PDFs/docs, independent 3rd-party posts, individualized secured docs, preexisting social posts), § 35.204 undue-burden procedural completeness, § 35.205 4-factor minimal-impact equivalence, and active PDF/UA-1 remediation budget. Operational triage worksheet only — not legal advice.',
1613
+ annotations: { title: 'Triage DOJ 28 CFR 35.201 Exceptions & 35.204 Undue Burden', ...READ_ONLY_LOCAL },
1614
+ inputSchema: {
1615
+ type: 'object',
1616
+ properties: {
1617
+ entityName: { type: 'string', description: 'Public entity name (city, county, school district, state agency, or special district).' },
1618
+ entityTier: { type: 'string', enum: ['pop_50k_plus', 'pop_under_50k', 'special_district'] },
1619
+ contentCategory: {
1620
+ type: 'string',
1621
+ enum: [
1622
+ 'archived_web_content',
1623
+ 'conventional_doc',
1624
+ 'third_party_content',
1625
+ 'individualized_secured_doc',
1626
+ 'preexisting_social_post',
1627
+ 'active_web_or_doc',
1628
+ ],
1629
+ },
1630
+ createdBeforeComplianceDate: { type: 'boolean', description: 'True if created/posted before the applicable Subpart H compliance date (April 26, 2027 or April 26, 2028 per 91 FR 20902).' },
1631
+ usedForActiveServiceOrProgram: { type: 'boolean', description: 'True if currently used by individuals to apply for, gain access to, or participate in public services/programs.' },
1632
+ retainedExclusivelyForReference: { type: 'boolean', description: 'True if retained solely for reference, research, or recordkeeping (§ 35.104(2)).' },
1633
+ storedInClearlyIdentifiedArchive: { type: 'boolean', description: 'True if kept in a dedicated area clearly identified as archived (§ 35.104(3)).' },
1634
+ unalteredSinceArchiving: { type: 'boolean', description: 'True if unaltered and unupdated since archiving (§ 35.104(4)).' },
1635
+ underContractualOrLicensingArrangement: { type: 'boolean', description: 'True if third-party content is posted under contract, license, or vendor arrangement (§ 35.201(c)).' },
1636
+ individualizedToSpecificPersonOrAccount: { type: 'boolean', description: 'True if conventional document pertains to a specific person, property, or account (§ 35.201(d)).' },
1637
+ passwordProtectedOrSecured: { type: 'boolean', description: 'True if document is password-protected or behind an authenticated portal (§ 35.201(d)).' },
1638
+ evaluate35204UndueBurden: { type: 'boolean', description: 'Evaluate 28 CFR § 35.204 undue financial/administrative burden procedural checklist.' },
1639
+ allProgramResourcesConsidered: { type: 'boolean', description: '§ 35.204: All funding & operational resources of the program/service considered.' },
1640
+ headOfEntityOrDesigneeNamed: { type: 'boolean', description: '§ 35.204: Head of public entity or formal designee identified.' },
1641
+ writtenStatementOfReasonsPrepared: { type: 'boolean', description: '§ 35.204: Formal written statement of reasons prepared.' },
1642
+ maximumExtentAlternativeActionDefined: { type: 'boolean', description: '§ 35.204: Alternative action providing maximum-extent disability access defined.' },
1643
+ evaluate35205MinimalImpact: { type: 'boolean', description: 'Evaluate 28 CFR § 35.205 4-factor minimal-impact equivalence.' },
1644
+ timelinessEquivalent: { type: 'boolean', description: '§ 35.205: Substantially equivalent timeliness.' },
1645
+ privacyEquivalent: { type: 'boolean', description: '§ 35.205: Substantially equivalent privacy.' },
1646
+ independenceEquivalent: { type: 'boolean', description: '§ 35.205: Substantially equivalent independence.' },
1647
+ easeOfUseEquivalent: { type: 'boolean', description: '§ 35.205: Substantially equivalent ease of use.' },
1648
+ docCount: { type: 'number', description: 'Number of documents in evaluated batch (default 25).' },
1649
+ avgPagesPerDoc: { type: 'number', description: 'Average pages per document (default 5).' },
1650
+ scannedSharePct: { type: 'number', description: 'Percentage of scanned image-only pages (default 20).' },
1651
+ acroFormCount: { type: 'number', description: 'Number of fillable forms in batch (default 0).' },
1652
+ proKey: { type: 'string', description: 'Optional Second Foreman SC1. Pro key to unlock full .md record & .csv export.' },
1653
+ },
1654
+ },
1655
+ },
1656
+ {
1657
+ name: 'ada_score_state_procurement_pdaa',
1658
+ description:
1659
+ 'Scores vendor ICT accessibility bid readiness across Texas DIR 1 TAC Ch. 206 & 213 (6-criterion PDAA self-assessment, 6-section VADSIR dev questionnaire, >$500k third-party testing gate), Washington WaTech USER-01 WCAG 2.2 AA, Virginia HB2541, and Colorado HB21-1110.',
1660
+ annotations: { title: 'Score State Procurement PDAA, VADSIR & WCAG 2.2 Readiness', ...READ_ONLY_LOCAL },
1661
+ inputSchema: {
1662
+ type: 'object',
1663
+ properties: {
1664
+ vendorName: { type: 'string', description: 'Bidder or vendor organization name.' },
1665
+ targetState: {
1666
+ type: 'string',
1667
+ enum: ['TX_DIR', 'WA_USER_01', 'VA_HB2541', 'CO_HB21_1110', 'MULTI_STATE'],
1668
+ description: 'Target state ICT procurement accessibility regime.',
1669
+ },
1670
+ contractValueUsd: { type: 'number', description: 'Estimated contract or RFO ceiling in USD.' },
1671
+ includesDevServices: { type: 'boolean', description: 'True if web, mobile, custom UI, or software development services are in scope.' },
1672
+ includesCotsOrSaas: { type: 'boolean', description: 'True if COTS software or SaaS products are in scope.' },
1673
+ hasVpat25: { type: 'boolean', description: 'True if a current ITI VPAT 2.4+ / 2.5 ACR is completed.' },
1674
+ vadsirPrepared: { type: 'boolean', description: 'True if a 6-section VADSIR narrative is prepared.' },
1675
+ thirdPartyTestingPlanned: { type: 'boolean', description: 'True if independent third-party accessibility testing is planned/budgeted.' },
1676
+ wcagTargetTested: {
1677
+ type: 'string',
1678
+ enum: ['wcag22_aa', 'wcag21_aa', 'untested'],
1679
+ description: 'WCAG conformance baseline tested across deliverables.',
1680
+ },
1681
+ pdaaPolicy: { type: 'number', minimum: 0, maximum: 3, description: 'PDAA Criterion 1 (ICT Accessibility Policy): 0=Missing, 1=Launch, 2=Integrate, 3=Optimize.' },
1682
+ pdaaOrgStructure: { type: 'number', minimum: 0, maximum: 3, description: 'PDAA Criterion 2 (Governance & Org Structure): 0..3.' },
1683
+ pdaaSdlcIntegration: { type: 'number', minimum: 0, maximum: 3, description: 'PDAA Criterion 3 (SDLC & Procurement Integration): 0..3.' },
1684
+ pdaaCorrectiveProcess: { type: 'number', minimum: 0, maximum: 3, description: 'PDAA Criterion 4 (Defect & Alternate-Access Process): 0..3.' },
1685
+ pdaaStaffSkills: { type: 'number', minimum: 0, maximum: 3, description: 'PDAA Criterion 5 (Staff Accessibility Skills & Training): 0..3.' },
1686
+ pdaaPublicInfo: { type: 'number', minimum: 0, maximum: 3, description: 'PDAA Criterion 6 (Customer-Facing Policy & ACR Info): 0..3.' },
1687
+ untaggedPdfCount: { type: 'number', description: 'Optional count of untagged proposal or product PDFs requiring PDF/UA-1 remediation.' },
1688
+ avgPagesPerPdf: { type: 'number', description: 'Optional average pages per PDF (default 5).' },
1689
+ proKey: {
1690
+ type: 'string',
1691
+ description: 'Optional Second Foreman SC1. Pro license key to unlock the full PDAA + 6-Section VADSIR .md packet and .csv scoring matrix.',
1692
+ },
1693
+ },
1694
+ required: ['targetState'],
1695
+ },
1696
+ },
1697
+ {
1698
+ name: 'epa608_calculate_a2l_room_charge_limit',
1699
+ description:
1700
+ 'Calculates UL 60335-2-40 (4th Ed. Annex GG & LL) and ASHRAE 15-2022 / 15.2 Class A2L refrigerant room-area limits (ducted TAmin Eq. GG.15DV & non-ducted Amin Annex GG.2), total single-circuit charge (factory + extra line set), mandatory RDS circulation airflow (Qmin CFM Eq. GG.17DV), motorized zoning damper isolation checks, and high-altitude AF multipliers for R-454B, R-32, R-454A, R-454C, R-1234yf, and R-1234ze(E).',
1701
+ annotations: { title: 'Calculate Class A2L Room Area, Charge Limit & RDS Qmin CFM', ...READ_ONLY_LOCAL },
1702
+ inputSchema: {
1703
+ type: 'object',
1704
+ properties: {
1705
+ projectOrSiteName: { type: 'string', description: 'Optional jobsite, RTU, or split-system identifier.' },
1706
+ refrigerant: {
1707
+ type: 'string',
1708
+ enum: ['R-454B', 'R-32', 'R-454A', 'R-454C', 'R-1234yf', 'R-1234ze(E)'],
1709
+ description: 'Class A2L refrigerant (default R-454B).',
1710
+ },
1711
+ systemType: {
1712
+ type: 'string',
1713
+ enum: ['ducted', 'non_ducted'],
1714
+ description: 'Air distribution type: ducted (TAmin Eq. GG.15DV) or non_ducted (Amin Annex GG.2).',
1715
+ },
1716
+ releaseHeightPreset: {
1717
+ type: 'string',
1718
+ enum: ['floor', 'window', 'wall', 'ceiling'],
1719
+ description: 'Non-ducted indoor release height h0 preset (floor=0.6m, window=1.0m, wall=1.8m, ceiling=2.2m).',
1720
+ },
1721
+ factoryChargeLb: { type: 'number', description: 'Condenser factory nameplate charge in lb (> 0).' },
1722
+ totalLineSetFt: { type: 'number', description: 'Total installed liquid line-set length in ft (>= 0, default 15).' },
1723
+ factoryPrechargeFt: { type: 'number', description: 'Factory precharged line-set length in ft (>= 0, default 15).' },
1724
+ extraOzPerFt: { type: 'number', description: 'Added liquid line-set trim factor in oz/ft (>= 0, default 0.6).' },
1725
+ conditionedAreaFt2: { type: 'number', description: 'Total conditioned floor area served by the system in sq ft (> 0).' },
1726
+ smallestZoneAreaFt2: { type: 'number', description: 'Smallest isolated zone floor area in sq ft (> 0) when motorized zone dampers are present.' },
1727
+ elevationFt: { type: 'number', description: 'Jobsite elevation above sea level in ft (>= 0, default 0).' },
1728
+ hasRdsInstalled: { type: 'boolean', description: 'True if an integral UL 60335-2-40 Annex LL Refrigerant Detection System (RDS) is installed.' },
1729
+ actualMitigationCfm: { type: 'number', description: 'Configured indoor circulation blower RDS mitigation airflow in CFM (>= 0).' },
1730
+ hasZoneDampers: { type: 'boolean', description: 'True if motorized zone dampers are installed on supply trunks.' },
1731
+ rdsOpensAllZoneDampers: { type: 'boolean', description: 'True if the zone control board drives all dampers 100% open upon RDS alarm.' },
1732
+ hasLowDuctOpeningUnder5_9Ft: { type: 'boolean', description: 'True if any supply/return opening is < 5.9 ft (1.8 m) above the floor.' },
1733
+ hasFalseCeilingReturnPlenum: { type: 'boolean', description: 'True if an unducted false-ceiling return air plenum is used.' },
1734
+ proKey: {
1735
+ type: 'string',
1736
+ description: 'Optional Second Foreman SC1. Pro license key to unlock the full 8-gate commissioning .md permit sheet and .csv schedule.',
1737
+ },
1738
+ },
1739
+ required: ['refrigerant'],
1740
+ },
1741
+ },
1742
+ ],
1743
+ },
1744
+ };
1745
+ }
1746
+
1747
+ if (method === 'tools/call') {
1748
+ const toolName = params?.name || '';
1749
+ const toolArgs = params?.arguments || {};
1750
+ let { isPro } = await resolveProStatus();
1751
+ if (!isPro && typeof toolArgs.proKey === 'string' && toolArgs.proKey.trim()) {
1752
+ const chk = await verifyContextGuardLicense(toolArgs.proKey.trim());
1753
+ isPro = Boolean(chk.valid);
1754
+ }
1755
+ if (options.isProOverride === true) isPro = true;
1756
+
1757
+ try {
1758
+ if (toolName === 'contextguard_audit_workspace') {
1759
+ const entries = collectWorkspaceEntries(toolArgs.directory || '.');
1760
+ const audit = auditContextBundle(entries, { isPro });
1761
+ return {
1762
+ jsonrpc: '2.0',
1763
+ id,
1764
+ result: {
1765
+ content: [{ type: 'text', text: JSON.stringify(audit, null, 2) }],
1766
+ },
1767
+ };
1768
+ }
1769
+
1770
+ if (toolName === 'contextguard_slim_boot_card') {
1771
+ const entries = collectWorkspaceEntries(toolArgs.directory || '.');
1772
+ const slim = compileSlimArtifacts(entries, { isPro });
1773
+ return {
1774
+ jsonrpc: '2.0',
1775
+ id,
1776
+ result: {
1777
+ content: [
1778
+ {
1779
+ type: 'text',
1780
+ text: `${slim.startMd}\n---\n# Suggested .claudeignore\n${slim.claudeIgnore}`,
1781
+ },
1782
+ ],
1783
+ },
1784
+ };
1785
+ }
1786
+
1787
+ if (toolName === 'contextguard_compress_web_doc') {
1788
+ const res = compressWebDocument(toolArgs.html_or_text || '', {
1789
+ budgetTokens: Number(toolArgs.budget_tokens) || 3000,
1790
+ isPro,
1791
+ });
1792
+ return {
1793
+ jsonrpc: '2.0',
1794
+ id,
1795
+ result: {
1796
+ content: [{ type: 'text', text: res.markdown }],
1797
+ },
1798
+ };
1799
+ }
1800
+
1801
+ if (toolName === 'bidradar_search_public_bids') {
1802
+ const qs = new URLSearchParams();
1803
+ if (toolArgs.category) qs.set('category', String(toolArgs.category));
1804
+ if (toolArgs.query) qs.set('q', String(toolArgs.query));
1805
+ const headers = { accept: 'application/json' };
1806
+ const proKey = process.env.SECOND_FOREMAN_PRO_KEY || '';
1807
+ if (proKey) headers.authorization = `Bearer ${proKey}`;
1808
+ const url = `https://secondforeman.com/api/bidradar${qs.toString() ? `?${qs.toString()}` : ''}`;
1809
+ const fetchFn = options.fetchImpl || globalThis.fetch;
1810
+ const resp = await fetchFn(url, { headers });
1811
+ const data = await resp.json();
1812
+ return {
1813
+ jsonrpc: '2.0',
1814
+ id,
1815
+ result: {
1816
+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
1817
+ },
1818
+ };
1819
+ }
1820
+
1821
+ if (toolName === 'ada_estimate_pdf_ua_remediation') {
1822
+ const out = estimateAdaPdfRemediation(toolArgs);
1823
+ return {
1824
+ jsonrpc: '2.0',
1825
+ id,
1826
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
1827
+ };
1828
+ }
1829
+
1830
+ if (toolName === 'ada_audit_public_webpage') {
1831
+ const out = await auditPublicWebpageWcagPdf(toolArgs.url, options.fetchImpl || globalThis.fetch);
1832
+ return {
1833
+ jsonrpc: '2.0',
1834
+ id,
1835
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
1836
+ };
1837
+ }
1838
+
1839
+ if (toolName === 'epa608_calculate_leak_rate') {
1840
+ const out = calculateEpa608LeakRate(toolArgs);
1841
+ return {
1842
+ jsonrpc: '2.0',
1843
+ id,
1844
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
1845
+ };
1846
+ }
1847
+
1848
+ if (toolName === 'govcon_calculate_gpc_unison_margin') {
1849
+ for (const reqNum of ['sellerBidUsd', 'supplierCogsUsd']) {
1850
+ if (typeof toolArgs[reqNum] !== 'number' || !Number.isFinite(toolArgs[reqNum])) {
1851
+ throw new Error(`Invalid params: "${reqNum}" is required and must be a finite number.`);
1852
+ }
1853
+ }
1854
+ const round2 = (n) => Math.round((Number(n) + Number.EPSILON) * 100) / 100;
1855
+ const bid = Math.max(1, round2(toolArgs.sellerBidUsd));
1856
+ const cogs = Math.max(0, round2(toolArgs.supplierCogsUsd));
1857
+ const ship = Math.max(0, round2(Number(toolArgs.shippingFobDestUsd ?? 0)));
1858
+ const feePct = Math.min(3.93, Math.max(0, Number(toolArgs.unisonFeePct ?? 3.0)));
1859
+ const f = feePct / 100;
1860
+ const method = ['GPC_CARD', 'ACH_EFT', 'OK_PCARD_DVBE'].includes(toolArgs.paymentMethod) ? toolArgs.paymentMethod : 'GPC_CARD';
1861
+ const targetMargin = Math.min(80, Math.max(1, Number(toolArgs.targetMarginPct ?? 20)));
1862
+ const minProfit = Math.max(0, Number(toolArgs.minProfitUsd ?? 1500));
1863
+
1864
+ const totalCogsUsd = round2(cogs + ship);
1865
+ const buyerAwardTotalUsd = round2(bid * (1 + f));
1866
+ const unisonFeeUsd = round2(buyerAwardTotalUsd - bid);
1867
+ const isCard = method === 'GPC_CARD' || method === 'OK_PCARD_DVBE';
1868
+ const stripeCardFeeUsd = isCard ? round2(buyerAwardTotalUsd * 0.029 + 0.3) : 0;
1869
+ const netProfitUsd = round2(bid - stripeCardFeeUsd - totalCogsUsd);
1870
+ const netMarginPct = Number(((netProfitUsd / bid) * 100).toFixed(2));
1871
+ const k = isCard ? 1 - 0.029 * (1 + f) : 1;
1872
+ const fixedCard = isCard ? 0.3 : 0;
1873
+ const recommendedSellerBidUsd = round2(
1874
+ Math.max((totalCogsUsd + minProfit + fixedCard) / k, (totalCogsUsd + fixedCard) / Math.max(0.05, k - targetMargin / 100))
1875
+ );
1876
+ const out = {
1877
+ sellerBidUsd: bid,
1878
+ supplierCogsUsd: cogs,
1879
+ shippingFobDestUsd: ship,
1880
+ totalCogsUsd,
1881
+ unisonFeePct: feePct,
1882
+ unisonFeeUsd,
1883
+ buyerAwardTotalUsd,
1884
+ paymentMethod: method,
1885
+ stripeCardFeeUsd,
1886
+ netProfitUsd,
1887
+ netMarginPct,
1888
+ recommendedSellerBidUsd,
1889
+ fitsFederalGpc15k: buyerAwardTotalUsd <= 15000,
1890
+ fitsOklahomaPcard25k: buyerAwardTotalUsd <= 25000,
1891
+ passesProfitFloor: netProfitUsd >= minProfit && netMarginPct >= targetMargin,
1892
+ calculatorUrl: 'https://secondforeman.com/bidradar/unison-gpc-margin-calculator/',
1893
+ };
1894
+ return {
1895
+ jsonrpc: '2.0',
1896
+ id,
1897
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
1898
+ };
1899
+ }
1900
+
1901
+ if (toolName === 'ada_inspect_public_pdf_ua') {
1902
+ let currentUrl = validateSafePublicHttpsUrl(toolArgs.url);
1903
+ const fetchFn = options.fetchImpl || globalThis.fetch;
1904
+ const pdfCtrl = new AbortController();
1905
+ const pdfTimer = setTimeout(() => pdfCtrl.abort(), 6000);
1906
+ let bytes;
1907
+ try {
1908
+ let resp;
1909
+ for (let hop = 0; hop <= 3; hop++) {
1910
+ resp = await fetchFn(currentUrl.toString(), {
1911
+ method: 'GET',
1912
+ redirect: 'manual',
1913
+ headers: {
1914
+ accept: 'application/pdf,*/*;q=0.8',
1915
+ 'user-agent': 'SecondForeman-PDFUA-Inspector/1.3 (+https://secondforeman.com/bidradar/pdf-ua-file-inspector/)',
1916
+ },
1917
+ signal: pdfCtrl.signal,
1918
+ });
1919
+ if (resp.status >= 300 && resp.status < 400) {
1920
+ const loc = resp.headers.get('location');
1921
+ if (!loc || hop === 3) throw new Error('Too many or invalid redirects.');
1922
+ currentUrl = validateSafePublicHttpsUrl(new URL(loc, currentUrl).toString());
1923
+ continue;
1924
+ }
1925
+ break;
1926
+ }
1927
+ if (!resp || !resp.ok) throw new Error(`Upstream PDF returned HTTP ${resp ? resp.status : 'error'}`);
1928
+
1929
+ const maxPdfBytes = 2097152;
1930
+ if (!resp.body || typeof resp.body.getReader !== 'function') {
1931
+ const ab = await resp.arrayBuffer();
1932
+ bytes = new Uint8Array(ab.byteLength > maxPdfBytes ? ab.slice(0, maxPdfBytes) : ab);
1933
+ } else {
1934
+ const reader = resp.body.getReader();
1935
+ const chunks = [];
1936
+ let total = 0;
1937
+ try {
1938
+ while (total < maxPdfBytes) {
1939
+ const { done, value } = await reader.read();
1940
+ if (done || !value) break;
1941
+ const take = value.byteLength > maxPdfBytes - total ? value.subarray(0, maxPdfBytes - total) : value;
1942
+ chunks.push(take);
1943
+ total += take.byteLength;
1944
+ if (total >= maxPdfBytes) {
1945
+ await reader.cancel().catch(() => {});
1946
+ break;
1947
+ }
1948
+ }
1949
+ } finally {
1950
+ reader.releaseLock();
1951
+ }
1952
+ bytes = new Uint8Array(total);
1953
+ let off = 0;
1954
+ for (const c of chunks) {
1955
+ bytes.set(c, off);
1956
+ off += c.byteLength;
1957
+ }
1958
+ }
1959
+ } finally {
1960
+ clearTimeout(pdfTimer);
1961
+ }
1962
+
1963
+ let raw = '';
1964
+ for (let i = 0; i < bytes.length; i += 32768) {
1965
+ raw += String.fromCharCode(...bytes.subarray(i, Math.min(bytes.length, i + 32768)));
1966
+ }
1967
+ const mVer = raw.slice(0, 1024).match(/%PDF-(\d\.\d)/);
1968
+ if (!mVer) throw new Error('Target URL is not a valid PDF document.');
1969
+
1970
+ const inflated = inflatePdfBufferFlate(bytes, raw);
1971
+ const fullText = inflated ? `${raw}\n${inflated}` : raw;
1972
+
1973
+ const isEncrypted = /\/Encrypt\b/.test(raw);
1974
+ const hasMarkedTrue = /\/Marked\s+true\b/.test(fullText);
1975
+ const hasStructTree = /\/StructTreeRoot\b/.test(fullText);
1976
+ const hasPdfUaXmp = /pdfuaid:part(?:\s*=\s*["']1["']|\s*>\s*1\s*<)/i.test(fullText);
1977
+ const hasLang = /\/Lang\s*\(\s*[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?\s*\)/.test(fullText);
1978
+ const hasDisplayDocTitle = /\/DisplayDocTitle\s+true\b/.test(fullText);
1979
+ const hasFont = /\/Type\s*\/Font\b|\/BaseFont\s*\//.test(fullText);
1980
+ const hasImageXObject = /\/Subtype\s*\/Image\b/.test(fullText);
1981
+ const hasAcroForm = /\/AcroForm\b/.test(fullText);
1982
+ const hasEmptyFieldsArray = /\/Fields\s*\[\s*\]/.test(fullText);
1983
+ const hasTabsStructure = /\/Tabs\s*\/S\b/.test(fullText);
1984
+ const isScannedLikely = !hasFont && hasImageXObject;
1985
+ let pageCount = 0;
1986
+ for (const m of fullText.matchAll(/\/Type\s*\/Pages\b[\s\S]{0,220}?\/Count\s+(\d+)/g)) {
1987
+ const n = Number.parseInt(m[1], 10);
1988
+ if (Number.isFinite(n) && n > pageCount) pageCount = n;
1989
+ }
1990
+ if (!pageCount) {
1991
+ for (const m of fullText.matchAll(/\/Count\s+(\d+)[\s\S]{0,160}?\/Type\s*\/Pages\b/g)) {
1992
+ const n = Number.parseInt(m[1], 10);
1993
+ if (Number.isFinite(n) && n > pageCount) pageCount = n;
1994
+ }
1995
+ }
1996
+ if (!pageCount) pageCount = Math.max(1, (fullText.match(/\/Type\s*\/Page\b(?!s)/g) || []).length);
1997
+ const pdfUaScore =
1998
+ (!isEncrypted ? 15 : 10) +
1999
+ (hasMarkedTrue ? 20 : 0) +
2000
+ (hasStructTree ? 20 : 0) +
2001
+ (hasPdfUaXmp ? 15 : 0) +
2002
+ (hasLang ? 10 : 0) +
2003
+ (hasDisplayDocTitle ? 10 : 0) +
2004
+ (!isScannedLikely && hasFont ? 10 : 0);
2005
+ const formAddon = hasAcroForm && !hasEmptyFieldsArray && !hasTabsStructure ? 25 : 0;
2006
+ const out = {
2007
+ auditedUrl: currentUrl.toString(),
2008
+ pdfVersion: mVer[1],
2009
+ pageCount,
2010
+ pdfUaScore,
2011
+ isScannedLikely,
2012
+ hasMarkedTrue,
2013
+ hasStructTree,
2014
+ hasPdfUaXmp,
2015
+ hasLang,
2016
+ hasDisplayDocTitle,
2017
+ estimatedRemediationUsd:
2018
+ pdfUaScore === 100 && formAddon === 0
2019
+ ? 0
2020
+ : Math.round((pageCount * (isScannedLikely ? 3.0 : 1.5) + formAddon) * 100) / 100,
2021
+ inspectorUrl: 'https://secondforeman.com/bidradar/pdf-ua-file-inspector/',
2022
+ };
2023
+ return {
2024
+ jsonrpc: '2.0',
2025
+ id,
2026
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2027
+ };
2028
+ }
2029
+
2030
+ if (toolName === 'contextguard_scan_public_repo') {
2031
+ const cleanRepo = String(toolArgs.repo || '')
2032
+ .trim()
2033
+ .replace(/^https?:\/\/github\.com\//i, '')
2034
+ .replace(/\/+$/, '')
2035
+ .replace(/\.git$/i, '');
2036
+ const parts = cleanRepo.split('/');
2037
+ if (
2038
+ parts.length !== 2 ||
2039
+ !/^[A-Za-z0-9_.-]{1,100}$/.test(parts[0]) ||
2040
+ !/^[A-Za-z0-9_.-]{1,100}$/.test(parts[1]) ||
2041
+ parts[0] === '.' || parts[0] === '..' || parts[1] === '.' || parts[1] === '..'
2042
+ ) {
2043
+ throw new Error('Invalid params: "repo" must match strict owner/repo syntax.');
2044
+ }
2045
+ const candidatePaths = ['AGENTS.md', 'CLAUDE.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md'];
2046
+ const fetchFn = options.fetchImpl || globalThis.fetch;
2047
+ const filesFound = [];
2048
+ let unicodeAlertCount = 0;
2049
+ const repoCtrl = new AbortController();
2050
+ const repoTimer = setTimeout(() => repoCtrl.abort(), 6000);
2051
+ try {
2052
+ await Promise.all(
2053
+ candidatePaths.map(async (relPath) => {
2054
+ const rawUrl = `https://raw.githubusercontent.com/${parts[0]}/${parts[1]}/HEAD/${relPath}`;
2055
+ try {
2056
+ const r = await fetchFn(rawUrl, { method: 'GET', redirect: 'manual', signal: repoCtrl.signal });
2057
+ if (r && r.status === 200) {
2058
+ const txt = await readStreamCappedUtf8(r, 262144);
2059
+ const bytes = Buffer.byteLength(txt, 'utf8');
2060
+ const bodyNoBom = txt.startsWith('\uFEFF') ? txt.slice(1) : txt;
2061
+ const bidi = bodyNoBom.match(/[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g);
2062
+ const alerts = bidi ? bidi.length : 0;
2063
+ unicodeAlertCount += alerts;
2064
+ filesFound.push({ path: relPath, bytes, unicodeAlerts: alerts });
2065
+ }
2066
+ } catch {
2067
+ /* ignore */
2068
+ }
2069
+ })
2070
+ );
2071
+ } finally {
2072
+ clearTimeout(repoTimer);
2073
+ }
2074
+ filesFound.sort((a, b) => a.path.localeCompare(b.path));
2075
+ const out = {
2076
+ repo: cleanRepo,
2077
+ filesFound,
2078
+ totalBytes: filesFound.reduce((s, f) => s + f.bytes, 0),
2079
+ unicodeAlertCount,
2080
+ scannerUrl: 'https://secondforeman.com/contextguard/repo-scanner/',
2081
+ };
2082
+ return {
2083
+ jsonrpc: '2.0',
2084
+ id,
2085
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2086
+ };
2087
+ }
2088
+
2089
+ if (toolName === 'ada_inspect_acroform_and_vpat') {
2090
+ let currentUrl = validateSafePublicHttpsUrl(toolArgs.url);
2091
+ const fetchFn = options.fetchImpl || globalThis.fetch;
2092
+ const vpatCtrl = new AbortController();
2093
+ const vpatTimer = setTimeout(() => vpatCtrl.abort(), 6000);
2094
+ let bytes;
2095
+ try {
2096
+ let resp;
2097
+ for (let hop = 0; hop <= 3; hop++) {
2098
+ resp = await fetchFn(currentUrl.toString(), {
2099
+ method: 'GET',
2100
+ redirect: 'manual',
2101
+ headers: {
2102
+ accept: 'application/pdf,*/*;q=0.8',
2103
+ 'user-agent': 'SecondForeman-VPAT-AcroForm-Auditor/1.4 (+https://secondforeman.com/bidradar/vpat-acroform-auditor/)',
2104
+ },
2105
+ signal: vpatCtrl.signal,
2106
+ });
2107
+ if (resp.status >= 300 && resp.status < 400) {
2108
+ const loc = resp.headers.get('location');
2109
+ if (!loc || hop === 3) throw new Error('Too many or invalid redirects.');
2110
+ currentUrl = validateSafePublicHttpsUrl(new URL(loc, currentUrl).toString());
2111
+ continue;
2112
+ }
2113
+ break;
2114
+ }
2115
+ if (!resp || !resp.ok) throw new Error(`Upstream PDF returned HTTP ${resp ? resp.status : 'error'}`);
2116
+
2117
+ const maxPdfBytes = 2097152;
2118
+ if (!resp.body || typeof resp.body.getReader !== 'function') {
2119
+ const ab = await resp.arrayBuffer();
2120
+ bytes = new Uint8Array(ab.byteLength > maxPdfBytes ? ab.slice(0, maxPdfBytes) : ab);
2121
+ } else {
2122
+ const reader = resp.body.getReader();
2123
+ const chunks = [];
2124
+ let total = 0;
2125
+ try {
2126
+ while (total < maxPdfBytes) {
2127
+ const { done, value } = await reader.read();
2128
+ if (done || !value) break;
2129
+ const take = value.byteLength > maxPdfBytes - total ? value.subarray(0, maxPdfBytes - total) : value;
2130
+ chunks.push(take);
2131
+ total += take.byteLength;
2132
+ if (total >= maxPdfBytes) {
2133
+ await reader.cancel().catch(() => {});
2134
+ break;
2135
+ }
2136
+ }
2137
+ } finally {
2138
+ reader.releaseLock();
2139
+ }
2140
+ bytes = new Uint8Array(total);
2141
+ let off = 0;
2142
+ for (const c of chunks) {
2143
+ bytes.set(c, off);
2144
+ off += c.byteLength;
2145
+ }
2146
+ }
2147
+ } finally {
2148
+ clearTimeout(vpatTimer);
2149
+ }
2150
+
2151
+ let raw = '';
2152
+ for (let i = 0; i < bytes.length; i += 32768) {
2153
+ raw += String.fromCharCode(...bytes.subarray(i, Math.min(bytes.length, i + 32768)));
2154
+ }
2155
+ const mVer = raw.slice(0, 1024).match(/%PDF-(\d\.\d)/);
2156
+ if (!mVer) throw new Error('Target URL did not return a valid %PDF-1.x/2.0 document.');
2157
+ const pdfVersion = mVer[1];
2158
+ const inflated = inflatePdfBufferFlate(bytes, raw);
2159
+ const fullText = inflated ? `${raw}\n${inflated}` : raw;
2160
+
2161
+ const rawSeg = currentUrl.pathname.split('/').filter(Boolean).pop() || 'remote-form.pdf';
2162
+ let fileName = rawSeg;
2163
+ try {
2164
+ fileName = decodeURIComponent(rawSeg);
2165
+ } catch {
2166
+ fileName = rawSeg;
2167
+ }
2168
+ const productName = String(toolArgs.productName || '').trim() || fileName;
2169
+
2170
+ const isEncrypted = /\/Encrypt\b/.test(raw);
2171
+ const hasMarkedTrue = /\/MarkInfo\s*<<[\s\S]{0,180}?\/Marked\s+true\b/.test(fullText) || /\/Marked\s+true\b/.test(fullText);
2172
+ const hasStructTree = /\/StructTreeRoot\b/.test(fullText);
2173
+ const hasPdfUaXmp = /pdfuaid:part(?:\s*=\s*["']1["']|\s*>\s*1\s*<)/i.test(fullText);
2174
+ const hasLang = /\/Lang\s*\(\s*[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?\s*\)/.test(fullText);
2175
+ const hasDisplayDocTitle = /\/DisplayDocTitle\s+true\b/.test(fullText);
2176
+ const hasFont = /\/Type\s*\/Font\b|\/BaseFont\s*\//.test(fullText);
2177
+ const hasImageXObject = /\/Subtype\s*\/Image\b/.test(fullText);
2178
+ const hasAcroForm = /\/AcroForm\b/.test(fullText);
2179
+ const hasEmptyFieldsArray = /\/Fields\s*\[\s*\]/.test(fullText);
2180
+ const hasTabsStructure = /\/Tabs\s*\/S\b/.test(fullText);
2181
+ const hasBookmarks = /\/Outlines\b/.test(fullText);
2182
+ const hasXfa = /\/XFA\b/.test(fullText);
2183
+ const isScannedLikely = !hasFont && hasImageXObject;
2184
+
2185
+ let pageCount = 0;
2186
+ for (const m of fullText.matchAll(/\/Type\s*\/Pages\b[\s\S]{0,220}?\/Count\s+(\d+)/g)) {
2187
+ const n = Number.parseInt(m[1], 10);
2188
+ if (Number.isFinite(n) && n > pageCount) pageCount = n;
2189
+ }
2190
+ if (!pageCount) {
2191
+ for (const m of fullText.matchAll(/\/Count\s+(\d+)[\s\S]{0,160}?\/Type\s*\/Pages\b/g)) {
2192
+ const n = Number.parseInt(m[1], 10);
2193
+ if (Number.isFinite(n) && n > pageCount) pageCount = n;
2194
+ }
2195
+ }
2196
+ if (!pageCount) pageCount = Math.max(1, (fullText.match(/\/Type\s*\/Page\b(?!s)/g) || []).length);
2197
+
2198
+ const baseScore =
2199
+ (!isEncrypted ? 15 : 10) +
2200
+ (hasMarkedTrue ? 20 : 0) +
2201
+ (hasStructTree ? 20 : 0) +
2202
+ (hasPdfUaXmp ? 15 : 0) +
2203
+ (hasLang ? 10 : 0) +
2204
+ (hasDisplayDocTitle ? 10 : 0) +
2205
+ (!isScannedLikely && hasFont ? 10 : 0);
2206
+
2207
+ const textFieldCount = (fullText.match(/\/FT\s*\/Tx\b/g) || []).length;
2208
+ const buttonFieldCount = (fullText.match(/\/FT\s*\/Btn\b/g) || []).length;
2209
+ const choiceFieldCount = (fullText.match(/\/FT\s*\/Ch\b/g) || []).length;
2210
+ const signatureFieldCount = (fullText.match(/\/FT\s*\/Sig\b/g) || []).length;
2211
+ const explicitTypedCount = textFieldCount + buttonFieldCount + choiceFieldCount + signatureFieldCount;
2212
+ const widgetAnnotCount = (fullText.match(/\/Subtype\s*\/Widget\b/g) || []).length;
2213
+ const totalFieldCount = Math.max(
2214
+ explicitTypedCount,
2215
+ widgetAnnotCount,
2216
+ hasAcroForm && !hasEmptyFieldsArray ? 1 : 0
2217
+ );
2218
+ const hasInteractiveFields = totalFieldCount > 0;
2219
+ const isFormDocument = hasInteractiveFields || hasXfa;
2220
+
2221
+ const tuLiteralMatches = fullText.match(/\/TU\s*\(\s*(?:\\.|[^)\\\s])(?:\\.|[^)\\\r\n]){0,512}\)/g) || [];
2222
+ const tuHexMatches = fullText.match(/\/TU\s*<(?!(?:feff|0020|0009|000a|000d|[ \t\r\n])*>)[0-9a-fA-F \t\r\n]{2,512}>/gi) || [];
2223
+ const tuTooltipCount = tuLiteralMatches.length + tuHexMatches.length;
2224
+ const hasFormStructTag = /\/S\s*\/Form\b/.test(fullText) || /\/StructParent(?:s)?\s+\d+/.test(fullText);
2225
+ const tuCoverageRatio = hasInteractiveFields ? Math.min(1, tuTooltipCount / totalFieldCount) : 0;
2226
+
2227
+ const formReadinessScore = isFormDocument
2228
+ ? Math.min(
2229
+ 100,
2230
+ (!hasXfa ? 15 : 0) +
2231
+ (hasInteractiveFields && tuCoverageRatio >= 1 ? 20 : hasInteractiveFields && tuCoverageRatio >= 0.5 ? 10 : 0) +
2232
+ (hasInteractiveFields && hasTabsStructure ? 15 : 0) +
2233
+ (hasInteractiveFields && hasFormStructTag ? 15 : 0) +
2234
+ Math.round(baseScore * 0.35)
2235
+ )
2236
+ : baseScore;
2237
+ const grade = !hasXfa && formReadinessScore === 100 ? 'PASS' : !hasXfa && formReadinessScore >= 70 ? 'PARTIAL' : 'FAIL';
2238
+
2239
+ let estimatedFormRemediationUsd = 0;
2240
+ if (formReadinessScore < 100 || hasXfa) {
2241
+ if (isFormDocument) {
2242
+ let baseFormUsd = 25;
2243
+ if (totalFieldCount > 150) baseFormUsd = 60 + (totalFieldCount - 150) * 0.4;
2244
+ else if (totalFieldCount >= 76) baseFormUsd = 60;
2245
+ else if (totalFieldCount >= 26) baseFormUsd = 40;
2246
+ const extraPagesUsd = Math.max(0, pageCount - 5) * 1.5;
2247
+ const ocrExtraUsd = isScannedLikely ? pageCount * 1.5 : 0;
2248
+ estimatedFormRemediationUsd = Math.max(25, Math.round((baseFormUsd + extraPagesUsd + ocrExtraUsd) * 100) / 100);
2249
+ } else {
2250
+ estimatedFormRemediationUsd = Math.max(25, Math.round(pageCount * (isScannedLikely ? 3.0 : 1.5) * 100) / 100);
2251
+ }
2252
+ }
2253
+
2254
+ const staticAccessible = !isScannedLikely && hasStructTree;
2255
+ const statusLabel = (ok, partial = false) => (ok ? 'Supports' : partial ? 'Partially Supports' : 'Does Not Support');
2256
+ const allCriteria = [
2257
+ { criterion: 'WCAG 1.1.1 Non-text Content (Level A)', standard: 'Section 508 / Title II / HHS 504', conformance: statusLabel(staticAccessible, hasStructTree), remarks: isScannedLikely ? 'Raster scan without embedded text font layer; OCR + /Alt tagging required.' : 'Born-digital text stream inspected; verify /Figure /Alt strings.' },
2258
+ { criterion: 'WCAG 1.3.1 Info and Relationships (Level A)', standard: 'ISO 14289-1 §7.1 / Section 508', conformance: statusLabel(hasMarkedTrue && hasStructTree && (!isFormDocument || (hasInteractiveFields && hasFormStructTag))), remarks: hasStructTree ? '/MarkInfo << /Marked true >> and /StructTreeRoot detected.' : 'Document lacks /StructTreeRoot logical tag hierarchy.' },
2259
+ { criterion: 'WCAG 1.3.2 Meaningful Sequence (Level A)', standard: 'ISO 14289-1 §7.2', conformance: statusLabel(hasStructTree), remarks: hasStructTree ? 'Reading sequence governed by /StructTreeRoot.' : 'Untagged content stream; assistive reading order undefined.' },
2260
+ { criterion: 'WCAG 2.1.1 Keyboard (Level A)', standard: 'Section 508 / HB21-1110', conformance: statusLabel(!hasXfa && !isEncrypted && (isFormDocument ? hasInteractiveFields : staticAccessible)), remarks: hasXfa ? 'Dynamic/legacy /XFA stream blocks standard PDF/UA assistive keyboard navigation.' : !isFormDocument && !staticAccessible ? 'Untagged/scanned static PDF lacks accessible text/tag layer for keyboard assistive navigation.' : 'Standard PDF/AcroForm object model accessible to keyboard navigation.' },
2261
+ { criterion: 'WCAG 2.4.1 Bypass Blocks / Bookmarks (Level A)', standard: 'ISO 14289-1 §7.8', conformance: statusLabel(pageCount < 5 || hasBookmarks, hasStructTree), remarks: hasBookmarks ? '/Outlines document bookmarks present.' : `${pageCount}-page PDF; add /Outlines bookmarks for multi-section navigation.` },
2262
+ { criterion: 'WCAG 2.4.2 Page Titled (Level A)', standard: 'ISO 14289-1 §7.1', conformance: statusLabel(hasDisplayDocTitle), remarks: hasDisplayDocTitle ? '/ViewerPreferences << /DisplayDocTitle true >> enabled.' : 'Missing /DisplayDocTitle true in Catalog ViewerPreferences.' },
2263
+ { criterion: 'WCAG 2.4.3 Focus Order (Level A)', standard: 'ISO 14289-1 §7.18.3', conformance: statusLabel(isFormDocument ? hasInteractiveFields && hasTabsStructure : staticAccessible), remarks: !isFormDocument ? (staticAccessible ? 'Static tagged PDF (0 interactive form widgets).' : 'Untagged static PDF lacks structure tree focus order.') : hasTabsStructure ? 'Page /Tabs /S enforces structure-based focus order.' : 'Missing /Tabs /S on page objects containing form fields.' },
2264
+ { criterion: 'WCAG 2.4.6 Headings and Labels (Level AA)', standard: 'WCAG 2.1/2.2 AA / HHS 504', conformance: statusLabel(isFormDocument ? hasInteractiveFields && tuCoverageRatio >= 1 : staticAccessible && hasMarkedTrue, isFormDocument ? tuCoverageRatio >= 0.5 : hasStructTree), remarks: isFormDocument ? `${tuTooltipCount}/${totalFieldCount} fields define non-empty /TU accessible labels.` : staticAccessible ? 'Static tagged document; verify H1-H6 tag nesting.' : 'Untagged static document lacks heading structure.' },
2265
+ { criterion: 'WCAG 3.1.1 Language of Page (Level A)', standard: 'ISO 14289-1 §7.2', conformance: statusLabel(hasLang), remarks: hasLang ? 'Catalog /Lang natural language identifier present.' : 'Missing Catalog /Lang (e.g. en-US).' },
2266
+ { criterion: 'WCAG 3.3.2 Labels or Instructions (Level A)', standard: 'ISO 14289-1 §7.18.1', conformance: statusLabel(isFormDocument ? hasInteractiveFields && tuCoverageRatio >= 1 : staticAccessible, isFormDocument ? tuCoverageRatio > 0 : false), remarks: isFormDocument ? `${tuTooltipCount} of ${totalFieldCount} interactive widgets expose programmatic /TU instructions.` : 'Not applicable (0 interactive fields).' },
2267
+ { criterion: 'WCAG 4.1.2 Name, Role, Value (Level A)', standard: 'ISO 14289-1 §7.18 / Section 508', conformance: statusLabel(!hasXfa && (isFormDocument ? hasInteractiveFields && hasFormStructTag && tuCoverageRatio >= 1 : staticAccessible && hasMarkedTrue)), remarks: hasXfa ? '/XFA stream fails PDF/UA-1 role/value exposure.' : isFormDocument ? `Typed widgets (Tx:${textFieldCount}, Btn:${buttonFieldCount}, Ch:${choiceFieldCount}, Sig:${signatureFieldCount}) inspected.` : staticAccessible ? 'Static tagged content.' : 'Untagged static content lacks semantic structure roles.' },
2268
+ { criterion: 'Revised Section 508 E205.4 Accessibility Standard', standard: '36 CFR Part 1194 / PDF/UA-1', conformance: statusLabel(hasPdfUaXmp && formReadinessScore === 100, !hasXfa && formReadinessScore >= 65), remarks: hasPdfUaXmp ? 'XMP pdfuaid:part=1 declared.' : 'Missing XMP pdfuaid:part=1 metadata stream.' },
2269
+ { criterion: 'HHS Section 504 (45 CFR Part 84 / 91 FR 25496)', standard: 'May 11, 2027 Healthcare Mandate', conformance: statusLabel(!hasXfa && formReadinessScore === 100, !hasXfa && formReadinessScore >= 65), remarks: 'Covers patient intake, consent, financial assistance, and Medicaid/Medicare PDF forms.' },
2270
+ { criterion: 'DOJ ADA Title II (28 CFR Part 35) & CO HB21-1110', standard: 'State & Local Electronic Docs', conformance: statusLabel(!hasXfa && formReadinessScore === 100, !hasXfa && formReadinessScore >= 65), remarks: `Automated structural readiness ${formReadinessScore}/100; est. Second Foreman remediation $${estimatedFormRemediationUsd}.` },
2271
+ ];
2272
+
2273
+ const headerBlock = [
2274
+ `# ITI VPAT 2.5 — Automated Technical Self-Assessment Draft`,
2275
+ `- **Document / Product Evaluated:** ${productName} (${fileName}, ${pageCount} page(s))`,
2276
+ `- **Applicable Standards:** Revised Section 508 (36 CFR 1194), WCAG 2.1/2.2 Level AA, ISO 14289-1 (PDF/UA-1), HHS Section 504 (91 FR 25496), DOJ ADA Title II (28 CFR Part 35), Colorado HB21-1110`,
2277
+ `- **Automated Form & PDF/UA-1 Readiness Score:** ${formReadinessScore}/100 (${grade}) | Interactive Fields: ${totalFieldCount} (/TU Tooltips: ${tuTooltipCount}, /XFA: ${hasXfa ? 'YES - BARRED' : 'No'})`,
2278
+ `- **Scope & Honesty Disclosure:** Generated automatically by Second Foreman LLC's binary/FlateDecode PDF inspector. This document is an automated structural self-assessment draft for engineering triage and procurement intake; it is not a human screen-reader audit or third-party signed certification.`,
2279
+ ``,
2280
+ `| Criterion | Regulatory Mapping | Automated Conformance | Technical Observations |`,
2281
+ `| :--- | :--- | :--- | :--- |`,
2282
+ ];
2283
+ const fmtRows = (rows) => rows.map((r) => `| ${r.criterion} | ${r.standard} | **${r.conformance}** | ${r.remarks} |`);
2284
+ const previewVpatMarkdown = [
2285
+ ...headerBlock,
2286
+ ...fmtRows(allCriteria.slice(0, 4)),
2287
+ `| ... *(10 additional Section 508 / ISO 14289-1 / HHS 504 / HB21-1110 criteria)* | *Pro Unlock* | *Locked on Free Preview* | *Unlock full 14-criterion VPAT 2.5 .md & .csv download with Second Foreman Pro ($29/mo or $149/yr).* |`,
2288
+ ].join('\n');
2289
+ const fullVpatMarkdown = isPro ? [...headerBlock, ...fmtRows(allCriteria)].join('\n') : null;
2290
+ const fullVpatCsv = isPro
2291
+ ? [
2292
+ 'criterion,regulatory_mapping,automated_conformance,technical_observations',
2293
+ ...allCriteria.map(
2294
+ (r) =>
2295
+ `"${r.criterion.replace(/"/g, '""')}","${r.standard.replace(/"/g, '""')}","${r.conformance}","${r.remarks.replace(/"/g, '""')}"`
2296
+ ),
2297
+ ].join('\n')
2298
+ : null;
2299
+
2300
+ const out = {
2301
+ auditedUrl: currentUrl.toString(),
2302
+ fileName,
2303
+ productName,
2304
+ isPro,
2305
+ pdfVersion,
2306
+ byteLength: bytes.length,
2307
+ pageCount,
2308
+ pdfUaScore: baseScore,
2309
+ formReadinessScore,
2310
+ grade,
2311
+ hasAcroForm,
2312
+ hasXfa,
2313
+ textFieldCount,
2314
+ buttonFieldCount,
2315
+ choiceFieldCount,
2316
+ signatureFieldCount,
2317
+ totalFieldCount,
2318
+ tuTooltipCount,
2319
+ hasTabsStructure,
2320
+ hasFormStructTag,
2321
+ isScannedLikely,
2322
+ estimatedFormRemediationUsd,
2323
+ vpatPreviewCriteria: allCriteria.slice(0, 4),
2324
+ vpatCriteria: isPro ? allCriteria : allCriteria.slice(0, 4),
2325
+ previewVpatMarkdown,
2326
+ fullVpatMarkdown,
2327
+ fullVpatCsv,
2328
+ auditorUrl: 'https://secondforeman.com/bidradar/vpat-acroform-auditor/',
2329
+ freePage1ProofUrl: 'https://secondforeman.com/pdf-remediation/',
2330
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
2331
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
2332
+ };
2333
+ return {
2334
+ jsonrpc: '2.0',
2335
+ id,
2336
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2337
+ };
2338
+ }
2339
+
2340
+ if (toolName === 'ada_audit_eaa_en301549') {
2341
+ if (typeof toolArgs.url !== 'string' || !toolArgs.url.trim()) {
2342
+ throw new Error('Invalid params: "url" must be a non-empty https:// URL string.');
2343
+ }
2344
+ for (const optStr of ['orgName', 'contactEmail', 'proKey']) {
2345
+ if (toolArgs[optStr] !== undefined && typeof toolArgs[optStr] !== 'string') {
2346
+ throw new Error(`Invalid params: "${optStr}" must be a string.`);
2347
+ }
2348
+ }
2349
+ let currentUrl = validateSafePublicHttpsUrl(toolArgs.url);
2350
+ const orgName = String(toolArgs.orgName || '').trim() || currentUrl.hostname;
2351
+ const contactEmail = String(toolArgs.contactEmail || '').trim() || 'accessibility@example.eu';
2352
+ const fetchFn = options.fetchImpl || globalThis.fetch;
2353
+ const eaaCtrl = new AbortController();
2354
+ const eaaTimer = setTimeout(() => eaaCtrl.abort(), 7000);
2355
+ let rawBytes;
2356
+ let ctype = '';
2357
+ try {
2358
+ let resp;
2359
+ for (let hop = 0; hop <= 3; hop++) {
2360
+ resp = await fetchFn(currentUrl.toString(), {
2361
+ method: 'GET',
2362
+ redirect: 'manual',
2363
+ headers: {
2364
+ accept: 'text/html,application/xhtml+xml,application/pdf;q=0.95,*/*;q=0.5',
2365
+ 'user-agent': 'SecondForeman-EAA-EN301549-Auditor/1.5 (+https://secondforeman.com/bidradar/eaa-en-301-549-auditor/)',
2366
+ },
2367
+ signal: eaaCtrl.signal,
2368
+ });
2369
+ if (resp.status >= 300 && resp.status < 400) {
2370
+ const loc = resp.headers.get('location');
2371
+ if (!loc || hop === 3) throw new Error('Too many or invalid redirects.');
2372
+ currentUrl = validateSafePublicHttpsUrl(new URL(loc, currentUrl).toString());
2373
+ continue;
2374
+ }
2375
+ break;
2376
+ }
2377
+ if (!resp || !resp.ok) throw new Error(`Upstream URL returned HTTP ${resp ? resp.status : 'error'}`);
2378
+ ctype = (resp.headers.get('content-type') || '').toLowerCase();
2379
+ const maxBytes = 2097152;
2380
+ if (!resp.body || typeof resp.body.getReader !== 'function') {
2381
+ const ab = await resp.arrayBuffer();
2382
+ rawBytes = new Uint8Array(ab.byteLength > maxBytes ? ab.slice(0, maxBytes) : ab);
2383
+ } else {
2384
+ const reader = resp.body.getReader();
2385
+ const chunks = [];
2386
+ let total = 0;
2387
+ try {
2388
+ while (total < maxBytes) {
2389
+ const { done, value } = await reader.read();
2390
+ if (done || !value) break;
2391
+ const take = value.byteLength > maxBytes - total ? value.subarray(0, maxBytes - total) : value;
2392
+ chunks.push(take);
2393
+ total += take.byteLength;
2394
+ if (total >= maxBytes) {
2395
+ await reader.cancel().catch(() => {});
2396
+ break;
2397
+ }
2398
+ }
2399
+ } finally {
2400
+ reader.releaseLock();
2401
+ }
2402
+ rawBytes = new Uint8Array(total);
2403
+ let off = 0;
2404
+ for (const c of chunks) {
2405
+ rawBytes.set(c, off);
2406
+ off += c.byteLength;
2407
+ }
2408
+ }
2409
+ } finally {
2410
+ clearTimeout(eaaTimer);
2411
+ }
2412
+
2413
+ let headLatin1 = '';
2414
+ const headCap = Math.min(rawBytes.length, 1024);
2415
+ for (let i = 0; i < headCap; i++) headLatin1 += String.fromCharCode(rawBytes[i]);
2416
+ const hasPdfMagic = /%PDF-\d\.\d/.test(headLatin1);
2417
+ const looksLikePdfByHeaderOrPath = ctype.includes('application/pdf') || /\.pdf$/i.test(currentUrl.pathname);
2418
+ if (ctype.includes('application/pdf') && !hasPdfMagic) {
2419
+ throw new Error('Target URL declared application/pdf but did not return a valid %PDF-1.x/2.0 byte stream.');
2420
+ }
2421
+ const isPdf = hasPdfMagic;
2422
+ if (!isPdf) {
2423
+ if (looksLikePdfByHeaderOrPath) {
2424
+ throw new Error('Target PDF URL did not return a valid %PDF-1.x/2.0 document.');
2425
+ }
2426
+ if (ctype && !ctype.includes('html') && !ctype.includes('xml') && !ctype.includes('text/plain')) {
2427
+ throw new Error(`Unsupported content-type "${ctype}" (expected HTML webpage or %PDF-1.x/2.0 document).`);
2428
+ }
2429
+ }
2430
+ const statusLabel = (ok, partial = false) => (ok ? 'Supports' : partial ? 'Partially Supports' : 'Does Not Support');
2431
+
2432
+ const targetKind = isPdf ? 'pdf' : 'webpage';
2433
+ let fileName = currentUrl.pathname.split('/').filter(Boolean).pop() || (isPdf ? 'document.pdf' : 'index.html');
2434
+ try {
2435
+ fileName = decodeURIComponent(fileName);
2436
+ } catch {
2437
+ /* keep raw */
2438
+ }
2439
+ let pageCount = 1;
2440
+ let linkedPdfCount = 0;
2441
+ let eaaReadinessScore = 0;
2442
+ let grade = 'FAIL';
2443
+ let estimatedRemediationUsd = 0;
2444
+ let allClauses = [];
2445
+
2446
+ if (isPdf) {
2447
+ let raw = '';
2448
+ for (let i = 0; i < rawBytes.length; i += 32768) {
2449
+ raw += String.fromCharCode(...rawBytes.subarray(i, Math.min(rawBytes.length, i + 32768)));
2450
+ }
2451
+ const inflated = inflatePdfBufferFlate(rawBytes, raw);
2452
+ const fullText = inflated ? `${raw}\n${inflated}` : raw;
2453
+ const isEncrypted = /\/Encrypt\b/.test(raw);
2454
+ const hasMarkedTrue = /\/MarkInfo\s*<<[\s\S]{0,180}?\/Marked\s+true\b/.test(fullText) || /\/Marked\s+true\b/.test(fullText);
2455
+ const hasStructTree = /\/StructTreeRoot\b/.test(fullText);
2456
+ const hasPdfUaXmp = /pdfuaid:part(?:\s*=\s*["']1["']|\s*>\s*1\s*<)/i.test(fullText);
2457
+ const hasLang = /\/Lang\s*\(\s*[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?\s*\)/.test(fullText);
2458
+ const hasDisplayDocTitle = /\/DisplayDocTitle\s+true\b/.test(fullText);
2459
+ const hasFont = /\/Type\s*\/Font\b|\/BaseFont\s*\//.test(fullText);
2460
+ const hasImageXObject = /\/Subtype\s*\/Image\b/.test(fullText);
2461
+ const hasAcroForm = /\/AcroForm\b/.test(fullText);
2462
+ const hasEmptyFieldsArray = /\/Fields\s*\[\s*\]/.test(fullText);
2463
+ const hasTabsStructure = /\/Tabs\s*\/S\b/.test(fullText);
2464
+ const hasBookmarks = /\/Outlines\b/.test(fullText);
2465
+ const hasXfa = /\/XFA\b/.test(fullText);
2466
+
2467
+ pageCount = 0;
2468
+ for (const m of fullText.matchAll(/\/Type\s*\/Pages\b[\s\S]{0,220}?\/Count\s+(\d+)/g)) {
2469
+ const n = Number.parseInt(m[1], 10);
2470
+ if (Number.isFinite(n) && n > pageCount) pageCount = n;
2471
+ }
2472
+ if (!pageCount) {
2473
+ for (const m of fullText.matchAll(/\/Count\s+(\d+)[\s\S]{0,160}?\/Type\s*\/Pages\b/g)) {
2474
+ const n = Number.parseInt(m[1], 10);
2475
+ if (Number.isFinite(n) && n > pageCount) pageCount = n;
2476
+ }
2477
+ }
2478
+ if (!pageCount) pageCount = Math.max(1, (fullText.match(/\/Type\s*\/Page\b(?!s)/g) || []).length);
2479
+
2480
+ const isScannedLikely = !hasFont && hasImageXObject;
2481
+ const baseScore =
2482
+ (!isEncrypted ? 15 : 10) +
2483
+ (hasMarkedTrue ? 20 : 0) +
2484
+ (hasStructTree ? 20 : 0) +
2485
+ (hasPdfUaXmp ? 15 : 0) +
2486
+ (hasLang ? 10 : 0) +
2487
+ (hasDisplayDocTitle ? 10 : 0) +
2488
+ (!isScannedLikely && hasFont ? 10 : 0);
2489
+
2490
+ const textFieldCount = (fullText.match(/\/FT\s*\/Tx\b/g) || []).length;
2491
+ const buttonFieldCount = (fullText.match(/\/FT\s*\/Btn\b/g) || []).length;
2492
+ const choiceFieldCount = (fullText.match(/\/FT\s*\/Ch\b/g) || []).length;
2493
+ const signatureFieldCount = (fullText.match(/\/FT\s*\/Sig\b/g) || []).length;
2494
+ const widgetAnnotCount = (fullText.match(/\/Subtype\s*\/Widget\b/g) || []).length;
2495
+ const totalFieldCount = Math.max(textFieldCount + buttonFieldCount + choiceFieldCount + signatureFieldCount, widgetAnnotCount, hasAcroForm && !hasEmptyFieldsArray ? 1 : 0);
2496
+ const hasInteractiveFields = totalFieldCount > 0;
2497
+ const isFormDocument = hasInteractiveFields || hasXfa;
2498
+ const tuLiteralMatches = fullText.match(/\/TU\s*\(\s*(?:\\.|[^)\\\s])(?:\\.|[^)\\\r\n]){0,512}\)/g) || [];
2499
+ const tuHexMatches = fullText.match(/\/TU\s*<(?!(?:feff|0020|0009|000a|000d|[ \t\r\n])*>)[0-9a-fA-F \t\r\n]{2,512}>/gi) || [];
2500
+ const tuTooltipCount = tuLiteralMatches.length + tuHexMatches.length;
2501
+ const hasFormStructTag = /\/S\s*\/Form\b/.test(fullText) || /\/StructParent(?:s)?\s+\d+/.test(fullText);
2502
+ const tuCoverageRatio = hasInteractiveFields ? Math.min(1, tuTooltipCount / totalFieldCount) : 0;
2503
+
2504
+ eaaReadinessScore = isFormDocument
2505
+ ? Math.min(
2506
+ 100,
2507
+ (!hasXfa ? 15 : 0) +
2508
+ (hasInteractiveFields && tuCoverageRatio >= 1 ? 20 : hasInteractiveFields && tuCoverageRatio >= 0.5 ? 10 : 0) +
2509
+ (hasInteractiveFields && hasTabsStructure ? 15 : 0) +
2510
+ (hasInteractiveFields && hasFormStructTag ? 15 : 0) +
2511
+ Math.round(baseScore * 0.35)
2512
+ )
2513
+ : baseScore;
2514
+ grade = !hasXfa && eaaReadinessScore === 100 ? 'PASS' : !hasXfa && eaaReadinessScore >= 70 ? 'PARTIAL' : 'FAIL';
2515
+ if (eaaReadinessScore < 100 || hasXfa) {
2516
+ if (isFormDocument) {
2517
+ let baseFormUsd = 25;
2518
+ if (totalFieldCount > 150) baseFormUsd = 60 + (totalFieldCount - 150) * 0.4;
2519
+ else if (totalFieldCount >= 76) baseFormUsd = 60;
2520
+ else if (totalFieldCount >= 26) baseFormUsd = 40;
2521
+ const extraPagesUsd = Math.max(0, pageCount - 5) * 1.5;
2522
+ const ocrExtraUsd = isScannedLikely ? pageCount * 1.5 : 0;
2523
+ estimatedRemediationUsd = Math.max(25, Math.round((baseFormUsd + extraPagesUsd + ocrExtraUsd) * 100) / 100);
2524
+ } else {
2525
+ estimatedRemediationUsd = Math.max(25, Math.round(pageCount * (isScannedLikely ? 3.0 : 1.5) * 100) / 100);
2526
+ }
2527
+ }
2528
+ const staticAccessible = !isScannedLikely && hasStructTree;
2529
+ allClauses = [
2530
+ { clause: 'EN 301 549 10.1.1.1 Non-text Content', mapping: 'WCAG 1.1.1 / EAA Annex I §I', conformance: statusLabel(staticAccessible, hasStructTree), remarks: isScannedLikely ? 'Raster scan without text font layer; OCR + /Alt required.' : 'Born-digital text stream inspected.' },
2531
+ { clause: 'EN 301 549 10.1.3.1 Info and Relationships', mapping: 'WCAG 1.3.1 / ISO 14289-1 §7.1', conformance: statusLabel(hasMarkedTrue && hasStructTree && (!isFormDocument || (hasInteractiveFields && hasFormStructTag))), remarks: hasStructTree ? '/Marked true and /StructTreeRoot present.' : 'Missing /StructTreeRoot tag hierarchy.' },
2532
+ { clause: 'EN 301 549 10.1.3.2 Meaningful Sequence', mapping: 'WCAG 1.3.2 / ISO 14289-1 §7.2', conformance: statusLabel(hasStructTree), remarks: hasStructTree ? 'Reading order governed by /StructTreeRoot.' : 'Untagged PDF stream.' },
2533
+ { clause: 'EN 301 549 10.2.1.1 Keyboard & No XFA Lockout', mapping: 'WCAG 2.1.1 / ISO 14289-1 §7.18.8', conformance: statusLabel(!hasXfa && !isEncrypted && (isFormDocument ? hasInteractiveFields : staticAccessible)), remarks: hasXfa ? 'Barred /XFA stream detected.' : 'Standard PDF/AcroForm keyboard model.' },
2534
+ { clause: 'EN 301 549 10.2.4.1 Bypass Blocks / Bookmarks', mapping: 'WCAG 2.4.1 / ISO 14289-1 §7.8', conformance: statusLabel(pageCount < 5 || hasBookmarks, hasStructTree), remarks: hasBookmarks ? '/Outlines bookmarks present.' : `${pageCount}-page document.` },
2535
+ { clause: 'EN 301 549 10.2.4.2 Document Titled', mapping: 'WCAG 2.4.2 / ISO 14289-1 §7.1', conformance: statusLabel(hasDisplayDocTitle), remarks: hasDisplayDocTitle ? '/DisplayDocTitle true enabled.' : 'Missing /DisplayDocTitle true.' },
2536
+ { clause: 'EN 301 549 10.2.4.3 Focus Order', mapping: 'WCAG 2.4.3 / ISO 14289-1 §7.18.3', conformance: statusLabel(isFormDocument ? hasInteractiveFields && hasTabsStructure : staticAccessible), remarks: !isFormDocument ? 'Static PDF.' : hasTabsStructure ? '/Tabs /S present.' : 'Missing /Tabs /S.' },
2537
+ { clause: 'EN 301 549 10.2.4.6 Headings and Labels', mapping: 'WCAG 2.4.6 / v3.2.1 & v4.1.1', conformance: statusLabel(isFormDocument ? hasInteractiveFields && tuCoverageRatio >= 1 : staticAccessible && hasMarkedTrue, isFormDocument ? tuCoverageRatio >= 0.5 : hasStructTree), remarks: isFormDocument ? `${tuTooltipCount}/${totalFieldCount} /TU labels.` : 'Static document.' },
2538
+ { clause: 'EN 301 549 10.2.4.11 Focus Not Obscured (Minimum)', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 2.4.11', conformance: statusLabel(!hasXfa && (isFormDocument ? hasInteractiveFields && hasTabsStructure : staticAccessible)), remarks: 'Focus indicator check.' },
2539
+ { clause: 'EN 301 549 10.2.5.8 Target Size (Minimum)', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 2.5.8', conformance: statusLabel(!isFormDocument || (!hasXfa && hasInteractiveFields), isFormDocument), remarks: !isFormDocument ? 'Not applicable (0 widgets).' : 'Verify widget /Rect >= 24x24 CSS px.' },
2540
+ { clause: 'EN 301 549 10.3.1.1 Language of Document', mapping: 'WCAG 3.1.1 / ISO 14289-1 §7.2', conformance: statusLabel(hasLang), remarks: hasLang ? 'Catalog /Lang present.' : 'Missing Catalog /Lang.' },
2541
+ { clause: 'EN 301 549 10.3.3.2 Labels or Instructions', mapping: 'WCAG 3.3.2 / ISO 14289-1 §7.18.1', conformance: statusLabel(isFormDocument ? hasInteractiveFields && tuCoverageRatio >= 1 : staticAccessible, isFormDocument && tuCoverageRatio > 0), remarks: isFormDocument ? `${tuTooltipCount}/${totalFieldCount} /TU tooltips.` : 'Static non-form PDF.' },
2542
+ { clause: 'EN 301 549 10.3.3.7 Redundant Entry', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 3.3.7', conformance: statusLabel(!hasXfa), remarks: 'Session field retention.' },
2543
+ { clause: 'EN 301 549 10.3.3.8 Accessible Authentication (Minimum)', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 3.3.8', conformance: statusLabel(!isEncrypted), remarks: isEncrypted ? 'Encrypted PDF gate detected.' : 'No cognitive authentication gate.' },
2544
+ { clause: 'EN 301 549 10.4.1.2 Name, Role, Value', mapping: 'WCAG 4.1.2 / ISO 14289-1 §7.18', conformance: statusLabel(!hasXfa && (isFormDocument ? hasInteractiveFields && hasFormStructTag && tuCoverageRatio >= 1 : staticAccessible && hasMarkedTrue)), remarks: 'Programmatic role/value exposure.' },
2545
+ { clause: 'ISO 14289-1 (PDF/UA-1) & Directive (EU) 2019/882 Annex V', mapping: 'EAA Art. 13(2) & Annex ZB (v4.1.1)', conformance: statusLabel(hasPdfUaXmp && eaaReadinessScore === 100, !hasXfa && eaaReadinessScore >= 70), remarks: hasPdfUaXmp ? 'XMP pdfuaid:part=1 declared.' : 'Missing XMP pdfuaid:part=1.' },
2546
+ ];
2547
+ } else {
2548
+ const html = new TextDecoder('utf-8', { fatal: false }).decode(rawBytes.subarray(0, Math.min(rawBytes.length, 524288)));
2549
+ const hasHtmlLang = /<html\b[^<>]{0,2048}\blang\s*=\s*["']?[a-zA-Z-]{2,}/i.test(html);
2550
+ const tOpen = html.search(/<title\b[^<>]{0,512}>/i);
2551
+ const titleMatch = tOpen >= 0 ? html.slice(tOpen, tOpen + 4096).match(/^<title\b[^<>]{0,512}>([\s\S]{0,2048}?)<\/title>/i) : null;
2552
+ const hasTitle = Boolean(titleMatch && titleMatch[1].trim());
2553
+ const h1Count = (html.match(/<h1[\s>]/gi) || []).length;
2554
+ const hasMainOrSkip = /<main[\s>]|role\s*=\s*["']main["']|href\s*=\s*["']#[a-z0-9_-]*content/i.test(html);
2555
+ const zoomLocked = /user-scalable\s*=\s*["']?no\b|maximum-scale\s*=\s*1(?:\.0)?\b/i.test(html);
2556
+ const imgTags = html.match(/<img\b[^<>]{0,2048}>/gi) || [];
2557
+ let imagesMissingAlt = 0;
2558
+ for (const t of imgTags) if (!/\balt\s*=/i.test(t)) imagesMissingAlt++;
2559
+ const iframeTags = html.match(/<iframe\b[^<>]{0,2048}>/gi) || [];
2560
+ let untitledIframes = 0;
2561
+ for (const t of iframeTags) if (!/\b(?:title|aria-label)\s*=\s*["'][^"']+["']/i.test(t)) untitledIframes++;
2562
+ const inputTags = html.match(/<input\b[^<>]{0,2048}>/gi) || [];
2563
+ let unlabeledInputs = 0;
2564
+ for (const t of inputTags) {
2565
+ if (/\btype\s*=\s*["']?(?:hidden|submit|button|reset|image)\b/i.test(t)) continue;
2566
+ if (!/\b(?:id|aria-label|aria-labelledby|title)\s*=\s*["'][^"']+["']/i.test(t)) unlabeledInputs++;
2567
+ }
2568
+ const pdfSet = new Set();
2569
+ for (const m of html.matchAll(/\bhref\s*=\s*["']([^"'#?]+\.pdf(?:\?[^"'#]*)?)["']/gi)) {
2570
+ try { pdfSet.add(new URL(m[1], currentUrl).toString()); } catch { /* ignore */ }
2571
+ }
2572
+ linkedPdfCount = pdfSet.size;
2573
+ estimatedRemediationUsd = linkedPdfCount > 0 ? Math.max(25, Math.round(linkedPdfCount * 6 * 1.5)) : 0;
2574
+
2575
+ allClauses = [
2576
+ { clause: 'EN 301 549 9.1.1.1 Non-text Content', mapping: 'WCAG 1.1.1 / EAA Annex I §I', conformance: statusLabel(imagesMissingAlt === 0), remarks: `${imagesMissingAlt} of ${imgTags.length} <img> elements lack an alt attribute.` },
2577
+ { clause: 'EN 301 549 9.1.3.1 Info and Relationships', mapping: 'WCAG 1.3.1', conformance: statusLabel(h1Count === 1, h1Count > 0), remarks: `Detected ${h1Count} <h1> heading landmark(s).` },
2578
+ { clause: 'EN 301 549 9.1.4.4 Resize Text / Viewport Zoom', mapping: 'WCAG 1.4.4', conformance: statusLabel(!zoomLocked), remarks: zoomLocked ? 'Viewport meta restricts user pinch-zoom.' : 'Viewport permits >= 200% browser/mobile zoom.' },
2579
+ { clause: 'EN 301 549 9.2.1.1 Keyboard Operability', mapping: 'WCAG 2.1.1', conformance: statusLabel(untitledIframes === 0, true), remarks: 'Verify custom interactive JS widgets expose native button/a semantics.' },
2580
+ { clause: 'EN 301 549 9.2.4.1 Bypass Blocks', mapping: 'WCAG 2.4.1', conformance: statusLabel(hasMainOrSkip), remarks: hasMainOrSkip ? '<main> landmark or skip-link detected.' : 'Missing <main> landmark and skip-to-content link.' },
2581
+ { clause: 'EN 301 549 9.2.4.2 Page Titled', mapping: 'WCAG 2.4.2', conformance: statusLabel(hasTitle), remarks: hasTitle ? 'Non-empty <title> element present.' : 'Missing <title> element.' },
2582
+ { clause: 'EN 301 549 9.2.4.6 Headings and Labels', mapping: 'WCAG 2.4.6', conformance: statusLabel(h1Count === 1 && unlabeledInputs === 0, h1Count > 0), remarks: `${unlabeledInputs} input(s) lack id/aria-label hooks.` },
2583
+ { clause: 'EN 301 549 9.2.4.11 Focus Not Obscured (Minimum)', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 2.4.11', conformance: 'Partially Supports', remarks: 'Verify sticky cookie/chat banners do not cover focused elements.' },
2584
+ { clause: 'EN 301 549 9.2.5.7 Dragging Movements', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 2.5.7', conformance: 'Supports', remarks: 'Ensure any slider/carousel offers single-pointer button equivalents.' },
2585
+ { clause: 'EN 301 549 9.2.5.8 Target Size (Minimum)', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 2.5.8', conformance: 'Partially Supports', remarks: 'Verify interactive pointer targets meet >= 24x24 CSS px or spacing exception.' },
2586
+ { clause: 'EN 301 549 9.3.1.1 Language of Page', mapping: 'WCAG 3.1.1', conformance: statusLabel(hasHtmlLang), remarks: hasHtmlLang ? '<html lang> attribute present.' : 'Missing <html lang> attribute.' },
2587
+ { clause: 'EN 301 549 9.3.2.6 Consistent Help', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 3.2.6', conformance: 'Supports', remarks: 'Keep contact/accessibility help in consistent header/footer order.' },
2588
+ { clause: 'EN 301 549 9.3.3.2 Labels or Instructions', mapping: 'WCAG 3.3.2', conformance: statusLabel(unlabeledInputs === 0), remarks: `${unlabeledInputs} unlabeled form input(s) detected.` },
2589
+ { clause: 'EN 301 549 9.3.3.8 Accessible Authentication (Minimum)', mapping: 'v4.1.1 (2026-09) WCAG 2.2 AA 3.3.8', conformance: 'Supports', remarks: 'Ensure login fields allow password managers and paste without puzzle CAPTCHAs.' },
2590
+ { clause: 'EN 301 549 9.4.1.2 Name, Role, Value', mapping: 'WCAG 4.1.2', conformance: statusLabel(untitledIframes === 0 && unlabeledInputs === 0), remarks: `${untitledIframes} untitled <iframe> element(s) detected.` },
2591
+ { clause: 'EN 301 549 Clause 10 Non-Web Linked PDFs & EAA Annex V', mapping: 'ISO 14289-1 / EAA Art. 13(2)', conformance: statusLabel(linkedPdfCount === 0, linkedPdfCount > 0), remarks: linkedPdfCount === 0 ? '0 linked PDFs detected on audited page.' : `${linkedPdfCount} linked PDF(s) require Clause 10 / PDF/UA-1 verification (est. $${estimatedRemediationUsd}).` },
2592
+ ];
2593
+ const supportsCount = allClauses.filter((c) => c.conformance === 'Supports').length;
2594
+ const partialCount = allClauses.filter((c) => c.conformance === 'Partially Supports').length;
2595
+ eaaReadinessScore = Math.round(((supportsCount + partialCount * 0.6) / allClauses.length) * 100);
2596
+ grade = eaaReadinessScore >= 90 && imagesMissingAlt === 0 && hasHtmlLang && hasTitle ? 'PASS' : eaaReadinessScore >= 70 ? 'PARTIAL' : 'FAIL';
2597
+ }
2598
+
2599
+ const statementHeader = [
2600
+ `# European Accessibility Act — Directive (EU) 2019/882 Annex V Automated Technical Self-Assessment Draft`,
2601
+ `- **Service Provider / Organization:** ${orgName}`,
2602
+ `- **Digital Service / Resource Evaluated:** ${currentUrl.toString()} (${targetKind === 'webpage' ? `Webpage + ${linkedPdfCount} linked PDF(s)` : `PDF Document, ${pageCount} page(s)`})`,
2603
+ `- **Harmonised & Technical Standards Checked:** EN 301 549 v3.2.1 (OJEU) & ETSI EN 301 549 v4.1.1 (2026-09, WCAG 2.2 AA & Annex ZB), Clause 9 Web & Clause 10 Non-Web Documents`,
2604
+ `- **Automated Readiness Score:** ${eaaReadinessScore}/100 (${grade}) | Accessibility Feedback Contact: ${contactEmail}`,
2605
+ `- **Scope & Honesty Notice:** This document is an Automated Technical Self-Assessment Draft generated for engineering triage and Directive (EU) 2019/882 Article 13(2) / Annex V preparation. It is not legal advice, manual assistive-technology testing, or a Notified Body conformity certificate.`,
2606
+ ``,
2607
+ `## 1. General Service & Accessibility Description (EAA Annex V)`,
2608
+ `${orgName} works continuously to align ${currentUrl.toString()} and associated downloadable electronic documents with Directive (EU) 2019/882 and EN 301 549.`,
2609
+ ``,
2610
+ `## 2. Automated EN 301 549 Conformance Summary`,
2611
+ `| EN 301 549 Clause | EAA / WCAG Mapping | Automated Status | Technical Observation |`,
2612
+ `| :--- | :--- | :--- | :--- |`,
2613
+ ];
2614
+ const fmtRows = (rows) => rows.map((r) => `| ${r.clause} | ${r.mapping} | **${r.conformance}** | ${r.remarks} |`);
2615
+ const previewStatementMarkdown = [
2616
+ ...statementHeader,
2617
+ ...fmtRows(allClauses.slice(0, 4)),
2618
+ `| ... *(12 additional EN 301 549 v3.2.1 / v4.1.1 & EAA Annex V clauses)* | *Pro Unlock* | *Locked on Free Preview* | *Unlock full 16-clause EAA Annex V Statement (.md) + Matrix (.csv) with Second Foreman Pro ($29/mo or $149/yr).* |`,
2619
+ ].join('\n');
2620
+ const fullStatementMarkdown = isPro
2621
+ ? [
2622
+ ...statementHeader,
2623
+ ...fmtRows(allClauses),
2624
+ ``,
2625
+ `## 3. Feedback & Competent Market Surveillance Authority Notice`,
2626
+ `- **Accessibility Feedback & Alternative Format Requests:** Contact ${contactEmail}.`,
2627
+ `- **Market Surveillance:** Users in EU Member States may notify the competent national market surveillance authority designated under Article 19 of Directive (EU) 2019/882 if accessibility barriers remain unresolved.`,
2628
+ ].join('\n')
2629
+ : null;
2630
+ const fullClauseCsv = isPro
2631
+ ? [
2632
+ 'en_301_549_clause,eaa_wcag_mapping,automated_status,technical_observation',
2633
+ ...allClauses.map((r) => `"${r.clause.replace(/"/g, '""')}","${r.mapping.replace(/"/g, '""')}","${r.conformance}","${r.remarks.replace(/"/g, '""')}"`),
2634
+ ].join('\n')
2635
+ : null;
2636
+
2637
+ const out = {
2638
+ auditedUrl: currentUrl.toString(),
2639
+ targetKind,
2640
+ fileName,
2641
+ orgName,
2642
+ contactEmail,
2643
+ isPro,
2644
+ pageCount,
2645
+ linkedPdfCount,
2646
+ eaaReadinessScore,
2647
+ grade,
2648
+ estimatedRemediationUsd,
2649
+ clauseCount: allClauses.length,
2650
+ clauses: isPro ? allClauses : allClauses.slice(0, 4),
2651
+ previewStatementMarkdown,
2652
+ fullStatementMarkdown,
2653
+ fullClauseCsv,
2654
+ auditorUrl: 'https://secondforeman.com/bidradar/eaa-en-301-549-auditor/',
2655
+ freePage1ProofUrl: 'https://secondforeman.com/pdf-remediation/',
2656
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
2657
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
2658
+ };
2659
+ return {
2660
+ jsonrpc: '2.0',
2661
+ id,
2662
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2663
+ };
2664
+ }
2665
+
2666
+ if (toolName === 'epa608_calculate_superheat_subcooling') {
2667
+ for (const reqNum of ['suctionPsig', 'suctionLineTempF', 'liquidPsig', 'liquidLineTempF']) {
2668
+ if (typeof toolArgs[reqNum] !== 'number' || !Number.isFinite(toolArgs[reqNum])) {
2669
+ throw new Error(`Invalid params: "${reqNum}" is required and must be a finite number.`);
2670
+ }
2671
+ }
2672
+ for (const optNum of ['indoorWetBulbF', 'outdoorDryBulbF', 'targetSubcoolingF', 'elevationFt']) {
2673
+ if (toolArgs[optNum] !== undefined && (typeof toolArgs[optNum] !== 'number' || !Number.isFinite(toolArgs[optNum]))) {
2674
+ throw new Error(`Invalid params: "${optNum}" must be a finite number.`);
2675
+ }
2676
+ }
2677
+ const ptTables = {
2678
+ 'R-454B': {
2679
+ safetyClass: 'A2L', gwp: 466, liquidChargeRequired: true,
2680
+ knots: [[-20,24.3,22.6],[-10,33.9,31.8],[0,45.3,42.7],[10,58.5,55.4],[20,73.9,70.3],[30,91.7,87.4],[35,101.5,96.9],[40,112.0,107.0],[45,123.1,117.8],[50,135.0,129.3],[55,147.7,141.6],[60,161.1,154.6],[70,190.5,183.1],[80,223.4,215.2],[90,260.0,251.0],[95,279.9,270.4],[100,300.8,290.9],[105,322.8,312.5],[110,345.9,335.2],[115,370.2,359.1],[120,395.7,384.3],[130,450.5,438.7],[140,510.7,498.8],[150,576.8,565.4]],
2681
+ },
2682
+ 'R-32': {
2683
+ safetyClass: 'A2L', gwp: 675, liquidChargeRequired: false,
2684
+ knots: [[-20,26.8,26.8],[-10,37.1,37.1],[0,49.3,49.3],[10,63.5,63.5],[20,80.0,80.0],[30,99.1,99.1],[35,109.7,109.7],[40,121.0,121.0],[45,133.0,133.0],[50,145.8,145.8],[60,174.0,174.0],[70,205.8,205.8],[80,241.5,241.5],[90,281.3,281.3],[100,325.6,325.6],[105,349.5,349.5],[110,374.7,374.7],[115,401.1,401.1],[120,428.8,428.8],[130,488.4,488.4],[140,553.9,553.9],[150,625.8,625.8]],
2685
+ },
2686
+ 'R-410A': {
2687
+ safetyClass: 'A1', gwp: 2088, liquidChargeRequired: true,
2688
+ knots: [[-20,26.1,25.9],[-10,36.2,36.0],[0,48.4,48.2],[10,62.5,62.3],[20,78.9,78.6],[30,97.4,97.0],[35,107.7,107.3],[40,118.8,118.4],[45,130.7,130.2],[50,143.3,142.8],[60,170.9,170.3],[70,201.7,201.1],[80,236.5,235.7],[90,275.3,274.5],[95,296.3,295.4],[100,318.6,317.6],[105,342.1,341.0],[110,366.9,365.8],[115,393.1,391.9],[120,420.7,419.4],[130,480.4,479.0],[140,546.5,545.1],[150,619.6,618.2]],
2689
+ },
2690
+ 'R-22': {
2691
+ safetyClass: 'A1', gwp: 1810, liquidChargeRequired: false,
2692
+ knots: [[-20,10.2,10.2],[-10,16.5,16.5],[0,24.0,24.0],[10,32.8,32.8],[20,43.1,43.1],[30,55.0,55.0],[35,61.5,61.5],[40,68.6,68.6],[45,76.1,76.1],[50,84.1,84.1],[60,101.6,101.6],[70,121.4,121.4],[80,143.6,143.6],[90,168.4,168.4],[100,195.9,195.9],[110,226.4,226.4],[120,260.0,260.0],[130,296.9,296.9],[140,337.4,337.4],[150,381.7,381.7]],
2693
+ },
2694
+ };
2695
+ const interp = (knots, p, col) => {
2696
+ if (p <= knots[0][col]) return knots[0][0];
2697
+ const last = knots[knots.length - 1];
2698
+ if (p >= last[col]) return last[0];
2699
+ for (let i = 0; i < knots.length - 1; i++) {
2700
+ const p0 = knots[i][col];
2701
+ const p1 = knots[i + 1][col];
2702
+ if (p >= p0 && p <= p1) return p1 === p0 ? knots[i][0] : knots[i][0] + ((p - p0) / (p1 - p0)) * (knots[i + 1][0] - knots[i][0]);
2703
+ }
2704
+ return knots[0][0];
2705
+ };
2706
+ const refrigerant = Object.hasOwn(ptTables, toolArgs.refrigerant) ? toolArgs.refrigerant : 'R-454B';
2707
+ const spec = ptTables[refrigerant];
2708
+ const meteringDevice = toolArgs.meteringDevice === 'fixed_orifice' ? 'fixed_orifice' : 'txv';
2709
+ const suctionPsig = Math.max(0, toolArgs.suctionPsig);
2710
+ const suctionLineTempF = toolArgs.suctionLineTempF;
2711
+ const liquidPsig = Math.max(0, toolArgs.liquidPsig);
2712
+ const liquidLineTempF = toolArgs.liquidLineTempF;
2713
+ const indoorWetBulbF = toolArgs.indoorWetBulbF ?? 63;
2714
+ const outdoorDryBulbF = toolArgs.outdoorDryBulbF ?? 85;
2715
+ const targetSubcoolingF = Math.max(2, Math.min(25, toolArgs.targetSubcoolingF ?? 10));
2716
+ const elevationFt = Math.max(-1000, Math.min(14000, toolArgs.elevationFt ?? 0));
2717
+ const localAtmPsia = Number((14.6959 * Math.pow(1 - 6.87559e-6 * elevationFt, 5.25588)).toFixed(3));
2718
+ const suctionSeaPsig = suctionPsig + localAtmPsia - 14.6959;
2719
+ const liquidSeaPsig = liquidPsig + localAtmPsia - 14.6959;
2720
+
2721
+ const evapSatDewTempF = Number(interp(spec.knots, suctionSeaPsig, 2).toFixed(2));
2722
+ const evapSatBubbleTempF = Number(interp(spec.knots, suctionSeaPsig, 1).toFixed(2));
2723
+ const condSatBubbleTempF = Number(interp(spec.knots, liquidSeaPsig, 1).toFixed(2));
2724
+ const glideAtEvapF = Number(Math.max(0, evapSatDewTempF - evapSatBubbleTempF).toFixed(2));
2725
+ const actualSuperheatF = Number((suctionLineTempF - evapSatDewTempF).toFixed(2));
2726
+ const actualSubcoolingF = Number((condSatBubbleTempF - liquidLineTempF).toFixed(2));
2727
+ const rawTargetSh = ((3 * indoorWetBulbF) - 80 - outdoorDryBulbF) / 2;
2728
+ const lowLoadCondition = meteringDevice === 'fixed_orifice' && rawTargetSh < 5;
2729
+ const targetSuperheatF = Number((lowLoadCondition ? Math.max(0, rawTargetSh) : Math.min(35, Math.max(5, rawTargetSh))).toFixed(2));
2730
+
2731
+ let chargeDiagnosis = 'WITHIN_TARGET';
2732
+ if (meteringDevice === 'txv') {
2733
+ if (actualSubcoolingF - targetSubcoolingF < -2.0) chargeDiagnosis = 'UNDERCHARGED';
2734
+ else if (actualSubcoolingF - targetSubcoolingF > 2.5) chargeDiagnosis = 'OVERCHARGED';
2735
+ } else if (lowLoadCondition) {
2736
+ chargeDiagnosis = 'LOW_LOAD_DO_NOT_ADD';
2737
+ } else {
2738
+ if (actualSuperheatF - targetSuperheatF > 3.0) chargeDiagnosis = 'UNDERCHARGED';
2739
+ else if (actualSuperheatF - targetSuperheatF < -3.0) chargeDiagnosis = 'OVERCHARGED';
2740
+ }
2741
+
2742
+ const proCommissioningCsv = isPro
2743
+ ? [
2744
+ 'refrigerant,safety_class,gwp,metering_device,elevation_ft,suction_psig,evap_dew_sat_f,suction_line_f,actual_superheat_f,target_superheat_f,liquid_psig,cond_bubble_sat_f,liquid_line_f,actual_subcooling_f,target_subcooling_f,evap_glide_f,charge_diagnosis',
2745
+ `${refrigerant},${spec.safetyClass},${spec.gwp},${meteringDevice},${elevationFt},${suctionPsig},${evapSatDewTempF},${suctionLineTempF},${actualSuperheatF},${targetSuperheatF},${liquidPsig},${condSatBubbleTempF},${liquidLineTempF},${actualSubcoolingF},${targetSubcoolingF},${glideAtEvapF},${chargeDiagnosis}`,
2746
+ ].join('\n')
2747
+ : null;
2748
+
2749
+ const out = {
2750
+ refrigerant,
2751
+ safetyClass: spec.safetyClass,
2752
+ gwp: spec.gwp,
2753
+ liquidChargeRequired: spec.liquidChargeRequired,
2754
+ meteringDevice,
2755
+ elevationFt,
2756
+ localAtmPsia,
2757
+ evapSatDewTempF,
2758
+ condSatBubbleTempF,
2759
+ glideAtEvapF,
2760
+ actualSuperheatF,
2761
+ targetSuperheatF,
2762
+ actualSubcoolingF,
2763
+ targetSubcoolingF,
2764
+ chargeDiagnosis,
2765
+ isPro,
2766
+ proCommissioningCsv,
2767
+ calculatorUrl: 'https://secondforeman.com/epa-608-practice-test/superheat-subcooling-calculator/',
2768
+ simulatorUrl: 'https://secondforeman.com/epa-608-practice-test/',
2769
+ proMonthlyCheckoutUrl: 'https://buy.stripe.com/bJeaEWbzU1Cd3Lt3wsfUQ05',
2770
+ proAnnualCheckoutUrl: 'https://buy.stripe.com/8x214meM6cgRchZ1okfUQ06',
2771
+ };
2772
+ return {
2773
+ jsonrpc: '2.0',
2774
+ id,
2775
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2776
+ };
2777
+ }
2778
+
2779
+ if (toolName === 'ada_triage_28cfr35_exceptions') {
2780
+ const out = triageAda28Cfr35Exceptions(toolArgs, { isPro });
2781
+ return {
2782
+ jsonrpc: '2.0',
2783
+ id,
2784
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2785
+ };
2786
+ }
2787
+
2788
+ if (toolName === 'ada_score_state_procurement_pdaa') {
2789
+ const out = scoreStateProcurementPdaa(toolArgs, { isPro });
2790
+ return {
2791
+ jsonrpc: '2.0',
2792
+ id,
2793
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2794
+ };
2795
+ }
2796
+
2797
+ if (toolName === 'epa608_calculate_a2l_room_charge_limit') {
2798
+ const out = calculateA2lRoomChargeLimit(toolArgs, { isPro });
2799
+ return {
2800
+ jsonrpc: '2.0',
2801
+ id,
2802
+ result: { content: [{ type: 'text', text: JSON.stringify(out, null, 2) }] },
2803
+ };
2804
+ }
2805
+
2806
+ return {
2807
+ jsonrpc: '2.0',
2808
+ id,
2809
+ error: { code: -32601, message: `Unknown tool: ${toolName}` },
2810
+ };
2811
+ } catch (err) {
2812
+ return {
2813
+ jsonrpc: '2.0',
2814
+ id,
2815
+ error: { code: -32602, message: err?.message || 'Tool execution error' },
2816
+ };
2817
+ }
2818
+ }
2819
+
2820
+ return {
2821
+ jsonrpc: '2.0',
2822
+ id,
2823
+ error: { code: -32601, message: `Method not found: ${method}` },
2824
+ };
2825
+ }
2826
+
2827
+ function startMcpStdioServer() {
2828
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
2829
+ rl.on('line', async (line) => {
2830
+ const trimmed = line.trim();
2831
+ if (!trimmed) return;
2832
+ try {
2833
+ const req = JSON.parse(trimmed);
2834
+ const res = await handleMcpRequest(req);
2835
+ if (res) {
2836
+ process.stdout.write(JSON.stringify(res) + '\n');
2837
+ }
2838
+ } catch {
2839
+ process.stdout.write(
2840
+ JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + '\n'
2841
+ );
2842
+ }
2843
+ });
2844
+ }
2845
+
2846
+ async function runCli() {
2847
+ const args = process.argv.slice(2);
2848
+ if (args.includes('--mcp') || args[0] === 'mcp' || (args.length === 0 && !process.stdin.isTTY)) {
2849
+ startMcpStdioServer();
2850
+ return;
2851
+ }
2852
+
2853
+ const cmd = args[0] || 'help';
2854
+ const { isPro } = await resolveProStatus();
2855
+
2856
+ if (cmd === 'audit') {
2857
+ const dir = args[1] && !args[1].startsWith('--') ? args[1] : '.';
2858
+ const entries = collectWorkspaceEntries(dir);
2859
+ const audit = auditContextBundle(entries, { isPro });
2860
+ if (args.includes('--json')) {
2861
+ console.log(JSON.stringify(audit, null, 2));
2862
+ } else {
2863
+ console.log(`\nContextGuard Audit — ${path.resolve(dir)}`);
2864
+ console.log(`Files scanned: ${audit.totalFilesScanned} | Startup tokens: ${audit.totalTokens.toLocaleString()} (${audit.windowSharePct}% of 200k window)`);
2865
+ console.log(`After START.md slimming: ${audit.optimizedTokens.toLocaleString()} tokens (-${audit.reductionPct}% burn | Est. Opus savings: $${audit.savingsMonthlyUsd.claude_opus}/mo)`);
2866
+ if (audit.findings.length) {
2867
+ console.log('\nFindings:');
2868
+ for (const f of audit.findings) {
2869
+ console.log(` [${f.severity.toUpperCase()}] ${f.code} (${f.target}) -> ${f.fix}`);
2870
+ }
2871
+ } else {
2872
+ console.log('\nNo context-bloat or compaction-loop hazards detected.');
2873
+ }
2874
+ console.log('\nWeb Workbench, Chrome MV3 Extension & Pro Key ($29/mo | $149/yr): https://secondforeman.com/contextguard/');
2875
+ console.log('Open Public B2B Bid & Compliance Radar: https://secondforeman.com/bidradar/\n');
2876
+ }
2877
+ const maxIdx = args.indexOf('--max-boot-tokens');
2878
+ if (maxIdx >= 0 && args[maxIdx + 1]) {
2879
+ const cap = Number(args[maxIdx + 1]);
2880
+ if (Number.isFinite(cap) && audit.totalTokens > cap) {
2881
+ console.error(`FAIL: Startup tokens (${audit.totalTokens}) exceed --max-boot-tokens ${cap}.`);
2882
+ process.exit(1);
2883
+ }
2884
+ }
2885
+ return;
2886
+ }
2887
+
2888
+ if (cmd === 'slim') {
2889
+ const dir = args[1] && !args[1].startsWith('--') ? args[1] : '.';
2890
+ const entries = collectWorkspaceEntries(dir);
2891
+ const compiled = compileSlimArtifacts(entries, { isPro });
2892
+ if (args.includes('--write')) {
2893
+ const targetStart = path.join(path.resolve(dir), 'START.contextguard.md');
2894
+ fs.writeFileSync(targetStart, compiled.startMd, 'utf8');
2895
+ console.log(`Wrote ${targetStart} (${compiled.startMdTokens} tokens).`);
2896
+ } else {
2897
+ console.log(compiled.startMd);
2898
+ }
2899
+ return;
2900
+ }
2901
+
2902
+ if (cmd === 'clip') {
2903
+ const file = args[1];
2904
+ if (!file || !fs.existsSync(file)) {
2905
+ console.error('Usage: contextguard clip <file> [--budget 3000]');
2906
+ process.exit(2);
2907
+ }
2908
+ const bIdx = args.indexOf('--budget');
2909
+ const budget = bIdx >= 0 && args[bIdx + 1] ? Number(args[bIdx + 1]) : 3000;
2910
+ const raw = fs.readFileSync(file, 'utf8');
2911
+ const res = compressWebDocument(raw, { budgetTokens: budget, isPro, sourceUrl: file });
2912
+ console.log(res.markdown);
2913
+ return;
2914
+ }
2915
+
2916
+ if (cmd === 'bids') {
2917
+ const cIdx = args.indexOf('--category');
2918
+ const cat = cIdx >= 0 && args[cIdx + 1] ? args[cIdx + 1] : '';
2919
+ const url = `https://secondforeman.com/api/bidradar${cat ? `?category=${encodeURIComponent(cat)}` : ''}`;
2920
+ const resp = await fetch(url);
2921
+ const data = await resp.json();
2922
+ console.log(JSON.stringify(data, null, 2));
2923
+ return;
2924
+ }
2925
+
2926
+ console.log(`ContextGuard v1.8.0 — AI-Coding Token-Burn Auditor & MCP Server (Second Foreman LLC)
2927
+
2928
+ Usage:
2929
+ npx github:oneandroid-max/contextguard-mcp audit [dir] [--max-boot-tokens 6000] [--json]
2930
+ npx github:oneandroid-max/contextguard-mcp slim [dir] [--write]
2931
+ npx github:oneandroid-max/contextguard-mcp clip <file> [--budget 3000]
2932
+ npx github:oneandroid-max/contextguard-mcp bids [--category web_redesign|ada_pdf|it_software]
2933
+ npx github:oneandroid-max/contextguard-mcp --mcp
2934
+
2935
+ Live Web Workbench, Chrome Extension & Pro Suite:
2936
+ https://secondforeman.com/contextguard/
2937
+ https://secondforeman.com/bidradar/
2938
+ https://secondforeman.com/bidradar/state-procurement-pdaa-vadsir-scorer/
2939
+ https://secondforeman.com/bidradar/ada-title-ii-exceptions-undue-burden-worksheet/
2940
+ https://secondforeman.com/bidradar/eaa-en-301-549-auditor/
2941
+ https://secondforeman.com/bidradar/vpat-acroform-auditor/
2942
+ https://secondforeman.com/epa-608-practice-test/a2l-charge-limit-calculator/
2943
+ https://secondforeman.com/epa-608-practice-test/superheat-subcooling-calculator/
2944
+ https://secondforeman.com/signalclip/`);
2945
+ }
2946
+
2947
+ import { pathToFileURL } from 'node:url';
2948
+
2949
+ const isDirectEntrypoint = (() => {
2950
+ if (!process.argv[1]) return false;
2951
+ try {
2952
+ if (pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) return true;
2953
+ } catch {
2954
+ // fall through to basename checks
2955
+ }
2956
+ return (
2957
+ import.meta.url === `file://${process.argv[1]}` ||
2958
+ process.argv[1].endsWith('secondforeman-mcp') ||
2959
+ process.argv[1].endsWith('contextguard') ||
2960
+ process.argv[1].endsWith('contextguard-mcp') ||
2961
+ process.argv[1].endsWith('contextguard.mjs')
2962
+ );
2963
+ })();
2964
+
2965
+ if (isDirectEntrypoint) {
2966
+ runCli().catch((err) => {
2967
+ console.error(err?.message || err);
2968
+ process.exit(1);
2969
+ });
2970
+ }