thumbgate 1.39.1 → 1.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * src/feedback.js — Re-exports and convenience entrypoint for ThumbGate feedback & lessons.
5
+ */
6
+ const feedbackLoop = require('../scripts/feedback-loop');
7
+ const lessonRetrieval = require('../scripts/lesson-retrieval');
8
+ const lessonSearch = require('../scripts/lesson-search');
9
+ const verifiedLessons = require('../scripts/verified-lessons');
10
+
11
+ module.exports = {
12
+ ...feedbackLoop,
13
+ ...lessonRetrieval,
14
+ ...lessonSearch,
15
+ ...verifiedLessons,
16
+ retrieve_lessons: lessonRetrieval.retrieve_lessons || lessonRetrieval.retrieveRelevantLessons,
17
+ retrieveLessons: lessonRetrieval.retrieveLessons || lessonRetrieval.retrieveRelevantLessons,
18
+ search_lessons: lessonSearch.search_lessons || lessonSearch.searchLessons,
19
+ searchLessons: lessonSearch.searchLessons,
20
+ capture_feedback: feedbackLoop.capture_feedback || feedbackLoop.captureFeedback,
21
+ };
@@ -134,9 +134,10 @@ class HermesSyncPlane {
134
134
  return this.readStatus(args);
135
135
  }
136
136
 
