@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
package/dist/pack.js ADDED
@@ -0,0 +1,609 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { mkdir, readFile, writeFile, readdir, access, appendFile, rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { adapterDisplayName, adapterLaunchesAgent } from "./adapter.js";
5
+ import { compileMarkdown, healthToStatusMarkdown, isRequirementId } from "./compile.js";
6
+ import { assertImplementAllowed, ImplementDisabledError, fixFromProofPrompt, implementPrompt, improvePrompt, IMPLEMENT_STOPPED, launchAdapter, requestImplementStop, } from "./implement.js";
7
+ import { assertFixFromProofAllowed, emitFixFromProofBrief, FixFromProofLockedError } from "./fix-from-proof.js";
8
+ import { assertImproveAllowed, emitImproveBrief, improveFindings } from "./improve.js";
9
+ import { clearImproveLog, readImproveLog, recordImprovePending } from "./improve-log.js";
10
+ import { beginImproveReview, ImproveReviewPendingError, readImproveSnapshot } from "./improve-review.js";
11
+ import { emitImplementBrief } from "./implement-brief.js";
12
+ import { hasJevAccess, JevRequestError, JevUnavailableError, resolveJevClient } from "./jev.js";
13
+ import { emitJevPack } from "./jev-pack.js";
14
+ import { parsePersonasYaml } from "./personas.js";
15
+ import { emitProofReport } from "./proof-report.js";
16
+ import { emitQaPlan, emitQaPlanYaml } from "./qa-plan.js";
17
+ import { assertProveAllowed, evaluateProof, persistProofRun, provePlan, ProveLockedError, } from "./proof.js";
18
+ import { applyReadyToHealth, attachReady, evaluateBuild, followImplementPid, IMPLEMENT_INTERRUPTED, implementProcessGone, IgnoreBuildLockedError, isFollowedImplement, specHash, unfollowImplementPid, } from "./ready.js";
19
+ import { ignoreBuildAllowed, packListMeters } from "./stages.js";
20
+ import { parseRuntimeYaml } from "./runtime.js";
21
+ import { inspectProductRepo, needsStackChoice, resolveStackId, StackRequiredError, UnknownStackError, writeAmplifyEnvExampleIfMissing, writeReq0Config, } from "./stack.js";
22
+ import { loadStarterRequirement, PERSONAS_STUB, RUNTIME_STUB } from "./template.js";
23
+ export const REQUIREMENT_FILE = "requirement.md";
24
+ export const PERSONAS_FILE = path.join("fixtures", "personas.yaml");
25
+ export const RUNTIME_FILE = path.join("fixtures", "runtime.yaml");
26
+ export function packPaths(root) {
27
+ const id = path.basename(root);
28
+ const derived = path.join(root, "derived");
29
+ return {
30
+ id,
31
+ root,
32
+ requirement: path.join(root, REQUIREMENT_FILE),
33
+ personas: path.join(root, PERSONAS_FILE),
34
+ derived,
35
+ spec: path.join(derived, "spec.json"),
36
+ health: path.join(derived, "health.json"),
37
+ status: path.join(derived, "status.md"),
38
+ jevPack: path.join(derived, "jev-pack.json"),
39
+ jevRun: path.join(derived, "jev-run.json"),
40
+ implementBrief: path.join(derived, "implement-brief.md"),
41
+ fixFromProofBrief: path.join(derived, "fix-from-proof-brief.md"),
42
+ improveBrief: path.join(derived, "improve-brief.md"),
43
+ improveSnapshot: path.join(derived, "improve-snapshot.json"),
44
+ improveLog: path.join(derived, "improve-log.json"),
45
+ buildRun: path.join(derived, "build-run.json"),
46
+ runtime: path.join(root, RUNTIME_FILE),
47
+ qaPlan: path.join(derived, "qa-plan.yaml"),
48
+ proofRun: path.join(derived, "proof-run.json"),
49
+ proofReport: path.join(derived, "proof-report.md"),
50
+ proveLog: path.join(derived, "prove-run.log"),
51
+ };
52
+ }
53
+ export async function isPackDir(dir) {
54
+ try {
55
+ await access(path.join(dir, REQUIREMENT_FILE));
56
+ return true;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ export async function resolveCockpitPack(cwd) {
63
+ const abs = path.resolve(cwd);
64
+ if (await isPackDir(abs))
65
+ return packPaths(abs);
66
+ const id = path.basename(abs);
67
+ const parent = path.basename(path.dirname(abs));
68
+ if (isRequirementId(id) && parent === "requirements") {
69
+ return packPaths(abs);
70
+ }
71
+ return null;
72
+ }
73
+ export async function resolvePack(cwd) {
74
+ const fromDir = await resolveCockpitPack(cwd);
75
+ if (fromDir)
76
+ return fromDir;
77
+ const named = path.join(path.resolve(cwd), "docs", "requirements");
78
+ const packs = await listPacks(named);
79
+ if (packs.length === 1)
80
+ return packs[0] ?? null;
81
+ return null;
82
+ }
83
+ export async function summarizePacks(packs) {
84
+ const items = [];
85
+ for (const pack of packs) {
86
+ items.push(await summarizePack(pack));
87
+ }
88
+ return items;
89
+ }
90
+ async function summarizePack(paths) {
91
+ const markdown = await readMarkdown(paths);
92
+ const title = titleFromMarkdown(markdown) || paths.id.replaceAll("-", " ");
93
+ const health = (await readStoredHealth(paths)) ?? (await compilePack(paths)).health;
94
+ return {
95
+ id: paths.id,
96
+ title,
97
+ meters: packListMeters(health, true),
98
+ };
99
+ }
100
+ function titleFromMarkdown(markdown) {
101
+ const match = markdown.match(/^#\s+(.+)$/m);
102
+ return match?.[1]?.trim() ?? "";
103
+ }
104
+ async function readStoredHealth(paths) {
105
+ try {
106
+ const raw = JSON.parse(await readFile(paths.health, "utf8"));
107
+ if (raw && typeof raw === "object" && raw.spec && raw.ready && raw.build && raw.proof) {
108
+ return raw;
109
+ }
110
+ }
111
+ catch {
112
+ /* compile on demand */
113
+ }
114
+ return null;
115
+ }
116
+ export async function listPacks(requirementsDir) {
117
+ try {
118
+ const entries = await readdir(requirementsDir, { withFileTypes: true });
119
+ const packs = [];
120
+ for (const entry of entries) {
121
+ if (!entry.isDirectory())
122
+ continue;
123
+ const root = path.join(requirementsDir, entry.name);
124
+ if (await isPackDir(root))
125
+ packs.push(packPaths(root));
126
+ }
127
+ return packs.sort((a, b) => a.id.localeCompare(b.id));
128
+ }
129
+ catch {
130
+ return [];
131
+ }
132
+ }
133
+ export async function findRequirementsDir(cwd) {
134
+ let dir = path.resolve(cwd);
135
+ for (let i = 0; i < 8; i++) {
136
+ const candidate = path.join(dir, "docs", "requirements");
137
+ try {
138
+ await access(candidate);
139
+ return candidate;
140
+ }
141
+ catch {
142
+ const parent = path.dirname(dir);
143
+ if (parent === dir)
144
+ break;
145
+ dir = parent;
146
+ }
147
+ }
148
+ return null;
149
+ }
150
+ export async function readMarkdown(paths) {
151
+ try {
152
+ return await readFile(paths.requirement, "utf8");
153
+ }
154
+ catch {
155
+ return "";
156
+ }
157
+ }
158
+ export async function loadPersonas(paths) {
159
+ try {
160
+ const text = await readFile(paths.personas, "utf8");
161
+ return parsePersonasYaml(text);
162
+ }
163
+ catch {
164
+ return {
165
+ personas: new Map(),
166
+ findings: [],
167
+ missingFile: true,
168
+ };
169
+ }
170
+ }
171
+ export async function compilePack(paths) {
172
+ const markdown = await readMarkdown(paths);
173
+ let result = compileMarkdown(paths.id, markdown);
174
+ if (result.spec)
175
+ result = { ...result, jevPack: emitJevPack(result.spec) };
176
+ const personas = await loadPersonas(paths);
177
+ const repo = await inspectProductRepo(paths.root);
178
+ if (repo.root && repo.recorded) {
179
+ await writeAmplifyEnvExampleIfMissing(repo.root, repo.stack);
180
+ }
181
+ if (result.spec) {
182
+ result = {
183
+ ...result,
184
+ implementBrief: emitImplementBrief({
185
+ spec: result.spec,
186
+ repo,
187
+ adapter: repo.adapter,
188
+ personas,
189
+ }),
190
+ };
191
+ }
192
+ const jevRun = result.spec ? await readJevRun(paths, result.spec) : null;
193
+ result = attachReady(result, {
194
+ personas,
195
+ jevRun,
196
+ hasApiKey: hasJevAccess(),
197
+ });
198
+ const improved = (await readImproveLog(paths)).accepted;
199
+ if (improved.length) {
200
+ result.health.ready = { ...result.health.ready, alreadyImproved: improved };
201
+ }
202
+ const buildRun = await readBuildRun(paths);
203
+ if (buildRun?.state === "running" &&
204
+ !isFollowedImplement(buildRun.pid) &&
205
+ implementProcessGone(buildRun.pid)) {
206
+ await writeBuildRun(paths, {
207
+ specHash: buildRun.specHash,
208
+ state: "failed",
209
+ adapter: buildRun.adapter,
210
+ at: new Date().toISOString(),
211
+ message: IMPLEMENT_INTERRUPTED,
212
+ });
213
+ }
214
+ const latestBuildRun = await readBuildRun(paths);
215
+ const build = evaluateBuild(result.spec, latestBuildRun);
216
+ result.health.build = repo.implement
217
+ ? {
218
+ ...build,
219
+ needsStack: needsStackChoice(repo),
220
+ adapter: build.adapter,
221
+ }
222
+ : {
223
+ state: "not_yet",
224
+ owned: false,
225
+ message: "Implement is off in req0.json. Build this repo another way. Prove uses fixtures/runtime.yaml.",
226
+ };
227
+ const runtime = await loadRuntime(paths);
228
+ if (result.spec) {
229
+ result.qaPlan = emitQaPlan(result.spec);
230
+ }
231
+ const proofRun = result.spec ? await readProofRun(paths) : null;
232
+ const succeededAt = repo.implement && result.health.build.state === "succeeded" ? buildRun?.at : undefined;
233
+ result.health.proof = evaluateProof({
234
+ spec: result.spec,
235
+ runtime: runtime.ok,
236
+ run: proofRun,
237
+ buildAt: succeededAt,
238
+ });
239
+ if (!runtime.ok && !runtime.missing) {
240
+ result.health.proof.message = runtime.findings[0]?.message;
241
+ }
242
+ result.health = applyReadyToHealth(result.health, result.health.ready);
243
+ await persistDerived(paths, result);
244
+ return result;
245
+ }
246
+ export async function checkPack(paths, client) {
247
+ const compiled = await compilePack(paths);
248
+ if (!compiled.spec || !compiled.jevPack)
249
+ return compiled;
250
+ const resolved = client ?? resolveJevClient();
251
+ try {
252
+ const answers = await resolved.judge(compiled.jevPack);
253
+ const run = {
254
+ specHash: specHash(compiled.spec),
255
+ checkedAt: new Date().toISOString(),
256
+ answers,
257
+ };
258
+ await mkdir(paths.derived, { recursive: true });
259
+ await writeFile(paths.jevRun, `${JSON.stringify(run, null, 2)}\n`, "utf8");
260
+ await clearImproveLog(paths);
261
+ return compilePack(paths);
262
+ }
263
+ catch (err) {
264
+ if (err instanceof JevUnavailableError) {
265
+ return attachReady(compiled, {
266
+ personas: await loadPersonas(paths),
267
+ jevRun: null,
268
+ hasApiKey: false,
269
+ });
270
+ }
271
+ if (err instanceof JevRequestError)
272
+ throw err;
273
+ throw new JevRequestError(err instanceof Error ? err.message : "Jev request failed.");
274
+ }
275
+ }
276
+ export async function persistDerived(paths, result) {
277
+ await mkdir(paths.derived, { recursive: true });
278
+ if (result.spec) {
279
+ await writeFile(paths.spec, `${JSON.stringify(result.spec, null, 2)}\n`, "utf8");
280
+ }
281
+ if (result.jevPack) {
282
+ await writeFile(paths.jevPack, `${JSON.stringify(result.jevPack, null, 2)}\n`, "utf8");
283
+ }
284
+ if (result.implementBrief) {
285
+ await writeFile(paths.implementBrief, result.implementBrief, "utf8");
286
+ }
287
+ if (result.qaPlan) {
288
+ await writeFile(paths.qaPlan, emitQaPlanYaml(result.qaPlan), "utf8");
289
+ }
290
+ await writeFile(paths.health, `${JSON.stringify(result.health, null, 2)}\n`, "utf8");
291
+ await writeFile(paths.status, healthToStatusMarkdown(result.health), "utf8");
292
+ }
293
+ async function readJevRun(paths, spec) {
294
+ try {
295
+ const raw = JSON.parse(await readFile(paths.jevRun, "utf8"));
296
+ if (raw.specHash !== specHash(spec))
297
+ return null;
298
+ if (!Array.isArray(raw.answers))
299
+ return null;
300
+ return raw;
301
+ }
302
+ catch {
303
+ return null;
304
+ }
305
+ }
306
+ export async function createPack(root) {
307
+ const paths = packPaths(root);
308
+ await mkdir(path.join(root, "fixtures"), { recursive: true });
309
+ await mkdir(path.join(root, "context"), { recursive: true });
310
+ await mkdir(paths.derived, { recursive: true });
311
+ try {
312
+ await access(paths.requirement);
313
+ }
314
+ catch {
315
+ await writeFile(paths.requirement, await loadStarterRequirement(), "utf8");
316
+ }
317
+ try {
318
+ await access(paths.personas);
319
+ }
320
+ catch {
321
+ await writeFile(paths.personas, PERSONAS_STUB, "utf8");
322
+ }
323
+ await writeRuntimeStubIfMissing(paths);
324
+ await compilePack(paths);
325
+ return paths;
326
+ }
327
+ export async function deletePack(paths) {
328
+ if (!(await isPackDir(paths.root))) {
329
+ throw new Error(`Not a requirement pack: ${paths.id}`);
330
+ }
331
+ await rm(paths.root, { recursive: true, force: true });
332
+ }
333
+ export async function writeRuntimeStubIfMissing(paths) {
334
+ try {
335
+ await access(paths.runtime);
336
+ return false;
337
+ }
338
+ catch {
339
+ await mkdir(path.dirname(paths.runtime), { recursive: true });
340
+ await writeFile(paths.runtime, RUNTIME_STUB, "utf8");
341
+ return true;
342
+ }
343
+ }
344
+ async function readBuildRun(paths) {
345
+ try {
346
+ const raw = JSON.parse(await readFile(paths.buildRun, "utf8"));
347
+ if (!raw.specHash || !raw.state)
348
+ return null;
349
+ return raw;
350
+ }
351
+ catch {
352
+ return null;
353
+ }
354
+ }
355
+ export async function implementPack(paths, options = {}) {
356
+ const compiled = await compilePack(paths);
357
+ assertImplementAllowed(compiled);
358
+ if (options.fromProof) {
359
+ assertFixFromProofAllowed(compiled.health, compiled.health.ready);
360
+ if (!compiled.spec)
361
+ throw new FixFromProofLockedError();
362
+ }
363
+ const repo = await inspectProductRepo(paths.root);
364
+ if (!repo.implement)
365
+ throw new ImplementDisabledError();
366
+ await writeRuntimeStubIfMissing(paths);
367
+ const adapter = options.adapter ?? (repo.adapterRecorded ? repo.adapter : "cursor");
368
+ const requested = options.stack !== undefined ? resolveStackId(options.stack) : null;
369
+ if (options.stack !== undefined && !requested)
370
+ throw new UnknownStackError(options.stack);
371
+ const stack = requested ?? (repo.recorded ? repo.stack : null);
372
+ if (!stack && needsStackChoice(repo))
373
+ throw new StackRequiredError();
374
+ if (repo.root) {
375
+ await writeReq0Config(repo.root, stack ? { adapter, stack } : { adapter });
376
+ if (stack)
377
+ await writeAmplifyEnvExampleIfMissing(repo.root, stack);
378
+ }
379
+ let briefPath = paths.implementBrief;
380
+ let prompt = implementPrompt(paths.implementBrief, stack?.id ?? repo.stack.id);
381
+ if (options.fromProof && compiled.spec) {
382
+ const brief = emitFixFromProofBrief({
383
+ spec: compiled.spec,
384
+ proof: compiled.health.proof,
385
+ reportPath: "derived/proof-report.md",
386
+ implementBriefPath: "derived/implement-brief.md",
387
+ });
388
+ await mkdir(paths.derived, { recursive: true });
389
+ await writeFile(paths.fixFromProofBrief, brief, "utf8");
390
+ briefPath = paths.fixFromProofBrief;
391
+ prompt = fixFromProofPrompt(paths.fixFromProofBrief, paths.proofReport, paths.implementBrief);
392
+ }
393
+ const launch = await launchAdapter(adapter, repo.root, briefPath, {
394
+ onLogLine: options.onLogLine,
395
+ prompt,
396
+ });
397
+ const following = launch.ok && adapterLaunchesAgent(adapter) && Boolean(launch.finished);
398
+ if (following)
399
+ followImplementPid(launch.child?.pid);
400
+ await writeBuildRun(paths, {
401
+ specHash: compiled.spec ? specHash(compiled.spec) : "",
402
+ state: !launch.ok ? "failed" : following ? "running" : "succeeded",
403
+ adapter,
404
+ at: new Date().toISOString(),
405
+ message: launch.message,
406
+ ...(following && launch.child?.pid ? { pid: launch.child.pid } : {}),
407
+ });
408
+ return { result: await compilePack(paths), message: launch.message, launch };
409
+ }
410
+ export async function finishImplement(paths, launch, adapter) {
411
+ const done = launch.finished ? await launch.finished : { code: launch.ok ? 0 : 1 };
412
+ unfollowImplementPid(launch.child?.pid);
413
+ const compiled = await compilePack(paths);
414
+ const stopped = launch.stop?.reason;
415
+ const ok = !stopped && launch.ok && done.code === 0;
416
+ const name = adapterDisplayName(adapter);
417
+ const message = stopped
418
+ ? stopped
419
+ : ok
420
+ ? `${name} agent finished. Build Succeeded is not proof the app boots.`
421
+ : `${name} agent exited (${done.code ?? "unknown"}). ${tailImplementLog(paths)}`.trim();
422
+ await writeBuildRun(paths, {
423
+ specHash: compiled.spec ? specHash(compiled.spec) : "",
424
+ state: ok ? "succeeded" : "failed",
425
+ adapter,
426
+ at: new Date().toISOString(),
427
+ message,
428
+ });
429
+ return { result: await compilePack(paths), message };
430
+ }
431
+ export class StopImplementLockedError extends Error {
432
+ code = "stop_implement_gate";
433
+ constructor(message = "Stop is only while Implement is running.") {
434
+ super(message);
435
+ this.name = "StopImplementLockedError";
436
+ }
437
+ }
438
+ export async function stopImplement(paths, launch, reason = IMPLEMENT_STOPPED) {
439
+ if (!launch.child && !launch.finished) {
440
+ throw new StopImplementLockedError();
441
+ }
442
+ const stop = launch.stop ?? (launch.stop = {});
443
+ requestImplementStop(launch.child, stop, reason);
444
+ const compiled = await compilePack(paths);
445
+ const previous = await readBuildRun(paths);
446
+ await writeBuildRun(paths, {
447
+ specHash: compiled.spec ? specHash(compiled.spec) : "",
448
+ state: "failed",
449
+ adapter: previous?.adapter ?? "cursor",
450
+ at: new Date().toISOString(),
451
+ message: reason,
452
+ });
453
+ return { result: await compilePack(paths), message: reason };
454
+ }
455
+ export async function ignoreBuild(paths, successful) {
456
+ const compiled = await compilePack(paths);
457
+ if (!ignoreBuildAllowed(compiled.health)) {
458
+ throw new IgnoreBuildLockedError();
459
+ }
460
+ const previous = await readBuildRun(paths);
461
+ await writeBuildRun(paths, {
462
+ specHash: compiled.spec ? specHash(compiled.spec) : previous?.specHash ?? "",
463
+ state: successful ? "succeeded" : "failed",
464
+ adapter: previous?.adapter ?? "cursor",
465
+ at: new Date().toISOString(),
466
+ message: successful
467
+ ? "Owner marked Build successful after Ignore."
468
+ : previous?.message ?? "Owner ignored this failed Build.",
469
+ ignored: true,
470
+ });
471
+ const result = await compilePack(paths);
472
+ return {
473
+ result,
474
+ message: successful
475
+ ? "Build marked successful. Prove is unlocked."
476
+ : "Build stays failed. Prove is unlocked.",
477
+ };
478
+ }
479
+ async function writeBuildRun(paths, run) {
480
+ await mkdir(paths.derived, { recursive: true });
481
+ await writeFile(paths.buildRun, `${JSON.stringify(run, null, 2)}\n`, "utf8");
482
+ }
483
+ function tailImplementLog(paths) {
484
+ try {
485
+ return readFileSync(path.join(paths.derived, "implement-agent.log"), "utf8")
486
+ .trim()
487
+ .split(/\r?\n/)
488
+ .slice(-3)
489
+ .join(" ")
490
+ .slice(0, 280);
491
+ }
492
+ catch {
493
+ return "";
494
+ }
495
+ }
496
+ export async function writeImproveBrief(paths, compiled) {
497
+ const result = compiled ?? (await compilePack(paths));
498
+ assertImproveAllowed(result.health.ready);
499
+ const findings = improveFindings(result.health.ready);
500
+ const brief = emitImproveBrief({
501
+ spec: result.spec,
502
+ ready: result.health.ready,
503
+ findings,
504
+ });
505
+ await mkdir(paths.derived, { recursive: true });
506
+ await writeFile(paths.improveBrief, brief, "utf8");
507
+ await beginImproveReview(paths);
508
+ if (findings.length)
509
+ await recordImprovePending(paths, findings);
510
+ return { result, brief };
511
+ }
512
+ export async function launchImprove(paths, options = {}) {
513
+ const repo = await inspectProductRepo(paths.root);
514
+ const adapter = options.adapter ?? (repo.adapterRecorded && adapterLaunchesAgent(repo.adapter) ? repo.adapter : "manual");
515
+ const name = adapterDisplayName(adapter);
516
+ return launchAdapter(adapter, repo.root, paths.improveBrief, {
517
+ prompt: improvePrompt(paths.improveBrief),
518
+ openIde: false,
519
+ successMessage: adapter === "manual"
520
+ ? "Wrote derived/improve-brief.md. Open it in any coding agent."
521
+ : `Started a ${name} agent. The cockpit will show a diff when the spec changes.`,
522
+ });
523
+ }
524
+ export async function improvePack(paths, options = {}) {
525
+ const written = await writeImproveBrief(paths);
526
+ const launch = await launchImprove(paths, options);
527
+ return { result: written.result, message: launch.message, brief: written.brief };
528
+ }
529
+ export async function writeRequirement(paths, markdown) {
530
+ if (await readImproveSnapshot(paths)) {
531
+ throw new ImproveReviewPendingError();
532
+ }
533
+ await mkdir(paths.root, { recursive: true });
534
+ await writeFile(paths.requirement, markdown, "utf8");
535
+ return compilePack(paths);
536
+ }
537
+ export async function loadRuntime(paths) {
538
+ try {
539
+ const text = await readFile(paths.runtime, "utf8");
540
+ if (!text.trim())
541
+ return { ok: false, missing: true };
542
+ return parseRuntimeYaml(text);
543
+ }
544
+ catch {
545
+ return { ok: false, missing: true };
546
+ }
547
+ }
548
+ async function readProofRun(paths) {
549
+ try {
550
+ const raw = JSON.parse(await readFile(paths.proofRun, "utf8"));
551
+ if (!raw.specHash || !Array.isArray(raw.cases) || !raw.boot)
552
+ return null;
553
+ return raw;
554
+ }
555
+ catch {
556
+ return null;
557
+ }
558
+ }
559
+ export async function provePack(paths, deps = {}) {
560
+ const compiled = await compilePack(paths);
561
+ assertProveAllowed(compiled);
562
+ const runtime = await loadRuntime(paths);
563
+ if (!runtime.ok || !compiled.spec || !compiled.qaPlan) {
564
+ throw new ProveLockedError("Prove is locked without fixtures/runtime.yaml (baseUrl and deterministic login).");
565
+ }
566
+ await mkdir(paths.derived, { recursive: true });
567
+ await writeFile(paths.proveLog, "");
568
+ let writing = Promise.resolve();
569
+ const onProgress = (message, level = "info") => {
570
+ const line = `${new Date().toISOString()} ${level} ${message}\n`;
571
+ writing = writing.then(() => appendFile(paths.proveLog, line)).catch(() => { });
572
+ deps.onProgress?.(message, level);
573
+ };
574
+ const personas = await loadPersonas(paths);
575
+ const repo = await inspectProductRepo(paths.root);
576
+ const buildRun = await readBuildRun(paths);
577
+ const buildAt = compiled.health.build.owned !== false && compiled.health.build.state === "succeeded"
578
+ ? buildRun?.at
579
+ : undefined;
580
+ const run = await provePlan({
581
+ spec: compiled.spec,
582
+ plan: compiled.qaPlan,
583
+ runtime: runtime.runtime,
584
+ personas,
585
+ productRoot: repo.root,
586
+ buildAt,
587
+ }, { ...deps, onProgress });
588
+ await persistProofRun(paths, run, emitProofReport({
589
+ spec: compiled.spec,
590
+ plan: compiled.qaPlan,
591
+ run,
592
+ ready: compiled.health.ready,
593
+ baseUrl: runtime.runtime.baseUrl,
594
+ }));
595
+ onProgress("Wrote derived/proof-report.md.", "ok");
596
+ const result = await compilePack(paths);
597
+ const failed = run.cases.filter((item) => item.verdict === "fail").length;
598
+ const review = run.cases.filter((item) => item.verdict === "review").length;
599
+ const message = !run.boot.ok
600
+ ? (run.boot.message ?? "Proof boot failed.")
601
+ : failed
602
+ ? `Proof failed (${failed} case${failed === 1 ? "" : "s"}).`
603
+ : review
604
+ ? `Proof needs review (${review} case${review === 1 ? "" : "s"}).`
605
+ : `Proof passed (${run.cases.length} case${run.cases.length === 1 ? "" : "s"}).`;
606
+ onProgress(message, !run.boot.ok || failed ? "error" : review ? "info" : "ok");
607
+ await writing;
608
+ return { result, message };
609
+ }
@@ -0,0 +1,13 @@
1
+ import type { Finding, SpecAst } from "./types.js";
2
+ export type Persona = {
3
+ role: string;
4
+ email: string;
5
+ password?: string;
6
+ };
7
+ export type PersonasResult = {
8
+ personas: Map<string, Persona>;
9
+ findings: Finding[];
10
+ missingFile: boolean;
11
+ };
12
+ export declare function parsePersonasYaml(source: string): PersonasResult;
13
+ export declare function missingPersonaRoles(spec: SpecAst, personas: PersonasResult): string[];