@ihyeon/error-to-test 0.2.8 → 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/README.ko.md CHANGED
@@ -260,7 +260,7 @@ Flow QA 설치와 실행 대상 설정은 별도로 필요합니다. 위 `flows/
260
260
 
261
261
  선택 실행 결과에는 `selection: { mode: 'selected', totalCases, selectedCaseIds }`를 기록하며 요약의 최신 실행에도 포함합니다. 기존 전체 실행 결과는 계속 읽을 수 있고, 새 선택 실행 결과는 이 버전 이상의 reader가 필요합니다. 이전 reader는 추가 필드를 거부합니다. 최신 실행에서 빠진 케이스는 과거에 통과했어도 `not-run`이며, 미실행을 CI 실패로 처리하려면 `results --fail-on not-run`을 사용하세요.
262
262
 
263
- 보고서에 실행 대상이 있으면 정제한 이름을 `targetName`으로 저장해 최신 실행 요약에 표시합니다. 대상 URL·기기 식별값은 복사하지 않습니다. 대상 이름은 고유 식별자가 아니므로 같은 이름을 다른 환경에 재사용하면 구별할 수 없습니다. 이전 reader는 이 추가 필드도 거부하며, 이름이 없는 기존 결과 파일은 계속 읽을 수 있습니다. 최신 실행은 연결된 전체 실행 중에서 고르므로 대상별 이력이 필요하면 번들을 분리하세요.
263
+ 보고서에 필요한 정보가 모두 있는 웹·모바일 실행 대상이 있으면 정제한 `targetName`과 `targetFingerprint`를 저장합니다. fingerprint는 Flow QA와 동일하게 웹 `{ kind: 'web', url }`, 모바일 `{ kind: 'mobile', platform, bundleId, device }`를 이 순서로 직렬화한 SHA-256입니다. 이름이 같아도 대상 정보가 다르면 서로 다른 실행으로 구별합니다. 대상 원본 값은 결과에 복사하지 않고 이름과 사유에서도 제거합니다. 다만 fingerprint는 대상을 아는 사람이 다시 계산해 대조할 수 있는 **안정적인 식별자이며 익명화가 아닙니다**. 이전 reader는 새 필드를 거부합니다. fingerprint가 없는 기존 전체·선택 실행 결과는 계속 읽지만 특정 대상 범위에는 넣지 않습니다. Flow QA가 초기 오류·중단을 빈 웹 URL로 보고하거나, 기기 지정이 없어 차단·중단된 모바일 실행을 빈 device로 보고한 경우에는 정제한 이름만 보존하고 fingerprint를 만들지 않습니다.
264
264
 
265
265
  연결한 결과는 `results`로 오류 묶음별 최신 TC 결과를 모아 볼 수 있습니다.
266
266
 
@@ -268,15 +268,16 @@ Flow QA 설치와 실행 대상 설정은 별도로 필요합니다. 위 `flows/
268
268
  error-to-test results .error-to-test/reviewed
269
269
  error-to-test results .error-to-test/reviewed --out ./run-summary.md
270
270
  error-to-test results .error-to-test/reviewed --format json --out ./run-summary.json
