thumbgate 1.37.3 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/.agents/skills/aws-strands-harness-not-clone/SKILL.md +53 -0
  2. package/.agents/skills/bolt-forge-opt-in-not-clone/SKILL.md +72 -0
  3. package/.agents/skills/decisive-step-evaluator/SKILL.md +47 -0
  4. package/.agents/skills/fiddler-control-plane-honesty/SKILL.md +61 -0
  5. package/.agents/skills/halo-trace-optimize-not-clone/SKILL.md +60 -0
  6. package/.agents/skills/harness-evolution-ceiling/SKILL.md +52 -0
  7. package/.agents/skills/infoq-architect-honesty-not-clone/SKILL.md +37 -0
  8. package/.agents/skills/meko-datapack-honesty-not-clone/SKILL.md +45 -0
  9. package/.agents/skills/mintlify-knowledge-honesty-not-clone/SKILL.md +49 -0
  10. package/.agents/skills/model-distress-governance/SKILL.md +56 -0
  11. package/.agents/skills/omp-coordination-honesty-not-clone/SKILL.md +94 -0
  12. package/.agents/skills/saas-moat-honesty-not-clone/SKILL.md +22 -0
  13. package/.agents/skills/salt-code-policy-honesty-not-clone/SKILL.md +76 -0
  14. package/.agents/skills/siren-mcp-governance/SKILL.md +50 -0
  15. package/.agents/skills/vs-coverage-gap-not-clone/SKILL.md +69 -0
  16. package/.agents/skills/wisdom-context-artifact-not-clone/SKILL.md +67 -0
  17. package/.claude-plugin/plugin.json +1 -1
  18. package/.well-known/mcp/server-card.json +1 -1
  19. package/adapters/claude/.mcp.json +2 -2
  20. package/adapters/forge/forge.yaml +3 -3
  21. package/adapters/future-agi/.mcp.json +1 -1
  22. package/adapters/future-agi/config.toml +1 -1
  23. package/adapters/future-agi/opencode.json +1 -1
  24. package/adapters/herdr/herdr-plugin.toml +2 -2
  25. package/adapters/hotdata/hotdata-vector-store.js +575 -0
  26. package/adapters/mcp/server-stdio.js +1 -1
  27. package/adapters/opencode/opencode.json +1 -1
  28. package/adapters/strands/STRANDS.md +107 -0
  29. package/adapters/strands/strands-box-diode.js +344 -0
  30. package/adapters/strands/strands-decider-adapter.js +445 -0
  31. package/adapters/strands/strands-middleware.js +192 -0
  32. package/adapters/tailscale/.mcp.json +15 -0
  33. package/adapters/tailscale/TAILSCALE.md +117 -0
  34. package/adapters/tailscale/config.toml +16 -0
  35. package/bin/cli.js +602 -21
  36. package/config/gate-templates.json +109 -0
  37. package/config/gates/default.json +13 -0
  38. package/config/schemas/task-outcome-receipt.schema.json +12 -0
  39. package/package.json +150 -21
  40. package/public/blog/2026-09-28-pretool-secret-deny.html +83 -0
  41. package/public/blog/2026-10-01-aws-strands-harness-token-firewall.html +77 -0
  42. package/public/blog/2026-10-01-model-distress-relief-seeking-firewall.html +71 -0
  43. package/public/blog/2026-10-02-salt-code-honest-steal-40-guardrails.html +106 -0
  44. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +119 -0
  45. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +141 -0
  46. package/public/connectors.html +329 -0
  47. package/public/enterprise-governance.html +311 -0
  48. package/public/gaming-playbook.html +732 -0
  49. package/public/index.html +77 -51
  50. package/public/install.html +7 -7
  51. package/public/learn.html +14 -0
  52. package/public/numbers.html +2 -2
  53. package/public/onboarding.html +794 -0
  54. package/public/operator-framework.html +385 -0
  55. package/public/pricing.html +14 -10
  56. package/scripts/activesaddler-curriculum-doctor.js +357 -0
  57. package/scripts/agent-context-artifact.js +325 -0
  58. package/scripts/agent-egress-policy.js +2 -2
  59. package/scripts/agent-operations-planner.js +1 -1
  60. package/scripts/agent-outcome-eval.js +1 -1
  61. package/scripts/agent-reliability-client.js +148 -0
  62. package/scripts/apple-minions-idle-compute-steal.js +428 -0
  63. package/scripts/autoresearch-runner.js +20 -1
  64. package/scripts/billing.js +0 -1
  65. package/scripts/cli-demo.js +505 -1
  66. package/scripts/cli-schema.js +36 -0
  67. package/scripts/colab-compute-honesty.js +93 -0
  68. package/scripts/corporate-email-isolation-diode.js +299 -0
  69. package/scripts/coverage-gap.js +396 -0
  70. package/scripts/dashboard-chat.js +3 -3
  71. package/scripts/dashboard.js +2 -2
  72. package/scripts/decisive-step-doctor.js +256 -0
  73. package/scripts/decisive-step-evaluator.js +390 -0
  74. package/scripts/entitlement.js +18 -7
  75. package/scripts/experiment-tracker.js +5 -3
  76. package/scripts/feedback-loop.js +26 -3
  77. package/scripts/fiddler-control-plane-honesty.js +303 -0
  78. package/scripts/financial-control-plane.js +10 -2
  79. package/scripts/gates-engine.js +3 -1
  80. package/scripts/github-license-compliance-diode.js +378 -0
  81. package/scripts/halo-trace-optimizer.js +631 -0
  82. package/scripts/harness-ceiling-doctor.js +326 -0
  83. package/scripts/hf-papers.js +1 -1
  84. package/scripts/human-escalation.js +7 -1
  85. package/scripts/hybrid-feedback-context.js +53 -7
  86. package/scripts/infoq-architect-honesty.js +362 -0
  87. package/scripts/lesson-graph.js +785 -0
  88. package/scripts/lesson-inference.js +1 -1
  89. package/scripts/lesson-retrieval.js +26 -18
  90. package/scripts/license.js +122 -21
  91. package/scripts/llm-behavior-monitor.js +1 -1
  92. package/scripts/llm-obs-honesty.js +52 -0
  93. package/scripts/local-model-profile.js +11 -7
  94. package/scripts/mailer/resend-mailer.js +6 -3
  95. package/scripts/mcp-transport-strategy.js +1 -1
  96. package/scripts/meko-datapack-honesty.js +414 -0
  97. package/scripts/migrate-lesson-graph.js +442 -0
  98. package/scripts/mintlify-knowledge-honesty.js +647 -0
  99. package/scripts/model-distress-detector.js +207 -0
  100. package/scripts/model-distress-doctor.js +368 -0
  101. package/scripts/multi-harness-invariants.js +305 -0
  102. package/scripts/omp-coordination-honesty.js +488 -0
  103. package/scripts/pro-local-dashboard.js +20 -3
  104. package/scripts/prompt-eval.js +1 -1
  105. package/scripts/prove-herdr-adapter.js +367 -3
  106. package/scripts/rag-embedding-identity.js +1 -1
  107. package/scripts/rrsi-regularizer.js +531 -0
  108. package/scripts/saas-moat-honesty.js +443 -0
  109. package/scripts/salt-code-policy-honesty.js +1204 -0
  110. package/scripts/secret-redaction.js +58 -0
  111. package/scripts/session-export-gate.js +368 -0
  112. package/scripts/siren-mcp-governance.js +539 -0
  113. package/scripts/strands-box-doctor.js +130 -0
  114. package/scripts/strands-harness-doctor.js +390 -0
  115. package/scripts/stripe-revenue-catalog-audit.js +12 -0
  116. package/scripts/stripe-revenue-catalog.js +40 -0
  117. package/scripts/switchyard-router.js +153 -0
  118. package/scripts/tailscale-p2p-doctor.js +252 -0
  119. package/scripts/task-outcomes.js +148 -3
  120. package/scripts/thumbgate-board-loop.js +4 -2
  121. package/scripts/thumbgate-daily-discoveries-publish.js +86 -38
  122. package/scripts/triage-savings-calculator.js +181 -0
  123. package/scripts/vector-store.js +41 -2
  124. package/scripts/vulnerability-pre-action-diode.js +319 -0
  125. package/scripts/windbg-evidence-diagnostics.js +241 -0
  126. package/scripts/workflow-intake-queue.js +1 -1
  127. package/scripts/workspace-agent-routines.js +534 -6
  128. package/scripts/workspace-evolver.js +143 -13
  129. package/server.json +2 -2
  130. package/skills/aws-strands-harness-not-clone/SKILL.md +53 -0
  131. package/skills/siren-mcp-governance/SKILL.md +50 -0
  132. package/src/api/server.js +191 -5
  133. package/src/mcp-writeguard.js +1 -1
  134. package/src/session-interactivity.js +284 -0
