@richjava/req0 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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -0
  3. package/cockpit/android-chrome-192x192.png +0 -0
  4. package/cockpit/android-chrome-512x512.png +0 -0
  5. package/cockpit/app.js +1710 -0
  6. package/cockpit/apple-touch-icon.png +0 -0
  7. package/cockpit/favicon-16x16.png +0 -0
  8. package/cockpit/favicon-32x32.png +0 -0
  9. package/cockpit/favicon.ico +0 -0
  10. package/cockpit/index.html +180 -0
  11. package/cockpit/markdown-editor.js +93 -0
  12. package/cockpit/req0-logo-horiz.png +0 -0
  13. package/cockpit/req0-logo-stacked.png +0 -0
  14. package/cockpit/site.webmanifest +19 -0
  15. package/cockpit/styles.css +1710 -0
  16. package/cockpit/tokens.css +118 -0
  17. package/dist/adapter.d.ts +5 -0
  18. package/dist/adapter.js +16 -0
  19. package/dist/browser.d.ts +33 -0
  20. package/dist/browser.js +524 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +265 -0
  23. package/dist/compile.d.ts +5 -0
  24. package/dist/compile.js +456 -0
  25. package/dist/diff.d.ts +15 -0
  26. package/dist/diff.js +114 -0
  27. package/dist/fix-from-proof.d.ts +13 -0
  28. package/dist/fix-from-proof.js +61 -0
  29. package/dist/gates.d.ts +7 -0
  30. package/dist/gates.js +7 -0
  31. package/dist/implement-brief.d.ts +9 -0
  32. package/dist/implement-brief.js +142 -0
  33. package/dist/implement.d.ts +70 -0
  34. package/dist/implement.js +615 -0
  35. package/dist/improve-log.d.ts +11 -0
  36. package/dist/improve-log.js +38 -0
  37. package/dist/improve-review.d.ts +45 -0
  38. package/dist/improve-review.js +182 -0
  39. package/dist/improve.d.ts +16 -0
  40. package/dist/improve.js +127 -0
  41. package/dist/jev-pack.d.ts +2 -0
  42. package/dist/jev-pack.js +114 -0
  43. package/dist/jev.d.ts +23 -0
  44. package/dist/jev.js +142 -0
  45. package/dist/pack.d.ts +101 -0
  46. package/dist/pack.js +609 -0
  47. package/dist/personas.d.ts +13 -0
  48. package/dist/personas.js +88 -0
  49. package/dist/proof-report.d.ts +8 -0
  50. package/dist/proof-report.js +82 -0
  51. package/dist/proof.d.ts +45 -0
  52. package/dist/proof.js +394 -0
  53. package/dist/qa-plan.d.ts +6 -0
  54. package/dist/qa-plan.js +58 -0
  55. package/dist/ready.d.ts +29 -0
  56. package/dist/ready.js +317 -0
  57. package/dist/runtime.d.ts +25 -0
  58. package/dist/runtime.js +125 -0
  59. package/dist/server.d.ts +15 -0
  60. package/dist/server.js +588 -0
  61. package/dist/stack.d.ts +35 -0
  62. package/dist/stack.js +220 -0
  63. package/dist/stages.d.ts +15 -0
  64. package/dist/stages.js +345 -0
  65. package/dist/template.d.ts +5 -0
  66. package/dist/template.js +55 -0
  67. package/dist/types.d.ts +282 -0
  68. package/dist/types.js +12 -0
  69. package/docs/requirement-template.md +341 -0
  70. package/package.json +81 -0
