@richjava/req0 0.2.0 → 0.4.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.
@@ -0,0 +1,103 @@
1
+ import type { AdapterId, Finding, Health, ProductRepo, ReadyMeter, SpecAst } from "./types.js";
2
+ export declare const AUTHOR_MAX_ROUNDS = 8;
3
+ export declare const AUTHOR_BRIEF_FILE = "author-brief.md";
4
+ export declare const AUTHOR_RUN_FILE = "author-run.json";
5
+ export declare const AUTHOR_AGENT_LOG = "author-agent.log";
6
+ export declare const AUTHOR_STOPPED = "Owner stopped authoring.";
7
+ export declare const AUTHOR_CAPPED = "Authoring stopped after 8 rounds. Keep editing, or Improve it once Ready is blocked.";
8
+ export declare const AUTHOR_ARTIFACT_MIMES: Record<string, string>;
9
+ export type AuthorQualityTarget = "spec_valid" | "ready";
10
+ export type AuthorRunStatus = "running" | "waiting_questions" | "done" | "stopped";
11
+ export type AuthorRun = {
12
+ version: 1;
13
+ status: AuthorRunStatus;
14
+ qualityTarget: AuthorQualityTarget;
15
+ description: string;
16
+ round: number;
17
+ at: string;
18
+ specHash?: string;
19
+ message?: string;
20
+ };
21
+ export type AuthorStepAction = "wait_questions" | "check" | "relaunch" | "done" | "capped";
22
+ export type AuthorStep = {
23
+ action: AuthorStepAction;
24
+ run: AuthorRun;
25
+ message: string;
26
+ };
27
+ export type AuthorPaths = {
28
+ id: string;
29
+ root: string;
30
+ requirement: string;
31
+ personas: string;
32
+ derived: string;
33
+ authorBrief: string;
34
+ authorRun: string;
35
+ context: string;
36
+ };
37
+ export type SiblingSummary = {
38
+ id: string;
39
+ title: string;
40
+ overview: string;
41
+ specIds: string[];
42
+ actors: string[];
43
+ };
44
+ export declare class AuthorLockedError extends Error {
45
+ readonly code = "author_gate";
46
+ constructor(message?: string);
47
+ }
48
+ export declare class AuthorArtifactError extends Error {
49
+ readonly code = "author_artifact";
50
+ constructor(message: string);
51
+ }
52
+ export declare function authorQualityTarget(hasApiKey: boolean): AuthorQualityTarget;
53
+ export declare function authorQualityMet(health: Pick<Health, "spec" | "ready">, target: AuthorQualityTarget): boolean;
54
+ export declare function shouldOfferAuthor(health: Pick<Health, "spec">, run: AuthorRun | null): boolean;
55
+ export declare function isAuthorActive(run: AuthorRun | null | undefined): boolean;
56
+ export declare function parseAuthorRun(raw: unknown): AuthorRun | null;
57
+ export declare function readAuthorRun(paths: Pick<AuthorPaths, "authorRun">): Promise<AuthorRun | null>;
58
+ export declare function writeAuthorRun(paths: Pick<AuthorPaths, "derived" | "authorRun">, run: AuthorRun): Promise<void>;
59
+ export declare function nextAuthorStep(input: {
60
+ run: AuthorRun;
61
+ specState: Health["spec"]["state"];
62
+ readyState: ReadyMeter["state"];
63
+ jevCurrent: boolean;
64
+ openQuestions: boolean;
65
+ hasApiKey: boolean;
66
+ justChecked?: boolean;
67
+ }): AuthorStep;
68
+ export declare function applyAuthorGate(health: Health, run: AuthorRun | null): Health;
69
+ export declare function titleFromRequirementId(id: string): string;
70
+ export declare function seedAuthorMarkdown(id: string, description: string, current: string): string;
71
+ export declare function summarizeRequirementMarkdown(id: string, markdown: string): SiblingSummary;
72
+ export declare function emitAuthorBrief(input: {
73
+ id: string;
74
+ description: string;
75
+ qualityTarget: AuthorQualityTarget;
76
+ round: number;
77
+ markdown: string;
78
+ compileFindings: Finding[];
79
+ spec: SpecAst | null;
80
+ ready: ReadyMeter | null;
81
+ siblings: SiblingSummary[];
82
+ product: {
83
+ empty: boolean;
84
+ stack: string;
85
+ adapter: AdapterId;
86
+ layout: string;
87
+ instruction: string;
88
+ };
89
+ contextFiles: string[];
90
+ }): string;
91
+ export declare function authorPrompt(briefPath: string): string;
92
+ export declare function sanitizeArtifactFilename(filename: string, mime: string): string;
93
+ export declare function decodeArtifactData(raw: string, mime: string): Buffer;
94
+ export declare function writeAuthorArtifact(paths: Pick<AuthorPaths, "context">, filename: string, mime: string, data: string): Promise<string>;
95
+ export declare function listContextFiles(paths: Pick<AuthorPaths, "context">): Promise<string[]>;
96
+ export declare function listProductLayout(repoRoot: string | null): Promise<string>;
97
+ export declare function productBriefBits(repo: ProductRepo, layout: string): {
98
+ empty: boolean;
99
+ stack: string;
100
+ adapter: AdapterId;
101
+ layout: string;
102
+ instruction: string;
103
+ };
package/dist/author.js ADDED
@@ -0,0 +1,435 @@
1
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { excerptForFinding } from "./improve.js";
4
+ import { NOUL_PASS } from "./gates.js";
5
+ import { questionsBriefSection } from "./agent-questions.js";
6
+ import { stackInstruction } from "./stack.js";
7
+ export const AUTHOR_MAX_ROUNDS = 8;
8
+ export const AUTHOR_BRIEF_FILE = "author-brief.md";
9
+ export const AUTHOR_RUN_FILE = "author-run.json";
10
+ export const AUTHOR_AGENT_LOG = "author-agent.log";
11
+ export const AUTHOR_STOPPED = "Owner stopped authoring.";
12
+ export const AUTHOR_CAPPED = `Authoring stopped after ${AUTHOR_MAX_ROUNDS} rounds. Keep editing, or Improve it once Ready is blocked.`;
13
+ export const AUTHOR_ARTIFACT_MIMES = {
14
+ "image/png": ".png",
15
+ "image/jpeg": ".jpg",
16
+ "image/webp": ".webp",
17
+ };
18
+ const ARTIFACT_MAX_BYTES = 5 * 1024 * 1024;
19
+ export class AuthorLockedError extends Error {
20
+ code = "author_gate";
21
+ constructor(message = "Authoring is already in progress.") {
22
+ super(message);
23
+ this.name = "AuthorLockedError";
24
+ }
25
+ }
26
+ export class AuthorArtifactError extends Error {
27
+ code = "author_artifact";
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "AuthorArtifactError";
31
+ }
32
+ }
33
+ export function authorQualityTarget(hasApiKey) {
34
+ return hasApiKey ? "ready" : "spec_valid";
35
+ }
36
+ export function authorQualityMet(health, target) {
37
+ if (health.spec.state !== "valid")
38
+ return false;
39
+ if (target === "spec_valid")
40
+ return true;
41
+ return health.ready.state === "ready";
42
+ }
43
+ export function shouldOfferAuthor(health, run) {
44
+ if (run && (run.status === "running" || run.status === "waiting_questions" || run.status === "done")) {
45
+ return false;
46
+ }
47
+ if (run?.status === "stopped")
48
+ return health.spec.state === "empty" || health.spec.state === "drafting";
49
+ return health.spec.state === "empty" || health.spec.state === "drafting";
50
+ }
51
+ export function isAuthorActive(run) {
52
+ return Boolean(run && (run.status === "running" || run.status === "waiting_questions"));
53
+ }
54
+ export function parseAuthorRun(raw) {
55
+ if (!raw || typeof raw !== "object")
56
+ return null;
57
+ const body = raw;
58
+ if (body.version !== 1)
59
+ return null;
60
+ if (body.status !== "running" && body.status !== "waiting_questions" && body.status !== "done" && body.status !== "stopped") {
61
+ return null;
62
+ }
63
+ if (body.qualityTarget !== "spec_valid" && body.qualityTarget !== "ready")
64
+ return null;
65
+ if (typeof body.description !== "string" || !body.description.trim())
66
+ return null;
67
+ if (typeof body.round !== "number" || !Number.isInteger(body.round) || body.round < 1)
68
+ return null;
69
+ if (typeof body.at !== "string" || !body.at.trim())
70
+ return null;
71
+ return {
72
+ version: 1,
73
+ status: body.status,
74
+ qualityTarget: body.qualityTarget,
75
+ description: body.description.trim(),
76
+ round: body.round,
77
+ at: body.at,
78
+ ...(typeof body.specHash === "string" ? { specHash: body.specHash } : {}),
79
+ ...(typeof body.message === "string" ? { message: body.message } : {}),
80
+ };
81
+ }
82
+ export async function readAuthorRun(paths) {
83
+ try {
84
+ return parseAuthorRun(JSON.parse(await readFile(paths.authorRun, "utf8")));
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ export async function writeAuthorRun(paths, run) {
91
+ await mkdir(paths.derived, { recursive: true });
92
+ await writeFile(paths.authorRun, `${JSON.stringify(run, null, 2)}\n`, "utf8");
93
+ }
94
+ export function nextAuthorStep(input) {
95
+ const health = {
96
+ spec: { state: input.specState, findings: [] },
97
+ ready: { state: input.readyState },
98
+ };
99
+ if (input.openQuestions) {
100
+ return {
101
+ action: "wait_questions",
102
+ run: { ...input.run, status: "waiting_questions", at: now(), message: "Waiting on owner questions." },
103
+ message: "Waiting on owner questions.",
104
+ };
105
+ }
106
+ if (authorQualityMet(health, input.run.qualityTarget)) {
107
+ const message = input.run.qualityTarget === "ready"
108
+ ? "Requirement meets Ready. Authoring is done."
109
+ : "Spec is Valid. Authoring is done (no TypeSafe key, so Ready stays Not yet).";
110
+ return {
111
+ action: "done",
112
+ run: { ...input.run, status: "done", at: now(), message },
113
+ message,
114
+ };
115
+ }
116
+ if (input.run.round >= AUTHOR_MAX_ROUNDS) {
117
+ return {
118
+ action: "capped",
119
+ run: { ...input.run, status: "stopped", at: now(), message: AUTHOR_CAPPED },
120
+ message: AUTHOR_CAPPED,
121
+ };
122
+ }
123
+ if (input.run.qualityTarget === "ready" &&
124
+ input.specState === "valid" &&
125
+ input.hasApiKey &&
126
+ !input.jevCurrent &&
127
+ !input.justChecked) {
128
+ return {
129
+ action: "check",
130
+ run: { ...input.run, status: "running", at: now(), message: "Checking the spec with Jev." },
131
+ message: "Checking the spec with Jev.",
132
+ };
133
+ }
134
+ const round = input.run.round + 1;
135
+ return {
136
+ action: "relaunch",
137
+ run: {
138
+ ...input.run,
139
+ status: "running",
140
+ round,
141
+ at: now(),
142
+ message: `Authoring round ${round} of ${AUTHOR_MAX_ROUNDS}.`,
143
+ },
144
+ message: `Authoring round ${round} of ${AUTHOR_MAX_ROUNDS}.`,
145
+ };
146
+ }
147
+ export function applyAuthorGate(health, run) {
148
+ if (isAuthorActive(run) && health.stages) {
149
+ const waiting = run?.status === "waiting_questions";
150
+ return {
151
+ ...health,
152
+ howThisIsGoing: waiting ? "The agent has questions." : "Authoring this requirement.",
153
+ nextAction: waiting
154
+ ? health.nextAction
155
+ : {
156
+ id: "stop-author",
157
+ label: "Stop",
158
+ enabled: true,
159
+ hint: "Stop authoring. The last requirement.md is kept.",
160
+ },
161
+ stages: {
162
+ ready: { ...health.stages.ready, enabled: false, hint: "Finish authoring, or Stop, before Check or Improve." },
163
+ build: { ...health.stages.build, enabled: false },
164
+ proof: { ...health.stages.proof, enabled: false },
165
+ ...(health.stages.fixFromProof ? { fixFromProof: { ...health.stages.fixFromProof, enabled: false } } : {}),
166
+ ...(health.stages.ignoreBuild ? { ignoreBuild: { ...health.stages.ignoreBuild, enabled: false } } : {}),
167
+ ...(health.stages.stopImplement ? { stopImplement: { ...health.stages.stopImplement, enabled: false } } : {}),
168
+ },
169
+ };
170
+ }
171
+ if (shouldOfferAuthor(health, run)) {
172
+ return {
173
+ ...health,
174
+ howThisIsGoing: "Describe this requirement, then Start.",
175
+ nextAction: {
176
+ id: "author-start",
177
+ label: "Start",
178
+ enabled: true,
179
+ hint: "Describe the requirement. The agent will ask questions until the spec is ready to compile.",
180
+ },
181
+ };
182
+ }
183
+ return health;
184
+ }
185
+ export function titleFromRequirementId(id) {
186
+ return id
187
+ .split("-")
188
+ .filter(Boolean)
189
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
190
+ .join(" ");
191
+ }
192
+ export function seedAuthorMarkdown(id, description, current) {
193
+ const title = titleFromRequirementId(id);
194
+ const overview = description.trim();
195
+ const looksLikeTemplate = !current.trim() ||
196
+ /Template guidance|Untitled Requirement|## Description/.test(current);
197
+ if (looksLikeTemplate) {
198
+ return [
199
+ `# ${title}`,
200
+ "",
201
+ "## Overview",
202
+ "",
203
+ overview,
204
+ "",
205
+ "## Business Rules",
206
+ "",
207
+ "## Use Cases",
208
+ "",
209
+ "## Roles & Permissions",
210
+ "",
211
+ ].join("\n");
212
+ }
213
+ if (/^## Overview\s*$/m.test(current) || /^## Overview$/m.test(current)) {
214
+ return replaceOverview(current, overview);
215
+ }
216
+ const titled = current.replace(/^#\s+.+$/m, `# ${title}`);
217
+ if (/^## Overview\b/m.test(titled))
218
+ return replaceOverview(titled, overview);
219
+ const match = titled.match(/^#\s+.+$/m);
220
+ if (!match || match.index === undefined) {
221
+ return `# ${title}\n\n## Overview\n\n${overview}\n\n${titled}`;
222
+ }
223
+ const insertAt = match.index + match[0].length;
224
+ return `${titled.slice(0, insertAt)}\n\n## Overview\n\n${overview}\n${titled.slice(insertAt)}`;
225
+ }
226
+ function replaceOverview(markdown, overview) {
227
+ return markdown.replace(/## Overview\n+[\s\S]*?(?=\n## |\n#[^#]|$)/, `## Overview\n\n${overview}\n`);
228
+ }
229
+ export function summarizeRequirementMarkdown(id, markdown) {
230
+ const title = markdown.match(/^#\s+(.+)$/m)?.[1]?.trim() || id.replaceAll("-", " ");
231
+ const overviewBlock = markdown.match(/## Overview\n+([\s\S]*?)(?=\n## |\n#[^#]|$)/);
232
+ const overview = (overviewBlock?.[1] ?? "").trim().replace(/\s+/g, " ").slice(0, 280);
233
+ const specIds = [...markdown.matchAll(/\b((?:BR|UC)-\d{3})\b/g)].map((match) => match[1] ?? "");
234
+ const actors = [
235
+ ...new Set([...markdown.matchAll(/^Actor:\s*(.+)$/gm)].map((match) => match[1]?.trim() ?? "").filter(Boolean)),
236
+ ];
237
+ return {
238
+ id,
239
+ title,
240
+ overview,
241
+ specIds: [...new Set(specIds)].slice(0, 24),
242
+ actors: actors.slice(0, 12),
243
+ };
244
+ }
245
+ export function emitAuthorBrief(input) {
246
+ const target = input.qualityTarget === "ready"
247
+ ? `Ready Clear: pack noul at or above ${NOUL_PASS.toFixed(2)}, zero blockers. The host Checks with Jev after Spec Valid. Do not fake scores.`
248
+ : "Spec Valid (frozen grammar). There is no TypeSafe key, so stop once the compiler is Valid. Ready may stay Not yet.";
249
+ const lines = [
250
+ `# Author: ${input.id}`,
251
+ "",
252
+ "Fill this requirement pack from the owner's description. Do not guess. Do not implement the product app.",
253
+ `This is authoring round ${input.round} of ${AUTHOR_MAX_ROUNDS}.`,
254
+ "",
255
+ "## Goal",
256
+ "",
257
+ `- Quality bar: ${target}`,
258
+ "- 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.",
259
+ "",
260
+ "## Owner description",
261
+ "",
262
+ input.description.trim() || "(empty)",
263
+ "",
264
+ "## Frozen grammar",
265
+ "",
266
+ "Replace the starter template. Allowed `##` headings only:",
267
+ "",
268
+ "- Required: `Business Rules`, `Use Cases`, `Roles & Permissions`",
269
+ "- Optional: `Overview`, `Out of scope`, `Open questions`, `Entities`, `UI notes`",
270
+ "- Put the owner's description in `## Overview`. Do not emit `## Description` or template guidance labels.",
271
+ "- Each business rule: `Id: BR-NNN`, Statement, Observable (what a person or test notices).",
272
+ "- 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`.",
274
+ "- 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
+ "- Edit `fixtures/personas.yaml` only when a role is confirmed (email `role-slug@example.test`, password `test-only-not-production`).",
276
+ "",
277
+ "## Current requirement.md",
278
+ "",
279
+ "~~~~markdown",
280
+ input.markdown.trim() || "(empty)",
281
+ "~~~~",
282
+ "",
283
+ "## Compile findings",
284
+ "",
285
+ ];
286
+ if (!input.compileFindings.length) {
287
+ lines.push("None. Spec grammar is Valid.", "");
288
+ }
289
+ else {
290
+ for (const finding of input.compileFindings) {
291
+ lines.push(`- L${finding.line} ${finding.severity}: ${finding.message}`);
292
+ }
293
+ lines.push("");
294
+ }
295
+ if (input.ready && input.spec) {
296
+ lines.push("## Ready findings", "");
297
+ lines.push(`- Ready is ${input.ready.state} (${input.ready.blockers} blocker${input.ready.blockers === 1 ? "" : "s"}, ${input.ready.nits} nit${input.ready.nits === 1 ? "" : "s"}).`);
298
+ if (typeof input.ready.packNoul === "number") {
299
+ lines.push(`- Pack noul is ${input.ready.packNoul.toFixed(2)}. Gate ${NOUL_PASS.toFixed(2)}.`);
300
+ }
301
+ lines.push("");
302
+ if (!input.ready.findings.length) {
303
+ lines.push("No Ready findings.", "");
304
+ }
305
+ else {
306
+ for (const [index, finding] of input.ready.findings.entries()) {
307
+ lines.push(`### ${index + 1}. ${finding.specId ?? finding.id}`, "");
308
+ lines.push(`- Kind: ${finding.kind}`);
309
+ lines.push(`- Severity: ${finding.severity}`);
310
+ lines.push(`- Message: ${finding.message}`, "");
311
+ lines.push(...excerptForFinding(finding, input.spec));
312
+ }
313
+ }
314
+ }
315
+ lines.push("## Sibling packs", "", "Match density and grammar. Do not copy IDs or steal this pack's scope.", "");
316
+ if (!input.siblings.length) {
317
+ lines.push("No other packs in this repo.", "");
318
+ }
319
+ else {
320
+ for (const sibling of input.siblings) {
321
+ lines.push(`### ${sibling.id}`, "");
322
+ lines.push(`- Title: ${sibling.title}`);
323
+ if (sibling.overview)
324
+ lines.push(`- Overview: ${sibling.overview}`);
325
+ if (sibling.actors.length)
326
+ lines.push(`- Actors: ${sibling.actors.join(", ")}`);
327
+ if (sibling.specIds.length)
328
+ lines.push(`- Spec IDs: ${sibling.specIds.join(", ")}`);
329
+ lines.push("");
330
+ }
331
+ }
332
+ lines.push("## Product repo", "");
333
+ lines.push(`- ${input.product.instruction}`);
334
+ lines.push(`- Stack: ${input.product.stack}. Adapter: ${input.product.adapter}.`);
335
+ lines.push(`- Top-level: ${input.product.layout || "(none listed)"}`);
336
+ lines.push("- Read existing screens, roles, and routes. Do not scaffold a second application.", "");
337
+ lines.push("## context/ artifacts", "");
338
+ if (!input.contextFiles.length) {
339
+ lines.push("None yet. If you need a screenshot, ask with `kind: \"artifact\"`. The owner may skip.", "");
340
+ }
341
+ else {
342
+ lines.push("Read each file (images included) and update the spec from what you see. Do not invent UI the files do not show.", "");
343
+ for (const file of input.contextFiles)
344
+ lines.push(`- context/${file}`);
345
+ lines.push("");
346
+ }
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.", "");
348
+ return `${lines.join("\n")}\n`;
349
+ }
350
+ export function authorPrompt(briefPath) {
351
+ return [
352
+ "Author this requirement pack from the brief.",
353
+ `Read ${briefPath} and requirement.md.`,
354
+ "Write frozen-grammar requirement.md. You may assign the first BR- and UC- IDs. Do not copy sibling IDs.",
355
+ "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
+ "Read files in context/ including images. Do not invent UI the owner did not confirm or upload.",
357
+ "You may edit fixtures/personas.yaml when a role is confirmed. Do not implement the product app. Do not Check with Jev.",
358
+ ].join(" ");
359
+ }
360
+ export function sanitizeArtifactFilename(filename, mime) {
361
+ const ext = AUTHOR_ARTIFACT_MIMES[mime];
362
+ if (!ext) {
363
+ throw new AuthorArtifactError("Upload a PNG, JPG, or WebP image.");
364
+ }
365
+ const base = path.basename(filename).replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
366
+ const stem = base.replace(/\.[a-zA-Z0-9]+$/, "") || "artifact";
367
+ return `${stem.slice(0, 80)}${ext}`;
368
+ }
369
+ export function decodeArtifactData(raw, mime) {
370
+ const ext = AUTHOR_ARTIFACT_MIMES[mime];
371
+ if (!ext)
372
+ throw new AuthorArtifactError("Upload a PNG, JPG, or WebP image.");
373
+ const trimmed = raw.trim();
374
+ const comma = trimmed.indexOf(",");
375
+ const payload = trimmed.startsWith("data:") && comma >= 0 ? trimmed.slice(comma + 1) : trimmed;
376
+ let bytes;
377
+ try {
378
+ bytes = Buffer.from(payload, "base64");
379
+ }
380
+ catch {
381
+ throw new AuthorArtifactError("Could not read the upload.");
382
+ }
383
+ if (!bytes.length)
384
+ throw new AuthorArtifactError("Upload is empty.");
385
+ if (bytes.length > ARTIFACT_MAX_BYTES) {
386
+ throw new AuthorArtifactError("Upload must be 5 MB or smaller.");
387
+ }
388
+ return bytes;
389
+ }
390
+ export async function writeAuthorArtifact(paths, filename, mime, data) {
391
+ const safe = sanitizeArtifactFilename(filename, mime);
392
+ const bytes = decodeArtifactData(data, mime);
393
+ await mkdir(paths.context, { recursive: true });
394
+ await writeFile(path.join(paths.context, safe), bytes);
395
+ return safe;
396
+ }
397
+ export async function listContextFiles(paths) {
398
+ try {
399
+ const entries = await readdir(paths.context, { withFileTypes: true });
400
+ return entries
401
+ .filter((entry) => entry.isFile() && /\.(png|jpe?g|webp)$/i.test(entry.name))
402
+ .map((entry) => entry.name)
403
+ .sort();
404
+ }
405
+ catch {
406
+ return [];
407
+ }
408
+ }
409
+ export async function listProductLayout(repoRoot) {
410
+ if (!repoRoot)
411
+ return "(no product repo)";
412
+ try {
413
+ const entries = await readdir(repoRoot, { withFileTypes: true });
414
+ return entries
415
+ .filter((entry) => !entry.name.startsWith("."))
416
+ .slice(0, 24)
417
+ .map((entry) => (entry.isDirectory() ? `${entry.name}/` : entry.name))
418
+ .join(", ");
419
+ }
420
+ catch {
421
+ return "(unreadable)";
422
+ }
423
+ }
424
+ export function productBriefBits(repo, layout) {
425
+ return {
426
+ empty: repo.empty,
427
+ stack: repo.stack.label,
428
+ adapter: repo.adapter,
429
+ layout,
430
+ instruction: stackInstruction(repo, repo.adapter),
431
+ };
432
+ }
433
+ function now() {
434
+ return new Date().toISOString();
435
+ }
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ import { isRequirementId } from "./compile.js";
10
10
  import { adapterInstructions, ImplementDisabledError, ImplementLockedError } from "./implement.js";
11
11
  import { FixFromProofLockedError } from "./fix-from-proof.js";
12
12
  import { StackRequiredError, UnknownStackError } from "./stack.js";
13
- import { checkPack, compilePack, createPack, findRequirementsDir, finishImplement, implementPack, provePack, resolveCockpitPack, resolvePack } from "./pack.js";
13
+ import { checkPack, compilePack, createPack, findRequirementsDir, finishImplement, implementPack, provePack, resolveCockpitPack, resolvePack, shouldRefreshForWatch } from "./pack.js";
14
14
  import { ProveLockedError } from "./proof.js";
15
15
  import { createAppState, createCockpitServer, refresh } from "./server.js";
16
16
  loadProjectEnv();
@@ -207,7 +207,11 @@ async function startCockpit(cwd) {
207
207
  };
208
208
  for (const watchPath of watchTargets) {
209
209
  try {
210
- const watcher = watch(watchPath, { recursive: Boolean(requirementsDir) }, () => schedule());
210
+ const watcher = watch(watchPath, { recursive: Boolean(requirementsDir) }, (_event, filename) => {
211
+ if (!shouldRefreshForWatch(watchPath, filename))
212
+ return;
213
+ schedule();
214
+ });
211
215
  watcher.on("error", (err) => {
212
216
  console.error(`File watch unavailable (${err.message}). Save from the cockpit still compiles.`);
213
217
  });
@@ -1,3 +1,4 @@
1
+ import { questionsBriefSection } from "./agent-questions.js";
1
2
  export class FixFromProofLockedError extends Error {
2
3
  code = "fix_from_proof_gate";
3
4
  constructor(message = "Fix from proof is only after Ready, a succeeded Build, and a Proof that failed or needs review.") {
@@ -56,6 +57,7 @@ export function emitFixFromProofBrief(input) {
56
57
  }
57
58
  lines.push("");
58
59
  }
60
+ lines.push(questionsBriefSection().trimEnd(), "");
59
61
  lines.push("## Done means", "", "The existing app matches the named cases in the proof report. Personas and `fixtures/runtime.yaml` still match that app. At most 3 `npx ampx sandbox --once` deploys. After the third, stop and report what is still failing. A coding-agent run finishing is **Build Succeeded**, not “the app boots.” Re-prove is next.", "");
60
62
  return `${lines.join("\n")}\n`;
61
63
  }
@@ -1,3 +1,4 @@
1
+ import { questionsBriefSection } from "./agent-questions.js";
1
2
  import { DEFAULT_STACK, isAmplifyStack, stackInstruction } from "./stack.js";
2
3
  export function emitImplementBrief(input) {
3
4
  const { spec, repo, adapter, personas } = input;
@@ -61,7 +62,7 @@ export function emitImplementBrief(input) {
61
62
  lines.push("## Open questions", "", spec.optional["Open questions"].trim(), "");
62
63
  }
63
64
  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), "~~~~", "");
64
- 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.", "", "## Security baseline", "", "- No production credentials in the spec or this brief.", "- Secrets via environment variables.", "- Personas are test-only.", "", "## Done means", "", isAmplifyStack(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)
65
66
  ? "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."
66
67
  : "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).", "");
67
68
  return `${lines.join("\n")}\n`;
@@ -8,6 +8,8 @@ export declare const IMPLEMENT_MAX_MS: number;
8
8
  export declare const IMPLEMENT_STOPPED = "Owner stopped Implement.";
9
9
  export declare const IMPLEMENT_SANDBOX_CAP = "Stopped after 3 sandbox deploys. Reimplement or Ignore, then Prove.";
10
10
  export declare const IMPLEMENT_TIME_CAP = "Stopped after 20 minutes. Reimplement or Ignore, then Prove.";
11
+ /** Cursor `--print` can emit `result` and then hang. Kill the leftover process after this grace. */
12
+ export declare const IMPLEMENT_EXIT_GRACE_MS = 3000;
11
13
  export type ImplementStop = {
12
14
  reason?: string;
13
15
  };
@@ -35,6 +37,8 @@ export type LaunchAdapterDeps = {
35
37
  maxMs?: number;
36
38
  heartbeatLabel?: string;
37
39
  cliName?: string;
40
+ /** After a stream `result` event, kill a hung CLI if it has not exited. Default 3s. */
41
+ exitGraceMs?: number;
38
42
  };
39
43
  export type LaunchAdapterResult = {
40
44
  ok: boolean;
@@ -61,10 +65,12 @@ export declare function attachAgentLog(child: ChildProcess, logPath: string, onL
61
65
  sandboxMax?: number;
62
66
  maxMs?: number;
63
67
  heartbeatLabel?: string;
68
+ exitGraceMs?: number;
64
69
  }): Promise<{
65
70
  code: number | null;
66
71
  }>;
67
72
  export declare function requestImplementStop(child: ChildProcess | undefined, stop: ImplementStop, reason: string): void;
68
73
  export declare function killImplementTree(child?: ChildProcess): void;
69
74
  export declare function isSandboxOnceStart(line: string): boolean;
75
+ export declare function agentStreamOutcome(line: string): "success" | "error" | null;
70
76
  export declare function summarizeAgentLine(line: string): string | null;