@ihyeon/error-to-test 0.2.4 → 0.2.6

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
@@ -188,6 +188,25 @@ TC 생성과 동일하게 모든 조건을 함께 검사해 기존 규칙이 적
188
188
 
189
189
  API는 `createProfileTemplate(analysis, { profile: existingProfile })`입니다. JSON 값만으로 구성한 객체 또는 BOM 하나를 지원하는 JSON 문자열을 1 MiB까지 받으며 입력 객체를 변경하지 않습니다. 객체의 선택 필드가 `undefined`이면 해당 속성을 생략하세요. `profile`을 생략하면 기존 빈 템플릿을 만듭니다.
190
190
 
191
+ 프로필을 보완한 뒤에는 **원본 로그 없이 기존 번들에서 TC를 다시 생성**할 수 있습니다.
192
+
193
+ ```sh
194
+ error-to-test refine ./initial-analysis --profile ./review-profile.json --out ./refined
195
+ error-to-test readiness ./refined
196
+ # 새 프로필과 TC를 검토한 뒤 별도 새 번들에 검토 확인
197
+ error-to-test refine ./initial-analysis --profile ./review-profile.json --reviewed --out ./refined-reviewed
198
+ ```
199
+
200
+ 기존에 실제 TC로 선택됐던 묶음만 저장된 순서대로 재생성합니다. 넓은 프로필 규칙도 이전에 제외된 묶음을 새로 선택하지 않으며, 선택된 한 묶음에 여러 규칙이 적용되면 여러 TC를 만들 수 있습니다. 전체 오류 묶음·원본 해시와 입력 파일 목록·수집 범위·이전 분석 기준과 그룹 선택 정보는 보존합니다. 선택 범위나 원본 메타데이터·필터·순위를 바꾸려면 원본 입력으로 `analyze`를 다시 실행하세요.
201
+
202
+ 새 프로필로 전체를 교체하며 기존 프로필과 병합하지 않습니다. 1 MiB 제한과 BOM 하나 지원을 유지하고 정확한 프로필 바이트를 새 해시에 반영합니다. 검증된 원본 번들은 한 번 읽으며, `analysis.refinement`에 직전 분석·suite·프로필 해시와 기존 선택 묶음 ID를 기록합니다. 반복 재생성 시 이 항목은 직전 번들 기준으로 교체합니다.
203
+
204
+ 대표 로그 5개 밖에서 확인된 질문과 충돌도 저장된 전체 묶음 맥락을 통해 계속 차단합니다. 이 맥락이 없는 오래된 번들, 선택된 TC가 없는 번들, 변경된 산출물, 잘못된 프로필은 거부합니다. 저장된 전체 맥락이 없으면 원본 로그로 다시 분석해야 합니다. `--reviewed`도 미해결 질문을 제거하지 않으며, 기존 번들이 검토됐어도 새 번들은 기본적으로 검토 대기입니다.
205
+
206
+ 출력은 원본 번들 전체의 바깥에 있는 새 디렉터리여야 하며 경로 별칭도 검사합니다. 원본 산출물과 연결 실행 결과는 수정하지 않고, 과거 실행 결과도 새 번들에 복사하지 않습니다. 원본 입력 바이트를 다시 확인하는 기능은 아니므로 원본이 있으면 `verify ./refined --input ... --profile ./review-profile.json`로 별도 검증하세요. `--profile`·`--out`은 필수이며 분석 필터나 그룹 선택 옵션은 받지 않습니다. 브라우저 실행이나 원본 오류의 수정 완료 처리는 수행하지 않습니다.
207
+
208
+ API는 `await refineBundle(directory, profileJsonText)`입니다. JSON 문자열을 받아 새 `Analysis`를 반환하며 파일 저장·검토 승인·종료 코드 변경은 하지 않습니다. 저장하려면 별도 새 경로에 `writeBundle()`을 호출하세요.
209
+
191
210
  ```sh
192
211
  node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
193
212
  node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --reviewed --out .error-to-test/reviewed
@@ -237,6 +256,27 @@ error-to-test results .error-to-test/reviewed --format json --out ./run-summary.
237
256
 
238
257
  API에서는 `await readRunSummary(directory)`로 같은 데이터를 읽고 `renderRunSummary(summary)`로 Markdown을 만듭니다.
239
258
 
259
+ CI에서는 `results --fail-on`으로 **최신 연결 실행의 TC 상태에 따라 실패 여부**를 정할 수 있습니다.
260
+
261
+ ```sh
262
+ error-to-test results ./analysis --fail-on failed --fail-on error
263
+ error-to-test results ./analysis --fail-on failed --fail-on error --fail-on not-run --format json --out ./ci-results.json
264
+ ```
265
+
266
+ `failed`·`flaky`·`blocked`·`skipped`·`error`·`not-run` 중 정확한 값을 반복 지정합니다. 중복은 한 번만 처리하고 입력 순서와 무관하게 같은 정책을 적용합니다. 쉼표로 합친 값이나 `passed`, 실행 전체 상태인 `interrupted` 등은 번들을 읽기 전에 거부합니다.
267
+
268
+ | 종료 코드 | `--fail-on` 사용 시 의미 |
269
+ | --- | --- |
270
+ | `0` | 선택된 TC가 하나 이상이고 지정한 상태에 해당하는 TC가 없음 |
271
+ | `1` | 잘못된 옵션·잘못되거나 변경된 번들/결과·출력 오류 |
272
+ | `2` | 지정한 상태의 TC가 있거나 선택된 TC가 없음 |
273
+
274
+ 전체 보고서를 출력하거나 저장한 뒤 0 또는 2를 반환하고 숫자로 된 판정 요약은 stderr에 씁니다. JSON stdout은 기존 `error-to-test/run-summary-1` 형식이며 판정 필드를 추가하지 않습니다. 출력 오류는 판정 요약 없이 코드 1로 처리하고 기존 파일은 보존합니다.
275
+
276
+ 최신 실행 하나의 TC 결과만 평가하며 과거 실패를 합치거나 실행 전체 상태를 별도 조건으로 삼지 않습니다. 연결 실행이 없으면 선택된 TC는 `not-run`이므로 미실행도 실패시킬 때 이 값을 지정하세요. 지정하지 않은 상태는 실패 조건이 아니지만, 선택된 TC가 없는 결과는 항상 코드 2입니다. 검토 대기와 미해결 맥락은 실행 전 `readiness`로 별도 점검하세요. 정책 통과는 검토 승인·브라우저 실행 증명·원본 오류 수정 완료를 의미하지 않습니다.
277
+
278
+ 옵션을 생략하면 기존 결과 조회 동작과 종료 코드를 유지합니다. `results`에서만 사용할 수 있고 API·저장 요약 형식은 바뀌지 않습니다. API에서는 `readRunSummary()`가 반환한 `counts`로 정책을 적용할 수 있습니다.
279
+
240
280
  직접 입력은 문자열, 텍스트 파일, 표준 입력, `error-to-test/manual-1` JSON을 지원합니다. 파일 구조는 [수동 오류 예제](examples/manual.json), 정상 기대 동작과 단계 연결은 [프로필 예제](examples/profile.json)를 참고하세요. 전체 옵션은 `node bin/error-to-test.mjs --help`로 확인할 수 있습니다.
241
281
 
242
282
  알려진 자격증명·이메일·URL 인증/쿼리 정보는 결과에서 정제합니다. 민감정보가 포함된 실행 단계나 기대 결과는 변경해 통과시키지 않고 질문으로 남깁니다. 모든 개인정보를 제거한다고 보장하지 않으므로 실제 업무 데이터를 입력하기 전에는 별도로 정제하세요. 비공개 오류는 셸 기록에 남는 인자 대신 파일·표준 입력을 사용하세요.
package/README.md CHANGED
@@ -233,6 +233,40 @@ New templates retain blank expectation fields, `setupConfirmed: false`, and the
233
233
 
234
234
  The API is `createProfileTemplate(analysis, { profile: existingProfile })`; `profile` accepts an object containing only JSON values or a JSON string, including one leading BOM, within 1 MiB. Omit undefined optional properties from object inputs. The function does not mutate either input. Without `profile`, it produces the original blank template.
235
235
 
236
+ ### Apply a new profile without the original logs
237
+
238
+ `refine` regenerates TC candidates from a verified saved bundle and a replacement profile. It is useful after editing a generated profile when the original log files are no longer available:
239
+
240
+ ```sh
241
+ error-to-test init-profile ./initial-analysis --out ./review-profile.json
242
+ # Fill confirmed requirements, setup, actions, and assertions in review-profile.json.
243
+ error-to-test refine ./initial-analysis --profile ./review-profile.json --out ./refined
244
+ error-to-test readiness ./refined
245
+ # After reviewing the replacement profile and cases, write another new bundle:
246
+ error-to-test refine ./initial-analysis --profile ./review-profile.json --reviewed --out ./refined-reviewed
247
+ ```
248
+
249
+ Only groups represented by the source bundle's selected candidates are regenerated, in their saved order. Broad profile rules cannot add previously excluded groups; several matching rules can create several cases for a selected group. All observed groups, source fingerprints, coverage, and baseline/group selection metadata are preserved. To change the selected groups, original metadata, filters, or ranking, run `analyze` again with the original input.
250
+
251
+ The replacement profile is parsed as a complete profile, not merged with the old one. Its exact bytes, including one optional leading BOM, determine the new profile hash; the 1 MiB profile limit applies. The source is read once as a verified snapshot. `analysis.refinement` records the immediate source analysis/suite/profile hashes and previously selected group IDs; repeated refinement replaces this lineage entry rather than embedding history.
252
+
253
+ Saved full-group context questions and conflicts remain blockers even when they came from records outside the five representative samples. Bundles without complete saved group context, empty selections, changed artifacts, invalid profiles, or unsupported data are rejected. Reanalyze original logs to upgrade older bundles missing that context. No source defect is marked resolved and no browser is executed.
254
+
255
+ The output must be a new directory outside the entire source bundle, including path aliases; source artifacts and linked results remain untouched. Linked runs are not copied. Review acknowledgement defaults to pending even if the old bundle was reviewed. `--reviewed` only acknowledges the new review and does not clear missing context.
256
+
257
+ Original input bytes are not rechecked by `refine`; retained fingerprints describe the supplied saved analysis. If originals are available, use `verify ./refined --input ... --profile ./review-profile.json` to check them separately. The command requires `--profile` and `--out`; analyze-only filters and selection options are not accepted.
258
+
259
+ ```js
260
+ import { readFile } from 'node:fs/promises';
261
+ import { refineBundle, writeBundle } from '@ihyeon/error-to-test';
262
+
263
+ const profileText = await readFile('./review-profile.json', 'utf8');
264
+ const analysis = await refineBundle('./initial-analysis', profileText);
265
+ await writeBundle('./refined', analysis); // Review remains pending by default.
266
+ ```
267
+
268
+ `refineBundle(directory, profileText)` accepts JSON text and returns a new `Analysis`. It does not write files, approve cases, or change process exit codes. Use a separate new output directory when writing the result.
269
+
236
270
  ## Review and use Flow QA
237
271
 
238
272
  Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
@@ -332,6 +366,29 @@ console.log(summary.counts);
332
366
  console.log(renderRunSummary(summary));
333
367
  ```
