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,326 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * harness-ceiling-doctor.js — arXiv:2610.11655 Doctor & Inspector
6
+ *
7
+ * Implements the diagnose-then-intervene rail from:
8
+ * "Harness Evolution Hits a Ceiling: When Weight Training Should Begin"
9
+ * (arXiv:2610.11655, Oct 8, 2026: Yuan Tian, Bing Hu, Hao Wang, Binghang Lu, Fang Wu)
10
+ *
11
+ * Core principles:
12
+ * 1. First-Signal-Fires Failure Classification:
13
+ * Separates process failures (blocked calls, loops, tool syntax, timeouts)
14
+ * from content failures (mechanically delivered output that is poor/wrong).
15
+ * 2. Harness Evolution Ceiling Detection:
16
+ * Harness evolution repairs process failures but hits an asymptotic ceiling
17
+ * when content failures dominate (>= 80% content, <= 20% process).
18
+ * 3. Diagnose-Then-Intervene Dual Protocol:
19
+ * - If process failures active: recommend harness_evolution (gates, tools, contracts).
20
+ * - If content ceiling reached: recommend weight_training_or_model_escalation
21
+ * (LoRA adapter / trajectory distillation or named model tier upgrade).
22
+ * 4. Partitioning Accepted Edits:
23
+ * Decides which harness edits to train into weights (formatting, response style,
24
+ * plan structure) vs which to keep in the runtime harness (security gates,
25
+ * single-writer checkout leases, task-scope boundaries, signature checks).
26
+ * 5. omp.sh Named-Model Escalation over Prompt Bloat:
27
+ * Prevents expanding prompt rules in AGENTS.md when content failure ceiling is hit.
28
+ */
29
+
30
+ const fs = require('node:fs');
31
+ const path = require('node:path');
32
+ const { classifyFailureType, calculateTaskOutcomeMetrics } = require('./task-outcomes');
33
+ const { evaluateHarnessCeiling, partitionAcceptedEdits } = require('./rrsi-regularizer');
34
+ const { diagnoseFailureIntervention, RAIL_MAP: OMP_RAILS } = require('./omp-coordination-honesty');
35
+
36
+ const SOURCE_PAPER = 'arXiv:2610.11655 (Tian et al., Oct 2026)';
37
+ const SOURCE_TITLE = 'Harness Evolution Hits a Ceiling: When Weight Training Should Begin';
38
+
39
+ const PILLARS = Object.freeze([
40
+ {
41
+ pillar: 'First-Signal-Fires Failure Classification',
42
+ paperFinding: 'Labelling failed trajectories by the first signal that fires separates process failures from content failures.',
43
+ thumbgateRail: 'scripts/task-outcomes.js (classifyFailureType)',
44
+ status: 'enforced',
45
+ },
46
+ {
47
+ pillar: 'Harness Evolution Ceiling Detection',
48
+ paperFinding: 'Harness evolution repairs process failures but hits an asymptotic ceiling when content failures dominate (>=80%).',
49
+ thumbgateRail: 'scripts/rrsi-regularizer.js (evaluateHarnessCeiling)',
50
+ status: 'enforced',
51
+ },
52
+ {
53
+ pillar: 'Diagnose-Then-Intervene Dual Rule',
54
+ paperFinding: 'Read failure composition to choose between harness evolution and weight training / model escalation.',
55
+ thumbgateRail: 'scripts/task-outcomes.js & scripts/rrsi-regularizer.js',
56
+ status: 'enforced',
57
+ },
58
+ {
59
+ pillar: 'Partitioning Accepted Edits (Train-in vs Keep-in-Runtime)',
60
+ paperFinding: 'Read what accepted edits changed to decide which gains to train into weights vs keep in runtime.',
61
+ thumbgateRail: 'scripts/rrsi-regularizer.js (partitionAcceptedEdits)',
62
+ status: 'enforced',
63
+ },
64
+ {
65
+ pillar: 'omp.sh Named-Model Route Escalation over Prompt Bloat',
66
+ paperFinding: 'When content ceiling is reached, switch model route or train weights instead of bloating harness prompts.',
67
+ thumbgateRail: 'scripts/omp-coordination-honesty.js (diagnoseFailureIntervention)',
68
+ status: 'enforced',
69
+ },
70
+ ]);
71
+
72
+ function auditHarnessCeiling() {
73
+ const checks = [];
74
+
75
+ // Check 1: First-Signal-Fires classification distinguishes process vs content
76
+ try {
77
+ const processFailure = {
78
+ status: 'failed',
79
+ toolCalls: [{ name: 'bash', contractValid: false, allowed: true, succeeded: false, attempts: 1 }],
80
+ workingReasons: ['tool_contract_invalid', 'status_failed'],
81
+ };
82
+ const contentFailure = {
83
+ status: 'completed',
84
+ toolCalls: [{ name: 'bash', contractValid: true, allowed: true, succeeded: true, attempts: 1 }],
85
+ verification: { performed: true, passed: false, evidence: [] },
86
+ workingReasons: ['verification_failed', 'evidence_missing'],
87
+ };
88
+
89
+ const pClass = classifyFailureType(processFailure);
90
+ const cClass = classifyFailureType(contentFailure);
91
+
92
+ const ok = pClass.type === 'process' && cClass.type === 'content' &&
93
+ pClass.firstSignal.startsWith('tool_contract_invalid') &&
94
+ cClass.firstSignal === 'verification_failed';
95
+
96
+ checks.push({
97
+ id: 'first-signal-failure-classifier',
98
+ pillar: 'First-Signal-Fires Failure Classification',
99
+ ok,
100
+ message: ok
101
+ ? 'First-signal-fires failure classifier correctly distinguishes process vs content failures'
102
+ : `Classifier failed: process=${JSON.stringify(pClass)}, content=${JSON.stringify(cClass)}`,
103
+ });
104
+ } catch (err) {
105
+ checks.push({
106
+ id: 'first-signal-failure-classifier',
107
+ pillar: 'First-Signal-Fires Failure Classification',
108
+ ok: false,
109
+ message: `Classifier threw error: ${err.message}`,
110
+ });
111
+ }
112
+
113
+ // Check 2: Harness ceiling evaluator flags weight training when content failures dominate
114
+ try {
115
+ const ceilingEval = evaluateHarnessCeiling({
116
+ failureComposition: {
117
+ totalFailures: 10,
118
+ processFailures: 1,
119
+ contentFailures: 9,
120
+ processFailureRate: 0.1,
121
+ contentFailureRate: 0.9,
122
+ },
123
+ });
124
+
125
+ const activeProcessEval = evaluateHarnessCeiling({
126
+ failureComposition: {
127
+ totalFailures: 10,
128
+ processFailures: 6,
129
+ contentFailures: 4,
130
+ processFailureRate: 0.6,
131
+ contentFailureRate: 0.4,
132
+ },
133
+ });
134
+
135
+ const ok = ceilingEval.ceilingDetected === true &&
136
+ ceilingEval.recommendation === 'weight_training_or_model_escalation' &&
137
+ activeProcessEval.ceilingDetected === false &&
138
+ activeProcessEval.recommendation === 'harness_evolution';
139
+
140
+ checks.push({
141
+ id: 'harness-ceiling-evaluator',
142
+ pillar: 'Harness Evolution Ceiling Detection',
143
+ ok,
144
+ message: ok
145
+ ? 'Ceiling evaluator correctly triggers weight_training_or_model_escalation on content domination'
146
+ : 'Ceiling evaluator misclassified failure distributions',
147
+ });
148
+ } catch (err) {
149
+ checks.push({
150
+ id: 'harness-ceiling-evaluator',
151
+ pillar: 'Harness Evolution Ceiling Detection',
152
+ ok: false,
153
+ message: `Ceiling evaluator threw error: ${err.message}`,
154
+ });
155
+ }
156
+
157
+ // Check 3: Partitioning accepted edits into weights vs runtime harness
158
+ try {
159
+ const sampleEdits = [
160
+ { name: 'response-format-template', rule: 'format output as structured json' },
161
+ { name: 'checkout-lease-guard', rule: 'security check single-writer checkout lease before checkout switch' },
162
+ { name: 'cot-planning-style', rule: 'reasoning_step planning convention' },
163
+ { name: 'task-scope-boundary', rule: 'firewall fence tool mutations to task scope' },
164
+ ];
165
+
166
+ const { trainableIntoWeights, keepInRuntimeHarness } = partitionAcceptedEdits(sampleEdits);
167
+ const ok = trainableIntoWeights.length === 2 &&
168
+ keepInRuntimeHarness.length === 2 &&
169
+ keepInRuntimeHarness.some((e) => e.name === 'checkout-lease-guard') &&
170
+ trainableIntoWeights.some((e) => e.name === 'response-format-template');
171
+
172
+ checks.push({
173
+ id: 'edit-partitioner',
174
+ pillar: 'Partitioning Accepted Edits (Train-in vs Keep-in-Runtime)',
175
+ ok,
176
+ message: ok
177
+ ? 'Accepted edit partitioner preserves security gates in runtime and isolates templates for weights'
178
+ : `Partitioner mismatch: trainable=${trainableIntoWeights.length}, runtime=${keepInRuntimeHarness.length}`,
179
+ });
180
+ } catch (err) {
181
+ checks.push({
182
+ id: 'edit-partitioner',
183
+ pillar: 'Partitioning Accepted Edits (Train-in vs Keep-in-Runtime)',
184
+ ok: false,
185
+ message: `Edit partitioner threw error: ${err.message}`,
186
+ });
187
+ }
188
+
189
+ // Check 4: omp.sh coordination integration rejects prompt bloat at ceiling
190
+ try {
191
+ const bloatDiag = diagnoseFailureIntervention({
192
+ totalFailures: 5,
193
+ processFailures: 0,
194
+ contentFailures: 5,
195
+ });
196
+ const processDiag = diagnoseFailureIntervention({
197
+ totalFailures: 5,
198
+ processFailures: 4,
199
+ contentFailures: 1,
200
+ });
201
+
202
+ const ok = bloatDiag.ceilingHit === true &&
203
+ bloatDiag.intervention === 'model_tier_escalation_or_weight_training' &&
204
+ processDiag.ceilingHit === false &&
205
+ processDiag.intervention === 'harness_evolution';
206
+
207
+ checks.push({
208
+ id: 'omp-coordination-prompt-bloat-guard',
209
+ pillar: 'omp.sh Named-Model Route Escalation over Prompt Bloat',
210
+ ok,
211
+ message: ok
212
+ ? 'omp.sh coordination guard prevents prompt bloat and enforces model tier escalation at ceiling'
213
+ : 'omp.sh failure diagnosis mismatch',
214
+ });
215
+ } catch (err) {
216
+ checks.push({
217
+ id: 'omp-coordination-prompt-bloat-guard',
218
+ pillar: 'omp.sh Named-Model Route Escalation over Prompt Bloat',
219
+ ok: false,
220
+ message: `omp diagnosis threw error: ${err.message}`,
221
+ });
222
+ }
223
+
224
+ const allPassed = checks.every((c) => c.ok);
225
+ return {
226
+ status: allPassed ? 'PASS' : 'FAIL',
227
+ paper: SOURCE_PAPER,
228
+ title: SOURCE_TITLE,
229
+ checkedAt: new Date().toISOString(),
230
+ checks,
231
+ pillars: PILLARS,
232
+ };
233
+ }
234
+
235
+ function parseCliArgs(argv = process.argv.slice(2)) {
236
+ const args = {
237
+ json: false,
238
+ mapOnly: false,
239
+ evaluate: false,
240
+ processFailures: 0,
241
+ contentFailures: 0,
242
+ };
243
+
244
+ for (const arg of argv) {
245
+ if (arg === '--json') args.json = true;
246
+ else if (arg === '--map-only') args.mapOnly = true;
247
+ else if (arg === '--evaluate') args.evaluate = true;
248
+ else if (arg.startsWith('--process=')) args.processFailures = Number(arg.slice(10)) || 0;
249
+ else if (arg.startsWith('--content=')) args.contentFailures = Number(arg.slice(10)) || 0;
250
+ }
251
+
252
+ return args;
253
+ }
254
+
255
+ function runCli(argv = process.argv.slice(2)) {
256
+ const args = parseCliArgs(argv);
257
+
258
+ if (args.mapOnly) {
259
+ const map = {
260
+ name: 'thumbgate-harness-ceiling-doctor',
261
+ paper: SOURCE_PAPER,
262
+ title: SOURCE_TITLE,
263
+ status: 'ready',
264
+ ok: true,
265
+ mapOnly: true,
266
+ pillars: PILLARS,
267
+ };
268
+ if (args.json) {
269
+ console.log(JSON.stringify(map, null, 2));
270
+ } else {
271
+ console.log(`\n=== Harness Evolution Ceiling Rail Map (${SOURCE_PAPER}) ===\n`);
272
+ for (const p of PILLARS) {
273
+ console.log(`Pillar: ${p.pillar}`);
274
+ console.log(` Paper Finding: ${p.paperFinding}`);
275
+ console.log(` ThumbGate Rail: ${p.thumbgateRail}`);
276
+ console.log(` Status: ${p.status}\n`);
277
+ }
278
+ }
279
+ return 0;
280
+ }
281
+
282
+ if (args.evaluate) {
283
+ const diag = diagnoseFailureIntervention({
284
+ processFailures: args.processFailures,
285
+ contentFailures: args.contentFailures,
286
+ });
287
+ if (args.json) {
288
+ console.log(JSON.stringify(diag, null, 2));
289
+ } else {
290
+ console.log(`\n=== Failure Composition Evaluation (arXiv:2610.11655) ===`);
291
+ console.log(`Process Failures: ${args.processFailures}`);
292
+ console.log(`Content Failures: ${args.contentFailures}`);
293
+ console.log(`Ceiling Hit: ${diag.ceilingHit}`);
294
+ console.log(`Intervention: ${diag.intervention}`);
295
+ console.log(`Rationale: ${diag.rationale}\n`);
296
+ }
297
+ return 0;
298
+ }
299
+
300
+ const report = auditHarnessCeiling();
301
+ if (args.json) {
302
+ console.log(JSON.stringify(report, null, 2));
303
+ } else {
304
+ console.log(`\n=== Harness Evolution Ceiling Doctor (${report.status}) ===`);
305
+ console.log(`Paper: ${report.paper} - ${report.title}\n`);
306
+ for (const check of report.checks) {
307
+ const sym = check.ok ? '✓' : '✗';
308
+ console.log(`${sym} [${check.pillar}] ${check.message}`);
309
+ }
310
+ console.log(`\nOverall Status: ${report.status}\n`);
311
+ }
312
+
313
+ return report.status === 'PASS' ? 0 : 1;
314
+ }
315
+
316
+ if (require.main === module) {
317
+ process.exit(runCli());
318
+ }
319
+
320
+ module.exports = {
321
+ SOURCE_PAPER,
322
+ SOURCE_TITLE,
323
+ PILLARS,
324
+ auditHarnessCeiling,
325
+ runCli,
326
+ };
@@ -149,7 +149,7 @@ async function searchPapers({
149
149
  try {
150
150
  const payload = await readJson(url, fetchImpl);
151
151
  const papers = extractPaperItems(payload)
152
- .map(normalizePaper)
152
+ .map((x) => normalizePaper(x))
153
153
  .filter((paper) => paper.paperId || paper.title);
154
154
 
155
155
  if (papers.length > 0) {
@@ -107,7 +107,13 @@ function decideEscalation(input = {}, options = {}) {
107
107
  const current = projectEscalations(ledger.events, options)
108
108
  .find((entry) => entry.escalationId === escalationId);
109
109
  if (!current) throw escalationError(`unknown escalation '${escalationId}'`);
110
- if (current.status !== 'pending') throw escalationError(`escalation '${escalationId}' is already ${current.status}`);
110
+ if (current.eventType === 'consumed') {
111
+ throw escalationError(`escalation '${escalationId}' is already consumed`);
112
+ }
113
+ const isWithdrawingUnconsumedApproval = current.status === 'approved' && decision === 'cancelled';
114
+ if (current.status !== 'pending' && !isWithdrawingUnconsumedApproval) {
115
+ throw escalationError(`escalation '${escalationId}' is already ${current.status}`);
116
+ }
111
117
  if (sameIdentity(current.requester, actor)) throw escalationError('requester cannot decide their own escalation');
112
118
  if (current.requiredReviewerRole && actor.role !== current.requiredReviewerRole) {
113
119
  throw escalationError(`authenticated reviewer must have role '${current.requiredReviewerRole}'`);
@@ -35,9 +35,11 @@ function getHybridPaths(options = {}) {
35
35
  feedbackDir: options.feedbackDir,
36
36
  home: options.home,
37
37
  });
38
+ const feedbackLog = options.feedbackLogPath || process.env.THUMBGATE_FEEDBACK_LOG || path.join(feedbackDir, 'feedback-log.jsonl');
38
39
  return {
39
40
  feedbackDir,
40
- feedbackLog: path.join(feedbackDir, 'feedback-log.jsonl'),
41
+ graphFeedbackDir: options.feedbackDir || path.dirname(feedbackLog),
42
+ feedbackLog,
41
43
  inbox: path.join(feedbackDir, 'inbox.jsonl'),
42
44
  pendingSync: path.join(feedbackDir, 'pending_cortex_sync.jsonl'),
43
45
  attributedFeedback: path.join(feedbackDir, 'attributed-feedback.jsonl'),
@@ -321,10 +323,33 @@ function buildHybridState(opts) {
321
323
  const pendingSyncPath = o.pendingSyncPath || process.env.THUMBGATE_PENDING_SYNC || paths.pendingSync;
322
324
  const attributedFeedbackPath = o.attributedFeedbackPath || process.env.THUMBGATE_ATTRIBUTED_FEEDBACK || paths.attributedFeedback;
323
325
 
324
- const feedbackEntries = readJsonl(feedbackLogPath, HYBRID_JSONL_READ_LIMIT);
325
- const inboxEntries = readJsonl(inboxPath, HYBRID_JSONL_READ_LIMIT);
326
- const pendingSyncEntries = readJsonl(pendingSyncPath, HYBRID_JSONL_READ_LIMIT);
327
- const attributedEntries = readJsonl(attributedFeedbackPath, HYBRID_JSONL_READ_LIMIT);
326
+ const { selectRecordsForScope } = require('./memory-scope-readiness');
327
+ if (o.requireScope && !o.scope) throw new Error('Scoped hybrid state requires scope');
328
+ const readEntries = file => {
329
+ const rows = readJsonl(file, HYBRID_JSONL_READ_LIMIT);
330
+ return o.scope ? selectRecordsForScope(rows, o.scope, { includeShared: o.includeShared !== false }).allowed : rows;
331
+ };
332
+ const feedbackEntries = readEntries(feedbackLogPath);
333
+ const inboxEntries = readEntries(inboxPath);
334
+ const pendingSyncEntries = readEntries(pendingSyncPath);
335
+ const attributedEntries = readEntries(attributedFeedbackPath);
336
+ const graph = require('./lesson-graph');
337
+ const graphOptions = { feedbackDir: paths.graphFeedbackDir };
338
+ const graphDb = graph.openGraphDBIfExists(graphOptions);
339
+ const identities = new Map();
340
+ let provenance = null;
341
+ try {
342
+ if (graphDb) graphDb.transaction(() => {
343
+ for (const entry of [...feedbackEntries, ...inboxEntries, ...pendingSyncEntries, ...attributedEntries]) {
344
+ identities.set(entry, JSON.stringify([graph.scopeKey(entry), graph.feedbackIdentity(graphDb, entry) || hashText(JSON.stringify(entry))]));
345
+ }
346
+ provenance = graph.graphProvenance(graphOptions, graphDb);
347
+ })();
348
+ } finally {
349
+ if (graphDb) graphDb.close();
350
+ }
351
+ const enforcementSeen = new Set();
352
+ const attributedSeen = new Set();
328
353
 
329
354
  // Deduplicate by id across all sources
330
355
  const seen = new Set();
@@ -354,6 +379,9 @@ function buildHybridState(opts) {
354
379
  // History-sync fallback and gate logs still count as events, but they must
355
380
  // not become recurring "Avoid" constraints injected on every PreToolUse.
356
381
  if (isAutomatedFeedback(entry)) continue;
382
+ const identity = identities.get(entry);
383
+ if (identity && enforcementSeen.has(identity)) continue;
384
+ if (identity) enforcementSeen.add(identity);
357
385
 
358
386
  const toolName = inferToolName(entry.toolName || entry.tool_name || 'unknown', entry.context || '');
359
387
  toolNegatives[toolName] = (toolNegatives[toolName] || 0) + 1;
@@ -398,6 +426,11 @@ function buildHybridState(opts) {
398
426
  for (const entry of attributedEntries) {
399
427
  if (classify(entry) !== 'negative') continue; // skip pruned/positive
400
428
  if (isAutomatedFeedback(entry)) continue; // skip automated gate blocks
429
+ const identity = identities.get(entry);
430
+ if (identity && attributedSeen.has(identity)) continue;
431
+ if (identity) attributedSeen.add(identity);
432
+ const alreadyCounted = identity && enforcementSeen.has(identity);
433
+ if (identity) enforcementSeen.add(identity);
401
434
  const toolName = inferToolName(entry.toolName || entry.tool_name || entry.attributed_tool || 'unknown', entry.context || '');
402
435
  toolNegativesAttributed[toolName] = (toolNegativesAttributed[toolName] || 0) + 1;
403
436
 
@@ -433,7 +466,7 @@ function buildHybridState(opts) {
433
466
  if (!patternMap[patKey].sources.includes('attributedFeedback')) {
434
467
  patternMap[patKey].sources.push('attributedFeedback');
435
468
  }
436
- patternMap[patKey].count++;
469
+ if (!alreadyCounted) patternMap[patKey].count++;
437
470
  const ts = getTimestampMs(entry.timestamp);
438
471
  if (ts > patternMap[patKey].lastSeen) patternMap[patKey].lastSeen = ts;
439
472
  }
@@ -450,6 +483,8 @@ function buildHybridState(opts) {
450
483
  .filter(Boolean);
451
484
 
452
485
  return {
486
+ graphScope: o.scope ? JSON.stringify([graph.scopeKey(o.scope), o.includeShared !== false]) : null,
487
+ graphProvenance: provenance,
453
488
  counts: { total, positive, negative },
454
489
  recurringNegativePatterns,
455
490
  preventionRules,
@@ -706,6 +741,8 @@ function compileGuardArtifact(state, opts) {
706
741
  });
707
742
 
708
743
  return {
744
+ graphScope: state.graphScope || null,
745
+ graphProvenance: state.graphProvenance || null,
709
746
  compiledAt: new Date().toISOString(),
710
747
  guardCount: guards.length,
711
748
  blockThreshold,
@@ -884,7 +921,11 @@ function evaluatePretool(toolName, toolInput, opts) {
884
921
  // Fast path: compiled artifact
885
922
  const artifactPath = o.guardArtifactPath || process.env.THUMBGATE_GUARDS_PATH || getHybridPaths(o).guardArtifact;
886
923
  const artifact = readGuardArtifact(artifactPath);
887
- if (artifact) {
924
+ const graph = require('./lesson-graph');
925
+ if ((o.requireScope && !o.scope) || (o.scope && !graph.scopeKey(o.scope))) throw new Error('Scoped hybrid evaluation requires complete scope');
926
+ const graphScope = o.scope ? JSON.stringify([graph.scopeKey(o.scope), o.includeShared !== false]) : null;
927
+ const provenance = graph.graphProvenance({ feedbackDir: getHybridPaths(o).graphFeedbackDir });
928
+ if (artifact && provenance !== 'unavailable' && (artifact.graphProvenance || null) === provenance && (artifact.graphScope || null) === graphScope) {
888
929
  const result = evaluateCompiledGuards(artifact, toolName, toolInput);
889
930
  if (result.mode !== 'allow') return result;
890
931
 
@@ -900,6 +941,11 @@ function evaluatePretool(toolName, toolInput, opts) {
900
941
 
901
942
  // Slow path: build live state (also used when compiled guards are stale)
902
943
  const state = buildHybridState({
944
+ scope: o.scope,
945
+ requireScope: o.requireScope,
946
+ includeShared: o.includeShared,
947
+ inboxPath: o.inboxPath,
948
+ pendingSyncPath: o.pendingSyncPath,
903
949
  feedbackDir: o.feedbackDir,
904
950
  feedbackLogPath: o.feedbackLogPath,
905
951
  attributedFeedbackPath: o.attributedFeedbackPath,