agent-dealer 1.4.2 → 1.4.4

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 (33) 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/args.js +7 -9
  4. package/bundle/server/dist/coordinator/args.test.js +5 -2
  5. package/bundle/server/dist/coordinator/auto-merge.js +17 -6
  6. package/bundle/server/dist/coordinator/commands.js +18 -2
  7. package/bundle/server/dist/coordinator/developer-effect.js +46 -5
  8. package/bundle/server/dist/coordinator/developer-effect.test.js +118 -4
  9. package/bundle/server/dist/coordinator/muse-spawn.js +1 -0
  10. package/bundle/server/dist/coordinator/operator-criteria.js +250 -17
  11. package/bundle/server/dist/coordinator/operator-criteria.test.js +177 -4
  12. package/bundle/server/dist/coordinator/operator-verification.integration.test.js +208 -0
  13. package/bundle/server/dist/coordinator/projection.js +5 -1
  14. package/bundle/server/dist/coordinator/prompts.js +77 -4
  15. package/bundle/server/dist/coordinator/prompts.test.js +22 -4
  16. package/bundle/server/dist/coordinator/reviewer-browser-probe.js +2 -3
  17. package/bundle/server/dist/coordinator/reviewer-effect.js +64 -45
  18. package/bundle/server/dist/coordinator/reviewer-effect.test.js +63 -10
  19. package/bundle/server/dist/coordinator/reviewer-pr-evidence.test.js +245 -0
  20. package/bundle/server/dist/coordinator/reviewer-result.js +4 -3
  21. package/bundle/server/dist/coordinator/reviewer-result.test.js +6 -0
  22. package/bundle/server/dist/coordinator/routing.js +3 -0
  23. package/bundle/server/dist/coordinator/routing.test.js +19 -0
  24. package/bundle/server/dist/coordinator/spawn.js +25 -5
  25. package/bundle/server/dist/coordinator/spawn.test.js +84 -0
  26. package/bundle/server/dist/docs-api-reference.test.js +89 -0
  27. package/bundle/server/dist/runners/muse-config-core.js +33 -9
  28. package/bundle/server/dist/runners/muse-config.test.js +13 -8
  29. package/bundle/server/dist/runners/spawn-cli.js +12 -4
  30. package/bundle/server/dist/runners/spawn-cli.test.js +19 -0
  31. package/bundle/server/package.json +2 -2
  32. package/bundle/shared/package.json +1 -1
  33. package/package.json +1 -1