271
+ error-to-test results .error-to-test/reviewed --target-fingerprint "$TARGET_FINGERPRINT" --fail-on not-run
271
272
  ```
272
273
 
273
- 연결된 실행 수, 최신 실행의 상태·시각, TC 상태별 건수와 묶음별 결과·사유를 표시합니다. 통과·실패·flaky·차단·건너뜀·오류를 구분하고, 실행 결과가 없으면 선택된 TC를 `not-run`으로 표시합니다. TC가 선택되지 않은 원본 묶음도 남습니다.
274
+ 연결된 실행 수, 최신 실행의 상태·시각, TC 상태별 건수와 묶음별 결과·사유를 표시합니다. 대상별 fingerprint·정제된 이름·실행 수와 범위를 알 수 없는 기존/대상 없는/초기 실패 실행 수도 표시합니다. 먼저 필터 없는 JSON의 `targets[].fingerprint` 또는 Markdown에서 값을 확인하고 `--target-fingerprint`나 API의 `readRunSummary(directory, { targetFingerprint })`에 넣으세요. 64자리 소문자 16진수만 받으며, 해당 fingerprint가 없으면 빈 결과를 통과 처리하지 않고 오류(종료 코드 `1`)를 반환합니다. 대상 범위에서는 `runCount`가 그 대상의 실행 수, `excludedRunCount`가 제외된 전체 실행 수이며 최신 실행·TC 상태도 그 대상만 기준으로 합니다. 범위 밖의 결과 파일도 모두 검증합니다. 통과·실패·flaky·차단·건너뜀·오류를 구분하고, 실행 결과가 없으면 선택된 TC를 `not-run`으로 표시합니다. TC가 선택되지 않은 원본 묶음도 남습니다.
274
275
 
275
- 보고된 종료 시각이 가장 늦은 실행 하나를 기준으로 합니다. 종료 시각이 같으면 시작 시각, 실행 ID 순으로 결정하며 파일 수정 시각은 사용하지 않습니다. 여러 실행의 통과 결과를 섞지 않습니다. 연결된 실행이 있으면 검토 대기와 미확인 맥락도 표시하며, 결과를 원래 오류의 수정 완료나 실행 승인으로 취급하지 않습니다.
276
+ 보고된 종료 시각이 가장 늦은 실행 하나를 기준으로 합니다. 종료 시각이 같으면 시작 시각, 실행 ID 순으로 결정하며 파일 수정 시각은 사용하지 않습니다. 필터가 없으면 기존처럼 전체 연결 실행 중 최신 하나를 고르고, 대상이 여러 개이거나 fingerprint가 없는 실행이 있으면 경고합니다. 대상 필터를 지정하면 대상 없는 실행과 이름만 저장한 기존 실행은 제외합니다. 여러 실행이나 다른 대상의 통과 결과를 섞지 않습니다. 연결된 실행이 있으면 검토 대기와 미확인 맥락도 표시하며, 결과를 원래 오류의 수정 완료나 실행 승인으로 취급하지 않습니다.
276
277
 
277
278
  출력 전에 번들과 연결 결과의 형식·원본/suite 해시·case/group/event 연결·상태·시각을 검사합니다. 오래된 결과라도 잘못된 JSON이 있으면 실패하며, 기존 산출물과 결과 파일은 수정하지 않습니다. 결과 폴더는 최대 1,000개 항목, 각 JSON은 2 MiB, 전체 결과는 64 MiB까지 지원합니다. 다른 확장자의 부수 파일은 무시하고 잘못된 JSON 이름·심볼릭 링크·일반 파일이 아닌 결과·한도 초과는 거부합니다. `--out`은 번들의 `results` 폴더 밖에 있는 새 파일만 허용합니다.
278
279
 
279
- API에서는 `await readRunSummary(directory)`로 같은 데이터를 읽고 `renderRunSummary(summary)`로 Markdown을 만듭니다.
280
+ API에서는 `await readRunSummary(directory)`로 전체 요약을 읽고 `renderRunSummary(summary)`로 Markdown을 만듭니다. 대상별 조회는 `await readRunSummary(directory, { targetFingerprint: summary.targets[0].fingerprint })`를 사용합니다. `targets`가 비어 있으면 지정할 수 있는 대상이 없습니다.
280
281
 
281
282
  CI에서는 `results --fail-on`으로 **최신 연결 실행의 TC 상태에 따라 실패 여부**를 정할 수 있습니다.
282
283
 
@@ -295,9 +296,9 @@ error-to-test results ./analysis --fail-on failed --fail-on error --fail-on not-
295
296
 
296
297
  전체 보고서를 출력하거나 저장한 뒤 0 또는 2를 반환하고 숫자로 된 판정 요약은 stderr에 씁니다. JSON stdout은 기존 `error-to-test/run-summary-1` 형식이며 판정 필드를 추가하지 않습니다. 출력 오류는 판정 요약 없이 코드 1로 처리하고 기존 파일은 보존합니다.
297
298
 
298
- 최신 실행 하나의 TC 결과만 평가하며 과거 실패를 합치거나 실행 전체 상태를 별도 조건으로 삼지 않습니다. 연결 실행이 없으면 선택된 TC는 `not-run`이므로 미실행도 실패시킬 때 이 값을 지정하세요. 지정하지 않은 상태는 실패 조건이 아니지만, 선택된 TC가 없는 결과는 항상 코드 2입니다. 검토 대기와 미해결 맥락은 실행 전 `readiness`로 별도 점검하세요. 정책 통과는 검토 승인·브라우저 실행 증명·원본 오류 수정 완료를 의미하지 않습니다.
299
+ 선택한 대상 범위의 최신 실행 하나에 있는 TC 결과만 평가하며 과거 실패나 다른 대상의 결과를 합치거나 실행 전체 상태를 별도 조건으로 삼지 않습니다. 연결 실행이 없으면 선택된 TC는 `not-run`이므로 미실행도 실패시킬 때 이 값을 지정하세요. 지정하지 않은 상태는 실패 조건이 아니지만, 선택된 TC가 없는 결과는 항상 코드 2입니다. 검토 대기와 미해결 맥락은 실행 전 `readiness`로 별도 점검하세요. 정책 통과는 검토 승인·브라우저 실행 증명·원본 오류 수정 완료를 의미하지 않습니다.
299
300
 
300
- 옵션을 생략하면 기존 결과 조회 동작과 종료 코드를 유지합니다. `results`에서만 사용할 수 있고 API·저장 요약 형식은 바뀌지 않습니다. API에서는 `readRunSummary()`가 반환한 `counts`로 정책을 적용할 수 있습니다.
301
+ `--fail-on`을 생략하면 기존 결과 조회 동작과 종료 코드를 유지합니다. `--fail-on`과 `--target-fingerprint`는 `results` 전용입니다. 요약은 `error-to-test/run-summary-1`을 유지하면서 대상 목록·범위 필드를 추가합니다. API에서는 `readRunSummary(directory, { targetFingerprint })`가 반환한 `counts`로 정책을 적용할 수 있습니다.
301
302
 
302
303
  직접 입력은 문자열, 텍스트 파일, 표준 입력, `error-to-test/manual-1` JSON을 지원합니다. 파일 구조는 [수동 오류 예제](examples/manual.json), 정상 기대 동작과 단계 연결은 [프로필 예제](examples/profile.json)를 참고하세요. 전체 옵션은 `node bin/error-to-test.mjs --help`로 확인할 수 있습니다.
303
304
 
package/README.md CHANGED
@@ -370,7 +370,7 @@ The run's suite hash and reported case IDs must match. Safe case results are sto
370
370
 
371
371
  Selected results add `selection: { mode: 'selected', totalCases, selectedCaseIds }` to `error-to-test/results-1` and the latest run in `error-to-test/run-summary-1`. Older full result files remain supported. Use this version or newer to read selected result files; older readers reject the added selection field. Unselected cases are `not-run`, including when a previous full run passed. Use `results --fail-on not-run` when incomplete execution should fail a CI gate.
372
372
 
373
- When a report includes a target, its sanitized name is retained as optional `targetName` and displayed in the latest-run summary. Target URLs and device identifiers are not copied. The name is a reported label, not a unique target identity: reusing one name for different environments does not establish they are equivalent. Older readers also reject the new target field; older files without it remain readable. Latest-run selection still considers all linked runs; use separate bundles when target-specific histories are required.
373
+ When a report includes a complete supported web or mobile target, the linked result retains its sanitized `targetName` and a `targetFingerprint`. This SHA-256 value matches Flow QA's canonical identity: web `{ kind: 'web', url }` or mobile `{ kind: 'mobile', platform, bundleId, device }`, serialized in that key order. The target name is only a label; two targets with the same name remain distinct when their identities differ. Raw target fields are scrubbed from linked names and reasons rather than copied into results. The fingerprint is a stable identifier, **not anonymization**: someone who knows or guesses a target can calculate and recognize its fingerprint. Earlier readers reject the added field. Older full and selected result files without a fingerprint remain readable, but cannot be assigned to a target scope. Flow QA may also report an early `error` or `interrupted` with an empty web URL, or a `blocked` or `interrupted` mobile run with an empty device; these known fallback reports retain a sanitized name without inventing a fingerprint and remain unscoped.
374
374
 
375
375
  ### Summarize linked runs
376
376
 
@@ -380,11 +380,12 @@ Read the latest linked run's case outcomes by original error group:
380
380
  error-to-test results .error-to-test/reviewed
381
381
  error-to-test results .error-to-test/reviewed --out ./run-summary.md
382
382
  error-to-test results .error-to-test/reviewed --format json --out ./run-summary.json
383
+ error-to-test results .error-to-test/reviewed --target-fingerprint "$TARGET_FINGERPRINT" --fail-on not-run
383
384
  ```