@@ -0,0 +1,88 @@
1
+ const ROLE_LINE = /^ {2}([^:\s][^:]*):[ \t]*$/;
2
+ const FIELD_LINE = /^ {4}([A-Za-z][A-Za-z0-9_-]*):[ \t]*(.*)$/;
3
+ export function parsePersonasYaml(source) {
4
+ const findings = [];
5
+ const personas = new Map();
6
+ const lines = source.replace(/^\uFEFF/, "").split(/\r?\n/);
7
+ let started = false;
8
+ let current = null;
9
+ const flush = () => {
10
+ if (!current)
11
+ return;
12
+ if (!current.email) {
13
+ findings.push({
14
+ line: current.line,
15
+ severity: "error",
16
+ message: `Persona "${current.role}" is missing email.`,
17
+ });
18
+ }
19
+ else {
20
+ personas.set(current.role, {
21
+ role: current.role,
22
+ email: current.email,
23
+ password: current.password,
24
+ });
25
+ }
26
+ current = null;
27
+ };
28
+ for (let i = 0; i < lines.length; i++) {
29
+ const raw = lines[i] ?? "";
30
+ const line = i + 1;
31
+ const trimmed = raw.trim();
32
+ if (!trimmed || trimmed.startsWith("#"))
33
+ continue;
34
+ if (!started) {
35
+ if (trimmed === "personas:" || trimmed === "personas") {
36
+ started = true;
37
+ continue;
38
+ }
39
+ findings.push({
40
+ line,
41
+ severity: "error",
42
+ message: `fixtures/personas.yaml must start with a top-level "personas:" map (got "${trimmed}").`,
43
+ });
44
+ return { personas, findings, missingFile: false };
45
+ }
46
+ const role = raw.match(ROLE_LINE);
47
+ if (role) {
48
+ flush();
49
+ const name = (role[1] ?? "").trim();
50
+ if (!name) {
51
+ findings.push({ line, severity: "error", message: "Persona role name cannot be blank." });
52
+ continue;
53
+ }
54
+ if (personas.has(name)) {
55
+ findings.push({ line, severity: "error", message: `Duplicate persona "${name}".` });
56
+ }
57
+ current = { role: name, line };
58
+ continue;
59
+ }
60
+ const field = raw.match(FIELD_LINE);
61
+ if (field && current) {
62
+ const key = (field[1] ?? "").toLowerCase();
63
+ const value = (field[2] ?? "").trim();
64
+ if (key === "email")
65
+ current.email = value;
66
+ else if (key === "password")
67
+ current.password = value;
68
+ continue;
69
+ }
70
+ findings.push({
71
+ line,
72
+ severity: "error",
73
+ message: "Unrecognized personas.yaml line. Use a role at 2-space indent and email/password at 4-space indent.",
74
+ });
75
+ }
76
+ flush();
77
+ if (!started) {
78
+ findings.push({
79
+ line: 1,
80
+ severity: "error",
81
+ message: 'fixtures/personas.yaml must contain a top-level "personas:" map.',
82
+ });
83
+ }
84
+ return { personas, findings, missingFile: false };
85
+ }
86
+ export function missingPersonaRoles(spec, personas) {
87
+ return spec.matrix.roles.filter((role) => !personas.personas.has(role));
88
+ }
@@ -0,0 +1,8 @@
1
+ import type { ProofRun, QaPlan, ReadyMeter, SpecAst } from "./types.js";
2
+ export declare function emitProofReport(input: {
3
+ spec: SpecAst;
4
+ plan: QaPlan;
5
+ run: ProofRun;
6
+ ready?: Pick<ReadyMeter, "state" | "packNoul">;
7
+ baseUrl?: string;
8
+ }): string;
@@ -0,0 +1,82 @@
1
+ const VERDICT_ORDER = {
2
+ fail: 0,
3
+ review: 1,
4
+ pass: 2,
5
+ };
6
+ const SECTION_HEADING = {
7
+ fail: "Failed",
8
+ review: "Needs review",
9
+ pass: "Passed",
10
+ };
11
+ export function emitProofReport(input) {
12
+ const { spec, plan, run } = input;
13
+ const passed = run.cases.filter((item) => item.verdict === "pass").length;
14
+ const failed = run.cases.filter((item) => item.verdict === "fail").length;
15
+ const review = run.cases.filter((item) => item.verdict === "review").length;
16
+ const result = !run.boot.ok
17
+ ? "Failed — app did not boot"
18
+ : failed
19
+ ? `Failed — ${passed} passed, ${failed} failed${review ? `, ${review} needs review` : ""}`
20
+ : review
21
+ ? `Needs review — ${passed} passed, ${review} needs review`
22
+ : `Passed — ${run.cases.length} case${run.cases.length === 1 ? "" : "s"}`;
23
+ const lines = [
24
+ `# Proof report — ${spec.requirementId}`,
25
+ "",
26
+ spec.title,
27
+ "",
28
+ `Checked at: ${run.checkedAt}`,
29
+ `Result: **${result}**`,
30
+ ];
31
+ if (input.ready) {
32
+ const noul = typeof input.ready.packNoul === "number" ? ` · ${input.ready.packNoul.toFixed(2)}` : "";
33
+ lines.push(`Ready: ${input.ready.state}${noul}`);
34
+ }
35
+ if (input.baseUrl)
36
+ lines.push(`Runtime: ${input.baseUrl}`);
37
+ lines.push(`Boot: ${run.boot.ok ? "ok" : (run.boot.message ?? "failed")}`);
38
+ lines.push("");
39
+ lines.push("This report is the last Prove. It uses the same use-case IDs as requirement.md. It is not a second test suite.");
40
+ lines.push("");
41
+ if (!run.boot.ok && !run.cases.length) {
42
+ lines.push("No cases were run.");
43
+ lines.push("");
44
+ return lines.join("\n");
45
+ }
46
+ const byId = new Map(plan.cases.map((item) => [item.id, item]));
47
+ const titles = new Map(spec.useCases.map((item) => [item.id, item.title]));
48
+ const ordered = [...run.cases].sort((a, b) => {
49
+ const rank = VERDICT_ORDER[a.verdict] - VERDICT_ORDER[b.verdict];
50
+ if (rank !== 0)
51
+ return rank;
52
+ return plan.cases.findIndex((item) => item.id === a.id) - plan.cases.findIndex((item) => item.id === b.id);
53
+ });
54
+ let section;
55
+ for (const item of ordered) {
56
+ if (item.verdict !== section) {
57
+ section = item.verdict;
58
+ lines.push(`## ${SECTION_HEADING[item.verdict]}`, "");
59
+ }
60
+ const qa = byId.get(item.id);
61
+ const title = titles.get(item.id);
62
+ lines.push(`### ${item.id}${title ? ` — ${title}` : ""}`, "");
63
+ lines.push(`- Actor: ${qa?.actor ?? "—"}`);
64
+ lines.push(`- Kind: ${item.kind}`);
65
+ lines.push(`- Verdict: ${item.verdict}`);
66
+ if (typeof item.noul === "number")
67
+ lines.push(`- Confidence (noul): ${item.noul.toFixed(2)}`);
68
+ if (qa?.preconditions)
69
+ lines.push(`- Preconditions: ${qa.preconditions}`);
70
+ if (qa?.steps.length) {
71
+ lines.push("- Steps:");
72
+ for (const [index, step] of qa.steps.entries()) {
73
+ lines.push(` ${index + 1}. ${step}`);
74
+ }
75
+ }
76
+ if (qa?.outcome)
77
+ lines.push(`- Expected: ${qa.outcome}`);
78
+ lines.push(`- Observed: ${item.message}`);
79
+ lines.push("");
80
+ }
81
+ return lines.join("\n");
82
+ }
@@ -0,0 +1,45 @@
1
+ import { type ProofDriver } from "./browser.js";
2
+ import { type JevClient } from "./jev.js";
3
+ import type { PersonasResult } from "./personas.js";
4
+ import type { QaPlan } from "./qa-plan.js";
5
+ import type { RuntimeFixture } from "./runtime.js";
6
+ import type { CompileResult, ProgressFn, ProofMeter, ProofRun, SpecAst } from "./types.js";
7
+ export type { ProofDriver } from "./browser.js";
8
+ export declare class ProveLockedError extends Error {
9
+ readonly code = "prove_gate";
10
+ constructor(message?: string);
11
+ }
12
+ export declare function emptyProof(runtime?: boolean, message?: string): ProofMeter;
13
+ export declare function evaluateProof(input: {
14
+ spec: SpecAst | null;
15
+ runtime: boolean;
16
+ run: ProofRun | null;
17
+ buildAt?: string | null;
18
+ }): ProofMeter;
19
+ export declare function assertProveAllowed(result: CompileResult): void;
20
+ export declare function provePlan(input: {
21
+ spec: SpecAst;
22
+ plan: QaPlan;
23
+ runtime: RuntimeFixture;
24
+ personas: PersonasResult;
25
+ productRoot: string | null;
26
+ buildAt?: string;
27
+ }, deps?: {
28
+ driver?: ProofDriver;
29
+ client?: JevClient;
30
+ fetchImpl?: typeof fetch;
31
+ waitForUrl?: (url: string) => Promise<boolean>;
32
+ inspectLogin?: boolean;
33
+ onProgress?: ProgressFn;
34
+ runReset?: (command: string, cwd: string) => Promise<void>;
35
+ }): Promise<ProofRun>;
36
+ export declare function persistProofRun(paths: {
37
+ derived: string;
38
+ proofRun: string;
39
+ proofReport?: string;
40
+ }, run: ProofRun, report?: string): Promise<void>;
41
+ export declare function inspectLoginPage(loginUrl: string, fetchImpl: typeof fetch, note?: ProgressFn): Promise<{
42
+ ok: boolean;
43
+ message?: string;
44
+ }>;
45
+ export declare function productRootFor(packRoot: string): Promise<string | null>;
package/dist/proof.js ADDED
@@ -0,0 +1,394 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { spawn } from "node:child_process";
3
+ import { createPlaywrightDriver, shortError } from "./browser.js";
4
+ import { NOUL_FAIL, NOUL_PASS } from "./gates.js";
5
+ import { createMockJevClient, resolveJevClient } from "./jev.js";
6
+ import { specHash } from "./ready.js";
7
+ import { buildAllowsProve } from "./stages.js";
8
+ import { inspectProductRepo } from "./stack.js";
9
+ export class ProveLockedError extends Error {
10
+ code = "prove_gate";
11
+ constructor(message = "Prove is locked until Ready is Ready, fixtures/runtime.yaml parses, and Build succeeded (unless implement is off in req0.json).") {
12
+ super(message);
13
+ this.name = "ProveLockedError";
14
+ }
15
+ }
16
+ export function emptyProof(runtime = false, message) {
17
+ return {
18
+ state: "not_yet",
19
+ runtime,
20
+ ...(message ? { message } : {}),
21
+ findings: [],
22
+ };
23
+ }
24
+ export function evaluateProof(input) {
25
+ if (!input.runtime)
26
+ return emptyProof(false);
27
+ if (!input.run || !input.spec)
28
+ return emptyProof(true);
29
+ if (input.run.specHash !== specHash(input.spec)) {
30
+ return {
31
+ state: "stale",
32
+ runtime: true,
33
+ message: "Spec changed after the last proof run.",
34
+ findings: [],
35
+ };
36
+ }
37
+ if (input.buildAt && input.run.buildAt !== input.buildAt) {
38
+ return {
39
+ state: "stale",
40
+ runtime: true,
41
+ message: "Build changed after the last proof run.",
42
+ findings: [],
43
+ };
44
+ }
45
+ if (!input.run.boot.ok) {
46
+ return {
47
+ state: "failed",
48
+ runtime: true,
49
+ message: input.run.boot.message ?? "App did not boot or accept deterministic login.",
50
+ failed: 1,
51
+ passed: 0,
52
+ review: 0,
53
+ findings: [
54
+ {
55
+ id: "proof.boot",
56
+ specId: input.spec.requirementId,
57
+ severity: "fail",
58
+ message: input.run.boot.message ?? "App did not boot or accept deterministic login.",
59
+ },
60
+ ],
61
+ };
62
+ }
63
+ const passed = input.run.cases.filter((item) => item.verdict === "pass").length;
64
+ const failed = input.run.cases.filter((item) => item.verdict === "fail").length;
65
+ const review = input.run.cases.filter((item) => item.verdict === "review").length;
66
+ const findings = input.run.cases
67
+ .filter((item) => item.verdict !== "pass")
68
+ .map((item) => ({
69
+ id: `proof.${item.id}`,
70
+ specId: item.id,
71
+ severity: item.verdict === "fail" ? "fail" : "review",
72
+ message: item.message,
73
+ noul: item.noul,
74
+ }));
75
+ const state = failed > 0 ? "failed" : review > 0 ? "needs_review" : "passed";
76
+ return { state, runtime: true, passed, failed, review, findings };
77
+ }
78
+ export function assertProveAllowed(result) {
79
+ if (result.health.ready.state !== "ready") {
80
+ throw new ProveLockedError("Prove is locked until Ready is Ready.");
81
+ }
82
+ if (!buildAllowsProve(result.health.build)) {
83
+ throw new ProveLockedError("Prove is locked until Build succeeded, or you Ignore a failed Build.");
84
+ }
85
+ if (!result.health.proof.runtime) {
86
+ throw new ProveLockedError("Prove is locked without fixtures/runtime.yaml (baseUrl and deterministic login).");
87
+ }
88
+ }
89
+ export async function provePlan(input, deps = {}) {
90
+ const fetchImpl = deps.fetchImpl ?? fetch;
91
+ const waitForUrl = deps.waitForUrl ?? ((url) => urlResponds(url, fetchImpl));
92
+ const note = deps.onProgress ?? (() => { });
93
+ const boot = await ensureBaseUrl(input.runtime, input.productRoot, waitForUrl, note, {
94
+ inspectLogin: deps.inspectLogin ?? !deps.waitForUrl,
95
+ fetchImpl,
96
+ });
97
+ if (!boot.ok) {
98
+ return stampProofRun(input.spec, boot, [], input.buildAt);
99
+ }
100
+ if (input.runtime.resetCommand && !input.productRoot) {
101
+ const message = "resetCommand is set, but there is no product repo root to run it in.";
102
+ note(message, "error");
103
+ return stampProofRun(input.spec, { ok: false, message }, [], input.buildAt);
104
+ }
105
+ const total = input.plan.cases.length;
106
+ note(`App is up. ${total} case${total === 1 ? "" : "s"} in derived/qa-plan.yaml.`);
107
+ let driver;
108
+ try {
109
+ if (!deps.driver)
110
+ note("Launching the browser…");
111
+ driver = deps.driver ?? (await createPlaywrightDriver(note));
112
+ }
113
+ catch (err) {
114
+ const message = shortError(err);
115
+ note(message, "error");
116
+ return stampProofRun(input.spec, { ok: false, message }, [], input.buildAt);
117
+ }
118
+ const client = deps.client ?? (process.env.REQ0_PROOF === "mock" ? createMockJevClient() : resolveJevClient());
119
+ const cases = [];
120
+ try {
121
+ for (const [index, qa] of input.plan.cases.entries()) {
122
+ const persona = input.personas.personas.get(qa.actor);
123
+ note(`Case ${index + 1}/${total} — ${qa.id} as ${qa.actor} (${qa.kind}).`);
124
+ if (!persona?.email) {
125
+ const message = `No persona email for actor "${qa.actor}".`;
126
+ note(message, "error");
127
+ cases.push({
128
+ id: qa.id,
129
+ kind: qa.kind,
130
+ verdict: "fail",
131
+ message,
132
+ });
133
+ continue;
134
+ }
135
+ if (input.runtime.resetCommand && input.productRoot) {
136
+ try {
137
+ note(`Resetting fixtures for ${qa.id} (\`${input.runtime.resetCommand}\`)…`);
138
+ await (deps.runReset ?? runResetCommand)(input.runtime.resetCommand, input.productRoot);
139
+ }
140
+ catch (err) {
141
+ const message = shortError(err);
142
+ note(message, "error");
143
+ cases.push({ id: qa.id, kind: qa.kind, verdict: "fail", message });
144
+ continue;
145
+ }
146
+ }
147
+ note(`Logging in as ${persona.email}…`);
148
+ let observed;
149
+ try {
150
+ observed = await driver.runCase({ runtime: input.runtime, persona, qa });
151
+ }
152
+ catch (err) {
153
+ const message = shortError(err);
154
+ note(`${qa.id}: ${message}`, "error");
155
+ cases.push({ id: qa.id, kind: qa.kind, verdict: "fail", message });
156
+ continue;
157
+ }
158
+ try {
159
+ const judged = await judgeCase(qa, persona, observed, client, input.spec.requirementId, note);
160
+ note(judged.message, judged.verdict === "fail" ? "error" : judged.verdict === "pass" ? "ok" : "info");
161
+ cases.push(judged);
162
+ }
163
+ catch (err) {
164
+ const message = shortError(err);
165
+ note(`${qa.id}: ${message}`, "error");
166
+ cases.push({ id: qa.id, kind: qa.kind, verdict: "review", message });
167
+ }
168
+ }
169
+ }
170
+ finally {
171
+ note("Closing the browser…");
172
+ await driver.close?.();
173
+ }
174
+ return stampProofRun(input.spec, { ok: true }, cases, input.buildAt);
175
+ }
176
+ function stampProofRun(spec, boot, cases, buildAt) {
177
+ return {
178
+ specHash: specHash(spec),
179
+ checkedAt: new Date().toISOString(),
180
+ ...(buildAt ? { buildAt } : {}),
181
+ boot,
182
+ cases,
183
+ };
184
+ }
185
+ export async function persistProofRun(paths, run, report) {
186
+ await mkdir(paths.derived, { recursive: true });
187
+ await writeFile(paths.proofRun, `${JSON.stringify(run, null, 2)}\n`, "utf8");
188
+ if (paths.proofReport && report !== undefined) {
189
+ await writeFile(paths.proofReport, report.endsWith("\n") ? report : `${report}\n`, "utf8");
190
+ }
191
+ }
192
+ async function judgeCase(qa, persona, observed, client, requirementId, note) {
193
+ if (observed.error) {
194
+ return { id: qa.id, kind: qa.kind, verdict: "fail", message: observed.error };
195
+ }
196
+ if (qa.kind === "deny") {
197
+ if (!qa.control) {
198
+ return {
199
+ id: qa.id,
200
+ kind: qa.kind,
201
+ verdict: "review",
202
+ message: `${qa.id} deny case has no Choose/Look-for control to check.`,
203
+ };
204
+ }
205
+ const hidden = !observed.controlAvailable || observed.controlDisabled;
206
+ return {
207
+ id: qa.id,
208
+ kind: qa.kind,
209
+ verdict: hidden ? "pass" : "fail",
210
+ message: hidden
211
+ ? `${qa.control} is absent or disabled for ${persona.role}.`
212
+ : `${qa.control} was available and enabled for ${persona.role}; deny failed.`,
213
+ };
214
+ }
215
+ if (qa.control && !observed.clicked) {
216
+ return {
217
+ id: qa.id,
218
+ kind: qa.kind,
219
+ verdict: "fail",
220
+ message: observed.controlAvailable
221
+ ? `${qa.control} was disabled for ${persona.role}.`
222
+ : `${qa.control} was not available for ${persona.role}.`,
223
+ };
224
+ }
225
+ note(`Asking Jev whether ${qa.id} matches the Outcome…`);
226
+ const answers = await withTimeout(client.judge({
227
+ requirementId,
228
+ catalog: "m4-proof-v1",
229
+ questions: [
230
+ {
231
+ id: `proof.outcome.${qa.id}`,
232
+ type: "noul",
233
+ specId: qa.id,
234
+ instructions: "Does this page observation match the Outcome? Score only clauses that url, text, and options can confirm or contradict. Clauses about later use cases do not lower the score when the visible clauses match.",
235
+ criteria: {
236
+ true: "Every Outcome clause this page can show is true (status, who is assigned or selected, who is listed in options, visible controls).",
237
+ false: "A checkable Outcome clause is missing or contradicted, or this is the wrong page.",
238
+ },
239
+ state: {
240
+ id: qa.id,
241
+ actor: qa.actor,
242
+ outcome: qa.outcome,
243
+ url: observed.url,
244
+ text: observed.text,
245
+ options: observed.options,
246
+ },
247
+ },
248
+ ],
249
+ }), 60_000, `Jev did not answer ${qa.id} within 60s.`);
250
+ const noul = answers[0]?.noul;
251
+ if (typeof noul !== "number") {
252
+ return {
253
+ id: qa.id,
254
+ kind: qa.kind,
255
+ verdict: "review",
256
+ message: `${qa.id} allow case did not get a noul from Jev.`,
257
+ };
258
+ }
259
+ const verdict = noul >= NOUL_PASS ? "pass" : noul <= NOUL_FAIL ? "fail" : "review";
260
+ return {
261
+ id: qa.id,
262
+ kind: qa.kind,
263
+ verdict,
264
+ noul,
265
+ message: verdict === "pass"
266
+ ? `${qa.id} outcome matched (noul ${noul.toFixed(2)}).`
267
+ : verdict === "fail"
268
+ ? `${qa.id} outcome did not match (noul ${noul.toFixed(2)}).`
269
+ : `${qa.id} outcome needs review (noul ${noul.toFixed(2)}).`,
270
+ };
271
+ }
272
+ async function ensureBaseUrl(runtime, productRoot, waitForUrl, note, options) {
273
+ const loginUrl = new URL(runtime.login.path, `${runtime.baseUrl}/`).toString();
274
+ note(`Checking ${runtime.baseUrl}…`);
275
+ if (await waitForUrl(runtime.baseUrl)) {
276
+ note(`Already listening at ${runtime.baseUrl}.`);
277
+ if (options.inspectLogin) {
278
+ const login = await inspectLoginPage(loginUrl, options.fetchImpl, note);
279
+ if (!login.ok)
280
+ return login;
281
+ }
282
+ return { ok: true };
283
+ }
284
+ if (!runtime.startCommand) {
285
+ return {
286
+ ok: false,
287
+ message: `Nothing is listening at ${runtime.baseUrl}. Add startCommand to fixtures/runtime.yaml or start the app.`,
288
+ };
289
+ }
290
+ if (!productRoot) {
291
+ return { ok: false, message: "No product repo root, so startCommand cannot run." };
292
+ }
293
+ note(`Starting the app (\`${runtime.startCommand}\`)…`);
294
+ spawn(runtime.startCommand, {
295
+ cwd: productRoot,
296
+ shell: true,
297
+ detached: true,
298
+ stdio: "ignore",
299
+ }).unref();
300
+ const deadline = Date.now() + 45_000;
301
+ let lastPing = Date.now();
302
+ while (Date.now() < deadline) {
303
+ if (await waitForUrl(runtime.baseUrl)) {
304
+ note(`App responded at ${runtime.baseUrl}.`);
305
+ if (options.inspectLogin) {
306
+ const login = await inspectLoginPage(loginUrl, options.fetchImpl, note);
307
+ if (!login.ok)
308
+ return login;
309
+ }
310
+ return { ok: true };
311
+ }
312
+ if (Date.now() - lastPing >= 5_000) {
313
+ lastPing = Date.now();
314
+ note(`Still waiting for ${runtime.baseUrl} (${Math.ceil((deadline - Date.now()) / 1000)}s left).`);
315
+ }
316
+ await new Promise((resolve) => setTimeout(resolve, 500));
317
+ }
318
+ return {
319
+ ok: false,
320
+ message: `startCommand ran but ${runtime.baseUrl} did not respond in time.`,
321
+ };
322
+ }
323
+ export async function inspectLoginPage(loginUrl, fetchImpl, note = () => { }) {
324
+ note(`Checking login ${loginUrl}…`);
325
+ try {
326
+ const response = await fetchImpl(loginUrl, { redirect: "manual", signal: AbortSignal.timeout(2500) });
327
+ const type = response.headers.get("content-type") ?? "";
328
+ if (response.status === 404 || (response.status >= 400 && /json/i.test(type))) {
329
+ return {
330
+ ok: false,
331
+ message: `${loginUrl} returned HTTP ${response.status}. ${new URL(loginUrl).origin} is answering, but it is not this product's login page. Stop the other process on that port or change fixtures/runtime.yaml baseUrl.`,
332
+ };
333
+ }
334
+ if (response.status >= 400 && response.status !== 401) {
335
+ return { ok: false, message: `${loginUrl} returned HTTP ${response.status}.` };
336
+ }
337
+ note(`Login page responded (${response.status}).`);
338
+ return { ok: true };
339
+ }
340
+ catch {
341
+ return { ok: false, message: `Could not reach ${loginUrl}.` };
342
+ }
343
+ }
344
+ async function urlResponds(url, fetchImpl = fetch) {
345
+ try {
346
+ const response = await fetchImpl(url, { redirect: "manual", signal: AbortSignal.timeout(2500) });
347
+ return response.status > 0;
348
+ }
349
+ catch {
350
+ return false;
351
+ }
352
+ }
353
+ export async function productRootFor(packRoot) {
354
+ return (await inspectProductRepo(packRoot)).root;
355
+ }
356
+ async function runResetCommand(command, cwd) {
357
+ await new Promise((resolve, reject) => {
358
+ const child = spawn(command, { cwd, shell: true, stdio: ["ignore", "pipe", "pipe"] });
359
+ let err = "";
360
+ child.stderr?.on("data", (chunk) => {
361
+ err += String(chunk);
362
+ });
363
+ const timer = setTimeout(() => {
364
+ child.kill();
365
+ reject(new Error(`resetCommand timed out: ${command}`));
366
+ }, 60_000);
367
+ child.on("error", (error) => {
368
+ clearTimeout(timer);
369
+ reject(error);
370
+ });
371
+ child.on("exit", (code) => {
372
+ clearTimeout(timer);
373
+ if (code === 0)
374
+ resolve();
375
+ else
376
+ reject(new Error(`resetCommand exited ${code}.${err.trim() ? ` ${err.trim().slice(0, 400)}` : ""}`));
377
+ });
378
+ });
379
+ }
380
+ async function withTimeout(promise, ms, message) {
381
+ let timer;
382
+ try {
383
+ return await Promise.race([
384
+ promise,
385
+ new Promise((_, reject) => {
386
+ timer = setTimeout(() => reject(new Error(message)), ms);
387
+ }),
388
+ ]);
389
+ }
390
+ finally {
391
+ if (timer)
392
+ clearTimeout(timer);
393
+ }
394
+ }
@@ -0,0 +1,6 @@
1
+ import type { QaCaseKind, QaPlan, SpecAst, UseCase } from "./types.js";
2
+ export type { QaCase, QaCaseKind, QaPlan } from "./types.js";
3
+ export declare function emitQaPlan(spec: SpecAst): QaPlan;
4
+ export declare function caseKind(useCase: UseCase): QaCaseKind;
5
+ export declare function controlName(useCase: UseCase): string | null;
6
+ export declare function emitQaPlanYaml(plan: QaPlan): string;
@@ -0,0 +1,58 @@
1
+ import { specHash } from "./ready.js";
2
+ export function emitQaPlan(spec) {
3
+ return {
4
+ requirementId: spec.requirementId,
5
+ specHash: specHash(spec),
6
+ cases: spec.useCases.map((useCase) => ({
7
+ id: useCase.id,
8
+ specId: useCase.id,
9
+ kind: caseKind(useCase),
10
+ actor: useCase.actor,
11
+ control: controlName(useCase),
12
+ steps: useCase.steps,
13
+ preconditions: useCase.preconditions,
14
+ outcome: useCase.outcome,
15
+ })),
16
+ };
17
+ }
18
+ export function caseKind(useCase) {
19
+ if (useCase.steps.some((step) => /^look for\b/i.test(step)))
20
+ return "deny";
21
+ // Choose is allow. After-success wording like "absent or disabled" is the new state, not a deny.
22
+ if (useCase.steps.some((step) => /^choose\b/i.test(step)))
23
+ return "allow";
24
+ if (/\b(not available|absent or disabled|is unchanged)\b/i.test(useCase.outcome)) {
25
+ return "deny";
26
+ }
27
+ return "allow";
28
+ }
29
+ export function controlName(useCase) {
30
+ for (const step of useCase.steps) {
31
+ const match = step.match(/^(?:Look for|Choose)\s+(.+)$/i);
32
+ if (match?.[1])
33
+ return match[1].trim();
34
+ }
35
+ return null;
36
+ }
37
+ export function emitQaPlanYaml(plan) {
38
+ const lines = [
39
+ `requirementId: ${yamlScalar(plan.requirementId)}`,
40
+ `specHash: ${yamlScalar(plan.specHash)}`,
41
+ "cases:",
42
+ ];
43
+ for (const item of plan.cases) {
44
+ lines.push(` - id: ${yamlScalar(item.id)}`, ` specId: ${yamlScalar(item.specId)}`, ` kind: ${item.kind}`, ` actor: ${yamlScalar(item.actor)}`, ` control: ${item.control ? yamlScalar(item.control) : "null"}`, ` preconditions: ${yamlScalar(item.preconditions)}`, ` outcome: ${yamlScalar(item.outcome)}`, " steps:");
45
+ for (const step of item.steps) {
46
+ lines.push(` - ${yamlScalar(step)}`);
47
+ }
48
+ }
49
+ return `${lines.join("\n")}\n`;
50
+ }
51
+ function yamlScalar(value) {
52
+ if (value === "")
53
+ return '""';
54
+ if (/[:#\n'"{}[\],&*?|<>=!%@`]|^\s|\s$|^[-?]/.test(value)) {
55
+ return JSON.stringify(value);
56
+ }
57
+ return value;
58
+ }