@jeffawe/understudy 0.2.3 → 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 +69 -19
- package/REASONER.md +31 -4
- package/dist/adapters/recorder/script.js +206 -4
- package/dist/core/distill.d.ts +12 -0
- package/dist/core/distill.js +25 -32
- package/dist/core/recording.d.ts +49 -1
- package/dist/core/recording.js +60 -0
- package/dist/core/replay.d.ts +70 -1
- package/dist/core/replay.js +251 -12
- package/dist/entry/cli.js +187 -11
- package/dist/entry/mcp.d.ts +2 -1
- package/dist/entry/mcp.js +187 -33
- package/dist/flows/destructive.d.ts +17 -1
- package/dist/flows/destructive.js +23 -5
- package/dist/flows/distill.js +2 -0
- package/dist/flows/emit.js +88 -5
- package/dist/flows/execute.d.ts +22 -2
- package/dist/flows/execute.js +19 -3
- package/dist/flows/findings.d.ts +4 -1
- package/dist/flows/findings.js +15 -3
- package/dist/flows/runs.d.ts +13 -0
- package/dist/flows/runs.js +43 -7
- package/dist/flows/save.d.ts +42 -1
- package/dist/flows/save.js +214 -14
- package/dist/memory/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +258 -0
- package/dist/memory/recall.d.ts +42 -25
- package/dist/memory/recall.js +61 -21
- package/dist/memory/vocabulary.js +9 -3
- package/dist/plan/planner.d.ts +8 -4
- package/dist/plan/planner.js +77 -4
- package/dist/store/reembed.js +18 -7
- package/dist/store/types.d.ts +78 -2
- package/package.json +1 -1
|
@@ -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;
|
|
@@ -24,6 +25,11 @@ export interface FlowMatch {
|
|
|
24
25
|
proven: boolean;
|
|
25
26
|
/** Why it's unproven, when it is. */
|
|
26
27
|
unprovenBecause?: string;
|
|
28
|
+
/** Proven only up to this step, its commit: found ready, never pressed. */
|
|
29
|
+
provenUpTo?: number;
|
|
30
|
+
/** App states it needs first, and ones it makes true. */
|
|
31
|
+
requires?: string[];
|
|
32
|
+
establishes?: string[];
|
|
27
33
|
score: number;
|
|
28
34
|
destructive: boolean;
|
|
29
35
|
requiresSession: boolean;
|
|
@@ -71,41 +77,52 @@ export interface Recall {
|
|
|
71
77
|
why: string;
|
|
72
78
|
flows: FlowMatch[];
|
|
73
79
|
notes: NoteMatch[];
|
|
80
|
+
/** Matching by meaning: the cutoffs the verdict used, and where they came from. */
|
|
81
|
+
cutoffs?: Cutoffs & {
|
|
82
|
+
source: CutoffSource;
|
|
83
|
+
};
|
|
74
84
|
}
|
|
75
85
|
/**
|
|
76
|
-
* When a match by MEANING is good enough to act on
|
|
77
|
-
* a real 28-flow corpus
|
|
78
|
-
* 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
|
|
79
89
|
* goal the app doesn't have still lands near something. What does separate
|
|
80
|
-
* them is how far the top match is ahead of the runner-up.
|
|
81
|
-
*
|
|
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).
|
|
82
95
|
*/
|
|
83
|
-
export declare const MEANING:
|
|
84
|
-
/** At or above this, the top flow is the answer. */
|
|
85
|
-
strong: number;
|
|
86
|
-
/** At or above this, the top flow is the answer IF it clearly beats the runner-up… */
|
|
87
|
-
good: number;
|
|
88
|
-
/** …by at least this much. */
|
|
89
|
-
margin: number;
|
|
90
|
-
};
|
|
96
|
+
export declare const MEANING: Cutoffs;
|
|
91
97
|
/** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
|
|
92
|
-
export declare const WORDS:
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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;
|
|
97
105
|
/** Pure: the verdict for a ranked list of scores. Exported for tests. */
|
|
98
|
-
export declare function judge(scores: number[], rule: {
|
|
99
|
-
strong: number;
|
|
100
|
-
good: number;
|
|
101
|
-
margin: number;
|
|
102
|
-
}): {
|
|
106
|
+
export declare function judge(scores: number[], rule: Cutoffs): {
|
|
103
107
|
verdict: Verdict;
|
|
104
108
|
why: string;
|
|
105
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';
|
|
106
119
|
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
107
120
|
export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title' | 'intent'>): number;
|
|
108
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* Highest score first; on a tie, a proven flow ahead of an unproven one, then
|
|
123
|
+
* one a person recorded ahead of one an agent made — a person's recording is
|
|
124
|
+
* the better word on how the app is meant to be used.
|
|
125
|
+
*/
|
|
109
126
|
export declare function rank(matches: FlowMatch[]): FlowMatch[];
|
|
110
127
|
/**
|
|
111
128
|
* `withSteps`: when the verdict is known, also return the best flow's steps and
|
package/dist/memory/recall.js
CHANGED
|
@@ -15,15 +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
|
+
import { valueRefsOf } from '../core/recording.js';
|
|
20
21
|
/**
|
|
21
|
-
* When a match by MEANING is good enough to act on
|
|
22
|
-
* a real 28-flow corpus
|
|
23
|
-
* 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
|
|
24
25
|
* goal the app doesn't have still lands near something. What does separate
|
|
25
|
-
* them is how far the top match is ahead of the runner-up.
|
|
26
|
-
*
|
|
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).
|
|
27
31
|
*/
|
|
28
32
|
export const MEANING = {
|
|
29
33
|
/** At or above this, the top flow is the answer. */
|
|
@@ -35,24 +39,46 @@ export const MEANING = {
|
|
|
35
39
|
};
|
|
36
40
|
/** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
|
|
37
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
|
+
}
|
|
38
52
|
/** Pure: the verdict for a ranked list of scores. Exported for tests. */
|
|
39
53
|
export function judge(scores, rule) {
|
|
40
54
|
const [top, second] = scores;
|
|
41
55
|
if (top === undefined)
|
|
42
56
|
return { verdict: 'unknown', why: 'this app has no flows yet' };
|
|
43
57
|
const f = (n) => n.toFixed(2);
|
|
44
|
-
if (top
|
|
45
|
-
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
|
+
}
|
|
46
61
|
if (top >= rule.good) {
|
|
47
|
-
// With only one flow there's no runner-up to beat, so only a strong match counts.
|
|
48
62
|
if (second === undefined)
|
|
49
63
|
return { verdict: 'unsure', why: `good match (${f(top)}), but only one flow to compare with` };
|
|
50
|
-
if (top - second >= rule.margin)
|
|
51
|
-
return { verdict: 'known', why: `good match (${f(top)}), clearly ahead of the next (${f(second)})` };
|
|
52
64
|
return { verdict: 'unsure', why: `good match (${f(top)}), but the next is close (${f(second)})` };
|
|
53
65
|
}
|
|
54
66
|
return { verdict: 'unknown', why: `nothing matches well (best ${f(top)})` };
|
|
55
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
|
+
}
|
|
56
82
|
const STOP = new Set(['a', 'an', 'the', 'to', 'my', 'of', 'for', 'and', 'in', 'on', 'as', 'i', 'me', 'it', 'is', 'with', 'at', 'up', 'out']);
|
|
57
83
|
const words = (s) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w && !STOP.has(w)));
|
|
58
84
|
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
@@ -69,14 +95,20 @@ export function wordScore(goal, flow) {
|
|
|
69
95
|
}
|
|
70
96
|
const toMatch = (f, score) => ({
|
|
71
97
|
slug: f.slug, title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
|
|
72
|
-
...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}),
|
|
98
|
+
...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}),
|
|
99
|
+
...(f.provenUpTo !== undefined ? { provenUpTo: f.provenUpTo } : {}),
|
|
100
|
+
...(f.requires?.length ? { requires: f.requires } : {}), ...(f.establishes?.length ? { establishes: f.establishes } : {}), score,
|
|
73
101
|
destructive: f.destructive, requiresSession: f.requiresSession,
|
|
74
102
|
});
|
|
75
103
|
/** Scores this close are a tie. */
|
|
76
104
|
const TIE = 0.005;
|
|
77
|
-
/**
|
|
105
|
+
/**
|
|
106
|
+
* Highest score first; on a tie, a proven flow ahead of an unproven one, then
|
|
107
|
+
* one a person recorded ahead of one an agent made — a person's recording is
|
|
108
|
+
* the better word on how the app is meant to be used.
|
|
109
|
+
*/
|
|
78
110
|
export function rank(matches) {
|
|
79
|
-
return [...matches].sort((a, b) => (Math.abs(a.score - b.score) <= TIE ? Number(b.proven) - Number(a.proven) || b.score - a.score : b.score - a.score));
|
|
111
|
+
return [...matches].sort((a, b) => (Math.abs(a.score - b.score) <= TIE ? Number(b.proven) - Number(a.proven) || Number(b.madeBy === 'user') - Number(a.madeBy === 'user') || b.score - a.score : b.score - a.score));
|
|
80
112
|
}
|
|
81
113
|
/** The verdict's reason, plus a warning when the flow it picked may not work. */
|
|
82
114
|
const withProven = (why, best) => best && !best.proven ? `${why} — but '${best.slug}' is unproven (${best.unprovenBecause ?? 'no passing run yet'}), so it may not work; a passing run proves it` : why;
|
|
@@ -98,7 +130,7 @@ async function plan(app, slug) {
|
|
|
98
130
|
...(s.valueRef ? { placeholder: s.valueRef } : s.value !== undefined ? { value: s.value } : s.action === 'goto' ? { value: s.url } : {}),
|
|
99
131
|
};
|
|
100
132
|
});
|
|
101
|
-
const refs =
|
|
133
|
+
const refs = valueRefsOf(flow.steps);
|
|
102
134
|
const found = valuesFromEnv(refs, app);
|
|
103
135
|
const needs = refs.map((placeholder) => ({ placeholder, readFrom: valueEnvNames(placeholder, app), set: placeholder in found }));
|
|
104
136
|
return { steps, ...(needs.length ? { needs } : {}) };
|
|
@@ -119,22 +151,30 @@ export async function recall(app, goal, opts = {}) {
|
|
|
119
151
|
return { goal, method: 'exact', verdict: 'known', best, why: withProven('named exactly', best), flows: [best], notes: [], ...(opts.withSteps ? await plan(app, best.slug) : {}) };
|
|
120
152
|
}
|
|
121
153
|
// 2. By meaning, if there's a model.
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const [
|
|
154
|
+
const cfg = embedderConfig();
|
|
155
|
+
if (cfg) {
|
|
156
|
+
const [vector] = await embed([goal], 'query', cfg);
|
|
157
|
+
const [flows, notes, rule] = await Promise.all([
|
|
125
158
|
vectorSearch(c.flows, app, vector, { limit }),
|
|
126
159
|
vectorSearch(c.notes, app, vector, { limit }),
|
|
160
|
+
cutoffsFor(app, cfg),
|
|
127
161
|
]);
|
|
128
162
|
const matches = rank(flows.map((f) => toMatch(f, f.score)));
|
|
129
|
-
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;
|
|
130
170
|
return {
|
|
131
|
-
goal, method: 'meaning', verdict, why:
|
|
171
|
+
goal, method: 'meaning', verdict, why, flows: matches, cutoffs: { ...cutoffs, source },
|
|
132
172
|
...(verdict === 'known' ? { best: matches[0], ...(opts.withSteps ? await plan(app, matches[0].slug) : {}) } : {}),
|
|
133
173
|
notes: notes.map((n) => ({ kind: n.kind, text: n.text, score: n.score })),
|
|
134
174
|
};
|
|
135
175
|
}
|
|
136
176
|
// 3. By words, with no model. Corpora are small, so scoring every flow is fine.
|
|
137
|
-
const all = await c.flows.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, destructive: 1, requiresSession: 1 } }).toArray();
|
|
177
|
+
const all = await c.flows.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, provenUpTo: 1, requires: 1, establishes: 1, destructive: 1, requiresSession: 1 } }).toArray();
|
|
138
178
|
const matches = all
|
|
139
179
|
.map((f) => toMatch(f, wordScore(goal, f)))
|
|
140
180
|
.filter((m) => m.score > 0);
|
|
@@ -9,16 +9,22 @@ import { collections } from '../store/db.js';
|
|
|
9
9
|
export async function vocabulary(app) {
|
|
10
10
|
const { flows, notes } = await collections();
|
|
11
11
|
const rows = await flows
|
|
12
|
-
.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, preconditions: 1, outcome: 1, steps: 1 } })
|
|
12
|
+
.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, preconditions: 1, outcome: 1, steps: 1, requires: 1, establishes: 1 } })
|
|
13
13
|
.sort({ kind: -1, slug: 1 })
|
|
14
14
|
.toArray();
|
|
15
15
|
const facts = await notes.find({ app, kind: 'fact' }, { projection: { text: 1 } }).toArray();
|
|
16
|
+
const stateOf = (f) => ({
|
|
17
|
+
...(f.requires?.length ? { requires: f.requires } : {}),
|
|
18
|
+
...(f.establishes?.length ? { establishes: f.establishes } : {}),
|
|
19
|
+
});
|
|
20
|
+
const states = [...new Set(rows.flatMap((f) => [...(f.requires ?? []), ...(f.establishes ?? [])]))].sort();
|
|
16
21
|
return {
|
|
17
22
|
segments: rows.filter((f) => f.kind === 'segment').map((f) => ({
|
|
18
23
|
slug: f.slug, title: f.title, intent: f.intent, steps: f.steps.length,
|
|
19
|
-
preconditions: f.preconditions, outcome: f.outcome || null,
|
|
24
|
+
preconditions: f.preconditions, outcome: f.outcome || null, ...stateOf(f),
|
|
20
25
|
})),
|
|
21
|
-
flows: rows.filter((f) => f.kind === 'recording').map((f) => ({ slug: f.slug, title: f.title, intent: f.intent })),
|
|
26
|
+
flows: rows.filter((f) => f.kind === 'recording').map((f) => ({ slug: f.slug, title: f.title, intent: f.intent, ...stateOf(f) })),
|
|
27
|
+
...(states.length ? { states } : {}),
|
|
22
28
|
facts: facts.map((n) => n.text),
|
|
23
29
|
};
|
|
24
30
|
}
|