384
385
 
385
- The summary includes the linked run count, latest run ID/status/timestamps and selected-run scope, case totals, and each group's cases and reported reasons. `passed`, `failed`, `flaky`, `blocked`, `skipped`, and `error` remain separate. Without any linked runs, or when a case was omitted from the latest selected run, that case is `not-run`; groups excluded from TC selection are shown without selected cases. An empty selection does not become a passing result.
386
+ The summary includes the linked run count, latest run ID/status/timestamps and selected-run scope, case totals, and each group's cases and reported reasons. It also lists each available target fingerprint, sanitized reported names, run count, and the number of unscoped legacy, targetless, or early fallback runs. Obtain a fingerprint from unfiltered JSON (`targets[].fingerprint`) or Markdown, then pass it to `--target-fingerprint` or `readRunSummary(directory, { targetFingerprint })`. The filter requires exactly 64 lowercase hex characters. An unknown fingerprint is an error (exit `1`), never a passing empty target. In a scoped summary, `runCount` counts only that target's runs, `excludedRunCount` counts all other runs, and the latest run and case counts come only from that target. Every linked file is still validated before filtering. `passed`, `failed`, `flaky`, `blocked`, `skipped`, and `error` remain separate. Without any linked runs, or when a case was omitted from the latest selected run, that case is `not-run`; groups excluded from TC selection are shown without selected cases. An empty selection does not become a passing result.
386
387
 
387
- Latest means the greatest reported `finishedAt`, then `startedAt`, then lexical run ID for ties. One whole run supplies all displayed case outcomes; earlier successes are never combined with newer runs to manufacture an all-passing result. When runs are linked, pending review and missing candidate context remain visible. These are supplied report outcomes, not review approval, independent execution proof, or evidence that the source issue is resolved.
388
+ Latest means the greatest reported `finishedAt`, then `startedAt`, then lexical run ID for ties. Without a target filter, latest still means latest across all linked runs; summaries warn when histories contain multiple target fingerprints or runs without one. A target filter excludes unscoped runs, including older name-only files. One whole run supplies all displayed case outcomes; earlier successes are never combined with newer runs to manufacture an all-passing result. When runs are linked, pending review and missing candidate context remain visible. These are supplied report outcomes, not review approval, independent execution proof, or evidence that the source issue is resolved.
388
389
 
389
390
  The bundle and every linked JSON result are checked before output: schema, source/suite hashes, exact case/group/event mappings, statuses, and timestamps must agree. Invalid older runs also fail the request. The reader accepts up to 1,000 directory entries, 2 MiB per result file, and 64 MiB total result bytes. Non-JSON incidental files are ignored; malformed JSON filenames, symlinks, non-regular result files, and limit violations are rejected. `--out` requires a new file outside the bundle's `results` directory and never overwrites existing content. Analysis artifacts and linked results remain unchanged.
390
391
 
@@ -396,6 +397,10 @@ import { readRunSummary, renderRunSummary } from '@ihyeon/error-to-test';
396
397
  const summary = await readRunSummary('./analysis');
397
398
  console.log(summary.counts);
398
399
  console.log(renderRunSummary(summary));
400
+ if (summary.targets.length) {
401
+ const targetSummary = await readRunSummary('./analysis', { targetFingerprint: summary.targets[0].fingerprint });
402
+ console.log(targetSummary.counts);
403
+ }
399
404
  ```
400
405
 
401
406
  ### Fail CI on selected case outcomes
@@ -417,9 +422,9 @@ Choose exact values from `failed`, `flaky`, `blocked`, `skipped`, `error`, and `
417
422
 
418
423
  The full existing Markdown/JSON report is output or saved before returning `0` or `2`. A numeric gate summary goes to stderr; JSON stdout remains `error-to-test/run-summary-1` without gate fields. Output errors take precedence and produce exit `1` without a gate outcome; existing output files and bundle results are preserved.
419
424
 
420
- Only the case outcomes from the one latest linked run are evaluated. Historical failures are not combined with newer results, and the overall run status is not a separate gate condition. Without a linked run, selected cases are `not-run`: include `--fail-on not-run` if unexecuted cases should fail. A status you did not choose does not fail the gate, but an empty selection always does. Use `readiness` separately to check recorded context/review blockers before execution. Passing this policy does not approve cases, prove a browser ran, or resolve source errors.
425
+ Only the case outcomes from the one latest linked run in the chosen scope are evaluated. Historical failures and outcomes from other targets are not combined with newer results, and the overall run status is not a separate gate condition. Without a linked run, selected cases are `not-run`: include `--fail-on not-run` if unexecuted cases should fail. A status you did not choose does not fail the gate, but an empty selection always does. Use `readiness` separately to check recorded context/review blockers before execution. Passing this policy does not approve cases, prove a browser ran, or resolve source errors.
421
426
 
422
- Omitting `--fail-on` preserves the existing results behavior and exit codes. The option is results-only; APIs and saved summary schemas are unchanged. API callers can apply their own policy to the `counts` returned by `await readRunSummary(directory)`.
427
+ Omitting `--fail-on` preserves the existing results behavior and exit codes. Both `--fail-on` and `--target-fingerprint` are results-only. The summary keeps `error-to-test/run-summary-1` with additive target inventory and scope fields. API callers can apply their own policy to the `counts` returned by `await readRunSummary(directory, { targetFingerprint })`.
423
428
 
424
429
  ## Data handling and checks
425
430
 
