@jeffawe/understudy 0.3.0 → 0.4.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/README.md +16 -4
- package/dist/entry/cli.js +75 -1
- package/dist/entry/mcp.d.ts +1 -0
- package/dist/entry/mcp.js +14 -0
- package/dist/memory/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +258 -0
- package/dist/memory/recall.d.ts +32 -24
- package/dist/memory/recall.js +49 -16
- package/dist/store/reembed.js +18 -7
- package/dist/store/types.d.ts +32 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -124,10 +124,22 @@ ollama pull mxbai-embed-large
|
|
|
124
124
|
understudy config set EMBED_URL=http://localhost:11434/v1/embeddings EMBED_MODEL=mxbai-embed-large EMBED_DIMS=1024
|
|
125
125
|
```
|
|
126
126
|
|
|
127
|
-
Two things to know
|
|
128
|
-
means `understudy reembed
|
|
129
|
-
but not it" was
|
|
130
|
-
|
|
127
|
+
Two things to know. One database holds one model's vectors, so switching later
|
|
128
|
+
means `understudy reembed`. And the line between "a flow I know" and "close,
|
|
129
|
+
but not it" was set for Voyage. Other models score on their own scale: with
|
|
130
|
+
the cutoffs set for Voyage, mxbai-embed-large called 12 of 14 goals an app didn't have
|
|
131
|
+
"known", so the wrong flow would have run. Fit the line to your app and model:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
understudy calibrate myapp --template > goals.json # every flow, to reword
|
|
135
|
+
# fill in 2–3 ways someone would ask for each flow, and 5+ goals that sound
|
|
136
|
+
# like the app but that it has no flow for
|
|
137
|
+
understudy calibrate myapp --goals goals.json
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The goals are kept, so after any later `understudy reembed` the line is re-fit
|
|
141
|
+
for the new model on its own. `recall` says when it's using cutoffs that
|
|
142
|
+
weren't fitted for the model you have.
|
|
131
143
|
|
|
132
144
|
## Use it
|
|
133
145
|
|
package/dist/entry/cli.js
CHANGED
|
@@ -44,7 +44,9 @@ USAGE
|
|
|
44
44
|
COMMANDS
|
|
45
45
|
config where settings come from; set them, or point at an env file
|
|
46
46
|
doctor check the MongoDB connection, vector search and embedder
|
|
47
|
-
reembed rebuild every vector with the model now configured
|
|
47
|
+
reembed rebuild every vector with the model now configured, then
|
|
48
|
+
re-fit each app's recall cutoffs from its kept goals
|
|
49
|
+
calibrate <app> fit when recall calls a goal known, for this app and model
|
|
48
50
|
record <app> capture a flow in your own Chrome, with the extension
|
|
49
51
|
extension where the Chrome extension is, and how to load it
|
|
50
52
|
app <app> an app's settings, e.g. --placeholder email
|
|
@@ -111,6 +113,13 @@ EMIT
|
|
|
111
113
|
--framework <name> playwright-ts (default) or cypress-js
|
|
112
114
|
--out <file> write to a file instead of printing
|
|
113
115
|
|
|
116
|
+
CALIBRATE
|
|
117
|
+
--goals <file> goals to fit on, kept for next time (reembed re-fits from them):
|
|
118
|
+
{"known": {"<flow-slug>": ["how someone would ask", …]},
|
|
119
|
+
"unknown": ["a goal that sounds like the app but isn't in it", …]}
|
|
120
|
+
--template print a goals file to fill in, listing the app's flows
|
|
121
|
+
--dry-run fit and show, keep nothing
|
|
122
|
+
|
|
114
123
|
DISTILL
|
|
115
124
|
--save <file> store the agent's answer (validated first)
|
|
116
125
|
|
|
@@ -228,6 +237,70 @@ async function cmdReembed() {
|
|
|
228
237
|
const { reembed } = await import('../store/reembed.js');
|
|
229
238
|
const r = await reembed();
|
|
230
239
|
console.log(`re-embedded ${r.flows} flows and ${r.notes} notes with ${r.model}`);
|
|
240
|
+
// A new model scores on a new scale: re-fit the cutoffs wherever there are goals to fit on.
|
|
241
|
+
const { recalibrateAll } = await import('../memory/calibrate.js');
|
|
242
|
+
const { refitted, withoutGoals } = await recalibrateAll();
|
|
243
|
+
for (const c of refitted) {
|
|
244
|
+
console.log(`calibrated ${c.app}: ${c.saved ? `${cutoffLine(c.after)} — ${c.after.correct}/${c.total} goals right` : `not saved — ${c.notes.join('; ')}`}`);
|
|
245
|
+
}
|
|
246
|
+
for (const app of withoutGoals)
|
|
247
|
+
console.log(`not calibrated ${app}: no goals kept — run: understudy calibrate ${app} --template`);
|
|
248
|
+
}
|
|
249
|
+
const cutoffLine = (c) => `strong ${c.strong.toFixed(3)}, good ${c.good.toFixed(3)} + margin ${c.margin.toFixed(3)}`;
|
|
250
|
+
/**
|
|
251
|
+
* understudy calibrate <app> [--goals file] [--dry-run] fit recall's cutoffs
|
|
252
|
+
* understudy calibrate <app> --template a goals file to fill in
|
|
253
|
+
*/
|
|
254
|
+
async function cmdCalibrate(positional, flags) {
|
|
255
|
+
const [app] = positional;
|
|
256
|
+
if (!app)
|
|
257
|
+
fail('calibrate needs an app', 'understudy calibrate myapp --goals goals.json');
|
|
258
|
+
const { calibrate } = await import('../memory/calibrate.js');
|
|
259
|
+
if (flags.has('template')) {
|
|
260
|
+
const { flows } = await store.collections();
|
|
261
|
+
const list = await flows.find({ app }, { projection: { slug: 1, title: 1 } }).toArray();
|
|
262
|
+
if (!list.length)
|
|
263
|
+
fail(`no flows for '${app}'`);
|
|
264
|
+
const known = Object.fromEntries(list.map((f) => [f.slug, [`<another way to say: ${f.title}>`]]));
|
|
265
|
+
console.log(JSON.stringify({ known, unknown: ['<a goal that sounds like this app, but that it has no flow for>'] }, null, 2));
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
let goals;
|
|
269
|
+
const file = str(flags.get('goals'));
|
|
270
|
+
if (file) {
|
|
271
|
+
let raw;
|
|
272
|
+
try {
|
|
273
|
+
raw = JSON.parse(await readFile(file, 'utf8'));
|
|
274
|
+
}
|
|
275
|
+
catch (e) {
|
|
276
|
+
fail(`can't read ${file}: ${e.message}`);
|
|
277
|
+
}
|
|
278
|
+
const placeholder = (g) => /^<.*>$/.test(g.trim());
|
|
279
|
+
goals = {
|
|
280
|
+
known: Object.entries(raw.known ?? {}).flatMap(([flow, gs]) => (gs ?? []).filter((g) => !placeholder(g)).map((goal) => ({ flow, goal }))),
|
|
281
|
+
unknown: (raw.unknown ?? []).filter((g) => !placeholder(g)),
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
const c = await calibrate(app, { ...(goals ? { goals } : {}), ...(flags.has('dry-run') ? { dryRun: true } : {}) });
|
|
285
|
+
console.log(`${c.app} with ${c.model}: ${c.flows} flows, ${c.total} goals — ${c.goals.known} known + ${c.goals.fromRuns} from runs, ${c.goals.unknown} unknown + ${c.goals.leftOut} by leaving a flow out\n`);
|
|
286
|
+
console.log(`before ${cutoffLine(c.before)} (${c.before.source}) ${c.before.correct}/${c.total} right`);
|
|
287
|
+
console.log(`fitted ${cutoffLine(c.after)} ${c.after.correct}/${c.total} right`);
|
|
288
|
+
if (c.mistakes.length) {
|
|
289
|
+
console.log('\nstill wrong with the fitted cutoffs');
|
|
290
|
+
for (const m of c.mistakes) {
|
|
291
|
+
console.log(` ${m.verdict === 'known' ? 'called known' : 'missed '} ${m.score.toFixed(3)}${m.next !== undefined ? ` (next ${m.next.toFixed(3)})` : ''} "${m.goal}" → ${m.top ?? '-'}${m.expected ? `, wanted ${m.expected}` : ''}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (c.misranked.length) {
|
|
295
|
+
console.log(`\n${c.model} ranked another flow first for ${c.misranked.length} known goal(s) — no cutoff fixes that:`);
|
|
296
|
+
for (const m of c.misranked)
|
|
297
|
+
console.log(` "${m.goal}" → ${m.top}, wanted ${m.expected}`);
|
|
298
|
+
}
|
|
299
|
+
for (const n of c.notes)
|
|
300
|
+
console.log(`\nnote: ${n}`);
|
|
301
|
+
console.log(c.saved ? '\nsaved — recall uses these cutoffs for this app with this model' : flags.has('dry-run') ? '\ndry run — nothing kept' : '\nnot saved (goals kept) — add more and run again');
|
|
302
|
+
if (!c.saved && !flags.has('dry-run'))
|
|
303
|
+
process.exitCode = 1;
|
|
231
304
|
}
|
|
232
305
|
// --- config ------------------------------------------------------------------
|
|
233
306
|
/**
|
|
@@ -1108,6 +1181,7 @@ async function main() {
|
|
|
1108
1181
|
case 'extension': return cmdExtension();
|
|
1109
1182
|
case 'app': return cmdApp(rest, flags);
|
|
1110
1183
|
case 'reembed': return cmdReembed();
|
|
1184
|
+
case 'calibrate': return cmdCalibrate(rest, flags);
|
|
1111
1185
|
case 'record': return cmdRecord(rest, flags);
|
|
1112
1186
|
case 'import': return cmdImport(rest, flags);
|
|
1113
1187
|
case 'recordings': return cmdRecordings(rest);
|
package/dist/entry/mcp.d.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* understudy_record wait for the user to record a flow in their Chrome
|
|
15
15
|
* understudy_save prove a recording by replaying it, then keep it as a flow (or prove a saved one)
|
|
16
16
|
* understudy_app an app's settings — e.g. keep email fields as placeholders
|
|
17
|
+
* understudy_calibrate fit when recall calls a goal known, for one app and embedding model
|
|
17
18
|
*
|
|
18
19
|
* Long-lived: reconnect (/mcp) after changing the source.
|
|
19
20
|
*/
|
package/dist/entry/mcp.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* understudy_record wait for the user to record a flow in their Chrome
|
|
15
15
|
* understudy_save prove a recording by replaying it, then keep it as a flow (or prove a saved one)
|
|
16
16
|
* understudy_app an app's settings — e.g. keep email fields as placeholders
|
|
17
|
+
* understudy_calibrate fit when recall calls a goal known, for one app and embedding model
|
|
17
18
|
*
|
|
18
19
|
* Long-lived: reconnect (/mcp) after changing the source.
|
|
19
20
|
*/
|
|
@@ -33,6 +34,7 @@ import { editFlow, proveAndSave, proveFlow } from '../flows/save.js';
|
|
|
33
34
|
import { MissingValuesError } from '../flows/execute.js';
|
|
34
35
|
import { parseScript } from '../adapters/recorder/script.js';
|
|
35
36
|
import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
|
|
37
|
+
import { calibrate } from '../memory/calibrate.js';
|
|
36
38
|
import { VERSION } from './version.js';
|
|
37
39
|
/**
|
|
38
40
|
* Sent to the agent when it connects. EVERY session pays for this, used or not,
|
|
@@ -438,4 +440,16 @@ server.registerTool('understudy_app', {
|
|
|
438
440
|
return setPlaceholders(app, placeholders);
|
|
439
441
|
return { app, placeholders: await appPlaceholders(app) };
|
|
440
442
|
}));
|
|
443
|
+
server.registerTool('understudy_calibrate', {
|
|
444
|
+
description: 'Fit when recall calls a goal "known", for this app and embedding model — needed after switching models, or when recall calls the wrong things known (its `cutoffs.source` says "uncalibrated"). Give 2–3 rewordings per flow (not its own title) and 5+ goals that sound like the app but that it has no flow for; they are kept, so later calls and `understudy reembed` re-fit from them. Tell the user the before/after and any mistakes.',
|
|
445
|
+
inputSchema: {
|
|
446
|
+
app: z.string(),
|
|
447
|
+
known: z.array(z.object({ flow: z.string().describe('the flow\'s slug'), goals: z.array(z.string()) })).optional(),
|
|
448
|
+
unknown: z.array(z.string()).optional(),
|
|
449
|
+
dryRun: z.boolean().optional().describe('fit and report, keep nothing'),
|
|
450
|
+
},
|
|
451
|
+
}, ({ app, known, unknown, dryRun }) => wrap(() => calibrate(app, {
|
|
452
|
+
goals: { known: (known ?? []).flatMap((k) => k.goals.map((goal) => ({ flow: k.flow, goal }))), unknown: unknown ?? [] },
|
|
453
|
+
...(dryRun ? { dryRun } : {}),
|
|
454
|
+
})));
|
|
441
455
|
await server.connect(new StdioServerTransport());
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* calibrate: fit recall's known/unknown cutoffs to one app and one embedding
|
|
3
|
+
* model, instead of trusting numbers set by hand for another model.
|
|
4
|
+
*
|
|
5
|
+
* recall says "known" when the top flow scores ≥ strong, or ≥ good and ≥
|
|
6
|
+
* margin ahead of the next (isKnown in recall.ts). Each model scores on its
|
|
7
|
+
* own scale, so those three numbers have to be learned from goals whose right
|
|
8
|
+
* answer is known:
|
|
9
|
+
*
|
|
10
|
+
* known goals "log into my account" → sign-in. Reworded, never a flow's
|
|
11
|
+
* own name (that matches exactly and proves nothing). From a
|
|
12
|
+
* goals file, and from runs that bound a flow and passed.
|
|
13
|
+
* unknown goals ones the app doesn't have, from a goals file. Short of
|
|
14
|
+
* MIN_GOALS of those, made up: leave each flow out and search
|
|
15
|
+
* for its own title among the rest (skipping the recording it
|
|
16
|
+
* was cut from and segments cut from it — those really do it).
|
|
17
|
+
* Only a fallback: a title is in the app's own words, so its
|
|
18
|
+
* sibling scores far higher than a goal a person would ask.
|
|
19
|
+
* On the 28-flow providernow corpus these drove voyage-4-lite's
|
|
20
|
+
* fitted strong cutoff to 0.96, missing 20 of 34 real goals.
|
|
21
|
+
*
|
|
22
|
+
* Every goal is embedded once and scored against the stored flow vectors here,
|
|
23
|
+
* with the score vector search gives cosine — (1 + cos) / 2 — so leaving a
|
|
24
|
+
* flow out costs nothing. Then a grid search picks the cutoffs that put the
|
|
25
|
+
* most goals on the right side, counting a wrong "known" (a flow runs that
|
|
26
|
+
* shouldn't) twice as bad as a missed one (it's shown, not run).
|
|
27
|
+
*
|
|
28
|
+
* The goals are kept on the app, so `reembed` re-fits every app for a new
|
|
29
|
+
* model without asking for them again.
|
|
30
|
+
*/
|
|
31
|
+
import type { CalibrationGoals, Cutoffs } from '../store/types.js';
|
|
32
|
+
import { type CutoffSource } from './recall.js';
|
|
33
|
+
/** Fewer than this many of either kind, and the fit isn't saved: too easy to fit by luck. */
|
|
34
|
+
export declare const MIN_GOALS = 5;
|
|
35
|
+
/** Below this many flows the scores bunch up; the fit is saved but flagged. */
|
|
36
|
+
export declare const FEW_FLOWS = 8;
|
|
37
|
+
export interface Sample {
|
|
38
|
+
goal: string;
|
|
39
|
+
/** The flow that does it, or null for a goal the app doesn't have. */
|
|
40
|
+
expect: string | null;
|
|
41
|
+
from: 'goals file' | 'run' | 'left out';
|
|
42
|
+
/** For 'left out': the flow removed before searching. */
|
|
43
|
+
without?: string;
|
|
44
|
+
topFlow?: string;
|
|
45
|
+
top: number;
|
|
46
|
+
second?: number;
|
|
47
|
+
}
|
|
48
|
+
export interface Fit extends Cutoffs {
|
|
49
|
+
cost: number;
|
|
50
|
+
correct: number;
|
|
51
|
+
}
|
|
52
|
+
/** How many samples a rule puts on the right side, and what its mistakes cost. */
|
|
53
|
+
export declare function score(samples: Sample[], rule: Cutoffs): {
|
|
54
|
+
cost: number;
|
|
55
|
+
correct: number;
|
|
56
|
+
wrong: Sample[];
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Pure: the cutoffs that cost least on these samples. Among equally good ones,
|
|
60
|
+
* the one whose decisions sit furthest from any cutoff — so a goal worded a
|
|
61
|
+
* little differently next time lands on the same side.
|
|
62
|
+
*/
|
|
63
|
+
export declare function fit(samples: Sample[]): Fit;
|
|
64
|
+
export interface CalibrateInput {
|
|
65
|
+
/** More goals to fit on, added to the ones already kept for the app. */
|
|
66
|
+
goals?: Partial<CalibrationGoals>;
|
|
67
|
+
/** Fit and report, but keep nothing. */
|
|
68
|
+
dryRun?: boolean;
|
|
69
|
+
}
|
|
70
|
+
export interface Calibration {
|
|
71
|
+
app: string;
|
|
72
|
+
model: string;
|
|
73
|
+
flows: number;
|
|
74
|
+
goals: {
|
|
75
|
+
known: number;
|
|
76
|
+
unknown: number;
|
|
77
|
+
fromRuns: number;
|
|
78
|
+
leftOut: number;
|
|
79
|
+
};
|
|
80
|
+
/** What recall uses now, and how it does on these goals. */
|
|
81
|
+
before: Cutoffs & {
|
|
82
|
+
source: CutoffSource;
|
|
83
|
+
correct: number;
|
|
84
|
+
};
|
|
85
|
+
after: Cutoffs & {
|
|
86
|
+
correct: number;
|
|
87
|
+
};
|
|
88
|
+
total: number;
|
|
89
|
+
/** Goals the fitted cutoffs still get wrong. */
|
|
90
|
+
mistakes: {
|
|
91
|
+
goal: string;
|
|
92
|
+
expected: string | null;
|
|
93
|
+
top?: string;
|
|
94
|
+
score: number;
|
|
95
|
+
next?: number;
|
|
96
|
+
verdict: 'known' | 'not known';
|
|
97
|
+
}[];
|
|
98
|
+
/** Known goals where the embedder ranked another flow first — no cutoff can fix those. */
|
|
99
|
+
misranked: {
|
|
100
|
+
goal: string;
|
|
101
|
+
expected: string;
|
|
102
|
+
top?: string;
|
|
103
|
+
}[];
|
|
104
|
+
saved: boolean;
|
|
105
|
+
/** Why not saved, or what to be wary of. */
|
|
106
|
+
notes: string[];
|
|
107
|
+
}
|
|
108
|
+
/** Fit, report, and (unless dryRun, or there's too little to go on) keep the cutoffs. */
|
|
109
|
+
export declare function calibrate(app: string, input?: CalibrateInput): Promise<Calibration>;
|
|
110
|
+
/** After `reembed`: re-fit every app that has goals kept, for the model now configured. */
|
|
111
|
+
export declare function recalibrateAll(): Promise<{
|
|
112
|
+
refitted: Calibration[];
|
|
113
|
+
withoutGoals: string[];
|
|
114
|
+
}>;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* calibrate: fit recall's known/unknown cutoffs to one app and one embedding
|
|
3
|
+
* model, instead of trusting numbers set by hand for another model.
|
|
4
|
+
*
|
|
5
|
+
* recall says "known" when the top flow scores ≥ strong, or ≥ good and ≥
|
|
6
|
+
* margin ahead of the next (isKnown in recall.ts). Each model scores on its
|
|
7
|
+
* own scale, so those three numbers have to be learned from goals whose right
|
|
8
|
+
* answer is known:
|
|
9
|
+
*
|
|
10
|
+
* known goals "log into my account" → sign-in. Reworded, never a flow's
|
|
11
|
+
* own name (that matches exactly and proves nothing). From a
|
|
12
|
+
* goals file, and from runs that bound a flow and passed.
|
|
13
|
+
* unknown goals ones the app doesn't have, from a goals file. Short of
|
|
14
|
+
* MIN_GOALS of those, made up: leave each flow out and search
|
|
15
|
+
* for its own title among the rest (skipping the recording it
|
|
16
|
+
* was cut from and segments cut from it — those really do it).
|
|
17
|
+
* Only a fallback: a title is in the app's own words, so its
|
|
18
|
+
* sibling scores far higher than a goal a person would ask.
|
|
19
|
+
* On the 28-flow providernow corpus these drove voyage-4-lite's
|
|
20
|
+
* fitted strong cutoff to 0.96, missing 20 of 34 real goals.
|
|
21
|
+
*
|
|
22
|
+
* Every goal is embedded once and scored against the stored flow vectors here,
|
|
23
|
+
* with the score vector search gives cosine — (1 + cos) / 2 — so leaving a
|
|
24
|
+
* flow out costs nothing. Then a grid search picks the cutoffs that put the
|
|
25
|
+
* most goals on the right side, counting a wrong "known" (a flow runs that
|
|
26
|
+
* shouldn't) twice as bad as a missed one (it's shown, not run).
|
|
27
|
+
*
|
|
28
|
+
* The goals are kept on the app, so `reembed` re-fits every app for a new
|
|
29
|
+
* model without asking for them again.
|
|
30
|
+
*/
|
|
31
|
+
import { collections } from '../store/db.js';
|
|
32
|
+
import { embed, embedderConfig } from '../store/embed.js';
|
|
33
|
+
import { cutoffsFor, isKnown } from './recall.js';
|
|
34
|
+
/** Fewer than this many of either kind, and the fit isn't saved: too easy to fit by luck. */
|
|
35
|
+
export const MIN_GOALS = 5;
|
|
36
|
+
/** Below this many flows the scores bunch up; the fit is saved but flagged. */
|
|
37
|
+
export const FEW_FLOWS = 8;
|
|
38
|
+
/** Should recall call this one known? Only when the embedder ranked the right flow first. */
|
|
39
|
+
const shouldBeKnown = (s) => s.expect !== null && s.topFlow === s.expect;
|
|
40
|
+
/** A wrong "known" runs the wrong flow; a missed one is only shown. */
|
|
41
|
+
const COST_WRONG_KNOWN = 2;
|
|
42
|
+
const COST_MISSED = 1;
|
|
43
|
+
const STEP = 0.005;
|
|
44
|
+
const grid = (from, to) => {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (let i = Math.round(from / STEP); i <= Math.round(to / STEP); i++)
|
|
47
|
+
out.push(Number((i * STEP).toFixed(3)));
|
|
48
|
+
return out;
|
|
49
|
+
};
|
|
50
|
+
/** How many samples a rule puts on the right side, and what its mistakes cost. */
|
|
51
|
+
export function score(samples, rule) {
|
|
52
|
+
let cost = 0;
|
|
53
|
+
const wrong = [];
|
|
54
|
+
for (const s of samples) {
|
|
55
|
+
const want = shouldBeKnown(s);
|
|
56
|
+
if (isKnown(s.top, s.second, rule) === want)
|
|
57
|
+
continue;
|
|
58
|
+
cost += want ? COST_MISSED : COST_WRONG_KNOWN;
|
|
59
|
+
wrong.push(s);
|
|
60
|
+
}
|
|
61
|
+
return { cost, correct: samples.length - wrong.length, wrong };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Pure: the cutoffs that cost least on these samples. Among equally good ones,
|
|
65
|
+
* the one whose decisions sit furthest from any cutoff — so a goal worded a
|
|
66
|
+
* little differently next time lands on the same side.
|
|
67
|
+
*/
|
|
68
|
+
export function fit(samples) {
|
|
69
|
+
const tops = samples.map((s) => s.top);
|
|
70
|
+
const gaps = samples.map((s) => (s.second === undefined ? -1 : s.top - s.second));
|
|
71
|
+
const want = samples.map(shouldBeKnown);
|
|
72
|
+
const n = samples.length;
|
|
73
|
+
const strongs = [...grid(0.5, 1), 1 + STEP]; // the last: never known on score alone
|
|
74
|
+
const margins = grid(0, 0.5);
|
|
75
|
+
let best;
|
|
76
|
+
for (const strong of strongs) {
|
|
77
|
+
for (const good of grid(0.5, Math.min(strong, 1))) {
|
|
78
|
+
for (const margin of margins) {
|
|
79
|
+
let cost = 0;
|
|
80
|
+
let wrong = 0;
|
|
81
|
+
for (let i = 0; i < n; i++) {
|
|
82
|
+
const t = tops[i];
|
|
83
|
+
const k = t >= strong || (t >= good && gaps[i] >= 0 && gaps[i] >= margin);
|
|
84
|
+
if (k !== want[i]) {
|
|
85
|
+
wrong++;
|
|
86
|
+
cost += want[i] ? COST_MISSED : COST_WRONG_KNOWN;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (best && cost > best.cost)
|
|
90
|
+
continue;
|
|
91
|
+
// How close the nearest decision is to flipping: smallest distance to a cutoff it was tested against.
|
|
92
|
+
let clearance = Infinity;
|
|
93
|
+
let spread = 0;
|
|
94
|
+
for (let i = 0; i < n; i++) {
|
|
95
|
+
const t = tops[i];
|
|
96
|
+
let d = Math.abs(t - strong);
|
|
97
|
+
if (t < strong)
|
|
98
|
+
d = Math.min(d, Math.abs(t - good));
|
|
99
|
+
if (t < strong && t >= good && gaps[i] >= 0)
|
|
100
|
+
d = Math.min(d, Math.abs(gaps[i] - margin));
|
|
101
|
+
clearance = Math.min(clearance, d);
|
|
102
|
+
spread += d;
|
|
103
|
+
}
|
|
104
|
+
if (!best || cost < best.cost || clearance > best.clearance + 1e-9 || (Math.abs(clearance - best.clearance) <= 1e-9 && spread > best.spread)) {
|
|
105
|
+
best = { strong, good, margin, cost, correct: n - wrong, clearance, spread };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const { clearance: _c, spread: _s, ...out } = best;
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
const cosine = (a, b) => {
|
|
114
|
+
let dot = 0, na = 0, nb = 0;
|
|
115
|
+
for (let i = 0; i < a.length; i++) {
|
|
116
|
+
dot += a[i] * b[i];
|
|
117
|
+
na += a[i] * a[i];
|
|
118
|
+
nb += b[i] * b[i];
|
|
119
|
+
}
|
|
120
|
+
return dot / (Math.sqrt(na * nb) || 1);
|
|
121
|
+
};
|
|
122
|
+
/** What $vectorSearch reports for cosine similarity. */
|
|
123
|
+
const searchScore = (a, b) => (1 + cosine(a, b)) / 2;
|
|
124
|
+
const norm = (s) => s.trim().toLowerCase();
|
|
125
|
+
/** Fit, report, and (unless dryRun, or there's too little to go on) keep the cutoffs. */
|
|
126
|
+
export async function calibrate(app, input = {}) {
|
|
127
|
+
const cfg = embedderConfig();
|
|
128
|
+
if (!cfg)
|
|
129
|
+
throw new Error('calibrate fits the cutoffs for matching by meaning, and no embedding model is configured — set EMBED_KEY, or EMBED_URL and EMBED_MODEL');
|
|
130
|
+
const c = await collections();
|
|
131
|
+
const flows = await c.flows.find({ app }, { projection: { slug: 1, title: 1, from: 1, embedding: 1 } }).toArray();
|
|
132
|
+
if (!flows.length)
|
|
133
|
+
throw new Error(`no flows for '${app}' — save some first`);
|
|
134
|
+
const unembedded = flows.filter((f) => f.embedding?.length !== cfg.dims);
|
|
135
|
+
if (unembedded.length) {
|
|
136
|
+
throw new Error(`${unembedded.length} of ${app}'s flows have no ${cfg.dims}-number vector from ${cfg.model} (e.g. ${unembedded[0].slug}) — run: understudy reembed`);
|
|
137
|
+
}
|
|
138
|
+
const slugs = new Set(flows.map((f) => f.slug));
|
|
139
|
+
const names = new Set(flows.flatMap((f) => [norm(f.slug), norm(f.title)]));
|
|
140
|
+
// Goals: the ones kept, plus the ones given now. A flow that no longer exists drops out.
|
|
141
|
+
const appDoc = await c.apps.findOne({ slug: app }, { projection: { calibrationGoals: 1 } });
|
|
142
|
+
const kept = appDoc?.calibrationGoals ?? { known: [], unknown: [] };
|
|
143
|
+
const badSlugs = [...new Set((input.goals?.known ?? []).map((k) => k.flow).filter((f) => !slugs.has(f)))];
|
|
144
|
+
if (badSlugs.length)
|
|
145
|
+
throw new Error(`no flow ${badSlugs.map((s) => `'${s}'`).join(', ')} in ${app} — known goals name a flow by its slug (understudy flows ${app})`);
|
|
146
|
+
const known = new Map();
|
|
147
|
+
for (const k of [...kept.known, ...(input.goals?.known ?? [])])
|
|
148
|
+
if (slugs.has(k.flow) && k.goal.trim())
|
|
149
|
+
known.set(norm(k.goal), { flow: k.flow, goal: k.goal.trim() });
|
|
150
|
+
const unknown = new Map();
|
|
151
|
+
for (const u of [...kept.unknown, ...(input.goals?.unknown ?? [])])
|
|
152
|
+
if (u.trim())
|
|
153
|
+
unknown.set(norm(u), u.trim());
|
|
154
|
+
const skippedExact = [...known.keys(), ...unknown.keys()].filter((g) => names.has(g)).length;
|
|
155
|
+
for (const g of names) {
|
|
156
|
+
known.delete(g);
|
|
157
|
+
unknown.delete(g);
|
|
158
|
+
}
|
|
159
|
+
const clash = [...known.keys()].filter((g) => unknown.has(g));
|
|
160
|
+
if (clash.length)
|
|
161
|
+
throw new Error(`listed as both known and unknown: ${clash.map((g) => `"${g}"`).join(', ')}`);
|
|
162
|
+
const goals = { known: [...known.values()], unknown: [...unknown.values()] };
|
|
163
|
+
// Free known goals: what runs were asked for, bound to a flow, and passed.
|
|
164
|
+
const fromRuns = new Map();
|
|
165
|
+
const runs = await c.runs.find({ app, mode: 'run', status: 'passed' }, { projection: { goal: 1, plan: 1, planning: 1 } }).toArray();
|
|
166
|
+
for (const r of runs) {
|
|
167
|
+
const pairs = r.planning?.subGoals && r.planning.bound?.length === r.planning.subGoals.length
|
|
168
|
+
? r.planning.subGoals.map((g, i) => [g, r.planning.bound[i]])
|
|
169
|
+
: r.plan.length === 1 ? [[r.goal, r.plan[0]]] : [];
|
|
170
|
+
for (const [g, flow] of pairs) {
|
|
171
|
+
if (flow && slugs.has(flow) && !names.has(norm(g)) && !known.has(norm(g)) && !unknown.has(norm(g)))
|
|
172
|
+
fromRuns.set(norm(g), JSON.stringify([g, flow]));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Embed every goal once, in as few requests as possible.
|
|
176
|
+
const titleTaken = (title, slug) => flows.some((f) => f.slug !== slug && norm(f.title) === norm(title));
|
|
177
|
+
const leftOut = flows.length > 1 && goals.unknown.length < MIN_GOALS ? flows.filter((f) => !titleTaken(f.title, f.slug)) : [];
|
|
178
|
+
/** With `slug` left out: it, the recording it was cut from, and segments cut from it. */
|
|
179
|
+
const related = (slug) => {
|
|
180
|
+
const left = flows.find((f) => f.slug === slug);
|
|
181
|
+
return new Set([slug, ...(left?.from ? [left.from.flow] : []), ...flows.filter((f) => f.from?.flow === slug).map((f) => f.slug)]);
|
|
182
|
+
};
|
|
183
|
+
const runPairs = [...fromRuns.values()].map((p) => JSON.parse(p));
|
|
184
|
+
const texts = [...new Set([...goals.known.map((k) => k.goal), ...goals.unknown, ...runPairs.map(([g]) => g), ...leftOut.map((f) => f.title)])];
|
|
185
|
+
const vectors = new Map();
|
|
186
|
+
const embedded = texts.length ? await embed(texts, 'query', cfg) : [];
|
|
187
|
+
texts.forEach((t, i) => vectors.set(t, embedded[i]));
|
|
188
|
+
const sample = (goal, expect, from, without) => {
|
|
189
|
+
const q = vectors.get(goal);
|
|
190
|
+
const skip = without ? related(without) : undefined;
|
|
191
|
+
const ranked = flows
|
|
192
|
+
.filter((f) => !skip?.has(f.slug))
|
|
193
|
+
.map((f) => ({ slug: f.slug, score: searchScore(q, f.embedding) }))
|
|
194
|
+
.sort((a, b) => b.score - a.score);
|
|
195
|
+
return {
|
|
196
|
+
goal, expect, from, ...(without ? { without } : {}),
|
|
197
|
+
...(ranked[0] ? { topFlow: ranked[0].slug, top: ranked[0].score } : { top: 0 }),
|
|
198
|
+
...(ranked[1] ? { second: ranked[1].score } : {}),
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
const samples = [
|
|
202
|
+
...goals.known.map((k) => sample(k.goal, k.flow, 'goals file')),
|
|
203
|
+
...runPairs.map(([g, flow]) => sample(g, flow, 'run')),
|
|
204
|
+
...goals.unknown.map((g) => sample(g, null, 'goals file')),
|
|
205
|
+
...leftOut.map((f) => sample(f.title, null, 'left out', f.slug)),
|
|
206
|
+
];
|
|
207
|
+
const nKnown = samples.filter((s) => s.expect !== null).length;
|
|
208
|
+
const nUnknown = samples.length - nKnown;
|
|
209
|
+
const current = await cutoffsFor(app, cfg);
|
|
210
|
+
const fitted = fit(samples);
|
|
211
|
+
const after = { strong: fitted.strong, good: fitted.good, margin: fitted.margin };
|
|
212
|
+
const { wrong } = score(samples, after);
|
|
213
|
+
const notes = [];
|
|
214
|
+
if (skippedExact)
|
|
215
|
+
notes.push(`${skippedExact} goal(s) skipped: they are a flow's exact name, which recall matches without scores`);
|
|
216
|
+
if (nKnown < MIN_GOALS)
|
|
217
|
+
notes.push(`only ${nKnown} known goal(s) — need ${MIN_GOALS}+: add rewordings of the app's flows (e.g. 2–3 ways someone would ask for each)`);
|
|
218
|
+
if (nUnknown < MIN_GOALS)
|
|
219
|
+
notes.push(`only ${nUnknown} unknown goal(s) — need ${MIN_GOALS}+: add goals that sound like the app but that it has no flow for`);
|
|
220
|
+
if (leftOut.length)
|
|
221
|
+
notes.push(`${leftOut.length} unknown goal(s) made by leaving a flow out and searching its title — harder than real goals, so the fit leans strict; add ${MIN_GOALS}+ real unknown goals instead`);
|
|
222
|
+
if (flows.length < FEW_FLOWS)
|
|
223
|
+
notes.push(`only ${flows.length} flows: scores bunch up on a small app, so treat these cutoffs as rough and calibrate again as it grows`);
|
|
224
|
+
const enough = nKnown >= MIN_GOALS && nUnknown >= MIN_GOALS;
|
|
225
|
+
const saved = enough && !input.dryRun;
|
|
226
|
+
// The goals are worth keeping even when they're too few to fit on yet.
|
|
227
|
+
if (!input.dryRun) {
|
|
228
|
+
const cutoffs = { ...after, model: cfg.model, dims: cfg.dims, fittedAt: new Date(), goals: { known: nKnown, unknown: nUnknown }, correct: samples.length - wrong.length };
|
|
229
|
+
await c.apps.updateOne({ slug: app }, { $set: { calibrationGoals: goals, ...(saved ? { cutoffs } : {}) }, $setOnInsert: { slug: app, name: app, urls: {}, createdAt: new Date() } }, { upsert: true });
|
|
230
|
+
}
|
|
231
|
+
const r3 = (x) => Number(x.toFixed(3));
|
|
232
|
+
return {
|
|
233
|
+
app, model: cfg.model, flows: flows.length,
|
|
234
|
+
goals: { known: goals.known.length, unknown: goals.unknown.length, fromRuns: runPairs.length, leftOut: leftOut.length },
|
|
235
|
+
before: { strong: current.strong, good: current.good, margin: current.margin, source: current.source, correct: score(samples, current).correct },
|
|
236
|
+
after: { ...after, correct: samples.length - wrong.length },
|
|
237
|
+
total: samples.length,
|
|
238
|
+
mistakes: wrong.map((s) => ({
|
|
239
|
+
goal: s.from === 'left out' ? `${s.goal} (with ${s.without} left out)` : s.goal,
|
|
240
|
+
expected: s.expect, ...(s.topFlow ? { top: s.topFlow } : {}), score: r3(s.top), ...(s.second !== undefined ? { next: r3(s.second) } : {}),
|
|
241
|
+
verdict: isKnown(s.top, s.second, after) ? 'known' : 'not known',
|
|
242
|
+
})),
|
|
243
|
+
misranked: samples.filter((s) => s.expect !== null && s.topFlow !== s.expect).map((s) => ({ goal: s.goal, expected: s.expect, ...(s.topFlow ? { top: s.topFlow } : {}) })),
|
|
244
|
+
saved, notes,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/** After `reembed`: re-fit every app that has goals kept, for the model now configured. */
|
|
248
|
+
export async function recalibrateAll() {
|
|
249
|
+
const { apps, flows } = await collections();
|
|
250
|
+
const withGoals = (await apps.find({ calibrationGoals: { $exists: true } }, { projection: { slug: 1 } }).toArray()).map((a) => a.slug);
|
|
251
|
+
const refitted = [];
|
|
252
|
+
for (const app of withGoals) {
|
|
253
|
+
if (await flows.findOne({ app }))
|
|
254
|
+
refitted.push(await calibrate(app));
|
|
255
|
+
}
|
|
256
|
+
const all = await flows.distinct('app');
|
|
257
|
+
return { refitted, withoutGoals: all.filter((a) => !withGoals.includes(a)) };
|
|
258
|
+
}
|
package/dist/memory/recall.d.ts
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
* words no model: match the goal's words against flow names
|
|
15
15
|
* Either way, a goal that IS a flow's name or slug matches exactly.
|
|
16
16
|
*/
|
|
17
|
-
import type { Flow, Note } from '../store/types.js';
|
|
17
|
+
import type { Cutoffs, Flow, Note } from '../store/types.js';
|
|
18
|
+
import { type EmbedderConfig } from '../store/embed.js';
|
|
18
19
|
export interface FlowMatch {
|
|
19
20
|
slug: string;
|
|
20
21
|
title: string;
|
|
@@ -76,38 +77,45 @@ export interface Recall {
|
|
|
76
77
|
why: string;
|
|
77
78
|
flows: FlowMatch[];
|
|
78
79
|
notes: NoteMatch[];
|
|
80
|
+
/** Matching by meaning: the cutoffs the verdict used, and where they came from. */
|
|
81
|
+
cutoffs?: Cutoffs & {
|
|
82
|
+
source: CutoffSource;
|
|
83
|
+
};
|
|
79
84
|
}
|
|
80
85
|
/**
|
|
81
|
-
* When a match by MEANING is good enough to act on
|
|
82
|
-
* a real 28-flow corpus
|
|
83
|
-
* unknown ones): no single score separates them, because a
|
|
86
|
+
* When a match by MEANING is good enough to act on — the built-in cutoffs, for
|
|
87
|
+
* voyage-4-lite. Set by hand 2026-11-18 on a real 28-flow corpus (15 known
|
|
88
|
+
* goals, 14 plausible unknown ones): no single score separates them, because a
|
|
84
89
|
* goal the app doesn't have still lands near something. What does separate
|
|
85
|
-
* them is how far the top match is ahead of the runner-up.
|
|
86
|
-
*
|
|
90
|
+
* them is how far the top match is ahead of the runner-up.
|
|
91
|
+
*
|
|
92
|
+
* Other models score on other scales (mxbai-embed-large puts unrelated goals
|
|
93
|
+
* at 0.72–0.80), so `understudy calibrate` fits these per app and model, and
|
|
94
|
+
* recall uses the fitted ones when there are any (see cutoffsFor).
|
|
87
95
|
*/
|
|
88
|
-
export declare const MEANING:
|
|
89
|
-
/** At or above this, the top flow is the answer. */
|
|
90
|
-
strong: number;
|
|
91
|
-
/** At or above this, the top flow is the answer IF it clearly beats the runner-up… */
|
|
92
|
-
good: number;
|
|
93
|
-
/** …by at least this much. */
|
|
94
|
-
margin: number;
|
|
95
|
-
};
|
|
96
|
+
export declare const MEANING: Cutoffs;
|
|
96
97
|
/** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
|
|
97
|
-
export declare const WORDS:
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
98
|
+
export declare const WORDS: Cutoffs;
|
|
99
|
+
/**
|
|
100
|
+
* Pure: is the top flow the answer? The whole rule, in one place — judge
|
|
101
|
+
* explains it, calibrate fits it. With only one flow there's no runner-up to
|
|
102
|
+
* beat, so only a strong match counts.
|
|
103
|
+
*/
|
|
104
|
+
export declare function isKnown(top: number, second: number | undefined, rule: Cutoffs): boolean;
|
|
102
105
|
/** Pure: the verdict for a ranked list of scores. Exported for tests. */
|
|
103
|
-
export declare function judge(scores: number[], rule: {
|
|
104
|
-
strong: number;
|
|
105
|
-
good: number;
|
|
106
|
-
margin: number;
|
|
107
|
-
}): {
|
|
106
|
+
export declare function judge(scores: number[], rule: Cutoffs): {
|
|
108
107
|
verdict: Verdict;
|
|
109
108
|
why: string;
|
|
110
109
|
};
|
|
110
|
+
/**
|
|
111
|
+
* Which cutoffs recall uses with this model: fitted for this app; else fitted
|
|
112
|
+
* for another app with the same model (better than another model's numbers);
|
|
113
|
+
* else the built-in ones, which were set for voyage-4-lite.
|
|
114
|
+
*/
|
|
115
|
+
export declare function cutoffsFor(app: string, cfg: Pick<EmbedderConfig, 'model' | 'dims'>): Promise<Cutoffs & {
|
|
116
|
+
source: CutoffSource;
|
|
117
|
+
}>;
|
|
118
|
+
export type CutoffSource = 'this app' | 'another app' | 'built-in' | 'uncalibrated';
|
|
111
119
|
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
112
120
|
export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title' | 'intent'>): number;
|
|
113
121
|
/**
|
package/dist/memory/recall.js
CHANGED
|
@@ -15,16 +15,19 @@
|
|
|
15
15
|
* Either way, a goal that IS a flow's name or slug matches exactly.
|
|
16
16
|
*/
|
|
17
17
|
import { collections, vectorSearch } from '../store/db.js';
|
|
18
|
-
import { embed, embedderConfig } from '../store/embed.js';
|
|
18
|
+
import { embed, embedderConfig, VOYAGE_DEFAULT } from '../store/embed.js';
|
|
19
19
|
import { valuesFromEnv, valueEnvNames } from '../store/settings.js';
|
|
20
20
|
import { valueRefsOf } from '../core/recording.js';
|
|
21
21
|
/**
|
|
22
|
-
* When a match by MEANING is good enough to act on
|
|
23
|
-
* a real 28-flow corpus
|
|
24
|
-
* unknown ones): no single score separates them, because a
|
|
22
|
+
* When a match by MEANING is good enough to act on — the built-in cutoffs, for
|
|
23
|
+
* voyage-4-lite. Set by hand 2026-11-18 on a real 28-flow corpus (15 known
|
|
24
|
+
* goals, 14 plausible unknown ones): no single score separates them, because a
|
|
25
25
|
* goal the app doesn't have still lands near something. What does separate
|
|
26
|
-
* them is how far the top match is ahead of the runner-up.
|
|
27
|
-
*
|
|
26
|
+
* them is how far the top match is ahead of the runner-up.
|
|
27
|
+
*
|
|
28
|
+
* Other models score on other scales (mxbai-embed-large puts unrelated goals
|
|
29
|
+
* at 0.72–0.80), so `understudy calibrate` fits these per app and model, and
|
|
30
|
+
* recall uses the fitted ones when there are any (see cutoffsFor).
|
|
28
31
|
*/
|
|
29
32
|
export const MEANING = {
|
|
30
33
|
/** At or above this, the top flow is the answer. */
|
|
@@ -36,24 +39,46 @@ export const MEANING = {
|
|
|
36
39
|
};
|
|
37
40
|
/** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
|
|
38
41
|
export const WORDS = { strong: 1, good: 0.6, margin: 0.2 };
|
|
42
|
+
/**
|
|
43
|
+
* Pure: is the top flow the answer? The whole rule, in one place — judge
|
|
44
|
+
* explains it, calibrate fits it. With only one flow there's no runner-up to
|
|
45
|
+
* beat, so only a strong match counts.
|
|
46
|
+
*/
|
|
47
|
+
export function isKnown(top, second, rule) {
|
|
48
|
+
if (top >= rule.strong)
|
|
49
|
+
return true;
|
|
50
|
+
return top >= rule.good && second !== undefined && top - second >= rule.margin;
|
|
51
|
+
}
|
|
39
52
|
/** Pure: the verdict for a ranked list of scores. Exported for tests. */
|
|
40
53
|
export function judge(scores, rule) {
|
|
41
54
|
const [top, second] = scores;
|
|
42
55
|
if (top === undefined)
|
|
43
56
|
return { verdict: 'unknown', why: 'this app has no flows yet' };
|
|
44
57
|
const f = (n) => n.toFixed(2);
|
|
45
|
-
if (top
|
|
46
|
-
return { verdict: 'known', why: `strong match (${f(top)})` };
|
|
58
|
+
if (isKnown(top, second, rule)) {
|
|
59
|
+
return { verdict: 'known', why: top >= rule.strong ? `strong match (${f(top)})` : `good match (${f(top)}), clearly ahead of the next (${f(second)})` };
|
|
60
|
+
}
|
|
47
61
|
if (top >= rule.good) {
|
|
48
|
-
// With only one flow there's no runner-up to beat, so only a strong match counts.
|
|
49
62
|
if (second === undefined)
|
|
50
63
|
return { verdict: 'unsure', why: `good match (${f(top)}), but only one flow to compare with` };
|
|
51
|
-
if (top - second >= rule.margin)
|
|
52
|
-
return { verdict: 'known', why: `good match (${f(top)}), clearly ahead of the next (${f(second)})` };
|
|
53
64
|
return { verdict: 'unsure', why: `good match (${f(top)}), but the next is close (${f(second)})` };
|
|
54
65
|
}
|
|
55
66
|
return { verdict: 'unknown', why: `nothing matches well (best ${f(top)})` };
|
|
56
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Which cutoffs recall uses with this model: fitted for this app; else fitted
|
|
70
|
+
* for another app with the same model (better than another model's numbers);
|
|
71
|
+
* else the built-in ones, which were set for voyage-4-lite.
|
|
72
|
+
*/
|
|
73
|
+
export async function cutoffsFor(app, cfg) {
|
|
74
|
+
const { apps } = await collections();
|
|
75
|
+
const same = { 'cutoffs.model': cfg.model, 'cutoffs.dims': cfg.dims };
|
|
76
|
+
const own = await apps.findOne({ slug: app, ...same }, { projection: { cutoffs: 1 } });
|
|
77
|
+
const fitted = own?.cutoffs ?? (await apps.findOne(same, { sort: { 'cutoffs.fittedAt': -1 }, projection: { cutoffs: 1 } }))?.cutoffs;
|
|
78
|
+
if (fitted)
|
|
79
|
+
return { strong: fitted.strong, good: fitted.good, margin: fitted.margin, source: own ? 'this app' : 'another app' };
|
|
80
|
+
return { ...MEANING, source: cfg.model === VOYAGE_DEFAULT.model ? 'built-in' : 'uncalibrated' };
|
|
81
|
+
}
|
|
57
82
|
const STOP = new Set(['a', 'an', 'the', 'to', 'my', 'of', 'for', 'and', 'in', 'on', 'as', 'i', 'me', 'it', 'is', 'with', 'at', 'up', 'out']);
|
|
58
83
|
const words = (s) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w && !STOP.has(w)));
|
|
59
84
|
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
@@ -126,16 +151,24 @@ export async function recall(app, goal, opts = {}) {
|
|
|
126
151
|
return { goal, method: 'exact', verdict: 'known', best, why: withProven('named exactly', best), flows: [best], notes: [], ...(opts.withSteps ? await plan(app, best.slug) : {}) };
|
|
127
152
|
}
|
|
128
153
|
// 2. By meaning, if there's a model.
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const [
|
|
154
|
+
const cfg = embedderConfig();
|
|
155
|
+
if (cfg) {
|
|
156
|
+
const [vector] = await embed([goal], 'query', cfg);
|
|
157
|
+
const [flows, notes, rule] = await Promise.all([
|
|
132
158
|
vectorSearch(c.flows, app, vector, { limit }),
|
|
133
159
|
vectorSearch(c.notes, app, vector, { limit }),
|
|
160
|
+
cutoffsFor(app, cfg),
|
|
134
161
|
]);
|
|
135
162
|
const matches = rank(flows.map((f) => toMatch(f, f.score)));
|
|
136
|
-
const
|
|
163
|
+
const judged = judge(matches.map((m) => m.score), rule);
|
|
164
|
+
const { verdict } = judged;
|
|
165
|
+
let why = verdict === 'known' ? withProven(judged.why, matches[0]) : judged.why;
|
|
166
|
+
if (rule.source === 'uncalibrated' && matches.length) {
|
|
167
|
+
why += ` (cutoffs not fitted for ${cfg.model} — run: understudy calibrate ${app})`;
|
|
168
|
+
}
|
|
169
|
+
const { source, ...cutoffs } = rule;
|
|
137
170
|
return {
|
|
138
|
-
goal, method: 'meaning', verdict, why:
|
|
171
|
+
goal, method: 'meaning', verdict, why, flows: matches, cutoffs: { ...cutoffs, source },
|
|
139
172
|
...(verdict === 'known' ? { best: matches[0], ...(opts.withSteps ? await plan(app, matches[0].slug) : {}) } : {}),
|
|
140
173
|
notes: notes.map((n) => ({ kind: n.kind, text: n.text, score: n.score })),
|
|
141
174
|
};
|
package/dist/store/reembed.js
CHANGED
|
@@ -13,20 +13,31 @@ export async function reembed() {
|
|
|
13
13
|
if (!cfg)
|
|
14
14
|
throw new Error('no embedding model configured — set EMBED_KEY (Voyage), or EMBED_URL and EMBED_MODEL for another model');
|
|
15
15
|
const c = await collections();
|
|
16
|
-
|
|
16
|
+
const flows = c.flows;
|
|
17
|
+
const notes = c.notes;
|
|
18
|
+
// Embed everything BEFORE changing anything: if the model fails (wrong
|
|
19
|
+
// name, not pulled, out of quota), the database is left as it was — still
|
|
20
|
+
// recorded as the old model, with the old model's vectors.
|
|
21
|
+
const [flowVectors, noteVectors] = [await vectorsFor(flows), await vectorsFor(notes)];
|
|
22
|
+
// Record the new model, so ensureSchema accepts it and resizes the indexes.
|
|
17
23
|
await c.meta.replaceOne({ _id: 'embedder' }, { model: cfg.model, dims: cfg.dims, setAt: new Date() }, { upsert: true });
|
|
18
24
|
await ensureSchema();
|
|
19
25
|
return {
|
|
20
|
-
flows: await
|
|
21
|
-
notes: await
|
|
26
|
+
flows: await write(flows, flowVectors),
|
|
27
|
+
notes: await write(notes, noteVectors),
|
|
22
28
|
model: cfg.model,
|
|
23
29
|
};
|
|
24
30
|
}
|
|
25
|
-
async function
|
|
31
|
+
async function vectorsFor(coll) {
|
|
26
32
|
const docs = await coll.find({}, { projection: { searchText: 1 } }).toArray();
|
|
27
33
|
if (!docs.length)
|
|
28
|
-
return
|
|
34
|
+
return [];
|
|
29
35
|
const vectors = await embed(docs.map((d) => d.searchText), 'document');
|
|
30
|
-
|
|
31
|
-
|
|
36
|
+
return docs.map((d, i) => ({ _id: d._id, embedding: vectors[i] }));
|
|
37
|
+
}
|
|
38
|
+
async function write(coll, vectors) {
|
|
39
|
+
if (!vectors.length)
|
|
40
|
+
return 0;
|
|
41
|
+
await coll.bulkWrite(vectors.map((v) => ({ updateOne: { filter: { _id: v._id }, update: { $set: { embedding: v.embedding } } } })));
|
|
42
|
+
return vectors.length;
|
|
32
43
|
}
|
package/dist/store/types.d.ts
CHANGED
|
@@ -33,8 +33,40 @@ export interface App {
|
|
|
33
33
|
* value moves to the user's env file. See memory/placeholders.ts.
|
|
34
34
|
*/
|
|
35
35
|
placeholders?: PlaceholderKind[];
|
|
36
|
+
/**
|
|
37
|
+
* Goals to fit recall's known/unknown cutoffs from (`understudy calibrate`).
|
|
38
|
+
* Kept so `reembed` can re-fit them for a new model without asking again.
|
|
39
|
+
*/
|
|
40
|
+
calibrationGoals?: CalibrationGoals;
|
|
41
|
+
/** The cutoffs fitted from them, for one embedding model. Ignored when the model changes. */
|
|
42
|
+
cutoffs?: FittedCutoffs;
|
|
36
43
|
createdAt: Date;
|
|
37
44
|
}
|
|
45
|
+
/** Goals labelled with the flow that does them; `unknown` ones the app doesn't have. */
|
|
46
|
+
export interface CalibrationGoals {
|
|
47
|
+
known: {
|
|
48
|
+
flow: string;
|
|
49
|
+
goal: string;
|
|
50
|
+
}[];
|
|
51
|
+
unknown: string[];
|
|
52
|
+
}
|
|
53
|
+
/** recall's rule for "known": top ≥ strong, or top ≥ good and ≥ margin ahead of the next flow. */
|
|
54
|
+
export interface Cutoffs {
|
|
55
|
+
strong: number;
|
|
56
|
+
good: number;
|
|
57
|
+
margin: number;
|
|
58
|
+
}
|
|
59
|
+
export interface FittedCutoffs extends Cutoffs {
|
|
60
|
+
model: string;
|
|
61
|
+
dims: number;
|
|
62
|
+
fittedAt: Date;
|
|
63
|
+
/** How many goals it was fitted on, and how many the cutoffs put on the right side. */
|
|
64
|
+
goals: {
|
|
65
|
+
known: number;
|
|
66
|
+
unknown: number;
|
|
67
|
+
};
|
|
68
|
+
correct: number;
|
|
69
|
+
}
|
|
38
70
|
export interface Flow {
|
|
39
71
|
_id?: ObjectId;
|
|
40
72
|
app: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jeffawe/understudy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "End-to-end tests for your own web apps: record a flow once, and Understudy remembers it, replays it, notices when the app changes, and runs goals you describe in words — on its own or as an MCP server for AI agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|