@jeffawe/understudy 0.3.0 → 0.5.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/CHANGELOG.md +127 -0
- package/README.md +69 -160
- package/REASONER.md +76 -86
- package/dist/adapters/recorder/script.d.ts +25 -2
- package/dist/adapters/recorder/script.js +126 -31
- package/dist/core/outline.d.ts +43 -0
- package/dist/core/outline.js +121 -0
- package/dist/core/recording.d.ts +19 -1
- package/dist/core/recording.js +38 -2
- package/dist/core/replay.d.ts +62 -1
- package/dist/core/replay.js +162 -106
- package/dist/entry/cli.js +185 -30
- package/dist/entry/mcp.d.ts +2 -0
- package/dist/entry/mcp.js +128 -23
- package/dist/flows/destructive.js +1 -1
- package/dist/flows/distill.js +11 -6
- package/dist/flows/emit.d.ts +7 -0
- package/dist/flows/emit.js +26 -10
- package/dist/flows/execute.d.ts +12 -0
- package/dist/flows/execute.js +23 -16
- package/dist/flows/runs.d.ts +2 -0
- package/dist/flows/runs.js +7 -3
- package/dist/flows/save.d.ts +5 -2
- package/dist/flows/save.js +38 -23
- package/dist/flows/session.d.ts +176 -0
- package/dist/flows/session.js +383 -0
- package/dist/flows/variants.d.ts +81 -0
- package/dist/flows/variants.js +139 -0
- package/dist/memory/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +260 -0
- package/dist/memory/pages.d.ts +34 -0
- package/dist/memory/pages.js +60 -0
- package/dist/memory/recall.d.ts +87 -25
- package/dist/memory/recall.js +242 -45
- package/dist/plan/planner.d.ts +11 -1
- package/dist/plan/planner.js +36 -19
- package/dist/store/app-settings.d.ts +26 -0
- package/dist/store/app-settings.js +49 -0
- package/dist/store/db.js +8 -1
- package/dist/store/reembed.js +18 -7
- package/dist/store/types.d.ts +50 -0
- package/package.json +3 -2
|
@@ -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,260 @@
|
|
|
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 { MAIN } from '../flows/variants.js';
|
|
32
|
+
import { collections } from '../store/db.js';
|
|
33
|
+
import { embed, embedderConfig } from '../store/embed.js';
|
|
34
|
+
import { cutoffsFor, isKnown } from './recall.js';
|
|
35
|
+
/** Fewer than this many of either kind, and the fit isn't saved: too easy to fit by luck. */
|
|
36
|
+
export const MIN_GOALS = 5;
|
|
37
|
+
/** Below this many flows the scores bunch up; the fit is saved but flagged. */
|
|
38
|
+
export const FEW_FLOWS = 8;
|
|
39
|
+
/** Should recall call this one known? Only when the embedder ranked the right flow first. */
|
|
40
|
+
const shouldBeKnown = (s) => s.expect !== null && s.topFlow === s.expect;
|
|
41
|
+
/** A wrong "known" runs the wrong flow; a missed one is only shown. */
|
|
42
|
+
const COST_WRONG_KNOWN = 2;
|
|
43
|
+
const COST_MISSED = 1;
|
|
44
|
+
const STEP = 0.005;
|
|
45
|
+
const grid = (from, to) => {
|
|
46
|
+
const out = [];
|
|
47
|
+
for (let i = Math.round(from / STEP); i <= Math.round(to / STEP); i++)
|
|
48
|
+
out.push(Number((i * STEP).toFixed(3)));
|
|
49
|
+
return out;
|
|
50
|
+
};
|
|
51
|
+
/** How many samples a rule puts on the right side, and what its mistakes cost. */
|
|
52
|
+
export function score(samples, rule) {
|
|
53
|
+
let cost = 0;
|
|
54
|
+
const wrong = [];
|
|
55
|
+
for (const s of samples) {
|
|
56
|
+
const want = shouldBeKnown(s);
|
|
57
|
+
if (isKnown(s.top, s.second, rule) === want)
|
|
58
|
+
continue;
|
|
59
|
+
cost += want ? COST_MISSED : COST_WRONG_KNOWN;
|
|
60
|
+
wrong.push(s);
|
|
61
|
+
}
|
|
62
|
+
return { cost, correct: samples.length - wrong.length, wrong };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Pure: the cutoffs that cost least on these samples. Among equally good ones,
|
|
66
|
+
* the one whose decisions sit furthest from any cutoff — so a goal worded a
|
|
67
|
+
* little differently next time lands on the same side.
|
|
68
|
+
*/
|
|
69
|
+
export function fit(samples) {
|
|
70
|
+
const tops = samples.map((s) => s.top);
|
|
71
|
+
const gaps = samples.map((s) => (s.second === undefined ? -1 : s.top - s.second));
|
|
72
|
+
const want = samples.map(shouldBeKnown);
|
|
73
|
+
const n = samples.length;
|
|
74
|
+
const strongs = [...grid(0.5, 1), 1 + STEP]; // the last: never known on score alone
|
|
75
|
+
const margins = grid(0, 0.5);
|
|
76
|
+
let best;
|
|
77
|
+
for (const strong of strongs) {
|
|
78
|
+
for (const good of grid(0.5, Math.min(strong, 1))) {
|
|
79
|
+
for (const margin of margins) {
|
|
80
|
+
let cost = 0;
|
|
81
|
+
let wrong = 0;
|
|
82
|
+
for (let i = 0; i < n; i++) {
|
|
83
|
+
const t = tops[i];
|
|
84
|
+
const k = t >= strong || (t >= good && gaps[i] >= 0 && gaps[i] >= margin);
|
|
85
|
+
if (k !== want[i]) {
|
|
86
|
+
wrong++;
|
|
87
|
+
cost += want[i] ? COST_MISSED : COST_WRONG_KNOWN;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (best && cost > best.cost)
|
|
91
|
+
continue;
|
|
92
|
+
// How close the nearest decision is to flipping: smallest distance to a cutoff it was tested against.
|
|
93
|
+
let clearance = Infinity;
|
|
94
|
+
let spread = 0;
|
|
95
|
+
for (let i = 0; i < n; i++) {
|
|
96
|
+
const t = tops[i];
|
|
97
|
+
let d = Math.abs(t - strong);
|
|
98
|
+
if (t < strong)
|
|
99
|
+
d = Math.min(d, Math.abs(t - good));
|
|
100
|
+
if (t < strong && t >= good && gaps[i] >= 0)
|
|
101
|
+
d = Math.min(d, Math.abs(gaps[i] - margin));
|
|
102
|
+
clearance = Math.min(clearance, d);
|
|
103
|
+
spread += d;
|
|
104
|
+
}
|
|
105
|
+
if (!best || cost < best.cost || clearance > best.clearance + 1e-9 || (Math.abs(clearance - best.clearance) <= 1e-9 && spread > best.spread)) {
|
|
106
|
+
best = { strong, good, margin, cost, correct: n - wrong, clearance, spread };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const { clearance: _c, spread: _s, ...out } = best;
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
const cosine = (a, b) => {
|
|
115
|
+
let dot = 0, na = 0, nb = 0;
|
|
116
|
+
for (let i = 0; i < a.length; i++) {
|
|
117
|
+
dot += a[i] * b[i];
|
|
118
|
+
na += a[i] * a[i];
|
|
119
|
+
nb += b[i] * b[i];
|
|
120
|
+
}
|
|
121
|
+
return dot / (Math.sqrt(na * nb) || 1);
|
|
122
|
+
};
|
|
123
|
+
/** What $vectorSearch reports for cosine similarity. */
|
|
124
|
+
const searchScore = (a, b) => (1 + cosine(a, b)) / 2;
|
|
125
|
+
const norm = (s) => s.trim().toLowerCase();
|
|
126
|
+
/** Fit, report, and (unless dryRun, or there's too little to go on) keep the cutoffs. */
|
|
127
|
+
export async function calibrate(app, input = {}) {
|
|
128
|
+
const cfg = embedderConfig();
|
|
129
|
+
if (!cfg)
|
|
130
|
+
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');
|
|
131
|
+
const c = await collections();
|
|
132
|
+
// Main flows only: a variant shares its flow's name, and would be scored as a second, competing answer.
|
|
133
|
+
const flows = await c.flows.find({ app, ...MAIN }, { projection: { slug: 1, title: 1, from: 1, embedding: 1 } }).toArray();
|
|
134
|
+
if (!flows.length)
|
|
135
|
+
throw new Error(`no flows for '${app}' — save some first`);
|
|
136
|
+
const unembedded = flows.filter((f) => f.embedding?.length !== cfg.dims);
|
|
137
|
+
if (unembedded.length) {
|
|
138
|
+
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`);
|
|
139
|
+
}
|
|
140
|
+
const slugs = new Set(flows.map((f) => f.slug));
|
|
141
|
+
const names = new Set(flows.flatMap((f) => [norm(f.slug), norm(f.title)]));
|
|
142
|
+
// Goals: the ones kept, plus the ones given now. A flow that no longer exists drops out.
|
|
143
|
+
const appDoc = await c.apps.findOne({ slug: app }, { projection: { calibrationGoals: 1 } });
|
|
144
|
+
const kept = appDoc?.calibrationGoals ?? { known: [], unknown: [] };
|
|
145
|
+
const badSlugs = [...new Set((input.goals?.known ?? []).map((k) => k.flow).filter((f) => !slugs.has(f)))];
|
|
146
|
+
if (badSlugs.length)
|
|
147
|
+
throw new Error(`no flow ${badSlugs.map((s) => `'${s}'`).join(', ')} in ${app} — known goals name a flow by its slug (understudy flows ${app})`);
|
|
148
|
+
const known = new Map();
|
|
149
|
+
for (const k of [...kept.known, ...(input.goals?.known ?? [])])
|
|
150
|
+
if (slugs.has(k.flow) && k.goal.trim())
|
|
151
|
+
known.set(norm(k.goal), { flow: k.flow, goal: k.goal.trim() });
|
|
152
|
+
const unknown = new Map();
|
|
153
|
+
for (const u of [...kept.unknown, ...(input.goals?.unknown ?? [])])
|
|
154
|
+
if (u.trim())
|
|
155
|
+
unknown.set(norm(u), u.trim());
|
|
156
|
+
const skippedExact = [...known.keys(), ...unknown.keys()].filter((g) => names.has(g)).length;
|
|
157
|
+
for (const g of names) {
|
|
158
|
+
known.delete(g);
|
|
159
|
+
unknown.delete(g);
|
|
160
|
+
}
|
|
161
|
+
const clash = [...known.keys()].filter((g) => unknown.has(g));
|
|
162
|
+
if (clash.length)
|
|
163
|
+
throw new Error(`listed as both known and unknown: ${clash.map((g) => `"${g}"`).join(', ')}`);
|
|
164
|
+
const goals = { known: [...known.values()], unknown: [...unknown.values()] };
|
|
165
|
+
// Free known goals: what runs were asked for, bound to a flow, and passed.
|
|
166
|
+
const fromRuns = new Map();
|
|
167
|
+
const runs = await c.runs.find({ app, mode: 'run', status: 'passed' }, { projection: { goal: 1, plan: 1, planning: 1 } }).toArray();
|
|
168
|
+
for (const r of runs) {
|
|
169
|
+
const pairs = r.planning?.subGoals && r.planning.bound?.length === r.planning.subGoals.length
|
|
170
|
+
? r.planning.subGoals.map((g, i) => [g, r.planning.bound[i]])
|
|
171
|
+
: r.plan.length === 1 ? [[r.goal, r.plan[0]]] : [];
|
|
172
|
+
for (const [g, flow] of pairs) {
|
|
173
|
+
if (flow && slugs.has(flow) && !names.has(norm(g)) && !known.has(norm(g)) && !unknown.has(norm(g)))
|
|
174
|
+
fromRuns.set(norm(g), JSON.stringify([g, flow]));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// Embed every goal once, in as few requests as possible.
|
|
178
|
+
const titleTaken = (title, slug) => flows.some((f) => f.slug !== slug && norm(f.title) === norm(title));
|
|
179
|
+
const leftOut = flows.length > 1 && goals.unknown.length < MIN_GOALS ? flows.filter((f) => !titleTaken(f.title, f.slug)) : [];
|
|
180
|
+
/** With `slug` left out: it, the recording it was cut from, and segments cut from it. */
|
|
181
|
+
const related = (slug) => {
|
|
182
|
+
const left = flows.find((f) => f.slug === slug);
|
|
183
|
+
return new Set([slug, ...(left?.from ? [left.from.flow] : []), ...flows.filter((f) => f.from?.flow === slug).map((f) => f.slug)]);
|
|
184
|
+
};
|
|
185
|
+
const runPairs = [...fromRuns.values()].map((p) => JSON.parse(p));
|
|
186
|
+
const texts = [...new Set([...goals.known.map((k) => k.goal), ...goals.unknown, ...runPairs.map(([g]) => g), ...leftOut.map((f) => f.title)])];
|
|
187
|
+
const vectors = new Map();
|
|
188
|
+
const embedded = texts.length ? await embed(texts, 'query', cfg) : [];
|
|
189
|
+
texts.forEach((t, i) => vectors.set(t, embedded[i]));
|
|
190
|
+
const sample = (goal, expect, from, without) => {
|
|
191
|
+
const q = vectors.get(goal);
|
|
192
|
+
const skip = without ? related(without) : undefined;
|
|
193
|
+
const ranked = flows
|
|
194
|
+
.filter((f) => !skip?.has(f.slug))
|
|
195
|
+
.map((f) => ({ slug: f.slug, score: searchScore(q, f.embedding) }))
|
|
196
|
+
.sort((a, b) => b.score - a.score);
|
|
197
|
+
return {
|
|
198
|
+
goal, expect, from, ...(without ? { without } : {}),
|
|
199
|
+
...(ranked[0] ? { topFlow: ranked[0].slug, top: ranked[0].score } : { top: 0 }),
|
|
200
|
+
...(ranked[1] ? { second: ranked[1].score } : {}),
|
|
201
|
+
};
|
|
202
|
+
};
|
|
203
|
+
const samples = [
|
|
204
|
+
...goals.known.map((k) => sample(k.goal, k.flow, 'goals file')),
|
|
205
|
+
...runPairs.map(([g, flow]) => sample(g, flow, 'run')),
|
|
206
|
+
...goals.unknown.map((g) => sample(g, null, 'goals file')),
|
|
207
|
+
...leftOut.map((f) => sample(f.title, null, 'left out', f.slug)),
|
|
208
|
+
];
|
|
209
|
+
const nKnown = samples.filter((s) => s.expect !== null).length;
|
|
210
|
+
const nUnknown = samples.length - nKnown;
|
|
211
|
+
const current = await cutoffsFor(app, cfg);
|
|
212
|
+
const fitted = fit(samples);
|
|
213
|
+
const after = { strong: fitted.strong, good: fitted.good, margin: fitted.margin };
|
|
214
|
+
const { wrong } = score(samples, after);
|
|
215
|
+
const notes = [];
|
|
216
|
+
if (skippedExact)
|
|
217
|
+
notes.push(`${skippedExact} goal(s) skipped: they are a flow's exact name, which recall matches without scores`);
|
|
218
|
+
if (nKnown < MIN_GOALS)
|
|
219
|
+
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)`);
|
|
220
|
+
if (nUnknown < MIN_GOALS)
|
|
221
|
+
notes.push(`only ${nUnknown} unknown goal(s) — need ${MIN_GOALS}+: add goals that sound like the app but that it has no flow for`);
|
|
222
|
+
if (leftOut.length)
|
|
223
|
+
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`);
|
|
224
|
+
if (flows.length < FEW_FLOWS)
|
|
225
|
+
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`);
|
|
226
|
+
const enough = nKnown >= MIN_GOALS && nUnknown >= MIN_GOALS;
|
|
227
|
+
const saved = enough && !input.dryRun;
|
|
228
|
+
// The goals are worth keeping even when they're too few to fit on yet.
|
|
229
|
+
if (!input.dryRun) {
|
|
230
|
+
const cutoffs = { ...after, model: cfg.model, dims: cfg.dims, fittedAt: new Date(), goals: { known: nKnown, unknown: nUnknown }, correct: samples.length - wrong.length };
|
|
231
|
+
await c.apps.updateOne({ slug: app }, { $set: { calibrationGoals: goals, ...(saved ? { cutoffs } : {}) }, $setOnInsert: { slug: app, name: app, urls: {}, createdAt: new Date() } }, { upsert: true });
|
|
232
|
+
}
|
|
233
|
+
const r3 = (x) => Number(x.toFixed(3));
|
|
234
|
+
return {
|
|
235
|
+
app, model: cfg.model, flows: flows.length,
|
|
236
|
+
goals: { known: goals.known.length, unknown: goals.unknown.length, fromRuns: runPairs.length, leftOut: leftOut.length },
|
|
237
|
+
before: { strong: current.strong, good: current.good, margin: current.margin, source: current.source, correct: score(samples, current).correct },
|
|
238
|
+
after: { ...after, correct: samples.length - wrong.length },
|
|
239
|
+
total: samples.length,
|
|
240
|
+
mistakes: wrong.map((s) => ({
|
|
241
|
+
goal: s.from === 'left out' ? `${s.goal} (with ${s.without} left out)` : s.goal,
|
|
242
|
+
expected: s.expect, ...(s.topFlow ? { top: s.topFlow } : {}), score: r3(s.top), ...(s.second !== undefined ? { next: r3(s.second) } : {}),
|
|
243
|
+
verdict: isKnown(s.top, s.second, after) ? 'known' : 'not known',
|
|
244
|
+
})),
|
|
245
|
+
misranked: samples.filter((s) => s.expect !== null && s.topFlow !== s.expect).map((s) => ({ goal: s.goal, expected: s.expect, ...(s.topFlow ? { top: s.topFlow } : {}) })),
|
|
246
|
+
saved, notes,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/** After `reembed`: re-fit every app that has goals kept, for the model now configured. */
|
|
250
|
+
export async function recalibrateAll() {
|
|
251
|
+
const { apps, flows } = await collections();
|
|
252
|
+
const withGoals = (await apps.find({ calibrationGoals: { $exists: true } }, { projection: { slug: 1 } }).toArray()).map((a) => a.slug);
|
|
253
|
+
const refitted = [];
|
|
254
|
+
for (const app of withGoals) {
|
|
255
|
+
if (await flows.findOne({ app }))
|
|
256
|
+
refitted.push(await calibrate(app));
|
|
257
|
+
}
|
|
258
|
+
const all = await flows.distinct('app');
|
|
259
|
+
return { refitted, withoutGoals: all.filter((a) => !withGoals.includes(a)) };
|
|
260
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What pages looked like: each page's controls (core/outline.ts) kept on the
|
|
3
|
+
* page map whenever a run or a session sees it, so the next visit can say what
|
|
4
|
+
* is different — "a follow-up question appeared on /intake" — instead of an
|
|
5
|
+
* agent re-reading the whole page, or trusting a flow recorded against a page
|
|
6
|
+
* that has since changed.
|
|
7
|
+
*
|
|
8
|
+
* Kept per page fingerprint (`sig`); compared across fingerprints of the same
|
|
9
|
+
* address, because a page that changed usually changed its fingerprint too.
|
|
10
|
+
*/
|
|
11
|
+
import { type Control, type OutlineDiff } from '../core/outline.js';
|
|
12
|
+
import type { Flow } from '../store/types.js';
|
|
13
|
+
/** `/inventory.html#bf3dd322` → `/inventory.html` */
|
|
14
|
+
export declare const pageOf: (sig: string) => string;
|
|
15
|
+
/** Keep what a page looks like now. */
|
|
16
|
+
export declare function rememberOutline(app: string, sig: string, outline: Control[], at?: Date): Promise<void>;
|
|
17
|
+
export interface PageChange extends OutlineDiff {
|
|
18
|
+
/** The page's address pattern. */
|
|
19
|
+
page: string;
|
|
20
|
+
/** When it was last seen looking different from now. */
|
|
21
|
+
since: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* What differs on this page from the last time it was seen looking otherwise:
|
|
25
|
+
* the newest kept outline of the same address under another fingerprint.
|
|
26
|
+
* Nothing when it has never been seen, or never seen any other way.
|
|
27
|
+
*/
|
|
28
|
+
export declare function changesSince(app: string, sig: string, outline: Control[]): Promise<PageChange | undefined>;
|
|
29
|
+
/**
|
|
30
|
+
* The flow's pages that have been seen looking different from what the flow
|
|
31
|
+
* expects, AFTER it last passed — a run of another flow, or a session, got
|
|
32
|
+
* there first. The flow may still work; it is worth checking before trusting.
|
|
33
|
+
*/
|
|
34
|
+
export declare function flowPagesChanged(app: string, flow: Pick<Flow, 'steps'>, lastPassed?: string): Promise<PageChange[]>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What pages looked like: each page's controls (core/outline.ts) kept on the
|
|
3
|
+
* page map whenever a run or a session sees it, so the next visit can say what
|
|
4
|
+
* is different — "a follow-up question appeared on /intake" — instead of an
|
|
5
|
+
* agent re-reading the whole page, or trusting a flow recorded against a page
|
|
6
|
+
* that has since changed.
|
|
7
|
+
*
|
|
8
|
+
* Kept per page fingerprint (`sig`); compared across fingerprints of the same
|
|
9
|
+
* address, because a page that changed usually changed its fingerprint too.
|
|
10
|
+
*/
|
|
11
|
+
import { collections } from '../store/db.js';
|
|
12
|
+
import { diffOutline } from '../core/outline.js';
|
|
13
|
+
/** `/inventory.html#bf3dd322` → `/inventory.html` */
|
|
14
|
+
export const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
|
|
15
|
+
/** Keep what a page looks like now. */
|
|
16
|
+
export async function rememberOutline(app, sig, outline, at = new Date()) {
|
|
17
|
+
const { pages } = await collections();
|
|
18
|
+
await pages.updateOne({ app, sig }, { $set: { outline, outlineAt: at, lastSeen: at }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: at } }, { upsert: true });
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* What differs on this page from the last time it was seen looking otherwise:
|
|
22
|
+
* the newest kept outline of the same address under another fingerprint.
|
|
23
|
+
* Nothing when it has never been seen, or never seen any other way.
|
|
24
|
+
*/
|
|
25
|
+
export async function changesSince(app, sig, outline) {
|
|
26
|
+
const { pages } = await collections();
|
|
27
|
+
const before = await pages.findOne({ app, urlPattern: pageOf(sig), sig: { $ne: sig }, outline: { $exists: true } }, { sort: { outlineAt: -1 }, projection: { outline: 1, outlineAt: 1 } });
|
|
28
|
+
if (!before?.outline)
|
|
29
|
+
return undefined;
|
|
30
|
+
const d = diffOutline(before.outline, outline, 12);
|
|
31
|
+
if (!d.appeared.length && !d.gone.length && !d.changed.length)
|
|
32
|
+
return undefined;
|
|
33
|
+
return { page: pageOf(sig), since: (before.outlineAt ?? new Date(0)).toISOString(), ...d };
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The flow's pages that have been seen looking different from what the flow
|
|
37
|
+
* expects, AFTER it last passed — a run of another flow, or a session, got
|
|
38
|
+
* there first. The flow may still work; it is worth checking before trusting.
|
|
39
|
+
*/
|
|
40
|
+
export async function flowPagesChanged(app, flow, lastPassed) {
|
|
41
|
+
const expected = [...new Set(flow.steps.map((s) => s.expectedSig).filter((s) => Boolean(s)))];
|
|
42
|
+
if (!expected.length)
|
|
43
|
+
return [];
|
|
44
|
+
const { pages } = await collections();
|
|
45
|
+
const after = lastPassed ? new Date(lastPassed) : new Date(0);
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const page of [...new Set(expected.map(pageOf))]) {
|
|
48
|
+
const ours = expected.filter((s) => pageOf(s) === page);
|
|
49
|
+
const newer = await pages.findOne({ app, urlPattern: page, sig: { $nin: ours }, outline: { $exists: true }, outlineAt: { $gt: after } }, { sort: { outlineAt: -1 }, projection: { outline: 1, outlineAt: 1 } });
|
|
50
|
+
if (!newer?.outline)
|
|
51
|
+
continue;
|
|
52
|
+
const known = await pages.findOne({ app, sig: { $in: ours }, outline: { $exists: true } }, { sort: { outlineAt: -1 }, projection: { outline: 1 } });
|
|
53
|
+
const d = known?.outline
|
|
54
|
+
? diffOutline(known.outline, newer.outline, 8)
|
|
55
|
+
: { appeared: [], gone: [], changed: ['it looks different, and how it looked before was never kept'] };
|
|
56
|
+
if (d.appeared.length || d.gone.length || d.changed.length)
|
|
57
|
+
out.push({ page, since: newer.outlineAt.toISOString(), ...d });
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
package/dist/memory/recall.d.ts
CHANGED
|
@@ -14,9 +14,13 @@
|
|
|
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, Step } from '../store/types.js';
|
|
18
|
+
import { type PageChange } from './pages.js';
|
|
19
|
+
import { type EmbedderConfig } from '../store/embed.js';
|
|
18
20
|
export interface FlowMatch {
|
|
19
21
|
slug: string;
|
|
22
|
+
/** This is the variant's copy of the flow, not the main one. */
|
|
23
|
+
variant?: string;
|
|
20
24
|
title: string;
|
|
21
25
|
kind: Flow['kind'];
|
|
22
26
|
madeBy: 'user' | 'agent';
|
|
@@ -32,6 +36,18 @@ export interface FlowMatch {
|
|
|
32
36
|
score: number;
|
|
33
37
|
destructive: boolean;
|
|
34
38
|
requiresSession: boolean;
|
|
39
|
+
/** When a run last got through this flow (up to its commit counts). */
|
|
40
|
+
lastPassed?: string;
|
|
41
|
+
/** When a run last failed inside this flow, and at which of its steps. */
|
|
42
|
+
lastFailed?: {
|
|
43
|
+
at: string;
|
|
44
|
+
step: number;
|
|
45
|
+
error?: string;
|
|
46
|
+
};
|
|
47
|
+
/** Its newest pass took a changed path that nobody has accepted yet. */
|
|
48
|
+
pathNotAccepted?: true;
|
|
49
|
+
/** Branches with their own copy of this flow — other than the one asked for. Pass one as `variant` to use it. */
|
|
50
|
+
variants?: string[];
|
|
35
51
|
}
|
|
36
52
|
/** One step of the flow to run, in a form an agent can drive from directly. */
|
|
37
53
|
export interface BriefStep {
|
|
@@ -39,16 +55,37 @@ export interface BriefStep {
|
|
|
39
55
|
action: string;
|
|
40
56
|
role?: string;
|
|
41
57
|
name?: string;
|
|
42
|
-
/**
|
|
58
|
+
/** The name must match exactly. */
|
|
59
|
+
exact?: boolean;
|
|
60
|
+
/** Also tells apart elements that share a role and name. */
|
|
43
61
|
testId?: string;
|
|
62
|
+
/** The attribute holding the test id, when it was recorded (`data-test`, …). */
|
|
63
|
+
testIdAttr?: string;
|
|
64
|
+
/** How to find it when there's no role + name, or test id. */
|
|
44
65
|
css?: string;
|
|
66
|
+
/** The iframe it's in: matches the end of the frame's name, or part of its address. */
|
|
67
|
+
frameHint?: string;
|
|
45
68
|
/** Which of several matching elements (0-based). */
|
|
46
69
|
nth?: number;
|
|
47
70
|
/** A literal value to type or select, or the address for a goto. */
|
|
48
71
|
value?: string;
|
|
49
72
|
/** A login value that was never stored — see `needs` for where it is. */
|
|
50
73
|
placeholder?: string;
|
|
74
|
+
/**
|
|
75
|
+
* The rest of what replay reads, under the stored names: how to match (`by`,
|
|
76
|
+
* `scope`, `hasText`, `nameRegex`, `force`), what an `assert` checks, when a
|
|
77
|
+
* `human` step is done (`untilText`, …), what a `wait_response` expects.
|
|
78
|
+
*/
|
|
79
|
+
hints?: Record<string, unknown>;
|
|
51
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Pure: a stored step as an agent gets it. Short — css is left out when there's
|
|
83
|
+
* a better way to find the element — but nothing that changes which element is
|
|
84
|
+
* meant, or what counts as passing, may be dropped.
|
|
85
|
+
*/
|
|
86
|
+
export declare function briefStep(s: Step, n: number): BriefStep;
|
|
87
|
+
/** Pure: a brief step as one line for a person (`recall --steps`), leaving nothing in it out. */
|
|
88
|
+
export declare function stepLine(s: BriefStep): string;
|
|
52
89
|
/** A login value the flow needs: where it's set, and whether it is — never the value. */
|
|
53
90
|
export interface Need {
|
|
54
91
|
placeholder: string;
|
|
@@ -76,38 +113,49 @@ export interface Recall {
|
|
|
76
113
|
why: string;
|
|
77
114
|
flows: FlowMatch[];
|
|
78
115
|
notes: NoteMatch[];
|
|
116
|
+
/** Matching by meaning: the cutoffs the verdict used, and where they came from. */
|
|
117
|
+
cutoffs?: Cutoffs & {
|
|
118
|
+
source: CutoffSource;
|
|
119
|
+
};
|
|
120
|
+
/** When the best flow is a variant's copy: how its steps differ from the main flow's. */
|
|
121
|
+
differsFromMain?: string[];
|
|
122
|
+
/** The best flow's pages, seen looking different since it last passed. */
|
|
123
|
+
pagesChanged?: PageChange[];
|
|
79
124
|
}
|
|
80
125
|
/**
|
|
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
|
|
126
|
+
* When a match by MEANING is good enough to act on — the built-in cutoffs, for
|
|
127
|
+
* voyage-4-lite. Set by hand 2026-11-18 on a real 28-flow corpus (15 known
|
|
128
|
+
* goals, 14 plausible unknown ones): no single score separates them, because a
|
|
84
129
|
* 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
|
-
*
|
|
130
|
+
* them is how far the top match is ahead of the runner-up.
|
|
131
|
+
*
|
|
132
|
+
* Other models score on other scales (mxbai-embed-large puts unrelated goals
|
|
133
|
+
* at 0.72–0.80), so `understudy calibrate` fits these per app and model, and
|
|
134
|
+
* recall uses the fitted ones when there are any (see cutoffsFor).
|
|
87
135
|
*/
|
|
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
|
-
};
|
|
136
|
+
export declare const MEANING: Cutoffs;
|
|
96
137
|
/** 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
|
-
|
|
138
|
+
export declare const WORDS: Cutoffs;
|
|
139
|
+
/**
|
|
140
|
+
* Pure: is the top flow the answer? The whole rule, in one place — judge
|
|
141
|
+
* explains it, calibrate fits it. With only one flow there's no runner-up to
|
|
142
|
+
* beat, so only a strong match counts.
|
|
143
|
+
*/
|
|
144
|
+
export declare function isKnown(top: number, second: number | undefined, rule: Cutoffs): boolean;
|
|
102
145
|
/** 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
|
-
}): {
|
|
146
|
+
export declare function judge(scores: number[], rule: Cutoffs): {
|
|
108
147
|
verdict: Verdict;
|
|
109
148
|
why: string;
|
|
110
149
|
};
|
|
150
|
+
/**
|
|
151
|
+
* Which cutoffs recall uses with this model: fitted for this app; else fitted
|
|
152
|
+
* for another app with the same model (better than another model's numbers);
|
|
153
|
+
* else the built-in ones, which were set for voyage-4-lite.
|
|
154
|
+
*/
|
|
155
|
+
export declare function cutoffsFor(app: string, cfg: Pick<EmbedderConfig, 'model' | 'dims'>): Promise<Cutoffs & {
|
|
156
|
+
source: CutoffSource;
|
|
157
|
+
}>;
|
|
158
|
+
export type CutoffSource = 'this app' | 'another app' | 'built-in' | 'uncalibrated';
|
|
111
159
|
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
112
160
|
export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title' | 'intent'>): number;
|
|
113
161
|
/**
|
|
@@ -116,6 +164,19 @@ export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title
|
|
|
116
164
|
* the better word on how the app is meant to be used.
|
|
117
165
|
*/
|
|
118
166
|
export declare function rank(matches: FlowMatch[]): FlowMatch[];
|
|
167
|
+
/**
|
|
168
|
+
* The verdict's reason, plus a warning when the flow it picked may not work:
|
|
169
|
+
* unproven, its last run failed, or it last passed on a path nobody accepted.
|
|
170
|
+
* A confident match on a stale flow is the most misleading thing recall can say.
|
|
171
|
+
*/
|
|
172
|
+
export declare function withWarnings(why: string, best: FlowMatch | undefined, now?: number): string;
|
|
173
|
+
/**
|
|
174
|
+
* Each flow's last pass and last failure, from recent runs. A run of a plan
|
|
175
|
+
* counts for a flow only if it got to that flow: a failure is the flow's when
|
|
176
|
+
* the first failed step is inside its steps (`starts`), and a pass up to a
|
|
177
|
+
* commit counts, since that is all a commit-shaped flow is ever run to.
|
|
178
|
+
*/
|
|
179
|
+
export declare function withHistory(app: string, matches: FlowMatch[], variant?: string): Promise<FlowMatch[]>;
|
|
119
180
|
/**
|
|
120
181
|
* `withSteps`: when the verdict is known, also return the best flow's steps and
|
|
121
182
|
* the login values it needs — what an agent driving the flow itself wants. Off
|
|
@@ -124,4 +185,5 @@ export declare function rank(matches: FlowMatch[]): FlowMatch[];
|
|
|
124
185
|
export declare function recall(app: string, goal: string, opts?: {
|
|
125
186
|
limit?: number;
|
|
126
187
|
withSteps?: boolean;
|
|
188
|
+
variant?: string;
|
|
127
189
|
}): Promise<Recall>;
|