334
368
 
369
+ ### Fail CI on selected case outcomes
370
+
371
+ Use repeatable `--fail-on` with `results` to apply a policy to the latest linked run's case counts:
372
+
373
+ ```sh
374
+ error-to-test results ./analysis --fail-on failed --fail-on error
375
+ error-to-test results ./analysis --fail-on failed --fail-on error --fail-on not-run --format json --out ./ci-results.json
376
+ ```
377
+
378
+ Choose exact values from `failed`, `flaky`, `blocked`, `skipped`, `error`, and `not-run`. Duplicates are counted once; option order does not change the policy or summary. Comma-separated values, `passed`, and run-level statuses such as `interrupted` are rejected before reading the bundle.
379
+
380
+ | Exit code | Meaning with `--fail-on` |
381
+ | --- | --- |
382
+ | `0` | At least one selected case, and none have a chosen outcome |
383
+ | `1` | Invalid options, invalid or changed bundle/result, or output error |
384
+ | `2` | A chosen outcome exists, or no cases were selected |
385
+
386
+ 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.
387
+
388
+ 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.
389
+
390
+ 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)`.
391
+
335
392
  ## Data handling and checks
336
393
 
337
394
  Known credential assignments, bearer/recognized token formats, email addresses, and URL userinfo/query/fragment are removed before artifacts. Sensitive execution steps are omitted and block the case rather than silently changing its assertion. This is best-effort redaction, not a guarantee of complete anonymization; remove private application data before submitting it. Use files/stdin for private reports to avoid shell history. Logs are source data, not instructions. No external URL from a log becomes an execution target automatically.
package/dist/artifacts.js CHANGED
@@ -30,6 +30,15 @@ export function renderReport(analysis) {
30
30
  'The source SHA-256 commits to the ordered file hashes and byte lengths. Verify with every original file in the same order.',
31
31
  ...analysis.source.inputs.map((input, index) => `${index + 1}. SHA-256: ${input.sha256} · Bytes: ${input.byteLength}`),
32
32
  ].join('\n')), '');
33
+ if (analysis.refinement)
34
+ lines.push('## Profile refinement', '', literal([
35
+ `Source analysis SHA-256: ${analysis.refinement.sourceAnalysisSha256}`,
36
+ ...(analysis.refinement.sourceSuiteSha256 ? [`Source suite SHA-256: ${analysis.refinement.sourceSuiteSha256}`] : []),
37
+ ...(analysis.refinement.sourceProfileSha256 ? [`Source profile SHA-256: ${analysis.refinement.sourceProfileSha256}`] : []),
38
+ `Previously selected group IDs: ${analysis.refinement.selectedGroupIds.join(', ')}`,
39
+ 'TCs were regenerated from the verified saved groups and a replacement profile. Original input was not rechecked; selection and source coverage were not expanded.',
40
+ 'The new bundle has its own review acknowledgement and suite. Linked run results were not transferred.',
41
+ ].join('\n')), '');
33
42
  if (analysis.groupFilter)
34
43
  lines.push('## Explicit group selection', '', literal([
35
44
  `Requested group IDs: ${analysis.groupFilter.groupIds.join(', ')}`,
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import { redactText } from "./redact.js";
11
11
  import { linkFlowQaReport } from "./results.js";
12
12
  import { readRunSummary, renderRunSummary } from "./run-summary.js";
13
13
  import { readReadiness, renderReadiness } from "./readiness.js";
14
+ import { refineBundle } from "./refinement.js";
14
15
  const help = `Error to Test — local error analysis and regression TC drafts
