@jeffawe/understudy 0.2.3 → 0.3.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';
@@ -54,6 +54,11 @@ COMMANDS
54
54
  flows <app> list an app's saved flows and how each last ran
55
55
  replay <hash> re-run a recording file headless
56
56
  replay <app> <flow> re-run a saved flow; records the run, drift and findings
57
+ prove <app> <flow> prove a saved flow where it stands; one that buys something
58
+ is replayed up to that step, checked, and never pressed
59
+ edit <app> <flow> --before <n> --step '<json>'
60
+ add a step to a saved flow: a person's step or a wait, e.g.
61
+ '{"action":"human","value":"Accept the visit","hints":{"untilText":"Accepted"}}'
57
62
  findings <app> what looked broken, most severe first
58
63
  recall <app> "<goal>" what memory knows about a goal — nothing runs
59
64
  run <app> "<goal>" find the flow that does the goal, and run it
@@ -93,6 +98,8 @@ SAVE
93
98
 
94
99
  FINDINGS
95
100
  --all include findings already triaged
101
+ --triage <fp>=<verdict> route a finding: issue, lesson, noise — or expected,
102
+ for a changed path the app made on purpose (repeatable)
96
103
 
97
104
  RUN
98
105
  --sub-goal <text> plan across several flows, in this order (repeatable)
@@ -491,7 +498,7 @@ async function cmdImport(positional, flags) {
491
498
  */
492
499
  async function executeWithReport(recording, flags, opts) {
493
500
  const values = valuesFromFlags(flags);
494
- const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons }))
501
+ const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons, ...personAtTerminal() }))
495
502
  .catch((e) => fail(e.message));
496
503
  if (x.sessionRestoredFrom)
497
504
  console.log(`session: restored (saved ${x.sessionRestoredFrom})`);
@@ -654,7 +661,7 @@ async function reportPlan(state, flags) {
654
661
  }
655
662
  console.log();
656
663
  const values = valuesFromFlags(flags);
657
- const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed') }))
664
+ const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed'), ...personAtTerminal() }))
658
665
  .catch((e) => fail(e.message));
659
666
  if (executed.lessons?.fired)
660
667
  console.log(`lessons ${executed.lessons.fired} fired, ${executed.lessons.helped} on steps that have failed before\n`);
@@ -717,6 +724,7 @@ function printReplay(result) {
717
724
  s.ambiguousByName && `ambiguous: ${s.ambiguousByName.matched} by name, resolved via ${s.ambiguousByName.disambiguatedBy}`,
718
725
  s.roleHadNoMatch && `role matched nothing, fell back to ${s.roleHadNoMatch.fellBackTo}`,
719
726
  s.roundTripMismatch && `value did not survive: wrote "${s.roundTripMismatch.expected}", read "${s.roundTripMismatch.actual}"`,
727
+ s.held && 'stopped here: its commit — found ready, not pressed',
720
728
  s.error,
721
729
  ].filter(Boolean).join('; ');
722
730
  console.log(` ${String(s.seq).padStart(2)} ${s.ok ? 'ok ' : 'FAIL'} ${s.action.padEnd(7)} ${(s.sig ?? '').padEnd(28)} ${notes}`);
