@webpieces/pr-gate 0.4.775 → 0.4.776

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/package.json +3 -3
  2. package/src/dashboard/checklist-comment-renderer.js +4 -4
  3. package/src/dashboard/checklist-comment-renderer.js.map +1 -1
  4. package/src/dashboard/checklist-comment-row.d.ts +2 -2
  5. package/src/dashboard/checklist-comment-row.js +3 -3
  6. package/src/dashboard/checklist-comment-row.js.map +1 -1
  7. package/src/scripts/commands/finish-upsert-pr-command.js +8 -8
  8. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  9. package/src/scripts/commands/review-upsert-pr-command.js +5 -4
  10. package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
  11. package/src/scripts/workflow/checklist-detector.js +1 -1
  12. package/src/scripts/workflow/checklist-detector.js.map +1 -1
  13. package/src/scripts/workflow/checklist-notice.js +6 -4
  14. package/src/scripts/workflow/checklist-notice.js.map +1 -1
  15. package/src/scripts/workflow/provenance-enforcer.d.ts +2 -2
  16. package/src/scripts/workflow/provenance-enforcer.js +24 -22
  17. package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
  18. package/src/scripts/workflow/repo-config-testkit.d.ts +5 -2
  19. package/src/scripts/workflow/repo-config-testkit.js +6 -2
  20. package/src/scripts/workflow/repo-config-testkit.js.map +1 -1
  21. package/src/scripts/workflow/review-report.d.ts +22 -2
  22. package/src/scripts/workflow/review-report.js +82 -12
  23. package/src/scripts/workflow/review-report.js.map +1 -1
  24. package/src/scripts/workflow/reviewer-briefing-builder.d.ts +1 -1
  25. package/src/scripts/workflow/reviewer-briefing-builder.js +5 -5
  26. package/src/scripts/workflow/reviewer-briefing-builder.js.map +1 -1
@@ -10,7 +10,7 @@ export declare class ProvenanceReport {
10
10
  constructor(verified: boolean, evidence: ReviewerEvidence[]);
11
11
  }
12
12
  /**
13
- * Proves each checklist verdict came from its OWN independently-run reviewer subagent, and records what
13
+ * Proves each checklist verdict came from an independently-run reviewer subagent, and records what
14
14
  * each one read.
15
15
  *
16
16
  * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam
@@ -100,7 +100,7 @@ export declare class ProvenanceEnforcer {
100
100
  * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.
101
101
  * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.
102
102
  *
103
- * Returns the agentTypes rather than a finished sentence so the caller can count CHECKLISTS at fault —
103
+ * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —
104
104
  * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.
105
105
  */
106
106
  private blindReviewers;
@@ -22,7 +22,7 @@ class ProvenanceReport {
22
22
  }
23
23
  exports.ProvenanceReport = ProvenanceReport;
24
24
  /**
25
- * Proves each checklist verdict came from its OWN independently-run reviewer subagent, and records what
25
+ * Proves each checklist verdict came from an independently-run reviewer subagent, and records what
26
26
  * each one read.
27
27
  *
28
28
  * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam
@@ -63,21 +63,25 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
63
63
  const result = (0, child_process_1.spawnSync)('git', args, { encoding: 'utf8' });
64
64
  return result.status === 0 ? (result.stdout ?? '').trim() : '';
65
65
  }
66
- // Enforce that EACH matched checklist was reviewed by its OWN named subagent, as a DISTINCT run —
67
- // the coding agent may not self-certify, and one reviewer may not stand in for several. A verified set
68
- // passes silently; no session id warns but passes; any missing reviewer throws so the PR does not open.
66
+ // Enforce that EACH matched checklist was reviewed by a subagent of the repo's reviewer agent type — the
67
+ // coding agent may not self-certify. Without `reviewerAgents` each checklist needs a DISTINCT run (one
68
+ // reviewer may not stand in for several); with it, one run may cover several checklists, because that
69
+ // grouping is what the repo configured. A verified set passes silently; no session id warns but passes;
70
+ // any missing reviewer throws so the PR does not open.
69
71
  // eslint-disable-next-line @typescript-eslint/max-params
70
72
  enforce(required, branch, repoRoot, config) {
71
73
  const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified
72
- const subagents = required.map((r) => r.subagent.trim()).filter((s) => s !== '');
74
+ const expected = required
75
+ .filter((r) => r.reviewer.agentName.trim() !== '')
76
+ .map((r) => new rules_config_1.ExpectedReviewer(r.id, r.reviewer.agentName.trim()));
73
77
  const context = this.contextFor(repoRoot, required, branch);
74
- // verifyDistinct short-circuits to OK on an empty set, so this runs unconditionally: a repo with no
78
+ // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no
75
79
  // checklists still gets a provenance record naming the session and the main agent's own transcript.
76
- const result = this.provenance.verifyDistinct(subagents, context);
80
+ const result = this.provenance.verifyReviewers(expected, context, config.reviewer.grouped());
77
81
  report.verified = result.status === rules_config_1.PROVENANCE_OK;
78
82
  if (result.status === rules_config_1.PROVENANCE_SKIPPED)
79
83
  process.stderr.write(`⚠️ ${result.detail}\n`);
80
- report.evidence = this.provenance.evidenceFor(context, result.agentIds);
84
+ report.evidence = this.provenance.evidenceFor(context, expected, result.agentIds);
81
85
  const blind = this.blindReviewers(report.evidence, config);
82
86
  // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record
83
87
  // that only ever appeared on success could not answer what the reviewers did the time it was refused.
@@ -110,7 +114,8 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
110
114
  if (result.status === rules_config_1.PROVENANCE_MISSING && missing.length === 0)
111
115
  paragraphs.push(result.detail);
112
116
  if (neverRan.length > 0) {
113
- paragraphs.push(`these reviewer subagents did not run on this branch (spawn each as its OWN subagent — do not self-certify): ${neverRan.join(', ')}`);
117
+ paragraphs.push('no reviewer subagent ran on this branch for these checklists (spawn the reviewer agent that ' +
118
+ `pnpm wp-review-upsert-pr names — do not self-certify): ${neverRan.join(', ')}`);
114
119
  }
115
120
  if (unattributed.length > 0)
116
121
  paragraphs.push(this.unattributedMessage(unattributed, context));
@@ -156,11 +161,8 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
156
161
  const docPaths = {};
157
162
  const verdictPaths = {};
158
163
  for (const req of required) {
159
- const type = req.subagent.trim();
160
- if (type === '')
161
- continue;
162
- docPaths[type] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);
163
- verdictPaths[type] = this.reviewJsonService.checklistResultPath((0, rules_config_1.reviewJsonPath)(repoRoot, featureName), req.id);
164
+ docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);
165
+ verdictPaths[req.id] = this.reviewJsonService.checklistResultPath((0, rules_config_1.reviewJsonPath)(repoRoot, featureName), req.id);
164
166
  }
165
167
  return new rules_config_1.ReviewerContext(branch, path.join((0, rules_config_1.prDirFor)(repoRoot, featureName), 'diff'), docPaths, verdictPaths);
166
168
  }
@@ -187,18 +189,18 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
187
189
  const prDir = (0, rules_config_1.prDirFor)(repoRoot, featureName);
188
190
  const request = new rules_config_1.ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);
189
191
  request.offered = new rules_config_1.OfferedContext(path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));
190
- request.reviewers = evidence.map((e) => new rules_config_1.ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.agentType)));
192
+ request.reviewers = evidence.map((e) => new rules_config_1.ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));
191
193
  const written = this.provenanceRecord.write(request);
192
194
  if (written !== '')
193
195
  process.stdout.write(` transcript provenance → ${written}\n`);
194
196
  }
195
- // Where ONE reviewer's verdict, instructions and checklist doc live. Keyed by agentType, which IS the
196
- // checklist id: ChecklistDefinition sets `id = subagent`, so the two never diverge.
197
+ // Where ONE checklist's verdict, instructions and doc live — keyed by the checklist id, never by the
198
+ // agent type, which every checklist now shares.
197
199
  // eslint-disable-next-line @typescript-eslint/max-params
198
- reviewerPathsFor(repoRoot, featureName, required, agentType) {
199
- const req = required.find((r) => r.subagent.trim() === agentType);
200
+ reviewerPathsFor(repoRoot, featureName, required, checklistId) {
201
+ const req = required.find((r) => r.id === checklistId);
200
202
  const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';
201
- return new rules_config_1.ReviewerPaths(this.reviewJsonService.checklistResultPath((0, rules_config_1.reviewJsonPath)(repoRoot, featureName), req?.id ?? agentType), this.reviewerInstructions.pathFor(repoRoot, featureName, agentType), doc);
203
+ return new rules_config_1.ReviewerPaths(this.reviewJsonService.checklistResultPath((0, rules_config_1.reviewJsonPath)(repoRoot, featureName), checklistId), this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId), doc);
202
204
  }
203
205
  /**
204
206
  * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for
@@ -208,14 +210,14 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
208
210
  * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.
209
211
  * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.
210
212
  *
211
- * Returns the agentTypes rather than a finished sentence so the caller can count CHECKLISTS at fault —
213
+ * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —
212
214
  * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.
213
215
  */
