thumbgate 1.40.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 (57) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/adapters/claude/.mcp.json +3 -3
  4. package/adapters/forge/forge.yaml +3 -3
  5. package/adapters/future-agi/.mcp.json +1 -1
  6. package/adapters/future-agi/config.toml +1 -1
  7. package/adapters/future-agi/opencode.json +1 -1
  8. package/adapters/herdr/herdr-plugin.toml +2 -2
  9. package/adapters/mcp/server-stdio.js +1 -1
  10. package/adapters/opencode/opencode.json +1 -1
  11. package/config/github-about.json +1 -1
  12. package/package.json +38 -5
  13. package/public/index.html +38 -152
  14. package/public/install.html +8 -8
  15. package/public/numbers.html +2 -2
  16. package/public/pricing.html +54 -335
  17. package/scripts/analytics-report.js +363 -0
  18. package/scripts/auto-context-packs.js +249 -0
  19. package/scripts/billing-setup.js +137 -0
  20. package/scripts/check-update.js +236 -0
  21. package/scripts/conversion-rate-stats.js +442 -0
  22. package/scripts/cost-cli.js +147 -0
  23. package/scripts/creator-campaigns.js +239 -0
  24. package/scripts/cuda-gate-batch.js +560 -0
  25. package/scripts/daemon-manager.js +108 -0
  26. package/scripts/dashboard.js +2 -2
  27. package/scripts/delegation-runtime.js +1036 -0
  28. package/scripts/dispatch-brief.js +159 -0
  29. package/scripts/distribution-surfaces.js +110 -0
  30. package/scripts/egm-goldfish-packet.js +95 -0
  31. package/scripts/embeddinggemma-adapter.js +407 -0
  32. package/scripts/funnel-analytics.js +35 -0
  33. package/scripts/gate-semantic-layer.js +292 -0
  34. package/scripts/implementation-notes.js +241 -0
  35. package/scripts/intent-router.js +518 -0
  36. package/scripts/latency-budget.js +164 -0
  37. package/scripts/mcp-writeguard.js +158 -0
  38. package/scripts/model-candidates.js +414 -0
  39. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  40. package/scripts/operational-dashboard.js +172 -0
  41. package/scripts/operational-summary.js +190 -0
  42. package/scripts/operator-artifacts.js +622 -0
  43. package/scripts/optimize-context.js +17 -0
  44. package/scripts/predictive-insights.js +449 -0
  45. package/scripts/profound-aeo-citation-engine.js +583 -0
  46. package/scripts/pulse.js +80 -0
  47. package/scripts/rrsi-doctor.js +2698 -0
  48. package/scripts/session-report.js +120 -0
  49. package/scripts/subagent-profiles.js +79 -0
  50. package/scripts/third-author-cli.js +118 -0
  51. package/scripts/third-author-governance.js +437 -0
  52. package/scripts/thumbgate-dream.js +878 -0
  53. package/server.json +2 -2
  54. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  55. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  56. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  57. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -0,0 +1,292 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Gate Semantic Layer — Curated "Gold" Rule View
