@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,45 @@
1
+ import { type DiffHunk } from "./diff.js";
2
+ import type { Health } from "./types.js";
3
+ import type { PackPaths } from "./pack.js";
4
+ export declare const IMPROVE_REVIEW_FILES: readonly ["requirement.md", "fixtures/personas.yaml"];
5
+ export declare class ImproveReviewPendingError extends Error {
6
+ readonly code = "improve_review_pending";
7
+ constructor(message?: string);
8
+ }
9
+ export declare class ImproveLintError extends Error {
10
+ readonly code = "improve_lint";
11
+ constructor(message?: string);
12
+ }
13
+ export declare const MATRIX_TALK: RegExp;
14
+ export type ImproveSnapshotFile = {
15
+ relative: (typeof IMPROVE_REVIEW_FILES)[number];
16
+ content: string | null;
17
+ };
18
+ export type ImproveSnapshot = {
19
+ at: string;
20
+ files: ImproveSnapshotFile[];
21
+ };
22
+ export type ImproveFileDiff = {
23
+ relative: string;
24
+ status: "modified" | "added" | "deleted";
25
+ additions: number;
26
+ deletions: number;
27
+ hunks: DiffHunk[];
28
+ };
29
+ export type ImproveLint = {
30
+ ok: boolean;
31
+ messages: string[];
32
+ };
33
+ export type ImproveReview = {
34
+ at: string;
35
+ waiting: boolean;
36
+ files: ImproveFileDiff[];
37
+ lint: ImproveLint;
38
+ };
39
+ export declare function readImproveSnapshot(paths: PackPaths): Promise<ImproveSnapshot | null>;
40
+ export declare function beginImproveReview(paths: PackPaths): Promise<ImproveSnapshot>;
41
+ export declare function evaluateImproveReview(paths: PackPaths): Promise<ImproveReview | null>;
42
+ export declare function lintImproveDiff(files: ImproveFileDiff[]): ImproveLint;
43
+ export declare function acceptImproveReview(paths: PackPaths): Promise<void>;
44
+ export declare function rejectImproveReview(paths: PackPaths): Promise<void>;
45
+ export declare function applyImproveReviewGate(health: Health, review: ImproveReview | null): Health;
@@ -0,0 +1,182 @@
1
+ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { unifiedDiff } from "./diff.js";
4
+ import { clearImprovePending, commitImprovePending } from "./improve-log.js";
5
+ export const IMPROVE_REVIEW_FILES = ["requirement.md", "fixtures/personas.yaml"];
6
+ export class ImproveReviewPendingError extends Error {
7
+ code = "improve_review_pending";
8
+ constructor(message = "Accept or reject the Improve patch first.") {
9
+ super(message);
10
+ this.name = "ImproveReviewPendingError";
11
+ }
12
+ }
13
+ export class ImproveLintError extends Error {
14
+ code = "improve_lint";
15
+ constructor(message = "Improve patch uses matrix talk. Reject it.") {
16
+ super(message);
17
+ this.name = "ImproveLintError";
18
+ }
19
+ }
20
+ export const MATRIX_TALK = /\bis allow\b|\bis deny\b|without changing the matrix cell/i;
21
+ const REVIEW_ABS = {
22
+ "requirement.md": (paths) => paths.requirement,
23
+ "fixtures/personas.yaml": (paths) => paths.personas,
24
+ };
25
+ export async function readImproveSnapshot(paths) {
26
+ try {
27
+ const raw = JSON.parse(await readFile(paths.improveSnapshot, "utf8"));
28
+ if (!raw.at || !Array.isArray(raw.files))
29
+ return null;
30
+ return raw;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ export async function beginImproveReview(paths) {
37
+ if (await readImproveSnapshot(paths)) {
38
+ throw new ImproveReviewPendingError();
39
+ }
40
+ const snapshot = {
41
+ at: new Date().toISOString(),
42
+ files: await Promise.all(IMPROVE_REVIEW_FILES.map(async (relative) => ({
43
+ relative,
44
+ content: await readReviewFile(paths, relative),
45
+ }))),
46
+ };
47
+ await mkdir(paths.derived, { recursive: true });
48
+ await writeFile(paths.improveSnapshot, `${JSON.stringify(snapshot, null, 2)}\n`, "utf8");
49
+ return snapshot;
50
+ }
51
+ export async function evaluateImproveReview(paths) {
52
+ const snapshot = await readImproveSnapshot(paths);
53
+ if (!snapshot)
54
+ return null;
55
+ const files = [];
56
+ for (const entry of snapshot.files) {
57
+ if (!isReviewFile(entry.relative))
58
+ continue;
59
+ const current = await readReviewFile(paths, entry.relative);
60
+ if (current === entry.content)
61
+ continue;
62
+ const hunks = unifiedDiff(entry.content, current);
63
+ const additions = hunks.reduce((sum, hunk) => sum + hunk.lines.filter((line) => line.kind === "add").length, 0);
64
+ const deletions = hunks.reduce((sum, hunk) => sum + hunk.lines.filter((line) => line.kind === "del").length, 0);
65
+ files.push({
66
+ relative: entry.relative,
67
+ status: entry.content == null ? "added" : current == null ? "deleted" : "modified",
68
+ additions,
69
+ deletions,
70
+ hunks,
71
+ });
72
+ }
73
+ return { at: snapshot.at, waiting: files.length === 0, files, lint: lintImproveDiff(files) };
74
+ }
75
+ export function lintImproveDiff(files) {
76
+ const messages = [];
77
+ for (const file of files) {
78
+ if (file.relative !== "requirement.md")
79
+ continue;
80
+ for (const hunk of file.hunks) {
81
+ for (const line of hunk.lines) {
82
+ if (line.kind !== "add" || !MATRIX_TALK.test(line.text))
83
+ continue;
84
+ messages.push(`Do not add matrix talk: ${line.text.trim()}`);
85
+ }
86
+ }
87
+ }
88
+ return { ok: messages.length === 0, messages };
89
+ }
90
+ export async function acceptImproveReview(paths) {
91
+ const review = await evaluateImproveReview(paths);
92
+ if (!review) {
93
+ throw new ImproveReviewPendingError("No Improve patch to review.");
94
+ }
95
+ if (!review.lint.ok) {
96
+ throw new ImproveLintError(review.lint.messages[0] ?? "Improve patch uses matrix talk. Reject it.");
97
+ }
98
+ await commitImprovePending(paths);
99
+ await clearImproveSnapshot(paths);
100
+ }
101
+ export async function rejectImproveReview(paths) {
102
+ const snapshot = await readImproveSnapshot(paths);
103
+ if (!snapshot) {
104
+ throw new ImproveReviewPendingError("No Improve patch to review.");
105
+ }
106
+ for (const entry of snapshot.files) {
107
+ if (!isReviewFile(entry.relative))
108
+ continue;
109
+ const file = REVIEW_ABS[entry.relative](paths);
110
+ if (entry.content == null) {
111
+ await unlink(file).catch(() => undefined);
112
+ }
113
+ else {
114
+ await mkdir(path.dirname(file), { recursive: true });
115
+ await writeFile(file, entry.content, "utf8");
116
+ }
117
+ }
118
+ await clearImprovePending(paths);
119
+ await clearImproveSnapshot(paths);
120
+ }
121
+ export function applyImproveReviewGate(health, review) {
122
+ if (!review || !health.stages)
123
+ return health;
124
+ if (review.files.length === 0) {
125
+ return {
126
+ ...health,
127
+ howThisIsGoing: "Waiting for the Improve patch.",
128
+ nextAction: {
129
+ id: "review-improve",
130
+ label: "Waiting for the patch",
131
+ enabled: false,
132
+ hint: "Reject to cancel and keep the current spec.",
133
+ },
134
+ stages: gateStages(health.stages, false),
135
+ };
136
+ }
137
+ const lintOk = review.lint?.ok !== false;
138
+ return {
139
+ ...health,
140
+ howThisIsGoing: lintOk
141
+ ? "Review the Improve patch."
142
+ : "Improve patch uses matrix talk. Reject it.",
143
+ nextAction: {
144
+ id: "review-improve",
145
+ label: "Accept the patch",
146
+ enabled: lintOk,
147
+ hint: lintOk
148
+ ? "Or reject to restore the spec from before Improve."
149
+ : review.lint?.messages[0] ?? "Outcome must not say is allow or is deny.",
150
+ },
151
+ stages: gateStages(health.stages, true),
152
+ };
153
+ }
154
+ function gateStages(stages, hasDiff) {
155
+ return {
156
+ ready: {
157
+ id: hasDiff ? "review-improve" : "improve",
158
+ label: hasDiff ? "Review" : "Improve it",
159
+ enabled: false,
160
+ hint: hasDiff ? "Accept or reject the Improve diff." : "A patch is in flight.",
161
+ },
162
+ build: { ...stages.build, enabled: false },
163
+ proof: { ...stages.proof, enabled: false },
164
+ ...(stages.fixFromProof ? { fixFromProof: { ...stages.fixFromProof, enabled: false } } : {}),
165
+ ...(stages.ignoreBuild ? { ignoreBuild: { ...stages.ignoreBuild, enabled: false } } : {}),
166
+ ...(stages.stopImplement ? { stopImplement: { ...stages.stopImplement, enabled: false } } : {}),
167
+ };
168
+ }
169
+ async function readReviewFile(paths, relative) {
170
+ try {
171
+ return await readFile(REVIEW_ABS[relative](paths), "utf8");
172
+ }
173
+ catch {
174
+ return null;
175
+ }
176
+ }
177
+ async function clearImproveSnapshot(paths) {
178
+ await unlink(paths.improveSnapshot).catch(() => undefined);
179
+ }
180
+ function isReviewFile(relative) {
181
+ return IMPROVE_REVIEW_FILES.includes(relative);
182
+ }
@@ -0,0 +1,16 @@
1
+ import type { ReadyFinding, ReadyMeter, SpecAst } from "./types.js";
2
+ export declare class ImproveLockedError extends Error {
3
+ readonly code = "improve_gate";
4
+ constructor(message?: string);
5
+ }
6
+ export declare function findingKeys(finding: ReadyFinding): string[];
7
+ export declare function improveFindings(ready: ReadyMeter): ReadyFinding[];
8
+ export declare function improveAllowed(ready: ReadyMeter): boolean;
9
+ export declare function improveHint(ready: ReadyMeter): string;
10
+ export declare function assertImproveAllowed(ready: ReadyMeter): void;
11
+ export declare function emitImproveBrief(input: {
12
+ spec: SpecAst | null;
13
+ ready: ReadyMeter;
14
+ findings?: ReadyFinding[];
15
+ }): string;
16
+ export declare function excerptForFinding(finding: ReadyFinding, spec: SpecAst | null | undefined): string[];
@@ -0,0 +1,127 @@
1
+ import { NOUL_PASS } from "./gates.js";
2
+ export class ImproveLockedError extends Error {
3
+ code = "improve_gate";
4
+ constructor(message = "Improve it is only when Ready is blocked or pack noul is below 0.75.") {
5
+ super(message);
6
+ this.name = "ImproveLockedError";
7
+ }
8
+ }
9
+ export function findingKeys(finding) {
10
+ return [finding.id, finding.specId].filter((key) => Boolean(key));
11
+ }
12
+ export function improveFindings(ready) {
13
+ const skip = new Set(ready.alreadyImproved ?? []);
14
+ return ready.findings.filter((finding) => !skip.has(finding.id) && !(finding.specId && skip.has(finding.specId)));
15
+ }
16
+ export function improveAllowed(ready) {
17
+ const open = improveFindings(ready);
18
+ if (open.length === 0)
19
+ return false;
20
+ if (open.some((finding) => finding.kind === "persona_missing"))
21
+ return true;
22
+ if (ready.jevCurrent !== true)
23
+ return false;
24
+ if (ready.state === "blocked")
25
+ return true;
26
+ return typeof ready.packNoul === "number" && ready.packNoul < NOUL_PASS;
27
+ }
28
+ export function improveHint(ready) {
29
+ if (typeof ready.packNoul === "number" && ready.packNoul < NOUL_PASS) {
30
+ return `Opinionated pass to raise pack noul above ${NOUL_PASS.toFixed(2)}.`;
31
+ }
32
+ const first = improveFindings(ready)[0];
33
+ return first?.message ?? "Opinionated pass for Ready blockers.";
34
+ }
35
+ export function assertImproveAllowed(ready) {
36
+ if (!improveAllowed(ready)) {
37
+ throw new ImproveLockedError();
38
+ }
39
+ }
40
+ export function emitImproveBrief(input) {
41
+ const findings = input.findings ?? improveFindings(input.ready);
42
+ const personas = findings.some((finding) => finding.kind === "persona_missing");
43
+ const noul = typeof input.ready.packNoul === "number" ? input.ready.packNoul.toFixed(2) : "unknown";
44
+ const specIds = input.spec
45
+ ? [
46
+ ...input.spec.businessRules.map((rule) => rule.id),
47
+ ...input.spec.useCases.map((useCase) => useCase.id),
48
+ ...input.spec.matrix.roles,
49
+ ]
50
+ : [];
51
+ const lines = [
52
+ `# Improve: ${input.spec?.requirementId ?? "requirement"}`,
53
+ "",
54
+ "Opinionated writer pass. Patch the pack so a coding agent can implement without guessing.",
55
+ "Do not interview the owner. Apply the rules below to every named finding in one diff.",
56
+ "",
57
+ "## Goal",
58
+ "",
59
+ `- Pack noul is ${noul}. The gate is ${NOUL_PASS.toFixed(2)}.`,
60
+ `- Ready is ${input.ready.state} (${input.ready.blockers} blocker${input.ready.blockers === 1 ? "" : "s"}, ${input.ready.nits} nit${input.ready.nits === 1 ? "" : "s"}).`,
61
+ "- Raise pack noul above the gate and clear Ready blockers.",
62
+ "",
63
+ "## Findings",
64
+ "",
65
+ ];
66
+ if (findings.length === 0) {
67
+ lines.push("No open Ready findings.", "");
68
+ }
69
+ for (const [index, finding] of findings.entries()) {
70
+ lines.push(`### ${index + 1}. ${finding.specId ?? finding.id}`, "");
71
+ lines.push(`- Kind: ${finding.kind}`);
72
+ lines.push(`- Severity: ${finding.severity}`);
73
+ if (finding.specId)
74
+ lines.push(`- Spec id: ${finding.specId}`);
75
+ if (typeof finding.noul === "number")
76
+ lines.push(`- Noul: ${finding.noul.toFixed(2)}`);
77
+ lines.push(`- Message: ${finding.message}`, "");
78
+ lines.push(...excerptForFinding(finding, input.spec));
79
+ }
80
+ lines.push("## Existing spec IDs", "", "Do not invent new BR- or UC- IDs. Use only these:", "");
81
+ if (specIds.length === 0) {
82
+ lines.push("- (none compiled)", "");
83
+ }
84
+ else {
85
+ for (const id of specIds)
86
+ lines.push(`- ${id}`);
87
+ lines.push("");
88
+ }
89
+ lines.push("## Opinionated rules", "", "- Rewrite every Outcome to what a person sees after the steps: a status or label, and whether a named control is present, absent, or disabled.", "- Tighten every rule Observable so a person or test can notice it.", "- `Choose …` is an allow path. `Look for …` is a deny path. Do not invert a use case to match a matrix cell.", "- A matrix allow cell plus a business rule that hides or disables the control is consistent. Keep those Look-for use cases.", "- Do not write matrix talk in Outcome or Entities: no `is allow`, `is deny`, no restating action cells, no `without changing the matrix cell`.", "- Name the exact Choose / Look for / Select controls. State tester preconditions.", personas
90
+ ? "- Missing persona: add `email: <role-slug>@example.test` and `password: test-only-not-production` in fixtures/personas.yaml."
91
+ : "- Do not add personas unless a finding is persona_missing.", "- You may edit every section the findings name. This is one pack pass.", "", "## Fence", "", "- Patch `requirement.md` only, then stop.", personas
92
+ ? "- At least one finding is a missing persona: you may also edit `fixtures/personas.yaml`."
93
+ : "- Do not add files except the patch to `requirement.md`.", "- Do not invent spec IDs.", "- Do not implement the product app.", "- Stop after the patch so the owner can review the diff, then Check with Jev. Do not Check yourself.", "");
94
+ return `${lines.join("\n")}\n`;
95
+ }
96
+ export function excerptForFinding(finding, spec) {
97
+ if (!spec)
98
+ return [];
99
+ const useCase = spec.useCases.find((item) => item.id === finding.specId);
100
+ if (useCase) {
101
+ const cells = spec.matrix.actions
102
+ .map((action) => `${action.id}: ${action.permissions[useCase.actor] ?? "—"}`)
103
+ .join("; ");
104
+ return [
105
+ "Current spec:",
106
+ "",
107
+ `- Actor: ${useCase.actor}`,
108
+ `- Preconditions: ${useCase.preconditions}`,
109
+ "- Steps:",
110
+ ...useCase.steps.map((step, index) => ` ${index + 1}. ${step}`),
111
+ `- Outcome: ${useCase.outcome}`,
112
+ `- Matrix for ${useCase.actor}: ${cells || "—"}`,
113
+ "",
114
+ ];
115
+ }
116
+ const rule = spec.businessRules.find((item) => item.id === finding.specId);
117
+ if (rule) {
118
+ return [
119
+ "Current spec:",
120
+ "",
121
+ `- Statement: ${rule.statement}`,
122
+ `- Observable: ${rule.observable}`,
123
+ "",
124
+ ];
125
+ }
126
+ return [];
127
+ }
@@ -0,0 +1,2 @@
1
+ import type { JevPack, SpecAst } from "./types.js";
2
+ export declare function emitJevPack(spec: SpecAst): JevPack;
@@ -0,0 +1,114 @@
1
+ import { JEV_CATALOG, SECTION_SCORE_LEVELS } from "./gates.js";
2
+ export function emitJevPack(spec) {
3
+ const questions = [];
4
+ for (const rule of spec.businessRules) {
5
+ questions.push({
6
+ id: `rule.observable.${rule.id}`,
7
+ type: "noul",
8
+ specId: rule.id,
9
+ instructions: "Is Statement observable via Observable?",
10
+ criteria: {
11
+ true: "A person or automated test could notice the Observable if the Statement holds or is violated.",
12
+ false: "The Observable is vague, missing, or not something a test could notice.",
13
+ },
14
+ state: {
15
+ id: rule.id,
16
+ title: rule.title,
17
+ statement: rule.statement,
18
+ observable: rule.observable,
19
+ },
20
+ });
21
+ }
22
+ for (const useCase of spec.useCases) {
23
+ const actorPermissions = {};
24
+ for (const action of spec.matrix.actions) {
25
+ const cell = action.permissions[useCase.actor];
26
+ if (cell)
27
+ actorPermissions[action.id] = cell;
28
+ }
29
+ questions.push({
30
+ id: `usecase.contradicts.${useCase.id}`,
31
+ type: "noul",
32
+ specId: useCase.id,
33
+ instructions: "Does this contradict the matrix for its Actor?",
34
+ criteria: {
35
+ true: "A step or outcome asks the actor to do something the Roles & Permissions matrix denies, or forbids something the matrix allows.",
36
+ false: "The use case stays inside the actor's allow/deny cells.",
37
+ },
38
+ state: {
39
+ id: useCase.id,
40
+ title: useCase.title,
41
+ actor: useCase.actor,
42
+ preconditions: useCase.preconditions,
43
+ steps: useCase.steps,
44
+ outcome: useCase.outcome,
45
+ actorPermissions,
46
+ },
47
+ });
48
+ }
49
+ questions.push(sectionScore("Business Rules", spec.businessRules.map((rule) => ({
50
+ id: rule.id,
51
+ statement: rule.statement,
52
+ observable: rule.observable,
53
+ }))), sectionScore("Use Cases", spec.useCases.map((useCase) => ({
54
+ id: useCase.id,
55
+ actor: useCase.actor,
56
+ steps: useCase.steps,
57
+ outcome: useCase.outcome,
58
+ }))), sectionScore("Roles & Permissions", {
59
+ roles: spec.matrix.roles,
60
+ actions: spec.matrix.actions.map((action) => ({
61
+ id: action.id,
62
+ permissions: action.permissions,
63
+ })),
64
+ }));
65
+ const choiceCriteria = {};
66
+ for (const rule of spec.businessRules) {
67
+ choiceCriteria[rule.id] = `Business rule: ${rule.title}`;
68
+ }
69
+ for (const useCase of spec.useCases) {
70
+ choiceCriteria[useCase.id] = `Use case: ${useCase.title}`;
71
+ }
72
+ if (Object.keys(choiceCriteria).length > 0) {
73
+ questions.push({
74
+ id: "pack.next-id",
75
+ type: "choice",
76
+ instructions: "Which ID should the Requirement Owner improve next?",
77
+ criteria: choiceCriteria,
78
+ state: {
79
+ ids: Object.keys(choiceCriteria),
80
+ titles: choiceCriteria,
81
+ },
82
+ });
83
+ }
84
+ questions.push({
85
+ id: "pack.agent-ready",
86
+ type: "noul",
87
+ instructions: "Is this pack safe to hand to a coding agent?",
88
+ criteria: {
89
+ true: "Rules are testable, use cases match the matrix, and an agent would not have to invent behavior.",
90
+ false: "An agent would have to guess, or the pack still contradicts itself.",
91
+ },
92
+ state: {
93
+ ruleIds: spec.businessRules.map((rule) => rule.id),
94
+ useCaseIds: spec.useCases.map((useCase) => useCase.id),
95
+ roles: spec.matrix.roles,
96
+ },
97
+ });
98
+ return {
99
+ requirementId: spec.requirementId,
100
+ catalog: JEV_CATALOG,
101
+ questions,
102
+ };
103
+ }
104
+ function sectionScore(section, body) {
105
+ const slug = section.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
106
+ return {
107
+ id: `section.score.${slug}`,
108
+ type: "score",
109
+ section,
110
+ instructions: `How complete is the ${section} section for a coding agent?`,
111
+ criteria: [...SECTION_SCORE_LEVELS],
112
+ state: { section, body },
113
+ };
114
+ }
package/dist/jev.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { JevAnswer, JevPack } from "./types.js";
2
+ export declare class JevUnavailableError extends Error {
3
+ readonly code = "no_api_key";
4
+ constructor(message?: string);
5
+ }
6
+ export declare class JevRequestError extends Error {
7
+ readonly code = "jev_request";
8
+ readonly status?: number;
9
+ constructor(message: string, status?: number);
10
+ }
11
+ export type JevClient = {
12
+ judge(pack: JevPack): Promise<JevAnswer[]>;
13
+ };
14
+ export declare function jevApiKey(): string | undefined;
15
+ export declare function hasJevAccess(): boolean;
16
+ export declare function resolveJevClient(): JevClient;
17
+ export declare function createUnavailableJevClient(): JevClient;
18
+ export declare function createMockJevClient(overrides?: {
19
+ noul?: Record<string, number>;
20
+ choice?: string;
21
+ score?: Record<string, number>;
22
+ }): JevClient;
23
+ export declare function createTypeSafeJevClient(apiKey: string, fetchImpl?: typeof fetch): JevClient;
package/dist/jev.js ADDED
@@ -0,0 +1,142 @@
1
+ import { JEV_ENDPOINT, JEV_MODEL } from "./gates.js";
2
+ export class JevUnavailableError extends Error {
3
+ code = "no_api_key";
4
+ constructor(message = "No TypeSafe API key. Set TYPESAFE_API_KEY.") {
5
+ super(message);
6
+ this.name = "JevUnavailableError";
7
+ }
8
+ }
9
+ export class JevRequestError extends Error {
10
+ code = "jev_request";
11
+ status;
12
+ constructor(message, status) {
13
+ super(message);
14
+ this.name = "JevRequestError";
15
+ this.status = status;
16
+ }
17
+ }
18
+ export function jevApiKey() {
19
+ const key = process.env.TYPESAFE_API_KEY;
20
+ return key?.trim() || undefined;
21
+ }
22
+ export function hasJevAccess() {
23
+ return Boolean(jevApiKey()) || process.env.REQ0_JEV === "mock";
24
+ }
25
+ export function resolveJevClient() {
26
+ if (process.env.REQ0_JEV === "mock")
27
+ return createMockJevClient();
28
+ const key = jevApiKey();
29
+ if (!key)
30
+ return createUnavailableJevClient();
31
+ return createTypeSafeJevClient(key);
32
+ }
33
+ export function createUnavailableJevClient() {
34
+ return {
35
+ async judge() {
36
+ throw new JevUnavailableError();
37
+ },
38
+ };
39
+ }
40
+ export function createMockJevClient(overrides) {
41
+ return {
42
+ async judge(pack) {
43
+ return pack.questions.map((question) => {
44
+ if (question.type === "noul") {
45
+ const noul = overrides?.noul?.[question.id] ??
46
+ noulByPrefix(overrides?.noul, question.id) ??
47
+ (question.id.startsWith("usecase.contradicts.") ? 0.05 : 0.95);
48
+ return { id: question.id, type: "noul", noul, confidence: 1 };
49
+ }
50
+ if (question.type === "choice") {
51
+ const keys = question.criteria && !Array.isArray(question.criteria) ? Object.keys(question.criteria) : [];
52
+ return {
53
+ id: question.id,
54
+ type: "choice",
55
+ choice: overrides?.choice ?? keys[0] ?? "",
56
+ confidence: 1,
57
+ };
58
+ }
59
+ const score = overrides?.score?.[question.id] ??
60
+ noulByPrefix(overrides?.score, question.id) ??
61
+ 2;
62
+ return { id: question.id, type: "score", score, confidence: 1 };
63
+ });
64
+ },
65
+ };
66
+ }
67
+ function noulByPrefix(map, id) {
68
+ if (!map)
69
+ return undefined;
70
+ if (id in map)
71
+ return map[id];
72
+ const hit = Object.keys(map).find((key) => id.startsWith(key));
73
+ return hit ? map[hit] : undefined;
74
+ }
75
+ export function createTypeSafeJevClient(apiKey, fetchImpl = fetch) {
76
+ return {
77
+ async judge(pack) {
78
+ const questions = {};
79
+ const combinedState = {};
80
+ for (const question of pack.questions) {
81
+ questions[question.id] = {
82
+ type: question.type,
83
+ instructions: question.instructions,
84
+ ...(question.criteria !== undefined ? { criteria: question.criteria } : {}),
85
+ };
86
+ combinedState[question.id] = question.state;
87
+ }
88
+ const response = await fetchImpl(JEV_ENDPOINT, {
89
+ method: "POST",
90
+ headers: {
91
+ Authorization: `Bearer ${apiKey}`,
92
+ "Content-Type": "application/json",
93
+ },
94
+ body: JSON.stringify({
95
+ model: JEV_MODEL,
96
+ state: { catalog: pack.catalog, requirementId: pack.requirementId, items: combinedState },
97
+ questions,
98
+ }),
99
+ });
100
+ const text = await response.text();
101
+ let raw = {};
102
+ if (text.trim()) {
103
+ try {
104
+ raw = JSON.parse(text);
105
+ }
106
+ catch {
107
+ throw new JevRequestError(`TypeSafe System One returned non-JSON (HTTP ${response.status}).`, response.status);
108
+ }
109
+ }
110
+ if (!response.ok) {
111
+ const nested = raw.error;
112
+ const message = typeof nested === "string"
113
+ ? nested
114
+ : nested && typeof nested === "object" && typeof nested.message === "string"
115
+ ? nested.message
116
+ : `TypeSafe System One returned HTTP ${response.status}.`;
117
+ throw new JevRequestError(message, response.status);
118
+ }
119
+ const answers = extractAnswers(raw);
120
+ return pack.questions.map((question) => normalizeAnswer(question.id, question.type, answers[question.id]));
121
+ },
122
+ };
123
+ }
124
+ function extractAnswers(body) {
125
+ const nested = body.answers;
126
+ if (nested && typeof nested === "object" && !Array.isArray(nested)) {
127
+ return nested;
128
+ }
129
+ const { model: _model, usage: _usage, ...rest } = body;
130
+ return rest;
131
+ }
132
+ function normalizeAnswer(id, type, raw) {
133
+ const value = raw && typeof raw === "object" ? raw : {};
134
+ return {
135
+ id,
136
+ type,
137
+ noul: typeof value.noul === "number" ? value.noul : undefined,
138
+ choice: typeof value.choice === "string" ? value.choice : undefined,
139
+ score: typeof value.score === "number" ? value.score : undefined,
140
+ confidence: typeof value.confidence === "number" ? value.confidence : undefined,
141
+ };
142
+ }