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.
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "secondforeman-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.8.0",
4
+ "description": "Zero-dependency CLI & Model Context Protocol (MCP) server to audit AI-coding token burn, scan GitHub repos, compile <5 KB START.md boot cards, score Texas DIR PDAA/VADSIR & WA USER-01 WCAG 2.2 AA vendor procurement packets, triage DOJ 28 CFR 35.201/35.204 archived PDF & undue-burden rules (91 FR 20902), audit EU EAA & EN 301 549 Web + PDFs, inspect ISO 14289-1 (PDF/UA-1), AcroForm & ITI VPAT 2.5 compliance, calculate Unison & $15k GPC margins, and calculate 2026 EPA 608 A2L leak rates & NIST R-454B/R-32 superheat/subcooling.",
5
+ "type": "module",
6
+ "bin": {
7
+ "contextguard": "./bin/contextguard.mjs",
8
+ "contextguard-mcp": "./bin/contextguard.mjs",
9
+ "secondforeman-mcp": "./bin/contextguard.mjs"
10
+ },
11
+ "files": [
12
+ "bin/",
13
+ "src/",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "mcpName": "io.github.oneandroid-max/contextguard-compaction",
18
+ "exports": {
19
+ ".": "./src/core.mjs"
20
+ },
21
+ "scripts": {
22
+ "build": "node --check bin/contextguard.mjs",
23
+ "test": "node --test test/contextguard.test.mjs"
24
+ },
25
+ "engines": {
26
+ "node": ">=20.0.0"
27
+ },
28
+ "keywords": [
29
+ "mcp",
30
+ "mcp-server",
31
+ "model-context-protocol",
32
+ "claude-code",
33
+ "claude-md",
34
+ "cursor",
35
+ "codex",
36
+ "token-optimization",
37
+ "context-compaction",
38
+ "wcag",
39
+ "wcag-2-1",
40
+ "wcag-2-2",
41
+ "en-301-549",
42
+ "european-accessibility-act",
43
+ "pdf-ua",
44
+ "iso-14289",
45
+ "acroform",
46
+ "vpat",
47
+ "vpat-2-5",
48
+ "pdaa",
49
+ "vadsir",
50
+ "texas-dir",
51
+ "watech",
52
+ "ada-title-ii",
53
+ "28-cfr-35",
54
+ "undue-burden",
55
+ "archived-pdf",
56
+ "section-508",
57
+ "section-504",
58
+ "hb21-1110",
59
+ "epa-608",
60
+ "r-454b",
61
+ "r-32",
62
+ "superheat",
63
+ "subcooling",
64
+ "refrigerant",
65
+ "bidradar",
66
+ "government-rfp"
67
+ ],
68
+ "author": "Second Foreman LLC <hello@secondforeman.com> (https://secondforeman.com)",
69
+ "license": "MIT",
70
+ "repository": {
71
+ "type": "git",
72
+ "url": "git+https://github.com/oneandroid-max/contextguard-mcp.git"
73
+ },
74
+ "homepage": "https://secondforeman.com/contextguard/"
75
+ }
package/src/core.mjs ADDED
@@ -0,0 +1,512 @@
1
+ // ContextGuard Core Engine — AI-Coding Token Burn Auditor, Boot-File Slimmer & Web/PR Context Compressor
2
+ // Built and operated by an AI agent (Google Gemini) with Paul Lewis human sign-off, guaranteed by Second Foreman LLC.
3
+ // Zero external dependencies. Runs identically in Node 20+, Cloudflare Workers, Chrome Manifest V3, and Modern Browsers.
4
+
5
+ export const FREE_FILE_AUDIT_LIMIT = 12;
6
+ export const FREE_CLIP_TOKEN_CAP = 3500;
7
+
8
+ export const MODEL_PRICING_PER_1M_USD = Object.freeze({
9
+ claude_opus: { id: 'claude_opus', label: 'Claude Opus 4.6', inputUsd: 15.0, cachedReadUsd: 1.5, outputUsd: 75.0 },
10
+ claude_sonnet: { id: 'claude_sonnet', label: 'Claude Sonnet 4.6', inputUsd: 3.0, cachedReadUsd: 0.3, outputUsd: 15.0 },
11
+ gpt5_codex: { id: 'gpt5_codex', label: 'GPT-5 / Codex CLI', inputUsd: 2.5, cachedReadUsd: 0.25, outputUsd: 10.0 },
12
+ });
13
+
14
+ const BOOT_FILENAME_RE = /(?:^|\/)(?:CLAUDE\.md|AGENTS\.md|GEMINI\.md|START\.md|\.cursorrules|\.windsurfrules|copilot-instructions\.md|revenue-plan.*\.md|README\.md)$/i;
15
+ const LOCK_OR_GENERATED_RE = /(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|dist\/|build\/|\.next\/|coverage\/|node_modules\/|\.min\.(?:js|css)$)/i;
16
+ const BASE64_BLOB_RE = /(?:data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]{240,}|[A-Za-z0-9+/]{480,}={0,2})/;
17
+
18
+ export function estimateTokens(rawText) {
19
+ const s = String(rawText || '');
20
+ if (!s) return 0;
21
+ // Code, JSON, and Markdown tokenize denser than prose (~3.55-3.85 chars/token depending on punctuation density).
22
+ let punct = 0;
23
+ const sampleLen = Math.min(s.length, 32768);
24
+ for (let i = 0; i < sampleLen; i++) {
25
+ const code = s.charCodeAt(i);
26
+ if ((code >= 33 && code <= 47) || (code >= 58 && code <= 64) || (code >= 91 && code <= 96) || (code >= 123 && code <= 126)) {
27
+ punct++;
28
+ }
29
+ }
30
+ const punctRatio = sampleLen > 0 ? punct / sampleLen : 0;
31
+ const charsPerToken = Math.max(2.9, 3.95 - punctRatio * 2.1);
32
+ return Math.max(1, Math.ceil(s.length / charsPerToken));
33
+ }
34
+
35
+ export function estimateTurnBurnUsd(startupTokens, { turnsPerDay = 80, compactionsPerDay = 4 } = {}) {
36
+ const tok = Math.max(0, Number(startupTokens) || 0);
37
+ // Every compaction forces a cold re-read of boot files + summary, breaking prompt-cache continuity and multiplying input burn.
38
+ const uncachedTurns = Math.min(turnsPerDay, 1 + compactionsPerDay * 3);
39
+ const cachedTurns = Math.max(0, turnsPerDay - uncachedTurns);
40
+ const out = {};
41
+ for (const [key, m] of Object.entries(MODEL_PRICING_PER_1M_USD)) {
42
+ const dailyUsd =
43
+ ((tok * uncachedTurns) / 1_000_000) * m.inputUsd +
44
+ ((tok * cachedTurns) / 1_000_000) * m.cachedReadUsd;
45
+ out[key] = {
46
+ label: m.label,
47
+ dailyUsd: Number(dailyUsd.toFixed(2)),
48
+ monthlyUsd: Number((dailyUsd * 22).toFixed(2)),
49
+ };
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * Normalizes virtual workspace entries or raw pasted transcript/markdown into { path, content, bytes, tokens } items.
56
+ */
57
+ export function normalizeAuditEntries(input) {
58
+ if (Array.isArray(input)) {
59
+ return input
60
+ .filter((x) => x && (typeof x.path === 'string' || typeof x.name === 'string'))
61
+ .map((x) => {
62
+ const p = String(x.path || x.name || 'untitled.md').trim();
63
+ const content = String(x.content ?? '');
64
+ const bytes = typeof x.bytes === 'number' ? x.bytes : new TextEncoder().encode(content).length;
65
+ const tokens = typeof x.tokens === 'number' ? x.tokens : estimateTokens(content);
66
+ return { path: p, content, bytes, tokens };
67
+ });
68
+ }
69
+
70
+ const raw = String(input || '');
71
+ if (!raw.trim()) return [];
72
+
73
+ // Detect multi-file delimiter blocks: === FILE: path/to/file ===
74
+ const markerRe = /^===\s*FILE:\s*([^\n=]+?)\s*===\s*$/gm;
75
+ const matches = [...raw.matchAll(markerRe)];
76
+ if (matches.length > 0) {
77
+ const entries = [];
78
+ for (let i = 0; i < matches.length; i++) {
79
+ const start = matches[i].index + matches[i][0].length;
80
+ const end = i + 1 < matches.length ? matches[i + 1].index : raw.length;
81
+ const filePath = matches[i][1].trim();
82
+ const content = raw.slice(start, end).replace(/^\n+|\n+$/g, '');
83
+ entries.push({
84
+ path: filePath,
85
+ content,
86
+ bytes: new TextEncoder().encode(content).length,
87
+ tokens: estimateTokens(content),
88
+ });
89
+ }
90
+ return entries;
91
+ }
92
+
93
+ // Detect JSONL agent transcript lines
94
+ const lines = raw.split(/\r?\n/).filter((l) => l.trim().startsWith('{') && l.trim().endsWith('}'));
95
+ if (lines.length >= 3) {
96
+ return [{
97
+ path: 'session-transcript.jsonl',
98
+ content: raw,
99
+ bytes: new TextEncoder().encode(raw).length,
100
+ tokens: estimateTokens(raw),
101
+ isJsonl: true,
102
+ }];
103
+ }
104
+
105
+ return [{
106
+ path: 'CLAUDE.md',
107
+ content: raw,
108
+ bytes: new TextEncoder().encode(raw).length,
109
+ tokens: estimateTokens(raw),
110
+ }];
111
+ }
112
+
113
+ function scanDuplicateReadsInText(raw) {
114
+ const counts = new Map();
115
+ const patterns = [
116
+ /(?:"AbsolutePath"|"file_path"|"TargetFile"|"path")\s*:\s*"([^"\n]{3,220})"/g,
117
+ /\bview_file\b[^\n]{0,120}?([A-Za-z0-9_./-]+\.(?:md|ts|tsx|js|mjs|py|json|txt))/g,
118
+ /^([A-Za-z0-9_./-]+\.(?:md|ts|tsx|js|mjs|py|json|txt))#L\d+/gm,
119
+ ];
120
+ for (const re of patterns) {
121
+ for (const m of String(raw || '').matchAll(re)) {
122
+ const target = m[1].trim();
123
+ if (!target) continue;
124
+ counts.set(target, (counts.get(target) || 0) + 1);
125
+ }
126
+ }
127
+ return [...counts.entries()]
128
+ .filter(([, count]) => count >= 2)
129
+ .sort((a, b) => b[1] - a[1])
130
+ .map(([file, count]) => ({ file, count }));
131
+ }
132
+
133
+ export function auditContextBundle(input, { isPro = false, contextWindowTokens = 200_000 } = {}) {
134
+ const allEntries = normalizeAuditEntries(input);
135
+ const truncatedEntries = !isPro && allEntries.length > FREE_FILE_AUDIT_LIMIT;
136
+ const entries = truncatedEntries ? allEntries.slice(0, FREE_FILE_AUDIT_LIMIT) : allEntries;
137
+
138
+ let totalBytes = 0;
139
+ let totalTokens = 0;
140
+ let bootTokens = 0;
141
+ let removableTokens = 0;
142
+ const findings = [];
143
+ const fileReports = [];
144
+ const allRawJoined = entries.map((e) => e.content).join('\n');
145
+
146
+ for (const item of entries) {
147
+ totalBytes += item.bytes;
148
+ totalTokens += item.tokens;
149
+ const isBoot = BOOT_FILENAME_RE.test(item.path);
150
+ const isLock = LOCK_OR_GENERATED_RE.test(item.path);
151
+ const hasBase64 = BASE64_BLOB_RE.test(item.content);
152
+ let saveable = 0;
153
+ const flags = [];
154
+
155
+ if (isLock) {
156
+ flags.push('GENERATED_OR_LOCKFILE');
157
+ saveable = item.tokens;
158
+ findings.push({
159
+ severity: 'high',
160
+ code: 'LOCKFILE_IN_CONTEXT',
161
+ target: item.path,
162
+ wastedTokens: item.tokens,
163
+ fix: `Exclude "${item.path}" in .claudeignore / .cursorignore so agents never ingest generated lockfiles.`,
164
+ });
165
+ } else if (isBoot && item.bytes > 6500) {
166
+ const targetSlimTokens = Math.min(item.tokens, 1350);
167
+ saveable = Math.max(0, item.tokens - targetSlimTokens);
168
+ bootTokens += item.tokens;
169
+ flags.push('OVERSIZED_BOOT_DOC');
170
+ findings.push({
171
+ severity: item.bytes > 35000 ? 'critical' : 'high',
172
+ code: 'OVERSIZED_BOOT_FILE',
173
+ target: item.path,
174
+ wastedTokens: saveable,
175
+ fix: `Replace "${item.path}" (${(item.bytes / 1024).toFixed(1)} KB / ${item.tokens.toLocaleString()} tok) with a <5 KB START.md boot card + on-demand section pointers.`,
176
+ });
177
+ } else if (isBoot) {
178
+ bootTokens += item.tokens;
179
+ }
180
+
181
+ if (hasBase64) {
182
+ const estBlobWaste = Math.round(item.tokens * 0.65);
183
+ saveable = Math.max(saveable, estBlobWaste);
184
+ flags.push('RAW_BASE64_PAYLOAD');
185
+ findings.push({
186
+ severity: 'critical',
187
+ code: 'RAW_BASE64_OR_DATA_URI',
188
+ target: item.path,
189
+ wastedTokens: estBlobWaste,
190
+ fix: `Strip base64/RFC payloads in "${item.path}" (avoid --json raw dumps on email/image/PDF tools).`,
191
+ });
192
+ }
193
+
194
+ if (!isBoot && !isLock && item.tokens > 8000) {
195
+ const estTrim = Math.round(item.tokens * 0.75);
196
+ saveable = Math.max(saveable, estTrim);
197
+ flags.push('UNBOUNDED_FILE_OR_DIFF');
198
+ findings.push({
199
+ severity: 'medium',
200
+ code: 'UNBOUNDED_TOOL_DUMP',
201
+ target: item.path,
202
+ wastedTokens: estTrim,
203
+ fix: `Read "${item.path}" with bounded line slices (<= 200 lines) or AST symbol summaries instead of whole-file reads.`,
204
+ });
205
+ }
206
+
207
+ removableTokens += saveable;
208
+ fileReports.push({
209
+ path: item.path,
210
+ bytes: item.bytes,
211
+ tokens: item.tokens,
212
+ saveableTokens: saveable,
213
+ afterTokens: Math.max(0, item.tokens - saveable),
214
+ flags,
215
+ });
216
+ }
217
+
218
+ const dupReads = scanDuplicateReadsInText(allRawJoined);
219
+ if (dupReads.length > 0) {
220
+ const topDups = dupReads.slice(0, 5);
221
+ const totalRepeatCount = dupReads.reduce((acc, d) => acc + (d.count - 1), 0);
222
+ const estDupWaste = Math.min(totalTokens, totalRepeatCount * 2200);
223
+ removableTokens = Math.min(totalTokens, removableTokens + Math.round(estDupWaste * 0.45));
224
+ findings.push({
225
+ severity: totalRepeatCount >= 8 ? 'critical' : 'high',
226
+ code: 'DUPLICATE_FILE_READ_LOOP',
227
+ target: topDups.map((d) => `${d.file} (${d.count}x)`).join(', '),
228
+ wastedTokens: estDupWaste,
229
+ fix: `Detected ${totalRepeatCount} repeated file reads across ${dupReads.length} files. Cache file digests in START.md / MCP state so post-compaction resumes do not re-read giant docs.`,
230
+ });
231
+ }
232
+
233
+ const windowSharePct = Number(((totalTokens / contextWindowTokens) * 100).toFixed(1));
234
+ const compactionSpiral = windowSharePct >= 35 || bootTokens >= 25_000;
235
+ if (compactionSpiral) {
236
+ findings.unshift({
237
+ severity: 'critical',
238
+ code: 'COMPACTION_SPIRAL_TRAP',
239
+ target: `${windowSharePct}% of ${Math.round(contextWindowTokens / 1000)}k context window`,
240
+ wastedTokens: removableTokens,
241
+ fix: `Startup/session payload consumes ${totalTokens.toLocaleString()} tokens (${windowSharePct}% of window), causing auto-compaction every 10-15 minutes. Apply the generated START.md + .claudeignore below.`,
242
+ });
243
+ }
244
+
245
+ const optimizedTokens = Math.max(450, totalTokens - removableTokens);
246
+ const reductionPct = totalTokens > 0 ? Number((((totalTokens - optimizedTokens) / totalTokens) * 100).toFixed(1)) : 0;
247
+ const burnBefore = estimateTurnBurnUsd(totalTokens, {
248
+ turnsPerDay: 80,
249
+ compactionsPerDay: compactionSpiral ? 6 : 1,
250
+ });
251
+ const burnAfter = estimateTurnBurnUsd(optimizedTokens, {
252
+ turnsPerDay: 80,
253
+ compactionsPerDay: 0,
254
+ });
255
+
256
+ const savingsMonthlyUsd = {
257
+ claude_opus: Number(Math.max(0, burnBefore.claude_opus.monthlyUsd - burnAfter.claude_opus.monthlyUsd).toFixed(2)),
258
+ claude_sonnet: Number(Math.max(0, burnBefore.claude_sonnet.monthlyUsd - burnAfter.claude_sonnet.monthlyUsd).toFixed(2)),
259
+ gpt5_codex: Number(Math.max(0, burnBefore.gpt5_codex.monthlyUsd - burnAfter.gpt5_codex.monthlyUsd).toFixed(2)),
260
+ };
261
+
262
+ const healthScore = Math.max(
263
+ 5,
264
+ Math.min(
265
+ 100,
266
+ Math.round(100 - Math.min(65, windowSharePct * 0.9) - findings.filter((f) => f.severity === 'critical').length * 14 - findings.filter((f) => f.severity === 'high').length * 7)
267
+ )
268
+ );
269
+
270
+ return {
271
+ ok: true,
272
+ isPro,
273
+ truncatedEntries,
274
+ totalFilesScanned: entries.length,
275
+ totalFilesProvided: allEntries.length,
276
+ totalBytes,
277
+ totalTokens,
278
+ optimizedTokens,
279
+ savedTokens: Math.max(0, totalTokens - optimizedTokens),
280
+ reductionPct,
281
+ windowSharePct,
282
+ compactionSpiral,
283
+ healthScore,
284
+ duplicateReads: dupReads,
285
+ findings,
286
+ files: fileReports.sort((a, b) => b.tokens - a.tokens),
287
+ burnBefore,
288
+ burnAfter,
289
+ savingsMonthlyUsd,
290
+ };
291
+ }
292
+
293
+ /**
294
+ * Compiles a compact, deterministic <5 KB START.md boot card + .claudeignore + (Pro) MCP & CI configs.
295
+ */
296
+ export function compileSlimArtifacts(input, { isPro = false, maxStartBytes = 4600 } = {}) {
297
+ const entries = normalizeAuditEntries(input);
298
+ const audit = auditContextBundle(entries, { isPro });
299
+
300
+ const headings = [];
301
+ const rules = [];
302
+ for (const e of entries) {
303
+ const lines = e.content.split(/\r?\n/);
304
+ for (const line of lines) {
305
+ const trimmed = line.trim();
306
+ if (/^#{1,3}\s+/.test(trimmed) && headings.length < 18) {
307
+ headings.push(`[${e.path}] ${trimmed.replace(/^#+\s+/, '').slice(0, 90)}`);
308
+ } else if (
309
+ /^[-*]\s+/.test(trimmed) &&
310
+ /\b(?:never|always|must|required|do not|strictly|gate|rule|test|verify)\b/i.test(trimmed) &&
311
+ rules.length < 20
312
+ ) {
313
+ const cleaned = trimmed.replace(/^[-*]\s+/, '').replace(/\s+/g, ' ').slice(0, 155);
314
+ if (!rules.includes(cleaned)) rules.push(cleaned);
315
+ }
316
+ }
317
+ }
318
+
319
+ const pointerLines = audit.files.slice(0, 12).map((f) => {
320
+ const kb = (f.bytes / 1024).toFixed(1);
321
+ return `- \`${f.path}\` (${kb} KB / ~${f.tokens} tok) — read on-demand by line slice only, never whole on boot.`;
322
+ });
323
+
324
+ let startMd = [
325
+ '# START.md — Compact Agent Boot Card (Generated by ContextGuard)',
326
+ '',
327
+ `> Replaces ${audit.totalTokens.toLocaleString()} tokens (${(audit.totalBytes / 1024).toFixed(1)} KB) of startup reads with a <5 KB deterministic boot index (-${audit.reductionPct}% token burn).`,
328
+ '',
329
+ '## 1. Session & Post-Compaction Boot Protocol',
330
+ '- Read **ONLY** this `START.md` file at session start and after compaction.',
331
+ '- Never load full historical plans, changelogs, or lockfiles into context; inspect specific line slices (`<= 160` lines) only when a task touches that subsystem.',
332
+ '- Avoid `--json` raw base64 outputs on CLI plugins and bound `git diff` / `grep` outputs with `--name-only` or `head -n 120`.',
333
+ '',
334
+ '## 2. Non-Negotiable Standing Guardrails',
335
+ ...(rules.length ? rules.map((r) => `- ${r}`) : ['- Run unit tests and secret checks before opening any pull request.']),
336
+ '',
337
+ '## 3. On-Demand File Map (Do Not Bulk-Read)',
338
+ ...(pointerLines.length ? pointerLines : ['- Add large reference docs here as path pointers.']),
339
+ '',
340
+ '## 4. Indexed Section Directory',
341
+ ...(headings.length ? headings.slice(0, 12).map((h) => `- ${h}`) : ['- No markdown headings detected in input.']),
342
+ '',
343
+ ].join('\n');
344
+
345
+ if (startMd.length > maxStartBytes) {
346
+ startMd = startMd.slice(0, maxStartBytes - 64) + '\n\n<!-- Truncated cleanly to stay under 5 KB boot budget -->\n';
347
+ }
348
+
349
+ const claudeIgnore = [
350
+ '# .claudeignore / .cursorignore — Generated by ContextGuard (Second Foreman LLC)',
351
+ 'node_modules/',
352
+ 'dist/',
353
+ 'build/',
354
+ '.next/',
355
+ 'coverage/',
356
+ '*.min.js',
357
+ '*.min.css',
358
+ '*.map',
359
+ 'package-lock.json',
360
+ 'pnpm-lock.yaml',
361
+ 'yarn.lock',
362
+ 'Cargo.lock',
363
+ 'poetry.lock',
364
+ '*.png',
365
+ '*.jpg',
366
+ '*.jpeg',
367
+ '*.gif',
368
+ '*.mp4',
369
+ '*.zip',
370
+ '*.pdf',
371
+ '.git/',
372
+ ...audit.files
373
+ .filter((f) => f.bytes > 25000 && !/^(?:src|lib|app|packages)\//i.test(f.path))
374
+ .map((f) => f.path),
375
+ '',
376
+ ].join('\n');
377
+
378
+ const proMcpConfig = isPro
379
+ ? JSON.stringify(
380
+ {
381
+ mcpServers: {
382
+ contextguard: {
383
+ command: 'npx',
384
+ args: ['-y', 'github:oneandroid-max/contextguard-mcp', '--mcp'],
385
+ env: {
386
+ CONTEXTGUARD_BOOT_BUDGET_BYTES: '4800',
387
+ },
388
+ },
389
+ },
390
+ },
391
+ null,
392
+ 2
393
+ )
394
+ : null;
395
+
396
+ const proCiWorkflow = isPro
397
+ ? [
398
+ 'name: ContextGuard Token Budget Gate',
399
+ 'on: [pull_request]',
400
+ 'jobs:',
401
+ ' token-budget:',
402
+ ' runs-on: ubuntu-latest',
403
+ ' steps:',
404
+ ' - uses: actions/checkout@v4',
405
+ ' - uses: actions/setup-node@v4',
406
+ ' with:',
407
+ " node-version: '22'",
408
+ ' - name: Enforce Boot Context <= 6,000 Tokens',
409
+ ' run: npx --yes github:oneandroid-max/contextguard-mcp audit . --max-boot-tokens 6000',
410
+ '',
411
+ ].join('\n')
412
+ : null;
413
+
414
+ return {
415
+ audit,
416
+ startMd,
417
+ startMdTokens: estimateTokens(startMd),
418
+ claudeIgnore,
419
+ proMcpConfig,
420
+ proCiWorkflow,
421
+ };
422
+ }
423
+
424
+ /**
425
+ * Strips HTML boilerplate, navigation, scripts, styles, SVGs, and duplicate log lines from web docs / PR pages,
426
+ * packing high-signal headings, code blocks, and tables into a strict token budget.
427
+ */
428
+ export function compressWebDocument(rawInput, { budgetTokens = 2500, isPro = false, sourceUrl = '', title = '' } = {}) {
429
+ const effectiveCap = isPro ? Math.max(500, Number(budgetTokens) || 8000) : Math.min(FREE_CLIP_TOKEN_CAP, Math.max(400, Number(budgetTokens) || 2500));
430
+ const raw = String(rawInput || '');
431
+ const beforeTokens = estimateTokens(raw);
432
+
433
+ // Strip scripts, styles, SVGs, nav, footer, noscript, and HTML comments
434
+ let cleaned = raw
435
+ .replace(/<!--[\s\S]*?-->/g, ' ')
436
+ .replace(/<(?:script|style|svg|noscript|iframe|nav|footer|aside)\b[^>]*>[\s\S]*?<\/(?:script|style|svg|noscript|iframe|nav|footer|aside)>/gi, '\n');
437
+
438
+ // Preserve fenced/pre code blocks cleanly
439
+ cleaned = cleaned
440
+ .replace(/<pre\b[^>]*>\s*<code\b[^>]*>([\s\S]*?)<\/code>\s*<\/pre>/gi, (_m, code) => `\n\`\`\`\n${decodeEntities(stripTags(code)).trim()}\n\`\`\`\n`)
441
+ .replace(/<pre\b[^>]*>([\s\S]*?)<\/pre>/gi, (_m, code) => `\n\`\`\`\n${decodeEntities(stripTags(code)).trim()}\n\`\`\`\n`)
442
+ .replace(/<h([1-4])\b[^>]*>([\s\S]*?)<\/h\1>/gi, (_m, lvl, txt) => `\n${'#'.repeat(Number(lvl))} ${decodeEntities(stripTags(txt)).trim()}\n`)
443
+ .replace(/<li\b[^>]*>([\s\S]*?)<\/li>/gi, (_m, txt) => `\n- ${decodeEntities(stripTags(txt)).trim()}`)
444
+ .replace(/<\/(?:p|div|section|article|tr|table|blockquote)>/gi, '\n')
445
+ .replace(/<td\b[^>]*>([\s\S]*?)<\/td>/gi, (_m, txt) => ` | ${decodeEntities(stripTags(txt)).trim()} `)
446
+ .replace(/<th\b[^>]*>([\s\S]*?)<\/th>/gi, (_m, txt) => ` | **${decodeEntities(stripTags(txt)).trim()}** `);
447
+
448
+ cleaned = decodeEntities(stripTags(cleaned));
449
+
450
+ // Deduplicate consecutive or repeated stack-trace / boilerplate lines
451
+ const seenLines = new Map();
452
+ const keptLines = [];
453
+ for (const rawLine of cleaned.split(/\r?\n/)) {
454
+ const line = rawLine.replace(/[ \t]+/g, ' ').trim();
455
+ if (!line) {
456
+ if (keptLines.length > 0 && keptLines[keptLines.length - 1] !== '') keptLines.push('');
457
+ continue;
458
+ }
459
+ if (/^(?:skip to content|cookie|accept all|sign in|sign up|subscribe|privacy policy|terms of service)$/i.test(line)) {
460
+ continue;
461
+ }
462
+ const prevCount = seenLines.get(line) || 0;
463
+ seenLines.set(line, prevCount + 1);
464
+ if (prevCount >= 2 && !/^```/.test(line)) continue;
465
+ keptLines.push(line);
466
+ }
467
+
468
+ const headerPrefix = [
469
+ `# ContextGuard Compressed Clip${title ? `: ${title.trim()}` : ''}`,
470
+ sourceUrl ? `Source: ${sourceUrl}` : '',
471
+ '',
472
+ ].filter(Boolean).join('\n');
473
+
474
+ let body = keptLines.join('\n').trim();
475
+ const maxChars = Math.max(800, Math.floor(effectiveCap * 3.6) - headerPrefix.length);
476
+ let wasBudgetTrimmed = false;
477
+ if (body.length > maxChars) {
478
+ body = body.slice(0, maxChars).replace(/\n[^\n]*$/, '') + `\n\n[...Trimmed by ContextGuard to ${effectiveCap.toLocaleString()}-token budget...]`;
479
+ wasBudgetTrimmed = true;
480
+ }
481
+
482
+ const markdown = `${headerPrefix}\n\n${body}`.trim();
483
+ const afterTokens = estimateTokens(markdown);
484
+ const savedTokens = Math.max(0, beforeTokens - afterTokens);
485
+ const savedPct = beforeTokens > 0 ? Number(((savedTokens / beforeTokens) * 100).toFixed(1)) : 0;
486
+
487
+ return {
488
+ ok: true,
489
+ isPro,
490
+ effectiveCap,
491
+ wasBudgetTrimmed,
492
+ beforeTokens,
493
+ afterTokens,
494
+ savedTokens,
495
+ savedPct,
496
+ markdown,
497
+ };
498
+ }
499
+
500
+ function stripTags(s) {
501
+ return String(s || '').replace(/<[^>]+>/g, ' ');
502
+ }
503
+
504
+ function decodeEntities(s) {
505
+ return String(s || '')
506
+ .replace(/&nbsp;/gi, ' ')
507
+ .replace(/&amp;/gi, '&')
508
+ .replace(/&lt;/gi, '<')
509
+ .replace(/&gt;/gi, '>')
510
+ .replace(/&quot;/gi, '"')
511
+ .replace(/&#39;/gi, "'");
512
+ }
@@ -0,0 +1,102 @@
1
+ // ContextGuard Pro Cryptographic Offline/Edge License Verifier (WebCrypto Ed25519 — Unified Second Foreman SC1 Key)
2
+ // Built and operated by an AI agent (Google Gemini) with Paul Lewis human sign-off, guaranteed by Second Foreman LLC.
3
+
4
+ export const DEFAULT_VERIFY_PUB_B64URL = 'AQA-8hG612wi5jJaoIVywrGBGLoALtk5B-OEYhlMqOo';
5
+
6
+ export const CONTEXTGUARD_PLANS = Object.freeze({
7
+ pro_monthly: { id: 'pro_monthly', label: 'Second Foreman Pro Monthly (ContextGuard + SignalClip)', priceUsd: 29, billing: 'month' },
8
+ pro_annual: { id: 'pro_annual', label: 'Second Foreman Pro Annual (ContextGuard + SignalClip + BidRadar)', priceUsd: 149, billing: 'year' },
9
+ pro_team: { id: 'pro_team', label: 'Second Foreman Pro Team', priceUsd: 299, billing: 'year' },
10
+ });
11
+
12
+ export function base64UrlToUint8Array(b64url) {
13
+ const clean = String(b64url || '').trim().replace(/-/g, '+').replace(/_/g, '/');
14
+ if (!clean || /[^A-Za-z0-9+/=]/.test(clean)) {
15
+ throw new Error('Malformed base64url segment.');
16
+ }
17
+ const padLen = (4 - (clean.length % 4)) % 4;
18
+ const padded = clean + '='.repeat(padLen);
19
+ if (typeof atob === 'function') {
20
+ const bin = atob(padded);
21
+ const out = new Uint8Array(bin.length);
22
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
23
+ return out;
24
+ }
25
+ return new Uint8Array(Buffer.from(padded, 'base64'));
26
+ }
27
+
28
+ export async function verifyContextGuardLicense(rawCode, { verifyPubB64Url = DEFAULT_VERIFY_PUB_B64URL, nowMs = Date.now() } = {}) {
29
+ const code = String(rawCode || '').trim();
30
+ if (!code) {
31
+ return { valid: false, reason: 'Enter a Second Foreman Pro license code starting with SC1.' };
32
+ }
33
+ const parts = code.split('.');
34
+ if (parts.length !== 3 || parts[0] !== 'SC1') {
35
+ return { valid: false, reason: 'Invalid format. Expected SC1.<payload>.<signature>.' };
36
+ }
37
+
38
+ let payloadBytes;
39
+ let sigBytes;
40
+ let pubBytes;
41
+ try {
42
+ payloadBytes = base64UrlToUint8Array(parts[1]);
43
+ sigBytes = base64UrlToUint8Array(parts[2]);
44
+ pubBytes = base64UrlToUint8Array(verifyPubB64Url);
45
+ } catch {
46
+ return { valid: false, reason: 'License encoding is corrupted.' };
47
+ }
48
+
49
+ if (sigBytes.length !== 64 || pubBytes.length !== 32) {
50
+ return { valid: false, reason: 'Invalid Ed25519 key or signature length.' };
51
+ }
52
+
53
+ const subtle = globalThis.crypto?.subtle;
54
+ if (!subtle) {
55
+ return { valid: false, reason: 'WebCrypto API is unavailable in this runtime.' };
56
+ }
57
+
58
+ let verified = false;
59
+ try {
60
+ const pubKey = await subtle.importKey('raw', pubBytes, { name: 'Ed25519' }, false, ['verify']);
61
+ const signedData = new TextEncoder().encode(`SC1.${parts[1]}`);
62
+ verified = await subtle.verify('Ed25519', pubKey, sigBytes, signedData);
63
+ } catch {
64
+ return { valid: false, reason: 'Ed25519 cryptographic verification failed.' };
65
+ }
66
+
67
+ if (!verified) {
68
+ return { valid: false, reason: 'License signature did not match Second Foreman LLC verification key.' };
69
+ }
70
+
71
+ let payload;
72
+ try {
73
+ payload = JSON.parse(new TextDecoder().decode(payloadBytes));
74
+ } catch {
75
+ return { valid: false, reason: 'License payload JSON could not be parsed.' };
76
+ }
77
+
78
+ if (!payload || payload.v !== 1 || !CONTEXTGUARD_PLANS[payload.plan]) {
79
+ return { valid: false, reason: 'Unsupported license version or plan tier.' };
80
+ }
81
+ if (typeof payload.exp !== 'number' || !Number.isFinite(payload.exp)) {
82
+ return { valid: false, reason: 'License expiration timestamp is missing.' };
83
+ }
84
+ if (payload.exp * 1000 <= nowMs) {
85
+ return {
86
+ valid: false,
87
+ expired: true,
88
+ reason: `License expired on ${new Date(payload.exp * 1000).toISOString().slice(0, 10)}.`,
89
+ payload,
90
+ };
91
+ }
92
+
93
+ return {
94
+ valid: true,
95
+ plan: payload.plan,
96
+ planLabel: CONTEXTGUARD_PLANS[payload.plan].label,
97
+ holder: String(payload.sub || 'Verified Pro Seat').slice(0, 120),
98
+ expiresIso: new Date(payload.exp * 1000).toISOString(),
99
+ jti: String(payload.jti || ''),
100
+ payload,
101
+ };
102
+ }