15
16
 
16
17
  error-to-test analyze --input errors-1.json --input errors-2.json --profile profile.json --out new-directory
@@ -23,8 +24,9 @@ const help = `Error to Test — local error analysis and regression TC drafts
23
24
  error-to-test verify new-directory [--input errors-1.json --input errors-2.json] [--profile profile.json]
24
25
  error-to-test init-profile new-directory --out profile.json
25
26
  error-to-test init-profile new-directory --profile existing.json --out extended.json
27
+ error-to-test refine new-directory --profile updated.json --out refined-directory [--reviewed]
26
28
  error-to-test link-run new-directory --report path/to/qa-report.json
27
- error-to-test results new-directory [--format text|json] [--out summary.md]
29
+ error-to-test results new-directory [--format text|json] [--out summary.md] [--fail-on STATUS ...]
28
30
  error-to-test readiness new-directory [--format text|json]
29
31
  error-to-test compare BASELINE CURRENT [--format text|json] [--out comparison.md] [--max-new N]
30
32
 
@@ -33,9 +35,11 @@ Options:
33
35
  --error TEXT Submit a single error directly; remaining lines are its stack
34
36
  --format auto|json|jsonl|text Analyze input format; JSONL requires explicit selection and one record per line; auto rejects malformed JSON-looking input
35
37
  --format text|json Results summary format (default: text Markdown)
38
+ --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)
36
39
  --format text|json Compare format (default: text Markdown)
37
40
  --format text|json Readiness format (default: text Markdown; exit 0 ready, 2 blocked/empty, 1 on error)
38
41
  --profile FILE Confirmed app scenarios and explicit assertions (analyze/verify); existing profile to extend (init-profile)
42
+ --profile FILE Replacement profile for the bundle's previously selected groups (refine; required)
39
43
  --baseline DIRECTORY Select only signatures absent from this verified bundle, before --min-count and --top; retain all groups in analysis.json (analyze only)
40
44
  --project NAME Metadata for a manual report
41
45
  --environment NAME Metadata for a manual report
@@ -52,6 +56,7 @@ Options:
52
56
  --group GROUP_ID Select TCs only for these exact current group IDs; repeat up to 100 times (analyze only; before --min-count/--top)
53
57
  --top N Generate TCs for the first N eligible ranked groups (1..100; after --min-count)
54
58
  --out DIRECTORY New analyze directory; existing files are never overwritten
59
+ --out DIRECTORY New refine directory outside the source bundle (required; review defaults to pending)
55
60
  --out FILE New init-profile JSON file; existing files are never overwritten
56
61
  --out FILE New results summary file; existing files are never overwritten
57
62
  --out FILE New comparison file; existing files are never overwritten
@@ -97,6 +102,7 @@ async function writeGateOutput(content) {
97
102
  });
98
103
  });
99
104
  }
105
+ const resultsGateStatuses = ['failed', 'flaky', 'blocked', 'skipped', 'error', 'not-run'];
100
106
  async function inputContents(paths, allowStdin) {
101
107
  if (paths.length < 1 || paths.length > 50)
102
108
  throw new Error('Provide between 1 and 50 --input files.');
@@ -142,12 +148,16 @@ function insideBundleResults(bundleRoot, path) {
142
148
  return false;
143
149
  return rest.split(sep, 1)[0]?.toLowerCase() === 'results';
144
150
  }
151
+ function insideBundle(bundleRoot, path) {
152
+ const rest = relative(bundleRoot.toLowerCase(), path.toLowerCase());
153
+ return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest));
154
+ }
145
155
  export async function main(args = process.argv.slice(2)) {
146
156
  const { values, positionals } = parseArgs({ args, allowPositionals: true, strict: true, options: {
147
157
  help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string', multiple: true }, error: { type: 'string' }, report: { type: 'string' },
148
158
  format: { type: 'string' }, profile: { type: 'string' }, baseline: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
149
159
  release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
150
- top: { type: 'string' }, 'min-count': { type: 'string' }, 'max-new': { type: 'string' }, group: { type: 'string', multiple: true }, out: { type: 'string' }, reviewed: { type: 'boolean' },
160
+ 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' },
151
161
  reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
152
162
  expected: { type: 'string' }, 'expected-source': { type: 'string' },
153
163
  } });
@@ -162,11 +172,26 @@ export async function main(args = process.argv.slice(2)) {
162
172
  }
163
173
  if (positionals.length === 0) {
164
174
  if (Object.keys(values).length)
165
- throw new Error('A command is required. Use analyze, init-profile, verify, link-run, results, compare, or readiness. See --help.');
175
+ throw new Error('A command is required. Use analyze, init-profile, refine, verify, link-run, results, compare, or readiness. See --help.');
166
176
  process.stdout.write(help);
167
177
  return;
168
178
  }
169
179
  const command = positionals[0];
180
+ if (command === 'refine') {
181
+ if (positionals.length !== 2 || !positionals[1]?.trim() || !values.profile?.trim() || !values.out?.trim())
182
+ throw new Error('refine requires one bundle directory, --profile FILE, and --out DIRECTORY.');
183
+ if (Object.keys(values).some(key => !['profile', 'out', 'reviewed', 'help'].includes(key)))
184
+ throw new Error('Unsupported option for refine. Use only --profile FILE, --out DIRECTORY, and --reviewed.');
185
+ const bundle = resolve(positionals[1]);
186
+ const out = resolve(values.out);
187
+ if (insideBundle(await realpath(bundle), await canonicalOutput(out)))
188
+ throw new Error('The refined output must be outside the source bundle. Choose a new --out DIRECTORY path.');
189
+ const analysis = await refineBundle(bundle, await readBoundedFile(resolve(values.profile), 1024 * 1024));
190
+ const files = await writeBundle(out, analysis, { reviewed: values.reviewed });
191
+ const drafts = analysis.candidates.filter(candidate => candidate.state === 'draft').length;
192
+ process.stdout.write(`${analysis.groups.length} error groups retained; ${analysis.candidates.length} refined TC candidates (${drafts} drafts, ${analysis.candidates.length - drafts} need context).\nReview ${resolve(out, 'report.md')}\n${files.length} artifacts written. Review acknowledgment: ${values.reviewed ? 'yes' : 'pending'}. Original input was not rechecked.\n`);
193
+ return;
194
+ }
170
195
  if (command === 'init-profile') {
171
196
  if (positionals.length !== 2 || !positionals[1] || !values.out)
172
197
  throw new Error('init-profile requires one bundle directory and --out FILE.');
@@ -219,18 +244,40 @@ export async function main(args = process.argv.slice(2)) {
219
244
  if (command === 'results') {
220
245
  if (positionals.length !== 2 || !positionals[1])
221
246
  throw new Error('results requires one bundle directory.');
222
- if (Object.keys(values).some(key => !['format', 'out', 'help'].includes(key)))
223
- throw new Error('Unsupported option for results. Use only --format text|json and --out FILE.');
247
+ if (Object.keys(values).some(key => !['format', 'out', 'fail-on', 'help'].includes(key)))
248
+ throw new Error('Unsupported option for results. Use only --format text|json, --out FILE, and --fail-on STATUS.');
224
249
  const format = values.format ?? 'text';
225
250
  if (format !== 'text' && format !== 'json')
226
251
  throw new Error('results --format must be text or json.');
252
+ const requestedStatuses = values['fail-on'];
253
+ if (requestedStatuses?.some(status => !resultsGateStatuses.includes(status))) {
254
+ throw new Error('results --fail-on must be failed, flaky, blocked, skipped, error, or not-run.');
255
+ }
256
+ const failOn = requestedStatuses === undefined ? undefined : resultsGateStatuses.filter(status => requestedStatuses.includes(status));
227
257
  const bundle = resolve(positionals[1]);
228
258
  const summary = await readRunSummary(bundle);
229
259
  const content = format === 'json' ? jsonText(summary) : renderRunSummary(summary);
230
260
  if (Buffer.byteLength(content) > 64 * 1024 * 1024)
231
261
  throw new Error('The results summary exceeds 64 MiB. Narrow the bundle before requesting output.');
262
+ const finishGate = () => {
263
+ if (failOn === undefined)
264
+ return;
265
+ const selectedTotal = Object.values(summary.counts).reduce((total, count) => total + count, 0);
266
+ const matchTotal = failOn.reduce((total, status) => total + summary.counts[status], 0);
267
+ const failed = selectedTotal === 0 || matchTotal > 0;
268
+ const detail = failOn.map(status => `${status}=${summary.counts[status]}`).join(', ');
269
+ process.stderr.write(selectedTotal === 0
270
+ ? 'Results gate failed: no selected cases.\n'
271
+ : `Results gate ${failed ? 'failed' : 'passed'}: ${matchTotal} cases match --fail-on (${detail}).\n`);
272
+ if (failed)
273
+ process.exitCode = 2;
274
+ };
232
275
  if (values.out === undefined) {
233
- process.stdout.write(content);
276
+ if (failOn === undefined)
277
+ process.stdout.write(content);
278
+ else
279
+ await writeGateOutput(content);
280
+ finishGate();
234
281
  return;
235
282
  }
236
283
  const out = resolve(values.out);
@@ -246,7 +293,12 @@ export async function main(args = process.argv.slice(2)) {
246
293
  throw new Error('The output file already exists. Choose a new --out FILE path.');
247
294
  throw error;
248
295
  }
249
- process.stdout.write(`Results summary written: ${out}\n`);
296
+ const written = `Results summary written: ${out}\n`;
297
+ if (failOn === undefined)
298
+ process.stdout.write(written);
299
+ else
300
+ await writeGateOutput(written);
301
+ finishGate();
250
302
  return;
251
303
  }
252
304
  if (command === 'readiness') {
@@ -339,9 +391,11 @@ export async function main(args = process.argv.slice(2)) {
339
391
  return;
340
392
  }
341
393
  if (command !== 'analyze' || positionals.length !== 1)
342
- throw new Error('Use analyze, init-profile, verify, link-run, results, compare, or readiness. See --help.');
394
+ throw new Error('Use analyze, init-profile, refine, verify, link-run, results, compare, or readiness. See --help.');
343
395
  if (values.report)
344
396
  throw new Error('--report applies to link-run only.');
397
+ if (values['fail-on'] !== undefined)
398
+ throw new Error('--fail-on applies to results only.');
345
399
  if (values['max-new'] !== undefined)
346
400
  throw new Error('--max-new applies to compare only.');
347
401
  if (values.baseline !== undefined && values.baseline.trim() === '')
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export { exportFlowQa } from './exports/flow-qa.ts';
6
6
  export { writeBundle, verifyBundle, renderReport } from './artifacts.ts';
7
7
  export { linkFlowQaReport } from './results.ts';
8
8
  export { createProfileTemplate, type ProfileTemplateOptions } from './profile-template.ts';
9
+ export { refineBundle } from './refinement.ts';
9
10
  export { readRunSummary, renderRunSummary, type RunSummary, type LinkedRunStatus, type LinkedCaseStatus } from './run-summary.ts';
10
11
  export { readReadiness, renderReadiness, type ReadinessSummary } from './readiness.ts';
11
12
  export { compareBundles, renderComparison, type AnalysisComparison, type ComparisonStatus, type ComparisonSide, type ComparisonOccurrence, type ComparisonIssue } from './comparison.ts';
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { exportFlowQa } from "./exports/flow-qa.js";
6
6
  export { writeBundle, verifyBundle, renderReport } from "./artifacts.js";
7
7
  export { linkFlowQaReport } from "./results.js";
8
8
  export { createProfileTemplate } from "./profile-template.js";
9
+ export { refineBundle } from "./refinement.js";
9
10
  export { readRunSummary, renderRunSummary } from "./run-summary.js";
10
11
  export { readReadiness, renderReadiness } from "./readiness.js";
11
12
  export { compareBundles, renderComparison } from "./comparison.js";
@@ -0,0 +1,3 @@
1
+ import type { Analysis } from './types.ts';
2
+ /** Rebuild candidates from a verified analysis snapshot without reading the original input or writing artifacts. */
3
+ export declare function refineBundle(directory: string, profile: string): Promise<Analysis>;
@@ -0,0 +1,249 @@
1
+ import { readVerifiedBundle } from "./artifacts.js";
2
+ import { createCandidates, parseProfile } from "./candidates.js";
3
+ import { validateInputSource } from "./input-source.js";
4
+ import { redactText } from "./redact.js";
5
+ import { hash, parseWebSteps, record } from "./validation.js";
6
+ const sha256 = /^[a-f0-9]{64}$/;
7
+ const groupId = /^group-[a-f0-9]{16}$/;
8
+ const caseId = /^TC_[a-f0-9]{16}$/;
9
+ const eventTypes = new Set(['javascript', 'promise', 'react', 'console', 'http', 'network', 'manual']);
10
+ const runtimes = new Set(['browser', 'webview-ios', 'webview-android', 'unknown']);
11
+ const kinds = new Set(['browser-error-json', 'manual-json', 'manual-text', 'browser-error-jsonl', 'manual-jsonl']);
12
+ const refinementNote = 'Refinement: Original input records were not rechecked; group ranking and the existing TC selection were preserved. Candidates were regenerated from the verified snapshot and supplied profile.';
13
+ function invalid(label) { throw new Error(`Invalid analysis snapshot: ${label}.`); }
14
+ function string(value, label, allowEmpty = false) {
15
+ if (typeof value !== 'string' || (!allowEmpty && !value.trim()))
16
+ invalid(label);
17
+ }
18
+ function optionalString(value, label) {
19
+ if (value !== undefined)
20
+ string(value, label, true);
21
+ }
22
+ function strings(value, label) {
23
+ if (!Array.isArray(value))
24
+ invalid(label);
25
+ for (const [index, item] of value.entries())
26
+ string(item, `${label}[${index}]`, true);
27
+ }
28
+ function optionalStrings(value, label) {
29
+ if (value !== undefined)
30
+ strings(value, label);
31
+ }
32
+ function integer(value, label, minimum = 0) {
33
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum)
34
+ invalid(label);
35
+ }
36
+ function steps(value, label, required) {
37
+ if (value === undefined && !required)
38
+ return;
39
+ if (!Array.isArray(value))
40
+ invalid(label);
41
+ parseWebSteps(value, label);
42
+ }
43
+ function coverage(value, label) {
44
+ const raw = record(value, label);
45
+ if (!kinds.has(raw.kind) ||
46
+ raw.frequency !== (raw.kind === 'browser-error-json' || raw.kind === 'browser-error-jsonl' ? 'captured-events' : 'submitted-reports') ||
47
+ typeof raw.partial !== 'boolean' || raw.retention !== 'unknown')
48
+ invalid(label);
49
+ integer(raw.inputCount, `${label}.inputCount`, 1);
50
+ integer(raw.duplicates, `${label}.duplicates`);
51
+ integer(raw.filtered, `${label}.filtered`);
52
+ if (raw.period !== undefined) {
53
+ const period = record(raw.period, `${label}.period`);
54
+ optionalString(period.from, `${label}.period.from`);
55
+ optionalString(period.to, `${label}.period.to`);
56
+ }
57
+ }
58
+ function observation(value, label) {
59
+ const raw = record(value, label);
60
+ for (const field of ['id', 'project', 'environment', 'release', 'message'])
61
+ string(raw[field], `${label}.${field}`);
62
+ if (raw.source !== 'browser-error' && raw.source !== 'manual')
63
+ invalid(`${label}.source`);
64
+ if (!eventTypes.has(raw.type) || !runtimes.has(raw.runtime))
65
+ invalid(`${label}.type/runtime`);
66
+ for (const field of ['name', 'stack', 'componentStack', 'page', 'occurredAt', 'viewId', 'expected', 'expectedSource']) {
67
+ optionalString(raw[field], `${label}.${field}`);
68
+ }
69
+ for (const field of ['reproduction', 'preconditions', 'questions'])
70
+ strings(raw[field], `${label}.${field}`);
71
+ steps(raw.steps, `${label}.steps`, true);
72
+ if (raw.network !== undefined) {
73
+ const network = record(raw.network, `${label}.network`);
74
+ string(network.method, `${label}.network.method`);
75
+ string(network.url, `${label}.network.url`);
76
+ if (network.status !== undefined) {
77
+ integer(network.status, `${label}.network.status`, 100);
78
+ if (network.status > 599)
79
+ invalid(`${label}.network.status`);
80
+ }
81
+ if (network.durationMs !== undefined && (typeof network.durationMs !== 'number' || !Number.isFinite(network.durationMs) || network.durationMs < 0)) {
82
+ invalid(`${label}.network.durationMs`);
83
+ }
84
+ }
85
+ }
86
+ function context(value, label, required) {
87
+ const missing = () => { throw new Error('Selected group lacks full source context. Reanalyze the original input before refining.'); };
88
+ if (value === undefined) {
89
+ if (required)
90
+ missing();
91
+ return;
92
+ }
93
+ try {
94
+ const raw = record(value, label);
95
+ for (const field of ['expected', 'expectedSource'])
96
+ optionalString(raw[field], `${label}.${field}`);
97
+ for (const field of ['reproduction', 'preconditions'])
98
+ optionalStrings(raw[field], `${label}.${field}`);
99
+ steps(raw.steps, `${label}.steps`, false);
100
+ strings(raw.questions, `${label}.questions`);
101
+ strings(raw.conflicts, `${label}.conflicts`);
102
+ }
103
+ catch (error) {
104
+ if (required)
105
+ missing();
106
+ throw error;
107
+ }
108
+ }
109
+ function group(value, label, requireContext) {
110
+ const raw = record(value, label);
111
+ if (typeof raw.id !== 'string' || !groupId.test(raw.id))
112
+ invalid(`${label}.id`);
113
+ if (raw.fingerprintVersion !== 1)
114
+ invalid(`${label}.fingerprintVersion`);
115
+ for (const field of ['project', 'environment', 'release', 'signature', 'message'])
116
+ string(raw[field], `${label}.${field}`);
117
+ string(raw.pagePath, `${label}.pagePath`, true);
118
+ if (!eventTypes.has(raw.type) || !runtimes.has(raw.runtime))
119
+ invalid(`${label}.type/runtime`);
120
+ integer(raw.count, `${label}.count`, 1);
121
+ integer(raw.viewCount, `${label}.viewCount`);
122
+ if (raw.viewCount > raw.count)
123
+ invalid(`${label}.viewCount`);
124
+ optionalString(raw.lastOccurredAt, `${label}.lastOccurredAt`);
125
+ strings(raw.eventIds, `${label}.eventIds`);
126
+ if (raw.eventIds.length !== raw.count)
127
+ invalid(`${label}.eventIds`);
128
+ if (!Array.isArray(raw.evidence) || raw.evidence.length < 1 || raw.evidence.length > 5 || raw.evidence.length > raw.count)
129
+ invalid(`${label}.evidence`);
130
+ for (const [index, item] of raw.evidence.entries()) {
131
+ observation(item, `${label}.evidence[${index}]`);
132
+ if (!raw.eventIds.includes(item.id))
133
+ invalid(`${label}.evidence[${index}].id`);
134
+ }
135
+ context(raw.context, `${label}.context`, requireContext);
136
+ return raw;
137
+ }
138
+ function checkedAnalysis(value, provenance) {
139
+ const raw = record(value, 'analysis');
140
+ if (raw.schemaVersion !== 'error-to-test/analysis-1')
141
+ invalid('schemaVersion');
142
+ const source = record(raw.source, 'analysis.source');
143
+ validateInputSource(source);
144
+ if (source.profileSha256 !== undefined && (typeof source.profileSha256 !== 'string' || !sha256.test(source.profileSha256)))
145
+ invalid('source.profileSha256');
146
+ coverage(raw.coverage, 'analysis.coverage');
147
+ if (!Array.isArray(raw.groups) || !Array.isArray(raw.candidates))
148
+ invalid('groups/candidates');
149
+ strings(raw.warnings, 'analysis.warnings');
150
+ if (raw.selection !== undefined) {
151
+ const selection = record(raw.selection, 'analysis.selection');
152
+ if (selection.mode !== 'only-current')
153
+ invalid('selection.mode');
154
+ const baseline = record(selection.baseline, 'analysis.selection.baseline');
155
+ for (const field of ['inputSha256', 'analysisSha256']) {
156
+ if (typeof baseline[field] !== 'string' || !sha256.test(baseline[field]))
157
+ invalid(`selection.baseline.${field}`);
158
+ }
159
+ coverage(baseline.coverage, 'analysis.selection.baseline.coverage');
160
+ integer(selection.onlyCurrentGroupCount, 'analysis.selection.onlyCurrentGroupCount');
161
+ integer(selection.excludedGroupCount, 'analysis.selection.excludedGroupCount');
162
+ }
163
+ if (raw.groupFilter !== undefined) {
164
+ const filter = record(raw.groupFilter, 'analysis.groupFilter');
165
+ strings(filter.groupIds, 'analysis.groupFilter.groupIds');
166
+ if (filter.groupIds.some(id => !groupId.test(id)) || new Set(filter.groupIds).size !== filter.groupIds.length)
167
+ invalid('groupFilter.groupIds');
168
+ }
169
+ const selectedIds = new Set();
170
+ const candidateIds = new Set();
171
+ if (!Array.isArray(provenance.mappings) || provenance.mappings.length !== raw.candidates.length)
172
+ invalid('provenance.mappings');
173
+ for (const [index, value] of raw.candidates.entries()) {
174
+ const candidate = record(value, `analysis.candidates[${index}]`);
175
+ const mapping = record(provenance.mappings[index], `provenance.mappings[${index}]`);
176
+ if (typeof candidate.id !== 'string' || !caseId.test(candidate.id) || candidateIds.has(candidate.id))
177
+ invalid(`analysis.candidates[${index}].id`);
178
+ if (typeof candidate.groupId !== 'string' || !groupId.test(candidate.groupId))
179
+ invalid(`analysis.candidates[${index}].groupId`);
180
+ strings(candidate.eventIds, `analysis.candidates[${index}].eventIds`);
181
+ if (mapping.caseId !== candidate.id || mapping.candidateId !== candidate.id || mapping.groupId !== candidate.groupId ||
182
+ JSON.stringify(mapping.eventIds) !== JSON.stringify(candidate.eventIds))
183
+ invalid(`provenance.mappings[${index}]`);
184
+ candidateIds.add(candidate.id);
185
+ selectedIds.add(candidate.groupId);
186
+ }
187
+ if (!selectedIds.size)
188
+ throw new Error('Refinement requires at least one selected candidate group.');
189
+ const seenGroups = new Set();
190
+ const selectedGroups = [];
191
+ for (const [index, value] of raw.groups.entries()) {
192
+ const item = group(value, `analysis.groups[${index}]`, selectedIds.has(value?.id));
193
+ if (seenGroups.has(item.id))
194
+ invalid(`analysis.groups[${index}].id`);
195
+ seenGroups.add(item.id);
196
+ if (selectedIds.has(item.id))
197
+ selectedGroups.push(item);
198
+ }
199
+ if (selectedGroups.length !== selectedIds.size)
200
+ invalid('selected candidate group');
201
+ for (const [index, value] of raw.candidates.entries()) {
202
+ const candidate = value;
203
+ const selected = selectedGroups.find(item => item.id === candidate.groupId);
204
+ if (JSON.stringify(candidate.eventIds) !== JSON.stringify([...new Set(selected.eventIds)]))
205
+ invalid(`analysis.candidates[${index}].eventIds`);
206
+ }
207
+ return { analysis: raw, selectedGroups };
208
+ }
209
+ /** Rebuild candidates from a verified analysis snapshot without reading the original input or writing artifacts. */
210
+ export async function refineBundle(directory, profile) {
211
+ if (typeof profile !== 'string')
212
+ throw new Error('The profile must be JSON text.');
213
+ if (Buffer.byteLength(profile, 'utf8') > 1024 * 1024)
214
+ throw new Error('The profile must be 1 MiB or smaller.');
215
+ let parsed;
216
+ try {
217
+ parsed = JSON.parse(profile.replace(/^\uFEFF/, ''));
218
+ }
219
+ catch {
220
+ throw new Error('The profile is not valid JSON.');
221
+ }
222
+ const appProfile = parseProfile(parsed);
223
+ if (appProfile.scenarios.some(rule => redactText(rule.id) !== rule.id ||
224
+ (rule.match.groupId !== undefined && redactText(rule.match.groupId) !== rule.match.groupId))) {
225
+ throw new Error('The profile contains sensitive scenario IDs; remove them before refining.');
226
+ }
227
+ const verified = await readVerifiedBundle(directory);
228
+ const { analysis, selectedGroups } = checkedAnalysis(verified.analysis, verified.provenance);
229
+ const candidates = createCandidates(selectedGroups, appProfile);
230
+ if (candidates.length > 100)
231
+ throw new Error(`Flow QA supports at most 100 cases; received ${candidates.length}. Narrow the selected scenario rules.`);
232
+ const sourceAnalysisSha256 = verified.provenance.analysisSha256;
233
+ if (typeof sourceAnalysisSha256 !== 'string' || !sha256.test(sourceAnalysisSha256))
234
+ invalid('provenance.analysisSha256');
235
+ const sourceSuiteSha256 = verified.provenance.suiteSha256;
236
+ if (sourceSuiteSha256 !== undefined && (typeof sourceSuiteSha256 !== 'string' || !sha256.test(sourceSuiteSha256)))
237
+ invalid('provenance.suiteSha256');
238
+ const sourceProfileSha256 = verified.provenance.profileSha256;
239
+ if (sourceProfileSha256 !== undefined && (typeof sourceProfileSha256 !== 'string' || !sha256.test(sourceProfileSha256)))
240
+ invalid('provenance.profileSha256');
241
+ return {
242
+ ...analysis,
243
+ source: { ...analysis.source, profileSha256: hash(profile) },
244
+ candidates,
245
+ warnings: [...analysis.warnings.filter(note => !note.startsWith('Refinement:')), refinementNote],
246
+ refinement: { sourceAnalysisSha256, ...(sourceSuiteSha256 === undefined ? {} : { sourceSuiteSha256 }),
247
+ ...(sourceProfileSha256 === undefined ? {} : { sourceProfileSha256 }), selectedGroupIds: selectedGroups.map(item => item.id) },
248
+ };
249
+ }
package/dist/types.d.ts CHANGED
@@ -182,6 +182,12 @@ export interface Analysis {
182
182
  groupFilter?: {
183
183
  groupIds: string[];
184
184
  };
185
+ refinement?: {
186
+ sourceAnalysisSha256: string;
187
+ sourceSuiteSha256?: string;
188
+ sourceProfileSha256?: string;
189
+ selectedGroupIds: string[];
190
+ };
185
191
  }
186
192
  export interface FlowQaSuite {
187
193
  schemaVersion: 'flow-qa/suite-1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ihyeon/error-to-test",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
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",