thumbgate 1.39.1 → 1.40.1

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 (160) 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 +62 -28
  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 +159 -69
  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 +75 -60
  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-window.js +7 -1
  67. package/scripts/async-job-runner.js +66 -11
  68. package/scripts/audit-trail.js +37 -24
  69. package/scripts/auto-promote-gates.js +37 -27
  70. package/scripts/backfill-lesson-scopes.js +122 -0
  71. package/scripts/billing.js +889 -132
  72. package/scripts/bot-detection.js +112 -0
  73. package/scripts/brand-standards-gate.js +571 -0
  74. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  75. package/scripts/cli-schema.js +1 -1
  76. package/scripts/commercial-offer.js +2 -2
  77. package/scripts/contextfs.js +9 -3
  78. package/scripts/cross-encoder-reranker.js +4 -0
  79. package/scripts/dashboard-chat.js +11 -0
  80. package/scripts/dashboard.js +574 -167
  81. package/scripts/decision-journal.js +7 -4
  82. package/scripts/docker-sandbox-planner.js +3 -3
  83. package/scripts/export-dpo-pairs.js +12 -7
  84. package/scripts/feedback-aggregate.js +4 -0
  85. package/scripts/feedback-attribution.js +6 -4
  86. package/scripts/feedback-history-distiller.js +18 -6
  87. package/scripts/feedback-loop.js +255 -89
  88. package/scripts/feedback-paths.js +8 -1
  89. package/scripts/feedback-sanitizer.js +5 -0
  90. package/scripts/feedback-scope.js +106 -0
  91. package/scripts/feedback-session.js +8 -2
  92. package/scripts/filesystem-search.js +13 -8
  93. package/scripts/financial-control-plane.js +707 -45
  94. package/scripts/gate-stats.js +8 -2
  95. package/scripts/gates-engine.js +694 -230
  96. package/scripts/generate-eval-scorecard.js +0 -1
  97. package/scripts/harness-tool-names.js +31 -5
  98. package/scripts/hybrid-feedback-context.js +5 -2
  99. package/scripts/intervention-policy.js +2 -1
  100. package/scripts/lesson-canonical.js +2 -2
  101. package/scripts/lesson-db.js +55 -14
  102. package/scripts/lesson-graph.js +2 -1
  103. package/scripts/lesson-retrieval.js +95 -9
  104. package/scripts/lesson-search.js +86 -22
  105. package/scripts/lesson-synthesis.js +21 -5
  106. package/scripts/mailer/index.js +17 -1
  107. package/scripts/mailer/resend-mailer.js +213 -179
  108. package/scripts/migrate-project-scope.js +209 -0
  109. package/scripts/operational-integrity.js +436 -3
  110. package/scripts/override-audit.js +2 -0
  111. package/scripts/owner-admin.js +338 -0
  112. package/scripts/pr-manager.js +194 -1
  113. package/scripts/progressive-signoff.js +260 -0
  114. package/scripts/project-catalog.js +243 -0
  115. package/scripts/project-dashboard.js +61 -0
  116. package/scripts/project-evidence.js +172 -0
  117. package/scripts/project-identity.js +182 -0
  118. package/scripts/project-scope.js +381 -0
  119. package/scripts/prompt-guard.js +446 -52
  120. package/scripts/proof-report.js +232 -0
  121. package/scripts/provider-action-normalizer.js +14 -6
  122. package/scripts/rate-limiter.js +41 -0
  123. package/scripts/secret-redaction.js +171 -25
  124. package/scripts/secret-scanner.js +101 -42
  125. package/scripts/self-protection.js +2 -2
  126. package/scripts/seo-gsd.js +14 -14
  127. package/scripts/session-context-dedupe.js +66 -0
  128. package/scripts/settings-hierarchy.js +4 -2
  129. package/scripts/statusline-meta.js +34 -23
  130. package/scripts/task-outcomes.js +29 -2
  131. package/scripts/telemetry-analytics.js +238 -13
  132. package/scripts/thumbgate-search.js +23 -9
  133. package/scripts/tool-kpi-tracker.js +5 -2
  134. package/scripts/tool-registry.js +42 -1
  135. package/scripts/triage-savings-calculator.js +1 -1
  136. package/scripts/vector-store.js +4 -1
  137. package/scripts/verified-lessons.js +270 -0
  138. package/scripts/verify-marketing-pages-deployed.js +2 -2
  139. package/scripts/workflow-sentinel.js +29 -10
  140. package/server.json +2 -2
  141. package/src/api/server.js +2371 -451
  142. package/src/feedback.js +21 -0
  143. package/src/hermes-sync-plane.js +2 -1
  144. package/src/index.js +2 -0
  145. package/src/lesson-search.js +9 -0
  146. package/src/mckinsey-top-company-ai-coding.js +493 -0
  147. package/src/mcp/server.js +3 -0
  148. package/src/mcp-writeguard.js +772 -11
  149. package/src/openshell-lovable-engine.js +1475 -0
  150. package/src/task-outcome.js +3 -0
  151. package/config/evals/agent-safety-eval.json +0 -447
  152. package/config/evals/retrieval-ranking-golden.json +0 -522
  153. package/config/progressive/01-wire-only.json +0 -11
  154. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  155. package/config/progressive/03-one-lesson.json +0 -10
  156. package/config/progressive/04-warn-fires.json +0 -11
  157. package/config/progressive/05-strict-optional.json +0 -11
  158. package/config/progressive/README.md +0 -15
  159. package/public/assets/diagrams/agent-integration.png +0 -0
  160. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Progressive Sign-off Removal (McKinsey / Industrial AI Engineering Steal)
