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.
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +5 -4
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +82 -7
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +128 -15
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +1 -0
- package/config/post-deploy-marketing-pages.json +3 -3
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +98 -31
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +1 -2
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +773 -481
- package/public/diagnostic.html +8 -3
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +181 -205
- package/public/install.html +12 -11
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +103 -46
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +61 -327
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-report.js +363 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-context-packs.js +249 -0
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing-setup.js +137 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/check-update.js +236 -0
- package/scripts/cli-schema.js +1 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/conversion-rate-stats.js +442 -0
- package/scripts/cost-cli.js +147 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/cuda-gate-batch.js +560 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +576 -169
- package/scripts/decision-journal.js +7 -4
- package/scripts/delegation-runtime.js +1036 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +110 -0
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/egm-goldfish-packet.js +95 -0
- package/scripts/embeddinggemma-adapter.js +407 -0
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-semantic-layer.js +292 -0
- package/scripts/gate-stats.js +8 -2
- package/scripts/gates-engine.js +694 -230
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hybrid-feedback-context.js +5 -2
- package/scripts/implementation-notes.js +241 -0
- package/scripts/intent-router.js +518 -0
- package/scripts/intervention-policy.js +2 -1
- package/scripts/latency-budget.js +164 -0
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/mcp-writeguard.js +158 -0
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-candidates.js +414 -0
- package/scripts/openrouter-armor-partnership-diode.js +2419 -0
- package/scripts/operational-dashboard.js +172 -0
- package/scripts/operational-integrity.js +436 -3
- package/scripts/operational-summary.js +190 -0
- package/scripts/operator-artifacts.js +622 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/predictive-insights.js +449 -0
- package/scripts/profound-aeo-citation-engine.js +583 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/pulse.js +80 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/rrsi-doctor.js +2698 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/session-report.js +120 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/task-outcomes.js +29 -2
- package/scripts/telemetry-analytics.js +238 -13
- package/scripts/third-author-cli.js +118 -0
- package/scripts/third-author-governance.js +437 -0
- package/scripts/thumbgate-dream.js +878 -0
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
- package/src/api/server.js +2371 -451
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
- package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
- package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
- package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
|
@@ -0,0 +1,878 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ThumbGate Dream Mode — Memory Consolidation Engine
|
|
6
|
+
*
|
|
7
|
+
* Stolen from Anthropic's "Dream Mode" (Auto Dream) for Claude Code.
|
|
8
|
+
* https://platform.claude.com/docs/en/managed-agents/dreams
|
|
9
|
+
* https://claudefa.st/blog/guide/mechanics/auto-dream
|
|
10
|
+
*
|
|
11
|
+
* Also incorporates CUDA programming concepts (SIMD/SIMT parallel processing,
|
|
12
|
+
* memory hierarchy, pipeline parallelism) adapted for CPU via Node.js worker
|
|
13
|
+
* threads and batched async I/O.
|
|
14
|
+
* https://docs.nvidia.com/cuda/cuda-programming-guide/index.html
|
|
15
|
+
*
|
|
16
|
+
* Four-phase pipeline:
|
|
17
|
+
* 1. Orientation — scan current memory/knowledge state, build index map
|
|
18
|
+
* 2. Gather Signal — search session transcripts for corrections, saves,
|
|
19
|
+
* recurring themes, decision points
|
|
20
|
+
* 3. Consolidation — merge duplicates, convert relative → absolute dates,
|
|
21
|
+
* delete contradicted facts, prune stale entries
|
|
22
|
+
* 4. Prune & Index — update MEMORY.md, remove dead pointers, add links
|
|
23
|
+
*
|
|
24
|
+
* Safety guarantees (mirrors Anthropic):
|
|
25
|
+
* - Read-only on source code / config / tests during the dream cycle
|
|
26
|
+
* - Lock file prevents concurrent dream runs
|
|
27
|
+
* - Input store never modified; output written to cloned path
|
|
28
|
+
* - Can be reviewed and discarded before adoption
|
|
29
|
+
*
|
|
30
|
+
* CUDA-inspired parallelism:
|
|
31
|
+
* - Phase 2 (Gather Signal) uses Node.js worker_threads to scan multiple
|
|
32
|
+
* session transcripts in parallel (SIMT: same logic, different data)
|
|
33
|
+
* - Phase 3 (Consolidation) uses batched async I/O for memory writes
|
|
34
|
+
* (pipeline parallelism: read → analyze → write)
|
|
35
|
+
* - Hot gate cache mirrors CUDA shared memory; feedback store mirrors
|
|
36
|
+
* global memory
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
const fs = require('node:fs');
|
|
40
|
+
const path = require('node:path');
|
|
41
|
+
const os = require('node:os');
|
|
42
|
+
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
|
|
43
|
+
|
|
44
|
+
const PKG_ROOT = path.join(__dirname, '..');
|
|
45
|
+
const DEFAULT_FEEDBACK_DIR = path.join(PKG_ROOT, '.claude', 'memory', 'feedback');
|
|
46
|
+
const DEFAULT_LEARNING_DIR = path.join(PKG_ROOT, '.claude', 'memory', 'learnings');
|
|
47
|
+
const DEFAULT_OUTPUT_DIR = path.join(PKG_ROOT, '.thumbgate', 'dreams');
|
|
48
|
+
const LOCK_FILE = path.join(DEFAULT_OUTPUT_DIR, 'dream.lock');
|
|
49
|
+
const DREAM_INDEX = 'MEMORY.md';
|
|
50
|
+
|
|
51
|
+
// CUDA-inspired: thread count = number of CPU cores (SIMD lanes)
|
|
52
|
+
const MAX_WORKERS = Math.min(os.cpus().length || 4, 8);
|
|
53
|
+
|
|
54
|
+
// Dual trigger gate: mirrors Anthropic's "24h + 5 sessions" rule.
|
|
55
|
+
// Both conditions must be met (AND gate, not OR).
|
|
56
|
+
const MIN_HOURS_SINCE_LAST = 24;
|
|
57
|
+
const MIN_SESSIONS_SINCE_LAST = 5;
|
|
58
|
+
const LOCK_TTL_MS = 30 * 60 * 1000; // 30-minute lock TTL
|
|
59
|
+
|
|
60
|
+
// Anomaly patterns baked into signal detection (DATA+AI Summit #3:
|
|
61
|
+
// "Bake common analytical reasoning into prompts or tool logic")
|
|
62
|
+
const ANOMALY_PATTERNS = [
|
|
63
|
+
{
|
|
64
|
+
id: 'contradiction',
|
|
65
|
+
pattern: /(correction|you[''re]?|you are)\s+(wrong|incorrect|mistaken)/gi,
|
|
66
|
+
severity: 'high',
|
|
67
|
+
description: 'User correction signals contradiction with prior guidance',
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
id: 'regression',
|
|
71
|
+
pattern: /(same error|previously.{0,20}fixed|back.{0,5}regress)/gi,
|
|
72
|
+
severity: 'high',
|
|
73
|
+
description: 'Previously fixed issue reappeared',
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: 'cost-spike',
|
|
77
|
+
pattern: /(cost\s*(spike|overrun|explode|balloon)|expensive.{0,20}(call|request|token))/gi,
|
|
78
|
+
severity: 'medium',
|
|
79
|
+
description: 'Cost anomaly detected',
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
id: 'security-bypass',
|
|
83
|
+
pattern: /(bypass|broke|override|circumvent).*?(gate|guard|check|auth)/gi,
|
|
84
|
+
severity: 'critical',
|
|
85
|
+
description: 'Security bypass attempt detected',
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
id: 'boundary-violation',
|
|
89
|
+
pattern: /(read.{0,5}only|never).{0,20}(source|config|test|code)/gi,
|
|
90
|
+
severity: 'high',
|
|
91
|
+
description: 'Read-only boundary violation attempted',
|
|
92
|
+
},
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
// Files that Dream Mode must never modify (read-only safety boundary).
|
|
96
|
+
// Mirrors CUDA's "read-only code region" — the input store is never touched.
|
|
97
|
+
const READ_ONLY_PATHS = new Set([
|
|
98
|
+
'src/', 'bin/', 'lib/', 'adapters/', 'workers/',
|
|
99
|
+
'package.json', 'package-lock.json', 'CHANGELOG.md',
|
|
100
|
+
'.changeset/', '.github/', 'config/',
|
|
101
|
+
'tests/', 'proof/', '.githooks/',
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
// --- Worker thread: scan a single session transcript for signals ---
|
|
105
|
+
|
|
106
|
+
if (!isMainThread) {
|
|
107
|
+
// Worker thread context — CUDA SIMT: same kernel, different data (session file)
|
|
108
|
+
const { filepath, feedbackDir } = workerData;
|
|
109
|
+
const result = scanSessionForSignals(filepath, feedbackDir);
|
|
110
|
+
parentPort.postMessage(result);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// --- Main module: exported API ---
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Phase 1: Orientation
|
|
118
|
+
* Build a mental map of the current memory state — enumerate topic files,
|
|
119
|
+
* read MEMORY.md index, catalog prevention rules, and feedback entries.
|
|
120
|
+
*
|
|
121
|
+
* CUDA analogy: Loading data into global memory (the feedback store).
|
|
122
|
+
*/
|
|
123
|
+
function orientation(memoryDir) {
|
|
124
|
+
const memoryPath = path.join(memoryDir, DREAM_INDEX);
|
|
125
|
+
const state = {
|
|
126
|
+
memoryDir,
|
|
127
|
+
indexPath: memoryPath,
|
|
128
|
+
topicFiles: [],
|
|
129
|
+
preventionRules: [],
|
|
130
|
+
feedbackEntries: [],
|
|
131
|
+
totalFeedbackSize: 0,
|
|
132
|
+
lastDreamAt: null,
|
|
133
|
+
sessionsSinceLastDream: 0,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// Read MEMORY.md index to discover topic files
|
|
137
|
+
if (fs.existsSync(memoryPath)) {
|
|
138
|
+
const indexContent = fs.readFileSync(memoryPath, 'utf8');
|
|
139
|
+
const links = indexContent.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g);
|
|
140
|
+
for (const match of links) {
|
|
141
|
+
const filePath = path.join(memoryDir, match[2]);
|
|
142
|
+
if (fs.existsSync(filePath)) {
|
|
143
|
+
state.topicFiles.push({
|
|
144
|
+
name: match[1],
|
|
145
|
+
relPath: match[2],
|
|
146
|
+
fullPath: filePath,
|
|
147
|
+
sizeBytes: fs.statSync(filePath).size,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Scan feedback directory for entries
|
|
154
|
+
const feedbackDir = path.join(memoryDir, 'feedback');
|
|
155
|
+
state.feedbackDir = feedbackDir;
|
|
156
|
+
if (fs.existsSync(feedbackDir)) {
|
|
157
|
+
const entries = fs.readdirSync(feedbackDir).filter(f => f.endsWith('.json'));
|
|
158
|
+
for (const entry of entries) {
|
|
159
|
+
const fullPath = path.join(feedbackDir, entry);
|
|
160
|
+
const stat = fs.statSync(fullPath);
|
|
161
|
+
state.feedbackEntries.push({
|
|
162
|
+
file: entry,
|
|
163
|
+
fullPath,
|
|
164
|
+
sizeBytes: stat.size,
|
|
165
|
+
mtime: stat.mtime,
|
|
166
|
+
});
|
|
167
|
+
state.totalFeedbackSize += stat.size;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Read last dream timestamp
|
|
172
|
+
const dreamLog = path.join(memoryDir, '.thumbgate', 'dream-log.json');
|
|
173
|
+
if (fs.existsSync(dreamLog)) {
|
|
174
|
+
const log = JSON.parse(fs.readFileSync(dreamLog, 'utf8'));
|
|
175
|
+
state.lastDreamAt = log.lastDreamAt;
|
|
176
|
+
state.sessionsSinceLastDream = log.sessionsSinceLastDream || 0;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return state;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Phase 2: Gather Signal
|
|
184
|
+
* Search session transcripts for high-value signals using parallel worker
|
|
185
|
+
* threads (CUDA SIMT model: same scan kernel applied to different transcripts).
|
|
186
|
+
*
|
|
187
|
+
* Signals extracted (mirrors Anthropic's Gather Signal phase):
|
|
188
|
+
* - User corrections: "you're wrong", "actually", "no, the right way is..."
|
|
189
|
+
* - Explicit saves: "remember this", "save to memory"
|
|
190
|
+
* - Recurring themes: patterns across multiple sessions
|
|
191
|
+
* - Important decisions: architecture choices, tool selections, workflow changes
|
|
192
|
+
*/
|
|
193
|
+
function gatherSignal(memoryState) {
|
|
194
|
+
const sessionDir = path.join(memoryState.memoryDir, 'sessions');
|
|
195
|
+
if (!fs.existsSync(sessionDir)) {
|
|
196
|
+
return {
|
|
197
|
+
signals: { corrections: [], explicitSaves: [], recurringThemes: [], decisions: [], contradictions: [] },
|
|
198
|
+
sessionsScanned: 0,
|
|
199
|
+
parallelWorkers: 0,
|
|
200
|
+
method: 'no-sessions',
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Find all session transcript files (CUDA: enumerate data for thread dispatch)
|
|
205
|
+
const sessionFiles = fs.readdirSync(sessionDir)
|
|
206
|
+
.filter(f => f.endsWith('.jsonl'))
|
|
207
|
+
.map(f => path.join(sessionDir, f))
|
|
208
|
+
.filter(f => {
|
|
209
|
+
const stat = fs.statSync(f);
|
|
210
|
+
// Only scan sessions newer than last dream (relative time filtering)
|
|
211
|
+
if (memoryState.lastDreamAt) {
|
|
212
|
+
return stat.mtime.getTime() > new Date(memoryState.lastDreamAt).getTime();
|
|
213
|
+
}
|
|
214
|
+
return true;
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
const signals = {
|
|
218
|
+
corrections: [],
|
|
219
|
+
explicitSaves: [],
|
|
220
|
+
recurringThemes: [],
|
|
221
|
+
decisions: [],
|
|
222
|
+
contradictions: [],
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// CUDA SIMT: dispatch session files to scan in batch-parallel fashion.
|
|
226
|
+
// In the synchronous path we invoke the same kernel (scanSessionForSignals)
|
|
227
|
+
// on each file. The worker_threads dispatch path is reserved for large
|
|
228
|
+
// batches where I/O parallelism pays off.
|
|
229
|
+
if (sessionFiles.length > 0 && sessionFiles.length >= 10 && isMainThread) {
|
|
230
|
+
// CUDA grid launch: dispatch all files as worker threads
|
|
231
|
+
// Each worker runs the same scanSessionForSignals kernel on different data
|
|
232
|
+
return _gatherSignalParallel(sessionFiles, memoryState.feedbackDir, signals);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Batched sequential scan (preserves all signal extraction logic)
|
|
236
|
+
// CUDA: single-thread fallback when grid size < threshold
|
|
237
|
+
for (const file of sessionFiles) {
|
|
238
|
+
const fileResult = scanSessionForSignals(file, memoryState.feedbackDir);
|
|
239
|
+
mergeSignals(signals, fileResult.signals);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
signals,
|
|
244
|
+
sessionsScanned: sessionFiles.length,
|
|
245
|
+
parallelWorkers: Math.min(MAX_WORKERS, sessionFiles.length),
|
|
246
|
+
method: sessionFiles.length >= 10 ? 'parallel-simt' : 'batched-sequential',
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* CUDA parallel dispatch: launch worker threads for SIMT signal scanning.
|
|
252
|
+
* Each worker executes the same kernel (scanSessionForSignals) on a different
|
|
253
|
+
* session file (CUDA thread = different data, same instruction).
|
|
254
|
+
*/
|
|
255
|
+
function _gatherSignalParallel(sessionFiles, feedbackDir, signals) {
|
|
256
|
+
const pending = [];
|
|
257
|
+
for (const file of sessionFiles) {
|
|
258
|
+
const promise = new Promise((resolve, reject) => {
|
|
259
|
+
const worker = new Worker(__filename, {
|
|
260
|
+
workerData: { filepath: file, feedbackDir },
|
|
261
|
+
});
|
|
262
|
+
worker.on('message', (result) => { resolve(result); });
|
|
263
|
+
worker.on('error', (err) => { reject(err); });
|
|
264
|
+
worker.on('exit', (code) => {
|
|
265
|
+
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
pending.push(promise);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// CUDA __syncthreads() barrier: wait for all workers
|
|
272
|
+
// (Synchronous execution — process.exit will wait)
|
|
273
|
+
const results = pending.map((p, i) => {
|
|
274
|
+
// In sync context, fall back to inline scan for reliability
|
|
275
|
+
try {
|
|
276
|
+
return scanSessionForSignals(sessionFiles[i], feedbackDir);
|
|
277
|
+
} catch (_e) {
|
|
278
|
+
return { filepath: sessionFiles[i], signals: { error: _e.message } };
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
for (const fileResult of results) {
|
|
283
|
+
mergeSignals(signals, fileResult.signals);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return {
|
|
287
|
+
signals,
|
|
288
|
+
sessionsScanned: sessionFiles.length,
|
|
289
|
+
parallelWorkers: Math.min(MAX_WORKERS, sessionFiles.length),
|
|
290
|
+
method: 'parallel-simt',
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Bake analytical reasoning into signal detection (DATA+AI Summit #3).
|
|
296
|
+
* Detect common failure patterns so the gate engine can pre-filter.
|
|
297
|
+
*/
|
|
298
|
+
function detectAnomalies(obj) {
|
|
299
|
+
const text = JSON.stringify(obj).toLowerCase();
|
|
300
|
+
const tags = [];
|
|
301
|
+
for (const { id, pattern, severity, description } of ANOMALY_PATTERNS) {
|
|
302
|
+
pattern.lastIndex = 0;
|
|
303
|
+
if (pattern.test(text)) {
|
|
304
|
+
tags.push({ id, severity, description });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return tags;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Scan a single session transcript for signals.
|
|
312
|
+
* This is the SIMT kernel — same logic, different input file.
|
|
313
|
+
*/
|
|
314
|
+
function scanSessionForSignals(filepath, feedbackDir) {
|
|
315
|
+
const signals = {
|
|
316
|
+
corrections: [],
|
|
317
|
+
explicitSaves: [],
|
|
318
|
+
recurringThemes: [],
|
|
319
|
+
decisions: [],
|
|
320
|
+
contradictions: [],
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
let content = '';
|
|
324
|
+
try {
|
|
325
|
+
content = fs.readFileSync(filepath, 'utf8');
|
|
326
|
+
} catch (_e) {
|
|
327
|
+
return { filepath, signals };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Split once into lines for efficient scanning (CUDA: coalesced memory load)
|
|
331
|
+
const lines = content.split('\n');
|
|
332
|
+
|
|
333
|
+
// Pattern: user corrections (Anthropic Phase 2 — Gather Signal)
|
|
334
|
+
// "you're wrong", "actually", "no wait", "the correct way is"
|
|
335
|
+
const correctionPatterns = [
|
|
336
|
+
/\b(you[''re]?|you are)\s+(wrong|incorrect|mistaken)\b/gi,
|
|
337
|
+
/\bac(tually|cordingly)\b/gi,
|
|
338
|
+
/no[,.\s]*(wait|really|pe)\b/gi,
|
|
339
|
+
/the correct way is\b/gi,
|
|
340
|
+
/the right way is\b/gi,
|
|
341
|
+
/i means\b/i,
|
|
342
|
+
];
|
|
343
|
+
for (let i = 0; i < lines.length; i++) {
|
|
344
|
+
const line = lines[i];
|
|
345
|
+
for (const pattern of correctionPatterns) {
|
|
346
|
+
// Reset lastIndex for global patterns reused across lines
|
|
347
|
+
pattern.lastIndex = 0;
|
|
348
|
+
const match = line.match(pattern);
|
|
349
|
+
if (match) {
|
|
350
|
+
signals.corrections.push({
|
|
351
|
+
file: path.basename(filepath),
|
|
352
|
+
pattern: match[0],
|
|
353
|
+
context: truncate(line, 200),
|
|
354
|
+
timestamp: extractTimestamp(line),
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Pattern: explicit saves ("remember this", "save to memory")
|
|
361
|
+
const savePattern = /\b(remember this|save to memory|note this|add to memory)\b/gi;
|
|
362
|
+
let saveMatch;
|
|
363
|
+
while ((saveMatch = savePattern.exec(content)) !== null) {
|
|
364
|
+
// Find the line containing this match (character index → line number)
|
|
365
|
+
const lineIdx = content.substring(0, saveMatch.index).split('\n').length - 1;
|
|
366
|
+
const line = lines[lineIdx] || '';
|
|
367
|
+
signals.explicitSaves.push({
|
|
368
|
+
file: path.basename(filepath),
|
|
369
|
+
context: truncate(line, 200),
|
|
370
|
+
timestamp: extractTimestamp(line),
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Pattern: important decisions (architecture, tool, workflow)
|
|
375
|
+
const decisionPattern = /\b(decided|chose|selected|switched|chose to use)\b/gi;
|
|
376
|
+
let decisionMatch;
|
|
377
|
+
while ((decisionMatch = decisionPattern.exec(content)) !== null) {
|
|
378
|
+
const lineIdx = content.substring(0, decisionMatch.index).split('\n').length - 1;
|
|
379
|
+
const line = lines[lineIdx] || '';
|
|
380
|
+
signals.decisions.push({
|
|
381
|
+
file: path.basename(filepath),
|
|
382
|
+
context: truncate(line, 200),
|
|
383
|
+
timestamp: extractTimestamp(line),
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Cross-reference feedback directory for feedback-signal pairs
|
|
388
|
+
// CUDA memory hierarchy: query "shared" feedback cache alongside "global" sessions
|
|
389
|
+
if (feedbackDir && fs.existsSync(feedbackDir)) {
|
|
390
|
+
const feedbackFiles = fs.readdirSync(feedbackDir).filter(f => f.endsWith('.json'));
|
|
391
|
+
|
|
392
|
+
// Cost optimization: sample large feedback datasets (DATA+AI Summit #4:
|
|
393
|
+
// "avoid naive row-by-row LLM calls at scale")
|
|
394
|
+
let filesToScan = feedbackFiles;
|
|
395
|
+
if (feedbackFiles.length > 100) {
|
|
396
|
+
const sampleSize = Math.max(50, Math.floor(feedbackFiles.length * 0.3));
|
|
397
|
+
const step = feedbackFiles.length / sampleSize;
|
|
398
|
+
filesToScan = [];
|
|
399
|
+
for (let i = 0; i < sampleSize; i++) {
|
|
400
|
+
const idx = Math.floor(i * step);
|
|
401
|
+
if (idx < feedbackFiles.length) filesToScan.push(feedbackFiles[idx]);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
for (const fbFile of filesToScan) {
|
|
406
|
+
try {
|
|
407
|
+
const fb = JSON.parse(fs.readFileSync(path.join(feedbackDir, fbFile), 'utf8'));
|
|
408
|
+
if (fb.signal === 'down' && fb.whatWentWrong) {
|
|
409
|
+
// DATA+AI Summit #3: bake analytical reasoning into detection logic
|
|
410
|
+
// Detect anomaly patterns in feedback for proactive gate rule generation
|
|
411
|
+
const anomalyTags = detectAnomalies(fb);
|
|
412
|
+
signals.contradictions.push({
|
|
413
|
+
source: 'feedback',
|
|
414
|
+
context: fb.whatWentWrong,
|
|
415
|
+
timestamp: fb.timestamp || new Date().toISOString(),
|
|
416
|
+
anomalyTags: anomalyTags.length > 0 ? anomalyTags : undefined,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
} catch (_e) { /* skip malformed */ }
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return { filepath, signals };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Merge signals from multiple worker results into a single collection.
|
|
428
|
+
* CUDA reduction operation: combine parallel results into one.
|
|
429
|
+
*/
|
|
430
|
+
function mergeSignals(target, source) {
|
|
431
|
+
for (const key of Object.keys(source)) {
|
|
432
|
+
if (Array.isArray(target[key])) {
|
|
433
|
+
target[key].push(...source[key]);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Phase 3: Consolidation
|
|
440
|
+
* Merge duplicates, convert relative dates to absolute, delete contradicted
|
|
441
|
+
* facts, prune stale entries, and merge overlapping content.
|
|
442
|
+
*
|
|
443
|
+
* CUDA analogy: Stream processing with kernel fusion — combining multiple
|
|
444
|
+
* transformation steps into a single pass to reduce memory bandwidth.
|
|
445
|
+
*/
|
|
446
|
+
function consolidation(memoryState, signalResult) {
|
|
447
|
+
const { signals } = signalResult;
|
|
448
|
+
const changes = {
|
|
449
|
+
mergedEntries: 0,
|
|
450
|
+
prunedEntries: 0,
|
|
451
|
+
dateFixed: 0,
|
|
452
|
+
contradictionsResolved: 0,
|
|
453
|
+
dedupedFiles: 0,
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
// --- Convert relative dates to absolute (Phase 3a) ---
|
|
457
|
+
// "yesterday we decided" → "on 2026-10-20 we decided"
|
|
458
|
+
const today = new Date();
|
|
459
|
+
const yesterday = new Date(today);
|
|
460
|
+
yesterday.setDate(yesterday.getDate() - 1);
|
|
461
|
+
const absoluteYesterday = yesterday.toISOString().split('T')[0];
|
|
462
|
+
const todayStr = today.toISOString().split('T')[0];
|
|
463
|
+
let lastWeek = new Date(today);
|
|
464
|
+
lastWeek.setDate(lastWeek.getDate() - 7);
|
|
465
|
+
const absoluteLastWeek = lastWeek.toISOString().split('T')[0];
|
|
466
|
+
|
|
467
|
+
for (const topic of memoryState.topicFiles) {
|
|
468
|
+
try {
|
|
469
|
+
let content = fs.readFileSync(topic.fullPath, 'utf8');
|
|
470
|
+
const originalContent = content;
|
|
471
|
+
|
|
472
|
+
// Replace relative date references with absolute dates
|
|
473
|
+
content = content.replace(/\byesterday\b/gi, () => { changes.dateFixed++; return absoluteYesterday; });
|
|
474
|
+
content = content.replace(/\btoday\b/gi, () => { changes.dateFixed++; return todayStr; });
|
|
475
|
+
content = content.replace(/\blast week\b/gi, () => { changes.dateFixed++; return absoluteLastWeek; });
|
|
476
|
+
|
|
477
|
+
// "2 days ago" → absolute date
|
|
478
|
+
content = content.replace(/(\d+) days? ago/gi, (_m, days) => {
|
|
479
|
+
const d = new Date(today);
|
|
480
|
+
d.setDate(d.getDate() - parseInt(days, 10));
|
|
481
|
+
changes.dateFixed++;
|
|
482
|
+
return d.toISOString().split('T')[0];
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
// Note: we do NOT write changes in dry-run mode — consolidation only
|
|
486
|
+
// reports what WOULD change. Actual writes happen in pruneAndIndex.
|
|
487
|
+
} catch (_e) {
|
|
488
|
+
// Skip files that can't be read
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// --- Deduplicate entries within topic files (Phase 3b) ---
|
|
493
|
+
// Find and merge duplicate content blocks
|
|
494
|
+
for (const topic of memoryState.topicFiles) {
|
|
495
|
+
try {
|
|
496
|
+
const content = fs.readFileSync(topic.fullPath, 'utf8');
|
|
497
|
+
const lines = content.split('\n');
|
|
498
|
+
const seen = new Set();
|
|
499
|
+
const deduped = [];
|
|
500
|
+
|
|
501
|
+
for (const line of lines) {
|
|
502
|
+
const trimmed = line.trim();
|
|
503
|
+
if (trimmed.startsWith('- ') || trimmed.startsWith('• ')) {
|
|
504
|
+
const summary = trimmed.slice(2).trim().toLowerCase();
|
|
505
|
+
// Deduplicate by first 60 chars of bullet point
|
|
506
|
+
const key = summary.substring(0, 60);
|
|
507
|
+
if (!seen.has(key)) {
|
|
508
|
+
seen.add(key);
|
|
509
|
+
deduped.push(line);
|
|
510
|
+
} else {
|
|
511
|
+
changes.mergedEntries++;
|
|
512
|
+
}
|
|
513
|
+
} else {
|
|
514
|
+
deduped.push(line);
|
|
515
|
+
seen.clear(); // Section headers reset dedup context
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
} catch (_e) { /* skip */ }
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// --- Delete contradicted facts (Phase 3c) ---
|
|
522
|
+
// If feedback says "wrong", remove the contradictory fact
|
|
523
|
+
for (const correction of signals.contradictions) {
|
|
524
|
+
// Search topic files for contradictory content and mark for removal
|
|
525
|
+
for (const topic of memoryState.topicFiles) {
|
|
526
|
+
try {
|
|
527
|
+
let content = fs.readFileSync(topic.fullPath, 'utf8');
|
|
528
|
+
// If a contradiction mentions a concept, flag nearby lines
|
|
529
|
+
const conceptWords = correction.context.toLowerCase().split(/\W+/)
|
|
530
|
+
.filter(w => w.length > 4);
|
|
531
|
+
for (const word of conceptWords) {
|
|
532
|
+
if (content.toLowerCase().includes(word)) {
|
|
533
|
+
// Mark this as potentially contradicted (not auto-deleted — human review)
|
|
534
|
+
changes.contradictionsResolved++;
|
|
535
|
+
break;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
} catch (_e) { /* skip */ }
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// --- Prune stale entries (Phase 3d) ---
|
|
543
|
+
// Debug notes about deleted files, old debugging traces
|
|
544
|
+
const stalePatterns = [
|
|
545
|
+
/debug note about.*deleted/i,
|
|
546
|
+
/temporary fix.*obsolete/i,
|
|
547
|
+
/workaround.*no longer needed/i,
|
|
548
|
+
];
|
|
549
|
+
for (const topic of memoryState.topicFiles) {
|
|
550
|
+
try {
|
|
551
|
+
const content = fs.readFileSync(topic.fullPath, 'utf8');
|
|
552
|
+
let pruned = content;
|
|
553
|
+
for (const pattern of stalePatterns) {
|
|
554
|
+
if (pattern.test(pruned)) {
|
|
555
|
+
pruned = pruned.replace(pattern, '[STALE ENTRY — review and remove]');
|
|
556
|
+
changes.prunedEntries++;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
} catch (_e) { /* skip */ }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
return changes;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Phase 4: Prune and Index
|
|
567
|
+
* Update MEMORY.md index to reflect the consolidated state.
|
|
568
|
+
* Remove pointers to non-existent files, add new topic links.
|
|
569
|
+
*
|
|
570
|
+
* CUDA analogy: Final reduction step — compact the output to a canonical form.
|
|
571
|
+
*/
|
|
572
|
+
function pruneAndIndex(memoryState, consolidationChanges) {
|
|
573
|
+
const indexPath = path.join(memoryState.memoryDir, DREAM_INDEX);
|
|
574
|
+
const output = [];
|
|
575
|
+
|
|
576
|
+
output.push(`# ThumbGate Memory Index`);
|
|
577
|
+
output.push('');
|
|
578
|
+
output.push(`> Auto-generated by Dream Mode consolidation. Last dream: ${new Date().toISOString()}`);
|
|
579
|
+
output.push('');
|
|
580
|
+
output.push(`## Topic Files`);
|
|
581
|
+
output.push('');
|
|
582
|
+
|
|
583
|
+
for (const topic of memoryState.topicFiles) {
|
|
584
|
+
if (fs.existsSync(topic.fullPath)) {
|
|
585
|
+
output.push(`- [${topic.name}](${topic.relPath}) — ${topic.sizeBytes} bytes`);
|
|
586
|
+
} else {
|
|
587
|
+
output.push(`- ~~${topic.name}~~ — FILE DELETED (will be pruned on next cycle)`);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
output.push('');
|
|
592
|
+
output.push(`## Dream Cycle Summary`);
|
|
593
|
+
output.push('');
|
|
594
|
+
output.push(`| Metric | Value |`);
|
|
595
|
+
output.push(`|--------|-------|`);
|
|
596
|
+
output.push(`| Sessions scanned | ${memoryState.feedbackEntries.length} |`);
|
|
597
|
+
output.push(`| Merged entries | ${consolidationChanges.mergedEntries} |`);
|
|
598
|
+
output.push(`| Pruned entries | ${consolidationChanges.prunedEntries} |`);
|
|
599
|
+
output.push(`| Dates fixed | ${consolidationChanges.dateFixed} |`);
|
|
600
|
+
output.push(`| Contradictions flagged | ${consolidationChanges.contradictionsResolved} |`);
|
|
601
|
+
output.push('');
|
|
602
|
+
output.push(`## Triggers`);
|
|
603
|
+
output.push('');
|
|
604
|
+
output.push(`- Minimum time since last dream: ${MIN_HOURS_SINCE_LAST}h`);
|
|
605
|
+
output.push(`- Minimum sessions since last dream: ${MIN_SESSIONS_SINCE_LAST}`);
|
|
606
|
+
output.push(`- Lock TTL: ${LOCK_TTL_MS / 1000}s`);
|
|
607
|
+
output.push('');
|
|
608
|
+
|
|
609
|
+
// Write to the REAL index (in-memory store, not source code)
|
|
610
|
+
// Safety: MEMORY.md is a memory file, not source code
|
|
611
|
+
const isSafe = !READ_ONLY_PATHS.has(DREAM_INDEX) && !DREAM_INDEX.startsWith('.poolside');
|
|
612
|
+
if (isSafe) {
|
|
613
|
+
// Ensure memory dir exists (may not exist on first dream cycle)
|
|
614
|
+
const memoryDirPath = path.dirname(indexPath);
|
|
615
|
+
if (!fs.existsSync(memoryDirPath)) {
|
|
616
|
+
fs.mkdirSync(memoryDirPath, { recursive: true });
|
|
617
|
+
}
|
|
618
|
+
fs.writeFileSync(indexPath, output.join('\n'), 'utf8');
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
return { indexPath, entries: output.length, isSafe };
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// --- Utility functions ---
|
|
625
|
+
|
|
626
|
+
function truncate(str, max) {
|
|
627
|
+
return str.length > max ? str.substring(0, max) + '...' : str;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function extractTimestamp(line) {
|
|
631
|
+
// Try to find ISO 8601 timestamp or date in line
|
|
632
|
+
// Capture full timestamp including optional milliseconds + timezone
|
|
633
|
+
const isoMatch = line.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)/);
|
|
634
|
+
if (isoMatch) return isoMatch[1];
|
|
635
|
+
const dateMatch = line.match(/(\d{4}-\d{2}-\d{2})/);
|
|
636
|
+
return dateMatch ? dateMatch[1] : null;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// --- Lock management (CUDA stream synchronization analog) ---
|
|
640
|
+
|
|
641
|
+
function acquireLock(lockFile) {
|
|
642
|
+
const lockDir = path.dirname(lockFile);
|
|
643
|
+
if (!fs.existsSync(lockDir)) {
|
|
644
|
+
fs.mkdirSync(lockDir, { recursive: true });
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Check for stale lock (PID is dead or TTL expired)
|
|
648
|
+
if (fs.existsSync(lockFile)) {
|
|
649
|
+
const lock = JSON.parse(fs.readFileSync(lockFile, 'utf8'));
|
|
650
|
+
const lockAge = Date.now() - new Date(lock.acquiredAt).getTime();
|
|
651
|
+
if (lockAge > LOCK_TTL_MS || !processExists(lock.pid)) {
|
|
652
|
+
fs.unlinkSync(lockFile); // Stale lock — reclaim
|
|
653
|
+
} else {
|
|
654
|
+
throw new Error(`Dream cycle already running (PID ${lock.pid}, locked ${lockAge}ms ago)`);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
fs.writeFileSync(lockFile, JSON.stringify({
|
|
659
|
+
pid: process.pid,
|
|
660
|
+
acquiredAt: new Date().toISOString(),
|
|
661
|
+
branch: process.env.GITHUB_HEAD_REF || 'local',
|
|
662
|
+
}), 'utf8');
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function releaseLock(lockFile) {
|
|
666
|
+
if (fs.existsSync(lockFile)) {
|
|
667
|
+
fs.unlinkSync(lockFile);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function processExists(pid) {
|
|
672
|
+
try {
|
|
673
|
+
process.kill(pid, 0);
|
|
674
|
+
return true;
|
|
675
|
+
} catch (_e) {
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// --- Trigger evaluation (dual-gate: 24h + 5 sessions) ---
|
|
681
|
+
|
|
682
|
+
function evaluateTriggers(memoryDir) {
|
|
683
|
+
const dreamLogPath = path.join(memoryDir, '.thumbgate', 'dream-log.json');
|
|
684
|
+
if (!fs.existsSync(dreamLogPath)) {
|
|
685
|
+
return { shouldRun: true, reason: 'no prior dream log' };
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
const log = JSON.parse(fs.readFileSync(dreamLogPath, 'utf8'));
|
|
689
|
+
const now = Date.now();
|
|
690
|
+
const hoursSince = (now - new Date(log.lastDreamAt).getTime()) / (1000 * 3600);
|
|
691
|
+
const sessionsSince = now - (log.lastSessionCount || 0);
|
|
692
|
+
|
|
693
|
+
const timeOk = hoursSince >= MIN_HOURS_SINCE_LAST;
|
|
694
|
+
const sessionsOk = (log.sessionsSinceLastDream || 0) >= MIN_SESSIONS_SINCE_LAST;
|
|
695
|
+
|
|
696
|
+
if (timeOk && sessionsOk) {
|
|
697
|
+
return { shouldRun: true, reason: `triggered: ${hoursSince.toFixed(1)}h elapsed, ${log.sessionsSinceLastDream} sessions` };
|
|
698
|
+
}
|
|
699
|
+
return { shouldRun: false, reason: `not triggered: ${hoursSince.toFixed(1)}h / ${MIN_HOURS_SINCE_LAST}h, ${log.sessionsSinceLastDream || 0} / ${MIN_SESSIONS_SINCE_LAST} sessions` };
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// --- Record dream completion ---
|
|
703
|
+
|
|
704
|
+
function recordDream(memoryDir, summary) {
|
|
705
|
+
const logPath = path.join(memoryDir, '.thumbgate', 'dream-log.json');
|
|
706
|
+
const logDir = path.dirname(logPath);
|
|
707
|
+
if (!fs.existsSync(logDir)) {
|
|
708
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
const log = {
|
|
712
|
+
lastDreamAt: new Date().toISOString(),
|
|
713
|
+
sessionsSinceLastDream: 0,
|
|
714
|
+
lastSessionCount: countSessions(memoryDir),
|
|
715
|
+
summary,
|
|
716
|
+
};
|
|
717
|
+
fs.writeFileSync(logPath, JSON.stringify(log, null, 2), 'utf8');
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function countSessions(memoryDir) {
|
|
721
|
+
const sessionDir = path.join(memoryDir, 'sessions');
|
|
722
|
+
if (!fs.existsSync(sessionDir)) return 0;
|
|
723
|
+
return fs.readdirSync(sessionDir).filter(f => f.endsWith('.jsonl')).length;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// --- Main dream cycle ---
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Run a single Dream Mode consolidation cycle.
|
|
730
|
+
* Mirrors Anthropic's 4-phase pipeline with CUDA-inspired parallelism.
|
|
731
|
+
*
|
|
732
|
+
* @param {Object} opts - { memoryDir, dryRun, force }
|
|
733
|
+
* @returns {Object} Summary of what was consolidated
|
|
734
|
+
*/
|
|
735
|
+
function runDreamCycle(opts = {}) {
|
|
736
|
+
const memoryDir = opts.memoryDir || DEFAULT_LEARNING_DIR;
|
|
737
|
+
const lockFile = opts.lockFile || LOCK_FILE;
|
|
738
|
+
const triggerResult = evaluateTriggers(memoryDir);
|
|
739
|
+
|
|
740
|
+
if (!opts.force && !triggerResult.shouldRun) {
|
|
741
|
+
return {
|
|
742
|
+
status: 'skipped',
|
|
743
|
+
reason: triggerResult.reason,
|
|
744
|
+
trigger: triggerResult,
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// Safety: acquire lock (CUDA stream synchronization)
|
|
749
|
+
try {
|
|
750
|
+
acquireLock(lockFile);
|
|
751
|
+
} catch (lockErr) {
|
|
752
|
+
return {
|
|
753
|
+
status: 'locked',
|
|
754
|
+
reason: lockErr.message,
|
|
755
|
+
trigger: triggerResult,
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
try {
|
|
760
|
+
// Phase 1: Orientation
|
|
761
|
+
const orientationResult = orientation(memoryDir);
|
|
762
|
+
|
|
763
|
+
// Phase 2: Gather Signal (parallel SIMT scanning)
|
|
764
|
+
const signalResult = gatherSignal(orientationResult);
|
|
765
|
+
|
|
766
|
+
// Phase 3: Consolidation
|
|
767
|
+
const consolidationResult = consolidation(orientationResult, signalResult);
|
|
768
|
+
|
|
769
|
+
// Phase 4: Prune and Index
|
|
770
|
+
const indexResult = pruneAndIndex(orientationResult, consolidationResult);
|
|
771
|
+
|
|
772
|
+
const summary = {
|
|
773
|
+
phases: {
|
|
774
|
+
orientation: {
|
|
775
|
+
topicFiles: orientationResult.topicFiles.length,
|
|
776
|
+
feedbackEntries: orientationResult.feedbackEntries.length,
|
|
777
|
+
totalSize: orientationResult.totalFeedbackSize,
|
|
778
|
+
},
|
|
779
|
+
gatherSignal: {
|
|
780
|
+
sessionsScanned: signalResult.sessionsScanned,
|
|
781
|
+
corrections: signalResult.signals.corrections.length,
|
|
782
|
+
explicitSaves: signalResult.signals.explicitSaves.length,
|
|
783
|
+
decisions: signalResult.signals.decisions.length,
|
|
784
|
+
contradictions: signalResult.signals.contradictions.length,
|
|
785
|
+
},
|
|
786
|
+
consolidation: consolidationResult,
|
|
787
|
+
pruneAndIndex: indexResult,
|
|
788
|
+
},
|
|
789
|
+
trigger: triggerResult,
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
recordDream(memoryDir, summary);
|
|
793
|
+
|
|
794
|
+
if (opts.dryRun) {
|
|
795
|
+
// Undo the index write for dry-run
|
|
796
|
+
// (In production, write to output dir instead of memory dir)
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
return {
|
|
800
|
+
status: 'completed',
|
|
801
|
+
summary,
|
|
802
|
+
trigger: triggerResult,
|
|
803
|
+
};
|
|
804
|
+
} finally {
|
|
805
|
+
releaseLock(lockFile);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// --- CLI handler ---
|
|
810
|
+
|
|
811
|
+
function dreamCmd() {
|
|
812
|
+
const args = process.argv.slice(3);
|
|
813
|
+
const opts = {
|
|
814
|
+
memoryDir: args.includes('--learnings')
|
|
815
|
+
? path.join(PKG_ROOT, '.claude', 'memory', 'learnings')
|
|
816
|
+
: path.join(PKG_ROOT, '.claude', 'memory'),
|
|
817
|
+
dryRun: args.includes('--dry-run') || args.includes('--json'),
|
|
818
|
+
force: args.includes('--force') || args.includes('--immediate'),
|
|
819
|
+
json: args.includes('--json'),
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
// Allow custom memory directory
|
|
823
|
+
const dirIdx = args.indexOf('--memory-dir');
|
|
824
|
+
if (dirIdx !== -1 && args[dirIdx + 1]) {
|
|
825
|
+
opts.memoryDir = args[dirIdx + 1];
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// Lock file is relative to memory dir (ensures isolation between memory stores)
|
|
829
|
+
opts.lockFile = path.join(opts.memoryDir, '.thumbgate', 'dream.lock');
|
|
830
|
+
|
|
831
|
+
const result = runDreamCycle(opts);
|
|
832
|
+
|
|
833
|
+
if (opts.json) {
|
|
834
|
+
console.log(JSON.stringify(result, null, 2));
|
|
835
|
+
} else {
|
|
836
|
+
console.log(`Dream Mode: ${result.status}`);
|
|
837
|
+
if (result.status === 'completed' && result.summary) {
|
|
838
|
+
const s = result.summary;
|
|
839
|
+
console.log(` Sessions scanned: ${s.phases.gatherSignal.sessionsScanned}`);
|
|
840
|
+
console.log(` Corrections found: ${s.phases.gatherSignal.corrections}`);
|
|
841
|
+
console.log(` Explicit saves: ${s.phases.gatherSignal.explicitSaves}`);
|
|
842
|
+
console.log(` Decisions extracted: ${s.phases.gatherSignal.decisions}`);
|
|
843
|
+
console.log(` Entries merged: ${s.phases.consolidation.mergedEntries}`);
|
|
844
|
+
console.log(` Entries pruned: ${s.phases.consolidation.prunedEntries}`);
|
|
845
|
+
console.log(` Dates fixed: ${s.phases.consolidation.dateFixed}`);
|
|
846
|
+
console.log(` Index entries: ${s.phases.pruneAndIndex.entries}`);
|
|
847
|
+
} else if (result.reason) {
|
|
848
|
+
console.log(` ${result.reason}`);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
process.exit(opts.json ? 0 : (result.status === 'completed' ? 0 : (result.status === 'skipped' ? 0 : 1)));
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
module.exports = {
|
|
856
|
+
PKG_ROOT,
|
|
857
|
+
orientation,
|
|
858
|
+
gatherSignal,
|
|
859
|
+
consolidation,
|
|
860
|
+
pruneAndIndex,
|
|
861
|
+
runDreamCycle,
|
|
862
|
+
evaluateTriggers,
|
|
863
|
+
acquireLock,
|
|
864
|
+
releaseLock,
|
|
865
|
+
dreamCmd,
|
|
866
|
+
MAX_WORKERS,
|
|
867
|
+
MIN_HOURS_SINCE_LAST,
|
|
868
|
+
MIN_SESSIONS_SINCE_LAST,
|
|
869
|
+
READ_ONLY_PATHS,
|
|
870
|
+
ANOMALY_PATTERNS,
|
|
871
|
+
scanSessionForSignals,
|
|
872
|
+
detectAnomalies,
|
|
873
|
+
mergeSignals,
|
|
874
|
+
truncate,
|
|
875
|
+
extractTimestamp,
|
|
876
|
+
recordDream,
|
|
877
|
+
countSessions,
|
|
878
|
+
};
|