@dsh-ray/assistant-association 0.0.1-seed.0 → 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 +132 -1
- 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 +149 -4
|
@@ -0,0 +1,1043 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { growthObjectDigest } from '@dsh-ray/assistant-growth-contract';
|
|
3
|
+
import { DEFAULT_HOLDOUT_RATE_BPS, evaluateHoldout } from './holdout.js';
|
|
4
|
+
import { normalizeEntityKey } from './tokenize.js';
|
|
5
|
+
export const WP04_CANDIDATE_ORIGIN_PROTOCOL = 'assistant-association/wp04-candidate-origin/v1';
|
|
6
|
+
export const IMPLICIT_SIGNAL_KINDS = ['re-ask', 'redo', 'owner-correction'];
|
|
7
|
+
export const SKILL_CANDIDATE_STATUSES = ['pending', 'staged', 'dismissed'];
|
|
8
|
+
const UNACHIEVED_OBJECTIVE_STATUSES = new Set([
|
|
9
|
+
'failed',
|
|
10
|
+
'partial',
|
|
11
|
+
'blocked',
|
|
12
|
+
'abandoned',
|
|
13
|
+
'not-achieved',
|
|
14
|
+
]);
|
|
15
|
+
export class Wp04OriginError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
constructor(code, message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.name = 'Wp04OriginError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export const DEFAULT_CLUSTERING_CONFIG = Object.freeze({
|
|
24
|
+
entityWeight: 0.4,
|
|
25
|
+
toolWeight: 0.6,
|
|
26
|
+
minSimilarity: 0.55,
|
|
27
|
+
minClusterSize: 3,
|
|
28
|
+
reAskWindowMs: 3_600_000,
|
|
29
|
+
reAskMinEntityJaccard: 0.5,
|
|
30
|
+
});
|
|
31
|
+
export function normalizeClusteringConfig(input) {
|
|
32
|
+
const entityWeight = input?.entityWeight !== undefined && Number.isFinite(input.entityWeight) && input.entityWeight >= 0
|
|
33
|
+
? input.entityWeight
|
|
34
|
+
: DEFAULT_CLUSTERING_CONFIG.entityWeight;
|
|
35
|
+
const toolWeight = input?.toolWeight !== undefined && Number.isFinite(input.toolWeight) && input.toolWeight >= 0
|
|
36
|
+
? input.toolWeight
|
|
37
|
+
: DEFAULT_CLUSTERING_CONFIG.toolWeight;
|
|
38
|
+
const minSimilarity = input?.minSimilarity !== undefined &&
|
|
39
|
+
Number.isFinite(input.minSimilarity) &&
|
|
40
|
+
input.minSimilarity >= 0 &&
|
|
41
|
+
input.minSimilarity <= 1
|
|
42
|
+
? input.minSimilarity
|
|
43
|
+
: DEFAULT_CLUSTERING_CONFIG.minSimilarity;
|
|
44
|
+
const minClusterSize = input?.minClusterSize !== undefined &&
|
|
45
|
+
Number.isSafeInteger(input.minClusterSize) &&
|
|
46
|
+
input.minClusterSize >= 2
|
|
47
|
+
? input.minClusterSize
|
|
48
|
+
: DEFAULT_CLUSTERING_CONFIG.minClusterSize;
|
|
49
|
+
const reAskWindowMs = input?.reAskWindowMs !== undefined &&
|
|
50
|
+
Number.isFinite(input.reAskWindowMs) &&
|
|
51
|
+
input.reAskWindowMs >= 0
|
|
52
|
+
? input.reAskWindowMs
|
|
53
|
+
: DEFAULT_CLUSTERING_CONFIG.reAskWindowMs;
|
|
54
|
+
const reAskMinEntityJaccard = input?.reAskMinEntityJaccard !== undefined &&
|
|
55
|
+
Number.isFinite(input.reAskMinEntityJaccard) &&
|
|
56
|
+
input.reAskMinEntityJaccard >= 0 &&
|
|
57
|
+
input.reAskMinEntityJaccard <= 1
|
|
58
|
+
? input.reAskMinEntityJaccard
|
|
59
|
+
: DEFAULT_CLUSTERING_CONFIG.reAskMinEntityJaccard;
|
|
60
|
+
return Object.freeze({
|
|
61
|
+
entityWeight,
|
|
62
|
+
toolWeight,
|
|
63
|
+
minSimilarity,
|
|
64
|
+
minClusterSize,
|
|
65
|
+
reAskWindowMs,
|
|
66
|
+
reAskMinEntityJaccard,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
export function ensureClusteringSchema(db) {
|
|
70
|
+
db.exec(`
|
|
71
|
+
CREATE TABLE IF NOT EXISTS assoc_skill_candidates (
|
|
72
|
+
candidate_id TEXT PRIMARY KEY,
|
|
73
|
+
owner_scope_key TEXT NOT NULL,
|
|
74
|
+
cluster_id TEXT NOT NULL,
|
|
75
|
+
signature_digest TEXT NOT NULL,
|
|
76
|
+
name TEXT NOT NULL,
|
|
77
|
+
description TEXT NOT NULL,
|
|
78
|
+
tool_sequence_json TEXT NOT NULL,
|
|
79
|
+
shared_entities_json TEXT NOT NULL,
|
|
80
|
+
member_task_ids_json TEXT NOT NULL,
|
|
81
|
+
goal_locators_json TEXT NOT NULL,
|
|
82
|
+
similarity REAL NOT NULL,
|
|
83
|
+
wp04_verified INTEGER NOT NULL CHECK (wp04_verified IN (0, 1)),
|
|
84
|
+
status TEXT NOT NULL CHECK (status IN ('pending', 'staged', 'dismissed')),
|
|
85
|
+
created_at INTEGER NOT NULL,
|
|
86
|
+
updated_at INTEGER NOT NULL
|
|
87
|
+
) STRICT;
|
|
88
|
+
|
|
89
|
+
CREATE INDEX IF NOT EXISTS assoc_skill_candidates_scope_time
|
|
90
|
+
ON assoc_skill_candidates(owner_scope_key, updated_at DESC);
|
|
91
|
+
|
|
92
|
+
CREATE INDEX IF NOT EXISTS assoc_skill_candidates_cluster
|
|
93
|
+
ON assoc_skill_candidates(cluster_id);
|
|
94
|
+
|
|
95
|
+
CREATE TABLE IF NOT EXISTS assoc_implicit_signals (
|
|
96
|
+
signal_id TEXT PRIMARY KEY,
|
|
97
|
+
owner_scope_key TEXT NOT NULL,
|
|
98
|
+
cluster_id TEXT NOT NULL,
|
|
99
|
+
kind TEXT NOT NULL CHECK (kind IN ('re-ask', 'redo', 'owner-correction')),
|
|
100
|
+
trust TEXT NOT NULL CHECK (trust = 'low'),
|
|
101
|
+
candidate_only INTEGER NOT NULL DEFAULT 1 CHECK (candidate_only = 1),
|
|
102
|
+
report_only INTEGER NOT NULL DEFAULT 1 CHECK (report_only = 1),
|
|
103
|
+
evidence_json TEXT NOT NULL,
|
|
104
|
+
created_at INTEGER NOT NULL
|
|
105
|
+
) STRICT;
|
|
106
|
+
|
|
107
|
+
CREATE INDEX IF NOT EXISTS assoc_implicit_signals_scope_time
|
|
108
|
+
ON assoc_implicit_signals(owner_scope_key, created_at DESC);
|
|
109
|
+
|
|
110
|
+
CREATE INDEX IF NOT EXISTS assoc_implicit_signals_cluster
|
|
111
|
+
ON assoc_implicit_signals(cluster_id);
|
|
112
|
+
`);
|
|
113
|
+
}
|
|
114
|
+
function hasTable(db, tableName) {
|
|
115
|
+
const row = db
|
|
116
|
+
.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?")
|
|
117
|
+
.get(tableName);
|
|
118
|
+
return row !== undefined;
|
|
119
|
+
}
|
|
120
|
+
function normalizeEntities(entities) {
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
const out = [];
|
|
123
|
+
for (const raw of entities) {
|
|
124
|
+
const key = normalizeEntityKey(raw) ?? raw.normalize('NFKC').toLocaleLowerCase('en-US').trim();
|
|
125
|
+
if (key.length === 0 || seen.has(key))
|
|
126
|
+
continue;
|
|
127
|
+
seen.add(key);
|
|
128
|
+
out.push(key);
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
function normalizeTools(tools) {
|
|
133
|
+
const out = [];
|
|
134
|
+
for (const raw of tools) {
|
|
135
|
+
const trimmed = raw.trim();
|
|
136
|
+
if (trimmed.length > 0)
|
|
137
|
+
out.push(trimmed);
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
export function computeEntityJaccard(a, b) {
|
|
142
|
+
const setA = new Set(normalizeEntities(a));
|
|
143
|
+
const setB = new Set(normalizeEntities(b));
|
|
144
|
+
if (setA.size === 0 && setB.size === 0)
|
|
145
|
+
return 0;
|
|
146
|
+
let intersection = 0;
|
|
147
|
+
for (const item of setA) {
|
|
148
|
+
if (setB.has(item))
|
|
149
|
+
intersection += 1;
|
|
150
|
+
}
|
|
151
|
+
const union = setA.size + setB.size - intersection;
|
|
152
|
+
return union === 0 ? 0 : intersection / union;
|
|
153
|
+
}
|
|
154
|
+
export function computeToolSequenceLcs(a, b) {
|
|
155
|
+
const seqA = normalizeTools(a);
|
|
156
|
+
const seqB = normalizeTools(b);
|
|
157
|
+
const m = seqA.length;
|
|
158
|
+
const n = seqB.length;
|
|
159
|
+
if (m === 0 || n === 0)
|
|
160
|
+
return [];
|
|
161
|
+
const dp = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0));
|
|
162
|
+
for (let i = 1; i <= m; i += 1) {
|
|
163
|
+
const row = dp[i];
|
|
164
|
+
const prevRow = dp[i - 1];
|
|
165
|
+
const itemA = seqA[i - 1];
|
|
166
|
+
for (let j = 1; j <= n; j += 1) {
|
|
167
|
+
if (itemA === seqB[j - 1]) {
|
|
168
|
+
row[j] = (prevRow[j - 1] ?? 0) + 1;
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
const up = prevRow[j] ?? 0;
|
|
172
|
+
const left = row[j - 1] ?? 0;
|
|
173
|
+
row[j] = up >= left ? up : left;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const out = [];
|
|
178
|
+
let i = m;
|
|
179
|
+
let j = n;
|
|
180
|
+
while (i > 0 && j > 0) {
|
|
181
|
+
if (seqA[i - 1] === seqB[j - 1]) {
|
|
182
|
+
out.push(seqA[i - 1]);
|
|
183
|
+
i -= 1;
|
|
184
|
+
j -= 1;
|
|
185
|
+
}
|
|
186
|
+
else if ((dp[i - 1]?.[j] ?? 0) >= (dp[i]?.[j - 1] ?? 0)) {
|
|
187
|
+
i -= 1;
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
j -= 1;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
out.reverse();
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
export function computeToolSequenceSimilarity(a, b) {
|
|
197
|
+
const seqA = normalizeTools(a);
|
|
198
|
+
const seqB = normalizeTools(b);
|
|
199
|
+
const maxLen = Math.max(seqA.length, seqB.length);
|
|
200
|
+
if (seqA.length === 0 || seqB.length === 0 || maxLen === 0)
|
|
201
|
+
return 0;
|
|
202
|
+
const lcs = computeToolSequenceLcs(seqA, seqB);
|
|
203
|
+
return lcs.length / maxLen;
|
|
204
|
+
}
|
|
205
|
+
export function computeEpisodeSimilarity(a, b, weights) {
|
|
206
|
+
const entityWeight = weights?.entityWeight ?? DEFAULT_CLUSTERING_CONFIG.entityWeight;
|
|
207
|
+
const toolWeight = weights?.toolWeight ?? DEFAULT_CLUSTERING_CONFIG.toolWeight;
|
|
208
|
+
const jaccard = computeEntityJaccard(a.entities, b.entities);
|
|
209
|
+
const lcsNorm = computeToolSequenceSimilarity(a.toolNames, b.toolNames);
|
|
210
|
+
return entityWeight * jaccard + toolWeight * lcsNorm;
|
|
211
|
+
}
|
|
212
|
+
export function loadHoldoutTaskIdSet(db, taskIds) {
|
|
213
|
+
const holdoutSet = new Set();
|
|
214
|
+
const tables = [
|
|
215
|
+
'assoc_holdout_assignments',
|
|
216
|
+
'assoc_replay_episodes',
|
|
217
|
+
'assoc_eval_pool',
|
|
218
|
+
];
|
|
219
|
+
const uniqueTaskIds = taskIds === undefined
|
|
220
|
+
? undefined
|
|
221
|
+
: [...new Set(taskIds.filter((t) => t.length > 0))];
|
|
222
|
+
if (uniqueTaskIds !== undefined && uniqueTaskIds.length === 0) {
|
|
223
|
+
return holdoutSet;
|
|
224
|
+
}
|
|
225
|
+
for (const table of tables) {
|
|
226
|
+
if (!hasTable(db, table))
|
|
227
|
+
continue;
|
|
228
|
+
if (uniqueTaskIds === undefined) {
|
|
229
|
+
const rows = db
|
|
230
|
+
.prepare(`SELECT task_id FROM ${table} WHERE in_holdout = 1`)
|
|
231
|
+
.all();
|
|
232
|
+
for (const row of rows) {
|
|
233
|
+
holdoutSet.add(row.task_id);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
const chunkSize = 200;
|
|
238
|
+
for (let i = 0; i < uniqueTaskIds.length; i += chunkSize) {
|
|
239
|
+
const chunk = uniqueTaskIds.slice(i, i + chunkSize);
|
|
240
|
+
const placeholders = chunk.map(() => '?').join(', ');
|
|
241
|
+
const rows = db
|
|
242
|
+
.prepare(`SELECT task_id FROM ${table} WHERE in_holdout = 1 AND task_id IN (${placeholders})`)
|
|
243
|
+
.all(...chunk);
|
|
244
|
+
for (const row of rows) {
|
|
245
|
+
holdoutSet.add(row.task_id);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return holdoutSet;
|
|
251
|
+
}
|
|
252
|
+
export async function assertWp04CandidateOrigin(input) {
|
|
253
|
+
if (input.holdoutSeedKey === null ||
|
|
254
|
+
!Buffer.isBuffer(input.holdoutSeedKey) ||
|
|
255
|
+
input.holdoutSeedKey.length === 0) {
|
|
256
|
+
throw new Wp04OriginError('missing-holdout-seed', 'WP04 guard: holdoutSeedKey is required before candidate generation');
|
|
257
|
+
}
|
|
258
|
+
if (input.benchmarkPlan !== undefined) {
|
|
259
|
+
let assertCandidateGenerationInput;
|
|
260
|
+
try {
|
|
261
|
+
const mod = await import('@dsh-ray/assistant-evaluation/benchmark');
|
|
262
|
+
assertCandidateGenerationInput = mod.assertCandidateGenerationInput;
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
throw new Wp04OriginError('benchmark-guard-unavailable', 'WP04 guard: @dsh-ray/assistant-evaluation/benchmark is unavailable');
|
|
266
|
+
}
|
|
267
|
+
if (typeof assertCandidateGenerationInput !== 'function') {
|
|
268
|
+
throw new Wp04OriginError('benchmark-guard-unavailable', 'WP04 guard: assertCandidateGenerationInput is unavailable');
|
|
269
|
+
}
|
|
270
|
+
assertCandidateGenerationInput(input.benchmarkPlan);
|
|
271
|
+
}
|
|
272
|
+
const rateBps = input.holdoutRateBps ?? DEFAULT_HOLDOUT_RATE_BPS;
|
|
273
|
+
const scopes = new Set();
|
|
274
|
+
const taskIds = [];
|
|
275
|
+
for (const ep of input.episodes) {
|
|
276
|
+
if (ep.ownerScopeKey.trim().length === 0) {
|
|
277
|
+
throw new Wp04OriginError('mixed-owner-scope', 'WP04 guard: episode ownerScopeKey must be non-empty');
|
|
278
|
+
}
|
|
279
|
+
scopes.add(ep.ownerScopeKey);
|
|
280
|
+
if (input.ownerScopeKey !== undefined && ep.ownerScopeKey !== input.ownerScopeKey) {
|
|
281
|
+
throw new Wp04OriginError('mixed-owner-scope', `WP04 guard: episode ${ep.taskId} belongs to a different ownerScopeKey`);
|
|
282
|
+
}
|
|
283
|
+
if (ep.inHoldout === true) {
|
|
284
|
+
throw new Wp04OriginError('holdout-episode', `WP04 guard: holdout episode ${ep.taskId} is excluded from candidate generation`);
|
|
285
|
+
}
|
|
286
|
+
const decision = evaluateHoldout(input.holdoutSeedKey, ep.taskId, rateBps);
|
|
287
|
+
if (decision.inHoldout !== false) {
|
|
288
|
+
throw new Wp04OriginError('holdout-episode', `WP04 guard: task ${ep.taskId} evaluates into sealed holdout`);
|
|
289
|
+
}
|
|
290
|
+
taskIds.push(ep.taskId);
|
|
291
|
+
}
|
|
292
|
+
if (scopes.size > 1) {
|
|
293
|
+
throw new Wp04OriginError('mixed-owner-scope', 'WP04 guard: candidate cluster must belong to a single ownerScopeKey');
|
|
294
|
+
}
|
|
295
|
+
if (input.db !== undefined && taskIds.length > 0) {
|
|
296
|
+
const dbHoldouts = loadHoldoutTaskIdSet(input.db, taskIds);
|
|
297
|
+
for (const taskId of taskIds) {
|
|
298
|
+
if (dbHoldouts.has(taskId)) {
|
|
299
|
+
throw new Wp04OriginError('holdout-episode', `WP04 guard: task ${taskId} is marked in_holdout = 1 in SQLite`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function loadCorrectedTaskIdSet(db, ownerScopeKey) {
|
|
305
|
+
const corrected = new Set();
|
|
306
|
+
if (hasTable(db, 'assoc_exposures')) {
|
|
307
|
+
const rows = db
|
|
308
|
+
.prepare('SELECT DISTINCT task_id FROM assoc_exposures WHERE owner_scope_key = ? AND corrected = 1')
|
|
309
|
+
.all(ownerScopeKey);
|
|
310
|
+
for (const row of rows) {
|
|
311
|
+
corrected.add(row.task_id);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (hasTable(db, 'assoc_replay_episodes')) {
|
|
315
|
+
const rows = db
|
|
316
|
+
.prepare('SELECT task_id, corrected_node_ids_json FROM assoc_replay_episodes WHERE owner_scope_key = ?')
|
|
317
|
+
.all(ownerScopeKey);
|
|
318
|
+
for (const row of rows) {
|
|
319
|
+
try {
|
|
320
|
+
const parsed = JSON.parse(row.corrected_node_ids_json);
|
|
321
|
+
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
322
|
+
corrected.add(row.task_id);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
// Ignore malformed JSON rows
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return corrected;
|
|
331
|
+
}
|
|
332
|
+
export function loadClusteringEpisodesFromDb(db, ownerScopeKey, options) {
|
|
333
|
+
const limit = Math.max(1, Math.min(5_000, Math.trunc(options?.limit ?? 1_000)));
|
|
334
|
+
const holdouts = loadHoldoutTaskIdSet(db);
|
|
335
|
+
const correctedTasks = loadCorrectedTaskIdSet(db, ownerScopeKey);
|
|
336
|
+
const poolInfoByTask = new Map();
|
|
337
|
+
if (hasTable(db, 'assoc_eval_pool')) {
|
|
338
|
+
const poolRows = db
|
|
339
|
+
.prepare(`SELECT task_id, objective_status, entities_json, tool_names_json
|
|
340
|
+
FROM assoc_eval_pool
|
|
341
|
+
WHERE owner_scope_key = ? AND status = 'active'`)
|
|
342
|
+
.all(ownerScopeKey);
|
|
343
|
+
for (const row of poolRows) {
|
|
344
|
+
let entities = [];
|
|
345
|
+
let toolNames = [];
|
|
346
|
+
try {
|
|
347
|
+
const e = JSON.parse(row.entities_json);
|
|
348
|
+
if (Array.isArray(e)) {
|
|
349
|
+
entities = e.filter((v) => typeof v === 'string');
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
entities = [];
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
const t = JSON.parse(row.tool_names_json);
|
|
357
|
+
if (Array.isArray(t)) {
|
|
358
|
+
toolNames = t.filter((v) => typeof v === 'string');
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
toolNames = [];
|
|
363
|
+
}
|
|
364
|
+
poolInfoByTask.set(row.task_id, {
|
|
365
|
+
objectiveStatus: row.objective_status,
|
|
366
|
+
entities,
|
|
367
|
+
toolNames,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (!hasTable(db, 'assoc_nodes')) {
|
|
372
|
+
return [];
|
|
373
|
+
}
|
|
374
|
+
const rows = db
|
|
375
|
+
.prepare(`SELECT id, source_ref, owner_scope_key, title, entities_json, metadata_json, created_at, updated_at
|
|
376
|
+
FROM assoc_nodes
|
|
377
|
+
WHERE owner_scope_key = ? AND kind = 'episode' AND status = 'active'
|
|
378
|
+
ORDER BY created_at ASC, id ASC
|
|
379
|
+
LIMIT ?`)
|
|
380
|
+
.all(ownerScopeKey, limit);
|
|
381
|
+
const out = [];
|
|
382
|
+
for (const row of rows) {
|
|
383
|
+
let entities = [];
|
|
384
|
+
let metadata = {};
|
|
385
|
+
try {
|
|
386
|
+
const parsedEntities = JSON.parse(row.entities_json);
|
|
387
|
+
if (Array.isArray(parsedEntities)) {
|
|
388
|
+
entities = parsedEntities.filter((v) => typeof v === 'string');
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
entities = [];
|
|
393
|
+
}
|
|
394
|
+
try {
|
|
395
|
+
const parsedMeta = JSON.parse(row.metadata_json);
|
|
396
|
+
if (parsedMeta !== null && typeof parsedMeta === 'object' && !Array.isArray(parsedMeta)) {
|
|
397
|
+
metadata = parsedMeta;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
metadata = {};
|
|
402
|
+
}
|
|
403
|
+
const extraTaskId = metadata.extra?.taskId;
|
|
404
|
+
const taskId = typeof extraTaskId === 'string' && extraTaskId.length > 0
|
|
405
|
+
? extraTaskId
|
|
406
|
+
: row.source_ref;
|
|
407
|
+
const poolInfo = poolInfoByTask.get(taskId);
|
|
408
|
+
const rawTools = Array.isArray(metadata.toolNames)
|
|
409
|
+
? metadata.toolNames.filter((v) => typeof v === 'string')
|
|
410
|
+
: [];
|
|
411
|
+
const toolNames = rawTools.length > 0 ? rawTools : (poolInfo?.toolNames ?? []);
|
|
412
|
+
const mergedEntities = entities.length > 0 ? entities : (poolInfo?.entities ?? []);
|
|
413
|
+
const objectiveStatus = typeof metadata.objectiveStatus === 'string' && metadata.objectiveStatus.length > 0
|
|
414
|
+
? metadata.objectiveStatus
|
|
415
|
+
: (poolInfo?.objectiveStatus ?? undefined);
|
|
416
|
+
const isCorrected = metadata.conflicted === true || correctedTasks.has(taskId);
|
|
417
|
+
const isInHoldout = holdouts.has(taskId);
|
|
418
|
+
out.push({
|
|
419
|
+
id: row.id,
|
|
420
|
+
taskId,
|
|
421
|
+
ownerScopeKey: row.owner_scope_key,
|
|
422
|
+
entities: mergedEntities,
|
|
423
|
+
toolNames,
|
|
424
|
+
createdAt: row.created_at,
|
|
425
|
+
updatedAt: row.updated_at,
|
|
426
|
+
title: row.title,
|
|
427
|
+
...(objectiveStatus === undefined ? {} : { objectiveStatus }),
|
|
428
|
+
corrected: isCorrected,
|
|
429
|
+
inHoldout: isInHoldout,
|
|
430
|
+
metadata,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
return out;
|
|
434
|
+
}
|
|
435
|
+
function filterNonHoldoutEpisodes(db, ownerScopeKey, episodes, holdoutSeedKey, holdoutRateBps) {
|
|
436
|
+
if (holdoutSeedKey === null ||
|
|
437
|
+
!Buffer.isBuffer(holdoutSeedKey) ||
|
|
438
|
+
holdoutSeedKey.length === 0) {
|
|
439
|
+
throw new Wp04OriginError('missing-holdout-seed', 'WP04 guard: holdoutSeedKey is required before clustering or implicit signal detection');
|
|
440
|
+
}
|
|
441
|
+
const taskIds = episodes.map((e) => e.taskId);
|
|
442
|
+
const dbHoldouts = loadHoldoutTaskIdSet(db, taskIds);
|
|
443
|
+
const eligible = [];
|
|
444
|
+
let excludedHoldoutCount = 0;
|
|
445
|
+
for (const ep of episodes) {
|
|
446
|
+
if (ep.ownerScopeKey !== ownerScopeKey)
|
|
447
|
+
continue;
|
|
448
|
+
if (ep.inHoldout === true || dbHoldouts.has(ep.taskId)) {
|
|
449
|
+
excludedHoldoutCount += 1;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const decision = evaluateHoldout(holdoutSeedKey, ep.taskId, holdoutRateBps);
|
|
453
|
+
if (decision.inHoldout !== false) {
|
|
454
|
+
excludedHoldoutCount += 1;
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
eligible.push(ep);
|
|
458
|
+
}
|
|
459
|
+
eligible.sort((a, b) => {
|
|
460
|
+
if (a.createdAt !== b.createdAt)
|
|
461
|
+
return a.createdAt - b.createdAt;
|
|
462
|
+
return a.id.localeCompare(b.id);
|
|
463
|
+
});
|
|
464
|
+
return { eligible, excludedHoldoutCount };
|
|
465
|
+
}
|
|
466
|
+
function computeSharedEntities(episodes) {
|
|
467
|
+
const counts = new Map();
|
|
468
|
+
for (const ep of episodes) {
|
|
469
|
+
for (const ent of new Set(normalizeEntities(ep.entities))) {
|
|
470
|
+
counts.set(ent, (counts.get(ent) ?? 0) + 1);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const threshold = Math.min(episodes.length, Math.max(2, Math.ceil(episodes.length / 2)));
|
|
474
|
+
const shared = [...counts.entries()]
|
|
475
|
+
.filter(([, count]) => count >= threshold)
|
|
476
|
+
.sort((a, b) => (b[1] !== a[1] ? b[1] - a[1] : a[0].localeCompare(b[0])))
|
|
477
|
+
.map(([ent]) => ent);
|
|
478
|
+
if (shared.length > 0)
|
|
479
|
+
return shared;
|
|
480
|
+
return [...counts.entries()]
|
|
481
|
+
.sort((a, b) => (b[1] !== a[1] ? b[1] - a[1] : a[0].localeCompare(b[0])))
|
|
482
|
+
.slice(0, 8)
|
|
483
|
+
.map(([ent]) => ent);
|
|
484
|
+
}
|
|
485
|
+
function computeClusterToolSequence(episodes) {
|
|
486
|
+
if (episodes.length === 0)
|
|
487
|
+
return [];
|
|
488
|
+
const first = episodes[0];
|
|
489
|
+
let common = normalizeTools(first.toolNames);
|
|
490
|
+
for (let i = 1; i < episodes.length; i += 1) {
|
|
491
|
+
common = computeToolSequenceLcs(common, episodes[i].toolNames);
|
|
492
|
+
if (common.length === 0)
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
if (common.length > 0)
|
|
496
|
+
return common;
|
|
497
|
+
return normalizeTools(first.toolNames);
|
|
498
|
+
}
|
|
499
|
+
function extractGoalLocators(episodes) {
|
|
500
|
+
const seen = new Set();
|
|
501
|
+
const out = [];
|
|
502
|
+
for (const ep of episodes) {
|
|
503
|
+
const extra = ep.metadata?.extra;
|
|
504
|
+
if (extra === undefined)
|
|
505
|
+
continue;
|
|
506
|
+
const goalId = extra.goalId;
|
|
507
|
+
const sessionId = extra.sessionId;
|
|
508
|
+
if (typeof goalId === 'string' &&
|
|
509
|
+
goalId.trim().length > 0 &&
|
|
510
|
+
typeof sessionId === 'string' &&
|
|
511
|
+
sessionId.trim().length > 0) {
|
|
512
|
+
const key = `${goalId}\0${sessionId}`;
|
|
513
|
+
if (seen.has(key))
|
|
514
|
+
continue;
|
|
515
|
+
seen.add(key);
|
|
516
|
+
out.push(Object.freeze({ goalId, sessionId }));
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
out.sort((a, b) => a.goalId !== b.goalId
|
|
520
|
+
? a.goalId.localeCompare(b.goalId)
|
|
521
|
+
: a.sessionId.localeCompare(b.sessionId));
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
function computeAveragePairwiseSimilarity(episodes, similarityFn) {
|
|
525
|
+
if (episodes.length <= 1)
|
|
526
|
+
return 1;
|
|
527
|
+
let sum = 0;
|
|
528
|
+
let count = 0;
|
|
529
|
+
for (let i = 0; i < episodes.length; i += 1) {
|
|
530
|
+
for (let j = i + 1; j < episodes.length; j += 1) {
|
|
531
|
+
sum += similarityFn(episodes[i], episodes[j]);
|
|
532
|
+
count += 1;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return count === 0 ? 1 : sum / count;
|
|
536
|
+
}
|
|
537
|
+
function deterministicSha256(payload) {
|
|
538
|
+
return growthObjectDigest(payload);
|
|
539
|
+
}
|
|
540
|
+
function truncateCandidateName(raw, maxCodePoints = 96, maxBytes = 128) {
|
|
541
|
+
const safe = raw.toWellFormed().normalize('NFC').trim();
|
|
542
|
+
let out = '';
|
|
543
|
+
let codePoints = 0;
|
|
544
|
+
let bytes = 0;
|
|
545
|
+
for (const ch of safe) {
|
|
546
|
+
const chBytes = Buffer.byteLength(ch, 'utf8');
|
|
547
|
+
if (codePoints + 1 > maxCodePoints || bytes + chBytes > maxBytes)
|
|
548
|
+
break;
|
|
549
|
+
out += ch;
|
|
550
|
+
codePoints += 1;
|
|
551
|
+
bytes += chBytes;
|
|
552
|
+
}
|
|
553
|
+
return out.trimEnd();
|
|
554
|
+
}
|
|
555
|
+
function buildCandidateName(sharedEntities, toolSequence, signatureDigest) {
|
|
556
|
+
const entityLabel = sharedEntities.slice(0, 2).join('-');
|
|
557
|
+
const toolLabel = toolSequence.slice(0, 2).join('-');
|
|
558
|
+
const base = entityLabel.length > 0
|
|
559
|
+
? `${entityLabel}${toolLabel.length > 0 ? `:${toolLabel}` : ''}`
|
|
560
|
+
: toolLabel.length > 0
|
|
561
|
+
? toolLabel
|
|
562
|
+
: `cluster-${signatureDigest.slice(0, 8)}`;
|
|
563
|
+
return truncateCandidateName(`skill-${base}`, 96, 128);
|
|
564
|
+
}
|
|
565
|
+
function buildCandidateDescription(episodes, sharedEntities, toolSequence) {
|
|
566
|
+
const entitiesSummary = sharedEntities.length > 0 ? sharedEntities.slice(0, 5).join(', ') : 'none';
|
|
567
|
+
const toolsSummary = toolSequence.join(' -> ');
|
|
568
|
+
return `Derived from ${episodes.length} verified non-holdout episodes (entities: ${entitiesSummary}; tools: ${toolsSummary}).`;
|
|
569
|
+
}
|
|
570
|
+
export async function clusterEpisodes(db, options) {
|
|
571
|
+
const cfg = normalizeClusteringConfig(options.config);
|
|
572
|
+
const holdoutRateBps = options.holdoutRateBps ?? DEFAULT_HOLDOUT_RATE_BPS;
|
|
573
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
574
|
+
const persist = options.persist ?? true;
|
|
575
|
+
// Validate seed and optional benchmarkPlan before touching or reading candidate inputs.
|
|
576
|
+
await assertWp04CandidateOrigin({
|
|
577
|
+
db,
|
|
578
|
+
holdoutSeedKey: options.holdoutSeedKey,
|
|
579
|
+
holdoutRateBps,
|
|
580
|
+
episodes: [],
|
|
581
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
582
|
+
...(options.benchmarkPlan === undefined ? {} : { benchmarkPlan: options.benchmarkPlan }),
|
|
583
|
+
});
|
|
584
|
+
if (persist) {
|
|
585
|
+
ensureClusteringSchema(db);
|
|
586
|
+
}
|
|
587
|
+
const rawEpisodes = options.episodes ?? loadClusteringEpisodesFromDb(db, options.ownerScopeKey);
|
|
588
|
+
const { eligible, excludedHoldoutCount } = filterNonHoldoutEpisodes(db, options.ownerScopeKey, rawEpisodes, options.holdoutSeedKey, holdoutRateBps);
|
|
589
|
+
// Skill candidate clustering requires non-empty tool sequence (T.length >= 1).
|
|
590
|
+
const toolEpisodes = eligible.filter((ep) => normalizeTools(ep.toolNames).length >= 1);
|
|
591
|
+
const assigned = new Set();
|
|
592
|
+
const clusters = [];
|
|
593
|
+
const candidates = [];
|
|
594
|
+
const similarityFn = (a, b) => computeEpisodeSimilarity(a, b, {
|
|
595
|
+
entityWeight: cfg.entityWeight,
|
|
596
|
+
toolWeight: cfg.toolWeight,
|
|
597
|
+
});
|
|
598
|
+
for (let i = 0; i < toolEpisodes.length; i += 1) {
|
|
599
|
+
const seed = toolEpisodes[i];
|
|
600
|
+
if (assigned.has(seed.id))
|
|
601
|
+
continue;
|
|
602
|
+
const members = [seed];
|
|
603
|
+
for (let j = i + 1; j < toolEpisodes.length; j += 1) {
|
|
604
|
+
const cand = toolEpisodes[j];
|
|
605
|
+
if (assigned.has(cand.id))
|
|
606
|
+
continue;
|
|
607
|
+
if (similarityFn(seed, cand) >= cfg.minSimilarity) {
|
|
608
|
+
members.push(cand);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (members.length < cfg.minClusterSize)
|
|
612
|
+
continue;
|
|
613
|
+
for (const m of members) {
|
|
614
|
+
assigned.add(m.id);
|
|
615
|
+
}
|
|
616
|
+
await assertWp04CandidateOrigin({
|
|
617
|
+
db,
|
|
618
|
+
holdoutSeedKey: options.holdoutSeedKey,
|
|
619
|
+
holdoutRateBps,
|
|
620
|
+
episodes: members,
|
|
621
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
622
|
+
...(options.benchmarkPlan === undefined ? {} : { benchmarkPlan: options.benchmarkPlan }),
|
|
623
|
+
});
|
|
624
|
+
const sortedTaskIds = members.map((m) => m.taskId).sort();
|
|
625
|
+
const sharedEntities = computeSharedEntities(members);
|
|
626
|
+
const toolSequence = computeClusterToolSequence(members);
|
|
627
|
+
const goalLocators = extractGoalLocators(members);
|
|
628
|
+
const similarity = computeAveragePairwiseSimilarity(members, similarityFn);
|
|
629
|
+
const signatureDigest = deterministicSha256({
|
|
630
|
+
protocol: 'assistant-association/cluster-signature/v1',
|
|
631
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
632
|
+
toolSequence,
|
|
633
|
+
sharedEntities,
|
|
634
|
+
});
|
|
635
|
+
const clusterId = deterministicSha256({
|
|
636
|
+
protocol: 'assistant-association/cluster/v1',
|
|
637
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
638
|
+
memberTaskIds: sortedTaskIds,
|
|
639
|
+
});
|
|
640
|
+
const candidateId = deterministicSha256({
|
|
641
|
+
protocol: 'assistant-association/skill-candidate/v1',
|
|
642
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
643
|
+
clusterId,
|
|
644
|
+
signatureDigest,
|
|
645
|
+
});
|
|
646
|
+
const cluster = Object.freeze({
|
|
647
|
+
clusterId,
|
|
648
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
649
|
+
signatureDigest,
|
|
650
|
+
toolSequence: Object.freeze(toolSequence),
|
|
651
|
+
sharedEntities: Object.freeze(sharedEntities),
|
|
652
|
+
memberTaskIds: Object.freeze(sortedTaskIds),
|
|
653
|
+
goalLocators: Object.freeze(goalLocators),
|
|
654
|
+
similarity,
|
|
655
|
+
episodes: Object.freeze(members),
|
|
656
|
+
});
|
|
657
|
+
clusters.push(cluster);
|
|
658
|
+
const candidate = Object.freeze({
|
|
659
|
+
candidateId,
|
|
660
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
661
|
+
clusterId,
|
|
662
|
+
signatureDigest,
|
|
663
|
+
name: buildCandidateName(sharedEntities, toolSequence, signatureDigest),
|
|
664
|
+
description: buildCandidateDescription(members, sharedEntities, toolSequence),
|
|
665
|
+
toolSequence: cluster.toolSequence,
|
|
666
|
+
sharedEntities: cluster.sharedEntities,
|
|
667
|
+
memberTaskIds: cluster.memberTaskIds,
|
|
668
|
+
goalLocators: cluster.goalLocators,
|
|
669
|
+
similarity,
|
|
670
|
+
wp04Verified: true,
|
|
671
|
+
status: 'pending',
|
|
672
|
+
createdAt: nowMs,
|
|
673
|
+
updatedAt: nowMs,
|
|
674
|
+
});
|
|
675
|
+
if (persist) {
|
|
676
|
+
db.prepare(`
|
|
677
|
+
INSERT INTO assoc_skill_candidates (
|
|
678
|
+
candidate_id, owner_scope_key, cluster_id, signature_digest,
|
|
679
|
+
name, description, tool_sequence_json, shared_entities_json,
|
|
680
|
+
member_task_ids_json, goal_locators_json, similarity,
|
|
681
|
+
wp04_verified, status, created_at, updated_at
|
|
682
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'pending', ?, ?)
|
|
683
|
+
ON CONFLICT(candidate_id) DO UPDATE SET
|
|
684
|
+
name = excluded.name,
|
|
685
|
+
description = excluded.description,
|
|
686
|
+
tool_sequence_json = excluded.tool_sequence_json,
|
|
687
|
+
shared_entities_json = excluded.shared_entities_json,
|
|
688
|
+
member_task_ids_json = excluded.member_task_ids_json,
|
|
689
|
+
goal_locators_json = excluded.goal_locators_json,
|
|
690
|
+
similarity = excluded.similarity,
|
|
691
|
+
wp04_verified = 1,
|
|
692
|
+
updated_at = excluded.updated_at
|
|
693
|
+
`).run(candidate.candidateId, candidate.ownerScopeKey, candidate.clusterId, candidate.signatureDigest, candidate.name, candidate.description, JSON.stringify(candidate.toolSequence), JSON.stringify(candidate.sharedEntities), JSON.stringify(candidate.memberTaskIds), JSON.stringify(candidate.goalLocators), candidate.similarity, candidate.createdAt, candidate.updatedAt);
|
|
694
|
+
const storedRow = db
|
|
695
|
+
.prepare('SELECT status, created_at FROM assoc_skill_candidates WHERE candidate_id = ?')
|
|
696
|
+
.get(candidate.candidateId);
|
|
697
|
+
if (storedRow !== undefined && (storedRow.status !== candidate.status || storedRow.created_at !== candidate.createdAt)) {
|
|
698
|
+
candidates.push(Object.freeze({
|
|
699
|
+
...candidate,
|
|
700
|
+
status: storedRow.status,
|
|
701
|
+
createdAt: storedRow.created_at,
|
|
702
|
+
}));
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
candidates.push(candidate);
|
|
707
|
+
}
|
|
708
|
+
return Object.freeze({
|
|
709
|
+
clusters: Object.freeze(clusters),
|
|
710
|
+
candidates: Object.freeze(candidates),
|
|
711
|
+
excludedHoldoutCount,
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
function hasReAskPattern(members, cfg) {
|
|
715
|
+
if (members.length < 2)
|
|
716
|
+
return { matched: false, maxEntityJaccard: 0 };
|
|
717
|
+
let maxJaccard = 0;
|
|
718
|
+
let shortWindowMatch = false;
|
|
719
|
+
let highOverlapMatch = false;
|
|
720
|
+
const normalizedTitles = new Map();
|
|
721
|
+
for (let i = 0; i < members.length; i += 1) {
|
|
722
|
+
const a = members[i];
|
|
723
|
+
const normTitle = (a.title ?? '').normalize('NFKC').toLocaleLowerCase('en-US').replace(/\s+/gu, ' ').trim();
|
|
724
|
+
if (normTitle.length > 0) {
|
|
725
|
+
const count = (normalizedTitles.get(normTitle) ?? 0) + 1;
|
|
726
|
+
normalizedTitles.set(normTitle, count);
|
|
727
|
+
if (count >= 2)
|
|
728
|
+
highOverlapMatch = true;
|
|
729
|
+
}
|
|
730
|
+
for (let j = i + 1; j < members.length; j += 1) {
|
|
731
|
+
const b = members[j];
|
|
732
|
+
const jacc = computeEntityJaccard(a.entities, b.entities);
|
|
733
|
+
if (jacc > maxJaccard)
|
|
734
|
+
maxJaccard = jacc;
|
|
735
|
+
const deltaMs = Math.abs(b.createdAt - a.createdAt);
|
|
736
|
+
if (deltaMs <= cfg.reAskWindowMs && jacc >= cfg.reAskMinEntityJaccard) {
|
|
737
|
+
shortWindowMatch = true;
|
|
738
|
+
}
|
|
739
|
+
if (jacc >= 0.75) {
|
|
740
|
+
highOverlapMatch = true;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return {
|
|
745
|
+
matched: shortWindowMatch || highOverlapMatch,
|
|
746
|
+
maxEntityJaccard: maxJaccard,
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
export function detectImplicitSignals(db, options) {
|
|
750
|
+
const cfg = normalizeClusteringConfig(options.config);
|
|
751
|
+
const holdoutRateBps = options.holdoutRateBps ?? DEFAULT_HOLDOUT_RATE_BPS;
|
|
752
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
753
|
+
const persist = options.persist ?? true;
|
|
754
|
+
if (persist) {
|
|
755
|
+
ensureClusteringSchema(db);
|
|
756
|
+
}
|
|
757
|
+
const rawEpisodes = options.episodes ?? loadClusteringEpisodesFromDb(db, options.ownerScopeKey);
|
|
758
|
+
const { eligible, excludedHoldoutCount } = filterNonHoldoutEpisodes(db, options.ownerScopeKey, rawEpisodes, options.holdoutSeedKey, holdoutRateBps);
|
|
759
|
+
const dbCorrectedTasks = loadCorrectedTaskIdSet(db, options.ownerScopeKey);
|
|
760
|
+
const signalSimilarity = (a, b) => {
|
|
761
|
+
const hasToolsA = normalizeTools(a.toolNames).length >= 1;
|
|
762
|
+
const hasToolsB = normalizeTools(b.toolNames).length >= 1;
|
|
763
|
+
if (hasToolsA && hasToolsB) {
|
|
764
|
+
return computeEpisodeSimilarity(a, b, {
|
|
765
|
+
entityWeight: cfg.entityWeight,
|
|
766
|
+
toolWeight: cfg.toolWeight,
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
return computeEntityJaccard(a.entities, b.entities);
|
|
770
|
+
};
|
|
771
|
+
const assigned = new Set();
|
|
772
|
+
const signalClusters = [];
|
|
773
|
+
for (let i = 0; i < eligible.length; i += 1) {
|
|
774
|
+
const seed = eligible[i];
|
|
775
|
+
if (assigned.has(seed.id))
|
|
776
|
+
continue;
|
|
777
|
+
const members = [seed];
|
|
778
|
+
for (let j = i + 1; j < eligible.length; j += 1) {
|
|
779
|
+
const cand = eligible[j];
|
|
780
|
+
if (assigned.has(cand.id))
|
|
781
|
+
continue;
|
|
782
|
+
if (signalSimilarity(seed, cand) >= cfg.minSimilarity) {
|
|
783
|
+
members.push(cand);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
const hasCorrection = members.some((m) => m.corrected === true ||
|
|
787
|
+
m.metadata?.conflicted === true ||
|
|
788
|
+
dbCorrectedTasks.has(m.taskId));
|
|
789
|
+
if (members.length >= 2 || hasCorrection) {
|
|
790
|
+
for (const m of members) {
|
|
791
|
+
assigned.add(m.id);
|
|
792
|
+
}
|
|
793
|
+
signalClusters.push(members);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
const signals = [];
|
|
797
|
+
const dbHoldouts = loadHoldoutTaskIdSet(db, eligible.map((e) => e.taskId));
|
|
798
|
+
for (const members of signalClusters) {
|
|
799
|
+
// Defense-in-depth: re-verify zero holdout episodes in each cluster
|
|
800
|
+
const safeMembers = members.filter((m) => m.inHoldout !== true &&
|
|
801
|
+
!dbHoldouts.has(m.taskId) &&
|
|
802
|
+
evaluateHoldout(options.holdoutSeedKey, m.taskId, holdoutRateBps).inHoldout === false);
|
|
803
|
+
if (safeMembers.length === 0)
|
|
804
|
+
continue;
|
|
805
|
+
const sortedTaskIds = safeMembers.map((m) => m.taskId).sort();
|
|
806
|
+
const clusterId = deterministicSha256({
|
|
807
|
+
protocol: 'assistant-association/cluster/v1',
|
|
808
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
809
|
+
memberTaskIds: sortedTaskIds,
|
|
810
|
+
});
|
|
811
|
+
const emitSignal = (kind, evidence) => {
|
|
812
|
+
const signalId = deterministicSha256({
|
|
813
|
+
protocol: 'assistant-association/implicit-signal/v1',
|
|
814
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
815
|
+
clusterId,
|
|
816
|
+
kind,
|
|
817
|
+
});
|
|
818
|
+
const signal = Object.freeze({
|
|
819
|
+
signalId,
|
|
820
|
+
ownerScopeKey: options.ownerScopeKey,
|
|
821
|
+
clusterId,
|
|
822
|
+
kind,
|
|
823
|
+
trust: 'low',
|
|
824
|
+
candidateOnly: true,
|
|
825
|
+
reportOnly: true,
|
|
826
|
+
evidence: Object.freeze({ ...evidence }),
|
|
827
|
+
createdAt: nowMs,
|
|
828
|
+
});
|
|
829
|
+
if (persist) {
|
|
830
|
+
db.prepare(`
|
|
831
|
+
INSERT INTO assoc_implicit_signals (
|
|
832
|
+
signal_id, owner_scope_key, cluster_id, kind,
|
|
833
|
+
trust, candidate_only, report_only, evidence_json, created_at
|
|
834
|
+
) VALUES (?, ?, ?, ?, 'low', 1, 1, ?, ?)
|
|
835
|
+
ON CONFLICT(signal_id) DO UPDATE SET
|
|
836
|
+
evidence_json = excluded.evidence_json,
|
|
837
|
+
created_at = excluded.created_at
|
|
838
|
+
`).run(signal.signalId, signal.ownerScopeKey, signal.clusterId, signal.kind, JSON.stringify(signal.evidence), signal.createdAt);
|
|
839
|
+
}
|
|
840
|
+
signals.push(signal);
|
|
841
|
+
};
|
|
842
|
+
// 1. 're-ask'
|
|
843
|
+
const reAsk = hasReAskPattern(safeMembers, cfg);
|
|
844
|
+
if (reAsk.matched) {
|
|
845
|
+
emitSignal('re-ask', {
|
|
846
|
+
taskIds: sortedTaskIds,
|
|
847
|
+
clusterSize: safeMembers.length,
|
|
848
|
+
windowMs: cfg.reAskWindowMs,
|
|
849
|
+
maxEntityJaccard: reAsk.maxEntityJaccard,
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
// 2. 'redo'
|
|
853
|
+
const failedIndices = [];
|
|
854
|
+
const failedTaskIds = [];
|
|
855
|
+
const objectiveStatuses = [];
|
|
856
|
+
for (let idx = 0; idx < safeMembers.length; idx += 1) {
|
|
857
|
+
const ep = safeMembers[idx];
|
|
858
|
+
const st = ep.objectiveStatus?.trim().toLowerCase();
|
|
859
|
+
if (st !== undefined && UNACHIEVED_OBJECTIVE_STATUSES.has(st)) {
|
|
860
|
+
failedIndices.push(idx);
|
|
861
|
+
failedTaskIds.push(ep.taskId);
|
|
862
|
+
objectiveStatuses.push(st);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (failedIndices.length > 0) {
|
|
866
|
+
const firstFailedIdx = failedIndices[0];
|
|
867
|
+
const followUpTaskIds = safeMembers
|
|
868
|
+
.slice(firstFailedIdx + 1)
|
|
869
|
+
.map((m) => m.taskId);
|
|
870
|
+
if (followUpTaskIds.length > 0) {
|
|
871
|
+
emitSignal('redo', {
|
|
872
|
+
taskIds: sortedTaskIds,
|
|
873
|
+
failedTaskIds,
|
|
874
|
+
followUpTaskIds,
|
|
875
|
+
objectiveStatuses,
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
// 3. 'owner-correction'
|
|
880
|
+
const correctedTaskIds = safeMembers
|
|
881
|
+
.filter((m) => m.corrected === true ||
|
|
882
|
+
m.metadata?.conflicted === true ||
|
|
883
|
+
dbCorrectedTasks.has(m.taskId))
|
|
884
|
+
.map((m) => m.taskId)
|
|
885
|
+
.sort();
|
|
886
|
+
if (correctedTaskIds.length > 0) {
|
|
887
|
+
emitSignal('owner-correction', {
|
|
888
|
+
taskIds: sortedTaskIds,
|
|
889
|
+
correctedTaskIds,
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
return Object.freeze({
|
|
894
|
+
signals: Object.freeze(signals),
|
|
895
|
+
excludedHoldoutCount,
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
function mapRawCandidate(row) {
|
|
899
|
+
return Object.freeze({
|
|
900
|
+
candidateId: row.candidate_id,
|
|
901
|
+
ownerScopeKey: row.owner_scope_key,
|
|
902
|
+
clusterId: row.cluster_id,
|
|
903
|
+
signatureDigest: row.signature_digest,
|
|
904
|
+
name: row.name,
|
|
905
|
+
description: row.description,
|
|
906
|
+
toolSequence: Object.freeze(JSON.parse(row.tool_sequence_json)),
|
|
907
|
+
sharedEntities: Object.freeze(JSON.parse(row.shared_entities_json)),
|
|
908
|
+
memberTaskIds: Object.freeze(JSON.parse(row.member_task_ids_json)),
|
|
909
|
+
goalLocators: Object.freeze(JSON.parse(row.goal_locators_json)),
|
|
910
|
+
similarity: row.similarity,
|
|
911
|
+
wp04Verified: row.wp04_verified === 1,
|
|
912
|
+
status: row.status,
|
|
913
|
+
createdAt: row.created_at,
|
|
914
|
+
updatedAt: row.updated_at,
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
export function listSkillCandidates(db, ownerScopeKey, options) {
|
|
918
|
+
if (!hasTable(db, 'assoc_skill_candidates'))
|
|
919
|
+
return [];
|
|
920
|
+
const limit = Math.max(1, Math.min(1_000, Math.trunc(options?.limit ?? 100)));
|
|
921
|
+
if (options?.status !== undefined) {
|
|
922
|
+
const rows = db
|
|
923
|
+
.prepare(`SELECT * FROM assoc_skill_candidates
|
|
924
|
+
WHERE owner_scope_key = ? AND status = ?
|
|
925
|
+
ORDER BY updated_at DESC, candidate_id ASC
|
|
926
|
+
LIMIT ?`)
|
|
927
|
+
.all(ownerScopeKey, options.status, limit);
|
|
928
|
+
return rows.map(mapRawCandidate);
|
|
929
|
+
}
|
|
930
|
+
const rows = db
|
|
931
|
+
.prepare(`SELECT * FROM assoc_skill_candidates
|
|
932
|
+
WHERE owner_scope_key = ?
|
|
933
|
+
ORDER BY updated_at DESC, candidate_id ASC
|
|
934
|
+
LIMIT ?`)
|
|
935
|
+
.all(ownerScopeKey, limit);
|
|
936
|
+
return rows.map(mapRawCandidate);
|
|
937
|
+
}
|
|
938
|
+
export function updateSkillCandidateStatus(db, ownerScopeKey, candidateId, status, updatedAt = Date.now()) {
|
|
939
|
+
if (!hasTable(db, 'assoc_skill_candidates'))
|
|
940
|
+
return false;
|
|
941
|
+
const res = db
|
|
942
|
+
.prepare(`UPDATE assoc_skill_candidates
|
|
943
|
+
SET status = ?, updated_at = ?
|
|
944
|
+
WHERE owner_scope_key = ? AND candidate_id = ?`)
|
|
945
|
+
.run(status, updatedAt, ownerScopeKey, candidateId);
|
|
946
|
+
return res.changes > 0;
|
|
947
|
+
}
|
|
948
|
+
function mapRawImplicitSignal(row) {
|
|
949
|
+
return Object.freeze({
|
|
950
|
+
signalId: row.signal_id,
|
|
951
|
+
ownerScopeKey: row.owner_scope_key,
|
|
952
|
+
clusterId: row.cluster_id,
|
|
953
|
+
kind: row.kind,
|
|
954
|
+
trust: 'low',
|
|
955
|
+
candidateOnly: true,
|
|
956
|
+
reportOnly: true,
|
|
957
|
+
evidence: Object.freeze(JSON.parse(row.evidence_json)),
|
|
958
|
+
createdAt: row.created_at,
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
export function listImplicitSignals(db, ownerScopeKey, options) {
|
|
962
|
+
if (!hasTable(db, 'assoc_implicit_signals'))
|
|
963
|
+
return [];
|
|
964
|
+
const limit = Math.max(1, Math.min(1_000, Math.trunc(options?.limit ?? 100)));
|
|
965
|
+
const clauses = ['owner_scope_key = ?'];
|
|
966
|
+
const params = [ownerScopeKey];
|
|
967
|
+
if (options?.kind !== undefined) {
|
|
968
|
+
clauses.push('kind = ?');
|
|
969
|
+
params.push(options.kind);
|
|
970
|
+
}
|
|
971
|
+
if (options?.clusterId !== undefined) {
|
|
972
|
+
clauses.push('cluster_id = ?');
|
|
973
|
+
params.push(options.clusterId);
|
|
974
|
+
}
|
|
975
|
+
params.push(limit);
|
|
976
|
+
const rows = db
|
|
977
|
+
.prepare(`SELECT * FROM assoc_implicit_signals
|
|
978
|
+
WHERE ${clauses.join(' AND ')}
|
|
979
|
+
ORDER BY created_at DESC, signal_id ASC
|
|
980
|
+
LIMIT ?`)
|
|
981
|
+
.all(...params);
|
|
982
|
+
return rows.map(mapRawImplicitSignal);
|
|
983
|
+
}
|
|
984
|
+
export function reportImplicitSignalsToEvaluation(evaluationPeer, signals, scope) {
|
|
985
|
+
if (evaluationPeer === undefined || typeof evaluationPeer.append !== 'function') {
|
|
986
|
+
return Object.freeze({ reported: 0, skipped: signals.length });
|
|
987
|
+
}
|
|
988
|
+
let reported = 0;
|
|
989
|
+
let skipped = 0;
|
|
990
|
+
for (const signal of signals) {
|
|
991
|
+
if (signal.trust !== 'low' || !signal.candidateOnly || !signal.reportOnly) {
|
|
992
|
+
throw new Error('assistant-association: implicit signals must remain low-trust, candidateOnly, reportOnly');
|
|
993
|
+
}
|
|
994
|
+
const digest = createHash('sha256')
|
|
995
|
+
.update(JSON.stringify(signal.evidence), 'utf8')
|
|
996
|
+
.digest('hex');
|
|
997
|
+
const envelope = {
|
|
998
|
+
scope: {
|
|
999
|
+
workspace: scope.workspace,
|
|
1000
|
+
preset: scope.preset,
|
|
1001
|
+
},
|
|
1002
|
+
situation: `association:implicit-signal:${signal.kind}`,
|
|
1003
|
+
executionStatus: 'unknown',
|
|
1004
|
+
objectiveStatus: signal.kind === 'redo' || signal.kind === 'owner-correction'
|
|
1005
|
+
? 'not-achieved'
|
|
1006
|
+
: 'partial',
|
|
1007
|
+
deliveryStatus: 'not-required',
|
|
1008
|
+
source: {
|
|
1009
|
+
kind: 'system',
|
|
1010
|
+
id: 'assistant-association',
|
|
1011
|
+
},
|
|
1012
|
+
// Strictly 'self-reported' (never 'trusted')
|
|
1013
|
+
trust: 'self-reported',
|
|
1014
|
+
evidence: [
|
|
1015
|
+
{
|
|
1016
|
+
kind: 'association-cluster',
|
|
1017
|
+
ref: signal.clusterId,
|
|
1018
|
+
digest,
|
|
1019
|
+
},
|
|
1020
|
+
{
|
|
1021
|
+
kind: 'implicit-signal',
|
|
1022
|
+
ref: signal.signalId,
|
|
1023
|
+
},
|
|
1024
|
+
],
|
|
1025
|
+
metrics: {},
|
|
1026
|
+
occurredAt: signal.createdAt,
|
|
1027
|
+
idempotencyKey: `assistant-association:implicit-signal:${signal.signalId}`,
|
|
1028
|
+
evaluator: {
|
|
1029
|
+
id: 'assistant-association',
|
|
1030
|
+
version: '1',
|
|
1031
|
+
},
|
|
1032
|
+
};
|
|
1033
|
+
try {
|
|
1034
|
+
evaluationPeer.append(envelope);
|
|
1035
|
+
reported += 1;
|
|
1036
|
+
}
|
|
1037
|
+
catch {
|
|
1038
|
+
skipped += 1;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return Object.freeze({ reported, skipped });
|
|
1042
|
+
}
|
|
1043
|
+
//# sourceMappingURL=clustering.js.map
|