@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/dist/entry/cli.js CHANGED
@@ -21,9 +21,9 @@ import { join, resolve as resolvePath } from 'node:path';
21
21
  import { existsSync } from 'node:fs';
22
22
  import { chromium } from 'playwright';
23
23
  import { emitFlow } from '../flows/emit.js';
24
- import { recordingFrom, proveAndSave, proveByRun } from '../flows/save.js';
25
- import { recordRun } from '../flows/runs.js';
26
- import { listFindings } from '../flows/findings.js';
24
+ import { editFlow, recordingFrom, proveAndSave, proveByRun, proveFlow } from '../flows/save.js';
25
+ import { acceptPaths, recordRun } from '../flows/runs.js';
26
+ import { listFindings, triage } from '../flows/findings.js';
27
27
  import { VERSION } from './version.js';
28
28
  import { recall } from '../memory/recall.js';
29
29
  import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
@@ -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
@@ -54,6 +56,11 @@ COMMANDS
54
56
  flows <app> list an app's saved flows and how each last ran
55
57
  replay <hash> re-run a recording file headless
56
58
  replay <app> <flow> re-run a saved flow; records the run, drift and findings
59
+ prove <app> <flow> prove a saved flow where it stands; one that buys something
60
+ is replayed up to that step, checked, and never pressed
61
+ edit <app> <flow> --before <n> --step '<json>'
62
+ add a step to a saved flow: a person's step or a wait, e.g.
63
+ '{"action":"human","value":"Accept the visit","hints":{"untilText":"Accepted"}}'
57
64
  findings <app> what looked broken, most severe first
58
65
  recall <app> "<goal>" what memory knows about a goal — nothing runs
59
66
  run <app> "<goal>" find the flow that does the goal, and run it
@@ -93,6 +100,8 @@ SAVE
93
100
 
94
101
  FINDINGS
95
102
  --all include findings already triaged
103
+ --triage <fp>=<verdict> route a finding: issue, lesson, noise — or expected,
104
+ for a changed path the app made on purpose (repeatable)
96
105
 
97
106
  RUN
98
107
  --sub-goal <text> plan across several flows, in this order (repeatable)
@@ -104,6 +113,13 @@ EMIT
104
113
  --framework <name> playwright-ts (default) or cypress-js
105
114
  --out <file> write to a file instead of printing
106
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
+
107
123
  DISTILL
108
124
  --save <file> store the agent's answer (validated first)
109
125
 
@@ -221,6 +237,70 @@ async function cmdReembed() {
221
237
  const { reembed } = await import('../store/reembed.js');
222
238
  const r = await reembed();
223
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;
224
304
  }
225
305
  // --- config ------------------------------------------------------------------
226
306
  /**
@@ -491,7 +571,7 @@ async function cmdImport(positional, flags) {
491
571
  */
492
572
  async function executeWithReport(recording, flags, opts) {
493
573
  const values = valuesFromFlags(flags);
494
- const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons }))
574
+ const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons, ...personAtTerminal() }))
495
575
  .catch((e) => fail(e.message));
496
576
  if (x.sessionRestoredFrom)
497
577
  console.log(`session: restored (saved ${x.sessionRestoredFrom})`);
@@ -654,7 +734,7 @@ async function reportPlan(state, flags) {
654
734
  }
655
735
  console.log();
656
736
  const values = valuesFromFlags(flags);
657
- const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed') }))
737
+ const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed'), ...personAtTerminal() }))
658
738
  .catch((e) => fail(e.message));
659
739
  if (executed.lessons?.fired)
660
740
  console.log(`lessons ${executed.lessons.fired} fired, ${executed.lessons.helped} on steps that have failed before\n`);
@@ -717,6 +797,7 @@ function printReplay(result) {
717
797
  s.ambiguousByName && `ambiguous: ${s.ambiguousByName.matched} by name, resolved via ${s.ambiguousByName.disambiguatedBy}`,
718
798
  s.roleHadNoMatch && `role matched nothing, fell back to ${s.roleHadNoMatch.fellBackTo}`,
719
799
  s.roundTripMismatch && `value did not survive: wrote "${s.roundTripMismatch.expected}", read "${s.roundTripMismatch.actual}"`,
800
+ s.held && 'stopped here: its commit — found ready, not pressed',
720
801
  s.error,
721
802
  ].filter(Boolean).join('; ');
