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
@@ -0,0 +1,232 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+
8
+ const PROOF_WINDOW_DAYS_DEFAULT = 30;
9
+ const MAX_EXAMPLE_CHARS = 160;
10
+
11
+ const CATEGORY_RULES = [
12
+ {
13
+ id: 'force_push',
14
+ label: 'Force push to a protected branch',
15
+ gateIds: ['force-push', 'force_push', 'protected-branch-force-push'],
16
+ pattern: /\bgit\s+push\b[^\n]{0,80}(--force\b|-f\b)/i,
17
+ },
18
+ {
19
+ id: 'secret_in_command',
20
+ label: 'Secret material in a command',
21
+ gateIds: ['secret-exfiltration', 'secret-guard', 'secret_in_command', 'credential-leak'],
22
+ pattern: /(secret|api[_-]?key|token|password|credential|exfiltration)/i,
23
+ },
24
+ {
25
+ id: 'destructive_shell',
26
+ label: 'Destructive shell command',
27
+ gateIds: ['destructive-delete', 'destructive-shell', 'rm-rf', 'hard-floor'],
28
+ pattern: /\brm\s+-[a-z]*r[a-z]*f|\bdrop\s+(database|table)\b|\btruncate\b/i,
29
+ },
30
+ {
31
+ id: 'repeated_mistake',
32
+ label: 'Repeated mistake the agent already corrected',
33
+ gateIds: ['repeated-mistake', 'lesson-repeat', 'recurring-block'],
34
+ pattern: /(repeat(ed)? mistake|already corrected|recurring)/i,
35
+ },
36
+ {
37
+ id: 'privilege_escalation',
38
+ label: 'Privilege escalation or unsafe sudo',
39
+ gateIds: ['privilege-escalation', 'unsafe-sudo'],
40
+ pattern: /\bsudo\b|\bchmod\s+777\b/i,
41
+ },
42
+ ];
43
+
44
+ const NOISE_SOURCE_PATTERN = /(test|cron|diagnostic|fixture)/i;
45
+ const NOISE_PATH_PATTERN = /(\/(?:tmp|var\/folders)\/|thumbgate-test|test-fixtures?|node_modules)/i;
46
+
47
+ function resolveProofPaths(env = process.env) {
48
+ const homeDir = env.HOME || os.homedir() || '/tmp';
49
+ const thumbgateDir = env.THUMBGATE_HOME || path.join(homeDir, '.thumbgate');
50
+ return {
51
+ thumbgateDir,
52
+ auditTrailPath: env.THUMBGATE_AUDIT_TRAIL_PATH || path.join(thumbgateDir, 'audit-trail.jsonl'),
53
+ };
54
+ }
55
+
56
+ function readJsonl(filePath) {
57
+ if (!filePath || !fs.existsSync(filePath)) return [];
58
+ const out = [];
59
+ for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
60
+ const trimmed = line.trim();
61
+ if (!trimmed) continue;
62
+ try {
63
+ out.push(JSON.parse(trimmed));
64
+ } catch {
65
+ // skip malformed line
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function isBlockedDecision(record) {
72
+ const decision = String(record?.decision || '').toLowerCase();
73
+ const mode = String(record?.mode || '').toLowerCase();
74
+ return decision === 'deny' || decision === 'block' || mode === 'block';
75
+ }
76
+
77
+ function extractCommandText(record) {
78
+ const input = record?.toolInput;
79
+ if (!input || typeof input !== 'object') return '';
80
+ return String(input.command || input.cmd || input.input || input.file_path || input.path || '').trim();
81
+ }
82
+
83
+ function classifyCategory(record) {
84
+ const gateId = String(record?.gateId || '').toLowerCase();
85
+ const reason = String(record?.reason || record?.message || '');
86
+ const command = extractCommandText(record);
87
+ const haystack = `${gateId}\n${reason}\n${command}`;
88
+ for (const rule of CATEGORY_RULES) {
89
+ if (rule.gateIds.some((id) => gateId === id || gateId.includes(id))) return rule;
90
+ if (rule.pattern.test(haystack)) return rule;
91
+ }
92
+ return { id: 'other_risky_action', label: 'Other risky action stopped' };
93
+ }
94
+
95
+ function isNoiseRecord(record) {
96
+ const source = String(record?.source || '');
97
+ const sessionId = String(record?.sessionId || '');
98
+ const identity = `${source} ${sessionId}`;
99
+ const command = extractCommandText(record);
100
+ return NOISE_SOURCE_PATTERN.test(identity) || NOISE_PATH_PATTERN.test(command);
101
+ }
102
+
103
+ function anonymizeExample(text) {
104
+ let out = String(text || '').replace(/\s+/g, ' ').trim();
105
+ out = out
106
+ .replace(/\/(?:Users|home)\/[^\s'"]+/gi, '~/<redacted-path>')
107
+ .replace(/\b[\w.-]+\/[\w./-]+/g, '<redacted-path>')
108
+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '<redacted-email>')
109
+ .replace(/\b(?:sk|rk|pk|ghp|gho|github_pat|xox[baprs]|AKIA|ASIA)[_-][A-Za-z0-9_\-]{8,}\b/g, '<redacted-secret>')
110
+ .replace(/\b[A-Z][A-Z0-9_]*(?:PAT|TOKEN|SECRET|PASSWORD|KEY)\b/g, '<redacted-secret>')
111
+ .replace(/\bwith-secrets\b/gi, '<redacted-secret>')
112
+ .replace(/\b(?:api[_-]?key|token|secret|password|passwd|credential|pat)\s*[:=]\s*\S+/gi, '<redacted-secret>');
113
+ if (out.length > MAX_EXAMPLE_CHARS) out = `${out.slice(0, MAX_EXAMPLE_CHARS - 1)}…`;
114
+ return out;
115
+ }
116
+
117
+ function buildProofReport(options = {}) {
118
+ const days = Math.max(1, Math.trunc(Number(options.days) || PROOF_WINDOW_DAYS_DEFAULT));
119
+ const nowMs = options.now ? new Date(options.now).getTime() : Date.now();
120
+ const windowStartMs = nowMs - days * 24 * 60 * 60 * 1000;
121
+ const paths = options.paths || resolveProofPaths(options.env);
122
+ const records = options.records || readJsonl(paths.auditTrailPath);
123
+
124
+ const realByCategory = new Map();
125
+ const excluded = { test: 0, cron: 0, diagnostic: 0, fixture: 0, other: 0 };
126
+ let realBlocked = 0;
127
+ let excludedTotal = 0;
128
+
129
+ for (const record of records) {
130
+ if (!isBlockedDecision(record)) continue;
131
+ const ts = new Date(record.timestamp || 0).getTime();
132
+ if (!Number.isFinite(ts) || ts < windowStartMs || ts > nowMs) continue;
133
+
134
+ if (isNoiseRecord(record)) {
135
+ excludedTotal += 1;
136
+ const haystack = `${record.source || ''} ${record.sessionId || ''} ${record.reason || ''} ${extractCommandText(record)}`.toLowerCase();
137
+ if (haystack.includes('cron')) excluded.cron += 1;
138
+ else if (haystack.includes('diagnostic')) excluded.diagnostic += 1;
139
+ else if (haystack.includes('fixture')) excluded.fixture += 1;
140
+ else if (haystack.includes('test')) excluded.test += 1;
141
+ else excluded.other += 1;
142
+ continue;
143
+ }
144
+
145
+ realBlocked += 1;
146
+ const category = classifyCategory(record);
147
+ const bucket = realByCategory.get(category.id) || {
148
+ id: category.id,
149
+ label: category.label,
150
+ count: 0,
151
+ example: '',
152
+ };
153
+ bucket.count += 1;
154
+ if (!bucket.example) {
155
+ const exampleSource = extractCommandText(record) || String(record.message || record.reason || '');
156
+ bucket.example = anonymizeExample(exampleSource);
157
+ }
158
+ realByCategory.set(category.id, bucket);
159
+ }
160
+
161
+ const categories = [...realByCategory.values()].sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
162
+
163
+ return {
164
+ windowDays: days,
165
+ generatedAt: new Date(nowMs).toISOString(),
166
+ source: 'founder-local-audit-trail',
167
+ realAgentToolCallsBlocked: realBlocked,
168
+ excludedNoise: {
169
+ total: excludedTotal,
170
+ ...excluded,
171
+ },
172
+ categories,
173
+ };
174
+ }
175
+
176
+ function formatProofText(report) {
177
+ const lines = [
178
+ `ThumbGate proof — last ${report.windowDays} days (founder local use, not a customer)`,
179
+ `Real agent tool calls blocked: ${report.realAgentToolCallsBlocked}`,
180
+ `Excluded noise (test/cron/diagnostic/fixture): ${report.excludedNoise.total}`,
181
+ '',
182
+ 'Top categories:',
183
+ ];
184
+ const top = report.categories.slice(0, 5);
185
+ if (!top.length) {
186
+ lines.push(' (none in window)');
187
+ } else {
188
+ for (const cat of top) {
189
+ lines.push(` - ${cat.label}: ${cat.count}`);
190
+ if (cat.example) lines.push(` example: ${cat.example}`);
191
+ }
192
+ }
193
+ return lines.join('\n');
194
+ }
195
+
196
+ function runProofCli(argv = process.argv.slice(3), options = {}) {
197
+ const args = {};
198
+ for (let i = 0; i < argv.length; i += 1) {
199
+ const arg = argv[i];
200
+ if (!arg.startsWith('--')) continue;
201
+ const [key, ...rest] = arg.slice(2).split('=');
202
+ if (rest.length) args[key] = rest.join('=');
203
+ else if (argv[i + 1] && !argv[i + 1].startsWith('--')) {
204
+ args[key] = argv[i + 1];
205
+ i += 1;
206
+ } else args[key] = true;
207
+ }
208
+ const report = buildProofReport({
209
+ days: args.days,
210
+ env: options.env,
211
+ paths: options.paths,
212
+ records: options.records,
213
+ now: options.now,
214
+ });
215
+ const out = args.json ? JSON.stringify(report, null, 2) : formatProofText(report);
216
+ if (!options.silent) process.stdout.write(`${out}\n`);
217
+ return report;
218
+ }
219
+
220
+ module.exports = {
221
+ CATEGORY_RULES,
222
+ anonymizeExample,
223
+ buildProofReport,
224
+ formatProofText,
225
+ isNoiseRecord,
226
+ resolveProofPaths,
227
+ runProofCli,
228
+ };
229
+
230
+ if (require.main === module) {
231
+ runProofCli(process.argv.slice(2));
232
+ }
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { normalizeCommandValue } = require('./harness-tool-names');
4
5
  const DEFAULT_SOFT_TOKEN_LIMIT = 8000;
5
6
  const DEFAULT_MAX_PARALLEL_BRANCHES = 4;
6
7
 
@@ -215,13 +216,20 @@ function collectAffectedFiles(toolInput = {}, fallback = {}) {
215
216
  return uniqueStrings(files);
216
217
  }
217
218
 
219
+ function coerceCommandCandidate(candidate) {
220
+ if (Array.isArray(candidate)) {
221
+ return normalizeCommandValue(candidate);
222
+ }
223
+ return candidate;
224
+ }
225
+
218
226
  function inferCommand(toolName, toolInput = {}, fallback = {}) {
219
227
  return firstString(
220
- toolInput.command,
221
- toolInput.cmd,
222
- toolInput.shell,
223
- fallback.command,
224
- fallback.cmd
228
+ coerceCommandCandidate(toolInput.command),
229
+ coerceCommandCandidate(toolInput.cmd),
230
+ coerceCommandCandidate(toolInput.shell),
231
+ coerceCommandCandidate(fallback.command),
232
+ coerceCommandCandidate(fallback.cmd)
225
233
  );
226
234
  }
227
235
 
@@ -232,7 +240,7 @@ function inferActionType(toolName, toolInput = {}, fallback = {}) {
232
240
  if (fallback.method === 'prompts/get') return 'prompt.get';
233
241
  const normalizedTool = String(toolName || '').trim();
234
242
  const lowerTool = normalizedTool.toLowerCase();
235
- if (normalizedTool === 'Bash' || containsAny(lowerTool, ['bash', 'shell', 'terminal', 'exec', 'run_command'])) {
243
+ if (normalizedTool === 'Bash' || containsAny(lowerTool, ['bash', 'shell', 'terminal', 'exec', 'run_command', 'powershell', 'pwsh'])) {
236
244
  return 'shell.exec';
237
245
  }
238
246
  if (EDIT_TOOL_NAMES.has(normalizedTool) || containsAny(lowerTool, ['edit', 'write', 'patch', 'file'])) {
@@ -0,0 +1,413 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * QwenWork Enterprise Premium newsletter (2026-10-28) — FORMAT steal.
6
+ *
7
+ * One org policy group decides at the action:
8
+ * model catalog, usage limit, marketplace installs (skill, connector, suite),
9
+ * trusted devices, trusted networks, sensitive words, and IM channels.
10
+ * Audit is admin, user, or ai, and it is exportable.
11
+ * Training use stays false unless the action is BYOK and the policy allows it.
12
+ *
13
+ * Does not buy seats, call Alibaba Cloud, install DingTalk, WeCom, or Feishu,
14
+ * or ship a white-label app.
15
+ */
16
+
17
+ const fs = require('node:fs');
18
+ const path = require('node:path');
19
+
20
+ const SOURCE = 'Alibaba Cloud newsletter, QwenWork Enterprise Premium, 2026-10-28';
21
+
22
+ const ACTION_POINTS = Object.freeze([
23
+ 'model.invoke',
24
+ 'skill.install',
25
+ 'connector.install',
26
+ 'suite.install',
27
+ 'device.join',
28
+ 'usage.record',
29
+ 'im.send',
30
+ 'brand.apply',
31
+ ]);
32
+
33
+ const IDENTITY_SLOTS = Object.freeze(['entra', 'ldap', 'scim', 'saml', 'oidc']);
34
+
35
+ const REFUSED_DIRECTORIES = Object.freeze(['dingtalk', 'wecom', 'feishu']);
36
+
37
+ const AUDIT_CLASS = Object.freeze({
38
+ 'skill.install': 'admin',
39
+ 'connector.install': 'admin',
40
+ 'suite.install': 'admin',
41
+ 'brand.apply': 'admin',
42
+ 'device.join': 'user',
43
+ 'usage.record': 'user',
44
+ 'model.invoke': 'ai',
45
+ 'im.send': 'ai',
46
+ });
47
+
48
+ const REFUSES = Object.freeze([
49
+ 'Buy Enterprise Premium seats',
50
+ 'Buy Enterprise Premium credits',
51
+ 'Call Alibaba Cloud',
52
+ 'Install DingTalk, WeCom, or Feishu',
53
+ 'Treat their seat price as a ThumbGate price',
54
+ 'Ship a white-label standalone app',
55
+ ]);
56
+
57
+ const RAIL_MAP = Object.freeze([
58
+ {
59
+ qwenwork: 'Policy at the action: trusted networks, trusted devices, sensitive words, IM channels',
60
+ thumbgate: 'PreToolUse denies the action before it runs. Empty allowlists deny.',
61
+ },
62
+ {
63
+ qwenwork: 'Dedicated org access, not a second Alibaba product',
64
+ thumbgate: 'policy.org is required. No new vendor account.',
65
+ },
66
+ {
67
+ qwenwork: 'Directory and SSO named as Entra, LDAP/AD, SCIM, SAML, and OIDC',
68
+ thumbgate: 'directory slot is entra, ldap, scim, saml, or oidc',
69
+ },
70
+ {
71
+ qwenwork: 'One policy group covers the model catalog, usage limits, and marketplace installs',
72
+ thumbgate: 'models, usageLimit, skills, connectors, and suites are allowlists',
73
+ },
74
+ {
75
+ qwenwork: 'Admin, user, and AI interaction logs, exportable, training off except BYOK',
76
+ thumbgate: 'audit.class is admin, user, or ai. exportable is true. trainingUse requires BYOK plus allowByokTraining.',
77
+ },
78
+ {
79
+ qwenwork: 'Custom branding is hosted configuration',
80
+ thumbgate: 'brand.apply records a branding label. clone and packageApp deny.',
81
+ },
82
+ ]);
83
+
84
+ function listed(policy, key) {
85
+ const value = policy && policy[key];
86
+ return Array.isArray(value) ? value.map((item) => String(item)) : [];
87
+ }
88
+
89
+ function hasWord(text, words) {
90
+ const hay = String(text || '').toLowerCase();
91
+ for (const word of words) {
92
+ const needle = String(word || '').trim().toLowerCase();
93
+ if (needle && hay.includes(needle)) return needle;
94
+ }
95
+ return '';
96
+ }
97
+
98
+ function numberOrZero(value) {
99
+ if (value == null || value === '') return 0;
100
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return null;
101
+ return value;
102
+ }
103
+
104
+ function trainingUse(policy, action, allowed) {
105
+ return allowed === true
106
+ && action
107
+ && action.byok === true
108
+ && policy
109
+ && policy.allowByokTraining === true;
110
+ }
111
+
112
+ function auditOf(point, decision, reason, policy, action, allowed) {
113
+ return {
114
+ class: AUDIT_CLASS[point] || 'admin',
115
+ exportable: true,
116
+ trainingUse: trainingUse(policy, action, allowed),
117
+ point: point || '',
118
+ decision,
119
+ reason,
120
+ };
121
+ }
122
+
123
+ function deny(point, reason, policy, action) {
124
+ return {
125
+ decision: 'deny',
126
+ reason,
127
+ audit: auditOf(point, 'deny', reason, policy || {}, action || {}, false),
128
+ };
129
+ }
130
+
131
+ function allow(point, policy, action) {
132
+ return {
133
+ decision: 'allow',
134
+ reason: '',
135
+ audit: auditOf(point, 'allow', '', policy, action, true),
136
+ };
137
+ }
138
+
139
+ function deviceGate(policy, action) {
140
+ const trusted = listed(policy, 'trustedDevices');
141
+ const device = String(action.device || '');
142
+ if (trusted.length === 0 || !device || !trusted.includes(device)) return 'untrusted-device';
143
+ return '';
144
+ }
145
+
146
+ function networkGate(policy, action) {
147
+ const trusted = listed(policy, 'trustedNetworks');
148
+ const network = String(action.network || '');
149
+ if (trusted.length === 0 || !network || !trusted.includes(network)) return 'untrusted-network';
150
+ return '';
151
+ }
152
+
153
+ function overLimit(policy, action, recording) {
154
+ const limit = policy.usageLimit;
155
+ if (recording) {
156
+ if (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0) return true;
157
+ const used = numberOrZero(action.used);
158
+ const units = action.units;
159
+ if (used == null) return true;
160
+ if (typeof units !== 'number' || !Number.isFinite(units) || units < 0) return true;
161
+ return used + units > limit;
162
+ }
163
+ if (typeof limit !== 'number' || !Number.isFinite(limit)) return false;
164
+ const used = numberOrZero(action.used);
165
+ if (used == null) return true;
166
+ return used >= limit;
167
+ }
168
+
169
+ function membership(policy, action, point, field, listKey, reason) {
170
+ const id = String(action[field] || '');
171
+ if (!id || !listed(policy, listKey).includes(id)) return deny(point, reason, policy, action);
172
+ const deviceReason = deviceGate(policy, action);
173
+ if (deviceReason) return deny(point, deviceReason, policy, action);
174
+ return allow(point, policy, action);
175
+ }
176
+
177
+ function directoryGate(policy, point, action) {
178
+ if (policy.directory == null || policy.directory === '') return '';
179
+ const directory = String(policy.directory).trim().toLowerCase();
180
+ if (REFUSED_DIRECTORIES.includes(directory)) return 'refused-directory';
181
+ if (!IDENTITY_SLOTS.includes(directory)) return 'unknown-directory';
182
+ return '';
183
+ }
184
+
185
+ function evaluatePolicyGroup(policy, action) {
186
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) {
187
+ return deny(action && action.point, 'missing-policy', {}, action);
188
+ }
189
+ if (!action || typeof action !== 'object' || Array.isArray(action)) {
190
+ return deny('', 'missing-action', policy, {});
191
+ }
192
+ const point = String(action.point || '');
193
+ if (!ACTION_POINTS.includes(point)) return deny(point, 'unknown-action', policy, action);
194
+ if (!String(policy.org || '').trim()) return deny(point, 'missing-org', policy, action);
195
+ const directoryReason = directoryGate(policy, point, action);
196
+ if (directoryReason) return deny(point, directoryReason, policy, action);
197
+
198
+ const sensitive = hasWord(action.text, listed(policy, 'sensitiveWords'));
199
+ if (sensitive && (point === 'model.invoke' || point === 'im.send')) {
200
+ return deny(point, 'sensitive-word', policy, action);
201
+ }
202
+
203
+ if (point === 'model.invoke') {
204
+ const model = String(action.model || '');
205
+ if (!model || !listed(policy, 'models').includes(model)) {
206
+ return deny(point, 'unapproved-model', policy, action);
207
+ }
208
+ const deviceReason = deviceGate(policy, action);
209
+ if (deviceReason) return deny(point, deviceReason, policy, action);
210
+ const networkReason = networkGate(policy, action);
211
+ if (networkReason) return deny(point, networkReason, policy, action);
212
+ if (overLimit(policy, action, false)) return deny(point, 'usage-limit', policy, action);
213
+ return allow(point, policy, action);
214
+ }
215
+ if (point === 'skill.install') {
216
+ return membership(policy, action, point, 'skill', 'skills', 'unapproved-skill');
217
+ }
218
+ if (point === 'connector.install') {
219
+ return membership(policy, action, point, 'connector', 'connectors', 'unapproved-connector');
220
+ }
221
+ if (point === 'suite.install') {
222
+ return membership(policy, action, point, 'suite', 'suites', 'unapproved-suite');
223
+ }
224
+ if (point === 'device.join') {
225
+ const device = String(action.device || '');
226
+ if (!device || !listed(policy, 'trustedDevices').includes(device)) {
227
+ return deny(point, 'untrusted-device', policy, action);
228
+ }
229
+ return allow(point, policy, action);
230
+ }
231
+ if (point === 'usage.record') {
232
+ if (overLimit(policy, action, true)) return deny(point, 'usage-limit', policy, action);
233
+ return allow(point, policy, action);
234
+ }
235
+ if (point === 'im.send') {
236
+ const channel = String(action.channel || '');
237
+ if (!channel || !listed(policy, 'imChannels').includes(channel)) {
238
+ return deny(point, 'unknown-im-channel', policy, action);
239
+ }
240
+ const deviceReason = deviceGate(policy, action);
241
+ if (deviceReason) return deny(point, deviceReason, policy, action);
242
+ const networkReason = networkGate(policy, action);
243
+ if (networkReason) return deny(point, networkReason, policy, action);
244
+ return allow(point, policy, action);
245
+ }
246
+ if (action.clone === true || action.packageApp === true) {
247
+ return deny(point, 'white-label-clone', policy, action);
248
+ }
249
+ if (!String(policy.branding || '').trim()) return deny(point, 'missing-branding', policy, action);
250
+ return allow(point, policy, action);
251
+ }
252
+
253
+ function triggeredRefusals(text) {
254
+ const hits = [];
255
+ if (/\bbuy\b/i.test(text) && /\b(seat|seats|credits?\s+pack)\b/i.test(text)) {
256
+ hits.push('Buy Enterprise Premium seats');
257
+ }
258
+ if (/\balibaba\s*cloud\b|\balibabacloud\b/i.test(text) && /\b(call|open|sign\s*in|account|api|fetch|request)\b/i.test(text)) {
259
+ hits.push('Call Alibaba Cloud');
260
+ }
261
+ if (/\b(dingtalk|wecom|feishu)\b/i.test(text) && /\b(install|adopt|connect|sync)\b/i.test(text)) {
262
+ hits.push('Install DingTalk, WeCom, or Feishu');
263
+ }
264
+ if (/\b(seat price|their price|credits pack)\b/i.test(text) && /\bthumbgate\b/i.test(text)) {
265
+ hits.push('Treat their seat price as a ThumbGate price');
266
+ }
267
+ if (/\b(white-?label|standalone app)\b/i.test(text) && /\b(clone|package|ship)\b/i.test(text)) {
268
+ hits.push('Ship a white-label standalone app');
269
+ }
270
+ return [...new Set(hits)];
271
+ }
272
+
273
+ function parseJson(value, label, findings) {
274
+ if (value == null || value === '') return null;
275
+ try {
276
+ return JSON.parse(value);
277
+ } catch {
278
+ findings.push({
279
+ gateId: 'policy-group',
280
+ severity: 'fail',
281
+ message: `${label} is not JSON`,
282
+ });
283
+ return null;
284
+ }
285
+ }
286
+
287
+ function readJsonFile(filePath, label, findings) {
288
+ if (!filePath) return null;
289
+ try {
290
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
291
+ } catch {
292
+ findings.push({
293
+ gateId: 'policy-group',
294
+ severity: 'fail',
295
+ message: `${label} is not readable JSON`,
296
+ });
297
+ return null;
298
+ }
299
+ }
300
+
301
+ function buildQwenWorkPolicyGroupReport(options = {}) {
302
+ const mapOnly = options.mapOnly === true || options.mapOnly === 'true';
303
+ const findings = [];
304
+ const text = [options.claim, options.command, options.text].filter(Boolean).join('\n');
305
+ if (!mapOnly && text) {
306
+ for (const hit of triggeredRefusals(text)) {
307
+ findings.push({ gateId: 'qwenwork-refuse', severity: 'fail', message: hit });
308
+ }
309
+ }
310
+
311
+ let evaluation = null;
312
+ if (!mapOnly) {
313
+ const policy = options.policy
314
+ || parseJson(options.policyJson, 'policy', findings)
315
+ || readJsonFile(options.policyPath, 'policy', findings);
316
+ const action = options.action
317
+ || parseJson(options.actionJson, 'action', findings)
318
+ || readJsonFile(options.actionPath, 'action', findings);
319
+ if (policy || action) {
320
+ evaluation = evaluatePolicyGroup(policy, action);
321
+ if (evaluation.decision !== 'allow') {
322
+ findings.push({
323
+ gateId: 'policy-group',
324
+ severity: 'fail',
325
+ message: evaluation.reason,
326
+ });
327
+ }
328
+ }
329
+ }
330
+
331
+ const failCount = findings.filter((item) => item.severity === 'fail').length;
332
+ return {
333
+ name: 'thumbgate-qwenwork-policy-group',
334
+ ok: failCount === 0,
335
+ status: failCount ? 'fail' : 'ready',
336
+ source: SOURCE,
337
+ refuses: REFUSES,
338
+ actionPoints: ACTION_POINTS,
339
+ identitySlots: IDENTITY_SLOTS,
340
+ map: RAIL_MAP,
341
+ evaluation,
342
+ findings,
343
+ summary: { findingCount: findings.length, failCount },
344
+ exampleCommand: 'npx thumbgate qwenwork-policy-group --json --map-only',
345
+ disclaimer: 'FORMAT steal from the 2026-10-28 QwenWork Enterprise Premium note. Not affiliated. Does not buy seats, call Alibaba Cloud, or install DingTalk, WeCom, or Feishu.',
346
+ };
347
+ }
348
+
349
+ function formatQwenWorkPolicyGroupReport(report) {
350
+ const lines = [
351
+ 'QwenWork Policy Group',
352
+ `Status : ${report.status}`,
353
+ `Source : ${report.source}`,
354
+ `Findings: ${report.summary.findingCount} (fail=${report.summary.failCount})`,
355
+ '',
356
+ 'Rail map:',
357
+ ];
358
+ for (const row of report.map) {
359
+ lines.push(`- ${row.qwenwork}`);
360
+ lines.push(` ThumbGate: ${row.thumbgate}`);
361
+ }
362
+ if (report.evaluation) {
363
+ lines.push('', `Decision: ${report.evaluation.decision} ${report.evaluation.reason}`.trim());
364
+ lines.push(`Audit: ${report.evaluation.audit.class} exportable=${report.evaluation.audit.exportable} trainingUse=${report.evaluation.audit.trainingUse}`);
365
+ }
366
+ for (const finding of report.findings) {
367
+ lines.push(`- [${finding.severity}] ${finding.gateId}: ${finding.message}`);
368
+ }
369
+ lines.push('', report.disclaimer, '');
370
+ return `${lines.join('\n')}\n`;
371
+ }
372
+
373
+ function main() {
374
+ const args = {};
375
+ const argv = process.argv.slice(2);
376
+ for (let index = 0; index < argv.length; index += 1) {
377
+ const arg = argv[index];
378
+ if (!arg.startsWith('--')) continue;
379
+ const [rawKey, inline] = arg.slice(2).split(/=(.*)/s, 2);
380
+ const key = rawKey.replaceAll(/-([a-z])/g, (_, letter) => letter.toUpperCase());
381
+ if (inline !== undefined) args[key] = inline;
382
+ else if (argv[index + 1] && !argv[index + 1].startsWith('--')) {
383
+ args[key] = argv[index + 1];
384
+ index += 1;
385
+ } else args[key] = true;
386
+ }
387
+ const report = buildQwenWorkPolicyGroupReport({
388
+ mapOnly: args.mapOnly === true,
389
+ claim: args.claim || '',
390
+ policyJson: args.policyJson || '',
391
+ actionJson: args.actionJson || '',
392
+ policyPath: args.policy || '',
393
+ actionPath: args.action || '',
394
+ });
395
+ if (args.json === true) console.log(JSON.stringify(report, null, 2));
396
+ else process.stdout.write(formatQwenWorkPolicyGroupReport(report));
397
+ if (report.status === 'fail') process.exitCode = 1;
398
+ }
399
+
400
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
401
+ main();
402
+ }
403
+
404
+ module.exports = {
405
+ ACTION_POINTS,
406
+ IDENTITY_SLOTS,
407
+ RAIL_MAP,
408
+ REFUSES,
409
+ buildQwenWorkPolicyGroupReport,
410
+ evaluatePolicyGroup,
411
+ formatQwenWorkPolicyGroupReport,
412
+ triggeredRefusals,
413
+ };