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,357 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * ActiveSaddler Curriculum Doctor — Compare, Do Not Clone
6
+ *
7
+ * Stolen from ActiveSaddler (arXiv:2610.00906):
8
+ * "Automated Curriculum Learning for Agent Harness Optimization"
9
+ *
10
+ * Implements the non-stationary Multi-Armed Bandit (MAB) curriculum for agent harness optimization:
11
+ * 1. Dynamic Failure-Pattern Arms: abstracts agent mistakes into adaptive bandit arms.
12
+ * 2. Discounted UCB Scoring: balances exploitation (frequent/severe failures) with exploration (detecting regression drift).
13
+ * 3. Fail-Fast Rule Prioritization: orders pre-tool validation so high-risk rules execute first (<0.5ms).
14
+ * 4. Grounded Arm Decay & Promotion: elevates recurring failure patterns and retires zero-violation rules with confidence bounds.
15
+ *
16
+ * Strictly fail-closed: Refuses external heavy RL/PyTorch dependencies. Pure CPU-local JS (<1ms budget).
17
+ */
18
+
19
+ const fs = require('node:fs');
20
+ const path = require('node:path');
21
+ const { performance } = require('node:perf_hooks');
22
+
23
+ const COMPARISON_MAP = {
24
+ paradigm: 'ActiveSaddler (arXiv:2610.00906) vs. ThumbGate Dynamic Curriculum',
25
+ verdict: 'COMPARE_NOT_CLONE',
26
+ stolenPractices: [
27
+ {
28
+ practice: 'Dynamic Failure-Pattern Arms',
29
+ activesaddler: 'Automated clustering of execution traces into non-stationary task arms',
30
+ thumbgate: 'Abstracts MistakePatterns into FailurePatternArms with severity and violation rates'
31
+ },
32
+ {
33
+ practice: 'Discounted UCB Policy',
34
+ activesaddler: 'Adaptive non-stationary bandit balancing known harness weaknesses and exploration',
35
+ thumbgate: 'Discounted UCB score weighting recent failure recency, severity, and exploration bonus'
36
+ },
37
+ {
38
+ practice: 'Fail-Fast Rule Prioritization',
39
+ activesaddler: 'Curriculum schedules high-difficulty evaluation environments first',
40
+ thumbgate: 'PreToolUse pipeline evaluates high-bandit-score prevention rules first (<0.5ms budget)'
41
+ },
42
+ {
43
+ practice: 'Automated Drift Detection',
44
+ activesaddler: 'Triggers curriculum re-weighting when agent policy shifts or regresses',
45
+ thumbgate: 'Detects distribution shift across failure categories and updates gate thresholds'
46
+ }
47
+ ],
48
+ antiCloneRules: [
49
+ 'NEVER install PyTorch, Ray, Stable-Baselines, or external RL frameworks',
50
+ 'NEVER spin up GPU training loops or heavy reinforcement learners in CI',
51
+ 'ALWAYS maintain deterministic CPU-local bandit math (<1ms evaluation latency)',
52
+ 'ALWAYS keep failure pattern state in local-first structured JSON receipts'
53
+ ]
54
+ };
55
+
56
+ const SEVERITY_MULTIPLIERS = {
57
+ CRITICAL: 3.0,
58
+ HIGH: 2.0,
59
+ MEDIUM: 1.2,
60
+ LOW: 1.0
61
+ };
62
+
63
+ const CANONICAL_FAILURE_ARMS = [
64
+ {
65
+ id: 'arm:force-push-main',
66
+ name: 'Destructive Force-Push on Main',
67
+ severity: 'CRITICAL',
68
+ baselineFrequency: 0.05,
69
+ description: 'Agent attempts git push --force origin main'
70
+ },
71
+ {
72
+ id: 'arm:bypass-branch-protection',
73
+ name: 'Branch Protection Bypass',
74
+ severity: 'CRITICAL',
75
+ baselineFrequency: 0.04,
76
+ description: 'Agent attempts PR self-approval or admin merge override'
77
+ },
78
+ {
79
+ id: 'arm:token-shunt-overflow',
80
+ name: 'Unbounded Token Shunt Dump',
81
+ severity: 'MEDIUM',
82
+ baselineFrequency: 0.15,
83
+ description: 'Agent dumps massive unindexed log or data files (>350 lines)'
84
+ },
85
+ {
86
+ id: 'arm:untracked-peer-clean',
87
+ name: 'Destructive Untracked File Clean',
88
+ severity: 'HIGH',
89
+ baselineFrequency: 0.08,
90
+ description: 'Agent runs git clean -fd wiping peer agent worktree files'
91
+ },
92
+ {
93
+ id: 'arm:runaway-halo-loop',
94
+ name: 'Runaway Agent Re-query Loop',
95
+ severity: 'HIGH',
96
+ baselineFrequency: 0.10,
97
+ description: 'Agent loops over failing subagent queries burning token budgets'
98
+ }
99
+ ];
100
+
101
+ class ActiveSaddlerCurriculum {
102
+ constructor(options = {}) {
103
+ this.discountFactor = options.discountFactor || 0.92;
104
+ this.explorationWeight = options.explorationWeight || 0.35;
105
+ this.arms = new Map();
106
+ this.history = [];
107
+ this.totalSteps = 0;
108
+
109
+ // Initialize canonical arms
110
+ for (const arm of CANONICAL_FAILURE_ARMS) {
111
+ this.registerArm(arm);
112
+ }
113
+ }
114
+
115
+ registerArm(armConfig) {
116
+ if (!armConfig || !armConfig.id) {
117
+ throw new Error('Arm configuration must have an id');
118
+ }
119
+ const severity = armConfig.severity || 'MEDIUM';
120
+ const multiplier = SEVERITY_MULTIPLIERS[severity] || 1.0;
121
+ this.arms.set(armConfig.id, {
122
+ id: armConfig.id,
123
+ name: armConfig.name || armConfig.id,
124
+ severity,
125
+ multiplier,
126
+ pulls: 0,
127
+ violations: 0,
128
+ discountedPulls: 0,
129
+ discountedViolations: 0,
130
+ lastObservedAt: null,
131
+ description: armConfig.description || ''
132
+ });
133
+ }
134
+
135
+ recordObservation(armId, observation = {}) {
136
+ const arm = this.arms.get(armId);
137
+ if (!arm) {
138
+ throw new Error(`Unknown failure pattern arm: ${armId}`);
139
+ }
140
+
141
+ const isViolation = Boolean(observation.violation);
142
+ const now = observation.timestamp || new Date().toISOString();
143
+
144
+ // Apply discounting to all arms
145
+ for (const [id, a] of this.arms.entries()) {
146
+ a.discountedPulls *= this.discountFactor;
147
+ a.discountedViolations *= this.discountFactor;
148
+ }
149
+
150
+ // Update target arm
151
+ arm.pulls += 1;
152
+ arm.discountedPulls += 1.0;
153
+ if (isViolation) {
154
+ arm.violations += 1;
155
+ arm.discountedViolations += 1.0;
156
+ }
157
+ arm.lastObservedAt = now;
158
+ this.totalSteps += 1;
159
+
160
+ const receipt = {
161
+ step: this.totalSteps,
162
+ armId,
163
+ violation: isViolation,
164
+ timestamp: now,
165
+ latencyMs: observation.latencyMs || 0
166
+ };
167
+ this.history.push(receipt);
168
+ return receipt;
169
+ }
170
+
171
+ computeArmScore(armId) {
172
+ const arm = this.arms.get(armId);
173
+ if (!arm) return 0;
174
+
175
+ if (arm.discountedPulls < 1e-4) {
176
+ // High priority for unvisited arms (optimism in face of uncertainty)
177
+ return 10.0 * arm.multiplier;
178
+ }
179
+
180
+ const empiricalFailureRate = arm.discountedViolations / arm.discountedPulls;
181
+ const totalDiscountedSteps = Array.from(this.arms.values())
182
+ .reduce((sum, a) => sum + a.discountedPulls, 0);
183
+
184
+ const explorationBonus = Math.sqrt(
185
+ (2 * Math.log(Math.max(1, totalDiscountedSteps))) / arm.discountedPulls
186
+ );
187
+
188
+ const rawScore = empiricalFailureRate + (this.explorationWeight * explorationBonus);
189
+ return rawScore * arm.multiplier;
190
+ }
191
+
192
+ prioritizeRules(rules = []) {
193
+ const start = performance.now();
194
+
195
+ // Map each rule to its corresponding arm (or default to general arm)
196
+ const scoredRules = rules.map((rule) => {
197
+ const armId = rule.armId || this.matchArmForRule(rule);
198
+ const score = this.computeArmScore(armId);
199
+ return {
200
+ ...rule,
201
+ armId,
202
+ curriculumScore: Number(score.toFixed(4))
203
+ };
204
+ });
205
+
206
+ // Sort descending by curriculum score (highest risk first)
207
+ scoredRules.sort((a, b) => b.curriculumScore - a.curriculumScore);
208
+
209
+ const elapsedMs = performance.now() - start;
210
+ return {
211
+ prioritizedRules: scoredRules,
212
+ evaluationLatencyMs: Number(elapsedMs.toFixed(3)),
213
+ withinBudget: elapsedMs < 1.0
214
+ };
215
+ }
216
+
217
+ matchArmForRule(rule = {}) {
218
+ const text = `${rule.id || ''} ${rule.name || ''} ${rule.description || ''}`.toLowerCase();
219
+ if (text.includes('force-push') || text.includes('push')) return 'arm:force-push-main';
220
+ if (text.includes('branch-protection') || text.includes('review') || text.includes('admin')) return 'arm:bypass-branch-protection';
221
+ if (text.includes('token') || text.includes('shunt') || text.includes('dump')) return 'arm:token-shunt-overflow';
222
+ if (text.includes('clean') || text.includes('untracked')) return 'arm:untracked-peer-clean';
223
+ if (text.includes('loop') || text.includes('halo') || text.includes('runaway')) return 'arm:runaway-halo-loop';
224
+ return 'arm:token-shunt-overflow';
225
+ }
226
+
227
+ detectDrift(windowSize = 20) {
228
+ if (this.history.length < 5) {
229
+ return { driftDetected: false, reason: 'INSUFFICIENT_OBSERVATIONS', count: this.history.length };
230
+ }
231
+
232
+ const recent = this.history.slice(-windowSize);
233
+ const violationsByArm = {};
234
+ for (const item of recent) {
235
+ if (item.violation) {
236
+ violationsByArm[item.armId] = (violationsByArm[item.armId] || 0) + 1;
237
+ }
238
+ }
239
+
240
+ const totalViolations = Object.values(violationsByArm).reduce((a, b) => a + b, 0);
241
+ if (totalViolations === 0) {
242
+ return { driftDetected: false, totalViolations: 0, reason: 'CLEAN_EXECUTION' };
243
+ }
244
+
245
+ // Check if any single arm accounts for > 60% of recent violations
246
+ for (const [armId, count] of Object.entries(violationsByArm)) {
247
+ const share = count / totalViolations;
248
+ if (share >= 0.6 && count >= 3) {
249
+ return {
250
+ driftDetected: true,
251
+ dominantArmId: armId,
252
+ violationShare: Number(share.toFixed(3)),
253
+ recentViolations: count,
254
+ totalViolations,
255
+ recommendation: `Elevate pre-action interdiction priority for ${armId}`
256
+ };
257
+ }
258
+ }
259
+
260
+ return { driftDetected: false, totalViolations, distributions: violationsByArm };
261
+ }
262
+
263
+ diagnose() {
264
+ const start = performance.now();
265
+ const armSummaries = [];
266
+
267
+ for (const [id, arm] of this.arms.entries()) {
268
+ const score = this.computeArmScore(id);
269
+ armSummaries.push({
270
+ id,
271
+ name: arm.name,
272
+ severity: arm.severity,
273
+ pulls: arm.pulls,
274
+ violations: arm.violations,
275
+ discountedViolations: Number(arm.discountedViolations.toFixed(3)),
276
+ curriculumScore: Number(score.toFixed(4)),
277
+ lastObservedAt: arm.lastObservedAt
278
+ });
279
+ }
280
+
281
+ armSummaries.sort((a, b) => b.curriculumScore - a.curriculumScore);
282
+ const drift = this.detectDrift();
283
+ const elapsed = performance.now() - start;
284
+
285
+ return {
286
+ status: 'HEALTHY',
287
+ paradigm: 'ActiveSaddler Dynamic Non-Stationary Curriculum',
288
+ totalSteps: this.totalSteps,
289
+ armCount: this.arms.size,
290
+ topPriorityArm: armSummaries[0] ? armSummaries[0].id : null,
291
+ arms: armSummaries,
292
+ driftAnalysis: drift,
293
+ performanceBudgetMs: Number(elapsed.toFixed(3)),
294
+ passedBudget: elapsed < 5.0
295
+ };
296
+ }
297
+ }
298
+
299
+ function runDoctor(options = {}) {
300
+ const curriculum = new ActiveSaddlerCurriculum();
301
+
302
+ if (Array.isArray(options.observations) && options.observations.length > 0) {
303
+ for (const obs of options.observations) {
304
+ if (obs && obs.armId) {
305
+ curriculum.recordObservation(obs.armId, obs);
306
+ }
307
+ }
308
+ } else {
309
+ // Feed baseline observations for initial curriculum diagnosis
310
+ curriculum.recordObservation('arm:force-push-main', { violation: false, latencyMs: 0.1 });
311
+ curriculum.recordObservation('arm:bypass-branch-protection', { violation: false, latencyMs: 0.1 });
312
+ curriculum.recordObservation('arm:token-shunt-overflow', { violation: true, latencyMs: 0.2 });
313
+ curriculum.recordObservation('arm:token-shunt-overflow', { violation: true, latencyMs: 0.2 });
314
+ curriculum.recordObservation('arm:runaway-halo-loop', { violation: false, latencyMs: 0.1 });
315
+ }
316
+
317
+ const diagnosis = curriculum.diagnose();
318
+
319
+ if (options.json) {
320
+ console.log(JSON.stringify(diagnosis, null, 2));
321
+ return diagnosis;
322
+ }
323
+
324
+ console.log('=== ActiveSaddler Curriculum Doctor (arXiv:2610.00906) ===');
325
+ console.log(`Status: ${diagnosis.status} | Arms: ${diagnosis.armCount} | Total Steps: ${diagnosis.totalSteps}`);
326
+ console.log(`Top Priority Arm: ${diagnosis.topPriorityArm}`);
327
+ console.log(`Doctor Diagnostic Latency: ${diagnosis.performanceBudgetMs}ms (Budget: <5.0ms)`);
328
+ console.log('\nFailure Pattern Arm Priority Ranking:');
329
+ for (const arm of diagnosis.arms) {
330
+ console.log(` - [${arm.severity}] ${arm.id} (Score: ${arm.curriculumScore}) - ${arm.violations} violations`);
331
+ }
332
+ if (diagnosis.driftAnalysis.driftDetected) {
333
+ console.log(`\n⚠️ DRIFT DETECTED: Dominant arm ${diagnosis.driftAnalysis.dominantArmId} (${(diagnosis.driftAnalysis.violationShare * 100).toFixed(1)}% of violations)`);
334
+ } else {
335
+ console.log('\n✓ Drift Status: Stable curriculum distribution');
336
+ }
337
+
338
+ return diagnosis;
339
+ }
340
+
341
+ if (require.main === module) {
342
+ const args = process.argv.slice(2);
343
+ if (args.includes('--map-only')) {
344
+ console.log(JSON.stringify(COMPARISON_MAP, null, 2));
345
+ process.exit(0);
346
+ }
347
+
348
+ const jsonMode = args.includes('--json');
349
+ runDoctor({ json: jsonMode });
350
+ }
351
+
352
+ module.exports = {
353
+ ActiveSaddlerCurriculum,
354
+ COMPARISON_MAP,
355
+ CANONICAL_FAILURE_ARMS,
356
+ runDoctor
357
+ };
@@ -0,0 +1,325 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Wisdom.ai / Soham Mazumdar FORMAT steal — not a product clone.
6
+ *
7
+ * Sources:
8
+ * https://www.wisdom.ai/
9
+ * https://music.youtube.com/watch?v=lRuI0imju0Y
10
+ * "What Context Really Means in Data Engineering and AI"
11
+ *
12
+ * Transfers:
13
+ * 1. Context is a reusable *agent* artifact (not tribal metadata)
14
+ * 2. Required fields: goal, constraints, sources, freshness, verifier
15
+ * 3. consumer must be `agent` (not human-analyst warehousing)
16
+ * 4. Explicit wrong-fit gate (must include wisdom_ai)
17
+ *
18
+ * Does NOT clone Adaptive Context Engine, Palantir Foundry, or Snowflake OSI.
19
+ * Complements six-block skill packs and ContextFS — does not replace them.
20
+ */
21
+
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+
25
+ const SOURCE_URLS = Object.freeze([
26
+ 'https://www.wisdom.ai/',
27
+ 'https://music.youtube.com/watch?v=lRuI0imju0Y',
28
+ ]);
29
+
30
+ const REQUIRED_FIELDS = Object.freeze(['goal', 'constraints', 'sources', 'freshness', 'verifier']);
31
+ const REQUIRED_WRONG_FIT = 'wisdom_ai';
32
+
33
+ const CLONE_PATTERNS = Object.freeze([
34
+ { id: 'ace_sku', re: /\b(clone|install|vendor)\b.{0,50}\b(adaptive context engine|wisdom\.?ai ace|ace)\b/i },
35
+ { id: 'foundry_sku', re: /\b(clone|install|vendor)\b.{0,40}\b(palantir )?foundry\b/i },
36
+ { id: 'osi_sku', re: /\b(clone|implement)\b.{0,40}\b(open semantic interchange|snowflake osi)\b/i },
37
+ ]);
38
+
39
+ function normalizeBoolean(value) {
40
+ if (value === true || value === 1) return true;
41
+ if (value === false || value === 0 || value == null) return false;
42
+ return /^(1|true|yes|on)$/i.test(String(value).trim());
43
+ }
44
+
45
+ function detectCloneAttempt(text) {
46
+ return CLONE_PATTERNS.filter((p) => p.re.test(String(text || ''))).map((p) => p.id);
47
+ }
48
+
49
+ function asList(value) {
50
+ if (Array.isArray(value)) return value;
51
+ if (value == null || value === '') return [];
52
+ return [value];
53
+ }
54
+
55
+ function resolveTrustedNow(options = {}) {
56
+ if (options.now != null && options.now !== '') {
57
+ const parsed = typeof options.now === 'number' ? options.now : Date.parse(String(options.now));
58
+ if (Number.isFinite(parsed)) return parsed;
59
+ }
60
+ return Date.now();
61
+ }
62
+
63
+ function lintPack(pack = {}, options = {}) {
64
+ const findings = [];
65
+ if (!pack || typeof pack !== 'object' || Array.isArray(pack)) {
66
+ return [{
67
+ severity: 'fail',
68
+ id: 'empty_pack',
69
+ message: 'Pack is missing. An agent-context artifact is a JSON object, not tribal knowledge.',
70
+ }];
71
+ }
72
+
73
+ const consumer = String(pack.consumer || '').toLowerCase();
74
+ if (consumer !== 'agent') {
75
+ findings.push({
76
+ severity: 'fail',
77
+ id: 'consumer_not_agent',
78
+ message: `consumer must be "agent" (got ${pack.consumer || '(missing)'}). Human-analyst warehousing is the old bar.`,
79
+ });
80
+ }
81
+
82
+ for (const field of REQUIRED_FIELDS) {
83
+ const v = pack[field];
84
+ const empty = v == null
85
+ || (typeof v === 'string' && !v.trim())
86
+ || (Array.isArray(v) && v.length === 0)
87
+ || (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0);
88
+ if (empty) {
89
+ findings.push({
90
+ severity: 'fail',
91
+ id: `missing_${field}`,
92
+ message: `Agent artifact missing ${field}. Context-as-product requires goal, constraints, sources, freshness, verifier.`,
93
+ });
94
+ }
95
+ }
96
+
97
+ const sources = asList(pack.sources);
98
+ for (const src of sources) {
99
+ if (src && typeof src === 'object' && !src.id && !src.path && !src.url) {
100
+ findings.push({
101
+ severity: 'fail',
102
+ id: 'source_unidentified',
103
+ message: 'Each source needs id, path, or url so agents can cite it.',
104
+ });
105
+ }
106
+ }
107
+
108
+ const freshness = pack.freshness && typeof pack.freshness === 'object' ? pack.freshness : {};
109
+ const maxAgeHours = Number(freshness.maxAgeHours);
110
+ const asOf = freshness.asOf ? Date.parse(String(freshness.asOf)) : NaN;
111
+ // Pack-supplied freshness.now is not a clock. A stale pack could set now=asOf
112
+ // and certify ready. CLI uses Date.now(); tests may pass options.now / --now=.
113
+ const now = resolveTrustedNow(options);
114
+ if (Number.isFinite(maxAgeHours) && Number.isFinite(asOf)) {
115
+ const ageHours = (now - asOf) / 3600000;
116
+ if (ageHours < 0) {
117
+ findings.push({
118
+ severity: 'fail',
119
+ id: 'freshness_in_future',
120
+ message: `Context asOf is ${(-ageHours).toFixed(1)}h ahead of the trusted clock. A future timestamp skips the staleness check.`,
121
+ });
122
+ } else if (ageHours > maxAgeHours) {
123
+ findings.push({
124
+ severity: 'fail',
125
+ id: 'stale_context',
126
+ message: `Context asOf is ${ageHours.toFixed(1)}h old; maxAgeHours=${maxAgeHours}. Agents must not consume stale packs.`,
127
+ });
128
+ }
129
+ } else if (pack.freshness && (!Number.isFinite(maxAgeHours) || !Number.isFinite(asOf))) {
130
+ findings.push({
131
+ severity: 'fail',
132
+ id: 'freshness_unmeasurable',
133
+ message: 'freshness needs maxAgeHours and asOf (ISO) so staleness is checkable.',
134
+ });
135
+ }
136
+
137
+ const verifier = pack.verifier && typeof pack.verifier === 'object' ? pack.verifier : {};
138
+ if (pack.verifier && !verifier.command && !verifier.check) {
139
+ findings.push({
140
+ severity: 'fail',
141
+ id: 'verifier_unrunnable',
142
+ message: 'verifier needs command or check. A prose "looks good" is not an agent verifier.',
143
+ });
144
+ }
145
+
146
+ const wrongFit = asList(pack.wrongFit || pack.wrong_fit).map((v) => String(v).toLowerCase());
147
+ if (!wrongFit.includes(REQUIRED_WRONG_FIT)) {
148
+ findings.push({
149
+ severity: 'fail',
150
+ id: 'missing_wrong_fit_wisdom_ai',
151
+ message: 'wrongFit must include "wisdom_ai". The episode\'s wrong-fit question is the buy-vs-build gate — ACE is not our SKU.',
152
+ });
153
+ }
154
+
155
+ return findings;
156
+ }
157
+
158
+ function loadPack(filePath) {
159
+ if (!filePath) return null;
160
+ if (typeof filePath === 'object') return filePath;
161
+ return JSON.parse(fs.readFileSync(String(filePath), 'utf8'));
162
+ }
163
+
164
+ function collectHaystack(options = {}) {
165
+ const parts = [
166
+ options.task,
167
+ options.query,
168
+ options['clone-ace'] ? 'clone Adaptive Context Engine vendor Palantir Foundry implement Snowflake OSI' : '',
169
+ ];
170
+ if (Array.isArray(options.argv)) parts.push(...options.argv);
171
+ return parts.filter(Boolean).join(' ');
172
+ }
173
+
174
+ function buildAgentContextArtifactReport(options = {}) {
175
+ const findings = [];
176
+ const cloneHits = [...new Set(detectCloneAttempt(collectHaystack(options)))];
177
+ if (cloneHits.length) {
178
+ findings.push({
179
+ severity: 'fail',
180
+ id: 'wisdom_clone_refused',
181
+ message: `Refusing ACE / Foundry / OSI clones (${cloneHits.join(', ')}). Lint a local agent pack; do not buy a semantic-layer SKU.`,
182
+ });
183
+ }
184
+
185
+ const mapOnly = normalizeBoolean(options.map || options['map-only']);
186
+ let pack = null;
187
+ let packLoadFailed = false;
188
+ if (!mapOnly) {
189
+ if (options.pack && typeof options.pack === 'object' && !Array.isArray(options.pack)) {
190
+ pack = options.pack;
191
+ } else if (options.pack) {
192
+ try {
193
+ pack = loadPack(options.pack);
194
+ } catch (error) {
195
+ packLoadFailed = true;
196
+ findings.push({
197
+ severity: 'fail',
198
+ id: 'pack_load_failed',
199
+ message: `Cannot load pack: ${error && error.message ? error.message : error}`,
200
+ });
201
+ }
202
+ }
203
+ if (pack) findings.push(...lintPack(pack, { now: options.now }));
204
+ else if (!cloneHits.length && !packLoadFailed) {
205
+ findings.push({
206
+ severity: 'warn',
207
+ id: 'no_pack',
208
+ message: 'No --pack JSON. Pass an agent-context artifact to lint. Complements six-block SKILL.md packs + ContextFS.',
209
+ });
210
+ }
211
+ }
212
+
213
+ let status = 'ready';
214
+ if (findings.some((f) => f.severity === 'fail')) status = 'fail';
215
+ else if (findings.some((f) => f.severity === 'warn')) status = 'ready_with_warnings';
216
+
217
+ return {
218
+ name: 'thumbgate-agent-context-artifact',
219
+ status,
220
+ ok: status !== 'fail',
221
+ requiredFields: REQUIRED_FIELDS,
222
+ requiredWrongFit: REQUIRED_WRONG_FIT,
223
+ pack: mapOnly ? null : pack,
224
+ compareNotClone: true,
225
+ complements: [
226
+ 'six-block SKILL.md packs (goal/constraints/reference/examples/procedures/rubric)',
227
+ 'ContextFS envelopes',
228
+ 'memory-vs-rag-route (stateful lessons vs stateless RAG)',
229
+ ],
230
+ never: [
231
+ 'clone Wisdom Adaptive Context Engine',
232
+ 'clone Palantir Foundry or Snowflake OSI',
233
+ 'treat catalogs/query logs as afterthought metadata',
234
+ 'ship a pack with consumer=human',
235
+ 'omit wisdom_ai from wrongFit',
236
+ ],
237
+ source: SOURCE_URLS,
238
+ disclaimer: 'FORMAT steal only. Not affiliated with Wisdom.ai, Palantir, or Snowflake. Local agent packs; no ACE SKU.',
239
+ findings,
240
+ };
241
+ }
242
+
243
+ function formatAgentContextArtifactReport(report) {
244
+ const lines = [
245
+ 'ThumbGate agent-context artifact (Wisdom.ai FORMAT steal)',
246
+ `Status : ${report.status}`,
247
+ `ok : ${report.ok}`,
248
+ `Fields : ${(report.requiredFields || []).join(', ')}`,
249
+ `wrongFit : must include ${report.requiredWrongFit}`,
250
+ ];
251
+ if (report.findings?.length) {
252
+ lines.push('Findings:');
253
+ for (const f of report.findings) lines.push(` [${f.severity}] ${f.id}: ${f.message}`);
254
+ }
255
+ lines.push(`Never : ${(report.never || []).join('; ')}`);
256
+ lines.push(`Source : ${(report.source || []).join(' · ')}`);
257
+ lines.push(report.disclaimer);
258
+ return `${lines.join('\n')}\n`;
259
+ }
260
+
261
+ function parseArgv(argv) {
262
+ const options = { argv };
263
+ const booleanFlags = {
264
+ json: 'json',
265
+ strict: 'strict',
266
+ map: 'map',
267
+ 'map-only': 'map',
268
+ 'clone-ace': 'clone-ace',
269
+ };
270
+ for (const arg of argv) {
271
+ const flag = /^--([^=]+)(?:=(.*))?$/.exec(arg);
272
+ if (flag && Object.hasOwn(booleanFlags, flag[1])) {
273
+ options[booleanFlags[flag[1]]] = normalizeBoolean(flag[2] === undefined ? true : flag[2]);
274
+ } else if (arg.startsWith('--pack=')) options.pack = arg.slice('--pack='.length);
275
+ else if (arg.startsWith('--now=')) options.now = arg.slice('--now='.length);
276
+ }
277
+ return options;
278
+ }
279
+
280
+ function printHelp() {
281
+ process.stdout.write(`Usage: node scripts/agent-context-artifact.js [options]
282
+
283
+ Wisdom.ai FORMAT: context as a reusable *agent* artifact
284
+ (goal, constraints, sources, freshness, verifier) + wrong-fit.
285
+ Does not clone ACE / Foundry / OSI.
286
+
287
+ Options:
288
+ --pack=<file.json>
289
+ --now=<ISO> Trusted clock (tests). Pack freshness.now is ignored.
290
+ --map-only
291
+ --clone-ace Fail closed
292
+ --json --strict
293
+ `);
294
+ }
295
+
296
+ function main(argv = process.argv.slice(2)) {
297
+ if (argv.includes('--help') || argv.includes('-h')) {
298
+ printHelp();
299
+ return 0;
300
+ }
301
+ const options = parseArgv(argv);
302
+ const report = buildAgentContextArtifactReport(options);
303
+ if (options.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
304
+ else process.stdout.write(formatAgentContextArtifactReport(report));
305
+ if (options.strict && report.status !== 'ready') return 1;
306
+ if (report.status === 'fail') return 1;
307
+ return 0;
308
+ }
309
+
310
+ module.exports = {
311
+ REQUIRED_FIELDS,
312
+ REQUIRED_WRONG_FIT,
313
+ SOURCE_URLS,
314
+ detectCloneAttempt,
315
+ normalizeBoolean,
316
+ resolveTrustedNow,
317
+ lintPack,
318
+ buildAgentContextArtifactReport,
319
+ formatAgentContextArtifactReport,
320
+ main,
321
+ };
322
+
323
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
324
+ process.exitCode = main();
325
+ }
@@ -176,7 +176,7 @@ function normalizeMethod(method) {
176
176
  return String(method || 'GET').trim().toUpperCase() || 'GET';
177
177
  }
178
178
 
179
- function parseTarget(input = {}) {
179
+ function parseTarget(input = {}) { // NOSONAR
180
180
  const rawUrl = input.url || input.target || input.href || '';
181
181
  const method = normalizeMethod(input.method);
182
182
  let url = String(rawUrl || '').trim();
@@ -336,7 +336,7 @@ function ruleMatches(compiled, target) {
336
336
  * @returns {{ hit: boolean, action?: string, rule?: object }}
337
337
  */
338
338
  function matchStaticRules(target, rules = []) {
339
- const compiled = (rules || []).map(compileRule);
339
+ const compiled = (rules || []).map((x) => compileRule(x));
340
340
  const denies = compiled.filter((r) => r.action === 'deny');
341
341
  const allows = compiled.filter((r) => r.action === 'allow');
342
342