@dsh-ray/assistant-association 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +133 -2
- package/cordis.patch.yml +26 -0
- package/lib/aho-corasick.d.ts +41 -0
- package/lib/aho-corasick.d.ts.map +1 -0
- package/lib/aho-corasick.js +352 -0
- package/lib/aho-corasick.js.map +1 -0
- package/lib/bm25.d.ts +17 -0
- package/lib/bm25.d.ts.map +1 -0
- package/lib/bm25.js +73 -0
- package/lib/bm25.js.map +1 -0
- package/lib/clustering.d.ts +161 -0
- package/lib/clustering.d.ts.map +1 -0
- package/lib/clustering.js +1043 -0
- package/lib/clustering.js.map +1 -0
- package/lib/config.d.ts +67 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +834 -0
- package/lib/config.js.map +1 -0
- package/lib/cues.d.ts +134 -0
- package/lib/cues.d.ts.map +1 -0
- package/lib/cues.js +793 -0
- package/lib/cues.js.map +1 -0
- package/lib/dreaming.d.ts +211 -0
- package/lib/dreaming.d.ts.map +1 -0
- package/lib/dreaming.js +1418 -0
- package/lib/dreaming.js.map +1 -0
- package/lib/entities.d.ts +18 -0
- package/lib/entities.d.ts.map +1 -0
- package/lib/entities.js +111 -0
- package/lib/entities.js.map +1 -0
- package/lib/eval-pool.d.ts +111 -0
- package/lib/eval-pool.d.ts.map +1 -0
- package/lib/eval-pool.js +392 -0
- package/lib/eval-pool.js.map +1 -0
- package/lib/hebbian.d.ts +54 -0
- package/lib/hebbian.d.ts.map +1 -0
- package/lib/hebbian.js +226 -0
- package/lib/hebbian.js.map +1 -0
- package/lib/holdout.d.ts +18 -0
- package/lib/holdout.d.ts.map +1 -0
- package/lib/holdout.js +97 -0
- package/lib/holdout.js.map +1 -0
- package/lib/hot-path.d.ts +8 -0
- package/lib/hot-path.d.ts.map +1 -0
- package/lib/hot-path.js +503 -0
- package/lib/hot-path.js.map +1 -0
- package/lib/hysteresis.d.ts +39 -0
- package/lib/hysteresis.d.ts.map +1 -0
- package/lib/hysteresis.js +297 -0
- package/lib/hysteresis.js.map +1 -0
- package/lib/index-memory.d.ts +112 -0
- package/lib/index-memory.d.ts.map +1 -0
- package/lib/index-memory.js +391 -0
- package/lib/index-memory.js.map +1 -0
- package/lib/index.d.ts +37 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +37 -0
- package/lib/index.js.map +1 -0
- package/lib/intake-signal.d.ts +158 -0
- package/lib/intake-signal.d.ts.map +1 -0
- package/lib/intake-signal.js +366 -0
- package/lib/intake-signal.js.map +1 -0
- package/lib/param-tuning.d.ts +302 -0
- package/lib/param-tuning.d.ts.map +1 -0
- package/lib/param-tuning.js +1743 -0
- package/lib/param-tuning.js.map +1 -0
- package/lib/service.d.ts +164 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +2071 -0
- package/lib/service.js.map +1 -0
- package/lib/sources.d.ts +42 -0
- package/lib/sources.d.ts.map +1 -0
- package/lib/sources.js +2024 -0
- package/lib/sources.js.map +1 -0
- package/lib/sqlite.d.ts +88 -0
- package/lib/sqlite.d.ts.map +1 -0
- package/lib/sqlite.js +1815 -0
- package/lib/sqlite.js.map +1 -0
- package/lib/tokenize.d.ts +4 -0
- package/lib/tokenize.d.ts.map +1 -0
- package/lib/tokenize.js +35 -0
- package/lib/tokenize.js.map +1 -0
- package/lib/tools.d.ts +27 -0
- package/lib/tools.d.ts.map +1 -0
- package/lib/tools.js +126 -0
- package/lib/tools.js.map +1 -0
- package/lib/types.d.ts +551 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +163 -0
- package/lib/types.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/lib/web-fetch.d.ts +95 -0
- package/lib/web-fetch.d.ts.map +1 -0
- package/lib/web-fetch.js +833 -0
- package/lib/web-fetch.js.map +1 -0
- package/lib/web-learning-interests.d.ts +42 -0
- package/lib/web-learning-interests.d.ts.map +1 -0
- package/lib/web-learning-interests.js +4344 -0
- package/lib/web-learning-interests.js.map +1 -0
- package/lib/web-learning-runner.d.ts +43 -0
- package/lib/web-learning-runner.d.ts.map +1 -0
- package/lib/web-learning-runner.js +322 -0
- package/lib/web-learning-runner.js.map +1 -0
- package/lib/web-learning-worker.d.ts +75 -0
- package/lib/web-learning-worker.d.ts.map +1 -0
- package/lib/web-learning-worker.js +367 -0
- package/lib/web-learning-worker.js.map +1 -0
- package/lib/web-learning.d.ts +161 -0
- package/lib/web-learning.d.ts.map +1 -0
- package/lib/web-learning.js +912 -0
- package/lib/web-learning.js.map +1 -0
- package/lib/write-queue.d.ts +42 -0
- package/lib/write-queue.d.ts.map +1 -0
- package/lib/write-queue.js +439 -0
- package/lib/write-queue.js.map +1 -0
- package/package.json +156 -3
package/lib/sqlite.js
ADDED
|
@@ -0,0 +1,1815 @@
|
|
|
1
|
+
import { chmodSync, closeSync, constants, lstatSync, mkdirSync, openSync, } from 'node:fs';
|
|
2
|
+
import { dirname, isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { ensureClusteringSchema } from './clustering.js';
|
|
5
|
+
import { ensureDreamingSchema } from './dreaming.js';
|
|
6
|
+
import { ensureEvalPoolSchema } from './eval-pool.js';
|
|
7
|
+
import { ensureIntakeSignalSchema } from './intake-signal.js';
|
|
8
|
+
import { computeDeterministicEdgeId, computeDeterministicSynonymId, DEFAULT_HEBBIAN_CONFIG, } from './types.js';
|
|
9
|
+
export const ASSOCIATION_SCHEMA_VERSION = 4;
|
|
10
|
+
export class AssociationDatabaseError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.name = 'AssociationDatabaseError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function assertSafePrivateFile(path) {
|
|
19
|
+
const stat = lstatSync(path);
|
|
20
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) {
|
|
21
|
+
throw new AssociationDatabaseError('unsafe-file', 'association database must be one regular, unlinked file');
|
|
22
|
+
}
|
|
23
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
24
|
+
throw new AssociationDatabaseError('unsafe-file', 'association database permissions must not allow group or other access');
|
|
25
|
+
}
|
|
26
|
+
const uid = process.getuid?.();
|
|
27
|
+
if (uid !== undefined && stat.uid !== uid) {
|
|
28
|
+
throw new AssociationDatabaseError('unsafe-file', 'association database must be owned by the current OS user');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function preparePrivateFile(path) {
|
|
32
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
33
|
+
try {
|
|
34
|
+
const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR, 0o600);
|
|
35
|
+
closeSync(fd);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST'))
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
assertSafePrivateFile(path);
|
|
42
|
+
for (const sidecar of [`${path}-wal`, `${path}-shm`]) {
|
|
43
|
+
try {
|
|
44
|
+
assertSafePrivateFile(sidecar);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const walRetryWait = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
53
|
+
function enableWal(database) {
|
|
54
|
+
const deadline = Date.now() + 5_000;
|
|
55
|
+
while (true) {
|
|
56
|
+
try {
|
|
57
|
+
const row = database.prepare('PRAGMA journal_mode = WAL').get();
|
|
58
|
+
if (row.journal_mode.toLowerCase() !== 'wal') {
|
|
59
|
+
throw new Error(`association database refused WAL mode: ${row.journal_mode}`);
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
const retryable = error instanceof Error && /database is (?:busy|locked)/i.test(error.message);
|
|
65
|
+
if (!retryable || Date.now() >= deadline)
|
|
66
|
+
throw error;
|
|
67
|
+
Atomics.wait(walRetryWait, 0, 0, 10);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function createV1Schema(database) {
|
|
72
|
+
database.exec(`
|
|
73
|
+
CREATE TABLE schema_meta (
|
|
74
|
+
key TEXT PRIMARY KEY,
|
|
75
|
+
value TEXT NOT NULL
|
|
76
|
+
) STRICT;
|
|
77
|
+
|
|
78
|
+
INSERT INTO schema_meta(key, value) VALUES ('schema-version', '1');
|
|
79
|
+
|
|
80
|
+
CREATE TABLE assoc_nodes (
|
|
81
|
+
id TEXT PRIMARY KEY CHECK (length(id) BETWEEN 3 AND 128),
|
|
82
|
+
kind TEXT NOT NULL CHECK (kind IN (
|
|
83
|
+
'memory', 'goal', 'work-item', 'automation', 'episode',
|
|
84
|
+
'wiki', 'skill', 'event', 'dream', 'abstraction', 'web'
|
|
85
|
+
)),
|
|
86
|
+
source_plugin TEXT NOT NULL CHECK (length(source_plugin) BETWEEN 1 AND 64),
|
|
87
|
+
source_ref TEXT NOT NULL CHECK (length(source_ref) BETWEEN 1 AND 512),
|
|
88
|
+
source_version INTEGER NOT NULL CHECK (source_version >= 0),
|
|
89
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
90
|
+
owner_mode TEXT NOT NULL CHECK (owner_mode IN ('delivery', 'headless', 'system')),
|
|
91
|
+
principal_digest TEXT CHECK (principal_digest IS NULL OR (length(principal_digest) = 64 AND principal_digest NOT GLOB '*[^0-9a-f]*')),
|
|
92
|
+
principal_record_id TEXT,
|
|
93
|
+
principal_version INTEGER CHECK (principal_version IS NULL OR principal_version >= 1),
|
|
94
|
+
scope_mode TEXT NOT NULL CHECK (scope_mode IN ('user-global', 'workspace')),
|
|
95
|
+
workspace TEXT NOT NULL,
|
|
96
|
+
agent_preset TEXT NOT NULL,
|
|
97
|
+
trust TEXT NOT NULL CHECK (trust IN ('trusted', 'low')),
|
|
98
|
+
sensitivity TEXT NOT NULL CHECK (sensitivity IN ('private', 'sensitive')),
|
|
99
|
+
title TEXT NOT NULL CHECK (length(title) <= 512),
|
|
100
|
+
body TEXT NOT NULL,
|
|
101
|
+
entities_json TEXT NOT NULL CHECK (json_valid(entities_json)),
|
|
102
|
+
tokens_json TEXT NOT NULL CHECK (json_valid(tokens_json)),
|
|
103
|
+
metadata_json TEXT NOT NULL CHECK (json_valid(metadata_json)),
|
|
104
|
+
ttl_ms INTEGER CHECK (ttl_ms IS NULL OR ttl_ms > 0),
|
|
105
|
+
expires_at INTEGER CHECK (expires_at IS NULL OR expires_at >= 0),
|
|
106
|
+
status TEXT NOT NULL CHECK (status IN ('active', 'suppressed', 'withdrawn')),
|
|
107
|
+
created_at INTEGER NOT NULL CHECK (created_at >= 0),
|
|
108
|
+
updated_at INTEGER NOT NULL CHECK (updated_at >= 0),
|
|
109
|
+
UNIQUE (owner_scope_key, source_plugin, kind, source_ref),
|
|
110
|
+
CHECK (
|
|
111
|
+
(owner_mode = 'delivery' AND principal_digest IS NOT NULL AND principal_record_id IS NOT NULL AND principal_record_id <> '' AND principal_version IS NOT NULL)
|
|
112
|
+
OR (owner_mode IN ('headless', 'system') AND principal_record_id IS NULL AND principal_version IS NULL)
|
|
113
|
+
)
|
|
114
|
+
) STRICT;
|
|
115
|
+
|
|
116
|
+
CREATE INDEX assoc_nodes_active_scope ON assoc_nodes(status, owner_scope_key, updated_at DESC);
|
|
117
|
+
CREATE INDEX assoc_nodes_source_lookup ON assoc_nodes(owner_scope_key, source_plugin, source_ref);
|
|
118
|
+
CREATE INDEX assoc_nodes_expires ON assoc_nodes(expires_at) WHERE expires_at IS NOT NULL;
|
|
119
|
+
|
|
120
|
+
CREATE TABLE assoc_edges (
|
|
121
|
+
edge_id TEXT PRIMARY KEY CHECK (length(edge_id) = 64 AND edge_id NOT GLOB '*[^0-9a-f]*'),
|
|
122
|
+
a_id TEXT NOT NULL REFERENCES assoc_nodes(id) ON DELETE CASCADE,
|
|
123
|
+
b_id TEXT NOT NULL REFERENCES assoc_nodes(id) ON DELETE CASCADE,
|
|
124
|
+
edge_type TEXT NOT NULL CHECK (edge_type IN ('cooccur', 'entity', 'dream', 'hebbian', 'synonym', 'abstraction')),
|
|
125
|
+
weight REAL NOT NULL CHECK (weight >= 0.0 AND weight <= 10.0),
|
|
126
|
+
trust TEXT NOT NULL CHECK (trust IN ('trusted', 'low')),
|
|
127
|
+
reason TEXT NOT NULL CHECK (length(reason) <= 256),
|
|
128
|
+
use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0),
|
|
129
|
+
last_used_at INTEGER CHECK (last_used_at IS NULL OR last_used_at >= 0),
|
|
130
|
+
created_at INTEGER NOT NULL CHECK (created_at >= 0),
|
|
131
|
+
updated_at INTEGER NOT NULL CHECK (updated_at >= 0),
|
|
132
|
+
CHECK (a_id <> b_id),
|
|
133
|
+
UNIQUE (a_id, b_id, edge_type)
|
|
134
|
+
) STRICT;
|
|
135
|
+
|
|
136
|
+
CREATE INDEX assoc_edges_a ON assoc_edges(a_id, weight DESC);
|
|
137
|
+
CREATE INDEX assoc_edges_b ON assoc_edges(b_id, weight DESC);
|
|
138
|
+
|
|
139
|
+
CREATE TABLE assoc_synonyms (
|
|
140
|
+
id TEXT PRIMARY KEY CHECK (length(id) BETWEEN 3 AND 128),
|
|
141
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
142
|
+
surface TEXT NOT NULL CHECK (length(surface) BETWEEN 1 AND 256),
|
|
143
|
+
canonical_entity TEXT NOT NULL CHECK (length(canonical_entity) BETWEEN 1 AND 256),
|
|
144
|
+
source_node_id TEXT REFERENCES assoc_nodes(id) ON DELETE CASCADE,
|
|
145
|
+
trust TEXT NOT NULL CHECK (trust IN ('trusted', 'low')),
|
|
146
|
+
created_at INTEGER NOT NULL CHECK (created_at >= 0),
|
|
147
|
+
UNIQUE (owner_scope_key, surface, canonical_entity)
|
|
148
|
+
) STRICT;
|
|
149
|
+
|
|
150
|
+
CREATE TABLE assoc_derived_from (
|
|
151
|
+
source_node_id TEXT NOT NULL,
|
|
152
|
+
source_version INTEGER NOT NULL CHECK (source_version >= 0),
|
|
153
|
+
target_kind TEXT NOT NULL CHECK (target_kind IN ('node', 'edge', 'synonym')),
|
|
154
|
+
target_id TEXT NOT NULL,
|
|
155
|
+
PRIMARY KEY (source_node_id, source_version, target_kind, target_id)
|
|
156
|
+
) STRICT, WITHOUT ROWID;
|
|
157
|
+
|
|
158
|
+
CREATE INDEX assoc_derived_from_target ON assoc_derived_from(target_kind, target_id);
|
|
159
|
+
|
|
160
|
+
CREATE TABLE assoc_ingest_cursors (
|
|
161
|
+
source_plugin TEXT NOT NULL,
|
|
162
|
+
scope_key TEXT NOT NULL,
|
|
163
|
+
cursor_json TEXT NOT NULL CHECK (json_valid(cursor_json)),
|
|
164
|
+
updated_at INTEGER NOT NULL CHECK (updated_at >= 0),
|
|
165
|
+
PRIMARY KEY (source_plugin, scope_key)
|
|
166
|
+
) STRICT, WITHOUT ROWID;
|
|
167
|
+
|
|
168
|
+
CREATE TABLE assoc_holdout_assignments (
|
|
169
|
+
task_id TEXT PRIMARY KEY CHECK (length(task_id) BETWEEN 1 AND 512),
|
|
170
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
171
|
+
task_kind TEXT NOT NULL CHECK (task_kind IN (
|
|
172
|
+
'foreground-turn', 'automation-run', 'goal-step', 'goal-outcome', 'work-item', 'headless-session'
|
|
173
|
+
)),
|
|
174
|
+
session_id TEXT,
|
|
175
|
+
turn_number INTEGER CHECK (turn_number IS NULL OR turn_number >= 0),
|
|
176
|
+
in_holdout INTEGER NOT NULL CHECK (in_holdout IN (0, 1)),
|
|
177
|
+
bucket_bps INTEGER NOT NULL CHECK (bucket_bps >= 0 AND bucket_bps < 10000),
|
|
178
|
+
rate_bps INTEGER NOT NULL CHECK (rate_bps >= 1000 AND rate_bps <= 1500),
|
|
179
|
+
hmac_digest TEXT NOT NULL CHECK (length(hmac_digest) = 64 AND hmac_digest NOT GLOB '*[^0-9a-f]*'),
|
|
180
|
+
assigned_at INTEGER NOT NULL CHECK (assigned_at >= 0)
|
|
181
|
+
) STRICT;
|
|
182
|
+
|
|
183
|
+
CREATE INDEX assoc_holdout_scope_time ON assoc_holdout_assignments(owner_scope_key, in_holdout, assigned_at DESC);
|
|
184
|
+
CREATE INDEX assoc_holdout_session ON assoc_holdout_assignments(session_id, turn_number) WHERE session_id IS NOT NULL;
|
|
185
|
+
|
|
186
|
+
CREATE TABLE assoc_step_metrics (
|
|
187
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
188
|
+
task_id TEXT,
|
|
189
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
190
|
+
in_holdout INTEGER NOT NULL CHECK (in_holdout IN (0, 1)),
|
|
191
|
+
latency_us INTEGER NOT NULL CHECK (latency_us >= 0),
|
|
192
|
+
timed_out INTEGER NOT NULL CHECK (timed_out IN (0, 1)),
|
|
193
|
+
fallback_mode TEXT NOT NULL CHECK (fallback_mode IN ('none', 'memory-only', 'cold-start', 'timeout', 'holdout')),
|
|
194
|
+
injected_count INTEGER NOT NULL CHECK (injected_count >= 0),
|
|
195
|
+
candidate_count INTEGER NOT NULL CHECK (candidate_count >= 0),
|
|
196
|
+
source_counts_json TEXT NOT NULL CHECK (json_valid(source_counts_json)),
|
|
197
|
+
occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
|
|
198
|
+
) STRICT;
|
|
199
|
+
|
|
200
|
+
CREATE INDEX assoc_step_metrics_time ON assoc_step_metrics(occurred_at DESC, seq DESC);
|
|
201
|
+
|
|
202
|
+
CREATE TABLE assoc_exposures (
|
|
203
|
+
task_id TEXT NOT NULL,
|
|
204
|
+
node_id TEXT NOT NULL,
|
|
205
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
206
|
+
source_plugin TEXT NOT NULL,
|
|
207
|
+
exposed_at INTEGER NOT NULL CHECK (exposed_at >= 0),
|
|
208
|
+
assoc_read_count INTEGER NOT NULL DEFAULT 0 CHECK (assoc_read_count >= 0),
|
|
209
|
+
weak_use_count INTEGER NOT NULL DEFAULT 0 CHECK (weak_use_count >= 0),
|
|
210
|
+
corrected INTEGER NOT NULL DEFAULT 0 CHECK (corrected IN (0, 1)),
|
|
211
|
+
PRIMARY KEY (task_id, node_id)
|
|
212
|
+
) STRICT, WITHOUT ROWID;
|
|
213
|
+
|
|
214
|
+
CREATE INDEX assoc_exposures_scope_time ON assoc_exposures(owner_scope_key, exposed_at DESC);
|
|
215
|
+
|
|
216
|
+
CREATE TABLE assoc_withdrawn_sources (
|
|
217
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
218
|
+
source_plugin TEXT NOT NULL,
|
|
219
|
+
source_ref TEXT NOT NULL,
|
|
220
|
+
withdrawn_at INTEGER NOT NULL CHECK (withdrawn_at >= 0),
|
|
221
|
+
PRIMARY KEY (owner_scope_key, source_plugin, source_ref)
|
|
222
|
+
) STRICT, WITHOUT ROWID;
|
|
223
|
+
|
|
224
|
+
CREATE TABLE assoc_owner_scopes (
|
|
225
|
+
owner_scope_key TEXT PRIMARY KEY CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
226
|
+
mode TEXT NOT NULL CHECK (mode IN ('delivery', 'headless', 'system')),
|
|
227
|
+
principal_id TEXT NOT NULL,
|
|
228
|
+
principal_digest TEXT NOT NULL CHECK (length(principal_digest) = 64 AND principal_digest NOT GLOB '*[^0-9a-f]*'),
|
|
229
|
+
principal_record_id TEXT,
|
|
230
|
+
principal_version INTEGER CHECK (principal_version IS NULL OR principal_version >= 1),
|
|
231
|
+
workspace TEXT NOT NULL,
|
|
232
|
+
agent_preset TEXT NOT NULL,
|
|
233
|
+
authority_id TEXT,
|
|
234
|
+
updated_at INTEGER NOT NULL CHECK (updated_at >= 0)
|
|
235
|
+
) STRICT;
|
|
236
|
+
`);
|
|
237
|
+
}
|
|
238
|
+
function migrateV1ToV2(database) {
|
|
239
|
+
database.exec(`
|
|
240
|
+
ALTER TABLE assoc_edges ADD COLUMN last_decayed_at INTEGER CHECK (last_decayed_at IS NULL OR last_decayed_at >= 0);
|
|
241
|
+
CREATE INDEX IF NOT EXISTS assoc_edges_decay ON assoc_edges(last_used_at, created_at, weight);
|
|
242
|
+
|
|
243
|
+
ALTER TABLE assoc_exposures ADD COLUMN was_exposed INTEGER NOT NULL DEFAULT 1 CHECK (was_exposed IN (0, 1));
|
|
244
|
+
ALTER TABLE assoc_exposures ADD COLUMN hop INTEGER NOT NULL DEFAULT 0 CHECK (hop >= 0 AND hop <= 2);
|
|
245
|
+
ALTER TABLE assoc_exposures ADD COLUMN score REAL NOT NULL DEFAULT 0.0;
|
|
246
|
+
ALTER TABLE assoc_exposures ADD COLUMN reason TEXT NOT NULL DEFAULT '';
|
|
247
|
+
ALTER TABLE assoc_exposures ADD COLUMN provenance_edges_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(provenance_edges_json));
|
|
248
|
+
ALTER TABLE assoc_exposures ADD COLUMN session_id TEXT;
|
|
249
|
+
ALTER TABLE assoc_exposures ADD COLUMN strong_used INTEGER NOT NULL DEFAULT 0 CHECK (strong_used IN (0, 1));
|
|
250
|
+
ALTER TABLE assoc_exposures ADD COLUMN weak_used INTEGER NOT NULL DEFAULT 0 CHECK (weak_used IN (0, 1));
|
|
251
|
+
ALTER TABLE assoc_exposures ADD COLUMN hebbian_delta_applied REAL NOT NULL DEFAULT 0.0;
|
|
252
|
+
ALTER TABLE assoc_exposures ADD COLUMN corrected_at INTEGER CHECK (corrected_at IS NULL OR corrected_at >= 0);
|
|
253
|
+
CREATE INDEX IF NOT EXISTS assoc_exposures_node_time ON assoc_exposures(owner_scope_key, node_id, exposed_at DESC);
|
|
254
|
+
|
|
255
|
+
UPDATE assoc_exposures
|
|
256
|
+
SET strong_used = CASE WHEN assoc_read_count > 0 THEN 1 ELSE 0 END,
|
|
257
|
+
weak_used = CASE WHEN weak_use_count > 0 THEN 1 ELSE 0 END
|
|
258
|
+
WHERE was_exposed = 1 AND (assoc_read_count > 0 OR weak_use_count > 0);
|
|
259
|
+
|
|
260
|
+
ALTER TABLE assoc_step_metrics ADD COLUMN profile_version INTEGER NOT NULL DEFAULT 0;
|
|
261
|
+
|
|
262
|
+
CREATE TABLE assoc_hebbian_events (
|
|
263
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
264
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
265
|
+
task_id TEXT,
|
|
266
|
+
node_id TEXT,
|
|
267
|
+
edge_id TEXT NOT NULL CHECK (length(edge_id) = 64 AND edge_id NOT GLOB '*[^0-9a-f]*'),
|
|
268
|
+
event_kind TEXT NOT NULL CHECK (event_kind IN ('strong-use', 'weak-use', 'correction', 'decay')),
|
|
269
|
+
delta REAL NOT NULL,
|
|
270
|
+
weight_before REAL NOT NULL,
|
|
271
|
+
weight_after REAL NOT NULL,
|
|
272
|
+
occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
|
|
273
|
+
) STRICT;
|
|
274
|
+
|
|
275
|
+
CREATE INDEX assoc_hebbian_events_scope_time ON assoc_hebbian_events(owner_scope_key, occurred_at DESC, seq DESC);
|
|
276
|
+
CREATE INDEX assoc_hebbian_events_edge ON assoc_hebbian_events(edge_id, occurred_at DESC);
|
|
277
|
+
|
|
278
|
+
CREATE TABLE assoc_read_events (
|
|
279
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
280
|
+
task_id TEXT,
|
|
281
|
+
node_id TEXT NOT NULL,
|
|
282
|
+
owner_scope_key TEXT NOT NULL,
|
|
283
|
+
hit INTEGER NOT NULL CHECK (hit IN (0, 1)),
|
|
284
|
+
reason TEXT NOT NULL,
|
|
285
|
+
occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
|
|
286
|
+
) STRICT;
|
|
287
|
+
|
|
288
|
+
CREATE INDEX assoc_read_events_time ON assoc_read_events(occurred_at DESC, seq DESC);
|
|
289
|
+
|
|
290
|
+
CREATE TABLE assoc_replay_episodes (
|
|
291
|
+
task_id TEXT PRIMARY KEY CHECK (length(task_id) BETWEEN 1 AND 512),
|
|
292
|
+
owner_scope_key TEXT NOT NULL CHECK (length(owner_scope_key) = 64 AND owner_scope_key NOT GLOB '*[^0-9a-f]*'),
|
|
293
|
+
in_holdout INTEGER NOT NULL CHECK (in_holdout IN (0, 1)),
|
|
294
|
+
cues_json TEXT NOT NULL CHECK (json_valid(cues_json)),
|
|
295
|
+
used_node_ids_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(used_node_ids_json)),
|
|
296
|
+
corrected_node_ids_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(corrected_node_ids_json)),
|
|
297
|
+
profile_version INTEGER NOT NULL DEFAULT 0 CHECK (profile_version >= 0),
|
|
298
|
+
occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
|
|
299
|
+
) STRICT;
|
|
300
|
+
|
|
301
|
+
CREATE INDEX assoc_replay_episodes_scope_time ON assoc_replay_episodes(owner_scope_key, occurred_at DESC);
|
|
302
|
+
|
|
303
|
+
CREATE TABLE assoc_task_telemetry (
|
|
304
|
+
task_id TEXT PRIMARY KEY,
|
|
305
|
+
owner_scope_key TEXT NOT NULL,
|
|
306
|
+
in_holdout INTEGER NOT NULL CHECK (in_holdout IN (0, 1)),
|
|
307
|
+
turns INTEGER NOT NULL DEFAULT 0 CHECK (turns >= 0),
|
|
308
|
+
steps INTEGER NOT NULL DEFAULT 0 CHECK (steps >= 0),
|
|
309
|
+
input_tokens INTEGER,
|
|
310
|
+
output_tokens INTEGER,
|
|
311
|
+
cost_usd_micros INTEGER,
|
|
312
|
+
updated_at INTEGER NOT NULL CHECK (updated_at >= 0)
|
|
313
|
+
) STRICT;
|
|
314
|
+
|
|
315
|
+
CREATE INDEX assoc_task_telemetry_time ON assoc_task_telemetry(updated_at DESC);
|
|
316
|
+
|
|
317
|
+
CREATE TABLE assoc_param_profile_versions (
|
|
318
|
+
scope_key TEXT NOT NULL,
|
|
319
|
+
version INTEGER NOT NULL CHECK (version >= 0),
|
|
320
|
+
parent_version INTEGER CHECK (parent_version IS NULL OR (parent_version >= 0 AND parent_version < version)),
|
|
321
|
+
params_json TEXT NOT NULL CHECK (json_valid(params_json)),
|
|
322
|
+
params_digest TEXT NOT NULL,
|
|
323
|
+
basis_json TEXT NOT NULL CHECK (json_valid(basis_json)),
|
|
324
|
+
change_json TEXT NOT NULL CHECK (json_valid(change_json)),
|
|
325
|
+
origin TEXT NOT NULL CHECK (origin IN ('baseline', 'auto', 'replay', 'manual')),
|
|
326
|
+
digest TEXT NOT NULL,
|
|
327
|
+
idempotency_key TEXT NOT NULL UNIQUE,
|
|
328
|
+
created_at INTEGER NOT NULL CHECK (created_at >= 0),
|
|
329
|
+
PRIMARY KEY (scope_key, version)
|
|
330
|
+
) STRICT;
|
|
331
|
+
|
|
332
|
+
CREATE TRIGGER assoc_param_profile_versions_immutable
|
|
333
|
+
BEFORE UPDATE ON assoc_param_profile_versions
|
|
334
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_versions are immutable'); END;
|
|
335
|
+
|
|
336
|
+
CREATE TRIGGER assoc_param_profile_versions_no_delete
|
|
337
|
+
BEFORE DELETE ON assoc_param_profile_versions
|
|
338
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_versions are durable'); END;
|
|
339
|
+
|
|
340
|
+
CREATE TABLE assoc_param_profile_heads (
|
|
341
|
+
scope_key TEXT PRIMARY KEY,
|
|
342
|
+
active_version INTEGER NOT NULL CHECK (active_version >= 0),
|
|
343
|
+
latest_version INTEGER NOT NULL CHECK (latest_version >= active_version),
|
|
344
|
+
active_digest TEXT NOT NULL,
|
|
345
|
+
state TEXT NOT NULL CHECK (state IN ('idle', 'observing')),
|
|
346
|
+
observing_version INTEGER,
|
|
347
|
+
observe_from INTEGER,
|
|
348
|
+
observe_until INTEGER,
|
|
349
|
+
changed_at INTEGER NOT NULL CHECK (changed_at >= 0),
|
|
350
|
+
CHECK (
|
|
351
|
+
(state = 'idle' AND observing_version IS NULL AND observe_from IS NULL AND observe_until IS NULL)
|
|
352
|
+
OR (state = 'observing' AND observing_version = active_version AND observe_from IS NOT NULL AND observe_until IS NOT NULL AND observe_until > observe_from)
|
|
353
|
+
)
|
|
354
|
+
) STRICT;
|
|
355
|
+
|
|
356
|
+
CREATE TRIGGER assoc_param_profile_heads_no_delete
|
|
357
|
+
BEFORE DELETE ON assoc_param_profile_heads
|
|
358
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_heads are durable'); END;
|
|
359
|
+
|
|
360
|
+
CREATE TABLE assoc_param_profile_events (
|
|
361
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
362
|
+
scope_key TEXT NOT NULL,
|
|
363
|
+
kind TEXT NOT NULL CHECK (kind IN ('adopted', 'rolled-back', 'settled', 'request-rejected')),
|
|
364
|
+
from_version INTEGER,
|
|
365
|
+
to_version INTEGER,
|
|
366
|
+
from_digest TEXT,
|
|
367
|
+
to_digest TEXT,
|
|
368
|
+
reason TEXT NOT NULL,
|
|
369
|
+
detail_json TEXT NOT NULL CHECK (json_valid(detail_json)),
|
|
370
|
+
idempotency_key TEXT NOT NULL UNIQUE,
|
|
371
|
+
occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0)
|
|
372
|
+
) STRICT;
|
|
373
|
+
|
|
374
|
+
CREATE INDEX assoc_param_profile_events_scope ON assoc_param_profile_events(scope_key, seq);
|
|
375
|
+
|
|
376
|
+
CREATE TRIGGER assoc_param_profile_events_immutable
|
|
377
|
+
BEFORE UPDATE ON assoc_param_profile_events
|
|
378
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_events are immutable'); END;
|
|
379
|
+
|
|
380
|
+
CREATE TRIGGER assoc_param_profile_events_no_delete
|
|
381
|
+
BEFORE DELETE ON assoc_param_profile_events
|
|
382
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_profile_events are durable'); END;
|
|
383
|
+
|
|
384
|
+
CREATE TABLE assoc_param_relax_proposals (
|
|
385
|
+
proposal_id TEXT PRIMARY KEY,
|
|
386
|
+
scope_key TEXT NOT NULL,
|
|
387
|
+
parent_version INTEGER NOT NULL,
|
|
388
|
+
parent_digest TEXT NOT NULL,
|
|
389
|
+
candidate_json TEXT NOT NULL CHECK (json_valid(candidate_json)),
|
|
390
|
+
params_digest TEXT NOT NULL,
|
|
391
|
+
change_json TEXT NOT NULL CHECK (json_valid(change_json)),
|
|
392
|
+
holdout_seal TEXT NOT NULL,
|
|
393
|
+
window_from INTEGER NOT NULL,
|
|
394
|
+
window_to INTEGER NOT NULL,
|
|
395
|
+
basis_json TEXT NOT NULL CHECK (json_valid(basis_json)),
|
|
396
|
+
status TEXT NOT NULL CHECK (status IN ('pending', 'adopted', 'rejected')),
|
|
397
|
+
created_at INTEGER NOT NULL CHECK (created_at >= 0)
|
|
398
|
+
) STRICT;
|
|
399
|
+
|
|
400
|
+
CREATE INDEX assoc_param_relax_proposals_scope ON assoc_param_relax_proposals(scope_key, created_at);
|
|
401
|
+
|
|
402
|
+
CREATE TRIGGER assoc_param_relax_proposals_immutable
|
|
403
|
+
BEFORE UPDATE ON assoc_param_relax_proposals
|
|
404
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_proposals are immutable'); END;
|
|
405
|
+
|
|
406
|
+
CREATE TRIGGER assoc_param_relax_proposals_no_delete
|
|
407
|
+
BEFORE DELETE ON assoc_param_relax_proposals
|
|
408
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_proposals are durable'); END;
|
|
409
|
+
|
|
410
|
+
CREATE TABLE assoc_param_relax_decisions (
|
|
411
|
+
decision_id TEXT PRIMARY KEY,
|
|
412
|
+
proposal_id TEXT NOT NULL UNIQUE,
|
|
413
|
+
scope_key TEXT NOT NULL,
|
|
414
|
+
status TEXT NOT NULL CHECK (status IN ('adopted', 'rejected')),
|
|
415
|
+
reason TEXT NOT NULL,
|
|
416
|
+
replay_json TEXT NOT NULL CHECK (json_valid(replay_json)),
|
|
417
|
+
decided_at INTEGER NOT NULL CHECK (decided_at >= 0),
|
|
418
|
+
FOREIGN KEY (proposal_id) REFERENCES assoc_param_relax_proposals(proposal_id) ON DELETE RESTRICT
|
|
419
|
+
) STRICT;
|
|
420
|
+
|
|
421
|
+
CREATE TRIGGER assoc_param_relax_decisions_immutable
|
|
422
|
+
BEFORE UPDATE ON assoc_param_relax_decisions
|
|
423
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_decisions are immutable'); END;
|
|
424
|
+
|
|
425
|
+
CREATE TRIGGER assoc_param_relax_decisions_no_delete
|
|
426
|
+
BEFORE DELETE ON assoc_param_relax_decisions
|
|
427
|
+
BEGIN SELECT RAISE(ABORT, 'assoc_param_relax_decisions are durable'); END;
|
|
428
|
+
|
|
429
|
+
CREATE TABLE assoc_param_rolled_back_digests (
|
|
430
|
+
scope_key TEXT NOT NULL,
|
|
431
|
+
params_digest TEXT NOT NULL,
|
|
432
|
+
rolled_back_at INTEGER NOT NULL CHECK (rolled_back_at >= 0),
|
|
433
|
+
from_version INTEGER NOT NULL,
|
|
434
|
+
reason TEXT NOT NULL,
|
|
435
|
+
PRIMARY KEY (scope_key, params_digest)
|
|
436
|
+
) STRICT;
|
|
437
|
+
|
|
438
|
+
INSERT INTO schema_meta(key, value) VALUES ('schema-version', '2')
|
|
439
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value;
|
|
440
|
+
`);
|
|
441
|
+
}
|
|
442
|
+
function migrateV2ToV3(database) {
|
|
443
|
+
ensureDreamingSchema(database);
|
|
444
|
+
ensureIntakeSignalSchema(database);
|
|
445
|
+
ensureClusteringSchema(database);
|
|
446
|
+
ensureEvalPoolSchema(database);
|
|
447
|
+
database.exec(`
|
|
448
|
+
INSERT INTO schema_meta(key, value) VALUES ('schema-version', '3')
|
|
449
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value;
|
|
450
|
+
`);
|
|
451
|
+
}
|
|
452
|
+
export function ensureWebLearningSchema(database) {
|
|
453
|
+
database.exec(`
|
|
454
|
+
CREATE TABLE IF NOT EXISTS assoc_web_learning_runs (
|
|
455
|
+
run_id TEXT PRIMARY KEY,
|
|
456
|
+
owner_scope_key TEXT NOT NULL,
|
|
457
|
+
started_at INTEGER NOT NULL,
|
|
458
|
+
finished_at INTEGER NOT NULL,
|
|
459
|
+
status TEXT NOT NULL CHECK (status IN ('completed', 'budget-exhausted', 'skipped', 'failed')),
|
|
460
|
+
reason TEXT,
|
|
461
|
+
topics_considered INTEGER NOT NULL DEFAULT 0,
|
|
462
|
+
requests_used INTEGER NOT NULL DEFAULT 0,
|
|
463
|
+
pages_fetched INTEGER NOT NULL DEFAULT 0,
|
|
464
|
+
bytes_fetched INTEGER NOT NULL DEFAULT 0,
|
|
465
|
+
nodes_written INTEGER NOT NULL DEFAULT 0,
|
|
466
|
+
details_json TEXT
|
|
467
|
+
) STRICT;
|
|
468
|
+
|
|
469
|
+
CREATE INDEX IF NOT EXISTS assoc_web_runs_scope_started
|
|
470
|
+
ON assoc_web_learning_runs(owner_scope_key, started_at DESC);
|
|
471
|
+
|
|
472
|
+
CREATE TABLE IF NOT EXISTS assoc_web_learning_budget_usage (
|
|
473
|
+
owner_scope_key TEXT NOT NULL,
|
|
474
|
+
utc_day TEXT NOT NULL,
|
|
475
|
+
requests_used INTEGER NOT NULL DEFAULT 0,
|
|
476
|
+
pages_fetched INTEGER NOT NULL DEFAULT 0,
|
|
477
|
+
bytes_fetched INTEGER NOT NULL DEFAULT 0,
|
|
478
|
+
updated_at INTEGER NOT NULL,
|
|
479
|
+
PRIMARY KEY (owner_scope_key, utc_day)
|
|
480
|
+
) STRICT, WITHOUT ROWID;
|
|
481
|
+
|
|
482
|
+
CREATE TABLE IF NOT EXISTS assoc_web_learning_fetches (
|
|
483
|
+
fetch_id TEXT PRIMARY KEY,
|
|
484
|
+
owner_scope_key TEXT NOT NULL,
|
|
485
|
+
run_id TEXT NOT NULL,
|
|
486
|
+
canonical_url TEXT NOT NULL,
|
|
487
|
+
domain TEXT NOT NULL,
|
|
488
|
+
interest_key TEXT NOT NULL,
|
|
489
|
+
status TEXT NOT NULL,
|
|
490
|
+
bytes_fetched INTEGER NOT NULL DEFAULT 0,
|
|
491
|
+
node_id TEXT,
|
|
492
|
+
fetched_at INTEGER NOT NULL,
|
|
493
|
+
expires_at INTEGER
|
|
494
|
+
) STRICT;
|
|
495
|
+
|
|
496
|
+
CREATE INDEX IF NOT EXISTS assoc_web_fetches_scope_url
|
|
497
|
+
ON assoc_web_learning_fetches(owner_scope_key, canonical_url, fetched_at DESC);
|
|
498
|
+
`);
|
|
499
|
+
}
|
|
500
|
+
function migrateV3ToV4(database) {
|
|
501
|
+
ensureWebLearningSchema(database);
|
|
502
|
+
database.exec(`
|
|
503
|
+
INSERT INTO schema_meta(key, value) VALUES ('schema-version', '4')
|
|
504
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value;
|
|
505
|
+
`);
|
|
506
|
+
}
|
|
507
|
+
function migrate(database) {
|
|
508
|
+
database.exec('BEGIN IMMEDIATE');
|
|
509
|
+
try {
|
|
510
|
+
const row = database.prepare('PRAGMA user_version').get();
|
|
511
|
+
if (row.user_version > ASSOCIATION_SCHEMA_VERSION) {
|
|
512
|
+
throw new AssociationDatabaseError('schema-too-new', `association schema ${row.user_version} is newer than supported schema ${ASSOCIATION_SCHEMA_VERSION}`);
|
|
513
|
+
}
|
|
514
|
+
if (row.user_version === 0) {
|
|
515
|
+
createV1Schema(database);
|
|
516
|
+
migrateV1ToV2(database);
|
|
517
|
+
migrateV2ToV3(database);
|
|
518
|
+
migrateV3ToV4(database);
|
|
519
|
+
database.exec(`PRAGMA user_version = ${ASSOCIATION_SCHEMA_VERSION}`);
|
|
520
|
+
}
|
|
521
|
+
else if (row.user_version === 1) {
|
|
522
|
+
migrateV1ToV2(database);
|
|
523
|
+
migrateV2ToV3(database);
|
|
524
|
+
migrateV3ToV4(database);
|
|
525
|
+
database.exec(`PRAGMA user_version = ${ASSOCIATION_SCHEMA_VERSION}`);
|
|
526
|
+
}
|
|
527
|
+
else if (row.user_version === 2) {
|
|
528
|
+
migrateV2ToV3(database);
|
|
529
|
+
migrateV3ToV4(database);
|
|
530
|
+
database.exec(`PRAGMA user_version = ${ASSOCIATION_SCHEMA_VERSION}`);
|
|
531
|
+
}
|
|
532
|
+
else if (row.user_version === 3) {
|
|
533
|
+
migrateV3ToV4(database);
|
|
534
|
+
database.exec(`PRAGMA user_version = ${ASSOCIATION_SCHEMA_VERSION}`);
|
|
535
|
+
}
|
|
536
|
+
database.exec('COMMIT');
|
|
537
|
+
}
|
|
538
|
+
catch (error) {
|
|
539
|
+
database.exec('ROLLBACK');
|
|
540
|
+
throw error;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
export function openAssociationDatabase(path) {
|
|
544
|
+
if (path !== ':memory:' && (!isAbsolute(path) || resolve(path) !== path)) {
|
|
545
|
+
throw new AssociationDatabaseError('invalid-path', 'association database path must be :memory: or a canonical absolute path');
|
|
546
|
+
}
|
|
547
|
+
if (path !== ':memory:') {
|
|
548
|
+
preparePrivateFile(path);
|
|
549
|
+
}
|
|
550
|
+
const database = new DatabaseSync(path);
|
|
551
|
+
try {
|
|
552
|
+
database.exec('PRAGMA foreign_keys = ON');
|
|
553
|
+
database.exec('PRAGMA busy_timeout = 5000');
|
|
554
|
+
database.exec('PRAGMA synchronous = FULL');
|
|
555
|
+
database.exec('PRAGMA secure_delete = ON');
|
|
556
|
+
migrate(database);
|
|
557
|
+
if (path !== ':memory:') {
|
|
558
|
+
enableWal(database);
|
|
559
|
+
chmodSync(path, 0o600);
|
|
560
|
+
for (const sidecar of [`${path}-wal`, `${path}-shm`]) {
|
|
561
|
+
try {
|
|
562
|
+
chmodSync(sidecar, 0o600);
|
|
563
|
+
assertSafePrivateFile(sidecar);
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
|
|
567
|
+
throw error;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return database;
|
|
572
|
+
}
|
|
573
|
+
catch (error) {
|
|
574
|
+
database.close();
|
|
575
|
+
throw error;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function mapRawNode(row) {
|
|
579
|
+
return {
|
|
580
|
+
id: row.id,
|
|
581
|
+
kind: row.kind,
|
|
582
|
+
sourcePlugin: row.source_plugin,
|
|
583
|
+
sourceRef: row.source_ref,
|
|
584
|
+
sourceVersion: row.source_version,
|
|
585
|
+
ownerScopeKey: row.owner_scope_key,
|
|
586
|
+
ownerMode: row.owner_mode,
|
|
587
|
+
principalDigest: row.principal_digest,
|
|
588
|
+
principalRecordId: row.principal_record_id,
|
|
589
|
+
principalVersion: row.principal_version,
|
|
590
|
+
scopeMode: row.scope_mode,
|
|
591
|
+
workspace: row.workspace,
|
|
592
|
+
agentPreset: row.agent_preset,
|
|
593
|
+
trust: row.trust,
|
|
594
|
+
sensitivity: row.sensitivity,
|
|
595
|
+
title: row.title,
|
|
596
|
+
body: row.body,
|
|
597
|
+
entities: JSON.parse(row.entities_json),
|
|
598
|
+
tokens: JSON.parse(row.tokens_json),
|
|
599
|
+
metadata: JSON.parse(row.metadata_json),
|
|
600
|
+
ttlMs: row.ttl_ms,
|
|
601
|
+
expiresAt: row.expires_at,
|
|
602
|
+
status: row.status,
|
|
603
|
+
createdAt: row.created_at,
|
|
604
|
+
updatedAt: row.updated_at,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function mapRawExposure(row) {
|
|
608
|
+
let provenanceEdges = [];
|
|
609
|
+
try {
|
|
610
|
+
const parsed = JSON.parse(row.provenance_edges_json);
|
|
611
|
+
if (Array.isArray(parsed)) {
|
|
612
|
+
provenanceEdges = parsed;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
catch {
|
|
616
|
+
provenanceEdges = [];
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
taskId: row.task_id,
|
|
620
|
+
nodeId: row.node_id,
|
|
621
|
+
ownerScopeKey: row.owner_scope_key,
|
|
622
|
+
sourcePlugin: row.source_plugin,
|
|
623
|
+
exposedAt: row.exposed_at,
|
|
624
|
+
wasExposed: row.was_exposed === 1,
|
|
625
|
+
hop: row.hop,
|
|
626
|
+
score: row.score,
|
|
627
|
+
reason: row.reason,
|
|
628
|
+
provenanceEdges,
|
|
629
|
+
sessionId: row.session_id,
|
|
630
|
+
assocReadCount: row.assoc_read_count,
|
|
631
|
+
weakUseCount: row.weak_use_count,
|
|
632
|
+
strongUsed: row.strong_used === 1,
|
|
633
|
+
weakUsed: row.weak_used === 1,
|
|
634
|
+
hebbianDeltaApplied: row.hebbian_delta_applied,
|
|
635
|
+
corrected: row.corrected === 1,
|
|
636
|
+
correctedAt: row.corrected_at,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
function clampEdgeWeight(value, weightMin, weightMax) {
|
|
640
|
+
const lo = Math.max(0.0, Math.min(10.0, weightMin));
|
|
641
|
+
const hi = Math.max(lo, Math.min(10.0, weightMax));
|
|
642
|
+
if (!Number.isFinite(value))
|
|
643
|
+
return lo;
|
|
644
|
+
return Math.min(hi, Math.max(lo, value));
|
|
645
|
+
}
|
|
646
|
+
function mergeUniqueStrings(existing, incoming) {
|
|
647
|
+
if (incoming.length === 0)
|
|
648
|
+
return [...existing];
|
|
649
|
+
const seen = new Set(existing);
|
|
650
|
+
const merged = [...existing];
|
|
651
|
+
for (const item of incoming) {
|
|
652
|
+
if (!seen.has(item)) {
|
|
653
|
+
seen.add(item);
|
|
654
|
+
merged.push(item);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return merged;
|
|
658
|
+
}
|
|
659
|
+
export class AssociationStore {
|
|
660
|
+
#db;
|
|
661
|
+
constructor(database) {
|
|
662
|
+
this.#db = database;
|
|
663
|
+
}
|
|
664
|
+
get database() {
|
|
665
|
+
return this.#db;
|
|
666
|
+
}
|
|
667
|
+
close() {
|
|
668
|
+
this.#db.close();
|
|
669
|
+
}
|
|
670
|
+
runInTransaction(fn) {
|
|
671
|
+
this.#db.exec('BEGIN IMMEDIATE');
|
|
672
|
+
try {
|
|
673
|
+
const result = fn();
|
|
674
|
+
this.#db.exec('COMMIT');
|
|
675
|
+
return result;
|
|
676
|
+
}
|
|
677
|
+
catch (error) {
|
|
678
|
+
this.#db.exec('ROLLBACK');
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
upsertBatch(input) {
|
|
683
|
+
return this.runInTransaction(() => {
|
|
684
|
+
const selectExisting = this.#db.prepare('SELECT id, source_version FROM assoc_nodes WHERE id = ?');
|
|
685
|
+
const checkWithdrawnStmt = this.#db.prepare('SELECT 1 AS ok FROM assoc_withdrawn_sources WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?');
|
|
686
|
+
const upsertNodeStmt = this.#db.prepare(`
|
|
687
|
+
INSERT INTO assoc_nodes (
|
|
688
|
+
id, kind, source_plugin, source_ref, source_version,
|
|
689
|
+
owner_scope_key, owner_mode, principal_digest, principal_record_id, principal_version,
|
|
690
|
+
scope_mode, workspace, agent_preset, trust, sensitivity,
|
|
691
|
+
title, body, entities_json, tokens_json, metadata_json,
|
|
692
|
+
ttl_ms, expires_at, status, created_at, updated_at
|
|
693
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
694
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
695
|
+
kind = excluded.kind,
|
|
696
|
+
source_plugin = excluded.source_plugin,
|
|
697
|
+
source_ref = excluded.source_ref,
|
|
698
|
+
source_version = excluded.source_version,
|
|
699
|
+
owner_scope_key = excluded.owner_scope_key,
|
|
700
|
+
owner_mode = excluded.owner_mode,
|
|
701
|
+
principal_digest = excluded.principal_digest,
|
|
702
|
+
principal_record_id = excluded.principal_record_id,
|
|
703
|
+
principal_version = excluded.principal_version,
|
|
704
|
+
scope_mode = excluded.scope_mode,
|
|
705
|
+
workspace = excluded.workspace,
|
|
706
|
+
agent_preset = excluded.agent_preset,
|
|
707
|
+
trust = excluded.trust,
|
|
708
|
+
sensitivity = excluded.sensitivity,
|
|
709
|
+
title = excluded.title,
|
|
710
|
+
body = excluded.body,
|
|
711
|
+
entities_json = excluded.entities_json,
|
|
712
|
+
tokens_json = excluded.tokens_json,
|
|
713
|
+
metadata_json = excluded.metadata_json,
|
|
714
|
+
ttl_ms = excluded.ttl_ms,
|
|
715
|
+
expires_at = excluded.expires_at,
|
|
716
|
+
status = excluded.status,
|
|
717
|
+
updated_at = excluded.updated_at
|
|
718
|
+
`);
|
|
719
|
+
const deletedNodeIds = [];
|
|
720
|
+
const deletedEdgeIds = [];
|
|
721
|
+
const deletedSynonymIds = [];
|
|
722
|
+
const skippedWithdrawnNodeIds = new Set();
|
|
723
|
+
const skippedSynonymIds = new Set();
|
|
724
|
+
const synonymIdMap = new Map();
|
|
725
|
+
for (const node of input.nodes) {
|
|
726
|
+
if (checkWithdrawnStmt.get(node.ownerScopeKey, node.sourcePlugin, node.sourceRef) !==
|
|
727
|
+
undefined) {
|
|
728
|
+
skippedWithdrawnNodeIds.add(node.id);
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
const existing = selectExisting.get(node.id);
|
|
732
|
+
if (existing !== undefined && existing.source_version !== node.sourceVersion) {
|
|
733
|
+
const cascade = this.#cascadeDerivedInCurrentTx([
|
|
734
|
+
{ nodeId: node.id, exactVersion: existing.source_version },
|
|
735
|
+
]);
|
|
736
|
+
deletedNodeIds.push(...cascade.deletedNodeIds);
|
|
737
|
+
deletedEdgeIds.push(...cascade.deletedEdgeIds);
|
|
738
|
+
deletedSynonymIds.push(...cascade.deletedSynonymIds);
|
|
739
|
+
}
|
|
740
|
+
upsertNodeStmt.run(node.id, node.kind, node.sourcePlugin, node.sourceRef, node.sourceVersion, node.ownerScopeKey, node.ownerMode, node.principalDigest, node.principalRecordId, node.principalVersion, node.scopeMode, node.workspace, node.agentPreset, node.trust, node.sensitivity, node.title.slice(0, 512), node.body, JSON.stringify(node.entities), JSON.stringify(node.tokens), JSON.stringify(node.metadata ?? {}), node.ttlMs ?? null, node.expiresAt ?? null, node.status ?? 'active', node.createdAt, node.updatedAt);
|
|
741
|
+
}
|
|
742
|
+
if (input.edges.length > 0) {
|
|
743
|
+
const checkNodeExists = this.#db.prepare('SELECT 1 AS ok FROM assoc_nodes WHERE id = ?');
|
|
744
|
+
const upsertEdgeStmt = this.#db.prepare(`
|
|
745
|
+
INSERT INTO assoc_edges (
|
|
746
|
+
edge_id, a_id, b_id, edge_type, weight, trust, reason,
|
|
747
|
+
use_count, last_used_at, created_at, updated_at
|
|
748
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
749
|
+
ON CONFLICT(a_id, b_id, edge_type) DO UPDATE SET
|
|
750
|
+
weight = excluded.weight,
|
|
751
|
+
trust = excluded.trust,
|
|
752
|
+
reason = excluded.reason,
|
|
753
|
+
updated_at = excluded.updated_at
|
|
754
|
+
`);
|
|
755
|
+
for (const edge of input.edges) {
|
|
756
|
+
if (edge.aId === edge.bId)
|
|
757
|
+
continue;
|
|
758
|
+
if (checkNodeExists.get(edge.aId) === undefined ||
|
|
759
|
+
checkNodeExists.get(edge.bId) === undefined) {
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
const clampedWeight = Math.min(10.0, Math.max(0.0, edge.weight));
|
|
763
|
+
upsertEdgeStmt.run(edge.edgeId, edge.aId, edge.bId, edge.edgeType, clampedWeight, edge.trust, edge.reason.slice(0, 256), edge.useCount ?? 0, edge.lastUsedAt ?? null, edge.createdAt, edge.updatedAt);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
if (input.synonyms && input.synonyms.length > 0) {
|
|
767
|
+
const checkNodeExists = this.#db.prepare('SELECT 1 AS ok FROM assoc_nodes WHERE id = ?');
|
|
768
|
+
const upsertSynonymStmt = this.#db.prepare(`
|
|
769
|
+
INSERT INTO assoc_synonyms (
|
|
770
|
+
id, owner_scope_key, surface, canonical_entity, source_node_id, trust, created_at
|
|
771
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
772
|
+
ON CONFLICT(owner_scope_key, surface, canonical_entity) DO UPDATE SET
|
|
773
|
+
source_node_id = excluded.source_node_id,
|
|
774
|
+
trust = excluded.trust
|
|
775
|
+
`);
|
|
776
|
+
for (const syn of input.synonyms) {
|
|
777
|
+
if (syn.sourceNodeId !== undefined && syn.sourceNodeId !== null) {
|
|
778
|
+
if (skippedWithdrawnNodeIds.has(syn.sourceNodeId) ||
|
|
779
|
+
checkNodeExists.get(syn.sourceNodeId) === undefined) {
|
|
780
|
+
skippedSynonymIds.add(syn.id);
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
const deterministicId = computeDeterministicSynonymId(syn.ownerScopeKey, syn.surface, syn.canonicalEntity);
|
|
785
|
+
const resolvedId = /^syn-[0-9a-f]{24}$/u.test(syn.id) ? syn.id : deterministicId;
|
|
786
|
+
synonymIdMap.set(syn.id, resolvedId);
|
|
787
|
+
upsertSynonymStmt.run(resolvedId, syn.ownerScopeKey, syn.surface, syn.canonicalEntity, syn.sourceNodeId ?? null, syn.trust, syn.createdAt);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
if (input.derivedRefs.length > 0) {
|
|
791
|
+
const insertDerivedStmt = this.#db.prepare(`
|
|
792
|
+
INSERT OR IGNORE INTO assoc_derived_from (
|
|
793
|
+
source_node_id, source_version, target_kind, target_id
|
|
794
|
+
) VALUES (?, ?, ?, ?)
|
|
795
|
+
`);
|
|
796
|
+
for (const ref of input.derivedRefs) {
|
|
797
|
+
if (skippedWithdrawnNodeIds.has(ref.sourceNodeId) ||
|
|
798
|
+
(ref.targetKind === 'node' && skippedWithdrawnNodeIds.has(ref.targetId)) ||
|
|
799
|
+
(ref.targetKind === 'synonym' && skippedSynonymIds.has(ref.targetId))) {
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
const resolvedTargetId = ref.targetKind === 'synonym'
|
|
803
|
+
? (synonymIdMap.get(ref.targetId) ?? ref.targetId)
|
|
804
|
+
: ref.targetId;
|
|
805
|
+
insertDerivedStmt.run(ref.sourceNodeId, ref.sourceVersion, ref.targetKind, resolvedTargetId);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
if (input.cursor) {
|
|
809
|
+
this.#db
|
|
810
|
+
.prepare(`
|
|
811
|
+
INSERT INTO assoc_ingest_cursors (source_plugin, scope_key, cursor_json, updated_at)
|
|
812
|
+
VALUES (?, ?, ?, ?)
|
|
813
|
+
ON CONFLICT(source_plugin, scope_key) DO UPDATE SET
|
|
814
|
+
cursor_json = excluded.cursor_json,
|
|
815
|
+
updated_at = excluded.updated_at
|
|
816
|
+
`)
|
|
817
|
+
.run(input.cursor.sourcePlugin, input.cursor.scopeKey, input.cursor.cursorJson, input.cursor.updatedAt ?? Date.now());
|
|
818
|
+
}
|
|
819
|
+
return {
|
|
820
|
+
deletedNodeIds,
|
|
821
|
+
suppressedNodeIds: [],
|
|
822
|
+
deletedEdgeIds,
|
|
823
|
+
deletedSynonymIds,
|
|
824
|
+
};
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
withdrawSource(input) {
|
|
828
|
+
return this.runInTransaction(() => {
|
|
829
|
+
const matchingNodes = this.#db
|
|
830
|
+
.prepare(`
|
|
831
|
+
SELECT id, source_version FROM assoc_nodes
|
|
832
|
+
WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?
|
|
833
|
+
`)
|
|
834
|
+
.all(input.ownerScopeKey, input.sourcePlugin, input.sourceRef);
|
|
835
|
+
const seeds = matchingNodes.map((row) => input.maxSourceVersion === undefined
|
|
836
|
+
? { nodeId: row.id }
|
|
837
|
+
: { nodeId: row.id, maxVersion: input.maxSourceVersion });
|
|
838
|
+
const cascade = this.#cascadeDerivedInCurrentTx(seeds);
|
|
839
|
+
const deletedNodeSet = new Set(cascade.deletedNodeIds);
|
|
840
|
+
const deletedEdgeSet = new Set(cascade.deletedEdgeIds);
|
|
841
|
+
const suppressedNodeIds = [];
|
|
842
|
+
const selectIncidentEdges = this.#db.prepare('SELECT edge_id FROM assoc_edges WHERE a_id = ? OR b_id = ?');
|
|
843
|
+
const deleteEdgeById = this.#db.prepare('DELETE FROM assoc_edges WHERE edge_id = ?');
|
|
844
|
+
const deleteDerivedEdgeByTarget = this.#db.prepare("DELETE FROM assoc_derived_from WHERE target_kind = 'edge' AND target_id = ?");
|
|
845
|
+
const deleteNodeById = this.#db.prepare('DELETE FROM assoc_nodes WHERE id = ?');
|
|
846
|
+
const suppressNodeById = this.#db.prepare("UPDATE assoc_nodes SET status = 'suppressed', updated_at = ? WHERE id = ?");
|
|
847
|
+
const nowMs = input.nowMs ?? Date.now();
|
|
848
|
+
for (const row of matchingNodes) {
|
|
849
|
+
const incident = selectIncidentEdges.all(row.id, row.id);
|
|
850
|
+
for (const edge of incident) {
|
|
851
|
+
deletedEdgeSet.add(edge.edge_id);
|
|
852
|
+
deleteEdgeById.run(edge.edge_id);
|
|
853
|
+
deleteDerivedEdgeByTarget.run(edge.edge_id);
|
|
854
|
+
}
|
|
855
|
+
if (input.hardDelete) {
|
|
856
|
+
deletedNodeSet.add(row.id);
|
|
857
|
+
deleteNodeById.run(row.id);
|
|
858
|
+
}
|
|
859
|
+
else {
|
|
860
|
+
suppressedNodeIds.push(row.id);
|
|
861
|
+
suppressNodeById.run(nowMs, row.id);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
if (input.recordWithdrawalTombstone) {
|
|
865
|
+
this.#db
|
|
866
|
+
.prepare(`
|
|
867
|
+
INSERT INTO assoc_withdrawn_sources (owner_scope_key, source_plugin, source_ref, withdrawn_at)
|
|
868
|
+
VALUES (?, ?, ?, ?)
|
|
869
|
+
ON CONFLICT(owner_scope_key, source_plugin, source_ref) DO UPDATE SET
|
|
870
|
+
withdrawn_at = excluded.withdrawn_at
|
|
871
|
+
`)
|
|
872
|
+
.run(input.ownerScopeKey, input.sourcePlugin, input.sourceRef, nowMs);
|
|
873
|
+
}
|
|
874
|
+
return {
|
|
875
|
+
deletedNodeIds: [...deletedNodeSet],
|
|
876
|
+
suppressedNodeIds,
|
|
877
|
+
deletedEdgeIds: [...deletedEdgeSet],
|
|
878
|
+
deletedSynonymIds: cascade.deletedSynonymIds,
|
|
879
|
+
};
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
#cascadeDerivedInCurrentTx(seeds) {
|
|
883
|
+
if (seeds.length === 0) {
|
|
884
|
+
return { deletedNodeIds: [], deletedEdgeIds: [], deletedSynonymIds: [] };
|
|
885
|
+
}
|
|
886
|
+
const selectAllBySource = this.#db.prepare('SELECT target_kind, target_id FROM assoc_derived_from WHERE source_node_id = ?');
|
|
887
|
+
const selectUpToVersionBySource = this.#db.prepare('SELECT target_kind, target_id FROM assoc_derived_from WHERE source_node_id = ? AND source_version <= ?');
|
|
888
|
+
const selectExactVersionBySource = this.#db.prepare('SELECT target_kind, target_id FROM assoc_derived_from WHERE source_node_id = ? AND source_version = ?');
|
|
889
|
+
const selectSynonymsBySourceNode = this.#db.prepare('SELECT id FROM assoc_synonyms WHERE source_node_id = ?');
|
|
890
|
+
const visitedNodes = new Set();
|
|
891
|
+
const deletedNodeIds = new Set();
|
|
892
|
+
const deletedEdgeIds = new Set();
|
|
893
|
+
const deletedSynonymIds = new Set();
|
|
894
|
+
const queue = [...seeds];
|
|
895
|
+
while (queue.length > 0) {
|
|
896
|
+
const current = queue.shift();
|
|
897
|
+
const visitKey = current.exactVersion !== undefined
|
|
898
|
+
? `${current.nodeId}:eq:${current.exactVersion}`
|
|
899
|
+
: current.maxVersion !== undefined
|
|
900
|
+
? `${current.nodeId}:le:${current.maxVersion}`
|
|
901
|
+
: `${current.nodeId}:*`;
|
|
902
|
+
if (visitedNodes.has(visitKey))
|
|
903
|
+
continue;
|
|
904
|
+
visitedNodes.add(visitKey);
|
|
905
|
+
const rows = (current.exactVersion !== undefined
|
|
906
|
+
? selectExactVersionBySource.all(current.nodeId, current.exactVersion)
|
|
907
|
+
: current.maxVersion === undefined
|
|
908
|
+
? selectAllBySource.all(current.nodeId)
|
|
909
|
+
: selectUpToVersionBySource.all(current.nodeId, current.maxVersion));
|
|
910
|
+
for (const row of rows) {
|
|
911
|
+
if (row.target_kind === 'edge') {
|
|
912
|
+
deletedEdgeIds.add(row.target_id);
|
|
913
|
+
}
|
|
914
|
+
else if (row.target_kind === 'synonym') {
|
|
915
|
+
deletedSynonymIds.add(row.target_id);
|
|
916
|
+
}
|
|
917
|
+
else if (row.target_kind === 'node') {
|
|
918
|
+
if (!deletedNodeIds.has(row.target_id)) {
|
|
919
|
+
deletedNodeIds.add(row.target_id);
|
|
920
|
+
queue.push({ nodeId: row.target_id });
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
const attachedSynonyms = selectSynonymsBySourceNode.all(current.nodeId);
|
|
925
|
+
for (const syn of attachedSynonyms) {
|
|
926
|
+
deletedSynonymIds.add(syn.id);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
const deleteDerivedByTarget = this.#db.prepare('DELETE FROM assoc_derived_from WHERE target_kind = ? AND target_id = ?');
|
|
930
|
+
const deleteSynonymById = this.#db.prepare('DELETE FROM assoc_synonyms WHERE id = ?');
|
|
931
|
+
const deleteEdgeById = this.#db.prepare('DELETE FROM assoc_edges WHERE edge_id = ?');
|
|
932
|
+
const selectIncidentEdges = this.#db.prepare('SELECT edge_id FROM assoc_edges WHERE a_id = ? OR b_id = ?');
|
|
933
|
+
const deleteNodeById = this.#db.prepare('DELETE FROM assoc_nodes WHERE id = ?');
|
|
934
|
+
const deleteDerivedBySourceAll = this.#db.prepare('DELETE FROM assoc_derived_from WHERE source_node_id = ?');
|
|
935
|
+
const deleteDerivedBySourceVersion = this.#db.prepare('DELETE FROM assoc_derived_from WHERE source_node_id = ? AND source_version <= ?');
|
|
936
|
+
const deleteDerivedBySourceExact = this.#db.prepare('DELETE FROM assoc_derived_from WHERE source_node_id = ? AND source_version = ?');
|
|
937
|
+
for (const synId of deletedSynonymIds) {
|
|
938
|
+
deleteSynonymById.run(synId);
|
|
939
|
+
deleteDerivedByTarget.run('synonym', synId);
|
|
940
|
+
}
|
|
941
|
+
for (const nodeId of deletedNodeIds) {
|
|
942
|
+
const incident = selectIncidentEdges.all(nodeId, nodeId);
|
|
943
|
+
for (const edge of incident) {
|
|
944
|
+
deletedEdgeIds.add(edge.edge_id);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
for (const edgeId of deletedEdgeIds) {
|
|
948
|
+
deleteEdgeById.run(edgeId);
|
|
949
|
+
deleteDerivedByTarget.run('edge', edgeId);
|
|
950
|
+
}
|
|
951
|
+
for (const nodeId of deletedNodeIds) {
|
|
952
|
+
deleteNodeById.run(nodeId);
|
|
953
|
+
deleteDerivedByTarget.run('node', nodeId);
|
|
954
|
+
deleteDerivedBySourceAll.run(nodeId);
|
|
955
|
+
}
|
|
956
|
+
for (const seed of seeds) {
|
|
957
|
+
if (seed.exactVersion !== undefined) {
|
|
958
|
+
deleteDerivedBySourceExact.run(seed.nodeId, seed.exactVersion);
|
|
959
|
+
}
|
|
960
|
+
else if (seed.maxVersion === undefined) {
|
|
961
|
+
deleteDerivedBySourceAll.run(seed.nodeId);
|
|
962
|
+
}
|
|
963
|
+
else {
|
|
964
|
+
deleteDerivedBySourceVersion.run(seed.nodeId, seed.maxVersion);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return {
|
|
968
|
+
deletedNodeIds: [...deletedNodeIds],
|
|
969
|
+
deletedEdgeIds: [...deletedEdgeIds],
|
|
970
|
+
deletedSynonymIds: [...deletedSynonymIds],
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
getNodeById(id) {
|
|
974
|
+
const row = this.#db
|
|
975
|
+
.prepare('SELECT * FROM assoc_nodes WHERE id = ?')
|
|
976
|
+
.get(id);
|
|
977
|
+
return row === undefined ? null : mapRawNode(row);
|
|
978
|
+
}
|
|
979
|
+
attachNodeOutcomeId(nodeId, outcomeId) {
|
|
980
|
+
const row = this.#db
|
|
981
|
+
.prepare('SELECT metadata_json FROM assoc_nodes WHERE id = ?')
|
|
982
|
+
.get(nodeId);
|
|
983
|
+
if (row === undefined)
|
|
984
|
+
return false;
|
|
985
|
+
const meta = JSON.parse(row.metadata_json);
|
|
986
|
+
const prevExtra = meta.extra !== null && typeof meta.extra === 'object' && !Array.isArray(meta.extra)
|
|
987
|
+
? meta.extra
|
|
988
|
+
: {};
|
|
989
|
+
if (prevExtra.outcomeId === outcomeId)
|
|
990
|
+
return false;
|
|
991
|
+
const nextMeta = {
|
|
992
|
+
...meta,
|
|
993
|
+
extra: {
|
|
994
|
+
...prevExtra,
|
|
995
|
+
outcomeId,
|
|
996
|
+
},
|
|
997
|
+
};
|
|
998
|
+
this.#db
|
|
999
|
+
.prepare('UPDATE assoc_nodes SET metadata_json = ? WHERE id = ?')
|
|
1000
|
+
.run(JSON.stringify(nextMeta), nodeId);
|
|
1001
|
+
return true;
|
|
1002
|
+
}
|
|
1003
|
+
isSourceWithdrawn(ownerScopeKey, sourcePlugin, sourceRef) {
|
|
1004
|
+
const row = this.#db
|
|
1005
|
+
.prepare('SELECT 1 AS ok FROM assoc_withdrawn_sources WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?')
|
|
1006
|
+
.get(ownerScopeKey, sourcePlugin, sourceRef);
|
|
1007
|
+
return row !== undefined;
|
|
1008
|
+
}
|
|
1009
|
+
countActiveNodes() {
|
|
1010
|
+
const row = this.#db
|
|
1011
|
+
.prepare("SELECT COUNT(*) AS cnt FROM assoc_nodes WHERE status = 'active'")
|
|
1012
|
+
.get();
|
|
1013
|
+
return row.cnt;
|
|
1014
|
+
}
|
|
1015
|
+
loadActiveNodesPage(limit, offset) {
|
|
1016
|
+
const rows = this.#db
|
|
1017
|
+
.prepare("SELECT * FROM assoc_nodes WHERE status = 'active' ORDER BY updated_at DESC, id ASC LIMIT ? OFFSET ?")
|
|
1018
|
+
.all(limit, offset);
|
|
1019
|
+
return rows.map(mapRawNode);
|
|
1020
|
+
}
|
|
1021
|
+
loadActiveEdgesPage(limit, offset) {
|
|
1022
|
+
const rows = this.#db
|
|
1023
|
+
.prepare(`
|
|
1024
|
+
SELECT e.edge_id, e.a_id, e.b_id, e.edge_type, e.weight, e.trust, e.reason,
|
|
1025
|
+
e.use_count, e.last_used_at, e.last_decayed_at, e.created_at, e.updated_at
|
|
1026
|
+
FROM assoc_edges e
|
|
1027
|
+
JOIN assoc_nodes a ON a.id = e.a_id AND a.status = 'active'
|
|
1028
|
+
JOIN assoc_nodes b ON b.id = e.b_id AND b.status = 'active'
|
|
1029
|
+
ORDER BY e.edge_id ASC
|
|
1030
|
+
LIMIT ? OFFSET ?
|
|
1031
|
+
`)
|
|
1032
|
+
.all(limit, offset);
|
|
1033
|
+
return rows.map((row) => ({
|
|
1034
|
+
edgeId: row.edge_id,
|
|
1035
|
+
aId: row.a_id,
|
|
1036
|
+
bId: row.b_id,
|
|
1037
|
+
edgeType: row.edge_type,
|
|
1038
|
+
weight: row.weight,
|
|
1039
|
+
trust: row.trust,
|
|
1040
|
+
reason: row.reason,
|
|
1041
|
+
useCount: row.use_count,
|
|
1042
|
+
lastUsedAt: row.last_used_at,
|
|
1043
|
+
lastDecayedAt: row.last_decayed_at,
|
|
1044
|
+
createdAt: row.created_at,
|
|
1045
|
+
updatedAt: row.updated_at,
|
|
1046
|
+
}));
|
|
1047
|
+
}
|
|
1048
|
+
loadActiveSynonymsPage(limit, offset) {
|
|
1049
|
+
const rows = this.#db
|
|
1050
|
+
.prepare('SELECT * FROM assoc_synonyms ORDER BY id ASC LIMIT ? OFFSET ?')
|
|
1051
|
+
.all(limit, offset);
|
|
1052
|
+
return rows.map((row) => ({
|
|
1053
|
+
id: row.id,
|
|
1054
|
+
ownerScopeKey: row.owner_scope_key,
|
|
1055
|
+
surface: row.surface,
|
|
1056
|
+
canonicalEntity: row.canonical_entity,
|
|
1057
|
+
sourceNodeId: row.source_node_id,
|
|
1058
|
+
trust: row.trust,
|
|
1059
|
+
createdAt: row.created_at,
|
|
1060
|
+
}));
|
|
1061
|
+
}
|
|
1062
|
+
getIngestCursor(sourcePlugin, scopeKey) {
|
|
1063
|
+
const row = this.#db
|
|
1064
|
+
.prepare('SELECT * FROM assoc_ingest_cursors WHERE source_plugin = ? AND scope_key = ?')
|
|
1065
|
+
.get(sourcePlugin, scopeKey);
|
|
1066
|
+
if (row === undefined)
|
|
1067
|
+
return null;
|
|
1068
|
+
return {
|
|
1069
|
+
sourcePlugin: row.source_plugin,
|
|
1070
|
+
scopeKey: row.scope_key,
|
|
1071
|
+
cursorJson: row.cursor_json,
|
|
1072
|
+
updatedAt: row.updated_at,
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
upsertIngestCursor(cursor) {
|
|
1076
|
+
this.#db
|
|
1077
|
+
.prepare(`
|
|
1078
|
+
INSERT INTO assoc_ingest_cursors (source_plugin, scope_key, cursor_json, updated_at)
|
|
1079
|
+
VALUES (?, ?, ?, ?)
|
|
1080
|
+
ON CONFLICT(source_plugin, scope_key) DO UPDATE SET
|
|
1081
|
+
cursor_json = excluded.cursor_json,
|
|
1082
|
+
updated_at = excluded.updated_at
|
|
1083
|
+
`)
|
|
1084
|
+
.run(cursor.sourcePlugin, cursor.scopeKey, cursor.cursorJson, cursor.updatedAt);
|
|
1085
|
+
}
|
|
1086
|
+
upsertOwnerScope(scope, nowMs = Date.now()) {
|
|
1087
|
+
this.#db
|
|
1088
|
+
.prepare(`
|
|
1089
|
+
INSERT INTO assoc_owner_scopes (
|
|
1090
|
+
owner_scope_key, mode, principal_id, principal_digest,
|
|
1091
|
+
principal_record_id, principal_version, workspace, agent_preset,
|
|
1092
|
+
authority_id, updated_at
|
|
1093
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1094
|
+
ON CONFLICT(owner_scope_key) DO UPDATE SET
|
|
1095
|
+
authority_id = COALESCE(excluded.authority_id, assoc_owner_scopes.authority_id),
|
|
1096
|
+
updated_at = excluded.updated_at
|
|
1097
|
+
`)
|
|
1098
|
+
.run(scope.ownerScopeKey, scope.mode, scope.principalId, scope.principalDigest, scope.principalRecordId, scope.principalVersion, scope.workspace, scope.agentPreset, scope.authorityId ?? null, nowMs);
|
|
1099
|
+
}
|
|
1100
|
+
listOwnerScopes() {
|
|
1101
|
+
const rows = this.#db
|
|
1102
|
+
.prepare('SELECT * FROM assoc_owner_scopes ORDER BY updated_at DESC, owner_scope_key ASC')
|
|
1103
|
+
.all();
|
|
1104
|
+
return rows.map((row) => ({
|
|
1105
|
+
mode: row.mode,
|
|
1106
|
+
ownerScopeKey: row.owner_scope_key,
|
|
1107
|
+
principalId: row.principal_id,
|
|
1108
|
+
principalDigest: row.principal_digest,
|
|
1109
|
+
principalRecordId: row.principal_record_id,
|
|
1110
|
+
principalVersion: row.principal_version,
|
|
1111
|
+
workspace: row.workspace,
|
|
1112
|
+
agentPreset: row.agent_preset,
|
|
1113
|
+
...(row.authority_id === null ? {} : { authorityId: row.authority_id }),
|
|
1114
|
+
}));
|
|
1115
|
+
}
|
|
1116
|
+
findNodeBySourceRef(ownerScopeKey, sourcePlugin, sourceRef) {
|
|
1117
|
+
const row = this.#db
|
|
1118
|
+
.prepare('SELECT * FROM assoc_nodes WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?')
|
|
1119
|
+
.get(ownerScopeKey, sourcePlugin, sourceRef);
|
|
1120
|
+
return row === undefined ? null : mapRawNode(row);
|
|
1121
|
+
}
|
|
1122
|
+
listActiveSourceRefsForPlugin(ownerScopeKey, sourcePlugin) {
|
|
1123
|
+
const rows = this.#db
|
|
1124
|
+
.prepare("SELECT source_ref FROM assoc_nodes WHERE owner_scope_key = ? AND source_plugin = ? AND status = 'active'")
|
|
1125
|
+
.all(ownerScopeKey, sourcePlugin);
|
|
1126
|
+
return rows.map((row) => row.source_ref);
|
|
1127
|
+
}
|
|
1128
|
+
listActiveNodesBySourcePlugin(ownerScopeKey, sourcePlugin) {
|
|
1129
|
+
const rows = this.#db
|
|
1130
|
+
.prepare("SELECT * FROM assoc_nodes WHERE owner_scope_key = ? AND source_plugin = ? AND status = 'active'")
|
|
1131
|
+
.all(ownerScopeKey, sourcePlugin);
|
|
1132
|
+
return rows.map(mapRawNode);
|
|
1133
|
+
}
|
|
1134
|
+
listCascadeNodeIdsForSource(ownerScopeKey, sourcePlugin, sourceRef) {
|
|
1135
|
+
const matching = this.#db
|
|
1136
|
+
.prepare('SELECT id FROM assoc_nodes WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?')
|
|
1137
|
+
.all(ownerScopeKey, sourcePlugin, sourceRef);
|
|
1138
|
+
if (matching.length === 0)
|
|
1139
|
+
return [];
|
|
1140
|
+
const selectDerivedNodes = this.#db.prepare("SELECT target_id FROM assoc_derived_from WHERE source_node_id = ? AND target_kind = 'node'");
|
|
1141
|
+
const visited = new Set();
|
|
1142
|
+
const queue = [];
|
|
1143
|
+
for (const row of matching) {
|
|
1144
|
+
if (!visited.has(row.id)) {
|
|
1145
|
+
visited.add(row.id);
|
|
1146
|
+
queue.push(row.id);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
while (queue.length > 0) {
|
|
1150
|
+
const current = queue.shift();
|
|
1151
|
+
const children = selectDerivedNodes.all(current);
|
|
1152
|
+
for (const child of children) {
|
|
1153
|
+
if (!visited.has(child.target_id)) {
|
|
1154
|
+
visited.add(child.target_id);
|
|
1155
|
+
queue.push(child.target_id);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
return [...visited];
|
|
1160
|
+
}
|
|
1161
|
+
loadEntityCandidateNodesForScope(ownerScopeKey, limit = 256) {
|
|
1162
|
+
const rows = this.#db
|
|
1163
|
+
.prepare(`
|
|
1164
|
+
SELECT id, source_version, owner_scope_key, trust, entities_json, updated_at
|
|
1165
|
+
FROM assoc_nodes
|
|
1166
|
+
WHERE status = 'active' AND owner_scope_key = ? AND sensitivity = 'private'
|
|
1167
|
+
ORDER BY updated_at DESC, id ASC
|
|
1168
|
+
LIMIT ?
|
|
1169
|
+
`)
|
|
1170
|
+
.all(ownerScopeKey, limit);
|
|
1171
|
+
return rows.map((row) => ({
|
|
1172
|
+
id: row.id,
|
|
1173
|
+
sourceVersion: row.source_version,
|
|
1174
|
+
ownerScopeKey: row.owner_scope_key,
|
|
1175
|
+
trust: row.trust,
|
|
1176
|
+
entities: JSON.parse(row.entities_json),
|
|
1177
|
+
updatedAt: row.updated_at,
|
|
1178
|
+
}));
|
|
1179
|
+
}
|
|
1180
|
+
suppressNodeConflict(input) {
|
|
1181
|
+
return this.runInTransaction(() => {
|
|
1182
|
+
const matchingNodes = this.#db
|
|
1183
|
+
.prepare(`
|
|
1184
|
+
SELECT id, source_version, metadata_json FROM assoc_nodes
|
|
1185
|
+
WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?
|
|
1186
|
+
`)
|
|
1187
|
+
.all(input.ownerScopeKey, input.sourcePlugin, input.sourceRef);
|
|
1188
|
+
const seeds = matchingNodes.map((row) => ({
|
|
1189
|
+
nodeId: row.id,
|
|
1190
|
+
}));
|
|
1191
|
+
const cascade = this.#cascadeDerivedInCurrentTx(seeds);
|
|
1192
|
+
const deletedEdgeSet = new Set(cascade.deletedEdgeIds);
|
|
1193
|
+
const suppressedNodeIds = [];
|
|
1194
|
+
const nowMs = input.nowMs ?? Date.now();
|
|
1195
|
+
const selectIncidentEdges = this.#db.prepare('SELECT edge_id FROM assoc_edges WHERE a_id = ? OR b_id = ?');
|
|
1196
|
+
const deleteEdgeById = this.#db.prepare('DELETE FROM assoc_edges WHERE edge_id = ?');
|
|
1197
|
+
const deleteDerivedEdgeByTarget = this.#db.prepare("DELETE FROM assoc_derived_from WHERE target_kind = 'edge' AND target_id = ?");
|
|
1198
|
+
const updateNodeStmt = this.#db.prepare(`
|
|
1199
|
+
UPDATE assoc_nodes
|
|
1200
|
+
SET status = 'suppressed', trust = 'low', metadata_json = ?, updated_at = ?
|
|
1201
|
+
WHERE id = ?
|
|
1202
|
+
`);
|
|
1203
|
+
for (const row of matchingNodes) {
|
|
1204
|
+
const incident = selectIncidentEdges.all(row.id, row.id);
|
|
1205
|
+
for (const edge of incident) {
|
|
1206
|
+
deletedEdgeSet.add(edge.edge_id);
|
|
1207
|
+
deleteEdgeById.run(edge.edge_id);
|
|
1208
|
+
deleteDerivedEdgeByTarget.run(edge.edge_id);
|
|
1209
|
+
}
|
|
1210
|
+
const prevMeta = JSON.parse(row.metadata_json);
|
|
1211
|
+
const nextMeta = {
|
|
1212
|
+
...prevMeta,
|
|
1213
|
+
conflicted: true,
|
|
1214
|
+
...(input.objectiveStatus !== undefined
|
|
1215
|
+
? { objectiveStatus: input.objectiveStatus }
|
|
1216
|
+
: {}),
|
|
1217
|
+
};
|
|
1218
|
+
updateNodeStmt.run(JSON.stringify(nextMeta), nowMs, row.id);
|
|
1219
|
+
suppressedNodeIds.push(row.id);
|
|
1220
|
+
}
|
|
1221
|
+
return {
|
|
1222
|
+
deletedNodeIds: cascade.deletedNodeIds,
|
|
1223
|
+
suppressedNodeIds,
|
|
1224
|
+
deletedEdgeIds: [...deletedEdgeSet],
|
|
1225
|
+
deletedSynonymIds: cascade.deletedSynonymIds,
|
|
1226
|
+
};
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
recordHoldoutAssignment(row) {
|
|
1230
|
+
this.#db
|
|
1231
|
+
.prepare(`
|
|
1232
|
+
INSERT OR IGNORE INTO assoc_holdout_assignments (
|
|
1233
|
+
task_id, owner_scope_key, task_kind, session_id, turn_number,
|
|
1234
|
+
in_holdout, bucket_bps, rate_bps, hmac_digest, assigned_at
|
|
1235
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1236
|
+
`)
|
|
1237
|
+
.run(row.taskId, row.ownerScopeKey, row.taskKind, row.sessionId, row.turnNumber, row.inHoldout ? 1 : 0, row.bucketBps, row.rateBps, row.hmacDigest, row.assignedAt);
|
|
1238
|
+
}
|
|
1239
|
+
getHoldoutAssignment(taskId) {
|
|
1240
|
+
const row = this.#db
|
|
1241
|
+
.prepare('SELECT * FROM assoc_holdout_assignments WHERE task_id = ?')
|
|
1242
|
+
.get(taskId);
|
|
1243
|
+
if (row === undefined)
|
|
1244
|
+
return null;
|
|
1245
|
+
return {
|
|
1246
|
+
taskId: row.task_id,
|
|
1247
|
+
ownerScopeKey: row.owner_scope_key,
|
|
1248
|
+
taskKind: row.task_kind,
|
|
1249
|
+
sessionId: row.session_id,
|
|
1250
|
+
turnNumber: row.turn_number,
|
|
1251
|
+
inHoldout: row.in_holdout === 1,
|
|
1252
|
+
bucketBps: row.bucket_bps,
|
|
1253
|
+
rateBps: row.rate_bps,
|
|
1254
|
+
hmacDigest: row.hmac_digest,
|
|
1255
|
+
assignedAt: row.assigned_at,
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
recordMetricsAndExposures(metrics, exposures) {
|
|
1259
|
+
if (metrics.length === 0 && exposures.length === 0)
|
|
1260
|
+
return;
|
|
1261
|
+
this.runInTransaction(() => {
|
|
1262
|
+
if (metrics.length > 0) {
|
|
1263
|
+
const insertMetric = this.#db.prepare(`
|
|
1264
|
+
INSERT INTO assoc_step_metrics (
|
|
1265
|
+
task_id, owner_scope_key, in_holdout, latency_us, timed_out,
|
|
1266
|
+
fallback_mode, injected_count, candidate_count, source_counts_json,
|
|
1267
|
+
profile_version, occurred_at
|
|
1268
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1269
|
+
`);
|
|
1270
|
+
for (const m of metrics) {
|
|
1271
|
+
insertMetric.run(m.taskId, m.ownerScopeKey, m.inHoldout ? 1 : 0, m.latencyUs, m.timedOut ? 1 : 0, m.fallbackMode, m.injectedCount, m.candidateCount, JSON.stringify(m.sourceCounts), m.profileVersion ?? 0, m.occurredAt);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
if (exposures.length > 0) {
|
|
1275
|
+
const upsertExposure = this.#db.prepare(`
|
|
1276
|
+
INSERT INTO assoc_exposures (
|
|
1277
|
+
task_id, node_id, owner_scope_key, source_plugin, exposed_at,
|
|
1278
|
+
assoc_read_count, weak_use_count, corrected,
|
|
1279
|
+
was_exposed, hop, score, reason, provenance_edges_json, session_id,
|
|
1280
|
+
strong_used, weak_used, hebbian_delta_applied, corrected_at
|
|
1281
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1282
|
+
ON CONFLICT(task_id, node_id) DO UPDATE SET
|
|
1283
|
+
was_exposed = MAX(assoc_exposures.was_exposed, excluded.was_exposed),
|
|
1284
|
+
hop = CASE WHEN excluded.was_exposed = 1 THEN excluded.hop ELSE assoc_exposures.hop END,
|
|
1285
|
+
score = CASE WHEN excluded.was_exposed = 1 THEN excluded.score ELSE assoc_exposures.score END,
|
|
1286
|
+
reason = CASE WHEN excluded.was_exposed = 1 AND excluded.reason <> '' THEN excluded.reason ELSE assoc_exposures.reason END,
|
|
1287
|
+
provenance_edges_json = CASE
|
|
1288
|
+
WHEN excluded.was_exposed = 1 AND excluded.hop = 0 THEN '[]'
|
|
1289
|
+
WHEN excluded.was_exposed = 1 AND excluded.provenance_edges_json <> '[]' THEN excluded.provenance_edges_json
|
|
1290
|
+
ELSE assoc_exposures.provenance_edges_json
|
|
1291
|
+
END,
|
|
1292
|
+
session_id = COALESCE(excluded.session_id, assoc_exposures.session_id),
|
|
1293
|
+
assoc_read_count = assoc_exposures.assoc_read_count + excluded.assoc_read_count,
|
|
1294
|
+
weak_use_count = assoc_exposures.weak_use_count + excluded.weak_use_count,
|
|
1295
|
+
strong_used = MAX(assoc_exposures.strong_used, excluded.strong_used),
|
|
1296
|
+
weak_used = MAX(assoc_exposures.weak_used, excluded.weak_used),
|
|
1297
|
+
hebbian_delta_applied = assoc_exposures.hebbian_delta_applied + excluded.hebbian_delta_applied,
|
|
1298
|
+
corrected = MAX(assoc_exposures.corrected, excluded.corrected),
|
|
1299
|
+
corrected_at = COALESCE(assoc_exposures.corrected_at, excluded.corrected_at)
|
|
1300
|
+
`);
|
|
1301
|
+
for (const exp of exposures) {
|
|
1302
|
+
const hop = Math.max(0, Math.min(2, Math.trunc(exp.hop ?? 0)));
|
|
1303
|
+
upsertExposure.run(exp.taskId, exp.nodeId, exp.ownerScopeKey, exp.sourcePlugin, exp.exposedAt, exp.assocReadCount ?? 0, exp.weakUseCount ?? 0, exp.corrected ? 1 : 0, exp.wasExposed === false ? 0 : 1, hop, exp.score ?? 0, exp.reason ?? '', JSON.stringify(exp.provenanceEdges ?? []), exp.sessionId ?? null, exp.strongUsed ? 1 : 0, exp.weakUsed ? 1 : 0, exp.hebbianDeltaApplied ?? 0, exp.correctedAt ?? null);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
recordReadEvent(event) {
|
|
1309
|
+
this.#db
|
|
1310
|
+
.prepare(`
|
|
1311
|
+
INSERT INTO assoc_read_events (
|
|
1312
|
+
task_id, node_id, owner_scope_key, hit, reason, occurred_at
|
|
1313
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
1314
|
+
`)
|
|
1315
|
+
.run(event.taskId ?? null, event.nodeId, event.ownerScopeKey, event.hit ? 1 : 0, event.reason, event.occurredAt);
|
|
1316
|
+
}
|
|
1317
|
+
upsertTaskTelemetry(input) {
|
|
1318
|
+
this.runInTransaction(() => {
|
|
1319
|
+
const existing = this.#db
|
|
1320
|
+
.prepare(`
|
|
1321
|
+
SELECT turns, steps, input_tokens, output_tokens, cost_usd_micros
|
|
1322
|
+
FROM assoc_task_telemetry
|
|
1323
|
+
WHERE task_id = ?
|
|
1324
|
+
`)
|
|
1325
|
+
.get(input.taskId);
|
|
1326
|
+
const turns = Math.max(0, Math.trunc(input.turns ?? ((existing?.turns ?? 0) + (input.turnsDelta ?? 0))));
|
|
1327
|
+
const steps = Math.max(0, Math.trunc(input.steps ?? ((existing?.steps ?? 0) + (input.stepsDelta ?? 0))));
|
|
1328
|
+
const resolveOptionalCounter = (abs, delta, prev) => {
|
|
1329
|
+
if (abs !== undefined)
|
|
1330
|
+
return abs;
|
|
1331
|
+
if (delta !== undefined && delta !== null) {
|
|
1332
|
+
return (prev ?? 0) + delta;
|
|
1333
|
+
}
|
|
1334
|
+
return prev;
|
|
1335
|
+
};
|
|
1336
|
+
const inputTokens = resolveOptionalCounter(input.inputTokens, input.inputTokensDelta, existing?.input_tokens ?? null);
|
|
1337
|
+
const outputTokens = resolveOptionalCounter(input.outputTokens, input.outputTokensDelta, existing?.output_tokens ?? null);
|
|
1338
|
+
const costUsdMicros = resolveOptionalCounter(input.costUsdMicros, input.costUsdMicrosDelta, existing?.cost_usd_micros ?? null);
|
|
1339
|
+
this.#db
|
|
1340
|
+
.prepare(`
|
|
1341
|
+
INSERT INTO assoc_task_telemetry (
|
|
1342
|
+
task_id, owner_scope_key, in_holdout, turns, steps,
|
|
1343
|
+
input_tokens, output_tokens, cost_usd_micros, updated_at
|
|
1344
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1345
|
+
ON CONFLICT(task_id) DO UPDATE SET
|
|
1346
|
+
in_holdout = excluded.in_holdout,
|
|
1347
|
+
turns = excluded.turns,
|
|
1348
|
+
steps = excluded.steps,
|
|
1349
|
+
input_tokens = excluded.input_tokens,
|
|
1350
|
+
output_tokens = excluded.output_tokens,
|
|
1351
|
+
cost_usd_micros = excluded.cost_usd_micros,
|
|
1352
|
+
updated_at = excluded.updated_at
|
|
1353
|
+
`)
|
|
1354
|
+
.run(input.taskId, input.ownerScopeKey, input.inHoldout ? 1 : 0, turns, steps, inputTokens, outputTokens, costUsdMicros, input.updatedAt);
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
upsertReplayEpisode(input) {
|
|
1358
|
+
this.runInTransaction(() => {
|
|
1359
|
+
const existing = this.#db
|
|
1360
|
+
.prepare(`
|
|
1361
|
+
SELECT cues_json, used_node_ids_json, corrected_node_ids_json, profile_version
|
|
1362
|
+
FROM assoc_replay_episodes
|
|
1363
|
+
WHERE task_id = ?
|
|
1364
|
+
`)
|
|
1365
|
+
.get(input.taskId);
|
|
1366
|
+
const cuesJson = input.cues.length > 0 || existing === undefined
|
|
1367
|
+
? JSON.stringify(input.cues)
|
|
1368
|
+
: existing.cues_json;
|
|
1369
|
+
const prevUsed = existing !== undefined ? JSON.parse(existing.used_node_ids_json) : [];
|
|
1370
|
+
const prevCorrected = existing !== undefined ? JSON.parse(existing.corrected_node_ids_json) : [];
|
|
1371
|
+
const usedIds = mergeUniqueStrings(prevUsed, input.usedNodeIds ?? []);
|
|
1372
|
+
const correctedIds = mergeUniqueStrings(prevCorrected, input.correctedNodeIds ?? []);
|
|
1373
|
+
const profileVersion = input.profileVersion ?? existing?.profile_version ?? 0;
|
|
1374
|
+
this.#db
|
|
1375
|
+
.prepare(`
|
|
1376
|
+
INSERT INTO assoc_replay_episodes (
|
|
1377
|
+
task_id, owner_scope_key, in_holdout, cues_json,
|
|
1378
|
+
used_node_ids_json, corrected_node_ids_json, profile_version, occurred_at
|
|
1379
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1380
|
+
ON CONFLICT(task_id) DO UPDATE SET
|
|
1381
|
+
in_holdout = excluded.in_holdout,
|
|
1382
|
+
cues_json = excluded.cues_json,
|
|
1383
|
+
used_node_ids_json = excluded.used_node_ids_json,
|
|
1384
|
+
corrected_node_ids_json = excluded.corrected_node_ids_json,
|
|
1385
|
+
profile_version = excluded.profile_version,
|
|
1386
|
+
occurred_at = excluded.occurred_at
|
|
1387
|
+
`)
|
|
1388
|
+
.run(input.taskId, input.ownerScopeKey, input.inHoldout ? 1 : 0, cuesJson, JSON.stringify(usedIds), JSON.stringify(correctedIds), profileVersion, input.occurredAt);
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
hasExposedRow(taskId, nodeId) {
|
|
1392
|
+
const row = this.#db
|
|
1393
|
+
.prepare('SELECT 1 AS ok FROM assoc_exposures WHERE task_id = ? AND node_id = ? AND was_exposed = 1')
|
|
1394
|
+
.get(taskId, nodeId);
|
|
1395
|
+
return row !== undefined;
|
|
1396
|
+
}
|
|
1397
|
+
findLatestUncorrectedMemoryExposure(ownerScopeKey, nodeId, minExposedAt = 0) {
|
|
1398
|
+
const row = this.#db
|
|
1399
|
+
.prepare(`
|
|
1400
|
+
SELECT * FROM assoc_exposures
|
|
1401
|
+
WHERE owner_scope_key = ?
|
|
1402
|
+
AND node_id = ?
|
|
1403
|
+
AND was_exposed = 1
|
|
1404
|
+
AND corrected = 0
|
|
1405
|
+
AND exposed_at >= ?
|
|
1406
|
+
ORDER BY (CASE WHEN strong_used = 1 OR weak_used = 1 THEN 1 ELSE 0 END) DESC,
|
|
1407
|
+
exposed_at DESC
|
|
1408
|
+
LIMIT 1
|
|
1409
|
+
`)
|
|
1410
|
+
.get(ownerScopeKey, nodeId, minExposedAt);
|
|
1411
|
+
return row === undefined ? null : mapRawExposure(row);
|
|
1412
|
+
}
|
|
1413
|
+
#taskKindFamilyFallbackClause(taskId) {
|
|
1414
|
+
if (taskId.startsWith('foreground-turn:')) {
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
if (taskId.startsWith('automation-run:')) {
|
|
1418
|
+
return { sql: "task_id LIKE 'automation-run:%'", params: [] };
|
|
1419
|
+
}
|
|
1420
|
+
if (taskId.startsWith('work-item:')) {
|
|
1421
|
+
return { sql: "task_id LIKE 'work-item:%'", params: [] };
|
|
1422
|
+
}
|
|
1423
|
+
if (taskId.startsWith('goal-step:') || taskId.startsWith('goal-outcome:')) {
|
|
1424
|
+
return { sql: "(task_id LIKE 'goal-step:%' OR task_id LIKE 'goal-outcome:%')", params: [] };
|
|
1425
|
+
}
|
|
1426
|
+
if (taskId.startsWith('headless-session:')) {
|
|
1427
|
+
return { sql: "task_id LIKE 'headless-session:%'", params: [] };
|
|
1428
|
+
}
|
|
1429
|
+
const colonIdx = taskId.indexOf(':');
|
|
1430
|
+
if (colonIdx > 0) {
|
|
1431
|
+
const prefix = taskId.slice(0, colonIdx);
|
|
1432
|
+
const escaped = prefix.replace(/[\\%_]/gu, (ch) => `\\${ch}`);
|
|
1433
|
+
return { sql: "task_id LIKE ? ESCAPE '\\'", params: [`${escaped}:%`] };
|
|
1434
|
+
}
|
|
1435
|
+
return { sql: "task_id NOT LIKE '%:%'", params: [] };
|
|
1436
|
+
}
|
|
1437
|
+
findExposuresByTaskOrSession(ownerScopeKey, taskId, sessionId) {
|
|
1438
|
+
const byTask = this.#db
|
|
1439
|
+
.prepare(`
|
|
1440
|
+
SELECT * FROM assoc_exposures
|
|
1441
|
+
WHERE owner_scope_key = ? AND task_id = ? AND was_exposed = 1
|
|
1442
|
+
ORDER BY exposed_at ASC, node_id ASC
|
|
1443
|
+
`)
|
|
1444
|
+
.all(ownerScopeKey, taskId);
|
|
1445
|
+
if (byTask.length > 0) {
|
|
1446
|
+
return byTask.map(mapRawExposure);
|
|
1447
|
+
}
|
|
1448
|
+
const fallbackClause = this.#taskKindFamilyFallbackClause(taskId);
|
|
1449
|
+
if (fallbackClause !== null &&
|
|
1450
|
+
sessionId !== undefined &&
|
|
1451
|
+
sessionId !== null &&
|
|
1452
|
+
sessionId.length > 0) {
|
|
1453
|
+
const bySession = this.#db
|
|
1454
|
+
.prepare(`
|
|
1455
|
+
SELECT * FROM assoc_exposures
|
|
1456
|
+
WHERE owner_scope_key = ? AND session_id = ?
|
|
1457
|
+
AND ${fallbackClause.sql}
|
|
1458
|
+
AND was_exposed = 1
|
|
1459
|
+
ORDER BY exposed_at ASC, node_id ASC
|
|
1460
|
+
`)
|
|
1461
|
+
.all(ownerScopeKey, sessionId, ...fallbackClause.params);
|
|
1462
|
+
return bySession.map(mapRawExposure);
|
|
1463
|
+
}
|
|
1464
|
+
return [];
|
|
1465
|
+
}
|
|
1466
|
+
applyHebbianUse(input) {
|
|
1467
|
+
return this.runInTransaction(() => {
|
|
1468
|
+
const cfg = input.hebbianConfig;
|
|
1469
|
+
const alpha = cfg?.alpha ?? DEFAULT_HEBBIAN_CONFIG.alpha;
|
|
1470
|
+
const weakRatio = cfg?.weakRatio ?? DEFAULT_HEBBIAN_CONFIG.weakRatio;
|
|
1471
|
+
const wMin = cfg?.weightMin ?? DEFAULT_HEBBIAN_CONFIG.weightMin;
|
|
1472
|
+
const wMax = cfg?.weightMax ?? DEFAULT_HEBBIAN_CONFIG.weightMax;
|
|
1473
|
+
const initWeight = clampEdgeWeight(cfg?.initialHebbianWeight ?? DEFAULT_HEBBIAN_CONFIG.initialHebbianWeight, wMin, wMax);
|
|
1474
|
+
const weakDelta = alpha * weakRatio;
|
|
1475
|
+
const rawExp = this.#db
|
|
1476
|
+
.prepare(`
|
|
1477
|
+
SELECT * FROM assoc_exposures
|
|
1478
|
+
WHERE task_id = ? AND node_id = ?
|
|
1479
|
+
`)
|
|
1480
|
+
.get(input.taskId, input.nodeId);
|
|
1481
|
+
if (rawExp === undefined ||
|
|
1482
|
+
rawExp.was_exposed !== 1 ||
|
|
1483
|
+
rawExp.owner_scope_key !== input.ownerScopeKey ||
|
|
1484
|
+
rawExp.corrected === 1) {
|
|
1485
|
+
return { appliedDelta: 0, updatedEdges: 0, createdEdges: 0 };
|
|
1486
|
+
}
|
|
1487
|
+
const exp = mapRawExposure(rawExp);
|
|
1488
|
+
let delta = 0;
|
|
1489
|
+
let nextStrongUsed = exp.strongUsed ? 1 : 0;
|
|
1490
|
+
let nextWeakUsed = exp.weakUsed ? 1 : 0;
|
|
1491
|
+
const addReadCount = input.useKind === 'strong' ? 1 : 0;
|
|
1492
|
+
const addWeakCount = input.useKind === 'weak' ? 1 : 0;
|
|
1493
|
+
if (input.useKind === 'strong') {
|
|
1494
|
+
if (exp.strongUsed) {
|
|
1495
|
+
delta = 0;
|
|
1496
|
+
}
|
|
1497
|
+
else if (exp.weakUsed) {
|
|
1498
|
+
const alreadyApplied = exp.hebbianDeltaApplied > 0 ? Math.min(alpha, exp.hebbianDeltaApplied) : weakDelta;
|
|
1499
|
+
delta = Math.max(0, alpha - alreadyApplied);
|
|
1500
|
+
nextStrongUsed = 1;
|
|
1501
|
+
}
|
|
1502
|
+
else {
|
|
1503
|
+
delta = Math.max(0, alpha);
|
|
1504
|
+
nextStrongUsed = 1;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
else {
|
|
1508
|
+
if (exp.strongUsed || exp.weakUsed) {
|
|
1509
|
+
delta = 0;
|
|
1510
|
+
}
|
|
1511
|
+
else {
|
|
1512
|
+
delta = Math.max(0, weakDelta);
|
|
1513
|
+
nextWeakUsed = 1;
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
this.#db
|
|
1517
|
+
.prepare(`
|
|
1518
|
+
UPDATE assoc_exposures
|
|
1519
|
+
SET assoc_read_count = assoc_read_count + ?,
|
|
1520
|
+
weak_use_count = weak_use_count + ?,
|
|
1521
|
+
strong_used = ?,
|
|
1522
|
+
weak_used = ?,
|
|
1523
|
+
hebbian_delta_applied = hebbian_delta_applied + ?,
|
|
1524
|
+
session_id = COALESCE(session_id, ?)
|
|
1525
|
+
WHERE task_id = ? AND node_id = ?
|
|
1526
|
+
`)
|
|
1527
|
+
.run(addReadCount, addWeakCount, nextStrongUsed, nextWeakUsed, delta, input.sessionId ?? null, input.taskId, input.nodeId);
|
|
1528
|
+
if (delta <= 0) {
|
|
1529
|
+
return { appliedDelta: 0, updatedEdges: 0, createdEdges: 0 };
|
|
1530
|
+
}
|
|
1531
|
+
const selectActiveNode = this.#db.prepare(`
|
|
1532
|
+
SELECT id, source_version, owner_scope_key, sensitivity, trust
|
|
1533
|
+
FROM assoc_nodes
|
|
1534
|
+
WHERE id = ? AND status = 'active'
|
|
1535
|
+
`);
|
|
1536
|
+
const targetNode = selectActiveNode.get(input.nodeId);
|
|
1537
|
+
if (targetNode === undefined) {
|
|
1538
|
+
return { appliedDelta: delta, updatedEdges: 0, createdEdges: 0 };
|
|
1539
|
+
}
|
|
1540
|
+
const eventKind = input.useKind === 'strong' ? 'strong-use' : 'weak-use';
|
|
1541
|
+
const provenance = input.provenanceEdges !== undefined && input.provenanceEdges.length > 0
|
|
1542
|
+
? input.provenanceEdges
|
|
1543
|
+
: exp.provenanceEdges;
|
|
1544
|
+
const selectActiveEdge = this.#db.prepare(`
|
|
1545
|
+
SELECT e.edge_id, e.weight
|
|
1546
|
+
FROM assoc_edges e
|
|
1547
|
+
JOIN assoc_nodes a ON a.id = e.a_id AND a.status = 'active'
|
|
1548
|
+
JOIN assoc_nodes b ON b.id = e.b_id AND b.status = 'active'
|
|
1549
|
+
WHERE e.edge_id = ?
|
|
1550
|
+
`);
|
|
1551
|
+
const updateEdgeStmt = this.#db.prepare(`
|
|
1552
|
+
UPDATE assoc_edges
|
|
1553
|
+
SET weight = ?, use_count = use_count + 1, last_used_at = ?, last_decayed_at = ?, updated_at = ?
|
|
1554
|
+
WHERE edge_id = ?
|
|
1555
|
+
`);
|
|
1556
|
+
const insertHebbianEvent = this.#db.prepare(`
|
|
1557
|
+
INSERT INTO assoc_hebbian_events (
|
|
1558
|
+
owner_scope_key, task_id, node_id, edge_id, event_kind,
|
|
1559
|
+
delta, weight_before, weight_after, occurred_at
|
|
1560
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1561
|
+
`);
|
|
1562
|
+
const processedEdges = new Set();
|
|
1563
|
+
let updatedEdges = 0;
|
|
1564
|
+
let createdEdges = 0;
|
|
1565
|
+
for (const prov of provenance) {
|
|
1566
|
+
if (processedEdges.has(prov.edgeId))
|
|
1567
|
+
continue;
|
|
1568
|
+
processedEdges.add(prov.edgeId);
|
|
1569
|
+
const edgeRow = selectActiveEdge.get(prov.edgeId);
|
|
1570
|
+
if (edgeRow === undefined)
|
|
1571
|
+
continue;
|
|
1572
|
+
const weightBefore = edgeRow.weight;
|
|
1573
|
+
const weightAfter = clampEdgeWeight(weightBefore + delta, wMin, wMax);
|
|
1574
|
+
updateEdgeStmt.run(weightAfter, input.nowMs, input.nowMs, input.nowMs, edgeRow.edge_id);
|
|
1575
|
+
insertHebbianEvent.run(input.ownerScopeKey, input.taskId, input.nodeId, edgeRow.edge_id, eventKind, weightAfter - weightBefore, weightBefore, weightAfter, input.nowMs);
|
|
1576
|
+
updatedEdges += 1;
|
|
1577
|
+
}
|
|
1578
|
+
if (provenance.length === 0 &&
|
|
1579
|
+
input.coActivatedNodeIds !== undefined &&
|
|
1580
|
+
input.coActivatedNodeIds.length > 0) {
|
|
1581
|
+
const insertEdgeStmt = this.#db.prepare(`
|
|
1582
|
+
INSERT INTO assoc_edges (
|
|
1583
|
+
edge_id, a_id, b_id, edge_type, weight, trust, reason,
|
|
1584
|
+
use_count, last_used_at, last_decayed_at, created_at, updated_at
|
|
1585
|
+
) VALUES (?, ?, ?, 'hebbian', ?, ?, 'hebbian:co-use', 1, ?, ?, ?, ?)
|
|
1586
|
+
`);
|
|
1587
|
+
const insertDerivedStmt = this.#db.prepare(`
|
|
1588
|
+
INSERT OR IGNORE INTO assoc_derived_from (
|
|
1589
|
+
source_node_id, source_version, target_kind, target_id
|
|
1590
|
+
) VALUES (?, ?, 'edge', ?)
|
|
1591
|
+
`);
|
|
1592
|
+
const seenPeers = new Set();
|
|
1593
|
+
for (const peerId of input.coActivatedNodeIds) {
|
|
1594
|
+
if (peerId === input.nodeId || seenPeers.has(peerId))
|
|
1595
|
+
continue;
|
|
1596
|
+
seenPeers.add(peerId);
|
|
1597
|
+
const peerNode = selectActiveNode.get(peerId);
|
|
1598
|
+
if (peerNode === undefined ||
|
|
1599
|
+
peerNode.owner_scope_key !== input.ownerScopeKey ||
|
|
1600
|
+
peerNode.sensitivity !== 'private') {
|
|
1601
|
+
continue;
|
|
1602
|
+
}
|
|
1603
|
+
const [aId, bId] = input.nodeId <= peerId ? [input.nodeId, peerId] : [peerId, input.nodeId];
|
|
1604
|
+
const hebbianEdgeId = computeDeterministicEdgeId(aId, bId, 'hebbian');
|
|
1605
|
+
if (processedEdges.has(hebbianEdgeId))
|
|
1606
|
+
continue;
|
|
1607
|
+
processedEdges.add(hebbianEdgeId);
|
|
1608
|
+
const existingEdge = selectActiveEdge.get(hebbianEdgeId);
|
|
1609
|
+
if (existingEdge !== undefined) {
|
|
1610
|
+
const weightBefore = existingEdge.weight;
|
|
1611
|
+
const weightAfter = clampEdgeWeight(weightBefore + delta, wMin, wMax);
|
|
1612
|
+
updateEdgeStmt.run(weightAfter, input.nowMs, input.nowMs, input.nowMs, existingEdge.edge_id);
|
|
1613
|
+
insertHebbianEvent.run(input.ownerScopeKey, input.taskId, input.nodeId, existingEdge.edge_id, eventKind, weightAfter - weightBefore, weightBefore, weightAfter, input.nowMs);
|
|
1614
|
+
updatedEdges += 1;
|
|
1615
|
+
}
|
|
1616
|
+
else {
|
|
1617
|
+
const createdWeight = clampEdgeWeight(initWeight + delta, wMin, wMax);
|
|
1618
|
+
const edgeTrust = targetNode.trust === 'low' || peerNode.trust === 'low' ? 'low' : 'trusted';
|
|
1619
|
+
insertEdgeStmt.run(hebbianEdgeId, aId, bId, createdWeight, edgeTrust, input.nowMs, input.nowMs, input.nowMs, input.nowMs);
|
|
1620
|
+
insertDerivedStmt.run(targetNode.id, targetNode.source_version, hebbianEdgeId);
|
|
1621
|
+
insertDerivedStmt.run(peerNode.id, peerNode.source_version, hebbianEdgeId);
|
|
1622
|
+
insertHebbianEvent.run(input.ownerScopeKey, input.taskId, input.nodeId, hebbianEdgeId, eventKind, createdWeight, 0, createdWeight, input.nowMs);
|
|
1623
|
+
createdEdges += 1;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
return { appliedDelta: delta, updatedEdges, createdEdges };
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
applyHebbianCorrection(input) {
|
|
1631
|
+
return this.runInTransaction(() => {
|
|
1632
|
+
const cfg = input.hebbianConfig;
|
|
1633
|
+
const beta = Math.max(0, cfg?.beta ?? DEFAULT_HEBBIAN_CONFIG.beta);
|
|
1634
|
+
const wMin = cfg?.weightMin ?? DEFAULT_HEBBIAN_CONFIG.weightMin;
|
|
1635
|
+
const wMax = cfg?.weightMax ?? DEFAULT_HEBBIAN_CONFIG.weightMax;
|
|
1636
|
+
let targets = [];
|
|
1637
|
+
if (input.taskId !== undefined && input.taskId !== null && input.taskId.length > 0) {
|
|
1638
|
+
if (input.nodeId !== undefined && input.nodeId !== null && input.nodeId.length > 0) {
|
|
1639
|
+
targets = this.#db
|
|
1640
|
+
.prepare(`
|
|
1641
|
+
SELECT * FROM assoc_exposures
|
|
1642
|
+
WHERE owner_scope_key = ? AND task_id = ? AND node_id = ?
|
|
1643
|
+
AND was_exposed = 1 AND corrected = 0
|
|
1644
|
+
`)
|
|
1645
|
+
.all(input.ownerScopeKey, input.taskId, input.nodeId);
|
|
1646
|
+
}
|
|
1647
|
+
else {
|
|
1648
|
+
targets = this.#db
|
|
1649
|
+
.prepare(`
|
|
1650
|
+
SELECT * FROM assoc_exposures
|
|
1651
|
+
WHERE owner_scope_key = ? AND task_id = ?
|
|
1652
|
+
AND was_exposed = 1 AND corrected = 0
|
|
1653
|
+
`)
|
|
1654
|
+
.all(input.ownerScopeKey, input.taskId);
|
|
1655
|
+
}
|
|
1656
|
+
const fallbackClause = this.#taskKindFamilyFallbackClause(input.taskId);
|
|
1657
|
+
if (targets.length === 0 &&
|
|
1658
|
+
fallbackClause !== null &&
|
|
1659
|
+
input.sessionId !== undefined &&
|
|
1660
|
+
input.sessionId !== null &&
|
|
1661
|
+
input.sessionId.length > 0) {
|
|
1662
|
+
targets = this.#db
|
|
1663
|
+
.prepare(`
|
|
1664
|
+
SELECT * FROM assoc_exposures
|
|
1665
|
+
WHERE owner_scope_key = ? AND session_id = ?
|
|
1666
|
+
AND ${fallbackClause.sql}
|
|
1667
|
+
AND was_exposed = 1 AND corrected = 0
|
|
1668
|
+
`)
|
|
1669
|
+
.all(input.ownerScopeKey, input.sessionId, ...fallbackClause.params);
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
else if (input.nodeId !== undefined && input.nodeId !== null && input.nodeId.length > 0) {
|
|
1673
|
+
const single = this.#db
|
|
1674
|
+
.prepare(`
|
|
1675
|
+
SELECT * FROM assoc_exposures
|
|
1676
|
+
WHERE owner_scope_key = ? AND node_id = ?
|
|
1677
|
+
AND was_exposed = 1 AND corrected = 0 AND exposed_at >= ?
|
|
1678
|
+
ORDER BY (CASE WHEN strong_used = 1 OR weak_used = 1 THEN 1 ELSE 0 END) DESC,
|
|
1679
|
+
exposed_at DESC
|
|
1680
|
+
LIMIT 1
|
|
1681
|
+
`)
|
|
1682
|
+
.get(input.ownerScopeKey, input.nodeId, input.minExposedAt ?? 0);
|
|
1683
|
+
if (single !== undefined) {
|
|
1684
|
+
targets = [single];
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
if (targets.length === 0) {
|
|
1688
|
+
return { correctedExposures: 0, updatedEdges: 0 };
|
|
1689
|
+
}
|
|
1690
|
+
const markCorrectedStmt = this.#db.prepare(`
|
|
1691
|
+
UPDATE assoc_exposures
|
|
1692
|
+
SET corrected = 1, corrected_at = ?
|
|
1693
|
+
WHERE task_id = ? AND node_id = ? AND corrected = 0
|
|
1694
|
+
`);
|
|
1695
|
+
let correctedExposures = 0;
|
|
1696
|
+
for (const row of targets) {
|
|
1697
|
+
const res = markCorrectedStmt.run(input.nowMs, row.task_id, row.node_id);
|
|
1698
|
+
if (res.changes > 0)
|
|
1699
|
+
correctedExposures += 1;
|
|
1700
|
+
}
|
|
1701
|
+
const mapped = targets.map(mapRawExposure);
|
|
1702
|
+
const usedTargets = mapped.filter((e) => e.strongUsed || e.weakUsed);
|
|
1703
|
+
const penalizedTargets = usedTargets.length > 0 ? usedTargets : mapped;
|
|
1704
|
+
const edgeCandidates = new Map();
|
|
1705
|
+
const selectTaskExposedNodes = this.#db.prepare(`
|
|
1706
|
+
SELECT node_id FROM assoc_exposures
|
|
1707
|
+
WHERE task_id = ? AND owner_scope_key = ? AND was_exposed = 1
|
|
1708
|
+
`);
|
|
1709
|
+
const selectIncidentHebbian = this.#db.prepare(`
|
|
1710
|
+
SELECT edge_id, a_id, b_id FROM assoc_edges
|
|
1711
|
+
WHERE edge_type = 'hebbian' AND (a_id = ? OR b_id = ?)
|
|
1712
|
+
`);
|
|
1713
|
+
const selectTaskHebbianEvents = this.#db.prepare(`
|
|
1714
|
+
SELECT DISTINCT edge_id FROM assoc_hebbian_events
|
|
1715
|
+
WHERE owner_scope_key = ? AND task_id = ? AND node_id = ?
|
|
1716
|
+
AND event_kind IN ('strong-use', 'weak-use')
|
|
1717
|
+
`);
|
|
1718
|
+
for (const exp of penalizedTargets) {
|
|
1719
|
+
for (const prov of exp.provenanceEdges) {
|
|
1720
|
+
if (!edgeCandidates.has(prov.edgeId)) {
|
|
1721
|
+
edgeCandidates.set(prov.edgeId, { taskId: exp.taskId, nodeId: exp.nodeId });
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
const hebbianEventRows = selectTaskHebbianEvents.all(input.ownerScopeKey, exp.taskId, exp.nodeId);
|
|
1725
|
+
for (const ev of hebbianEventRows) {
|
|
1726
|
+
if (!edgeCandidates.has(ev.edge_id)) {
|
|
1727
|
+
edgeCandidates.set(ev.edge_id, { taskId: exp.taskId, nodeId: exp.nodeId });
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
const peerRows = selectTaskExposedNodes.all(exp.taskId, input.ownerScopeKey);
|
|
1731
|
+
const taskPeers = new Set(peerRows.map((p) => p.node_id));
|
|
1732
|
+
const incidentHebbian = selectIncidentHebbian.all(exp.nodeId, exp.nodeId);
|
|
1733
|
+
for (const edge of incidentHebbian) {
|
|
1734
|
+
const otherId = edge.a_id === exp.nodeId ? edge.b_id : edge.a_id;
|
|
1735
|
+
if (taskPeers.has(otherId) && !edgeCandidates.has(edge.edge_id)) {
|
|
1736
|
+
edgeCandidates.set(edge.edge_id, { taskId: exp.taskId, nodeId: exp.nodeId });
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
const selectEdgeWeight = this.#db.prepare('SELECT edge_id, weight FROM assoc_edges WHERE edge_id = ?');
|
|
1741
|
+
const updateEdgeWeight = this.#db.prepare('UPDATE assoc_edges SET weight = ?, updated_at = ? WHERE edge_id = ?');
|
|
1742
|
+
const insertHebbianEvent = this.#db.prepare(`
|
|
1743
|
+
INSERT INTO assoc_hebbian_events (
|
|
1744
|
+
owner_scope_key, task_id, node_id, edge_id, event_kind,
|
|
1745
|
+
delta, weight_before, weight_after, occurred_at
|
|
1746
|
+
) VALUES (?, ?, ?, ?, 'correction', ?, ?, ?, ?)
|
|
1747
|
+
`);
|
|
1748
|
+
let updatedEdges = 0;
|
|
1749
|
+
for (const [edgeId, meta] of edgeCandidates) {
|
|
1750
|
+
const edgeRow = selectEdgeWeight.get(edgeId);
|
|
1751
|
+
if (edgeRow === undefined)
|
|
1752
|
+
continue;
|
|
1753
|
+
const weightBefore = edgeRow.weight;
|
|
1754
|
+
const weightAfter = clampEdgeWeight(weightBefore - beta, wMin, wMax);
|
|
1755
|
+
updateEdgeWeight.run(weightAfter, input.nowMs, edgeRow.edge_id);
|
|
1756
|
+
insertHebbianEvent.run(input.ownerScopeKey, meta.taskId, meta.nodeId, edgeRow.edge_id, weightAfter - weightBefore, weightBefore, weightAfter, input.nowMs);
|
|
1757
|
+
updatedEdges += 1;
|
|
1758
|
+
}
|
|
1759
|
+
return { correctedExposures, updatedEdges };
|
|
1760
|
+
});
|
|
1761
|
+
}
|
|
1762
|
+
applyHebbianDecayBatch(input) {
|
|
1763
|
+
const safeLimit = Math.max(1, Math.min(200, Math.trunc(input.limit ?? 200)));
|
|
1764
|
+
const wMin = Math.max(0.0, Math.min(10.0, input.weightMin));
|
|
1765
|
+
const wMax = Math.max(wMin, Math.min(10.0, input.weightMax));
|
|
1766
|
+
return this.runInTransaction(() => {
|
|
1767
|
+
const rows = this.#db
|
|
1768
|
+
.prepare(`
|
|
1769
|
+
SELECT e.edge_id, e.a_id, e.weight, e.last_used_at, e.created_at, e.last_decayed_at,
|
|
1770
|
+
a.owner_scope_key
|
|
1771
|
+
FROM assoc_edges e
|
|
1772
|
+
JOIN assoc_nodes a ON a.id = e.a_id
|
|
1773
|
+
WHERE e.weight > ?
|
|
1774
|
+
AND COALESCE(e.last_used_at, e.created_at) <= ?
|
|
1775
|
+
AND COALESCE(e.last_decayed_at, COALESCE(e.last_used_at, e.created_at) + ?) < ?
|
|
1776
|
+
ORDER BY COALESCE(e.last_decayed_at, COALESCE(e.last_used_at, e.created_at) + ?) ASC, e.edge_id ASC
|
|
1777
|
+
LIMIT ?
|
|
1778
|
+
`)
|
|
1779
|
+
.all(wMin, input.nowMs - input.nonUseGraceMs, input.nonUseGraceMs, input.nowMs, input.nonUseGraceMs, safeLimit + 1);
|
|
1780
|
+
const hasMore = rows.length > safeLimit;
|
|
1781
|
+
const batch = hasMore ? rows.slice(0, safeLimit) : rows;
|
|
1782
|
+
if (batch.length === 0) {
|
|
1783
|
+
return { decayedEdges: 0, hasMore: false };
|
|
1784
|
+
}
|
|
1785
|
+
const updateEdge = this.#db.prepare(`
|
|
1786
|
+
UPDATE assoc_edges
|
|
1787
|
+
SET weight = ?, last_decayed_at = ?, updated_at = ?
|
|
1788
|
+
WHERE edge_id = ?
|
|
1789
|
+
`);
|
|
1790
|
+
const insertEvent = this.#db.prepare(`
|
|
1791
|
+
INSERT INTO assoc_hebbian_events (
|
|
1792
|
+
owner_scope_key, task_id, node_id, edge_id, event_kind,
|
|
1793
|
+
delta, weight_before, weight_after, occurred_at
|
|
1794
|
+
) VALUES (?, NULL, ?, ?, 'decay', ?, ?, ?, ?)
|
|
1795
|
+
`);
|
|
1796
|
+
let decayedEdges = 0;
|
|
1797
|
+
for (const edge of batch) {
|
|
1798
|
+
const anchor = edge.last_used_at ?? edge.created_at;
|
|
1799
|
+
const graceEnd = anchor + input.nonUseGraceMs;
|
|
1800
|
+
const decayStart = Math.max(edge.last_decayed_at ?? graceEnd, graceEnd);
|
|
1801
|
+
const dt = Math.max(0, input.nowMs - decayStart);
|
|
1802
|
+
if (dt <= 0 || input.decayHalfLifeMs <= 0)
|
|
1803
|
+
continue;
|
|
1804
|
+
const baseWeight = clampEdgeWeight(edge.weight, wMin, wMax);
|
|
1805
|
+
const decayed = baseWeight * Math.exp((-Math.LN2 * dt) / input.decayHalfLifeMs);
|
|
1806
|
+
const weightAfter = clampEdgeWeight(decayed, wMin, wMax);
|
|
1807
|
+
updateEdge.run(weightAfter, input.nowMs, input.nowMs, edge.edge_id);
|
|
1808
|
+
insertEvent.run(edge.owner_scope_key, edge.a_id, edge.edge_id, weightAfter - edge.weight, edge.weight, weightAfter, input.nowMs);
|
|
1809
|
+
decayedEdges += 1;
|
|
1810
|
+
}
|
|
1811
|
+
return { decayedEdges, hasMore };
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
//# sourceMappingURL=sqlite.js.map
|