137
- appendEvent({ threadId, recordId, type, txnId, payload } = {}) {
137
+ appendEvent({ threadId, recordId, type, txnId, payload, projectKey, projectName, identitySource } = {}) {
138
138
  this._offset += 1;
139
139
  const event = {
140
+ ...require('../scripts/project-identity').projectForRecord({ ...payload, projectKey: projectKey || payload?.projectKey, projectName: projectName || payload?.projectName, identitySource: identitySource || payload?.identitySource }),
140
141
  offset: this._offset,
141
142
  threadId: threadId || null,
142
143
  recordId: recordId || null,
package/src/index.js CHANGED
@@ -18,6 +18,7 @@ const {
18
18
  DEFAULT_READ_ONLY_TOOLS,
19
19
  DEFAULT_MUTATING_TOOLS,
20
20
  } = require('./integrations/ideabrowser-connector');
21
+ const openshellLovable = require('./openshell-lovable-engine');
21
22
 
22
23
  // The package entry point is the production surface for `thumbgate`.
23
24
  // The hosted-Hermes identity/lifecycle/approval gates are exported here so
@@ -39,4 +40,5 @@ module.exports = Object.assign({}, feedbackLoop, {
39
40
  ToolTier,
40
41
  DEFAULT_READ_ONLY_TOOLS,
41
42
  DEFAULT_MUTATING_TOOLS,
43
+ ...openshellLovable,
42
44
  });
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+
3
+ const lessonSearch = require('../scripts/lesson-search');
4
+ const { lookupLessonByError } = require('../scripts/verified-lessons');
5
+
6
+ module.exports = {
7
+ ...lessonSearch,
8
+ lookupLessonByError,
9
+ };
@@ -0,0 +1,493 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * McKinsey Top-Performing AI Coding Operating Model (2x End-to-End Throughput)
5
+ * Source: Martin Harrysson, Prakhar Dixit, and Shilpa —
6
+ * "What the Top Companies Do Differently With AI Coding" (https://www.youtube.com/watch?v=21tuT-e4NVo)
7
+ *
8
+ * Implements the 5 operational and technical control loops:
9
+ * 1. Operating Model & Delivery Flow (1-2 day Night-Shift Kanban loops, standardized PRD/Spec inputs, progressive HITL removal)
10
+ * 2. Team & Role Restructure (2-4 person mini-pods, collapsed Definer/Builder roles, review-vs-generation parity)
11
+ * 3. Curated Context, Golden Examples & Tight Vetted Skills (SME semantic layer, top-decile golden examples over codebase averages, skill cap <= 7)
12
+ * 4. Upstream, Downstream & Sideways Bottleneck Guardrails (customer inbox/log wiring + baked-in WCAG contrast, colorblind safety, DLP, compliance)
13
+ * 5. AIOps Token ROI & Business Impact Scoring (value-per-token gate before scaling)
14
+ */
15
+
16
+ const MAX_KANBAN_CYCLE_HOURS = 48;
17
+ const MIN_POD_SIZE = 2;
18
+ const MAX_POD_SIZE = 4;
19
+ const MAX_VETTED_SKILLS_PER_LOOP = 7;
20
+ const MIN_GOLDEN_EXAMPLE_PERCENTILE = 90;
21
+ const WCAG_AA_NORMAL_CONTRAST = 4.5;
22
+ const WCAG_AA_LARGE_CONTRAST = 3.0;
23
+ // Default air-gap patterns: private-network IPs and internal-only hostnames.
24
+ // Callers pass their own organisation's hosts through `airgapPatterns`; none are hardcoded here.
25
+ const DEFAULT_AIRGAP_PATTERNS = [
26
+ /\b(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})\b/,
27
+ /\b[a-z0-9-]+\.(?:internal|corp|intranet|lan)\b/i,
28
+ ];
29
+
30
+ function toAirgapRegexes(patterns) {
31
+ if (!Array.isArray(patterns) || patterns.length === 0) return DEFAULT_AIRGAP_PATTERNS;
32
+ return patterns.map((pattern) => (pattern instanceof RegExp ? pattern : new RegExp(String(pattern), 'i')));
33
+ }
34
+
35
+ const COLLAPSED_ROLES = new Set(['definer', 'builder', 'verifier']);
36
+
37
+ /**
38
+ * Pillar 1A: Standardized Input Artifact Validator (06:40 - 07:04)
39
+ * Rejects fragmented or freeform prompts before agents execute night-shift loops.
40
+ */
41
+ function validateStandardSpecArtifact(spec = {}) {
42
+ const findings = [];
43
+ const cycleHours = Number(spec.targetCycleHours ?? 24);
44
+ if (!Number.isFinite(cycleHours) || cycleHours <= 0 || cycleHours > MAX_KANBAN_CYCLE_HOURS) {
45
+ findings.push({
46
+ code: 'sprint_batch_too_large',
47
+ message: `Target cycle (${cycleHours}h) exceeds the 1-2 day Kanban loop ceiling (${MAX_KANBAN_CYCLE_HOURS}h). Ditch 2-week sprints for 1-2 day night-shift loops.`,
48
+ });
49
+ }
50
+
51
+ if (typeof spec.problemStatement !== 'string' || spec.problemStatement.trim().length < 20) {
52
+ findings.push({
53
+ code: 'missing_problem_statement',
54
+ message: 'Standardized spec requires a clear problemStatement (>= 20 chars).',
55
+ });
56
+ }
57
+
58
+ if (!Array.isArray(spec.verifiableOutcomes) || spec.verifiableOutcomes.length === 0) {
59
+ findings.push({
60
+ code: 'missing_verifiable_outcomes',
61
+ message: 'Standardized spec requires at least one machine-verifiable outcome.',
62
+ });
63
+ }
64
+
65
+ // A reference is a path string (already curated) or { ref, qualityPercentile }.
66
+ // Scored references below the golden percentile do not count.
67
+ const goldenReferences = Array.isArray(spec.goldenReferences)
68
+ ? spec.goldenReferences.filter(
69
+ (ref) =>
70
+ typeof ref === 'string'
71
+ ? ref.trim().length > 0
72
+ : ref && Number(ref.qualityPercentile || 0) >= MIN_GOLDEN_EXAMPLE_PERCENTILE
73
+ )
74
+ : [];
75
+ if (goldenReferences.length === 0) {
76
+ findings.push({
77
+ code: 'missing_golden_references',
78
+ message: `Standardized spec must cite at least one golden example reference (path, or scored >= P${MIN_GOLDEN_EXAMPLE_PERCENTILE}).`,
79
+ });
80
+ }
81
+
82
+ if (!spec.sidewaysConstraints || typeof spec.sidewaysConstraints !== 'object') {
83
+ findings.push({
84
+ code: 'missing_sideways_constraints',
85
+ message: 'Standardized spec must declare sidewaysConstraints (security, compliance, accessibility).',
86
+ });
87
+ }
88
+
89
+ const tokenBudgetUsd = Number(spec.tokenBudgetUsd ?? 0);
90
+ if (!Number.isFinite(tokenBudgetUsd) || tokenBudgetUsd <= 0) {
91
+ findings.push({
92
+ code: 'missing_token_budget',
93
+ message: 'Standardized spec requires a positive tokenBudgetUsd.',
94
+ });
95
+ }
96
+
97
+ return {
98
+ ok: findings.length === 0,
99
+ kanbanLoopMode: cycleHours <= 24 ? 'night_shift_24h' : 'kanban_48h',
100
+ findings,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Pillar 1B: Progressive Human-in-the-Loop (HITL) Gate (05:29 - 06:03)
106
+ * Systematically removes human sign-off bottlenecks as empirical loop confidence grows,
107
+ * while keeping human review on irreversible or low-confidence boundaries.
108
+ */
109
+ function evaluateProgressiveHitlGate({
110
+ loopId = 'default-loop',
111
+ historicalPassRate = 0,
112
+ consecutiveCleanRuns = 0,
113
+ blastRadius = 'reversible',
114
+ allAutomatedGatesPassed = false,
115
+ } = {}) {
116
+ const clampedPassRate = Math.max(0, Math.min(1, Number(historicalPassRate) || 0));
117
+ const streakBonus = Math.min(0.15, (Math.max(0, Number(consecutiveCleanRuns) || 0) / 20) * 0.15);
118
+ const confidenceScore = Number(Math.min(1, clampedPassRate * 0.85 + streakBonus).toFixed(4));
119
+
120
+ const isIrreversible = blastRadius === 'irreversible' || blastRadius === 'production_auth_billing';
121
+ const canAutoAdvanceNightShift =
122
+ Boolean(allAutomatedGatesPassed) && !isIrreversible && confidenceScore >= 0.85;
123
+
124
+ return {
125
+ loopId,
126
+ confidenceScore,
127
+ blastRadius,
128
+ requireHumanSignOff: !canAutoAdvanceNightShift,
129
+ executionMode: canAutoAdvanceNightShift
130
+ ? 'autonomous_night_shift_auto_advance'
131
+ : 'human_in_the_loop_validation_required',
132
+ reason: !allAutomatedGatesPassed
133
+ ? 'automated_gates_failed'
134
+ : isIrreversible
135
+ ? 'irreversible_blast_radius_guardrail'
136
+ : confidenceScore >= 0.85
137
+ ? 'high_confidence_progressive_hitl_bypass'
138
+ : 'confidence_below_0.85_threshold',
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Pillar 2: Team Topology & Review Coaching Guard (07:25 - 07:49, 12:07 - 12:25, 18:23)
144
+ * Enforces 2-4 person mini-pods, collapsed Definer/Builder roles, and code-review parity
145
+ * so faster generation does not inflate per-PR bug/incident rates.
146
+ */
147
+ function auditPodTopologyAndReviewRatio({
148
+ podMembers = [],
149
+ generationMinutes = 0,
150
+ reviewAndVerificationMinutes = 0,
151
+ changedLines = 0,
152
+ verifiedTestAssertions = 0,
153
+ } = {}) {
154
+ const findings = [];
155
+ const podSize = Array.isArray(podMembers) ? podMembers.length : 0;
156
+
157
+ if (podSize < MIN_POD_SIZE || podSize > MAX_POD_SIZE) {
158
+ findings.push({
159
+ code: 'invalid_pod_size',
160
+ message: `Pod size (${podSize}) must be ${MIN_POD_SIZE}-${MAX_POD_SIZE} people (halved mini-pod topology).`,
161
+ });
162
+ }
163
+
164
+ const legacySiloRoles = (podMembers || []).filter(
165
+ (m) => !COLLAPSED_ROLES.has(String(m.role || '').toLowerCase())
166
+ );
167
+ if (legacySiloRoles.length > 0) {
168
+ findings.push({
169
+ code: 'siloed_legacy_roles_detected',
170
+ message: `Collapse narrow roles into 'definer', 'builder', or 'verifier' (found: ${legacySiloRoles.map((m) => m.role).join(', ')}).`,
171
+ });
172
+ }
173
+
174
+ const genMins = Math.max(1, Number(generationMinutes) || 1);
175
+ const revMins = Math.max(0, Number(reviewAndVerificationMinutes) || 0);
176
+ const reviewToGenerationRatio = Number((revMins / genMins).toFixed(3));
177
+
178
+ if (reviewToGenerationRatio < 0.5) {
179
+ findings.push({
180
+ code: 'insufficient_review_investment',
181
+ message: `Review-to-generation ratio (${reviewToGenerationRatio}) is below 0.50; AI generation speed without review discipline increases per-PR bug rates.`,
182
+ });
183
+ }
184
+
185
+ const lines = Math.max(0, Number(changedLines) || 0);
186
+ const assertions = Math.max(0, Number(verifiedTestAssertions) || 0);
187
+ if (lines >= 50 && assertions === 0) {
188
+ findings.push({
189
+ code: 'unverified_ai_code_batch',
190
+ message: `${lines} changed lines submitted with 0 verified test assertions.`,
191
+ });
192
+ }
193
+
194
+ return {
195
+ ok: findings.length === 0,
196
+ podSize,
197
+ reviewToGenerationRatio,
198
+ findings,
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Pillar 3: Semantic Layer, Golden Examples & Tight Vetted Skills (08:37 - 13:34)
204
+ * Rejects codebase-average RAG dumps, requires top-decile golden examples, and caps
205
+ * active skills per workflow to prevent agent decision paralysis.
206
+ */
207
+ function curateContextGoldenExamplesAndSkills({
208
+ semanticLayer = {},
209
+ candidateExamples = [],
210
+ requestedSkills = [],
211
+ } = {}) {
212
+ const findings = [];
213
+
214
+ if (
215
+ !semanticLayer ||
216
+ !Array.isArray(semanticLayer.domainInvariants) ||
217
+ semanticLayer.domainInvariants.length === 0 ||
218
+ typeof semanticLayer.smeOwner !== 'string' ||
219
+ !semanticLayer.smeOwner.trim()
220
+ ) {
221
+ findings.push({
222
+ code: 'missing_tribal_semantic_layer',
223
+ message: 'Semantic layer must codify SME domainInvariants and smeOwner.',
224
+ });
225
+ }
226
+
227
+ const goldenExamples = (candidateExamples || []).filter(
228
+ (ex) =>
229
+ Number(ex.qualityPercentile || 0) >= MIN_GOLDEN_EXAMPLE_PERCENTILE &&
230
+ ex.passesArchitectureStandards === true &&
231
+ ex.isCodebaseAverage !== true
232
+ );
233
+
234
+ if (goldenExamples.length === 0) {
235
+ findings.push({
236
+ code: 'no_golden_examples_selected',
237
+ message: `Must provide at least one golden example (>= P${MIN_GOLDEN_EXAMPLE_PERCENTILE}, passesArchitectureStandards=true) instead of codebase averages.`,
238
+ });
239
+ }
240
+
241
+ const vettedSkills = (requestedSkills || []).filter((s) => s && s.centrallyVetted === true);
242
+ if (vettedSkills.length === 0) {
243
+ findings.push({
244
+ code: 'no_centrally_vetted_skills',
245
+ message: 'Workflow must use centrally vetted skills for the stack.',
246
+ });
247
+ }
248
+
249
+ if (vettedSkills.length > MAX_VETTED_SKILLS_PER_LOOP) {
250
+ findings.push({
251
+ code: 'skill_sprawl_decision_paralysis',
252
+ message: `Active vetted skills (${vettedSkills.length}) exceed cap of ${MAX_VETTED_SKILLS_PER_LOOP}. Curate a tight skill set to prevent agent decision paralysis.`,
253
+ });
254
+ }
255
+
256
+ return {
257
+ ok: findings.length === 0,
258
+ goldenExampleIds: goldenExamples.map((g) => g.id),
259
+ rejectedAverageCount: (candidateExamples || []).length - goldenExamples.length,
260
+ activeSkillNames: vettedSkills.slice(0, MAX_VETTED_SKILLS_PER_LOOP).map((s) => s.name),
261
+ findings,
262
+ };
263
+ }
264
+
265
+ function parseHexChannel(hex, start) {
266
+ const val = parseInt(hex.slice(start, start + 2), 16) / 255;
267
+ return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
268
+ }
269
+
270
+ function computeRelativeLuminance(hexColor) {
271
+ const clean = String(hexColor || '').replace(/^#/, '').trim();
272
+ const normalized =
273
+ clean.length === 3
274
+ ? clean
275
+ .split('')
276
+ .map((c) => c + c)
277
+ .join('')
278
+ : clean;
279
+ if (!/^[0-9a-fA-F]{6}$/.test(normalized)) {
280
+ return null;
281
+ }
282
+ const r = parseHexChannel(normalized, 0);
283
+ const g = parseHexChannel(normalized, 2);
284
+ const b = parseHexChannel(normalized, 4);
285
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
286
+ }
287
+
288
+ function computeContrastRatio(foregroundHex, backgroundHex) {
289
+ const l1 = computeRelativeLuminance(foregroundHex);
290
+ const l2 = computeRelativeLuminance(backgroundHex);
291
+ if (l1 === null || l2 === null) return null;
292
+ const lighter = Math.max(l1, l2);
293
+ const darker = Math.min(l1, l2);
294
+ return Number(((lighter + 0.05) / (darker + 0.05)).toFixed(2));
295
+ }
296
+
297
+ /**
298
+ * Pillar 4: Upstream, Downstream & Sideways Enterprise Guardrails (09:07, 14:15 - 15:52)
299
+ * Encodes security, compliance, design, and accessibility (WCAG contrast + colorblind safety)
300
+ * directly into agent guardrails to eliminate manual cross-team sign-off bottlenecks.
301
+ */
302
+ function evaluateSidewaysEnterpriseGuardrails({
303
+ upstreamSignals = [],
304
+ releaseChecklistComplete = false,
305
+ uiPalette = {},
306
+ codeSnippet = '',
307
+ complianceTags = [],
308
+ airgapPatterns = [],
309
+ } = {}) {
310
+ const findings = [];
311
+
312
+ if (!Array.isArray(upstreamSignals) || upstreamSignals.length === 0) {
313
+ findings.push({
314
+ code: 'disconnected_upstream_context',
315
+ message: 'Wire agent loop to upstream customer signals (inbox, logs, or telemetry).',
316
+ });
317
+ }
318
+
319
+ if (!releaseChecklistComplete) {
320
+ findings.push({
321
+ code: 'incomplete_downstream_release_checklist',
322
+ message: 'Downstream automated release checklist must be satisfied before deployment.',
323
+ });
324
+ }
325
+
326
+ const fg = uiPalette.foregroundHex || '#ffffff';
327
+ const bg = uiPalette.backgroundHex || '#0a0e17';
328
+ const minContrast = uiPalette.isLargeText ? WCAG_AA_LARGE_CONTRAST : WCAG_AA_NORMAL_CONTRAST;
329
+ const contrastRatio = computeContrastRatio(fg, bg);
330
+
331
+ const visualIssues = Array.isArray(uiPalette.visualFindings) ? [...uiPalette.visualFindings] : [];
332
+ const sel = uiPalette.selector || '.tg-surface';
333
+
334
+ if (contrastRatio === null || contrastRatio < minContrast) {
335
+ visualIssues.push({ type: 'low_contrast', selector: sel, fgHex: fg, bgHex: bg, minContrast });
336
+ }
337
+ if (uiPalette.reliesOnRedGreenOnly === true && uiPalette.hasNonColorShapeOrLabel !== true) {
338
+ visualIssues.push({ type: 'colorblind_unsafe_status', selector: sel });
339
+ }
340
+
341
+ const { runDesignSelfCorrectionPipeline } = require('./openshell-lovable-engine');
342
+ const selfCorrection = (visualIssues.length > 0 || uiPalette.layoutSource)
343
+ ? runDesignSelfCorrectionPipeline({
344
+ sourceCode: String(uiPalette.layoutSource || ''),
345
+ visualFindings: visualIssues,
346
+ defaultBgHex: bg,
347
+ minContrast,
348
+ allowTailwind: uiPalette.allowTailwind !== false,
349
+ })
350
+ : null;
351
+
352
+ if (contrastRatio === null || contrastRatio < minContrast) {
353
+ const cEdit = selfCorrection?.inlineEdits.find((e) => e.selector === sel) || selfCorrection?.inlineEdits[0] || null;
354
+ const cCss = selfCorrection?.cssOverrides.find((c) => c.selector === sel) || selfCorrection?.cssOverrides[0] || null;
355
+ const cTw = selfCorrection?.tailwindAdjustments.find((t) => t.selector === sel) || selfCorrection?.tailwindAdjustments[0] || null;
356
+ findings.push({
357
+ code: 'accessibility_contrast_violation',
358
+ message: `UI contrast ratio (${contrastRatio ?? 'invalid'}) between ${fg} and ${bg} is below WCAG AA minimum (${minContrast}:1).`,
359
+ remediation: { cssOverrides: cCss, tailwindAdjustments: cTw, inlineCodeEdit: cEdit },
360
+ });
361
+ }
362
+
363
+ if (uiPalette.reliesOnRedGreenOnly === true && uiPalette.hasNonColorShapeOrLabel !== true) {
364
+ const cbEdit = selfCorrection?.inlineEdits[selfCorrection.inlineEdits.length - 1] || null;
365
+ const cbCss = selfCorrection?.cssOverrides[selfCorrection.cssOverrides.length - 1] || null;
366
+ const cbTw = selfCorrection?.tailwindAdjustments[selfCorrection.tailwindAdjustments.length - 1] || null;
367
+ findings.push({
368
+ code: 'colorblind_accessibility_violation',
369
+ message: 'Colorblind accessibility guardrail: status indicators cannot rely on red/green hue alone without an icon/text label.',
370
+ remediation: { cssOverrides: cbCss, tailwindAdjustments: cbTw, inlineCodeEdit: cbEdit },
371
+ });
372
+ }
373
+
374
+ const snippet = String(codeSnippet || '');
375
+ if (toAirgapRegexes(airgapPatterns).some((re) => re.test(snippet))) {
376
+ findings.push({
377
+ code: 'corporate_airgap_leak_blocked',
378
+ message: 'Sideways DLP guardrail: corporate air-gapped hostname/IP detected in payload.',
379
+ });
380
+ }
381
+
382
+ if (!Array.isArray(complianceTags) || !complianceTags.includes('pretool_diode_verified')) {
383
+ findings.push({
384
+ code: 'missing_compliance_diode_tag',
385
+ message: 'Sideways compliance guardrail requires pretool_diode_verified attestation.',
386
+ });
387
+ }
388
+
389
+ return {
390
+ ok: findings.length === 0,
391
+ contrastRatio,
392
+ findings,
393
+ ...(selfCorrection ? { selfCorrection } : {}),
394
+ };
395
+ }
396
+
397
+ /**
398
+ * Pillar 5: AIOps Token ROI & Business Impact Scorer (10:10, 17:25)
399
+ * Evaluates feature intent and business impact against token spend so budgets
400
+ * go toward high-impact outcomes with $0 outbound cash spend.
401
+ */
402
+ function scoreTokenRoiAndBusinessImpact({
403
+ featureId = 'feature-001',
404
+ estimatedTokens = 0,
405
+ costPerMillionTokensUsd = 3.0,
406
+ expectedRevenueImpactUsd = 0,
407
+ engineeringHoursSaved = 0,
408
+ hourlyEngineeringRateUsd = 150,
409
+ outboundCashSpendUsd = 0,
410
+ } = {}) {
411
+ const findings = [];
412
+ if (Number(outboundCashSpendUsd) > 0) {
413
+ findings.push({
414
+ code: 'zero_outbound_spend_violation',
415
+ message: `outboundCashSpendUsd (${outboundCashSpendUsd}) must be 0 under the They-Pay-Us mandate.`,
416
+ });
417
+ }
418
+
419
+ const tokens = Math.max(1, Number(estimatedTokens) || 1);
420
+ const rate = Math.max(0, Number(costPerMillionTokensUsd) || 0);
421
+ const tokenCostUsd = Number(((tokens / 1_000_000) * rate).toFixed(4));
422
+ const effectiveTokenCostUsd = Math.max(0.01, tokenCostUsd);
423
+
424
+ const totalBusinessValueUsd = Number(
425
+ (
426
+ Math.max(0, Number(expectedRevenueImpactUsd) || 0) +
427
+ Math.max(0, Number(engineeringHoursSaved) || 0) * Math.max(0, Number(hourlyEngineeringRateUsd) || 0)
428
+ ).toFixed(2)
429
+ );
430
+
431
+ const roiMultiplier = Number((totalBusinessValueUsd / effectiveTokenCostUsd).toFixed(2));
432
+ if (roiMultiplier < 10) {
433
+ findings.push({
434
+ code: 'low_token_roi_feature',
435
+ message: `Token ROI multiplier (${roiMultiplier}x) is below the 10x high-impact threshold.`,
436
+ });
437
+ }
438
+
439
+ return {
440
+ ok: findings.length === 0,
441
+ featureId,
442
+ tokenCostUsd,
443
+ totalBusinessValueUsd,
444
+ roiMultiplier,
445
+ priorityTier: roiMultiplier >= 100 ? 'P0_HIGH_ROI' : roiMultiplier >= 10 ? 'P1_APPROVED' : 'REJECT_LOW_ROI',
446
+ findings,
447
+ };
448
+ }
449
+
450
+ /**
451
+ * Unified 5-Pillar McKinsey AI Coding Operating Model Audit
452
+ */
453
+ function runMcKinseyAiCodingAudit(input = {}) {
454
+ const specVerdict = validateStandardSpecArtifact(input.spec);
455
+ const podVerdict = auditPodTopologyAndReviewRatio(input.pod);
456
+ const contextVerdict = curateContextGoldenExamplesAndSkills(input.context);
457
+ const sidewaysVerdict = evaluateSidewaysEnterpriseGuardrails(input.sideways);
458
+ const roiVerdict = scoreTokenRoiAndBusinessImpact(input.roi);
459
+
460
+ const allAutomatedGatesPassed =
461
+ specVerdict.ok && podVerdict.ok && contextVerdict.ok && sidewaysVerdict.ok && roiVerdict.ok;
462
+
463
+ const hitlVerdict = evaluateProgressiveHitlGate({
464
+ ...(input.hitl || {}),
465
+ allAutomatedGatesPassed,
466
+ });
467
+
468
+ return {
469
+ ok: allAutomatedGatesPassed,
470
+ specVerdict,
471
+ podVerdict,
472
+ contextVerdict,
473
+ sidewaysVerdict,
474
+ roiVerdict,
475
+ hitlVerdict,
476
+ };
477
+ }
478
+
479
+ module.exports = {
480
+ MAX_KANBAN_CYCLE_HOURS,
481
+ MIN_POD_SIZE,
482
+ MAX_POD_SIZE,
483
+ MAX_VETTED_SKILLS_PER_LOOP,
484
+ MIN_GOLDEN_EXAMPLE_PERCENTILE,
485
+ validateStandardSpecArtifact,
486
+ evaluateProgressiveHitlGate,
487
+ auditPodTopologyAndReviewRatio,
488
+ curateContextGoldenExamplesAndSkills,
489
+ computeContrastRatio,
490
+ evaluateSidewaysEnterpriseGuardrails,
491
+ scoreTokenRoiAndBusinessImpact,
492
+ runMcKinseyAiCodingAudit,
493
+ };
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ module.exports = require('../../adapters/mcp/server-stdio');