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.
Files changed (180) hide show
  1. package/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
  2. package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.well-known/llms.txt +2 -2
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +11 -5
  7. package/adapters/claude/.mcp.json +6 -2
  8. package/adapters/codex/config.toml +5 -0
  9. package/adapters/forge/forge.yaml +4 -4
  10. package/adapters/future-agi/.mcp.json +1 -1
  11. package/adapters/future-agi/config.toml +1 -1
  12. package/adapters/future-agi/opencode.json +1 -1
  13. package/adapters/herdr/herdr-plugin.toml +2 -2
  14. package/adapters/mcp/server-stdio.js +104 -7
  15. package/adapters/opencode/opencode.json +1 -1
  16. package/adapters/strands/strands-middleware.js +31 -4
  17. package/bin/cli.js +191 -54
  18. package/config/brand-standards.json +131 -0
  19. package/config/gates/default.json +18 -1
  20. package/config/github-about.json +1 -1
  21. package/config/mcp-allowlists.json +16 -3
  22. package/config/merge-quality-checks.json +3 -1
  23. package/config/post-deploy-marketing-pages.json +4 -4
  24. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  25. package/hooks/hooks.json +24 -0
  26. package/openapi/openapi.yaml +7 -3
  27. package/package.json +87 -33
  28. package/public/about.html +2 -2
  29. package/public/admin.html +771 -0
  30. package/public/agent-manager.html +3 -3
  31. package/public/agents-cost-savings.html +1 -1
  32. package/public/ai-malpractice-prevention.html +12 -12
  33. package/public/architecture.html +0 -1
  34. package/public/assets/diagrams/decision.svg +3 -3
  35. package/public/assets/diagrams/hero-thumbs.svg +2 -4
  36. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  37. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  38. package/public/blog/git-at-agent-scale.html +2 -2
  39. package/public/blog/inside-your-boundary.html +1 -1
  40. package/public/blog/process-over-outcome-gates.html +1 -1
  41. package/public/case-studies.html +5 -6
  42. package/public/codex-enterprise.html +1 -1
  43. package/public/codex-plugin.html +1 -1
  44. package/public/dashboard.html +775 -483
  45. package/public/diagnostic.html +15 -10
  46. package/public/enterprise-governance.html +26 -174
  47. package/public/eval-scorecard.html +3 -4
  48. package/public/eval-scorecard.json +2 -2
  49. package/public/evaluations.html +0 -1
  50. package/public/founders.html +3 -3
  51. package/public/gaming-playbook.html +4 -4
  52. package/public/guide.html +3 -5
  53. package/public/index.html +302 -97
  54. package/public/install.html +16 -10
  55. package/public/js/buyer-intent.js +49 -8
  56. package/public/lessons.html +246 -83
  57. package/public/numbers.html +32 -33
  58. package/public/operator-framework.html +44 -72
  59. package/public/peter.html +3 -3
  60. package/public/platform-partners.html +1 -1
  61. package/public/pricing.html +163 -66
  62. package/public/pro.html +3 -1
  63. package/public/project-switcher.js +76 -0
  64. package/public/whitepaper.html +1 -2
  65. package/scripts/action-receipts.js +393 -0
  66. package/scripts/activation-quickstart.js +15 -3
  67. package/scripts/activation-tracker.js +280 -3
  68. package/scripts/agent-action-inventory.js +235 -143
  69. package/scripts/agent-operations-planner.js +1 -1
  70. package/scripts/agent-readiness.js +36 -6
  71. package/scripts/agentic-prompt-pipelines.js +901 -0
  72. package/scripts/analytics-window.js +7 -1
  73. package/scripts/async-job-runner.js +66 -11
  74. package/scripts/audit-trail.js +37 -24
  75. package/scripts/auto-promote-gates.js +37 -27
  76. package/scripts/auto-wire-hooks.js +64 -25
  77. package/scripts/backfill-lesson-scopes.js +122 -0
  78. package/scripts/billing.js +889 -132
  79. package/scripts/bot-detection.js +112 -0
  80. package/scripts/brand-standards-gate.js +571 -0
  81. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  82. package/scripts/cli-demo.js +5 -27
  83. package/scripts/cli-schema.js +25 -1
  84. package/scripts/commercial-offer.js +2 -2
  85. package/scripts/contextfs.js +9 -3
  86. package/scripts/craft-playbook-gate.js +550 -0
  87. package/scripts/cross-encoder-reranker.js +4 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +574 -167
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/docker-sandbox-planner.js +3 -3
  92. package/scripts/export-dpo-pairs.js +12 -7
  93. package/scripts/failure-diagnostics.js +11 -0
  94. package/scripts/feedback-aggregate.js +4 -0
  95. package/scripts/feedback-attribution.js +6 -4
  96. package/scripts/feedback-history-distiller.js +18 -6
  97. package/scripts/feedback-loop.js +255 -89
  98. package/scripts/feedback-paths.js +8 -1
  99. package/scripts/feedback-sanitizer.js +5 -0
  100. package/scripts/feedback-scope.js +106 -0
  101. package/scripts/feedback-session.js +8 -2
  102. package/scripts/filesystem-search.js +13 -8
  103. package/scripts/financial-control-plane.js +707 -45
  104. package/scripts/gate-stats.js +38 -5
  105. package/scripts/gates-engine.js +1326 -240
  106. package/scripts/generate-eval-scorecard.js +0 -1
  107. package/scripts/gitlab-sdlc-prompts.js +397 -0
  108. package/scripts/harness-tool-names.js +31 -5
  109. package/scripts/hook-runtime.js +10 -0
  110. package/scripts/hybrid-feedback-context.js +7 -2
  111. package/scripts/intervention-policy.js +2 -1
  112. package/scripts/lesson-canonical.js +2 -2
  113. package/scripts/lesson-db.js +55 -14
  114. package/scripts/lesson-graph.js +2 -1
  115. package/scripts/lesson-retrieval.js +95 -9
  116. package/scripts/lesson-search.js +86 -22
  117. package/scripts/lesson-synthesis.js +21 -5
  118. package/scripts/mabl-failure-honesty.js +273 -0
  119. package/scripts/mailer/index.js +17 -1
  120. package/scripts/mailer/resend-mailer.js +213 -179
  121. package/scripts/migrate-project-scope.js +209 -0
  122. package/scripts/model-distress-detector.js +3 -3
  123. package/scripts/operational-integrity.js +436 -3
  124. package/scripts/override-audit.js +2 -0
  125. package/scripts/owner-admin.js +338 -0
  126. package/scripts/pr-manager.js +194 -1
  127. package/scripts/product-feedback.js +35 -0
  128. package/scripts/progressive-signoff.js +260 -0
  129. package/scripts/project-catalog.js +243 -0
  130. package/scripts/project-dashboard.js +61 -0
  131. package/scripts/project-evidence.js +172 -0
  132. package/scripts/project-identity.js +182 -0
  133. package/scripts/project-scope.js +381 -0
  134. package/scripts/prompt-eval.js +1 -1
  135. package/scripts/prompt-guard.js +446 -52
  136. package/scripts/proof-report.js +232 -0
  137. package/scripts/provider-action-normalizer.js +14 -6
  138. package/scripts/qwenwork-policy-group.js +413 -0
  139. package/scripts/rate-limiter.js +41 -0
  140. package/scripts/secret-redaction.js +171 -25
  141. package/scripts/secret-scanner.js +101 -42
  142. package/scripts/self-protection.js +2 -2
  143. package/scripts/seo-gsd.js +14 -14
  144. package/scripts/session-context-dedupe.js +66 -0
  145. package/scripts/settings-hierarchy.js +4 -2
  146. package/scripts/statusline-meta.js +34 -23
  147. package/scripts/tailscale-october-access.js +416 -0
  148. package/scripts/task-outcomes.js +58 -2
  149. package/scripts/telemetry-analytics.js +260 -16
  150. package/scripts/thumbgate-search.js +23 -9
  151. package/scripts/tool-kpi-tracker.js +5 -2
  152. package/scripts/tool-registry.js +42 -1
  153. package/scripts/triage-savings-calculator.js +1 -1
  154. package/scripts/vector-store.js +4 -1
  155. package/scripts/verified-lessons.js +270 -0
  156. package/scripts/verify-marketing-pages-deployed.js +2 -2
  157. package/scripts/workflow-sentinel.js +29 -10
  158. package/server.json +2 -2
  159. package/src/api/server.js +2478 -470
  160. package/src/feedback.js +21 -0
  161. package/src/hermes-sync-plane.js +2 -1
  162. package/src/index.js +2 -0
  163. package/src/lesson-search.js +9 -0
  164. package/src/mckinsey-top-company-ai-coding.js +493 -0
  165. package/src/mcp/email-triage-server/index.js +973 -0
  166. package/src/mcp/email-triage-server/package.json +12 -0
  167. package/src/mcp/server.js +3 -0
  168. package/src/mcp-writeguard.js +772 -11
  169. package/src/openshell-lovable-engine.js +1475 -0
  170. package/src/task-outcome.js +3 -0
  171. package/config/evals/agent-safety-eval.json +0 -447
  172. package/config/evals/retrieval-ranking-golden.json +0 -522
  173. package/config/progressive/01-wire-only.json +0 -11
  174. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  175. package/config/progressive/03-one-lesson.json +0 -10
  176. package/config/progressive/04-warn-fires.json +0 -11
  177. package/config/progressive/05-strict-optional.json +0 -11
  178. package/config/progressive/README.md +0 -15
  179. package/public/assets/diagrams/agent-integration.png +0 -0
  180. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