214
216
  blindReviewers(evidence, config) {
215
217
  const blind = evidence.filter((e) => !e.readDiff);
216
218
  if (blind.length === 0)
217
219
  return [];
218
- const names = blind.map((e) => e.agentType);
220
+ const names = blind.map((e) => e.checklistId);
219
221
  if (config.requireDiffEvidence)
220
222
  return names;
221
223
  process.stderr.write(`\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\n` +
@@ -1 +1 @@
1
- {"version":3,"file":"provenance-enforcer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/provenance-enforcer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,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ChB,SAAS,KAAK,CAAC,MAAM,8EAA8E,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YACvH,yGAAyG,CAAC,CAAC;QAC/G,OAAO,EAAE,CAAC;IACd,CAAC;CACJ,CAAA;AAnMY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIF,mCAAY;QACd,wCAAyB;QACnB,sCAAuB;QACnB,0CAA2B;QAC9B,gCAAiB;GAPhD,kBAAkB,CAmM9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n prDirFor, reviewJsonPath, RequiredChecklist, PrGateConfig, ReviewJsonService,\n SubagentProvenanceService, PROVENANCE_OK, PROVENANCE_MISSING, PROVENANCE_SKIPPED,\n ProvenanceResult, ReviewerEvidence, ReviewerContext,\n ReviewProvenanceService, ProvenanceWriteRequest, ReviewerTranscript, ReviewerPaths, OfferedContext,\n ReviewerInstructionsService, InformAiError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from './git-readAiBranchName';\n\n/**\n * The provenance outcome: whether each reviewer was VERIFIED to have run (the integrity check, which\n * blocks) plus what each one actually read (the quality signal, which is published). Data-only.\n */\nexport class ProvenanceReport {\n verified: boolean;\n evidence: ReviewerEvidence[];\n\n constructor(verified: boolean, evidence: ReviewerEvidence[]) {\n this.verified = verified;\n this.evidence = evidence;\n }\n}\n\n/**\n * Proves each checklist verdict came from its OWN independently-run reviewer subagent, and records what\n * each one read.\n *\n * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam\n * twice over: this is a self-contained integrity check with its own spec\n * (`finish-provenance-record.spec.ts`), and that spec previously had to reach through\n * `command as unknown as { enforceProvenance(...) }` to get at it. Now `enforce` is simply public.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProvenanceEnforcer {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly aiBranchName: AiBranchName,\n private readonly provenance: SubagentProvenanceService,\n private readonly provenanceRecord: ReviewProvenanceService,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly reviewJsonService: ReviewJsonService,\n ) {}\n\n /**\n * Archive this round's provenance.json alongside the archived review.json, so an archived review keeps\n * the transcript links belonging to the round that produced it — a record overwritten by the NEXT\n * round audits nothing.\n *\n * Here rather than in the command because this class owns the record; the command only knows WHEN to\n * archive, not what the record is.\n */\n archiveRecord(prDir: string): void {\n this.provenanceRecord.archive(prDir);\n }\n\n // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades\n // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Enforce that EACH matched checklist was reviewed by its OWN named subagent, as a DISTINCT run —\n // the coding agent may not self-certify, and one reviewer may not stand in for several. A verified set\n // passes silently; no session id warns but passes; any missing reviewer throws so the PR does not open.\n // eslint-disable-next-line @typescript-eslint/max-params\n enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport {\n const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified\n const subagents = required.map((r: RequiredChecklist): string => r.subagent.trim()).filter((s: string): boolean => s !== '');\n const context = this.contextFor(repoRoot, required, branch);\n // verifyDistinct short-circuits to OK on an empty set, so this runs unconditionally: a repo with no\n // checklists still gets a provenance record naming the session and the main agent's own transcript.\n const result = this.provenance.verifyDistinct(subagents, context);\n report.verified = result.status === PROVENANCE_OK;\n if (result.status === PROVENANCE_SKIPPED) process.stderr.write(`⚠️ ${result.detail}\\n`);\n report.evidence = this.provenance.evidenceFor(context, result.agentIds);\n const blind = this.blindReviewers(report.evidence, config);\n // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record\n // that only ever appeared on success could not answer what the reviewers did the time it was refused.\n this.writeProvenanceRecord(repoRoot, required, result, report.evidence);\n this.refuse(result, blind, context);\n return report;\n }\n\n /**\n * Refuse — with an instruction that matches WHICH failure this is.\n *\n * The count is the number of CHECKLISTS at fault, not the number of message paragraphs. It used to be\n * `errors.length`, which printed \"1 checklist(s) require …\" above a list of seven names.\n *\n * The split matters more than the count. A checklist with no verdict file needs a reviewer spawned. A\n * checklist WITH one needs the opposite: the reviewer already ran, the verdict is on disk, and only the\n * attribution failed — so telling an agent to \"spawn each as its OWN subagent\" makes it overwrite seven\n * verdicts with runs that are stamped identically and refused identically. That is a loop that destroys\n * evidence on every iteration, and it is what the previous single message guaranteed.\n *\n * The BLOCK decision is the STATUS, not the length of `missing`. Those agree today — but a\n * `PROVENANCE_MISSING` that arrived carrying no names would otherwise be a silent pass: reported\n * unverified and refused by nothing. Refusing on the status makes the unverified verdict block whatever\n * else is true, and `detail` carries the wording when there are no names to word it from.\n */\n private refuse(result: ProvenanceResult, blind: readonly string[], context: ReviewerContext): void {\n const missing = result.missing;\n const neverRan = missing.filter((t: string): boolean => !fs.existsSync(context.verdictPaths[t] ?? ''));\n const unattributed = missing.filter((t: string): boolean => fs.existsSync(context.verdictPaths[t] ?? ''));\n const paragraphs: string[] = [];\n if (result.status === PROVENANCE_MISSING && missing.length === 0) paragraphs.push(result.detail);\n if (neverRan.length > 0) {\n paragraphs.push(\n `these reviewer subagents did not run on this branch (spawn each as its OWN subagent — do not self-certify): ${neverRan.join(', ')}`);\n }\n if (unattributed.length > 0) paragraphs.push(this.unattributedMessage(unattributed, context));\n if (blind.length > 0) {\n paragraphs.push(`these reviewers wrote a verdict without opening the diff (pr-gate.requireDiffEvidence is on): ${blind.join(', ')}`);\n }\n if (paragraphs.length === 0) return;\n // The UNION, because one checklist can be both unattributed and blind, and counting the paragraphs\n // is what printed \"1 checklist(s) require …\" above a list of seven names. Floored at 1 so the\n // nameless-MISSING case above cannot announce \"0 checklist(s) failed\" and then refuse.\n const atFault = Math.max(new Set([...missing, ...blind]).size, 1);\n throw new InformAiError(\n `${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n paragraphs.map((e: string): string => ` • ${e}`).join('\\n\\n'));\n }\n\n /**\n * The verdict exists but nothing can prove WHICH branch its reviewer looked at.\n *\n * Reachable when a session rooted in the PRIMARY CLONE spawns reviewers for a branch that lives in a\n * linked worktree: the harness stamps record 0 from the spawning session's cwd (the Agent tool has no\n * cwd parameter), so every respawn is stamped identically and re-spawning cannot change the outcome.\n * Saying so is the whole point of this message — the remedy is a session rooted in the worktree, or a\n * reviewer that names this branch's own files.\n */\n private unattributedMessage(unattributed: readonly string[], context: ReviewerContext): string {\n return `these reviewers WROTE a verdict for this branch that provenance cannot attribute to them: ${unattributed.join(', ')}\\n` +\n ` Do NOT re-spawn them. A re-spawn overwrites the verdict file it already wrote and is stamped with the\\n` +\n ` same cwd, so it is refused again — that loop destroys the verdicts and cannot change the outcome.\\n` +\n ` A reviewer is attributed when it names this branch's own files: its verdict\\n` +\n ` (${context.verdictPaths[unattributed[0]] ?? '<verdict path>'}) or the extracted diff (${context.diffDir}).\\n` +\n ` If the reviewers ran before pnpm wp-review-upsert-pr materialized that diff, re-run this from a Claude\\n` +\n ` Code session whose cwd IS the worktree holding ${context.branch} — that is the only cwd the harness will\\n` +\n ` stamp on them.`;\n }\n\n /**\n * WHERE this branch's review materials live — the paths BOTH provenance passes compare against.\n *\n * One object for crediting and for evidence: they ask different questions of the same files, and\n * building the paths twice is how the two could drift apart.\n */\n private contextFor(repoRoot: string, required: readonly RequiredChecklist[], branch: string): ReviewerContext {\n const featureName = this.aiBranchName.getFeatureName();\n const docPaths: Record<string, string> = {};\n const verdictPaths: Record<string, string> = {};\n for (const req of required) {\n const type = req.subagent.trim();\n if (type === '') continue;\n docPaths[type] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n verdictPaths[type] = this.reviewJsonService.checklistResultPath(reviewJsonPath(repoRoot, featureName), req.id);\n }\n return new ReviewerContext(branch, path.join(prDirFor(repoRoot, featureName), 'diff'), docPaths, verdictPaths);\n }\n\n /**\n * Write this round's audit record: `.webpieces/pr-review/<featureSlug>/provenance.json`, linking each\n * verdict to the transcript of the subagent that produced it.\n *\n * `<featureSlug>`, not `<branch>`: the dir is named by `AiBranchName.getFeatureName()`, which\n * dash-sanitizes the branch. Calling it `<branch>` is what led a bug reporter to conclude the gate\n * must be comparing a dash-form name against a slash-form git branch — see\n * ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.\n *\n * A SEPARATE file rather than a field inside review.json / review-<id>.json, for two reasons. The\n * reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no\n * agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files\n * byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about\n * itself. Every path here is derived by the tooling from the harness's own artifacts.\n *\n * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeProvenanceRecord(repoRoot: string, required: readonly RequiredChecklist[], result: ProvenanceResult, evidence: readonly ReviewerEvidence[]): void {\n const featureName = this.aiBranchName.getFeatureName();\n const prDir = prDirFor(repoRoot, featureName);\n const request = new ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);\n request.offered = new OfferedContext(\n path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));\n request.reviewers = evidence.map((e: ReviewerEvidence): ReviewerTranscript =>\n new ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.agentType)));\n const written = this.provenanceRecord.write(request);\n if (written !== '') process.stdout.write(` transcript provenance → ${written}\\n`);\n }\n\n // Where ONE reviewer's verdict, instructions and checklist doc live. Keyed by agentType, which IS the\n // checklist id: ChecklistDefinition sets `id = subagent`, so the two never diverge.\n // eslint-disable-next-line @typescript-eslint/max-params\n private reviewerPathsFor(repoRoot: string, featureName: string, required: readonly RequiredChecklist[], agentType: string): ReviewerPaths {\n const req = required.find((r: RequiredChecklist): boolean => r.subagent.trim() === agentType);\n const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';\n return new ReviewerPaths(\n this.reviewJsonService.checklistResultPath(reviewJsonPath(repoRoot, featureName), req?.id ?? agentType),\n this.reviewerInstructions.pathFor(repoRoot, featureName, agentType),\n doc,\n );\n }\n\n /**\n * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for\n * {@link refuse} to block on (opt-in).\n *\n * Default-warn because the signal is derived from undocumented Claude Code transcript internals: if the\n * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.\n * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.\n *\n * Returns the agentTypes rather than a finished sentence so the caller can count CHECKLISTS at fault —\n * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.\n */\n private blindReviewers(evidence: readonly ReviewerEvidence[], config: PrGateConfig): string[] {\n const blind = evidence.filter((e: ReviewerEvidence): boolean => !e.readDiff);\n if (blind.length === 0) return [];\n const names = blind.map((e: ReviewerEvidence): string => e.agentType);\n if (config.requireDiffEvidence) return names;\n process.stderr.write(\n `\\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\\n` +\n ' Published on the PR as a note. Not blocking — set pr-gate.requireDiffEvidence:true to make it one.\\n');\n return [];\n }\n}\n"]}
1
+ {"version":3,"file":"provenance-enforcer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/provenance-enforcer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAMiC;AACjC,yCAA2D;AAC3D,iEAAsD;AAEtD;;;GAGG;AACH,MAAa,gBAAgB;IACzB,QAAQ,CAAU;IAClB,QAAQ,CAAqB;IAE7B,YAAY,QAA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IAAI,CAAC,IAAI,CAAC,IAAI;YACvH,yGAAyG,CAAC,CAAC;QAC/G,OAAO,EAAE,CAAC;IACd,CAAC;CACJ,CAAA;AAtMY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIF,mCAAY;QACd,wCAAyB;QACnB,sCAAuB;QACnB,0CAA2B;QAC9B,gCAAiB;GAPhD,kBAAkB,CAsM9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n prDirFor, reviewJsonPath, RequiredChecklist, PrGateConfig, ReviewJsonService,\n SubagentProvenanceService, PROVENANCE_OK, PROVENANCE_MISSING, PROVENANCE_SKIPPED,\n ProvenanceResult, ReviewerEvidence, ReviewerContext, ExpectedReviewer,\n ReviewProvenanceService, ProvenanceWriteRequest, ReviewerTranscript, ReviewerPaths, OfferedContext,\n ReviewerInstructionsService, InformAiError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from './git-readAiBranchName';\n\n/**\n * The provenance outcome: whether each reviewer was VERIFIED to have run (the integrity check, which\n * blocks) plus what each one actually read (the quality signal, which is published). Data-only.\n */\nexport class ProvenanceReport {\n verified: boolean;\n evidence: ReviewerEvidence[];\n\n constructor(verified: boolean, evidence: ReviewerEvidence[]) {\n this.verified = verified;\n this.evidence = evidence;\n }\n}\n\n/**\n * Proves each checklist verdict came from an independently-run reviewer subagent, and records what\n * each one read.\n *\n * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam\n * twice over: this is a self-contained integrity check with its own spec\n * (`finish-provenance-record.spec.ts`), and that spec previously had to reach through\n * `command as unknown as { enforceProvenance(...) }` to get at it. Now `enforce` is simply public.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProvenanceEnforcer {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly aiBranchName: AiBranchName,\n private readonly provenance: SubagentProvenanceService,\n private readonly provenanceRecord: ReviewProvenanceService,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly reviewJsonService: ReviewJsonService,\n ) {}\n\n /**\n * Archive this round's provenance.json alongside the archived review.json, so an archived review keeps\n * the transcript links belonging to the round that produced it — a record overwritten by the NEXT\n * round audits nothing.\n *\n * Here rather than in the command because this class owns the record; the command only knows WHEN to\n * archive, not what the record is.\n */\n archiveRecord(prDir: string): void {\n this.provenanceRecord.archive(prDir);\n }\n\n // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades\n // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Enforce that EACH matched checklist was reviewed by a subagent of the repo's reviewer agent type — the\n // coding agent may not self-certify. Without `reviewerAgents` each checklist needs a DISTINCT run (one\n // reviewer may not stand in for several); with it, one run may cover several checklists, because that\n // grouping is what the repo configured. A verified set passes silently; no session id warns but passes;\n // any missing reviewer throws so the PR does not open.\n // eslint-disable-next-line @typescript-eslint/max-params\n enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport {\n const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified\n const expected = required\n .filter((r: RequiredChecklist): boolean => r.reviewer.agentName.trim() !== '')\n .map((r: RequiredChecklist): ExpectedReviewer => new ExpectedReviewer(r.id, r.reviewer.agentName.trim()));\n const context = this.contextFor(repoRoot, required, branch);\n // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no\n // checklists still gets a provenance record naming the session and the main agent's own transcript.\n const result = this.provenance.verifyReviewers(expected, context, config.reviewer.grouped());\n report.verified = result.status === PROVENANCE_OK;\n if (result.status === PROVENANCE_SKIPPED) process.stderr.write(`⚠️ ${result.detail}\\n`);\n report.evidence = this.provenance.evidenceFor(context, expected, result.agentIds);\n const blind = this.blindReviewers(report.evidence, config);\n // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record\n // that only ever appeared on success could not answer what the reviewers did the time it was refused.\n this.writeProvenanceRecord(repoRoot, required, result, report.evidence);\n this.refuse(result, blind, context);\n return report;\n }\n\n /**\n * Refuse — with an instruction that matches WHICH failure this is.\n *\n * The count is the number of CHECKLISTS at fault, not the number of message paragraphs. It used to be\n * `errors.length`, which printed \"1 checklist(s) require …\" above a list of seven names.\n *\n * The split matters more than the count. A checklist with no verdict file needs a reviewer spawned. A\n * checklist WITH one needs the opposite: the reviewer already ran, the verdict is on disk, and only the\n * attribution failed — so telling an agent to \"spawn each as its OWN subagent\" makes it overwrite seven\n * verdicts with runs that are stamped identically and refused identically. That is a loop that destroys\n * evidence on every iteration, and it is what the previous single message guaranteed.\n *\n * The BLOCK decision is the STATUS, not the length of `missing`. Those agree today — but a\n * `PROVENANCE_MISSING` that arrived carrying no names would otherwise be a silent pass: reported\n * unverified and refused by nothing. Refusing on the status makes the unverified verdict block whatever\n * else is true, and `detail` carries the wording when there are no names to word it from.\n */\n private refuse(result: ProvenanceResult, blind: readonly string[], context: ReviewerContext): void {\n const missing = result.missing;\n const neverRan = missing.filter((t: string): boolean => !fs.existsSync(context.verdictPaths[t] ?? ''));\n const unattributed = missing.filter((t: string): boolean => fs.existsSync(context.verdictPaths[t] ?? ''));\n const paragraphs: string[] = [];\n if (result.status === PROVENANCE_MISSING && missing.length === 0) paragraphs.push(result.detail);\n if (neverRan.length > 0) {\n paragraphs.push(\n 'no reviewer subagent ran on this branch for these checklists (spawn the reviewer agent that ' +\n `pnpm wp-review-upsert-pr names — do not self-certify): ${neverRan.join(', ')}`);\n }\n if (unattributed.length > 0) paragraphs.push(this.unattributedMessage(unattributed, context));\n if (blind.length > 0) {\n paragraphs.push(`these reviewers wrote a verdict without opening the diff (pr-gate.requireDiffEvidence is on): ${blind.join(', ')}`);\n }\n if (paragraphs.length === 0) return;\n // The UNION, because one checklist can be both unattributed and blind, and counting the paragraphs\n // is what printed \"1 checklist(s) require …\" above a list of seven names. Floored at 1 so the\n // nameless-MISSING case above cannot announce \"0 checklist(s) failed\" and then refuse.\n const atFault = Math.max(new Set([...missing, ...blind]).size, 1);\n throw new InformAiError(\n `${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n paragraphs.map((e: string): string => ` • ${e}`).join('\\n\\n'));\n }\n\n /**\n * The verdict exists but nothing can prove WHICH branch its reviewer looked at.\n *\n * Reachable when a session rooted in the PRIMARY CLONE spawns reviewers for a branch that lives in a\n * linked worktree: the harness stamps record 0 from the spawning session's cwd (the Agent tool has no\n * cwd parameter), so every respawn is stamped identically and re-spawning cannot change the outcome.\n * Saying so is the whole point of this message — the remedy is a session rooted in the worktree, or a\n * reviewer that names this branch's own files.\n */\n private unattributedMessage(unattributed: readonly string[], context: ReviewerContext): string {\n return `these reviewers WROTE a verdict for this branch that provenance cannot attribute to them: ${unattributed.join(', ')}\\n` +\n ` Do NOT re-spawn them. A re-spawn overwrites the verdict file it already wrote and is stamped with the\\n` +\n ` same cwd, so it is refused again — that loop destroys the verdicts and cannot change the outcome.\\n` +\n ` A reviewer is attributed when it names this branch's own files: its verdict\\n` +\n ` (${context.verdictPaths[unattributed[0]] ?? '<verdict path>'}) or the extracted diff (${context.diffDir}).\\n` +\n ` If the reviewers ran before pnpm wp-review-upsert-pr materialized that diff, re-run this from a Claude\\n` +\n ` Code session whose cwd IS the worktree holding ${context.branch} — that is the only cwd the harness will\\n` +\n ` stamp on them.`;\n }\n\n /**\n * WHERE this branch's review materials live — the paths BOTH provenance passes compare against.\n *\n * One object for crediting and for evidence: they ask different questions of the same files, and\n * building the paths twice is how the two could drift apart.\n */\n private contextFor(repoRoot: string, required: readonly RequiredChecklist[], branch: string): ReviewerContext {\n const featureName = this.aiBranchName.getFeatureName();\n const docPaths: Record<string, string> = {};\n const verdictPaths: Record<string, string> = {};\n for (const req of required) {\n docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n verdictPaths[req.id] = this.reviewJsonService.checklistResultPath(reviewJsonPath(repoRoot, featureName), req.id);\n }\n return new ReviewerContext(branch, path.join(prDirFor(repoRoot, featureName), 'diff'), docPaths, verdictPaths);\n }\n\n /**\n * Write this round's audit record: `.webpieces/pr-review/<featureSlug>/provenance.json`, linking each\n * verdict to the transcript of the subagent that produced it.\n *\n * `<featureSlug>`, not `<branch>`: the dir is named by `AiBranchName.getFeatureName()`, which\n * dash-sanitizes the branch. Calling it `<branch>` is what led a bug reporter to conclude the gate\n * must be comparing a dash-form name against a slash-form git branch — see\n * ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.\n *\n * A SEPARATE file rather than a field inside review.json / review-<id>.json, for two reasons. The\n * reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no\n * agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files\n * byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about\n * itself. Every path here is derived by the tooling from the harness's own artifacts.\n *\n * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeProvenanceRecord(repoRoot: string, required: readonly RequiredChecklist[], result: ProvenanceResult, evidence: readonly ReviewerEvidence[]): void {\n const featureName = this.aiBranchName.getFeatureName();\n const prDir = prDirFor(repoRoot, featureName);\n const request = new ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);\n request.offered = new OfferedContext(\n path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));\n request.reviewers = evidence.map((e: ReviewerEvidence): ReviewerTranscript =>\n new ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));\n const written = this.provenanceRecord.write(request);\n if (written !== '') process.stdout.write(` transcript provenance → ${written}\\n`);\n }\n\n // Where ONE checklist's verdict, instructions and doc live — keyed by the checklist id, never by the\n // agent type, which every checklist now shares.\n // eslint-disable-next-line @typescript-eslint/max-params\n private reviewerPathsFor(repoRoot: string, featureName: string, required: readonly RequiredChecklist[], checklistId: string): ReviewerPaths {\n const req = required.find((r: RequiredChecklist): boolean => r.id === checklistId);\n const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';\n return new ReviewerPaths(\n this.reviewJsonService.checklistResultPath(reviewJsonPath(repoRoot, featureName), checklistId),\n this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId),\n doc,\n );\n }\n\n /**\n * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for\n * {@link refuse} to block on (opt-in).\n *\n * Default-warn because the signal is derived from undocumented Claude Code transcript internals: if the\n * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.\n * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.\n *\n * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —\n * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.\n */\n private blindReviewers(evidence: readonly ReviewerEvidence[], config: PrGateConfig): string[] {\n const blind = evidence.filter((e: ReviewerEvidence): boolean => !e.readDiff);\n if (blind.length === 0) return [];\n const names = blind.map((e: ReviewerEvidence): string => e.checklistId);\n if (config.requireDiffEvidence) return names;\n process.stderr.write(\n `\\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\\n` +\n ' Published on the PR as a note. Not blocking — set pr-gate.requireDiffEvidence:true to make it one.\\n');\n return [];\n }\n}\n"]}
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Specs that exercise a command end-to-end need a config the REAL validator accepts, and using the
5
5
  * repo's own file (rather than a hand-rolled minimal one) is what keeps them honest — a stub drifts out