722
803
  console.log(` ${String(s.seq).padStart(2)} ${s.ok ? 'ok ' : 'FAIL'} ${s.action.padEnd(7)} ${(s.sig ?? '').padEnd(28)} ${notes}`);
@@ -732,6 +813,8 @@ function printReplay(result) {
732
813
  /** What recording the run added: drift against earlier runs, and findings. */
733
814
  function printRunReport(run) {
734
815
  const { drift } = run;
816
+ if (run.pending)
817
+ console.log('\npath CHANGED, not accepted yet — it joins the history once you triage its finding: understudy findings <app> --triage <fp>=expected');
735
818
  if (drift.notCompared)
736
819
  console.log(`\ndrift not compared — ${drift.notCompared}`);
737
820
  else if (drift.firstRun)
@@ -786,17 +869,41 @@ async function askYesNo(question, byDefault = false) {
786
869
  const answer = (await ask(`${question} ${byDefault ? '[Y/n]' : '[y/N]'} `)).trim();
787
870
  return answer ? /^y(es)?$/i.test(answer) : byDefault;
788
871
  }
789
- /** Ask for a line in the terminal. */
790
- async function ask(question) {
872
+ /** Ask for a line in the terminal. A `signal` withdraws the question. */
873
+ async function ask(question, signal) {
791
874
  const { createInterface } = await import('node:readline/promises');
792
875
  const rl = createInterface({ input: process.stdin, output: process.stdout });
793
876
  try {
794
- return await rl.question(question);
877
+ return await rl.question(question, signal ? { signal } : {});
795
878
  }
796
879
  finally {
797
880
  rl.close();
798
881
  }
799
882
  }
883
+ /**
884
+ * The terminal as the person a run asks: at a human step, and — in a visible
885
+ * browser — at a step that failed. Nothing to ask without a terminal.
886
+ */
887
+ function personAtTerminal() {
888
+ if (!process.stdin.isTTY)
889
+ return {};
890
+ return {
891
+ onHuman: async (req, signal) => {
892
+ console.log(`\nyour turn step ${req.seq}: ${req.instruction}`);
893
+ if (req.until)
894
+ console.log(` it carries on by itself once the page shows ${req.until.text ? `"${req.until.text}"` : req.until.url}`);
895
+ const line = await ask(' press Enter when it is done, or type "abort": ', signal).catch(() => '');
896
+ if (signal.aborted)
897
+ console.log('\n the page shows it done — carrying on');
898
+ return /^abort$/i.test(line.trim()) ? { action: 'abort', reason: 'aborted at the terminal' } : { action: 'done' };
899
+ },
900
+ onStuck: async (st) => {
901
+ console.log(`\nstuck step ${st.seq} (${st.action}${st.target ? ` "${st.target}"` : ''}) failed: ${st.error}`);
902
+ const yes = await askYesNo(' do it by hand in the browser window, then carry on?');
903
+ return yes ? 'done' : 'abort';
904
+ },
905
+ };
906
+ }
800
907
  /** Ask for a line without showing it (a password): each key shows as *. */
801
908
  function askHidden(question) {
802
909
  const stdin = process.stdin;
@@ -924,10 +1031,62 @@ async function saveAndReport(recording, title, opts) {
924
1031
  console.log(` UNPROVEN — ${flow.unprovenBecause}. The first run that passes proves it.`);
925
1032
  if (flow.destructive)
926
1033
  console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --allow-purchases.`);
1034
+ const upTo = provenUpToNote(flow);
1035
+ if (upTo)
1036
+ console.log(` ${upTo}`);
1037
+ const ends = out.proven?.result.endChecks;
1038
+ if (ends?.length) {
1039
+ console.log(`\nhow it ended — add the ones that mean "it ended right" (nothing is added unless you do):`);
1040
+ for (const step of ends)
1041
+ console.log(` understudy edit ${flow.app} ${flow.slug} --before ${flow.steps.length} --step '${JSON.stringify(step).replace(/'/g, "'\\''")}'`);
1042
+ }
927
1043
  if (out.run)
928
1044
  printRunReport(out.run);
929
1045
  console.log(`\nreplay it any time: understudy replay ${flow.app} ${flow.slug}`);
930
1046
  }
1047
+ /** "PROVEN UP TO step 2 ("Confirm & Submit")…", for a flow proven only to its commit. */
1048
+ function provenUpToNote(flow) {
1049
+ if (flow.provenUpTo === undefined)
1050
+ return undefined;
1051
+ const s = flow.steps[flow.provenUpTo];
1052
+ return `PROVEN UP TO step ${flow.provenUpTo}${s?.name ? ` ("${s.name}")` : ''}, its commit — found ready, not pressed. ` +
1053
+ 'A full run with --allow-purchases proves the rest.';
1054
+ }
1055
+ /** `edit <app> <flow> --before n --step '{…}'`: add a person's step or a wait to a saved flow. */
1056
+ async function cmdEdit(positional, flags) {
1057
+ const app = positional[0] ?? fail('edit needs an app and a flow', `understudy edit myapp book-a-visit --before 3 --step '{"action":"human","value":"…"}'`);
1058
+ const slug = positional[1] ?? fail('edit needs a flow', `understudy flows ${app}`);
1059
+ const before = Number(str(flags.get('before')) ?? fail('edit needs --before <step index>'));
1060
+ const raw = str(flags.get('step')) ?? fail(`edit needs --step '<json>'`);
1061
+ let step;
1062
+ try {
1063
+ step = JSON.parse(raw);
1064
+ }
1065
+ catch {
1066
+ fail(`--step isn't JSON: ${raw}`);
1067
+ }
1068
+ const flow = await editFlow(app, slug, [{ before, step: step }]).catch((e) => fail(e.message));
1069
+ console.log(`added step ${before} to ${app}/${slug} (${flow.steps.length} steps now)`);
1070
+ console.log(` UNPROVEN until a run passes — understudy prove ${app} ${slug}`);
1071
+ }
1072
+ /** `prove <app> <flow>`: prove a saved flow without committing anything. */
1073
+ async function cmdProve(positional, flags) {
1074
+ const app = positional[0] ?? fail('prove needs an app and a flow', 'understudy prove myapp book-a-visit');
1075
+ const slug = positional[1] ?? fail('prove needs a flow', `understudy flows ${app}`);
1076
+ const out = await withLoginValues(valuesFromFlags(flags), (values) => proveFlow(app, slug, { values, headed: flags.has('headed') }))
1077
+ .catch((e) => fail(e.message));
1078
+ if (out.commit)
1079
+ console.log(`stopping before step ${out.commit.index}: ${out.commit.reason}\n`);
1080
+ printReplay(out.result);
1081
+ printRunReport(out.run);
1082
+ const upTo = provenUpToNote(out.flow);
1083
+ if (out.newlyProven)
1084
+ console.log(`\nproven '${slug}'${upTo ? ` — ${upTo}` : ''}`);
1085
+ else if (out.result.ok)
1086
+ console.log(`\npassed '${slug}' was already proven this far`);
1087
+ if (!out.result.ok)
1088
+ process.exitCode = 3;
1089
+ }
931
1090
  async function cmdFlows(positional) {
932
1091
  const app = positional[0] ?? fail('flows needs an app name', 'understudy flows myapp');
933
1092
  const { flows, runs } = await store.collections();
@@ -939,7 +1098,7 @@ async function cmdFlows(positional) {
939
1098
  for (const f of rows) {
940
1099
  const last = await runs.find({ app, plan: [f.slug] }).sort({ startedAt: -1 }).limit(1).next();
941
1100
  const status = last ? `${last.status} ${last.startedAt.toISOString().slice(0, 16).replace('T', ' ')}` : 'never run';
942
- const marks = [f.proven === false && 'UNPROVEN', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment', f.madeBy === 'agent' && 'made by an agent']
1101
+ const marks = [f.proven === false && 'UNPROVEN', f.provenUpTo !== undefined && `proven to step ${f.provenUpTo}`, f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment', f.madeBy === 'agent' && 'made by an agent']
943
1102
  .filter(Boolean).join(', ');
944
1103
  console.log(` ${f.slug.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
945
1104
  }
@@ -947,13 +1106,27 @@ async function cmdFlows(positional) {
947
1106
  async function cmdFindings(positional, flags) {
948
1107
  const app = positional[0] ?? fail('findings needs an app name', 'understudy findings myapp');
949
1108
  const { findings } = await store.collections();
1109
+ // --triage <fingerprint>=<verdict>, repeatable.
1110
+ const asked = (flags.get('triage') ?? []).filter((v) => typeof v === 'string').map((v) => {
1111
+ const [fingerprint, verdict] = v.split('=');
1112
+ return { fingerprint: fingerprint ?? '', verdict: (verdict ?? '') };
1113
+ });
1114
+ if (asked.length) {
1115
+ const routed = await triage(findings, app, asked);
1116
+ for (const p of routed.problems)
1117
+ console.error(` ${p}`);
1118
+ console.log(`triaged ${routed.routed} finding(s)`);
1119
+ const accepted = await acceptPaths(app, routed.expected);
1120
+ if (accepted.runs)
1121
+ console.log(`accepted the new path: ${accepted.runs} run(s) join the history; ${accepted.flows.join(', ')} now expect it\n`);
1122
+ }
950
1123
  const rows = await listFindings(findings, app, { all: flags.has('all'), limit: 50 });
951
1124
  if (!rows.length) {
952
1125
  console.log(flags.has('all') ? `no findings for '${app}'` : `no open findings for '${app}' (--all to include triaged ones)`);
953
1126
  return;
954
1127
  }
955
1128
  for (const f of rows) {
956
- console.log(` ${f.severity.padEnd(6)} ×${String(f.occurrences).padEnd(4)} ${f.kind.padEnd(14)} ${f.statement.slice(0, 110)}${f.evidence?.fromUnprovenFlow ? ' [from an unproven flow — may be the recording]' : ''}`);
1129
+ console.log(` ${f.fingerprint} ${f.severity.padEnd(6)} ×${String(f.occurrences).padEnd(4)} ${f.kind.padEnd(14)} ${f.statement.slice(0, 110)}${f.evidence?.fromUnprovenFlow ? ' [from an unproven flow — may be the recording]' : ''}`);
957
1130
  }
958
1131
  }
959
1132
  /** emit <app> <flow> — print a saved flow as a Playwright or Cypress test. */
@@ -1008,10 +1181,13 @@ async function main() {
1008
1181
  case 'extension': return cmdExtension();
1009
1182
  case 'app': return cmdApp(rest, flags);
1010
1183
  case 'reembed': return cmdReembed();
1184
+ case 'calibrate': return cmdCalibrate(rest, flags);
1011
1185
  case 'record': return cmdRecord(rest, flags);
1012
1186
  case 'import': return cmdImport(rest, flags);
1013
1187
  case 'recordings': return cmdRecordings(rest);
1014
1188
  case 'replay': return cmdReplay(rest, flags);
1189
+ case 'prove': return cmdProve(rest, flags);
1190
+ case 'edit': return cmdEdit(rest, flags);
1015
1191
  case 'save': return cmdSave(rest, flags);
1016
1192
  case 'flows': return cmdFlows(rest);
1017
1193
  case 'findings': return cmdFindings(rest, flags);
@@ -12,8 +12,9 @@
12
12
  * understudy_remember store facts, lessons, findings, goals reached by other means
13
13
  * understudy_findings list open findings; triage them
14
14
  * understudy_record wait for the user to record a flow in their Chrome
15
- * understudy_save prove a recording by replaying it, then keep it as a flow
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
  */