@ihyeon/error-to-test 0.2.3 → 0.2.5
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 +34 -0
- package/README.md +53 -0
- package/dist/analysis.d.ts +1 -0
- package/dist/analysis.js +15 -0
- package/dist/artifacts.js +15 -0
- package/dist/cli.js +31 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/refinement.d.ts +3 -0
- package/dist/refinement.js +249 -0
- package/dist/types.d.ts +9 -0
- package/package.json +1 -1
package/README.ko.md
CHANGED
|
@@ -137,6 +137,21 @@ error-to-test analyze --input current-errors.json --baseline ./before --min-coun
|
|
|
137
137
|
|
|
138
138
|
이전에 없었다는 표시가 새로 유입된 버그나 회귀를 확정하지는 않습니다. 부분 내보내기·기간·수집 범위 차이 등 비교 경고를 유지하고, 수집 이벤트와 수동 제출 보고서를 섞으면 거부합니다. 출력은 이전 번들의 `results` 폴더 밖에 있는 새 디렉터리만 허용합니다. API는 `await analyzeWithBaseline(content, baselineDirectory, { minCount: 3, top: 10, profile })`이며 이전 번들 검증도 수행합니다.
|
|
139
139
|
|
|
140
|
+
**특정 오류 묶음만 골라 TC를 생성**하려면 `--group`을 사용하세요. 먼저 분석한 `report.md`나 `analysis.json`에서 묶음 ID를 확인합니다.
|
|
141
|
+
|
|
142
|
+
```sh
|
|
143
|
+
error-to-test analyze --input errors.json --out ./all-errors
|
|
144
|
+
# 아래 예시 ID를 ./all-errors/report.md의 실제 ID로 바꾸세요.
|
|
145
|
+
error-to-test analyze --input errors.json --group group-0123456789abcdef --group group-fedcba9876543210 --out ./selected-tcs
|
|
146
|
+
error-to-test init-profile ./selected-tcs --out ./selected-profile.json
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
최대 100회 지정할 수 있으며 중복 ID는 한 번만 적용합니다. `group-` 뒤에 소문자 16진수 16자리가 붙는 정확한 ID여야 하며, 현재 입력의 원본·날짜 필터를 적용한 뒤에도 존재해야 합니다. 다른 릴리스·변경된 입력·제외된 기간의 ID 등 알 수 없는 ID는 번들 생성 전에 오류로 알립니다. ID를 얻은 분석과 같은 원본 파일·순서·수동 메타데이터·날짜 필터로 다시 분석하세요.
|
|
150
|
+
|
|
151
|
+
지정한 묶음과 `--baseline`의 교집합에 기존 순위대로 `--min-count`, `--top`을 적용합니다. ID를 입력한 순서로 우선순위가 바뀌지 않습니다. 알려진 ID라도 이 조건 때문에 TC가 생성되지 않을 수 있으며, 선택된 TC가 없으면 suite 없는 정상 번들을 만들고 `readiness`는 `empty`와 종료 코드 2를 반환합니다. 한 묶음에 여러 프로필 규칙이 적용되면 기존처럼 여러 TC를 생성할 수 있습니다.
|
|
152
|
+
|
|
153
|
+
전체 오류 묶음·원본 해시·수집 범위는 보존합니다. 요청한 ID는 정렬·중복 제거해 `analysis.groupFilter.groupIds`에 기록하고 분석 해시로 보호하며, 보고서에도 선택 범위를 남깁니다. 비교와 이전 분석 기준의 건수는 전체 묶음을 계속 사용합니다. 맥락 질문과 검토 조건도 유지합니다. `--group`을 생략하면 기존 선택 방식이며, 다른 명령에서는 거부합니다. API는 `analyzeErrors(content, { groupIds: [groupId] })`와 `analyzeWithBaseline()`의 같은 옵션입니다. 비어 있지 않은 최대 100개 항목 배열을 받으며 입력 배열을 변경하지 않습니다.
|
|
154
|
+
|
|
140
155
|
`report.md` 상단에서 TC 초안 수와 추가 정보가 필요한 TC 수를 확인할 수 있습니다. 초안도 실행 전에 검토해야 합니다. 오류 묶음·수집 건수와 함께 대표 로그의 오류·React 컴포넌트 스택, 재현 방법·사전 조건·테스트 단계·부족한 정보도 표시합니다. 같은 스택은 한 번만 표시하며, 전체 로그의 모든 스택을 나열하지는 않습니다. 재현 단계와 정상 기대 결과, 명시적인 assertion이 없으면 질문이 있는 TC를 생성합니다. 직접 입력한 보고서에는 실제 발생 시각·사용자 수를 만들어 넣지 않습니다. 수집 건수도 실제 발생률을 뜻하지 않으며, 원본 내보내기의 일부 데이터 표시를 유지합니다.
|
|
141
156
|
|
|
142
157
|
기본 suite는 검토 질문으로 실행이 차단됩니다. TC와 프로필을 확인한 뒤 다른 출력 폴더에 `--reviewed`로 다시 생성하면 검토 질문만 제거됩니다. 나머지 질문은 그대로 실행을 차단합니다. 프로필의 `setupConfirmed`는 준비 조건을 확인했다는 표시이며, 계정·데이터를 자동으로 준비하는 기능은 아닙니다.
|
|
@@ -173,6 +188,25 @@ TC 생성과 동일하게 모든 조건을 함께 검사해 기존 규칙이 적
|
|
|
173
188
|
|
|
174
189
|
API는 `createProfileTemplate(analysis, { profile: existingProfile })`입니다. JSON 값만으로 구성한 객체 또는 BOM 하나를 지원하는 JSON 문자열을 1 MiB까지 받으며 입력 객체를 변경하지 않습니다. 객체의 선택 필드가 `undefined`이면 해당 속성을 생략하세요. `profile`을 생략하면 기존 빈 템플릿을 만듭니다.
|
|
175
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
|
+
|
|
176
210
|
```sh
|
|
177
211
|
node bin/error-to-test.mjs verify .error-to-test/example --input examples/errors.json --profile examples/profile.json
|
|
178
212
|
node bin/error-to-test.mjs analyze --input examples/errors.json --profile examples/profile.json --reviewed --out .error-to-test/reviewed
|
package/README.md
CHANGED
|
@@ -172,6 +172,25 @@ The analysis records `selection.mode: "only-current"`, the baseline input and ve
|
|
|
172
172
|
|
|
173
173
|
The async API is `await analyzeWithBaseline(content, baselineDirectory, { minCount: 3, top: 10, profile })`. It verifies the baseline bundle itself and accepts the same analysis options as `analyzeErrors`.
|
|
174
174
|
|
|
175
|
+
### Generate TCs for specific error groups
|
|
176
|
+
|
|
177
|
+
Use `--group` to focus on exact group IDs from an initial `report.md` or `analysis.json`:
|
|
178
|
+
|
|
179
|
+
```sh
|
|
180
|
+
error-to-test analyze --input errors.json --out ./all-errors
|
|
181
|
+
# Replace these example IDs with actual IDs from ./all-errors/report.md.
|
|
182
|
+
error-to-test analyze --input errors.json --group group-0123456789abcdef --group group-fedcba9876543210 --out ./selected-tcs
|
|
183
|
+
error-to-test init-profile ./selected-tcs --out ./selected-profile.json
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Repeat `--group` up to 100 times. Each ID must have the exact `group-` plus 16 lowercase hexadecimal digits format and exist in the current input after source/date filters. Duplicate IDs are counted once. Unknown IDs fail before a bundle is written, so an ID from a different release, changed input, or excluded period cannot silently generate an empty suite. Reuse the same input files, order, manual metadata, and date filters used to obtain the IDs.
|
|
187
|
+
|
|
188
|
+
Requested groups are intersected with any `--baseline` selection, then `--min-count` and `--top` apply in the original ranked order. Argument order does not change priority. A known group can still be excluded by these conditions; zero selected cases creates a valid bundle without a suite, and `readiness` reports `empty` with exit `2`. A selected group may produce several profile-based TCs as before.
|
|
189
|
+
|
|
190
|
+
The complete observed groups, input hashes, and source coverage remain in the new bundle. `analysis.groupFilter.groupIds` stores the sorted, deduplicated requested IDs, covered by the analysis hash, and the report records the scope. Comparison and baseline counts continue to use all observed groups. Missing-context and review questions still block execution. Omitting `--group` keeps the existing selection behavior; other commands reject this analyze-only option.
|
|
191
|
+
|
|
192
|
+
The API accepts `analyzeErrors(content, { groupIds: [groupId], top: 10 })` and the same option in `analyzeWithBaseline()`. `groupIds` must be a nonempty array of at most 100 entries; it is not mutated.
|
|
193
|
+
|
|
175
194
|
## Confirm the intended behavior
|
|
176
195
|
|
|
177
196
|
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.
|
|
@@ -214,6 +233,40 @@ New templates retain blank expectation fields, `setupConfirmed: false`, and the
|
|
|
214
233
|
|
|
215
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.
|
|
216
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
|
+
|
|
217
270
|
## Review and use Flow QA
|
|
218
271
|
|
|
219
272
|
Generated files (Flow QA source is limited to 128 KB; suite JSON to 512 KiB):
|
package/dist/analysis.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export interface AnalyzeOptions extends ParseInputOptions {
|
|
|
4
4
|
profile?: unknown;
|
|
5
5
|
top?: number;
|
|
6
6
|
minCount?: number;
|
|
7
|
+
groupIds?: readonly string[];
|
|
7
8
|
}
|
|
8
9
|
export declare function analyzeErrors(content: string | readonly string[], options?: AnalyzeOptions): Analysis;
|
|
9
10
|
export declare function analyzeWithBaseline(content: string | readonly string[], baselineDirectory: string, options?: AnalyzeOptions): Promise<Analysis>;
|
package/dist/analysis.js
CHANGED
|
@@ -11,6 +11,12 @@ function analyze(content, options, baseline) {
|
|
|
11
11
|
const minCount = options.minCount ?? 1;
|
|
12
12
|
if (!Number.isInteger(minCount) || minCount < 1 || minCount > 10000)
|
|
13
13
|
throw new Error('minCount must be an integer between 1 and 10000.');
|
|
14
|
+
const requestedGroupIds = options.groupIds;
|
|
15
|
+
if (requestedGroupIds !== undefined && (!Array.isArray(requestedGroupIds) || requestedGroupIds.length < 1 || requestedGroupIds.length > 100 ||
|
|
16
|
+
!requestedGroupIds.every(id => typeof id === 'string' && /^group-[0-9a-f]{16}$/.test(id)))) {
|
|
17
|
+
throw new Error('groupIds must contain 1 to 100 valid group IDs.');
|
|
18
|
+
}
|
|
19
|
+
const groupIds = requestedGroupIds === undefined ? undefined : [...new Set(requestedGroupIds)].sort();
|
|
14
20
|
let rawProfile = options.profile;
|
|
15
21
|
const profileSource = typeof rawProfile === 'string' ? rawProfile : rawProfile === undefined ? undefined : JSON.stringify(rawProfile);
|
|
16
22
|
if (typeof rawProfile === 'string') {
|
|
@@ -26,6 +32,9 @@ function analyze(content, options, baseline) {
|
|
|
26
32
|
const profile = rawProfile === undefined ? undefined : parseProfile(rawProfile);
|
|
27
33
|
const input = parseInput(content, options);
|
|
28
34
|
const groups = groupObservations(input.observations);
|
|
35
|
+
if (groupIds && groupIds.some(id => !groups.some(group => group.id === id))) {
|
|
36
|
+
throw new Error('A requested group ID was not found in the filtered input.');
|
|
37
|
+
}
|
|
29
38
|
const source = { sha256: input.sha256, ...(input.inputs ? { inputs: input.inputs } : {}),
|
|
30
39
|
...(profileSource !== undefined ? { profileSha256: hash(profileSource) } : {}) };
|
|
31
40
|
const warnings = [...input.warnings];
|
|
@@ -59,6 +68,11 @@ function analyze(content, options, baseline) {
|
|
|
59
68
|
warnings.push('Baseline JSONL has no export coverage metadata; partial false means unmarked, and collection completeness and retention are unknown.');
|
|
60
69
|
}
|
|
61
70
|
}
|
|
71
|
+
if (groupIds) {
|
|
72
|
+
const requested = new Set(groupIds);
|
|
73
|
+
selectedGroups = selectedGroups.filter(group => requested.has(group.id));
|
|
74
|
+
warnings.push(`Explicit group TC selection: ${groupIds.length} requested groups; ${selectedGroups.length} intersect the current selection before minCount and top. All groups remain in analysis.json.`);
|
|
75
|
+
}
|
|
62
76
|
const eligibleGroups = selectedGroups.filter(group => group.count >= minCount);
|
|
63
77
|
if (eligibleGroups.length < selectedGroups.length)
|
|
64
78
|
warnings.push(`TC selection requires at least ${minCount} supplied records per group; ${eligibleGroups.length} of ${selectedGroups.length} groups are eligible. All groups remain in analysis.json. These counts are supplied records, not global rates.`);
|
|
@@ -74,6 +88,7 @@ function analyze(content, options, baseline) {
|
|
|
74
88
|
candidates: createCandidates(eligibleGroups.slice(0, top), profile),
|
|
75
89
|
warnings,
|
|
76
90
|
...(selection ? { selection } : {}),
|
|
91
|
+
...(groupIds ? { groupFilter: { groupIds } } : {}),
|
|
77
92
|
};
|
|
78
93
|
}
|
|
79
94
|
export function analyzeErrors(content, options = {}) {
|
package/dist/artifacts.js
CHANGED
|
@@ -30,6 +30,21 @@ 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')), '');
|
|
42
|
+
if (analysis.groupFilter)
|
|
43
|
+
lines.push('## Explicit group selection', '', literal([
|
|
44
|
+
`Requested group IDs: ${analysis.groupFilter.groupIds.join(', ')}`,
|
|
45
|
+
'TCs are selected from these exact current groups, intersected with any baseline selection, before min-count and top. Input ID order does not change ranking.',
|
|
46
|
+
'All observed groups remain in this analysis. Unselected groups are outside the TC scope.',
|
|
47
|
+
].join('\n')), '');
|
|
33
48
|
if (analysis.selection)
|
|
34
49
|
lines.push('## Baseline candidate selection', '', literal([
|
|
35
50
|
'Mode: only-current (signatures absent from the supplied baseline)',
|
package/dist/cli.js
CHANGED
|
@@ -11,10 +11,12 @@ 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
|
|
17
18
|
error-to-test analyze --input errors.json --baseline previous-bundle --out new-directory
|
|
19
|
+
error-to-test analyze --input errors.json --group GROUP_ID --group OTHER_GROUP_ID --out selected-directory
|
|
18
20
|
error-to-test analyze --input error.txt --format text --page /items --out new-directory
|
|
19
21
|
error-to-test analyze --input errors.jsonl --format jsonl --out new-directory
|
|
20
22
|
error-to-test analyze --error "TypeError: item is undefined" --page /items --out new-directory
|
|
@@ -22,6 +24,7 @@ const help = `Error to Test — local error analysis and regression TC drafts
|
|
|
22
24
|
error-to-test verify new-directory [--input errors-1.json --input errors-2.json] [--profile profile.json]
|
|
23
25
|
error-to-test init-profile new-directory --out profile.json
|
|
24
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]
|
|
25
28
|
error-to-test link-run new-directory --report path/to/qa-report.json
|
|
26
29
|
error-to-test results new-directory [--format text|json] [--out summary.md]
|
|
27
30
|
error-to-test readiness new-directory [--format text|json]
|
|
@@ -35,6 +38,7 @@ Options:
|
|
|
35
38
|
--format text|json Compare format (default: text Markdown)
|
|
36
39
|
--format text|json Readiness format (default: text Markdown; exit 0 ready, 2 blocked/empty, 1 on error)
|
|
37
40
|
--profile FILE Confirmed app scenarios and explicit assertions (analyze/verify); existing profile to extend (init-profile)
|
|
41
|
+
--profile FILE Replacement profile for the bundle's previously selected groups (refine; required)
|
|
38
42
|
--baseline DIRECTORY Select only signatures absent from this verified bundle, before --min-count and --top; retain all groups in analysis.json (analyze only)
|
|
39
43
|
--project NAME Metadata for a manual report
|
|
40
44
|
--environment NAME Metadata for a manual report
|
|
@@ -48,8 +52,10 @@ Options:
|
|
|
48
52
|
--expected-source TEXT Expected-result source (--error only)
|
|
49
53
|
--from ISO --to ISO Filter observed timestamps; undated reports are excluded
|
|
50
54
|
--min-count N Select groups with at least N records after dedup/date filtering (1..10000)
|
|
55
|
+
--group GROUP_ID Select TCs only for these exact current group IDs; repeat up to 100 times (analyze only; before --min-count/--top)
|
|
51
56
|
--top N Generate TCs for the first N eligible ranked groups (1..100; after --min-count)
|
|
52
57
|
--out DIRECTORY New analyze directory; existing files are never overwritten
|
|
58
|
+
--out DIRECTORY New refine directory outside the source bundle (required; review defaults to pending)
|
|
53
59
|
--out FILE New init-profile JSON file; existing files are never overwritten
|
|
54
60
|
--out FILE New results summary file; existing files are never overwritten
|
|
55
61
|
--out FILE New comparison file; existing files are never overwritten
|
|
@@ -140,12 +146,16 @@ function insideBundleResults(bundleRoot, path) {
|
|
|
140
146
|
return false;
|
|
141
147
|
return rest.split(sep, 1)[0]?.toLowerCase() === 'results';
|
|
142
148
|
}
|
|
149
|
+
function insideBundle(bundleRoot, path) {
|
|
150
|
+
const rest = relative(bundleRoot.toLowerCase(), path.toLowerCase());
|
|
151
|
+
return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest));
|
|
152
|
+
}
|
|
143
153
|
export async function main(args = process.argv.slice(2)) {
|
|
144
154
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, strict: true, options: {
|
|
145
155
|
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, input: { type: 'string', multiple: true }, error: { type: 'string' }, report: { type: 'string' },
|
|
146
156
|
format: { type: 'string' }, profile: { type: 'string' }, baseline: { type: 'string' }, project: { type: 'string' }, environment: { type: 'string' },
|
|
147
157
|
release: { type: 'string' }, page: { type: 'string' }, type: { type: 'string' }, runtime: { type: 'string' }, from: { type: 'string' }, to: { type: 'string' },
|
|
148
|
-
top: { type: 'string' }, 'min-count': { type: 'string' }, 'max-new': { type: 'string' }, out: { type: 'string' }, reviewed: { type: 'boolean' },
|
|
158
|
+
top: { type: 'string' }, 'min-count': { type: 'string' }, 'max-new': { type: 'string' }, group: { type: 'string', multiple: true }, out: { type: 'string' }, reviewed: { type: 'boolean' },
|
|
149
159
|
reproduce: { type: 'string', multiple: true }, precondition: { type: 'string', multiple: true },
|
|
150
160
|
expected: { type: 'string' }, 'expected-source': { type: 'string' },
|
|
151
161
|
} });
|
|
@@ -160,11 +170,26 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
160
170
|
}
|
|
161
171
|
if (positionals.length === 0) {
|
|
162
172
|
if (Object.keys(values).length)
|
|
163
|
-
throw new Error('A command is required. Use analyze, init-profile, verify, link-run, results, compare, or readiness. See --help.');
|
|
173
|
+
throw new Error('A command is required. Use analyze, init-profile, refine, verify, link-run, results, compare, or readiness. See --help.');
|
|
164
174
|
process.stdout.write(help);
|
|
165
175
|
return;
|
|
166
176
|
}
|
|
167
177
|
const command = positionals[0];
|
|
178
|
+
if (command === 'refine') {
|
|
179
|
+
if (positionals.length !== 2 || !positionals[1]?.trim() || !values.profile?.trim() || !values.out?.trim())
|
|
180
|
+
throw new Error('refine requires one bundle directory, --profile FILE, and --out DIRECTORY.');
|
|
181
|
+
if (Object.keys(values).some(key => !['profile', 'out', 'reviewed', 'help'].includes(key)))
|
|
182
|
+
throw new Error('Unsupported option for refine. Use only --profile FILE, --out DIRECTORY, and --reviewed.');
|
|
183
|
+
const bundle = resolve(positionals[1]);
|
|
184
|
+
const out = resolve(values.out);
|
|
185
|
+
if (insideBundle(await realpath(bundle), await canonicalOutput(out)))
|
|
186
|
+
throw new Error('The refined output must be outside the source bundle. Choose a new --out DIRECTORY path.');
|
|
187
|
+
const analysis = await refineBundle(bundle, await readBoundedFile(resolve(values.profile), 1024 * 1024));
|
|
188
|
+
const files = await writeBundle(out, analysis, { reviewed: values.reviewed });
|
|
189
|
+
const drafts = analysis.candidates.filter(candidate => candidate.state === 'draft').length;
|
|
190
|
+
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`);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
168
193
|
if (command === 'init-profile') {
|
|
169
194
|
if (positionals.length !== 2 || !positionals[1] || !values.out)
|
|
170
195
|
throw new Error('init-profile requires one bundle directory and --out FILE.');
|
|
@@ -337,7 +362,7 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
337
362
|
return;
|
|
338
363
|
}
|
|
339
364
|
if (command !== 'analyze' || positionals.length !== 1)
|
|
340
|
-
throw new Error('Use analyze, init-profile, verify, link-run, results, compare, or readiness. See --help.');
|
|
365
|
+
throw new Error('Use analyze, init-profile, refine, verify, link-run, results, compare, or readiness. See --help.');
|
|
341
366
|
if (values.report)
|
|
342
367
|
throw new Error('--report applies to link-run only.');
|
|
343
368
|
if (values['max-new'] !== undefined)
|
|
@@ -380,6 +405,7 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
380
405
|
project: values.project, environment: values.environment, release: values.release, page: values.page, type: values.type, runtime: values.runtime,
|
|
381
406
|
from: values.from, to: values.to, ...(values.top !== undefined ? { top: Number(values.top) } : {}),
|
|
382
407
|
...(values['min-count'] !== undefined ? { minCount: Number(values['min-count']) } : {}),
|
|
408
|
+
...(values.group !== undefined ? { groupIds: values.group } : {}),
|
|
383
409
|
};
|
|
384
410
|
const baseline = values.baseline === undefined ? undefined : resolve(values.baseline);
|
|
385
411
|
const analysis = baseline === undefined ? analyzeErrors(content, options) : await analyzeWithBaseline(content, baseline, options);
|
|
@@ -392,6 +418,8 @@ export async function main(args = process.argv.slice(2)) {
|
|
|
392
418
|
process.stdout.write(`${analysis.groups.length} error groups; ${analysis.candidates.length} TC candidates (${drafts} drafts, ${analysis.candidates.length - drafts} need context).\n`);
|
|
393
419
|
if (analysis.selection)
|
|
394
420
|
process.stdout.write(`${analysis.selection.onlyCurrentGroupCount} only-current groups; ${analysis.selection.excludedGroupCount} baseline-matched groups excluded from TC selection.\n`);
|
|
421
|
+
if (analysis.groupFilter)
|
|
422
|
+
process.stdout.write(`${analysis.groupFilter.groupIds.length} explicit group IDs requested; min-count, top, and baseline selection still apply.\n`);
|
|
395
423
|
process.stdout.write(`Review ${resolve(out, 'report.md')}\n${files.length} artifacts written. Review acknowledgment: ${values.reviewed ? 'yes' : 'pending'}.\n`);
|
|
396
424
|
}
|
|
397
425
|
export function reportCliError(error) {
|
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,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
|
@@ -179,6 +179,15 @@ export interface Analysis {
|
|
|
179
179
|
onlyCurrentGroupCount: number;
|
|
180
180
|
excludedGroupCount: number;
|
|
181
181
|
};
|
|
182
|
+
groupFilter?: {
|
|
183
|
+
groupIds: string[];
|
|
184
|
+
};
|
|
185
|
+
refinement?: {
|
|
186
|
+
sourceAnalysisSha256: string;
|
|
187
|
+
sourceSuiteSha256?: string;
|
|
188
|
+
sourceProfileSha256?: string;
|
|
189
|
+
selectedGroupIds: string[];
|
|
190
|
+
};
|
|
182
191
|
}
|
|
183
192
|
export interface FlowQaSuite {
|
|
184
193
|
schemaVersion: 'flow-qa/suite-1';
|
package/package.json
CHANGED