package/dist/cli.js CHANGED
@@ -28,7 +28,7 @@ const help = `Error to Test — local error analysis and regression TC drafts
28
28
  error-to-test refine new-directory --profile updated.json --out refined-directory [--reviewed]
29
29
  error-to-test issue new-directory --group GROUP_ID [--out issue.md]
30
30
  error-to-test link-run new-directory --report path/to/qa-report.json
31
- error-to-test results new-directory [--format text|json] [--out summary.md] [--fail-on STATUS ...]
31
+ error-to-test results new-directory [--format text|json] [--out summary.md] [--target-fingerprint SHA256] [--fail-on STATUS ...]
32
32
  error-to-test readiness new-directory [--format text|json]
33
33
  error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md] [--max-new N]
34
34
 
@@ -38,6 +38,7 @@ Options:
38
38
  --format auto|json|jsonl|text Analyze input format; JSONL requires explicit selection and one record per line; auto rejects malformed JSON-looking input
39
39
  --format text|json Results summary format (default: text Markdown)
40
40
  --fail-on STATUS Results gate: failed|flaky|blocked|skipped|error|not-run (repeatable; exit 2 on a match or no selected cases, 1 on error)
41
+ --target-fingerprint SHA256 Scope results and gate to this target's 64-character lowercase SHA-256 fingerprint
41
42
  --format text|json Compare format (default: text Markdown)
42
43
  --format text|json Readiness format (default: text Markdown; exit 0 ready, 2 blocked/empty, 1 on error)
43
44
  --profile FILE Confirmed app scenarios and explicit assertions (analyze/verify); existing profile to extend (init-profile)
@@ -160,7 +161,7 @@ export async function main(args = process.argv.slice(2)) {
160
161
  help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string', multiple: true }, error: { type: 'string' }, report: { type: 'string' },
161
162
  format: { type: 'string' }, profile: { type: 'string' }, baseline: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
162
163
  release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
163
- top: { type: 'string' }, 'min-count': { type: 'string' }, 'max-new': { type: 'string' }, group: { type: 'string', multiple: true }, 'fail-on': { type: 'string', multiple: true }, out: { type: 'string' }, reviewed: { type: 'boolean' },
164
+ top: { type: 'string' }, 'min-count': { type: 'string' }, 'max-new': { type: 'string' }, group: { type: 'string', multiple: true }, 'fail-on': { type: 'string', multiple: true }, 'target-fingerprint': { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
164
165
  reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
165
166
  expected: { type: 'string' }, 'expected-source': { type: 'string' },
166
167
  } });
@@ -275,8 +276,8 @@ export async function main(args = process.argv.slice(2)) {
275
276
  if (command === 'results') {
276
277
  if (positionals.length !== 2 || !positionals[1])
277
278
  throw new Error('results requires one bundle directory.');
278
- if (Object.keys(values).some(key => !['format', 'out', 'fail-on', 'help'].includes(key)))
279
- throw new Error('Unsupported option for results. Use only --format text|json, --out FILE, and --fail-on STATUS.');
279
+ if (Object.keys(values).some(key => !['format', 'out', 'fail-on', 'target-fingerprint', 'help'].includes(key)))
280
+ throw new Error('Unsupported option for results. Use only --format text|json, --out FILE, --target-fingerprint SHA256, and --fail-on STATUS.');
280
281
  const format = values.format ?? 'text';
281
282
  if (format !== 'text' && format !== 'json')
282
283
  throw new Error('results --format must be text or json.');
@@ -286,7 +287,7 @@ export async function main(args = process.argv.slice(2)) {
286
287
  }
287
288
  const failOn = requestedStatuses === undefined ? undefined : resultsGateStatuses.filter(status => requestedStatuses.includes(status));
288
289
  const bundle = resolve(positionals[1]);
289
- const summary = await readRunSummary(bundle);
290
+ const summary = await readRunSummary(bundle, { targetFingerprint: values['target-fingerprint'] });
290
291
  const content = format === 'json' ? jsonText(summary) : renderRunSummary(summary);
291
292
  if (Buffer.byteLength(content) > 64 * 1024 * 1024)
292
293
  throw new Error('The results summary exceeds 64 MiB. Narrow the bundle before requesting output.');
@@ -427,6 +428,8 @@ export async function main(args = process.argv.slice(2)) {
427
428
  throw new Error('--report applies to link-run only.');
428
429
  if (values['fail-on'] !== undefined)
429
430
  throw new Error('--fail-on applies to results only.');
431
+ if (values['target-fingerprint'] !== undefined)
432
+ throw new Error('--target-fingerprint applies to results only.');
430
433
  if (values['max-new'] !== undefined)
431
434
  throw new Error('--max-new applies to compare only.');
432
435
  if (values.baseline !== undefined && values.baseline.trim() === '')
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@ export { readIssueReport } from './issue-report.ts';
8
8
  export { linkFlowQaReport } from './results.ts';
9
9
  export { createProfileTemplate, type ProfileTemplateOptions } from './profile-template.ts';
10
10
  export { refineBundle } from './refinement.ts';
11
- export { readRunSummary, renderRunSummary, type RunSummary, type LinkedRunStatus, type LinkedCaseStatus } from './run-summary.ts';
11
+ export { readRunSummary, renderRunSummary, type RunSummary, type ReadRunSummaryOptions, type LinkedRunStatus, type LinkedCaseStatus } from './run-summary.ts';
12
12
  export { readReadiness, renderReadiness, type ReadinessSummary } from './readiness.ts';
13
13
  export { compareBundles, renderComparison, type AnalysisComparison, type ComparisonStatus, type ComparisonSide, type ComparisonOccurrence, type ComparisonIssue } from './comparison.ts';
14
14
  export type * from './types.ts';
@@ -6,4 +6,10 @@ export interface LinkedSelection {
6
6
  }
7
7
  /** Keep a reported label without persisting any URL that may carry sensitive path data. */
8
8
  export declare function safeReportedTargetName(value: unknown, label: string): string;
9
+ export declare function validatedTargetFingerprint(value: unknown, label: string): string;
10
+ /** Match Flow QA targetFingerprint's canonical identity and key order exactly. */
11
+ export declare function reportedTargetIdentity(value: unknown, status: string): {
12
+ targetName: string;
13
+ targetFingerprint?: string;
14
+ };
9
15
  export declare function validateResultSelection(value: unknown, present: boolean, caseIds: readonly string[], expectedIds: ReadonlySet<string>, source: 'Flow QA report' | 'Linked result'): LinkedSelection | undefined;
@@ -1,10 +1,69 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { redactText } from "./redact.js";
2
- import { text } from "./validation.js";
3
+ import { record, text } from "./validation.js";
3
4
  /** Keep a reported label without persisting any URL that may carry sensitive path data. */
4
5
  export function safeReportedTargetName(value, label) {
5
6
  const name = text(value, label);
6
7
  return redactText(name.replace(/[a-z][a-z0-9+.-]*:\/\/[^\s<>"']+|(?<!:)\/\/[^\s<>"']+/gi, '[redacted-url]'));
7
8
  }
9
+ const fingerprintPattern = /^[0-9a-f]{64}$/;
10
+ export function validatedTargetFingerprint(value, label) {
11
+ if (typeof value !== 'string' || !fingerprintPattern.test(value)) {
12
+ throw new Error(`${label} must be a lowercase SHA-256 fingerprint (64 hex characters).`);
13
+ }
14
+ return value;
15
+ }
16
+ /** Match Flow QA targetFingerprint's canonical identity and key order exactly. */
17
+ export function reportedTargetIdentity(value, status) {
18
+ const target = record(value, 'report.target');
19
+ const kind = target.kind;
20
+ const keys = kind === 'mobile' ? ['name', 'kind', 'platform', 'bundleId', 'device'] : ['name', 'kind', 'url'];
21
+ if ((kind !== undefined && kind !== 'web' && kind !== 'mobile')
22
+ || Object.keys(target).some(key => !keys.includes(key))) {
23
+ throw new Error('report.target has an unsupported shape or kind.');
24
+ }
25
+ let targetName = text(target.name, 'report.target.name');
26
+ let identity;
27
+ if (kind === 'mobile') {
28
+ if (target.platform !== 'ios' && target.platform !== 'android')
29
+ throw new Error('report.target.platform must be ios or android.');
30
+ const bundleId = text(target.bundleId, 'report.target.bundleId');
31
+ if (target.device === '') {
32
+ if (status !== 'blocked' && status !== 'interrupted')
33
+ throw new Error('report.target.device may be empty only for a blocked or interrupted mobile fallback report.');
34
+ targetName = targetName.replaceAll(bundleId, '[redacted-target]');
35
+ return { targetName: safeReportedTargetName(targetName, 'report.target.name') };
36
+ }
37
+ identity = {
38
+ kind: 'mobile', platform: target.platform,
39
+ bundleId,
40
+ device: text(target.device, 'report.target.device'),
41
+ };
42
+ for (const value of [identity.bundleId, identity.device])
43
+ targetName = targetName.replaceAll(value, '[redacted-target]');
44
+ }
45
+ else {
46
+ if (target.url === '') {
47
+ if (kind !== undefined || (status !== 'error' && status !== 'interrupted')) {
48
+ throw new Error('report.target.url may be empty only for an error or interrupted web fallback report.');
49
+ }
50
+ return { targetName: safeReportedTargetName(targetName, 'report.target.name') };
51
+ }
52
+ const url = text(target.url, 'report.target.url');
53
+ try {
54
+ const parsed = new URL(url);
55
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
56
+ throw new Error('Unsupported protocol');
57
+ }
58
+ catch {
59
+ throw new Error('report.target.url must be an HTTP or HTTPS URL.');
60
+ }
61
+ identity = { kind: 'web', url };
62
+ targetName = targetName.replaceAll(url, '[redacted-url]');
63
+ }
64
+ targetName = safeReportedTargetName(targetName, 'report.target.name');
65
+ return { targetName, targetFingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') };
66
+ }
8
67
  export function validateResultSelection(value, present, caseIds, expectedIds, source) {
9
68
  if (!present) {
10
69
  if (caseIds.length !== expectedIds.size)
package/dist/results.js CHANGED
@@ -3,7 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { jsonText, readVerifiedBundle } from "./artifacts.js";
4
4
  import { record, text, timestamp } from "./validation.js";
5
5
  import { redactText } from "./redact.js";
6
- import { safeReportedTargetName, validateResultSelection } from "./result-selection.js";
6
+ import { reportedTargetIdentity, validateResultSelection } from "./result-selection.js";
7
7
  const runStatuses = new Set(['passed', 'failed', 'blocked', 'error', 'interrupted']);
8
8
  const caseStatuses = new Set(['passed', 'failed', 'flaky', 'blocked', 'skipped', 'error']);
9
9
  /** Associate a normalized Flow QA report with the exact exported immutable suite. */
@@ -23,6 +23,11 @@ export async function linkFlowQaReport(directory, rawReport) {
23
23
  const status = text(report.status, 'report.status');
24
24
  if (!runStatuses.has(status))
25
25
  throw new Error('Invalid Flow QA run status.');
26
+ const rawTarget = report.target === undefined ? undefined : record(report.target, 'report.target');
27
+ const target = rawTarget === undefined ? undefined : reportedTargetIdentity(rawTarget, status);
28
+ const targetValues = rawTarget === undefined ? [] : rawTarget.kind === 'mobile'
29
+ ? [rawTarget.bundleId, rawTarget.device]
30
+ : [rawTarget.url];
26
31
  if (!Array.isArray(report.cases) || report.cases.length > 100 || !Array.isArray(provenance.mappings))
27
32
  throw new Error('Invalid Flow QA case list.');
28
33
  const mappings = provenance.mappings.map((item, index) => record(item, `mappings[${index}]`));
@@ -39,7 +44,14 @@ export async function linkFlowQaReport(directory, rawReport) {
39
44
  const caseStatus = text(original.status, 'case.status');
40
45
  if (!caseStatuses.has(caseStatus))
41
46
  throw new Error('Invalid Flow QA case status.');
42
- return { ...mapping, status: caseStatus, ...(original.reason === undefined ? {} : { reason: redactText(text(original.reason, 'case.reason')) }) };
47
+ let reason = original.reason === undefined ? undefined : text(original.reason, 'case.reason');
48
+ if (reason !== undefined) {
49
+ for (const value of targetValues)
50
+ if (value)
51
+ reason = reason.replaceAll(value, '[redacted-target]');
52
+ reason = redactText(reason);
53
+ }
54
+ return { ...mapping, status: caseStatus, ...(reason === undefined ? {} : { reason }) };
43
55
  });
44
56
  const selection = validateResultSelection(report.selection, Object.hasOwn(report, 'selection'), reportCaseIds, new Set(expected.keys()), 'Flow QA report');
45
57
  if (status === 'passed' && cases.some(item => item.status === 'failed' || item.status === 'error'))
@@ -47,13 +59,11 @@ export async function linkFlowQaReport(directory, rawReport) {
47
59
  const startedAt = timestamp(report.startedAt, 'report.startedAt'), finishedAt = timestamp(report.finishedAt, 'report.finishedAt');
48
60
  if (finishedAt < startedAt)
49
61
  throw new Error('The run finished before its start timestamp.');
50
- const targetName = report.target === undefined ? undefined
51
- : safeReportedTargetName(record(report.target, 'report.target').name, 'report.target.name');
52
62
  const output = {
53
63
  schemaVersion: 'error-to-test/results-1', runId,
54
64
  inputSha256: provenance.inputSha256, suiteSha256: provenance.suiteSha256,
55
65
  startedAt, finishedAt,
56
- status, ...(targetName === undefined ? {} : { targetName }),
66
+ status, ...(target === undefined ? {} : target),
57
67
  ...(selection === undefined ? {} : { selection }), cases,
58
68
  note: 'These results cover the specified assertions. No source issue was automatically closed.',
59
69
  };
@@ -7,12 +7,24 @@ export interface RunSummary {
7
7
  inputSha256: string;
8
8
  suiteSha256?: string;
9
9
  runCount: number;
10
+ /** Present only when a target fingerprint was requested. Counts and latestRun then use that target alone. */
11
+ selectedTargetFingerprint?: string;
12
+ /** Number of linked runs excluded from the selected target scope. */
13
+ excludedRunCount?: number;
14
+ /** Linked runs with no fingerprint, including legacy files with only targetName. */
15
+ unscopedRunCount: number;
16
+ targets: {
17
+ fingerprint: string;
18
+ names: string[];
19
+ runCount: number;
20
+ }[];
10
21
  latestRun?: {
11
22
  runId: string;
12
23
  status: LinkedRunStatus;
13
24
  startedAt: string;
14
25
  finishedAt: string;
15
26
  targetName?: string;
27
+ targetFingerprint?: string;
16
28
  selection?: LinkedSelection;
17
29
  };
18
30
  counts: Record<DisplayCaseStatus, number>;
@@ -29,6 +41,9 @@ export interface RunSummary {
29
41
  }[];
30
42
  warnings: string[];
31
43
  }
32
- export declare function readRunSummary(directory: string): Promise<RunSummary>;
44
+ export interface ReadRunSummaryOptions {
45
+ targetFingerprint?: string;
46
+ }
47
+ export declare function readRunSummary(directory: string, options?: ReadRunSummaryOptions): Promise<RunSummary>;
33
48
  export declare function renderRunSummary(summary: RunSummary): string;
34
49
  export {};
@@ -4,7 +4,7 @@ import { join, resolve } from 'node:path';
4
4
  import { literal, readVerifiedBundle } from "./artifacts.js";
5
5
  import { redactText } from "./redact.js";
6
6
  import { record, text, timestamp } from "./validation.js";
7
- import { safeReportedTargetName, validateResultSelection } from "./result-selection.js";
7
+ import { safeReportedTargetName, validatedTargetFingerprint, validateResultSelection } from "./result-selection.js";
8
8
  const runStatuses = new Set(['passed', 'failed', 'blocked', 'error', 'interrupted']);
9
9
  const caseStatuses = new Set(['passed', 'failed', 'flaky', 'blocked', 'skipped', 'error']);
10
10
  const countStatuses = ['passed', 'failed', 'flaky', 'blocked', 'skipped', 'error', 'not-run'];
@@ -82,7 +82,7 @@ function parseResult(content, name, inputSha256, suiteSha256, expected) {
82
82
  catch {
83
83
  throw new Error(`Linked result ${name} is not a valid JSON object.`);
84
84
  }
85
- exactKeys(raw, ['schemaVersion', 'runId', 'inputSha256', 'suiteSha256', 'startedAt', 'finishedAt', 'status', 'cases', 'note'], ['targetName', 'selection'], `Linked result ${name}`);
85
+ exactKeys(raw, ['schemaVersion', 'runId', 'inputSha256', 'suiteSha256', 'startedAt', 'finishedAt', 'status', 'cases', 'note'], ['targetName', 'targetFingerprint', 'selection'], `Linked result ${name}`);
86
86
  if (raw.schemaVersion !== 'error-to-test/results-1')
87
87
  throw new Error(`Linked result ${name} uses an unsupported schema.`);
88
88
  const runId = text(raw.runId, `${name}.runId`);
@@ -100,6 +100,8 @@ function parseResult(content, name, inputSha256, suiteSha256, expected) {
100
100
  throw new Error(`Linked result ${name} finished before it started.`);
101
101
  text(raw.note, `${name}.note`);
102
102
  const targetName = raw.targetName === undefined ? undefined : safeReportedTargetName(raw.targetName, `${name}.targetName`);
103
+ const targetFingerprint = raw.targetFingerprint === undefined ? undefined
104
+ : validatedTargetFingerprint(raw.targetFingerprint, `${name}.targetFingerprint`);
103
105
  if (!Array.isArray(raw.cases) || raw.cases.length > expected.size)
104
106
  throw new Error(`Linked result ${name} has an invalid case list.`);
105
107
  const seen = new Set();
@@ -126,7 +128,9 @@ function parseResult(content, name, inputSha256, suiteSha256, expected) {
126
128
  throw new Error(`Linked result ${name} contradicts its case results.`);
127
129
  }
128
130
  return { runId, status: status, startedAt, finishedAt,
129
- ...(targetName === undefined ? {} : { targetName }), ...(selection === undefined ? {} : { selection }), cases };
131
+ ...(targetName === undefined ? {} : { targetName }),
132
+ ...(targetFingerprint === undefined ? {} : { targetFingerprint }),
133
+ ...(selection === undefined ? {} : { selection }), cases };
130
134
  }
131
135
  function later(a, b) {
132
136
  if (a.finishedAt !== b.finishedAt)
@@ -140,7 +144,13 @@ function nonnegativeCount(value, label) {
140
144
  throw new Error(`${label} must be a non-negative integer.`);
141
145
  return value;
142
146
  }
143
- export async function readRunSummary(directory) {
147
+ export async function readRunSummary(directory, options = {}) {
148
+ if (options === null || typeof options !== 'object' || Array.isArray(options)
149
+ || Object.keys(options).some(key => key !== 'targetFingerprint')) {
150
+ throw new Error('readRunSummary options support only targetFingerprint.');
151
+ }
152
+ const selectedTargetFingerprint = options.targetFingerprint === undefined ? undefined
153
+ : validatedTargetFingerprint(options.targetFingerprint, 'targetFingerprint');
144
154
  const root = resolve(directory);
145
155
  const { analysis, provenance, verification } = await readVerifiedBundle(root);
146
156
  const inputSha256 = sha256(provenance.inputSha256, 'provenance.inputSha256');
@@ -180,7 +190,10 @@ export async function readRunSummary(directory) {
180
190
  if (error.code !== 'ENOENT')
181
191
  throw error;
182
192
  }
193
+ let totalRunCount = 0;
183
194
  let runCount = 0;
195
+ let unscopedRunCount = 0;
196
+ const targets = new Map();
184
197
  let latest;
185
198
  if (resultsInfo) {
186
199
  if (!resultsInfo.isDirectory() || resultsInfo.isSymbolicLink())
@@ -209,14 +222,32 @@ export async function readRunSummary(directory) {
209
222
  if (totalBytes > maxTotalBytes)
210
223
  throw new Error('Linked results exceed 64 MiB in total.');
211
224
  const run = parseResult(content, name, inputSha256, suiteSha256, expected);
212
- runCount++;
213
- if (!latest || later(run, latest))
214
- latest = run;
225
+ totalRunCount++;
226
+ if (run.targetFingerprint === undefined)
227
+ unscopedRunCount++;
228
+ else {
229
+ let target = targets.get(run.targetFingerprint);
230
+ if (!target) {
231
+ target = { fingerprint: run.targetFingerprint, names: new Set(), runCount: 0 };
232
+ targets.set(run.targetFingerprint, target);
233
+ }
234
+ target.runCount++;
235
+ if (run.targetName !== undefined)
236
+ target.names.add(run.targetName);
237
+ }
238
+ if (selectedTargetFingerprint === undefined || run.targetFingerprint === selectedTargetFingerprint) {
239
+ runCount++;
240
+ if (!latest || later(run, latest))
241
+ latest = run;
242
+ }
215
243
  }
216
244
  const after = await lstat(resultsRoot);
217
245
  if (!after.isDirectory() || after.isSymbolicLink() || !sameFile(resultsInfo, after))
218
246
  throw new Error('Results directory changed while reading.');
219
247
  }
248
+ if (selectedTargetFingerprint !== undefined && !targets.has(selectedTargetFingerprint)) {
249
+ throw new Error('No linked runs match the requested target fingerprint. Inspect the unfiltered results inventory.');
250
+ }
220
251
  const latestCases = new Map(latest?.cases.map(item => [item.caseId, item]) ?? []);
221
252
  const counts = Object.fromEntries(countStatuses.map(status => [status, 0]));
222
253
  for (const mapping of mappings) {
@@ -229,6 +260,15 @@ export async function readRunSummary(directory) {
229
260
  });
230
261
  }
231
262
  const warnings = ['Counts are the latest reported case outcomes, not proof that any source issue is resolved.'];
263
+ if (selectedTargetFingerprint === undefined && targets.size > 1) {
264
+ warnings.push(`This history contains ${targets.size} target fingerprints. Unfiltered counts use only the latest run across all targets; select a target fingerprint for target-specific counts.`);
265
+ }
266
+ if (unscopedRunCount > 0) {
267
+ warnings.push(`${unscopedRunCount} linked run(s) have no target fingerprint and cannot be assigned to a target scope (including legacy results).`);
268
+ }
269
+ if (selectedTargetFingerprint !== undefined && totalRunCount > runCount) {
270
+ warnings.push(`The selected target scope excludes ${totalRunCount - runCount} linked run(s), including ${unscopedRunCount} unscoped run(s).`);
271
+ }
232
272
  if (latest?.selection)
233
273
  warnings.push(`Latest linked run selected ${latest.selection.selectedCaseIds.length} of ${latest.selection.totalCases} exported cases. Unselected cases are not-run even if an earlier run reported outcomes for them.`);
234
274
  if (analysis.warnings !== undefined)
@@ -249,8 +289,13 @@ export async function readRunSummary(directory) {
249
289
  return {
250
290
  schemaVersion: 'error-to-test/run-summary-1', inputSha256,
251
291
  ...(suiteSha256 === undefined ? {} : { suiteSha256 }), runCount,
292
+ ...(selectedTargetFingerprint === undefined ? {} : { selectedTargetFingerprint, excludedRunCount: totalRunCount - runCount }),
293
+ unscopedRunCount,
294
+ targets: [...targets.values()].sort((a, b) => a.fingerprint.localeCompare(b.fingerprint))
295
+ .map(target => ({ fingerprint: target.fingerprint, names: [...target.names].sort(), runCount: target.runCount })),
252
296
  ...(latest === undefined ? {} : { latestRun: { runId: latest.runId, status: latest.status, startedAt: latest.startedAt, finishedAt: latest.finishedAt,
253
297
  ...(latest.targetName === undefined ? {} : { targetName: latest.targetName }),
298
+ ...(latest.targetFingerprint === undefined ? {} : { targetFingerprint: latest.targetFingerprint }),
254
299
  ...(latest.selection === undefined ? {} : { selection: latest.selection }) } }),
255
300
  counts, groups, warnings,
256
301
  };
@@ -259,7 +304,22 @@ export function renderRunSummary(summary) {
259
304
  const lines = ['# Linked run summary', '', `Input SHA-256: ${sha256(summary.inputSha256, 'summary.inputSha256')}`];
260
305
  if (summary.suiteSha256 !== undefined)
261
306
  lines.push(`Suite SHA-256: ${sha256(summary.suiteSha256, 'summary.suiteSha256')}`);
262
- lines.push(`Linked runs: ${nonnegativeCount(summary.runCount, 'summary.runCount')}`, '');
307
+ if (summary.selectedTargetFingerprint !== undefined) {
308
+ lines.push(`Selected target fingerprint: ${validatedTargetFingerprint(summary.selectedTargetFingerprint, 'summary.selectedTargetFingerprint')}`, `Excluded linked runs: ${nonnegativeCount(summary.excludedRunCount, 'summary.excludedRunCount')}`);
309
+ }
310
+ lines.push(`Linked runs: ${nonnegativeCount(summary.runCount, 'summary.runCount')}`, `Unscoped linked runs: ${nonnegativeCount(summary.unscopedRunCount, 'summary.unscopedRunCount')}`, '');
311
+ lines.push('## Available targets', '');
312
+ if (!Array.isArray(summary.targets) || !summary.targets.length)
313
+ lines.push('No fingerprinted targets were found.', '');
314
+ else {
315
+ for (const target of summary.targets) {
316
+ lines.push(`Fingerprint: ${validatedTargetFingerprint(target.fingerprint, 'summary.targets.fingerprint')}`, `Linked runs: ${nonnegativeCount(target.runCount, 'summary.targets.runCount')}`, '');
317
+ if (!Array.isArray(target.names))
318
+ throw new Error('summary.targets.names must be an array.');
319
+ if (target.names.length)
320
+ lines.push('Reported names:', '', literal(target.names.map(name => safeReportedTargetName(name, 'summary.targets.names')).join('\n')), '');
321
+ }
322
+ }
263
323
  if (summary.latestRun) {
264
324
  const run = summary.latestRun;
265
325
  if (!uuidPattern.test(run.runId) || !runStatuses.has(run.status))
@@ -267,6 +327,8 @@ export function renderRunSummary(summary) {
267
327
  lines.push('## Latest linked run', '', `Run ID: ${run.runId}`, `Reported status: ${run.status}`, `Started: ${timestamp(run.startedAt, 'summary.latestRun.startedAt')}`, `Finished: ${timestamp(run.finishedAt, 'summary.latestRun.finishedAt')}`, '');
268
328
  if (run.targetName)
269
329
  lines.push('Reported target name:', '', literal(safeReportedTargetName(run.targetName, 'summary.latestRun.targetName')), '');
330
+ if (run.targetFingerprint)
331
+ lines.push(`Target fingerprint: ${validatedTargetFingerprint(run.targetFingerprint, 'summary.latestRun.targetFingerprint')}`, '');
270
332
  if (run.selection)
271
333
  lines.push(`Selected cases: ${run.selection.selectedCaseIds.length} of ${run.selection.totalCases} exported cases`, '');
272
334
  }
package/docs/releases.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  Package: `@ihyeon/error-to-test` · Repository: [hyeonse-swing/error-to-test](https://github.com/hyeonse-swing/error-to-test) · Workflow: `.github/workflows/ci.yml`.
4
4
 
5
+ ## 0.3.0 — target-scoped linked results
6
+
7
+ Linked Flow QA results now retain an optional SHA-256 `targetFingerprint` calculated from Flow QA's exact canonical web or mobile target identity. Target names are sanitized labels; two targets can use the same name. Raw target fields are scrubbed from linked names and reasons. A fingerprint is a stable, guessable identifier rather than anonymization. The linker validates the target kind and required fields before writing. Flow QA's early error/interrupted report with an empty web URL, and blocked/interrupted mobile report with an empty device, remain linkable with a sanitized name but no invented fingerprint; other incomplete target/status combinations are rejected.
8
+
9
+ `results --target-fingerprint SHA256` and `readRunSummary(directory, { targetFingerprint })` select one target's latest run and case counts, including `--fail-on` decisions. Unfiltered results still use the latest run across all targets. Summaries list fingerprinted targets, their sanitized names and run counts, and the number of unscoped runs; scoped summaries also report excluded runs. Legacy full and partial files, targetless reports, and early fallback reports without a fingerprint remain readable but cannot join a target scope. Unknown fingerprints fail rather than producing a passing gate. Every linked file is validated before scope selection, including older and nonselected files. New additive fields keep the `error-to-test/results-1` and `error-to-test/run-summary-1` schema labels; older readers reject new linked files that contain the fingerprint.
10
+
11
+ The ecosystem smoke also exercises same-name distinct target URLs and a real Flow QA unresolved-target error. To include the standalone SQLite collector, set `BROWSER_ERROR_LOG_MICRO_DIRECTORY` to a built or extracted micro-server directory containing `server.mjs` and `export.mjs`; the smoke stores captured SDK events, stops the collector, verifies a read-only export, and analyzes that export through the installed CLI.
12
+
13
+ Local checks on 2026-11-16: `npm run check` passed type checking, build, and 203 tests; `npm run check:package` passed the isolated package consumer smoke.
14
+
5
15
  ## 0.2.8
6
16
 
7
17
  Restores compatibility with Browser Error Log resource events across input, CLI, profiles, comparisons and refinement, and with Flow QA selected-run reports. Valid v1 network status values (0..599) are preserved; values below 100 are described as unavailable HTTP status rather than a response.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ihyeon/error-to-test",
3
- "version": "0.2.8",
3
+ "version": "0.3.0",
4
4
  "description": "Turn captured browser errors and pasted error reports into traceable regression test candidates.",
5
5
  "license": "MIT",
6
6
  "author": "Hyeonse Im",