thumbgate 1.29.2 → 1.30.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 (55) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/adapters/claude/.mcp.json +2 -2
  4. package/adapters/forge/forge.yaml +3 -3
  5. package/adapters/mcp/server-stdio.js +78 -7
  6. package/adapters/opencode/opencode.json +1 -1
  7. package/bin/cli.js +7 -5
  8. package/config/mcp-allowlists.json +26 -2
  9. package/config/post-deploy-marketing-pages.json +26 -1
  10. package/package.json +38 -7
  11. package/public/architecture.html +130 -0
  12. package/public/assets/diagrams/agent-integration.png +0 -0
  13. package/public/assets/diagrams/before-after.svg +21 -0
  14. package/public/assets/diagrams/decision.svg +36 -0
  15. package/public/assets/diagrams/feedback-pipeline.png +0 -0
  16. package/public/assets/diagrams/loop.svg +34 -0
  17. package/public/assets/diagrams/plugin-topology.png +0 -0
  18. package/public/assets/diagrams/pre-action-gate-loop.svg +59 -0
  19. package/public/assets/diagrams/stack.svg +18 -0
  20. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  21. package/public/case-studies.html +151 -0
  22. package/public/eval-scorecard.html +195 -0
  23. package/public/eval-scorecard.json +18 -0
  24. package/public/evaluations.html +168 -0
  25. package/public/index.html +4 -3
  26. package/public/numbers.html +2 -2
  27. package/public/whitepaper.html +189 -0
  28. package/scripts/activation-quickstart.js +1 -0
  29. package/scripts/agent-outcome-monitor.js +71 -1
  30. package/scripts/billing.js +3 -1
  31. package/scripts/claude-feedback-sync.js +3 -2
  32. package/scripts/cli-feedback.js +13 -7
  33. package/scripts/cross-encoder-reranker.js +3 -0
  34. package/scripts/feedback-aggregate.js +5 -2
  35. package/scripts/feedback-loop.js +244 -182
  36. package/scripts/gates-engine.js +81 -4
  37. package/scripts/generate-case-study-outreach.js +253 -0
  38. package/scripts/generate-eval-scorecard.js +276 -0
  39. package/scripts/growth-campaigns.js +183 -0
  40. package/scripts/jsonl-watcher.js +1 -0
  41. package/scripts/lesson-inference.js +23 -4
  42. package/scripts/lesson-retrieval.js +71 -4
  43. package/scripts/lesson-search.js +26 -3
  44. package/scripts/mcp-config.js +26 -5
  45. package/scripts/mcp-oauth.js +37 -2
  46. package/scripts/model-eval.js +308 -0
  47. package/scripts/parallel-workflow-orchestrator.js +86 -22
  48. package/scripts/published-cli.js +11 -1
  49. package/scripts/refresh-proof-pack.js +261 -0
  50. package/scripts/risk-scorer.js +144 -15
  51. package/scripts/statusline-local-stats.js +1 -1
  52. package/scripts/thumbgate-bench.js +13 -0
  53. package/scripts/tool-kpi-tracker.js +124 -0
  54. package/scripts/tool-registry.js +49 -1
  55. package/src/api/server.js +230 -86
@@ -5,6 +5,7 @@ const fs = require('fs');
5
5
  const path = require('path');
6
6
  const { resolveFeedbackDir: resolveSharedFeedbackDir } = require('./feedback-paths');
7
7
  const { requireLearnedModelsEntitlement } = require('./entitlement');
8
+ const { stratifiedSplit, evaluate, roundReport } = require('./model-eval');
8
9
 
9
10
  const PROJECT_ROOT = path.join(__dirname, '..');
10
11
  const DEFAULT_FEEDBACK_DIR = resolveSharedFeedbackDir();
@@ -187,10 +188,16 @@ function stumpPredict(value, threshold, polarity) {
187
188
  return decision * polarity;
188
189
  }
189
190
 
