@ihyeon/error-to-test 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hyeonse Im
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.ko.md ADDED
@@ -0,0 +1,51 @@
1
+ # Error to Test
2
+
3
+ SDK에서 내보낸 브라우저 오류 로그 또는 **직접 입력한 오류 메시지·스택**을 분석해 반복 오류 묶음과 회귀 TC 초안으로 만듭니다. 모델이나 수집 서버 없이 로컬에서 사용하며, Flow QA 형식으로 내보냅니다.
4
+
5
+ [English](README.md)
6
+
7
+ ```sh
8
+ npm install -g @ihyeon/error-to-test
9
+ error-to-test analyze --error "TypeError: item is undefined" --page /items --out ./new-result
10
+ ```
11
+
12
+ JavaScript API는 `npm install @ihyeon/error-to-test`로 설치합니다. [배포·검증 안내](docs/releases.md)에서 자동 게시 방식과 검증 범위를 확인할 수 있습니다.
13
+
14
+ Node.js 24.8 이상이 필요합니다. 현재 폴더에서 `npm ci`, `npm run check`를 실행한 뒤 사용하세요.
15
+
16
+ ```sh
17
+ # SDK 없이 오류 하나를 직접 입력
18
+ node bin/error-to-test.mjs analyze --error "TypeError: item is undefined" --page /items --runtime browser --reproduce "View item 버튼 클릭" --expected "빈 상태 안내 표시" --expected-source "사용자가 설명한 기대 동작" --out .error-to-test/pasted
19
+
20
+ # 기존 오류 텍스트 파일 입력
21
+ node bin/error-to-test.mjs analyze --input examples/error.txt --page /items --runtime browser --out .error-to-test/text
22
+
23
+ # SDK JSON + 확인한 화면 계약으로 TC 생성
24
+ node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --out .error-to-test/example
25
+ ```
26
+
27
+ 결과는 `analysis.json`, `report.md`, `flows/error-to-test.md`, `cases/error-to-test.json`, `provenance.json`입니다. 빈 조회 결과에는 suite를 만들지 않습니다. 출력 폴더는 매번 새 경로를 지정해야 합니다.
28
+
29
+ `report.md`에서 오류 묶음·수집 건수·부족한 정보를 확인하세요. 재현 단계와 정상 기대 결과, 명시적인 assertion이 없으면 질문이 있는 TC를 생성합니다. 직접 입력한 보고서에는 실제 발생 시각·사용자 수를 만들어 넣지 않습니다. 수집 건수도 실제 발생률을 뜻하지 않으며, 원본 내보내기의 일부 데이터 표시를 유지합니다.
30
+
31
+ 기본 suite는 검토 질문으로 실행이 차단됩니다. TC와 프로필을 확인한 뒤 다른 출력 폴더에 `--reviewed`로 다시 생성하면 검토 질문만 제거됩니다. 나머지 질문은 그대로 실행을 차단합니다. 프로필의 `setupConfirmed`는 준비 조건을 확인했다는 표시이며, 계정·데이터를 자동으로 준비하는 기능은 아닙니다.
32
+
33
+ ```sh
34
+ node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
35
+ node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --reviewed --out .error-to-test/reviewed
36
+ cd .error-to-test/reviewed
37
+ flow-qa validate cases/error-to-test.json
38
+ flow-qa generate cases/error-to-test.json
39
+ flow-qa init
40
+ flow-qa ui
41
+ ```
42
+
43
+ Flow QA 설치와 실행 대상 설정은 별도로 필요합니다. 위 `flows/`·`cases/` 구조를 기존 검토 화면에서 읽을 수 있습니다. 분석 명령은 브라우저를 실행하거나 외부 모델에 요청하지 않습니다. TC 통과만으로 원래 오류를 수정 완료 처리하지 않습니다.
44
+
45
+ 실행 후 `node bin/error-to-test.mjs link-run .error-to-test/reviewed --report /path/to/qa-report.json`으로 결과를 원래 오류 묶음에 연결할 수 있습니다. suite 해시와 모든 case ID가 일치해야 하며, 결과는 `results/<runId>.json`에 저장합니다. 원본 e2e 리포트 대신 Flow QA가 정리한 `report-1`을 사용하세요.
46
+
47
+ 직접 입력은 문자열, 텍스트 파일, 표준 입력, `error-to-test/manual-1` JSON을 지원합니다. 파일 구조는 [수동 오류 예제](examples/manual.json), 정상 기대 동작과 단계 연결은 [프로필 예제](examples/profile.json)를 참고하세요. 전체 옵션은 `node bin/error-to-test.mjs --help`로 확인할 수 있습니다.
48
+
49
+ 알려진 자격증명·이메일·URL 인증/쿼리 정보는 결과에서 정제합니다. 민감정보가 포함된 실행 단계나 기대 결과는 변경해 통과시키지 않고 질문으로 남깁니다. 모든 개인정보를 제거한다고 보장하지 않으므로 실제 업무 데이터를 입력하기 전에는 별도로 정제하세요. 비공개 오류는 셸 기록에 남는 인자 대신 파일·표준 입력을 사용하세요.
50
+
51
+ 검증은 `npm run check`, `npm run check:package`입니다. 로컬 SDK·Flow QA와 Chromium이 준비되면 `FLOW_QA_SOURCE=/path/to/flow-qa BROWSER_ERROR_SOURCE=/path/to/browser-error-log npm run smoke:flowqa`로 수정 전 실패·수정 후 통과와 미확인 TC 차단을 확인할 수 있습니다. 자세한 입력 계약과 제한은 [영문 문서](README.md)에 있습니다.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # Error to Test
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Turn captured browser errors **or a pasted error report** into grouped issues, reviewable regression test candidates, and Flow QA suites. Runs locally without a model, browser SDK, or external service connection.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@ihyeon/error-to-test)](https://www.npmjs.com/package/@ihyeon/error-to-test) [![CI](https://github.com/hyeonse-swing/error-to-test/actions/workflows/ci.yml/badge.svg)](https://github.com/hyeonse-swing/error-to-test/actions/workflows/ci.yml)
6
+
7
+ [한국어](README.ko.md)
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install -g @ihyeon/error-to-test
13
+ error-to-test analyze --error "TypeError: item is undefined" --page /items --out ./new-result
14
+ ```
15
+
16
+ For the JavaScript API, install `npm install @ihyeon/error-to-test`. See [release and verification notes](docs/releases.md) for automatic publishing and the integration proof boundary.
17
+
18
+ ## Run locally
19
+
20
+ Requires Node.js 24.8+. From this directory:
21
+
22
+ ```sh
23
+ npm ci
24
+ npm run check
25
+ node bin/error-to-test.mjs --help
26
+ node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --out .error-to-test/example
27
+ ```
28
+
29
+ Every output directory must be new. The command never overwrites an existing analysis.
30
+
31
+ ## Submit an error without an SDK
32
+
33
+ ```sh
34
+ node bin/error-to-test.mjs analyze --error "TypeError: item is undefined" --page /items --runtime browser --reproduce "Click View item" --expected "Show the empty state" --expected-source "Reporter" --out .error-to-test/pasted
35
+ node bin/error-to-test.mjs analyze --input examples/error.txt --page /items --runtime browser --out .error-to-test/text
36
+ node bin/error-to-test.mjs analyze --input examples/manual.json --profile examples/profile.json --out .error-to-test/manual
37
+ cat examples/error.txt | node bin/error-to-test.mjs analyze --input - --out .error-to-test/stdin
38
+ ```
39
+
40
+ One text input is one report: its first line is the message and the remaining lines are its stack. Common `[ERROR]`, `[vite]`, and timestamp prefixes work in automatic mode. Use `--format text` for other text formats. Malformed JSON is rejected rather than silently reinterpreted as an error report.
41
+
42
+ Manual JSON uses `schemaVersion: "error-to-test/manual-1"` and an `errors` array. Each report requires `message`; optional fields include `id`, `type`, `project`, `environment`, `release`, `runtime`, `page`, `name`, `stack`, `componentStack`, `occurredAt`, `reproduction`, `preconditions`, `expected`, `expectedSource`, `questions`, and explicit web `steps`. Unknown runtime, time, action, or expectation stays unknown. No occurrence date or user session is invented.
43
+
44
+ Textual expected behavior alone does not establish a runnable assertion. Supply confirmed scenarios in a profile, or explicit manual steps and an expectation source. Missing information remains a question on the TC.
45
+
46
+ ## Analyze collected errors
47
+
48
+ Accepts Browser Error Log v1 `{schemaVersion: 1, partial?: boolean, events: [...]}` exports or arrays of full v1 events. Files are limited to 10 MiB and 10,000 records. Identity duplicates are removed; conflicting payloads with the same project/event ID are rejected. `--from`/`--to` require timezone-qualified ISO timestamps. Undated manual reports are excluded when a date filter is requested.
49
+
50
+ Grouping is deterministic and separates project, environment, release, runtime, page path, error message/name, and source location or HTTP method/path/status. Similar messages do not establish the same root cause. Counts mean **captured events** or **submitted reports**, not actual occurrence rates or affected users. Collection retention is unknown; imported `partial` status is preserved. TC selection defaults to the first 100 ranked groups; all groups remain in the analysis. More than 100 generated cases must be narrowed with `--top` or a smaller profile.
51
+
52
+ ## Confirm the intended behavior
53
+
54
+ See [examples/profile.json](examples/profile.json). Profiles use `schemaVersion: "error-to-test/profile-1"`, a name, and up to 100 scenarios. Each scenario has a unique ID, title, at least one match predicate, a requirement, its `expectedSource`, and explicit steps. Set `setupConfirmed: true` only after confirming how preconditions are established. Preconditions are descriptions; this package does not prepare accounts or data.
55
+
56
+ Supported web steps match Flow QA: `open`, `click`, `fill`, `act`, `assertVisible`, `assertText`, `assertUrl`, and `assertAgent`. Several matching rules produce several traceable candidates. Conflicts/questions in any original report are checked before representative evidence is sampled and stay blocked even when a profile matches.
57
+
58
+ ## Review and use Flow QA
59
+
60
+ Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
61
+
62
+ - `analysis.json`: coverage, ranked groups, safe representative evidence, full-source context checks, and TC candidates.
63
+ - `report.md`: human-readable analysis and missing context.
64
+ - `flows/error-to-test.md`: observed facts, requirements, steps, and questions.
65
+ - `cases/error-to-test.json`: Flow QA `suite-1` (omitted when no records match).
66
+ - `provenance.json`: source/profile/analysis/report/flow/suite hashes and event → group → case mappings.
67
+
68
+ Default suites have a review question on every case. Read the artifacts, confirm the profile/steps, then repeat analysis to **another output directory** with `--reviewed`. This acknowledges review; missing context still blocks execution. No analysis command runs the browser.
69
+
70
+ ```sh
71
+ node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
72
+ node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --reviewed --out .error-to-test/reviewed
73
+ cd .error-to-test/reviewed
74
+ flow-qa validate cases/error-to-test.json
75
+ flow-qa generate cases/error-to-test.json
76
+ flow-qa init
77
+ flow-qa ui
78
+ ```
79
+
80
+ Flow QA is installed/configured separately. Its UI can read this `flows/` + `cases/` layout. Select the intended test target, review the cases in Flow QA, and execute there or with its CLI. Source changes invalidate existing bundles/suites; regenerate after review. `verify` checks artifact consistency, and checks original input/profile bytes only when supplied. It is not a signature or proof that a testcase fixes the reported cause. A passing functional assertion does not automatically close an error issue.
81
+
82
+ ## JavaScript API
83
+
84
+ ```js
85
+ import { analyzeErrors, exportFlowQa, writeBundle } from '@ihyeon/error-to-test';
86
+
87
+ const analysis = analyzeErrors('TypeError: item is undefined', { page: '/items', runtime: 'browser' });
88
+ const { suite, flow, provenance } = exportFlowQa(analysis);
89
+ await writeBundle('./new-result', analysis);
90
+ ```
91
+
92
+ Analysis is deterministic and has no runtime dependencies. Optional model-assisted drafting, collecting new interaction breadcrumbs, direct collector APIs, and a dedicated web input screen are later extensions. Browser/WebView logs can be analyzed; native or WebView execution is not established by a log and remains blocked until the correct context is supplied.
93
+
94
+ After a Flow QA run, associate its normalized report with the exact exported suite:
95
+
96
+ ```sh
97
+ node bin/error-to-test.mjs link-run .error-to-test/reviewed --report /path/to/qa-report.json
98
+ ```
99
+
100
+ The run's suite hash and every case ID must match. Safe case results are stored under `results/<runId>.json`, linked to their source groups/events. Unknown, missing, or duplicate cases are rejected; existing results are never overwritten. A raw e2e report is not accepted. Failed, blocked, and passed results remain distinct; no issue is automatically marked fixed.
101
+
102
+ ## Data handling and checks
103
+
104
+ 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.
105
+
106
+ ```sh
107
+ npm run check
108
+ npm run check:package
109
+ FLOW_QA_SOURCE=/path/to/flow-qa BROWSER_ERROR_SOURCE=/path/to/browser-error-log npm run smoke:flowqa
110
+ ```
111
+
112
+ The optional integration smoke uses the actual Browser Error Log SDK and Flow QA/e2e in a controlled local Chromium demo: collect errors, generate TCs, observe failures before repair and passes after repair, preserve an unresolved case, and check stale-source rejection. It requires their local source/dependencies and an installed Chromium browser. It does not access production, login, or call a model.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main, reportCliError } from '../dist/cli.js';
3
+ await main().catch(reportCliError);
@@ -0,0 +1,7 @@
1
+ import { type ParseInputOptions } from './input.ts';
2
+ import type { Analysis } from './types.ts';
3
+ export interface AnalyzeOptions extends ParseInputOptions {
4
+ profile?: unknown;
5
+ top?: number;
6
+ }
7
+ export declare function analyzeErrors(content: string, options?: AnalyzeOptions): Analysis;
@@ -0,0 +1,35 @@
1
+ import { parseInput } from "./input.js";
2
+ import { groupObservations } from "./grouping.js";
3
+ import { createCandidates, parseProfile } from "./candidates.js";
4
+ import { hash } from "./validation.js";
5
+ export function analyzeErrors(content, options = {}) {
6
+ const top = options.top ?? 100;
7
+ if (!Number.isInteger(top) || top < 1 || top > 100)
8
+ throw new Error('top must be an integer between 1 and 100.');
9
+ let rawProfile = options.profile;
10
+ const profileSource = typeof rawProfile === 'string' ? rawProfile : rawProfile === undefined ? undefined : JSON.stringify(rawProfile);
11
+ if (typeof rawProfile === 'string') {
12
+ if (Buffer.byteLength(rawProfile) > 1024 * 1024)
13
+ throw new Error('The profile must be 1 MiB or smaller.');
14
+ try {
15
+ rawProfile = JSON.parse(rawProfile);
16
+ }
17
+ catch {
18
+ throw new Error('The profile is not valid JSON.');
19
+ }
20
+ }
21
+ const profile = rawProfile === undefined ? undefined : parseProfile(rawProfile);
22
+ const input = parseInput(content, options);
23
+ const groups = groupObservations(input.observations);
24
+ const warnings = [...input.warnings];
25
+ if (groups.length > top)
26
+ warnings.push(`TC selection includes the first ${top} of ${groups.length} ranked groups. All groups remain in analysis.json.`);
27
+ return {
28
+ schemaVersion: 'error-to-test/analysis-1',
29
+ source: { sha256: input.sha256, ...(profileSource !== undefined ? { profileSha256: hash(profileSource) } : {}) },
30
+ coverage: input.coverage,
31
+ groups,
32
+ candidates: createCandidates(groups.slice(0, top), profile),
33
+ warnings,
34
+ };
35
+ }
@@ -0,0 +1,15 @@
1
+ import type { Analysis } from './types.ts';
2
+ export declare function jsonText(value: unknown): string;
3
+ export declare function renderReport(analysis: Analysis): string;
4
+ export declare function writeBundle(directory: string, analysis: Analysis, options?: {
5
+ reviewed?: boolean;
6
+ }): Promise<string[]>;
7
+ export declare function readBoundedFile(path: string, maxBytes?: number): Promise<string>;
8
+ export declare function verifyBundle(directory: string, options?: {
9
+ input?: string;
10
+ profile?: string;
11
+ }): Promise<{
12
+ suite: boolean;
13
+ reviewed: boolean;
14
+ sourceChecked: boolean;
15
+ }>;
@@ -0,0 +1,120 @@
1
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { exportFlowQa } from "./exports/flow-qa.js";
4
+ import { hash, record, text } from "./validation.js";
5
+ import { redactText } from "./redact.js";
6
+ export function jsonText(value) { return `${JSON.stringify(value, null, 2)}\n`; }
7
+ function literal(value) {
8
+ const safe = redactText(value);
9
+ const runs = safe.match(/`+/g) ?? [];
10
+ const fence = '`'.repeat(Math.max(3, ...runs.map(run => run.length + 1)));
11
+ return `${fence}text\n${safe}\n${fence}`;
12
+ }
13
+ export function renderReport(analysis) {
14
+ const lines = ['# Error to Test analysis', '',
15
+ `Groups: ${analysis.groups.length} · TC candidates: ${analysis.candidates.length}`,
16
+ `Input: ${analysis.coverage.kind} · Count meaning: ${analysis.coverage.frequency}`,
17
+ `Partial export: ${analysis.coverage.partial ? 'yes' : 'no'} · Retention coverage: unknown`,
18
+ `Duplicate records: ${analysis.coverage.duplicates} · Filtered records: ${analysis.coverage.filtered}`, '',
19
+ 'Counts describe the supplied records. They are not error rates, affected-user counts, or proof of complete collection.',
20
+ 'Drafts require review. A passing TC proves only its assertions; it does not automatically close the source issue.', ''];
21
+ if (analysis.warnings.length)
22
+ lines.push('## Coverage and selection notes', '', literal(analysis.warnings.join('\n')), '');
23
+ if (!analysis.groups.length)
24
+ lines.push('No matching errors were found. No suite was generated.', '');
25
+ for (const group of analysis.groups) {
26
+ lines.push(`## ${group.id}`, '', `Records: ${group.count} · Observed page views: ${group.viewCount} · Last observed: ${group.lastOccurredAt ?? 'unknown'}`, '', literal(`${group.project} / ${group.environment} / ${group.release} / ${group.runtime}\n${group.type} ${group.pagePath}\n${group.message}`), '');
27
+ for (const candidate of analysis.candidates.filter(item => item.groupId === group.id)) {
28
+ lines.push(`### ${candidate.id} · ${candidate.state}`, '', literal(candidate.title), '', 'Observed facts:', literal(candidate.facts.join('\n')), '', 'Expected behavior:', literal(candidate.expected ? `${candidate.expected.text}\nSource: ${candidate.expected.source}` : 'Unresolved'), '', 'Questions:', literal(candidate.questions.join('\n') || 'No context questions. Review is still required before execution.'), '');
29
+ }
30
+ }
31
+ return `${lines.join('\n')}\n`;
32
+ }
33
+ export async function writeBundle(directory, analysis, options = {}) {
34
+ const exported = exportFlowQa(analysis, options);
35
+ const report = renderReport(analysis);
36
+ exported.provenance.reportSha256 = hash(report);
37
+ const files = {
38
+ 'analysis.json': jsonText(analysis), 'report.md': report,
39
+ 'flows/error-to-test.md': exported.flow, 'provenance.json': jsonText(exported.provenance),
40
+ ...(exported.suite ? { 'cases/error-to-test.json': jsonText(exported.suite) } : {}),
41
+ };
42
+ if (Buffer.byteLength(files['analysis.json']) > 64 * 1024 * 1024 || Buffer.byteLength(report) > 64 * 1024 * 1024)
43
+ throw new Error('The analysis artifacts exceed 64 MiB. Narrow the input or selected scenario details.');
44
+ const root = resolve(directory);
45
+ await mkdir(dirname(root), { recursive: true });
46
+ try {
47
+ await mkdir(root, { mode: 0o700 });
48
+ }
49
+ catch (error) {
50
+ if (error.code === 'EEXIST')
51
+ throw new Error('The output directory already exists. Choose a new --out path.');
52
+ throw error;
53
+ }
54
+ // Exclusive files preserve any concurrent or user-supplied edits. A failed write leaves
55
+ // an inspectable partial bundle, never an apparently verified complete result.
56
+ for (const [name, content] of Object.entries(files)) {
57
+ await mkdir(dirname(resolve(root, name)), { recursive: true });
58
+ await writeFile(resolve(root, name), content, { flag: 'wx', mode: 0o600 });
59
+ }
60
+ return Object.keys(files).map(name => resolve(root, name));
61
+ }
62
+ export async function readBoundedFile(path, maxBytes = 10 * 1024 * 1024) {
63
+ const info = await stat(path);
64
+ if (!info.isFile() || info.size > maxBytes)
65
+ throw new Error('Input must be a regular file within the size limit.');
66
+ const content = await readFile(path, 'utf8');
67
+ if (Buffer.byteLength(content) > maxBytes)
68
+ throw new Error('Input exceeded the size limit while reading.');
69
+ return content;
70
+ }
71
+ export async function verifyBundle(directory, options = {}) {
72
+ const root = resolve(directory);
73
+ const parse = (content, label) => {
74
+ try {
75
+ return record(JSON.parse(content), label);
76
+ }
77
+ catch {
78
+ throw new Error(`${label} is not a valid JSON object.`);
79
+ }
80
+ };
81
+ const provenance = parse(await readBoundedFile(resolve(root, 'provenance.json')), 'provenance');
82
+ if (provenance.schemaVersion !== 'error-to-test/provenance-1' || typeof provenance.reviewed !== 'boolean')
83
+ throw new Error('Unsupported provenance contract.');
84
+ const report = await readBoundedFile(resolve(root, 'report.md'), 64 * 1024 * 1024);
85
+ if (hash(report) !== provenance.reportSha256)
86
+ throw new Error('STALE_BUNDLE: The review report changed since export.');
87
+ const analysisText = await readBoundedFile(resolve(root, 'analysis.json'), 64 * 1024 * 1024);
88
+ if (hash(analysisText) !== provenance.analysisSha256)
89
+ throw new Error('STALE_BUNDLE: The analysis changed since export.');
90
+ const analysis = parse(analysisText, 'analysis');
91
+ if (analysis.schemaVersion !== 'error-to-test/analysis-1')
92
+ throw new Error('Unsupported analysis contract.');
93
+ const source = record(analysis.source, 'analysis.source');
94
+ const flow = await readBoundedFile(resolve(root, 'flows/error-to-test.md'), 8 * 1024 * 1024);
95
+ if (hash(flow) !== provenance.flowSha256 || source.sha256 !== provenance.inputSha256 || source.profileSha256 !== provenance.profileSha256)
96
+ throw new Error('STALE_BUNDLE: Analysis, flow, and provenance no longer match.');
97
+ if (!Array.isArray(analysis.candidates))
98
+ throw new Error('Analysis candidates are missing.');
99
+ const mappings = analysis.candidates.map((raw, index) => {
100
+ const candidate = record(raw, `candidates[${index}]`);
101
+ return { caseId: candidate.id, candidateId: candidate.id, groupId: candidate.groupId, eventIds: candidate.eventIds };
102
+ });
103
+ if (JSON.stringify(mappings) !== JSON.stringify(provenance.mappings))
104
+ throw new Error('STALE_BUNDLE: Case provenance mappings no longer match the analysis.');
105
+ let suiteExists = false;
106
+ if (provenance.suiteSha256 !== undefined) {
107
+ const content = await readBoundedFile(resolve(root, 'cases/error-to-test.json'), 8 * 1024 * 1024);
108
+ if (hash(content) !== provenance.suiteSha256)
109
+ throw new Error('STALE_BUNDLE: The exported suite changed. Regenerate the bundle after review.');
110
+ const suite = parse(content, 'suite'), suiteSource = record(suite.source, 'suite.source');
111
+ if (suite.schemaVersion !== 'flow-qa/suite-1' || suiteSource.file !== 'flows/error-to-test.md' || suiteSource.sha256 !== provenance.flowSha256)
112
+ throw new Error('STALE_BUNDLE: Suite source no longer matches the flow.');
113
+ suiteExists = true;
114
+ }
115
+ if (options.input !== undefined && hash(options.input) !== text(provenance.inputSha256, 'provenance.inputSha256'))
116
+ throw new Error('STALE_BUNDLE: Input changed since analysis.');
117
+ if (options.profile !== undefined && hash(options.profile) !== provenance.profileSha256)
118
+ throw new Error('STALE_BUNDLE: Profile changed since analysis.');
119
+ return { suite: suiteExists, reviewed: provenance.reviewed, sourceChecked: options.input !== undefined };
120
+ }
@@ -0,0 +1,3 @@
1
+ import type { AppProfile, IssueGroup, TestCandidate } from './types.ts';
2
+ export declare function parseProfile(raw: unknown): AppProfile;
3
+ export declare function createCandidates(groups: IssueGroup[], profile?: AppProfile): TestCandidate[];
@@ -0,0 +1,188 @@
1
+ import { hash, optionalText, parseWebSteps, record, strings, text } from "./validation.js";
2
+ import { pagePath, redactText, safeUrl } from "./redact.js";
3
+ const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/;
4
+ const eventTypes = new Set(['javascript', 'promise', 'react', 'console', 'http', 'network', 'manual']);
5
+ const runtimes = new Set(['browser', 'webview-ios', 'webview-android', 'unknown']);
6
+ function identifier(value, label) {
7
+ const result = text(value, label);
8
+ if (!idPattern.test(result))
9
+ throw new Error(`${label} must be a Flow QA-compatible ID.`);
10
+ return result;
11
+ }
12
+ function path(value, label) {
13
+ if (!value.startsWith('/') || value.startsWith('//') || value.includes('\\') || value.includes('?') || value.includes('#'))
14
+ throw new Error(`${label} must be an app-relative path without query or fragment.`);
15
+ return value;
16
+ }
17
+ function profileText(value, label) {
18
+ const result = text(value, label);
19
+ if (redactText(result) !== result)
20
+ throw new Error(`${label} contains sensitive data; remove it before using this profile.`);
21
+ return result;
22
+ }
23
+ function profileStrings(value, label) {
24
+ return strings(value, label).map((item, index) => profileText(item, `${label}[${index}]`));
25
+ }
26
+ function stepsContainSensitiveData(steps) {
27
+ const credentialFill = steps.some((step) => step.type === 'fill' &&
28
+ /password|passwd|secret|token|api[_-]?key|authorization|cookie|session/i.test(`${step.locator.value} ${'name' in step.locator ? step.locator.name ?? '' : ''}`));
29
+ if (credentialFill)
30
+ return true;
31
+ const sanitized = steps.map((step) => {
32
+ switch (step.type) {
33
+ case 'open': return { ...step, path: safeUrl(step.path) };
34
+ case 'assertUrl': return { ...step, expected: safeUrl(step.expected) };
35
+ default: return JSON.parse(JSON.stringify(step, (_key, value) => typeof value === 'string' ? redactText(value) : value));
36
+ }
37
+ });
38
+ return JSON.stringify(steps) !== JSON.stringify(sanitized);
39
+ }
40
+ export function parseProfile(raw) {
41
+ const input = record(raw, 'profile');
42
+ if (input.schemaVersion !== 'error-to-test/profile-1')
43
+ throw new Error('Unsupported profile schemaVersion.');
44
+ if (!Array.isArray(input.scenarios) || input.scenarios.length > 100)
45
+ throw new Error('profile.scenarios must be an array of at most 100 scenarios.');
46
+ const scenarios = input.scenarios.map((rawRule, index) => {
47
+ const label = `profile.scenarios[${index}]`;
48
+ const rule = record(rawRule, label);
49
+ const match = record(rule.match, `${label}.match`);
50
+ const fields = ['type', 'messageIncludes', 'pagePath', 'networkPath', 'environment', 'release', 'runtime'];
51
+ if (!fields.some((field) => match[field] !== undefined))
52
+ throw new Error(`${label}.match needs at least one predicate.`);
53
+ const type = optionalText(match.type, `${label}.match.type`);
54
+ const runtime = optionalText(match.runtime, `${label}.match.runtime`);
55
+ if (type && !eventTypes.has(type))
56
+ throw new Error(`${label}.match.type is invalid.`);
57
+ if (runtime && !runtimes.has(runtime))
58
+ throw new Error(`${label}.match.runtime is invalid.`);
59
+ const page = match.pagePath === undefined ? undefined : profileText(match.pagePath, `${label}.match.pagePath`);
60
+ const network = match.networkPath === undefined ? undefined : profileText(match.networkPath, `${label}.match.networkPath`);
61
+ if (page)
62
+ path(page, `${label}.match.pagePath`);
63
+ if (network)
64
+ path(network, `${label}.match.networkPath`);
65
+ return {
66
+ id: identifier(rule.id, `${label}.id`),
67
+ title: profileText(rule.title, `${label}.title`),
68
+ match: {
69
+ ...(type ? { type: type } : {}),
70
+ ...(match.messageIncludes !== undefined ? { messageIncludes: profileText(match.messageIncludes, `${label}.match.messageIncludes`) } : {}),
71
+ ...(page ? { pagePath: page } : {}),
72
+ ...(network ? { networkPath: network } : {}),
73
+ ...(match.environment !== undefined ? { environment: profileText(match.environment, `${label}.match.environment`) } : {}),
74
+ ...(match.release !== undefined ? { release: profileText(match.release, `${label}.match.release`) } : {}),
75
+ ...(runtime ? { runtime: runtime } : {}),
76
+ },
77
+ requirement: profileText(rule.requirement, `${label}.requirement`),
78
+ expectedSource: profileText(rule.expectedSource, `${label}.expectedSource`),
79
+ preconditions: profileStrings(rule.preconditions, `${label}.preconditions`),
80
+ setupConfirmed: rule.setupConfirmed === undefined ? false : confirmed(rule.setupConfirmed, `${label}.setupConfirmed`),
81
+ questions: profileStrings(rule.questions, `${label}.questions`),
82
+ steps: parseWebSteps(rule.steps, `${label}.steps`),
83
+ };
84
+ });
85
+ if (new Set(scenarios.map((rule) => rule.id)).size !== scenarios.length)
86
+ throw new Error('Profile scenario IDs must be unique.');
87
+ return { schemaVersion: 'error-to-test/profile-1', name: profileText(input.name, 'profile.name'), scenarios };
88
+ }
89
+ function confirmed(value, label) {
90
+ if (typeof value !== 'boolean')
91
+ throw new Error(`${label} must be a boolean.`);
92
+ return value;
93
+ }
94
+ function matches(rule, group) {
95
+ const match = rule.match;
96
+ return (!match.type || match.type === group.type)
97
+ && (!match.messageIncludes || group.message.includes(match.messageIncludes))
98
+ && (!match.pagePath || match.pagePath === group.pagePath)
99
+ && (!match.environment || match.environment === group.environment)
100
+ && (!match.release || match.release === group.release)
101
+ && (!match.runtime || match.runtime === group.runtime)
102
+ && (!match.networkPath || group.evidence.some((event) => event.network && pagePath(event.network.url) === match.networkPath));
103
+ }
104
+ function common(items) {
105
+ if (!items.length)
106
+ return undefined;
107
+ const first = items[0];
108
+ return items.every((item) => JSON.stringify(item) === JSON.stringify(first)) ? first : undefined;
109
+ }
110
+ function hasAssertion(steps) {
111
+ return steps.some((step) => step.type.startsWith('assert'));
112
+ }
113
+ function hasAction(steps) {
114
+ return steps.some((step) => step.type === 'act' || step.type === 'click' || step.type === 'fill');
115
+ }
116
+ function questionsForSteps(steps, directNavigation) {
117
+ const questions = [];
118
+ if (steps[0]?.type !== 'open' || !steps[0].path)
119
+ questions.push('Which explicit app path should this web case open first?');
120
+ if (!hasAction(steps) && !directNavigation)
121
+ questions.push('What user action reproduced the issue? Supply explicit steps, or document a confirmed direct-navigation scenario.');
122
+ if (!hasAssertion(steps))
123
+ questions.push('What observable assertion confirms the expected behavior?');
124
+ return questions;
125
+ }
126
+ function safeFacts(group) {
127
+ const facts = [`${group.count} captured event(s); ${group.viewCount} view(s).`, `Observed ${group.type} error: ${redactText(group.message)}`, `Runtime: ${group.runtime}; environment: ${redactText(group.environment)}; release: ${redactText(group.release)}.`];
128
+ if (group.pagePath)
129
+ facts.push(`Observed page path: ${redactText(group.pagePath)}`);
130
+ for (const event of group.evidence) {
131
+ if (event.network)
132
+ facts.push(`Observed network response: ${event.network.method} ${safeUrl(event.network.url)}${event.network.status === undefined ? '' : ` (${event.network.status})`}.`);
133
+ if (event.source === 'manual' && event.expected)
134
+ facts.push(`Reporter-provided expected behavior: ${redactText(event.expected)}${event.expectedSource ? ` (source: ${redactText(event.expectedSource)})` : ' (source missing)'}.`);
135
+ }
136
+ if (group.context?.expected)
137
+ facts.push(`Reporter-provided expected behavior: ${redactText(group.context.expected)}${group.context.expectedSource ? ` (source: ${redactText(group.context.expectedSource)})` : ' (source missing)'}.`);
138
+ return [...new Set(facts)];
139
+ }
140
+ function createOne(group, rule) {
141
+ const evidence = group.evidence;
142
+ const context = group.context;
143
+ const questions = [...(rule?.questions ?? []), ...(context?.questions ?? evidence.flatMap((event) => event.questions)), ...(context?.conflicts ?? [])];
144
+ const manualSteps = !rule ? (context ? context.steps : common(evidence.map((event) => event.steps))) : undefined;
145
+ const submittedSteps = rule?.steps ?? manualSteps ?? [];
146
+ const steps = stepsContainSensitiveData(submittedSteps) ? [] : submittedSteps;
147
+ const manualExpected = !rule ? (context
148
+ ? context.expected && context.expectedSource ? { text: context.expected, source: context.expectedSource } : undefined
149
+ : common(evidence.map((event) => event.expected && event.expectedSource ? { text: event.expected, source: event.expectedSource } : undefined))) : undefined;
150
+ const expected = rule ? { text: rule.requirement, source: rule.expectedSource } : manualExpected;
151
+ const preconditions = rule?.preconditions ?? (context ? context.preconditions : common(evidence.map((event) => event.preconditions))) ?? [];
152
+ const reproduction = context ? context.reproduction ?? [] : [...new Set(evidence.flatMap((event) => event.reproduction))];
153
+ if (!rule && !context && !common(evidence.map((event) => event.reproduction)) && reproduction.length)
154
+ questions.push('Which reported reproduction sequence applies to this group?');
155
+ if (!rule && !manualSteps)
156
+ questions.push('Which explicit reproduction steps apply to all events in this group?');
157
+ if (steps.length !== submittedSteps.length)
158
+ questions.push('Execution steps contained sensitive data. Provide safe, reviewed steps before running.');
159
+ if (!expected)
160
+ questions.push('What is the expected behavior, and which requirement or reporter establishes it?');
161
+ if (!rule && preconditions.length)
162
+ questions.push('Have the reported setup and preconditions been confirmed?');
163
+ if (preconditions.some((condition) => redactText(condition) !== condition))
164
+ questions.push('Reported preconditions contained sensitive data. Provide safe setup instructions.');
165
+ if (rule && !rule.setupConfirmed)
166
+ questions.push('Has the scenario setup and its preconditions been confirmed?');
167
+ if (group.runtime !== 'browser')
168
+ questions.push(`Which actual test engine and context cover the ${group.runtime} runtime?`);
169
+ if (!rule && expected && !hasAssertion(steps))
170
+ questions.push('The reported expected behavior needs an explicit observable assertion.');
171
+ questions.push(...questionsForSteps(steps, Boolean(rule?.setupConfirmed && preconditions.length)));
172
+ const id = `TC_${hash(`${group.id}:${rule?.id ?? 'manual'}`).slice(0, 16)}`;
173
+ return {
174
+ id, groupId: group.id, title: rule?.title ?? `Investigate ${group.type} error`,
175
+ state: questions.length ? 'needs-context' : 'draft',
176
+ facts: safeFacts(group), hypotheses: [], reproduction: reproduction.map(redactText),
177
+ preconditions: preconditions.filter((condition) => redactText(condition) === condition),
178
+ ...(expected ? { expected: { text: redactText(expected.text), source: redactText(expected.source) } } : {}),
179
+ questions: [...new Set(questions.map(redactText))], steps,
180
+ eventIds: [...new Set(group.eventIds)], ...(rule ? { ruleId: rule.id } : {}),
181
+ };
182
+ }
183
+ export function createCandidates(groups, profile) {
184
+ return groups.flatMap((group) => {
185
+ const rules = (profile?.scenarios ?? []).filter((rule) => matches(rule, group)).sort((a, b) => a.id.localeCompare(b.id));
186
+ return rules.length ? rules.map((rule) => createOne(group, rule)) : [createOne(group)];
187
+ });
188
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function main(args?: string[]): Promise<void>;
2
+ export declare function reportCliError(error: unknown): void;