agent-dealer 1.4.1 → 1.4.3

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 (26) hide show
  1. package/bundle/server/dist/adapters/github.js +66 -3
  2. package/bundle/server/dist/adapters/github.test.js +90 -0
  3. package/bundle/server/dist/coordinator/auto-merge.js +17 -6
  4. package/bundle/server/dist/coordinator/commands.js +18 -2
  5. package/bundle/server/dist/coordinator/developer-effect.js +49 -7
  6. package/bundle/server/dist/coordinator/developer-effect.test.js +118 -4
  7. package/bundle/server/dist/coordinator/muse-developer.integration.test.js +2 -1
  8. package/bundle/server/dist/coordinator/operator-criteria.js +250 -17
  9. package/bundle/server/dist/coordinator/operator-criteria.test.js +177 -4
  10. package/bundle/server/dist/coordinator/operator-verification.integration.test.js +208 -0
  11. package/bundle/server/dist/coordinator/projection.js +5 -1
  12. package/bundle/server/dist/coordinator/prompts.js +77 -4
  13. package/bundle/server/dist/coordinator/prompts.test.js +22 -4
  14. package/bundle/server/dist/coordinator/reviewer-effect.js +64 -45
  15. package/bundle/server/dist/coordinator/reviewer-effect.test.js +63 -10
  16. package/bundle/server/dist/coordinator/reviewer-pr-evidence.test.js +245 -0
  17. package/bundle/server/dist/coordinator/reviewer-result.js +4 -3
  18. package/bundle/server/dist/coordinator/reviewer-result.test.js +6 -0
  19. package/bundle/server/dist/coordinator/routing.js +3 -0
  20. package/bundle/server/dist/coordinator/routing.test.js +19 -0
  21. package/bundle/server/dist/coordinator/usage.js +35 -2
  22. package/bundle/server/dist/coordinator/usage.test.js +49 -1
  23. package/bundle/server/dist/docs-api-reference.test.js +89 -0
  24. package/bundle/server/package.json +2 -2
  25. package/bundle/shared/package.json +1 -1
  26. package/package.json +1 -1
@@ -438,6 +438,214 @@ test("NOT-538: not_applicable visual evidence (no Visual workflow) on a UI head
438
438
  assert.deepEqual(calls, [{ cwd: managedCwd, number: 42 }]);
439
439
  assert.equal(getIssue(issueId).status, "done");
440
440
  });