6
- * from under the validator on the next config change. Two adjustments are needed to make that file
7
- * usable outside this checkout, and both are the same for every such spec, so they live here once:
6
+ * from under the validator on the next config change. These adjustments are needed to make that file
7
+ * usable outside this checkout, and all are the same for every such spec, so they live here once:
8
8
  *
9
9
  * 1. `checklists` is dropped. Its `doc` paths are validated REPO-RELATIVE and point at
10
10
  * `.claude/review/*.md`, which exist here and not in a temp clone.
@@ -18,6 +18,9 @@
18
18
  * is retired in this working tree, the repo's config must KEEP its entry until the release carrying
19
19
  * the retirement ships (deleting it early would fail the published validator and block every Bash
20
20
  * call), while the LOCAL validator already REJECTS it. Same trade as (2), same fix.
21
+ * 4. A newly-required `commands.pr-gate` key is completed the same way, when absent — today that is
22
+ * `reviewerAgentName` (issue #938), which the published validator does not know yet, so the repo's
23
+ * config cannot carry it until that release ships.
21
24
  *
22
25
  * A testkit, not product code: nothing in a published bin imports it (same role as ai-hook-rules'
23
26
  * `shim-testkit.ts`).
@@ -10,8 +10,8 @@ const rules_config_1 = require("@webpieces/rules-config");
10
10
  *
11
11
  * Specs that exercise a command end-to-end need a config the REAL validator accepts, and using the
12
12
  * repo's own file (rather than a hand-rolled minimal one) is what keeps them honest — a stub drifts out
13
- * from under the validator on the next config change. Two adjustments are needed to make that file
14
- * usable outside this checkout, and both are the same for every such spec, so they live here once:
13
+ * from under the validator on the next config change. These adjustments are needed to make that file
14
+ * usable outside this checkout, and all are the same for every such spec, so they live here once:
15
15
  *
16
16
  * 1. `checklists` is dropped. Its `doc` paths are validated REPO-RELATIVE and point at
17
17
  * `.claude/review/*.md`, which exist here and not in a temp clone.
@@ -25,6 +25,9 @@ const rules_config_1 = require("@webpieces/rules-config");
25
25
  * is retired in this working tree, the repo's config must KEEP its entry until the release carrying
26
26
  * the retirement ships (deleting it early would fail the published validator and block every Bash
27
27
  * call), while the LOCAL validator already REJECTS it. Same trade as (2), same fix.
28
+ * 4. A newly-required `commands.pr-gate` key is completed the same way, when absent — today that is
29
+ * `reviewerAgentName` (issue #938), which the published validator does not know yet, so the repo's
30
+ * config cannot carry it until that release ships.
28
31
  *
29
32
  * A testkit, not product code: nothing in a published bin imports it (same role as ai-hook-rules'
30
33
  * `shim-testkit.ts`).
@@ -40,6 +43,7 @@ class RepoConfigFixture {
40
43
  const commands = config['commands'];
41
44
  delete commands['pr-gate']['checklists'];
42
45
  delete commands['pr-gate']['checklistsWhy'];
46
+ commands['pr-gate']['reviewerAgentName'] ??= rules_config_1.DEFAULT_REVIEWER_AGENT_NAME;
43
47
  this.dropRetiredRules(config);
44
48
  this.completeRulesFromSeed(config);
45
49
  return config;
@@ -1 +1 @@
1
- {"version":3,"file":"repo-config-testkit.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/repo-config-testkit.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAE7B,0DAAyG;AAEzG;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,iBAAiB;IAC1B,iGAAiG;IACjG,mGAAmG;IACnG,IAAI;QACA,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,uBAAuB,CAAC,CAAC;QACjG,mFAAmF;QACnF,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,CAA4B,CAAC;QACtF,mEAAmE;QACnE,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAA4C,CAAC;QAC/E,OAAO,QAAQ,CAAC,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;QACzC,OAAO,QAAQ,CAAC,SAAS,CAAC,CAAC,eAAe,CAAC,CAAC;QAC5C,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;QACnC,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,8FAA8F;IAC9F,iDAAiD;IACzC,gBAAgB,CAAC,MAA+B;QACpD,KAAK,MAAM,OAAO,I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AAI,EAAE,GAAG,QAAQ,EAAE,CAAC;QAC7E,CAAC;IACL,CAAC;CACJ;AAjDD,8CAiDC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport { allRuleNames, retiredRuleFor, sectionForRule, seedEntryForRule } from '@webpieces/rules-config';\n\n/**\n * THIS repo's own `webpieces.config.json`, prepared for use inside a temp clone.\n *\n * Specs that exercise a command end-to-end need a config the REAL validator accepts, and using the\n * repo's own file (rather than a hand-rolled minimal one) is what keeps them honest — a stub drifts out\n * from under the validator on the next config change. Two adjustments are needed to make that file\n * usable outside this checkout, and both are the same for every such spec, so they live here once:\n *\n * 1. `checklists` is dropped. Its `doc` paths are validated REPO-RELATIVE and point at\n * `.claude/review/*.md`, which exist here and not in a temp clone.\n * 2. Every locally-known rule is completed from its SEED. The repo's config is validated by the PUBLISHED\n * validator and therefore lags local source by one release\n * (`.claude/rules/published-vs-local-source.md`): a rule added in this working tree cannot get a\n * config entry or newly-required field until its release ships,\n * while the LOCAL validator a spec runs already demands one. Without this, adding any rule turns\n * these specs red for exactly one release — a failure that says nothing about the code under test.\n * 3. Every RETIRED rule entry is dropped — the same one-release lag pointing the other way. When a rule\n * is retired in this working tree, the repo's config must KEEP its entry until the release carrying\n * the retirement ships (deleting it early would fail the published validator and block every Bash\n * call), while the LOCAL validator already REJECTS it. Same trade as (2), same fix.\n *\n * A testkit, not product code: nothing in a published bin imports it (same role as ai-hook-rules'\n * `shim-testkit.ts`).\n */\nexport class RepoConfigFixture {\n /** The repo's config as a mutable object, checklists dropped and local seed fields completed. */\n // webpieces-disable no-any-unknown -- the repo's own config document, opaque until a spec edits it\n load(): Record<string, unknown> {\n const source = path.join(__dirname, '..', '..', '..', '..', '..', '..', 'webpieces.config.json');\n // webpieces-disable no-any-unknown -- parsed JSON, narrowed by the accessors below\n const config = JSON.parse(fs.readFileSync(source, 'utf8')) as Record<string, unknown>;\n // webpieces-disable no-any-unknown -- narrowing one nested section\n const commands = config['commands'] as Record<string, Record<string, unknown>>;\n delete commands['pr-gate']['checklists'];\n delete commands['pr-gate']['checklistsWhy'];\n this.dropRetiredRules(config);\n this.completeRulesFromSeed(config);\n return config;\n }\n\n // Drop every rule/guard name this build knows to be RETIRED, from whichever section holds it.\n // webpieces-disable no-any-unknown -- see load()\n private dropRetiredRules(config: Record<string, unknown>): void {\n for (const section of ['rules', 'hookGuards']) {\n // webpieces-disable no-any-unknown -- narrowing one rule section\n const entries = config[section] as Record<string, unknown> | undefined;\n if (entries === undefined) continue;\n for (const name of Object.keys(entries)) {\n if (retiredRuleFor(name) !== null) delete entries[name];\n }\n }\n }\n\n /** Write `config` (usually a `load()` result a spec has edited) as the config of `dir`. */\n // webpieces-disable no-any-unknown -- see load()\n writeTo(dir: string, config: Record<string, unknown>): void {\n fs.writeFileSync(path.join(dir, 'webpieces.config.json'), JSON.stringify(config, null, 4) + '\\n');\n }\n\n // webpieces-disable no-any-unknown -- see load()\n private completeRulesFromSeed(config: Record<string, unknown>): void {\n // webpieces-disable no-any-unknown -- narrowing the two rule sections\n const rules = config['rules'] as Record<string, unknown>;\n // webpieces-disable no-any-unknown -- narrowing the two rule sections\n const guards = config['hookGuards'] as Record<string, unknown>;\n for (const name of allRuleNames()) {\n const section = sectionForRule(name) === 'hookGuards' ? guards : rules;\n const seed = seedEntryForRule(name);\n // webpieces-disable no-any-unknown -- one rule's opaque config entry, merged over its typed seed\n const existing = section[name] as Record<string, unknown> | undefined;\n section[name] = existing === undefined ? seed : { ...seed, ...existing };\n }\n }\n}\n"]}
1
+ {"version":3,"file":"repo-config-testkit.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/repo-config-testkit.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAE7B,0DAEiC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,iBAAiB;IAC1B,iGAAiG;IACjG,mGAAmG;IACnG,IAAI;QACA,MAAM,MAAM,GAAG,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AC,GAAG,EAAE,uBAAuB,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACtG,CAAC;IAED,iDAAiD;IACzC,qBAAqB,CAAC,MAA+B;QACzD,sEAAsE;QACtE,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAA4B,CAAC;QACzD,sEAAsE;QACtE,MAAM,MAAM,GAAG,MAAM,CAAC,YAAY,CAA4B,CAAC;QAC/D,KAAK,MAAM,IAAI,IAAI,IAAA,2BAAY,GAAE,EAAE,CAAC;YAChC,MAAM,OAAO,GAAG,IAAA,6BAAc,EAAC,IAAI,CAAC,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;YACvE,MAAM,IAAI,GAAG,IAAA,+BAAgB,EAAC,IAAI,CAAC,CAAC;YACpC,iGAAiG;YACjG,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAwC,CAAC;YACtE,OAAO,CAAC,IAAI,CAAC,GAAG,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,GAAG,QAAQ,EAAE,CAAC;QAC7E,CAAC;IACL,CAAC;CACJ;AAlDD,8CAkDC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nimport {\n allRuleNames, DEFAULT_REVIEWER_AGENT_NAME, retiredRuleFor, sectionForRule, seedEntryForRule,\n} from '@webpieces/rules-config';\n\n/**\n * THIS repo's own `webpieces.config.json`, prepared for use inside a temp clone.\n *\n * Specs that exercise a command end-to-end need a config the REAL validator accepts, and using the\n * repo's own file (rather than a hand-rolled minimal one) is what keeps them honest — a stub drifts out\n * from under the validator on the next config change. These adjustments are needed to make that file\n * usable outside this checkout, and all are the same for every such spec, so they live here once:\n *\n * 1. `checklists` is dropped. Its `doc` paths are validated REPO-RELATIVE and point at\n * `.claude/review/*.md`, which exist here and not in a temp clone.\n * 2. Every locally-known rule is completed from its SEED. The repo's config is validated by the PUBLISHED\n * validator and therefore lags local source by one release\n * (`.claude/rules/published-vs-local-source.md`): a rule added in this working tree cannot get a\n * config entry or newly-required field until its release ships,\n * while the LOCAL validator a spec runs already demands one. Without this, adding any rule turns\n * these specs red for exactly one release — a failure that says nothing about the code under test.\n * 3. Every RETIRED rule entry is dropped — the same one-release lag pointing the other way. When a rule\n * is retired in this working tree, the repo's config must KEEP its entry until the release carrying\n * the retirement ships (deleting it early would fail the published validator and block every Bash\n * call), while the LOCAL validator already REJECTS it. Same trade as (2), same fix.\n * 4. A newly-required `commands.pr-gate` key is completed the same way, when absent — today that is\n * `reviewerAgentName` (issue #938), which the published validator does not know yet, so the repo's\n * config cannot carry it until that release ships.\n *\n * A testkit, not product code: nothing in a published bin imports it (same role as ai-hook-rules'\n * `shim-testkit.ts`).\n */\nexport class RepoConfigFixture {\n /** The repo's config as a mutable object, checklists dropped and local seed fields completed. */\n // webpieces-disable no-any-unknown -- the repo's own config document, opaque until a spec edits it\n load(): Record<string, unknown> {\n const source = path.join(__dirname, '..', '..', '..', '..', '..', '..', 'webpieces.config.json');\n // webpieces-disable no-any-unknown -- parsed JSON, narrowed by the accessors below\n const config = JSON.parse(fs.readFileSync(source, 'utf8')) as Record<string, unknown>;\n // webpieces-disable no-any-unknown -- narrowing one nested section\n const commands = config['commands'] as Record<string, Record<string, unknown>>;\n delete commands['pr-gate']['checklists'];\n delete commands['pr-gate']['checklistsWhy'];\n commands['pr-gate']['reviewerAgentName'] ??= DEFAULT_REVIEWER_AGENT_NAME;\n this.dropRetiredRules(config);\n this.completeRulesFromSeed(config);\n return config;\n }\n\n // Drop every rule/guard name this build knows to be RETIRED, from whichever section holds it.\n // webpieces-disable no-any-unknown -- see load()\n private dropRetiredRules(config: Record<string, unknown>): void {\n for (const section of ['rules', 'hookGuards']) {\n // webpieces-disable no-any-unknown -- narrowing one rule section\n const entries = config[section] as Record<string, unknown> | undefined;\n if (entries === undefined) continue;\n for (const name of Object.keys(entries)) {\n if (retiredRuleFor(name) !== null) delete entries[name];\n }\n }\n }\n\n /** Write `config` (usually a `load()` result a spec has edited) as the config of `dir`. */\n // webpieces-disable no-any-unknown -- see load()\n writeTo(dir: string, config: Record<string, unknown>): void {\n fs.writeFileSync(path.join(dir, 'webpieces.config.json'), JSON.stringify(config, null, 4) + '\\n');\n }\n\n // webpieces-disable no-any-unknown -- see load()\n private completeRulesFromSeed(config: Record<string, unknown>): void {\n // webpieces-disable no-any-unknown -- narrowing the two rule sections\n const rules = config['rules'] as Record<string, unknown>;\n // webpieces-disable no-any-unknown -- narrowing the two rule sections\n const guards = config['hookGuards'] as Record<string, unknown>;\n for (const name of allRuleNames()) {\n const section = sectionForRule(name) === 'hookGuards' ? guards : rules;\n const seed = seedEntryForRule(name);\n // webpieces-disable no-any-unknown -- one rule's opaque config entry, merged over its typed seed\n const existing = section[name] as Record<string, unknown> | undefined;\n section[name] = existing === undefined ? seed : { ...seed, ...existing };\n }\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { RequiredChecklist, ReviewerBriefing, ReviewerInstructionsService } from '@webpieces/rules-config';
1
+ import { ChecklistInstructionsService, RequiredChecklist, ReviewerAgentPolicy, ReviewerBriefing, ReviewerInstructionsService } from '@webpieces/rules-config';
2
2
  import { ChecklistNotice } from './checklist-notice';
3
3
  /**
4
4
  * One reviewer that ALREADY ANSWERED on this branch and refused, with the refusal rendered by
@@ -60,6 +60,7 @@ export declare class ReviewReportInput {
60
60
  singleRoundReview: boolean;
61
61
  singleRoundRepeat: boolean;
62
62
  singleRoundReviewers: string[];
63
+ reviewer: ReviewerAgentPolicy;
63
64
  constructor(repoRoot: string, featureName: string, reviewPath: string);
64
65
  }
65
66
  /**
@@ -86,7 +87,8 @@ export declare class ReviewReportInput {
86
87
  export declare class ReviewReport {
87
88
  private readonly checklistNotice;
88
89
  private readonly reviewerInstructions;
89
- constructor(checklistNotice: ChecklistNotice, reviewerInstructions: ReviewerInstructionsService);
90
+ private readonly checklistInstructions;
91
+ constructor(checklistNotice: ChecklistNotice, reviewerInstructions: ReviewerInstructionsService, checklistInstructions: ChecklistInstructionsService);
90
92
  render(input: ReviewReportInput): string;
91
93
  /**
92
94
  * Name what this block is actually about. A repo with reviewers owed is being told to SPAWN; a repo with
@@ -217,6 +219,7 @@ export declare class ReviewReport {
217
219
  * shrugging off a red verdict would make the whole exercise theater.
218
220
  */
219
221
  private offerStep;
222
+ private optionalAgentLines;
220
223
  private refusedWarning;
221
224
  private finishStep;
222
225
  private owedReviewers;
@@ -235,6 +238,23 @@ export declare class ReviewReport {
235
238
  * loop this exists to break.
236
239
  */
237
240
  private oneSpawnBlock;
241
+ /**
242
+ * HOW MANY subagents, of WHICH type — the one place this report states it, shared by the required and
243
+ * the optional step so the two cannot disagree.
244
+ *
245
+ * Without `commands.pr-gate.reviewerAgents` it is one separate subagent per checklist, as it always was.
246
+ * With it, the main AI gets a CAP and the grouping decision: the point of the key is to stop paying for
247
+ * N agents re-reading the same diff, and the AI is the one that can see which checklists belong together.
248
+ * The cap is per ROUND, so a re-run after a red verdict re-reviews only the owed checklists — the only
249
+ * ones listed — under the same cap.
250
+ */
251
+ private howManyAgents;
252
+ /**
253
+ * The ONE canonical reviewer definition, named for a harness that cannot spawn it by type. Codex has no
254
+ * registered agent types, so its subagent is generic; pointing it at the same committed file keeps one
255
+ * definition for both harnesses instead of a Codex-specific copy that drifts (#863).
256
+ */
257
+ private agentDefinitionLine;
238
258
  private leadIn;
239
259
  /**
240
260
  * The checklist's guidance doc, for OPTIONAL reviewers only.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ReviewReport = exports.ReviewReportInput = exports.RefusedReviewer = void 0;
4
4
  const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
5
6
  const inversify_1 = require("inversify");
6
7
  const rules_config_1 = require("@webpieces/rules-config");
7
8
  const checklist_notice_1 = require("./checklist-notice");
@@ -70,6 +71,8 @@ class ReviewReportInput {
70
71
  singleRoundReview;
71
72
  singleRoundRepeat;
72
73
  singleRoundReviewers;
74
+ // commands.pr-gate.reviewerAgentName + reviewerAgents: which agent type to spawn, and the per-round cap.
75
+ reviewer;
73
76
  constructor(repoRoot, featureName, reviewPath) {
74
77
  this.repoRoot = repoRoot;
75
78
  this.featureName = featureName;
@@ -86,6 +89,7 @@ class ReviewReportInput {
86
89
  this.singleRoundReview = false;
87
90
  this.singleRoundRepeat = false;
88
91
  this.singleRoundReviewers = [];
92
+ this.reviewer = new rules_config_1.ReviewerAgentPolicy('', rules_config_1.REVIEWER_AGENTS_ONE_PER_CHECKLIST);
89
93
  }
90
94
  }
91
95
  exports.ReviewReportInput = ReviewReportInput;
@@ -113,9 +117,11 @@ exports.ReviewReportInput = ReviewReportInput;
113
117
  let ReviewReport = class ReviewReport {
114
118
  checklistNotice;
115
119
  reviewerInstructions;
116
- constructor(checklistNotice, reviewerInstructions) {
120
+ checklistInstructions;
121
+ constructor(checklistNotice, reviewerInstructions, checklistInstructions) {
117
122
  this.checklistNotice = checklistNotice;
118
123
  this.reviewerInstructions = reviewerInstructions;
124
+ this.checklistInstructions = checklistInstructions;
119
125
  }
120
126
  render(input) {
121
127
  return '\n' + SEP + this.header(input) + SEP
@@ -170,7 +176,7 @@ let ReviewReport = class ReviewReport {
170
176
  // all-clear is not printed when anything is still owed — and "some reviewers are reused, others
171
177
  // must be spawned" is exactly the shape in which an agent re-spawns the reused ones too.
172
178
  for (const r of input.reviewed) {
173
- lines.push(` ✓ ${r.subagent} — already reviewed on this branch; verdict STANDS, do NOT re-spawn (review-${r.id}.json)`);
179
+ lines.push(` ✓ ${r.id} — already reviewed on this branch; verdict STANDS, do NOT re-spawn (review-${r.id}.json)`);
174
180
  }
175
181
  // A verdict file that EXISTS but is unreadable as a verdict is called out here. Without it this
176
182
  // reports the checklist as simply owed, and the AI re-runs a reviewer that already ran instead of
@@ -205,7 +211,7 @@ let ReviewReport = class ReviewReport {
205
211
  + `${required.length} of them REQUIRED:`,
206
212
  ];
207
213
  for (const r of input.suppressed) {
208
- lines.push(` • ${r.subagent}${r.required ? ' (REQUIRED — suppressed anyway)' : ' (optional)'}`);
214
+ lines.push(` • ${r.id}${r.required ? ' (REQUIRED — suppressed anyway)' : ' (optional)'}`);
209
215
  }
210
216
  lines.push('', ` Switched off by: experimental.${rules_config_1.HOME_KEY_TURN_OFF_ALL_REVIEWERS}: true`, ` Read from: ~/${rules_config_1.HOME_CONFIG_DIR}/${rules_config_1.HOME_CONFIG_FILE} (machine-local; no repo config can set this)`, '', ' There is NOTHING to spawn — no reviewer was briefed and no instructions file was written,', ' so any attempt to spawn one has nothing to read. Do NOT hand-write a verdict file in their', ' place: a fabricated verdict is worse than the absent one this flag deliberately produces.', '', ' The dashboard is the whole review product for this PR, and the suppression is carried into', ' the PR body — which is the squash-merge commit body — so main\'s history records it.', ' To get the reviewers back, set that key to false (or delete it) and re-run this command.');
211
217
  return lines.join('\n') + '\n';
@@ -222,7 +228,7 @@ let ReviewReport = class ReviewReport {
222
228
  return [
223
229
  '',
224
230
  ` ⏭️ ${skipped.length} OPTIONAL checklist(s) matched this diff and were SKIPPED (--no-optional):`,
225
- ...skipped.map((b) => ` ${b.subagent} — ${this.why(b)}`),
231
+ ...skipped.map((b) => ` ${b.checklistId} — ${this.why(b)}`),
226
232
  ' Not blocking. Drop the flag and re-run this command to offer them after all.',
227
233
  ];
228
234
  }
@@ -327,9 +333,10 @@ let ReviewReport = class ReviewReport {
327
333
  */
328
334
  spawnStep(input, owed, step, withAwait) {
329
335
  const lines = [
330
- `STEP ${step} — only once that file is written, spawn these ${owed.length} REQUIRED reviewer subagent(s) — a`,
331
- ' SEPARATE one each. They block the PR, so do NOT ask whether to run them. You may NOT',
332
- ' review your own work, and you may NOT write a reviewer\'s verdict file on its behalf.',
336
+ `STEP ${step} — only once that file is written, review these ${owed.length} REQUIRED checklist(s) with`,
337
+ ...this.howManyAgents(input, owed.length),
338
+ ' They block the PR, so do NOT ask whether to run them. You may NOT review your own',
339
+ ' work, and you may NOT write a reviewer\'s verdict file on its behalf.',
333
340
  '',
334
341
  ];
335
342
  lines.push(...this.refusedWarning(input, owed));
@@ -401,6 +408,7 @@ let ReviewReport = class ReviewReport {
401
408
  ' optional reviewer blocks the PR exactly like a required one.',
402
409
  '',
403
410
  ];
411
+ lines.push(...this.optionalAgentLines(input, offerable.length));
404
412
  lines.push(...this.refusedWarning(input, offerable));
405
413
  for (const b of offerable)
406
414
  lines.push(...this.oneSpawnBlock(input, b));
@@ -409,6 +417,24 @@ let ReviewReport = class ReviewReport {
409
417
  lines.push('');
410
418
  return lines.join('\n');
411
419
  }
420
+ // How the picked optional checklists are staffed. Grouped, the cap covers the WHOLE round, required
421
+ // reviewers included — otherwise "at most N" would quietly become 2N the moment a human said yes.
422
+ optionalAgentLines(input, count) {
423
+ const reviewer = input.reviewer;
424
+ const required = this.requiredOwed(input).length;
425
+ // The Codex pointer is printed once per report: by the required step when there is one.
426
+ const codex = required > 0 ? [] : [this.agentDefinitionLine(input)];
427
+ if (!reviewer.grouped()) {
428
+ return [` Each picked checklist gets its own \`${reviewer.agentName}\` subagent, spawned as its block shows.`, ...codex, ''];
429
+ }
430
+ const scope = required > 0 ? `, COUNTING the ${required} required checklist(s) above — fold picked ones into those subagents` : '';
431
+ return [
432
+ ` Review what they picked with \`${reviewer.agentName}\` subagents: at most ${reviewer.maxAgents} IN TOTAL`,
433
+ ` this round${scope}. Hand each subagent the instructions file of every checklist it covers.`,
434
+ ...codex,
435
+ ...(count > 0 ? [''] : []),
436
+ ];
437
+ }
412
438
  // Said up front, not only beside the block: an agent that has decided to spawn everything listed here
413
439
  // needs to know BEFORE it starts that one of these entries is not a spawn-shaped task. Scoped to the
414
440
  // group being printed — a refusal among the REQUIRED reviewers is not a caveat on the optional list.
@@ -468,23 +494,66 @@ let ReviewReport = class ReviewReport {
468
494
  * loop this exists to break.
469
495
  */
470
496
  oneSpawnBlock(input, b) {
471
- const instructionsFile = this.reviewerInstructions.pathFor(input.repoRoot, input.featureName, b.subagent);
497
+ const instructionsFile = this.reviewerInstructions.pathFor(input.repoRoot, input.featureName, b.checklistId);
498
+ if (input.reviewer.grouped()) {
499
+ // Grouped: the subagent_type is stated once, above; each block is one checklist's file to hand
500
+ // to whichever subagent covers it.
501
+ return [...this.leadIn(input, b), ` instructions: ${instructionsFile}`, ''];
502
+ }
472
503
  return [
473
504
  ...this.leadIn(input, b),
474
- ` subagent_type: ${b.subagent}`,
505
+ ` subagent_type: ${b.agentName}`,
475
506
  ' prompt: Read your instructions file FIRST and follow it exactly:',
476
507
  ` ${instructionsFile}`,
477
508
  '',
478
509
  ];
479
510
  }
511
+ /**
512
+ * HOW MANY subagents, of WHICH type — the one place this report states it, shared by the required and
513
+ * the optional step so the two cannot disagree.
514
+ *
515
+ * Without `commands.pr-gate.reviewerAgents` it is one separate subagent per checklist, as it always was.
516
+ * With it, the main AI gets a CAP and the grouping decision: the point of the key is to stop paying for
517
+ * N agents re-reading the same diff, and the AI is the one that can see which checklists belong together.
518
+ * The cap is per ROUND, so a re-run after a red verdict re-reviews only the owed checklists — the only
519
+ * ones listed — under the same cap.
520
+ */
521
+ howManyAgents(input, count) {
522
+ const reviewer = input.reviewer;
523
+ if (!reviewer.grouped()) {
524
+ return [` a SEPARATE \`${reviewer.agentName}\` subagent for each.`, this.agentDefinitionLine(input)];
525
+ }
526
+ const cap = Math.min(reviewer.maxAgents, count);
527
+ return [
528
+ ` AT MOST ${cap} subagent(s) of type \`${reviewer.agentName}\` (commands.pr-gate.reviewerAgents = ${reviewer.maxAgents}).`,
529
+ ` ${this.checklistInstructions.groupingHint(count, cap)}`,
530
+ ' Spawn each one as:',
531
+ ` subagent_type: ${reviewer.agentName}`,
532
+ ' prompt: Read EACH instructions file below FIRST and follow it exactly. Review each',
533
+ ' checklist only over its own in-scope files and write ONE verdict file per',
534
+ ' checklist — never one for a checklist you were not given.',
535
+ ' <then list the instructions file of every checklist this subagent covers>',
536
+ ' Every checklist below must be covered by exactly one of those subagents.',
537
+ this.agentDefinitionLine(input),
538
+ ];
539
+ }
540
+ /**
541
+ * The ONE canonical reviewer definition, named for a harness that cannot spawn it by type. Codex has no
542
+ * registered agent types, so its subagent is generic; pointing it at the same committed file keeps one
543
+ * definition for both harnesses instead of a Codex-specific copy that drifts (#863).
544
+ */
545
+ agentDefinitionLine(input) {
546
+ const file = path.join(input.repoRoot, '.claude', 'agents', `${input.reviewer.agentName}.md`);
547
+ return ` Codex (no agent types): spawn a generic subagent and have it read ${file} first.`;
548
+ }
480
549
  // The lines above the spawn coordinates: normally just why this reviewer is in scope; for one that
481
550
  // already refused, its verdict verbatim plus the order the two actions must happen in.
482
551
  leadIn(input, b) {
483
552
  const refusal = input.refused.find((r) => r.checklistId === b.checklistId);
484
553
  if (!refusal)
485
- return [` ▶ ${b.subagent} — ${this.why(b)}`, ...this.docLine(b)];
554
+ return [` ▶ ${b.checklistId} — ${this.why(b)}`, ...this.docLine(b)];
486
555
  return [
487
- ` ⛔ ${b.subagent} — ALREADY REVIEWED THIS BRANCH AND REFUSED. It will refuse again on unchanged code.`,
556
+ ` ⛔ ${b.checklistId} — ALREADY REVIEWED THIS BRANCH AND REFUSED. It will refuse again on unchanged code.`,
488
557
  ` ${refusal.message}`,
489
558
  ' FIX THE FINDING FIRST (or record a human-authored override). ONLY THEN spawn it again, to',
490
559
  ' write a fresh verdict:',
@@ -515,6 +584,7 @@ exports.ReviewReport = ReviewReport;
515
584
  exports.ReviewReport = ReviewReport = tslib_1.__decorate([
516
585
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
517
586
  tslib_1.__metadata("design:paramtypes", [checklist_notice_1.ChecklistNotice,
518
- rules_config_1.ReviewerInstructionsService])
587
+ rules_config_1.ReviewerInstructionsService,
588
+ rules_config_1.ChecklistInstructionsService])
519
589
  ], ReviewReport);
520
590
  //# sourceMappingURL=review-report.js.map