@@ -31,7 +31,7 @@ const { getActiveWorkflowInstance, listWorkflowEventsForIssue } = await import("
31
31
  const { startWorkflow, resolveHumanActionAndAdvance } = await import("./commands.js");
32
32
  const { registerEffectHandler, resetEffectHandlers } = await import("./effect-registry.js");
33
33
  const { runCoordinatorTick, drainCoordinator } = await import("./worker-loop.js");
34
- const { runDeveloperEffect } = await import("./developer-effect.js");
34
+ const { runDeveloperEffect, extractPrDescription } = await import("./developer-effect.js");
35
35
  const { realDeveloperSpawn } = await import("./spawn.js");
36
36
  const { realGithubAdapter } = await import("../adapters/github.js");
37
37
  const { branchExists, roleWorktreePath, withRepoLock, observeGitCommands } = await import("../adapters/git-worktree.js");
@@ -113,6 +113,23 @@ const commitingSpawn = async (input) => {
113
113
  const noopSpawn = async () => ({ exitCode: 0, transcript: "", logPath: "/dev/null", timedOut: false });
114
114
  const crashingSpawn = async () => ({ exitCode: 1, transcript: "boom", logPath: "/dev/null", timedOut: false });
115
115
  const timedOutSpawn = async () => ({ exitCode: 1, transcript: "", logPath: "/dev/null", timedOut: true });
116
+ test("extractPrDescription returns one block's contents", () => {
117
+ assert.equal(extractPrDescription("done\n````pr-description\n## Summary\nBuilt it.\n````"), "## Summary\nBuilt it.");
118
+ });
119
+ test("extractPrDescription uses the last block", () => {
120
+ const transcript = "````pr-description\nold\n````\nnotes\n````pr-description\nnew\n````";
121
+ assert.equal(extractPrDescription(transcript), "new");
122
+ });
123
+ test("extractPrDescription preserves template headings and nested triple-backtick fences", () => {
124
+ const body = "## Record\n\n```ts\nconst answer = 42;\n```";
125
+ assert.equal(extractPrDescription(`conclusion\n\`\`\`\`pr-description\n${body}\n\`\`\`\``), body);
126
+ });
127
+ test("extractPrDescription returns null without a block", () => {
128
+ assert.equal(extractPrDescription("Implementation conclusion only."), null);
129
+ });
130
+ test("extractPrDescription returns null for a blank block", () => {
131
+ assert.equal(extractPrDescription("````pr-description\n \n````"), null);
132
+ });
116
133
  /**
117
134
  * In-memory PR store keyed by branch — real git tells it the head SHA, nothing hits real
118
135
  * GitHub. `viewPr`/`createDraftPr` deliberately require an explicit `branch`/`head` and
@@ -139,16 +156,22 @@ function fakeGithub(opts = {}) {
139
156
  return null;
140
157
  return { number: pr.number, url: pr.url, baseRefName: pr.base, headRefName: branch, headRefOid: remoteHead(branch), isDraft: true };
141
158
  },
142
- async createDraftPr({ base, head }) {
159
+ async createDraftPr({ base, head, bodyFilePath }) {
143
160
  if (shouldFailCreate())
144
161
  return { ok: false, reason: "gh: simulated failure", noCommits: false };
145
162
  if (!head)
146
163
  throw new Error("fakeGithub.createDraftPr requires an explicit --head — bare create is the NOT-82 bug");
164
+ opts.createdBodies?.push(fs.readFileSync(bodyFilePath, "utf8"));
147
165
  const number = nextNumber++;
148
166
  const url = `https://github.com/o/r/pull/${number}`;
149
167
  prs.set(head, { number, url, base });
150
168
  return { ok: true, number, url };
151
169
  },
170
+ async updatePrBody({ bodyFilePath }) {
171
+ opts.updatedBodies?.push(fs.readFileSync(bodyFilePath, "utf8"));
172
+ if (opts.updateFails)
173
+ throw new Error("gh: simulated body edit failure");
174
+ },
152
175
  async checksSnapshot({ number, branch }) {
153
176
  if (number == null && !branch) {
154
177
  throw new Error("fakeGithub.checksSnapshot requires an explicit number or branch — bare checks lookup is the NOT-82 bug");
@@ -557,6 +580,91 @@ test("checks_failed: CI failure after a clean push/PR retries without a human ac
557
580
  assert.ok(kinds.includes("implementation_conclusion"), "conclusion must survive a post-session verification failure");
558
581
  assert.ok(kinds.includes("developer_transcript"), "raw trace must survive a post-session verification failure");
559
582
  });
583
+ test("PR creation uses the developer's full pr-description block", async () => {
584
+ const issueId = await makeIssue();
585
+ const createdBodies = [];
586
+ const body = "## Summary\nBuilt the widget.\n\n## Record\nDealer-owned.";
587
+ const spawn = async (input) => {
588
+ const result = await commitingSpawn(input);
589
+ return { ...result, transcript: `Implementation conclusion: done.\n\n\`\`\`\`pr-description\n${body}\n\`\`\`\`` };
590
+ };
591
+ registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn, github: fakeGithub({ createdBodies }) }));
592
+ startWorkflow(issueId);
593
+ await pump(1);
594
+ assert.deepEqual(createdBodies, [body]);
595
+ });
596
+ test("PR creation falls back to the implementation conclusion when there is no block", async () => {
597
+ const issueId = await makeIssue();
598
+ const createdBodies = [];
599
+ registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn: commitingSpawn, github: fakeGithub({ createdBodies }) }));
600
+ startWorkflow(issueId);
601
+ await pump(1);
602
+ assert.deepEqual(createdBodies, ["Implementation conclusion: added the widget."]);
603
+ });
604
+ test("PR creation falls back to the ticket description when the transcript is blank", async () => {
605
+ const issueId = await makeIssue();
606
+ const createdBodies = [];
607
+ const spawn = async (input) => {
608
+ const result = await commitingSpawn(input);
609
+ return { ...result, transcript: "" };
610
+ };
611
+ registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn, github: fakeGithub({ createdBodies }) }));
612
+ startWorkflow(issueId);
613
+ await pump(1);
614
+ assert.deepEqual(createdBodies, ["Build the widget."]);
615
+ });
616
+ async function runBodyRefreshScenario(opts) {
617
+ const issueId = await makeIssue();
618
+ const updatedBodies = [];
619
+ let calls = 0;
620
+ const spawn = async (input) => {
621
+ calls++;
622
+ const file = calls === 1 ? "feature.txt" : "followup.txt";
623
+ fs.writeFileSync(path.join(input.cwd, file), `${calls}\n`);
624
+ git(input.cwd, "add", ".");
625
+ git(input.cwd, "-c", "user.email=agent@test", "-c", "user.name=Agent", "commit", "-q", "-m", `round ${calls}`);
626
+ const description = calls === 1 ? "initial body" : opts.secondBody;
627
+ const transcript = description
628
+ ? `Implementation conclusion: round ${calls}.\n\n\`\`\`\`pr-description\n${description}\n\`\`\`\``
629
+ : `Implementation conclusion: round ${calls}.`;
630
+ return { exitCode: 0, transcript, logPath: "/dev/null", timedOut: false };
631
+ };
632
+ const github = fakeGithub({
633
+ checks: () => (calls === 1 ? "failure" : "success"),
634
+ updatedBodies,
635
+ updateFails: opts.updateFails,
636
+ });
637
+ registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn, github }));
638
+ startWorkflow(issueId);
639
+ await pump(2);
640
+ return { issueId, calls, updatedBodies };
641
+ }
642
+ test("an existing PR is replaced with the later round's pr-description", async () => {
643
+ const result = await runBodyRefreshScenario({ secondBody: "current full body" });
644
+ assert.equal(result.calls, 2);
645
+ assert.deepEqual(result.updatedBodies, ["current full body"]);
646
+ assert.equal(getIssue(result.issueId).status, "reviewing");
647
+ });
648
+ test("an existing PR is left unchanged when the later round has no pr-description", async () => {
649
+ const result = await runBodyRefreshScenario({ secondBody: null });
650
+ assert.equal(result.calls, 2);
651
+ assert.deepEqual(result.updatedBodies, []);
652
+ assert.equal(getIssue(result.issueId).status, "reviewing");
653
+ });
654
+ test("a failed existing-PR body update is logged and does not fail the round", async () => {
655
+ const warnings = [];
656
+ const originalWarn = console.warn;
657
+ console.warn = (...args) => warnings.push(args.map(String).join(" "));
658
+ try {
659
+ const result = await runBodyRefreshScenario({ secondBody: "current full body", updateFails: true });
660
+ assert.deepEqual(result.updatedBodies, ["current full body"]);
661
+ assert.equal(getIssue(result.issueId).status, "reviewing");
662
+ assert.ok(warnings.some((warning) => /PR body update failed/.test(warning)));
663
+ }
664
+ finally {
665
+ console.warn = originalWarn;
666
+ }
667
+ });
560
668
  test("NOT-311: checks_pending — checks still pending at the poll deadline defers, spending no attempt", async () => {
561
669
  // Previously this returned `timed_out`, spending an infra attempt on a session that
562
670
  // had already ended cleanly. Now the item waits on backoff and re-polls.
@@ -1133,10 +1241,15 @@ test("publish-only retry: post-push gh create failure reopens the PR without res
1133
1241
  const issueId = await makeIssue();
1134
1242
  let createAttempt = 0;
1135
1243
  let spawnCalls = 0;
1136
- const github = fakeGithub({ createFails: () => ++createAttempt === 1 });
1244
+ const createdBodies = [];
1245
+ const github = fakeGithub({ createFails: () => ++createAttempt === 1, createdBodies });
1137
1246
  const countingSpawn = async (input) => {
1138
1247
  spawnCalls++;
1139
- return commitingSpawn(input);
1248
+ const result = await commitingSpawn(input);
1249
+ return {
1250
+ ...result,
1251
+ transcript: "Implementation conclusion: added the widget.\n\n````pr-description\n## Summary\nFull retry body.\n````",
1252
+ };
1140
1253
  };
1141
1254
  registerEffectHandler("developer", (ctx) => runDeveloperEffect(ctx, { deckCallTool: okDeckCallTool, spawn: countingSpawn, github }));
1142
1255
  startWorkflow(issueId);
@@ -1147,6 +1260,7 @@ test("publish-only retry: post-push gh create failure reopens the PR without res
1147
1260
  assert.equal(issue.status, "reviewing");
1148
1261
  assert.ok(issue.prNumber, "draft PR must exist after the publish-only retry");
1149
1262
  assert.equal(issue.currentRound, 1, "publish-only infra retry does not spend a review round");
1263
+ assert.deepEqual(createdBodies, ["## Summary\nFull retry body."], "publish retry must reuse the stored description");
1150
1264
  });
1151
1265
  test("unpushed_commit: the coordinator's own push is rejected by a diverged remote branch — escalates, work preserved", async () => {
1152
1266
  const issueId = await makeIssue();
@@ -245,6 +245,7 @@ export async function runMuseDeveloperSession(input) {
245
245
  timeoutMs: input.timeoutMs,
246
246
  env: { ...attempt.env },
247
247
  exactEnv: true,
248
+ runtime: "muse_code",
248
249
  stdin: attempt.stdin,
249
250
  signal: input.signal,
250
251
  onSpawn: input.onSpawn,
@@ -34,20 +34,49 @@ export const OPERATOR_VERIFICATION_RESPONSE_OPTIONS = [
34
34
  export function operatorVerificationRequestId(headSha) {
35
35
  return `operator-verification:${headSha}`;
36
36
  }
37
- const OPERATOR_TAG_RE = /\[operator\]/i;
37
+ /**
38
+ * NOT-575: the planner deck tags each criterion `[agent]`, `[ci]` or
39
+ * `[operator]` at the END of the criterion line. Only that trailing tag
40
+ * decides — a criterion whose prose merely mentions `[operator]` but ends in
41
+ * `[agent]` is an agent criterion, never a gate. Case-insensitive; trailing
42
+ * whitespace (including a CR from CRLF ticket text) is ignored. Strictly the
43
+ * last token: `[operator].` with trailing punctuation is NOT a tag.
44
+ *
45
+ * Repair round 2: Linear markdown escapes the brackets (`\[operator\]`), and
46
+ * neither intake nor the contract compiler unescapes them — the raw text ends
47
+ * in `\]`, so a plain `]`-anchored match never fires and genuine operator
48
+ * criteria sail through the gate (the NOT-567/569-572 missed-gate shape).
49
+ * Each bracket therefore accepts one optional backslash.
50
+ */
51
+ const TRAILING_OPERATOR_TAG_RE = /\\?\[operator\\?\]\s*$/i;
52
+ /** True when the criterion text carries a trailing `[operator]` tag (NOT-575). */
53
+ export function hasTrailingOperatorTag(criterionText) {
54
+ return TRAILING_OPERATOR_TAG_RE.test(criterionText.trim());
55
+ }
38
56
  /** An indented checkbox (a nested sub-task) — never a command, never a gate. */
39
57
  const INDENTED_CHECKBOX_RE = /^\s+[-*]\s*\[[ xX]?\]/;
40
58
  /** An indented plain bullet — an evidence/command sub-bullet. */
41
59
  const INDENTED_BULLET_RE = /^\s+[-*]\s+(.*)$/;
42
60
  /**
43
- * Returns each top-level (unindented) checkbox AC whose text contains the token
44
- * `[operator]` (case-insensitive, anywhere in the line), together with the
45
- * indented bullet lines directly under it (the command to run).
61
+ * NOT-575: the planner contract's indented `Evidence:` line under a criterion
62
+ * (` Evidence: ...`, or the nested-bullet form ` * Evidence: ...` the
63
+ * contract compiler also accepts). Collected as the criterion's command the
64
+ * same way a sub-bullet is — without this every contract-ticket criterion
65
+ * gates with an empty command list.
66
+ */
67
+ const INDENTED_EVIDENCE_RE = /^\s+(?:[-*+]\s+)?Evidence\s*:\s*(.*)$/i;
68
+ /**
69
+ * Returns each top-level (unindented) checkbox AC with a trailing `[operator]`
70
+ * tag (NOT-575: the tag at the end of the criterion line only, never a
71
+ * mention inside the criterion text), together with the indented evidence
72
+ * lines directly under it (sub-bullets and `Evidence:` lines — the commands
73
+ * to run).
46
74
  *
47
75
  * "Top-level" means the checkbox marker starts at column 0; indented
48
76
  * checkboxes (sub-tasks) never open the gate. Collection of a criterion's
49
- * commands stops at the next column-0 checkbox, a non-bullet line, or EOF —
50
- * blank lines inside the sub-bullet block are skipped, not terminators.
77
+ * commands stops at the next column-0 checkbox, an indented checkbox, a
78
+ * non-bullet non-evidence line, or EOF — blank lines inside the block are
79
+ * skipped, not terminators.
51
80
  */
52
81
  export function extractOperatorCriteria(acceptanceCriteria) {
53
82
  const found = [];
@@ -56,7 +85,7 @@ export function extractOperatorCriteria(acceptanceCriteria) {
56
85
  while (i < lines.length) {
57
86
  const line = lines[i];
58
87
  const top = line.match(/^[-*]\s*\[[ xX]?\]\s*(.*)$/);
59
- if (top && OPERATOR_TAG_RE.test(top[1] ?? "")) {
88
+ if (top && hasTrailingOperatorTag(top[1] ?? "")) {
60
89
  const criterion = { text: (top[1] ?? "").trim(), commands: [] };
61
90
  i += 1;
62
91
  while (i < lines.length) {
@@ -73,6 +102,12 @@ export function extractOperatorCriteria(acceptanceCriteria) {
73
102
  // the block without being collected.
74
103
  if (INDENTED_CHECKBOX_RE.test(sub))
75
104
  break;
105
+ const evidence = sub.match(INDENTED_EVIDENCE_RE);
106
+ if (evidence) {
107
+ criterion.commands.push(`Evidence: ${(evidence[1] ?? "").trim()}`);
108
+ i += 1;
109
+ continue;
110
+ }
76
111
  const bullet = sub.match(INDENTED_BULLET_RE);
77
112
  if (bullet) {
78
113
  criterion.commands.push((bullet[1] ?? "").trim());
@@ -88,6 +123,49 @@ export function extractOperatorCriteria(acceptanceCriteria) {
88
123
  }
89
124
  return found;
90
125
  }
126
+ /**
127
+ * NOT-575: the same trailing-tag detection over the frozen execution
128
+ * contract's structured criteria. The contract is the authoritative criterion
129
+ * list for contract tickets — when an explicitly-provided acceptance-criteria
130
+ * string diverges from it, a genuine trailing-`[operator]` contract criterion
131
+ * must still gate. Pure (no DB): the caller supplies the frozen contract.
132
+ */
133
+ export function extractOperatorCriteriaFromContract(contract) {
134
+ if (!contract)
135
+ return [];
136
+ const found = [];
137
+ for (const criterion of contract.acceptanceCriteria) {
138
+ if (!hasTrailingOperatorTag(criterion.text))
139
+ continue;
140
+ found.push({
141
+ text: criterion.text.trim(),
142
+ commands: criterion.evidence?.trim() ? [`Evidence: ${criterion.evidence.trim()}`] : [],
143
+ });
144
+ }
145
+ return found;
146
+ }
147
+ /**
148
+ * NOT-575: union of the AC-text criteria and the structured-contract
149
+ * criteria, deduped by exact criterion text (contract tickets render their AC
150
+ * text from the contract, so the two lists normally agree — the union only
151
+ * matters when they diverge). Pure: the caller supplies the frozen snapshot
152
+ * fields, so the gate, the developer prompt, and the reviewer prompt all
153
+ * classify identically without each reading the DB.
154
+ */
155
+ export function operatorCriteriaForSnapshot(snapshot) {
156
+ const seen = new Set();
157
+ const merged = [];
158
+ for (const criterion of [
159
+ ...extractOperatorCriteria(snapshot.acceptanceCriteria),
160
+ ...extractOperatorCriteriaFromContract(snapshot.executionContract),
161
+ ]) {
162
+ if (seen.has(criterion.text))
163
+ continue;
164
+ seen.add(criterion.text);
165
+ merged.push(criterion);
166
+ }
167
+ return merged;
168
+ }
91
169
  /** The frozen snapshot's acceptanceCriteria, falling back to the live issue
92
170
  * fields for items queued before snapshots existed (same fallback as
93
171
  * commands.ts's getTaskSnapshot). */
@@ -105,38 +183,161 @@ export function snapshotAcceptanceCriteria(issue) {
105
183
  }
106
184
  return issue.acceptanceCriteria ?? "";
107
185
  }
186
+ /**
187
+ * NOT-575: the frozen snapshot's execution contract, falling back to the
188
+ * live-issue derived contract for items queued before snapshots existed (same
189
+ * fallback shape as snapshotAcceptanceCriteria above). The contract is the
190
+ * authoritative criterion list when AC text and contract diverge.
191
+ */
192
+ export function snapshotExecutionContract(issue) {
193
+ try {
194
+ const artifact = latestIssueArtifact(issue.id, TASK_SNAPSHOT_KIND);
195
+ if (artifact?.contentJson) {
196
+ const parsed = JSON.parse(artifact.contentJson);
197
+ if (parsed.executionContract && typeof parsed.executionContract === "object") {
198
+ return parsed.executionContract;
199
+ }
200
+ return null;
201
+ }
202
+ }
203
+ catch {
204
+ // fall through to the live-field fallback below
205
+ }
206
+ return issue.executionContract ?? null;
207
+ }
108
208
  /** The frozen snapshot's `[operator]` criteria for this issue ([] when none). */
109
209
  export function getOperatorCriteriaForIssue(issue) {
110
- return extractOperatorCriteria(snapshotAcceptanceCriteria(issue));
210
+ return operatorCriteriaForSnapshot({
211
+ acceptanceCriteria: snapshotAcceptanceCriteria(issue),
212
+ executionContract: snapshotExecutionContract(issue),
213
+ });
111
214
  }
112
215
  function recordHeadSha(record) {
113
216
  return record && typeof record.headSha === "string" && record.headSha ? record.headSha : null;
114
217
  }
218
+ /**
219
+ * NOT-575: the criterion texts a record covers, or null when the record
220
+ * predates per-criterion coverage (absent/non-list `criteria`) — a legacy
221
+ * record covers the whole head it pins, so a verify-then-crash recovery never
222
+ * re-blocks behind a result the operator already recorded.
223
+ */
224
+ function recordCoveredCriteria(record) {
225
+ if (!record || record.criteria === undefined)
226
+ return null;
227
+ if (!Array.isArray(record.criteria))
228
+ return null;
229
+ return record.criteria.filter((c) => typeof c === "string" && !!c);
230
+ }
231
+ /** Every recorded result (verified artifact or waiver event) for exactly `headSha`. */
232
+ function verificationRecordsForHead(issueId, headSha) {
233
+ const records = [];
234
+ try {
235
+ for (const artifact of listArtifactsForIssueByKind(issueId, OPERATOR_VERIFICATION_ARTIFACT_KIND)) {
236
+ if (!artifact.contentJson)
237
+ continue;
238
+ try {
239
+ const record = JSON.parse(artifact.contentJson);
240
+ if (recordHeadSha(record) === headSha)
241
+ records.push(record);
242
+ }
243
+ catch {
244
+ // unreadable artifact content cannot prove verification
245
+ }
246
+ }
247
+ }
248
+ catch {
249
+ // a read failure fails closed below (no verification found → gate blocks)
250
+ }
251
+ try {
252
+ for (const event of listWorkflowEventsForIssue(issueId)) {
253
+ if (event.type !== "operator_verification.waived" || !event.payloadJson)
254
+ continue;
255
+ try {
256
+ const record = JSON.parse(event.payloadJson);
257
+ if (recordHeadSha(record) === headSha)
258
+ records.push(record);
259
+ }
260
+ catch {
261
+ // unreadable payload cannot prove a waiver
262
+ }
263
+ }
264
+ }
265
+ catch {
266
+ // same fail-closed reasoning as above
267
+ }
268
+ return records;
269
+ }
115
270
  /**
116
271
  * True when the human already recorded a result for exactly `headSha`: either a
117
272
  * `verified` artifact (kind `operator_verification`, author human) or a
118
273
  * `operator_verification.waived` workflow event. A result pins the head it was
119
274
  * recorded at — new commits re-block the gate.
275
+ *
276
+ * Head-level only: the visual-evidence hold (which has no criterion list)
277
+ * releases on this. Criterion gating uses missingOperatorCriteriaForHead so
278
+ * each trailing-`[operator]` criterion needs its own recorded result.
120
279
  */
121
280
  export function hasOperatorVerificationForHead(issueId, headSha) {
122
281
  if (!headSha)
123
282
  return false;
283
+ return verificationRecordsForHead(issueId, headSha).length > 0;
284
+ }
285
+ /**
286
+ * NOT-575: the subset of `criteria` with no recorded result for exactly
287
+ * `headSha` ([] when every criterion is covered). A `verified` artifact or a
288
+ * `operator_verification.waived` event covers the criterion texts it lists —
289
+ * the resolve path stores the gated action's exact criterion list, so a
290
+ * result recorded for one criterion never releases another. Legacy records
291
+ * without a criterion list cover the whole head (see recordCoveredCriteria).
292
+ */
293
+ export function missingOperatorCriteriaForHead(issueId, headSha, criteria) {
294
+ if (criteria.length === 0 || !headSha)
295
+ return [];
296
+ const records = verificationRecordsForHead(issueId, headSha);
297
+ if (records.length === 0)
298
+ return [...criteria];
299
+ return criteria.filter((criterion) => {
300
+ for (const record of records) {
301
+ const covered = recordCoveredCriteria(record);
302
+ if (covered === null)
303
+ return false;
304
+ if (covered.includes(criterion.text))
305
+ return false;
306
+ }
307
+ return true;
308
+ });
309
+ }
310
+ function attestationNote(record) {
311
+ return typeof record.note === "string" ? record.note : "";
312
+ }
313
+ /** Every recorded operator attestation for the issue, oldest first ([] when none). */
314
+ export function listOperatorAttestations(issueId) {
315
+ const attestations = [];
124
316
  try {
125
317
  for (const artifact of listArtifactsForIssueByKind(issueId, OPERATOR_VERIFICATION_ARTIFACT_KIND)) {
126
318
  if (!artifact.contentJson)
127
319
  continue;
128
320
  try {
129
321
  const record = JSON.parse(artifact.contentJson);
130
- if (recordHeadSha(record) === headSha)
131
- return true;
322
+ const headSha = recordHeadSha(record);
323
+ if (!headSha)
324
+ continue;
325
+ attestations.push({
326
+ kind: "verified",
327
+ headSha,
328
+ note: attestationNote(record),
329
+ by: typeof record.verifiedBy === "string" ? record.verifiedBy : null,
330
+ at: typeof record.verifiedAt === "string" ? record.verifiedAt : (artifact.createdAt ?? null),
331
+ criteria: recordCoveredCriteria(record) ?? [],
332
+ });
132
333
  }
133
334
  catch {
134
- // unreadable artifact content cannot prove verification
335
+ // unreadable content is not an attestation
135
336
  }
136
337
  }
137
338
  }
138
339
  catch {
139
- // a read failure fails closed below (no verification found → gate blocks)
340
+ // a read failure yields no attestations (the reviewer judges without them)
140
341
  }
141
342
  try {
142
343
  for (const event of listWorkflowEventsForIssue(issueId)) {
@@ -144,18 +345,50 @@ export function hasOperatorVerificationForHead(issueId, headSha) {
144
345
  continue;
145
346
  try {
146
347
  const record = JSON.parse(event.payloadJson);
147
- if (recordHeadSha(record) === headSha)
148
- return true;
348
+ const headSha = recordHeadSha(record);
349
+ if (!headSha)
350
+ continue;
351
+ attestations.push({
352
+ kind: "waived",
353
+ headSha,
354
+ note: attestationNote(record),
355
+ by: typeof record.waivedBy === "string" ? record.waivedBy : null,
356
+ at: event.ts ?? null,
357
+ criteria: recordCoveredCriteria(record) ?? [],
358
+ });
149
359
  }
150
360
  catch {
151
- // unreadable payload cannot prove a waiver
361
+ // unreadable payload is not an attestation
152
362
  }
153
363
  }
154
364
  }
155
365
  catch {
156
- // same fail-closed reasoning as above
366
+ // same leniency as above
367
+ }
368
+ return attestations;
369
+ }
370
+ /**
371
+ * NOT-575: the criterion texts an `operator_verification` action gates (its
372
+ * stored `evidence.operatorVerification.criteria`), or null when the action
373
+ * predates that evidence shape or is unreadable. The resolve path stores
374
+ * exactly this list on the recorded result, so the result covers the gated
375
+ * criteria — that exact criterion set — and nothing else.
376
+ */
377
+ export function criteriaTextsFromActionEvidence(action) {
378
+ if (!action.evidenceJson)
379
+ return null;
380
+ try {
381
+ const evidence = JSON.parse(action.evidenceJson);
382
+ const criteria = evidence.operatorVerification?.criteria;
383
+ if (!Array.isArray(criteria))
384
+ return null;
385
+ return criteria
386
+ .map((c) => (c && typeof c === "object" ? c.text : null))
387
+ .filter((t) => typeof t === "string" && !!t);
388
+ }
389
+ catch {
390
+ return null;
157
391
  }
158
- return false;
159
392
  }
160
393
  /** One numbered criterion + its commands, for the gate's reason/question. */
161
394
  export function formatOperatorCriteria(criteria) {