441
+ test("NOT-575: an [agent] criterion that merely mentions [operator] never opens the gate", async () => {
442
+ const calls = [];
443
+ setMergePrForTests(async (opts) => {
444
+ calls.push(opts);
445
+ return { ok: true };
446
+ });
447
+ // The NOT-568 shape: the [agent] criterion's prose contains the string
448
+ // [operator], but its trailing tag is [agent] — not a gate.
449
+ const issueId = newIssue([
450
+ "- [ ] Verify the [operator] handoff renders for the agent review [agent]",
451
+ " Evidence: agent run | run the render test | green",
452
+ "- [ ] Docs describe the probe [agent]",
453
+ " Evidence: doc review | read the probe doc | command documented",
454
+ ].join("\n"));
455
+ startWorkflow(issueId);
456
+ const result = await approve(issueId);
457
+ assert.equal(result.applied, true);
458
+ if (result.applied) {
459
+ assert.equal(result.issueStatus, "done");
460
+ assert.equal(result.instanceCompleted, true);
461
+ }
462
+ assert.deepEqual(calls, [{ cwd: managedCwd, number: 42 }]);
463
+ assert.equal(getIssue(issueId).status, "done");
464
+ assert.equal(listHumanActionsForIssue(issueId).filter((a) => a.status === "open").length, 0);
465
+ });
466
+ test("NOT-575: a trailing-[operator] criterion with an Evidence line gates with the evidence in the action", async () => {
467
+ const calls = [];
468
+ setMergePrForTests(async (opts) => {
469
+ calls.push(opts);
470
+ return { ok: true };
471
+ });
472
+ const issueId = newIssue([
473
+ "- [ ] Agent can list sessions from the registry [agent]",
474
+ " Evidence: unit tests | run the registry suite | green",
475
+ "- [ ] Operator can sign in with SSO and see the org dashboard [operator]",
476
+ " Evidence: operator run | `npm run probe:sso -- --env staging` | dashboard lists orgs",
477
+ ].join("\n"));
478
+ startWorkflow(issueId);
479
+ await approve(issueId);
480
+ assert.equal(calls.length, 0, "the merge adapter must not run behind the gate");
481
+ assert.equal(getIssue(issueId).status, "needs_human");
482
+ const action = openOperatorAction(issueId);
483
+ assert.match(action.question, /sign in with SSO and see the org dashboard \[operator\]/);
484
+ assert.match(action.question, /Evidence: operator run \| `npm run probe:sso -- --env staging`/);
485
+ assert.doesNotMatch(action.question, /list sessions from the registry/);
486
+ const evidence = JSON.parse(action.evidenceJson);
487
+ assert.equal(evidence.operatorVerification.headSha, "abc123");
488
+ assert.equal(evidence.operatorVerification.criteria.length, 1);
489
+ assert.deepEqual(evidence.operatorVerification.criteria[0].commands, [
490
+ "Evidence: operator run | `npm run probe:sso -- --env staging` | dashboard lists orgs",
491
+ ]);
492
+ const resolved = await resolveHumanActionAndAdvanceAsync(action.id, "op", "verified", {
493
+ note: "SSO login OK — org dashboard listed 3 orgs.",
494
+ });
495
+ assert.equal(resolved.ok, true);
496
+ if (resolved.ok)
497
+ assert.equal(resolved.issueStatus, "done");
498
+ assert.equal(calls.length, 1);
499
+ assert.equal(getIssue(issueId).status, "done");
500
+ });
501
+ test("NOT-575: a result recorded for only one of two [operator] criteria still blocks the merge", async () => {
502
+ let merges = 0;
503
+ setMergePrForTests(async () => {
504
+ merges += 1;
505
+ return { ok: true };
506
+ });
507
+ const issueId = newIssue([
508
+ "- [ ] Operator can sign in with SSO [operator]",
509
+ " Evidence: operator run | `npm run probe:sso` | dashboard shown",
510
+ "- [ ] Operator can complete a paid checkout [operator]",
511
+ " Evidence: operator run | `npm run probe:checkout` | receipt shown",
512
+ ].join("\n"));
513
+ startWorkflow(issueId);
514
+ await approve(issueId);
515
+ assert.equal(merges, 0);
516
+ const action = openOperatorAction(issueId);
517
+ const evidence = JSON.parse(action.evidenceJson);
518
+ assert.equal(evidence.operatorVerification.criteria.length, 2);
519
+ // A result covering only the first criterion (same head) must not release
520
+ // the second — the gate still holds and reuses the open action.
521
+ createIssueArtifact({
522
+ issueId,
523
+ kind: "operator_verification",
524
+ author: "human",
525
+ content: {
526
+ headSha: "abc123",
527
+ note: "SSO login OK.",
528
+ verifiedBy: "op",
529
+ verifiedAt: new Date().toISOString(),
530
+ criteria: ["Operator can sign in with SSO [operator]"],
531
+ },
532
+ });
533
+ const stillBlocked = await finalizeAutoMerge(issueId);
534
+ assert.equal(stillBlocked.issueStatus, "needs_human");
535
+ assert.equal(stillBlocked.humanActionId, action.id, "the same head reuses the open action");
536
+ assert.equal(merges, 0);
537
+ // Resolving the gated action covers both listed criteria and merges.
538
+ const resolved = await resolveHumanActionAndAdvanceAsync(action.id, "op", "verified", {
539
+ note: "SSO login OK; paid checkout receipt shown.",
540
+ });
541
+ assert.equal(resolved.ok, true);
542
+ if (resolved.ok)
543
+ assert.equal(resolved.issueStatus, "done");
544
+ assert.equal(merges, 1);
545
+ const stored = listArtifactsForIssueByKind(issueId, "operator_verification");
546
+ // Newest first: [0] is the resolve-recorded result covering both criteria.
547
+ const recorded = JSON.parse(stored[0].contentJson);
548
+ assert.deepEqual(recorded.criteria, [
549
+ "Operator can sign in with SSO [operator]",
550
+ "Operator can complete a paid checkout [operator]",
551
+ ]);
552
+ });
553
+ test("NOT-575: a trailing-[operator] contract criterion gates even when the AC string diverges", async () => {
554
+ let merges = 0;
555
+ setMergePrForTests(async () => {
556
+ merges += 1;
557
+ return { ok: true };
558
+ });
559
+ // The contract carries the genuine trailing-[operator] tag while an
560
+ // explicitly-provided AC string has no tags at all — the gate must still
561
+ // flag the contract criterion (the Agent Deck program's missed-gate shape).
562
+ const description = [
563
+ "Ship the SSO probe.",
564
+ "",
565
+ "## Builder execution mode",
566
+ "bug fix",
567
+ "",
568
+ "## Non-goals",
569
+ "- Rewriting the installer",
570
+ "",
571
+ "## Exit predicate",
572
+ "SSO sign-in works with operator proof.",
573
+ "",
574
+ "## One-PR stopping point",
575
+ "Stop after the probe lands.",
576
+ "",
577
+ "## Acceptance criteria",
578
+ "- [ ] Agent lists sessions [agent]",
579
+ " Evidence: unit tests | run the registry suite | green",
580
+ "- [ ] Operator signs in with SSO [operator]",
581
+ " Evidence: operator run | paste the output | dashboard shown",
582
+ "",
583
+ ].join("\n");
584
+ const issueId = createIssue({
585
+ title: "SSO probe",
586
+ description,
587
+ acceptanceCriteria: "- [ ] Agent lists sessions\n- [ ] Operator signs in with SSO",
588
+ repo: "acme/app",
589
+ developerAgentId: BUILTIN_AGENT_CLAUDE_ID,
590
+ reviewerAgentId: BUILTIN_AGENT_CURSOR_ID,
591
+ baseBranch: "main",
592
+ maxReviewRounds: 3,
593
+ maxInfraAttempts: 3,
594
+ source: "manual",
595
+ autoMerge: true,
596
+ }).id;
597
+ startWorkflow(issueId);
598
+ await approve(issueId);
599
+ assert.equal(merges, 0, "the contract-tagged criterion must gate");
600
+ assert.equal(getIssue(issueId).status, "needs_human");
601
+ const action = openOperatorAction(issueId);
602
+ assert.match(action.question, /Operator signs in with SSO \[operator\]/);
603
+ const resolved = await resolveHumanActionAndAdvanceAsync(action.id, "op", "verified", {
604
+ note: "SSO login OK — dashboard shown.",
605
+ });
606
+ assert.equal(resolved.ok, true);
607
+ if (resolved.ok)
608
+ assert.equal(resolved.issueStatus, "done");
609
+ assert.equal(merges, 1);
610
+ });
611
+ test("NOT-575 repair 2: a Linear-escaped trailing \\[operator\\] gates and merges after verify", async () => {
612
+ const calls = [];
613
+ setMergePrForTests(async (opts) => {
614
+ calls.push(opts);
615
+ return { ok: true };
616
+ });
617
+ // The NOT-567/569-572 shape: Linear escapes the tag brackets, so the
618
+ // frozen text ends in `\]` — the gate must still flag the genuine
619
+ // operator criterion, while the escaped `\[agent\]` criterion whose prose
620
+ // mentions [operator] (the NOT-568 shape) must not appear in the action.
621
+ const issueId = newIssue([
622
+ "- [ ] Verify the `[operator]` handoff renders for the agent review \\[agent\\]",
623
+ " Evidence: agent run | run the render test | green",
624
+ "- [ ] Operator can sign in with SSO and see the org dashboard \\[operator\\]",
625
+ " Evidence: operator run | `npm run probe:sso -- --env staging` | dashboard lists orgs",
626
+ ].join("\n"));
627
+ startWorkflow(issueId);
628
+ await approve(issueId);
629
+ assert.equal(calls.length, 0, "the merge adapter must not run behind the gate");
630
+ assert.equal(getIssue(issueId).status, "needs_human");
631
+ const action = openOperatorAction(issueId);
632
+ assert.match(action.question, /sign in with SSO and see the org dashboard/);
633
+ assert.doesNotMatch(action.question, /handoff renders for the agent review/);
634
+ const evidence = JSON.parse(action.evidenceJson);
635
+ assert.equal(evidence.operatorVerification.headSha, "abc123");
636
+ assert.equal(evidence.operatorVerification.criteria.length, 1);
637
+ assert.deepEqual(evidence.operatorVerification.criteria[0].commands, [
638
+ "Evidence: operator run | `npm run probe:sso -- --env staging` | dashboard lists orgs",
639
+ ]);
640
+ const resolved = await resolveHumanActionAndAdvanceAsync(action.id, "op", "verified", {
641
+ note: "SSO login OK — org dashboard listed 3 orgs.",
642
+ });
643
+ assert.equal(resolved.ok, true);
644
+ if (resolved.ok)
645
+ assert.equal(resolved.issueStatus, "done");
646
+ assert.equal(calls.length, 1);
647
+ assert.equal(getIssue(issueId).status, "done");
648
+ });
441
649
  test("NOT-384: [operator] criteria plus a visual hold raise one action naming both", async () => {
442
650
  let merges = 0;
443
651
  setMergePrForTests(async () => {
@@ -94,7 +94,11 @@ export function projectReviewerRoute(route, round, hasVerdict) {
94
94
  currentIntent: "Awaiting final human review",
95
95
  events: ["worker.completed", ...verdictEvents],
96
96
  },
97
- effect: { kind: "human_action", actionType: "final_review", reason: "Reviewer approved the PR" },
97
+ effect: {
98
+ kind: "human_action",
99
+ actionType: "final_review",
100
+ reason: route.reason ?? "Reviewer approved the PR",
101
+ },
98
102
  advance: "none",
99
103
  hasVerdict,
100
104
  };
@@ -303,7 +303,7 @@ export function buildDeveloperPrompt(input) {
303
303
  // NOT-146: timed-spawn handoff bar is commits + targeted tests for the change.
304
304
  // Full suite / Lens run on a separate verify/review budget (NOT-74) — they do not
305
305
  // gate developer clean_handoff; the coordinator does not block on full-suite alone.
306
- `Run targeted tests for the change. A clean handoff is valid with commits plus those targeted tests — full suite / Lens checks are not required inside this timed developer spawn (they run on a separate review/verify budget). Make incremental commits with \`git\` at coherent slice boundaries (for example after the tests for that slice pass) — do not leave all work uncommitted until the very end. A final commit of any remaining changes and the **implementation conclusion** remain required before you exit.`, `Commit any remaining changes with \`git\` — do NOT push and do NOT open a pull request; the coordinator pushes your branch and opens/updates the draft PR after this session ends.`, `End your reply with a short **implementation conclusion**: what changed, why, any deviations from the acceptance criteria, and known follow-ups. This is distinct from the PR description and is required every round.`);
306
+ `Run targeted tests for the change. A clean handoff is valid with commits plus those targeted tests — full suite / Lens checks are not required inside this timed developer spawn (they run on a separate review/verify budget). Make incremental commits with \`git\` at coherent slice boundaries (for example after the tests for that slice pass) — do not leave all work uncommitted until the very end. A final commit of any remaining changes and the **implementation conclusion** remain required before you exit.`, `Commit any remaining changes with \`git\` — do NOT push and do NOT open a pull request; the coordinator pushes your branch and opens/updates the draft PR after this session ends.`, `Every round, end your reply with a short **implementation conclusion**: what changed, why, any deviations from the acceptance criteria, and known follow-ups. After it, end with exactly one block fenced by four backticks whose info string is \`pr-description\` (\`\`\`\`pr-description\`). The block must contain the full PR description for the branch as it now stands, not only this round's change. If the repository contains \`.github/pull_request_template.md\`, \`.github/PULL_REQUEST_TEMPLATE.md\`, \`PULL_REQUEST_TEMPLATE.md\`, or \`docs/pull_request_template.md\`, read it from this worktree, keep every heading, and fill it in. Four-backtick fencing lets triple-backtick code fences survive inside the description.`);
307
307
  return parts.join("\n");
308
308
  }
309
309
  const REVIEWER_RESULT_SHAPE = '{"verdict":"approved"|"changes_requested"|"escalated","baseSha":"...","headSha":"...","acceptanceCriteriaAssessment":"...","evidenceAssessment":"...","exitPredicateAssessment":"...","findings":[{"fingerprint":"stable-slug","severity":"blocking"|"non_blocking","title":"...","rationale":"...","file":"...","line":0}],"risks":["..."],"productScopeQuestion":"..."}';
@@ -323,7 +323,7 @@ function reviewerContractSection(baseSha, headSha) {
323
323
  `- "acceptanceCriteriaAssessment" judges the acceptance criteria; "evidenceAssessment" must judge EACH criterion's stated evidence (where to look, action/command, expected result) one by one — never a blanket "evidence looks good".`,
324
324
  `- When the task carries an execution contract, set "exitPredicateAssessment" to whether the frozen exit predicate observably holds at this tip, and "approved" additionally requires the exit predicate to hold (AC met alone is not enough). Tasks without a contract omit "exitPredicateAssessment".`,
325
325
  `- "approved": AC met for this tip and no finding is "blocking" (non_blocking nits allowed).`,
326
- `- "changes_requested": any "blocking" finding a coding pass can address — including incomplete review because AC-critical files were omitted/truncated from the diff. List omitted paths in a blocking finding.`,
326
+ `- "changes_requested": any "blocking" finding a coding pass can address. Do not add a finding solely because the coordinator omitted files from an oversized diff; the coordinator routes an otherwise incomplete truncated review to the operator.`,
327
327
  `- "escalated": only when acceptance criteria / product scope are ambiguous, contradictory, or need a human product call — not ordinary code defects, not "diff too large". You MUST set non-empty "productScopeQuestion"; omit the field otherwise.`,
328
328
  // NOT-303: a missing screenshot is never a pass. Some runtimes (Muse Code: the
329
329
  // Chrome.app headless abort) cannot do visual QA in-session and say so in the
@@ -340,7 +340,7 @@ function reviewerContractSection(baseSha, headSha) {
340
340
  * omitted and listed in `omittedPaths`. Truncation policy (PRD §6.4 / NOT-150): coordinator
341
341
  * remaps illegal escalate / approved+blocking; never blind escalate → Resume|Close.
342
342
  */
343
- export const TOTAL_DIFF_LIMIT = 300_000;
343
+ export const TOTAL_DIFF_LIMIT = 600_000;
344
344
  function pathFromDiffGitHeader(headerLine) {
345
345
  // `diff --git a/path b/path` — prefer the b/ side; fall back to a/.
346
346
  const m = headerLine.match(/^diff --git a\/(.+?) b\/(.+)$/);
@@ -368,7 +368,7 @@ export function formatDiffForPrompt(diff) {
368
368
  }
369
369
  const truncated = omittedPaths.length > 0;
370
370
  const footer = truncated
371
- ? `\n... [${omittedPaths.length} changed file(s) omitted — diff exceeds ${TOTAL_DIFF_LIMIT} characters. Omitted: ${omittedPaths.join(", ")}. If any omitted path is AC-critical, verdict MUST be "changes_requested" with a blocking finding listing those paths. If AC is still certifiable from the visible tip with only non_blocking findings, "approved" is allowed. Do NOT use "escalated" for truncation — escalate only with productScopeQuestion for a true product gap.]`
371
+ ? `\n... [${omittedPaths.length} changed file(s) omitted — diff exceeds ${TOTAL_DIFF_LIMIT} characters. Omitted: ${omittedPaths.join(", ")}. Review the visible diff normally. Do not add a blocking finding or use "escalated" solely because files were omitted; the coordinator sends an otherwise incomplete truncated review to the operator. If AC is still certifiable from the visible tip with only non_blocking findings, "approved" is allowed.]`
372
372
  : "";
373
373
  return {
374
374
  text: `Changed files (${blocks.length}):\n${manifest}\n\n${pieces.join("\n")}${footer}`,
@@ -419,6 +419,75 @@ function visualEvidenceSection(evidence) {
419
419
  ``,
420
420
  ];
421
421
  }
422
+ /** NOT-575: cap for the live PR body embedded as reviewer evidence — a body
423
+ * can carry a full ticket description plus pasted output. */
424
+ export const PR_BODY_EVIDENCE_MAX_CHARS = 8000;
425
+ /** NOT-575: at most this many attestations render (the most recent win). */
426
+ export const OPERATOR_ATTESTATIONS_MAX_COUNT = 5;
427
+ /** NOT-575: per-attestation note cap — pasted probe output can be long. */
428
+ export const OPERATOR_ATTESTATION_NOTE_MAX_CHARS = 2000;
429
+ function capText(text, maxChars, what) {
430
+ const trimmed = text.trim();
431
+ if (trimmed.length <= maxChars)
432
+ return trimmed;
433
+ return `${trimmed.slice(0, maxChars).trimEnd()}\n\n... [${what} truncated to ${maxChars} characters]`;
434
+ }
435
+ /**
436
+ * NOT-575: the PR's live body as reviewer evidence. The reviewer's sandbox
437
+ * has no network and no `gh`, so ticket evidence that says to paste output,
438
+ * commands, or verification notes in the PR body is invisible to it unless
439
+ * the coordinator embeds the body here. Pasted output that matches the
440
+ * criterion IS the evidence — never escalate only because it lives in the PR
441
+ * body instead of the diff. Blank/absent renders nothing.
442
+ */
443
+ export function prBodyEvidenceSection(prBody) {
444
+ if (!prBody?.trim())
445
+ return [];
446
+ return [
447
+ `## PR body (live — evidence pasted there counts)`,
448
+ `Your sandbox cannot read the PR body, so the coordinator fetched it live for this review. When a criterion's stated evidence says to paste output, a command, or verification notes in the PR body, that pasted text IS the evidence — judge it like any other evidence and never escalate only because it lives here instead of in the diff.`,
449
+ ``,
450
+ capText(prBody, PR_BODY_EVIDENCE_MAX_CHARS, "PR body"),
451
+ ``,
452
+ ];
453
+ }
454
+ /**
455
+ * NOT-575: recorded operator attestations as reviewer evidence. A `verified`
456
+ * result's note carries the operator's pasted output; a `waive` carries the
457
+ * waiver reason. Either counts as the evidence for the criteria it names —
458
+ * never escalate for evidence an attestation already provides. A result
459
+ * pinned to a different head does not release this head's gate (Dealer
460
+ * handles that itself), but its pasted output is still evidence you can
461
+ * judge. Empty/absent renders nothing.
462
+ */
463
+ export function operatorAttestationsSection(attestations, pinnedHeadSha) {
464
+ if (!attestations?.length)
465
+ return [];
466
+ const shown = attestations.slice(-OPERATOR_ATTESTATIONS_MAX_COUNT);
467
+ const lines = [
468
+ `## Operator attestations (recorded results count as evidence)`,
469
+ `A human operator already recorded these results on this issue. A recorded result counts as the evidence for the criteria it names — never escalate for evidence an attestation below already provides. Only a result pinned to this exact head (\`${pinnedHeadSha.slice(0, 8)}\`) releases this head's merge gate; other heads' output below is still evidence you can judge.`,
470
+ ``,
471
+ ];
472
+ for (const attestation of shown) {
473
+ const head8 = attestation.headSha.slice(0, 8);
474
+ const pinned = attestation.headSha === pinnedHeadSha ? "this head" : `head \`${head8}\``;
475
+ const by = attestation.by ? ` by ${attestation.by}` : "";
476
+ const at = attestation.at ? ` at ${attestation.at}` : "";
477
+ lines.push(`### ${attestation.kind === "verified" ? "Verified" : "Waived"} (${pinned}${by}${at})`);
478
+ if (attestation.criteria.length > 0) {
479
+ for (const criterion of attestation.criteria)
480
+ lines.push(`- Criterion: ${criterion}`);
481
+ }
482
+ lines.push(attestation.note.trim()
483
+ ? capText(attestation.note, OPERATOR_ATTESTATION_NOTE_MAX_CHARS, "attestation note")
484
+ : "(no note recorded)", ``);
485
+ }
486
+ if (attestations.length > shown.length) {
487
+ lines.push(`... [${attestations.length - shown.length} older attestation(s) omitted]`, ``);
488
+ }
489
+ return lines;
490
+ }
422
491
  export function buildReviewerPrompt(input) {
423
492
  const parts = [
424
493
  input.round === 1
@@ -460,6 +529,10 @@ export function buildReviewerPrompt(input) {
460
529
  // NOT-381: the coordinator-validated visual receipt (or loud rejection),
461
530
  // SHA-bound to the pinned head — the raw conclusion line above is unverified.
462
531
  parts.push(...visualQaReviewerSection(input.visualQa?.record ?? null, input.visualQa?.pinnedHeadSha ?? input.headSha));
532
+ // NOT-575: the live PR body and recorded operator attestations — evidence
533
+ // the sandbox cannot fetch itself. Absent renders nothing.
534
+ parts.push(...prBodyEvidenceSection(input.prBody));
535
+ parts.push(...operatorAttestationsSection(input.operatorAttestations, input.headSha));
463
536
  if (input.findings?.length) {
464
537
  parts.push(`## Findings from prior rounds (verify each is actually resolved)`);
465
538
  for (const f of input.findings) {
@@ -27,6 +27,15 @@ test("developer prompt asks for incremental commits at slice boundaries and keep
27
27
  assert.match(prompt, /implementation conclusion/i);
28
28
  assert.match(prompt, /do NOT push and do NOT open a pull request/);
29
29
  });
30
+ test("developer prompt requires a full template-preserving pr-description every round", () => {
31
+ const prompt = buildDeveloperPrompt({ taskSnapshot, round: 1 });
32
+ assert.match(prompt, /Every round/);
33
+ assert.match(prompt, /````pr-description/);
34
+ assert.match(prompt, /full PR description for the branch as it now stands/);
35
+ assert.match(prompt, /\.github\/pull_request_template\.md/);
36
+ assert.match(prompt, /keep every heading/);
37
+ assert.doesNotMatch(prompt, /distinct from the PR description/);
38
+ });
30
39
  // NOT-146: timed developer spawn covers implement + targeted tests; full suite / Lens
31
40
  // live on a separate budget (NOT-74), not inside the same wall clock.
32
41
  test("NOT-146: developer prompt handoff bar is commits + targeted tests, not full suite/Lens in-spawn", () => {
@@ -189,16 +198,25 @@ test("NOT-150: reviewer verdict rules match the design table (blocking ⇒ chang
189
198
  assert.match(prompt, /not ordinary code defects/);
190
199
  assert.match(prompt, /not "diff too large"/);
191
200
  });
192
- test("NOT-150: truncated-diff footer does not reject approved/changes_requested; forbids escalate-for-truncation", async () => {
201
+ test("NOT-630: truncated-diff footer names omissions and leaves non-truncation findings to the reviewer", async () => {
193
202
  const { formatDiffForPrompt, TOTAL_DIFF_LIMIT } = await import("./prompts.js");
194
203
  const big = "x".repeat(TOTAL_DIFF_LIMIT + 1);
195
204
  const diff = `diff --git a/small.ts b/small.ts\n+ok\n\ndiff --git a/huge.ts b/huge.ts\n+${big}\n`;
196
205
  const formatted = formatDiffForPrompt(diff);
197
206
  assert.equal(formatted.truncated, true);
198
207
  assert.ok(formatted.omittedPaths.some((p) => p.includes("huge.ts")));
199
- assert.match(formatted.text, /changes_requested/);
200
- assert.match(formatted.text, /Do NOT use "escalated" for truncation/);
201
- assert.doesNotMatch(formatted.text, /will not accept "approved" or "changes_requested"/);
208
+ assert.match(formatted.text, /Omitted: huge\.ts/);
209
+ assert.match(formatted.text, /Do not add a blocking finding or use "escalated" solely because files were omitted/);
210
+ assert.match(formatted.text, /coordinator sends an otherwise incomplete truncated review to the operator/);
211
+ });
212
+ test("NOT-630: a 450,000-character file reaches the reviewer without truncation", async () => {
213
+ const { formatDiffForPrompt, TOTAL_DIFF_LIMIT } = await import("./prompts.js");
214
+ assert.equal(TOTAL_DIFF_LIMIT, 600_000);
215
+ const body = "x".repeat(450_000);
216
+ const formatted = formatDiffForPrompt(`diff --git a/large.ts b/large.ts\n+${body}\n`);
217
+ assert.equal(formatted.truncated, false);
218
+ assert.deepEqual(formatted.omittedPaths, []);
219
+ assert.match(formatted.text, new RegExp(`${body.slice(0, 100)}$`));
202
220
  });
203
221
  test("reviewer prompt includes the developer's conclusion, checks summary, and prior findings when given", () => {
204
222
  const prompt = buildReviewerPrompt({
@@ -26,13 +26,13 @@ import os from "node:os";
26
26
  import path from "node:path";
27
27
  import { parseProfileSnapshot, roleCeiling } from "@agent-dealer/shared";
28
28
  import { getTaskSnapshot } from "./commands.js";
29
- import { extractOperatorCriteria } from "./operator-criteria.js";
29
+ import { listOperatorAttestations, operatorCriteriaForSnapshot } from "./operator-criteria.js";
30
30
  import { buildReviewerPrompt, formatDiffForPrompt, TOTAL_DIFF_LIMIT } from "./prompts.js";
31
31
  import { cleanupStagedVisualArtifacts, resolveReviewerVisualEvidence, toReviewerVisualEvidenceInput, } from "./reviewer-visual-evidence.js";
32
32
  import { readLatestVisualQa } from "./visual-qa.js";
33
33
  import { guidanceForNextSession } from "./guidance.js";
34
34
  import { realReviewerSpawn, reviewerSessionLogPath } from "./spawn.js";
35
- import { parseReviewerResult, normalizeReviewerResult, INCOMPLETE_REVIEW_FINGERPRINT, ReviewerResult as ReviewerResultSchema, } from "./reviewer-result.js";
35
+ import { parseReviewerResult, normalizeReviewerResult, ReviewerResult as ReviewerResultSchema, } from "./reviewer-result.js";
36
36
  import { createRoleWorktree, safeRemoveWorktree, isWorktreeClean, listChangedFiles, mergeBase, fetchRef, diffShas, } from "../adapters/git-worktree.js";
37
37
  import { ensureIssueRepoCheckout, roleWorktreePathForResolution, resolveCheckoutBaseBranch, } from "../adapters/managed-repo.js";
38
38
  import { prepareWorkerDeckConnection, releaseWorkerDeckConnection } from "../adapters/agent-deck-bind.js";
@@ -121,46 +121,24 @@ async function bestEffortRemove(repo, worktreePath) {
121
121
  // leave it for crash-recovery inspection — cleanup is a courtesy, not part of the contract
122
122
  }
123
123
  }
124
- /** Inject a stable blocking incomplete-review finding listing omitted paths (NOT-150). */
125
- function withIncompleteReviewFinding(result, omittedPaths) {
126
- if (result.findings.some((f) => f.fingerprint === INCOMPLETE_REVIEW_FINGERPRINT)) {
127
- const { productScopeQuestion: _drop, ...rest } = result;
128
- return { ...rest, verdict: "changes_requested" };
129
- }
130
- const paths = omittedPaths.length > 0 ? omittedPaths.join(", ") : "(unlisted omitted files)";
131
- const { productScopeQuestion: _drop, ...rest } = result;
132
- return {
133
- ...rest,
134
- verdict: "changes_requested",
135
- findings: [
136
- ...result.findings,
137
- {
138
- fingerprint: INCOMPLETE_REVIEW_FINGERPRINT,
139
- severity: "blocking",
140
- title: "Diff truncated — incomplete review",
141
- rationale: `Reviewer prompt omitted path(s): ${paths}. Cannot fully certify acceptance criteria without them; shrink the change set or split the PR so the next review sees the full AC-critical surface.`,
142
- },
143
- ],
144
- };
145
- }
146
124
  /**
147
- * Truncation remap (PRD §6.4 / design NOT-150): never blind escalate → Resume|Close.
148
- * Shippable approved (no blocking) stays approved; otherwise ensure changes_requested with
149
- * the incomplete-review finding listing omitted paths (in addition to any other blocking).
125
+ * NOT-630 truncation policy: shippable approved stays approved; a reviewer's own blocking
126
+ * findings take the normal repair path; every other incomplete review goes to the operator.
150
127
  */
151
128
  function applyTruncationVerdictPolicy(result, omittedPaths) {
152
- const normalized = normalizeReviewerResult(result);
153
- const hasProductQ = !!normalized.productScopeQuestion?.trim();
154
- const hasBlocking = normalized.findings.some((f) => f.severity === "blocking");
155
- if (normalized.verdict === "escalated" && hasProductQ) {
156
- return normalized;
129
+ const hasBlocking = result.findings.some((f) => f.severity === "blocking");
130
+ if (result.verdict === "approved" && !hasBlocking) {
131
+ return { result };
157
132
  }
158
- if (normalized.verdict === "approved" && !hasBlocking) {
159
- return normalized;
133
+ if (hasBlocking) {
134
+ const { productScopeQuestion: _drop, ...rest } = result;
135
+ return { result: { ...rest, verdict: "changes_requested" } };
160
136
  }
161
- // Truncated + not shippable-approved → changes_requested with incomplete-review (omitted paths).
162
- const { productScopeQuestion: _drop, ...rest } = normalized;
163
- return withIncompleteReviewFinding({ ...rest, verdict: "changes_requested" }, omittedPaths);
137
+ const paths = omittedPaths.length > 0 ? omittedPaths.join(", ") : "(unlisted omitted files)";
138
+ return {
139
+ result,
140
+ finalReviewReason: `Diff exceeds the reviewer limit (${TOTAL_DIFF_LIMIT.toLocaleString("en-US")} characters); not reviewed: ${paths}`,
141
+ };
164
142
  }
165
143
  function readImplementationConclusion(issueId) {
166
144
  const artifact = latestIssueArtifact(issueId, "implementation_conclusion");
@@ -187,6 +165,21 @@ function readChecksSummary(issueId) {
187
165
  return null;
188
166
  }
189
167
  }
168
+ /**
169
+ * NOT-575: the PR's live body for the reviewer prompt. Null without a PR
170
+ * number, without the adapter read, or on any lookup failure — every one of
171
+ * those renders no section rather than failing the review.
172
+ */
173
+ export async function readPrBodyForReview(github, cwd, prNumber) {
174
+ if (prNumber == null || !github.prBody)
175
+ return null;
176
+ try {
177
+ return await github.prBody({ cwd, number: prNumber });
178
+ }
179
+ catch {
180
+ return null;
181
+ }
182
+ }
190
183
  /**
191
184
  * Unique per queued reviewer work item — embedded in the published review body purely
192
185
  * as a human-readable audit trail back to the exact work item that produced it.
@@ -271,6 +264,8 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
271
264
  return { kind: "session_failed" };
272
265
  let worktreePath;
273
266
  let result;
267
+ let truncationFinalReviewReason;
268
+ let truncationOmittedPaths;
274
269
  let workerAuthority = null;
275
270
  let repoPath;
276
271
  let baseBranch;
@@ -364,10 +359,17 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
364
359
  // NOT-314: the frozen snapshot's operator criteria — the reviewer must not
365
360
  // treat missing operator evidence as a defect (Dealer gates the merge), but
366
361
  // the probe and doc must exist. Rendered only when non-empty.
367
- const operatorCriteria = extractOperatorCriteria(taskSnapshot.acceptanceCriteria);
362
+ // NOT-575: the same union the gate uses (AC text + structured contract).
363
+ const operatorCriteria = operatorCriteriaForSnapshot(taskSnapshot);
368
364
  // NOT-381: the latest coordinator-validated visual receipt (or loud
369
365
  // rejection), SHA-checked against the pinned head inside the prompt section.
370
366
  const visualQaRecord = readLatestVisualQa(issue.id);
367
+ // NOT-575: the PR's live body and recorded operator attestations — best
368
+ // effort, never failing the review. A lookup failure (or an adapter
369
+ // without the read) yields no section, and the reviewer judges without
370
+ // it; a missing body is never evidence of anything.
371
+ const prBody = await readPrBodyForReview(deps.github, worktreePath, issue.prNumber);
372
+ const operatorAttestations = listOperatorAttestations(issue.id);
371
373
  const prompt = buildReviewerPrompt({
372
374
  taskSnapshot,
373
375
  round: workItem.round,
@@ -383,6 +385,8 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
383
385
  operatorCriteria: operatorCriteria.length > 0 ? operatorCriteria : undefined,
384
386
  visualEvidence,
385
387
  visualQa: visualQaRecord ? { record: visualQaRecord, pinnedHeadSha: headSha } : undefined,
388
+ prBody: prBody ?? undefined,
389
+ operatorAttestations: operatorAttestations.length > 0 ? operatorAttestations : undefined,
386
390
  });
387
391
  // NOT-83 review finding — see developer-effect.ts's identical check for the full
388
392
  // rationale: re-verify this item is still leased right before the real spawn, since an
@@ -559,7 +563,9 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
559
563
  author: "system",
560
564
  blobPath: spawned.logPath,
561
565
  });
562
- const parsed = parseReviewerResult(spawned.transcript);
566
+ // Preserve the reviewer's own findings on a truncated diff so NOT-630 can distinguish
567
+ // them from normalizeReviewer's synthetic bare-escalate repair finding.
568
+ const parsed = parseReviewerResult(spawned.transcript, { normalize: !diffTruncated });
563
569
  if (!parsed) {
564
570
  await bestEffortRemove(repoPath, worktreePath);
565
571
  return { kind: "session_failed" };
@@ -574,11 +580,14 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
574
580
  return { kind: "session_failed" };
575
581
  }
576
582
  result = parsed;
577
- // Truncation policy (PRD §6.4 / design NOT-150): never blind-escalate to Resume|Close.
578
- // Persist evidence; remap bare escalate / approved+blocking; keep shippable approved.
583
+ // NOT-630: persist truncation evidence; keep shippable approved and genuine blockers,
584
+ // but send every other incomplete review to a final_review operator action.
579
585
  if (diffTruncated) {
580
586
  const reportedVerdict = result.verdict;
581
- result = applyTruncationVerdictPolicy(result, omittedPaths);
587
+ const policy = applyTruncationVerdictPolicy(result, omittedPaths);
588
+ result = policy.result;
589
+ truncationFinalReviewReason = policy.finalReviewReason;
590
+ truncationOmittedPaths = omittedPaths;
582
591
  createIssueArtifact({
583
592
  issueId: issue.id,
584
593
  workerSessionId: sessionId,
@@ -641,8 +650,14 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
641
650
  // attempt, or the winner itself failed) has nothing safe to report — escalate.
642
651
  if (claim.row?.state === "published" && claim.row.resultJson) {
643
652
  const winnerParsed = ReviewerResultSchema.parse(JSON.parse(claim.row.resultJson));
644
- const winnerResult = normalizeReviewerResult(winnerParsed);
645
- return { kind: "verdict", result: winnerResult };
653
+ const winnerPolicy = truncationOmittedPaths
654
+ ? applyTruncationVerdictPolicy(winnerParsed, truncationOmittedPaths)
655
+ : { result: normalizeReviewerResult(winnerParsed) };
656
+ return {
657
+ kind: "verdict",
658
+ result: winnerPolicy.result,
659
+ ...(winnerPolicy.finalReviewReason ? { finalReviewReason: winnerPolicy.finalReviewReason } : {}),
660
+ };
646
661
  }
647
662
  return { kind: "publish_failed" };
648
663
  }
@@ -675,7 +690,11 @@ export async function runReviewerEffect(ctx, deps = defaultDeps) {
675
690
  content: { event: published.event, usedCommentFallback: published.usedCommentFallback, verdict: result.verdict },
676
691
  });
677
692
  await bestEffortRemove(repoPath, worktreePath);
678
- return { kind: "verdict", result };
693
+ return {
694
+ kind: "verdict",
695
+ result,
696
+ ...(truncationFinalReviewReason ? { finalReviewReason: truncationFinalReviewReason } : {}),
697
+ };
679
698
  }
680
699
  catch {
681
700
  await bestEffortRemove(repoPath, worktreePath);