thumbgate 1.39.1 → 1.40.2

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 (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -1,42 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- /**
5
- * agent-action-inventory.js — "what did the agents actually do here?"
6
- *
7
- * WHY THIS EXISTS
8
- * ---------------
9
- * ThumbGate already records gate decisions (`audit-trail.jsonl`), gate firings
10
- * (`gate-events-log.jsonl`) and per-tool KPIs (`tool-kpi.jsonl`). What it did
11
- * not have is one read-only rollup an operator can point at a repo and get:
12
- * which agents ran, which tools they reached for, how much was allowed, how
13
- * much was blocked, by which gate, on which day — and how often a block was
14
- * later reversed (the false-deny signal).
15
- *
16
- * TWO HONESTY RULES THIS FILE ENFORCES
17
- * ------------------------------------
18
- * 1. A missing source and an empty source are DIFFERENT facts and must look
19
- * different in the output. `sources.auditTrail === 'missing'` means the file
20
- * is not there; `'empty'` means it is there and holds nothing. Reporting
21
- * both as `0` would let "we never instrumented this" masquerade as "the
22
- * agents did nothing".
23
- * 2. `falseDenyRate` is null unless a real numerator AND a real denominator
24
- * were observed. A rate over zero denies is an invented denominator, so it
25
- * stays null and `falseDenyReason` says why. `falseDenyNumerator` and
26
- * `falseDenyDenominator` are always present so a reader can redo the math.
27
- *
28
- * All functions here are read-only. Nothing in this module writes to the store.
29
- */
4
+ // Read-only rollup + 30-day AI governance system of record over audit-trail, gate-events, tool-kpi, and agent-registry.
30
5
 
31
6
  const fs = require('node:fs');
7
+ const os = require('node:os');
32
8
  const path = require('node:path');
33
9
 
34
- // Filenames come from the modules that own the writes, so a rename there can
35
- // never silently turn this report into a "source missing" false negative.
36
- const { AUDIT_LOG_FILENAME, GATE_EVENTS_LOG_FILENAME } = require('./audit-trail');
37
-
38
- // scripts/tool-kpi-tracker.js writes this; it is the only store in the feedback
39
- // dir that carries an agentId, which is why agent identity comes from here.
10
+ const { AUDIT_LOG_FILENAME, GATE_EVENTS_LOG_FILENAME, REGISTRY_FILENAME, OBSERVED_FILENAME } = require('./audit-trail');
40
11
  const KPI_LOG_FILENAME = 'tool-kpi.jsonl';
41
12
 
42
13
  const MIN_WINDOW_DAYS = 1;
@@ -45,31 +16,7 @@ const DEFAULT_WINDOW_DAYS = 30;
45
16
 
46
17
  const DENY_DECISION = 'deny';
47
18
 
48
- /**
49
- * WHAT COUNTS AS A REVERSAL — and the trap that makes this subtle.
50
- *
51
- * Only two record shapes in audit-trail.jsonl mean "a block was actually cleared":
52
- *
53
- * 1. decision === 'override'
54
- * Written by scripts/override-audit.js for satisfy_gate, the CLI
55
- * satisfyCondition path, and break-glass. Always carries the cleared gateId.
56
- *
57
- * 2. decision === 'allow' AND source === 'gates-engine-admin-override'
58
- * Written by gates-engine.js when a single-use admin override is CONSUMED
59
- * against a blocking gate. The decision field reads 'allow' — the reversal
60
- * is identifiable only by the source.
61
- *
62
- * `decision: 'approve'` is NOT a reversal, despite the name. gates-engine.js
63
- * emits it when a gate's action is 'approve' and the action needs human
64
- * sign-off: it ships alongside `requiresApproval: true`, formatOutput renders it
65
- * to the harness as `permissionDecision: 'deny'` with "APPROVAL REQUIRED",
66
- * isBlockingDecision() groups it with 'deny', and recordStat files it under
67
- * `pendingApproval`. It is a HELD action — another kind of block.
68
- *
69
- * Counting 'approve' as a clearance inflates the false-deny numerator with
70
- * records that are themselves blocks. It is reported separately as
71
- * `approvalRequiredCount` and never enters the numerator.
72
- */
19
+ // Only decision==='override' or consumed admin-override ('allow' + ADMIN_OVERRIDE_SOURCE) clears a block; 'approve' is a held block.
73
20
  const CLEARING_DECISION = 'override';
74
21
  const ADMIN_OVERRIDE_SOURCE = 'gates-engine-admin-override';
75
22
  const APPROVAL_REQUIRED_DECISION = 'approve';
@@ -106,29 +53,7 @@ function normalizeWindowDays(input) {
106
53
  // Source reading
107
54
  // ---------------------------------------------------------------------------
108
55
 
109
- /**
110
- * Default tail window per source. Matches scripts/override-audit.js, which
111
- * reads the tail rather than the whole file because audit logs reach hundreds
112
- * of MB and a report must not allocate the entire history to summarise it.
113
- */
114
56
  const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
115
-
116
- /**
117
- * Read one JSONL store and report WHY it produced the records it did.
118
- *
119
- * Reads at most `maxBytes` from the END of the file, following the
120
- * scripts/override-audit.js convention: allocate `Math.min(size, maxBytes)`,
121
- * seek to `size - readBytes`, then discard the partial first line, since a
122
- * byte-offset read almost always lands mid-record.
123
- *
124
- * When the file was larger than the window, `truncated` is true and
125
- * `records`/`lines` describe only the tail that was read. Callers MUST surface
126
- * that — a truncated `recordsTotal` presented as a whole-file count is exactly
127
- * the kind of silently-partial number this module exists to avoid.
128
- *
129
- * @returns {{ status: string, path: string, records: object[], lines: number,
130
- * malformed: number, truncated: boolean, bytesRead: number, fileBytes: number }}
131
- */
132
57
  function readJsonlSource(filePath, options = {}) {
133
58
  const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0
134
59
  ? options.maxBytes
@@ -219,13 +144,7 @@ function readJsonlSource(filePath, options = {}) {
219
144
  };
220
145
  }
221
146
 
222
- /**
223
- * Did the tail window actually cover the whole requested window?
224
- *
225
- * If the file was truncated AND its oldest surviving record is newer than
226
- * `since`, then records inside the window were dropped and every count derived
227
- * from this source is a partial view. That must be reported, not assumed away.
228
- */
147
+ // False when truncated and oldest surviving record is newer than sinceMs.
229
148
  function coversWindow(source, sinceMs) {
230
149
  if (source.status !== SOURCE_STATUS.OK) return null;
231
150
  if (!source.truncated) return true;
@@ -258,22 +177,7 @@ function dayKey(record, field = 'timestamp') {
258
177
  return new Date(ms).toISOString().slice(0, 10);
259
178
  }
260
179
 
261
- // ---------------------------------------------------------------------------
262
- // False-deny pairing
263
- // ---------------------------------------------------------------------------
264
-
265
- /**
266
- * Pair each clearing event (override/approve) with the most recent UNPAIRED
267
- * preceding deny of the same gate.
268
- *
269
- * Why 1:1 and not "any later clear marks every earlier deny of that gate":
270
- * one break-glass override would then retroactively brand hundreds of
271
- * force-push denies as false, which is a fabricated numerator. One receipt
272
- * clears at most one block. The pairing is therefore a LOWER BOUND on
273
- * reversals, and the method string in the output says so.
274
- *
275
- * @returns {{ numerator: number, denominator: number, clearEvents: number, pairs: object[] }}
276
- */
180
+ // 1:1 pairing: each reversal matches the most recent unpaired preceding deny of the same gate.
277
181
  function pairDeniesWithClears(records) {
278
182
  const denyStack = new Map(); // gateId -> ascending [{ ts, record }]
279
183
  const clearEvents = [];
@@ -389,12 +293,6 @@ function buildTopGates(records, limit = 5) {
389
293
  .slice(0, limit);
390
294
  }
391
295
 
392
- /**
393
- * Per-day calls/denies. Only days that ACTUALLY APPEAR in the log are listed —
394
- * a zero-filled calendar would print "0 calls" for days the store may simply
395
- * predate, which is exactly the measured-vs-absent confusion this report exists
396
- * to avoid. `undated` counts rows whose timestamp could not be parsed.
397
- */
398
296
  function buildDaily(records) {
399
297
  const byDay = new Map();
400
298
  let undated = 0;
@@ -411,11 +309,6 @@ function buildDaily(records) {
411
309
  return { daily, undated };
412
310
  }
413
311
 
414
- /**
415
- * Agents come from tool-kpi.jsonl — the ONLY store here that records an agentId.
416
- * audit-trail.jsonl rows carry no agent identity, which is why gate decisions
417
- * are reported repo-wide and never split per agent.
418
- */
419
312
  function buildAgents(kpiRecords) {
420
313
  const byAgent = new Map();
421
314
  for (const r of kpiRecords) {
@@ -465,8 +358,6 @@ function sourceDetail(source, inWindow, sinceMs) {
465
358
  const detail = {
466
359
  status: source.status,
467
360
  path: source.path,
468
- // NOTE: when `truncated` is true this counts only the records inside the
469
- // tail window that was read, never the whole file.
470
361
  recordsTotal: source.records.length,
471
362
  recordsInWindow: source.status === SOURCE_STATUS.OK ? inWindow : null,
472
363
  malformedLines: source.malformed,
@@ -482,8 +373,6 @@ function sourceDetail(source, inWindow, sinceMs) {
482
373
  function buildAgentAttribution(kpiSource, agents) {
483
374
  const base = {
484
375
  identitySource: KPI_LOG_FILENAME,
485
- // Stated explicitly because it is the single biggest limitation of this
486
- // report: allow/deny counts are repo-wide, NOT per-agent.
487
376
  gateDecisionsPerAgent: 'unavailable',
488
377
  reason: `${AUDIT_LOG_FILENAME} records carry no agentId, so allow/deny/warn counts cannot be split per agent. Agent rows come from ${KPI_LOG_FILENAME} and cover tool calls only.`,
489
378
  };
@@ -524,13 +413,7 @@ function buildAgentAttribution(kpiSource, agents) {
524
413
  };
525
414
  }
526
415
 
527
- /**
528
- * falseDenyRate = paired reversals / denies observed.
529
- *
530
- * Returns null (with a reason) whenever a real denominator was not observed.
531
- * The numerator and denominator are ALWAYS returned raw so the caller can see
532
- * exactly what the rate was — or was not — computed from.
533
- */
416
+ // falseDenyRate = paired reversals / denies observed (null when denominator is 0 or source missing/empty).
534
417
  function computeFalseDeny(auditSource, auditInWindow, windowDays) {
535
418
  const unmeasurable = (reason) => ({
536
419
  falseDenyRate: null,
@@ -575,18 +458,7 @@ function computeFalseDeny(auditSource, auditInWindow, windowDays) {
575
458
  };
576
459
  }
577
460
 
578
- /**
579
- * Build the agent action inventory for one ThumbGate data directory.
580
- *
581
- * Read-only: opens files, writes nothing.
582
- *
583
- * @param {object} [opts]
584
- * @param {string} [opts.dataDir] — a ThumbGate store dir (e.g. `<repo>/.thumbgate`).
585
- * Defaults to the resolved feedback dir.
586
- * @param {number|string} [opts.windowDays] — lookback in days (clamped 1..365, default 30).
587
- * @param {number} [opts.topGateLimit=5]
588
- * @returns {object} the inventory
589
- */
461
+ // Build read-only agent action inventory for dataDir.
590
462
  function buildInventory(opts = {}) {
591
463
  const windowDays = normalizeWindowDays(opts.windowDays);
592
464
  const topGateLimit = Number.isFinite(opts.topGateLimit) && opts.topGateLimit > 0
@@ -627,8 +499,6 @@ function buildInventory(opts = {}) {
627
499
  else if (r.decision === 'warn') warnCount += 1;
628
500
  else if (r.decision === 'allow') allowCount += 1;
629
501
  else otherDecisionCount += 1;
630
- // Counted independently of the buckets above: a consumed admin override is
631
- // recorded as decision 'allow', so it is both an allow and a reversal.
632
502
  if (isClearingRecord(r)) overrideCount += 1;
633
503
  }
634
504
 
@@ -645,16 +515,11 @@ function buildInventory(opts = {}) {
645
515
  gateEvents: gateSource.status,
646
516
  toolKpi: kpiSource.status,
647
517
  },
648
- // Per-source detail so "0 calls" is always traceable to a file that exists,
649
- // parsed, and simply had nothing inside the window.
650
518
  sourceDetail: {
651
519
  auditTrail: sourceDetail(auditSource, auditInWindow.length, sinceMs),
652
520
  gateEvents: sourceDetail(gateSource, gateInWindow.length, sinceMs),
653
521
  toolKpi: sourceDetail(kpiSource, kpiInWindow.length, sinceMs),
654
522
  },
655
- // false when a source's tail window did not reach back to `since`, i.e.
656
- // records inside the requested window were dropped and every count below is
657
- // a partial view. null when the audit trail was not readable at all.
658
523
  windowFullyCovered: coversWindow(auditSource, sinceMs),
659
524
 
660
525
  agents,
@@ -806,6 +671,225 @@ function renderInventoryText(inv) {
806
671
  return lines.join('\n') + '\n';
807
672
  }
808
673
 
674
+ const AGENT_REGISTER_CONFIG_FILENAME = 'agent-register.json';
675
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
676
+ const UNREGISTERED_AGENT_FLAG = 'unregistered agent';
677
+ const UNATTRIBUTED_IDS = new Set(['unknown', '(no agentId recorded)']);
678
+ const BUILTIN_MCP_SERVERS = new Set(['thumbgate', 'mcp', 'mcp-http']);
679
+ const alphaCmp = (a, b) => a.localeCompare(b);
680
+ const isSafeKey = (k) => typeof k === 'string' && k.trim().length > 0 && k.trim().length <= 128 && !UNSAFE_KEYS.has(k.trim());
681
+ const firstStr = (arr) => { for (const v of arr) if (typeof v === 'string' && v.trim()) return v.trim(); return null; };
682
+ const resolveDataDir = (d) => path.resolve(d ? String(d) : require('./feedback-paths').resolveFeedbackDir());
683
+
684
+ function badRequestError(msg) {
685
+ const err = new Error(msg);
686
+ err.statusCode = 400;
687
+ return err;
688
+ }
689
+
690
+ function resolveDefaultOwner(opts = {}) {
691
+ const explicit = firstStr([opts.defaultOwner, process.env.THUMBGATE_DEFAULT_OWNER]);
692
+ if (explicit) return explicit;
693
+ try { const u = os.userInfo().username; if (u?.trim()) return u.trim(); } catch {}
694
+ return firstStr([process.env.USER, process.env.USERNAME]) || 'local-operator';
695
+ }
696
+
697
+ function readJsonObj(p) {
698
+ if (!p || !fs.existsSync(p)) return null;
699
+ try { const x = JSON.parse(fs.readFileSync(p, 'utf8')); return x && typeof x === 'object' && !Array.isArray(x) ? x : null; } catch { return null; }
700
+ }
701
+
702
+ function mergeOwnersObj(owners, raw) {
703
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
704
+ for (const [k, v] of Object.entries(raw)) {
705
+ if (isSafeKey(k) && typeof v === 'string' && v.trim()) owners.set(k.trim(), v.trim().slice(0, 128));
706
+ }
707
+ }
708
+
709
+ function mergeRegDoc(owners, registered, src) {
710
+ if (!src || typeof src !== 'object') return;
711
+ mergeOwnersObj(owners, src.owners);
712
+ if (!Array.isArray(src.registered)) return;
713
+ for (const x of src.registered) if (isSafeKey(x)) registered.add(x.trim());
714
+ }
715
+
716
+ function loadAgentRegisterConfig(dataDir) {
717
+ const owners = new Map(), registered = new Set();
718
+ for (const f of ['settings.json', 'settings.local.json']) mergeRegDoc(owners, registered, readJsonObj(path.join(dataDir, f))?.agents);
719
+ mergeRegDoc(owners, registered, readJsonObj(path.join(dataDir, AGENT_REGISTER_CONFIG_FILENAME)));
720
+ return { owners, registered };
721
+ }
722
+
723
+ function applyOwnerUpdate(owners, key, owner) {
724
+ if (owner === undefined) return;
725
+ if (owner !== null && typeof owner !== 'string') throw badRequestError('Owner must be a string or null.');
726
+ const clean = owner === null ? '' : owner.trim().slice(0, 128);
727
+ if (!clean) owners.delete(key);
728
+ else owners.set(key, clean);
729
+ }
730
+
731
+ function updateAgentRegisterEntry({ dataDir, id, owner, registered } = {}) {
732
+ if (!isSafeKey(id)) throw badRequestError('Valid agent or surface id is required.');
733
+ const dir = resolveDataDir(dataDir), filePath = path.join(dir, AGENT_REGISTER_CONFIG_FILENAME);
734
+ const owners = new Map(), regSet = new Set(), key = id.trim();
735
+ mergeRegDoc(owners, regSet, readJsonObj(filePath));
736
+ applyOwnerUpdate(owners, key, owner);
737
+ if (registered === true) regSet.add(key);
738
+ else if (registered === false) regSet.delete(key);
739
+ const nextDoc = { owners: Object.fromEntries(owners), registered: [...regSet].sort(alphaCmp), updatedAt: new Date().toISOString() };
740
+ fs.mkdirSync(dir, { recursive: true });
741
+ fs.writeFileSync(filePath, `${JSON.stringify(nextDoc, null, 2)}\n`);
742
+ return nextDoc;
743
+ }
744
+
745
+ function parseMcpTool(t) {
746
+ const raw = typeof t === 'string' ? t.trim() : '';
747
+ if (!raw.startsWith('mcp__')) return null;
748
+ const rest = raw.slice(5), d = rest.indexOf('__'), s = rest.indexOf('_');
749
+ if (d > 0) return { server: rest.slice(0, d), tool: rest.slice(d + 2) };
750
+ return s > 0 ? { server: rest.slice(0, s), tool: rest.slice(s + 1) } : null;
751
+ }
752
+
753
+ function loadMcpAllowlistIndex(allowlistsPath) {
754
+ const p = allowlistsPath || process.env.THUMBGATE_MCP_POLICY_PATH || path.join(__dirname, '..', 'config', 'mcp-allowlists.json');
755
+ const parsed = readJsonObj(p) || {}, tools = new Set(), agents = new Set(), mcpServers = new Set(BUILTIN_MCP_SERVERS);
756
+ for (const list of Object.values(parsed.profiles || {})) {
757
+ if (Array.isArray(list)) for (const t of list) if (typeof t === 'string' && t.trim()) tools.add(t.trim());
758
+ }
759
+ for (const a of (parsed.agents || parsed.allowlistedAgents || [])) if (isSafeKey(a)) agents.add(a.trim());
760
+ for (const s of (parsed.mcpServers || parsed.servers || [])) if (isSafeKey(s)) mcpServers.add(s.trim());
761
+ return { path: p, tools, agents, mcpServers };
762
+ }
763
+
764
+ function touchBucket(map, id, kind, tsMs, delta = 1) {
765
+ if (!isSafeKey(id)) return null;
766
+ const key = id.trim();
767
+ let b = map.get(key);
768
+ if (!b) { b = { id: key, kind, callCount: 0, firstSeenMs: null, lastSeenMs: null, tools: new Set() }; map.set(key, b); }
769
+ b.callCount += delta;
770
+ if (tsMs !== null && Number.isFinite(tsMs)) {
771
+ if (b.firstSeenMs === null || tsMs < b.firstSeenMs) b.firstSeenMs = tsMs;
772
+ if (b.lastSeenMs === null || tsMs > b.lastSeenMs) b.lastSeenMs = tsMs;
773
+ }
774
+ return b;
775
+ }
776
+
777
+ function resolveRecordMcpServer(r, tool, allowTools) {
778
+ const pm = parseMcpTool(tool);
779
+ const explicit = pm?.server || firstStr([r.mcpServer, r.metadata?.mcpServer, r.metadata?.serverName, r.serverName]);
780
+ if (explicit && explicit !== 'default') return explicit;
781
+ return tool && allowTools.has(tool) ? 'thumbgate' : null;
782
+ }
783
+
784
+ function ingestSingleRecord(r, maps, allowTools) {
785
+ const ts = timestampMs(r), tool = firstStr([r.toolName]) || '';
786
+ const rawAgent = firstStr([r.agentId]);
787
+ if (rawAgent && !UNATTRIBUTED_IDS.has(rawAgent)) {
788
+ const ab = touchBucket(maps.agents, rawAgent, 'agent', ts, 1);
789
+ if (ab && tool) ab.tools.add(tool);
790
+ } else {
791
+ maps.unattributedCalls += 1;
792
+ }
793
+ const model = firstStr([r.model, r.metadata?.model, r.toolInput?.model]);
794
+ if (model) touchBucket(maps.models, model, 'model', ts, 1);
795
+ const srv = resolveRecordMcpServer(r, tool, allowTools);
796
+ if (srv) { const sb = touchBucket(maps.mcpServers, srv, 'mcp_server', ts, 1); if (sb && tool) sb.tools.add(tool); }
797
+ const hook = firstStr([r.source, r.metadata?.hookSource, r.metadata?.source]);
798
+ if (hook) touchBucket(maps.hookSources, hook, 'hook_source', ts, 1);
799
+ }
800
+
801
+ function ingestRecords(records, maps, allowTools) {
802
+ for (const r of records) if (r && typeof r === 'object') ingestSingleRecord(r, maps, allowTools);
803
+ }
804
+
805
+ function ingestRegistryEntry(reg, sinceMs, maps, state) {
806
+ if (!reg || !isSafeKey(reg.id)) return;
807
+ const id = reg.id.trim(), meta = reg.metadata && typeof reg.metadata === 'object' ? reg.metadata : {};
808
+ if (meta.lifecycleStatus === 'retired') { state.retired.add(id); state.active.delete(id); }
809
+ else { state.retired.delete(id); state.active.add(id); }
810
+ if (typeof meta.owner === 'string' && meta.owner.trim()) state.owners.set(id, meta.owner.trim());
811
+ const lastMs = timestampMs(reg, 'lastSeenAt') ?? timestampMs(reg, 'registeredAt');
812
+ if (lastMs === null || lastMs < sinceMs) return;
813
+ const b = touchBucket(maps.agents, id, 'agent', timestampMs(reg, 'registeredAt') ?? lastMs, 0);
814
+ if (b) { touchBucket(maps.agents, id, 'agent', lastMs, 0); b.callCount = Math.max(b.callCount, Number(reg.toolCalls) || 0); }
815
+ const m = firstStr([meta.model]), s = firstStr([reg.source]);
816
+ if (m) touchBucket(maps.models, m, 'model', lastMs, 0);
817
+ if (s && s !== 'unknown') touchBucket(maps.hookSources, s, 'hook_source', lastMs, 0);
818
+ }
819
+
820
+ function ingestObservedEntry(obs, sinceMs, maps) {
821
+ if (!obs || !isSafeKey(obs.id)) return;
822
+ const lastMs = timestampMs(obs, 'lastSeenAt') ?? timestampMs(obs, 'seenAt');
823
+ if (lastMs === null || lastMs < sinceMs) return;
824
+ const id = obs.id.trim(), cnt = Number(obs.observations) > 0 ? Number(obs.observations) : 1;
825
+ const cur = maps.agents.get(id);
826
+ const b = touchBucket(maps.agents, id, 'agent', timestampMs(obs, 'firstSeenAt') ?? lastMs, cur ? Math.max(0, cnt - cur.callCount) : cnt);
827
+ if (b) touchBucket(maps.agents, id, 'agent', lastMs, 0);
828
+ }
829
+
830
+ function isMcpServerRegistered(b, regCfg, allow) {
831
+ if (regCfg.registered.has(b.id) || allow.mcpServers.has(b.id)) return true;
832
+ return b.tools.size > 0 && [...b.tools].every((t) => allow.tools.has(t));
833
+ }
834
+
835
+ const toRow = (b, owner, registered) => ({
836
+ id: b.id, kind: b.kind,
837
+ firstSeen: b.firstSeenMs !== null ? new Date(b.firstSeenMs).toISOString() : null,
838
+ lastSeen: b.lastSeenMs !== null ? new Date(b.lastSeenMs).toISOString() : null,
839
+ callCount: b.callCount, owner, registered,
840
+ status: registered ? 'registered' : UNREGISTERED_AGENT_FLAG,
841
+ flag: registered ? null : UNREGISTERED_AGENT_FLAG,
842
+ tools: [...b.tools].sort(alphaCmp),
843
+ });
844
+ const sortRows = (rows) => rows.sort((a, b) => b.callCount - a.callCount || a.id.localeCompare(b.id));
845
+
846
+ function buildAgentRegister(opts = {}) {
847
+ const windowDays = normalizeWindowDays(opts.windowDays), dataDir = resolveDataDir(opts.dataDir);
848
+ const parsedNow = opts.now ? new Date(opts.now).getTime() : Date.now();
849
+ const nowMs = Number.isFinite(parsedNow) ? parsedNow : Date.now(), sinceMs = nowMs - windowDays * 86400000;
850
+ const defaultOwner = resolveDefaultOwner(opts), regCfg = loadAgentRegisterConfig(dataDir), allow = loadMcpAllowlistIndex(opts.allowlistsPath);
851
+ const ro = { maxBytes: opts.maxBytes };
852
+ const maps = { agents: new Map(), models: new Map(), mcpServers: new Map(), hookSources: new Map(), unattributedCalls: 0 };
853
+ ingestRecords(require('./project-catalog').readProjectRows(dataDir, AUDIT_LOG_FILENAME, { ...opts, projectKey: opts.projectKey }).filter((r) => withinWindow(r, sinceMs)), maps, allow.tools);
854
+ ingestRecords(require('./project-catalog').readProjectRows(dataDir, KPI_LOG_FILENAME, { ...opts, projectKey: opts.projectKey }).filter((r) => withinWindow(r, sinceMs)), maps, allow.tools);
855
+ const regState = { active: new Set(), retired: new Set(), owners: new Map() };
856
+ for (const reg of require('./project-catalog').readProjectRows(dataDir, REGISTRY_FILENAME, { ...opts, projectKey: opts.projectKey, dedupe: false })) ingestRegistryEntry(reg, sinceMs, maps, regState);
857
+ for (const obs of require('./project-catalog').readProjectRows(dataDir, OBSERVED_FILENAME, { ...opts, projectKey: opts.projectKey, dedupe: false })) ingestObservedEntry(obs, sinceMs, maps);
858
+ const ownerFor = (id) => regCfg.owners.get(id) || regState.owners.get(id) || defaultOwner;
859
+ const agents = sortRows([...maps.agents.values()].map((b) => {
860
+ const inReg = regCfg.registered.has(b.id) || (regState.active.has(b.id) && !regState.retired.has(b.id));
861
+ return toRow(b, ownerFor(b.id), inReg || allow.agents.has(b.id));
862
+ }));
863
+ const mcpServers = sortRows([...maps.mcpServers.values()].map((b) => toRow(b, ownerFor(b.id), isMcpServerRegistered(b, regCfg, allow))));
864
+ const models = sortRows([...maps.models.values()].map((b) => toRow(b, ownerFor(b.id), true)));
865
+ const hookSources = sortRows([...maps.hookSources.values()].map((b) => toRow(b, ownerFor(b.id), true)));
866
+ const unregisteredAgentsList = agents.filter((a) => !a.registered);
867
+ const unregistered = [...unregisteredAgentsList, ...mcpServers.filter((s) => !s.registered)];
868
+ return {
869
+ generatedAt: new Date(nowMs).toISOString(), dataDir, windowDays, since: new Date(sinceMs).toISOString(), defaultOwner, allowlistsPath: allow.path,
870
+ summary: {
871
+ totalAgents: agents.length, registeredAgents: agents.length - unregisteredAgentsList.length, unregisteredAgents: unregisteredAgentsList.length,
872
+ unregisteredMcpServers: mcpServers.length - mcpServers.filter((s) => s.registered).length, unregisteredTotal: unregistered.length,
873
+ unattributedCalls: maps.unattributedCalls, totalModels: models.length, totalMcpServers: mcpServers.length, totalHookSources: hookSources.length,
874
+ },
875
+ agents, models, mcpServers, hookSources, unregistered,
876
+ };
877
+ }
878
+
879
+ function renderAgentRegisterText(report) {
880
+ const out = [
881
+ `ThumbGate Agent Register (last ${report.windowDays}d, default owner: ${report.defaultOwner})`,
882
+ ` agents: ${report.summary.totalAgents} (${report.summary.registeredAgents} registered, ${report.summary.unregisteredAgents} ${UNREGISTERED_AGENT_FLAG})`,
883
+ ` models: ${report.summary.totalModels} · mcp servers: ${report.summary.totalMcpServers} · hook sources: ${report.summary.totalHookSources}`, '',
884
+ ];
885
+ for (const [label, rows, badge] of [['Agents', report.agents, true], ['Models', report.models, false], ['MCP servers', report.mcpServers, true], ['Hook sources', report.hookSources, false]]) {
886
+ out.push(label);
887
+ if (!rows.length) out.push(' none seen in window');
888
+ for (const r of rows) out.push(` ${r.id.padEnd(24)} calls=${r.callCount} owner=${r.owner} first=${r.firstSeen || 'n/a'} last=${r.lastSeen || 'n/a'}${badge ? ` [${r.status}]` : ''}`);
889
+ out.push('');
890
+ }
891
+ return out.join('\n');
892
+ }
809
893
  // ---------------------------------------------------------------------------
810
894
  // Exports
811
895
  // ---------------------------------------------------------------------------
@@ -813,6 +897,12 @@ function renderInventoryText(inv) {
813
897
  module.exports = {
814
898
  buildInventory,
815
899
  renderInventoryText,
900
+ buildAgentRegister,
901
+ renderAgentRegisterText,
902
+ updateAgentRegisterEntry,
903
+ loadAgentRegisterConfig,
904
+ isSafeKey,
905
+ resolveDefaultOwner,
816
906
  normalizeWindowDays,
817
907
  readJsonlSource,
818
908
  pairDeniesWithClears,
@@ -829,6 +919,8 @@ module.exports = {
829
919
  APPROVAL_REQUIRED_DECISION,
830
920
  DEFAULT_MAX_BYTES,
831
921
  KPI_LOG_FILENAME,
922
+ AGENT_REGISTER_CONFIG_FILENAME,
923
+ UNREGISTERED_AGENT_FLAG,
832
924
  MIN_WINDOW_DAYS,
833
925
  MAX_WINDOW_DAYS,
834
926
  DEFAULT_WINDOW_DAYS,
@@ -778,7 +778,7 @@ function buildMarketingAgencyGtmPlan(input = {}) {
778
778
  status: ready ? 'ready-to-sell-workflow-sprint' : 'build-gtm-proof-first',
779
779
  channels,
780
780
  monthlyRetainer,
781
- offer: 'AI Agent Governance Workflow Hardening Sprint',
781
+ offer: 'AI Agent Governance Setup Sprint',
782
782
  gates: [
783
783
  'target lead generation around one expensive repeated AI-agent mistake, not generic AI automation',
784
784
  'use CRM automation only after consent, attribution, and unsubscribe paths are configured',
@@ -7,6 +7,10 @@ const {
7
7
  getActiveMcpProfile,
8
8
  getAllowedTools,
9
9
  } = require('./mcp-policy');
10
+ const {
11
+ evaluateProgressiveSignoff,
12
+ formatProgressiveSignoffSection,
13
+ } = require('./progressive-signoff');
10
14
 
11
15
  const PROJECT_ROOT = path.join(__dirname, '..');
12
16
 
@@ -302,10 +306,9 @@ function summarizeGitScale(projectRoot) {
302
306
  }
303
307
  }
304
308
 
305
- function generateAgentReadinessReport({
306
- projectRoot = PROJECT_ROOT,
307
- mcpProfile = null,
308
- } = {}) {
309
+ function generateAgentReadinessReport(options = {}) {
310
+ const projectRoot = options.projectRoot || PROJECT_ROOT;
311
+ const mcpProfile = options.mcpProfile || null;
309
312
  const runtime = detectRuntimeIsolation();
310
313
  const bootstrap = collectBootstrapFiles(projectRoot);
311
314
  const permissions = summarizePermissionTier(mcpProfile || getActiveMcpProfile());
@@ -313,9 +316,15 @@ function generateAgentReadinessReport({
313
316
 
314
317
  const preToolUseHookRegistered = detectPreToolUseHookRegistered(projectRoot);
315
318
  const gitScale = summarizeGitScale(projectRoot);
319
+ const progressiveSignoff = evaluateProgressiveSignoff({
320
+ projectRoot,
321
+ ...(options && options.progressiveSignoff ? options.progressiveSignoff : {}),
322
+ });
316
323
 
317
324
  const warnings = [];
318
- if (!runtime.isolated) warnings.push(runtime.recommendation);
325
+ // Host runtime is the normal case on a developer laptop, so it is advice, not a failure.
326
+ const advisories = [];
327
+ if (!runtime.isolated) advisories.push(runtime.recommendation);
319
328
  if (!bootstrap.ready) warnings.push(bootstrap.recommendation);
320
329
  if (!permissions.ready) warnings.push(permissions.recommendation);
321
330
  // Missing operator verifiers is advisory (not every project asserts SQL row counts).
@@ -343,6 +352,7 @@ function generateAgentReadinessReport({
343
352
  claimVerification,
344
353
  preToolUseHookRegistered,
345
354
  gitScale,
355
+ progressiveSignoff,
346
356
  articleAlignment: {
347
357
  runtimeIsolation: runtime.isolated,
348
358
  contextConditioning: bootstrap.ready,
@@ -351,6 +361,7 @@ function generateAgentReadinessReport({
351
361
  preToolUseHook: preToolUseHookRegistered,
352
362
  },
353
363
  warnings,
364
+ advisories,
354
365
  };
355
366
  }
356
367
 
@@ -382,6 +393,14 @@ function reportToText(report) {
382
393
  );
383
394
  }
384
395
 
396
+ if (report.progressiveSignoff && report.progressiveSignoff.recommendations && report.progressiveSignoff.recommendations.length > 0) {
397
+ const signoffSection = formatProgressiveSignoffSection(report.progressiveSignoff);
398
+ if (signoffSection) {
399
+ lines.push('');
400
+ lines.push(signoffSection);
401
+ }
402
+ }
403
+
385
404
  if (report.warnings.length > 0) {
386
405
  lines.push('');
387
406
  lines.push('Warnings:');
@@ -390,6 +409,14 @@ function reportToText(report) {
390
409
  });
391
410
  }
392
411
 
412
+ if (report.advisories && report.advisories.length > 0) {
413
+ lines.push('');
414
+ lines.push('Advisories (do not affect readiness):');
415
+ report.advisories.forEach((advisory) => {
416
+ lines.push(`- ${advisory}`);
417
+ });
418
+ }
419
+
393
420
  return `${lines.join('\n')}\n`;
394
421
  }
395
422
 
@@ -403,9 +430,12 @@ module.exports = {
403
430
  recommendationForClaimState,
404
431
  detectStopHookRegistered,
405
432
  detectPreToolUseHookRegistered,
406
- generateAgentReadinessReport,
407
433
  summarizeGitScale,
434
+ evaluateProgressiveSignoff,
435
+ formatProgressiveSignoffSection,
436
+ generateAgentReadinessReport,
408
437
  reportToText,
438
+ findProjectRoot,
409
439
  };
410
440
 
411
441
  if (require.main === module) {