@richjava/req0 0.1.0 → 0.3.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/dist/implement.js CHANGED
@@ -10,6 +10,9 @@ export const IMPLEMENT_MAX_MS = 20 * 60 * 1000;
10
10
  export const IMPLEMENT_STOPPED = "Owner stopped Implement.";
11
11
  export const IMPLEMENT_SANDBOX_CAP = `Stopped after ${IMPLEMENT_SANDBOX_MAX} sandbox deploys. Reimplement or Ignore, then Prove.`;
12
12
  export const IMPLEMENT_TIME_CAP = `Stopped after ${IMPLEMENT_MAX_MS / 60_000} minutes. Reimplement or Ignore, then Prove.`;
13
+ /** Cursor `--print` can emit `result` and then hang. Kill the leftover process after this grace. */
14
+ export const IMPLEMENT_EXIT_GRACE_MS = 3_000;
15
+ const AGENT_LOG_LINE_MAX = 65_536;
13
16
  export class ImplementLockedError extends Error {
14
17
  code = "ready_gate";
15
18
  constructor(message = "Implement is locked until Ready is Ready. Check this spec with Jev first.") {
@@ -41,6 +44,7 @@ export function implementPrompt(briefPath, stackId) {
41
44
  "Implement this requirement from the brief.",
42
45
  `Read ${briefPath} and derived/spec.json.`,
43
46
  "Do not invent spec IDs. Implement only the named BR- and UC- IDs.",
47
+ "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.",
44
48
  "If this product repo has no customer app, use the stack recorded in req0.json.",
45
49
  "Seed the app from existing fixtures/personas.yaml. Do not invent personas.",
46
50
  "Finish fixtures/runtime.yaml so baseUrl, startCommand, and resetCommand match the app. Keep login selectors unless you change /login to match.",
@@ -57,6 +61,7 @@ export function fixFromProofPrompt(briefPath, reportPath, implementBriefPath) {
57
61
  "Fix the existing product from the last Prove.",
58
62
  `Read ${briefPath}, then ${reportPath}, then ${implementBriefPath}.`,
59
63
  "Close only the Failed and Needs review cases. Do not invent spec IDs.",
64
+ "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.",
60
65
  "Do not edit requirement.md. Do not scaffold a second application.",
61
66
  "Boot or Sign-in observations may be fixtures or runtime.yaml, not a missing control.",
62
67
  "Do not treat this launch as proof the app boots.",
@@ -70,6 +75,7 @@ export function improvePrompt(briefPath) {
70
75
  "Patch requirement.md only. If the brief asks for a persona, you may also edit fixtures/personas.yaml.",
71
76
  "Outcome is what a person sees. Do not paste matrix allow/deny cells into Outcome. Look for is deny; Choose is allow.",
72
77
  "Do not invent spec IDs. Do not implement the product app.",
78
+ "If a required decision is missing, write derived/agent-questions.json and stop. Do not guess. Do not patch requirement.md in that same turn.",
73
79
  "Stop after the patch so the owner can review the diff, then Check with Jev.",
74
80
  ].join(" ");
75
81
  }
@@ -288,6 +294,7 @@ function launchLogged(run, bin, args, cwd, logPath, deps) {
288
294
  sandboxMax: deps.sandboxMax ?? IMPLEMENT_SANDBOX_MAX,
289
295
  maxMs: deps.maxMs ?? IMPLEMENT_MAX_MS,
290
296
  heartbeatLabel: deps.heartbeatLabel ?? `${deps.cliName ?? "Cursor"} agent still running.`,
297
+ exitGraceMs: deps.exitGraceMs ?? IMPLEMENT_EXIT_GRACE_MS,
291
298
  });
292
299
  child.once("error", (err) => {
293
300
  resolve({
@@ -310,9 +317,25 @@ export function attachAgentLog(child, logPath, onLogLine, control = {}) {
310
317
  const sandboxMax = control.sandboxMax ?? IMPLEMENT_SANDBOX_MAX;
311
318
  const maxMs = control.maxMs ?? IMPLEMENT_MAX_MS;
312
319
  const heartbeatLabel = control.heartbeatLabel ?? "Agent still running.";
320
+ const exitGraceMs = control.exitGraceMs ?? IMPLEMENT_EXIT_GRACE_MS;
313
321
  let lastEmit = Date.now();
314
322
  let lastShown = "";
315
323
  let sandboxStarts = 0;
324
+ let settled = false;
325
+ let heartbeat;
326
+ let deadline;
327
+ let hangKill;
328
+ let settle = () => undefined;
329
+ const finish = (code) => {
330
+ if (settled)
331
+ return;
332
+ settled = true;
333
+ if (heartbeat)
334
+ clearInterval(heartbeat);
335
+ if (deadline)
336
+ clearTimeout(deadline);
337
+ settle({ code });
338
+ };
316
339
  const feed = makeLineFeeder((line) => {
317
340
  if (isSandboxOnceStart(line)) {
318
341
  sandboxStarts += 1;
@@ -326,16 +349,26 @@ export function attachAgentLog(child, logPath, onLogLine, control = {}) {
326
349
  return;
327
350
  }
328
351
  }
329
- const text = summarizeAgentLine(redactSecrets(line));
330
- if (!text || text === lastShown)
352
+ const raw = redactSecrets(line);
353
+ const outcome = agentStreamOutcome(raw);
354
+ const text = summarizeAgentLine(raw);
355
+ if (text && text !== lastShown) {
356
+ lastShown = text;
357
+ lastEmit = Date.now();
358
+ onLogLine?.(text);
359
+ }
360
+ if (!outcome || settled)
331
361
  return;
332
- lastShown = text;
333
- lastEmit = Date.now();
334
- onLogLine?.(text);
362
+ finish(outcome === "success" ? 0 : 1);
363
+ hangKill = setTimeout(() => {
364
+ if (child.exitCode === null || child.exitCode === undefined)
365
+ killImplementTree(child);
366
+ }, Math.max(0, exitGraceMs));
367
+ hangKill.unref?.();
335
368
  });
336
- const heartbeat = onLogLine
369
+ heartbeat = onLogLine
337
370
  ? setInterval(() => {
338
- if (Date.now() - lastEmit < 20_000)
371
+ if (settled || Date.now() - lastEmit < 20_000)
339
372
  return;
340
373
  lastEmit = Date.now();
341
374
  lastShown = heartbeatLabel;
@@ -343,16 +376,17 @@ export function attachAgentLog(child, logPath, onLogLine, control = {}) {
343
376
  }, 5_000)
344
377
  : undefined;
345
378
  heartbeat?.unref?.();
346
- const deadline = maxMs > 0
347
- ? setTimeout(() => {
348
- requestImplementStop(child, stop, IMPLEMENT_TIME_CAP);
349
- if (IMPLEMENT_TIME_CAP !== lastShown) {
350
- lastShown = IMPLEMENT_TIME_CAP;
351
- lastEmit = Date.now();
352
- onLogLine?.(IMPLEMENT_TIME_CAP);
353
- }
354
- }, maxMs)
355
- : undefined;
379
+ deadline =
380
+ maxMs > 0
381
+ ? setTimeout(() => {
382
+ requestImplementStop(child, stop, IMPLEMENT_TIME_CAP);
383
+ if (IMPLEMENT_TIME_CAP !== lastShown) {
384
+ lastShown = IMPLEMENT_TIME_CAP;
385
+ lastEmit = Date.now();
386
+ onLogLine?.(IMPLEMENT_TIME_CAP);
387
+ }
388
+ }, maxMs)
389
+ : undefined;
356
390
  deadline?.unref?.();
357
391
  child.stdout?.on("data", (chunk) => {
358
392
  stream.write(chunk);
@@ -363,14 +397,17 @@ export function attachAgentLog(child, logPath, onLogLine, control = {}) {
363
397
  feed(chunk);
364
398
  });
365
399
  return new Promise((resolve) => {
400
+ settle = resolve;
366
401
  child.once("close", (code) => {
402
+ if (hangKill)
403
+ clearTimeout(hangKill);
367
404
  if (heartbeat)
368
405
  clearInterval(heartbeat);
369
406
  if (deadline)
370
407
  clearTimeout(deadline);
371
408
  feed("\n");
372
409
  stream.end();
373
- resolve({ code });
410
+ finish(code);
374
411
  });
375
412
  });
376
413
  }
@@ -421,6 +458,20 @@ export function isSandboxOnceStart(line) {
421
458
  return false;
422
459
  }
423
460
  }
461
+ export function agentStreamOutcome(line) {
462
+ const text = line.trim();
463
+ if (!text.startsWith("{"))
464
+ return null;
465
+ try {
466
+ const event = JSON.parse(text);
467
+ if (event.type !== "result")
468
+ return null;
469
+ return event.is_error === true || event.subtype === "error" ? "error" : "success";
470
+ }
471
+ catch {
472
+ return null;
473
+ }
474
+ }
424
475
  export function summarizeAgentLine(line) {
425
476
  const text = line.trim();
426
477
  if (!text)
@@ -573,7 +624,7 @@ function makeLineFeeder(onLine) {
573
624
  for (const line of lines) {
574
625
  const text = line.trim();
575
626
  if (text)
576
- onLine(text.slice(0, 280));
627
+ onLine(text.length > AGENT_LOG_LINE_MAX ? text.slice(0, AGENT_LOG_LINE_MAX) : text);
577
628
  }
578
629
  };
579
630
  }
@@ -590,7 +641,7 @@ async function waitForAgent(child, settleMs, logPath, bin, agentName = "Cursor")
590
641
  if (settleMs > 0) {
591
642
  await new Promise((resolve) => setTimeout(resolve, settleMs));
592
643
  }
593
- if (!child || child.exitCode === null || child.exitCode === undefined) {
644
+ if (!child || child.exitCode === null || child.exitCode === undefined || child.exitCode === 0) {
594
645
  return { ok: true, message: "started" };
595
646
  }
596
647
  const tail = tailLog(logPath);
package/dist/improve.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { NOUL_PASS } from "./gates.js";
2
+ import { questionsBriefSection } from "./agent-questions.js";
2
3
  export class ImproveLockedError extends Error {
3
4
  code = "improve_gate";
4
5
  constructor(message = "Improve it is only when Ready is blocked or pack noul is below 0.75.") {
@@ -52,7 +53,7 @@ export function emitImproveBrief(input) {
52
53
  `# Improve: ${input.spec?.requirementId ?? "requirement"}`,
53
54
  "",
54
55
  "Opinionated writer pass. Patch the pack so a coding agent can implement without guessing.",
55
- "Do not interview the owner. Apply the rules below to every named finding in one diff.",
56
+ "If a required decision is missing, write derived/agent-questions.json and stop. Do not guess. Do not patch requirement.md in that same turn.",
56
57
  "",
57
58
  "## Goal",
58
59
  "",
@@ -87,8 +88,8 @@ export function emitImproveBrief(input) {
87
88
  lines.push("");
88
89
  }
89
90
  lines.push("## Opinionated rules", "", "- Rewrite every Outcome to what a person sees after the steps: a status or label, and whether a named control is present, absent, or disabled.", "- Tighten every rule Observable so a person or test can notice it.", "- `Choose …` is an allow path. `Look for …` is a deny path. Do not invert a use case to match a matrix cell.", "- A matrix allow cell plus a business rule that hides or disables the control is consistent. Keep those Look-for use cases.", "- Do not write matrix talk in Outcome or Entities: no `is allow`, `is deny`, no restating action cells, no `without changing the matrix cell`.", "- Name the exact Choose / Look for / Select controls. State tester preconditions.", personas
90
- ? "- Missing persona: add `email: <role-slug>@example.test` and `password: test-only-not-production` in fixtures/personas.yaml."
91
- : "- Do not add personas unless a finding is persona_missing.", "- You may edit every section the findings name. This is one pack pass.", "", "## Fence", "", "- Patch `requirement.md` only, then stop.", personas
91
+ ? "- 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
92
93
  ? "- At least one finding is a missing persona: you may also edit `fixtures/personas.yaml`."
93
94
  : "- Do not add files except the patch to `requirement.md`.", "- Do not invent spec IDs.", "- Do not implement the product app.", "- Stop after the patch so the owner can review the diff, then Check with Jev. Do not Check yourself.", "");
94
95
  return `${lines.join("\n")}\n`;
package/dist/pack.d.ts CHANGED
@@ -29,8 +29,10 @@ export type PackPaths = {
29
29
  proofRun: string;
30
30
  proofReport: string;
31
31
  proveLog: string;
32
+ agentQuestions: string;
32
33
  };
33
34
  export declare function packPaths(root: string): PackPaths;
35
+ export declare function withRememberedAnswers(paths: PackPaths, prompt: string): Promise<string>;
34
36
  export declare function isPackDir(dir: string): Promise<boolean>;
35
37
  export declare function resolveCockpitPack(cwd: string): Promise<PackPaths | null>;
36
38
  export declare function resolvePack(cwd: string): Promise<PackPaths | null>;
@@ -41,6 +43,8 @@ export declare function readMarkdown(paths: PackPaths): Promise<string>;
41
43
  export declare function loadPersonas(paths: PackPaths): Promise<PersonasResult>;
42
44
  export declare function compilePack(paths: PackPaths): Promise<CompileResult>;
43
45
  export declare function checkPack(paths: PackPaths, client?: JevClient): Promise<CompileResult>;
46
+ export declare function isPackWatchInput(filename: string): boolean;
47
+ export declare function shouldRefreshForWatch(watchPath: string, filename?: string | Buffer | null): boolean;
44
48
  export declare function persistDerived(paths: PackPaths, result: CompileResult): Promise<void>;
45
49
  export declare function createPack(root: string): Promise<PackPaths>;
46
50
  export declare function deletePack(paths: PackPaths): Promise<void>;
@@ -50,6 +54,8 @@ export declare function implementPack(paths: PackPaths, options?: {
50
54
  stack?: string;
51
55
  fromProof?: boolean;
52
56
  onLogLine?: (line: string) => void;
57
+ extraPrompt?: string;
58
+ resume?: boolean;
53
59
  }): Promise<{
54
60
  result: CompileResult;
55
61
  message: string;
@@ -63,7 +69,7 @@ export declare class StopImplementLockedError extends Error {
63
69
  readonly code = "stop_implement_gate";
64
70
  constructor(message?: string);
65
71
  }
66
- export declare function stopImplement(paths: PackPaths, launch: LaunchAdapterResult, reason?: string): Promise<{
72
+ export declare function stopImplement(paths: PackPaths, launch: LaunchAdapterResult | null, reason?: string): Promise<{
67
73
  result: CompileResult;
68
74
  message: string;
69
75
  }>;
@@ -77,9 +83,21 @@ export declare function writeImproveBrief(paths: PackPaths, compiled?: CompileRe
77
83
  }>;
78
84
  export declare function launchImprove(paths: PackPaths, options?: {
79
85
  adapter?: AdapterId;
86
+ extraPrompt?: string;
87
+ }): Promise<LaunchAdapterResult>;
88
+ export declare function answerAgentQuestions(paths: PackPaths, answers: Record<string, string>, options?: {
89
+ adapter?: AdapterId;
90
+ onLogLine?: (line: string) => void;
80
91
  }): Promise<{
81
- ok: boolean;
92
+ result: CompileResult;
93
+ message: string;
94
+ channel: "improve" | "implement";
95
+ launch?: LaunchAdapterResult;
96
+ }>;
97
+ export declare function discardAgentQuestions(paths: PackPaths, launch: LaunchAdapterResult | null): Promise<{
98
+ result: CompileResult;
82
99
  message: string;
100
+ channel: "improve" | "implement";
83
101
  }>;
84
102
  export declare function improvePack(paths: PackPaths, options?: {
85
103
  adapter?: AdapterId;
package/dist/pack.js CHANGED
@@ -7,7 +7,7 @@ import { assertImplementAllowed, ImplementDisabledError, fixFromProofPrompt, imp
7
7
  import { assertFixFromProofAllowed, emitFixFromProofBrief, FixFromProofLockedError } from "./fix-from-proof.js";
8
8
  import { assertImproveAllowed, emitImproveBrief, improveFindings } from "./improve.js";
9
9
  import { clearImproveLog, readImproveLog, recordImprovePending } from "./improve-log.js";
10
- import { beginImproveReview, ImproveReviewPendingError, readImproveSnapshot } from "./improve-review.js";
10
+ import { beginImproveReview, ImproveReviewPendingError, readImproveSnapshot, rejectImproveReview } from "./improve-review.js";
11
11
  import { emitImplementBrief } from "./implement-brief.js";
12
12
  import { hasJevAccess, JevRequestError, JevUnavailableError, resolveJevClient } from "./jev.js";
13
13
  import { emitJevPack } from "./jev-pack.js";
@@ -20,6 +20,7 @@ import { ignoreBuildAllowed, packListMeters } from "./stages.js";
20
20
  import { parseRuntimeYaml } from "./runtime.js";
21
21
  import { inspectProductRepo, needsStackChoice, resolveStackId, StackRequiredError, UnknownStackError, writeAmplifyEnvExampleIfMissing, writeReq0Config, } from "./stack.js";
22
22
  import { loadStarterRequirement, PERSONAS_STUB, RUNTIME_STUB } from "./template.js";
23
+ import { AGENT_QUESTIONS_WAITING, AgentAnswersError, applyAnswers, clearAgentQuestions, isOpenQuestions, readAgentQuestions, withOwnerAnswers, writeAgentQuestions, } from "./agent-questions.js";
23
24
  export const REQUIREMENT_FILE = "requirement.md";
24
25
  export const PERSONAS_FILE = path.join("fixtures", "personas.yaml");
25
26
  export const RUNTIME_FILE = path.join("fixtures", "runtime.yaml");
@@ -48,8 +49,15 @@ export function packPaths(root) {
48
49
  proofRun: path.join(derived, "proof-run.json"),
49
50
  proofReport: path.join(derived, "proof-report.md"),
50
51
  proveLog: path.join(derived, "prove-run.log"),
52
+ agentQuestions: path.join(derived, "agent-questions.json"),
51
53
  };
52
54
  }
55
+ export async function withRememberedAnswers(paths, prompt) {
56
+ const round = await readAgentQuestions(paths);
57
+ if (!round || round.status !== "answered" || round.channel !== "implement")
58
+ return prompt;
59
+ return withOwnerAnswers(prompt, round);
60
+ }
53
61
  export async function isPackDir(dir) {
54
62
  try {
55
63
  await access(path.join(dir, REQUIREMENT_FILE));
@@ -201,6 +209,7 @@ export async function compilePack(paths) {
201
209
  }
202
210
  const buildRun = await readBuildRun(paths);
203
211
  if (buildRun?.state === "running" &&
212
+ !buildRun.waitingOnQuestions &&
204
213
  !isFollowedImplement(buildRun.pid) &&
205
214
  implementProcessGone(buildRun.pid)) {
206
215
  await writeBuildRun(paths, {
@@ -273,22 +282,45 @@ export async function checkPack(paths, client) {
273
282
  throw new JevRequestError(err instanceof Error ? err.message : "Jev request failed.");
274
283
  }
275
284
  }
285
+ export function isPackWatchInput(filename) {
286
+ const relative = filename.replaceAll("\\", "/").replace(/^\.\//, "");
287
+ if (!relative || relative.split("/").includes("derived"))
288
+ return false;
289
+ const base = path.posix.basename(relative);
290
+ return base === REQUIREMENT_FILE || base === path.posix.basename(PERSONAS_FILE) || base === path.posix.basename(RUNTIME_FILE);
291
+ }
292
+ export function shouldRefreshForWatch(watchPath, filename) {
293
+ const relative = typeof filename === "string" ? filename : Buffer.isBuffer(filename) ? filename.toString("utf8") : "";
294
+ if (relative.trim())
295
+ return isPackWatchInput(relative);
296
+ return isPackWatchInput(path.basename(watchPath));
297
+ }
276
298
  export async function persistDerived(paths, result) {
277
299
  await mkdir(paths.derived, { recursive: true });
278
300
  if (result.spec) {
279
- await writeFile(paths.spec, `${JSON.stringify(result.spec, null, 2)}\n`, "utf8");
301
+ await writeIfChanged(paths.spec, `${JSON.stringify(result.spec, null, 2)}\n`);
280
302
  }
281
303
  if (result.jevPack) {
282
- await writeFile(paths.jevPack, `${JSON.stringify(result.jevPack, null, 2)}\n`, "utf8");
304
+ await writeIfChanged(paths.jevPack, `${JSON.stringify(result.jevPack, null, 2)}\n`);
283
305
  }
284
306
  if (result.implementBrief) {
285
- await writeFile(paths.implementBrief, result.implementBrief, "utf8");
307
+ await writeIfChanged(paths.implementBrief, result.implementBrief);
286
308
  }
287
309
  if (result.qaPlan) {
288
- await writeFile(paths.qaPlan, emitQaPlanYaml(result.qaPlan), "utf8");
310
+ await writeIfChanged(paths.qaPlan, emitQaPlanYaml(result.qaPlan));
311
+ }
312
+ await writeIfChanged(paths.health, `${JSON.stringify(result.health, null, 2)}\n`);
313
+ await writeIfChanged(paths.status, healthToStatusMarkdown(result.health));
314
+ }
315
+ async function writeIfChanged(file, contents) {
316
+ try {
317
+ if ((await readFile(file, "utf8")) === contents)
318
+ return;
319
+ }
320
+ catch {
321
+ // missing
289
322
  }
290
- await writeFile(paths.health, `${JSON.stringify(result.health, null, 2)}\n`, "utf8");
291
- await writeFile(paths.status, healthToStatusMarkdown(result.health), "utf8");
323
+ await writeFile(file, contents, "utf8");
292
324
  }
293
325
  async function readJevRun(paths, spec) {
294
326
  try {
@@ -344,7 +376,7 @@ export async function writeRuntimeStubIfMissing(paths) {
344
376
  async function readBuildRun(paths) {
345
377
  try {
346
378
  const raw = JSON.parse(await readFile(paths.buildRun, "utf8"));
347
- if (!raw.specHash || !raw.state)
379
+ if (typeof raw.specHash !== "string" || !raw.state)
348
380
  return null;
349
381
  return raw;
350
382
  }
@@ -354,8 +386,11 @@ async function readBuildRun(paths) {
354
386
  }
355
387
  export async function implementPack(paths, options = {}) {
356
388
  const compiled = await compilePack(paths);
389
+ if (!options.resume && isOpenQuestions(await readAgentQuestions(paths))) {
390
+ throw new AgentAnswersError("Answer the agent's questions, or Stop, before starting a new Implement.");
391
+ }
357
392
  assertImplementAllowed(compiled);
358
- if (options.fromProof) {
393
+ if (options.fromProof && !options.resume) {
359
394
  assertFixFromProofAllowed(compiled.health, compiled.health.ready);
360
395
  if (!compiled.spec)
361
396
  throw new FixFromProofLockedError();
@@ -390,6 +425,9 @@ export async function implementPack(paths, options = {}) {
390
425
  briefPath = paths.fixFromProofBrief;
391
426
  prompt = fixFromProofPrompt(paths.fixFromProofBrief, paths.proofReport, paths.implementBrief);
392
427
  }
428
+ prompt = await withRememberedAnswers(paths, prompt);
429
+ if (options.extraPrompt)
430
+ prompt = `${prompt}\n\n${options.extraPrompt}`;
393
431
  const launch = await launchAdapter(adapter, repo.root, briefPath, {
394
432
  onLogLine: options.onLogLine,
395
433
  prompt,
@@ -404,6 +442,7 @@ export async function implementPack(paths, options = {}) {
404
442
  at: new Date().toISOString(),
405
443
  message: launch.message,
406
444
  ...(following && launch.child?.pid ? { pid: launch.child.pid } : {}),
445
+ ...(options.fromProof ? { fromProof: true } : {}),
407
446
  });
408
447
  return { result: await compilePack(paths), message: launch.message, launch };
409
448
  }
@@ -411,7 +450,21 @@ export async function finishImplement(paths, launch, adapter) {
411
450
  const done = launch.finished ? await launch.finished : { code: launch.ok ? 0 : 1 };
412
451
  unfollowImplementPid(launch.child?.pid);
413
452
  const compiled = await compilePack(paths);
453
+ const previous = await readBuildRun(paths);
414
454
  const stopped = launch.stop?.reason;
455
+ const waiting = !stopped && isOpenQuestions(await readAgentQuestions(paths));
456
+ if (waiting) {
457
+ await writeBuildRun(paths, {
458
+ specHash: compiled.spec ? specHash(compiled.spec) : previous?.specHash ?? "",
459
+ state: "running",
460
+ adapter,
461
+ at: new Date().toISOString(),
462
+ message: AGENT_QUESTIONS_WAITING,
463
+ waitingOnQuestions: true,
464
+ ...(previous?.fromProof ? { fromProof: true } : {}),
465
+ });
466
+ return { result: await compilePack(paths), message: AGENT_QUESTIONS_WAITING };
467
+ }
415
468
  const ok = !stopped && launch.ok && done.code === 0;
416
469
  const name = adapterDisplayName(adapter);
417
470
  const message = stopped
@@ -425,6 +478,7 @@ export async function finishImplement(paths, launch, adapter) {
425
478
  adapter,
426
479
  at: new Date().toISOString(),
427
480
  message,
481
+ ...(previous?.fromProof ? { fromProof: true } : {}),
428
482
  });
429
483
  return { result: await compilePack(paths), message };
430
484
  }
@@ -436,11 +490,15 @@ export class StopImplementLockedError extends Error {
436
490
  }
437
491
  }
438
492
  export async function stopImplement(paths, launch, reason = IMPLEMENT_STOPPED) {
439
- if (!launch.child && !launch.finished) {
493
+ const waiting = isOpenQuestions(await readAgentQuestions(paths));
494
+ if (!waiting && !launch?.child && !launch?.finished) {
440
495
  throw new StopImplementLockedError();
441
496
  }
442
- const stop = launch.stop ?? (launch.stop = {});
443
- requestImplementStop(launch.child, stop, reason);
497
+ if (launch?.child || launch?.finished) {
498
+ const stop = launch.stop ?? (launch.stop = {});
499
+ requestImplementStop(launch.child, stop, reason);
500
+ }
501
+ await clearAgentQuestions(paths);
444
502
  const compiled = await compilePack(paths);
445
503
  const previous = await readBuildRun(paths);
446
504
  await writeBuildRun(paths, {
@@ -449,6 +507,7 @@ export async function stopImplement(paths, launch, reason = IMPLEMENT_STOPPED) {
449
507
  adapter: previous?.adapter ?? "cursor",
450
508
  at: new Date().toISOString(),
451
509
  message: reason,
510
+ ...(previous?.fromProof ? { fromProof: true } : {}),
452
511
  });
453
512
  return { result: await compilePack(paths), message: reason };
454
513
  }
@@ -494,6 +553,9 @@ function tailImplementLog(paths) {
494
553
  }
495
554
  }
496
555
  export async function writeImproveBrief(paths, compiled) {
556
+ if (isOpenQuestions(await readAgentQuestions(paths))) {
557
+ throw new AgentAnswersError("Answer the agent's questions, or Stop, before starting a new Improve.");
558
+ }
497
559
  const result = compiled ?? (await compilePack(paths));
498
560
  assertImproveAllowed(result.health.ready);
499
561
  const findings = improveFindings(result.health.ready);
@@ -513,14 +575,67 @@ export async function launchImprove(paths, options = {}) {
513
575
  const repo = await inspectProductRepo(paths.root);
514
576
  const adapter = options.adapter ?? (repo.adapterRecorded && adapterLaunchesAgent(repo.adapter) ? repo.adapter : "manual");
515
577
  const name = adapterDisplayName(adapter);
578
+ const prompt = options.extraPrompt
579
+ ? `${improvePrompt(paths.improveBrief)}\n\n${options.extraPrompt}`
580
+ : improvePrompt(paths.improveBrief);
516
581
  return launchAdapter(adapter, repo.root, paths.improveBrief, {
517
- prompt: improvePrompt(paths.improveBrief),
582
+ prompt,
518
583
  openIde: false,
519
584
  successMessage: adapter === "manual"
520
585
  ? "Wrote derived/improve-brief.md. Open it in any coding agent."
521
586
  : `Started a ${name} agent. The cockpit will show a diff when the spec changes.`,
522
587
  });
523
588
  }
589
+ export async function answerAgentQuestions(paths, answers, options = {}) {
590
+ const open = await readAgentQuestions(paths);
591
+ if (!isOpenQuestions(open)) {
592
+ throw new AgentAnswersError("No open questions to answer.");
593
+ }
594
+ const answered = applyAnswers(open, answers);
595
+ await writeAgentQuestions(paths, answered);
596
+ const extraPrompt = withOwnerAnswers("", answered).trim();
597
+ if (answered.channel === "improve") {
598
+ const launch = await launchImprove(paths, { adapter: options.adapter, extraPrompt });
599
+ return {
600
+ result: await compilePack(paths),
601
+ message: launch.message,
602
+ channel: "improve",
603
+ launch: launch.ok && launch.finished ? launch : undefined,
604
+ };
605
+ }
606
+ const previous = await readBuildRun(paths);
607
+ const launched = await implementPack(paths, {
608
+ adapter: options.adapter ?? previous?.adapter,
609
+ fromProof: previous?.fromProof === true,
610
+ onLogLine: options.onLogLine,
611
+ resume: true,
612
+ });
613
+ return {
614
+ result: launched.result,
615
+ message: launched.message,
616
+ channel: "implement",
617
+ launch: launched.launch,
618
+ };
619
+ }
620
+ export async function discardAgentQuestions(paths, launch) {
621
+ const open = await readAgentQuestions(paths);
622
+ if (!isOpenQuestions(open)) {
623
+ throw new AgentAnswersError("No open questions to discard.");
624
+ }
625
+ if (open.channel === "implement") {
626
+ const stopped = await stopImplement(paths, launch);
627
+ return { result: stopped.result, message: stopped.message, channel: "implement" };
628
+ }
629
+ await clearAgentQuestions(paths);
630
+ if (await readImproveSnapshot(paths)) {
631
+ await rejectImproveReview(paths);
632
+ }
633
+ return {
634
+ result: await compilePack(paths),
635
+ message: "Discarded the agent's questions.",
636
+ channel: "improve",
637
+ };
638
+ }
524
639
  export async function improvePack(paths, options = {}) {
525
640
  const written = await writeImproveBrief(paths);
526
641
  const launch = await launchImprove(paths, options);
package/dist/ready.js CHANGED
@@ -29,6 +29,13 @@ export function evaluateBuild(spec, run) {
29
29
  };
30
30
  }
31
31
  if (run.state === "running" && !isFollowedImplement(run.pid)) {
32
+ if (run.waitingOnQuestions) {
33
+ return {
34
+ state: "running",
35
+ adapter: run.adapter,
36
+ message: run.message,
37
+ };
38
+ }
32
39
  return {
33
40
  state: "failed",
34
41
  adapter: run.adapter,
package/dist/server.d.ts CHANGED
@@ -6,7 +6,8 @@ export type AppState = {
6
6
  cwd: string;
7
7
  pack: PackPaths | null;
8
8
  last: CompileResult | null;
9
- activity: ActivityLine[];
9
+ implementActivity: ActivityLine[];
10
+ proveActivity: ActivityLine[];
10
11
  busy: "prove" | "improve" | "implement" | null;
11
12
  implementLaunch: LaunchAdapterResult | null;
12
13
  };