thumbgate 1.39.0 → 1.40.1
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/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
- package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +11 -5
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +104 -7
- package/adapters/opencode/opencode.json +1 -1
- package/adapters/strands/strands-middleware.js +31 -4
- package/bin/cli.js +191 -54
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +3 -1
- package/config/post-deploy-marketing-pages.json +4 -4
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/hooks/hooks.json +24 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +87 -33
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/assets/diagrams/hero-thumbs.svg +2 -4
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +5 -6
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +775 -483
- package/public/diagnostic.html +15 -10
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +302 -97
- package/public/install.html +16 -10
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +246 -83
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +163 -66
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/action-receipts.js +393 -0
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/auto-wire-hooks.js +64 -25
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/cli-demo.js +5 -27
- package/scripts/cli-schema.js +25 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/craft-playbook-gate.js +550 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +574 -167
- package/scripts/decision-journal.js +7 -4
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/failure-diagnostics.js +11 -0
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/gate-stats.js +38 -5
- package/scripts/gates-engine.js +1326 -240
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/gitlab-sdlc-prompts.js +397 -0
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hook-runtime.js +10 -0
- package/scripts/hybrid-feedback-context.js +7 -2
- package/scripts/intervention-policy.js +2 -1
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mabl-failure-honesty.js +273 -0
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-distress-detector.js +3 -3
- package/scripts/operational-integrity.js +436 -3
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/product-feedback.js +35 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-eval.js +1 -1
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/qwenwork-policy-group.js +413 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/tailscale-october-access.js +416 -0
- package/scripts/task-outcomes.js +58 -2
- package/scripts/telemetry-analytics.js +260 -16
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/src/api/server.js +2478 -470
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/email-triage-server/index.js +973 -0
- package/src/mcp/email-triage-server/package.json +12 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
|
@@ -0,0 +1,1475 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* NVIDIA OpenShell (v0.1.8) + Adobe MAX Nov-2026 + Lovable AST Self-Correcting Design Engine.
|
|
5
|
+
*/
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const { computeChunkHash, evaluateHashAnchoredEdit } = require('./hash-anchored-edit');
|
|
9
|
+
|
|
10
|
+
const PROVER_COVERAGE_DOMAINS = Object.freeze(['filesystem', 'network_l4', 'network_rest', 'process', 'landlock']);
|
|
11
|
+
const MODELED_PROTOCOLS = new Set(['tcp', 'rest']);
|
|
12
|
+
const OPAQUE_L4_BINARIES = new Set(['git', 'ssh', 'scp', 'sftp', 'nc', 'ncat', 'netcat', 'socat', 'openssl', 'telnet']);
|
|
13
|
+
const DB_OR_CACHE_PORTS = new Set([3306, 5432, 6379, 9200, 11211, 27017]);
|
|
14
|
+
const LAYERED_PROJECT_EXT_RE = /\.(psd|psb|ai|prproj|aep|indd|fig|sketch|svg)$/i;
|
|
15
|
+
const DESTRUCTIVE_ASSET_OP_RE = /(?:^|[^a-z])(flatten|rasterize|merge[-_ ]?visible|bake[-_ ]?layers|overwrite[-_ ]?master|strip[-_ ]?layers)(?:[^a-z]|$)/i;
|
|
16
|
+
|
|
17
|
+
const DEFAULT_FORBIDDEN_CROSS_BRAND_PATTERNS = Object.freeze([
|
|
18
|
+
{ id: 'other_business_conflation', pattern: /\b(tax[- ]deeds?|197\.552|5[- ]folio|miami[- ]dade|foreclosures?|real\s*estate|deals\.igorganapolsky\.com|bJe28rduQ5v82dz6i73sJ0n)\b/i },
|
|
19
|
+
{ id: 'corporate_airgap', pattern: /\b(ecisolutions\.com|ecinexus\.com|lore\.eciplatform\.net|psn[-_]stockservice|dist03)\b/i },
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
function isAscii(value) {
|
|
23
|
+
return typeof value === 'string' && /^[\x20-\x7E]*$/.test(value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isPrivateOrLinkLocalHost(host) {
|
|
27
|
+
const h = String(host || '').trim().toLowerCase();
|
|
28
|
+
if (!h) return { linkLocal: false, privateIp: false };
|
|
29
|
+
if (['metadata.google.internal', 'metadata', '100.100.100.200', 'localhost', '::1'].includes(h) || /^(?:127\.|169\.254\.|fe80:)/i.test(h)) {
|
|
30
|
+
return { linkLocal: true, privateIp: true };
|
|
31
|
+
}
|
|
32
|
+
if (/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|fc00:|fd)/i.test(h)) return { linkLocal: false, privateIp: true };
|
|
33
|
+
return { linkLocal: false, privateIp: false };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function proverVerdict(result, exitCode, extra = {}) {
|
|
37
|
+
return { result, exitCode, passed: result === 'within_boundary', coverage: { domains: [...PROVER_COVERAGE_DOMAINS] }, ...extra };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* NVIDIA OpenShell Formal Policy Boundary Check (`openshell-prover check`).
|
|
42
|
+
* Only `within_boundary` (exitCode 0) passes; every other verdict fails closed.
|
|
43
|
+
*/
|
|
44
|
+
function provePolicyBoundary(candidate, boundary) {
|
|
45
|
+
if (!candidate || typeof candidate !== 'object' || !boundary || typeof boundary !== 'object') {
|
|
46
|
+
return proverVerdict('error', 2, { reason_code: 'invalid_policy_object', reason: 'Both candidate and boundary policies must be objects.' });
|
|
47
|
+
}
|
|
48
|
+
const candRules = Array.isArray(candidate.network_policies) ? candidate.network_policies : [];
|
|
49
|
+
const boundRules = Array.isArray(boundary.network_policies) ? boundary.network_policies : [];
|
|
50
|
+
const totalEndpoints = [...candRules, ...boundRules].reduce((acc, r) => acc + (Array.isArray(r?.endpoints) ? r.endpoints.length : 0), 0);
|
|
51
|
+
if (candRules.length + boundRules.length > 1024 || totalEndpoints > 4096) {
|
|
52
|
+
return proverVerdict('inconclusive', 3, { reason_code: 'resource_limit', reason: 'Policy exceeds 1,024 network rules or 4,096 endpoints.' });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 1. Landlock check (fails closed if boundary hard_requirement is downgraded or omitted)
|
|
56
|
+
const cLandlock = candidate.landlock?.compatibility;
|
|
57
|
+
if (boundary.landlock?.compatibility === 'hard_requirement' && cLandlock !== 'hard_requirement') {
|
|
58
|
+
return proverVerdict('exceeds_boundary', 1, { reason_code: 'landlock_downgrade', counterexample: `landlock compatibility ${cLandlock || '(missing)'}` });
|
|
59
|
+
}
|
|
60
|
+
for (const field of ['run_as_user', 'run_as_group']) {
|
|
61
|
+
const cVal = candidate.process_policy?.[field];
|
|
62
|
+
const bVal = boundary.process_policy?.[field];
|
|
63
|
+
if (cVal !== undefined && bVal !== undefined && String(cVal) !== String(bVal)) {
|
|
64
|
+
const cRoot = String(cVal) === '0' || String(cVal).toLowerCase() === 'root';
|
|
65
|
+
const bRoot = String(bVal) === '0' || String(bVal).toLowerCase() === 'root';
|
|
66
|
+
if (cRoot && !bRoot) return proverVerdict('exceeds_boundary', 1, { reason_code: 'privilege_escalation_root', counterexample: `process ${field} ${cVal}` });
|
|
67
|
+
return proverVerdict('unsupported', 3, { reason_code: 'uid_remap_unverifiable', reason: `Cannot verify ${field} remap '${bVal}' -> '${cVal}'.` });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const cRo = new Set(candidate.filesystem_policy?.read_only || []);
|
|
71
|
+
const cRw = new Set(candidate.filesystem_policy?.read_write || []);
|
|
72
|
+
const bRo = new Set(boundary.filesystem_policy?.read_only || []);
|
|
73
|
+
const bRw = new Set(boundary.filesystem_policy?.read_write || []);
|
|
74
|
+
const bAllRead = new Set([...bRo, ...bRw]);
|
|
75
|
+
for (const p of [...cRo, ...cRw]) {
|
|
76
|
+
if (!String(p).startsWith('/')) return proverVerdict('unsupported', 3, { reason_code: 'workdir_relative_path', reason: `Relative path '${p}'.` });
|
|
77
|
+
}
|
|
78
|
+
for (const p of cRw) {
|
|
79
|
+
if (bRw.has('/') || bRw.has(p)) continue;
|
|
80
|
+
if (bRw.size === 0 || bRo.has(p)) return proverVerdict('exceeds_boundary', 1, { reason_code: 'filesystem_write_exceeds', counterexample: `filesystem write ${p}` });
|
|
81
|
+
return proverVerdict('unsupported', 3, { reason_code: 'symlink_subpath_unverifiable', reason: `Unverifiable write subpath '${p}'.` });
|
|
82
|
+
}
|
|
83
|
+
for (const p of cRo) {
|
|
84
|
+
if (bAllRead.has('/') || bAllRead.has(p)) continue;
|
|
85
|
+
if (bAllRead.size === 0) return proverVerdict('exceeds_boundary', 1, { reason_code: 'filesystem_read_exceeds', counterexample: `filesystem read ${p}` });
|
|
86
|
+
return proverVerdict('unsupported', 3, { reason_code: 'symlink_subpath_unverifiable', reason: `Unverifiable read subpath '${p}'.` });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 4 & 5. Network L4 + REST checks
|
|
90
|
+
const bEndpoints = [];
|
|
91
|
+
for (const rule of boundRules) {
|
|
92
|
+
const bins = Array.isArray(rule?.binaries) ? rule.binaries.map((b) => b.path || b) : [];
|
|
93
|
+
for (const ep of rule?.endpoints || []) {
|
|
94
|
+
bEndpoints.push({ ...ep, binaries: bins, ruleName: rule.name || 'boundary_rule' });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
for (const rule of candRules) {
|
|
99
|
+
const cBins = Array.isArray(rule?.binaries) ? rule.binaries.map((b) => b.path || b) : [];
|
|
100
|
+
for (const ep of rule?.endpoints || []) {
|
|
101
|
+
const proto = String(ep.protocol || 'tcp').toLowerCase();
|
|
102
|
+
if (!MODELED_PROTOCOLS.has(proto)) {
|
|
103
|
+
return proverVerdict('unsupported', 3, { reason_code: 'unsupported_policy_shape', reason: `Protocol '${proto}' unmodeled; only tcp and rest supported.` });
|
|
104
|
+
}
|
|
105
|
+
if (!ep.host || (ep.port !== undefined && ep.ports !== undefined) || String(ep.host).includes(':') || !isAscii(ep.host)) {
|
|
106
|
+
return proverVerdict('unsupported', 3, { reason_code: 'unsupported_endpoint_shape', reason: `Unsupported endpoint '${ep.host || '(missing)'}'.` });
|
|
107
|
+
}
|
|
108
|
+
if (proto === 'rest' && ep.enforcement && ep.enforcement !== 'enforce') {
|
|
109
|
+
return proverVerdict('unsupported', 3, { reason_code: 'audit_mode_non_enforcing', reason: `REST endpoint '${ep.host}' is non-enforcing.` });
|
|
110
|
+
}
|
|
111
|
+
const port = Number(ep.port || 443);
|
|
112
|
+
const matchingBoundary = bEndpoints.find((b) => b.host === ep.host && Number(b.port || 443) === port);
|
|
113
|
+
if (!matchingBoundary) {
|
|
114
|
+
const wildcardOverlap = bEndpoints.find((b) => Number(b.port || 443) === port && (String(b.host).startsWith('*.') || String(ep.host).startsWith('*.')));
|
|
115
|
+
if (wildcardOverlap && (!ep.allowed_ips || !wildcardOverlap.allowed_ips)) {
|
|
116
|
+
return proverVerdict('unsupported', 3, { reason_code: 'wildcard_host_overlap', reason: `Wildcard host overlap on port ${port}.` });
|
|
117
|
+
}
|
|
118
|
+
return proverVerdict('exceeds_boundary', 1, { reason_code: 'network_destination_exceeds', counterexample: `network ${proto} ${ep.host}:${port}` });
|
|
119
|
+
}
|
|
120
|
+
for (const cb of cBins) {
|
|
121
|
+
if (matchingBoundary.binaries.length > 0 && !matchingBoundary.binaries.includes(cb)) {
|
|
122
|
+
const globMatch = matchingBoundary.binaries.find((bb) => String(bb).endsWith('*') && String(cb).startsWith(String(bb).slice(0, -1)));
|
|
123
|
+
if (globMatch) return proverVerdict('unsupported', 3, { reason_code: 'binary_glob_symlink_unverifiable', reason: `Glob '${globMatch}' unverifiable.` });
|
|
124
|
+
return proverVerdict('exceeds_boundary', 1, { reason_code: 'binary_exceeds_boundary', counterexample: `binary ${cb} -> ${ep.host}:${port}` });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const bProto = String(matchingBoundary.protocol || 'tcp').toLowerCase();
|
|
128
|
+
if (proto !== bProto) {
|
|
129
|
+
return proverVerdict('exceeds_boundary', 1, {
|
|
130
|
+
reason_code: 'protocol_mismatch_exceeds',
|
|
131
|
+
counterexample: `network protocol mismatch ${proto} -> boundary ${bProto} on ${ep.host}:${port}`,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
if (proto === 'rest') {
|
|
135
|
+
const bAllows = (matchingBoundary.rules || []).filter((r) => r.allow).map((r) => r.allow);
|
|
136
|
+
for (const r of ep.rules || []) {
|
|
137
|
+
if (!r.allow) continue;
|
|
138
|
+
const method = String(r.allow.method || 'GET').toUpperCase();
|
|
139
|
+
const rPath = String(r.allow.path || '/');
|
|
140
|
+
if (rPath.includes('?') || rPath.includes('[')) return proverVerdict('unsupported', 3, { reason_code: 'unsupported_rest_path_matcher', reason: `Unsupported path '${rPath}'.` });
|
|
141
|
+
const covered = bAllows.some((ba) => {
|
|
142
|
+
const bm = String(ba.method || '*').toUpperCase();
|
|
143
|
+
if (bm !== '*' && bm !== method) return false;
|
|
144
|
+
const bp = String(ba.path || '/');
|
|
145
|
+
if (bp === '/**' || bp === rPath) return true;
|
|
146
|
+
if (bp.endsWith('/**')) {
|
|
147
|
+
const prefix = bp.slice(0, -3);
|
|
148
|
+
return rPath === prefix || rPath.startsWith(`${prefix}/`);
|
|
149
|
+
}
|
|
150
|
+
return false;
|
|
151
|
+
});
|
|
152
|
+
if (!covered) {
|
|
153
|
+
return proverVerdict('exceeds_boundary', 1, {
|
|
154
|
+
reason_code: 'rest_method_or_path_exceeds',
|
|
155
|
+
counterexample: `network rest ${method} ${ep.host}:${port}${rPath}`,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return proverVerdict('within_boundary', 0, { reason_code: 'ok' });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* NVIDIA OpenShell Policy Advisor Proposal Risk Check.
|
|
168
|
+
*/
|
|
169
|
+
function evaluateProposalRisk(currentPolicy, proposedRule, options = {}) {
|
|
170
|
+
const providers = Array.isArray(options.providers) ? options.providers : [];
|
|
171
|
+
const approvalMode = options.approvalMode === 'auto' ? 'auto' : 'manual';
|
|
172
|
+
const globalPolicyActive = Boolean(options.globalPolicyActive);
|
|
173
|
+
|
|
174
|
+
if (!proposedRule || typeof proposedRule !== 'object' || !Array.isArray(proposedRule.endpoints) || proposedRule.endpoints.length === 0) {
|
|
175
|
+
return { valid: false, status: 'validation_unavailable', autoApproved: false, findings: ['invalid_proposal_shape'], securityFlags: [] };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const findings = new Set();
|
|
179
|
+
const securityFlags = new Set();
|
|
180
|
+
let neverApprovable = false;
|
|
181
|
+
|
|
182
|
+
const currentEndpoints = new Map();
|
|
183
|
+
for (const r of currentPolicy?.network_policies || []) {
|
|
184
|
+
for (const ep of r?.endpoints || []) {
|
|
185
|
+
const key = `${String(ep.host || '').toLowerCase()}:${Number(ep.port || 443)}`;
|
|
186
|
+
const methods = new Set((ep.rules || []).filter((x) => x.allow?.method).map((x) => String(x.allow.method).toUpperCase()));
|
|
187
|
+
currentEndpoints.set(key, { methods });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const credentialHosts = new Set();
|
|
192
|
+
for (const p of providers) {
|
|
193
|
+
for (const ep of p?.endpoints || []) {
|
|
194
|
+
credentialHosts.add(`${String(ep.host || '').toLowerCase()}:${Number(ep.port || 443)}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const binNames = (proposedRule.binaries || []).map((b) => String(b.path || b || '').split('/').pop().toLowerCase());
|
|
199
|
+
|
|
200
|
+
for (const ep of proposedRule.endpoints) {
|
|
201
|
+
const proto = String(ep.protocol || '').toLowerCase();
|
|
202
|
+
if (proto === 'tcp' || ep.tls === 'skip') {
|
|
203
|
+
return {
|
|
204
|
+
valid: false,
|
|
205
|
+
status: 'rejected_uninspectable',
|
|
206
|
+
autoApproved: false,
|
|
207
|
+
neverApprovable: true,
|
|
208
|
+
findings: ['uninspectable_protocol_or_tls_skip'],
|
|
209
|
+
securityFlags: [],
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
const host = String(ep.host || '').trim().toLowerCase();
|
|
213
|
+
const port = Number(ep.port || 443);
|
|
214
|
+
const hostKey = `${host}:${port}`;
|
|
215
|
+
const ipCheck = isPrivateOrLinkLocalHost(host);
|
|
216
|
+
if (ipCheck.linkLocal) {
|
|
217
|
+
findings.add('link_local_reach');
|
|
218
|
+
neverApprovable = true;
|
|
219
|
+
}
|
|
220
|
+
if (ipCheck.privateIp) securityFlags.add('private_ip_host');
|
|
221
|
+
if (host.startsWith('*.') || host === '*') securityFlags.add('wildcard_host');
|
|
222
|
+
if (port > 49152) securityFlags.add('ephemeral_port_gt_49152');
|
|
223
|
+
if (DB_OR_CACHE_PORTS.has(port)) securityFlags.add('database_or_cache_port');
|
|
224
|
+
|
|
225
|
+
const hasCred = credentialHosts.has(hostKey);
|
|
226
|
+
if (hasCred) {
|
|
227
|
+
if (binNames.some((b) => OPAQUE_L4_BINARIES.has(b))) {
|
|
228
|
+
findings.add('l7_bypass_credentialed');
|
|
229
|
+
}
|
|
230
|
+
const existing = currentEndpoints.get(hostKey);
|
|
231
|
+
if (!existing) {
|
|
232
|
+
findings.add('credential_reach_expansion');
|
|
233
|
+
} else {
|
|
234
|
+
for (const r of ep.rules || []) {
|
|
235
|
+
const m = String(r.allow?.method || '').toUpperCase();
|
|
236
|
+
if (m && !existing.methods.has(m) && !existing.methods.has('*')) {
|
|
237
|
+
findings.add('capability_expansion');
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const findingsList = [...findings];
|
|
245
|
+
const flagsList = [...securityFlags];
|
|
246
|
+
const autoApproved = !neverApprovable && !globalPolicyActive && approvalMode === 'auto' && findingsList.length === 0 && flagsList.length === 0;
|
|
247
|
+
return {
|
|
248
|
+
valid: true,
|
|
249
|
+
status: neverApprovable ? 'blocked_never_approvable' : (autoApproved ? 'auto_approved' : 'pending_human_review'),
|
|
250
|
+
autoApproved, neverApprovable, findings: findingsList, securityFlags: flagsList,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function verifyProviderCredentialEgress(request, providers = []) {
|
|
255
|
+
let parsed;
|
|
256
|
+
try { parsed = new URL(String(request?.url || '')); } catch { return { allowed: false, reason: 'invalid_destination_url' }; }
|
|
257
|
+
const host = parsed.hostname.toLowerCase();
|
|
258
|
+
const port = Number(parsed.port || (parsed.protocol === 'http:' ? 80 : 443));
|
|
259
|
+
const method = String(request?.method || 'GET').toUpperCase();
|
|
260
|
+
const placeholderMatch = JSON.stringify(request?.headers || {}).match(/tg_cred:\/\/([a-z0-9_-]+)\/([A-Za-z0-9_]+)/i);
|
|
261
|
+
const providerName = request?.provider || (placeholderMatch ? placeholderMatch[1] : null);
|
|
262
|
+
if (!providerName) return { allowed: true, injected: false };
|
|
263
|
+
const provider = providers.find((p) => p && p.name === providerName);
|
|
264
|
+
if (!provider || !Array.isArray(provider.endpoints) || provider.endpoints.length === 0) return { allowed: false, reason: 'profileless_or_unknown_provider' };
|
|
265
|
+
const endpointOk = provider.endpoints.some((ep) => (
|
|
266
|
+
String(ep.host || '').toLowerCase() === host
|
|
267
|
+
&& Number(ep.port || 443) === port
|
|
268
|
+
&& (!Array.isArray(ep.methods) || ep.methods.length === 0 || ep.methods.map((m) => m.toUpperCase()).includes(method))
|
|
269
|
+
&& (!ep.pathPrefix || parsed.pathname.startsWith(ep.pathPrefix))
|
|
270
|
+
));
|
|
271
|
+
if (!endpointOk) {
|
|
272
|
+
return { allowed: false, reason: 'credential_destination_mismatch', detail: `Provider '${providerName}' credential cannot be sent to ${method} ${host}:${port}${parsed.pathname}` };
|
|
273
|
+
}
|
|
274
|
+
return { allowed: true, injected: true, provider: providerName };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function verifyNonDestructiveProjectEdit(action = {}) {
|
|
278
|
+
const targetPath = String(action.targetPath || action.file || '').trim();
|
|
279
|
+
const outputPath = String(action.outputPath || '').trim();
|
|
280
|
+
const operation = String(action.operation || action.command || '').trim();
|
|
281
|
+
if (!LAYERED_PROJECT_EXT_RE.test(targetPath)) return { allowed: true, nonDestructive: true };
|
|
282
|
+
if (DESTRUCTIVE_ASSET_OP_RE.test(operation) && (!outputPath || outputPath === targetPath) && action.preserveLayers !== true) {
|
|
283
|
+
const ext = targetPath.match(LAYERED_PROJECT_EXT_RE)[0];
|
|
284
|
+
return { allowed: false, reason: 'destructive_layer_flatten_blocked', suggestedPatch: { preserveLayers: true, outputPath: `${targetPath.slice(0, -ext.length)}.export${ext}` } };
|
|
285
|
+
}
|
|
286
|
+
return { allowed: true, nonDestructive: true };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function evaluateBrandAdherence(content, policy = {}) {
|
|
290
|
+
const text = String(content || '');
|
|
291
|
+
const violations = [];
|
|
292
|
+
const forbidden = Array.isArray(policy.forbiddenPatterns) ? policy.forbiddenPatterns : DEFAULT_FORBIDDEN_CROSS_BRAND_PATTERNS;
|
|
293
|
+
for (const rule of forbidden) {
|
|
294
|
+
const m = rule.pattern.exec(text);
|
|
295
|
+
if (m) violations.push({ id: rule.id, matched: m[0] });
|
|
296
|
+
}
|
|
297
|
+
for (const phrase of policy.disallowedClaims || []) {
|
|
298
|
+
if (phrase && text.toLowerCase().includes(String(phrase).toLowerCase())) {
|
|
299
|
+
violations.push({ id: 'unverified_product_claim', matched: phrase });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (policy.requireDisclosure && !/disclosure:\s*i\s+build\s+it/i.test(text)) {
|
|
303
|
+
violations.push({ id: 'missing_builder_disclosure', matched: null });
|
|
304
|
+
}
|
|
305
|
+
return { compliant: violations.length === 0, violations };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const TAILWIND_HEX_PALETTE = Object.freeze({
|
|
309
|
+
'slate-950': '#020617', 'slate-900': '#0f172a', 'slate-800': '#1e293b', 'slate-700': '#334155',
|
|
310
|
+
'slate-600': '#475569', 'slate-500': '#64748b', 'slate-400': '#94a3b8', 'slate-300': '#cbd5e1',
|
|
311
|
+
'slate-200': '#e2e8f0', 'slate-100': '#f1f5f9', 'slate-50': '#f8fafc',
|
|
312
|
+
'gray-950': '#030712', 'gray-900': '#111827', 'gray-800': '#1f2937', 'gray-700': '#374151',
|
|
313
|
+
'gray-600': '#4b5563', 'gray-500': '#6b7280', 'gray-400': '#9ca3af', 'gray-300': '#d1d5db',
|
|
314
|
+
'gray-200': '#e5e7eb', 'gray-100': '#f3f4f6', 'gray-50': '#f9fafb',
|
|
315
|
+
'zinc-950': '#09090b', 'zinc-900': '#18181b', 'zinc-800': '#27272a', 'zinc-700': '#3f3f46',
|
|
316
|
+
'zinc-600': '#52525b', 'zinc-500': '#71717a', 'zinc-400': '#a1a1aa', 'zinc-300': '#d4d4d8',
|
|
317
|
+
'zinc-200': '#e4e4e7', 'zinc-100': '#f4f4f5', 'zinc-50': '#fafafa',
|
|
318
|
+
'red-800': '#991b1b', 'red-700': '#b91c1c', 'red-600': '#dc2626', 'red-400': '#f87171', 'red-200': '#fecaca',
|
|
319
|
+
'amber-800': '#92400e', 'amber-700': '#b45309', 'amber-400': '#fbbf24', 'amber-200': '#fde68a',
|
|
320
|
+
'emerald-800': '#065f46', 'emerald-700': '#047857', 'emerald-400': '#34d399', 'emerald-300': '#6ee7b7', 'emerald-200': '#a7f3d0',
|
|
321
|
+
'cyan-800': '#155e75', 'cyan-700': '#0e7490', 'cyan-400': '#22d3ee', 'cyan-300': '#67e8f9', 'cyan-200': '#a5f3fc',
|
|
322
|
+
'blue-800': '#1e40af', 'blue-700': '#1d4ed8', 'blue-600': '#2563eb', 'blue-400': '#60a5fa', 'blue-300': '#93c5fd', 'blue-200': '#bfdbfe',
|
|
323
|
+
'indigo-700': '#4338ca', 'indigo-400': '#818cf8', 'indigo-300': '#a5b4fc', 'indigo-200': '#c7d2fe',
|
|
324
|
+
white: '#ffffff', black: '#000000',
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
function parseHexColor(input) {
|
|
328
|
+
const raw = String(input || '').trim().replace(/^#/, '');
|
|
329
|
+
if (/^[0-9a-f]{3}$/i.test(raw)) return [0, 1, 2].map((i) => parseInt(raw[i] + raw[i], 16));
|
|
330
|
+
if (/^[0-9a-f]{6}$/i.test(raw)) return [0, 2, 4].map((i) => parseInt(raw.slice(i, i + 2), 16));
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function rgbToHex([r, g, b]) {
|
|
335
|
+
const clamp = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0');
|
|
336
|
+
return `#${clamp(r)}${clamp(g)}${clamp(b)}`;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function rgbToHsl([r, g, b]) {
|
|
340
|
+
const rn = r / 255; const gn = g / 255; const bn = b / 255;
|
|
341
|
+
const max = Math.max(rn, gn, bn); const min = Math.min(rn, gn, bn);
|
|
342
|
+
const l = (max + min) / 2;
|
|
343
|
+
if (max === min) return [0, 0, l];
|
|
344
|
+
const d = max - min;
|
|
345
|
+
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
|
346
|
+
let h = max === rn ? (gn - bn) / d + (gn < bn ? 6 : 0) : max === gn ? (bn - rn) / d + 2 : (rn - gn) / d + 4;
|
|
347
|
+
return [h / 6, s, l];
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function hslToRgb([h, s, l]) {
|
|
351
|
+
if (s === 0) { const v = Math.round(l * 255); return [v, v, v]; }
|
|
352
|
+
const hue2rgb = (p, q, t) => {
|
|
353
|
+
let tn = t < 0 ? t + 1 : t > 1 ? t - 1 : t;
|
|
354
|
+
if (tn < 1 / 6) return p + (q - p) * 6 * tn;
|
|
355
|
+
if (tn < 1 / 2) return q;
|
|
356
|
+
if (tn < 2 / 3) return p + (q - p) * (2 / 3 - tn) * 6;
|
|
357
|
+
return p;
|
|
358
|
+
};
|
|
359
|
+
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
|
360
|
+
const p = 2 * l - q;
|
|
361
|
+
return [hue2rgb(p, q, h + 1 / 3) * 255, hue2rgb(p, q, h) * 255, hue2rgb(p, q, h - 1 / 3) * 255];
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function relativeLuminance(rgb) {
|
|
365
|
+
const chan = rgb.map((v) => {
|
|
366
|
+
const s = v / 255;
|
|
367
|
+
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
368
|
+
});
|
|
369
|
+
return 0.2126 * chan[0] + 0.7152 * chan[1] + 0.0722 * chan[2];
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function computeContrastRatio(fgHex, bgHex) {
|
|
373
|
+
const fg = parseHexColor(fgHex);
|
|
374
|
+
const bg = parseHexColor(bgHex);
|
|
375
|
+
if (!fg || !bg) return null;
|
|
376
|
+
const [l1, l2] = [relativeLuminance(fg), relativeLuminance(bg)];
|
|
377
|
+
return Number(((Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05)).toFixed(2));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function solveAccessibleForeground(fgHex, bgHex, minRatio = 4.5, existingClass = '') {
|
|
381
|
+
const fg = parseHexColor(fgHex);
|
|
382
|
+
const bg = parseHexColor(bgHex);
|
|
383
|
+
if (!fg || !bg) return { hex: '#f8fafc', tailwindClass: 'text-slate-50', ratio: 15.0 };
|
|
384
|
+
const bgLum = relativeLuminance(bg);
|
|
385
|
+
const targetTowardWhite = bgLum < 0.5;
|
|
386
|
+
const [h, s, origL] = rgbToHsl(fg);
|
|
387
|
+
let lo = targetTowardWhite ? origL : 0;
|
|
388
|
+
let hi = targetTowardWhite ? 1 : origL;
|
|
389
|
+
let solvedHex = targetTowardWhite ? '#ffffff' : '#000000';
|
|
390
|
+
for (let iter = 0; iter < 24; iter++) {
|
|
391
|
+
const mid = (lo + hi) / 2;
|
|
392
|
+
const hex = rgbToHex(hslToRgb([h, s, mid]));
|
|
393
|
+
if ((computeContrastRatio(hex, bgHex) || 0) >= minRatio) {
|
|
394
|
+
solvedHex = hex;
|
|
395
|
+
if (targetTowardWhite) hi = mid; else lo = mid;
|
|
396
|
+
} else if (targetTowardWhite) {
|
|
397
|
+
lo = mid;
|
|
398
|
+
} else {
|
|
399
|
+
hi = mid;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const solvedRgb = parseHexColor(solvedHex);
|
|
403
|
+
const familyMatch = /^text-([a-z]+)-\d+$/.exec(String(existingClass || '').trim());
|
|
404
|
+
const preferredFamily = familyMatch ? familyMatch[1] : (s < 0.2 ? 'slate' : null);
|
|
405
|
+
if (preferredFamily === 'slate') {
|
|
406
|
+
const slateOrder = targetTowardWhite
|
|
407
|
+
? ['slate-300', 'slate-200', 'slate-100', 'slate-50', 'white']
|
|
408
|
+
: ['slate-700', 'slate-800', 'slate-900', 'slate-950', 'black'];
|
|
409
|
+
for (const tok of slateOrder) {
|
|
410
|
+
if ((computeContrastRatio(TAILWIND_HEX_PALETTE[tok], bgHex) || 0) >= minRatio) {
|
|
411
|
+
return { hex: solvedHex, tailwindClass: `text-${tok}`, ratio: computeContrastRatio(solvedHex, bgHex) };
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
let bestToken = null;
|
|
416
|
+
let bestScore = Infinity;
|
|
417
|
+
for (const [tok, tokHex] of Object.entries(TAILWIND_HEX_PALETTE)) {
|
|
418
|
+
if ((computeContrastRatio(tokHex, bgHex) || 0) < minRatio) continue;
|
|
419
|
+
const rgb = parseHexColor(tokHex);
|
|
420
|
+
const dist = Math.hypot(rgb[0] - solvedRgb[0], rgb[1] - solvedRgb[1], rgb[2] - solvedRgb[2]);
|
|
421
|
+
const bonus = preferredFamily && tok.startsWith(`${preferredFamily}-`) ? -85 : 0;
|
|
422
|
+
if (dist + bonus < bestScore) { bestScore = dist + bonus; bestToken = tok; }
|
|
423
|
+
}
|
|
424
|
+
return {
|
|
425
|
+
hex: solvedHex,
|
|
426
|
+
tailwindClass: bestToken ? `text-${bestToken}` : `text-[${solvedHex}]`,
|
|
427
|
+
ratio: computeContrastRatio(solvedHex, bgHex),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const VOID_HTML_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
|
|
432
|
+
|
|
433
|
+
function buildLineLookup(text) {
|
|
434
|
+
const starts = [0];
|
|
435
|
+
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);
|
|
436
|
+
return (offset) => {
|
|
437
|
+
let lo = 0; let hi = starts.length - 1;
|
|
438
|
+
while (lo <= hi) {
|
|
439
|
+
const mid = (lo + hi) >> 1;
|
|
440
|
+
if (starts[mid] <= offset) lo = mid + 1; else hi = mid - 1;
|
|
441
|
+
}
|
|
442
|
+
return hi + 1;
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const UNITLESS_JSX_PROPS = new Set([
|
|
447
|
+
'opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex', 'flexGrow', 'flexShrink', 'order', 'zoom', 'scale', 'aspectRatio', 'gridRow', 'gridColumn',
|
|
448
|
+
]);
|
|
449
|
+
|
|
450
|
+
function parseCssRulesAst(source, baseOffset = 0, lineAt = buildLineLookup(source), recursionDepth = 0) {
|
|
451
|
+
const rules = [];
|
|
452
|
+
const len = source.length;
|
|
453
|
+
let i = 0;
|
|
454
|
+
while (i < len) {
|
|
455
|
+
while (i < len && /\s/.test(source[i])) i++;
|
|
456
|
+
if (i + 1 < len && source[i] === '/' && source[i + 1] === '*') {
|
|
457
|
+
const endC = source.indexOf('*/', i + 2);
|
|
458
|
+
i = endC === -1 ? len : endC + 2;
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
if (i >= len) break;
|
|
462
|
+
const openBrace = source.indexOf('{', i);
|
|
463
|
+
if (source[i] === '@') {
|
|
464
|
+
const semi = source.indexOf(';', i);
|
|
465
|
+
if (semi !== -1 && (openBrace === -1 || semi < openBrace)) {
|
|
466
|
+
i = semi + 1;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
if (openBrace === -1) break;
|
|
471
|
+
const selector = source.slice(i, openBrace).trim();
|
|
472
|
+
let depth = 1; let j = openBrace + 1;
|
|
473
|
+
while (j < len && depth > 0) {
|
|
474
|
+
if (source[j] === '{') depth++; else if (source[j] === '}') depth--;
|
|
475
|
+
j++;
|
|
476
|
+
}
|
|
477
|
+
const closeBrace = j - 1;
|
|
478
|
+
if (depth !== 0) break;
|
|
479
|
+
if (selector.startsWith('@')) {
|
|
480
|
+
if (recursionDepth < 8 && /^@(?:media|supports|layer|container|scope)\b/i.test(selector)) {
|
|
481
|
+
rules.push(...parseCssRulesAst(source.slice(openBrace + 1, closeBrace), baseOffset + openBrace + 1, lineAt, recursionDepth + 1));
|
|
482
|
+
}
|
|
483
|
+
i = j;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
const declarations = {};
|
|
487
|
+
for (const part of splitCssDeclarations(source.slice(openBrace + 1, closeBrace))) {
|
|
488
|
+
const colon = part.indexOf(':');
|
|
489
|
+
if (colon > 0) declarations[part.slice(0, colon).trim().toLowerCase()] = part.slice(colon + 1).trim();
|
|
490
|
+
}
|
|
491
|
+
const startOffset = baseOffset + i;
|
|
492
|
+
const endOffset = baseOffset + closeBrace + 1;
|
|
493
|
+
rules.push({
|
|
494
|
+
type: 'CssRule', selector, declarations, bodyText: source.slice(openBrace + 1, closeBrace),
|
|
495
|
+
startOffset, endOffset, startLine: lineAt(startOffset), endLine: lineAt(endOffset), rawRule: source.slice(i, closeBrace + 1),
|
|
496
|
+
});
|
|
497
|
+
i = closeBrace + 1;
|
|
498
|
+
}
|
|
499
|
+
return rules;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function splitCssDeclarations(str) {
|
|
503
|
+
const out = [];
|
|
504
|
+
let start = 0; let paren = 0; let quote = null;
|
|
505
|
+
for (let i = 0; i < str.length; i++) {
|
|
506
|
+
const ch = str[i];
|
|
507
|
+
if (quote) { if (ch === '\\') i++; else if (ch === quote) quote = null; }
|
|
508
|
+
else if (ch === '"' || ch === "'") quote = ch;
|
|
509
|
+
else if (ch === '(') paren++; else if (ch === ')' && paren > 0) paren--;
|
|
510
|
+
else if (ch === ';' && paren === 0) { out.push(str.slice(start, i)); start = i + 1; }
|
|
511
|
+
}
|
|
512
|
+
out.push(str.slice(start));
|
|
513
|
+
return out;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function extractSafeColorHex(val) {
|
|
517
|
+
const cleaned = String(val || '').replace(/(?:url|image-set)\s*\([^()]*\)/gi, ' ');
|
|
518
|
+
return /(#[0-9a-fA-F]{3,6})\b/.exec(cleaned);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function escapeCssIdent(ident) {
|
|
522
|
+
return String(ident || '').replace(/[^a-zA-Z0-9_-]/g, (ch) => `\\${ch}`);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function unescapeCssIdent(ident) {
|
|
526
|
+
return String(ident || '').replace(/\\(.)/g, '$1');
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function splitTopLevelCommas(str) {
|
|
530
|
+
const out = [];
|
|
531
|
+
let start = 0; let paren = 0; let brace = 0; let quote = null;
|
|
532
|
+
for (let i = 0; i < str.length; i++) {
|
|
533
|
+
const ch = str[i];
|
|
534
|
+
if (quote) { if (ch === '\\') i++; else if (ch === quote) quote = null; }
|
|
535
|
+
else if (ch === '"' || ch === "'" || ch === '`') quote = ch;
|
|
536
|
+
else if (ch === '(') paren++; else if (ch === ')' && paren > 0) paren--;
|
|
537
|
+
else if (ch === '{') brace++; else if (ch === '}' && brace > 0) brace--;
|
|
538
|
+
else if (ch === ',' && paren === 0 && brace === 0) { out.push(str.slice(start, i)); start = i + 1; }
|
|
539
|
+
}
|
|
540
|
+
out.push(str.slice(start));
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function formatJsxStyleValue(v) {
|
|
545
|
+
if (typeof v === 'number') return String(v);
|
|
546
|
+
const s = String(v);
|
|
547
|
+
if (s.includes("'")) return JSON.stringify(s);
|
|
548
|
+
return `'${s.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r')}'`;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function parseStyleEntries(attrsRaw) {
|
|
552
|
+
const sMatch = /(?:^|[\s"'`}])(style\s*=)/.exec(attrsRaw || '');
|
|
553
|
+
if (sMatch) {
|
|
554
|
+
const sIdx = sMatch.index + (sMatch[0].length - sMatch[1].length);
|
|
555
|
+
let cur = sIdx + sMatch[1].length;
|
|
556
|
+
while (cur < attrsRaw.length && /\s/.test(attrsRaw[cur])) cur++;
|
|
557
|
+
if (attrsRaw.startsWith('{{', cur)) {
|
|
558
|
+
let d = 2; let k = cur + 2; let quote = null;
|
|
559
|
+
while (k < attrsRaw.length && d > 0) {
|
|
560
|
+
const ch = attrsRaw[k];
|
|
561
|
+
if (quote) { if (ch === '\\') k++; else if (ch === quote) quote = null; }
|
|
562
|
+
else if (ch === '"' || ch === "'" || ch === '`') quote = ch;
|
|
563
|
+
else if (ch === '{') d++; else if (ch === '}') d--;
|
|
564
|
+
k++;
|
|
565
|
+
}
|
|
566
|
+
const inner = attrsRaw.slice(cur + 2, Math.max(cur + 2, k - 2));
|
|
567
|
+
const map = {};
|
|
568
|
+
const preserved = [];
|
|
569
|
+
for (const part of splitTopLevelCommas(inner)) {
|
|
570
|
+
const trimmed = part.trim();
|
|
571
|
+
if (!trimmed) continue;
|
|
572
|
+
const m = /^([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:\s*(?:'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"|(-?\d+(?:\.\d+)?))$/.exec(trimmed);
|
|
573
|
+
if (m) {
|
|
574
|
+
const key = m[1];
|
|
575
|
+
if (m[4] !== undefined) {
|
|
576
|
+
map[key] = UNITLESS_JSX_PROPS.has(key) ? Number(m[4]) : `${m[4]}px`;
|
|
577
|
+
} else {
|
|
578
|
+
const rawStr = m[2] !== undefined ? m[2].replace(/\\'/g, "'").replace(/\\\\/g, '\\') : m[3].replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
579
|
+
map[key] = rawStr;
|
|
580
|
+
}
|
|
581
|
+
preserved.push({ type: 'prop', key, static: true });
|
|
582
|
+
} else {
|
|
583
|
+
const dynKey = /^([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/.exec(trimmed);
|
|
584
|
+
if (dynKey) preserved.push({ type: 'prop', key: dynKey[1], static: false, raw: trimmed });
|
|
585
|
+
else preserved.push({ type: 'raw', raw: trimmed });
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return { kind: 'jsx', rawMatch: attrsRaw.slice(sIdx, k), map, preserved };
|
|
589
|
+
}
|
|
590
|
+
if (attrsRaw[cur] === '"' || attrsRaw[cur] === "'") {
|
|
591
|
+
const q = attrsRaw[cur];
|
|
592
|
+
const endQ = attrsRaw.indexOf(q, cur + 1);
|
|
593
|
+
if (endQ > cur) {
|
|
594
|
+
const map = {};
|
|
595
|
+
for (const decl of splitCssDeclarations(attrsRaw.slice(cur + 1, endQ))) {
|
|
596
|
+
const idx = decl.indexOf(':');
|
|
597
|
+
if (idx > 0) map[decl.slice(0, idx).trim().toLowerCase()] = decl.slice(idx + 1).trim();
|
|
598
|
+
}
|
|
599
|
+
return { kind: 'css', rawMatch: attrsRaw.slice(sIdx, endQ + 1), map, preserved: [] };
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return { kind: null, rawMatch: null, map: {}, preserved: [] };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function serializeStyleAttr(kind, map, preserved = []) {
|
|
607
|
+
const toCamel = (k) => k.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
|
|
608
|
+
const toKebab = (k) => k.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);
|
|
609
|
+
if (kind === 'jsx') {
|
|
610
|
+
const normalizedMap = new Map();
|
|
611
|
+
for (const [k, v] of Object.entries(map)) {
|
|
612
|
+
if (v !== undefined && v !== '') normalizedMap.set(toCamel(k), v);
|
|
613
|
+
}
|
|
614
|
+
const emitted = new Set();
|
|
615
|
+
const out = [];
|
|
616
|
+
for (const item of preserved) {
|
|
617
|
+
if (typeof item === 'string') { out.push(item); continue; }
|
|
618
|
+
if (item.type === 'raw') { out.push(item.raw); continue; }
|
|
619
|
+
const ck = toCamel(item.key);
|
|
620
|
+
if (emitted.has(ck)) continue;
|
|
621
|
+
if (normalizedMap.has(ck)) {
|
|
622
|
+
out.push(`${ck}: ${formatJsxStyleValue(normalizedMap.get(ck))}`);
|
|
623
|
+
emitted.add(ck);
|
|
624
|
+
} else if (!item.static) {
|
|
625
|
+
out.push(item.raw);
|
|
626
|
+
emitted.add(ck);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
for (const [ck, v] of normalizedMap.entries()) {
|
|
630
|
+
if (!emitted.has(ck)) out.push(`${ck}: ${formatJsxStyleValue(v)}`);
|
|
631
|
+
}
|
|
632
|
+
return `style={{ ${out.join(', ')} }}`;
|
|
633
|
+
}
|
|
634
|
+
const entries = Object.entries(map).filter(([, v]) => v !== undefined && v !== '');
|
|
635
|
+
return `style="${entries.map(([k, v]) => `${toKebab(k)}: ${v}`).join('; ')}"`;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function resolveColorFromNode(classes, styleMap, kind) {
|
|
639
|
+
const styleVal = kind === 'fg' ? styleMap.color : (styleMap.backgroundColor || styleMap['background-color'] || styleMap.background);
|
|
640
|
+
const styleHex = styleVal && extractSafeColorHex(styleVal);
|
|
641
|
+
if (styleHex) return { hex: styleHex[1], token: null, fromStyle: true };
|
|
642
|
+
const prefix = kind === 'fg' ? 'text-' : 'bg-';
|
|
643
|
+
for (const cls of classes) {
|
|
644
|
+
if (!cls.startsWith(prefix)) continue;
|
|
645
|
+
const suffix = cls.slice(prefix.length);
|
|
646
|
+
const arb = /^\[(#[0-9a-fA-F]{3,6})\]$/.exec(suffix);
|
|
647
|
+
if (arb) return { hex: arb[1], token: cls, fromStyle: false };
|
|
648
|
+
if (Object.hasOwn(TAILWIND_HEX_PALETTE, suffix)) return { hex: TAILWIND_HEX_PALETTE[suffix], token: cls, fromStyle: false };
|
|
649
|
+
}
|
|
650
|
+
return null;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function parseDesignAst(source, defaultBgHex = '#0f172a') {
|
|
654
|
+
const text = String(source || '');
|
|
655
|
+
const lineAt = buildLineLookup(text);
|
|
656
|
+
const isPureCss = !text.includes('<') && text.includes('{') && text.includes(':');
|
|
657
|
+
if (isPureCss) {
|
|
658
|
+
return { root: { type: 'Root', astPath: 'root', inheritedBgHex: defaultBgHex, children: [] }, nodes: [], cssRules: parseCssRulesAst(text, 0, lineAt), language: 'css' };
|
|
659
|
+
}
|
|
660
|
+
const root = { type: 'Root', astPath: 'root', inheritedBgHex: defaultBgHex, children: [] };
|
|
661
|
+
const stack = [root];
|
|
662
|
+
const nodes = [];
|
|
663
|
+
const cssRules = [];
|
|
664
|
+
const len = text.length;
|
|
665
|
+
let i = 0;
|
|
666
|
+
|
|
667
|
+
while (i < len) {
|
|
668
|
+
const lt = text.indexOf('<', i);
|
|
669
|
+
if (lt === -1) break;
|
|
670
|
+
if (text.startsWith('<!--', lt)) {
|
|
671
|
+
const endC = text.indexOf('-->', lt + 4);
|
|
672
|
+
i = endC === -1 ? len : endC + 3;
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
const lineStart = text.lastIndexOf('\n', lt - 1) + 1;
|
|
676
|
+
if (/^\s*\/\//.test(text.slice(lineStart, lt))) {
|
|
677
|
+
const nl = text.indexOf('\n', lt);
|
|
678
|
+
i = nl === -1 ? len : nl + 1;
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
let cur = lt + 1;
|
|
682
|
+
let closing = false;
|
|
683
|
+
if (text[cur] === '/') { closing = true; cur++; }
|
|
684
|
+
if (!/[a-zA-Z]/.test(text[cur] || '')) { i = lt + 1; continue; }
|
|
685
|
+
const nameStart = cur;
|
|
686
|
+
while (cur < len && /[a-zA-Z0-9._:-]/.test(text[cur])) cur++;
|
|
687
|
+
const tagName = text.slice(nameStart, cur);
|
|
688
|
+
|
|
689
|
+
let braceDepth = 0;
|
|
690
|
+
let quote = null;
|
|
691
|
+
while (cur < len) {
|
|
692
|
+
const ch = text[cur];
|
|
693
|
+
if (quote) {
|
|
694
|
+
if (ch === '\\') cur++;
|
|
695
|
+
else if (ch === quote) quote = null;
|
|
696
|
+
} else if (ch === '/' && text[cur + 1] === '*' && braceDepth > 0) {
|
|
697
|
+
const cEnd = text.indexOf('*/', cur + 2);
|
|
698
|
+
cur = cEnd === -1 ? len : cEnd + 1;
|
|
699
|
+
} else if (ch === '/' && text[cur + 1] === '/' && braceDepth > 0) {
|
|
700
|
+
const nl = text.indexOf('\n', cur + 2);
|
|
701
|
+
cur = nl === -1 ? len : nl;
|
|
702
|
+
} else if (ch === '"' || ch === "'" || ch === '`') {
|
|
703
|
+
quote = ch;
|
|
704
|
+
} else if (ch === '{') {
|
|
705
|
+
braceDepth++;
|
|
706
|
+
} else if (ch === '}' && braceDepth > 0) {
|
|
707
|
+
braceDepth--;
|
|
708
|
+
} else if (ch === '>' && braceDepth === 0) {
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
cur++;
|
|
712
|
+
}
|
|
713
|
+
if (cur >= len) break;
|
|
714
|
+
const tagEnd = cur + 1;
|
|
715
|
+
if (closing) {
|
|
716
|
+
for (let s = stack.length - 1; s >= 1; s--) {
|
|
717
|
+
if (stack[s].tagName === tagName) { stack.length = s; break; }
|
|
718
|
+
}
|
|
719
|
+
i = tagEnd;
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
const selfClose = text[cur - 1] === '/' ? '/' : '';
|
|
724
|
+
const attrsRaw = text.slice(nameStart + tagName.length, selfClose ? cur - 1 : cur);
|
|
725
|
+
const tagLower = tagName.toLowerCase();
|
|
726
|
+
if ((tagLower === 'style' || tagLower === 'script') && !selfClose) {
|
|
727
|
+
const closeRe = tagLower === 'style' ? /<\/style\b[^<>]*>/ig : /<\/script\b[^<>]*>/ig;
|
|
728
|
+
closeRe.lastIndex = tagEnd;
|
|
729
|
+
const closeMatch = closeRe.exec(text);
|
|
730
|
+
if (!closeMatch) break;
|
|
731
|
+
if (tagLower === 'style') {
|
|
732
|
+
const styleBody = text.slice(tagEnd, closeMatch.index);
|
|
733
|
+
if (!styleBody.trimStart().startsWith('{')) cssRules.push(...parseCssRulesAst(styleBody, tagEnd, lineAt));
|
|
734
|
+
}
|
|
735
|
+
i = closeMatch.index + closeMatch[0].length;
|
|
736
|
+
continue;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const parent = stack[stack.length - 1];
|
|
740
|
+
const idMatch = /(?:^|[\s"'`}])id=(?:"([^"]+)"|'([^']+)')/.exec(attrsRaw);
|
|
741
|
+
const classMatch = /(?:^|[\s"'`}])((class|className)=(?:"([^"]*)"|'([^']*)'))/.exec(attrsRaw);
|
|
742
|
+
const classes = classMatch ? (classMatch[3] ?? classMatch[4] ?? '').trim().split(/\s+/).filter(Boolean) : [];
|
|
743
|
+
const styleInfo = parseStyleEntries(attrsRaw);
|
|
744
|
+
const id = idMatch ? (idMatch[1] ?? idMatch[2]) : null;
|
|
745
|
+
const selector = id ? `#${escapeCssIdent(id)}` : (classes[0] && !classes[0].includes('[') && !classes[0].includes(':') ? `${tagName}.${escapeCssIdent(classes[0])}` : tagName);
|
|
746
|
+
const matchedCssBg = cssRules.find((r) => r.selector === selector || (id && r.selector === `#${escapeCssIdent(id)}`) || classes.some((c) => r.selector === `.${escapeCssIdent(c)}`));
|
|
747
|
+
const cssBgHex = matchedCssBg && extractSafeColorHex(matchedCssBg.declarations['background-color'] || matchedCssBg.declarations.background || '');
|
|
748
|
+
const ownBg = resolveColorFromNode(classes, styleInfo.map, 'bg') || (cssBgHex ? { hex: cssBgHex[1], token: null, fromStyle: true } : null);
|
|
749
|
+
const effectiveBgHex = ownBg ? ownBg.hex : parent.inheritedBgHex;
|
|
750
|
+
const siblingIdx = parent.children.filter((c) => c.tagName === tagName).length;
|
|
751
|
+
const seg = `${tagName}${id ? `#${id}` : (classes[0] ? `.${classes[0]}` : '')}[${siblingIdx}]`;
|
|
752
|
+
const openTag = text.slice(lt, tagEnd);
|
|
753
|
+
const node = {
|
|
754
|
+
type: 'Element',
|
|
755
|
+
tagName,
|
|
756
|
+
id,
|
|
757
|
+
selector,
|
|
758
|
+
astPath: parent === root ? seg : `${parent.astPath} > ${seg}`,
|
|
759
|
+
openTag,
|
|
760
|
+
attrsRaw,
|
|
761
|
+
selfClose,
|
|
762
|
+
startOffset: lt,
|
|
763
|
+
endOffset: tagEnd,
|
|
764
|
+
startLine: lineAt(lt),
|
|
765
|
+
endLine: lineAt(tagEnd),
|
|
766
|
+
classAttrName: classMatch ? classMatch[2] : (/\bclassName=/.test(text) ? 'className' : 'class'),
|
|
767
|
+
classRawMatch: classMatch ? classMatch[1] : null,
|
|
768
|
+
classes,
|
|
769
|
+
styleInfo,
|
|
770
|
+
ownBgHex: ownBg ? ownBg.hex : null,
|
|
771
|
+
inheritedBgHex: effectiveBgHex,
|
|
772
|
+
children: [],
|
|
773
|
+
};
|
|
774
|
+
parent.children.push(node);
|
|
775
|
+
nodes.push(node);
|
|
776
|
+
if (!selfClose && !VOID_HTML_TAGS.has(tagName.toLowerCase())) stack.push(node);
|
|
777
|
+
i = tagEnd;
|
|
778
|
+
}
|
|
779
|
+
return { root, nodes, cssRules, language: /\bclassName=|\bstyle=\{\{/.test(text) ? 'jsx' : 'html' };
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
const SAFE_VISUAL_SELECTOR_RE = /^(?:#[a-zA-Z0-9_\\-]+|\.[a-zA-Z0-9_\\-]+|[a-zA-Z][a-zA-Z0-9_-]*(?:(?:#|\.)[a-zA-Z0-9_\\-]+)?)$/;
|
|
783
|
+
|
|
784
|
+
function normalizeVisualFindings(findings = []) {
|
|
785
|
+
const rawList = Array.isArray(findings) ? findings : (findings ? [findings] : []);
|
|
786
|
+
return rawList
|
|
787
|
+
.slice(0, 64)
|
|
788
|
+
.filter((item) => typeof item === 'string' || (item !== null && typeof item === 'object' && !Array.isArray(item)))
|
|
789
|
+
.map((item) => {
|
|
790
|
+
if (typeof item === 'string') {
|
|
791
|
+
const selMatch = /(#[a-z0-9_-]+|\.[a-z0-9_-]+|\b(?:button|a|p|span|h[1-6]|div|section|img|input)(?:\.[a-z0-9_-]+)?)/i.exec(item);
|
|
792
|
+
const issue = /colorblind|red\/green/i.test(item) ? 'colorblind_unsafe_status'
|
|
793
|
+
: /contrast/i.test(item) ? 'low_contrast'
|
|
794
|
+
: /tap|touch|target|44px|small\s+button/i.test(item) ? 'undersized_tap_target'
|
|
795
|
+
: /overflow|clip|viewport|horizontal/i.test(item) ? 'fixed_width_mobile_overflow'
|
|
796
|
+
: /focus|outline|ring/i.test(item) ? 'missing_focus_ring'
|
|
797
|
+
: /cls|shift|aspect|dimension/i.test(item) ? 'cls_unsized_media' : 'low_contrast';
|
|
798
|
+
return { selector: selMatch ? selMatch[1] : null, issue, raw: item };
|
|
799
|
+
}
|
|
800
|
+
const rawSel = typeof item.selector === 'string' ? item.selector.trim() : '';
|
|
801
|
+
return {
|
|
802
|
+
...item,
|
|
803
|
+
selector: rawSel && SAFE_VISUAL_SELECTOR_RE.test(rawSel) ? rawSel : null,
|
|
804
|
+
fgHex: typeof (item.fgHex || item.foregroundHex) === 'string' ? (item.fgHex || item.foregroundHex) : null,
|
|
805
|
+
bgHex: typeof (item.bgHex || item.backgroundHex) === 'string' ? (item.bgHex || item.backgroundHex) : null,
|
|
806
|
+
issue: String(item.issue || item.type || item.code || 'low_contrast'),
|
|
807
|
+
};
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
function nodeMatchesSelector(node, sel) {
|
|
812
|
+
if (!sel) return true;
|
|
813
|
+
const s = String(sel).trim();
|
|
814
|
+
if (s === node.astPath || s === node.selector || s === node.tagName) return true;
|
|
815
|
+
if (s.startsWith('#')) return node.id === unescapeCssIdent(s.slice(1));
|
|
816
|
+
if (s.startsWith('.')) return node.classes.includes(unescapeCssIdent(s.slice(1)));
|
|
817
|
+
const dotIdx = s.search(/(?<!\\)\./);
|
|
818
|
+
if (dotIdx === -1) return node.tagName.toLowerCase() === s.toLowerCase();
|
|
819
|
+
const tag = s.slice(0, dotIdx);
|
|
820
|
+
const cls = unescapeCssIdent(s.slice(dotIdx + 1));
|
|
821
|
+
return (!tag || node.tagName.toLowerCase() === tag.toLowerCase()) && (!cls || node.classes.includes(cls));
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function inspectCssAstRules(source, ast, visualQueue, options = {}) {
|
|
825
|
+
const minContrast = Number(options.minContrast || 4.5);
|
|
826
|
+
const defaultBg = options.defaultBgHex || '#0f172a';
|
|
827
|
+
const patches = [];
|
|
828
|
+
const inlineEdits = [];
|
|
829
|
+
const cssOverrides = [];
|
|
830
|
+
for (const rule of ast.cssRules || []) {
|
|
831
|
+
const decls = { ...rule.declarations };
|
|
832
|
+
const ruleProps = {};
|
|
833
|
+
const fgM = extractSafeColorHex(decls.color || '');
|
|
834
|
+
const bgM = extractSafeColorHex(decls['background-color'] || decls.background || '') || [null, defaultBg];
|
|
835
|
+
const vfC = visualQueue.find((v) => (!v.selector || v.selector === rule.selector) && /contrast/i.test(v.issue));
|
|
836
|
+
if (fgM || vfC) {
|
|
837
|
+
const fgHex = vfC?.fgHex || fgM?.[1] || '#64748b';
|
|
838
|
+
const bgHex = vfC?.bgHex || bgM[1] || defaultBg;
|
|
839
|
+
const ratio = computeContrastRatio(fgHex, bgHex);
|
|
840
|
+
if (vfC || (ratio !== null && ratio < minContrast)) {
|
|
841
|
+
const solved = solveAccessibleForeground(fgHex, bgHex, minContrast);
|
|
842
|
+
decls.color = solved.hex;
|
|
843
|
+
ruleProps.color = solved.hex;
|
|
844
|
+
patches.push({ type: 'low_contrast', element: 'CssRule', selector: rule.selector, astPath: `css:${rule.selector}`, measuredRatio: ratio, targetRatio: minContrast, fixedRatio: solved.ratio, cssOverride: `color: ${solved.hex};`, tailwindPatch: { remove: [], add: [solved.tailwindClass] } });
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
const rawH = decls.height || decls['min-height'];
|
|
848
|
+
const hPx = rawH && /^\d+(?:\.\d+)?px$/.test(rawH) ? parseFloat(rawH) : null;
|
|
849
|
+
if ((/button|btn|cta|nav-link|input/i.test(rule.selector) && hPx !== null && hPx < 44) || visualQueue.some((v) => v.selector === rule.selector && /tap|touch|target/i.test(v.issue))) {
|
|
850
|
+
delete decls.height;
|
|
851
|
+
decls['min-height'] = '44px';
|
|
852
|
+
decls['min-width'] = '44px';
|
|
853
|
+
ruleProps['min-height'] = '44px';
|
|
854
|
+
ruleProps['min-width'] = '44px';
|
|
855
|
+
patches.push({ type: 'undersized_tap_target', element: 'CssRule', selector: rule.selector, astPath: `css:${rule.selector}`, cssOverride: 'min-height: 44px; min-width: 44px;', tailwindPatch: { remove: [], add: ['min-h-11', 'min-w-11'] } });
|
|
856
|
+
}
|
|
857
|
+
if (Object.keys(ruleProps).length > 0) {
|
|
858
|
+
const body = Object.entries(decls).map(([k, v]) => `${k}: ${v};`).join(' ');
|
|
859
|
+
const afterRule = `${rule.selector} { ${body} }`;
|
|
860
|
+
inlineEdits.push({ filePath: options.filePath || null, nodeType: 'CssRule', astPath: `css:${rule.selector}`, selector: rule.selector, startOffset: rule.startOffset, endOffset: rule.endOffset, startLine: rule.startLine, endLine: rule.endLine, expectedChunkHash: computeChunkHash(rule.rawRule), before: rule.rawRule, after: afterRule });
|
|
861
|
+
cssOverrides.push({ selector: rule.selector, properties: ruleProps, cssRule: `${rule.selector} { ${Object.entries(ruleProps).map(([k, v]) => `${k}: ${v};`).join(' ')} }` });
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return { patches, inlineEdits, cssOverrides };
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function inspectAndPatchDesignSource(source, options = {}) {
|
|
868
|
+
const rawSource = String(source || '');
|
|
869
|
+
const minContrast = Number(options.minContrast || 4.5);
|
|
870
|
+
const defaultBg = options.defaultBgHex || '#0f172a';
|
|
871
|
+
const allowTailwind = options.allowTailwind !== false;
|
|
872
|
+
const ast = parseDesignAst(rawSource, defaultBg);
|
|
873
|
+
const visualQueue = normalizeVisualFindings(options.visualFindings);
|
|
874
|
+
const cssPass = inspectCssAstRules(rawSource, ast, visualQueue, { ...options, minContrast, defaultBgHex: defaultBg });
|
|
875
|
+
const patches = [...cssPass.patches];
|
|
876
|
+
const inlineEdits = [...cssPass.inlineEdits];
|
|
877
|
+
const cssOverrides = [...cssPass.cssOverrides];
|
|
878
|
+
const tailwindAdjustments = [];
|
|
879
|
+
|
|
880
|
+
for (const node of ast.nodes) {
|
|
881
|
+
let classes = [...node.classes];
|
|
882
|
+
const styleMap = { ...node.styleInfo.map };
|
|
883
|
+
let mutatedClasses = false;
|
|
884
|
+
let mutatedStyle = false;
|
|
885
|
+
const nodeCssProps = {};
|
|
886
|
+
const matchedVisuals = visualQueue.filter((vf) => nodeMatchesSelector(node, vf.selector));
|
|
887
|
+
|
|
888
|
+
// 1. Contrast AST check + visual-model `low_contrast` remediation (uses ancestor-inherited or <style> bg)
|
|
889
|
+
const fgInfo = resolveColorFromNode(classes, styleMap, 'fg');
|
|
890
|
+
const vfContrast = matchedVisuals.find((v) => /contrast/i.test(v.issue));
|
|
891
|
+
const effFgHex = vfContrast?.fgHex || fgInfo?.hex;
|
|
892
|
+
const effBgHex = vfContrast?.bgHex || node.inheritedBgHex || defaultBg;
|
|
893
|
+
if (effFgHex || vfContrast) {
|
|
894
|
+
const startFg = effFgHex || '#64748b';
|
|
895
|
+
const targetMin = Number(vfContrast?.minContrast || minContrast);
|
|
896
|
+
const currentRatio = computeContrastRatio(startFg, effBgHex);
|
|
897
|
+
if (vfContrast || (currentRatio !== null && currentRatio < targetMin)) {
|
|
898
|
+
const solved = solveAccessibleForeground(startFg, effBgHex, targetMin, fgInfo?.token || '');
|
|
899
|
+
nodeCssProps.color = solved.hex;
|
|
900
|
+
if (!allowTailwind || fgInfo?.fromStyle || node.styleInfo.kind) {
|
|
901
|
+
styleMap.color = solved.hex;
|
|
902
|
+
mutatedStyle = true;
|
|
903
|
+
} else {
|
|
904
|
+
classes = fgInfo?.token ? classes.map((c) => (c === fgInfo.token ? solved.tailwindClass : c)) : [...classes, solved.tailwindClass];
|
|
905
|
+
mutatedClasses = true;
|
|
906
|
+
}
|
|
907
|
+
const twPatch = { remove: fgInfo?.token ? [fgInfo.token] : [], add: [solved.tailwindClass] };
|
|
908
|
+
tailwindAdjustments.push({ selector: node.selector, astPath: node.astPath, ...twPatch });
|
|
909
|
+
patches.push({
|
|
910
|
+
type: 'low_contrast', element: node.tagName, selector: node.selector, astPath: node.astPath,
|
|
911
|
+
measuredRatio: currentRatio, targetRatio: targetMin, fixedRatio: solved.ratio,
|
|
912
|
+
cssOverride: `color: ${solved.hex};`, tailwindPatch: twPatch,
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// 2. Interactive tap-target (<44px) & focus-ring AST check + visual-model remediation
|
|
918
|
+
const isInteractive = /^(button|a|input|select)$/i.test(node.tagName) || /\brole=["']button["']/i.test(node.attrsRaw);
|
|
919
|
+
const vfTap = matchedVisuals.find((v) => /tap|touch|target/i.test(v.issue));
|
|
920
|
+
if (isInteractive || vfTap) {
|
|
921
|
+
const smallTw = classes.filter((c) => /^(h-[3456789]|h-3\.5|p-[01]|p-0\.5|py-(?:0|0\.5|1)|px-(?:0|0\.5|1|1\.5)|text-\[(?:9|10)px\])$/.test(c));
|
|
922
|
+
const rawCssH = styleMap.height || styleMap.minHeight || styleMap['min-height'];
|
|
923
|
+
const cssHeightPx = rawCssH ? parseFloat(rawCssH) : null;
|
|
924
|
+
if (vfTap || smallTw.length > 0 || (cssHeightPx !== null && cssHeightPx < 44)) {
|
|
925
|
+
nodeCssProps['min-height'] = '44px';
|
|
926
|
+
nodeCssProps['min-width'] = '44px';
|
|
927
|
+
const addTw = ['min-h-11', 'min-w-11', 'px-4', 'py-2.5'];
|
|
928
|
+
if (!allowTailwind || (node.styleInfo.kind && cssHeightPx !== null && cssHeightPx < 44)) {
|
|
929
|
+
delete styleMap.height;
|
|
930
|
+
delete styleMap['min-height'];
|
|
931
|
+
styleMap.minHeight = '44px';
|
|
932
|
+
styleMap.minWidth = '44px';
|
|
933
|
+
mutatedStyle = true;
|
|
934
|
+
} else {
|
|
935
|
+
classes = classes.filter((c) => !smallTw.includes(c));
|
|
936
|
+
for (const cls of addTw) if (!classes.includes(cls)) classes.push(cls);
|
|
937
|
+
mutatedClasses = true;
|
|
938
|
+
}
|
|
939
|
+
const twPatch = { remove: smallTw, add: addTw };
|
|
940
|
+
tailwindAdjustments.push({ selector: node.selector, astPath: node.astPath, ...twPatch });
|
|
941
|
+
patches.push({
|
|
942
|
+
type: 'undersized_tap_target', element: node.tagName, selector: node.selector, astPath: node.astPath,
|
|
943
|
+
cssOverride: 'min-height: 44px; min-width: 44px; padding: 0.625rem 1rem;', tailwindPatch: twPatch,
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
const vfFocus = matchedVisuals.find((v) => /focus|ring/i.test(v.issue));
|
|
947
|
+
if (vfFocus || (classes.includes('outline-none') && !classes.some((c) => c.startsWith('focus-visible:ring') || c.startsWith('focus:ring')))) {
|
|
948
|
+
const ringClasses = ['focus-visible:ring-2', 'focus-visible:ring-cyan-400', 'focus-visible:ring-offset-2'];
|
|
949
|
+
if (allowTailwind) {
|
|
950
|
+
for (const rc of ringClasses) if (!classes.includes(rc)) classes.push(rc);
|
|
951
|
+
mutatedClasses = true;
|
|
952
|
+
} else {
|
|
953
|
+
styleMap.outline = '2px solid #22d3ee';
|
|
954
|
+
mutatedStyle = true;
|
|
955
|
+
}
|
|
956
|
+
nodeCssProps.outline = '2px solid #22d3ee';
|
|
957
|
+
tailwindAdjustments.push({ selector: node.selector, astPath: node.astPath, remove: [], add: ringClasses });
|
|
958
|
+
patches.push({
|
|
959
|
+
type: 'missing_focus_ring', element: node.tagName, selector: node.selector, astPath: node.astPath,
|
|
960
|
+
cssOverride: 'outline: 2px solid #22d3ee; outline-offset: 2px;', tailwindPatch: { remove: [], add: ringClasses },
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// 3. Mobile horizontal overflow AST check + visual-model remediation
|
|
966
|
+
const fixedTw = classes.find((c) => /^w-\[(\d+)px\]$/.test(c) && Number(/^w-\[(\d+)px\]$/.exec(c)[1]) >= 360);
|
|
967
|
+
const cssWidthPx = styleMap.width && /^\d+(?:\.\d+)?px$/.test(styleMap.width) ? Number.parseFloat(styleMap.width) : null;
|
|
968
|
+
const vfOverflow = matchedVisuals.find((v) => /overflow/i.test(v.issue));
|
|
969
|
+
if (vfOverflow || (fixedTw && !classes.includes('max-w-full')) || (cssWidthPx !== null && cssWidthPx >= 360 && !styleMap.maxWidth && !styleMap['max-width'])) {
|
|
970
|
+
const px = fixedTw ? /^w-\[(\d+)px\]$/.exec(fixedTw)[1] : String(cssWidthPx || vfOverflow?.measuredWidthPx || 640);
|
|
971
|
+
nodeCssProps.width = '100%';
|
|
972
|
+
nodeCssProps['max-width'] = `${px}px`;
|
|
973
|
+
nodeCssProps['box-sizing'] = 'border-box';
|
|
974
|
+
if (!allowTailwind || (node.styleInfo.kind && cssWidthPx !== null)) {
|
|
975
|
+
styleMap.width = '100%';
|
|
976
|
+
styleMap.maxWidth = `${px}px`;
|
|
977
|
+
mutatedStyle = true;
|
|
978
|
+
} else {
|
|
979
|
+
classes = fixedTw ? classes.map((c) => (c === fixedTw ? 'w-full' : c)) : [...classes, 'w-full'];
|
|
980
|
+
if (!classes.includes(`max-w-[${px}px]`)) classes.push(`max-w-[${px}px]`);
|
|
981
|
+
mutatedClasses = true;
|
|
982
|
+
}
|
|
983
|
+
const twPatch = { remove: fixedTw ? [fixedTw] : [], add: ['w-full', `max-w-[${px}px]`] };
|
|
984
|
+
tailwindAdjustments.push({ selector: node.selector, astPath: node.astPath, ...twPatch });
|
|
985
|
+
patches.push({
|
|
986
|
+
type: 'fixed_width_mobile_overflow', element: node.tagName, selector: node.selector, astPath: node.astPath,
|
|
987
|
+
cssOverride: `width: 100%; max-width: ${px}px; box-sizing: border-box;`, tailwindPatch: twPatch,
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// 4. Unbounded media CLS check + colorblind non-hue affordance remediation
|
|
992
|
+
const vfMedia = matchedVisuals.find((v) => /cls|shift|aspect|media/i.test(v.issue));
|
|
993
|
+
const isUnsizedImg = /^img$/i.test(node.tagName) && !/\bwidth=/.test(node.attrsRaw) && !/\bheight=/.test(node.attrsRaw) && !classes.some((c) => c.startsWith('aspect-') || c.startsWith('h-') || c.startsWith('w-'));
|
|
994
|
+
if (vfMedia || isUnsizedImg) {
|
|
995
|
+
const addMediaTw = ['aspect-video', 'w-full', 'h-auto'];
|
|
996
|
+
nodeCssProps['aspect-ratio'] = '16 / 9';
|
|
997
|
+
nodeCssProps.width = '100%';
|
|
998
|
+
if (allowTailwind) {
|
|
999
|
+
for (const mc of addMediaTw) if (!classes.includes(mc)) classes.push(mc);
|
|
1000
|
+
mutatedClasses = true;
|
|
1001
|
+
} else {
|
|
1002
|
+
styleMap.aspectRatio = '16 / 9';
|
|
1003
|
+
styleMap.width = '100%';
|
|
1004
|
+
mutatedStyle = true;
|
|
1005
|
+
}
|
|
1006
|
+
tailwindAdjustments.push({ selector: node.selector, astPath: node.astPath, remove: [], add: addMediaTw });
|
|
1007
|
+
patches.push({
|
|
1008
|
+
type: 'cls_unsized_media', element: node.tagName, selector: node.selector, astPath: node.astPath,
|
|
1009
|
+
cssOverride: 'aspect-ratio: 16 / 9; width: 100%; height: auto;', tailwindPatch: { remove: [], add: addMediaTw },
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
const vfColorblind = matchedVisuals.find((v) => /colorblind/i.test(v.issue));
|
|
1014
|
+
if (vfColorblind) {
|
|
1015
|
+
const cbTw = ['underline', 'decoration-2', 'underline-offset-2', 'font-semibold'];
|
|
1016
|
+
nodeCssProps['text-decoration'] = 'underline 2px solid currentColor';
|
|
1017
|
+
nodeCssProps['font-weight'] = '600';
|
|
1018
|
+
if (allowTailwind) {
|
|
1019
|
+
for (const cc of cbTw) if (!classes.includes(cc)) classes.push(cc);
|
|
1020
|
+
mutatedClasses = true;
|
|
1021
|
+
} else {
|
|
1022
|
+
styleMap.textDecoration = 'underline';
|
|
1023
|
+
styleMap.fontWeight = '600';
|
|
1024
|
+
mutatedStyle = true;
|
|
1025
|
+
}
|
|
1026
|
+
tailwindAdjustments.push({ selector: node.selector, astPath: node.astPath, remove: [], add: cbTw });
|
|
1027
|
+
patches.push({
|
|
1028
|
+
type: 'colorblind_unsafe_status', element: node.tagName, selector: node.selector, astPath: node.astPath,
|
|
1029
|
+
cssOverride: 'text-decoration: underline 2px solid currentColor; font-weight: 600;', tailwindPatch: { remove: [], add: cbTw },
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
if (mutatedClasses || mutatedStyle) {
|
|
1034
|
+
let updatedAttrs = node.attrsRaw;
|
|
1035
|
+
if (mutatedClasses) {
|
|
1036
|
+
const serializedClass = `${node.classAttrName}="${classes.join(' ')}"`;
|
|
1037
|
+
updatedAttrs = node.classRawMatch ? updatedAttrs.replace(node.classRawMatch, () => serializedClass) : `${updatedAttrs} ${serializedClass}`;
|
|
1038
|
+
}
|
|
1039
|
+
if (mutatedStyle) {
|
|
1040
|
+
const serializedStyle = serializeStyleAttr(node.styleInfo.kind || (ast.language === 'jsx' ? 'jsx' : 'css'), styleMap, node.styleInfo.preserved);
|
|
1041
|
+
updatedAttrs = node.styleInfo.rawMatch ? updatedAttrs.replace(node.styleInfo.rawMatch, () => serializedStyle) : `${updatedAttrs} ${serializedStyle}`;
|
|
1042
|
+
}
|
|
1043
|
+
const afterTag = `<${node.tagName}${updatedAttrs}${node.selfClose}>`;
|
|
1044
|
+
inlineEdits.push({
|
|
1045
|
+
filePath: options.filePath || null,
|
|
1046
|
+
nodeType: 'Element',
|
|
1047
|
+
astPath: node.astPath,
|
|
1048
|
+
selector: node.selector,
|
|
1049
|
+
startOffset: node.startOffset,
|
|
1050
|
+
endOffset: node.endOffset,
|
|
1051
|
+
startLine: node.startLine,
|
|
1052
|
+
endLine: node.endLine,
|
|
1053
|
+
expectedChunkHash: computeChunkHash(node.openTag),
|
|
1054
|
+
before: node.openTag,
|
|
1055
|
+
after: afterTag,
|
|
1056
|
+
});
|
|
1057
|
+
if (Object.keys(nodeCssProps).length > 0) {
|
|
1058
|
+
const decls = Object.entries(nodeCssProps).map(([k, v]) => `${k}: ${v};`).join(' ');
|
|
1059
|
+
cssOverrides.push({ selector: node.selector, properties: nodeCssProps, cssRule: `${node.selector} { ${decls} }` });
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Synthesize standalone CSS/Tailwind overrides when visualFindings are provided without matching source elements
|
|
1065
|
+
if (ast.nodes.length === 0 && (ast.cssRules || []).length === 0 && visualQueue.length > 0) {
|
|
1066
|
+
for (const vf of visualQueue) {
|
|
1067
|
+
const sel = vf.selector || '.tg-surface';
|
|
1068
|
+
if (/colorblind/i.test(vf.issue)) {
|
|
1069
|
+
const cssRule = `${sel} { text-decoration: underline 2px solid currentColor; font-weight: 600; }`;
|
|
1070
|
+
cssOverrides.push({ selector: sel, properties: { 'text-decoration': 'underline 2px solid currentColor', 'font-weight': '600' }, cssRule });
|
|
1071
|
+
tailwindAdjustments.push({ selector: sel, astPath: null, remove: [], add: ['underline', 'decoration-2', 'underline-offset-2', 'font-semibold'] });
|
|
1072
|
+
inlineEdits.push({ filePath: options.filePath || null, nodeType: 'CssStyleSheetOverride', astPath: null, selector: sel, startOffset: null, endOffset: null, startLine: null, endLine: null, expectedChunkHash: null, before: '', after: cssRule });
|
|
1073
|
+
patches.push({ type: 'colorblind_unsafe_status', element: null, selector: sel, astPath: null, cssOverride: 'text-decoration: underline 2px solid currentColor; font-weight: 600;', tailwindPatch: { remove: [], add: ['underline', 'decoration-2', 'underline-offset-2', 'font-semibold'] } });
|
|
1074
|
+
} else if (/tap|touch|target/i.test(vf.issue)) {
|
|
1075
|
+
const cssRule = `${sel} { min-height: 44px; min-width: 44px; padding: 0.625rem 1rem; }`;
|
|
1076
|
+
cssOverrides.push({ selector: sel, properties: { 'min-height': '44px', 'min-width': '44px', padding: '0.625rem 1rem' }, cssRule });
|
|
1077
|
+
tailwindAdjustments.push({ selector: sel, astPath: null, remove: [], add: ['min-h-11', 'min-w-11', 'px-4', 'py-2.5'] });
|
|
1078
|
+
inlineEdits.push({ filePath: options.filePath || null, nodeType: 'CssStyleSheetOverride', astPath: null, selector: sel, startOffset: null, endOffset: null, startLine: null, endLine: null, expectedChunkHash: null, before: '', after: cssRule });
|
|
1079
|
+
patches.push({ type: 'undersized_tap_target', element: null, selector: sel, astPath: null, cssOverride: 'min-height: 44px; min-width: 44px; padding: 0.625rem 1rem;', tailwindPatch: { remove: [], add: ['min-h-11', 'min-w-11', 'px-4', 'py-2.5'] } });
|
|
1080
|
+
} else {
|
|
1081
|
+
const startFg = vf.fgHex || '#64748b';
|
|
1082
|
+
const bg = vf.bgHex || defaultBg;
|
|
1083
|
+
const tMin = Number(vf.minContrast || minContrast);
|
|
1084
|
+
const solved = solveAccessibleForeground(startFg, bg, tMin);
|
|
1085
|
+
const cssRule = `${sel} { color: ${solved.hex}; }`;
|
|
1086
|
+
cssOverrides.push({ selector: sel, properties: { color: solved.hex }, cssRule });
|
|
1087
|
+
tailwindAdjustments.push({ selector: sel, astPath: null, remove: [], add: [solved.tailwindClass] });
|
|
1088
|
+
inlineEdits.push({ filePath: options.filePath || null, nodeType: 'CssStyleSheetOverride', astPath: null, selector: sel, startOffset: null, endOffset: null, startLine: null, endLine: null, expectedChunkHash: null, before: '', after: cssRule });
|
|
1089
|
+
patches.push({ type: 'low_contrast', element: null, selector: sel, astPath: null, measuredRatio: computeContrastRatio(startFg, bg), targetRatio: tMin, fixedRatio: solved.ratio, cssOverride: `color: ${solved.hex};`, tailwindPatch: { remove: [], add: [solved.tailwindClass] } });
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
let patchedSource = rawSource;
|
|
1095
|
+
const anchoredEdits = inlineEdits.filter((e) => typeof e.startOffset === 'number' && typeof e.endOffset === 'number');
|
|
1096
|
+
for (const edit of [...anchoredEdits].sort((a, b) => b.startOffset - a.startOffset)) {
|
|
1097
|
+
if (patchedSource.slice(edit.startOffset, edit.endOffset) === edit.before) {
|
|
1098
|
+
patchedSource = patchedSource.slice(0, edit.startOffset) + edit.after + patchedSource.slice(edit.endOffset);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
return {
|
|
1103
|
+
changed: anchoredEdits.length > 0 && patchedSource !== rawSource,
|
|
1104
|
+
language: ast.language,
|
|
1105
|
+
issueCount: patches.length,
|
|
1106
|
+
patches,
|
|
1107
|
+
inlineEdits,
|
|
1108
|
+
cssOverrides,
|
|
1109
|
+
stylesheetOverride: cssOverrides.map((r) => r.cssRule).join('\n'),
|
|
1110
|
+
tailwindAdjustments,
|
|
1111
|
+
patchedSource,
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
function remediateVisualFindings(source, visualFindings = [], options = {}) {
|
|
1116
|
+
return inspectAndPatchDesignSource(source, { ...options, visualFindings });
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function makeFailedDesignReport(error) {
|
|
1120
|
+
return {
|
|
1121
|
+
ok: false,
|
|
1122
|
+
error,
|
|
1123
|
+
mode: 'active_self_correcting_design_engine',
|
|
1124
|
+
changed: false,
|
|
1125
|
+
language: 'html',
|
|
1126
|
+
issueCount: 0,
|
|
1127
|
+
patches: [],
|
|
1128
|
+
inlineEdits: [],
|
|
1129
|
+
cssOverrides: [],
|
|
1130
|
+
stylesheetOverride: '',
|
|
1131
|
+
tailwindAdjustments: [],
|
|
1132
|
+
patchedSource: '',
|
|
1133
|
+
appliedInPlace: false,
|
|
1134
|
+
guardReceipt: null,
|
|
1135
|
+
verification: { changed: false, remainingIssueCount: 0, remainingIssues: [] },
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
function runDesignSelfCorrectionPipeline(input = {}) {
|
|
1140
|
+
const maxBytes = Math.max(4096, Number(process.env.THUMBGATE_DESIGN_MAX_SOURCE_BYTES) || 262144);
|
|
1141
|
+
const filePath = input.filePath ? path.resolve(String(input.filePath)) : null;
|
|
1142
|
+
let sourceCode = typeof input.sourceCode === 'string' ? input.sourceCode : '';
|
|
1143
|
+
if (!sourceCode && input.allowDiskRead === true && filePath) {
|
|
1144
|
+
let lst;
|
|
1145
|
+
try {
|
|
1146
|
+
lst = fs.lstatSync(filePath);
|
|
1147
|
+
} catch {
|
|
1148
|
+
return makeFailedDesignReport('file_not_found');
|
|
1149
|
+
}
|
|
1150
|
+
if (lst.isSymbolicLink() || !lst.isFile()) {
|
|
1151
|
+
return makeFailedDesignReport('symlink_or_non_regular_file_rejected');
|
|
1152
|
+
}
|
|
1153
|
+
if (input.workspaceRoot) {
|
|
1154
|
+
let realRoot;
|
|
1155
|
+
let realFile;
|
|
1156
|
+
try {
|
|
1157
|
+
realRoot = fs.realpathSync(path.resolve(String(input.workspaceRoot)));
|
|
1158
|
+
realFile = fs.realpathSync(filePath);
|
|
1159
|
+
} catch {
|
|
1160
|
+
return makeFailedDesignReport('outside_workspace_root');
|
|
1161
|
+
}
|
|
1162
|
+
if (realFile !== realRoot && !realFile.startsWith(realRoot + path.sep)) {
|
|
1163
|
+
return makeFailedDesignReport('outside_workspace_root');
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
if (lst.size > maxBytes) {
|
|
1167
|
+
return makeFailedDesignReport('source_too_large');
|
|
1168
|
+
}
|
|
1169
|
+
sourceCode = fs.readFileSync(filePath, 'utf8');
|
|
1170
|
+
}
|
|
1171
|
+
if (Buffer.byteLength(sourceCode, 'utf8') > maxBytes) {
|
|
1172
|
+
return makeFailedDesignReport('source_too_large');
|
|
1173
|
+
}
|
|
1174
|
+
const report = inspectAndPatchDesignSource(sourceCode, {
|
|
1175
|
+
filePath,
|
|
1176
|
+
visualFindings: input.visualFindings,
|
|
1177
|
+
minContrast: input.minContrast,
|
|
1178
|
+
defaultBgHex: input.defaultBgHex,
|
|
1179
|
+
allowTailwind: input.allowTailwind !== false,
|
|
1180
|
+
});
|
|
1181
|
+
const postReport = report.patchedSource ? inspectAndPatchDesignSource(report.patchedSource, { defaultBgHex: input.defaultBgHex, minContrast: input.minContrast }) : { issueCount: 0, patches: [] };
|
|
1182
|
+
let appliedInPlace = false;
|
|
1183
|
+
let guardReceipt = null;
|
|
1184
|
+
if (input.applyInPlace === true && input.allowDiskRead === true && filePath && sourceCode && report.changed) {
|
|
1185
|
+
let currentStat = null;
|
|
1186
|
+
try { currentStat = fs.lstatSync(filePath); } catch { currentStat = null; }
|
|
1187
|
+
if (currentStat && !currentStat.isSymbolicLink() && currentStat.isFile()) {
|
|
1188
|
+
guardReceipt = evaluateHashAnchoredEdit({ filePath, targetContent: sourceCode, expectedHash: computeChunkHash(sourceCode) });
|
|
1189
|
+
if (guardReceipt.allowed) {
|
|
1190
|
+
fs.writeFileSync(filePath, report.patchedSource, 'utf8');
|
|
1191
|
+
appliedInPlace = true;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
return {
|
|
1196
|
+
ok: postReport.issueCount === 0,
|
|
1197
|
+
mode: 'active_self_correcting_design_engine',
|
|
1198
|
+
...report,
|
|
1199
|
+
appliedInPlace,
|
|
1200
|
+
guardReceipt,
|
|
1201
|
+
verification: {
|
|
1202
|
+
changed: report.changed,
|
|
1203
|
+
remainingIssueCount: postReport.issueCount,
|
|
1204
|
+
remainingIssues: postReport.patches.map((p) => ({ type: p.type, selector: p.selector })),
|
|
1205
|
+
},
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
function parseFiniteNonNeg(v, fallback = 0) {
|
|
1210
|
+
if (v === undefined || v === null || v === '') return { ok: true, value: fallback, provided: false };
|
|
1211
|
+
if (typeof v === 'boolean' || typeof v === 'object') return { ok: false, value: 0, provided: true };
|
|
1212
|
+
const n = Number(v);
|
|
1213
|
+
if (!Number.isFinite(n) || n < 0) return { ok: false, value: 0, provided: true };
|
|
1214
|
+
return { ok: true, value: n, provided: true };
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function scrubBoostTelemetryMetadata(event = {}) {
|
|
1218
|
+
const ev = event && typeof event === 'object' && !Array.isArray(event) ? event : {};
|
|
1219
|
+
const safeModel = String(ev.model || 'unknown').replace(/[^a-zA-Z0-9._:-]/g, '').slice(0, 64) || 'unknown';
|
|
1220
|
+
const safeGate = ev.gateRuleId ? String(ev.gateRuleId).replace(/[^a-zA-Z0-9._:-]/g, '').slice(0, 64) : null;
|
|
1221
|
+
const inTok = parseFiniteNonNeg(ev.inputTokens, 0);
|
|
1222
|
+
const outTok = parseFiniteNonNeg(ev.outputTokens, 0);
|
|
1223
|
+
const cost = parseFiniteNonNeg(ev.costUsd, 0);
|
|
1224
|
+
const rawTs = typeof ev.timestamp === 'string' ? ev.timestamp.trim() : '';
|
|
1225
|
+
const safeTs = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(rawTs) ? rawTs : new Date().toISOString();
|
|
1226
|
+
return {
|
|
1227
|
+
storesPrompts: false,
|
|
1228
|
+
storesResponses: false,
|
|
1229
|
+
storesRepoPromptContext: false,
|
|
1230
|
+
metadata: {
|
|
1231
|
+
timestamp: safeTs,
|
|
1232
|
+
lane: ev.lane === 'boost_lane' ? 'boost_lane' : 'primary_subscription',
|
|
1233
|
+
model: safeModel,
|
|
1234
|
+
inputTokens: Math.trunc(inTok.value),
|
|
1235
|
+
outputTokens: Math.trunc(outTok.value),
|
|
1236
|
+
costUsd: Math.round(cost.value * 1e6) / 1e6,
|
|
1237
|
+
gateRuleId: safeGate,
|
|
1238
|
+
},
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
function evaluateComputeBoostLane(rawInput = {}) {
|
|
1243
|
+
const input = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput) ? rawInput : null;
|
|
1244
|
+
if (!input) {
|
|
1245
|
+
return { ok: false, allowed: false, stopReason: 'invalid_boost_input', selectedLane: 'boost_lane', economics: { cashWithdrawalAllowed: false, canOverspend: false, outboundCashSpendUsd: 0 }, balances: { totalAvailableBoostUsd: 0, deductedBoostUsd: 0, remainingBoostUsd: 0, savedBoostUsd: 0 }, metering: { meteredUnits: 0 }, telemetry: scrubBoostTelemetryMetadata({}) };
|
|
1246
|
+
}
|
|
1247
|
+
const grossP = parseFiniteNonNeg(input.grossBoostUsd, 0);
|
|
1248
|
+
const sharedP = parseFiniteNonNeg(input.sharedPoolReleaseUsd, 0);
|
|
1249
|
+
const balP = parseFiniteNonNeg(input.boostBalanceUsd, 0);
|
|
1250
|
+
const estP = parseFiniteNonNeg(input.estimatedRequestUsd, 0);
|
|
1251
|
+
const inFlightP = parseFiniteNonNeg(input.activeInFlightRequests, 0);
|
|
1252
|
+
const opKind = String(input.operationKind || 'cloud_chat_reply').trim().toLowerCase();
|
|
1253
|
+
const isUnmeteredLocal = opKind === 'pre_tool_use_gate' || opKind === 'kb_setup_upload' || opKind === 'greeting_no_model' || input.blockedBeforeModel === true;
|
|
1254
|
+
const chatP = parseFiniteNonNeg(input.chatReplies, isUnmeteredLocal ? 0 : 1);
|
|
1255
|
+
const docsP = parseFiniteNonNeg(input.documentsUploaded, 0);
|
|
1256
|
+
const pagesP = parseFiniteNonNeg(input.pagesGenerated, 0);
|
|
1257
|
+
const tasksP = parseFiniteNonNeg(input.tasksExecuted, 0);
|
|
1258
|
+
if (![grossP, sharedP, balP, estP, inFlightP, chatP, docsP, pagesP, tasksP].every((x) => x.ok)) {
|
|
1259
|
+
return { ok: false, allowed: false, stopReason: 'invalid_boost_input', selectedLane: 'boost_lane', economics: { cashWithdrawalAllowed: false, canOverspend: false, outboundCashSpendUsd: 0 }, balances: { totalAvailableBoostUsd: 0, deductedBoostUsd: 0, remainingBoostUsd: 0, savedBoostUsd: 0 }, metering: { meteredUnits: 0 }, telemetry: scrubBoostTelemetryMetadata(input.telemetry) };
|
|
1260
|
+
}
|
|
1261
|
+
const grossBoostUsd = grossP.value;
|
|
1262
|
+
const platformFeeUsd = Math.round(grossBoostUsd * 0.05 * 100) / 100;
|
|
1263
|
+
const creditedCapacityUsd = Math.round((grossBoostUsd - platformFeeUsd) * 100) / 100;
|
|
1264
|
+
const totalAvailableBoostUsd = Math.round((balP.value + creditedCapacityUsd + sharedP.value) * 1e6) / 1e6;
|
|
1265
|
+
const chatReplies = Math.trunc(chatP.value);
|
|
1266
|
+
const documentsUploaded = Math.trunc(docsP.value);
|
|
1267
|
+
const pagesGenerated = Math.trunc(pagesP.value);
|
|
1268
|
+
const tasksExecuted = Math.trunc(tasksP.value);
|
|
1269
|
+
const meteredUnits = isUnmeteredLocal ? 0 : (chatReplies + documentsUploaded + pagesGenerated + tasksExecuted);
|
|
1270
|
+
const effectiveCostUsd = isUnmeteredLocal ? 0 : estP.value;
|
|
1271
|
+
const savedBoostUsd = input.blockedBeforeModel === true ? estP.value : 0;
|
|
1272
|
+
const primaryStatus = String(input.primarySubscriptionStatus || 'active').trim().toLowerCase();
|
|
1273
|
+
const primaryPaused = primaryStatus === 'window_paused' || primaryStatus === 'rate_limited' || primaryStatus === 'none';
|
|
1274
|
+
const inFlight = Math.trunc(inFlightP.value);
|
|
1275
|
+
const selectedLane = isUnmeteredLocal ? 'local_zero_burn' : (primaryPaused ? 'boost_lane' : 'primary_subscription');
|
|
1276
|
+
let allowed = true;
|
|
1277
|
+
let stopReason = null;
|
|
1278
|
+
if (selectedLane === 'boost_lane') {
|
|
1279
|
+
if (inFlight >= 1) { allowed = false; stopReason = 'boost_single_flight_busy'; }
|
|
1280
|
+
else if (effectiveCostUsd <= 0) { allowed = false; stopReason = totalAvailableBoostUsd <= 0 ? 'boost_balance_exhausted' : 'invalid_boost_input'; }
|
|
1281
|
+
else if (effectiveCostUsd > totalAvailableBoostUsd) { allowed = false; stopReason = 'boost_balance_exhausted'; }
|
|
1282
|
+
}
|
|
1283
|
+
const deductedBoostUsd = allowed && selectedLane === 'boost_lane' ? effectiveCostUsd : 0;
|
|
1284
|
+
const remainingBoostUsd = Math.max(0, Math.round((totalAvailableBoostUsd - deductedBoostUsd) * 1e6) / 1e6);
|
|
1285
|
+
return {
|
|
1286
|
+
ok: true,
|
|
1287
|
+
allowed,
|
|
1288
|
+
stopReason,
|
|
1289
|
+
selectedLane,
|
|
1290
|
+
economics: { grossBoostUsd, creditedCapacityUsd, platformFeeUsd, developerCapacitySharePct: 95, platformFeePct: 5, cashWithdrawalAllowed: false, supporterAccountRequired: false, canOverspend: false, outboundCashSpendUsd: 0 },
|
|
1291
|
+
balances: { totalAvailableBoostUsd, deductedBoostUsd, remainingBoostUsd, savedBoostUsd },
|
|
1292
|
+
metering: {
|
|
1293
|
+
operationKind: opKind,
|
|
1294
|
+
isUnmeteredLocal,
|
|
1295
|
+
meteredUnits,
|
|
1296
|
+
regenerationsCountFresh: true,
|
|
1297
|
+
breakdown: isUnmeteredLocal ? { chatReplies: 0, documentsUploaded: 0, pagesGenerated: 0, tasksExecuted: 0 } : { chatReplies, documentsUploaded, pagesGenerated, tasksExecuted },
|
|
1298
|
+
},
|
|
1299
|
+
telemetry: scrubBoostTelemetryMetadata({ ...(input.telemetry && typeof input.telemetry === 'object' ? input.telemetry : {}), lane: selectedLane === 'boost_lane' ? 'boost_lane' : 'primary_subscription', costUsd: deductedBoostUsd }),
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const SUBQ_SNAP_MODELS = new Set(['subq-snap-1.2', 'subq-snap-latest', 'subq-snap']);
|
|
1304
|
+
const SUBQ_ALLOWED_IMAGE_MEDIA = new Set(['image/png', 'image/jpeg', 'image/webp']);
|
|
1305
|
+
const SUBQ_SAFE_KEY_RE = /^(?!__proto__$|constructor$|prototype$)[a-zA-Z0-9_.-]{1,100}$/;
|
|
1306
|
+
const SUBQ_MAX_WINDOW_TOKENS = 393216;
|
|
1307
|
+
const SUBQ_PRICE_PER_MILLION_INPUT_USD = 0.04;
|
|
1308
|
+
|
|
1309
|
+
function buildSubQSnap12Payload(rawInput = {}) {
|
|
1310
|
+
const input = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput) ? rawInput : null;
|
|
1311
|
+
if (!input || input.state === undefined || input.state === null) return { ok: false, error: 'missing_state' };
|
|
1312
|
+
const requestedModel = String(input.model || 'subq-snap-1.2').trim();
|
|
1313
|
+
const model = SUBQ_SNAP_MODELS.has(requestedModel) ? requestedModel : 'subq-snap-1.2';
|
|
1314
|
+
const rawQuestions = input.questions && typeof input.questions === 'object' && !Array.isArray(input.questions) ? input.questions : null;
|
|
1315
|
+
const qEntries = rawQuestions ? Object.entries(rawQuestions) : [];
|
|
1316
|
+
if (qEntries.length < 1 || qEntries.length > 128) return { ok: false, error: 'invalid_questions_count' };
|
|
1317
|
+
const questionPairs = [];
|
|
1318
|
+
for (const [qName, qDef] of qEntries) {
|
|
1319
|
+
if (!SUBQ_SAFE_KEY_RE.test(qName) || !qDef || typeof qDef !== 'object' || Array.isArray(qDef)) return { ok: false, error: 'invalid_question_key' };
|
|
1320
|
+
const qType = String(qDef.type || '').trim();
|
|
1321
|
+
const instructions = String(qDef.instructions || '').trim();
|
|
1322
|
+
if (!instructions || !['noul', 'choice', 'score'].includes(qType)) return { ok: false, error: `invalid_question_schema:${qName}` };
|
|
1323
|
+
if (qType === 'choice') {
|
|
1324
|
+
const cObj = qDef.criteria && typeof qDef.criteria === 'object' && !Array.isArray(qDef.criteria) ? qDef.criteria : null;
|
|
1325
|
+
const keys = cObj ? Object.keys(cObj) : [];
|
|
1326
|
+
if (keys.length < 2 || keys.length > 255 || !keys.every((k) => SUBQ_SAFE_KEY_RE.test(k))) return { ok: false, error: `invalid_choice_criteria:${qName}` };
|
|
1327
|
+
const criteria = Object.fromEntries([...keys].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map((k) => [k, cObj[k] === null ? null : String(cObj[k])]));
|
|
1328
|
+
questionPairs.push([qName, { type: 'choice', instructions, criteria }]);
|
|
1329
|
+
} else if (qType === 'score') {
|
|
1330
|
+
if (!Array.isArray(qDef.criteria) || qDef.criteria.length < 2 || qDef.criteria.length > 10) return { ok: false, error: `invalid_score_criteria:${qName}` };
|
|
1331
|
+
questionPairs.push([qName, { type: 'score', instructions, criteria: qDef.criteria.map((x) => String(x)) }]);
|
|
1332
|
+
} else {
|
|
1333
|
+
const entry = { type: 'noul', instructions };
|
|
1334
|
+
if (qDef.criteria && typeof qDef.criteria === 'object' && !Array.isArray(qDef.criteria)) {
|
|
1335
|
+
const noulPairs = [];
|
|
1336
|
+
if (Object.hasOwn(qDef.criteria, 'true')) noulPairs.push(['true', String(qDef.criteria.true)]);
|
|
1337
|
+
if (Object.hasOwn(qDef.criteria, 'false')) noulPairs.push(['false', String(qDef.criteria.false)]);
|
|
1338
|
+
if (noulPairs.length > 0) entry.criteria = Object.fromEntries(noulPairs);
|
|
1339
|
+
}
|
|
1340
|
+
questionPairs.push([qName, entry]);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
const questions = Object.fromEntries(questionPairs);
|
|
1344
|
+
let images;
|
|
1345
|
+
let imageTokens = 0;
|
|
1346
|
+
if (input.images !== undefined) {
|
|
1347
|
+
if (!Array.isArray(input.images) || input.images.length > 4) return { ok: false, error: 'invalid_images_count' };
|
|
1348
|
+
let totalDecodedBytes = 0;
|
|
1349
|
+
images = [];
|
|
1350
|
+
for (const img of input.images) {
|
|
1351
|
+
if (!img || typeof img !== 'object') return { ok: false, error: 'invalid_image_entry' };
|
|
1352
|
+
const mediaType = String(img.mediaType || '').trim().toLowerCase();
|
|
1353
|
+
if (!SUBQ_ALLOWED_IMAGE_MEDIA.has(mediaType)) return { ok: false, error: 'unsupported_image_media_type' };
|
|
1354
|
+
const cleanedB64 = String(img.base64 || '').replace(/^data:[^;]+;base64,/i, '').replace(/\s+/g, '');
|
|
1355
|
+
if (!cleanedB64 || /^https?:\/\//i.test(cleanedB64)) return { ok: false, error: 'invalid_image_base64' };
|
|
1356
|
+
const decodedLen = Buffer.from(cleanedB64, 'base64').length;
|
|
1357
|
+
if (decodedLen <= 0 || decodedLen > 4 * 1024 * 1024) return { ok: false, error: 'image_over_4_mib' };
|
|
1358
|
+
totalDecodedBytes += decodedLen;
|
|
1359
|
+
if (totalDecodedBytes > 8 * 1024 * 1024) return { ok: false, error: 'images_over_8_mib_total' };
|
|
1360
|
+
imageTokens += 800;
|
|
1361
|
+
images.push({ mediaType, base64: cleanedB64 });
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
const stateSerialized = typeof input.state === 'string' ? input.state : String(JSON.stringify(input.state) ?? '');
|
|
1365
|
+
const questionsSerialized = JSON.stringify(questions);
|
|
1366
|
+
const estTokens = Math.ceil((Buffer.byteLength(stateSerialized, 'utf8') + Buffer.byteLength(questionsSerialized, 'utf8')) / 4) + imageTokens;
|
|
1367
|
+
if (estTokens > SUBQ_MAX_WINDOW_TOKENS) return { ok: false, error: 'exceeds_384k_context_window', estimatedInputTokens: estTokens };
|
|
1368
|
+
return {
|
|
1369
|
+
ok: true,
|
|
1370
|
+
payload: { model, state: input.state, questions, ...(images && images.length > 0 ? { images } : {}) },
|
|
1371
|
+
estimatedInputTokens: estTokens,
|
|
1372
|
+
estimatedInputCostUsd: Math.round((estTokens / 1e6) * SUBQ_PRICE_PER_MILLION_INPUT_USD * 1e8) / 1e8,
|
|
1373
|
+
outputCostUsd: 0,
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
async function callSubQSnapSystemOneApi(rawInput = {}, options = {}) {
|
|
1378
|
+
const built = buildSubQSnap12Payload(rawInput);
|
|
1379
|
+
if (!built.ok) return { ok: false, mode: 'validation_rejected', error: built.error, abstained: true, action: 'UNCERTAIN_ESCALATE_TO_FRONTIER' };
|
|
1380
|
+
const rawTau = typeof options.confidenceThreshold === 'number' && Number.isFinite(options.confidenceThreshold) ? options.confidenceThreshold : 0.65;
|
|
1381
|
+
const tau = Math.min(1, Math.max(0.01, rawTau));
|
|
1382
|
+
const apiKey = String(options.apiKey !== undefined ? options.apiKey : (process.env.SUBQ_API_KEY || '')).trim();
|
|
1383
|
+
const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : fetch;
|
|
1384
|
+
if (!apiKey) {
|
|
1385
|
+
return {
|
|
1386
|
+
ok: true,
|
|
1387
|
+
mode: 'local_offline_no_api_key',
|
|
1388
|
+
model: built.payload.model,
|
|
1389
|
+
estimatedInputTokens: built.estimatedInputTokens,
|
|
1390
|
+
estimatedInputCostUsd: built.estimatedInputCostUsd,
|
|
1391
|
+
outputCostUsd: 0,
|
|
1392
|
+
abstained: true,
|
|
1393
|
+
action: 'UNCERTAIN_ESCALATE_TO_FRONTIER',
|
|
1394
|
+
reason: 'subq_api_key_missing',
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
let res;
|
|
1398
|
+
try {
|
|
1399
|
+
res = await fetchImpl('https://api.subq.ai/v1/systemone', {
|
|
1400
|
+
method: 'POST',
|
|
1401
|
+
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
1402
|
+
body: JSON.stringify(built.payload),
|
|
1403
|
+
signal: AbortSignal.timeout(Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 8000),
|
|
1404
|
+
});
|
|
1405
|
+
} catch {
|
|
1406
|
+
return { ok: false, mode: 'upstream_error', status: 502, error: 'subq_network_error', abstained: true, action: 'UNCERTAIN_ESCALATE_TO_FRONTIER' };
|
|
1407
|
+
}
|
|
1408
|
+
if (res.status === 402) {
|
|
1409
|
+
return { ok: false, mode: 'credit_exhausted_zero_overspend', status: 402, error: 'subq_credits_exhausted', outboundCashSpendUsd: 0, abstained: true, action: 'UNCERTAIN_ESCALATE_TO_FRONTIER' };
|
|
1410
|
+
}
|
|
1411
|
+
if (!res.ok) {
|
|
1412
|
+
return { ok: false, mode: 'upstream_error', status: res.status, error: `subq_http_${res.status}`, abstained: true, action: 'UNCERTAIN_ESCALATE_TO_FRONTIER' };
|
|
1413
|
+
}
|
|
1414
|
+
let data;
|
|
1415
|
+
try {
|
|
1416
|
+
data = await res.json();
|
|
1417
|
+
} catch {
|
|
1418
|
+
return { ok: false, mode: 'upstream_error', status: 502, error: 'subq_invalid_json', abstained: true, action: 'UNCERTAIN_ESCALATE_TO_FRONTIER' };
|
|
1419
|
+
}
|
|
1420
|
+
const answers = data && typeof data.answers === 'object' && !Array.isArray(data.answers) ? data.answers : {};
|
|
1421
|
+
const expectedKeys = Object.keys(built.payload.questions);
|
|
1422
|
+
let invalidAnswer = expectedKeys.length === 0;
|
|
1423
|
+
let minConfidence = expectedKeys.length > 0 ? 1 : 0;
|
|
1424
|
+
for (const qk of expectedKeys) {
|
|
1425
|
+
const expectedType = built.payload.questions[qk].type;
|
|
1426
|
+
const ans = Object.hasOwn(answers, qk) ? answers[qk] : null;
|
|
1427
|
+
if (!ans || typeof ans !== 'object' || ans.type !== expectedType) { invalidAnswer = true; minConfidence = 0; break; }
|
|
1428
|
+
let conf = NaN;
|
|
1429
|
+
if (expectedType === 'noul') {
|
|
1430
|
+
const nv = typeof ans.noul === 'number' ? ans.noul : NaN;
|
|
1431
|
+
conf = Number.isFinite(nv) && nv >= 0 && nv <= 1 ? Math.max(nv, 1 - nv) : NaN;
|
|
1432
|
+
} else {
|
|
1433
|
+
const cv = typeof ans.confidence === 'number' ? ans.confidence : NaN;
|
|
1434
|
+
conf = Number.isFinite(cv) && cv >= 0 && cv <= 1 ? cv : NaN;
|
|
1435
|
+
}
|
|
1436
|
+
if (!Number.isFinite(conf)) { invalidAnswer = true; minConfidence = 0; break; }
|
|
1437
|
+
if (conf < minConfidence) minConfidence = conf;
|
|
1438
|
+
}
|
|
1439
|
+
const usageTok = parseFiniteNonNeg(data?.usage?.input_tokens, built.estimatedInputTokens);
|
|
1440
|
+
const inputTokens = Math.trunc(usageTok.ok ? usageTok.value : built.estimatedInputTokens);
|
|
1441
|
+
const abstained = invalidAnswer || minConfidence < tau;
|
|
1442
|
+
return {
|
|
1443
|
+
ok: true,
|
|
1444
|
+
mode: 'live_subq_systemone',
|
|
1445
|
+
model: data?.model || built.payload.model,
|
|
1446
|
+
answers,
|
|
1447
|
+
usage: { input_tokens: inputTokens, output_tokens: 0 },
|
|
1448
|
+
costUsd: Math.round((inputTokens / 1e6) * SUBQ_PRICE_PER_MILLION_INPUT_USD * 1e8) / 1e8,
|
|
1449
|
+
outboundCashSpendUsd: 0,
|
|
1450
|
+
minConfidence: Math.round(minConfidence * 1e4) / 1e4,
|
|
1451
|
+
abstained,
|
|
1452
|
+
action: abstained ? 'UNCERTAIN_ESCALATE_TO_FRONTIER' : 'PROCEED_WITH_SUBQ_DECISION',
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
module.exports = {
|
|
1457
|
+
PROVER_COVERAGE_DOMAINS,
|
|
1458
|
+
TAILWIND_HEX_PALETTE,
|
|
1459
|
+
provePolicyBoundary,
|
|
1460
|
+
evaluateProposalRisk,
|
|
1461
|
+
verifyProviderCredentialEgress,
|
|
1462
|
+
verifyNonDestructiveProjectEdit,
|
|
1463
|
+
evaluateBrandAdherence,
|
|
1464
|
+
computeContrastRatio,
|
|
1465
|
+
solveAccessibleForeground,
|
|
1466
|
+
parseCssRulesAst,
|
|
1467
|
+
parseDesignAst,
|
|
1468
|
+
inspectAndPatchDesignSource,
|
|
1469
|
+
remediateVisualFindings,
|
|
1470
|
+
runDesignSelfCorrectionPipeline,
|
|
1471
|
+
scrubBoostTelemetryMetadata,
|
|
1472
|
+
evaluateComputeBoostLane,
|
|
1473
|
+
buildSubQSnap12Payload,
|
|
1474
|
+
callSubQSnapSystemOneApi,
|
|
1475
|
+
};
|