@@ -732,6 +740,8 @@ function printReplay(result) {
732
740
  /** What recording the run added: drift against earlier runs, and findings. */
733
741
  function printRunReport(run) {
734
742
  const { drift } = run;
743
+ if (run.pending)
744
+ console.log('\npath CHANGED, not accepted yet — it joins the history once you triage its finding: understudy findings <app> --triage <fp>=expected');
735
745
  if (drift.notCompared)
736
746
  console.log(`\ndrift not compared — ${drift.notCompared}`);
737
747
  else if (drift.firstRun)
@@ -786,17 +796,41 @@ async function askYesNo(question, byDefault = false) {
786
796
  const answer = (await ask(`${question} ${byDefault ? '[Y/n]' : '[y/N]'} `)).trim();
787
797
  return answer ? /^y(es)?$/i.test(answer) : byDefault;
788
798
  }
789
- /** Ask for a line in the terminal. */
790
- async function ask(question) {
799
+ /** Ask for a line in the terminal. A `signal` withdraws the question. */
800
+ async function ask(question, signal) {
791
801
  const { createInterface } = await import('node:readline/promises');
792
802
  const rl = createInterface({ input: process.stdin, output: process.stdout });
793
803
  try {
794
- return await rl.question(question);
804
+ return await rl.question(question, signal ? { signal } : {});
795
805
  }
796
806
  finally {
797
807
  rl.close();
798
808
  }
799
809
  }
810
+ /**
811
+ * The terminal as the person a run asks: at a human step, and — in a visible
812
+ * browser — at a step that failed. Nothing to ask without a terminal.
813
+ */
814
+ function personAtTerminal() {
815
+ if (!process.stdin.isTTY)
816
+ return {};
817
+ return {
818
+ onHuman: async (req, signal) => {
819
+ console.log(`\nyour turn step ${req.seq}: ${req.instruction}`);
820
+ if (req.until)
821
+ console.log(` it carries on by itself once the page shows ${req.until.text ? `"${req.until.text}"` : req.until.url}`);
822
+ const line = await ask(' press Enter when it is done, or type "abort": ', signal).catch(() => '');
823
+ if (signal.aborted)
824
+ console.log('\n the page shows it done — carrying on');
825
+ return /^abort$/i.test(line.trim()) ? { action: 'abort', reason: 'aborted at the terminal' } : { action: 'done' };
826
+ },
827
+ onStuck: async (st) => {
828
+ console.log(`\nstuck step ${st.seq} (${st.action}${st.target ? ` "${st.target}"` : ''}) failed: ${st.error}`);
829
+ const yes = await askYesNo(' do it by hand in the browser window, then carry on?');
830
+ return yes ? 'done' : 'abort';
831
+ },
832
+ };
833
+ }
800
834
  /** Ask for a line without showing it (a password): each key shows as *. */
801
835
  function askHidden(question) {
802
836
  const stdin = process.stdin;
@@ -924,10 +958,62 @@ async function saveAndReport(recording, title, opts) {
924
958
  console.log(` UNPROVEN — ${flow.unprovenBecause}. The first run that passes proves it.`);
925
959
  if (flow.destructive)
926
960
  console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --allow-purchases.`);
961
+ const upTo = provenUpToNote(flow);
962
+ if (upTo)
963
+ console.log(` ${upTo}`);
964
+ const ends = out.proven?.result.endChecks;
965
+ if (ends?.length) {
966
+ console.log(`\nhow it ended — add the ones that mean "it ended right" (nothing is added unless you do):`);
967
+ for (const step of ends)
968
+ console.log(` understudy edit ${flow.app} ${flow.slug} --before ${flow.steps.length} --step '${JSON.stringify(step).replace(/'/g, "'\\''")}'`);
969
+ }
927
970
  if (out.run)
928
971
  printRunReport(out.run);
929
972
  console.log(`\nreplay it any time: understudy replay ${flow.app} ${flow.slug}`);
930
973
  }
974
+ /** "PROVEN UP TO step 2 ("Confirm & Submit")…", for a flow proven only to its commit. */
975
+ function provenUpToNote(flow) {
976
+ if (flow.provenUpTo === undefined)
977
+ return undefined;
978
+ const s = flow.steps[flow.provenUpTo];
979
+ return `PROVEN UP TO step ${flow.provenUpTo}${s?.name ? ` ("${s.name}")` : ''}, its commit — found ready, not pressed. ` +
980
+ 'A full run with --allow-purchases proves the rest.';
981
+ }
982
+ /** `edit <app> <flow> --before n --step '{…}'`: add a person's step or a wait to a saved flow. */
983
+ async function cmdEdit(positional, flags) {
984
+ const app = positional[0] ?? fail('edit needs an app and a flow', `understudy edit myapp book-a-visit --before 3 --step '{"action":"human","value":"…"}'`);
985
+ const slug = positional[1] ?? fail('edit needs a flow', `understudy flows ${app}`);
986
+ const before = Number(str(flags.get('before')) ?? fail('edit needs --before <step index>'));
987
+ const raw = str(flags.get('step')) ?? fail(`edit needs --step '<json>'`);
988
+ let step;
989
+ try {
990
+ step = JSON.parse(raw);
991
+ }
992
+ catch {
993
+ fail(`--step isn't JSON: ${raw}`);
994
+ }
995
+ const flow = await editFlow(app, slug, [{ before, step: step }]).catch((e) => fail(e.message));
996
+ console.log(`added step ${before} to ${app}/${slug} (${flow.steps.length} steps now)`);
997
+ console.log(` UNPROVEN until a run passes — understudy prove ${app} ${slug}`);
998
+ }
999
+ /** `prove <app> <flow>`: prove a saved flow without committing anything. */
1000
+ async function cmdProve(positional, flags) {
1001
+ const app = positional[0] ?? fail('prove needs an app and a flow', 'understudy prove myapp book-a-visit');
1002
+ const slug = positional[1] ?? fail('prove needs a flow', `understudy flows ${app}`);
1003
+ const out = await withLoginValues(valuesFromFlags(flags), (values) => proveFlow(app, slug, { values, headed: flags.has('headed') }))
1004
+ .catch((e) => fail(e.message));
1005
+ if (out.commit)
1006
+ console.log(`stopping before step ${out.commit.index}: ${out.commit.reason}\n`);
1007
+ printReplay(out.result);
1008
+ printRunReport(out.run);
1009
+ const upTo = provenUpToNote(out.flow);
1010
+ if (out.newlyProven)
1011
+ console.log(`\nproven '${slug}'${upTo ? ` — ${upTo}` : ''}`);
1012
+ else if (out.result.ok)
1013
+ console.log(`\npassed '${slug}' was already proven this far`);
1014
+ if (!out.result.ok)
1015
+ process.exitCode = 3;
1016
+ }
931
1017
  async function cmdFlows(positional) {
932
1018
  const app = positional[0] ?? fail('flows needs an app name', 'understudy flows myapp');
933
1019
  const { flows, runs } = await store.collections();
@@ -939,7 +1025,7 @@ async function cmdFlows(positional) {
939
1025
  for (const f of rows) {
940
1026
  const last = await runs.find({ app, plan: [f.slug] }).sort({ startedAt: -1 }).limit(1).next();
941
1027
  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']
1028
+ 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
1029
  .filter(Boolean).join(', ');
944
1030
  console.log(` ${f.slug.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
945
1031
  }
@@ -947,13 +1033,27 @@ async function cmdFlows(positional) {
947
1033
  async function cmdFindings(positional, flags) {
948
1034
  const app = positional[0] ?? fail('findings needs an app name', 'understudy findings myapp');
949
1035
  const { findings } = await store.collections();
1036
+ // --triage <fingerprint>=<verdict>, repeatable.
1037
+ const asked = (flags.get('triage') ?? []).filter((v) => typeof v === 'string').map((v) => {
1038
+ const [fingerprint, verdict] = v.split('=');
1039
+ return { fingerprint: fingerprint ?? '', verdict: (verdict ?? '') };
1040
+ });
1041
+ if (asked.length) {
1042
+ const routed = await triage(findings, app, asked);
1043
+ for (const p of routed.problems)
1044
+ console.error(` ${p}`);
1045
+ console.log(`triaged ${routed.routed} finding(s)`);
1046
+ const accepted = await acceptPaths(app, routed.expected);
1047
+ if (accepted.runs)
1048
+ console.log(`accepted the new path: ${accepted.runs} run(s) join the history; ${accepted.flows.join(', ')} now expect it\n`);
1049
+ }
950
1050
  const rows = await listFindings(findings, app, { all: flags.has('all'), limit: 50 });
951
1051
  if (!rows.length) {
952
1052
  console.log(flags.has('all') ? `no findings for '${app}'` : `no open findings for '${app}' (--all to include triaged ones)`);
953
1053
  return;
954
1054
  }
955
1055
  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]' : ''}`);
1056
+ 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
1057
  }
958
1058
  }
959
1059
  /** emit <app> <flow> — print a saved flow as a Playwright or Cypress test. */
@@ -1012,6 +1112,8 @@ async function main() {
1012
1112
  case 'import': return cmdImport(rest, flags);
1013
1113
  case 'recordings': return cmdRecordings(rest);
1014
1114
  case 'replay': return cmdReplay(rest, flags);
1115
+ case 'prove': return cmdProve(rest, flags);
1116
+ case 'edit': return cmdEdit(rest, flags);
1015
1117
  case 'save': return cmdSave(rest, flags);
1016
1118
  case 'flows': return cmdFlows(rest);
1017
1119
  case 'findings': return cmdFindings(rest, flags);
@@ -12,7 +12,7 @@
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
17
  *
18
18
  * Long-lived: reconnect (/mcp) after changing the source.
package/dist/entry/mcp.js CHANGED
@@ -12,7 +12,7 @@
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
17
  *
18
18
  * Long-lived: reconnect (/mcp) after changing the source.
@@ -25,26 +25,22 @@ import { remember } from '../memory/notes.js';
25
25
  import { start, answer, runPlan } from '../plan/planner.js';
26
26
  import { distillRequest, saveDistilled } from '../flows/distill.js';
27
27
  import { triage, listFindings } from '../flows/findings.js';
28
+ import { acceptPaths } from '../flows/runs.js';
28
29
  import { collections } from '../store/db.js';
29
30
  import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
30
31
  import { saveRecording, loadRecording, recordingPath } from '../core/recording-store.js';
31
- import { proveAndSave } from '../flows/save.js';
32
+ import { editFlow, proveAndSave, proveFlow } from '../flows/save.js';
32
33
  import { MissingValuesError } from '../flows/execute.js';
33
34
  import { parseScript } from '../adapters/recorder/script.js';
34
35
  import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
35
36
  import { VERSION } from './version.js';
36
37
  /**
37
- * Sent to the agent when it connects — its copy of the contract, since an
38
- * agent that installed Understudy from npm never sees REASONER.md. Kept short:
39
- * every session pays for it.
38
+ * Sent to the agent when it connects. EVERY session pays for this, used or not,
39
+ * so it says only what Understudy is and where to start. Everything else lives
40
+ * on the tool it is about: a client that loads tools on demand pays for those
41
+ * words only when the tool is used.
40
42
  */
41
- const INSTRUCTIONS = `Understudy remembers the user's web-app flows and runs them as end-to-end tests. You supply judgement; it calls no model.
42
- - Recall first: free, runs nothing. A known flow comes with its steps and the login values it needs. Run it with understudy_run, or drive it yourself — say which.
43
- - Runs ask before a browser opens. decompose: subGoals in the order the app does them, in the words of its flows. seam: one click or goto, or [] unless you know — answers are reused forever. Start with dryRun.
44
- - Never ask for a password in chat. Values come from the user's settings (UNDERSTUDY_<NAME>), or pass ones you fetched yourself.
45
- - No flow for it? understudy_record (the user records) then understudy_save — or save a Playwright script of what you drove (understudy_save with script). Save what's worth testing again.
46
- - Ask the user before each distill. Gather facts, lessons and findings, get approval, then one understudy_remember.
47
- Full guide: REASONER.md in the package.`;
43
+ const INSTRUCTIONS = `Understudy runs end-to-end tests of the user's web apps from flows it remembers; it calls no model. Start with understudy_recall.`;
48
44
  const server = new McpServer({ name: 'understudy', version: VERSION }, { instructions: INSTRUCTIONS });
49
45
  /** Credentials passed to `run`, kept in memory (never stored) until the run executes. */
50
46
  const valuesByRun = new Map();
@@ -74,27 +70,103 @@ const missingValues = (e, retry) => ({
74
70
  });
75
71
  /** Drop undefined fields: the zod types allow them, the functions here don't. */
76
72
  const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
73
+ class LiveRun {
74
+ queue = [];
75
+ waiter;
76
+ /** The question waiting for an answer, if any. */
77
+ pending;
78
+ push(e) {
79
+ const w = this.waiter;
80
+ if (w) {
81
+ this.waiter = undefined;
82
+ w(e);
83
+ }
84
+ else
85
+ this.queue.push(e);
86
+ }
87
+ /** The page showed the step done: nobody needs to answer that question now. */
88
+ withdraw(seq) {
89
+ this.queue = this.queue.filter((e) => !(e.kind === 'question' && e.seq === seq));
90
+ if (this.pending?.seq === seq)
91
+ this.pending = undefined;
92
+ }
93
+ next() {
94
+ const e = this.queue.shift();
95
+ return e ? Promise.resolve(e) : new Promise((r) => { this.waiter = r; });
96
+ }
97
+ }
98
+ const liveRuns = new Map();
99
+ const HUMAN_HOW = 'A step only a person can do. Tell the user exactly what to do, then answer {"done": true} when they say it is done, or {"abort": "why"}.';
100
+ const STUCK_HOW = 'This step failed, and the run\'s browser is open on screen. Ask the user to do just this step by hand in that window, then answer {"done": true} — or {"abort": "why"}. Then suggest re-recording, so it works next time.';
101
+ function personSaid(reply) {
102
+ const r = reply;
103
+ if (r?.done === true)
104
+ return { done: true };
105
+ if (typeof r?.abort === 'string' && r.abort.trim())
106
+ return { abort: r.abort.trim() };
107
+ throw new Error('answer {"done": true} once they have done it, or {"abort": "why"}');
108
+ }
109
+ /** Wait for the live run's next question, or its result. */
110
+ async function nextFrom(runId) {
111
+ const run = liveRuns.get(runId);
112
+ const e = await run.next();
113
+ if (e.kind === 'question')
114
+ return { status: 'waiting', runId, question: e.question };
115
+ liveRuns.delete(runId);
116
+ valuesByRun.delete(runId);
117
+ if (e.kind === 'error')
118
+ throw e.error;
119
+ return e.result;
120
+ }
77
121
  /** After planning: run it now, unless it was a dry run or is waiting/blocked. */
78
122
  async function continueRun(state, opts) {
79
123
  if (state.status !== 'planned' || state.dryRun)
80
124
  return state;
81
- const values = valuesByRun.get(state.runId) ?? {};
82
- const { executed, recorded, plan, nowProven } = await runPlan(state.runId, { values, ...opts });
83
- valuesByRun.delete(state.runId);
125
+ const runId = state.runId;
126
+ const live = new LiveRun();
127
+ liveRuns.set(runId, live);
128
+ const ask = (seq, question) => new Promise((resolve) => {
129
+ live.pending = { seq, resolve };
130
+ live.push({ kind: 'question', seq, question });
131
+ });
132
+ runPlan(runId, {
133
+ values: valuesByRun.get(runId) ?? {}, ...opts,
134
+ onHuman: async (req, signal) => {
135
+ signal.addEventListener('abort', () => live.withdraw(req.seq));
136
+ const said = await ask(req.seq, {
137
+ kind: 'human', step: req.seq, ask: req.instruction, page: req.url,
138
+ ...(req.until ? { doneWhen: req.until, carriesOnWhen: 'the page shows doneWhen — it checks that after your answer too' } : {}),
139
+ how: HUMAN_HOW,
140
+ });
141
+ return 'done' in said ? { action: 'done' } : { action: 'abort', reason: said.abort };
142
+ },
143
+ onStuck: async (stuck) => {
144
+ const said = await ask(stuck.seq, { kind: 'handoff', step: stuck.seq, failed: { action: stuck.action, target: stuck.target, error: stuck.error }, page: stuck.url, how: STUCK_HOW });
145
+ return 'done' in said ? 'done' : 'abort';
146
+ },
147
+ }).then((out) => live.push({ kind: 'done', result: report(state, out) }), (error) => live.push({ kind: 'error', error }));
148
+ return nextFrom(runId);
149
+ }
150
+ /** What a finished run tells the agent. */
151
+ function report(state, out) {
152
+ const { executed, recorded, plan, nowProven } = out;
84
153
  const r = executed.result;
154
+ const byPerson = r.steps.filter((s) => s.viaHuman || s.viaHandoff);
85
155
  return {
86
156
  status: r.ok ? 'passed' : 'failed',
87
157
  runId: state.runId,
88
158
  plan,
89
159
  seams: state.seams,
90
160
  failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
161
+ ...(byPerson.length ? { doneByAPerson: byPerson.map((s) => ({ seq: s.seq, how: s.viaHuman ? `human step, ${s.viaHuman === 'page' ? 'the page showed it done' : 'they said it was done'}` : 'a failed step they did by hand' })) } : {}),
91
162
  unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
92
163
  path: r.sigSequence,
93
164
  drift: recorded.drift.notCompared ? `not compared: ${recorded.drift.notCompared}`
94
165
  : recorded.drift.firstRun ? 'first passed run of this plan — now the baseline' : recorded.drift.changed
95
166
  ? { added: recorded.drift.added, removed: recorded.drift.removed, stateChanged: recorded.drift.stateChanged }
96
167
  : 'same path',
97
- findings: recorded.findings.map((f) => ({ kind: f.kind, severity: f.severity, statement: f.statement })),
168
+ findings: recorded.findings.map((f) => ({ kind: f.kind, severity: f.severity, statement: f.statement, fingerprint: f.fingerprint })),
169
+ ...(recorded.pending ? { pathNotAccepted: 'it passed on a changed path, so it isn\'t history yet: ask the user if the change is right, then understudy_findings triage its flow_drift finding as expected (or issue)' } : {}),
98
170
  ...(executed.lessons?.fired ? { lessons: executed.lessons } : {}),
99
171
  ...(nowProven.length ? { nowProven } : {}),
100
172
  ...(executed.missingValues.length ? { missingValues: executed.missingValues } : {}),
@@ -102,13 +174,13 @@ async function continueRun(state, opts) {
102
174
  };
103
175
  }
104
176
  const values = z.record(z.string(), z.string()).optional()
105
- .describe('Login values you fetched yourself, e.g. {"SECRET.password":"…"}; otherwise read from settings. Never stored.');
177
+ .describe('Login values you fetched yourself, e.g. {"SECRET.password":"…"}; otherwise read from the user\'s settings. Never stored. Never ask the user to paste one into chat.');
106
178
  server.registerTool('understudy_recall', {
107
- description: 'What memory knows about a goal: closest flows and notes, and a verdict. A known flow comes with its steps and needed login values. Free; nothing runs.',
179
+ description: 'Call first: what memory knows about a goal — closest flows, notes, a verdict. Free; nothing runs. A known flow comes with its steps and needed login values: run it with understudy_run or drive it yourself, and tell the user which. Unknown: the user records it (understudy_record), or you drive it and save the script (understudy_save).',
108
180
  inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional() },
109
181
  }, ({ app, goal, limit }) => wrap(() => recall(app, goal, { withSteps: true, ...(limit ? { limit } : {}) })));
110
182
  server.registerTool('understudy_run', {
111
- description: 'Plan a goal and run it headless. Returns a question to answer with understudy_answer, "blocked" with why, or the result.',
183
+ description: 'Plan a goal and run it headless (visible when a step needs a person). Start with dryRun. Returns a question for understudy_answer, "blocked" with why, or the result.',
112
184
  inputSchema: {
113
185
  app: z.string(), goal: z.string(),
114
186
  subGoals: z.array(z.string()).optional().describe('Skip the decompose question.'),
@@ -128,9 +200,18 @@ server.registerTool('understudy_run', {
128
200
  return continueRun(state, a.headed ? { headed: true } : {});
129
201
  }));
130
202
  server.registerTool('understudy_answer', {
131
- description: 'Answer a waiting run\'s question; returns the next one, or the result. decompose: {"subGoals":[…]}. seam: {"steps":[…]}, or {"steps":[]} unless you know.',
203
+ description: 'Answer a waiting run\'s question, as its "how" says. Returns the next question, or the result.',
132
204
  inputSchema: { runId: z.string(), answer: z.record(z.string(), z.unknown()), values, headed: z.boolean().optional() },
133
205
  }, (a) => wrap(async () => {
206
+ // A run waiting on a person, browser open: answer it where it is.
207
+ const live = liveRuns.get(a.runId);
208
+ if (live) {
209
+ const said = personSaid(a.answer);
210
+ const waiting = live.pending;
211
+ live.pending = undefined;
212
+ waiting?.resolve(said); // none: the page showed it done, and it carried on
213
+ return nextFrom(a.runId);
214
+ }
134
215
  if (a.values)
135
216
  valuesByRun.set(a.runId, a.values);
136
217
  return continueRun(await answer(a.runId, a.answer), a.headed ? { headed: true } : {});
@@ -144,7 +225,7 @@ server.registerTool('understudy_save_distilled', {
144
225
  inputSchema: { app: z.string(), flow: z.string(), distilled: z.record(z.string(), z.unknown()) },
145
226
  }, ({ app, flow, distilled }) => wrap(() => saveDistilled(app, flow, distilled)));
146
227
  server.registerTool('understudy_remember', {
147
- description: 'Store what you learned, as one approved batch: facts, lessons (trigger never empty), findings, and goals you reached without understudy_run.',
228
+ description: 'Store what you learned, as one batch the user has approved: facts (change plans), lessons (change one step; trigger never empty), findings (the app is broken), and goals you reached without understudy_run.',
148
229
  inputSchema: {
149
230
  app: z.string(),
150
231
  facts: z.array(z.object({ text: z.string(), marksDestructive: z.string().optional() })).optional(),
@@ -159,18 +240,20 @@ server.registerTool('understudy_remember', {
159
240
  reached: reached?.map((r) => defined(r)),
160
241
  }))));
161
242
  server.registerTool('understudy_findings', {
162
- description: 'Open findings for an app, most severe first, then most frequent. Pass triage to route them: issue, lesson or noise.',
243
+ description: 'Open findings for an app, most severe first, then most frequent. Pass triage to route them: issue, lesson, noise — or, for a changed path (flow_drift), expected: the app changed on purpose and the new path becomes the normal one. Ask the user before expected.',
163
244
  inputSchema: {
164
245
  app: z.string(),
165
- triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise']) })).optional(),
246
+ triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise', 'expected']) })).optional(),
166
247
  all: z.boolean().optional().describe('Include already-triaged findings.'),
167
248
  },
168
249
  }, ({ app, triage: items, all }) => wrap(async () => {
169
250
  const { findings } = await collections();
170
251
  const routed = items?.length ? await triage(findings, app, items) : undefined;
252
+ const accepted = routed?.expected.length ? await acceptPaths(app, routed.expected) : undefined;
171
253
  const rows = await listFindings(findings, app, { ...(all ? { all } : {}), limit: 40 });
172
254
  return {
173
- ...(routed ? { triaged: routed } : {}),
255
+ ...(routed ? { triaged: { routed: routed.routed, problems: routed.problems } } : {}),
256
+ ...(accepted ? { acceptedPath: accepted } : {}),
174
257
  findings: rows.map((f) => ({ fingerprint: f.fingerprint, kind: f.kind, severity: f.severity, occurrences: f.occurrences, status: f.status, statement: f.statement })),
175
258
  };
176
259
  }));
@@ -206,21 +289,34 @@ server.registerTool('understudy_record', {
206
289
  }));
207
290
  server.registerTool('understudy_save', {
208
291
  description: [
209
- 'Prove a flow by replaying it, and keep it only if every step passes: the user\'s latest recording, a recording hash, or a script of a flow you drove.',
210
- 'A script is READ, not run: only literal page calls are kept, so no loops, no values computed at runtime, no reading logs or emails mid-flow.',
211
- 'Kept: goto, click, dblclick, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; locators getByRole, getByText, getByLabel, getByPlaceholder, getByTitle, getByAltText, getByTestId, locator(css), frameLocator, filter({hasText}), first/last/nth;',
212
- 'assertions expect(page).toHaveURL/toHaveTitle, expect(locator).toBeVisible/toBeHidden/toHaveText/toContainText/toHaveValue/toBeChecked (and .not on visible/hidden/checked), page.waitForURL, page.waitForSelector.',
213
- 'Write locators inline in expect(...), not via a variable. Other assertions come back in droppedAssertions; calls that would change the steps (evaluate, hover, route…) refuse the save.',
292
+ 'Keep a flow, proven by replaying it: the user\'s latest recording, a recording hash, or a Playwright script of a flow you drove.',
293
+ 'A script is read, not run — literal page calls only: no loops, no values computed at runtime (a code from an email is a human step).',
294
+ 'Understood: goto, click, dblclick, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; getBy* locators, locator(css), frameLocator, filter({hasText}), first/last/nth;',
295
+ 'inline expect(page | locator) checks of URL, title, visible, hidden, text, value, checked; page.waitForURL, waitForSelector, waitForResponse.',
296
+ 'Other checks come back in droppedAssertions; calls that change the steps (evaluate, hover, route…) refuse the save.',
297
+ 'Where only a person can act: human(\'what they do\', { untilText | untilUrl | untilResponse }).',
214
298
  ].join(' '),
215
299
  inputSchema: {
216
- app: z.string(), name: z.string().describe('What the flow does, as someone would ask for it.'),
300
+ app: z.string(), name: z.string().optional().describe('What the flow does, as someone would ask for it. Needed unless flow is given.'),
301
+ flow: z.string().optional().describe('A saved flow to prove where it stands (e.g. one kept with verify false), instead of saving a new one.'),
302
+ add: z.array(z.object({ before: z.number().int(), step: z.record(z.string(), z.unknown()) })).optional()
303
+ .describe('With flow: steps to add first, each before step n. {"action":"human","value":"what they do","hints":{"untilText":"…"}}, {"action":"wait_response","value":"/api/visits","hints":{"method":"POST","status":201,"field":"commission.amount","above":0}}, {"action":"assert","role":"checkbox","name":"…","hints":{"assert":"checked"}}; also wait_url, wait_text.'),
217
304
  hash: z.string().optional(),
218
305
  script: z.string().optional().describe('Path to a Playwright script of a flow you drove; read passwords from process.env.'),
219
306
  intent: z.string().optional(), slug: z.string().optional(), values,
220
- verify: z.boolean().optional().describe('false: keep it without replaying (e.g. it ends in a real purchase). Saved as unproven until a run passes.'),
307
+ verify: z.boolean().optional().describe('A flow that commits something real (a purchase, a submission) is replayed only up to that step, which is checked and never pressed. false: keep it without replaying at all; saved as unproven until a run passes.'),
221
308
  note: z.string().optional().describe('With verify false: why, e.g. what you checked yourself.'),
222
309
  },
223
310
  }, (a) => wrap(async () => {
311
+ if (a.flow) {
312
+ const edited = a.add?.length ? await editFlow(a.app, a.flow, a.add) : undefined;
313
+ if (edited && a.verify === false)
314
+ return { flow: edited.slug, steps: edited.steps.length, unproven: edited.unprovenBecause };
315
+ return { ...(edited ? { added: a.add.length } : {}), ...(await proveSaved(a.app, a.flow, a)) };
316
+ }
317
+ if (!a.name)
318
+ throw new Error('name is required — what the flow does, as someone would ask for it (or pass flow to prove a saved one)');
319
+ const name = a.name;
224
320
  let rec;
225
321
  let madeBy = 'user';
226
322
  let dropped = [];
@@ -250,7 +346,7 @@ server.registerTool('understudy_save', {
250
346
  let out;
251
347
  try {
252
348
  out = await proveAndSave(rec, {
253
- title: a.name, madeBy,
349
+ title: name, madeBy,
254
350
  ...(a.verify === false ? { verify: false, unproven: a.note ? `saved by an agent without a replay: ${a.note}` : 'saved by an agent without a replay' } : {}),
255
351
  ...(a.values ? { values: a.values } : {}), ...(a.intent ? { intent: a.intent } : {}), ...(a.slug ? { slug: a.slug } : {}),
256
352
  });
@@ -258,7 +354,7 @@ server.registerTool('understudy_save', {
258
354
  catch (e) {
259
355
  // The recording is kept; saving it again by hash needs nothing re-recorded.
260
356
  if (e instanceof MissingValuesError)
261
- return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name: a.name }) };
357
+ return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name }) };
262
358
  throw e;
263
359
  }
264
360
  const r = out.proven?.result;
@@ -283,10 +379,54 @@ server.registerTool('understudy_save', {
283
379
  proveIt: `when it should pass: understudy_run with subGoals ["${out.flow.slug}"] — a passing run proves it`,
284
380
  } : {}),
285
381
  ...(out.flow.destructive ? { destructive: out.flow.destructiveBecause } : {}),
382
+ ...provenUpTo(out.flow),
383
+ ...endChecks(out.flow, r?.endChecks),
286
384
  ...(out.run ? { findings: out.run.findings.map((f) => f.statement) } : {}),
287
385
  ...(out.placeholders.converted.length ? { placeholders: out.placeholders.converted } : {}),
288
386
  };
289
387
  }));
388
+ /** understudy_save with `flow`: prove a saved flow — up to its commit, if it has one. Records the run. */
389
+ async function proveSaved(app, slug, a) {
390
+ const out = await proveFlow(app, slug, a.values ? { values: a.values } : {});
391
+ const r = out.result;
392
+ return {
393
+ flow: out.flow.slug, passed: r.ok, newlyProven: out.newlyProven,
394
+ proven: out.flow.proven !== false,
395
+ ...(out.flow.proven === false ? { unproven: out.flow.unprovenBecause } : {}),
396
+ ...provenUpTo(out.flow),
397
+ ...(out.commit && !r.ok ? { wouldStopBefore: `step ${out.commit.index}: ${out.commit.reason}` } : {}),
398
+ failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
399
+ findings: out.run.findings.map((f) => f.statement),
400
+ };
401
+ }
402
+ /**
403
+ * How the flow ended, offered as checks to add — never added unasked. A
404
+ * person's own recording is the best word on how it should end; an agent's
405
+ * may have taken a path the user wouldn't, so the user says either way.
406
+ */
407
+ function endChecks(flow, checks) {
408
+ if (!checks?.length)
409
+ return {};
410
+ return {
411
+ endChecks: {
412
+ suggest: checks.map((step) => ({ before: flow.steps.length, step })),
413
+ how: (flow.madeBy === 'agent'
414
+ ? 'You drove this, so ask the user how it should end: '
415
+ : 'From the user\'s own recording — ask them: ')
416
+ + 'which of these say it ended right? Add those with understudy_save { flow, add }. Without them the flow only checks that each step could be done.',
417
+ },
418
+ };
419
+ }
420
+ /** What "proven up to its commit" means, for a flow that is. */
421
+ function provenUpTo(flow) {
422
+ if (flow.provenUpTo === undefined)
423
+ return {};
424
+ const s = flow.steps[flow.provenUpTo];
425
+ return {
426
+ provenUpTo: flow.provenUpTo,
427
+ stoppedBefore: `step ${flow.provenUpTo}${s?.name ? ` ("${s.name}")` : ''}, its commit: the control was there and ready, and was not pressed — nothing after it has run`,
428
+ };
429
+ }
290
430
  server.registerTool('understudy_app', {
291
431
  description: 'An app\'s settings. placeholders ["email"] keeps email addresses out of memory: they become placeholders, and the values move to the user\'s env file.',
292
432
  inputSchema: {
@@ -15,5 +15,21 @@
15
15
  import type { Step } from '../store/types.js';
16
16
  /** Why this step is destructive, or null if nothing says it is. */
17
17
  export declare function destructiveReason(step: Pick<Step, 'action' | 'name' | 'url'>): string | null;
18
- /** The first reason any step in the flow is destructive, or null. */
18
+ /** A step that commits something real, and why. */
19
+ export interface CommitStep {
20
+ index: number;
21
+ reason: string;
22
+ }
23
+ /**
24
+ * EVERY step that commits something, in order — not just the first.
25
+ *
26
+ * A booking flow often has two: "Confirm & Submit" creates the visit, "Pay
27
+ * Now" charges for it. Naming only the first hid the payment, and proving a
28
+ * flow up to its commit needs the first one exactly (flows/save.ts).
29
+ *
30
+ * `controls` are names a fact says commit something (notes.destructiveControls),
31
+ * matched the same way the run's safety gate matches them.
32
+ */
33
+ export declare function commitSteps(steps: Pick<Step, 'action' | 'name' | 'url'>[], controls?: ReadonlyMap<string, string>): CommitStep[];
34
+ /** Why the flow is destructive — every step that makes it so — or null. */
19
35
  export declare function flowDestructiveReason(steps: Pick<Step, 'action' | 'name' | 'url'>[]): string | null;
@@ -37,12 +37,30 @@ export function destructiveReason(step) {
37
37
  }
38
38
  return null;
39
39
  }
40
- /** The first reason any step in the flow is destructive, or null. */
41
- export function flowDestructiveReason(steps) {
42
- for (const [i, s] of steps.entries()) {
40
+ /**
41
+ * EVERY step that commits something, in order — not just the first.
42
+ *
43
+ * A booking flow often has two: "Confirm & Submit" creates the visit, "Pay
44
+ * Now" charges for it. Naming only the first hid the payment, and proving a
45
+ * flow up to its commit needs the first one exactly (flows/save.ts).
46
+ *
47
+ * `controls` are names a fact says commit something (notes.destructiveControls),
48
+ * matched the same way the run's safety gate matches them.
49
+ */
50
+ export function commitSteps(steps, controls = new Map()) {
51
+ const out = [];
52
+ for (const [index, s] of steps.entries()) {
43
53
  const why = destructiveReason(s);
54
+ const fact = s.name && COMMITTING_ACTIONS.has(s.action) ? controls.get(s.name.toLowerCase()) : undefined;
44
55
  if (why)
45
- return `step ${i}: ${why}`;
56
+ out.push({ index, reason: why });
57
+ else if (fact)
58
+ out.push({ index, reason: `"${s.name}" — a fact says it commits something: ${fact}` });
46
59
  }
47
- return null;
60
+ return out;
61
+ }
62
+ /** Why the flow is destructive — every step that makes it so — or null. */
63
+ export function flowDestructiveReason(steps) {
64
+ const found = commitSteps(steps);
65
+ return found.length ? found.map((c) => `step ${c.index}: ${c.reason}`).join('; ') : null;
48
66
  }