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
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ // Per-session dedupe for the static context ThumbGate hooks attach to every tool call
4
+ // (recent corrective actions, recurring failure patterns). The same text re-read on every
5
+ // call costs input tokens; inject it only when it changed since the last injection in the
6
+ // same session. Context matched to the current tool call is never routed through here.
7
+
8
+ const crypto = require('node:crypto');
9
+ const fs = require('node:fs');
10
+ const os = require('node:os');
11
+ const path = require('node:path');
12
+
13
+ function storeDir(options = {}) {
14
+ return options.dir || process.env.THUMBGATE_CONTEXT_DEDUPE_DIR
15
+ || path.join(os.tmpdir(), 'thumbgate-context-dedupe');
16
+ }
17
+
18
+ function safeSessionId(sessionId) {
19
+ return String(sessionId || '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 80);
20
+ }
21
+
22
+ function hashText(text) {
23
+ return crypto.createHash('sha256').update(String(text)).digest('hex');
24
+ }
25
+
26
+ function readHash(file) {
27
+ try {
28
+ return JSON.parse(fs.readFileSync(file, 'utf8')).hash || '';
29
+ } catch {
30
+ return '';
31
+ }
32
+ }
33
+
34
+ /**
35
+ * @param {string} sessionId
36
+ * @param {string|null} text static context for this call
37
+ * @returns {string|null} text if it should be injected, null if identical to the last
38
+ * injection in this session. Without a session id nothing is deduped.
39
+ */
40
+ function dedupeSessionContext(sessionId, text, options = {}) {
41
+ if (typeof text !== 'string' || text.length === 0) return null;
42
+ const sid = safeSessionId(sessionId);
43
+ if (!sid) return text;
44
+ const file = path.join(storeDir(options), `${sid}.json`);
45
+ const hash = hashText(text);
46
+ if (readHash(file) === hash) return null;
47
+ try {
48
+ fs.mkdirSync(path.dirname(file), { recursive: true });
49
+ fs.writeFileSync(file, JSON.stringify({ hash, at: Date.now() }));
50
+ } catch {
51
+ // a failed write only means the next call injects again
52
+ }
53
+ return text;
54
+ }
55
+
56
+ function logInjection(entry, options = {}) {
57
+ try {
58
+ const dir = options.logDir || process.env.THUMBGATE_CONTEXT_DEDUPE_LOG_DIR || storeDir(options);
59
+ fs.mkdirSync(dir, { recursive: true });
60
+ fs.appendFileSync(path.join(dir, 'injection-bytes.jsonl'), `${JSON.stringify(entry)}\n`);
61
+ } catch {
62
+ // logging is best effort
63
+ }
64
+ }
65
+
66
+ module.exports = { dedupeSessionContext, logInjection, hashText };
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ const MIN_WINDOW_HOURS = 1;
4
+ const MAX_WINDOW_HOURS = 24 * 30;
5
+ const DEFAULT_WINDOW_HOURS = 24;
6
+
7
+ function normalizeWindowHours(input) {
8
+ if (input === null || input === undefined || input === '') return DEFAULT_WINDOW_HOURS;
9
+ const n = Number(input);
10
+ if (!Number.isFinite(n)) return DEFAULT_WINDOW_HOURS;
11
+ if (n < MIN_WINDOW_HOURS) return MIN_WINDOW_HOURS;
12
+ if (n > MAX_WINDOW_HOURS) return MAX_WINDOW_HOURS;
13
+ return Math.floor(n);
14
+ }
15
+
16
+ function topNegativeTags(tags, limit = 5) {
17
+ if (!tags || typeof tags !== 'object') return [];
18
+ return Object.entries(tags)
19
+ .map(([tag, counts]) => ({
20
+ tag,
21
+ negative: (counts && counts.negative) || 0,
22
+ positive: (counts && counts.positive) || 0,
23
+ total: (counts && counts.total) || 0,
24
+ }))
25
+ .filter((row) => row.negative > 0)
26
+ .sort((a, b) => b.negative - a.negative)
27
+ .slice(0, limit);
28
+ }
29
+
30
+ function topGates(byGate, limit = 5) {
31
+ if (!byGate || typeof byGate !== 'object') return [];
32
+ return Object.entries(byGate)
33
+ .map(([gate, counts]) => ({
34
+ gate,
35
+ blocked: (counts && counts.blocked) || 0,
36
+ warned: (counts && counts.warned) || 0,
37
+ pendingApproval: (counts && counts.pendingApproval) || 0,
38
+ }))
39
+ .sort((a, b) => b.blocked - a.blocked || b.warned - a.warned)
40
+ .slice(0, limit);
41
+ }
42
+
43
+ function summarizeProvenance(events, sinceMs) {
44
+ if (!Array.isArray(events)) return { total: 0, byType: {} };
45
+ const byType = {};
46
+ let total = 0;
47
+ for (const evt of events) {
48
+ const ts = Date.parse(evt && evt.timestamp ? evt.timestamp : '');
49
+ if (!Number.isFinite(ts) || ts < sinceMs) continue;
50
+ total += 1;
51
+ const type = (evt && evt.type) || 'unknown';
52
+ byType[type] = (byType[type] || 0) + 1;
53
+ }
54
+ return { total, byType };
55
+ }
56
+
57
+ function buildSessionReport({ windowHours } = {}) {
58
+ const hours = normalizeWindowHours(windowHours);
59
+ const sinceMs = Date.now() - hours * 60 * 60 * 1000;
60
+ const report = {
61
+ generatedAt: new Date().toISOString(),
62
+ windowHours: hours,
63
+ since: new Date(sinceMs).toISOString(),
64
+ feedback: { totalPositive: 0, totalNegative: 0, topNegativeTags: [] },
65
+ gates: { blocked: 0, warned: 0, passed: 0, topGates: [] },
66
+ provenance: { total: 0, byType: {} },
67
+ errors: {},
68
+ };
69
+
70
+ try {
71
+ const { analyzeFeedback } = require('./feedback-loop');
72
+ const feedback = analyzeFeedback() || {};
73
+ report.feedback = {
74
+ totalPositive: feedback.totalPositive || 0,
75
+ totalNegative: feedback.totalNegative || 0,
76
+ topNegativeTags: topNegativeTags(feedback.tags || {}),
77
+ };
78
+ } catch (err) {
79
+ report.errors.feedback = String(err && err.message ? err.message : err);
80
+ }
81
+
82
+ try {
83
+ const { loadStats } = require('./gates-engine');
84
+ const stats = loadStats() || {};
85
+ report.gates = {
86
+ blocked: stats.blocked || 0,
87
+ warned: stats.warned || 0,
88
+ passed: stats.passed || 0,
89
+ pendingApproval: stats.pendingApproval || 0,
90
+ topGates: topGates(stats.byGate || {}),
91
+ };
92
+ } catch (err) {
93
+ report.errors.gates = String(err && err.message ? err.message : err);
94
+ }
95
+
96
+ try {
97
+ const { getProvenance } = require('./contextfs');
98
+ const events = getProvenance(500) || [];
99
+ report.provenance = summarizeProvenance(events, sinceMs);
100
+ } catch (err) {
101
+ report.errors.provenance = String(err && err.message ? err.message : err);
102
+ }
103
+
104
+ if (Object.keys(report.errors).length === 0) {
105
+ delete report.errors;
106
+ }
107
+
108
+ return report;
109
+ }
110
+
111
+ module.exports = {
112
+ buildSessionReport,
113
+ normalizeWindowHours,
114
+ topNegativeTags,
115
+ topGates,
116
+ summarizeProvenance,
117
+ MIN_WINDOW_HOURS,
118
+ MAX_WINDOW_HOURS,
119
+ DEFAULT_WINDOW_HOURS,
120
+ };
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { tenantDataScope } = require('./feedback-scope');
5
+
4
6
  const fs = require('fs');
5
7
  const os = require('os');
6
8
  const path = require('path');
@@ -86,8 +88,8 @@ function getNestedValue(target, dottedPath) {
86
88
  }
87
89
 
88
90
  function resolveSettingsPaths(options = {}) {
89
- const projectRoot = options.projectRoot || PROJECT_ROOT;
90
- const homeDir = options.homeDir || process.env.HOME || os.homedir();
91
+ const projectRoot = tenantDataScope()?.feedbackDir || options.projectRoot || PROJECT_ROOT;
92
+ const homeDir = tenantDataScope()?.feedbackDir || options.homeDir || process.env.HOME || os.homedir();
91
93
 
92
94
  return {
93
95
  managed: path.join(projectRoot, 'config', 'thumbgate-settings.managed.json'),
@@ -1,39 +1,50 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- const path = require('path');
5
- const { isProLicensed, isValidKey } = require('./license');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { verifyLicense, isProLicensed, isValidKey } = require('./license');
7
+
8
+ function readDiskOperatorKey(homeDir) {
9
+ try {
10
+ const configPath = path.join(homeDir, '.config', 'thumbgate', 'operator.json');
11
+ if (!fs.existsSync(configPath)) return '';
12
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
13
+ return config.operatorKey || config.apiKey || '';
14
+ } catch {
15
+ // Ignore missing or unreadable operator.json on personal machines
16
+ return '';
17
+ }
18
+ }
19
+
20
+ function resolveActiveTier(licenseResult, apiKey, options, env, homeDir) {
21
+ if ((licenseResult.valid && licenseResult.tier === 'enterprise') || apiKey.startsWith('tg_ent_')) {
22
+ return 'Enterprise';
23
+ }
24
+ if (licenseResult.valid && licenseResult.tier === 'team') {
25
+ return 'Team';
26
+ }
27
+ if (isProLicensed({ ...options, env, homeDir }) || apiKey.startsWith('tg_pro_')) {
28
+ return 'Pro';
29
+ }
30
+ return 'Free';
31
+ }
6
32
 
7
33
  function getStatuslineMeta(options = {}) {
8
34
  const pkg = require(path.join(__dirname, '..', 'package.json'));
9
35
  const env = options.env || process.env;
10
36
  const homeDir = options.homeDir || env.HOME || env.USERPROFILE || '.';
11
- const fs = require('fs');
12
-
13
- // Enterprise detection based on key prefix
37
+
14
38
  let apiKey = env.THUMBGATE_OPERATOR_KEY || env.THUMBGATE_API_KEY || '';
15
- if (apiKey && !isValidKey(apiKey)) {
39
+ if (apiKey && !isValidKey(apiKey, { env, homeDir })) {
16
40
  apiKey = '';
17
41
  }
18
-
19
- // Fallback to reading from disk if not in env
20
42
  if (!apiKey) {
21
- try {
22
- const configPath = path.join(homeDir, '.config', 'thumbgate', 'operator.json');
23
- if (fs.existsSync(configPath)) {
24
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
25
- apiKey = config.operatorKey || config.apiKey || '';
26
- }
27
- } catch (_) { /* ignore disk read errors */ }
43
+ apiKey = readDiskOperatorKey(homeDir);
28
44
  }
29
45
 
30
- let activeTier = 'Free';
31
-
32
- if (apiKey.startsWith('tg_op_') || apiKey.startsWith('tg_creator_')) {
33
- activeTier = 'Enterprise';
34
- } else if (isProLicensed({ homeDir }) || apiKey.startsWith('tg_pro_')) {
35
- activeTier = 'Pro';
36
- }
46
+ const licenseResult = verifyLicense({ ...options, env, homeDir });
47
+ const activeTier = resolveActiveTier(licenseResult, apiKey, options, env, homeDir);
37
48
 
38
49
  return {
39
50
  version: String(pkg.version || '').trim() || 'unknown',
@@ -41,7 +52,7 @@ function getStatuslineMeta(options = {}) {
41
52
  };
42
53
  }
43
54
 
44
- if (require.main === module) {
55
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
45
56
  process.stdout.write(JSON.stringify(getStatuslineMeta()));
46
57
  }
47
58
 
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { loadMcpPolicy } = require('./mcp-policy');
5
+
6
+ const PROJECT_ROOT = path.join(__dirname, '..');
7
+ const DEFAULT_SUBAGENT_PROFILE_PATH = path.join(PROJECT_ROOT, 'config', 'subagent-profiles.json');
8
+
9
+ function getSubagentProfilePath() {
10
+ return process.env.THUMBGATE_SUBAGENT_PROFILE_PATH || DEFAULT_SUBAGENT_PROFILE_PATH;
11
+ }
12
+
13
+ function loadSubagentProfiles() {
14
+ const raw = fs.readFileSync(getSubagentProfilePath(), 'utf-8');
15
+ const parsed = JSON.parse(raw);
16
+ if (!parsed.profiles || typeof parsed.profiles !== 'object') {
17
+ throw new Error('Invalid subagent profile config: missing profiles object');
18
+ }
19
+ return parsed;
20
+ }
21
+
22
+ function listSubagentProfiles() {
23
+ const parsed = loadSubagentProfiles();
24
+ return Object.keys(parsed.profiles);
25
+ }
26
+
27
+ function getSubagentProfile(name) {
28
+ const parsed = loadSubagentProfiles();
29
+ const profile = parsed.profiles[name];
30
+ if (!profile) {
31
+ throw new Error(`Unknown subagent profile: ${name}`);
32
+ }
33
+ return profile;
34
+ }
35
+
36
+ function validateSubagentProfiles() {
37
+ const parsed = loadSubagentProfiles();
38
+ const policy = loadMcpPolicy();
39
+ const issues = [];
40
+
41
+ for (const [name, profile] of Object.entries(parsed.profiles)) {
42
+ if (!profile.mcpProfile) {
43
+ issues.push(`${name}: missing mcpProfile`);
44
+ } else if (!policy.profiles[profile.mcpProfile]) {
45
+ issues.push(`${name}: unknown mcpProfile '${profile.mcpProfile}'`);
46
+ }
47
+
48
+ if (!profile.context || typeof profile.context !== 'object') {
49
+ issues.push(`${name}: missing context settings`);
50
+ } else {
51
+ if (!Number.isFinite(profile.context.maxItems) || profile.context.maxItems <= 0) {
52
+ issues.push(`${name}: invalid context.maxItems`);
53
+ }
54
+ if (!Number.isFinite(profile.context.maxChars) || profile.context.maxChars <= 0) {
55
+ issues.push(`${name}: invalid context.maxChars`);
56
+ }
57
+ }
58
+ }
59
+
60
+ return {
61
+ valid: issues.length === 0,
62
+ issues,
63
+ };
64
+ }
65
+
66
+ module.exports = {
67
+ DEFAULT_SUBAGENT_PROFILE_PATH,
68
+ getSubagentProfilePath,
69
+ loadSubagentProfiles,
70
+ listSubagentProfiles,
71
+ getSubagentProfile,
72
+ validateSubagentProfiles,
73
+ };
74
+
75
+ if (require.main === module) {
76
+ const result = validateSubagentProfiles();
77
+ console.log(JSON.stringify({ profiles: listSubagentProfiles(), ...result }, null, 2));
78
+ process.exit(result.valid ? 0 : 1);
79
+ }
@@ -13,6 +13,7 @@ const crypto = require('node:crypto');
13
13
  const fs = require('node:fs');
14
14
  const path = require('node:path');
15
15
  const { getFeedbackPaths } = require('./feedback-paths');
16
+ const { projectForCapture, projectForRecord, matchesProject } = require('./project-identity');
16
17
  const { validateToolContract } = require('./tool-contract-validator');
17
18
 
18
19
  const OUTCOMES_FILE = 'task-outcome-receipts.jsonl';
@@ -145,8 +146,9 @@ function recordTaskOutcome(input = {}, options = {}) {
145
146
  throw error;
146
147
  }
147
148
 
149
+ Object.assign(receipt, projectForCapture({ ...input, ...options }, { hosted: Boolean(options.projectKey || options.hosted || require('./feedback-scope').tenantDataScope() || process.env.RAILWAY_PROJECT_ID || process.env.RAILWAY_ENVIRONMENT) }));
148
150
  const outcomesPath = getTaskOutcomesPath(options);
149
- const existing = readTaskOutcomes(options);
151
+ const existing = readTaskOutcomes({ ...options, projectKey: receipt.projectKey });
150
152
  const duplicate = existing.find((entry) => entry.idempotencyKey === receipt.idempotencyKey);
151
153
  if (duplicate) {
152
154
  if (duplicate.receiptHash !== receipt.receiptHash) {
@@ -160,6 +162,30 @@ function recordTaskOutcome(input = {}, options = {}) {
160
162
  fs.mkdirSync(path.dirname(outcomesPath), { recursive: true });
161
163
  fs.appendFileSync(outcomesPath, `${JSON.stringify(receipt)}\n`, 'utf8');
162
164
  recordOutcomeTrace(receipt, options);
165
+
166
+ // If task outcome succeeded and verified, verify any applied lessons
167
+ try {
168
+ const isSuccess = receipt.status === 'completed' && receipt.verification?.passed === true;
169
+ const lessonsToVerify = Array.isArray(input.appliedLessons)
170
+ ? input.appliedLessons
171
+ : Array.isArray(input.lessonIds)
172
+ ? input.lessonIds
173
+ : Array.isArray(input.metadata?.appliedLessons)
174
+ ? input.metadata.appliedLessons
175
+ : [];
176
+ if (isSuccess && lessonsToVerify.length > 0) {
177
+ const { verifyLesson } = require('./verified-lessons');
178
+ const checkCmd = receipt.verification?.verifier
179
+ || receipt.verification?.method
180
+ || (receipt.verification?.evidence && receipt.verification.evidence[0])
181
+ || 'task outcome verification passed';
182
+ for (const lessonId of lessonsToVerify) {
183
+ verifyLesson(lessonId, checkCmd, options);
184
+ }
185
+ }
186
+ } catch (_verErr) {
187
+ /* lesson verification on task outcome is non-blocking */
188
+ }
163
189
  return { recorded: true, duplicate: false, receipt };
164
190
  }
165
191
 
@@ -178,7 +204,8 @@ function readTaskOutcomes(options = {}) {
178
204
  .filter(Boolean)
179
205
  .flatMap((line) => {
180
206
  try {
181
- return [JSON.parse(line)];
207
+ const row = JSON.parse(line);
208
+ return matchesProject(projectForRecord(row), options.projectKey) ? [row] : [];
182
209
  } catch {
183
210
  return [];
184
211
  }