@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.
@@ -55,6 +55,7 @@ export async function saveDistilled(app, slug, answer) {
55
55
  await c.flows.updateOne({ app, slug }, {
56
56
  $set: {
57
57
  intent: d.intent, outcome: d.outcome, preconditions: d.preconditions,
58
+ requires: d.requires ?? [], establishes: d.establishes ?? [],
58
59
  corrections: (d.corrections ?? []).map((x) => `${x.rule}: ${x.detail}${x.stepIndex !== undefined ? ` (step ${x.stepIndex})` : ''}`),
59
60
  searchText: parentText, ...(vectors[0] ? { embedding: vectors[0] } : {}), updatedAt: now,
60
61
  },
@@ -95,6 +96,7 @@ function segmentFrom(parent, s) {
95
96
  madeBy: parent.madeBy ?? 'user',
96
97
  from: { flow: parent.slug, steps: [start, end] },
97
98
  preconditions: (s.preconditions ?? []),
99
+ requires: s.requires ?? [], establishes: s.establishes ?? [],
98
100
  outcome: s.outcome ?? '',
99
101
  destructive: Boolean(why), ...(why ? { destructiveBecause: why } : {}),
100
102
  corrections: [], recording: parent.recording,
@@ -11,6 +11,8 @@
11
11
  *
12
12
  * Ported from the old emit.ts; it now reads the flow document directly.
13
13
  */
14
+ import { forced, humanUntil, responseCheckOf, valueRefsOf } from '../core/recording.js';
15
+ import { urlGlob } from '../core/replay.js';
14
16
  import { valueEnvName } from '../store/settings.js';
15
17
  const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
16
18
  /** SECRET.password → UNDERSTUDY_SECRET_PASSWORD: the same variable replay reads, so one setting serves both. */
@@ -77,6 +79,30 @@ function assertion(s, loc, value, pw, warn) {
77
79
  warn(`"${describe(s)}" is an assertion of a kind this output doesn't know (${kind}); skipped`);
78
80
  return `// TODO: assert ${kind}`;
79
81
  }
82
+ /** `r => r.url().includes('/api/visits') && r.request().method() === 'POST' && r.status() === 201` */
83
+ function responsePredicate(c) {
84
+ const url = c.url.includes('*') ? `/${urlGlob(c.url).source}/.test(r.url())` : `r.url().includes(${quote(c.url)})`;
85
+ return `(r) => ${[url, c.method && `r.request().method() === ${quote(c.method)}`, c.status !== undefined && `r.status() === ${c.status}`].filter(Boolean).join(' && ')}`;
86
+ }
87
+ /** `body.items[0].id` as optional chaining, so a missing field fails the expect, not the line. */
88
+ const fieldPath = (root, path) => root + path.split('.').map((k) => (/^\d+$/.test(k) ? `?.[${k}]` : `?.${k}`)).join('');
89
+ function playwrightResponseCheck(c, name) {
90
+ if (!c.field)
91
+ return [`await ${name};`];
92
+ const v = fieldPath(`(await (await ${name}).json())`, c.field);
93
+ return [`expect(${v})${c.equals !== undefined ? `.toBe(${JSON.stringify(c.equals)})` : c.above !== undefined ? `.toBeGreaterThan(${c.above})` : '.toBeDefined()'};`];
94
+ }
95
+ function cypressIntercept(c, name) {
96
+ const url = c.url.includes('*') ? quote(c.url) : `new RegExp(${quote(c.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))})`;
97
+ return `cy.intercept({ ${c.method ? `method: ${quote(c.method)}, ` : ''}url: ${url} }).as(${quote(name)});`;
98
+ }
99
+ function cypressResponseCheck(c, name) {
100
+ const checks = [
101
+ c.status !== undefined && `expect(response?.statusCode).to.eq(${c.status});`,
102
+ c.field && `expect(${fieldPath('response?.body', c.field)})${c.equals !== undefined ? `.to.eq(${JSON.stringify(c.equals)})` : c.above !== undefined ? '.to.be.greaterThan(' + c.above + ')' : '.to.exist'};`,
103
+ ].filter(Boolean);
104
+ return checks.length ? [`cy.wait(${quote('@' + name)}).then(({ response }) => { ${checks.join(' ')} });`] : [`cy.wait(${quote('@' + name)});`];
105
+ }
80
106
  /** Best locator first — the same order replay tries, so the code fails where replay would. */
81
107
  function playwrightLocator(s, warn) {
82
108
  const scope = s.frameHint ? `page.frameLocator(${quote(`[id$="${s.frameHint}"]`)})` : 'page';
@@ -119,12 +145,18 @@ export function emitFlow(flow, framework = 'playwright-ts') {
119
145
  if (flow.requiresSession)
120
146
  warnings.push('this flow starts signed in; the generated test starts signed out — add a login first');
121
147
  const lines = [];
122
- for (const s of flow.steps) {
148
+ /** Where the last action's code starts: a response wait is set up just before it. */
149
+ let lastActionAt = -1;
150
+ for (const [i, s] of flow.steps.entries()) {
123
151
  if (s.action === 'snapshot')
124
152
  continue;
125
- const pageLevel = s.action === 'goto' || s.action === 'wait_url' || s.action === 'wait_text' || (s.action === 'assert' && s.hints?.assert === 'title');
153
+ const startsAt = lines.length;
154
+ const pageLevel = ['goto', 'wait_url', 'wait_text', 'wait_response', 'human'].includes(s.action) || (s.action === 'assert' && s.hints?.assert === 'title');
126
155
  const loc = pageLevel ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
127
- const value = s.valueRef ? (required.add(s.valueRef), envName(s.valueRef).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
156
+ const ref = valueRefsOf([s])[0];
157
+ const value = ref ? (required.add(ref), envName(ref).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
158
+ // Both frameworks spell it the same way.
159
+ const force = forced(s) ? '{ force: true }' : '';
128
160
  switch (s.action) {
129
161
  case 'goto':
130
162
  lines.push(pw ? `await page.goto(${value});` : `cy.visit(${value});`);
@@ -136,7 +168,10 @@ export function emitFlow(flow, framework = 'playwright-ts') {
136
168
  lines.push(pw ? `await ${loc}.selectOption(${value});` : `${loc}.select(${value});`);
137
169
  break;
138
170
  case 'check':
139
- lines.push(pw ? `await ${loc}.check();` : `${loc}.check();`);
171
+ lines.push(pw ? `await ${loc}.check(${force});` : `${loc}.check(${force});`);
172
+ break;
173
+ case 'uncheck':
174
+ lines.push(pw ? `await ${loc}.uncheck(${force});` : `${loc}.uncheck(${force});`);
140
175
  break;
141
176
  case 'press':
142
177
  lines.push(pw ? `await ${loc}.press(${value});` : `${loc}.type(${value});`);
@@ -161,11 +196,59 @@ export function emitFlow(flow, framework = 'playwright-ts') {
161
196
  case 'assert':
162
197
  lines.push(assertion(s, loc, value, pw, warn));
163
198
  break;
199
+ case 'human': {
200
+ // A person's step: say what, then wait for its sign — or pause.
201
+ lines.push(`// A PERSON DOES THIS: ${(s.value ?? '').replace(/\n/g, ' ')}`);
202
+ const t = typeof s.hints?.untilText === 'string' ? s.hints.untilText : undefined;
203
+ const u = typeof s.hints?.untilUrl === 'string' ? s.hints.untilUrl : undefined;
204
+ const r = humanUntil(s)?.response;
205
+ if (r) {
206
+ // The person acts after this line, so waiting here misses nothing.
207
+ if (pw)
208
+ lines.push(`const response${i} = page.waitForResponse(${responsePredicate(r)}, { timeout: 15 * 60_000 });`, ...playwrightResponseCheck(r, `response${i}`));
209
+ else
210
+ lines.push(cypressIntercept(r, `response${i}`), ...cypressResponseCheck(r, `response${i}`).map((l) => l.replace(/\)\.then/, ', { timeout: 15 * 60_000 }).then')));
211
+ }
212
+ if (pw) {
213
+ if (u)
214
+ lines.push(`await page.waitForURL(${u.includes('*') ? quote(u) : `(u) => u.href.includes(${quote(u)})`}, { timeout: 15 * 60_000 });`);
215
+ if (t)
216
+ lines.push(`await page.getByText(${quote(t)}).first().waitFor({ timeout: 15 * 60_000 });`);
217
+ if (!u && !t && !r)
218
+ lines.push('await page.pause();');
219
+ }
220
+ else {
221
+ if (u)
222
+ lines.push(`cy.url({ timeout: 15 * 60_000 }).should('include', ${quote(u)});`);
223
+ if (t)
224
+ lines.push(`cy.contains(${quote(t)}, { timeout: 15 * 60_000 });`);
225
+ if (!u && !t && !r)
226
+ lines.push('cy.pause();');
227
+ }
228
+ warn(`step "${s.value ?? 'human'}" needs a person — run this test headed, with someone there`);
229
+ break;
230
+ }
164
231
  case 'wait_text':
165
232
  lines.push(pw ? `await page.getByText(${value}).waitFor();` : `cy.contains(${value});`);
166
233
  break;
167
- default: lines.push(pw ? `await ${loc}.click();` : `${loc}.click();`);
234
+ case 'wait_response': {
235
+ const check = responseCheckOf(s.value, s.hints);
236
+ if (!check)
237
+ break;
238
+ // Set up BEFORE the action that triggers it, or a fast answer is missed.
239
+ const name = `response${i}`;
240
+ const setup = pw ? `const ${name} = page.waitForResponse(${responsePredicate(check)});` : cypressIntercept(check, name);
241
+ const at = lastActionAt >= 0 ? lastActionAt : lines.length;
242
+ lines.splice(at, 0, setup);
243
+ if (lastActionAt >= 0)
244
+ lastActionAt++;
245
+ lines.push(...(pw ? playwrightResponseCheck(check, name) : cypressResponseCheck(check, name)));
246
+ break;
247
+ }
248
+ default: lines.push(pw ? `await ${loc}.click(${force});` : `${loc}.click(${force});`);
168
249
  }
250
+ if (!['wait_url', 'wait_text', 'wait_response', 'assert', 'human'].includes(s.action))
251
+ lastActionAt = startsAt;
169
252
  }
170
253
  const refs = [...required];
171
254
  // Values come from the environment, never the file.
@@ -9,8 +9,8 @@
9
9
  * the MCP server. Throws with a readable message instead of printing, so each
10
10
  * caller decides how to show it.
11
11
  */
12
- import type { RawRecording } from '../core/recording.js';
13
- import { type ReplayResult } from '../core/replay.js';
12
+ import { type RawRecording } from '../core/recording.js';
13
+ import { type ReplayOptions, type ReplayResult } from '../core/replay.js';
14
14
  /** A login value a recording needs, and where it may be set. */
15
15
  export interface MissingValue {
16
16
  placeholder: string;
@@ -38,6 +38,26 @@ export interface ExecuteOptions {
38
38
  * what gets saved is what the recording does on its own.
39
39
  */
40
40
  useLessons?: boolean;
41
+ /** Stop before this step: look at its control, don't use it (see replay's `stopBefore`). */
42
+ stopBefore?: number;
43
+ /** Someone to ask at a `human` step. Without it, a flow with one fails there. */
44
+ onHuman?: ReplayOptions['onHuman'];
45
+ /**
46
+ * Someone to ask when a step fails: do it by hand in the open browser, then
47
+ * say so. Only offered when the browser is visible — nobody can do a step in
48
+ * a window they can't see.
49
+ */
50
+ onStuck?: (stuck: StuckStep) => Promise<'done' | 'abort'>;
51
+ /** Read the last page into `result.endChecks`, after a full pass. */
52
+ endChecks?: boolean;
53
+ }
54
+ /** A step that failed, put to a person who can see the browser. */
55
+ export interface StuckStep {
56
+ seq: number;
57
+ action: string;
58
+ target?: string;
59
+ error: string;
60
+ url: string;
41
61
  }
42
62
  export interface Executed {
43
63
  result: ReplayResult;
@@ -10,6 +10,7 @@
10
10
  * caller decides how to show it.
11
11
  */
12
12
  import { loadSession, forgetSession, loadSessionById, forgetSessionById } from '../core/auth-cache.js';
13
+ import { valueRefsOf } from '../core/recording.js';
13
14
  import { replay } from '../core/replay.js';
14
15
  import { foldLessons, lessonsFor } from '../memory/notes.js';
15
16
  import { valuesFromEnv, valueEnvNames, reloadEnvFiles, writableEnvFile } from '../store/settings.js';
@@ -34,7 +35,7 @@ export class MissingValuesError extends Error {
34
35
  /** The login values this recording needs that neither `given` nor the environment supply. */
35
36
  export function missingValuesFor(recording, given = {}) {
36
37
  reloadEnvFiles();
37
- const refs = new Set(recording.events.map((e) => e.valueRef).filter((r) => Boolean(r)));
38
+ const refs = new Set(valueRefsOf(recording.events));
38
39
  const found = { ...valuesFromEnv(refs, recording.appSlug), ...given };
39
40
  return [...refs].filter((r) => !(r in found)).map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) }));
40
41
  }
@@ -46,7 +47,7 @@ export async function execute(recording, opts = {}) {
46
47
  // Login values: given explicitly, else from UNDERSTUDY_<REF> in the environment
47
48
  // (env files re-read, so one just added is seen).
48
49
  reloadEnvFiles();
49
- const refs = new Set(recording.events.map((e) => e.valueRef).filter((r) => Boolean(r)));
50
+ const refs = new Set(valueRefsOf(recording.events));
50
51
  const values = { ...valuesFromEnv(refs, recording.appSlug), ...(opts.values ?? {}) };
51
52
  const missingValues = [...refs].filter((r) => !(r in values));
52
53
  // Checked BEFORE a browser opens: a run that reached the password step
@@ -73,11 +74,26 @@ export async function execute(recording, opts = {}) {
73
74
  sessionRestoredFrom = cached.savedAt;
74
75
  }
75
76
  const app = recording.appSlug;
77
+ // A person's step needs a browser they can see — unless told otherwise (CI).
78
+ const forPerson = Boolean(opts.onHuman) && recording.events.some((e) => e.action === 'human') && process.env.UNDERSTUDY_HEADLESS !== '1';
79
+ const headed = Boolean(opts.headed) || forPerson;
80
+ const onStuck = opts.onStuck;
76
81
  const result = await replay(recording, {
77
82
  values,
78
83
  ...(storageState ? { storageState } : {}),
79
- ...(opts.headed ? { headless: false } : {}),
84
+ ...(headed ? { headless: false } : {}),
85
+ ...(opts.onHuman ? { onHuman: opts.onHuman } : {}),
86
+ ...(opts.endChecks ? { endChecks: true } : {}),
87
+ ...(onStuck && headed
88
+ ? {
89
+ onHandoff: async (r) => {
90
+ const said = await onStuck({ seq: r.seq, action: r.failed?.action ?? 'step', ...(r.failed?.target ? { target: r.failed.target } : {}), error: r.reason, url: r.url });
91
+ return said === 'done' ? { action: 'continue' } : { action: 'abort', reason: 'declined at the handoff' };
92
+ },
93
+ }
94
+ : {}),
80
95
  ...(opts.useLessons ? { lessonsFor: (ctx) => lessonsFor(app, ctx) } : {}),
96
+ ...(opts.stopBefore !== undefined ? { stopBefore: opts.stopBefore } : {}),
81
97
  });
82
98
  const out = { result, missingValues, ...(sessionRestoredFrom ? { sessionRestoredFrom } : {}) };
83
99
  // Step 0 of a late-armed recording carries the fingerprint of where it was
@@ -32,11 +32,13 @@ export declare function listFindings(coll: Collection<Finding>, app: string, opt
32
32
  all?: boolean;
33
33
  limit?: number;
34
34
  }): Promise<Finding[]>;
35
- export type Verdict = 'issue' | 'lesson' | 'noise';
35
+ export type Verdict = 'issue' | 'lesson' | 'noise' | 'expected';
36
36
  /**
37
37
  * Route open findings. issue: the app is wrong and someone should fix it.
38
38
  * lesson: accepted — the agent works around it (pass the lesson to store).
39
39
  * noise: not a problem (third-party telemetry, framework warnings).
40
+ * expected: a changed path the app made on purpose — flow_drift only. The
41
+ * caller then accepts the runs that took it (runs.ts, acceptPaths).
40
42
  * Returns what couldn't be routed instead of throwing, so one bad item
41
43
  * doesn't lose the rest.
42
44
  */
@@ -46,4 +48,5 @@ export declare function triage(coll: Collection<Finding>, app: string, items: {
46
48
  }[]): Promise<{
47
49
  routed: number;
48
50
  problems: string[];
51
+ expected: string[];
49
52
  }>;
@@ -138,22 +138,34 @@ export async function listFindings(coll, app, opts = {}) {
138
138
  * Route open findings. issue: the app is wrong and someone should fix it.
139
139
  * lesson: accepted — the agent works around it (pass the lesson to store).
140
140
  * noise: not a problem (third-party telemetry, framework warnings).
141
+ * expected: a changed path the app made on purpose — flow_drift only. The
142
+ * caller then accepts the runs that took it (runs.ts, acceptPaths).
141
143
  * Returns what couldn't be routed instead of throwing, so one bad item
142
144
  * doesn't lose the rest.
143
145
  */
144
146
  export async function triage(coll, app, items) {
145
147
  const problems = [];
148
+ const expected = [];
146
149
  let routed = 0;
147
150
  for (const [i, item] of items.entries()) {
148
- if (!['issue', 'lesson', 'noise'].includes(item?.verdict)) {
149
- problems.push(`triage[${i}].verdict must be issue, lesson or noise`);
151
+ if (!['issue', 'lesson', 'noise', 'expected'].includes(item?.verdict)) {
152
+ problems.push(`triage[${i}].verdict must be issue, lesson, noise or expected`);
150
153
  continue;
151
154
  }
155
+ if (item.verdict === 'expected') {
156
+ const f = await coll.findOne({ app, fingerprint: item.fingerprint }, { projection: { kind: 1 } });
157
+ if (f && f.kind !== 'flow_drift') {
158
+ problems.push(`triage[${i}]: expected is for a changed path (flow_drift); this is ${f.kind} — use issue, lesson or noise`);
159
+ continue;
160
+ }
161
+ if (f)
162
+ expected.push(item.fingerprint);
163
+ }
152
164
  const { matchedCount } = await coll.updateOne({ app, fingerprint: item.fingerprint }, { $set: { status: item.verdict } });
153
165
  if (matchedCount)
154
166
  routed++;
155
167
  else
156
168
  problems.push(`triage[${i}]: no finding with fingerprint ${item.fingerprint}`);
157
169
  }
158
- return { routed, problems };
170
+ return { routed, problems, expected };
159
171
  }
@@ -17,6 +17,8 @@ export interface RecordedRun {
17
17
  runId: ObjectId;
18
18
  drift: Drift;
19
19
  findings: FindingDraft[];
20
+ /** It passed on a changed path: kept out of history until that's accepted. */
21
+ pending?: true;
20
22
  }
21
23
  export declare function recordRun(opts: {
22
24
  app: string;
@@ -39,4 +41,15 @@ export declare function recordRun(opts: {
39
41
  /** Fill in this existing run (one that was planned first) instead of adding a new one. */
40
42
  runId?: ObjectId;
41
43
  startedAt?: Date;
44
+ /** Where each flow of the plan starts in the steps. Defaults to [0]. */
45
+ starts?: number[];
42
46
  }): Promise<RecordedRun>;
47
+ /**
48
+ * A changed path was triaged `expected`: the runs that took it join the
49
+ * history, and the newest one's pages become what each of its flows expects
50
+ * step by step — so the change is accepted once, not flagged on every run.
51
+ */
52
+ export declare function acceptPaths(app: string, fingerprints: string[]): Promise<{
53
+ runs: number;
54
+ flows: string[];
55
+ }>;
@@ -24,15 +24,18 @@ export async function recordRun(opts) {
24
24
  // 1. Drift, against the most recent passed runs of this flow — however it
25
25
  // was started, it walked the same steps.
26
26
  const history = await c.runs
27
- .find({ app, plan, mode: { $in: ['replay', 'run'] }, status: 'passed', ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
27
+ .find({ app, plan, mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
28
28
  .sort({ startedAt: -1 })
29
29
  .limit(LOOKBACK)
30
30
  .toArray();
31
31
  // A failed run stops early; comparing its short path would report every
32
32
  // page it never reached as "gone", which is noise, not drift.
33
- const drift = result.ok
34
- ? compareToHistory(result.sigSequence, history.map((h) => h.sigSequence))
35
- : { ...compareToHistory([], []), firstRun: false, notCompared: 'the run failed, so its path is incomplete' };
33
+ // A run that stopped before its commit step is just as short, on purpose.
34
+ const drift = !result.ok
35
+ ? { ...compareToHistory([], []), firstRun: false, notCompared: 'the run failed, so its path is incomplete' }
36
+ : result.stoppedBefore !== undefined
37
+ ? { ...compareToHistory([], []), firstRun: false, notCompared: `it stopped before step ${result.stoppedBefore}, its commit, so its path is incomplete` }
38
+ : compareToHistory(result.sigSequence, history.map((h) => h.sigSequence));
36
39
  // 2. Findings.
37
40
  const name = plan.join(' + ');
38
41
  const drafts = extractFindings(result, name);
@@ -59,7 +62,9 @@ export async function recordRun(opts) {
59
62
  }
60
63
  prev = sig;
61
64
  }
62
- // 4. The run.
65
+ // 4. The run. One whose path changed waits to be accepted before it
66
+ // counts as history — see Run.accepted.
67
+ const changedPath = result.ok && !drift.firstRun && (drift.changed || result.steps.some((s) => s.unexpectedPage));
63
68
  const run = {
64
69
  app,
65
70
  goal: opts.goal ?? flow,
@@ -77,6 +82,9 @@ export async function recordRun(opts) {
77
82
  };
78
83
  }),
79
84
  sigSequence: result.sigSequence,
85
+ ...(result.stoppedBefore !== undefined ? { stoppedBefore: result.stoppedBefore } : {}),
86
+ ...(changedPath ? { accepted: false } : {}),
87
+ starts: opts.starts ?? [0],
80
88
  events: result.signals.slice(0, 200).map((s) => ({ ...s })),
81
89
  findings: drafts.map((d) => d.fingerprint),
82
90
  durationMs: result.durationMs,
@@ -86,8 +94,36 @@ export async function recordRun(opts) {
86
94
  if (opts.runId) {
87
95
  // A planned run: keep its question history and planning, add what happened.
88
96
  await c.runs.updateOne({ _id: opts.runId }, { $set: run, $unset: { question: '' } });
89
- return { runId: opts.runId, drift, findings: drafts };
97
+ return { runId: opts.runId, drift, findings: drafts, ...(changedPath ? { pending: true } : {}) };
90
98
  }
91
99
  const { insertedId } = await c.runs.insertOne(run);
92
- return { runId: insertedId, drift, findings: drafts };
100
+ return { runId: insertedId, drift, findings: drafts, ...(changedPath ? { pending: true } : {}) };
101
+ }
102
+ /**
103
+ * A changed path was triaged `expected`: the runs that took it join the
104
+ * history, and the newest one's pages become what each of its flows expects
105
+ * step by step — so the change is accepted once, not flagged on every run.
106
+ */
107
+ export async function acceptPaths(app, fingerprints) {
108
+ if (!fingerprints.length)
109
+ return { runs: 0, flows: [] };
110
+ const c = await collections();
111
+ const pending = await c.runs.find({ app, accepted: false, findings: { $in: fingerprints } }).sort({ startedAt: 1 }).toArray();
112
+ if (!pending.length)
113
+ return { runs: 0, flows: [] };
114
+ await c.runs.updateMany({ _id: { $in: pending.map((r) => r._id) } }, { $unset: { accepted: '' } });
115
+ const newest = pending.at(-1);
116
+ const updated = [];
117
+ for (const [i, slug] of newest.plan.entries()) {
118
+ const flow = await c.flows.findOne({ app, slug });
119
+ if (!flow)
120
+ continue;
121
+ const start = newest.starts?.[i] ?? 0;
122
+ const sigAt = new Map(newest.steps.filter((s) => s.sig).map((s) => [s.seq - start, s.sig]));
123
+ const steps = flow.steps.map((s, j) => (sigAt.has(j) ? { ...s, expectedSig: sigAt.get(j) } : s));
124
+ const last = sigAt.get(flow.steps.length - 1);
125
+ await c.flows.updateOne({ _id: flow._id }, { $set: { steps, ...(last ? { endState: last } : {}), updatedAt: new Date() } });
126
+ updated.push(slug);
127
+ }
128
+ return { runs: pending.length, flows: updated };
93
129
  }
@@ -11,7 +11,8 @@
11
11
  import type { RawRecording } from '../core/recording.js';
12
12
  import type { ReplayResult } from '../core/replay.js';
13
13
  import type { Flow, Step } from '../store/types.js';
14
- import { type Proven } from './execute.js';
14
+ import { type CommitStep } from './destructive.js';
15
+ import { type Executed, type Proven } from './execute.js';
15
16
  import { type RecordedRun } from './runs.js';
16
17
  import { type Applied } from '../memory/placeholders.js';
17
18
  /** "Log in as a member!" → "log-in-as-a-member" */
@@ -70,5 +71,45 @@ export declare function proveAndSave(recording: RawRecording, opts: ProveAndSave
70
71
  * An unproven flow that just passed a run is proven now: mark it, and fill in
71
72
  * what its missing replay would have recorded — the page each step lands on,
72
73
  * and where it starts and ends. `offset` skips steps the run added in front.
74
+ *
75
+ * A run that stopped before the flow's commit step proves it that far
76
+ * (`provenUpTo`); a full run that passes proves the rest, and clears it.
73
77
  */
74
78
  export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number): Promise<boolean>;
79
+ export interface ProvedFlow extends Executed {
80
+ flow: Flow;
81
+ /** The commit step it stopped before, when the flow has one. */
82
+ commit?: CommitStep;
83
+ run: RecordedRun;
84
+ /** True when this run changed what the flow is proven to do. */
85
+ newlyProven: boolean;
86
+ }
87
+ /**
88
+ * Prove a saved flow where it stands — the way out for one kept with
89
+ * `verify: false` because it ends in a real purchase. A flow with a commit step
90
+ * is replayed up to it, and the commit's control is checked but never pressed;
91
+ * any other flow is simply run. Either way the run is recorded.
92
+ */
93
+ export declare function proveFlow(app: string, slug: string, opts?: {
94
+ values?: Record<string, string>;
95
+ headed?: boolean;
96
+ }): Promise<ProvedFlow>;
97
+ export interface StepToAdd {
98
+ /** Goes in front of the step at this index; the flow's length appends. */
99
+ before: number;
100
+ /** As stored: { action, value, hints? }. */
101
+ step: Record<string, unknown>;
102
+ }
103
+ /** Every problem with these additions at once, or the steps to insert. */
104
+ export declare function checkAdditions(flow: Pick<Flow, 'steps' | 'startUrl'>, adds: StepToAdd[]): {
105
+ steps: {
106
+ before: number;
107
+ step: Step;
108
+ }[];
109
+ problems: string[];
110
+ };
111
+ /**
112
+ * Add steps to a saved flow. It is unproven afterwards — a run that passes
113
+ * proves it again — and segments cut from it keep pointing at the same steps.
114
+ */
115
+ export declare function editFlow(app: string, slug: string, adds: StepToAdd[]): Promise<Flow>;