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,531 @@
1
+ 'use strict';
2
+ /**
3
+ * RRSI: Regularized Recursive Self-Improvement of Agent Harnesses
4
+ *
5
+ * Implements the mathematical regularization framework from Google Cloud AI Research
6
+ * (arXiv:2609.24972, Sep 2026: Xia, Han, Wang, Pfister, Lee, et al.).
7
+ *
8
+ * Prevents recursive agent harness evolution from overfitting to finite evaluation
9
+ * noise, leaking benchmark/test cheats, and accumulating unconstrained prompt/rule
10
+ * complexity ($L_0$ and $L_1$ explosions).
11
+ *
12
+ * Core Planes:
13
+ * 1. Proposal Regularization:
14
+ * - Cosine-Annealed Update Sparsity (b_t budget)
15
+ * - Annealed Step Sizing (alpha_t step attenuation)
16
+ * - Stagnation-Driven Structured Exploration (Entropy Regularization)
17
+ * - Credit-Assignment Falsification Conditioning
18
+ *
19
+ * 2. Selection Regularization:
20
+ * - Leakage Critic (pre-screening benchmark/fixture hardcoding)
21
+ * - Complexity-Aware Scoring (L1 cost penalty: Delta S_reg = Delta S - lambda * Delta C)
22
+ * - Stability-Aware Acceptance Floor (Delta S_reg > epsilon)
23
+ * - Structural Pruning (L0 redundancy and dormancy removal)
24
+ *
25
+ * Zero external dependencies — deterministic Node.js.
26
+ */
27
+
28
+ const RRSI_DEFAULTS = Object.freeze({
29
+ MIN_BUDGET: 1,
30
+ MAX_BUDGET: 3,
31
+ MIN_STEP_MULTIPLIER: 0.25,
32
+ MAX_STEP_MULTIPLIER: 1.0,
33
+ COMPLEXITY_LAMBDA: 0.05,
34
+ STABILITY_FLOOR: 0.002,
35
+ STAGNATION_WINDOW: 3,
36
+ STAGNATION_THRESHOLD: 0.001,
37
+ });
38
+
39
+ /**
40
+ * Compute the cosine-annealed cardinality budget b_t (L0 update sparsity).
41
+ * Early in evolution (t -> 0), b_t allows multi-parameter exploration (b_max).
42
+ * Late in evolution (t -> T), b_t anneals to isolated, fine-grained edits (b_min).
43
+ *
44
+ * Formula:
45
+ * b_t = floor(b_min + (b_max - b_min) * 0.5 * (1 + cos(pi * min(t, T) / T)))
46
+ *
47
+ * @param {number} iteration - 0-indexed current iteration t
48
+ * @param {number} totalIterations - Total scheduled iterations T
49
+ * @param {object} [options]
50
+ * @returns {number} Integer budget in [minBudget, maxBudget]
51
+ */
52
+ function calculateAnnealedBudget(iteration, totalIterations, options = {}) {
53
+ const minBudget = Number.isFinite(options.minBudget) ? options.minBudget : RRSI_DEFAULTS.MIN_BUDGET;
54
+ const maxBudget = Number.isFinite(options.maxBudget) ? options.maxBudget : RRSI_DEFAULTS.MAX_BUDGET;
55
+
56
+ if (totalIterations <= 1 || iteration <= 0) {
57
+ return maxBudget;
58
+ }
59
+ if (iteration >= totalIterations) {
60
+ return minBudget;
61
+ }
62
+
63
+ const progress = Math.min(1, Math.max(0, iteration / totalIterations));
64
+ const cosineFactor = 0.5 * (1 + Math.cos(Math.PI * progress));
65
+ const budget = Math.floor(minBudget + (maxBudget - minBudget) * cosineFactor);
66
+
67
+ return Math.max(minBudget, Math.min(maxBudget, budget));
68
+ }
69
+
70
+ /**
71
+ * Compute the cosine-annealed step multiplier alpha_t.
72
+ * Scales mutation step size down as iteration index approaches total iterations.
73
+ *
74
+ * Formula:
75
+ * alpha_t = alpha_min + (alpha_max - alpha_min) * 0.5 * (1 + cos(pi * min(t, T) / T))
76
+ *
77
+ * @param {number} iteration - 0-indexed current iteration t
78
+ * @param {number} totalIterations - Total scheduled iterations T
79
+ * @param {object} [options]
80
+ * @returns {number} Float multiplier in [minMultiplier, maxMultiplier]
81
+ */
82
+ function calculateAnnealedStepMultiplier(iteration, totalIterations, options = {}) {
83
+ const minMultiplier = Number.isFinite(options.minMultiplier)
84
+ ? options.minMultiplier
85
+ : RRSI_DEFAULTS.MIN_STEP_MULTIPLIER;
86
+ const maxMultiplier = Number.isFinite(options.maxMultiplier)
87
+ ? options.maxMultiplier
88
+ : RRSI_DEFAULTS.MAX_STEP_MULTIPLIER;
89
+
90
+ if (totalIterations <= 1 || iteration <= 0) {
91
+ return maxMultiplier;
92
+ }
93
+ if (iteration >= totalIterations) {
94
+ return minMultiplier;
95
+ }
96
+
97
+ const progress = Math.min(1, Math.max(0, iteration / totalIterations));
98
+ const cosineFactor = 0.5 * (1 + Math.cos(Math.PI * progress));
99
+ const multiplier = minMultiplier + (maxMultiplier - minMultiplier) * cosineFactor;
100
+
101
+ return Math.round(Math.max(minMultiplier, Math.min(maxMultiplier, multiplier)) * 10000) / 10000;
102
+ }
103
+
104
+ /**
105
+ * Leakage Critic: Pre-screens proposed mutations, diffs, rules, or values
106
+ * to reject benchmark-specific hardcoded strings, test fixtures, or cheats.
107
+ *
108
+ * @param {string|object} candidate - Proposed text, diff, or mutation object
109
+ * @param {object} [options]
110
+ * @returns {{ passed: boolean, leaks: string[], reason: string | null }}
111
+ */
112
+ function extractScreenableText(candidate) {
113
+ if (typeof candidate === 'string') return candidate;
114
+ if (!candidate || typeof candidate !== 'object') return '';
115
+ const clone = { ...candidate };
116
+ if (clone.metrics && typeof clone.metrics === 'object') {
117
+ const { evolutionStatePath, ...cleanedMetrics } = clone.metrics;
118
+ clone.metrics = cleanedMetrics;
119
+ }
120
+ return JSON.stringify(clone);
121
+ }
122
+
123
+ function screenLeakage(candidate, options = {}) {
124
+ const text = extractScreenableText(candidate);
125
+
126
+ const customDenyPatterns = Array.isArray(options.denyPatterns) ? options.denyPatterns : [];
127
+
128
+ const BENCHMARK_LEAKAGE_PATTERNS = [
129
+ { name: 'benchmark_dataset', regex: /\b(?:swe[-_]?bench|humaneval|mbpp|gsm8k|arc[-_]?challenge|webarena|synthetic[-_]?eval)\b/i },
130
+ { name: 'test_fixture_hardcode', regex: /(?:tests?\/fixtures\/|fixture_[a-z0-9_]+\.(?:json|html|txt)|mock_[a-z0-9_]+_response)/i },
131
+ { name: 'session_lease_leak', regex: /(?:thumbgate-session-lease\.json|\.thumbgate\/session-lease)/i },
132
+ { name: 'temp_filesystem_leak', regex: /(?:\/private\/tmp\/|\/tmp\/[a-z0-9_.-]+|\/var\/folders\/)/i },
133
+ { name: 'golden_cheat_token', regex: /(?:golden[-_]?answer|expected[-_]?golden(?:[-_]?answer)?|cheat[-_]?bypass|assert_true_always)/i },
134
+ ...customDenyPatterns.map((pat, idx) => ({
135
+ name: `custom_pattern_${idx}`,
136
+ regex: pat instanceof RegExp ? pat : new RegExp(pat, 'i'),
137
+ })),
138
+ ];
139
+
140
+ const leaks = [];
141
+ for (const pattern of BENCHMARK_LEAKAGE_PATTERNS) {
142
+ if (pattern.regex.test(text)) {
143
+ leaks.push(pattern.name);
144
+ }
145
+ }
146
+
147
+ const passed = leaks.length === 0;
148
+ const reason = passed ? null : `Leakage Critic rejected candidate containing: ${leaks.join(', ')}`;
149
+
150
+ return {
151
+ passed,
152
+ leaks,
153
+ reason,
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Measure complexity delta between candidate and baseline.
159
+ * Can evaluate parameter displacement, string length, or token delta.
160
+ *
161
+ * @param {object} candidate
162
+ * @param {object} baseline
163
+ * @param {object} [options]
164
+ * @returns {number} Normalized complexity delta (>= 0)
165
+ */
166
+ function computeComplexityDelta(candidate, baseline, options = {}) {
167
+ // If numeric parameter change:
168
+ if (typeof candidate === 'number' && typeof baseline === 'number') {
169
+ const range = Array.isArray(options.range) && options.range.length === 2
170
+ ? Math.max(1e-6, Math.abs(options.range[1] - options.range[0]))
171
+ : Math.max(1, Math.abs(baseline) || 1);
172
+ return Math.abs(candidate - baseline) / range;
173
+ }
174
+
175
+ // If text/string (e.g. prompt or rule):
176
+ if (typeof candidate === 'string' && typeof baseline === 'string') {
177
+ const lengthDelta = Math.max(0, candidate.length - baseline.length);
178
+ const baseLength = Math.max(1, baseline.length);
179
+ return lengthDelta / baseLength;
180
+ }
181
+
182
+ // If object mutation:
183
+ if (candidate && typeof candidate === 'object' && baseline && typeof baseline === 'object') {
184
+ const candidateKeys = Object.keys(candidate).length;
185
+ const baselineKeys = Object.keys(baseline).length;
186
+ return Math.max(0, (candidateKeys - baselineKeys) / Math.max(1, baselineKeys));
187
+ }
188
+
189
+ return 0;
190
+ }
191
+
192
+ /**
193
+ * Evaluate complexity-regularized score and acceptance decision.
194
+ *
195
+ * Regularization formula:
196
+ * Delta S = S_cand - S_base
197
+ * ComplexityPenalty = lambda * max(0, Delta Complexity)
198
+ * Delta S_reg = Delta S - ComplexityPenalty
199
+ *
200
+ * Accepted iff:
201
+ * 1. candidate passed all tests
202
+ * 2. candidate score >= baseline score
203
+ * 3. Delta S_reg > stabilityFloor
204
+ *
205
+ * @param {object} params
206
+ * @param {number} params.baselineScore - S_base in [0, 1]
207
+ * @param {number} params.candidateScore - S_cand in [0, 1]
208
+ * @param {boolean} [params.testsPassed=true] - Whether evaluation tests passed
209
+ * @param {number} [params.complexityDelta=0] - Complexity growth (>= 0)
210
+ * @param {object} [options]
211
+ * @returns {object}
212
+ */
213
+ function evaluateComplexityRegularizedScore(params, options = {}) {
214
+ const baselineScore = Number.isFinite(params.baselineScore) ? params.baselineScore : 0;
215
+ const candidateScore = Number.isFinite(params.candidateScore) ? params.candidateScore : 0;
216
+ const testsPassed = params.testsPassed !== false;
217
+ const complexityDelta = Number.isFinite(params.complexityDelta) ? Math.max(0, params.complexityDelta) : 0;
218
+
219
+ const lambda = Number.isFinite(options.lambda) ? options.lambda : RRSI_DEFAULTS.COMPLEXITY_LAMBDA;
220
+ const stabilityFloor = Number.isFinite(options.stabilityFloor) ? options.stabilityFloor : RRSI_DEFAULTS.STABILITY_FLOOR;
221
+
222
+ const rawDelta = Math.round((candidateScore - baselineScore) * 10000) / 10000;
223
+ const penalty = Math.round((lambda * complexityDelta) * 10000) / 10000;
224
+ const regularizedDelta = Math.round((rawDelta - penalty) * 10000) / 10000;
225
+
226
+ let accepted = false;
227
+ let reason = '';
228
+
229
+ if (!testsPassed) {
230
+ accepted = false;
231
+ reason = 'Candidate evaluation failed test execution';
232
+ } else if (candidateScore < baselineScore) {
233
+ accepted = false;
234
+ reason = `Score regressed from ${baselineScore} to ${candidateScore} (delta: ${rawDelta})`;
235
+ } else if (regularizedDelta <= stabilityFloor) {
236
+ accepted = false;
237
+ reason = `Score gain (${rawDelta}) penalized by complexity (${penalty}) leaves regularized delta (${regularizedDelta}) below stability floor (${stabilityFloor})`;
238
+ } else {
239
+ accepted = true;
240
+ reason = `Regularized delta (+${regularizedDelta}) clears stability floor (+${stabilityFloor}) with complexity penalty (${penalty})`;
241
+ }
242
+
243
+ return {
244
+ accepted,
245
+ rawDelta,
246
+ regularizedDelta,
247
+ penalty,
248
+ complexityDelta,
249
+ stabilityFloor,
250
+ reason,
251
+ };
252
+ }
253
+
254
+ /**
255
+ * Stagnation Detector: Detects when recursive self-improvement has stalled
256
+ * over a sliding window w of experiments.
257
+ *
258
+ * @param {Array<object>} history - Array of previous experiment results
259
+ * @param {object} [options]
260
+ * @returns {{ isStagnant: boolean, windowSize: number, recentDeltas: number[], reason: string }}
261
+ */
262
+ function detectStagnation(history = [], options = {}) {
263
+ const windowSize = Number.isFinite(options.windowSize) ? options.windowSize : RRSI_DEFAULTS.STAGNATION_WINDOW;
264
+ const threshold = Number.isFinite(options.threshold) ? options.threshold : RRSI_DEFAULTS.STAGNATION_THRESHOLD;
265
+
266
+ if (!Array.isArray(history) || history.length < windowSize) {
267
+ return {
268
+ isStagnant: false,
269
+ windowSize,
270
+ recentDeltas: [],
271
+ reason: `Insufficient history (${(history || []).length}/${windowSize}) to evaluate stagnation`,
272
+ };
273
+ }
274
+
275
+ const recent = history.slice(-windowSize);
276
+ const recentDeltas = recent.map((item) => {
277
+ if (typeof item.regularizedDelta === 'number') return item.regularizedDelta;
278
+ if (typeof item.delta === 'number') return item.delta;
279
+ if (typeof item.score === 'number' && typeof item.baseline === 'number') {
280
+ return item.score - item.baseline;
281
+ }
282
+ return 0;
283
+ });
284
+
285
+ const allFlat = recentDeltas.every((d) => Math.abs(d) <= threshold);
286
+ const allDiscarded = recent.every((item) => item.kept === false || item.status === 'discarded');
287
+
288
+ const isStagnant = allFlat || allDiscarded;
289
+ const reason = isStagnant
290
+ ? `Stagnation detected: last ${windowSize} experiments flat/discarded (max |delta| = ${Math.max(...recentDeltas.map(Math.abs)).toFixed(4)})`
291
+ : `Progress healthy: recent variations exceed threshold ${threshold}`;
292
+
293
+ return {
294
+ isStagnant,
295
+ windowSize,
296
+ recentDeltas,
297
+ reason,
298
+ };
299
+ }
300
+
301
+ /**
302
+ * Structured Exploration Selector (Entropy Regularization):
303
+ * Directs proposal generation to under-explored targets when stagnation occurs,
304
+ * and conditions selection on credit-assignment history to prevent re-testing
305
+ * previously falsified values.
306
+ *
307
+ * @param {object} params
308
+ * @param {Array<object>} params.targets - List of available evolution targets
309
+ * @param {Array<object>} [params.history=[]] - Past experiment history
310
+ * @param {boolean} [params.isStagnant=false] - Whether stagnation is currently flagged
311
+ * @returns {{ target: object, strategy: string, rationale: string }}
312
+ */
313
+ function selectTargetWithExploration({ targets = [], history = [], isStagnant = false } = {}) {
314
+ if (!Array.isArray(targets) || targets.length === 0) {
315
+ throw new Error('selectTargetWithExploration requires a non-empty targets array');
316
+ }
317
+
318
+ // Count visits per target name
319
+ const visitCounts = new Map();
320
+ targets.forEach((t) => visitCounts.set(t.name, 0));
321
+
322
+ (history || []).forEach((exp) => {
323
+ const targetName = exp.target?.name || exp.mutation?.target || exp.targetName;
324
+ if (targetName && visitCounts.has(targetName)) {
325
+ visitCounts.set(targetName, visitCounts.get(targetName) + 1);
326
+ }
327
+ });
328
+
329
+ // If stagnant: pick the target with the LOWEST visit count (forced exploration)
330
+ if (isStagnant) {
331
+ let minTarget = targets[0];
332
+ let minCount = visitCounts.get(minTarget.name) || 0;
333
+
334
+ for (const t of targets) {
335
+ const count = visitCounts.get(t.name) || 0;
336
+ if (count < minCount) {
337
+ minCount = count;
338
+ minTarget = t;
339
+ }
340
+ }
341
+
342
+ return {
343
+ target: minTarget,
344
+ strategy: 'entropy_exploration',
345
+ rationale: `Stagnation active: selected under-explored target "${minTarget.name}" (exercised ${minCount} times)`,
346
+ };
347
+ }
348
+
349
+ // Exploitation / weighted selection: prefer targets with higher success rates
350
+ const successCounts = new Map();
351
+ targets.forEach((t) => successCounts.set(t.name, 0));
352
+
353
+ (history || []).forEach((exp) => {
354
+ const targetName = exp.target?.name || exp.mutation?.target || exp.targetName;
355
+ if (targetName && successCounts.has(targetName) && exp.kept) {
356
+ successCounts.set(targetName, successCounts.get(targetName) + 1);
357
+ }
358
+ });
359
+
360
+ // Pick target with best win rate or least recent failure
361
+ const sorted = [...targets].sort((a, b) => {
362
+ const aWins = successCounts.get(a.name) || 0;
363
+ const bWins = successCounts.get(b.name) || 0;
364
+ if (bWins !== aWins) return bWins - aWins;
365
+ return (visitCounts.get(a.name) || 0) - (visitCounts.get(b.name) || 0);
366
+ });
367
+
368
+ return {
369
+ target: sorted[0],
370
+ strategy: 'exploitation',
371
+ rationale: `Exploitation active: selected top-performing target "${sorted[0].name}"`,
372
+ };
373
+ }
374
+
375
+ /**
376
+ * Structural Pruner (L0 Rule Pruning):
377
+ * Identifies and strips redundant, duplicate, or subsumed rules
378
+ * to halt unbounded agent harness bloat.
379
+ *
380
+ * @param {Array<string|object>} rules - Array of rules (strings or rule objects)
381
+ * @param {object} [options]
382
+ * @returns {{ prunedRules: Array<any>, removedRules: Array<any>, reductionCount: number }}
383
+ */
384
+ function pruneStructuralRedundancy(rules = [], options = {}) {
385
+ if (!Array.isArray(rules)) {
386
+ return { prunedRules: [], removedRules: [], reductionCount: 0 };
387
+ }
388
+
389
+ const seen = new Set();
390
+ const prunedRules = [];
391
+ const removedRules = [];
392
+
393
+ for (const rule of rules) {
394
+ const ruleText = typeof rule === 'string'
395
+ ? rule.trim()
396
+ : (rule.text || rule.title || rule.description || JSON.stringify(rule)).trim();
397
+
398
+ const normalized = ruleText.toLowerCase().replace(/[\s\-_]+/g, ' ');
399
+
400
+ if (!normalized) {
401
+ removedRules.push({ rule, reason: 'empty_rule' });
402
+ continue;
403
+ }
404
+
405
+ if (seen.has(normalized)) {
406
+ removedRules.push({ rule, reason: 'duplicate_rule' });
407
+ continue;
408
+ }
409
+
410
+ // Check for subsumption (if a shorter rule already captured this concept)
411
+ let isSubsumed = false;
412
+ for (const existing of seen) {
413
+ if (existing.length >= 15 && normalized.includes(existing)) {
414
+ isSubsumed = true;
415
+ break;
416
+ }
417
+ }
418
+
419
+ if (isSubsumed) {
420
+ removedRules.push({ rule, reason: 'subsumed_rule' });
421
+ continue;
422
+ }
423
+
424
+ seen.add(normalized);
425
+ prunedRules.push(rule);
426
+ }
427
+
428
+ return {
429
+ prunedRules,
430
+ removedRules,
431
+ reductionCount: removedRules.length,
432
+ };
433
+ }
434
+
435
+ /**
436
+ * arXiv:2610.11655 Harness Evolution Ceiling Evaluator:
437
+ * "Harness Evolution Hits a Ceiling: When Weight Training Should Begin"
438
+ *
439
+ * Separates process failures (repaired by harness evolution) from content failures
440
+ * (repaired by weight training or model escalation).
441
+ *
442
+ * @param {object} params
443
+ * @param {object} [params.failureComposition]
444
+ * @param {object} [params.stagnationResult]
445
+ * @param {Array<object|string>} [params.recentEdits]
446
+ * @returns {object}
447
+ */
448
+ function evaluateHarnessCeiling({ failureComposition = {}, stagnationResult = {}, recentEdits = [] } = {}) {
449
+ const processRate = Number.isFinite(failureComposition.processFailureRate) ? failureComposition.processFailureRate : 0;
450
+ const contentRate = Number.isFinite(failureComposition.contentFailureRate) ? failureComposition.contentFailureRate : 0;
451
+ const totalFailures = Number.isFinite(failureComposition.totalFailures) ? failureComposition.totalFailures : 0;
452
+ const isStagnant = stagnationResult.isStagnant === true;
453
+
454
+ const ceilingDetected = totalFailures >= 3 && processRate <= 0.2 && contentRate >= 0.8;
455
+
456
+ let recommendation = 'continue_harness_evolution';
457
+ let rationale = '';
458
+
459
+ if (ceilingDetected) {
460
+ recommendation = 'weight_training_or_model_escalation';
461
+ rationale = `Harness evolution ceiling hit: process failures suppressed (${(processRate * 100).toFixed(1)}%), ` +
462
+ `content failures dominate (${(contentRate * 100).toFixed(1)}%)${isStagnant ? ' (evolution stagnant)' : ''}. Switch lever from harness prompt bloat to ` +
463
+ `weight training (LoRA/distillation) or model tier escalation.`;
464
+ } else if (processRate >= 0.2) {
465
+ recommendation = 'harness_evolution';
466
+ rationale = `Process failures active (${(processRate * 100).toFixed(1)}%). Harness evolution (rules, gates, tool contracts) has high ROI.`;
467
+ } else {
468
+ recommendation = 'monitor';
469
+ rationale = `Failure rates balanced or sample too small (${totalFailures} failures).`;
470
+ }
471
+
472
+ const partitions = partitionAcceptedEdits(recentEdits);
473
+
474
+ return {
475
+ ceilingDetected,
476
+ recommendation,
477
+ rationale,
478
+ processFailureRate: processRate,
479
+ contentFailureRate: contentRate,
480
+ totalFailures,
481
+ partitions,
482
+ };
483
+ }
484
+
485
+ /**
486
+ * Partition accepted harness edits into those that can be internalized into
487
+ * weights (LoRA / distillation) vs those that must remain in the runtime harness.
488
+ * (arXiv:2610.11655)
489
+ *
490
+ * @param {Array<object|string>} edits
491
+ * @returns {{ trainableIntoWeights: Array, keepInRuntimeHarness: Array }}
492
+ */
493
+ function partitionAcceptedEdits(edits = []) {
494
+ const trainableIntoWeights = [];
495
+ const keepInRuntimeHarness = [];
496
+
497
+ const RUNTIME_KEYWORDS = /security|gate|lease|credential|secret|token|firewall|authoriz|sandbox|fence|verify|signature/i;
498
+ const TRAINABLE_KEYWORDS = /style|format|prompt|tone|template|convention|plan_format|reasoning_step|cot|persona/i;
499
+
500
+ for (const edit of edits) {
501
+ const text = typeof edit === 'string'
502
+ ? edit
503
+ : [edit.name, edit.description, edit.rule].filter(Boolean).join(' ') || JSON.stringify(edit);
504
+ if (RUNTIME_KEYWORDS.test(text)) {
505
+ keepInRuntimeHarness.push(edit);
506
+ } else if (TRAINABLE_KEYWORDS.test(text)) {
507
+ trainableIntoWeights.push(edit);
508
+ } else {
509
+ keepInRuntimeHarness.push(edit);
510
+ }
511
+ }
512
+
513
+ return {
514
+ trainableIntoWeights,
515
+ keepInRuntimeHarness,
516
+ };
517
+ }
518
+
519
+ module.exports = {
520
+ RRSI_DEFAULTS,
521
+ calculateAnnealedBudget,
522
+ calculateAnnealedStepMultiplier,
523
+ screenLeakage,
524
+ computeComplexityDelta,
525
+ evaluateComplexityRegularizedScore,
526
+ detectStagnation,
527
+ selectTargetWithExploration,
528
+ pruneStructuralRedundancy,
529
+ evaluateHarnessCeiling,
530
+ partitionAcceptedEdits,
531
+ };