6
+ *
7
+ * Evaluates human-in-the-loop gates whose action is `approve`.
8
+ * When a gate passes N clean runs in a row (Beta-Bernoulli Thompson-sampling
9
+ * confidence above threshold, default N=20, confidence >= 0.90), ThumbGate doctor
10
+ * recommends downgrading the action from `approve` to `warn`.
11
+ *
12
+ * CRITICAL SAFETY INVARIANT:
13
+ * Recommend only. Never edit gate definition files under config/ or .thumbgate/.
14
+ * The self-protect gate blocks direct configuration edits, and must.
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const { resolveFeedbackDir } = require('./feedback-paths');
20
+
21
+ const DEFAULT_CLEAN_RUNS_N = 20;
22
+ const DEFAULT_CONFIDENCE_THRESHOLD = 0.90;
23
+
24
+ /**
25
+ * Compute Beta posterior mean as Thompson-sampling confidence:
26
+ * confidence = alpha / (alpha + beta)
27
+ * where alpha = 1.0 + cleanRuns, beta = 1.0 + failures (using uniform prior Beta(1,1)).
28
+ *
29
+ * @param {number} cleanRuns - Number of consecutive clean runs
30
+ * @param {number} [failures=0] - Number of failures (0 for clean streak)
31
+ * @returns {number} Confidence value in [0, 1]
32
+ */
33
+ function computeThompsonConfidence(cleanRuns, failures = 0) {
34
+ const alpha = 1.0 + Math.max(0, Number(cleanRuns) || 0);
35
+ const beta = 1.0 + Math.max(0, Number(failures) || 0);
36
+ return alpha / (alpha + beta);
37
+ }
38
+
39
+ /**
40
+ * Load all gates from default or custom gate paths.
41
+ *
42
+ * @param {object} [options]
43
+ * @param {string} [options.projectRoot]
44
+ * @param {string} [options.manualGatesPath]
45
+ * @param {Array} [options.gates]
46
+ * @returns {Array<object>}
47
+ */
48
+ function loadApprovalGates(options = {}) {
49
+ if (Array.isArray(options.gates)) {
50
+ return options.gates.filter((g) => g && g.action === 'approve');
51
+ }
52
+
53
+ const projectRoot = options.projectRoot || path.join(__dirname, '..');
54
+ const manualGatesPath = options.manualGatesPath
55
+ || path.join(projectRoot, 'config', 'gates', 'default.json');
56
+
57
+ if (!fs.existsSync(manualGatesPath)) return [];
58
+
59
+ try {
60
+ const raw = fs.readFileSync(manualGatesPath, 'utf8');
61
+ const parsed = JSON.parse(raw);
62
+ const gates = Array.isArray(parsed.gates) ? parsed.gates : [];
63
+ return gates.filter((g) => g && g.action === 'approve');
64
+ } catch {
65
+ return [];
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Scan audit-trail.jsonl backwards to count consecutive clean runs for a gate.
71
+ *
72
+ * @param {string} gateId
73
+ * @param {string} auditTrailPath
74
+ * @returns {number} Consecutive clean runs
75
+ */
76
+ function countCleanRunsFromAuditTrail(gateId, auditTrailPath) {
77
+ if (!fs.existsSync(auditTrailPath)) return 0;
78
+
79
+ try {
80
+ const content = fs.readFileSync(auditTrailPath, 'utf8').trim();
81
+ if (!content) return 0;
82
+ const lines = content.split('\n');
83
+
84
+ let cleanStreak = 0;
85
+ // Iterate from newest to oldest
86
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
87
+ const line = lines[i].trim();
88
+ if (!line) continue;
89
+ let record;
90
+ try {
91
+ record = JSON.parse(line);
92
+ } catch {
93
+ continue;
94
+ }
95
+
96
+ if (record.gateId === gateId || record.gate === gateId) {
97
+ const isDeny = record.decision === 'deny' || record.error === true || record.violation === true;
98
+ if (isDeny) {
99
+ // Streak broken
100
+ break;
101
+ }
102
+
103
+ const isClean = record.decision === 'approve'
104
+ || record.decision === 'allow'
105
+ || record.status === 'clean'
106
+ || record.status === 'success'
107
+ || record.clean === true;
108
+
109
+ if (isClean) {
110
+ cleanStreak += 1;
111
+ }
112
+ }
113
+ }
114
+ return cleanStreak;
115
+ } catch {
116
+ return 0;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Resolve clean runs for a gate across explicit overrides, gate-stats, and audit-trail.
122
+ *
123
+ * @param {string} gateId
124
+ * @param {object} [options]
125
+ * @returns {number}
126
+ */
127
+ function resolveCleanRunsForGate(gateId, options = {}) {
128
+ // 1. Explicit override (e.g. for testing or telemetry injected directly)
129
+ if (options.cleanRunsByGate && typeof options.cleanRunsByGate[gateId] === 'number') {
130
+ return Math.max(0, options.cleanRunsByGate[gateId]);
131
+ }
132
+
133
+ // 2. Check gate-stats.json if present
134
+ const statsPath = options.statsPath
135
+ || (options.feedbackDir ? path.join(options.feedbackDir, 'gate-stats.json') : null)
136
+ || path.join(resolveFeedbackDir(), 'gate-stats.json');
137
+
138
+ if (fs.existsSync(statsPath)) {
139
+ try {
140
+ const stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
141
+ if (stats.byGate && stats.byGate[gateId]) {
142
+ const entry = stats.byGate[gateId];
143
+ if (typeof entry.cleanRuns === 'number') {
144
+ return Math.max(0, entry.cleanRuns);
145
+ }
146
+ if (typeof entry.consecutiveCleanRuns === 'number') {
147
+ return Math.max(0, entry.consecutiveCleanRuns);
148
+ }
149
+ }
150
+ } catch {
151
+ // fallback to audit-trail
152
+ }
153
+ }
154
+
155
+ // 3. Scan audit-trail.jsonl
156
+ const auditPath = options.auditTrailPath
157
+ || (options.feedbackDir ? path.join(options.feedbackDir, 'audit-trail.jsonl') : null)
158
+ || path.join(resolveFeedbackDir(), 'audit-trail.jsonl');
159
+
160
+ return countCleanRunsFromAuditTrail(gateId, auditPath);
161
+ }
162
+
163
+ /**
164
+ * Evaluate human-in-the-loop approval gates for progressive sign-off removal recommendations.
165
+ *
166
+ * @param {object} [options]
167
+ * @param {number} [options.thresholdN=20] - Number of clean runs required
168
+ * @param {number} [options.confidenceThreshold=0.90] - Thompson-sampling confidence threshold
169
+ * @param {object} [options.cleanRunsByGate] - Optional map of gateId -> clean run count
170
+ * @param {Array<object>} [options.gates] - Optional explicit list of gates
171
+ * @param {string} [options.projectRoot] - Project root directory
172
+ * @returns {object} Evaluation results with recommendations
173
+ */
174
+ function evaluateProgressiveSignoff(options = {}) {
175
+ const rawN = Number(options.thresholdN || options.cleanRunsThreshold);
176
+ const thresholdN = Number.isFinite(rawN) && rawN > 0 ? rawN : DEFAULT_CLEAN_RUNS_N;
177
+
178
+ const rawConf = Number(options.confidenceThreshold);
179
+ const confidenceThreshold = Number.isFinite(rawConf) && rawConf > 0 && rawConf <= 1.0
180
+ ? rawConf
181
+ : DEFAULT_CONFIDENCE_THRESHOLD;
182
+
183
+ const approvalGates = loadApprovalGates(options);
184
+ const evaluatedGates = [];
185
+ const recommendations = [];
186
+
187
+ for (const gate of approvalGates) {
188
+ if (!gate || !gate.id) continue;
189
+ const cleanRuns = resolveCleanRunsForGate(gate.id, options);
190
+ const confidence = computeThompsonConfidence(cleanRuns, 0);
191
+ const eligible = cleanRuns >= thresholdN && confidence >= confidenceThreshold;
192
+
193
+ const evaluation = {
194
+ gateId: gate.id,
195
+ currentAction: gate.action,
196
+ cleanRuns,
197
+ requiredCleanRuns: thresholdN,
198
+ confidence: Number(confidence.toFixed(4)),
199
+ confidenceThreshold,
200
+ eligibleForDowngrade: eligible,
201
+ };
202
+ evaluatedGates.push(evaluation);
203
+
204
+ if (eligible) {
205
+ recommendations.push({
206
+ gateId: gate.id,
207
+ currentAction: 'approve',
208
+ recommendedAction: 'warn',
209
+ cleanRuns,
210
+ requiredCleanRuns: thresholdN,
211
+ confidence: Number(confidence.toFixed(4)),
212
+ confidenceThreshold,
213
+ reason: `Passed ${cleanRuns} clean runs in a row (Thompson-sampling confidence ${(confidence * 100).toFixed(1)}% >= ${(confidenceThreshold * 100).toFixed(1)}%). Recommend downgrade 'approve' -> 'warn'.`,
214
+ advisoryOnly: true,
215
+ });
216
+ }
217
+ }
218
+
219
+ return {
220
+ evaluatedCount: evaluatedGates.length,
221
+ thresholdN,
222
+ confidenceThreshold,
223
+ evaluatedGates,
224
+ recommendations,
225
+ hasRecommendations: recommendations.length > 0,
226
+ safetyNotice: 'Advisory only. Gate definition files under config/ are protected and must never be auto-edited.',
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Format progressive sign-off recommendations for human-readable doctor output.
232
+ *
233
+ * @param {object} progressiveSignoff
234
+ * @returns {string|null}
235
+ */
236
+ function formatProgressiveSignoffSection(progressiveSignoff) {
237
+ if (!progressiveSignoff || !Array.isArray(progressiveSignoff.recommendations) || progressiveSignoff.recommendations.length === 0) {
238
+ return null;
239
+ }
240
+
241
+ const lines = ['Progressive Sign-off Recommendations:'];
242
+ for (const rec of progressiveSignoff.recommendations) {
243
+ const pct = (rec.confidence * 100).toFixed(1);
244
+ lines.push(
245
+ ` - Gate "${rec.gateId}": ${rec.cleanRuns} clean runs (Thompson confidence: ${pct}%). Recommend downgrade 'approve' -> 'warn'. (Advisory only — manual config change required)`
246
+ );
247
+ }
248
+ return lines.join('\n');
249
+ }
250
+
251
+ module.exports = {
252
+ DEFAULT_CLEAN_RUNS_N,
253
+ DEFAULT_CONFIDENCE_THRESHOLD,
254
+ computeThompsonConfidence,
255
+ loadApprovalGates,
256
+ countCleanRunsFromAuditTrail,
257
+ resolveCleanRunsForGate,
258
+ evaluateProgressiveSignoff,
259
+ formatProgressiveSignoffSection,
260
+ };
@@ -0,0 +1,243 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { assertScopedDataPath, tenantDataScope } = require('./feedback-scope');
6
+ const { buildAliases, resolveProjectEvidence, projectForRecord, matchesProject, gateAppliesToProject, isGeneratedGate } = require('./project-identity');
7
+
8
+ const SIGNAL_FILES = ['feedback-log.jsonl', 'memory-log.jsonl', 'audit-trail.jsonl', 'gate-events-log.jsonl', 'telemetry-pings.jsonl', 'telemetry-log.jsonl', 'agent-registry.jsonl', 'observed-agents.jsonl', 'diagnostic-log.jsonl', 'decision-journal.jsonl', 'tool-kpi.jsonl', 'task-outcome-receipts.jsonl'];
9
+ function accountDirectories(root) {
10
+ const absolute = assertScopedDataPath(path.resolve(root));
11
+ if (!fs.existsSync(absolute)) return [];
12
+ const canonical = fs.realpathSync(absolute);
13
+ const directories = [canonical];
14
+ const projects = path.join(canonical, 'projects');
15
+ if (fs.existsSync(projects)) {
16
+ if (fs.lstatSync(projects).isSymbolicLink()) throw new Error('Symlink signal directory refused');
17
+ for (const item of fs.readdirSync(projects, { withFileTypes: true })) {
18
+ if (item.isSymbolicLink()) throw new Error('Symlink project directory refused');
19
+ if (item.isDirectory()) directories.push(path.join(projects, item.name));
20
+ }
21
+ }
22
+ return [...new Set(directories)];
23
+ }
24
+ function signalPaths(root, filename) {
25
+ return accountDirectories(root).map((dir) => assertScopedDataPath(path.join(dir, filename))).filter((file) => {
26
+ if (!fs.existsSync(file)) return false;
27
+ if (fs.lstatSync(file).isSymbolicLink()) throw new Error('Symlink signal file refused');
28
+ return fs.statSync(file).isFile();
29
+ });
30
+ }
31
+ function *iterateRows(file) {
32
+ const fd = fs.openSync(file, 'r');
33
+ const buffer = Buffer.alloc(64 * 1024);
34
+ const decoder = new (require('node:string_decoder').StringDecoder)('utf8');
35
+ let pending = '';
36
+ const parse = (line) => { try { const row = JSON.parse(line); return row && typeof row === 'object' && !Array.isArray(row) ? row : null; } catch { return null; } };
37
+ try {
38
+ let n;
39
+ while ((n = fs.readSync(fd, buffer, 0, buffer.length, null))) {
40
+ pending += decoder.write(buffer.subarray(0, n));
41
+ let end;
42
+ while ((end = pending.indexOf('\n')) !== -1) {
43
+ const row = parse(pending.slice(0, end));
44
+ pending = pending.slice(end + 1);
45
+ if (row) yield row;
46
+ }
47
+ if (pending.length > 8 * 1024 * 1024) throw new Error('Signal row exceeds supported size');
48
+ }
49
+ const row = parse(pending + decoder.end());
50
+ if (row) yield row;
51
+ } finally { fs.closeSync(fd); }
52
+ }
53
+ function readRows(file) { return [...iterateRows(file)]; }
54
+ function uniqueSourceIndex(records, aliases) {
55
+ const index = new Map();
56
+ for (const record of records) {
57
+ if (!record.id) continue;
58
+ const resolved = record.descriptor ? record : resolveProjectEvidence(record, { aliases });
59
+ const descriptor = resolved.descriptor;
60
+ if (descriptor.projectKey === 'unassigned') {
61
+ if (/^(conflicting_|ambiguous_)/.test(resolved.reason || '')) index.set(record.id, { ambiguous: true, projectKey: 'unassigned' });
62
+ continue;
63
+ }
64
+ const prior = index.get(record.id);
65
+ index.set(record.id, prior && (prior.ambiguous || prior.projectKey !== descriptor.projectKey) ? { ambiguous: true, projectKey: 'unassigned' } : (prior || { ...descriptor, evidence: resolved.evidence || descriptor.identitySource }));
66
+ }
67
+ return index;
68
+ }
69
+ function compactEvidence(row, filename) {
70
+ const { pathCandidates } = require('./project-evidence');
71
+ return {
72
+ id: row.id, projectKey: row.projectKey, projectName: row.projectName, identitySource: row.identitySource,
73
+ remoteUrl: row.remoteUrl, remote: row.remote, scope: row.scope ? { projectId: row.scope.projectId, sessionId: row.scope.sessionId, remoteUrl: row.scope.remoteUrl, remote: row.scope.remote } : undefined,
74
+ metadata: row.metadata ? { project: row.metadata.project, repo: row.metadata.repo, remoteUrl: row.metadata.remoteUrl, remote: row.metadata.remote, machineId: row.metadata.machineId, importedFrom: row.metadata.importedFrom, sourceType: row.metadata.sourceType } : undefined,
75
+ projectId: row.projectId, registryProject: filename === 'agent-registry.jsonl' ? row.project : undefined,
76
+ sourceFeedbackId: row.sourceFeedbackId, sourceLessonId: row.sourceLessonId, agentId: row.agentId,
77
+ sessionId: row.sessionId, timestamp: row.timestamp, seenAt: row.seenAt, registeredAt: row.registeredAt, lastSeenAt: row.lastSeenAt,
78
+ source: row.source, sourceType: row.sourceType, machineId: row.machineId, sourceMachineId: row.sourceMachineId,
79
+ imported: row.imported, importedFrom: row.importedFrom, syncedFrom: row.syncedFrom, provenance: row.provenance ? { imported: row.provenance.imported, origin: row.provenance.origin, machineId: row.provenance.machineId } : undefined,
80
+ recordType: filename, pathCandidates: pathCandidates({ ...row, registryProject: filename === 'agent-registry.jsonl' ? row.project : undefined }).slice(0, 17),
81
+ };
82
+ }
83
+ function sessionToken(record, options = {}) {
84
+ const id = record.sessionId || record.scope?.sessionId;
85
+ if (typeof id !== 'string' || !id || /^(unknown|default|none|null|session|\d+)$/i.test(id)) return null;
86
+ const machines = [record.sourceMachineId, record.machineId, record.metadata?.machineId, record.provenance?.machineId].filter(Boolean);
87
+ if (new Set(machines).size > 1) return null;
88
+ const machine = machines[0];
89
+ if (require('./project-evidence').provenanceReason(record, { sourceMachineId: machine })) return null;
90
+ if (!machine && options.trustedLocalSource !== true) return null;
91
+ if (machine && options.sourceMachineId && machine !== options.sourceMachineId) return null;
92
+ return `${machine || 'trusted_local'}\0${record.source || record.sourceType || record.recordType || ''}\0${id}`;
93
+ }
94
+ function accountAttribution(root, options = {}) {
95
+ const records = []; const directories = new Map();
96
+ for (const filename of SIGNAL_FILES) for (const file of signalPaths(root, filename)) {
97
+ const local = directories.get(path.dirname(file)) || []; directories.set(path.dirname(file), local);
98
+ for (const row of iterateRows(file)) {
99
+ const record = compactEvidence(row, filename);
100
+ // Identity indexes never retain duplicated context/tool payloads from large logs.
101
+ if (!record.id && !record.agentId && !record.projectKey && !record.remoteUrl && !record.remote && !record.scope?.projectId && !record.registryProject && !record.sessionId && !record.sourceFeedbackId && !record.sourceLessonId && !record.pathCandidates.length) continue;
102
+ records.push(record); local.push(record);
103
+ }
104
+ }
105
+ const aliases = buildAliases(records);
106
+ const pathEvidence = require('./project-evidence').createPathEvidence(options.localPathEvidence);
107
+ const state = { aliases, pathEvidence, localPathEvidence: options.localPathEvidence, feedbackById: new Map(), lessonById: new Map(), feedbackByDirectory: new Map(), lessonByDirectory: new Map(), registryByDirectory: new Map(), sessionsByDirectory: new Map() };
108
+ const resolveRows = (rows, filename, context) => rows.filter((row) => row.recordType === filename).map((row) => ({ id: row.id, ...resolveProjectEvidence(row, context) }));
109
+ for (const [directory, local] of directories) state.registryByDirectory.set(directory, uniqueSourceIndex(resolveRows(local, 'agent-registry.jsonl', { aliases, pathEvidence })));
110
+ for (const [directory, local] of directories) {
111
+ const context = { aliases, pathEvidence, registryById: state.registryByDirectory.get(directory) };
112
+ state.feedbackByDirectory.set(directory, uniqueSourceIndex(resolveRows(local, 'feedback-log.jsonl', context)));
113
+ }
114
+ state.feedbackById = mergeSourceIndexes(state.feedbackByDirectory);
115
+ for (const [directory, local] of directories) {
116
+ const context = attributionForFile(state, path.join(directory, 'memory-log.jsonl'));
117
+ state.lessonByDirectory.set(directory, uniqueSourceIndex(resolveRows(local, 'memory-log.jsonl', context)));
118
+ }
119
+ state.lessonById = mergeSourceIndexes(state.lessonByDirectory);
120
+ for (const [directory, local] of directories) {
121
+ const sessions = new Map();
122
+ for (const row of local) {
123
+ const token = sessionToken(row, options.localPathEvidence); const stamp = Date.parse(row.timestamp || row.seenAt || row.registeredAt || row.lastSeenAt);
124
+ if (!token || !Number.isFinite(stamp)) continue;
125
+ const resolved = resolveProjectEvidence(row, attributionForFile(state, path.join(directory, row.recordType)));
126
+ if (resolved.descriptor.projectKey === 'unassigned') continue;
127
+ const prior = sessions.get(token);
128
+ sessions.set(token, prior ? { ...prior, ambiguous: prior.ambiguous || prior.projectKey !== resolved.descriptor.projectKey, first: Math.min(prior.first, stamp), last: Math.max(prior.last, stamp) } : { ...resolved.descriptor, evidence: resolved.evidence, first: stamp, last: stamp });
129
+ }
130
+ state.sessionsByDirectory.set(directory, sessions);
131
+ }
132
+ // Fixed session anchors may support typed descendants, but descendants never
133
+ // feed back into session anchors or scope aliases.
134
+ for (const [directory, local] of directories) state.feedbackByDirectory.set(directory, uniqueSourceIndex(resolveRows(local, 'feedback-log.jsonl', attributionForFile(state, path.join(directory, 'feedback-log.jsonl')))));
135
+ state.feedbackById = mergeSourceIndexes(state.feedbackByDirectory);
136
+ for (const [directory, local] of directories) state.lessonByDirectory.set(directory, uniqueSourceIndex(resolveRows(local, 'memory-log.jsonl', attributionForFile(state, path.join(directory, 'memory-log.jsonl')))));
137
+ state.lessonById = mergeSourceIndexes(state.lessonByDirectory);
138
+ return state;
139
+ }
140
+ function mergeSourceIndexes(byDirectory) {
141
+ const merged = new Map();
142
+ for (const index of byDirectory.values()) for (const [id, descriptor] of index) {
143
+ const prior = merged.get(id);
144
+ merged.set(id, descriptor.ambiguous || (prior && (prior.ambiguous || prior.projectKey !== descriptor.projectKey)) ? { ambiguous: true, projectKey: 'unassigned' } : descriptor);
145
+ }
146
+ return merged;
147
+ }
148
+ function attributionForFile(attribution, file) {
149
+ const directory = path.dirname(file);
150
+ const overlay = (global, local) => local?.size ? new Map([...(global || []), ...local]) : global;
151
+ const sessions = attribution.sessionsByDirectory?.get(directory);
152
+ return { ...attribution, recordType: path.basename(file),
153
+ feedbackById: overlay(attribution.feedbackById, attribution.feedbackByDirectory?.get(directory)),
154
+ lessonById: overlay(attribution.lessonById, attribution.lessonByDirectory?.get(directory)),
155
+ registryById: attribution.registryByDirectory?.get(directory),
156
+ sessionLookup(record) {
157
+ const candidate = sessions?.get(sessionToken({ ...record, recordType: path.basename(file) }, attribution.localPathEvidence));
158
+ if (!candidate) return null;
159
+ const stamp = Date.parse(record.timestamp || record.seenAt || record.registeredAt || record.lastSeenAt);
160
+ if (!Number.isFinite(stamp) || candidate.last - candidate.first > 86400000 || stamp < candidate.first || stamp > candidate.last) return null;
161
+ return candidate;
162
+ },
163
+ };
164
+ }
165
+ function readProjectRows(root, filename, options = {}) {
166
+ const attribution = options.attribution || accountAttribution(root, options);
167
+ const seen = new Set();
168
+ const rows = [];
169
+ for (const file of signalPaths(root, filename)) {
170
+ for (const record of iterateRows(file)) {
171
+ const row = { ...record, ...projectForRecord(record, attributionForFile(attribution, file)) };
172
+ if (!matchesProject(row, options.projectKey)) continue;
173
+ const id = row.id || row.feedbackId;
174
+ const key = id ? `${row.projectKey}\0${id}` : null;
175
+ if (options.dedupe !== false && key && seen.has(key)) continue;
176
+ if (key) seen.add(key);
177
+ rows.push(row);
178
+ }
179
+ }
180
+ return rows;
181
+ }
182
+ function readProjectGates(root, options = {}) {
183
+ const attribution = options.attribution || accountAttribution(root, options);
184
+ const defaultFile = path.join(__dirname, '..', 'config', 'gates', 'default.json');
185
+ // The primary policy file is the operator's configured safety policy: always global, never re-attributed to a project.
186
+ const primaryFile = tenantDataScope() ? defaultFile : (process.env.THUMBGATE_GATES_CONFIG || defaultFile);
187
+ const files = [primaryFile, ...accountDirectories(root).flatMap((dir) => ['auto-promoted-gates.json', 'custom-gates.json'].map((name) => path.join(dir, name)))];
188
+ const gates = new Map();
189
+ for (const file of files) {
190
+ if (!fs.existsSync(file) || fs.lstatSync(file).isSymbolicLink()) continue;
191
+ let config; try { config = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
192
+ for (const item of Array.isArray(config) ? config : config.gates || []) {
193
+ let gate = { ...item };
194
+ const generated = file !== primaryFile && (path.basename(file) === 'auto-promoted-gates.json' || isGeneratedGate(gate));
195
+ if (generated && (!gate.projectKey || gate.projectKey === 'unassigned')) {
196
+ gate = { ...gate, ...projectForRecord(gate, attributionForFile(attribution, file)), scope: 'project' };
197
+ if (gate.projectKey === 'unassigned') gate.active = false;
198
+ } else gate.scope = gate.scope || (gate.projectKey ? 'project' : 'global');
199
+ if (options.projectKey != null && !gateAppliesToProject(gate, options.projectKey)) continue;
200
+ gates.set(`${gate.projectKey || 'global'}\0${gate.id}`, gate);
201
+ }
202
+ }
203
+ return [...gates.values()];
204
+ }
205
+ function buildProjectCatalog(root, options = {}) {
206
+ const projects = new Map();
207
+ const attribution = options.attribution || accountAttribution(root, options);
208
+ const ensure = (row) => {
209
+ const descriptor = projectForRecord(row, attribution);
210
+ if (!projects.has(descriptor.projectKey)) projects.set(descriptor.projectKey, { ...descriptor, counts: { feedback: 0, lessons: 0, gates: 0, blocks: 0, warns: 0, toolCalls: 0, agents: 0 }, lastActivity: null });
211
+ return projects.get(descriptor.projectKey);
212
+ };
213
+ for (const filename of SIGNAL_FILES) {
214
+ const agents = new Set();
215
+ for (const row of readProjectRows(root, filename, { attribution })) {
216
+ const project = ensure(row);
217
+ const stamp = row.timestamp || row.lastSeenAt || row.registeredAt;
218
+ if (stamp && Number.isFinite(Date.parse(stamp)) && (!project.lastActivity || Date.parse(stamp) > Date.parse(project.lastActivity))) project.lastActivity = stamp;
219
+ if (filename === 'feedback-log.jsonl') project.counts.feedback++;
220
+ if (filename === 'memory-log.jsonl') project.counts.lessons++;
221
+ if (filename === 'audit-trail.jsonl') {
222
+ if (['deny', 'block'].includes(row.decision || row.action)) project.counts.blocks++;
223
+ if ((row.decision || row.action) === 'warn') project.counts.warns++;
224
+ project.counts.toolCalls++;
225
+ }
226
+ if (filename === 'agent-registry.jsonl') {
227
+ const key = `${row.projectKey}\0${row.agentId || row.id}`;
228
+ if (!agents.has(key)) { project.counts.agents++; agents.add(key); }
229
+ }
230
+ }
231
+ }
232
+ const gates = readProjectGates(root, { ...options, attribution });
233
+ for (const gate of gates) {
234
+ if (gate.scope !== 'project') continue;
235
+ const project = ensure(gate);
236
+ if (gateAppliesToProject(gate, gate.projectKey)) project.counts.gates++;
237
+ for (const stamp of [gate.timestamp, gate.promotedAt, gate.updatedAt]) {
238
+ if (stamp && Number.isFinite(Date.parse(stamp)) && (!project.lastActivity || Date.parse(stamp) > Date.parse(project.lastActivity))) project.lastActivity = stamp;
239
+ }
240
+ }
241
+ return { projects: [...projects.values()].sort((a, b) => a.projectName.localeCompare(b.projectName)), globalGateCount: gates.filter((gate) => gate.scope === 'global' && gate.active !== false && gate.enabled !== false).length };
242
+ }
243
+ module.exports = { attributionForFile, uniqueSourceIndex, iterateRows, SIGNAL_FILES, accountDirectories, signalPaths, readRows, accountAttribution, readProjectRows, readProjectGates, buildProjectCatalog };
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ const { readProjectRows, readProjectGates, buildProjectCatalog } = require('./project-catalog');
4
+
5
+ function generateProjectDashboard(feedbackDir, options = {}) {
6
+ const dashboard = require('./dashboard');
7
+ options = { ...options, attribution: options.attribution || require('./project-catalog').accountAttribution(feedbackDir, options) };
8
+ const rows = (file) => readProjectRows(feedbackDir, file, options);
9
+ const feedback = rows('feedback-log.jsonl').filter((row) => !options.humanOnly || !row.reviewOrigin || row.reviewOrigin === 'human');
10
+ const memories = rows('memory-log.jsonl');
11
+ const audit = rows('audit-trail.jsonl');
12
+ const gates = readProjectGates(feedbackDir, options).filter((gate) => gate.active !== false && gate.enabled !== false).map((gate) => ({ ...gate, name: gate.name || gate.id, scopeLabel: gate.scope === 'global' ? 'Global' : 'Project' }));
13
+ const byGate = {};
14
+ const gateStats = { totalGates: gates.length, manualCount: gates.filter((g) => g.scope === 'global').length, autoCount: gates.filter((g) => g.scope === 'project').length, blocked: 0, warned: 0, passed: 0, byGate };
15
+ for (const row of audit) {
16
+ const metric = ['deny', 'block'].includes(row.decision) ? 'blocked' : row.decision === 'warn' ? 'warned' : row.decision === 'allow' ? 'passed' : null;
17
+ if (!metric) continue;
18
+ gateStats[metric]++;
19
+ const bucket = byGate[row.gateId || 'unknown'] ||= { blocked: 0, warned: 0, passed: 0 };
20
+ bucket[metric]++;
21
+ }
22
+ const now = new Date(options.now || Date.now());
23
+ const dayKey = (stamp) => { const date = new Date(stamp); return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : null; };
24
+ const days = [];
25
+ for (let i = 29; i >= 0; i--) {
26
+ const date = new Date(now); date.setUTCDate(date.getUTCDate() - i);
27
+ const key = dayKey(date);
28
+ const signals = feedback.filter((row) => dayKey(row.timestamp) === key);
29
+ days.push({ dayKey: key, positive: signals.filter((r) => ['positive', 'up'].includes(r.signal)).length, negative: signals.filter((r) => ['negative', 'down'].includes(r.signal)).length, total: signals.length, lessons: memories.filter((r) => dayKey(r.timestamp) === key).length });
30
+ }
31
+ const auditDays = days.slice(-14).map(({ dayKey: key }) => {
32
+ const entries = audit.filter((row) => dayKey(row.timestamp) === key);
33
+ const allow = entries.filter((r) => r.decision === 'allow').length;
34
+ const deny = entries.filter((r) => ['deny', 'block'].includes(r.decision)).length;
35
+ const warn = entries.filter((r) => r.decision === 'warn').length;
36
+ return { dayKey: key, allow, deny, warn, intercepted: deny + warn, total: allow + deny + warn };
37
+ });
38
+ const reviewSnapshot = dashboard.buildReviewSnapshot(feedbackDir, { feedbackEntries: feedback, memoryEntries: memories, auditEntries: audit, projectRoot: null, reviewedAt: now.toISOString() });
39
+ const baseline = dashboard.readDashboardReviewState(feedbackDir, options);
40
+ const project = buildProjectCatalog(feedbackDir, options).projects.find((item) => item.projectKey === options.projectKey) || { projectKey: options.projectKey, projectName: options.projectKey === 'unassigned' ? 'Unassigned' : 'Project' };
41
+ const unavailableMetrics = ['analytics', 'billing', 'prevention', 'harness', 'health', 'delegation', 'observability', 'instrumentation', 'readiness', 'agentSurfaceInventory', 'backgroundAgents', 'regulatedProof', 'interventionPolicy', 'decisions', 'settingsStatus', 'team', 'templateLibrary', 'predictive', 'tokenSavings'];
42
+ const data = Object.fromEntries(unavailableMetrics.map((name) => [name, null]));
43
+ const today = auditDays.at(-1);
44
+ const feedbackAnalysis = require('./feedback-loop').analyzeFeedback(require('node:path').join(feedbackDir, 'feedback-log.jsonl'), { ...options, entries: feedback });
45
+ return {
46
+ ...data, projectKey: options.projectKey, project, unavailableMetrics,
47
+ operational: { source: 'project-records' }, approval: dashboard.computeApprovalStats(feedback), gateStats, gates,
48
+ trend: dashboard.computeSessionTrend(feedback, 10),
49
+ gateAudit: { dayCount: 14, days: auditDays, totals: auditDays.reduce((sum, row) => { for (const key of ['allow', 'deny', 'warn', 'total', 'intercepted']) sum[key] += row[key]; return sum; }, { allow: 0, deny: 0, warn: 0, total: 0, intercepted: 0 }) },
50
+ diagnostics: require('./failure-diagnostics').aggregateFailureDiagnostics([...feedback, ...rows('diagnostic-log.jsonl')]),
51
+ secretGuard: dashboard.computeSecretGuardStats(rows('diagnostic-log.jsonl')),
52
+ feedbackAnalysis,
53
+ actionableRemediations: feedbackAnalysis.actionableRemediations || [],
54
+ agentRegister: require('./agent-action-inventory').buildAgentRegister({ ...options, dataDir: feedbackDir }),
55
+ reviewDelta: dashboard.summarizeReviewDelta(feedback, memories, audit, baseline, reviewSnapshot),
56
+ feedbackTimeSeries: { days, dayCount: 30, totals: { positive: feedback.filter((r) => r.signal === 'positive').length, negative: feedback.filter((r) => r.signal === 'negative').length, total: feedback.length, lessons: memories.length } },
57
+ todayOverview: { gateStatusChips: { blockedToday: today.deny, warnedToday: today.warn, activeGates: gates.length }, lessonStorage: { lessonCount: memories.length, location: null, bytes: null, label: 'Project lessons' }, upNext: null },
58
+ lessonPipeline: { stages: [{ id: 'feedback', label: 'Feedback Signals', count: feedback.length }, { id: 'lessons', label: 'Lessons Distilled', count: memories.length }, { id: 'gates', label: 'Project Gates', count: gateStats.autoCount }, { id: 'blocked', label: 'Actions Blocked', count: gateStats.blocked }], rates: { feedbackToLesson: feedback.length ? Math.round(memories.length / feedback.length * 100) : 0, lessonToGate: memories.length ? Math.round(gateStats.autoCount / memories.length * 100) : 0 } },
59
+ };
60
+ }
61
+ module.exports = { generateProjectDashboard };