@richjava/req0 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,18 +10,14 @@ Req0 allows you to keep structured requirement packs in your product git repo. T
10
10
 
11
11
  A local **cockpit** runs that loop: a coding agent (Cursor, Copilot, Claude, or Codex) interviews you, drafts frozen-grammar `requirement.md`, and later implements — only after you answer, a compiler checks the grammar, and **Jev** (TypeSafe System One) judges Ready. The browser then proves the app against the spec. If proof fails, **Fix from proof** sends that report back so the same agent can repair the implementation — not the spec.
12
12
 
13
+ Implement is optional. On first run pick **I’ll write the code**, or set `"implement": false` in `req0.json` at the product repo root. Req0 then stays on the pack and QA; you implement your own way.
14
+
13
15
  Req0 is a CLI plus a thin HTML cockpit, free and open source. It is not a hosted SaaS.
14
16
 
15
17
  ## Install
16
18
 
17
19
  Node.js **22.15** or newer.
18
20
 
19
- ```bash
20
- npm install -g @richjava/req0
21
- ```
22
-
23
- Or run without a global install:
24
-
25
21
  ```bash
26
22
  npx @richjava/req0 start
27
23
  ```
@@ -34,7 +30,7 @@ From the **product** repo (the app you are specifying), not from inside this pac
34
30
 
35
31
  ```bash
36
32
  cd /path/to/your-product
37
- req0 start
33
+ npx @richjava/req0 start
38
34
  ```
39
35
 
40
36
  The cockpit opens at `http://127.0.0.1:4370` (or the next free port). From the requirement list, create a pack with a kebab-case id such as `001`. That writes `docs/requirements/<id>/`. On **Define**, describe the requirement and **Start** — the recorded coding agent interviews you (you can skip questions) and drafts frozen-grammar `requirement.md`. Optional PNG/JPG/WebP go in that pack’s `context/` folder. `req0 create` on the CLI still writes the starter template only.
@@ -69,7 +65,11 @@ docs/requirements/invoice-approval/
69
65
  derived/ # generated; do not hand-edit
