thumbgate 1.37.3 → 1.39.0
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/.agents/skills/aws-strands-harness-not-clone/SKILL.md +53 -0
- package/.agents/skills/bolt-forge-opt-in-not-clone/SKILL.md +72 -0
- package/.agents/skills/decisive-step-evaluator/SKILL.md +47 -0
- package/.agents/skills/fiddler-control-plane-honesty/SKILL.md +61 -0
- package/.agents/skills/halo-trace-optimize-not-clone/SKILL.md +60 -0
- package/.agents/skills/harness-evolution-ceiling/SKILL.md +52 -0
- package/.agents/skills/infoq-architect-honesty-not-clone/SKILL.md +37 -0
- package/.agents/skills/meko-datapack-honesty-not-clone/SKILL.md +45 -0
- package/.agents/skills/mintlify-knowledge-honesty-not-clone/SKILL.md +49 -0
- package/.agents/skills/model-distress-governance/SKILL.md +56 -0
- package/.agents/skills/omp-coordination-honesty-not-clone/SKILL.md +94 -0
- package/.agents/skills/saas-moat-honesty-not-clone/SKILL.md +22 -0
- package/.agents/skills/salt-code-policy-honesty-not-clone/SKILL.md +76 -0
- package/.agents/skills/siren-mcp-governance/SKILL.md +50 -0
- package/.agents/skills/vs-coverage-gap-not-clone/SKILL.md +69 -0
- package/.agents/skills/wisdom-context-artifact-not-clone/SKILL.md +67 -0
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/adapters/claude/.mcp.json +2 -2
- package/adapters/forge/forge.yaml +3 -3
- 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/hotdata/hotdata-vector-store.js +575 -0
- package/adapters/mcp/server-stdio.js +1 -1
- package/adapters/opencode/opencode.json +1 -1
- package/adapters/strands/STRANDS.md +107 -0
- package/adapters/strands/strands-box-diode.js +344 -0
- package/adapters/strands/strands-decider-adapter.js +445 -0
- package/adapters/strands/strands-middleware.js +192 -0
- package/adapters/tailscale/.mcp.json +15 -0
- package/adapters/tailscale/TAILSCALE.md +117 -0
- package/adapters/tailscale/config.toml +16 -0
- package/bin/cli.js +602 -21
- package/config/gate-templates.json +109 -0
- package/config/gates/default.json +13 -0
- package/config/schemas/task-outcome-receipt.schema.json +12 -0
- package/package.json +150 -21
- package/public/blog/2026-09-28-pretool-secret-deny.html +83 -0
- package/public/blog/2026-10-01-aws-strands-harness-token-firewall.html +77 -0
- package/public/blog/2026-10-01-model-distress-relief-seeking-firewall.html +71 -0
- package/public/blog/2026-10-02-salt-code-honest-steal-40-guardrails.html +106 -0
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +119 -0
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +141 -0
- package/public/connectors.html +329 -0
- package/public/enterprise-governance.html +311 -0
- package/public/gaming-playbook.html +732 -0
- package/public/index.html +77 -51
- package/public/install.html +7 -7
- package/public/learn.html +14 -0
- package/public/numbers.html +2 -2
- package/public/onboarding.html +794 -0
- package/public/operator-framework.html +385 -0
- package/public/pricing.html +14 -10
- package/scripts/activesaddler-curriculum-doctor.js +357 -0
- package/scripts/agent-context-artifact.js +325 -0
- package/scripts/agent-egress-policy.js +2 -2
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-outcome-eval.js +1 -1
- package/scripts/agent-reliability-client.js +148 -0
- package/scripts/apple-minions-idle-compute-steal.js +428 -0
- package/scripts/autoresearch-runner.js +20 -1
- package/scripts/billing.js +0 -1
- package/scripts/cli-demo.js +505 -1
- package/scripts/cli-schema.js +36 -0
- package/scripts/colab-compute-honesty.js +93 -0
- package/scripts/corporate-email-isolation-diode.js +299 -0
- package/scripts/coverage-gap.js +396 -0
- package/scripts/dashboard-chat.js +3 -3
- package/scripts/dashboard.js +2 -2
- package/scripts/decisive-step-doctor.js +256 -0
- package/scripts/decisive-step-evaluator.js +390 -0
- package/scripts/entitlement.js +18 -7
- package/scripts/experiment-tracker.js +5 -3
- package/scripts/feedback-loop.js +26 -3
- package/scripts/fiddler-control-plane-honesty.js +303 -0
- package/scripts/financial-control-plane.js +10 -2
- package/scripts/gates-engine.js +3 -1
- package/scripts/github-license-compliance-diode.js +378 -0
- package/scripts/halo-trace-optimizer.js +631 -0
- package/scripts/harness-ceiling-doctor.js +326 -0
- package/scripts/hf-papers.js +1 -1
- package/scripts/human-escalation.js +7 -1
- package/scripts/hybrid-feedback-context.js +53 -7
- package/scripts/infoq-architect-honesty.js +362 -0
- package/scripts/lesson-graph.js +785 -0
- package/scripts/lesson-inference.js +1 -1
- package/scripts/lesson-retrieval.js +26 -18
- package/scripts/license.js +122 -21
- package/scripts/llm-behavior-monitor.js +1 -1
- package/scripts/llm-obs-honesty.js +52 -0
- package/scripts/local-model-profile.js +11 -7
- package/scripts/mailer/resend-mailer.js +6 -3
- package/scripts/mcp-transport-strategy.js +1 -1
- package/scripts/meko-datapack-honesty.js +414 -0
- package/scripts/migrate-lesson-graph.js +442 -0
- package/scripts/mintlify-knowledge-honesty.js +647 -0
- package/scripts/model-distress-detector.js +207 -0
- package/scripts/model-distress-doctor.js +368 -0
- package/scripts/multi-harness-invariants.js +305 -0
- package/scripts/omp-coordination-honesty.js +488 -0
- package/scripts/pro-local-dashboard.js +20 -3
- package/scripts/prompt-eval.js +1 -1
- package/scripts/prove-herdr-adapter.js +367 -3
- package/scripts/rag-embedding-identity.js +1 -1
- package/scripts/rrsi-regularizer.js +531 -0
- package/scripts/saas-moat-honesty.js +443 -0
- package/scripts/salt-code-policy-honesty.js +1204 -0
- package/scripts/secret-redaction.js +58 -0
- package/scripts/session-export-gate.js +368 -0
- package/scripts/siren-mcp-governance.js +539 -0
- package/scripts/strands-box-doctor.js +130 -0
- package/scripts/strands-harness-doctor.js +390 -0
- package/scripts/stripe-revenue-catalog-audit.js +12 -0
- package/scripts/stripe-revenue-catalog.js +40 -0
- package/scripts/switchyard-router.js +153 -0
- package/scripts/tailscale-p2p-doctor.js +252 -0
- package/scripts/task-outcomes.js +148 -3
- package/scripts/thumbgate-board-loop.js +4 -2
- package/scripts/thumbgate-daily-discoveries-publish.js +86 -38
- package/scripts/triage-savings-calculator.js +181 -0
- package/scripts/vector-store.js +41 -2
- package/scripts/vulnerability-pre-action-diode.js +319 -0
- package/scripts/windbg-evidence-diagnostics.js +241 -0
- package/scripts/workflow-intake-queue.js +1 -1
- package/scripts/workspace-agent-routines.js +534 -6
- package/scripts/workspace-evolver.js +143 -13
- package/server.json +2 -2
- package/skills/aws-strands-harness-not-clone/SKILL.md +53 -0
- package/skills/siren-mcp-governance/SKILL.md +50 -0
- package/src/api/server.js +191 -5
- package/src/mcp-writeguard.js +1 -1
- package/src/session-interactivity.js +284 -0
|
@@ -0,0 +1,785 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// Scoped identity and lineage overlay. JSONL remains the content authority.
|
|
5
|
+
// Edges: newer -> older for supersedes/refines/contradicts; duplicate -> canonical.
|
|
6
|
+
// Unknown or incomplete scopes remain independent and never authorize graph substitution.
|
|
7
|
+
|
|
8
|
+
const path = require('node:path');
|
|
9
|
+
const fs = require('node:fs');
|
|
10
|
+
const { normalizeScope, missingScopeFields } = require('./memory-scope-readiness');
|
|
11
|
+
|
|
12
|
+
function scopeKey(record) {
|
|
13
|
+
const scope = normalizeScope(record || {});
|
|
14
|
+
return missingScopeFields(scope).length ? null : JSON.stringify([scope.entityId, scope.projectId, scope.processId, scope.sessionId]);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function sameScope(a, b) {
|
|
18
|
+
const key = scopeKey(a);
|
|
19
|
+
return key !== null && key === scopeKey(b);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function sameScopeIdentity(a, b) {
|
|
23
|
+
const left = normalizeScope(a);
|
|
24
|
+
const right = normalizeScope(b);
|
|
25
|
+
return Object.keys(left).every(field => left[field] === right[field]);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const EDGE_TYPES = ['supersedes', 'contradicts', 'duplicate_of', 'refines'];
|
|
29
|
+
const LINEAGE_EDGE_TYPES = new Set(['supersedes', 'refines']);
|
|
30
|
+
const MAX_TRAVERSAL_HOPS = 32;
|
|
31
|
+
|
|
32
|
+
// High-confidence duplicate threshold on character-bigram Jaccard of the
|
|
33
|
+
// canonicalized text. 0.9 is deliberately stricter than the 0.82 retrieval
|
|
34
|
+
// heuristic in lesson-retrieval.dedupeSupersededLessons: incrementing a
|
|
35
|
+
// counter instead of storing a record is destructive-ish, so only collapse
|
|
36
|
+
// when the texts are essentially the same sentence.
|
|
37
|
+
const DUPLICATE_SIMILARITY_THRESHOLD = 0.9;
|
|
38
|
+
|
|
39
|
+
// Same-topic threshold used to flag contradictions (opposite signal on the
|
|
40
|
+
// same topic). Mirrors dedupeSupersededLessons' similarityThreshold.
|
|
41
|
+
const CONTRADICTION_SIMILARITY_THRESHOLD = 0.82;
|
|
42
|
+
|
|
43
|
+
function resolveDefaultGraphDbPath(options = {}) {
|
|
44
|
+
if (options.graphDbPath) return options.graphDbPath;
|
|
45
|
+
if (process.env.THUMBGATE_LESSON_GRAPH_DB_PATH) {
|
|
46
|
+
return process.env.THUMBGATE_LESSON_GRAPH_DB_PATH;
|
|
47
|
+
}
|
|
48
|
+
const { resolveFeedbackDir } = require('./feedback-paths');
|
|
49
|
+
const dir = options.feedbackDir || resolveFeedbackDir(options);
|
|
50
|
+
return path.join(dir, 'lesson-graph.sqlite');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @returns {import('better-sqlite3').Database} */
|
|
54
|
+
function initGraphDB(dbPath) {
|
|
55
|
+
const Database = require('better-sqlite3');
|
|
56
|
+
const resolvedPath = dbPath || resolveDefaultGraphDbPath();
|
|
57
|
+
|
|
58
|
+
const dir = path.dirname(resolvedPath);
|
|
59
|
+
if (!fs.existsSync(dir)) {
|
|
60
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const db = new Database(resolvedPath);
|
|
64
|
+
db.pragma('busy_timeout = 3000');
|
|
65
|
+
db.pragma('journal_mode = WAL');
|
|
66
|
+
|
|
67
|
+
db.exec(`
|
|
68
|
+
CREATE TABLE IF NOT EXISTS lesson_nodes (
|
|
69
|
+
id TEXT PRIMARY KEY,
|
|
70
|
+
source_feedback_id TEXT,
|
|
71
|
+
entityId TEXT, projectId TEXT, processId TEXT, sessionId TEXT,
|
|
72
|
+
canonical_id TEXT,
|
|
73
|
+
title TEXT,
|
|
74
|
+
signal TEXT,
|
|
75
|
+
canonical_hash TEXT,
|
|
76
|
+
canonical_text TEXT,
|
|
77
|
+
duplicate_count INTEGER NOT NULL DEFAULT 1,
|
|
78
|
+
valid_from TEXT NOT NULL,
|
|
79
|
+
valid_to TEXT,
|
|
80
|
+
ingested_at TEXT NOT NULL
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
CREATE INDEX IF NOT EXISTS idx_lesson_nodes_source_feedback
|
|
84
|
+
ON lesson_nodes(source_feedback_id);
|
|
85
|
+
CREATE INDEX IF NOT EXISTS idx_lesson_nodes_canonical_hash
|
|
86
|
+
ON lesson_nodes(canonical_hash);
|
|
87
|
+
CREATE INDEX IF NOT EXISTS idx_lesson_nodes_canonical_id
|
|
88
|
+
ON lesson_nodes(canonical_id);
|
|
89
|
+
|
|
90
|
+
CREATE TABLE IF NOT EXISTS lesson_edges (
|
|
91
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
92
|
+
src TEXT NOT NULL,
|
|
93
|
+
dst TEXT NOT NULL,
|
|
94
|
+
type TEXT NOT NULL CHECK(type IN ('supersedes','contradicts','duplicate_of','refines')),
|
|
95
|
+
valid_from TEXT NOT NULL,
|
|
96
|
+
valid_to TEXT,
|
|
97
|
+
ingested_at TEXT NOT NULL,
|
|
98
|
+
UNIQUE(src, dst, type)
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
CREATE INDEX IF NOT EXISTS idx_lesson_edges_src ON lesson_edges(src);
|
|
102
|
+
CREATE INDEX IF NOT EXISTS idx_lesson_edges_dst ON lesson_edges(dst);
|
|
103
|
+
`);
|
|
104
|
+
|
|
105
|
+
const columns = new Set(db.prepare('PRAGMA table_info(lesson_nodes)').all().map(row => row.name));
|
|
106
|
+
for (const field of ['entityId', 'projectId', 'processId', 'sessionId']) {
|
|
107
|
+
if (!columns.has(field)) db.exec('ALTER TABLE lesson_nodes ADD COLUMN ' + field + ' TEXT');
|
|
108
|
+
}
|
|
109
|
+
db.exec(`
|
|
110
|
+
CREATE INDEX IF NOT EXISTS idx_lesson_nodes_scope
|
|
111
|
+
ON lesson_nodes(entityId, projectId, processId, sessionId, signal, canonical_hash);
|
|
112
|
+
CREATE TABLE IF NOT EXISTS graph_version (id INTEGER PRIMARY KEY CHECK(id = 1), generation TEXT, revision INTEGER NOT NULL);
|
|
113
|
+
INSERT OR IGNORE INTO graph_version VALUES (1, lower(hex(randomblob(16))), 0);
|
|
114
|
+
CREATE TRIGGER IF NOT EXISTS graph_node_insert AFTER INSERT ON lesson_nodes BEGIN UPDATE graph_version SET revision = revision + 1; END;
|
|
115
|
+
CREATE TRIGGER IF NOT EXISTS graph_node_update AFTER UPDATE ON lesson_nodes BEGIN UPDATE graph_version SET revision = revision + 1; END;
|
|
116
|
+
CREATE TRIGGER IF NOT EXISTS graph_node_delete AFTER DELETE ON lesson_nodes BEGIN UPDATE graph_version SET revision = revision + 1; END;
|
|
117
|
+
CREATE TRIGGER IF NOT EXISTS graph_edge_insert AFTER INSERT ON lesson_edges BEGIN UPDATE graph_version SET revision = revision + 1; END;
|
|
118
|
+
CREATE TRIGGER IF NOT EXISTS graph_edge_delete AFTER DELETE ON lesson_edges BEGIN UPDATE graph_version SET revision = revision + 1; END;
|
|
119
|
+
CREATE TRIGGER IF NOT EXISTS graph_edge_update AFTER UPDATE ON lesson_edges BEGIN UPDATE graph_version SET revision = revision + 1; END;
|
|
120
|
+
`);
|
|
121
|
+
return db;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Open the graph DB only when its file already exists. The retrieval hot
|
|
126
|
+
* path (PreToolUse hook) must never create new files in a feedback dir that
|
|
127
|
+
* was never migrated — absence of the graph means "graph layer disabled".
|
|
128
|
+
*
|
|
129
|
+
* @returns {import('better-sqlite3').Database|null}
|
|
130
|
+
*/
|
|
131
|
+
function openGraphDBIfExists(options = {}) {
|
|
132
|
+
try {
|
|
133
|
+
const dbPath = resolveDefaultGraphDbPath(options);
|
|
134
|
+
if (!fs.existsSync(dbPath)) return null;
|
|
135
|
+
return initGraphDB(dbPath);
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------------------------------------------------------------------------
|
|
142
|
+
// Node / edge primitives
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
function nowIso() {
|
|
146
|
+
return new Date().toISOString();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function lessonSignal(lesson) {
|
|
150
|
+
if (!lesson || typeof lesson !== 'object') return 'positive';
|
|
151
|
+
if (lesson.signal === 'negative' || lesson.signal === 'positive') return lesson.signal;
|
|
152
|
+
if (Array.isArray(lesson.tags) && lesson.tags.includes('negative')) return 'negative';
|
|
153
|
+
if (lesson.feedback === 'down' || lesson.signal === 'down') return 'negative';
|
|
154
|
+
return 'positive';
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function lessonText(lesson) {
|
|
158
|
+
if (!lesson || typeof lesson !== 'object') return '';
|
|
159
|
+
return [lesson.title, lesson.content, lesson.whatWentWrong, lesson.whatToChange, lesson.context]
|
|
160
|
+
.filter(Boolean)
|
|
161
|
+
.map(String)
|
|
162
|
+
.join(' ')
|
|
163
|
+
.trim();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Upsert a node. Preserves duplicate_count / canonical_id / valid_to on
|
|
168
|
+
* conflict so re-registering a lesson never resets graph state (idempotent).
|
|
169
|
+
*/
|
|
170
|
+
function upsertNode(db, node) {
|
|
171
|
+
if (!node || !node.id) return null;
|
|
172
|
+
const old = getNode(db, node.id);
|
|
173
|
+
if (old && !sameScopeIdentity(old, node)) throw new Error('lesson-graph: id already belongs to another scope');
|
|
174
|
+
const scope = normalizeScope(node);
|
|
175
|
+
const { canonicalizeText } = require('./lesson-canonical');
|
|
176
|
+
const canonicalText = node.canonicalText != null
|
|
177
|
+
? node.canonicalText
|
|
178
|
+
: canonicalizeText(node.title || '');
|
|
179
|
+
db.prepare(`
|
|
180
|
+
INSERT INTO lesson_nodes
|
|
181
|
+
(id, entityId, projectId, processId, sessionId, source_feedback_id, canonical_id, title, signal, canonical_hash, canonical_text,
|
|
182
|
+
duplicate_count, valid_from, valid_to, ingested_at)
|
|
183
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
184
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
185
|
+
title = excluded.title,
|
|
186
|
+
signal = excluded.signal,
|
|
187
|
+
canonical_hash = COALESCE(excluded.canonical_hash, lesson_nodes.canonical_hash),
|
|
188
|
+
canonical_text = COALESCE(excluded.canonical_text, lesson_nodes.canonical_text),
|
|
189
|
+
source_feedback_id = COALESCE(excluded.source_feedback_id, lesson_nodes.source_feedback_id),
|
|
190
|
+
duplicate_count = MAX(lesson_nodes.duplicate_count, excluded.duplicate_count)
|
|
191
|
+
`).run(
|
|
192
|
+
node.id,
|
|
193
|
+
scope.entityId, scope.projectId, scope.processId, scope.sessionId,
|
|
194
|
+
node.sourceFeedbackId || null,
|
|
195
|
+
node.canonicalId || null,
|
|
196
|
+
node.title != null ? String(node.title).slice(0, 500) : null,
|
|
197
|
+
node.signal || 'positive',
|
|
198
|
+
node.canonicalHash || null,
|
|
199
|
+
canonicalText != null ? String(canonicalText).slice(0, 2000) : null,
|
|
200
|
+
Number.isFinite(node.duplicateCount) && node.duplicateCount > 0 ? Math.floor(node.duplicateCount) : 1,
|
|
201
|
+
node.validFrom || nowIso(),
|
|
202
|
+
node.validTo || null,
|
|
203
|
+
node.ingestedAt || nowIso(),
|
|
204
|
+
);
|
|
205
|
+
return node.id;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function getNode(db, id) {
|
|
209
|
+
if (!id) return null;
|
|
210
|
+
return db.prepare('SELECT * FROM lesson_nodes WHERE id = ?').get(id) || null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Resolve a lesson reference to a node id. References in correction text are
|
|
215
|
+
* frequently truncated ("fb_1780589059204" for "fb_1780589059204_abc123"),
|
|
216
|
+
* so fall back to a unique prefix match on id / source_feedback_id.
|
|
217
|
+
*/
|
|
218
|
+
function resolveNodeRef(db, ref, scope, { exactOnly = false } = {}) {
|
|
219
|
+
if (!ref || !scopeKey(scope)) return null;
|
|
220
|
+
const rows = db.prepare('SELECT * FROM lesson_nodes WHERE id = ? OR source_feedback_id = ?').all(ref, ref)
|
|
221
|
+
.filter(row => sameScope(row, scope));
|
|
222
|
+
if (rows.length === 1) return rows[0].id;
|
|
223
|
+
if (rows.length > 1) return null;
|
|
224
|
+
if (exactOnly) return null;
|
|
225
|
+
const normalized = normalizeScope(scope);
|
|
226
|
+
const needle = String(ref);
|
|
227
|
+
const prefixed = db.prepare(`
|
|
228
|
+
SELECT id, source_feedback_id FROM lesson_nodes
|
|
229
|
+
WHERE entityId = ? AND projectId = ? AND processId = ? AND sessionId = ?
|
|
230
|
+
`).all(normalized.entityId, normalized.projectId, normalized.processId, normalized.sessionId)
|
|
231
|
+
.filter(row => row.id.startsWith(needle) || String(row.source_feedback_id || '').startsWith(needle));
|
|
232
|
+
return prefixed.length === 1 ? prefixed[0].id : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Close a node's validity interval (it is no longer the current fact).
|
|
237
|
+
* Only sets valid_to when currently open, preserving the first closure.
|
|
238
|
+
*/
|
|
239
|
+
function closeNodeValidity(db, id, at) {
|
|
240
|
+
if (!id) return false;
|
|
241
|
+
const result = db.prepare(
|
|
242
|
+
'UPDATE lesson_nodes SET valid_to = ? WHERE id = ? AND valid_to IS NULL',
|
|
243
|
+
).run(at || nowIso(), id);
|
|
244
|
+
return result.changes > 0;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Add a typed edge src → dst. Idempotent (UNIQUE(src,dst,type) + OR IGNORE).
|
|
249
|
+
* For supersedes/refines the old fact's valid_to is closed at the edge's
|
|
250
|
+
* valid_from — the bitemporal contract of a correction.
|
|
251
|
+
*/
|
|
252
|
+
function addEdge(db, edge) {
|
|
253
|
+
const { src, dst, type } = edge || {};
|
|
254
|
+
if (!src || !dst || src === dst) return false;
|
|
255
|
+
if (!sameScope(getNode(db, src), getNode(db, dst))) return false;
|
|
256
|
+
if (!EDGE_TYPES.includes(type)) {
|
|
257
|
+
throw new Error('lesson-graph: unknown edge type "' + type + '"');
|
|
258
|
+
}
|
|
259
|
+
const validFrom = edge.validFrom || nowIso();
|
|
260
|
+
const result = db.prepare(`
|
|
261
|
+
INSERT OR IGNORE INTO lesson_edges (src, dst, type, valid_from, valid_to, ingested_at)
|
|
262
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
263
|
+
`).run(src, dst, type, validFrom, edge.validTo || null, edge.ingestedAt || nowIso());
|
|
264
|
+
|
|
265
|
+
if (LINEAGE_EDGE_TYPES.has(type)) {
|
|
266
|
+
closeNodeValidity(db, dst, validFrom);
|
|
267
|
+
}
|
|
268
|
+
if (type === 'duplicate_of') {
|
|
269
|
+
// The duplicate row is suppressed from day one; the canonical carries it.
|
|
270
|
+
closeNodeValidity(db, src, validFrom);
|
|
271
|
+
}
|
|
272
|
+
return result.changes > 0;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ---------------------------------------------------------------------------
|
|
276
|
+
// Traversal
|
|
277
|
+
// ---------------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
function canonicalOf(db, id) {
|
|
280
|
+
const node = getNode(db, id);
|
|
281
|
+
if (node && node.canonical_id && node.canonical_id !== id) return node.canonical_id;
|
|
282
|
+
const dup = db.prepare(
|
|
283
|
+
"SELECT dst FROM lesson_edges WHERE src = ? AND type = 'duplicate_of' LIMIT 1",
|
|
284
|
+
).get(id);
|
|
285
|
+
return dup ? dup.dst : id;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function newestSuccessor(db, id) {
|
|
289
|
+
const row = db.prepare(`
|
|
290
|
+
SELECT src FROM lesson_edges
|
|
291
|
+
WHERE dst = ? AND type IN ('supersedes','refines')
|
|
292
|
+
ORDER BY valid_from DESC, id DESC
|
|
293
|
+
LIMIT 1
|
|
294
|
+
`).get(id);
|
|
295
|
+
return row ? row.src : null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Follow duplicate_of → canonical, then supersedes/refines chains forward to
|
|
300
|
+
* the CURRENT fact. Cycle-safe; bounded by MAX_TRAVERSAL_HOPS.
|
|
301
|
+
*
|
|
302
|
+
* @returns {{id: string, path: string[], hops: number}}
|
|
303
|
+
*/
|
|
304
|
+
function resolveCurrentId(db, id, options = {}) {
|
|
305
|
+
const maxHops = Number.isFinite(options.maxHops) ? options.maxHops : MAX_TRAVERSAL_HOPS;
|
|
306
|
+
const origin = getNode(db, id);
|
|
307
|
+
const visited = new Set();
|
|
308
|
+
let current = id;
|
|
309
|
+
const chain = [id];
|
|
310
|
+
|
|
311
|
+
for (let hop = 0; hop < maxHops; hop++) {
|
|
312
|
+
if (visited.has(current)) break;
|
|
313
|
+
visited.add(current);
|
|
314
|
+
|
|
315
|
+
const canonical = canonicalOf(db, current);
|
|
316
|
+
if (canonical !== current && !visited.has(canonical) && sameScope(origin, getNode(db, canonical))) {
|
|
317
|
+
current = canonical;
|
|
318
|
+
chain.push(current);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const successor = newestSuccessor(db, current);
|
|
323
|
+
if (successor && !visited.has(successor) && sameScope(origin, getNode(db, successor))) {
|
|
324
|
+
current = successor;
|
|
325
|
+
chain.push(current);
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return { id: current, path: chain, hops: chain.length - 1 };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Lineage of a lesson: ordered chain from the referenced id to the current
|
|
337
|
+
* fact, with the edge type taken at each hop.
|
|
338
|
+
*/
|
|
339
|
+
function getLineage(db, id, options = {}) {
|
|
340
|
+
const { path: chain } = resolveCurrentId(db, id, options);
|
|
341
|
+
const steps = [];
|
|
342
|
+
for (let i = 0; i < chain.length - 1; i++) {
|
|
343
|
+
const edge = db.prepare(`
|
|
344
|
+
SELECT type FROM lesson_edges
|
|
345
|
+
WHERE ((src = ? AND dst = ?) OR (src = ? AND dst = ?))
|
|
346
|
+
AND type IN ('supersedes','refines','duplicate_of')
|
|
347
|
+
ORDER BY id DESC LIMIT 1
|
|
348
|
+
`).get(chain[i + 1], chain[i], chain[i], chain[i + 1]);
|
|
349
|
+
steps.push({ from: chain[i], to: chain[i + 1], type: edge ? edge.type : 'supersedes' });
|
|
350
|
+
}
|
|
351
|
+
return { currentId: chain[chain.length - 1], steps };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* A lesson is suppressed when it is not the current fact for its chain, or
|
|
356
|
+
* its validity interval is closed in the past (bitemporal expiry).
|
|
357
|
+
*/
|
|
358
|
+
function isSuppressed(db, id, options = {}) {
|
|
359
|
+
const node = getNode(db, id);
|
|
360
|
+
if (!node) return false;
|
|
361
|
+
const now = options.now ? new Date(options.now).getTime() : Date.now();
|
|
362
|
+
const current = resolveCurrentId(db, id, options);
|
|
363
|
+
if (current.id !== id) return true;
|
|
364
|
+
if (node.valid_to) {
|
|
365
|
+
const closedAt = new Date(node.valid_to).getTime();
|
|
366
|
+
if (Number.isFinite(closedAt) && closedAt <= now) return true;
|
|
367
|
+
}
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function contradictionBetween(db, aId, bId) {
|
|
372
|
+
return db.prepare(`
|
|
373
|
+
SELECT * FROM lesson_edges
|
|
374
|
+
WHERE type = 'contradicts'
|
|
375
|
+
AND ((src = ? AND dst = ?) OR (src = ? AND dst = ?))
|
|
376
|
+
LIMIT 1
|
|
377
|
+
`).get(aId, bId, bId, aId) || null;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
// Ingest-time resolution
|
|
382
|
+
// ---------------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
const CORRECTION_PATTERN = /\b(CORRECTION|REFINEMENT)\s+to\b/i;
|
|
385
|
+
const LESSON_ID_PATTERN = /\b((?:fb|mem|lesson)_[A-Za-z0-9]+(?:_[A-Za-z0-9]+)?)\b/;
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Detect "CORRECTION to <id>" / "REFINEMENT to <id>" markers. The referenced
|
|
389
|
+
* id may follow immediately or appear in parentheses later in the sentence
|
|
390
|
+
* ("REFINEMENT to the 2026-06-04 fix (fb_1780589059204)"), so scan a bounded
|
|
391
|
+
* window after the marker for the first lesson-id token.
|
|
392
|
+
*
|
|
393
|
+
* @returns {{edgeType: 'supersedes'|'refines', targetRef: string}|null}
|
|
394
|
+
*/
|
|
395
|
+
function extractCorrectionTarget(text) {
|
|
396
|
+
const scanned = String(text || '').slice(0, 600);
|
|
397
|
+
const marker = scanned.match(CORRECTION_PATTERN);
|
|
398
|
+
if (!marker) return null;
|
|
399
|
+
const window = scanned.slice(marker.index, marker.index + 260);
|
|
400
|
+
const idMatch = window.match(LESSON_ID_PATTERN);
|
|
401
|
+
if (!idMatch) return null;
|
|
402
|
+
return {
|
|
403
|
+
edgeType: marker[1].toUpperCase() === 'CORRECTION' ? 'supersedes' : 'refines',
|
|
404
|
+
targetRef: idMatch[1],
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function bigramSet(text) {
|
|
409
|
+
const normalized = String(text || '')
|
|
410
|
+
.toLowerCase()
|
|
411
|
+
.replace(/[^a-z0-9\s]/g, ' ')
|
|
412
|
+
.replace(/\s+/g, ' ')
|
|
413
|
+
.trim();
|
|
414
|
+
const set = new Set();
|
|
415
|
+
for (let i = 0; i < normalized.length - 1; i++) {
|
|
416
|
+
set.add(normalized.slice(i, i + 2));
|
|
417
|
+
}
|
|
418
|
+
return set;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function bigramJaccard(a, b) {
|
|
422
|
+
if (a.size === 0 && b.size === 0) return 1;
|
|
423
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
424
|
+
let intersection = 0;
|
|
425
|
+
for (const item of a) {
|
|
426
|
+
if (b.has(item)) intersection++;
|
|
427
|
+
}
|
|
428
|
+
const union = a.size + b.size - intersection;
|
|
429
|
+
return union === 0 ? 0 : intersection / union;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Find the canonical current node this lesson duplicates, if any.
|
|
434
|
+
* Two-layer match, both against OPEN canonical nodes of the same signal:
|
|
435
|
+
* 1. canonical-hash equality (lesson-canonical.js — cross-schema, wording-drift safe)
|
|
436
|
+
* 2. bigram Jaccard of canonicalized text >= DUPLICATE_SIMILARITY_THRESHOLD
|
|
437
|
+
* An optional options.similarityFn(textA, textB) → 0..1 (e.g. cosine over
|
|
438
|
+
* lancedb embeddings) is consulted as layer 3 when provided.
|
|
439
|
+
*/
|
|
440
|
+
function findDuplicateNode(db, lesson, options = {}) {
|
|
441
|
+
const { canonicalHash, canonicalizeText } = require('./lesson-canonical');
|
|
442
|
+
if (!scopeKey(lesson)) return null;
|
|
443
|
+
const scope = normalizeScope(lesson);
|
|
444
|
+
const scopeValues = [scope.entityId, scope.projectId, scope.processId, scope.sessionId];
|
|
445
|
+
const signal = lessonSignal(lesson);
|
|
446
|
+
const hash = canonicalHash(lesson) || null;
|
|
447
|
+
|
|
448
|
+
if (hash) {
|
|
449
|
+
const byHash = db.prepare(`
|
|
450
|
+
SELECT * FROM lesson_nodes
|
|
451
|
+
WHERE canonical_hash = ? AND signal = ? AND entityId = ? AND projectId = ? AND processId = ? AND sessionId = ? AND valid_to IS NULL
|
|
452
|
+
AND (canonical_id IS NULL OR canonical_id = id)
|
|
453
|
+
LIMIT 1
|
|
454
|
+
`).get(hash, signal, ...scopeValues);
|
|
455
|
+
if (byHash && byHash.id !== lesson.id) return byHash;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const text = canonicalizeText(lessonText(lesson));
|
|
459
|
+
if (!text) return null;
|
|
460
|
+
const grams = bigramSet(text);
|
|
461
|
+
const threshold = Number.isFinite(options.similarityThreshold)
|
|
462
|
+
? options.similarityThreshold
|
|
463
|
+
: DUPLICATE_SIMILARITY_THRESHOLD;
|
|
464
|
+
|
|
465
|
+
const candidates = db.prepare(`
|
|
466
|
+
SELECT * FROM lesson_nodes
|
|
467
|
+
WHERE signal = ? AND entityId = ? AND projectId = ? AND processId = ? AND sessionId = ? AND valid_to IS NULL
|
|
468
|
+
AND (canonical_id IS NULL OR canonical_id = id)
|
|
469
|
+
ORDER BY ingested_at DESC
|
|
470
|
+
LIMIT 500
|
|
471
|
+
`).all(signal, ...scopeValues);
|
|
472
|
+
|
|
473
|
+
for (const candidate of candidates) {
|
|
474
|
+
if (candidate.id === lesson.id) continue;
|
|
475
|
+
const candidateText = candidate.canonical_text || '';
|
|
476
|
+
if (!candidateText) continue;
|
|
477
|
+
if (bigramJaccard(grams, bigramSet(candidateText)) >= threshold) return candidate;
|
|
478
|
+
if (typeof options.similarityFn === 'function') {
|
|
479
|
+
try {
|
|
480
|
+
const score = options.similarityFn(text, candidateText);
|
|
481
|
+
if (Number.isFinite(score) && score >= threshold) return candidate;
|
|
482
|
+
} catch {
|
|
483
|
+
// best-effort external similarity — never break ingest
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Ingest-time entry point: register a newly captured lesson in the graph.
|
|
492
|
+
*
|
|
493
|
+
* - CORRECTION/REFINEMENT markers → supersedes/refines edge to the target,
|
|
494
|
+
* closing the target's valid_to (the chain now resolves to this lesson).
|
|
495
|
+
* - High-confidence near-duplicate → increment the canonical node's
|
|
496
|
+
* duplicate_count and record a duplicate_of edge; NO new current fact.
|
|
497
|
+
* - Otherwise → plain new node.
|
|
498
|
+
*
|
|
499
|
+
* @returns {{status: 'superseding'|'refining'|'duplicate'|'new',
|
|
500
|
+
* id: string, canonicalId?: string, targetId?: string,
|
|
501
|
+
* duplicateCount?: number}}
|
|
502
|
+
*/
|
|
503
|
+
function registerLesson(db, lesson, options = {}) {
|
|
504
|
+
return db.transaction(() => registerLessonInTransaction(db, lesson, options))();
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function registerLessonInTransaction(db, lesson, options = {}) {
|
|
508
|
+
if (!lesson || !lesson.id) return { status: 'new', id: null };
|
|
509
|
+
const existing = getNode(db, lesson.id);
|
|
510
|
+
if (existing) {
|
|
511
|
+
if (!sameScopeIdentity(existing, lesson)) throw new Error('lesson-graph: id already belongs to another scope');
|
|
512
|
+
return { status: existing.canonical_id ? 'duplicate' : 'new', id: lesson.id, canonicalId: existing.canonical_id };
|
|
513
|
+
}
|
|
514
|
+
const { canonicalHash, canonicalizeText } = require('./lesson-canonical');
|
|
515
|
+
const validFrom = lesson.timestamp || nowIso();
|
|
516
|
+
const ingestedAt = options.ingestedAt || nowIso();
|
|
517
|
+
const baseNode = {
|
|
518
|
+
id: lesson.id,
|
|
519
|
+
...normalizeScope(lesson),
|
|
520
|
+
sourceFeedbackId: lesson.sourceFeedbackId || null,
|
|
521
|
+
title: lesson.title || lesson.context || null,
|
|
522
|
+
signal: lessonSignal(lesson),
|
|
523
|
+
canonicalHash: canonicalHash(lesson) || null,
|
|
524
|
+
canonicalText: canonicalizeText(lessonText(lesson)),
|
|
525
|
+
validFrom,
|
|
526
|
+
ingestedAt,
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
const correction = extractCorrectionTarget(lessonText(lesson));
|
|
530
|
+
if (correction) {
|
|
531
|
+
const referencedId = resolveNodeRef(db, correction.targetRef, lesson);
|
|
532
|
+
const targetId = referencedId ? resolveCurrentId(db, referencedId).id : null;
|
|
533
|
+
if (targetId && targetId !== lesson.id) {
|
|
534
|
+
upsertNode(db, baseNode);
|
|
535
|
+
addEdge(db, {
|
|
536
|
+
src: lesson.id,
|
|
537
|
+
dst: targetId,
|
|
538
|
+
type: correction.edgeType,
|
|
539
|
+
validFrom,
|
|
540
|
+
ingestedAt,
|
|
541
|
+
});
|
|
542
|
+
return {
|
|
543
|
+
status: correction.edgeType === 'supersedes' ? 'superseding' : 'refining',
|
|
544
|
+
id: lesson.id,
|
|
545
|
+
targetId,
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const duplicate = findDuplicateNode(db, lesson, options);
|
|
551
|
+
if (duplicate) {
|
|
552
|
+
db.prepare(
|
|
553
|
+
'UPDATE lesson_nodes SET duplicate_count = duplicate_count + 1 WHERE id = ?',
|
|
554
|
+
).run(duplicate.id);
|
|
555
|
+
upsertNode(db, { ...baseNode, canonicalId: duplicate.id, validTo: validFrom });
|
|
556
|
+
addEdge(db, {
|
|
557
|
+
src: lesson.id,
|
|
558
|
+
dst: duplicate.id,
|
|
559
|
+
type: 'duplicate_of',
|
|
560
|
+
validFrom,
|
|
561
|
+
ingestedAt,
|
|
562
|
+
});
|
|
563
|
+
const updated = getNode(db, duplicate.id);
|
|
564
|
+
return {
|
|
565
|
+
status: 'duplicate',
|
|
566
|
+
id: lesson.id,
|
|
567
|
+
canonicalId: duplicate.id,
|
|
568
|
+
duplicateCount: updated ? updated.duplicate_count : null,
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
upsertNode(db, baseNode);
|
|
573
|
+
return { status: 'new', id: lesson.id };
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// ---------------------------------------------------------------------------
|
|
577
|
+
// Retrieval-side resolution
|
|
578
|
+
// ---------------------------------------------------------------------------
|
|
579
|
+
|
|
580
|
+
function formatShortDate(iso) {
|
|
581
|
+
const t = iso ? String(iso).slice(0, 10) : '';
|
|
582
|
+
return t || 'unknown-date';
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Resolve a retrieved lesson list through the graph:
|
|
587
|
+
* (a) follow supersedes/refines edges to the CURRENT fact and return only
|
|
588
|
+
* that, with a one-line lineage note;
|
|
589
|
+
* (b) suppress superseded / expired / duplicate lessons;
|
|
590
|
+
* (c) when two retrieved lessons carry a contradicts edge, keep the newer
|
|
591
|
+
* valid one and note the conflict in ONE line instead of showing both.
|
|
592
|
+
*
|
|
593
|
+
* Content for a substituted current fact is looked up via options.lookup
|
|
594
|
+
* (a Map<id, memoryRecord>) from the authorized, sanitized retrieval corpus.
|
|
595
|
+
* Missing replacement content is suppressed; graph titles are never a fallback.
|
|
596
|
+
*
|
|
597
|
+
* Pure with respect to its input list (returns new objects); never throws —
|
|
598
|
+
* on any internal error callers fall back to the original list.
|
|
599
|
+
*
|
|
600
|
+
* @param {import('better-sqlite3').Database} db
|
|
601
|
+
* @param {Array<object>} lessons - retrieval hits (id/title/content/signal/timestamp)
|
|
602
|
+
* @param {object} [options]
|
|
603
|
+
* @param {Map<string, object>} [options.lookup] - id → full memory record
|
|
604
|
+
* @param {string|number} [options.now]
|
|
605
|
+
* @returns {Array<object>}
|
|
606
|
+
*/
|
|
607
|
+
function annotateAndFilterLessons(db, lessons, options = {}) {
|
|
608
|
+
if (!Array.isArray(lessons) || lessons.length === 0) return [];
|
|
609
|
+
|
|
610
|
+
const lookup = options.lookup instanceof Map ? options.lookup : null;
|
|
611
|
+
const resolved = [];
|
|
612
|
+
const seenCurrent = new Map(); // currentId → index in resolved
|
|
613
|
+
|
|
614
|
+
for (const lesson of lessons) {
|
|
615
|
+
if (!lesson || !lesson.id || !getNode(db, lesson.id)) {
|
|
616
|
+
// Unknown to the graph — pass through untouched.
|
|
617
|
+
resolved.push({ ...lesson });
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const source = lookup ? lookup.get(lesson.id) : lesson;
|
|
622
|
+
const sourceNode = getNode(db, lesson.id);
|
|
623
|
+
if (!source || !sameScope(source, sourceNode)) {
|
|
624
|
+
resolved.push({ ...lesson });
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
const { id: currentId, path: chain } = resolveCurrentId(db, lesson.id, options);
|
|
628
|
+
const currentNode = getNode(db, currentId);
|
|
629
|
+
|
|
630
|
+
// Expired current fact with no successor → suppress entirely.
|
|
631
|
+
if (currentNode && currentNode.valid_to) {
|
|
632
|
+
const closedAt = new Date(currentNode.valid_to).getTime();
|
|
633
|
+
const now = options.now ? new Date(options.now).getTime() : Date.now();
|
|
634
|
+
if (Number.isFinite(closedAt) && closedAt <= now) continue;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
if (seenCurrent.has(currentId)) {
|
|
638
|
+
// Another retrieved hit already collapsed onto this fact.
|
|
639
|
+
const survivor = resolved[seenCurrent.get(currentId)];
|
|
640
|
+
if (survivor && chain.length > 1 && !(survivor.lessonGraph && survivor.lessonGraph.lineageNote)) {
|
|
641
|
+
survivor.lessonGraph = {
|
|
642
|
+
...(survivor.lessonGraph || {}),
|
|
643
|
+
lineageNote: buildLineageNote(chain, currentNode),
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
let shaped;
|
|
650
|
+
if (currentId === lesson.id) {
|
|
651
|
+
shaped = { ...lesson };
|
|
652
|
+
} else {
|
|
653
|
+
// Substitute the CURRENT fact for the stale hit.
|
|
654
|
+
const record = lookup ? lookup.get(currentId) : null;
|
|
655
|
+
if (!record || !sameScope(source, record) || !sameScope(record, currentNode)) continue;
|
|
656
|
+
shaped = {
|
|
657
|
+
...record,
|
|
658
|
+
signal: lessonSignal(record),
|
|
659
|
+
relevanceScore: lesson.relevanceScore,
|
|
660
|
+
rerankedScore: lesson.rerankedScore,
|
|
661
|
+
rule: record.structuredRule || null,
|
|
662
|
+
};
|
|
663
|
+
shaped.lessonGraph = {
|
|
664
|
+
...(shaped.lessonGraph || {}),
|
|
665
|
+
lineageNote: buildLineageNote(chain, currentNode),
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
if (currentNode && currentNode.duplicate_count > 1) {
|
|
670
|
+
shaped.lessonGraph = {
|
|
671
|
+
...(shaped.lessonGraph || {}),
|
|
672
|
+
duplicateCount: currentNode.duplicate_count,
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Resolved records carry lineage metadata; this does not waive entropy policy.
|
|
677
|
+
shaped.lessonGraph = { ...(shaped.lessonGraph || {}), resolved: true };
|
|
678
|
+
|
|
679
|
+
seenCurrent.set(currentId, resolved.length);
|
|
680
|
+
resolved.push(shaped);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// Contradiction pass: for any surviving pair with a contradicts edge, keep
|
|
684
|
+
// the newer valid lesson and fold the conflict into one line.
|
|
685
|
+
const kept = [];
|
|
686
|
+
const droppedByConflict = new Set();
|
|
687
|
+
for (let i = 0; i < resolved.length; i++) {
|
|
688
|
+
if (droppedByConflict.has(i)) continue;
|
|
689
|
+
const a = resolved[i];
|
|
690
|
+
if (!a.id || !getNode(db, a.id)) {
|
|
691
|
+
kept.push(a);
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
let aDropped = false;
|
|
695
|
+
for (let j = i + 1; j < resolved.length; j++) {
|
|
696
|
+
if (droppedByConflict.has(j)) continue;
|
|
697
|
+
const b = resolved[j];
|
|
698
|
+
if (!b.id || !getNode(db, b.id) || !a.lessonGraph?.resolved || !b.lessonGraph?.resolved) continue;
|
|
699
|
+
if (!sameScope(getNode(db, a.id), getNode(db, b.id)) || !contradictionBetween(db, a.id, b.id)) continue;
|
|
700
|
+
|
|
701
|
+
const aTime = a.timestamp ? new Date(a.timestamp).getTime() : -Infinity;
|
|
702
|
+
const bTime = b.timestamp ? new Date(b.timestamp).getTime() : -Infinity;
|
|
703
|
+
const winnerIsA = aTime >= bTime;
|
|
704
|
+
const winner = winnerIsA ? a : b;
|
|
705
|
+
const loser = winnerIsA ? b : a;
|
|
706
|
+
winner.lessonGraph = {
|
|
707
|
+
...(winner.lessonGraph || {}),
|
|
708
|
+
conflictNote: 'conflicts with ' + loser.id + ' (' + formatShortDate(loser.timestamp)
|
|
709
|
+
+ '); newer lesson kept',
|
|
710
|
+
};
|
|
711
|
+
if (winnerIsA) {
|
|
712
|
+
droppedByConflict.add(j);
|
|
713
|
+
} else {
|
|
714
|
+
droppedByConflict.add(i);
|
|
715
|
+
aDropped = true;
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
if (!aDropped) kept.push(a);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
return kept;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function buildLineageNote(chain, currentNode) {
|
|
726
|
+
const hops = Math.max(1, chain.length - 1);
|
|
727
|
+
const origin = chain[0];
|
|
728
|
+
const currentId = chain[chain.length - 1];
|
|
729
|
+
const since = currentNode ? formatShortDate(currentNode.valid_from) : 'unknown-date';
|
|
730
|
+
return 'current fact (supersedes ' + hops + ' earlier version' + (hops === 1 ? '' : 's')
|
|
731
|
+
+ ': ' + origin + ' → ' + currentId + ', since ' + since + ')';
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function readProvenance(db) {
|
|
735
|
+
const row = db.prepare('SELECT generation, revision FROM graph_version WHERE id = 1').get();
|
|
736
|
+
return row ? row.generation + ':' + row.revision : 'legacy';
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function graphProvenance(options = {}, openDb) {
|
|
740
|
+
const file = resolveDefaultGraphDbPath(options);
|
|
741
|
+
if (openDb) return file + ':' + readProvenance(openDb);
|
|
742
|
+
if (!fs.existsSync(file)) return null;
|
|
743
|
+
let db;
|
|
744
|
+
try {
|
|
745
|
+
const Database = require('better-sqlite3');
|
|
746
|
+
db = new Database(file, { readonly: true, fileMustExist: true });
|
|
747
|
+
return file + ':' + readProvenance(db);
|
|
748
|
+
} catch {
|
|
749
|
+
return 'unavailable';
|
|
750
|
+
} finally {
|
|
751
|
+
if (db) db.close();
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function feedbackIdentity(db, record) {
|
|
756
|
+
if (!scopeKey(record)) return record.id || null;
|
|
757
|
+
const id = resolveNodeRef(db, record.sourceFeedbackId || record.feedbackId || record.id, record, { exactOnly: true });
|
|
758
|
+
if (!id) return record.id || null;
|
|
759
|
+
return resolveCurrentId(db, id).id;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
module.exports = {
|
|
763
|
+
scopeKey, sameScope, sameScopeIdentity, graphProvenance, feedbackIdentity,
|
|
764
|
+
EDGE_TYPES,
|
|
765
|
+
DUPLICATE_SIMILARITY_THRESHOLD,
|
|
766
|
+
CONTRADICTION_SIMILARITY_THRESHOLD,
|
|
767
|
+
initGraphDB,
|
|
768
|
+
openGraphDBIfExists,
|
|
769
|
+
resolveDefaultGraphDbPath,
|
|
770
|
+
upsertNode,
|
|
771
|
+
getNode,
|
|
772
|
+
resolveNodeRef,
|
|
773
|
+
closeNodeValidity,
|
|
774
|
+
addEdge,
|
|
775
|
+
resolveCurrentId,
|
|
776
|
+
getLineage,
|
|
777
|
+
isSuppressed,
|
|
778
|
+
contradictionBetween,
|
|
779
|
+
extractCorrectionTarget,
|
|
780
|
+
findDuplicateNode,
|
|
781
|
+
registerLesson,
|
|
782
|
+
annotateAndFilterLessons,
|
|
783
|
+
lessonSignal,
|
|
784
|
+
lessonText,
|
|
785
|
+
};
|