190
- function findBestWeakLearner(examples, weights, featureNames) {
191
+ function findBestWeakLearner(examples, weights, featureNames, options = {}) {
192
+ const usage = options.usage || null;
193
+ const maxPerFeature = Number(options.maxPerFeature || Infinity);
191
194
  let best = null;
192
195
 
193
196
  featureNames.forEach((feature) => {
197
+ // Diversity bound: once a feature has been split on maxPerFeature times, later rounds must
198
+ // find signal elsewhere or stop. Off by default (Infinity) so existing behaviour is bit
199
+ // identical unless a caller opts in.
200
+ if (usage && Number.isFinite(maxPerFeature) && (usage.get(feature) || 0) >= maxPerFeature) return;
194
201
  const values = examples.map((example) => example.features[feature]);
195
202
  const thresholds = candidateThresholds(values);
196
203
  thresholds.forEach((threshold) => {
@@ -268,18 +275,14 @@ function buildPatternSummary(rows) {
268
275
  };
269
276
  }
270
277
 
271
- function trainRiskModel(rows, options = {}) {
272
- requireLearnedModelsEntitlement({
273
- ...(options.entitlement || {}),
274
- label: 'risk-scorer AdaBoost training',
275
- });
276
- const registry = buildFeatureRegistry(rows, options);
277
- const examples = rows.map((row) => ({
278
- row,
279
- label: deriveTargetRisk(row) === 1 ? 1 : -1,
280
- features: extractFeatureMap(row, registry),
281
- }));
282
-
278
+ /**
279
+ * Fit the ensemble on a given set of examples.
280
+ *
281
+ * Extracted from trainRiskModel so that the held-out probe below is fitted by IDENTICAL code.
282
+ * If the probe were trained by a separate path, its score would describe a model we do not
283
+ * ship, and the resulting "generalization" number would be fiction.
284
+ */
285
+ function fitBoostedModel(examples, registry, options = {}) {
283
286
  const model = {
284
287
  version: 1,
285
288
  algorithm: 'adaboost-stumps',
@@ -292,7 +295,7 @@ function trainRiskModel(rows, options = {}) {
292
295
  featureRegistry: registry,
293
296
  featureNames: examples[0] ? Object.keys(examples[0].features) : [],
294
297
  learners: [],
295
- patterns: buildPatternSummary(rows),
298
+ patterns: options.patterns || { tags: [], domains: [], skills: [] },
296
299
  metrics: {
297
300
  trainingAccuracy: 0,
298
301
  rounds: 0,
@@ -307,9 +310,16 @@ function trainRiskModel(rows, options = {}) {
307
310
 
308
311
  let weights = normalizeWeights(Array(examples.length).fill(1));
309
312
  const rounds = Math.max(1, Math.min(12, Number(options.rounds || 8)));
313
+ // Boosting is free to pick the same feature every round. On the real corpus it did exactly
314
+ // that — six of eight stumps split on `recentTrend`, so an "ensemble" was in practice a
315
+ // one-feature model of how the session had been going lately. maxPerFeature bounds that.
316
+ // Default is Infinity (historical behaviour); enabling it is an evidence-based decision made
317
+ // by comparing held-out lift, not an assumption. See docs/ML-EVALUATION.md.
318
+ const maxPerFeature = Number(options.maxPerFeature || Infinity);
319
+ const usage = new Map();
310
320
 
311
321
  for (let round = 0; round < rounds; round += 1) {
312
- const learner = findBestWeakLearner(examples, weights, model.featureNames);
322
+ const learner = findBestWeakLearner(examples, weights, model.featureNames, { usage, maxPerFeature });
313
323
  if (!learner) break;
314
324
 
315
325
  const clippedError = Math.min(Math.max(learner.error, 1e-6), 1 - 1e-6);
@@ -322,6 +332,7 @@ function trainRiskModel(rows, options = {}) {
322
332
  polarity: learner.polarity,
323
333
  alpha: Math.round(alpha * 1000) / 1000,
324
334
  });
335
+ usage.set(learner.feature, (usage.get(learner.feature) || 0) + 1);
325
336
 
326
337
  weights = normalizeWeights(weights.map((weight, index) => (
327
338
  weight * Math.exp(-alpha * examples[index].label * learner.predictions[index])
@@ -334,6 +345,119 @@ function trainRiskModel(rows, options = {}) {
334
345
  return model;
335
346
  }
336
347
 
348
+ /** Score a fitted model over examples as (probability, label) pairs for model-eval. */
349
+ function scorePairs(model, examples) {
350
+ return examples.map((example) => ({
351
+ probability: predictRisk(model, example.row).probability,
352
+ label: example.label === 1 ? 1 : 0,
353
+ }));
354
+ }
355
+
356
+ /**
357
+ * Held-out estimate of what this training procedure generalizes to.
358
+ *
359
+ * Split on CONTENT, not position or an RNG. Content hashing gives two properties we need:
360
+ * the split is reproducible on every machine, and near-duplicate rows (which this corpus has
361
+ * plenty of, since similar actions recur) land in the SAME fold instead of leaking an answer
362
+ * from train into test and inflating the score.
363
+ */
364
+ function holdoutEvaluation(examples, registry, options = {}) {
365
+ const { train, test } = stratifiedSplit(examples, {
366
+ testFraction: Number(options.testFraction || 0.25),
367
+ // splitSalt exists so the SAME corpus can be re-split many ways for repeated-resampling
368
+ // validation. A single split of a few hundred rows cannot distinguish a real improvement
369
+ // from sampling noise, and picking a configuration on one split is how you overfit the
370
+ // validation set itself.
371
+ // Key on the extracted feature vector ALONE. The model observes nothing else, so two rows
372
+ // with identical features are the same input to it and must share a fold. An earlier
373
+ // version also mixed in the raw `context` string, which split rows whose different prose
374
+ // maps to identical features — recreating the very leakage this splitter exists to stop.
375
+ keyFn: options.groupKeyFn
376
+ ? (example) => JSON.stringify([options.splitSalt || '', options.groupKeyFn(example)])
377
+ : (example) => JSON.stringify([options.splitSalt || '', example.features]),
378
+ });
379
+
380
+ // Saying "not measurable" is the honest output for a corpus too small or too one-sided to
381
+ // hold anything out. Reporting a number here would be worse than reporting nothing.
382
+ if (test.length === 0 || train.length < 6) {
383
+ return { available: false, reason: 'corpus-too-small-or-single-class' };
384
+ }
385
+
386
+ // REBUILD THE VOCABULARY FROM THE TRAINING FOLD ONLY.
387
+ //
388
+ // buildFeatureRegistry picks top tags and skills by frequency. Deriving it from the whole
389
+ // corpus lets held-out rows decide which features exist — a transductive fit. The probe would
390
+ // see vocabulary chosen with knowledge of the test fold, and the "held-out" number would then
391
+ // describe a procedure we never run in production. Registry and features come from train only.
392
+ const foldRegistry = buildFeatureRegistry(train.map((example) => example.row), options);
393
+ const trainRefit = train.map((example) => ({
394
+ row: example.row,
395
+ label: example.label,
396
+ features: extractFeatureMap(example.row, foldRegistry),
397
+ }));
398
+
399
+ const probe = fitBoostedModel(trainRefit, foldRegistry, { ...options, patterns: undefined });
400
+ // Test rows are scored via predictRisk, which extracts features using the probe's OWN
401
+ // registry — so the test fold is judged under exactly the vocabulary the probe learned.
402
+ const report = evaluate(scorePairs(probe, test));
403
+ return {
404
+ available: true,
405
+ trainCount: train.length,
406
+ testCount: test.length,
407
+ ...roundReport(report),
408
+ };
409
+ }
410
+
411
+ function trainRiskModel(rows, options = {}) {
412
+ requireLearnedModelsEntitlement({
413
+ ...(options.entitlement || {}),
414
+ label: 'risk-scorer AdaBoost training',
415
+ });
416
+ const registry = buildFeatureRegistry(rows, options);
417
+ const examples = rows.map((row) => ({
418
+ row,
419
+ label: deriveTargetRisk(row) === 1 ? 1 : -1,
420
+ features: extractFeatureMap(row, registry),
421
+ }));
422
+
423
+ const model = fitBoostedModel(examples, registry, {
424
+ ...options,
425
+ patterns: buildPatternSummary(rows),
426
+ });
427
+
428
+ // The shipped model is fitted on everything — that is the right thing to deploy. The probe
429
+ // above estimates what that procedure generalizes to. Both numbers are recorded, and
430
+ // `inSample` is labelled as such so it can never again be quoted as if it were quality.
431
+ model.metrics.inSample = roundReport(evaluate(scorePairs(model, examples)));
432
+ if (options.skipHoldout !== true) {
433
+ // TWO held-out estimates, because they answer different questions and only reporting the
434
+ // friendlier one would repeat the original sin of this file.
435
+ //
436
+ // holdout — IID split on the full feature vector. "Does this work on new
437
+ // rows of the kinds we have seen?" Measured 2026-07-28: +0.091
438
+ // lift, AUC 0.884, 12/12 resamples beat baseline.
439
+ //
440
+ // holdoutNovelContext — split by coarse content group, so whole action categories are
441
+ // absent from training. "Does this work on kinds of actions we
442
+ // have never seen?" Measured: NEGATIVE lift.
443
+ //
444
+ // For a firewall the second question is the one that matters most — novel attacks are by
445
+ // definition unfamiliar — so the pessimistic number is recorded next to the optimistic one
446
+ // permanently, and docs/ML-EVALUATION.md explains the gap.
447
+ model.metrics.holdout = holdoutEvaluation(examples, registry, options);
448
+ model.metrics.holdoutNovelContext = holdoutEvaluation(examples, registry, {
449
+ ...options,
450
+ groupKeyFn: (example) => JSON.stringify([
451
+ example.row && example.row.context,
452
+ example.row && example.row.domain,
453
+ example.row && example.row.skill,
454
+ example.row && example.row.targetTags,
455
+ ]),
456
+ });
457
+ }
458
+ return model;
459
+ }
460
+
337
461
  function rawScore(model, row) {
338
462
  if (!model || !model.featureRegistry) {
339
463
  return 0;
@@ -457,6 +581,11 @@ module.exports = {
457
581
  trainAndPersistRiskModel,
458
582
  trainRiskModel,
459
583
  getRiskSummary,
584
+ // Exported for the evaluation harness (scripts/eval-risk-model.js) and its tests: measuring
585
+ // this model requires fitting it on a fold, which requires reaching the fit step directly.
586
+ fitBoostedModel,
587
+ holdoutEvaluation,
588
+ scorePairs,
460
589
  };
461
590
 
462
591
  if (require.main === module) {
@@ -16,7 +16,7 @@ try {
16
16
  const scope = String(process.env.THUMBGATE_STATUSLINE_SCOPE || 'global').toLowerCase();
17
17
  const stats = scope !== 'project' && shouldAggregateFeedback({ env: process.env })
18
18
  ? computeAggregateFeedbackStats({ projectDir, env: process.env })
19
- : analyzeFeedback();
19
+ : analyzeFeedback(undefined, { humanOnly: true });
20
20
  const payload = {
21
21
  ...normalizeStatsPayload(stats),
22
22
  aggregate: stats.aggregate || { enabled: false },
@@ -268,6 +268,13 @@ function withGateRuntime(options, callback) {
268
268
  'THUMBGATE_SECRET_SCAN_PROVIDER',
269
269
  'THUMBGATE_HARNESS',
270
270
  'THUMBGATE_HARNESS_CONFIG',
271
+ // Isolated bench must not inherit operator license / posture / daily-cap state.
272
+ // Without strict enforcement, deny expectations become warn-by-default and the
273
+ // published scorecard is unreproducible on a clean free-tier install.
274
+ 'THUMBGATE_STRICT_ENFORCEMENT',
275
+ 'THUMBGATE_ENFORCE_ENTITLEMENTS',
276
+ 'THUMBGATE_PRO_LICENSE_KEY',
277
+ 'THUMBGATE_LICENSE_KEY',
271
278
  ]);
272
279
  const runtimeDir = options.useRuntimeState
273
280
  ? null
@@ -289,6 +296,12 @@ function withGateRuntime(options, callback) {
289
296
  process.env.THUMBGATE_ATTRIBUTED_FEEDBACK = path.join(runtimeDir, 'attributed-feedback.jsonl');
290
297
  process.env.THUMBGATE_GUARDS_PATH = path.join(runtimeDir, 'pretool-guards.json');
291
298
  process.env.THUMBGATE_SECRET_SCAN_PROVIDER = 'heuristic';
299
+ // Pin enforcement posture for golden deny expectations (scorecard reproducibility).
300
+ process.env.THUMBGATE_STRICT_ENFORCEMENT = '1';
301
+ // Do not hard-fail free-tier installs; isolation already avoids daily-cap state.
302
+ delete process.env.THUMBGATE_ENFORCE_ENTITLEMENTS;
303
+ delete process.env.THUMBGATE_PRO_LICENSE_KEY;
304
+ delete process.env.THUMBGATE_LICENSE_KEY;
292
305
  fs.mkdirSync(process.env.THUMBGATE_FEEDBACK_DIR, { recursive: true });
293
306
  fs.writeFileSync(process.env.THUMBGATE_FEEDBACK_LOG, '');
294
307
  fs.writeFileSync(process.env.THUMBGATE_ATTRIBUTED_FEEDBACK, '');
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { resolveFeedbackDir } = require('./feedback-paths');
8
+ const { readJsonl } = require('./fs-utils');
9
+
10
+ function getKpiLogPath(options = {}) {
11
+ return path.join(
12
+ options.feedbackDir ? path.resolve(options.feedbackDir) : resolveFeedbackDir(),
13
+ 'tool-kpi.jsonl',
14
+ );
15
+ }
16
+
17
+ function recordToolCall({
18
+ toolName,
19
+ serverName,
20
+ latencyMs,
21
+ success,
22
+ agentId,
23
+ metadata,
24
+ feedbackDir,
25
+ } = {}) {
26
+ const logPath = getKpiLogPath({ feedbackDir });
27
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
28
+ const entry = {
29
+ id: `kpi_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`,
30
+ timestamp: new Date().toISOString(),
31
+ toolName: toolName || 'unknown',
32
+ serverName: serverName || 'default',
33
+ latencyMs: typeof latencyMs === 'number' ? latencyMs : 0,
34
+ success: success !== false,
35
+ agentId: agentId || 'unknown',
36
+ metadata: metadata || {},
37
+ };
38
+ fs.appendFileSync(logPath, `${JSON.stringify(entry)}\n`);
39
+ return entry;
40
+ }
41
+
42
+ function percentile(sorted, quantile) {
43
+ if (sorted.length === 0) return 0;
44
+ const index = Math.ceil((quantile / 100) * sorted.length) - 1;
45
+ return sorted[Math.max(0, index)];
46
+ }
47
+
48
+ function computeToolKpis({ periodHours = 24, feedbackDir } = {}) {
49
+ const entries = readJsonl(getKpiLogPath({ feedbackDir }));
50
+ const cutoff = Date.now() - periodHours * 60 * 60 * 1000;
51
+ const recent = entries.filter((entry) => new Date(entry.timestamp).getTime() > cutoff);
52
+ const byTool = {};
53
+ for (const entry of recent) {
54
+ const key = entry.toolName;
55
+ if (!byTool[key]) {
56
+ byTool[key] = {
57
+ toolName: key,
58
+ calls: [],
59
+ successes: 0,
60
+ failures: 0,
61
+ };
62
+ }
63
+ byTool[key].calls.push(entry.latencyMs);
64
+ if (entry.success) byTool[key].successes += 1;
65
+ else byTool[key].failures += 1;
66
+ }
67
+ const tools = Object.values(byTool)
68
+ .map((tool) => {
69
+ const sorted = tool.calls.slice().sort((left, right) => left - right);
70
+ const total = tool.successes + tool.failures;
71
+ return {
72
+ toolName: tool.toolName,
73
+ requestCount: total,
74
+ successRate: total > 0 ? Math.round((tool.successes / total) * 1000) / 10 : 100,
75
+ p50: Math.round(percentile(sorted, 50)),
76
+ p90: Math.round(percentile(sorted, 90)),
77
+ p95: Math.round(percentile(sorted, 95)),
78
+ successes: tool.successes,
79
+ failures: tool.failures,
80
+ };
81
+ })
82
+ .sort((left, right) => right.requestCount - left.requestCount);
83
+
84
+ const byServer = {};
85
+ for (const entry of recent) {
86
+ const key = entry.serverName;
87
+ if (!byServer[key]) byServer[key] = { serverName: key, total: 0, successes: 0 };
88
+ byServer[key].total += 1;
89
+ if (entry.success) byServer[key].successes += 1;
90
+ }
91
+ const servers = Object.values(byServer).map((server) => ({
92
+ serverName: server.serverName,
93
+ totalCalls: server.total,
94
+ successRate: server.total > 0
95
+ ? Math.round((server.successes / server.total) * 1000) / 10
96
+ : 100,
97
+ }));
98
+ return {
99
+ periodHours,
100
+ totalCalls: recent.length,
101
+ evidenceStatus: recent.length > 0 ? 'measured' : 'insufficient_evidence',
102
+ tools,
103
+ servers,
104
+ };
105
+ }
106
+
107
+ function getAtRiskTools({
108
+ successRateThreshold = 90,
109
+ p95Threshold = 500,
110
+ periodHours = 24,
111
+ feedbackDir,
112
+ } = {}) {
113
+ const { tools } = computeToolKpis({ periodHours, feedbackDir });
114
+ return tools.filter((tool) => tool.requestCount >= 3
115
+ && (tool.successRate < successRateThreshold || tool.p95 > p95Threshold));
116
+ }
117
+
118
+ module.exports = {
119
+ computeToolKpis,
120
+ getAtRiskTools,
121
+ getKpiLogPath,
122
+ percentile,
123
+ recordToolCall,
124
+ };
@@ -133,8 +133,20 @@ const TASK_OUTCOME_INPUT_SCHEMA = {
133
133
  },
134
134
  };
135
135
 
136
+ const MEMORY_SCOPE_SCHEMA = {
137
+ type: 'object',
138
+ additionalProperties: false,
139
+ required: ['entityId', 'projectId', 'processId', 'sessionId'],
140
+ properties: {
141
+ entityId: { type: 'string', minLength: 1 },
142
+ projectId: { type: 'string', minLength: 1 },
143
+ processId: { type: 'string', minLength: 1 },
144
+ sessionId: { type: 'string', minLength: 1 },
145
+ },
146
+ };
147
+
136
148
  const TOOLS = [
137
- readOnlyTool({
149
+ destructiveTool({
138
150
  name: 'capture_feedback',
139
151
  description: 'Capture an up/down signal plus one line of why. Vague feedback is logged, then returned with a clarification prompt instead of memory promotion.',
140
152
  inputSchema: {
@@ -218,6 +230,9 @@ const TOOLS = [
218
230
  limit: { type: 'number', description: 'Maximum results to return (default 10)' },
219
231
  category: { type: 'string', enum: ['error', 'learning', 'preference'] },
220
232
  tags: { type: 'array', items: { type: 'string' }, description: 'Require all tags to be present on a lesson' },
233
+ scope: MEMORY_SCOPE_SCHEMA,
234
+ requireScope: { type: 'boolean', description: 'Fail closed unless a complete four-field scope is supplied.' },
235
+ includeShared: { type: 'boolean', description: 'Include explicitly shared memories with scoped results. Defaults true.' },
221
236
  },
222
237
  },
223
238
  }),
@@ -230,6 +245,9 @@ const TOOLS = [
230
245
  toolName: { type: 'string', description: 'The tool being called (e.g., Bash, Edit, Read)' },
231
246
  actionContext: { type: 'string', description: 'Description of what the tool call is doing' },
232
247
  maxResults: { type: 'number', description: 'Max lessons to return (default 5)' },
248
+ scope: MEMORY_SCOPE_SCHEMA,
249
+ requireScope: { type: 'boolean', description: 'Fail closed unless a complete four-field scope is supplied.' },
250
+ includeShared: { type: 'boolean', description: 'Include explicitly shared memories with scoped results. Defaults true.' },
233
251
  },
234
252
  required: ['toolName'],
235
253
  },
@@ -904,6 +922,10 @@ const TOOLS = [
904
922
  items: { type: 'string' },
905
923
  description: 'Optional protected-file globs that require explicit approval before editing or publishing',
906
924
  },
925
+ ttlMs: {
926
+ type: 'number',
927
+ description: 'Optional lease length in milliseconds. With it the scope becomes time-bounded authority (e.g. 90000 for "write under ./src for 90 seconds") and FAILS CLOSED on expiry: a lapsed lease authorises nothing until renewed. Omit for a permanent scope. Clamped to 60s..24h.',
928
+ },
907
929
  workflowContract: {
908
930
  type: 'object',
909
931
  description: 'Optional deterministic workflow run contract. Supports workflowId, allowedBranches, blockedActions, requiredEvidence, and completionGate.',
@@ -1047,6 +1069,16 @@ const TOOLS = [
1047
1069
  title: 'Record Verified Task Outcome',
1048
1070
  description: 'Record an idempotent task-level outcome with verification evidence, tool correctness, policy behavior, latency, cost, and business KPI movement. A completed response without evidence is recorded as not working.',
1049
1071
  inputSchema: TASK_OUTCOME_INPUT_SCHEMA,
1072
+ outputSchema: {
1073
+ type: 'object',
1074
+ additionalProperties: false,
1075
+ required: ['recorded', 'duplicate', 'receipt'],
1076
+ properties: {
1077
+ recorded: { type: 'boolean' },
1078
+ duplicate: { type: 'boolean' },
1079
+ receipt: { type: 'object', additionalProperties: true },
1080
+ },
1081
+ },
1050
1082
  }),
1051
1083
  readOnlyTool({
1052
1084
  name: 'get_task_outcomes',
@@ -1070,6 +1102,22 @@ const TOOLS = [
1070
1102
  additionalProperties: false,
1071
1103
  properties: {},
1072
1104
  },
1105
+ outputSchema: {
1106
+ type: 'object',
1107
+ additionalProperties: true,
1108
+ required: ['generatedAt', 'sampleSize', 'evidenceStatus', 'task', 'tools', 'safety', 'escalation', 'efficiency', 'businessOutcomes'],
1109
+ properties: {
1110
+ generatedAt: { type: 'string', format: 'date-time' },
1111
+ sampleSize: { type: 'integer', minimum: 0 },
1112
+ evidenceStatus: { type: 'string', enum: ['measured', 'insufficient_evidence'] },
1113
+ task: { type: 'object', additionalProperties: true },
1114
+ tools: { type: 'object', additionalProperties: true },
1115
+ safety: { type: 'object', additionalProperties: true },
1116
+ escalation: { type: 'object', additionalProperties: true },
1117
+ efficiency: { type: 'object', additionalProperties: true },
1118
+ businessOutcomes: { type: 'array' },
1119
+ },
1120
+ },
1073
1121
  }),
1074
1122
  destructiveTool({
1075
1123
  name: 'request_human_escalation',