70
66
  ```
71
67
 
72
- First run in an empty product repo asks how code should be written (**I’ll write the code**, **Cursor**, **Copilot**, **Claude**, or **Codex**) and, if an agent will implement, which stack. That writes `req0.json`. Set `"implement": false` when Req0 should not own Implement.
68
+ First run asks how code should be written (**I’ll write the code**, **Cursor**, **Copilot**, **Claude**, or **Codex**) and, if an agent will implement, which stack. That writes `req0.json` at the product repo root. Edit that file later: `"implement": false` turns Implement off (same as **I’ll write the code**); `"adapter": "cursor"` (or `copilot`, `claude`, `codex`) records which CLI to launch.
69
+
70
+ House standards (optional freeform markdown) live at `docs/requirement-standards/pack.md` and `document.md`. Authoring, Improve, and Implement **Read** those files and follow them in substance while still emitting frozen `requirement.md` grammar. Point `req0.json` at other paths with `"standards": { "pack": "…", "document": "…" }`. Missing files fall back to the copies shipped with the package. Jev scores the pack against that house style as Ready **nits** only — they do not block Implement.
71
+
72
+ The as-built schema map is `docs/system.md` at the product root (override with `"system"` in `req0.json`). Every Implement **plans first**: the agent Reads that map, writes `derived/implement-plan.md`, and asks if a schema change has implications. Continue / Skip answers land under Decisions. Coding starts only after that round closes. Each accepted plan is copied to `derived/plans/<timestamp>.md`. After Build succeeded, the coding agent updates `docs/system.md`. Missing map is fine on the first pass. Off when Implement is off. Prove still checks the app against the spec, not the plan.
73
73
 
74
74
  Copy names-only env vars into `.env` as needed. Do not put secrets in `.env.example`.
75
75
 
@@ -92,7 +92,7 @@ Install the agent CLI you recorded: [Cursor](https://cursor.com) agent, [GitHub
92
92
 
93
93
  ## Grammar (short)
94
94
 
95
- `requirement.md` needs one `#` title and these `##` sections: **Business Rules**, **Use Cases**, **Roles & Permissions**. Rules use `Id: BR-001` with Statement and Observable. Use cases use `Id: UC-001` with Actor, numbered Steps, and Outcome. The roles table cells are only `allow` or `deny`. Full rules: [docs/grammar.md](https://github.com/richjava/req0/blob/main/docs/grammar.md).
95
+ `requirement.md` needs one `#` title and these `##` sections: **Business Rules**, **Use Cases**, **Roles & Permissions**. Optional headings include Overview, Definitions, Data Definition, Verification Scenarios, Related Requirements, and Implementation Notes. Rules use `Id: BR-001` with Statement and Observable. Use cases use `Id: UC-001` with Actor, numbered Steps, and Outcome. The roles table cells are only `allow` or `deny`. Full rules: [docs/grammar.md](https://github.com/richjava/req0/blob/main/docs/grammar.md).
96
96
 
97
97
  ## Docs
98
98
 
package/cockpit/app.js CHANGED
@@ -498,6 +498,10 @@ function openQuestions() {
498
498
  return round;
499
499
  }
500
500
 
501
+ function isImplementChannel(channel) {
502
+ return channel === "implement" || channel === "plan";
503
+ }
504
+
501
505
  function questionsContinueEnabled(round = openQuestions()) {
502
506
  if (!round) return false;
503
507
  return round.questions.every((question) => {
@@ -524,8 +528,8 @@ function syncQuestionDrafts(round) {
524
528
  function maybeOpenQuestions(round) {
525
529
  const key = round ? `${round.channel}|${round.at}` : "";
526
530
  if (key && key !== lastQuestionsKey) {
527
- currentView = round.channel === "implement" ? "implement" : "define";
528
- if (round.channel === "implement") implementTab = "questions";
531
+ currentView = isImplementChannel(round.channel) ? "implement" : "define";
532
+ if (isImplementChannel(round.channel)) implementTab = "questions";
529
533
  else defineTab = "questions";
530
534
  }
531
535
  lastQuestionsKey = key;
@@ -790,7 +794,7 @@ function renderQuestions() {
790
794
  hidden: !askingDefine,
791
795
  });
792
796
  if (els.implementQuestions) {
793
- if (round?.channel === "implement") fillQuestionPanel(els.implementQuestions, round);
797
+ if (isImplementChannel(round?.channel)) fillQuestionPanel(els.implementQuestions, round);
794
798
  else {
795
799
  els.implementQuestions.innerHTML = "";
796
800
  delete els.implementQuestions.dataset.sig;
@@ -849,7 +853,7 @@ function renderDefineLayout() {
849
853
  }
850
854
 
851
855
  function renderImplementLayout() {
852
- const asking = openQuestions()?.channel === "implement";
856
+ const asking = isImplementChannel(openQuestions()?.channel);
853
857
  const hasActivity = implementLines.length > 0;
854
858
  const showTabs = Boolean(asking && hasActivity);
855
859
  if (!asking) implementTab = "questions";
@@ -1824,7 +1828,7 @@ function viewForAction(id) {
1824
1828
  return "define";
1825
1829
  }
1826
1830
  if (id === "answer-questions" || id === "discard-questions" || id === "skip-all-questions") {
1827
- return openQuestions()?.channel === "implement" ? "implement" : "define";
1831
+ return isImplementChannel(openQuestions()?.channel) ? "implement" : "define";
1828
1832
  }
1829
1833
  if (id === "implement" || id === "stop-implement" || id === "ignore-build" || id === "fix-from-proof") {
1830
1834
  return state?.health?.build?.owned === false ? null : "implement";
@@ -1944,7 +1948,7 @@ async function runStageAction(id) {
1944
1948
  return;
1945
1949
  }
1946
1950
  if (id === "stop-implement") {
1947
- if (openQuestions()?.channel === "implement") {
1951
+ if (isImplementChannel(openQuestions()?.channel)) {
1948
1952
  const confirmed = await askDiscardQuestions();
1949
1953
  if (!confirmed) return;
1950
1954
  }
@@ -304,10 +304,11 @@ body {
304
304
  #all-requirements {
305
305
  display: inline-flex;
306
306
  align-items: center;
307
+ justify-content: flex-start;
307
308
  gap: 6px;
308
309
  flex-shrink: 0;
309
310
  white-space: nowrap;
310
- align-self: center;
311
+ align-self: flex-start;
311
312
  }
312
313
 
313
314
  #all-requirements svg {
@@ -1797,6 +1798,10 @@ body {
1797
1798
  align-items: stretch;
1798
1799
  }
1799
1800
 
1801
+ #all-requirements {
1802
+ align-self: flex-start;
1803
+ }
1804
+
1800
1805
  .pack-row {
1801
1806
  flex-direction: column;
1802
1807
  align-items: stretch;
@@ -10,7 +10,7 @@ export declare class AgentAnswersError extends Error {
10
10
  readonly code = "agent_answers";
11
11
  constructor(message: string);
12
12
  }
13
- export type AgentQuestionsChannel = "author" | "improve" | "implement";
13
+ export type AgentQuestionsChannel = "author" | "improve" | "implement" | "plan";
14
14
  export type AgentQuestionKind = "text" | "choice" | "artifact";
15
15
  export declare const SKIP_ANSWER = "__skip__";
16
16
  export declare const AUTHOR_ARTIFACT_ACCEPT: readonly ["image/png", "image/jpeg", "image/webp"];
@@ -56,7 +56,7 @@ export function questionsBriefSection(options = {}) {
56
56
  }, null, 2),
57
57
  "~~~~",
58
58
  "",
59
- "Set `channel` to `author` when filling a new pack from a description, `improve` when patching after Ready, or `implement` when writing product code.",
59
+ "Set `channel` to `author` when filling a new pack from a description, `improve` when patching after Ready, `plan` when proposing a schema delta before coding, or `implement` when writing product code.",
60
60
  "",
61
61
  ].join("\n");
62
62
  }
@@ -66,8 +66,12 @@ export function parseAgentQuestions(raw) {
66
66
  const body = raw;
67
67
  if (body.version !== 1)
68
68
  return null;
69
- if (body.channel !== "author" && body.channel !== "improve" && body.channel !== "implement")
69
+ if (body.channel !== "author" &&
70
+ body.channel !== "improve" &&
71
+ body.channel !== "implement" &&
72
+ body.channel !== "plan") {
70
73
  return null;
74
+ }
71
75
  if (body.status !== "open" && body.status !== "answered")
72
76
  return null;
73
77
  if (typeof body.at !== "string" || !body.at.trim())
package/dist/author.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { AdapterId, Finding, Health, ProductRepo, ReadyMeter, SpecAst } from "./types.js";
1
+ import { type LoadedStandards } from "./standards.js";
2
+ import { type AdapterId, type Finding, type Health, type ProductRepo, type ReadyMeter, type SpecAst } from "./types.js";
2
3
  export declare const AUTHOR_MAX_ROUNDS = 8;
3
4
  export declare const AUTHOR_BRIEF_FILE = "author-brief.md";
4
5
  export declare const AUTHOR_RUN_FILE = "author-run.json";
@@ -87,6 +88,7 @@ export declare function emitAuthorBrief(input: {
87
88
  instruction: string;
88
89
  };
89
90
  contextFiles: string[];
91
+ standards?: LoadedStandards | null;
90
92
  }): string;
91
93
  export declare function authorPrompt(briefPath: string): string;
92
94
  export declare function sanitizeArtifactFilename(filename: string, mime: string): string;
package/dist/author.js CHANGED
@@ -3,7 +3,9 @@ import path from "node:path";
3
3
  import { excerptForFinding } from "./improve.js";
4
4
  import { NOUL_PASS } from "./gates.js";
5
5
  import { questionsBriefSection } from "./agent-questions.js";
6
+ import { standardsBriefSection } from "./standards.js";
6
7
  import { stackInstruction } from "./stack.js";
8
+ import { OPTIONAL_H2 } from "./types.js";
7
9
  export const AUTHOR_MAX_ROUNDS = 8;
8
10
  export const AUTHOR_BRIEF_FILE = "author-brief.md";
9
11
  export const AUTHOR_RUN_FILE = "author-run.json";
@@ -256,6 +258,7 @@ export function emitAuthorBrief(input) {
256
258
  "",
257
259
  `- Quality bar: ${target}`,
258
260
  "- Align substance to a high-quality requirement (roles, permissions, business rules, use cases, observables, deny paths) while writing **frozen grammar** so the compiler can parse it.",
261
+ "- Read the house standards. Satisfy them in substance. Do not copy those files into the pack.",
259
262
  "",
260
263
  "## Owner description",
261
264
  "",
@@ -266,11 +269,11 @@ export function emitAuthorBrief(input) {
266
269
  "Replace the starter template. Allowed `##` headings only:",
267
270
  "",
268
271
  "- Required: `Business Rules`, `Use Cases`, `Roles & Permissions`",
269
- "- Optional: `Overview`, `Out of scope`, `Open questions`, `Entities`, `UI notes`",
272
+ `- Optional: ${OPTIONAL_H2.map((name) => `\`${name}\``).join(", ")}`,
270
273
  "- Put the owner's description in `## Overview`. Do not emit `## Description` or template guidance labels.",
271
274
  "- Each business rule: `Id: BR-NNN`, Statement, Observable (what a person or test notices).",
272
275
  "- Each use case: `Id: UC-NNN`, Actor (a matrix column), Preconditions, numbered Steps with `Open` / `Choose` / `Look for` / `Select`, Outcome of what a person sees.",
273
- "- `Choose` is allow. `Look for` is deny. Matrix cells are only `allow` or `deny`.",
276
+ "- `Choose` is allow. `Look for` is deny. Matrix cells are only `allow` or `deny`. Do not emit `REQ_…` folders, `BR_016.1`, Yes/No/Conditional cells, or an `Artifacts/` heading.",
274
277
  "- You may assign the **first** BR- and UC- IDs in this pack. Do not reuse sibling IDs. Do not invent product stack, auth, storage, copy, or screens the owner did not confirm or upload.",
275
278
  "- Edit `fixtures/personas.yaml` only when a role is confirmed (email `role-slug@example.test`, password `test-only-not-production`).",
276
279
  "",
@@ -344,13 +347,14 @@ export function emitAuthorBrief(input) {
344
347
  lines.push(`- context/${file}`);
345
348
  lines.push("");
346
349
  }
347
- lines.push("## Opinionated rules", "", "- Prefer asking over assuming. One round, at most four questions, then stop if you wrote questions.", "- Recommended choice first. Set `allowCustom` when none of the options may fit.", "- If the owner skipped, leave that area incomplete or ask a *different* question. Never fill skipped gaps with guesses.", "- Observables and Outcomes are what a person sees: a status or label, and whether a named control is present, absent, or disabled.", "- Do not write matrix talk in Outcome (`is allow`, `is deny`).", "- Conditional template topics (definitions, data, states, empty/error paths) belong in Entities, rules, and use cases when they matter.", "", questionsBriefSection({ channel: "author", inventIds: true }).trimEnd(), "", "## Fence", "", "- Patch `requirement.md` (and personas.yaml only when a role is confirmed).", "- Do not implement the product app. Do not Check with Jev yourself; the host will.", "- If you wrote `derived/agent-questions.json`, stop without patching in that same turn.", "");
350
+ lines.push("## Opinionated rules", "", "- Prefer asking over assuming. One round, at most four questions, then stop if you wrote questions.", "- Recommended choice first. Set `allowCustom` when none of the options may fit.", "- If the owner skipped, leave that area incomplete or ask a *different* question. Never fill skipped gaps with guesses.", "- Observables and Outcomes are what a person sees: a status or label, and whether a named control is present, absent, or disabled.", "- Do not write matrix talk in Outcome (`is allow`, `is deny`).", "- Conditional topics (definitions, data, verification, related packs, implementation notes) belong in the matching optional headings, or in Entities, rules, and use cases when they matter.", "- Prefer `context/{UC-id}__{purpose}.png` and mention the file from that use case. Screenshots illustrate stated behaviour; they do not replace it.", "", ...standardsBriefSection(input.standards), questionsBriefSection({ channel: "author", inventIds: true }).trimEnd(), "", "## Fence", "", "- Patch `requirement.md` (and personas.yaml only when a role is confirmed).", "- Do not implement the product app. Do not Check with Jev yourself; the host will.", "- If you wrote `derived/agent-questions.json`, stop without patching in that same turn.", "");
348
351
  return `${lines.join("\n")}\n`;
349
352
  }
350
353
  export function authorPrompt(briefPath) {
351
354
  return [
352
355
  "Author this requirement pack from the brief.",
353
356
  `Read ${briefPath} and requirement.md.`,
357
+ "Read the house pack and document standards listed in the brief. Satisfy them in substance; emit frozen grammar.",
354
358
  "Write frozen-grammar requirement.md. You may assign the first BR- and UC- IDs. Do not copy sibling IDs.",
355
359
  "If a required decision is missing, write derived/agent-questions.json with channel author and stop. Do not guess. Do not patch requirement.md in that same turn.",
356
360
  "Read files in context/ including images. Do not invent UI the owner did not confirm or upload.",
package/dist/cli.js CHANGED
@@ -96,11 +96,13 @@ async function main(command, rest) {
96
96
  let result = launched.result;
97
97
  let message = launched.message;
98
98
  const used = adapter ?? result.health.build.adapter ?? "cursor";
99
- if (launched.launch?.finished) {
99
+ let current = launched.launch;
100
+ while (current?.finished) {
100
101
  console.log(`Build running — ${message}`);
101
- const done = await finishImplement(pack, launched.launch, used);
102
+ const done = await finishImplement(pack, current, used);
102
103
  result = done.result;
103
104
  message = done.message;
105
+ current = done.launch;
104
106
  }
105
107
  console.log(`Build ${result.health.build.state} — ${message}`);
106
108
  console.log(adapterInstructions(used, fromProof ? pack.fixFromProofBrief : pack.implementBrief));
@@ -1,9 +1,13 @@
1
1
  import type { PersonasResult } from "./personas.js";
2
+ import { type LoadedStandards } from "./standards.js";
3
+ import { type LoadedSystemMap } from "./system-map.js";
2
4
  import type { AdapterId, ProductRepo, SpecAst, StackChoice } from "./types.js";
3
5
  export declare function emitImplementBrief(input: {
4
6
  spec: SpecAst;
5
7
  repo: ProductRepo;
6
8
  adapter: AdapterId;
7
9
  personas?: PersonasResult;
10
+ standards?: LoadedStandards | null;
11
+ system?: LoadedSystemMap | null;
8
12
  }): string;
9
13
  export declare function productReadmeTemplate(spec: SpecAst, stack: StackChoice): string;
@@ -1,4 +1,6 @@
1
1
  import { questionsBriefSection } from "./agent-questions.js";
2
+ import { standardsBriefSection } from "./standards.js";
3
+ import { systemMapBriefSection } from "./system-map.js";
2
4
  import { DEFAULT_STACK, isAmplifyStack, stackInstruction } from "./stack.js";
3
5
  export function emitImplementBrief(input) {
4
6
  const { spec, repo, adapter, personas } = input;
@@ -6,6 +8,8 @@ export function emitImplementBrief(input) {
6
8
  `# Implement: ${spec.title}`,
7
9
  "",
8
10
  "Portable coding-agent brief. Read this file, then the compiled `derived/spec.json`. Do not invent rule, use-case, or role IDs.",
11
+ "Read the house pack and document standards listed below. Satisfy them in substance. The spec already uses frozen grammar; do not rename IDs or headings.",
12
+ "Read the accepted `derived/implement-plan.md` and the product `docs/system.md` (as-built map). After this pass lands, update the system map. Do not treat the map as the spec.",
9
13
  "",
10
14
  "## Stack",
11
15
  "",
@@ -61,8 +65,21 @@ export function emitImplementBrief(input) {
61
65
  if (spec.optional["Open questions"]?.trim()) {
62
66
  lines.push("## Open questions", "", spec.optional["Open questions"].trim(), "");
63
67
  }
68
+ for (const name of [
69
+ "Definitions",
70
+ "Data Definition",
71
+ "Verification Scenarios",
72
+ "Related Requirements",
73
+ "Implementation Notes",
74
+ ]) {
75
+ if (spec.optional[name]?.trim()) {
76
+ lines.push(`## ${name}`, "", spec.optional[name].trim(), "");
77
+ }
78
+ }
79
+ lines.push(...systemMapBriefSection(input.system));
80
+ lines.push(...standardsBriefSection(input.standards));
64
81
  lines.push("## Product README", "", "Write `README.md` at the product repo root so a stranger can run the app. If a README already exists, update the setup section. Use this requirement's title and the pack paths below. Do not invent a product name.", "", "~~~~markdown", productReadmeTemplate(spec, repo.stack), "~~~~", "");
65
- lines.push("## Pack files", "", "- Seed the app from existing `fixtures/personas.yaml`. Do not add roles. Do not invent emails.", "- `fixtures/runtime.yaml` may be a stub. Set `baseUrl`, `startCommand`, and `resetCommand` to the app you started. Keep login selectors unless you change `/login` to match — then change both.", "- Write or update the product-repo `.env.example` with variable names only. No real keys.", "- Write `README.md` at the product repo root using the Product README section. Use this requirement's title and pack paths. Do not invent a product name.", "- The seed/reset script command must match `runtime.yaml` `resetCommand`.", "- First-party `/login` must match those selectors.", "", questionsBriefSection().trimEnd(), "", "## Security baseline", "", "- No production credentials in the spec or this brief.", "- Secrets via environment variables.", "- Personas are test-only.", "", "## Done means", "", isAmplifyStack(repo.stack)
82
+ lines.push("## Pack files", "", "- Seed the app from existing `fixtures/personas.yaml`. Do not add roles. Do not invent emails.", "- `fixtures/runtime.yaml` may be a stub. Set `baseUrl`, `startCommand`, and `resetCommand` to the app you started. Keep login selectors unless you change `/login` to match — then change both.", "- Write or update the product-repo `.env.example` with variable names only. No real keys.", "- Write `README.md` at the product repo root using the Product README section. Use this requirement's title and pack paths. Do not invent a product name.", "- The seed/reset script command must match `runtime.yaml` `resetCommand`.", "- First-party `/login` must match those selectors.", "- Keep `context/` screenshots named `{UC-id}__{purpose}.ext` and referenced from the spec. Do not treat a screenshot as the spec.", "", questionsBriefSection().trimEnd(), "", "## Security baseline", "", "- No production credentials in the spec or this brief.", "- Secrets via environment variables.", "- Personas are test-only.", "", "## Done means", "", isAmplifyStack(repo.stack)
66
83
  ? "The app exists in the recorded stack. AWS identity was available (profile or inherited keys). `npx ampx sandbox --once` has been run. `amplify_outputs.json` has real Cognito ids, not `REPLACE_VIA_SANDBOX`. Personas are seeded in Cognito. `fixtures/runtime.yaml` matches that app. Product `.env.example` has names only. Product `README.md` has setup for this stack."
67
84
  : "The app exists in the recorded stack. Personas are seeded. `fixtures/runtime.yaml` matches that app. Product `.env.example` has names only. Product `README.md` has setup for this stack.", "A coding-agent run finishing is **Build Succeeded**, not “the app boots.” Boot and login are Proof (Milestone 4).", "");
68
85
  return `${lines.join("\n")}\n`;
@@ -0,0 +1,41 @@
1
+ import { type AgentQuestionsRound } from "./agent-questions.js";
2
+ import { type LoadedStandards } from "./standards.js";
3
+ import { type LoadedSystemMap } from "./system-map.js";
4
+ import type { SpecAst } from "./types.js";
5
+ export declare const IMPLEMENT_PLAN_FILE = "implement-plan.md";
6
+ export declare const IMPLEMENT_PLAN_STATE_FILE = "implement-plan.json";
7
+ export declare const IMPLEMENT_PLAN_BRIEF_FILE = "implement-plan-brief.md";
8
+ export declare const IMPLEMENT_PLANS_DIR = "plans";
9
+ export type ImplementPlanStatus = "running" | "waiting_questions" | "accepted" | "failed";
10
+ export type ImplementPlanState = {
11
+ version: 1;
12
+ specHash: string;
13
+ status: ImplementPlanStatus;
14
+ at: string;
15
+ snapshot?: string;
16
+ };
17
+ export type ImplementPlanPaths = {
18
+ derived: string;
19
+ implementPlan: string;
20
+ implementPlanState: string;
21
+ implementPlanBrief: string;
22
+ implementPlans: string;
23
+ };
24
+ export declare function parseImplementPlanState(raw: unknown): ImplementPlanState | null;
25
+ export declare function readImplementPlanState(paths: ImplementPlanPaths): Promise<ImplementPlanState | null>;
26
+ export declare function writeImplementPlanState(paths: ImplementPlanPaths, state: ImplementPlanState): Promise<void>;
27
+ export declare function readImplementPlanMarkdown(paths: ImplementPlanPaths): Promise<string>;
28
+ export declare function planIsStale(state: ImplementPlanState | null, specHash: string): boolean;
29
+ export declare function snapshotPlanFilename(at: Date): string;
30
+ export declare function snapshotAcceptedPlan(paths: ImplementPlanPaths, at?: Date): Promise<string>;
31
+ export declare function formatPlanDecisionsRound(round: AgentQuestionsRound): string;
32
+ export declare function appendDecisionsSection(markdown: string, block: string): string;
33
+ export declare function appendPlanDecisions(paths: ImplementPlanPaths, round: AgentQuestionsRound): Promise<void>;
34
+ export declare const MANUAL_STUB_PLAN = "# Implement plan\n\n## Intent\n\nManual adapter: the owner implements from the coding brief.\n\n## Schema delta\n\nNone unless the owner changes the system map.\n\n## Implications\n\nNone recorded.\n\n## Decisions\n\nNone. Manual adapter does not interview.\n\n## Traceability\n\nSee the named BR- and UC- IDs in `derived/implement-brief.md`.\n\n## Approach\n\nFollow the implement brief. Update `docs/system.md` after the change lands.\n";
35
+ export declare function emitImplementPlanBrief(input: {
36
+ spec: SpecAst;
37
+ system: LoadedSystemMap;
38
+ standards?: LoadedStandards | null;
39
+ fromProof?: boolean;
40
+ }): string;
41
+ export declare function implementPlanPrompt(briefPath: string): string;
@@ -0,0 +1,214 @@
1
+ import { access, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { questionsBriefSection } from "./agent-questions.js";
4
+ import { standardsBriefSection } from "./standards.js";
5
+ import { systemMapBriefSection } from "./system-map.js";
6
+ export const IMPLEMENT_PLAN_FILE = "implement-plan.md";
7
+ export const IMPLEMENT_PLAN_STATE_FILE = "implement-plan.json";
8
+ export const IMPLEMENT_PLAN_BRIEF_FILE = "implement-plan-brief.md";
9
+ export const IMPLEMENT_PLANS_DIR = "plans";
10
+ export function parseImplementPlanState(raw) {
11
+ if (!raw || typeof raw !== "object")
12
+ return null;
13
+ const body = raw;
14
+ if (body.version !== 1)
15
+ return null;
16
+ if (typeof body.specHash !== "string")
17
+ return null;
18
+ if (body.status !== "running" &&
19
+ body.status !== "waiting_questions" &&
20
+ body.status !== "accepted" &&
21
+ body.status !== "failed") {
22
+ return null;
23
+ }
24
+ if (typeof body.at !== "string" || !body.at.trim())
25
+ return null;
26
+ const snapshot = typeof body.snapshot === "string" && body.snapshot.trim() ? body.snapshot : undefined;
27
+ return {
28
+ version: 1,
29
+ specHash: body.specHash,
30
+ status: body.status,
31
+ at: body.at,
32
+ ...(snapshot ? { snapshot } : {}),
33
+ };
34
+ }
35
+ export async function readImplementPlanState(paths) {
36
+ try {
37
+ return parseImplementPlanState(JSON.parse(await readFile(paths.implementPlanState, "utf8")));
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ export async function writeImplementPlanState(paths, state) {
44
+ await mkdir(paths.derived, { recursive: true });
45
+ await writeFile(paths.implementPlanState, `${JSON.stringify(state, null, 2)}\n`, "utf8");
46
+ }
47
+ export async function readImplementPlanMarkdown(paths) {
48
+ try {
49
+ return await readFile(paths.implementPlan, "utf8");
50
+ }
51
+ catch {
52
+ return "";
53
+ }
54
+ }
55
+ export function planIsStale(state, specHash) {
56
+ if (!state)
57
+ return true;
58
+ if (state.status === "failed")
59
+ return true;
60
+ return state.specHash !== specHash;
61
+ }
62
+ export function snapshotPlanFilename(at) {
63
+ return `${at.toISOString().replaceAll(":", "")}.md`;
64
+ }
65
+ export async function snapshotAcceptedPlan(paths, at = new Date()) {
66
+ const markdown = await readImplementPlanMarkdown(paths);
67
+ await mkdir(paths.implementPlans, { recursive: true });
68
+ let name = snapshotPlanFilename(at);
69
+ let dest = path.join(paths.implementPlans, name);
70
+ let n = 2;
71
+ while (await fileExists(dest)) {
72
+ name = snapshotPlanFilename(at).replace(/\.md$/, `-${n}.md`);
73
+ dest = path.join(paths.implementPlans, name);
74
+ n += 1;
75
+ }
76
+ await writeFile(dest, markdown, "utf8");
77
+ return `derived/${IMPLEMENT_PLANS_DIR}/${name}`;
78
+ }
79
+ async function fileExists(file) {
80
+ try {
81
+ await access(file);
82
+ return true;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ export function formatPlanDecisionsRound(round) {
89
+ const lines = [`### Round ${round.at}`, ""];
90
+ for (const question of round.questions) {
91
+ lines.push(`- \`${question.id}\`: ${question.prompt}`);
92
+ if (question.kind === "choice" && question.options?.length) {
93
+ const labels = question.options.map((option, index) => index === 0 ? `${option.label} (recommended)` : option.label);
94
+ lines.push(` - Options: ${labels.join("; ")}`);
95
+ }
96
+ if (question.answer?.skipped) {
97
+ lines.push(" - Answer: skipped. The agent must decide and record that decision.");
98
+ }
99
+ else if (question.answer?.optionId) {
100
+ const option = question.options?.find((item) => item.id === question.answer?.optionId);
101
+ lines.push(` - Answer: ${option?.label ?? question.answer.optionId}`);
102
+ }
103
+ else if (question.answer?.text?.trim()) {
104
+ lines.push(` - Answer: ${question.answer.text.trim()}`);
105
+ }
106
+ else if (question.answer?.artifact) {
107
+ lines.push(` - Answer: uploaded context/${question.answer.artifact}`);
108
+ }
109
+ else {
110
+ lines.push(" - Answer: (none)");
111
+ }
112
+ }
113
+ lines.push("");
114
+ return lines.join("\n");
115
+ }
116
+ export function appendDecisionsSection(markdown, block) {
117
+ const trimmed = markdown.trimEnd();
118
+ const heading = "## Decisions";
119
+ const idx = trimmed.search(/^## Decisions\s*$/m);
120
+ if (idx < 0) {
121
+ return `${trimmed}\n\n${heading}\n\n${block.trimEnd()}\n`;
122
+ }
123
+ const after = trimmed.slice(idx + heading.length).replace(/^\s*/, "");
124
+ const next = after.search(/^## /m);
125
+ const beforeHeading = trimmed.slice(0, idx).trimEnd();
126
+ const existing = (next < 0 ? after : after.slice(0, next)).trimEnd();
127
+ const rest = next < 0 ? "" : `\n\n${after.slice(next).trimStart()}`;
128
+ const body = existing ? `${existing}\n\n${block.trimEnd()}` : block.trimEnd();
129
+ return `${beforeHeading}\n\n${heading}\n\n${body}${rest}\n`;
130
+ }
131
+ export async function appendPlanDecisions(paths, round) {
132
+ const current = await readImplementPlanMarkdown(paths);
133
+ const next = appendDecisionsSection(current || "# Implement plan\n", formatPlanDecisionsRound(round));
134
+ await mkdir(paths.derived, { recursive: true });
135
+ await writeFile(paths.implementPlan, next, "utf8");
136
+ }
137
+ export const MANUAL_STUB_PLAN = `# Implement plan
138
+
139
+ ## Intent
140
+
141
+ Manual adapter: the owner implements from the coding brief.
142
+
143
+ ## Schema delta
144
+
145
+ None unless the owner changes the system map.
146
+
147
+ ## Implications
148
+
149
+ None recorded.
150
+
151
+ ## Decisions
152
+
153
+ None. Manual adapter does not interview.
154
+
155
+ ## Traceability
156
+
157
+ See the named BR- and UC- IDs in \`derived/implement-brief.md\`.
158
+
159
+ ## Approach
160
+
161
+ Follow the implement brief. Update \`docs/system.md\` after the change lands.
162
+ `;
163
+ export function emitImplementPlanBrief(input) {
164
+ const { spec, system } = input;
165
+ const lines = [
166
+ `# Implement plan: ${spec.title}`,
167
+ "",
168
+ "Write a plan for this Implement pass. Do not write product code. Do not edit `requirement.md`.",
169
+ "`requirement.md` is the spec. The system map is as-built. The plan is the proposed delta for this pass.",
170
+ "",
171
+ ...systemMapBriefSection(system),
172
+ ...standardsBriefSection(input.standards),
173
+ "## Pack",
174
+ "",
175
+ "- Read `derived/implement-brief.md` and `derived/spec.json`.",
176
+ "- Read `requirement.md`.",
177
+ input.fromProof
178
+ ? "- This pass is Fix from proof. Also read `derived/proof-report.md`. Schema delta may be none."
179
+ : "- Propose how this pack lands in the current system.",
180
+ "",
181
+ "## Write `derived/implement-plan.md`",
182
+ "",
183
+ "Use these headings:",
184
+ "",
185
+ "- Intent",
186
+ "- Schema delta (none / add / change). Optional mermaid is illustration only.",
187
+ "- Implications",
188
+ "- Decisions (do not delete the host Q&A log under this heading)",
189
+ "- Traceability (which BR- and UC- IDs this pass covers)",
190
+ "- Approach",
191
+ "",
192
+ "If adding or changing entities or relationships has implications the owner should decide, write `derived/agent-questions.json` with `channel: \"plan\"` and **stop**. At most four questions. Recommended choice first. Set `allowCustom` when they may type something else.",
193
+ "The owner may skip. Skipped is not an answer: decide and record that decision under Decisions. Do not invent BR- or UC- IDs.",
194
+ "If no decision is required, write the plan and stop with no questions file.",
195
+ "",
196
+ questionsBriefSection({ channel: "plan" }).trimEnd(),
197
+ "",
198
+ "## Fence",
199
+ "",
200
+ "- Patch `derived/implement-plan.md` (and questions if needed), then stop.",
201
+ "- Do not implement the product app. Do not Check with Jev. Do not edit `requirement.md`.",
202
+ "- If you wrote questions, stop without writing product code in that same turn.",
203
+ "",
204
+ ];
205
+ return `${lines.join("\n")}\n`;
206
+ }
207
+ export function implementPlanPrompt(briefPath) {
208
+ return [
209
+ "Plan this Implement pass from the brief.",
210
+ `Read ${briefPath}, docs/system.md if it exists, derived/implement-brief.md, derived/spec.json, and requirement.md.`,
211
+ "Write derived/implement-plan.md. Do not write product code. Do not edit requirement.md.",
212
+ "If a schema change has implications, write derived/agent-questions.json with channel plan and stop. Do not guess. Do not invent spec IDs.",
213
+ ].join(" ");
214
+ }
package/dist/implement.js CHANGED
@@ -48,8 +48,10 @@ export function implementPrompt(briefPath, stackId) {
48
48
  : "";
49
49
  return [
50
50
  "Implement this requirement from the brief.",
51
- `Read ${briefPath} and derived/spec.json.`,
51
+ `Read ${briefPath}, derived/implement-plan.md, derived/spec.json, and docs/system.md if it exists.`,
52
+ "Follow the accepted implement plan. Read the house standards listed in the brief. Satisfy them in substance. Do not rename spec IDs or headings.",
52
53
  "Do not invent spec IDs. Implement only the named BR- and UC- IDs.",
54
+ "After the change lands, update docs/system.md to match what you built (Entities, Relationships, Notes). A failed run is not as-built.",
53
55
  "If a required decision is missing, write derived/agent-questions.json and stop. Do not guess stack, auth, storage, or owner-facing copy. Do not write product code in that same turn.",
54
56
  "If this product repo has no customer app, use the stack recorded in req0.json.",
55
57
  "Seed the app from existing fixtures/personas.yaml. Do not invent personas.",
@@ -65,10 +67,11 @@ export function implementPrompt(briefPath, stackId) {
65
67
  export function fixFromProofPrompt(briefPath, reportPath, implementBriefPath) {
66
68
  return [
67
69
  "Fix the existing product from the last Prove.",
68
- `Read ${briefPath}, then ${reportPath}, then ${implementBriefPath}.`,
70
+ `Read ${briefPath}, then ${reportPath}, then ${implementBriefPath}, then derived/implement-plan.md and docs/system.md if it exists.`,
69
71
  "Close only the Failed and Needs review cases. Do not invent spec IDs.",
70
72
  "If a required decision is missing, write derived/agent-questions.json and stop. Do not guess. Do not write product code in that same turn.",
71
73
  "Do not edit requirement.md. Do not scaffold a second application.",
74
+ "After the change lands, update docs/system.md to match what you built. A failed run is not as-built.",
72
75
  "Boot or Sign-in observations may be fixtures or runtime.yaml, not a missing control.",
73
76
  "Do not treat this launch as proof the app boots.",
74
77
  `At most ${IMPLEMENT_SANDBOX_MAX} npx ampx sandbox --once deploys in this run. After the third, stop and tell the owner what is still failing. Do not start a fourth.`,
@@ -78,6 +81,7 @@ export function improvePrompt(briefPath) {
78
81
  return [
79
82
  "Improve this requirement pack from the brief.",
80
83
  `Read ${briefPath} and requirement.md.`,
84
+ "Read the house standards listed in the brief. Satisfy them in substance; emit frozen grammar.",
81
85
  "Patch requirement.md only. If the brief asks for a persona, you may also edit fixtures/personas.yaml.",
82
86
  "Outcome is what a person sees. Do not paste matrix allow/deny cells into Outcome. Look for is deny; Choose is allow.",
83
87
  "Do not invent spec IDs. Do not implement the product app.",
package/dist/improve.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type LoadedStandards } from "./standards.js";
1
2
  import type { ReadyFinding, ReadyMeter, SpecAst } from "./types.js";
2
3
  export declare class ImproveLockedError extends Error {
3
4
  readonly code = "improve_gate";
@@ -12,5 +13,6 @@ export declare function emitImproveBrief(input: {
12
13
  spec: SpecAst | null;
13
14
  ready: ReadyMeter;
14
15
  findings?: ReadyFinding[];
16
+ standards?: LoadedStandards | null;
15
17
  }): string;
16
18
  export declare function excerptForFinding(finding: ReadyFinding, spec: SpecAst | null | undefined): string[];
package/dist/improve.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { NOUL_PASS } from "./gates.js";
2
2
  import { questionsBriefSection } from "./agent-questions.js";
3
+ import { standardsBriefSection } from "./standards.js";
3
4
  export class ImproveLockedError extends Error {
4
5
  code = "improve_gate";
5
6
  constructor(message = "Improve it is only when Ready is blocked or pack noul is below 0.75.") {
@@ -60,6 +61,7 @@ export function emitImproveBrief(input) {
60
61
  `- Pack noul is ${noul}. The gate is ${NOUL_PASS.toFixed(2)}.`,
61
62
  `- Ready is ${input.ready.state} (${input.ready.blockers} blocker${input.ready.blockers === 1 ? "" : "s"}, ${input.ready.nits} nit${input.ready.nits === 1 ? "" : "s"}).`,
62
63
  "- Raise pack noul above the gate and clear Ready blockers.",
64
+ "- Read the house standards. Satisfy them in substance. Emit frozen grammar. Do not copy those files into the pack.",
63
65
  "",
64
66
  "## Findings",
65
67
  "",
@@ -89,7 +91,7 @@ export function emitImproveBrief(input) {
89
91
  }
90
92
  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
91
93
  ? "- Missing persona: prefer asking whether the owner has a real test user. If they do not, add `email: <role-slug>@example.test` and `password: test-only-not-production` in fixtures/personas.yaml."
92
- : "- Do not add personas unless a finding is persona_missing.", "- You may edit every section the findings name. This is one pack pass.", "", questionsBriefSection().trimEnd(), "", "## Fence", "", "- Patch `requirement.md` only, then stop.", personas
94
+ : "- Do not add personas unless a finding is persona_missing.", "- You may edit every section the findings name. This is one pack pass.", "- House-standard nits (kind standards) are in this pass when Improve is allowed. They never block Ready by themselves.", "", ...standardsBriefSection(input.standards), questionsBriefSection().trimEnd(), "", "## Fence", "", "- Patch `requirement.md` only, then stop.", personas
93
95
  ? "- At least one finding is a missing persona: you may also edit `fixtures/personas.yaml`."
94
96
  : "- 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.", "");
95
97
  return `${lines.join("\n")}\n`;