@ihyeon/flow-qa 0.10.13 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ko.md CHANGED
@@ -80,6 +80,8 @@ CLI에서는 `flow-qa run cases/task-flow.json --target demo --case TC-001 --cas
80
80
 
81
81
  CLI에서는 `flow-qa reruns .flowqa/runs/<원본-실행-ID> --workspace my-qa --lang ko`로 원본에서 직접 시작한 재실행의 상태와 저장 폴더를 찾습니다. 목록에 나온 폴더는 같은 `--workspace`의 `flow-qa report`에 넘기거나 원본 폴더와 함께 `flow-qa compare`에 넘길 수 있습니다. 불완전한 기록은 목록에서 제외합니다.
82
82
 
83
+ `flow-qa rerun .flowqa/runs/<원본-실행-ID> --workspace my-qa --lang ko`를 실행하면 원본에서 실패·실행 오류가 난 케이스만 원래 등록한 대상에 다시 실행합니다. 새 보고서에 원본 실행 ID가 남으므로 `reruns`와 `compare`에서 결과 변화를 볼 수 있습니다. 실패·오류 케이스가 없으면 새 실행을 만들지 않고 안내와 함께 정상 종료합니다. 저장된 케이스·원본 플로우·대상이 바뀌었다면 실행 전에 중단합니다. 각 케이스에는 독립적인 시작 상태가 필요합니다.
84
+
83
85
  `0.8.0`부터 **상세 보고서**에서 케이스·오류 내용을 검색하고 상태별로 좁히거나 **실패·오류만** 볼 수 있습니다. **시도 2회 이상만 보기**(0.8.7)를 켜면 여러 번 시도한 케이스만 표시합니다. 표시 건수와 보고서 전체 케이스 수를 구분하며, Markdown·JSON 다운로드와 실패·오류 재실행 준비는 보고서 전체 범위를 유지합니다. 필터에 맞는 ID만 화면 순서대로 저장하려면 **표시된 케이스 ID 다운로드**(0.8.6)를 선택하세요. 자세한 동작은 [보고서 케이스 탐색](docs/ui.md#explore-cases-in-a-report)을 참고하세요.
84
86
 
85
87
  ## 실행 결과 비교
package/README.md CHANGED
@@ -80,6 +80,8 @@ From an original report, **Find reruns of this run** shows directly linked runs
80
80
 
81
81
  In the CLI, `flow-qa reruns .flowqa/runs/<original-run-id> --workspace my-qa` lists direct reruns with their status and saved directory. Pass a listed directory to `flow-qa report` or compare it with the original using `flow-qa compare` and the same `--workspace`. The command checks the saved reports and skips incomplete entries.
82
82
 
83
+ Run `flow-qa rerun .flowqa/runs/<original-run-id> --workspace my-qa` to execute only its failed and errored cases against the original registered target. The new report records the original run ID, so `reruns` and `compare` can show what changed. A report with no failed or errored cases prints a message and exits successfully without creating another run. If the saved cases, source flow, or target changed, the command stops before starting a run. Each case must establish its own starting state.
84
+
83
85
  From `0.8.0`, **Detailed report** supports case/error-text search, status filters, and **Failed/error only**. Use **At least 2 attempts** (0.8.7) to see only cases with multiple recorded attempts. Counts distinguish displayed matches from all recorded cases. Markdown/JSON downloads and failed/error preparation retain the full report scope. To save just the filtered IDs in the displayed order, choose **Download visible case IDs** (0.8.6). See [report case exploration](docs/ui.md#explore-cases-in-a-report).
84
86
 
85
87
  ## Compare recorded runs
package/dist/src/cli.js CHANGED
@@ -5,13 +5,14 @@ import { resolve, dirname, basename, join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { parseArgs } from 'node:util';
7
7
  import { localeFromEnv, localized, localizeProductMessage } from "./i18n.js";
8
- import { configSchema, idSchema, modelSchema, targetSchema } from "./schema.js";
8
+ import { configSchema, idSchema, modelSchema, suiteSchema, targetSchema } from "./schema.js";
9
9
  import { initWorkspace, readConfig, readSuite, sha256, verifySuiteSource, withConfigLock, writeConfig, writeJSON } from "./workspace.js";
10
10
  import { buildPlanningPrompt, planFlow } from "./planner.js";
11
11
  import { compileSuite } from "./compiler.js";
12
12
  import { CaseSelectionError, isReportSelectionValid, selectCases } from "./case-selection.js";
13
13
  import { runSuite } from "./engine.js";
14
14
  import { MAX_SAVED_REPORT_BYTES, RUN_ID, parseArchivedReportEnvelope, renderSavedMarkdown } from "./report.js";
15
+ import { prepareRerunSelection } from "./rerun.js";
15
16
  import { registrationTarget, sameReportTarget, targetLabel } from "./targets.js";
16
17
  import { compareCaseSteps } from "./step-comparison.js";
17
18
  import { createAgentHandoff, reviewAgentHandoff } from "./agent-handoff.js";
@@ -38,6 +39,7 @@ Usage: flow-qa <command> [arguments] [options]
38
39
  agent-review <handoff-dir> <result.json>
39
40
  Check agent-supplied findings and evidence references
40
41
  report <run-directory> View a saved QA report
42
+ rerun <run-directory> Rerun failed/error cases from a saved report
41
43
  reruns <run-directory> List runs prepared from a saved report
42
44
  compare <run-a> <run-b> Compare case results and authored steps
43
45
  ui [--demo] [--port 4310] Start the local QA UI
@@ -70,6 +72,7 @@ Local example: flow-qa ui --demo
70
72
  agent-review <handoff-dir> <result.json>
71
73
  에이전트 관찰 결과와 증거 파일 참조 검사
72
74
  report <run-directory> 저장된 QA 리포트 보기
75
+ rerun <run-directory> 저장된 실행의 실패·오류 케이스 재실행
73
76
  reruns <run-directory> 저장된 리포트에서 시작한 재실행 찾기
74
77
  compare <run-a> <run-b> 케이스 결과와 원본 단계 비교
75
78
  ui [--demo] [--port 4310] 로컬 QA 화면 실행
@@ -137,6 +140,82 @@ async function chromiumInstalled() {
137
140
  return false;
138
141
  }
139
142
  }
143
+ const SAFE_CASE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
144
+ async function safeWorkspaceDirectory(workspace, parts, message = 'Invalid workspace path.') {
145
+ let directory = workspace;
146
+ for (const part of parts) {
147
+ directory = join(directory, part);
148
+ const info = await lstat(directory);
149
+ if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== directory) {
150
+ throw new Error(message);
151
+ }
152
+ }
153
+ return directory;
154
+ }
155
+ async function readSafeFile(directory, name, limit) {
156
+ const path = join(directory, name);
157
+ const info = await lstat(path);
158
+ if (!info.isFile() || info.isSymbolicLink() || info.size > limit || await realpath(path) !== path) {
159
+ throw new Error('Invalid saved file path or size.');
160
+ }
161
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
162
+ try {
163
+ const opened = await handle.stat();
164
+ if (!opened.isFile() || opened.size > limit)
165
+ throw new Error('Invalid saved file path or size.');
166
+ return await handle.readFile('utf8');
167
+ }
168
+ finally {
169
+ await handle.close();
170
+ }
171
+ }
172
+ function savedFlowName(suite, roots) {
173
+ if (!suite.source)
174
+ return undefined;
175
+ const file = suite.source.file;
176
+ const relative = /^(?:\.\/)?flows\/([^/\\]+)$/.exec(file);
177
+ const name = relative?.[1] ?? (roots.includes(dirname(file)) ? basename(file) : undefined);
178
+ if (!name || !SAFE_CASE_NAME.test(name) || name.includes('..') || !name.endsWith('.md')) {
179
+ throw new Error('Invalid source flow path.');
180
+ }
181
+ return name;
182
+ }
183
+ async function savedRunPath(workspace, input, locale) {
184
+ const canonicalWorkspace = await realpath(workspace);
185
+ const root = await safeWorkspaceDirectory(canonicalWorkspace, ['.flowqa', 'runs'], localized(locale, 'Invalid workspace run path.', '작업 공간의 실행 경로가 유효하지 않습니다.'));
186
+ const selectedDir = resolve(workspace, required(input, localized(locale, 'Run directory', '실행 폴더'), locale));
187
+ const id = basename(selectedDir);
188
+ const info = await lstat(selectedDir);
189
+ if (!RUN_ID.test(id) || !info.isDirectory() || info.isSymbolicLink() || await realpath(selectedDir) !== join(root, id)) {
190
+ throw new Error(localized(locale, 'Choose a saved run in this workspace.', '이 작업 공간에 저장된 실행을 선택하세요.'));
191
+ }
192
+ return { canonicalWorkspace, root, id };
193
+ }
194
+ async function readArchivedRun(root, id) {
195
+ const directory = join(root, id);
196
+ const info = await lstat(directory);
197
+ if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== directory)
198
+ return undefined;
199
+ const report = parseArchivedReportEnvelope(JSON.parse(await readSafeFile(directory, 'qa-report.json', MAX_SAVED_REPORT_BYTES)));
200
+ return report?.runId === id ? report : undefined;
201
+ }
202
+ async function executeRun(options, locale, rerun = false) {
203
+ const controller = new AbortController();
204
+ const interrupt = () => controller.abort();
205
+ process.once('SIGINT', interrupt);
206
+ process.once('SIGTERM', interrupt);
207
+ try {
208
+ const { report, runDir } = await runSuite({ ...options, signal: controller.signal });
209
+ if (report.selection)
210
+ console.log(localized(locale, `${rerun ? 'Selected rerun' : 'Selected run'}: ${report.selection.caseIds.length}/${report.selection.totalCases} cases; the full suite was not evaluated.`, `${rerun ? '선택 재실행' : '선택 실행'}: ${report.selection.totalCases}개 중 ${report.selection.caseIds.length}개. 전체 케이스를 검증한 결과가 아닙니다.`));
211
+ console.log(localized(locale, `Run result: ${report.status}\nQA report: ${resolve(runDir, 'qa-report.md')}\nRaw result: ${resolve(runDir, 'qa-report.json')}`, `실행 결과: ${report.status}\nQA 리포트: ${resolve(runDir, 'qa-report.md')}\n원본 결과: ${resolve(runDir, 'qa-report.json')}`));
212
+ process.exitCode = report.status === 'passed' ? 0 : report.status === 'interrupted' ? 130 : 1;
213
+ }
214
+ finally {
215
+ process.off('SIGINT', interrupt);
216
+ process.off('SIGTERM', interrupt);
217
+ }
218
+ }
140
219
  export async function main(args) {
141
220
  let locale = localeFromEnv();
142
221
  try {
@@ -250,7 +329,11 @@ export async function main(args) {
250
329
  throw error;
251
330
  }
252
331
  const suite = await planFlow(flow, config.planner, { platform });
253
- suite.source = { file: arg, sha256: sha256(flow) };
332
+ const sourceDirectory = dirname(flowPath);
333
+ const inWorkspaceFlows = sourceDirectory === join(workspace, 'flows')
334
+ || sourceDirectory === join(await realpath(workspace), 'flows');
335
+ const sourceFile = inWorkspaceFlows ? `flows/${basename(flowPath)}` : arg;
336
+ suite.source = { file: sourceFile, sha256: sha256(flow) };
254
337
  await writeJSON(output, suite, true);
255
338
  console.log(localized(locale, `Cases created: ${output}\n${suite.cases.filter((c) => c.questions.length).length} of ${suite.cases.length} cases have open questions.`, `케이스 생성: ${output}\n${suite.cases.length}개 중 확인 질문이 있는 케이스 ${suite.cases.filter((c) => c.questions.length).length}개`));
256
339
  return;
@@ -315,22 +398,8 @@ export async function main(args) {
315
398
  throw new Error(localizeProductMessage('Select one or more unique cases from this suite.', locale));
316
399
  throw error;
317
400
  }
318
- const controller = new AbortController();
319
- const interrupt = () => controller.abort();
320
- process.once('SIGINT', interrupt);
321
- process.once('SIGTERM', interrupt);
322
- try {
323
- const { report, runDir } = await runSuite({ workspace, suite, config, targetName: required(targetName, '--target', locale), signal: controller.signal,
324
- ...(caseIds ? { caseIds } : {}) });
325
- if (report.selection)
326
- console.log(localized(locale, `Selected run: ${report.selection.caseIds.length}/${report.selection.totalCases} cases; the full suite was not evaluated.`, `선택 실행: ${report.selection.totalCases}개 중 ${report.selection.caseIds.length}개. 전체 케이스를 검증한 결과가 아닙니다.`));
327
- console.log(localized(locale, `Run result: ${report.status}\nQA report: ${resolve(runDir, 'qa-report.md')}\nRaw result: ${resolve(runDir, 'qa-report.json')}`, `실행 결과: ${report.status}\nQA 리포트: ${resolve(runDir, 'qa-report.md')}\n원본 결과: ${resolve(runDir, 'qa-report.json')}`));
328
- process.exitCode = report.status === 'passed' ? 0 : report.status === 'interrupted' ? 130 : 1;
329
- }
330
- finally {
331
- process.off('SIGINT', interrupt);
332
- process.off('SIGTERM', interrupt);
333
- }
401
+ await executeRun({ workspace, suite, config, targetName: required(targetName, '--target', locale),
402
+ ...(caseIds ? { caseIds } : {}) }, locale);
334
403
  return;
335
404
  }
336
405
  if (command === 'report') {
@@ -343,52 +412,66 @@ export async function main(args) {
343
412
  console.log(content.replace(/\u001b/g, ''));
344
413
  return;
345
414
  }
346
- if (command === 'reruns') {
347
- if (second)
348
- throw new Error(localized(locale, 'reruns accepts one run directory.', 'reruns에는 실행 폴더 하나만 지정하세요.'));
349
- const canonicalWorkspace = await realpath(workspace);
350
- let root = canonicalWorkspace;
351
- for (const part of ['.flowqa', 'runs']) {
352
- root = join(root, part);
353
- const info = await lstat(root);
354
- if (!info.isDirectory() || info.isSymbolicLink() || await realpath(root) !== root) {
355
- throw new Error(localized(locale, 'Invalid workspace run path.', '작업 공간의 실행 경로가 유효하지 않습니다.'));
356
- }
415
+ if (command === 'rerun') {
416
+ if (positionals.length !== 2 || values.target !== undefined || values.out !== undefined ||
417
+ values.url !== undefined || values.model !== undefined || values['key-env'] !== undefined || values['prompt-only']) {
418
+ throw new Error(localized(locale, 'rerun accepts one run directory and the saved target.', 'rerun에는 실행 폴더 하나와 저장된 대상만 사용할 수 있습니다.'));
419
+ }
420
+ const { canonicalWorkspace, root: runsRoot, id: originalId } = await savedRunPath(workspace, arg, locale);
421
+ let previous;
422
+ try {
423
+ previous = await readArchivedRun(runsRoot, originalId);
357
424
  }
358
- const selectedDir = resolve(workspace, required(arg, localized(locale, 'Run directory', '실행 폴더'), locale));
359
- const originalId = basename(selectedDir);
360
- const selectedInfo = await lstat(selectedDir);
361
- if (!RUN_ID.test(originalId) || selectedInfo.isSymbolicLink() ||
362
- await realpath(selectedDir) !== join(root, originalId)) {
363
- throw new Error(localized(locale, 'Choose a saved run in this workspace.', '이 작업 공간에 저장된 실행을 선택하세요.'));
425
+ catch { /* Invalid or unsafe saved run. */ }
426
+ if (!previous || previous.runId !== originalId) {
427
+ throw new Error(localized(locale, 'This is not a valid saved run.', '유효한 저장 실행이 아닙니다.'));
364
428
  }
365
- const readReport = async (id) => {
366
- const dir = join(root, id);
367
- const dirInfo = await lstat(dir);
368
- if (!dirInfo.isDirectory() || dirInfo.isSymbolicLink() || await realpath(dir) !== dir)
369
- return undefined;
370
- const file = join(dir, 'qa-report.json');
371
- const fileInfo = await lstat(file);
372
- if (!fileInfo.isFile() || fileInfo.isSymbolicLink() || fileInfo.size > MAX_SAVED_REPORT_BYTES ||
373
- await realpath(file) !== file)
374
- return undefined;
375
- const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
376
- let contents;
429
+ const casesRoot = await safeWorkspaceDirectory(canonicalWorkspace, ['cases']);
430
+ const matches = [];
431
+ const flowRoots = [join(canonicalWorkspace, 'flows'), join(workspace, 'flows')];
432
+ for (const file of await readdir(casesRoot)) {
433
+ if (!SAFE_CASE_NAME.test(file) || file.includes('..') || !file.endsWith('.json'))
434
+ continue;
377
435
  try {
378
- const opened = await handle.stat();
379
- if (!opened.isFile() || opened.size > MAX_SAVED_REPORT_BYTES)
380
- return undefined;
381
- contents = await handle.readFile('utf8');
436
+ const suite = suiteSchema.parse(JSON.parse(await readSafeFile(casesRoot, file, 1024 * 1024)));
437
+ savedFlowName(suite, flowRoots);
438
+ if (suite.id === previous.suiteId)
439
+ matches.push({ file, suite });
382
440
  }
383
- finally {
384
- await handle.close();
441
+ catch { /* Invalid or unsafe case files are absent from the saved library. */ }
442
+ }
443
+ if (matches.length !== 1) {
444
+ throw new Error(localized(locale, matches.length ? 'Multiple saved case files match this report.' : 'No saved case file matches this report.', matches.length ? '이 보고서와 일치하는 케이스 파일이 여러 개입니다.' : '이 보고서와 일치하는 케이스 파일이 없습니다.'));
445
+ }
446
+ const suite = matches[0].suite;
447
+ const flowName = savedFlowName(suite, flowRoots);
448
+ if (flowName) {
449
+ const flowRoot = await safeWorkspaceDirectory(canonicalWorkspace, ['flows']);
450
+ const flow = await readSafeFile(flowRoot, flowName, 128 * 1024);
451
+ if (sha256(flow) !== suite.source.sha256) {
452
+ throw new Error(localized(locale, 'The source flow changed. Save the cases again.', '원본 플로우가 변경됐습니다. 케이스를 다시 저장하세요.'));
385
453
  }
386
- const report = parseArchivedReportEnvelope(JSON.parse(contents));
387
- return report?.runId === id ? report : undefined;
388
- };
454
+ }
455
+ const config = configSchema.parse(JSON.parse(await readSafeFile(canonicalWorkspace, 'flowqa.config.json', 256 * 1024)));
456
+ const prepared = prepareRerunSelection(previous, suite, config);
457
+ if (prepared.caseIds.length === 0) {
458
+ console.log(localizeProductMessage('No failed or errored cases are available to rerun.', locale));
459
+ return;
460
+ }
461
+ if (!prepared.targetMatches) {
462
+ throw new Error(localized(locale, 'The selected target changed. Review it again.', '실행 대상 설정이 변경됐습니다. 다시 확인하세요.'));
463
+ }
464
+ await executeRun({ workspace: canonicalWorkspace, suite, config, targetName: prepared.targetName,
465
+ caseIds: prepared.caseIds, parentRunId: originalId }, locale, true);
466
+ return;
467
+ }
468
+ if (command === 'reruns') {
469
+ if (second)
470
+ throw new Error(localized(locale, 'reruns accepts one run directory.', 'reruns에는 실행 폴더 하나만 지정하세요.'));
471
+ const { root, id: originalId } = await savedRunPath(workspace, arg, locale);
389
472
  let original;
390
473
  try {
391
- original = await readReport(originalId);
474
+ original = await readArchivedRun(root, originalId);
392
475
  }
393
476
  catch { /* Invalid saved run. */ }
394
477
  if (!original)
@@ -398,7 +481,7 @@ export async function main(args) {
398
481
  if (!RUN_ID.test(id) || id === originalId)
399
482
  continue;
400
483
  try {
401
- const report = await readReport(id);
484
+ const report = await readArchivedRun(root, id);
402
485
  if (report?.parentRunId !== originalId)
403
486
  continue;
404
487
  matches.push({ id, status: report.status, mtime: (await lstat(join(root, id))).mtimeMs });
@@ -0,0 +1,28 @@
1
+ import { isReportSelectionValid } from "./case-selection.js";
2
+ import { targetFingerprint } from "./targets.js";
3
+ import { sha256 } from "./workspace.js";
4
+ /** Keep CLI and UI reruns tied to the same saved suite, cases, and target. */
5
+ export function prepareRerunSelection(previous, suite, settings) {
6
+ if (sha256(`${JSON.stringify(suite, null, 2)}\n`) !== previous.suiteHash) {
7
+ throw new Error('The saved case file changed since this run. Review it before rerunning.');
8
+ }
9
+ const available = new Set(suite.cases.map((item) => item.id));
10
+ if (previous.cases.some((item) => !item.id.trim() || !available.has(item.id)) ||
11
+ new Set(previous.cases.map((item) => item.id)).size !== previous.cases.length ||
12
+ (!previous.selection && previous.cases.length !== suite.cases.length)) {
13
+ throw new Error('The report cases do not match the saved case file.');
14
+ }
15
+ if (previous.selection && (previous.selection.totalCases !== suite.cases.length ||
16
+ !isReportSelectionValid(previous.cases, previous.selection))) {
17
+ throw new Error('The report selection does not match the saved case file.');
18
+ }
19
+ const failing = new Set(previous.cases.filter((item) => item.status === 'failed' || item.status === 'error').map((item) => item.id));
20
+ const caseIds = suite.cases.filter((item) => failing.has(item.id)).map((item) => item.id);
21
+ const targetName = previous.target.name;
22
+ const expectedFingerprint = targetFingerprint(previous.target);
23
+ const currentTarget = Object.hasOwn(settings.targets, targetName) ? settings.targets[targetName] : undefined;
24
+ return { caseIds, targetName, targetFingerprint: expectedFingerprint,
25
+ targetMatches: Boolean(currentTarget &&
26
+ (suite.platform ?? 'web') === (currentTarget.kind === 'mobile' ? 'mobile' : 'web') &&
27
+ targetFingerprint(currentTarget) === expectedFingerprint) };
28
+ }
@@ -34,9 +34,10 @@ async function start(args, locale) {
34
34
  throw new StartupError(localized(locale, 'Port must be an integer from 0 to 65535. Example: flow-qa ui --port 4311', '포트는 0~65535 사이 정수여야 합니다. 예: flow-qa ui --port 4311'));
35
35
  if (values.demo && values.workspace)
36
36
  throw new StartupError(localized(locale, '--demo and --workspace cannot be used together.', '--demo와 --workspace는 함께 사용할 수 없습니다.'));
37
+ const requestedWorkspace = resolve(values.workspace ?? '.');
37
38
  let workspace;
38
39
  try {
39
- workspace = await realpath(resolve(values.workspace ?? '.'));
40
+ workspace = await realpath(requestedWorkspace);
40
41
  }
41
42
  catch {
42
43
  throw new StartupError(localized(locale, 'Workspace directory not found. Run flow-qa init /path/to/my-qa first, then pass --workspace.', '작업 공간 디렉터리를 찾을 수 없습니다. 먼저 flow-qa init /path/to/my-qa로 준비한 뒤 --workspace로 지정하세요.'));
@@ -69,7 +70,7 @@ async function start(args, locale) {
69
70
  throw error;
70
71
  }
71
72
  }
72
- ui = await startUIServer({ workspace, port });
73
+ ui = await startUIServer({ workspace, port, ...(values.demo ? {} : { workspaceAlias: requestedWorkspace }) });
73
74
  console.log(localized(locale, `Flow QA: ${ui.url}\nWorkspace: ${workspace}`, `Flow QA: ${ui.url}\n작업 공간: ${workspace}`));
74
75
  if (demo)
75
76
  console.log(localized(locale, `Local demo app: ${demo.url}\nOpen the example in the case library, review it, then run it in a real browser. No model call is made.`, `로컬 데모 앱: ${demo.url}\n케이스 보관함에서 예제를 열고 검토한 뒤 실제 브라우저로 실행하세요. 모델 호출은 없습니다.`));
@@ -107,6 +107,13 @@
107
107
  return Boolean(app.draft && app.script && app.savedFile && app.savedHash && !app.dirty && !app.stale && !app.busy && !hasUnsavedScenario());
108
108
  }
109
109
  function canDownloadSourceMarkdown() { return canDownloadSavedCases() && Boolean(app.draft.source); }
110
+ function sourceFileName(source) { return source.file.split(/[\\/]/).at(-1); }
111
+ function downloadSavedCases() {
112
+ if (!canDownloadSavedCases()) return;
113
+ const { source } = app.draft;
114
+ const suite = source ? { ...app.draft, source: { ...source, file: `flows/${sourceFileName(source)}` } } : app.draft;
115
+ download(app.savedFile, `${JSON.stringify(suite, null, 2)}\n`, 'application/json');
116
+ }
110
117
  function readiness() {
111
118
  const active = app.state?.active;
112
119
  const ready = !!app.draft && !!app.script && !app.stale && !app.dirty;
@@ -704,7 +711,10 @@
704
711
  if (jsonFiles[0].size > 1024 * 1024 || (markdownFiles[0] && markdownFiles[0].size > 128 * 1024)) throw localizedError('app.importTooLarge');
705
712
  let suite;
706
713
  try { suite = JSON.parse(await jsonFiles[0].text()); } catch { throw localizedError('app.invalidJson'); }
707
- const flow = markdownFiles[0] ? await markdownFiles[0].text() : undefined;
714
+ // Keep an initial UTF-8 BOM in the text used to verify the source hash.
715
+ const flow = markdownFiles[0]
716
+ ? new TextDecoder('utf-8', { ignoreBOM: true }).decode(await markdownFiles[0].arrayBuffer())
717
+ : undefined;
708
718
  const body = { suite, ...(flow === undefined ? {} : { flow }) };
709
719
  if (new TextEncoder().encode(JSON.stringify(body)).byteLength > 256 * 1024) throw localizedError('app.importTooLarge');
710
720
  const result = await api('/api/import', body);
@@ -1073,8 +1083,8 @@
1073
1083
  $('import-btn').addEventListener('click', importFiles);
1074
1084
  $('global-stop-btn').addEventListener('click', stop);
1075
1085
  $('reconnect-btn').addEventListener('click', () => refresh(true).catch(showError));
1076
- $('suite-download').addEventListener('click', () => { if (canDownloadSavedCases()) download(app.savedFile, `${JSON.stringify(app.draft, null, 2)}\n`, 'application/json'); });
1077
- $('flow-download').addEventListener('click', () => { if (canDownloadSourceMarkdown()) download(app.draft.source.file.split('/').pop(), app.sourceFlow, 'text/markdown'); });
1086
+ $('suite-download').addEventListener('click', downloadSavedCases);
1087
+ $('flow-download').addEventListener('click', () => { if (canDownloadSourceMarkdown()) download(sourceFileName(app.draft.source), app.sourceFlow, 'text/markdown'); });
1078
1088
  $('script-download').addEventListener('click', () => { if (app.draft && !app.dirty && !app.stale) download(`${app.draft.id || 'flow-qa'}.test.mjs`, app.script, 'text/javascript'); });
1079
1089
  $('report-md').addEventListener('click', downloadReportMarkdown);
1080
1090
  $('report-json').addEventListener('click', () => { if (app.report) download(`${app.selectedRun}.json`, JSON.stringify(app.report, null, 2), 'application/json'); });
@@ -15,12 +15,13 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
15
15
  import { z } from 'zod';
16
16
  import { chromium } from 'playwright';
17
17
  import { compileSuite } from "../compiler.js";
18
- import { CaseSelectionError, isReportSelectionValid, selectCases } from "../case-selection.js";
18
+ import { CaseSelectionError, selectCases } from "../case-selection.js";
19
19
  import { runSuite } from "../engine.js";
20
20
  import { localeFromAcceptLanguage, localizeProductMessage } from "../i18n.js";
21
21
  import { EvidenceError, readEvidence } from "./evidence.js";
22
22
  import { buildPlanningPrompt, planFlow, PlannerError } from "../planner.js";
23
23
  import { MAX_SAVED_REPORT_BYTES, RUN_ID, parseArchivedReportEnvelope, renderSavedMarkdown } from "../report.js";
24
+ import { prepareRerunSelection } from "../rerun.js";
24
25
  import { compareReports, ComparisonError, renderComparisonMarkdown } from "../run-comparison.js";
25
26
  import { configSchema, idSchema, modelSchema, suiteSchema, targetSchema } from "../schema.js";
26
27
  import { registrationTarget, targetFingerprint } from "../targets.js";
@@ -180,13 +181,17 @@ function safeBasename(value, extension) {
180
181
  invalid('Invalid file name.');
181
182
  return value;
182
183
  }
183
- function sourceName(suite) {
184
+ function sourceName(suite, workspaceFlowRoots = []) {
184
185
  if (!suite.source)
185
186
  return undefined;
186
- const match = /^flows\/([^/\\]+)$/.exec(suite.source.file);
187
- if (!match)
188
- invalid('Invalid source flow path.');
189
- return safeBasename(match[1], '.md');
187
+ const file = suite.source.file;
188
+ const match = /^(?:\.\/)?flows\/([^/\\]+)$/.exec(file);
189
+ if (match)
190
+ return safeBasename(match[1], '.md');
191
+ if (path.isAbsolute(file) && workspaceFlowRoots.includes(path.dirname(file))) {
192
+ return safeBasename(path.basename(file), '.md');
193
+ }
194
+ return invalid('Invalid source flow path.');
190
195
  }
191
196
  function headers(response) {
192
197
  response.setHeader('Cache-Control', 'no-store');
@@ -224,6 +229,7 @@ export async function startUIServer(options) {
224
229
  const workspace = await realpath(options.workspace);
225
230
  if (!(await lstat(workspace)).isDirectory())
226
231
  throw new Error('Flow QA workspace does not exist.');
232
+ const workspaceFlowRoots = [path.join(workspace, 'flows'), path.resolve(options.workspaceAlias ?? options.workspace, 'flows')];
227
233
  const port = options.port ?? 4310;
228
234
  if (!Number.isInteger(port) || port < 0 || port > 65535)
229
235
  throw new Error('Invalid UI port.');
@@ -338,7 +344,7 @@ export async function startUIServer(options) {
338
344
  }
339
345
  }
340
346
  async function readSource(suite, verify) {
341
- const name = sourceName(suite);
347
+ const name = sourceName(suite, workspaceFlowRoots);
342
348
  if (!name)
343
349
  return undefined;
344
350
  const root = await directory(['flows']);
@@ -380,7 +386,7 @@ export async function startUIServer(options) {
380
386
  for (const file of files) {
381
387
  try {
382
388
  const suite = parse(suiteSchema, jsonObject(await readRegular(root, file, MAX_SUITE)));
383
- sourceName(suite);
389
+ sourceName(suite, workspaceFlowRoots);
384
390
  summaries.push({ file, id: suite.id, title: suite.title, caseCount: suite.cases.length,
385
391
  questionCount: suite.cases.reduce((count, testCase) => count + testCase.questions.length, 0) });
386
392
  }
@@ -439,33 +445,17 @@ export async function startUIServer(options) {
439
445
  }
440
446
  throw error;
441
447
  }
442
- const { suite } = selected;
443
- if (sha256(`${JSON.stringify(suite, null, 2)}\n`) !== previous.suiteHash) {
444
- throw new HTTPError(409, 'The saved case file changed since this run. Review it before rerunning.');
445
- }
446
- const available = new Set(suite.cases.map((item) => item.id));
447
- if (previous.cases.some((item) => !item.id.trim() || !available.has(item.id)) ||
448
- new Set(previous.cases.map((item) => item.id)).size !== previous.cases.length ||
449
- (!previous.selection && previous.cases.length !== suite.cases.length)) {
450
- throw new HTTPError(409, 'The report cases do not match the saved case file.');
448
+ const settings = await config();
449
+ try {
450
+ const prepared = prepareRerunSelection(previous, selected.suite, settings);
451
+ if (prepared.caseIds.length === 0)
452
+ throw new Error('No failed or errored cases are available to rerun.');
453
+ return { originRunId: runId, file, ...selected,
454
+ ...prepared };
451
455
  }
452
- if (previous.selection && (previous.selection.totalCases !== suite.cases.length ||
453
- !isReportSelectionValid(previous.cases, previous.selection))) {
454
- throw new HTTPError(409, 'The report selection does not match the saved case file.');
456
+ catch (error) {
457
+ throw new HTTPError(409, error.message);
455
458
  }
456
- const failing = new Set(previous.cases.filter((item) => item.status === 'failed' || item.status === 'error').map((item) => item.id));
457
- const caseIds = suite.cases.filter((item) => failing.has(item.id)).map((item) => item.id);
458
- if (caseIds.length === 0)
459
- throw new HTTPError(409, 'No failed or errored cases are available to rerun.');
460
- const settings = await config();
461
- const targetName = previous.target.name;
462
- const expectedFingerprint = targetFingerprint(previous.target);
463
- const currentTarget = Object.hasOwn(settings.targets, targetName) ? settings.targets[targetName] : undefined;
464
- return { originRunId: runId, file, ...selected, caseIds, targetName,
465
- targetFingerprint: expectedFingerprint,
466
- targetMatches: Boolean(currentTarget &&
467
- (suite.platform ?? 'web') === (currentTarget.kind === 'mobile' ? 'mobile' : 'web') &&
468
- targetFingerprint(currentTarget) === expectedFingerprint) };
469
459
  }
470
460
  async function runCandidates() {
471
461
  const root = await directory(['.flowqa', 'runs']);
package/docs/releases.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Releases and verification
2
2
 
3
+ ## 0.11.0 — rerun failed cases from the CLI
4
+
5
+ `flow-qa rerun <saved-run> --workspace <workspace>` runs the failed or errored cases from an original report against its unchanged registered target. It shares the local UI's checks for the saved suite, selected cases, and target identity. The new report retains `parentRunId`, and `reruns` lists it. A report without failed or errored cases exits successfully with an informational message and creates no run. Changed definitions, source flows, targets, and unsafe saved paths stop before execution.
6
+
3
7
  ## 0.10.8 — Concurrent configuration updates
4
8
 
5
9
  CLI `connect` and `model` commands and the local UI's target and model settings now lock the same canonical configuration file before reading and saving it. Concurrent commands that update different targets or model roles retain every successful change. The lock is stored in the private `.flowqa` directory beside the actual configuration file, including when a CLI workspace uses a symlink to that file. A terminated writer releases its SQLite lock automatically, so another command can retry. Each save still replaces the complete JSON file after it is written.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ihyeon/flow-qa",
3
- "version": "0.10.13",
3
+ "version": "0.11.0",
4
4
  "license": "MIT",
5
5
  "author": "Hyeonse Im",
6
6
  "repository": {