@@ -218,6 +218,44 @@ function getUsage(action, authContext) {
218
218
  return { count: lifetimeCount, limit: lifetimeLimit, remaining: Math.max(0, lifetimeLimit - lifetimeCount) };
219
219
  }
220
220
 
221
+ const PRO_REPEAT_URL = 'https://thumbgate.ai/pro';
222
+ const RULE_SECTION_SKIP = new Set([
223
+ 'High-Priority Contracts',
224
+ 'Rubric Failure Dimensions',
225
+ 'Root Cause Categories',
226
+ 'Repeated Failure Constraints',
227
+ ]);
228
+
229
+ function scrubRepeatText(value) {
230
+ return String(value || '')
231
+ .replace(/\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b/g, '[redacted]')
232
+ .replace(/\b(?:sk|ghp|github_pat|AKIA)[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
233
+ .replace(/\/Users\/[^\s]+/g, '[path]')
234
+ .replace(/\s+/g, ' ')
235
+ .trim()
236
+ .slice(0, 140);
237
+ }
238
+
239
+ function proWouldHaveBlockedSentence(mistake) {
240
+ const clean = scrubRepeatText(mistake);
241
+ if (!clean) return null;
242
+ return `Pro would have blocked this repeat: ${clean}. ${PRO_REPEAT_URL}`;
243
+ }
244
+
245
+ function droppedRepeatFromRulesMarkdown(markdown, maxActive = FREE_TIER_MAX_GATES) {
246
+ const mistakes = [];
247
+ for (const section of String(markdown || '').split(/\n## /)) {
248
+ const title = section.replace(/^## /, '').split('\n')[0].trim();
249
+ if (!title || RULE_SECTION_SKIP.has(title)) continue;
250
+ if (!/^- Rule: /m.test(section) && !/^- Latest mistake: /m.test(section)) continue;
251
+ const latest = (section.match(/^- Latest mistake: (.+)$/m) || [])[1];
252
+ const rule = (section.match(/^- Rule: (.+)$/m) || [])[1];
253
+ const text = scrubRepeatText(latest || rule || title);
254
+ if (text) mistakes.push(text);
255
+ }
256
+ return mistakes.length > maxActive ? mistakes[maxActive] : null;
257
+ }
258
+
221
259
  module.exports = {
222
260
  checkLimit,
223
261
  getUsage,
@@ -235,4 +273,7 @@ module.exports = {
235
273
  UPGRADE_MESSAGE,
236
274
  PAYWALL_MESSAGES,
237
275
  USAGE_FILE,
276
+ proWouldHaveBlockedSentence,
277
+ droppedRepeatFromRulesMarkdown,
278
+ scrubRepeatText,
238
279
  };
@@ -158,47 +158,178 @@ function redactSecretsDeep(value) {
158
158
  return value;
159
159
  }
160
160
  const crypto = require('node:crypto');
161
+ const fs = require('node:fs');
162
+ const path = require('node:path');
161
163
 
162
- /**
163
- * Capital One Databolt-style Vaultless Format-Preserving Tokenization (FPT).
164
- */
165
- function tokenizeFormatPreservingVaultless(text, { salt = process.env.THUMBGATE_FPT_KEY } = {}) {
166
- if (typeof text !== 'string' || text.length === 0) return text;
167
- if (typeof salt !== 'string' || salt.length < 16) {
168
- throw new Error('tokenizeFormatPreservingVaultless requires a secret key of at least 16 characters');
164
+ function computeLuhnCheckDigit(digitsWithoutCheck) {
165
+ let sum = 0;
166
+ let shouldDouble = true;
167
+ for (let i = digitsWithoutCheck.length - 1; i >= 0; i -= 1) {
168
+ let digit = Number(digitsWithoutCheck[i]);
169
+ if (shouldDouble) {
170
+ digit *= 2;
171
+ if (digit > 9) digit -= 9;
172
+ }
173
+ sum += digit;
174
+ shouldDouble = !shouldDouble;
175
+ }
176
+ return String((10 - (sum % 10)) % 10);
177
+ }
178
+
179
+ function formatCardToken(rawMatch, digestDigits) {
180
+ const digitsOnly = rawMatch.replaceAll(/\D/g, '');
181
+ if (digitsOnly.startsWith('9999')) return rawMatch;
182
+ const middleLen = digitsOnly.length - 5;
183
+ const payload = `9999${digestDigits(digitsOnly, middleLen)}`;
184
+ const fullDigits = `${payload}${computeLuhnCheckDigit(payload)}`;
185
+ let cursor = 0;
186
+ let formatted = '';
187
+ for (const ch of rawMatch) {
188
+ if (ch >= '0' && ch <= '9') {
189
+ formatted += fullDigits[cursor];
190
+ cursor += 1;
191
+ } else {
192
+ formatted += ch;
193
+ }
194
+ }
195
+ return formatted;
196
+ }
197
+
198
+ function tokenizeSecretsReferentially(text, digestHex) {
199
+ let out = text;
200
+ for (const pattern of SECRET_REDACTION_PATTERNS) {
201
+ pattern.regex.lastIndex = 0;
202
+ if (pattern.id === 'bearer_token') {
203
+ out = out.replaceAll(pattern.regex, (full, scheme) => {
204
+ const rawSecret = full.slice(scheme.length).trim();
205
+ return `${scheme} [FPT:bearer_token#${digestHex(rawSecret).slice(0, 8)}]`;
206
+ });
207
+ } else if (pattern.id === 'secret_assignment') {
208
+ out = out.replaceAll(pattern.regex, (match, key, pre, value, post) => (
209
+ (SECRET_KEY_NAME.test(key) && !PUBLIC_KEY_NAME.test(key))
210
+ ? `${key}${pre}[FPT:secret_assignment#${digestHex(value).slice(0, 8)}]${post}`
211
+ : match
212
+ ));
213
+ } else {
214
+ out = out.replaceAll(pattern.regex, (match) => `[FPT:${pattern.id}#${digestHex(match).slice(0, 8)}]`);
215
+ }
169
216
  }
170
- const digestHex = (val) => crypto.createHmac('sha256', String(salt)).update(String(val)).digest('hex');
217
+ return out;
218
+ }
219
+
220
+ function createVaultlessDigesters(salt) {
221
+ const digestHex = (val) => crypto.createHmac('sha256', salt).update(String(val)).digest('hex');
171
222
  const digestDigits = (val, len) => {
172
223
  const hex = digestHex(val);
173
224
  let out = '';
174
- for (let i = 0; i < hex.length && out.length < len; i += 2) {
225
+ for (let i = 0; i < len * 2; i += 2) {
175
226
  out += String(Number.parseInt(hex.slice(i, i + 2), 16) % 10);
176
227
  }
177
- return out.padEnd(len, '0').slice(0, len);
228
+ return out;
178
229
  };
230
+ return { digestHex, digestDigits };
231
+ }
179
232
 
180
- let out = redactSecrets(text);
181
- out = out.replace(/\b([A-Za-z0-9._%+-]{1,64})@([A-Za-z0-9.-]+\.[A-Za-z]{2,})\b/g, (match, _local, domain) => {
182
- if (domain.toLowerCase() === 'tokenized.local') return match;
183
- return `tok_${digestHex(match.toLowerCase()).slice(0, 8)}@tokenized.local`;
184
- });
185
- out = out.replace(/\b(?!900-)\d{3}-\d{2}-\d{4}\b/g, (match) => {
186
- const d = digestDigits(match, 6);
187
- return `900-${d.slice(0, 2)}-${d.slice(2, 6)}`;
188
- });
189
- out = out.replace(/\b(\d{3})-(\d{3})-(\d{4})\b/g, (match, a, b) => {
190
- if (a === '900' || (a === '555' && b.startsWith('01'))) return match;
191
- const d = digestDigits(match, 6);
192
- return `555-01${d.slice(0, 1)}-${d.slice(1, 5)}`;
233
+ function formatEmailToken(match, _local, domain, digestHex) {
234
+ if (domain.toLowerCase() === 'tokenized.local') return match;
235
+ return `tok_${digestHex(match.toLowerCase()).slice(0, 8)}@tokenized.local`;
236
+ }
237
+
238
+ function formatSsnToken(match, sep, digestDigits) {
239
+ const canonical = match.replaceAll(/\D/g, '');
240
+ const d = digestDigits(canonical, 6);
241
+ return `900${sep}${d.slice(0, 2)}${sep}${d.slice(2, 6)}`;
242
+ }
243
+
244
+ function formatUsPhoneToken(match, countryPrefix, area, exchange, digestDigits) {
245
+ if (area === '900' || (area === '555' && exchange.startsWith('01'))) return match;
246
+ const canonical = `${area}${exchange}${match.replaceAll(/\D/g, '').slice(-4)}`;
247
+ const d = digestDigits(canonical, 6);
248
+ const prefix = countryPrefix || '';
249
+ return `${prefix}555-01${d.slice(0, 1)}-${d.slice(1, 5)}`;
250
+ }
251
+
252
+ const FPT_EMAIL_RE = /\b([A-Za-z0-9._%+-]{1,64})@([A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24})\b/g;
253
+ const FPT_CARD_RE = /\b(?:\d{4}[ -]?){3}\d{1,7}\b/g;
254
+ const FPT_SSN_RE = /\b(?!900[-.\s])\d{3}([-.\s])\d{2}\1\d{4}\b/g;
255
+ const FPT_US_PHONE_RE = /(?:\+?1[-.\s]?)?\(?(\d{3})\)?[-.\s](\d{3})[-.\s]\d{4}\b/g;
256
+
257
+ /**
258
+ * Capital One Databolt-style Vaultless Format-Preserving Tokenization (FPT).
259
+ * Tokenizes sensitive values at ingestion while preserving format and referential integrity.
260
+ */
261
+ function tokenizeFormatPreservingVaultless(text, {
262
+ salt = process.env.THUMBGATE_FPT_KEY,
263
+ preserveSecretReferentialIntegrity = false,
264
+ } = {}) {
265
+ if (typeof text !== 'string' || text.length === 0) return text;
266
+ if (typeof salt !== 'string' || salt.length < 16) {
267
+ throw new TypeError('tokenizeFormatPreservingVaultless requires a secret key of at least 16 characters');
268
+ }
269
+ const { digestHex, digestDigits } = createVaultlessDigesters(salt);
270
+ let out = preserveSecretReferentialIntegrity
271
+ ? tokenizeSecretsReferentially(text, digestHex)
272
+ : redactSecrets(text);
273
+ out = out.replaceAll(FPT_EMAIL_RE, (m, local, dom) => formatEmailToken(m, local, dom, digestHex));
274
+ out = out.replaceAll(FPT_CARD_RE, (m) => formatCardToken(m, digestDigits));
275
+ out = out.replaceAll(FPT_SSN_RE, (m, sep) => formatSsnToken(m, sep, digestDigits));
276
+ out = out.replaceAll(FPT_US_PHONE_RE, (m, area, exch) => {
277
+ const prefixMatch = m.match(/^\+?1[-.\s]/);
278
+ return formatUsPhoneToken(m, prefixMatch ? prefixMatch[0] : '', area, exch, digestDigits);
193
279
  });
194
280
  return out;
195
281
  }
196
282
 
283
+ function tokenizeDeepAtSource(value, options = {}) {
284
+ let fieldsTokenized = 0;
285
+ function walk(node) {
286
+ if (typeof node === 'string') {
287
+ const tokenized = tokenizeFormatPreservingVaultless(node, options);
288
+ if (tokenized !== node) fieldsTokenized += 1;
289
+ return tokenized;
290
+ }
291
+ if (Array.isArray(node)) return node.map((item) => walk(item));
292
+ if (node && typeof node === 'object') {
293
+ const copy = {};
294
+ for (const [k, v] of Object.entries(node)) copy[k] = walk(v);
295
+ return copy;
296
+ }
297
+ return node;
298
+ }
299
+ return {
300
+ data: walk(value),
301
+ fieldsTokenized,
302
+ referentialIntegrity: true,
303
+ };
304
+ }
305
+
306
+ function collectFieldDetokenizationBlockers(requestedFields, allowedFields) {
307
+ if (!Array.isArray(requestedFields) || requestedFields.length === 0) return [];
308
+ if (!Array.isArray(allowedFields)) return [];
309
+ const allowedSet = new Set(allowedFields);
310
+ return requestedFields
311
+ .filter((field) => !allowedSet.has(field))
312
+ .map((field) => `unauthorized_field_detokenization:${field}`);
313
+ }
314
+
315
+ function writeDetokenizationAudit(auditEntry, { auditLogPath, onAuditEvent }) {
316
+ if (typeof onAuditEvent === 'function') onAuditEvent(auditEntry);
317
+ if (typeof auditLogPath === 'string' && auditLogPath.length > 0) {
318
+ fs.mkdirSync(path.dirname(auditLogPath), { recursive: true });
319
+ fs.appendFileSync(auditLogPath, `${JSON.stringify(auditEntry)}\n`, { mode: 0o600 });
320
+ }
321
+ }
322
+
197
323
  function enforceZeroTrustDetokenizationGate({
198
324
  authenticated = false,
199
325
  roleAuthorizedForPlaintext = false,
200
326
  explicitDetokenizePermission = false,
201
327
  crossesExternalNetwork = false,
328
+ principalId = null,
329
+ requestedFields = [],
330
+ allowedFields = null,
331
+ auditLogPath = null,
332
+ onAuditEvent = null,
202
333
  } = {}) {
203
334
  const blockers = [];
204
335
  if (authenticated !== true) blockers.push('unauthenticated_caller');
@@ -206,11 +337,24 @@ function enforceZeroTrustDetokenizationGate({
206
337
  if (roleAuthorizedForPlaintext !== true || explicitDetokenizePermission !== true) {
207
338
  blockers.push('default_tokenized_view_enforced_explicit_detokenize_permission_required');
208
339
  }
340
+ blockers.push(...collectFieldDetokenizationBlockers(requestedFields, allowedFields));
341
+ const allowed = blockers.length === 0;
342
+ const viewMode = allowed ? 'DETOKENIZED_PLAINTEXT' : 'TOKENIZED_ONLY';
343
+ const auditEntry = {
344
+ recordedAt: new Date().toISOString(),
345
+ principalId: principalId || 'anonymous',
346
+ requestedFields: Array.isArray(requestedFields) ? [...requestedFields] : [],
347
+ allowed,
348
+ viewMode,
349
+ blockers: [...blockers],
350
+ };
351
+ writeDetokenizationAudit(auditEntry, { auditLogPath, onAuditEvent });
209
352
  return {
210
- allowed: blockers.length === 0,
211
- viewMode: blockers.length === 0 ? 'DETOKENIZED_PLAINTEXT' : 'TOKENIZED_ONLY',
353
+ allowed,
354
+ viewMode,
212
355
  vaultlessInEnvironment: !crossesExternalNetwork,
213
356
  blockers,
357
+ auditEntry,
214
358
  };
215
359
  }
216
360
 
@@ -219,6 +363,8 @@ module.exports = {
219
363
  redactSecrets,
220
364
  redactSecretsDeep,
221
365
  containsSecret,
366
+ computeLuhnCheckDigit,
222
367
  tokenizeFormatPreservingVaultless,
368
+ tokenizeDeepAtSource,
223
369
  enforceZeroTrustDetokenizationGate,
224
370
  };
@@ -34,7 +34,7 @@ const SECRET_FILE_PATTERNS = [
34
34
  { id: 'pypirc_file', label: 'Python package credentials file', regex: /(^|\/)\.pypirc$/i },
35
35
  // Do not match *.pub — public keys are routinely read for SSH setup.
36
36
  { id: 'ssh_private_key', label: 'SSH private key', regex: /(^|\/)(?:id_rsa|id_ed25519|id_dsa|id_ecdsa)$/i },
37
- { id: 'ssh_private_key_path', label: 'SSH private key path', regex: /(^|\/)\.ssh\/id_[A-Za-z0-9_-]+$/i },
37
+ { id: 'ssh_private_key_path', label: 'SSH private key path', regex: /(^|\/)\.ssh\/id_[a-z0-9_-]+$/i },
38
38
  { id: 'aws_credentials', label: 'AWS credentials file', regex: /(^|\/)\.aws\/credentials$/i },
39
39
  { id: 'kubeconfig', label: 'Kubernetes config', regex: /(^|\/)\.kube\/config$/i },
40
40
  { id: 'docker_config', label: 'Docker config credentials', regex: /(^|\/)\.docker\/config\.json$/i },
@@ -44,7 +44,46 @@ const SECRET_FILE_PATTERNS = [
44
44
 
45
45
  // Env vars that commonly hold secrets. Used to catch exfil when the secret
46
46
  // never appears as a literal in the command (e.g. echo $API_KEY | curl ...).
47
- const SECRET_ENV_VAR_PATTERN = /\$\{?(?:API[_-]?KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|GEMINI_API_KEY|AWS_SECRET_ACCESS_KEY|AWS_ACCESS_KEY_ID|AWS_SESSION_TOKEN|GITHUB_TOKEN|GH_TOKEN|STRIPE_SECRET_KEY|STRIPE_API_KEY|NPM_TOKEN|HF_TOKEN|HUGGINGFACE_TOKEN|DATABASE_URL|DB_PASSWORD|POSTGRES_PASSWORD|MYSQL_PWD|PRIVATE_KEY|SECRET_KEY|ACCESS_TOKEN|AUTH_TOKEN|CLIENT_SECRET|SLACK_BOT_TOKEN|DISCORD_TOKEN)(?!\w)/i;
47
+ const SECRET_ENV_VAR_NAMES = new Set([
48
+ 'API_KEY',
49
+ 'APIKEY',
50
+ 'API-KEY',
51
+ 'OPENAI_API_KEY',
52
+ 'ANTHROPIC_API_KEY',
53
+ 'GEMINI_API_KEY',
54
+ 'AWS_SECRET_ACCESS_KEY',
55
+ 'AWS_ACCESS_KEY_ID',
56
+ 'AWS_SESSION_TOKEN',
57
+ 'GITHUB_TOKEN',
58
+ 'GH_TOKEN',
59
+ 'STRIPE_SECRET_KEY',
60
+ 'STRIPE_API_KEY',
61
+ 'NPM_TOKEN',
62
+ 'HF_TOKEN',
63
+ 'HUGGINGFACE_TOKEN',
64
+ 'DATABASE_URL',
65
+ 'DB_PASSWORD',
66
+ 'POSTGRES_PASSWORD',
67
+ 'MYSQL_PWD',
68
+ 'PRIVATE_KEY',
69
+ 'SECRET_KEY',
70
+ 'ACCESS_TOKEN',
71
+ 'AUTH_TOKEN',
72
+ 'CLIENT_SECRET',
73
+ 'SLACK_BOT_TOKEN',
74
+ 'DISCORD_TOKEN',
75
+ ]);
76
+
77
+ function hasSecretEnvVarRef(text) {
78
+ const input = String(text || '');
79
+ const refRe = /\$\{?([a-z0-9_-]+)(?!\w)/gi;
80
+ let match = refRe.exec(input);
81
+ while (match) {
82
+ if (SECRET_ENV_VAR_NAMES.has(match[1].toUpperCase())) return true;
83
+ match = refRe.exec(input);
84
+ }
85
+ return false;
86
+ }
48
87
 
49
88
  const BASH_SECRET_READ_PREFIXES = [
50
89
  'cat',
@@ -221,6 +260,23 @@ function sonarScanFile(filePath) {
221
260
  };
222
261
  }
223
262
 
263
+ function isCodePropertyAccessValue(rawMatch, nextChar) {
264
+ const sepIdx = rawMatch.search(/[:=]/);
265
+ if (sepIdx === -1) return false;
266
+ const rhs = rawMatch.slice(sepIdx + 1).trim();
267
+ const isQuoted = (rhs.startsWith('"') && rhs.endsWith('"')) || (rhs.startsWith("'") && rhs.endsWith("'"));
268
+ if (isQuoted) return false;
269
+ if (nextChar === '(' && /^[A-Za-z_$][A-Za-z0-9_$.]*$/.test(rhs)) return true;
270
+ return /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)+$/.test(rhs);
271
+ }
272
+
273
+ function shouldSkipGenericAssignment(patternId, rawMatch, nextChar) {
274
+ if (patternId !== 'generic_assignment') return false;
275
+ const lowered = rawMatch.toLowerCase();
276
+ if (lowered.includes('sk_test_') || lowered.includes('test_token')) return true;
277
+ return isCodePropertyAccessValue(rawMatch, nextChar);
278
+ }
279
+
224
280
  function heuristicScanText(text, source = 'text') {
225
281
  const input = String(text || '');
226
282
  const findings = [];
@@ -228,20 +284,16 @@ function heuristicScanText(text, source = 'text') {
228
284
  pattern.regex.lastIndex = 0;
229
285
  let match = pattern.regex.exec(input);
230
286
  while (match) {
231
- // Safe test key bypass
232
- const matchedString = match[0].toLowerCase();
233
- if (pattern.id === 'generic_assignment' && (matchedString.includes('sk_test_') || matchedString.includes('test_token'))) {
234
- match = pattern.regex.exec(input);
235
- continue;
287
+ const nextChar = input[match.index + match[0].length] || '';
288
+ if (!shouldSkipGenericAssignment(pattern.id, match[0], nextChar)) {
289
+ findings.push({
290
+ id: pattern.id,
291
+ label: pattern.label,
292
+ source,
293
+ line: computeLineNumber(input, match.index),
294
+ reason: `${pattern.label} detected`,
295
+ });
236
296
  }
237
-
238
- findings.push({
239
- id: pattern.id,
240
- label: pattern.label,
241
- source,
242
- line: computeLineNumber(input, match.index),
243
- reason: `${pattern.label} detected`,
244
- });
245
297
  match = pattern.regex.exec(input);
246
298
  }
247
299
  }
@@ -706,9 +758,9 @@ function detectCommandSubstitutionExfil(command, cwd) {
706
758
  // $(cat .env), $(base64 .env), `cat .env`, <(cat .env) — secret not literal in curl argv.
707
759
  const findings = [];
708
760
  const patterns = [
709
- /\$\(\s*([a-z0-9._+-]+)\s+([^)]+)\)/gi,
710
- /`\s*([a-z0-9._+-]+)\s+([^`]+)`/gi,
711
- /<\(\s*([a-z0-9._+-]+)\s+([^)]+)\)/gi,
761
+ /\$\(\s*([a-z0-9._+-]+)\s+([^\s)][^)]*)\)/gi,
762
+ /`\s*([a-z0-9._+-]+)\s+([^\s`][^`]*)`/gi,
763
+ /<\(\s*([a-z0-9._+-]+)\s+([^\s)][^)]*)\)/gi,
712
764
  ];
713
765
  for (const pattern of patterns) {
714
766
  pattern.lastIndex = 0;
@@ -744,7 +796,7 @@ function detectCommandSubstitutionExfil(command, cwd) {
744
796
  function detectPipelineExfil(command, cwd) {
745
797
  // cat .env | nc … ; base64 .env | curl … ; echo $API_KEY | curl …
746
798
  const findings = [];
747
- const segments = String(command || '').split(/(?<![|])\|(?![|])/);
799
+ const segments = String(command || '').split(/(?<!\|)\|(?!\|)/);
748
800
  if (segments.length < 2) return findings;
749
801
 
750
802
  for (let i = 0; i < segments.length - 1; i += 1) {
@@ -762,8 +814,7 @@ function detectPipelineExfil(command, cwd) {
762
814
  });
763
815
  }
764
816
 
765
- SECRET_ENV_VAR_PATTERN.lastIndex = 0;
766
- if (SECRET_ENV_VAR_PATTERN.test(left) || SECRET_ENV_VAR_PATTERN.test(right)) {
817
+ if (hasSecretEnvVarRef(left) || hasSecretEnvVarRef(right)) {
767
818
  findings.push({
768
819
  id: 'secret_env_exfil',
769
820
  label: 'Secret environment variable',
@@ -775,7 +826,29 @@ function detectPipelineExfil(command, cwd) {
775
826
  return findings;
776
827
  }
777
828
 
778
- function detectScpRsyncExfil(command, cwd) {
829
+ function resolveTransferLocalSide(token) {
830
+ const str = String(token);
831
+ if (str.includes(':') && !str.startsWith('/')) {
832
+ return str.split(':').slice(1).join(':');
833
+ }
834
+ return token;
835
+ }
836
+
837
+ function collectTransferTokenFindings(tokens, verb, findings) {
838
+ for (const token of tokens) {
839
+ if (String(token).startsWith('-')) continue;
840
+ const localSide = resolveTransferLocalSide(token);
841
+ const pathFinding = classifySecretPathToken(localSide) || classifySecretPathToken(token);
842
+ if (!pathFinding) continue;
843
+ findings.push({
844
+ ...pathFinding,
845
+ source: 'transfer_exfil',
846
+ reason: `${pathFinding.label} referenced by ${verb} transfer`,
847
+ });
848
+ }
849
+ }
850
+
851
+ function detectScpRsyncExfil(command) {
779
852
  const findings = [];
780
853
  for (const segment of splitCommandSegments(command)) {
781
854
  const tokens = tokenizeCommand(segment);
@@ -783,20 +856,8 @@ function detectScpRsyncExfil(command, cwd) {
783
856
  let index = 0;
784
857
  while (isShellAssignment(tokens[index])) index += 1;
785
858
  const verb = path.basename(String(tokens[index] || '')).toLowerCase();
786
- if (verb !== 'scp' && verb !== 'rsync' && verb !== 'sftp') continue;
787
- for (const token of tokens.slice(index + 1)) {
788
- if (String(token).startsWith('-')) continue;
789
- // scp local secret → remote OR remote → local (still sensitive move)
790
- const localSide = String(token).includes(':') && !String(token).startsWith('/')
791
- ? String(token).split(':').slice(1).join(':')
792
- : token;
793
- const pathFinding = classifySecretPathToken(localSide) || classifySecretPathToken(token);
794
- if (!pathFinding) continue;
795
- findings.push({
796
- ...pathFinding,
797
- source: 'transfer_exfil',
798
- reason: `${pathFinding.label} referenced by ${verb} transfer`,
799
- });
859
+ if (verb === 'scp' || verb === 'rsync' || verb === 'sftp') {
860
+ collectTransferTokenFindings(tokens.slice(index + 1), verb, findings);
800
861
  }
801
862
  }
802
863
  return findings;
@@ -808,8 +869,7 @@ function detectEnvVarNetworkExfil(command) {
808
869
  // Require a parsed network/transfer verb or /dev/tcp — a URL in docs text alone
809
870
  // must not hard-deny (e.g. printf 'Set $OPENAI_API_KEY then visit https://…').
810
871
  const text = String(command || '');
811
- SECRET_ENV_VAR_PATTERN.lastIndex = 0;
812
- const hasEnvRef = SECRET_ENV_VAR_PATTERN.test(text)
872
+ const hasEnvRef = hasSecretEnvVarRef(text)
813
873
  || /\bprintenv\s+(?:API[_-]?KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|AWS_SECRET_ACCESS_KEY|GITHUB_TOKEN|GH_TOKEN|STRIPE_SECRET_KEY|NPM_TOKEN|ACCESS_TOKEN|CLIENT_SECRET)\b/i.test(text)
814
874
  || /\benv\s+(?:API[_-]?KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|AWS_SECRET_ACCESS_KEY|GITHUB_TOKEN)\b/i.test(text);
815
875
  if (!hasEnvRef) return [];
@@ -835,7 +895,7 @@ function detectRedirectExfil(command, cwd) {
835
895
  if (!hasNetwork) return findings;
836
896
 
837
897
  // stdin redirect from a secret path
838
- const redirectRe = /(?:^|[\s;|&])\d*\s*<\s*([^\s;|&><]+)/g;
898
+ const redirectRe = /(?<=^|[\s;|&0-9])<\s*([^\s;|&><]+)/g;
839
899
  let match = redirectRe.exec(text);
840
900
  while (match) {
841
901
  const pathFinding = classifySecretPathToken(match[1]);
@@ -848,7 +908,6 @@ function detectRedirectExfil(command, cwd) {
848
908
  }
849
909
  match = redirectRe.exec(text);
850
910
  }
851
-
852
911
  // Bash /dev/tcp with secret path anywhere in the same command
853
912
  if (/\/dev\/tcp\//i.test(text)) {
854
913
  const tokens = tokenizeCommand(text.replace(/[<>]/g, ' '));
@@ -945,7 +1004,7 @@ function detectArchivePipeExfil(command, cwd) {
945
1004
  if (!/\|/.test(text) && !segmentHasNetworkExfil(text) && !/https?:\/\//i.test(text)) {
946
1005
  return findings;
947
1006
  }
948
- const segments = text.split(/(?<![|])\|(?![|])/);
1007
+ const segments = text.split(/(?<!\|)\|(?!\|)/);
949
1008
  const left = segments[0] || text;
950
1009
  const archiveVerb = path.basename(String(tokenizeCommand(left)[0] || '')).toLowerCase();
951
1010
  if (!['tar', 'zip', 'gzip', 'pigz', '7z', 'rar'].includes(archiveVerb)) {
@@ -984,7 +1043,7 @@ function detectInterpreterExfil(command, cwd) {
984
1043
  && /(?:-c|-e|--eval)\b/i.test(text);
985
1044
  if (!isInterpreter) return [];
986
1045
 
987
- const touchesSecretPath = /\.env(?:\.[A-Za-z0-9_-]+)?|\.aws\/credentials|\.ssh\/id_|\.netrc|\.npmrc|application_default_credentials/i.test(text);
1046
+ const touchesSecretPath = /\.env(?:\.[a-z0-9_-]+)?|\.aws\/credentials|\.ssh\/id_|\.netrc|\.npmrc|application_default_credentials/i.test(text);
988
1047
  const touchesSecretEnv = /(?:API_KEY|OPENAI_API_KEY|AWS_SECRET|GITHUB_TOKEN|STRIPE_SECRET|os\.environ|process\.env)/i.test(text);
989
1048
  const touchesNetwork = /https?:\/\/|requests\.|urllib|fetch\(|http\.request|httpx\.|aiohttp|socket\.|urlopen/i.test(text);
990
1049
  if (!(touchesSecretPath || touchesSecretEnv) || !touchesNetwork) return [];
@@ -36,7 +36,7 @@ const SELF_GOVERNANCE_PATH_PATTERNS = [
36
36
  /(?:^|\/)thumbgate\.json$/i,
37
37
  ];
38
38
 
39
- const EDIT_LIKE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit']);
39
+ const EDIT_LIKE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
40
40
 
41
41
  /**
42
42
  * Returns the matched governance file path, or null. Accepts both camelCase
@@ -44,7 +44,7 @@ const EDIT_LIKE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit']);
44
44
  */
45
45
  function selfProtectionTarget(toolName, toolInput) {
46
46
  if (!EDIT_LIKE_TOOLS.has(toolName)) return null;
47
- const filePath = String((toolInput && (toolInput.file_path || toolInput.filePath)) || '');
47
+ const filePath = String((toolInput && (toolInput.file_path || toolInput.filePath || toolInput.notebook_path || toolInput.notebookPath || toolInput.path)) || '');
48
48
  if (!filePath) return null;
49
49
  return SELF_GOVERNANCE_PATH_PATTERNS.some((re) => re.test(filePath)) ? filePath : null;
50
50
  }