6
+ *
7
+ * Stolen from DATA+AI Summit principle: "Plug agents into Gold tables and
8
+ * semantic layers, not raw data." Instead of letting agents (or gate evaluators)
9
+ * read raw feedback JSON files directly, we provide a curated, pre-validated,
10
+ * deduplicated "Gold" layer of prevention rules.
11
+ *
12
+ * Key improvements over raw rule loading:
13
+ * 1. Query pushdown: Only rules matching the specific tool + category are loaded
14
+ * (stops SELECT * from the entire feedback store)
15
+ * 2. Tiered caching: Global (disk) → Shared (hot cache) → Thread-local (input hash)
16
+ * 3. Human-reviewed metadata: Each rule carries source confidence, last reviewed date
17
+ * 4. Analytical reasoning baked in: Rules are tagged with anomaly patterns so the
18
+ * gate engine can pre-filter based on common failure modes
19
+ *
20
+ * https://docs.nvidia.com/cuda/cuda-programming-guide/index.html
21
+ */
22
+
23
+ const fs = require('node:fs');
24
+ const path = require('node:path');
25
+ const os = require('node:os');
26
+
27
+ const PKG_ROOT = path.join(__dirname, '..');
28
+ const FEEDBACK_DIR = path.join(PKG_ROOT, '.claude', 'memory', 'feedback');
29
+ const DEFAULT_RULES_FILE = path.join(PKG_ROOT, '.thumbgate', 'prevention-rules.json');
30
+
31
+ // CUDA L1 shared memory analog — hot cache for frequently accessed rules
32
+ const HOT_CACHE_TTL_MS = 60 * 1000;
33
+ const HOT_CACHE_MAX_ENTRIES = 1000;
34
+
35
+ // Sampling threshold: if feedback store exceeds this many entries, sample
36
+ // (stolen from DATA+AI Summit: "avoid naive row-by-row LLM calls at scale")
37
+ const SAMPLING_THRESHOLD = 100;
38
+ const SAMPLING_RATIO = 0.3; // 30% sample for large datasets
39
+
40
+ // Anomaly patterns baked into the semantic layer (DATA+AI Summit #3:
41
+ // "Bake common analytical reasoning into prompts")
42
+ const ANOMALY_PATTERNS = [
43
+ {
44
+ id: 'contradiction',
45
+ pattern: /(you[''re]?|you are)\s+(wrong|incorrect|mistaken)/gi,
46
+ severity: 'high',
47
+ description: 'User correction signals contradiction with prior guidance',
48
+ },
49
+ {
50
+ id: 'regression',
51
+ pattern: /(regression|back.{0,5}regress|same error again|previously.{0,20}fixed)/gi,
52
+ severity: 'high',
53
+ description: 'Previously fixed issue reappeared — regression risk',
54
+ },
55
+ {
56
+ id: 'cost-spike',
57
+ pattern: /(cost\s*(spike|overrun|explode|balloon)|expensive.{0,20}(call|request|token))/gi,
58
+ severity: 'medium',
59
+ description: 'Cost anomaly detected in agent behavior',
60
+ },
61
+ {
62
+ id: 'security-bypass',
63
+ pattern: /(bypass|broke|override|circumvent).*?(gate|guard|check|proteCTION|auth)/gi,
64
+ severity: 'critical',
65
+ description: 'Security bypass attempt detected',
66
+ },
67
+ {
68
+ id: 'boundary-violation',
69
+ pattern: /(read.{0,10}only|protect|never|don.t).*?(source|config|test|code)/gi,
70
+ severity: 'high',
71
+ description: 'Read-only boundary violation attempted',
72
+ },
73
+ ];
74
+
75
+ // Tool capability tags (for pushdown filtering)
76
+ const TOOL_TAGS = {
77
+ Bash: ['command', 'shell', 'execution'],
78
+ Edit: ['file-modification', 'path', 'write'],
79
+ Write: ['file-creation', 'path', 'write'],
80
+ Read: ['file-read', 'path', 'read'],
81
+ MultiSearch: ['search', 'multi-edit', 'glob'],
82
+ NotebookExec: ['code-execution', 'ipython', 'cell'],
83
+ };
84
+
85
+ /**
86
+ * Gold layer: A curated, pre-validated view of prevention rules.
87
+ * Instead of reading raw feedback JSON per-request, the Gold layer
88
+ * pre-processes rules with metadata: source confidence, last reviewed,
89
+ * anomaly tags, and tool applicability.
90
+ *
91
+ * @param {Object} opts - { rulesDir, feedbackDir, toolName, category }
92
+ * @returns {Array} Curated rules filtered by pushdown predicates
93
+ */
94
+ function loadGoldRules(opts = {}) {
95
+ const { rulesDir = PKG_ROOT, feedbackDir = FEEDBACK_DIR, toolName, category, sample = true } = opts;
96
+
97
+ // Handle both cases: rulesDir as PKG_ROOT or as the .thumbgate dir itself
98
+ let rulesFile = path.join(rulesDir, '.thumbgate', 'prevention-rules.json');
99
+ if (!fs.existsSync(rulesFile)) {
100
+ // Maybe rulesDir IS the .thumbgate directory
101
+ const altPath = path.join(rulesDir, 'prevention-rules.json');
102
+ if (fs.existsSync(altPath)) {
103
+ rulesFile = altPath;
104
+ }
105
+ }
106
+ const allRules = [];
107
+
108
+ // --- Global memory: read full prevention-rules.json ---
109
+ if (fs.existsSync(rulesFile)) {
110
+ try {
111
+ const data = JSON.parse(fs.readFileSync(rulesFile, 'utf8'));
112
+ for (const rule of (data.rules || [])) {
113
+ allRules.push(annotateRule(rule, 'curated', rulesFile));
114
+ }
115
+ } catch (_e) { /* skip malformed */ }
116
+ }
117
+
118
+ // --- Global memory: read feedback-derived rules ---
119
+ if (fs.existsSync(feedbackDir)) {
120
+ const entries = fs.readdirSync(feedbackDir).filter(f => f.endsWith('.json'));
121
+
122
+ // Query pushdown: if toolName is specified, only load feedback entries
123
+ // relevant to that tool (avoids loading the entire feedback store)
124
+ let filesToLoad = entries;
125
+ if (toolName) {
126
+ filesToLoad = entries.filter(f => {
127
+ const fullPath = path.join(feedbackDir, f);
128
+ try {
129
+ const data = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
130
+ return ruleAppliesToTool(data, toolName);
131
+ } catch (_e) {
132
+ return true; // On parse error, include (fail open for safety)
133
+ }
134
+ });
135
+ }
136
+
137
+ // Sampling for large datasets (cost optimization)
138
+ if (sample && filesToLoad.length > SAMPLING_THRESHOLD) {
139
+ const sampleSize = Math.max(
140
+ MATH_FLOOR(filesToLoad.length * SAMPLING_RATIO),
141
+ SAMPLING_THRESHOLD
142
+ );
143
+ // Deterministic sampling: evenly spread across the dataset
144
+ const step = filesToLoad.length / sampleSize;
145
+ const sampled = [];
146
+ for (let i = 0; i < sampleSize; i++) {
147
+ const idx = Math.floor(i * step);
148
+ if (idx < filesToLoad.length) {
149
+ sampled.push(filesToLoad[idx]);
150
+ }
151
+ }
152
+ filesToLoad = sampled;
153
+ }
154
+
155
+ for (const entry of filesToLoad) {
156
+ try {
157
+ const fb = JSON.parse(fs.readFileSync(path.join(feedbackDir, entry), 'utf8'));
158
+ if (fb.type === 'prevention_rule' && fb.rule) {
159
+ allRules.push(annotateRule(fb.rule, 'feedback', entry, {
160
+ feedbackId: fb.feedbackId || fb.id,
161
+ confidence: computeConfidence(fb),
162
+ anomalyTags: detectAnomalies(fb),
163
+ }));
164
+ }
165
+ } catch (_e) { /* skip malformed */ }
166
+ }
167
+ }
168
+
169
+ // --- Query pushdown: filter by tool + category ---
170
+ let filtered = allRules;
171
+ if (toolName) {
172
+ filtered = filtered.filter(r =>
173
+ ruleAppliesToTool(r, toolName) || r.tools === undefined
174
+ );
175
+ }
176
+ if (category) {
177
+ filtered = filtered.filter(r =>
178
+ (r.category || 'prevention') === category
179
+ );
180
+ }
181
+
182
+ return filtered;
183
+ }
184
+
185
+ /**
186
+ * Annotate a rule with metadata (source, confidence, review date).
187
+ * Gold layer rules carry richer metadata than raw feedback entries.
188
+ */
189
+ function annotateRule(rule, source, origin, extra = {}) {
190
+ return {
191
+ ...rule,
192
+ id: rule.id || `rule-${source}-${Math.random().toString(36).slice(2, 8)}`,
193
+ type: rule.type || 'pattern',
194
+ source,
195
+ origin: origin,
196
+ confidence: extra.confidence || 0.5,
197
+ lastReviewed: rule.lastReviewed || new Date().toISOString(),
198
+ anomalyTags: extra.anomalyTags || [],
199
+ tools: rule.tools || [],
200
+ decision: rule.decision || 'deny',
201
+ category: rule.category || 'prevention',
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Check if a rule applies to a specific tool.
207
+ * Rules with no tool restriction apply to all tools.
208
+ * Rules with tool restriction only apply to listed tools.
209
+ */
210
+ function ruleAppliesToTool(rule, toolName) {
211
+ if (!rule.tools || rule.tools.length === 0) return true;
212
+ return rule.tools.includes(toolName);
213
+ }
214
+
215
+ /**
216
+ * Compute confidence score for a feedback-derived rule.
217
+ * Higher confidence = more frequently violated rule.
218
+ */
219
+ function computeConfidence(feedbackEntry) {
220
+ const severity = feedbackEntry.severity || 1;
221
+ const recurrence = feedbackEntry.recurrenceCount || 1;
222
+ // Logarithmic scaling to avoid overfitting to outliers
223
+ return Math.min(0.99, 0.3 + Math.log(1 + recurrence * severity) / 10);
224
+ }
225
+
226
+ /**
227
+ * Detect anomaly patterns in feedback (DATA+AI Summit #3:
228
+ * bake analytical reasoning into prompts / tooling logic).
229
+ */
230
+ function detectAnomalies(feedbackEntry) {
231
+ const text = JSON.stringify(feedbackEntry).toLowerCase();
232
+ const tags = [];
233
+ for (const { id, pattern, severity } of ANOMALY_PATTERNS) {
234
+ if (pattern.test(text)) {
235
+ tags.push({ id, severity, description: pattern.description || id });
236
+ }
237
+ pattern.lastIndex = 0; // Reset for reuse
238
+ }
239
+ return tags;
240
+ }
241
+
242
+ /**
243
+ * Get the tool tags for a given tool name (pushdown filter optimization).
244
+ */
245
+ function getToolTags(toolName) {
246
+ return TOOL_TAGS[toolName] || [];
247
+ }
248
+
249
+ /**
250
+ * Describe the Gold layer schema (semantic layer metadata).
251
+ * Mirrors the DATA+AI Summit principle of providing a curated
252
+ * semantic layer that agents can explore in a single call.
253
+ */
254
+ function describeGoldLayer() {
255
+ return {
256
+ name: 'ThumbGate Prevention Rules — Gold Layer',
257
+ description: 'Curated, pre-validated, deduplicated prevention rules from feedback store and hand-authored rules',
258
+ version: '1.0',
259
+ sources: ['prevention-rules.json (curated)', '.claude/memory/feedback/ (feedback-derived)'],
260
+ ruleTypes: ['pattern', 'path', 'command', 'tool'],
261
+ categories: ['security', 'prevention', 'policy', 'compliance'],
262
+ anomalyPatterns: ANOMALY_PATTERNS.map(p => ({ id: p.id, severity: p.severity, description: p.description })),
263
+ sampling: {
264
+ threshold: SAMPLING_THRESHOLD,
265
+ ratio: SAMPLING_RATIO,
266
+ method: 'deterministic-even-sample',
267
+ },
268
+ pushdownFilters: ['toolName', 'category'],
269
+ cache: {
270
+ ttlMs: HOT_CACHE_TTL_MS,
271
+ maxEntries: HOT_CACHE_MAX_ENTRIES,
272
+ },
273
+ };
274
+ }
275
+
276
+ function MATH_FLOOR(x) { return Math.floor(x); }
277
+
278
+ module.exports = {
279
+ loadGoldRules,
280
+ annotateRule,
281
+ ruleAppliesToTool,
282
+ computeConfidence,
283
+ detectAnomalies,
284
+ getToolTags,
285
+ describeGoldLayer,
286
+ ANOMALY_PATTERNS,
287
+ TOOL_TAGS,
288
+ SAMPLING_THRESHOLD,
289
+ SAMPLING_RATIO,
290
+ HOT_CACHE_TTL_MS,
291
+ HOT_CACHE_MAX_ENTRIES,
292
+ };
@@ -0,0 +1,241 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+
7
+ const REPO_ROOT = path.resolve(__dirname, '..');
8
+ const DEFAULT_DIR = path.join(REPO_ROOT, '.thumbgate');
9
+ const MARKDOWN_NAME = 'implementation-notes.md';
10
+ const JSONL_NAME = 'implementation-notes.jsonl';
11
+
12
+ function resolvePaths({ dir } = {}) {
13
+ const base = dir ? path.resolve(dir) : DEFAULT_DIR;
14
+ return {
15
+ dir: base,
16
+ markdownPath: path.join(base, MARKDOWN_NAME),
17
+ jsonlPath: path.join(base, JSONL_NAME),
18
+ };
19
+ }
20
+
21
+ function ensureDir(dir) {
22
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
23
+ }
24
+
25
+ function normalizeText(value) {
26
+ if (value === null || value === undefined) return '';
27
+ return String(value).trim();
28
+ }
29
+
30
+ function noteId(record) {
31
+ const seed = `${record.timestamp}|${record.tool}|${record.decision}|${record.rationale}`;
32
+ return `note_${crypto.createHash('sha256').update(seed).digest('hex').slice(0, 12)}`;
33
+ }
34
+
35
+ function renderMarkdownEntry(record) {
36
+ const lines = [
37
+ `### ${record.id} — ${record.timestamp}`,
38
+ '',
39
+ `- **Tool**: ${record.tool || '(unspecified)'}`,
40
+ `- **Decision**: ${record.decision || '(none)'}`,
41
+ ];
42
+ if (record.rationale) lines.push(`- **Rationale**: ${record.rationale}`);
43
+ if (record.signal && record.signal !== 'info') lines.push(`- **Signal**: ${record.signal}`);
44
+ if (record.specSection) lines.push(`- **Spec section**: ${record.specSection}`);
45
+ if (record.tags && record.tags.length) lines.push(`- **Tags**: ${record.tags.join(', ')}`);
46
+ lines.push('');
47
+ return lines.join('\n');
48
+ }
49
+
50
+ function appendNote({ tool, decision, rationale, signal, specSection, tags, timestamp, dir } = {}) {
51
+ const decisionText = normalizeText(decision);
52
+ if (!decisionText) {
53
+ throw new Error('appendNote: decision is required');
54
+ }
55
+ const paths = resolvePaths({ dir });
56
+ ensureDir(paths.dir);
57
+
58
+ const record = {
59
+ timestamp: timestamp || new Date().toISOString(),
60
+ tool: normalizeText(tool) || 'unspecified',
61
+ decision: decisionText,
62
+ rationale: normalizeText(rationale),
63
+ signal: normalizeText(signal) || 'info',
64
+ specSection: normalizeText(specSection),
65
+ tags: Array.isArray(tags) ? tags.map(normalizeText).filter(Boolean) : [],
66
+ };
67
+ record.id = noteId(record);
68
+
69
+ if (!fs.existsSync(paths.markdownPath)) {
70
+ fs.writeFileSync(
71
+ paths.markdownPath,
72
+ '# Implementation Notes\n\nAuto-captured agent decisions, tradeoffs, and ambiguities. ' +
73
+ 'Promote high-value entries to durable lessons via `thumbgate notes promote <id>`.\n\n',
74
+ 'utf8',
75
+ );
76
+ }
77
+ fs.appendFileSync(paths.markdownPath, renderMarkdownEntry(record), 'utf8');
78
+ fs.appendFileSync(paths.jsonlPath, `${JSON.stringify(record)}\n`, 'utf8');
79
+
80
+ return record;
81
+ }
82
+
83
+ function listNotes({ dir, limit = 20 } = {}) {
84
+ const paths = resolvePaths({ dir });
85
+ if (!fs.existsSync(paths.jsonlPath)) return [];
86
+ const raw = fs.readFileSync(paths.jsonlPath, 'utf8');
87
+ const records = raw
88
+ .split('\n')
89
+ .filter(Boolean)
90
+ .map((line) => {
91
+ try {
92
+ return JSON.parse(line);
93
+ } catch (_err) {
94
+ return null;
95
+ }
96
+ })
97
+ .filter(Boolean);
98
+ return records.slice(-Math.max(1, Number(limit) || 20));
99
+ }
100
+
101
+ function findNote({ id, dir }) {
102
+ if (!id) return null;
103
+ const paths = resolvePaths({ dir });
104
+ if (!fs.existsSync(paths.jsonlPath)) return null;
105
+ const raw = fs.readFileSync(paths.jsonlPath, 'utf8');
106
+ for (const line of raw.split('\n').filter(Boolean)) {
107
+ try {
108
+ const record = JSON.parse(line);
109
+ if (record.id === id) return record;
110
+ } catch (_err) {
111
+ // ignore malformed lines
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+
117
+ function promoteToLesson({ id, dir, capture }) {
118
+ const record = findNote({ id, dir });
119
+ if (!record) {
120
+ throw new Error(`promoteToLesson: no note with id ${id}`);
121
+ }
122
+ if (typeof capture !== 'function') {
123
+ throw new Error('promoteToLesson: capture function required (inject the feedback-capture module to keep this module dependency-free)');
124
+ }
125
+ const result = capture({
126
+ feedback: record.signal === 'down' ? 'down' : record.signal === 'up' ? 'up' : 'down',
127
+ context: `[implementation-note ${record.id}] ${record.decision}`,
128
+ whatWentWrong: record.signal === 'down' ? record.rationale || record.decision : '',
129
+ whatWorked: record.signal === 'up' ? record.rationale || record.decision : '',
130
+ whatToChange: record.specSection ? `Update spec section: ${record.specSection}` : '',
131
+ tags: ['implementation-note', ...(record.tags || [])],
132
+ sourceNoteId: record.id,
133
+ });
134
+ return { noteId: record.id, captureResult: result };
135
+ }
136
+
137
+ function parseCliArgs(argv) {
138
+ const args = { _: [] };
139
+ for (const raw of argv) {
140
+ if (raw.startsWith('--')) {
141
+ const [key, value] = raw.slice(2).split('=');
142
+ if (value === undefined) args[key] = true;
143
+ else if (key === 'tags') args[key] = value.split(',').map((t) => t.trim()).filter(Boolean);
144
+ else args[key] = value;
145
+ } else {
146
+ args._.push(raw);
147
+ }
148
+ }
149
+ return args;
150
+ }
151
+
152
+ function cli(argv = process.argv.slice(3)) {
153
+ const subcommand = argv[0];
154
+ const rest = argv.slice(1);
155
+ const args = parseCliArgs(rest);
156
+
157
+ switch (subcommand) {
158
+ case 'append': {
159
+ const record = appendNote({
160
+ tool: args.tool,
161
+ decision: args.decision,
162
+ rationale: args.rationale,
163
+ signal: args.signal,
164
+ specSection: args['spec-section'] || args.section,
165
+ tags: args.tags,
166
+ dir: args.dir,
167
+ });
168
+ console.log(JSON.stringify(record, null, 2));
169
+ return record;
170
+ }
171
+ case 'list': {
172
+ const records = listNotes({ dir: args.dir, limit: args.limit });
173
+ if (args.json) {
174
+ console.log(JSON.stringify(records, null, 2));
175
+ } else if (records.length === 0) {
176
+ console.log('No implementation notes yet. Capture one via: thumbgate notes append --decision="..."');
177
+ } else {
178
+ for (const r of records) {
179
+ console.log(`${r.id} [${r.signal}] ${r.tool} ${r.decision.slice(0, 80)}`);
180
+ }
181
+ }
182
+ return records;
183
+ }
184
+ case 'show': {
185
+ const id = args._[0] || args.id;
186
+ const record = findNote({ id, dir: args.dir });
187
+ if (!record) {
188
+ console.error(`No note with id ${id}`);
189
+ process.exitCode = 1;
190
+ return null;
191
+ }
192
+ console.log(JSON.stringify(record, null, 2));
193
+ return record;
194
+ }
195
+ case 'promote': {
196
+ const id = args._[0] || args.id;
197
+ let capture;
198
+ try {
199
+ ({ captureFeedback: capture } = require(path.join(REPO_ROOT, 'scripts', 'capture-feedback')));
200
+ } catch (_err) {
201
+ capture = (payload) => {
202
+ console.log('[notes promote] (no capture-feedback module wired) payload:');
203
+ console.log(JSON.stringify(payload, null, 2));
204
+ return { dryRun: true };
205
+ };
206
+ }
207
+ const result = promoteToLesson({ id, dir: args.dir, capture });
208
+ console.log(JSON.stringify(result, null, 2));
209
+ return result;
210
+ }
211
+ default:
212
+ console.log('Usage: thumbgate notes <append|list|show|promote> [flags]');
213
+ console.log('');
214
+ console.log(' append Append an implementation note.');
215
+ console.log(' --decision="..." (required) --tool=<name> --rationale="..."');
216
+ console.log(' --signal=info|up|down --spec-section=<id> --tags=a,b,c');
217
+ console.log(' list Show recent notes. --json for raw, --limit=N to cap.');
218
+ console.log(' show Show a single note by id.');
219
+ console.log(' promote Promote a note to a durable lesson via capture-feedback.');
220
+ console.log('');
221
+ console.log('Storage: .thumbgate/implementation-notes.{md,jsonl} (gitignored).');
222
+ return null;
223
+ }
224
+ }
225
+
226
+ function isCliInvocation(argv = process.argv) {
227
+ return path.resolve(argv[1] || '') === path.resolve(__filename);
228
+ }
229
+
230
+ if (isCliInvocation()) {
231
+ cli(process.argv.slice(2));
232
+ }
233
+
234
+ module.exports = {
235
+ appendNote,
236
+ listNotes,
237
+ findNote,
238
+ promoteToLesson,
239
+ cli,
240
+ resolvePaths,
241
+ };