@@ -0,0 +1,445 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Strands Decider Adapter — AWS Strands Labs & Strands Decider Format Steal
5
+ *
6
+ * Implements ultra-fast, deterministic pre-action tool decision routing:
7
+ * - Sub-25ms CPU-local execution budget
8
+ * - Constrained categorical decision space: [ALLOW, REVIEW, BLOCK, ESCALATE]
9
+ * - Context-aware security diodes & side-effect analysis
10
+ * - Idempotent decision receipts
11
+ */
12
+
13
+ const { performance } = require('node:perf_hooks');
14
+
15
+ const DECISION_ALLOW = 'ALLOW';
16
+ const DECISION_REVIEW = 'REVIEW';
17
+ const DECISION_BLOCK = 'BLOCK';
18
+ const DECISION_ESCALATE = 'ESCALATE';
19
+
20
+ const INTERVENTION_PROCEED = 'Proceed';
21
+ const INTERVENTION_DENY = 'Deny';
22
+ const INTERVENTION_CONFIRM = 'Confirm';
23
+ const INTERVENTION_GUIDE = 'Guide';
24
+
25
+ const ALLOWED_DECISIONS = new Set([
26
+ DECISION_ALLOW,
27
+ DECISION_REVIEW,
28
+ DECISION_BLOCK,
29
+ DECISION_ESCALATE
30
+ ]);
31
+
32
+ const ALLOWED_INTERVENTIONS = new Set([
33
+ INTERVENTION_PROCEED,
34
+ INTERVENTION_DENY,
35
+ INTERVENTION_CONFIRM,
36
+ INTERVENTION_GUIDE,
37
+ ]);
38
+
39
+ const SOURCE_URL = 'https://strandsagents.com/blog/introducing-strands-decider/';
40
+ const GATE_ID = 'strands-decider-intervention-diode';
41
+
42
+ const RAIL_MAP = Object.freeze([
43
+ {
44
+ strandsDeciderConcept: 'Pointer head (~1M params) over Qwen3.5-2B + rank-16 LoRA torso; LM head removed (no freeform text generation)',
45
+ thumbgateRail: 'scoreChoiceQuestion (deterministic option-position scoring + reliability confidence; canGenerateFreeformText=false)',
46
+ },
47
+ {
48
+ strandsDeciderConcept: 'Parallel Decider.noul questions (args_grounded + premature) over one conversation/tool state before tool execution',
49
+ thumbgateRail: 'evaluateToolGroundednessAndPrematurity (detects guessed/invented tool arguments not grounded in user messages)',
50
+ },
51
+ {
52
+ strandsDeciderConcept: 'InterventionHandler.before_tool_call returning Proceed, Deny, Confirm, or Guide (hands turn back with feedback)',
53
+ thumbgateRail: 'beforeToolCallIntervention (maps ungrounded args -> Guide with clarification prompt; destructive -> Deny; high-risk -> Confirm)',
54
+ },
55
+ {
56
+ strandsDeciderConcept: 'JevBench accuracy + Brier score calibration and linear task-token latency (115ms RTX3090 / 153ms M3 MacBook)',
57
+ thumbgateRail: 'computeBrierScore + estimateDeciderLatencyMs (<0.5ms deterministic local CPU diode; 0 pip/HF weight installs)',
58
+ },
59
+ ]);
60
+ const CRITICAL_BLOCK_PATTERNS = [
61
+ /git\s+push\s+.*(?:--force|-f).*main/i,
62
+ /gh\s+pr\s+merge.*--admin/i,
63
+ /gh\s+pr\s+review.*--approve/i,
64
+ /rm\s+-rf\s+\/(?:\s|$|\*)/i,
65
+ /chmod\s+-R\s+777\s+\//i,
66
+ /dd\s+if=\/dev\/zero/i
67
+ ];
68
+
69
+ const HIGH_RISK_REVIEW_PATTERNS = [
70
+ /git\s+clean\s+-[a-zA-Z]*f/i,
71
+ /git\s+reset\s+--hard/i,
72
+ /git\s+checkout\s+-f/i,
73
+ /npm\s+publish/i,
74
+ /pkill\s+-9/i
75
+ ];
76
+
77
+ const READ_ONLY_TOOLS = new Set([
78
+ 'view_file',
79
+ 'read_url_content',
80
+ 'search_web',
81
+ 'list_resources',
82
+ 'read_resource'
83
+ ]);
84
+
85
+ /**
86
+ * Evaluates a tool call payload through the Strands Decider routing matrix.
87
+ *
88
+ * @param {Object} invocation - The tool invocation descriptor
89
+ * @param {string} invocation.toolName - Name of the tool
90
+ * @param {Object} invocation.args - Arguments passed to the tool
91
+ * @param {Object} [invocation.context] - Session or caller context
92
+ * @returns {Object} Structured decision receipt
93
+ */
94
+ function decide(invocation = {}) {
95
+ const start = performance.now();
96
+ const toolName = String(invocation.toolName || '').trim();
97
+ const args = invocation.args || {};
98
+ const command = String(args.CommandLine || args.command || '').trim();
99
+
100
+ // 1. Read-only tools without side effects -> Instant ALLOW (<1ms)
101
+ if (READ_ONLY_TOOLS.has(toolName)) {
102
+ const elapsed = performance.now() - start;
103
+ return {
104
+ decision: DECISION_ALLOW,
105
+ reason: 'SAFE_READ_ONLY_TOOL',
106
+ toolName,
107
+ confidence: 1.0,
108
+ latencyMs: Number(elapsed.toFixed(3)),
109
+ budgetCompliant: elapsed < 25.0
110
+ };
111
+ }
112
+
113
+ // 2. Command analysis for Bash / shell executions
114
+ if (command) {
115
+ for (const pattern of CRITICAL_BLOCK_PATTERNS) {
116
+ if (pattern.test(command)) {
117
+ const elapsed = performance.now() - start;
118
+ return {
119
+ decision: DECISION_BLOCK,
120
+ reason: 'CRITICAL_SECURITY_INTERDICTION',
121
+ pattern: pattern.source,
122
+ command,
123
+ confidence: 1.0,
124
+ latencyMs: Number(elapsed.toFixed(3)),
125
+ budgetCompliant: elapsed < 25.0
126
+ };
127
+ }
128
+ }
129
+
130
+ for (const pattern of HIGH_RISK_REVIEW_PATTERNS) {
131
+ if (pattern.test(command)) {
132
+ const elapsed = performance.now() - start;
133
+ return {
134
+ decision: DECISION_REVIEW,
135
+ reason: 'HIGH_RISK_MUTATING_ACTION',
136
+ pattern: pattern.source,
137
+ command,
138
+ confidence: 0.95,
139
+ latencyMs: Number(elapsed.toFixed(3)),
140
+ budgetCompliant: elapsed < 25.0
141
+ };
142
+ }
143
+ }
144
+ }
145
+
146
+ // 3. Sensitive file modifications
147
+ const targetFile = String(args.TargetFile || args.path || '').trim();
148
+ if (targetFile) {
149
+ const sensitiveFilePatterns = [
150
+ /\.env(?:\..+)?$/,
151
+ /id_rsa|id_ed25519/,
152
+ /branch-ruleset\.json$/,
153
+ /main-branch-ruleset\.json$/
154
+ ];
155
+
156
+ for (const pat of sensitiveFilePatterns) {
157
+ if (pat.test(targetFile)) {
158
+ const elapsed = performance.now() - start;
159
+ return {
160
+ decision: DECISION_ESCALATE,
161
+ reason: 'GOVERNANCE_CONFIG_PROTECTED',
162
+ targetFile,
163
+ confidence: 0.99,
164
+ latencyMs: Number(elapsed.toFixed(3)),
165
+ budgetCompliant: elapsed < 25.0
166
+ };
167
+ }
168
+ }
169
+ }
170
+
171
+ // 4. Default safe mutation
172
+ const elapsed = performance.now() - start;
173
+ return {
174
+ decision: DECISION_ALLOW,
175
+ reason: 'ACTION_POLICY_CLEAR',
176
+ toolName,
177
+ confidence: 0.9,
178
+ latencyMs: Number(elapsed.toFixed(3)),
179
+ budgetCompliant: elapsed < 25.0
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Score a multi-option `--choice` question (pointer-head option scoring format).
185
+ * Returns normalized option probabilities sorted descending and calibrated confidence.
186
+ */
187
+ function scoreChoiceQuestion({ state = '', question = '', options = [] } = {}) {
188
+ const cleanOptions = (Array.isArray(options) ? options : [])
189
+ .map((o) => String(o || '').trim())
190
+ .filter(Boolean);
191
+ if (cleanOptions.length === 0) {
192
+ return {
193
+ valid: false,
194
+ reason: 'empty_options',
195
+ canGenerateFreeformText: false,
196
+ };
197
+ }
198
+
199
+ const hay = `${state} ${question}`.toLowerCase();
200
+ const rawScores = cleanOptions.map((opt) => {
201
+ const token = opt.toLowerCase();
202
+ let score = 1.0;
203
+ if (hay.includes(token)) score += 6.0;
204
+ if (token === 'billing' && /\b(?:payouts?|invoice|charge|payment|refund|billing|stripe)\b/i.test(hay)) score += 8.0;
205
+ if (token === 'sales' && /\b(?:quote|pricing|demo|lead|prospect|contract)\b/i.test(hay)) score += 8.0;
206
+ if (token === 'retail' && /\b(?:store|inventory|shipping|pos|merchandise)\b/i.test(hay)) score += 8.0;
207
+ return { option: opt, raw: score };
208
+ });
209
+
210
+ const total = rawScores.reduce((acc, item) => acc + item.raw, 0);
211
+ const distribution = rawScores
212
+ .map((item) => ({
213
+ option: item.option,
214
+ probability: Number((item.raw / total).toFixed(3)),
215
+ }))
216
+ .sort((a, b) => b.probability - a.probability);
217
+
218
+ const top = distribution[0];
219
+ const second = distribution[1] ? distribution[1].probability : 0;
220
+ const margin = Math.max(0, top.probability - second);
221
+ const confidence = Number(Math.min(0.999, 0.5 + margin * 0.5).toFixed(3));
222
+
223
+ return {
224
+ valid: true,
225
+ architecture: 'pointer_head_v19',
226
+ canGenerateFreeformText: false,
227
+ topChoice: top.option,
228
+ confidence,
229
+ distribution,
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Evaluate the two canonical `Decider.noul` pre-tool questions from the Strands
235
+ * Decider blog post (`args_grounded` and `premature`) over the user conversation
236
+ * and proposed tool arguments.
237
+ */
238
+ function evaluateToolGroundednessAndPrematurity({
239
+ userMessages = [],
240
+ toolName = '',
241
+ args = {},
242
+ exemptKeys = ['timeout', 'cwd', 'format'],
243
+ } = {}) {
244
+ const userCorpus = (Array.isArray(userMessages) ? userMessages : [userMessages])
245
+ .map((m) => String(m || '').toLowerCase())
246
+ .join(' ');
247
+ const exempt = new Set((Array.isArray(exemptKeys) ? exemptKeys : []).map((k) => String(k).toLowerCase()));
248
+ const ungroundedArgs = [];
249
+
250
+ for (const [key, val] of Object.entries(args || {})) {
251
+ if (exempt.has(key.toLowerCase())) continue;
252
+ if (val === undefined || val === null || typeof val === 'boolean') continue;
253
+ const strVal = String(val).trim();
254
+ if (!strVal) {
255
+ ungroundedArgs.push({ key, value: strVal, reason: 'empty_argument' });
256
+ continue;
257
+ }
258
+ if (!userCorpus.includes(strVal.toLowerCase())) {
259
+ ungroundedArgs.push({ key, value: strVal, reason: 'guessed_or_invented_not_in_user_input' });
260
+ }
261
+ }
262
+
263
+ const argsGrounded = ungroundedArgs.length === 0;
264
+ const premature = !argsGrounded;
265
+
266
+ return {
267
+ toolName: String(toolName || '').trim(),
268
+ questions: {
269
+ args_grounded: {
270
+ answer: argsGrounded ? 'true' : 'false',
271
+ confidence: argsGrounded ? 0.96 : 0.94,
272
+ description: argsGrounded
273
+ ? 'every argument value traces back to something the user said'
274
+ : 'an argument value was guessed or invented, not stated by the user',
275
+ },
276
+ premature: {
277
+ answer: premature ? 'true' : 'false',
278
+ confidence: premature ? 0.93 : 0.95,
279
+ description: premature
280
+ ? 'the assistant should ask a clarifying question before calling the tool'
281
+ : 'there is nothing left to clarify; calling now is appropriate',
282
+ },
283
+ },
284
+ argsGrounded,
285
+ premature,
286
+ ungroundedArgs,
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Strands `InterventionHandler.before_tool_call` implementation returning one
292
+ * of the 4 typed actions: `Proceed`, `Deny`, `Confirm`, or `Guide`.
293
+ */
294
+ function beforeToolCallIntervention(invocation = {}) {
295
+ const baseDecision = decide(invocation);
296
+ if (baseDecision.decision === DECISION_BLOCK) {
297
+ return {
298
+ action: INTERVENTION_DENY,
299
+ reason: baseDecision.reason,
300
+ confidence: baseDecision.confidence,
301
+ latencyMs: baseDecision.latencyMs,
302
+ feedback: null,
303
+ };
304
+ }
305
+ if (baseDecision.decision === DECISION_REVIEW || baseDecision.decision === DECISION_ESCALATE) {
306
+ return {
307
+ action: INTERVENTION_CONFIRM,
308
+ reason: baseDecision.reason,
309
+ confidence: baseDecision.confidence,
310
+ latencyMs: baseDecision.latencyMs,
311
+ feedback: `Human confirmation required for ${invocation.toolName || 'tool'} (${baseDecision.reason}).`,
312
+ };
313
+ }
314
+
315
+ if (Array.isArray(invocation.userMessages) && invocation.userMessages.length > 0) {
316
+ const noul = evaluateToolGroundednessAndPrematurity({
317
+ userMessages: invocation.userMessages,
318
+ toolName: invocation.toolName,
319
+ args: invocation.args,
320
+ exemptKeys: invocation.exemptKeys,
321
+ });
322
+ if (!noul.argsGrounded || noul.premature) {
323
+ const missingList = noul.ungroundedArgs.map((u) => `${u.key}="${u.value}"`).join(', ');
324
+ return {
325
+ action: INTERVENTION_GUIDE,
326
+ reason: 'UNGROUNDED_OR_PREMATURE_TOOL_CALL',
327
+ confidence: noul.questions.args_grounded.confidence,
328
+ latencyMs: baseDecision.latencyMs,
329
+ noul: noul.questions,
330
+ ungroundedArgs: noul.ungroundedArgs,
331
+ feedback: `Do not guess tool arguments (${missingList}). Ask the user to clarify before calling ${invocation.toolName}.`,
332
+ };
333
+ }
334
+ }
335
+
336
+ return {
337
+ action: INTERVENTION_PROCEED,
338
+ reason: baseDecision.reason,
339
+ confidence: baseDecision.confidence,
340
+ latencyMs: baseDecision.latencyMs,
341
+ feedback: null,
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Compute Brier calibration score: BS = (1/N) * sum((p_i - y_i)^2).
347
+ * Lower is better (0.0 = perfect calibration).
348
+ */
349
+ function computeBrierScore(samples = []) {
350
+ if (!Array.isArray(samples) || samples.length === 0) {
351
+ return { valid: false, brierScore: null, count: 0 };
352
+ }
353
+ let sumSq = 0;
354
+ for (const s of samples) {
355
+ const p = Math.min(1, Math.max(0, Number(s.probability ?? s.confidence ?? 0)));
356
+ const y = s.outcome === true || s.outcome === 1 ? 1 : 0;
357
+ sumSq += (p - y) ** 2;
358
+ }
359
+ return {
360
+ valid: true,
361
+ count: samples.length,
362
+ brierScore: Number((sumSq / samples.length).toFixed(4)),
363
+ };
364
+ }
365
+
366
+ /**
367
+ * Compare Strands Decider 2B linear token latency (~115ms RTX3090 / ~153ms M3 MacBook)
368
+ * against ThumbGate's sub-0.5ms deterministic local CPU diode.
369
+ */
370
+ function estimateDeciderLatencyMs({ tokenCount = 128, target = 'thumbgate_cpu_diode' } = {}) {
371
+ const tokens = Math.max(1, Number(tokenCount) || 128);
372
+ if (target === 'rtx3090_2b') {
373
+ return { target, medianMs: Number((100 + tokens * 0.12).toFixed(2)), requiresModelWeights: true };
374
+ }
375
+ if (target === 'm3_macbook_2b') {
376
+ return { target, medianMs: Number((135 + tokens * 0.14).toFixed(2)), requiresModelWeights: true };
377
+ }
378
+ return { target: 'thumbgate_cpu_diode', medianMs: 0.08, requiresModelWeights: false };
379
+ }
380
+
381
+ function buildStrandsDeciderHonestyReport(options = {}) {
382
+ const findings = [];
383
+ const claim = String(options.claim || '').trim();
384
+ if (/pip\s+install\s+strands-decider|huggingface\.co\/StrandsAgents\/strands-decider/i.test(claim)) {
385
+ findings.push({
386
+ id: 'refuse-2b-weight-install-in-hot-path',
387
+ severity: 'fail',
388
+ gateId: GATE_ID,
389
+ message: 'Do not install strands-decider Python weights into the <5ms PreToolUse hot path; use the deterministic local diode + InterventionHandler contract.',
390
+ });
391
+ }
392
+ if (/\bdecider\s+generates\s+code\b|\bdecider\s+chatbot\b/i.test(claim)) {
393
+ findings.push({
394
+ id: 'pointer-head-cannot-generate-text',
395
+ severity: 'fail',
396
+ gateId: GATE_ID,
397
+ message: 'Strands Decider removes the LM head in favor of a pointer head; it scores options and cannot generate freeform text.',
398
+ });
399
+ }
400
+
401
+ return {
402
+ ok: findings.length === 0,
403
+ status: findings.length === 0 ? 'ready' : 'fail',
404
+ sourceUrl: SOURCE_URL,
405
+ gateId: GATE_ID,
406
+ railMap: RAIL_MAP,
407
+ findings,
408
+ };
409
+ }
410
+
411
+ function runCli(argv = process.argv.slice(2)) {
412
+ const args = {};
413
+ for (const arg of argv) {
414
+ if (!arg.startsWith('--')) continue;
415
+ const [k, ...rest] = arg.slice(2).split('=');
416
+ args[k] = rest.length ? rest.join('=') : true;
417
+ }
418
+ const report = buildStrandsDeciderHonestyReport(args);
419
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
420
+ return report.ok ? 0 : 1;
421
+ }
422
+
423
+ module.exports = {
424
+ SOURCE_URL,
425
+ GATE_ID,
426
+ RAIL_MAP,
427
+ decide,
428
+ scoreChoiceQuestion,
429
+ evaluateToolGroundednessAndPrematurity,
430
+ beforeToolCallIntervention,
431
+ computeBrierScore,
432
+ estimateDeciderLatencyMs,
433
+ buildStrandsDeciderHonestyReport,
434
+ runCli,
435
+ DECISION_ALLOW,
436
+ DECISION_REVIEW,
437
+ DECISION_BLOCK,
438
+ DECISION_ESCALATE,
439
+ ALLOWED_DECISIONS,
440
+ INTERVENTION_PROCEED,
441
+ INTERVENTION_DENY,
442
+ INTERVENTION_CONFIRM,
443
+ INTERVENTION_GUIDE,
444
+ ALLOWED_INTERVENTIONS,
445
+ };
@@ -0,0 +1,192 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * adapters/strands/strands-middleware.js
5
+ *
6
+ * ThumbGate Governance Middleware for AWS Strands Harness (`@strands-agents/harness` & Python `strands-harness`).
7
+ *
8
+ * Injects:
9
+ * 1. PreToolUse Safety Diode: Intercepts and blocks dangerous or unverified tool mutations before execution.
10
+ * 2. Token-Shunt Output Truncation: Prevents massive tool outputs from blowing up the context window.
11
+ * 3. Context Compaction Guardian: Retains durable ThumbGate prevention rules during window compaction.
12
+ */
13
+
14
+ const { evaluateOutputShunt, evaluatePreActionDiode } = require('../../scripts/strands-harness-doctor');
15
+
16
+ function createStrandsGateMiddleware(options = {}) {
17
+ const shuntConfig = options.tokenShunt || { maxOutputLines: 350, maxOutputBytes: 16384 };
18
+ const preActionEnabled = options.preActionDiode?.enabled !== false;
19
+ const defaultPinnedRules = options.pinnedRules && options.pinnedRules.length > 0
20
+ ? options.pinnedRules
21
+ : ['Always verify against local tests before claiming completion'];
22
+
23
+ return {
24
+ name: 'thumbgate-strands-middleware',
25
+ version: '1.0.0',
26
+
27
+ /**
28
+ * Hook called by Strands Harness right before a tool is dispatched.
29
+ * Supports both Strands native event format (event.toolUse, event.cancel)
30
+ * and direct parameters ({ toolName, input }).
31
+ */
32
+ async beforeToolCall(event = {}) {
33
+ if (!preActionEnabled) {
34
+ return { allow: true };
35
+ }
36
+
37
+ const toolName = event.toolUse?.name || event.toolName || '';
38
+ const input = event.toolUse?.input !== undefined ? event.toolUse.input : event.input;
39
+
40
+ const evaluation = evaluatePreActionDiode({ name: toolName, input });
41
+ if (evaluation.decision === 'BLOCK') {
42
+ const reason = evaluation.violation || 'Action blocked by ThumbGate pre-action diode';
43
+ if (typeof event === 'object' && event !== null) {
44
+ event.cancel = true;
45
+ event.reason = reason;
46
+ }
47
+ return {
48
+ allow: false,
49
+ decision: 'BLOCK',
50
+ reason,
51
+ toolName,
52
+ timestamp: new Date().toISOString(),
53
+ };
54
+ }
55
+
56
+ return {
57
+ allow: true,
58
+ decision: 'ALLOW',
59
+ toolName,
60
+ };
61
+ },
62
+
63
+ /**
64
+ * Hook called by Strands Harness right after a tool produces output.
65
+ * Truncates oversized returns to enforce token efficiency.
66
+ * Supports updating native event.result in place (retaining ToolResultBlock structure).
67
+ */
68
+ async afterToolCall(event = {}) {
69
+ const rawResult = event.result !== undefined ? event.result : event;
70
+ let outputText = '';
71
+ if (typeof rawResult === 'string') {
72
+ outputText = rawResult;
73
+ } else if (rawResult && typeof rawResult === 'object') {
74
+ if (Array.isArray(rawResult.content)) {
75
+ outputText = rawResult.content.map((c) => (typeof c === 'string' ? c : c.text || '')).join('\n');
76
+ } else if (typeof rawResult.text === 'string') {
77
+ outputText = rawResult.text;
78
+ } else {
79
+ outputText = JSON.stringify(rawResult);
80
+ }
81
+ } else {
82
+ outputText = String(rawResult || '');
83
+ }
84
+
85
+ const shunt = evaluateOutputShunt(outputText, shuntConfig);
86
+
87
+ if (shunt.shunted) {
88
+ if (typeof event === 'object' && event !== null && 'result' in event) {
89
+ if (event.result && typeof event.result === 'object') {
90
+ if (Array.isArray(event.result.content)) {
91
+ event.result.content = [{ type: 'text', text: shunt.shuntedContent }];
92
+ } else if ('text' in event.result) {
93
+ event.result.text = shunt.shuntedContent;
94
+ } else {
95
+ event.result.content = [{ type: 'text', text: shunt.shuntedContent }];
96
+ }
97
+ } else {
98
+ event.result = shunt.shuntedContent;
99
+ }
100
+ }
101
+ return {
102
+ shunted: true,
103
+ result: shunt.shuntedContent,
104
+ reductionPct: shunt.reductionPct,
105
+ originalLines: shunt.originalLineCount,
106
+ shuntedLines: shunt.shuntedLineCount,
107
+ };
108
+ }
109
+
110
+ return {
111
+ shunted: false,
112
+ result: rawResult,
113
+ };
114
+ },
115
+
116
+ /**
117
+ * Hook or ContextStrategy called when context utilization reaches threshold.
118
+ * Implements Strands ContextStrategy.apply(context) returning boolean while
119
+ * retaining pinned rules in conversation history.
120
+ */
121
+ onContextCompaction(param = {}) {
122
+ const context = param.context || param;
123
+ const history = Array.isArray(param.history)
124
+ ? param.history
125
+ : (context && Array.isArray(context.messages) ? context.messages : []);
126
+ const pinnedRules = (param && Array.isArray(param.pinnedRules) && param.pinnedRules.length > 0)
127
+ ? param.pinnedRules
128
+ : defaultPinnedRules;
129
+ const preservedRules = pinnedRules.map((r) => `[PINNED RULE]: ${r}`);
130
+
131
+ let applied = false;
132
+ if (preservedRules.length > 0) {
133
+ const prefix = preservedRules.join('\n');
134
+ if (history.length > 0 && typeof history[0] === 'object') {
135
+ if (typeof history[0].content === 'string') {
136
+ if (!history[0].content.includes('[PINNED RULE]')) {
137
+ history[0].content = `${prefix}\n\n${history[0].content}`;
138
+ applied = true;
139
+ }
140
+ } else if (Array.isArray(history[0].content)) {
141
+ history[0].content.unshift({ type: 'text', text: prefix });
142
+ applied = true;
143
+ }
144
+ } else if (Array.isArray(history)) {
145
+ history.unshift({ role: 'system', content: prefix });
146
+ applied = true;
147
+ }
148
+ }
149
+
150
+ return {
151
+ compacted: true,
152
+ applied,
153
+ injectedPrefix: preservedRules.join('\n'),
154
+ timestamp: new Date().toISOString(),
155
+ };
156
+ },
157
+
158
+ /**
159
+ * Strands ContextStrategy contract: apply(context) => boolean
160
+ */
161
+ apply(context) {
162
+ if (!context) return false;
163
+ const res = this.onContextCompaction(context);
164
+ return res && typeof res === 'object' ? Boolean(res.applied || res.compacted) : Boolean(res);
165
+ },
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Helper to register ThumbGate middleware with a Strands Agent instance.
171
+ */
172
+ function registerStrandsGatePlugin(agent, options = {}) {
173
+ const middleware = createStrandsGateMiddleware(options);
174
+ if (agent && typeof agent.addHook === 'function') {
175
+ agent.addHook('beforeToolCall', (e) => middleware.beforeToolCall(e));
176
+ agent.addHook('afterToolCall', (e) => middleware.afterToolCall(e));
177
+ agent.addHook('onContextCompaction', (e) => middleware.onContextCompaction(e));
178
+ }
179
+ if (agent && agent.contextManager) {
180
+ if (typeof agent.contextManager.addStrategy === 'function') {
181
+ agent.contextManager.addStrategy(middleware);
182
+ } else if (typeof agent.contextManager.onCompaction === 'function') {
183
+ agent.contextManager.onCompaction((e) => middleware.onContextCompaction(e));
184
+ }
185
+ }
186
+ return middleware;
187
+ }
188
+
189
+ module.exports = {
190
+ createStrandsGateMiddleware,
191
+ registerStrandsGatePlugin,
192
+ };
@@ -0,0 +1,15 @@
1
+ {
2
+ "mcpServers": {
3
+ "thumbgate-tailscale": {
4
+ "command": "node",
5
+ "args": [
6
+ "scripts/tailscale-p2p-doctor.js",
7
+ "--serve-mcp"
8
+ ],
9
+ "env": {
10
+ "THUMBGATE_ADAPTER": "tailscale",
11
+ "THUMBGATE_P2P_PORT": "9877"
12
+ }
13
+ }
14
+ }
15
+ }