@webpieces/pr-gate 0.4.801 → 0.4.802

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 (45) hide show
  1. package/package.json +4 -3
  2. package/src/scripts/commands/await-reviews-command.d.ts +8 -2
  3. package/src/scripts/commands/await-reviews-command.js +27 -5
  4. package/src/scripts/commands/await-reviews-command.js.map +1 -1
  5. package/src/scripts/commands/review-upsert-pr-command.js +12 -2
  6. package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
  7. package/src/scripts/commands/write-review-command.d.ts +50 -0
  8. package/src/scripts/commands/write-review-command.js +175 -0
  9. package/src/scripts/commands/write-review-command.js.map +1 -0
  10. package/src/scripts/pr-gate-app.d.ts +8 -1
  11. package/src/scripts/pr-gate-app.js +12 -1
  12. package/src/scripts/pr-gate-app.js.map +1 -1
  13. package/src/scripts/workflow/checklist-scanner.d.ts +27 -1
  14. package/src/scripts/workflow/checklist-scanner.js +52 -4
  15. package/src/scripts/workflow/checklist-scanner.js.map +1 -1
  16. package/src/scripts/workflow/checklist-scope-hasher.d.ts +34 -0
  17. package/src/scripts/workflow/checklist-scope-hasher.js +67 -0
  18. package/src/scripts/workflow/checklist-scope-hasher.js.map +1 -0
  19. package/src/scripts/workflow/diff-materializer.d.ts +1 -1
  20. package/src/scripts/workflow/diff-materializer.js +2 -2
  21. package/src/scripts/workflow/diff-materializer.js.map +1 -1
  22. package/src/scripts/workflow/provenance-enforcer.d.ts +8 -1
  23. package/src/scripts/workflow/provenance-enforcer.js +34 -7
  24. package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
  25. package/src/scripts/workflow/review-report.d.ts +19 -0
  26. package/src/scripts/workflow/review-report.js +58 -12
  27. package/src/scripts/workflow/review-report.js.map +1 -1
  28. package/src/scripts/workflow/review-stage-receipt.d.ts +9 -0
  29. package/src/scripts/workflow/review-stage-receipt.js +29 -1
  30. package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
  31. package/src/scripts/workflow/reviewer-briefing-builder.d.ts +3 -2
  32. package/src/scripts/workflow/reviewer-briefing-builder.js +4 -2
  33. package/src/scripts/workflow/reviewer-briefing-builder.js.map +1 -1
  34. package/src/scripts/workflow/reviewer-identity.d.ts +39 -0
  35. package/src/scripts/workflow/reviewer-identity.js +90 -0
  36. package/src/scripts/workflow/reviewer-identity.js.map +1 -0
  37. package/src/scripts/workflow/reviewer-verdict-gate.d.ts +8 -0
  38. package/src/scripts/workflow/reviewer-verdict-gate.js +21 -1
  39. package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
  40. package/src/scripts/workflow/verdict-provenance.d.ts +90 -0
  41. package/src/scripts/workflow/verdict-provenance.js +214 -0
  42. package/src/scripts/workflow/verdict-provenance.js.map +1 -0
  43. package/src/scripts/wp-write-review.d.ts +2 -0
  44. package/src/scripts/wp-write-review.js +25 -0
  45. package/src/scripts/wp-write-review.js.map +1 -0
@@ -16,6 +16,12 @@ class ReviewStageReceipt {
16
16
  buildCommand;
17
17
  buildPassedAt; // ISO; '' when the gate was skipped (mode OFF / no command)
18
18
  reviewersBriefed;
19
+ /**
20
+ * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`
21
+ * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries
22
+ * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.
23
+ */
24
+ scopeHashes;
19
25
  // eslint-disable-next-line @typescript-eslint/max-params
20
26
  constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed = []) {
21
27
  this.headSha = headSha;
@@ -23,6 +29,7 @@ class ReviewStageReceipt {
23
29
  this.buildCommand = buildCommand;
24
30
  this.buildPassedAt = buildPassedAt;
25
31
  this.reviewersBriefed = reviewersBriefed;
32
+ this.scopeHashes = {};
26
33
  }
27
34
  }
28
35
  exports.ReviewStageReceipt = ReviewStageReceipt;
@@ -65,7 +72,9 @@ let ReviewStageReceiptService = class ReviewStageReceiptService {
65
72
  try {
66
73
  // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below
67
74
  const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
68
- return new ReviewStageReceipt(typeof raw['headSha'] === 'string' ? raw['headSha'] : '', raw['mergeValidated'] === true, typeof raw['buildCommand'] === 'string' ? raw['buildCommand'] : '', typeof raw['buildPassedAt'] === 'string' ? raw['buildPassedAt'] : '', Array.isArray(raw['reviewersBriefed']) ? raw['reviewersBriefed'] : []);
75
+ const receipt = new ReviewStageReceipt(typeof raw['headSha'] === 'string' ? raw['headSha'] : '', raw['mergeValidated'] === true, typeof raw['buildCommand'] === 'string' ? raw['buildCommand'] : '', typeof raw['buildPassedAt'] === 'string' ? raw['buildPassedAt'] : '', Array.isArray(raw['reviewersBriefed']) ? raw['reviewersBriefed'] : []);
76
+ receipt.scopeHashes = this.stringMap(raw['scopeHashes']);
77
+ return receipt;
69
78
  }
70
79
  catch (err) {
71
80
  const error = (0, rules_config_1.toError)(err);
@@ -73,6 +82,25 @@ let ReviewStageReceiptService = class ReviewStageReceiptService {
73
82
  return null;
74
83
  }
75
84
  }
85
+ /** The receipt file's mtime in epoch ms, or 0 when there is none — when stage ② last briefed anyone. */
86
+ writtenAtMs(repoRoot, featureName) {
87
+ const p = this.receiptPath(repoRoot, featureName);
88
+ return fs.existsSync(p) ? fs.statSync(p).mtimeMs : 0;
89
+ }
90
+ // webpieces-disable no-any-unknown -- one opaque JSON value, narrowed to string→string
91
+ stringMap(value) {
92
+ const out = {};
93
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
94
+ return out;
95
+ // webpieces-disable no-any-unknown -- entries of an opaque JSON object, each narrowed below
96
+ const obj = value;
97
+ for (const key of Object.keys(obj)) {
98
+ const v = obj[key];
99
+ if (typeof v === 'string')
100
+ out[key] = v;
101
+ }
102
+ return out;
103
+ }
76
104
  };
77
105
  exports.ReviewStageReceiptService = ReviewStageReceiptService;
78
106
  exports.ReviewStageReceiptService = ReviewStageReceiptService = tslib_1.__decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"review-stage-receipt.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-stage-receipt.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqE;AACrE,yCAA2D;AAE9C,QAAA,YAAY,GAAG,mBAAmB,CAAC;AAEhD;;GAEG;AACH,MAAa,kBAAkB;IAC3B,OAAO,CAAS,CAAU,gEAAgE;IAC1F,cAAc,CAAU,CAAE,oEAAoE;IAC9F,YAAY,CAAS;IACrB,aAAa,CAAS,CAAI,4DAA4D;IACtF,gBAAgB,CAAW;IAE3B,yDAAyD;IACzD,YAAY,OAAO,GAAG,EAAE,EAAE,cAAc,GAAG,KAAK,EAAE,YAAY,GAAG,EAAE,EAAE,aAAa,GAAG,EAAE,EAAE,mBAA6B,EAAE;QACpH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;IAC7C,CAAC;CACJ;AAfD,gDAeC;AAED;;;;;;;;;;;;;;GAcG;AAEI,IAAM,yBAAyB,GAA/B,MAAM,yBAAyB;IACL;IAA7B,YAA6B,iBAAoC;QAApC,sBAAiB,GAAjB,iBAAiB,CAAmB;IAAG,CAAC;IAErE,WAAW,CAAC,QAAgB,EAAE,WAAmB;QAC7C,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,EAAE,oBAAY,CAAC,CAAC;IAC3F,CAAC;IAED,KAAK,CAAC,QAAgB,EAAE,WAAmB,EAAE,OAA2B;QACpE,MAAM,CAAC,GAAG,IAAI,CAAC,WAAW,CAA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CAAC,EAAE,CACtF,CAAC;QACN,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,6EAA6E;YACzF,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ,CAAA;AApCY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,yBAAyB,CAoCrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { ReviewJsonService, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nexport const RECEIPT_FILE = 'review-stage.json';\n\n/**\n * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).\n */\nexport class ReviewStageReceipt {\n headSha: string; // the sha the merge was validated and the build was run against\n mergeValidated: boolean; // a 3-point merge was finalized here, or there was none to finalize\n buildCommand: string;\n buildPassedAt: string; // ISO; '' when the gate was skipped (mode OFF / no command)\n reviewersBriefed: string[];\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed: string[] = []) {\n this.headSha = headSha;\n this.mergeValidated = mergeValidated;\n this.buildCommand = buildCommand;\n this.buildPassedAt = buildPassedAt;\n this.reviewersBriefed = reviewersBriefed;\n }\n}\n\n/**\n * Reads/writes the stage-② receipt.\n *\n * WHY a receipt rather than relying on the artifacts that already exist: `wp-finish-upsert-pr` already\n * refuses when a reviewer has no verdict and when review.json is absent, so a repo WITH checklists is\n * mostly interlocked already. A repo with NO checklists is not — review.json is the only thing standing\n * between it and a PR, and the AI writes review.json itself. Nothing stopped it from writing that file and\n * going straight to finish, skipping the merge validation and the build entirely.\n *\n * The receipt also pays for itself in the other direction: because it records the sha the build passed on,\n * finish can SKIP its own build when HEAD has not moved, so adding a gate in the middle did not cost a\n * second full `nx affected` run.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewStageReceiptService {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n receiptPath(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), RECEIPT_FILE);\n }\n\n write(repoRoot: string, featureName: string, receipt: ReviewStageReceipt): string {\n const p = this.receiptPath(repoRoot, featureName);\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(receipt, null, 2) + '\\n');\n return p;\n }\n\n /** The receipt, or null when stage ② never ran (or left something unreadable behind). */\n read(repoRoot: string, featureName: string): ReviewStageReceipt | null {\n const p = this.receiptPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable receipt is treated as absent, which re-runs stage ②\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n return new ReviewStageReceipt(\n typeof raw['headSha'] === 'string' ? (raw['headSha'] as string) : '',\n raw['mergeValidated'] === true,\n typeof raw['buildCommand'] === 'string' ? (raw['buildCommand'] as string) : '',\n typeof raw['buildPassedAt'] === 'string' ? (raw['buildPassedAt'] as string) : '',\n Array.isArray(raw['reviewersBriefed']) ? (raw['reviewersBriefed'] as string[]) : [],\n );\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable ⇒ treated as absent, which re-runs stage ② (the safe direction)\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"review-stage-receipt.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/review-stage-receipt.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mD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import { ReviewJsonService, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nexport const RECEIPT_FILE = 'review-stage.json';\n\n/**\n * Proof that stage ② (`wp-review-upsert-pr`) actually ran, and on WHICH commit. Data-only (per CLAUDE.md).\n */\nexport class ReviewStageReceipt {\n headSha: string; // the sha the merge was validated and the build was run against\n mergeValidated: boolean; // a 3-point merge was finalized here, or there was none to finalize\n buildCommand: string;\n buildPassedAt: string; // ISO; '' when the gate was skipped (mode OFF / no command)\n reviewersBriefed: string[];\n /**\n * checklist id → the hash of its in-scope diff at `headSha` (ChecklistScopeHasher). `wp-write-review`\n * stamps a verdict's provenance with the hash its reviewer was BRIEFED on, and the next stage ② carries\n * a green/yellow forward only while that hash is unchanged (issue #863). Assigned after construction.\n */\n scopeHashes: Record<string, string>;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(headSha = '', mergeValidated = false, buildCommand = '', buildPassedAt = '', reviewersBriefed: string[] = []) {\n this.headSha = headSha;\n this.mergeValidated = mergeValidated;\n this.buildCommand = buildCommand;\n this.buildPassedAt = buildPassedAt;\n this.reviewersBriefed = reviewersBriefed;\n this.scopeHashes = {};\n }\n}\n\n/**\n * Reads/writes the stage-② receipt.\n *\n * WHY a receipt rather than relying on the artifacts that already exist: `wp-finish-upsert-pr` already\n * refuses when a reviewer has no verdict and when review.json is absent, so a repo WITH checklists is\n * mostly interlocked already. A repo with NO checklists is not — review.json is the only thing standing\n * between it and a PR, and the AI writes review.json itself. Nothing stopped it from writing that file and\n * going straight to finish, skipping the merge validation and the build entirely.\n *\n * The receipt also pays for itself in the other direction: because it records the sha the build passed on,\n * finish can SKIP its own build when HEAD has not moved, so adding a gate in the middle did not cost a\n * second full `nx affected` run.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewStageReceiptService {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n receiptPath(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), RECEIPT_FILE);\n }\n\n write(repoRoot: string, featureName: string, receipt: ReviewStageReceipt): string {\n const p = this.receiptPath(repoRoot, featureName);\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(receipt, null, 2) + '\\n');\n return p;\n }\n\n /** The receipt, or null when stage ② never ran (or left something unreadable behind). */\n read(repoRoot: string, featureName: string): ReviewStageReceipt | null {\n const p = this.receiptPath(repoRoot, featureName);\n if (!fs.existsSync(p)) return null;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable receipt is treated as absent, which re-runs stage ②\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque parsed JSON, narrowed field-by-field below\n const raw = JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;\n const receipt = new ReviewStageReceipt(\n typeof raw['headSha'] === 'string' ? (raw['headSha'] as string) : '',\n raw['mergeValidated'] === true,\n typeof raw['buildCommand'] === 'string' ? (raw['buildCommand'] as string) : '',\n typeof raw['buildPassedAt'] === 'string' ? (raw['buildPassedAt'] as string) : '',\n Array.isArray(raw['reviewersBriefed']) ? (raw['reviewersBriefed'] as string[]) : [],\n );\n receipt.scopeHashes = this.stringMap(raw['scopeHashes']);\n return receipt;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable ⇒ treated as absent, which re-runs stage ② (the safe direction)\n return null;\n }\n }\n\n /** The receipt file's mtime in epoch ms, or 0 when there is none — when stage ② last briefed anyone. */\n writtenAtMs(repoRoot: string, featureName: string): number {\n const p = this.receiptPath(repoRoot, featureName);\n return fs.existsSync(p) ? fs.statSync(p).mtimeMs : 0;\n }\n\n // webpieces-disable no-any-unknown -- one opaque JSON value, narrowed to string→string\n private stringMap(value: unknown): Record<string, string> {\n const out: Record<string, string> = {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return out;\n // webpieces-disable no-any-unknown -- entries of an opaque JSON object, each narrowed below\n const obj = value as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const v = obj[key];\n if (typeof v === 'string') out[key] = v;\n }\n return out;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { PrGateConfig, ReviewerBriefing, ReviewJsonService } from '@webpieces/rules-config';
1
+ import { PrGateConfig, RequiredChecklist, ReviewerBriefing, ReviewJsonService } from '@webpieces/rules-config';
2
2
  import { DiffManifest } from './diff-materializer';
3
3
  import { ChecklistScan } from './checklist-scanner';
4
4
  /**
@@ -11,7 +11,8 @@ import { ChecklistScan } from './checklist-scanner';
11
11
  export declare class ReviewerBriefingBuilder {
12
12
  private readonly reviewJsonService;
13
13
  constructor(reviewJsonService: ReviewJsonService);
14
- build(repoRoot: string, scan: ChecklistScan, manifest: DiffManifest, diffDir: string, config: PrGateConfig): ReviewerBriefing[];
14
+ /** One briefing per checklist in `checklists` — the OWED ones; a carried verdict is not re-briefed. */
15
+ build(repoRoot: string, scan: ChecklistScan, checklists: readonly RequiredChecklist[], manifest: DiffManifest, diffDir: string, config: PrGateConfig): ReviewerBriefing[];
15
16
  private one;
16
17
  /**
17
18
  * One row of the reviewer's table. The SOURCE path comes over with the diff path because the two need
@@ -18,14 +18,16 @@ let ReviewerBriefingBuilder = class ReviewerBriefingBuilder {
18
18
  constructor(reviewJsonService) {
19
19
  this.reviewJsonService = reviewJsonService;
20
20
  }
21
- build(repoRoot, scan, manifest, diffDir, config) {
21
+ /** One briefing per checklist in `checklists` — the OWED ones; a carried verdict is not re-briefed. */
22
+ // eslint-disable-next-line @typescript-eslint/max-params
23
+ build(repoRoot, scan, checklists, manifest, diffDir, config) {
22
24
  // Resolved ONCE for the whole run, not per reviewer: `require.resolve` hits the filesystem, and the
23
25
  // answer cannot differ between two reviewers in the same process.
24
26
  const shared = this.contextEntries(repoRoot, config);
25
27
  const entryByFile = new Map();
26
28
  for (const e of manifest.entries)
27
29
  entryByFile.set(e.file, e);
28
- return scan.applicable.map((req) => this.one(repoRoot, req, scan, entryByFile, diffDir, shared, manifest));
30
+ return checklists.map((req) => this.one(repoRoot, req, scan, entryByFile, diffDir, shared, manifest));
29
31
  }
30
32
  // eslint-disable-next-line @typescript-eslint/max-params
31
33
  one(repoRoot, req, scan, entryByFile, diffDir, shared, manifest) {
@@ -1 +1 @@
1
- {"version":3,"file":"reviewer-briefing-builder.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-briefing-builder.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAEiC;AACjC,yCAA2D;AAI3D;;;;;;GAMG;AAEI,IAAM,uBAAuB,GAA7B,MAAM,uBAAuB;IACH;IAA7B,YAA6B,iBAAoC;QAApC,sBAAiB,GAAjB,iBAAiB,CAAmB;IAAG,CAAC;IAErE,KAAK,CAAC,QAAgB,EAAE,IAAmB,EAAE,QAAsB,EAAE,OAAe,EAAE,MAAoB;QACtG,oGAAoG;QACpG,kEAAkE;QAClE,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACrD,MAAM,WAAW,GAAG,IAAI,GAAG,EAA6B,CAAC;QACzD,KAAK,MAAM,CAAC,IAAI,QAAQ,CAAC,OAAO;YAAE,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC7D,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,GAAsB,EAAoB,EAAE,CACpE,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC/E,CAAC;IAED,yDAAyD;IACjD,GAAG,CACP,QAAgB,EAAE,GAAsB,EAAE,IAAmB,EAC7D,WAA2C,EAAE,OAAe,EAAE,MAAsB,EAAE,QAAsB;QAE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AG,CAAC,CAAC;QACzE,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,yDAAyD;YACrE,OAAO,IAAI,2BAAY,CAAC,GAAG,EAAE,EAAE,EAAE,+DAA+D,CAAC,CAAC;QACtG,CAAC;IACL,CAAC;CACJ,CAAA;AA7HY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,uBAAuB,CA6HnC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n BriefedFile, ContextEntry, PrGateConfig, RequiredChecklist, ReviewerBriefing, ReviewJsonService, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { DiffManifest, DiffManifestEntry } from './diff-materializer';\nimport { ChecklistScan } from './checklist-scanner';\n\n/**\n * Turns a {@link ChecklistScan} plus the materialized {@link DiffManifest} into one {@link ReviewerBriefing}\n * per reviewer — resolving every path to an absolute one, because a reviewer that has to resolve a path\n * ends up searching, and searching is the cost this whole feature exists to remove.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerBriefingBuilder {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n build(repoRoot: string, scan: ChecklistScan, manifest: DiffManifest, diffDir: string, config: PrGateConfig): ReviewerBriefing[] {\n // Resolved ONCE for the whole run, not per reviewer: `require.resolve` hits the filesystem, and the\n // answer cannot differ between two reviewers in the same process.\n const shared = this.contextEntries(repoRoot, config);\n const entryByFile = new Map<string, DiffManifestEntry>();\n for (const e of manifest.entries) entryByFile.set(e.file, e);\n return scan.applicable.map((req: RequiredChecklist): ReviewerBriefing =>\n this.one(repoRoot, req, scan, entryByFile, diffDir, shared, manifest));\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private one(\n repoRoot: string, req: RequiredChecklist, scan: ChecklistScan,\n entryByFile: Map<string, DiffManifestEntry>, diffDir: string, shared: ContextEntry[], manifest: DiffManifest,\n ): ReviewerBriefing {\n const b = new ReviewerBriefing(req.reviewer.agentName, req.id, repoRoot);\n b.docPath = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n b.diffDir = diffDir;\n b.allDiffPath = diffDir === '' ? '' : path.join(diffDir, 'ALL.diff');\n b.manifestPath = diffDir === '' ? '' : path.join(diffDir, 'manifest.json');\n b.myFiles = req.matchedFiles.map((f: string): BriefedFile => this.briefedFile(repoRoot, f, entryByFile));\n b.matchedPatterns = req.matchedPatterns;\n b.required = req.required;\n b.sourceDirs = this.sourceDirsFor(repoRoot, req.matchedFiles);\n b.contextEntries = shared;\n b.verdictPath = this.reviewJsonService.checklistResultPath(scan.reviewPath, req.id);\n b.fileDiffCommand = scan.context.fileDiffCommand;\n b.dirty = scan.basis.dirty;\n b.ownAgentFileInDiff = this.ownAgentFileIn(manifest, req.reviewer.agentName);\n this.copyManifestFacts(b, manifest);\n return b;\n }\n\n /**\n * One row of the reviewer's table. The SOURCE path comes over with the diff path because the two need\n * identical affordance: when the diff was an absolute path and the source was a parent directory, four of\n * four reviewers read the diff and none opened a source file.\n */\n private briefedFile(repoRoot: string, file: string, entryByFile: Map<string, DiffManifestEntry>): BriefedFile {\n const e = entryByFile.get(file);\n if (e === undefined) return new BriefedFile(file, '', path.resolve(repoRoot, file));\n return new BriefedFile(file, e.diffAbs, e.fileAbs, e.status, e.bytes, e.truncated);\n }\n\n /**\n * Manifest headline facts, copied onto the briefing so the instructions can state them INLINE. A reviewer\n * that never opens the manifest still has to learn whether anything was truncated or excluded — that is\n * precisely the thing it could not otherwise know it was missing.\n */\n private copyManifestFacts(b: ReviewerBriefing, manifest: DiffManifest): void {\n b.changedFileCount = manifest.entries.length;\n b.truncatedCount = manifest.entries.filter((e: DiffManifestEntry): boolean => e.truncated).length;\n b.excludedCount = manifest.excluded.length;\n b.allDiffLines = manifest.allDiffLines;\n b.allDiffBytes = manifest.allDiffBytes;\n b.hashForkPoint = manifest.hashForkPoint;\n b.hashFeatureHead = manifest.hashFeatureHead;\n b.hashMainHead = manifest.hashMainHead;\n }\n\n /**\n * The reviewer agent's own `.claude/agents/<agentName>.md`, when THIS diff changes it. Detected here rather than\n * left to the reviewer to notice: on the measured run two reviewers reviewed their own definition and\n * neither mentioned it, and every PR that edits the review gate reproduces that.\n */\n private ownAgentFileIn(manifest: DiffManifest, agentName: string): string {\n const suffix = path.join('.claude', 'agents', `${agentName}.md`);\n const hit = manifest.entries.find((e: DiffManifestEntry): boolean => e.file.split('/').join(path.sep).endsWith(suffix));\n return hit === undefined ? '' : (hit.fileAbs === '' ? hit.file : hit.fileAbs);\n }\n\n /**\n * Deduped absolute parent dirs of the matched files. Dirs rather than files because the point is to say\n * \"the neighbourhood is here\" — a reviewer already has the file list; what it lacks is where to look for\n * the code AROUND the change.\n */\n private sourceDirsFor(repoRoot: string, files: readonly string[]): string[] {\n const dirs = new Set<string>();\n for (const f of files) dirs.add(path.resolve(repoRoot, path.dirname(f)));\n return [...dirs].sort();\n }\n\n /**\n * The pre-resolved context list, from two config keys with deliberately different jobs:\n *\n * `reviewContextPackages` — installed packages, resolved to their real on-disk dir. This is what deletes\n * the repeated `node_modules/@webpieces` greps: the tooling knows where a package resolved to, and the\n * reviewer does not.\n * `reviewContext` — the repo-specific escape hatch (`{label, path}`) for what tooling cannot possibly\n * guess, e.g. \"queue names live in terraform/services/\".\n *\n * Neither ever drops an entry: an unresolvable package or a missing path is LISTED, with the reason. A\n * silently shorter list is indistinguishable from a complete one.\n */\n private contextEntries(repoRoot: string, config: PrGateConfig): ContextEntry[] {\n const entries: ContextEntry[] = [];\n for (const pkg of config.reviewContextPackages) entries.push(this.resolvePackage(repoRoot, pkg));\n for (const item of config.reviewContext) {\n const abs = path.resolve(repoRoot, item.path);\n entries.push(fs.existsSync(abs)\n ? new ContextEntry(item.label, abs)\n : new ContextEntry(item.label, '', `(configured as \"${item.path}\" but missing)`));\n }\n return entries;\n }\n\n private resolvePackage(repoRoot: string, pkg: string): ContextEntry {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unresolvable package is REPORTED as such, never fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const manifestPath = require.resolve(`${pkg}/package.json`, { paths: [repoRoot] });\n const dir = path.dirname(manifestPath);\n // webpieces-disable no-any-unknown -- opaque package.json, only `description` is read\n const meta = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as Record<string, unknown>;\n const desc = typeof meta['description'] === 'string' ? (meta['description'] as string) : '';\n return new ContextEntry(desc === '' ? pkg : `${pkg} — ${desc}`, dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // an unresolvable package is REPORTED below, never fatal\n return new ContextEntry(pkg, '', '(not installed — configured in pr-gate.reviewContextPackages)');\n }\n }\n}\n"]}
1
+ {"version":3,"file":"reviewer-briefing-builder.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-briefing-builder.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAEiC;AACjC,yCAA2D;AAI3D;;;;;;GAMG;AAEI,IAAM,uBAAuB,GAA7B,MAAM,uBAAuB;IACH;IAA7B,YAA6B,iBAAoC;QAApC,sBAAiB,GAAjB,iBAAiB,CAAmB;IAAG,CAAC;IAErE,uGAAuG;IACvG,yDAAyD;IACzD,KAAK,CACD,QAAgB,EAAE,IAAmB,EAAE,UAAwC,EAAE,QAAsB,EACvG,OAAe,EAAE,MAAoB;QAErC,oGAAoG;QACpG,kEAAkE;QAClE,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACrD,MAAM,WAAW,GAAG,IAAI,GAAG,EAA6B,CAAC;QACzD,KAAK,MAAM,CAAC,IAA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,CAAC,YAAY,CAAC,CAAC;YACvC,sFAAsF;YACtF,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,YAAY,EAAE,MAAM,CAAC,CAA4B,CAAC;YAC1F,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAE,IAAI,CAAC,aAAa,CAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5F,OAAO,IAAI,2BAAY,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,MAAM,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC;QACzE,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC,CAAC,yDAAyD;YACrE,OAAO,IAAI,2BAAY,CAAC,GAAG,EAAE,EAAE,EAAE,+DAA+D,CAAC,CAAC;QACtG,CAAC;IACL,CAAC;CACJ,CAAA;AAlIY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,uBAAuB,CAkInC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n BriefedFile, ContextEntry, PrGateConfig, RequiredChecklist, ReviewerBriefing, ReviewJsonService, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { DiffManifest, DiffManifestEntry } from './diff-materializer';\nimport { ChecklistScan } from './checklist-scanner';\n\n/**\n * Turns a {@link ChecklistScan} plus the materialized {@link DiffManifest} into one {@link ReviewerBriefing}\n * per reviewer — resolving every path to an absolute one, because a reviewer that has to resolve a path\n * ends up searching, and searching is the cost this whole feature exists to remove.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerBriefingBuilder {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n /** One briefing per checklist in `checklists` — the OWED ones; a carried verdict is not re-briefed. */\n // eslint-disable-next-line @typescript-eslint/max-params\n build(\n repoRoot: string, scan: ChecklistScan, checklists: readonly RequiredChecklist[], manifest: DiffManifest,\n diffDir: string, config: PrGateConfig,\n ): ReviewerBriefing[] {\n // Resolved ONCE for the whole run, not per reviewer: `require.resolve` hits the filesystem, and the\n // answer cannot differ between two reviewers in the same process.\n const shared = this.contextEntries(repoRoot, config);\n const entryByFile = new Map<string, DiffManifestEntry>();\n for (const e of manifest.entries) entryByFile.set(e.file, e);\n return checklists.map((req: RequiredChecklist): ReviewerBriefing =>\n this.one(repoRoot, req, scan, entryByFile, diffDir, shared, manifest));\n }\n\n // eslint-disable-next-line @typescript-eslint/max-params\n private one(\n repoRoot: string, req: RequiredChecklist, scan: ChecklistScan,\n entryByFile: Map<string, DiffManifestEntry>, diffDir: string, shared: ContextEntry[], manifest: DiffManifest,\n ): ReviewerBriefing {\n const b = new ReviewerBriefing(req.reviewer.agentName, req.id, repoRoot);\n b.docPath = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n b.diffDir = diffDir;\n b.allDiffPath = diffDir === '' ? '' : path.join(diffDir, 'ALL.diff');\n b.manifestPath = diffDir === '' ? '' : path.join(diffDir, 'manifest.json');\n b.myFiles = req.matchedFiles.map((f: string): BriefedFile => this.briefedFile(repoRoot, f, entryByFile));\n b.matchedPatterns = req.matchedPatterns;\n b.required = req.required;\n b.sourceDirs = this.sourceDirsFor(repoRoot, req.matchedFiles);\n b.contextEntries = shared;\n b.verdictPath = this.reviewJsonService.checklistResultPath(scan.reviewPath, req.id);\n b.fileDiffCommand = scan.context.fileDiffCommand;\n b.dirty = scan.basis.dirty;\n b.ownAgentFileInDiff = this.ownAgentFileIn(manifest, req.reviewer.agentName);\n this.copyManifestFacts(b, manifest);\n return b;\n }\n\n /**\n * One row of the reviewer's table. The SOURCE path comes over with the diff path because the two need\n * identical affordance: when the diff was an absolute path and the source was a parent directory, four of\n * four reviewers read the diff and none opened a source file.\n */\n private briefedFile(repoRoot: string, file: string, entryByFile: Map<string, DiffManifestEntry>): BriefedFile {\n const e = entryByFile.get(file);\n if (e === undefined) return new BriefedFile(file, '', path.resolve(repoRoot, file));\n return new BriefedFile(file, e.diffAbs, e.fileAbs, e.status, e.bytes, e.truncated);\n }\n\n /**\n * Manifest headline facts, copied onto the briefing so the instructions can state them INLINE. A reviewer\n * that never opens the manifest still has to learn whether anything was truncated or excluded — that is\n * precisely the thing it could not otherwise know it was missing.\n */\n private copyManifestFacts(b: ReviewerBriefing, manifest: DiffManifest): void {\n b.changedFileCount = manifest.entries.length;\n b.truncatedCount = manifest.entries.filter((e: DiffManifestEntry): boolean => e.truncated).length;\n b.excludedCount = manifest.excluded.length;\n b.allDiffLines = manifest.allDiffLines;\n b.allDiffBytes = manifest.allDiffBytes;\n b.hashForkPoint = manifest.hashForkPoint;\n b.hashFeatureHead = manifest.hashFeatureHead;\n b.hashMainHead = manifest.hashMainHead;\n }\n\n /**\n * The reviewer agent's own `.claude/agents/<agentName>.md`, when THIS diff changes it. Detected here rather than\n * left to the reviewer to notice: on the measured run two reviewers reviewed their own definition and\n * neither mentioned it, and every PR that edits the review gate reproduces that.\n */\n private ownAgentFileIn(manifest: DiffManifest, agentName: string): string {\n const suffix = path.join('.claude', 'agents', `${agentName}.md`);\n const hit = manifest.entries.find((e: DiffManifestEntry): boolean => e.file.split('/').join(path.sep).endsWith(suffix));\n return hit === undefined ? '' : (hit.fileAbs === '' ? hit.file : hit.fileAbs);\n }\n\n /**\n * Deduped absolute parent dirs of the matched files. Dirs rather than files because the point is to say\n * \"the neighbourhood is here\" — a reviewer already has the file list; what it lacks is where to look for\n * the code AROUND the change.\n */\n private sourceDirsFor(repoRoot: string, files: readonly string[]): string[] {\n const dirs = new Set<string>();\n for (const f of files) dirs.add(path.resolve(repoRoot, path.dirname(f)));\n return [...dirs].sort();\n }\n\n /**\n * The pre-resolved context list, from two config keys with deliberately different jobs:\n *\n * `reviewContextPackages` — installed packages, resolved to their real on-disk dir. This is what deletes\n * the repeated `node_modules/@webpieces` greps: the tooling knows where a package resolved to, and the\n * reviewer does not.\n * `reviewContext` — the repo-specific escape hatch (`{label, path}`) for what tooling cannot possibly\n * guess, e.g. \"queue names live in terraform/services/\".\n *\n * Neither ever drops an entry: an unresolvable package or a missing path is LISTED, with the reason. A\n * silently shorter list is indistinguishable from a complete one.\n */\n private contextEntries(repoRoot: string, config: PrGateConfig): ContextEntry[] {\n const entries: ContextEntry[] = [];\n for (const pkg of config.reviewContextPackages) entries.push(this.resolvePackage(repoRoot, pkg));\n for (const item of config.reviewContext) {\n const abs = path.resolve(repoRoot, item.path);\n entries.push(fs.existsSync(abs)\n ? new ContextEntry(item.label, abs)\n : new ContextEntry(item.label, '', `(configured as \"${item.path}\" but missing)`));\n }\n return entries;\n }\n\n private resolvePackage(repoRoot: string, pkg: string): ContextEntry {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unresolvable package is REPORTED as such, never fatal\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const manifestPath = require.resolve(`${pkg}/package.json`, { paths: [repoRoot] });\n const dir = path.dirname(manifestPath);\n // webpieces-disable no-any-unknown -- opaque package.json, only `description` is read\n const meta = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as Record<string, unknown>;\n const desc = typeof meta['description'] === 'string' ? (meta['description'] as string) : '';\n return new ContextEntry(desc === '' ? pkg : `${pkg} — ${desc}`, dir);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // an unresolvable package is REPORTED below, never fatal\n return new ContextEntry(pkg, '', '(not installed — configured in pr-gate.reviewContextPackages)');\n }\n }\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import { ReviewIdentityStampService } from '@webpieces/rules-config';
2
+ /** WHO is submitting a verdict. Data-only. */
3
+ export declare class ReviewerIdentity {
4
+ harness: string;
5
+ sessionId: string;
6
+ agentId: string;
7
+ agentType: string;
8
+ constructor(harness: string, sessionId: string, agentId: string, agentType: string);
9
+ }
10
+ /**
11
+ * Answers "who is running `wp-write-review`?" — and REFUSES the coordinating agent (issue #863).
12
+ *
13
+ * The mechanism, per harness, and why it is not the environment:
14
+ * - CLAUDE CODE: a Bash child inherits `CLAUDE_CODE_SESSION_ID`, which is the PARENT session's id inside
15
+ * a subagent too, and there is no agent id in the env at all. Env cannot tell a reviewer from its
16
+ * coordinator.
17
+ * - CODEX: `CODEX_SESSION_ID` / `CODEX_THREAD_ID` are exported, but nothing documents — and nothing here
18
+ * has measured — that a spawned subagent gets its own thread id instead of the coordinator's.
19
+ * - BOTH: the PreToolUse hook payload carries `agent_id`, empty for the main loop and set for a subagent,
20
+ * on the same key in both harnesses. So the hook writes a {@link ReviewIdentityStamp} for each
21
+ * checklist a `wp-write-review` command names, just before the command runs, and this consumes it.
22
+ *
23
+ * The plain-terminal story: with NO harness env and no stamp, the caller is a HUMAN at a terminal. That is
24
+ * a legitimate reviewer, and the verdict is recorded with harness `terminal`. CI never submits verdicts —
25
+ * `.webpieces/` is not in the repo, so there is nothing for CI to read or write here.
26
+ *
27
+ * NOT tamper-proof: an agent can scrub its env AND invoke the bin some way the hook does not recognise, or
28
+ * forge a stamp file. That is deliberate, visible forgery in the transcript — the bar the rest of reviewer
29
+ * provenance sets — rather than the one ordinary file write it used to take.
30
+ *
31
+ * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.
32
+ */
33
+ export declare class ReviewerIdentityResolver {
34
+ private readonly stamps;
35
+ constructor(stamps: ReviewIdentityStampService);
36
+ resolve(cwd: string, checklistId: string, env?: NodeJS.ProcessEnv): ReviewerIdentity;
37
+ private coordinatorRefusal;
38
+ private unstampedRefusal;
39
+ }
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ReviewerIdentityResolver = exports.ReviewerIdentity = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const rules_config_1 = require("@webpieces/rules-config");
6
+ const inversify_1 = require("inversify");
7
+ const verdict_provenance_1 = require("./verdict-provenance");
8
+ /**
9
+ * Env vars whose presence means an AI harness launched this process. Any one of them and there MUST be a
10
+ * hook stamp — a harness-launched submission without one either bypassed the hook or ran where the hook is
11
+ * not installed, and neither can say who is calling.
12
+ */
13
+ const HARNESS_ENV = ['CLAUDECODE', 'CLAUDE_CODE_SESSION_ID', 'CODEX_SESSION_ID', 'CODEX_THREAD_ID'];
14
+ /** WHO is submitting a verdict. Data-only. */
15
+ class ReviewerIdentity {
16
+ harness;
17
+ sessionId;
18
+ agentId;
19
+ agentType;
20
+ // eslint-disable-next-line @typescript-eslint/max-params
21
+ constructor(harness, sessionId, agentId, agentType) {
22
+ this.harness = harness;
23
+ this.sessionId = sessionId;
24
+ this.agentId = agentId;
25
+ this.agentType = agentType;
26
+ }
27
+ }
28
+ exports.ReviewerIdentity = ReviewerIdentity;
29
+ /**
30
+ * Answers "who is running `wp-write-review`?" — and REFUSES the coordinating agent (issue #863).
31
+ *
32
+ * The mechanism, per harness, and why it is not the environment:
33
+ * - CLAUDE CODE: a Bash child inherits `CLAUDE_CODE_SESSION_ID`, which is the PARENT session's id inside
34
+ * a subagent too, and there is no agent id in the env at all. Env cannot tell a reviewer from its
35
+ * coordinator.
36
+ * - CODEX: `CODEX_SESSION_ID` / `CODEX_THREAD_ID` are exported, but nothing documents — and nothing here
37
+ * has measured — that a spawned subagent gets its own thread id instead of the coordinator's.
38
+ * - BOTH: the PreToolUse hook payload carries `agent_id`, empty for the main loop and set for a subagent,
39
+ * on the same key in both harnesses. So the hook writes a {@link ReviewIdentityStamp} for each
40
+ * checklist a `wp-write-review` command names, just before the command runs, and this consumes it.
41
+ *
42
+ * The plain-terminal story: with NO harness env and no stamp, the caller is a HUMAN at a terminal. That is
43
+ * a legitimate reviewer, and the verdict is recorded with harness `terminal`. CI never submits verdicts —
44
+ * `.webpieces/` is not in the repo, so there is nothing for CI to read or write here.
45
+ *
46
+ * NOT tamper-proof: an agent can scrub its env AND invoke the bin some way the hook does not recognise, or
47
+ * forge a stamp file. That is deliberate, visible forgery in the transcript — the bar the rest of reviewer
48
+ * provenance sets — rather than the one ordinary file write it used to take.
49
+ *
50
+ * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.
51
+ */
52
+ let ReviewerIdentityResolver = class ReviewerIdentityResolver {
53
+ stamps;
54
+ constructor(stamps) {
55
+ this.stamps = stamps;
56
+ }
57
+ resolve(cwd, checklistId, env = process.env) {
58
+ const stamp = this.stamps.take(cwd, checklistId);
59
+ if (stamp !== null) {
60
+ if (this.stamps.isCoordinator(stamp))
61
+ throw new rules_config_1.InformAiError(this.coordinatorRefusal(checklistId, stamp.aiType));
62
+ return new ReviewerIdentity(stamp.aiType, stamp.sessionId, stamp.agentId, stamp.agentType);
63
+ }
64
+ const inHarness = HARNESS_ENV.filter((name) => (env[name] ?? '').trim() !== '');
65
+ if (inHarness.length > 0)
66
+ throw new rules_config_1.InformAiError(this.unstampedRefusal(checklistId, inHarness));
67
+ return new ReviewerIdentity(verdict_provenance_1.HARNESS_TERMINAL, '', '', '');
68
+ }
69
+ coordinatorRefusal(checklistId, aiType) {
70
+ return `${rules_config_1.WRITE_REVIEW_BIN} REFUSED: the ${aiType} harness reports this call comes from the COORDINATING agent, not a\n`
71
+ + `reviewer subagent. The coordinator may never submit a reviewer's verdict for "${checklistId}" — not by this\n`
72
+ + 'bin, and not by writing the file (wp-finish-upsert-pr rejects a verdict this bin did not write).\n\n'
73
+ + 'Spawn the reviewer subagent pnpm wp-review-upsert-pr names and hand it the instructions file; the\n'
74
+ + 'reviewer submits its own verdict.';
75
+ }
76
+ unstampedRefusal(checklistId, harnessEnv) {
77
+ return `${rules_config_1.WRITE_REVIEW_BIN} REFUSED: this process runs under an AI harness (${harnessEnv.join(', ')} set), but the\n`
78
+ + `webpieces PreToolUse hook left no identity stamp for checklist "${checklistId}", so nothing can say whether a\n`
79
+ + 'reviewer subagent or the coordinator is calling.\n\n'
80
+ + `Run it as a plain Bash command the hook can read, naming the checklist literally:\n`
81
+ + ` pnpm ${rules_config_1.WRITE_REVIEW_BIN} --checklist ${checklistId} <<'EOF' … EOF\n`
82
+ + 'If it already was, the webpieces hooks are not installed in this harness: pnpm wp-install-ai-hooks.';
83
+ }
84
+ };
85
+ exports.ReviewerIdentityResolver = ReviewerIdentityResolver;
86
+ exports.ReviewerIdentityResolver = ReviewerIdentityResolver = tslib_1.__decorate([
87
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
88
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.ReviewIdentityStampService])
89
+ ], ReviewerIdentityResolver);
90
+ //# sourceMappingURL=reviewer-identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reviewer-identity.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-identity.ts"],"names":[],"mappings":";;;;AAAA,0DAAsG;AACtG,yCAA2D;AAC3D,6DAAwD;AAExD;;;;GAIG;AACH,MAAM,WAAW,GAAG,CAAC,YAAY,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,iBAAiB,CAAU,CAAC;AAE7G,8CAA8C;AAC9C,MAAa,gBAAgB;IACzB,OAAO,CAAS;IAChB,SAAS,CAAS;IAClB,OAAO,CAAS;IAChB,SAAS,CAAS;IAElB,yDAAyD;IACzD,YAAY,OAAe,EAAE,SAAiB,EAAE,OAAe,EAAE,SAAiB;QAC9E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AAbD,4CAaC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEI,IAAM,w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mB,EAAE,UAA6B;QACvE,OAAO,GAAG,+BAAgB,oDAAoD,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB;cAC/G,mEAAmE,WAAW,mCAAmC;cACjH,sDAAsD;cACtD,qFAAqF;cACrF,YAAY,+BAAgB,gBAAgB,WAAW,kBAAkB;cACzE,qGAAqG,CAAC;IAChH,CAAC;CACJ,CAAA;AA9BY,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,yCAA0B;GADtD,wBAAwB,CA8BpC","sourcesContent":["import { InformAiError, ReviewIdentityStampService, WRITE_REVIEW_BIN } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { HARNESS_TERMINAL } from './verdict-provenance';\n\n/**\n * Env vars whose presence means an AI harness launched this process. Any one of them and there MUST be a\n * hook stamp — a harness-launched submission without one either bypassed the hook or ran where the hook is\n * not installed, and neither can say who is calling.\n */\nconst HARNESS_ENV = ['CLAUDECODE', 'CLAUDE_CODE_SESSION_ID', 'CODEX_SESSION_ID', 'CODEX_THREAD_ID'] as const;\n\n/** WHO is submitting a verdict. Data-only. */\nexport class ReviewerIdentity {\n harness: string;\n sessionId: string;\n agentId: string;\n agentType: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(harness: string, sessionId: string, agentId: string, agentType: string) {\n this.harness = harness;\n this.sessionId = sessionId;\n this.agentId = agentId;\n this.agentType = agentType;\n }\n}\n\n/**\n * Answers \"who is running `wp-write-review`?\" — and REFUSES the coordinating agent (issue #863).\n *\n * The mechanism, per harness, and why it is not the environment:\n * - CLAUDE CODE: a Bash child inherits `CLAUDE_CODE_SESSION_ID`, which is the PARENT session's id inside\n * a subagent too, and there is no agent id in the env at all. Env cannot tell a reviewer from its\n * coordinator.\n * - CODEX: `CODEX_SESSION_ID` / `CODEX_THREAD_ID` are exported, but nothing documents — and nothing here\n * has measured — that a spawned subagent gets its own thread id instead of the coordinator's.\n * - BOTH: the PreToolUse hook payload carries `agent_id`, empty for the main loop and set for a subagent,\n * on the same key in both harnesses. So the hook writes a {@link ReviewIdentityStamp} for each\n * checklist a `wp-write-review` command names, just before the command runs, and this consumes it.\n *\n * The plain-terminal story: with NO harness env and no stamp, the caller is a HUMAN at a terminal. That is\n * a legitimate reviewer, and the verdict is recorded with harness `terminal`. CI never submits verdicts —\n * `.webpieces/` is not in the repo, so there is nothing for CI to read or write here.\n *\n * NOT tamper-proof: an agent can scrub its env AND invoke the bin some way the hook does not recognise, or\n * forge a stamp file. That is deliberate, visible forgery in the transcript — the bar the rest of reviewer\n * provenance sets — rather than the one ordinary file write it used to take.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerIdentityResolver {\n constructor(private readonly stamps: ReviewIdentityStampService) {}\n\n resolve(cwd: string, checklistId: string, env: NodeJS.ProcessEnv = process.env): ReviewerIdentity {\n const stamp = this.stamps.take(cwd, checklistId);\n if (stamp !== null) {\n if (this.stamps.isCoordinator(stamp)) throw new InformAiError(this.coordinatorRefusal(checklistId, stamp.aiType));\n return new ReviewerIdentity(stamp.aiType, stamp.sessionId, stamp.agentId, stamp.agentType);\n }\n const inHarness = HARNESS_ENV.filter((name: string): boolean => (env[name] ?? '').trim() !== '');\n if (inHarness.length > 0) throw new InformAiError(this.unstampedRefusal(checklistId, inHarness));\n return new ReviewerIdentity(HARNESS_TERMINAL, '', '', '');\n }\n\n private coordinatorRefusal(checklistId: string, aiType: string): string {\n return `${WRITE_REVIEW_BIN} REFUSED: the ${aiType} harness reports this call comes from the COORDINATING agent, not a\\n`\n + `reviewer subagent. The coordinator may never submit a reviewer's verdict for \"${checklistId}\" — not by this\\n`\n + 'bin, and not by writing the file (wp-finish-upsert-pr rejects a verdict this bin did not write).\\n\\n'\n + 'Spawn the reviewer subagent pnpm wp-review-upsert-pr names and hand it the instructions file; the\\n'\n + 'reviewer submits its own verdict.';\n }\n\n private unstampedRefusal(checklistId: string, harnessEnv: readonly string[]): string {\n return `${WRITE_REVIEW_BIN} REFUSED: this process runs under an AI harness (${harnessEnv.join(', ')} set), but the\\n`\n + `webpieces PreToolUse hook left no identity stamp for checklist \"${checklistId}\", so nothing can say whether a\\n`\n + 'reviewer subagent or the coordinator is calling.\\n\\n'\n + `Run it as a plain Bash command the hook can read, naming the checklist literally:\\n`\n + ` pnpm ${WRITE_REVIEW_BIN} --checklist ${checklistId} <<'EOF' … EOF\\n`\n + 'If it already was, the webpieces hooks are not installed in this harness: pnpm wp-install-ai-hooks.';\n }\n}\n"]}
@@ -57,6 +57,14 @@ export declare class ReviewerVerdictGate {
57
57
  * one line an agent acts on first, and acting on it here IS the loop.
58
58
  */
59
59
  private refusedSection;
60
+ /**
61
+ * Verdict files that EXIST but do not count (issue #863), each with why — printed before the spawn
62
+ * list so the reader does not mistake them for reviewers that never ran, and so a hand-written verdict
63
+ * is named as what it is. REJECTED: no `wp-write-review` provenance, or edited after submission — a
64
+ * coordinator writing a reviewer's verdict lands here, and that is the forgery this gate exists to
65
+ * refuse. STALE: the checklist's in-scope files changed since it was submitted.
66
+ */
67
+ private discountedSection;
60
68
  /**
61
69
  * The reviewers that genuinely never ran — LAST, and listing ONLY these. When there are none this block
62
70
  * is absent entirely, which is the whole point: the "You MUST run these N reviewer subagent(s)"
@@ -4,6 +4,7 @@ exports.ReviewerVerdictGate = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const rules_config_1 = require("@webpieces/rules-config");
6
6
  const inversify_1 = require("inversify");
7
+ const verdict_provenance_1 = require("./verdict-provenance");
7
8
  /**
8
9
  * The gate `wp-finish-upsert-pr` runs before it parses review.json: REFUSE the PR while any applicable
9
10
  * checklist is not clear, and say — per checklist — which of three different things went wrong.
@@ -55,6 +56,7 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
55
56
  throw new rules_config_1.InformAiError(this.headline(scan, refused, neverRan)
56
57
  + this.unreadableSection(scan)
57
58
  + this.refusedSection(refusals, scan.singleRoundReview)
59
+ + this.discountedSection(scan, neverRan)
58
60
  + this.neverRanSection(scan, neverRan)
59
61
  + this.footer(refused.length > 0, scan.singleRoundReview));
60
62
  }
@@ -117,6 +119,24 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
117
119
  + ' the same answer: fix what it found (or get a HUMAN to authorize an override), THEN review again.\n\n'
118
120
  + refusals.map((r) => ` • ${r}`).join('\n\n') + '\n\n';
119
121
  }
122
+ /**
123
+ * Verdict files that EXIST but do not count (issue #863), each with why — printed before the spawn
124
+ * list so the reader does not mistake them for reviewers that never ran, and so a hand-written verdict
125
+ * is named as what it is. REJECTED: no `wp-write-review` provenance, or edited after submission — a
126
+ * coordinator writing a reviewer's verdict lands here, and that is the forgery this gate exists to
127
+ * refuse. STALE: the checklist's in-scope files changed since it was submitted.
128
+ */
129
+ discountedSection(scan, neverRan) {
130
+ const owed = new Set(neverRan.map((r) => r.id));
131
+ const discounted = scan.standings.filter((s) => owed.has(s.checklistId)
132
+ && (s.standing === verdict_provenance_1.STANDING_REJECTED || s.standing === verdict_provenance_1.STANDING_STALE));
133
+ if (discounted.length === 0)
134
+ return '';
135
+ return '🚫 NOT COUNTED — these verdict files exist, but they are not a current review:\n\n'
136
+ + discounted.map((s) => ` • ${s.checklistId} — ${s.standing.toUpperCase()}: ${s.reason}`).join('\n')
137
+ + '\n A reviewer SUBAGENT must submit a fresh verdict with pnpm wp-write-review. Do NOT write or copy the\n'
138
+ + ' file yourself: the bin refuses the coordinating agent, and this gate rejects a verdict it did not write.\n\n';
139
+ }
120
140
  /**
121
141
  * The reviewers that genuinely never ran — LAST, and listing ONLY these. When there are none this block
122
142
  * is absent entirely, which is the whole point: the "You MUST run these N reviewer subagent(s)"
@@ -125,7 +145,7 @@ let ReviewerVerdictGate = class ReviewerVerdictGate {
125
145
  neverRanSection(scan, neverRan) {
126
146
  if (neverRan.length === 0)
127
147
  return '';
128
- return '❓ NO VERDICT YET — nothing has been written for these, so they must actually be run:\n\n'
148
+ return '❓ NO VERDICT YET — nothing that counts has been submitted for these, so they must actually be run:\n\n'
129
149
  + `${this.instructions.render(neverRan, scan.reviewPath, scan.context)}\n\n`;
130
150
  }
131
151
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"reviewer-verdict-gate.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-verdict-gate.ts"],"names":[],"mappings":";;;;AAAA,0DAGiC;AACjC,yCAA2D;AAG3D;;;;;;;;;;;;;;;;;;;;GAoBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IAFrB,YACqB,iBAAoC,EACpC,YAA0C;QAD1C,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,iBAAY,GAAZ,YAAY,CAA8B;IAC5D,CAAC;IAEJ;;;;;;;OAOG;IACH,sBAAsB,CAAC,IAAmB;QACtC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAC1C,qGAAqG;QACrG,kGAAkG;QAClG,gGAAgG;QAChG,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACzF,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAoB,EAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAChF,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAoB,EAAW,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACnG,qGAAqG;QACrG,kGAAkG;QAClG,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,GAAsB,EAAU,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,IA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;QACd,CAAC;IACL,CAAC;IAED,yGAAyG;IACzG,0GAA0G;IAC1G,2BAA2B;IACnB,MAAM,CAAC,UAAmB,EAAE,iBAA0B;QAC1D,IAAI,UAAU,EAAE,CAAC;YACb,IAAI,iBAAiB,EAAE,CAAC;gBACpB,OAAO,8FAA8F;sBAC/F,wEAAwE;sBACxE,wFAAwF,CAAC;YACnG,CAAC;YACD,OAAO,mGAAmG;kBACpG,2FAA2F,CAAC;QACtG,CAAC;QACD,OAAO,yCAAyC;cAC1C,0GAA0G;cAC1G,oDAAoD,CAAC;IAC/D,CAAC;CACJ,CAAA;AApKY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGG,gCAAiB;QACtB,2CAA4B;GAHtD,mBAAmB,CAoK/B","sourcesContent":["import {\n ChecklistInstructionsService, InformAiError, RequiredChecklist, ReviewJsonService,\n SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ChecklistScan } from './checklist-scanner';\n\n/**\n * The gate `wp-finish-upsert-pr` runs before it parses review.json: REFUSE the PR while any applicable\n * checklist is not clear, and say — per checklist — which of three different things went wrong.\n *\n * It is its own class, not a private method on the command, for two reasons. It is the one piece of finish\n * that both MUTATES the branch (it retires red verdicts) and produces the text an AI acts on, so it is the\n * piece most worth asserting on directly; and the command it came out of is already the largest file in this\n * package, against a hard `@webpieces/max-file-lines` limit.\n *\n * THE BUG THIS EXISTS TO FIX. The message used to be one bucket and one imperative — \"You MUST run these N\n * reviewer subagent(s)\" — for three unrelated states. Handed to an agent, the literal, obedient response for\n * a checklist that had ALREADY REFUSED was to spawn the reviewer again; it re-read the same unchanged code,\n * refused again, and the loop cost a full subagent run per pass while the reviewer's actual finding was\n * never printed at all. Three states, three actions, in this order:\n *\n * 1. UNREADABLE (`scan.formatErrors`) -> fix four characters of JSON. Not a reviewer problem.\n * 2. REFUSED (CK_FAIL) -> fix the finding (or get a HUMAN override). Not a missing step.\n * 3. NEVER RAN (the rest) -> spawn the subagent. The ONLY case where that is the right move.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerVerdictGate {\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly instructions: ChecklistInstructionsService,\n ) {}\n\n /**\n * Refuse the PR while ANY applicable checklist still owes a passing verdict — naming exactly what each\n * one needs. No-op for a repo with no applicable checklists.\n *\n * SIDE EFFECT, deliberately: every REFUSED checklist's verdict file is RETIRED to review-<id>.json.old on\n * the way out (see {@link retireAndReport}). Only red verdicts are ever moved — a green, yellow or\n * overridden one is reused across finish attempts and retiring it would force a needless subagent re-run.\n */\n assertEveryReviewerRan(scan: ChecklistScan): void {\n if (scan.outstanding.length === 0) return;\n // The split is computed from the verdicts the SCAN already loaded, never from a second read of disk:\n // a re-read here could disagree with the set that produced `outstanding`, and a checklist that is\n // \"outstanding\" per one read and \"clear\" per another belongs to neither section of the message.\n const refused = this.reviewJsonService.refusedChecklists(scan.outstanding, scan.results);\n const refusedIds = new Set(refused.map((r: RequiredChecklist): string => r.id));\n const neverRan = scan.outstanding.filter((r: RequiredChecklist): boolean => !refusedIds.has(r.id));\n // Rendered BEFORE the throw and, per checklist, with the verdict resolved before its file is moved —\n // the message quotes the reviewer's own words, so losing them to the move would defeat the point.\n const refusals = refused.map((req: RequiredChecklist): string => this.retireAndReport(scan, req));\n throw new InformAiError(\n this.headline(scan, refused, neverRan)\n + this.unreadableSection(scan)\n + this.refusedSection(refusals, scan.singleRoundReview)\n + this.neverRanSection(scan, neverRan)\n + this.footer(refused.length > 0, scan.singleRoundReview),\n );\n }\n\n /**\n * Say plainly how many REFUSED and how many never ran.\n *\n * The old headline said all of them \"have no passing verdict yet\", which is technically true of a refusal\n * and reads as though nobody had looked. It is the sentence that framed a decision as an omission.\n */\n private headline(scan: ChecklistScan, refused: readonly RequiredChecklist[], neverRan: readonly RequiredChecklist[]): string {\n const lines = [\n `⛔ NO PR — ${scan.outstanding.length} of ${scan.applicable.length} review checklist(s) that apply to this branch are not clear:`,\n ];\n if (refused.length > 0) {\n lines.push(` • ${refused.length} REFUSED — a reviewer ran, judged this change, and said no: ${this.instructions.names(refused)}`);\n }\n if (neverRan.length > 0) {\n lines.push(` • ${neverRan.length} never ran — no verdict has been written yet: ${this.instructions.names(neverRan)}`);\n }\n return lines.join('\\n') + this.skippedNote(scan) + '\\n\\n';\n }\n\n /**\n * The optional checklists nobody ran, stated OUT LOUD on the refusal.\n *\n * They are not why the PR is being refused and this block says so — but a message that lists only what\n * blocked reads as \"everything else was reviewed\", and here that is false: those reviews were declined,\n * not passed. The one moment a human is looking at the review state is the moment to be honest about\n * which reviews did not happen, and it is also the prompt an AI needs to offer them again if the human\n * has changed their mind now that something else came back red.\n */\n private skippedNote(scan: ChecklistScan): string {\n if (scan.optionalNotRun.length === 0) return '';\n return `\\n (Not blocking: ${scan.optionalNotRun.length} OPTIONAL checklist(s) were not run — `\n + `${this.instructions.names(scan.optionalNotRun)}. They do not have to run; re-run\\n`\n + ' pnpm wp-review-upsert-pr if you now want to offer them.)';\n }\n\n // Unreadable verdict files come FIRST. A reviewer that wrote its verdict in the removed `success` format\n // is otherwise indistinguishable from one that never ran, and the AI would go re-run a subagent instead\n // of correcting four characters of JSON.\n private unreadableSection(scan: ChecklistScan): string {\n if (scan.formatErrors.length === 0) return '';\n return `${scan.formatErrors.length} verdict file(s) are in an UNREADABLE format:\\n\\n`\n + scan.formatErrors.map((e: string): string => ` • ${e}`).join('\\n') + '\\n\\n';\n }\n\n /**\n * The refusals — SECOND, above anything that says to spawn a subagent, because a spawn instruction is the\n * one line an agent acts on first, and acting on it here IS the loop.\n */\n private refusedSection(refusals: readonly string[], singleRoundReview: boolean): string {\n if (refusals.length === 0) return '';\n if (singleRoundReview) {\n return '⛔ REFUSED — SINGLE-ROUND MODE. These reviewers ALREADY ANSWERED and MUST NOT be rerun.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n'\n + ` main_agent_instructions: ${SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS}\\n\\n`;\n }\n return '⛔ REFUSED — these reviewers ALREADY ANSWERED. Re-spawning one against unchanged code only buys\\n'\n + ' the same answer: fix what it found (or get a HUMAN to authorize an override), THEN review again.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n';\n }\n\n /**\n * The reviewers that genuinely never ran — LAST, and listing ONLY these. When there are none this block\n * is absent entirely, which is the whole point: the \"You MUST run these N reviewer subagent(s)\"\n * imperative must not appear at all on a run whose only problem is a refusal.\n */\n private neverRanSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n if (neverRan.length === 0) return '';\n return '❓ NO VERDICT YET — nothing has been written for these, so they must actually be run:\\n\\n'\n + `${this.instructions.render(neverRan, scan.reviewPath, scan.context)}\\n\\n`;\n }\n\n /**\n * Retire ONE refused checklist's verdict and render the refusal that reports it.\n *\n * ORDER IS LOAD-BEARING. The verdict is resolved from the already-loaded results, so the finding is in\n * hand before the file moves; the move then happens; and only then is the message rendered, because it\n * names the archive path and must not claim a move that did not happen.\n *\n * The move is NON-FATAL. A finish that died after retiring a verdict would leave the AI with a red\n * verdict gone from the live path and no message saying where it went or why the PR was refused — a\n * silent gap, and the worst possible outcome for a feature whose entire purpose is a durable record. So a\n * failed move warns and the refusal is reported without an archive path (the file is then still live,\n * which the un-archived wording of `refusalError` describes correctly).\n */\n private retireAndReport(scan: ChecklistScan, req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, scan.results);\n if (scan.singleRoundReview) {\n const live = this.reviewJsonService.checklistResultPath(scan.reviewPath, req.id);\n return `Checklist \"${req.id}\" FAILED review (status:\"red\"). The reviewer wrote:\\n`\n + ` ${verdict.detail}\\n`\n + ` DO NOT RERUN this reviewer. After fixing every finding, edit ${live}.\\n`\n + ' Change its addressed red status to \"yellow\". Yellow is accepted by the gate. If you genuinely\\n'\n + ' disagree, leave it red and flag the human BEFORE posting the PR; red remains blocking.';\n }\n return this.reviewJsonService.refusalError(\n req, verdict, scan.reviewPath, this.archiveOrWarn(scan.reviewPath, req.id));\n }\n\n // The archive path, or '' when there was nothing to move or the move failed (see retireAndReport).\n private archiveOrWarn(reviewPath: string, checklistId: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a failed archive must never swallow the refusal it belongs to\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.reviewJsonService.archiveChecklistResult(reviewPath, checklistId);\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(\n `⚠️ Could not retire the refused verdict for \"${checklistId}\" (non-fatal — the refusal is still `\n + `reported below): ${error.message}\\n`);\n return '';\n }\n }\n\n // Re-running stage 2 is normally optional. It stops being optional after a refusal, because the only way\n // past one is to CHANGE the code — which is exactly the condition that makes the extracted diff and every\n // reviewer briefing stale.\n private footer(anyRefused: boolean, singleRoundReview: boolean): string {\n if (anyRefused) {\n if (singleRoundReview) {\n return 'Do NOT run pnpm wp-review-upsert-pr and do NOT re-run a reviewer. Fix the findings, change\\n'\n + 'addressed red verdicts to yellow, then run: pnpm wp-finish-upsert-pr\\n'\n + 'If any red remains because you disagree, STOP and ask the human before posting the PR.';\n }\n return 'Then re-run: pnpm wp-review-upsert-pr (the code changed, so the extracted diff and the reviewer\\n'\n + 'briefings are stale), re-run the reviewer(s) above, and finally: pnpm wp-finish-upsert-pr';\n }\n return 'Then re-run: pnpm wp-finish-upsert-pr\\n'\n + '(Each reviewer\\'s generated instructions file is already written — re-running pnpm wp-review-upsert-pr\\n'\n + ' is only needed if the code changed since it ran.)';\n }\n}\n"]}
1
+ {"version":3,"file":"reviewer-verdict-gate.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/reviewer-verdict-gate.ts"],"names":[],"mappings":";;;;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AAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,UAAU,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACpF,CAAC;IAED,mGAAmG;IAC3F,aAAa,CAAC,UAAkB,EAAE,WAAmB;QACzD,yHAAyH;QACzH,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,sBAAsB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;QAClF,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,sBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,iDAAiD,WAAW,sCAAsC;kBAChG,oBAAoB,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC;YAC7C,OAAO,EAAE,CAAC;QACd,CAAC;IACL,CAAC;IAED,yGAAyG;IACzG,0GAA0G;IAC1G,2BAA2B;IACnB,MAAM,CAAC,UAAmB,EAAE,iBAA0B;QAC1D,IAAI,UAAU,EAAE,CAAC;YACb,IAAI,iBAAiB,EAAE,CAAC;gBACpB,OAAO,8FAA8F;sBAC/F,wEAAwE;sBACxE,wFAAwF,CAAC;YACnG,CAAC;YACD,OAAO,mGAAmG;kBACpG,2FAA2F,CAAC;QACtG,CAAC;QACD,OAAO,yCAAyC;cAC1C,0GAA0G;cAC1G,oDAAoD,CAAC;IAC/D,CAAC;CACJ,CAAA;AAvLY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGG,gCAAiB;QACtB,2CAA4B;GAHtD,mBAAmB,CAuL/B","sourcesContent":["import {\n ChecklistInstructionsService, InformAiError, RequiredChecklist, ReviewJsonService,\n SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS, toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ChecklistScan } from './checklist-scanner';\nimport { STANDING_REJECTED, STANDING_STALE, VerdictStanding } from './verdict-provenance';\n\n/**\n * The gate `wp-finish-upsert-pr` runs before it parses review.json: REFUSE the PR while any applicable\n * checklist is not clear, and say — per checklist — which of three different things went wrong.\n *\n * It is its own class, not a private method on the command, for two reasons. It is the one piece of finish\n * that both MUTATES the branch (it retires red verdicts) and produces the text an AI acts on, so it is the\n * piece most worth asserting on directly; and the command it came out of is already the largest file in this\n * package, against a hard `@webpieces/max-file-lines` limit.\n *\n * THE BUG THIS EXISTS TO FIX. The message used to be one bucket and one imperative — \"You MUST run these N\n * reviewer subagent(s)\" — for three unrelated states. Handed to an agent, the literal, obedient response for\n * a checklist that had ALREADY REFUSED was to spawn the reviewer again; it re-read the same unchanged code,\n * refused again, and the loop cost a full subagent run per pass while the reviewer's actual finding was\n * never printed at all. Three states, three actions, in this order:\n *\n * 1. UNREADABLE (`scan.formatErrors`) -> fix four characters of JSON. Not a reviewer problem.\n * 2. REFUSED (CK_FAIL) -> fix the finding (or get a HUMAN override). Not a missing step.\n * 3. NEVER RAN (the rest) -> spawn the subagent. The ONLY case where that is the right move.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ReviewerVerdictGate {\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly instructions: ChecklistInstructionsService,\n ) {}\n\n /**\n * Refuse the PR while ANY applicable checklist still owes a passing verdict — naming exactly what each\n * one needs. No-op for a repo with no applicable checklists.\n *\n * SIDE EFFECT, deliberately: every REFUSED checklist's verdict file is RETIRED to review-<id>.json.old on\n * the way out (see {@link retireAndReport}). Only red verdicts are ever moved — a green, yellow or\n * overridden one is reused across finish attempts and retiring it would force a needless subagent re-run.\n */\n assertEveryReviewerRan(scan: ChecklistScan): void {\n if (scan.outstanding.length === 0) return;\n // The split is computed from the verdicts the SCAN already loaded, never from a second read of disk:\n // a re-read here could disagree with the set that produced `outstanding`, and a checklist that is\n // \"outstanding\" per one read and \"clear\" per another belongs to neither section of the message.\n const refused = this.reviewJsonService.refusedChecklists(scan.outstanding, scan.results);\n const refusedIds = new Set(refused.map((r: RequiredChecklist): string => r.id));\n const neverRan = scan.outstanding.filter((r: RequiredChecklist): boolean => !refusedIds.has(r.id));\n // Rendered BEFORE the throw and, per checklist, with the verdict resolved before its file is moved —\n // the message quotes the reviewer's own words, so losing them to the move would defeat the point.\n const refusals = refused.map((req: RequiredChecklist): string => this.retireAndReport(scan, req));\n throw new InformAiError(\n this.headline(scan, refused, neverRan)\n + this.unreadableSection(scan)\n + this.refusedSection(refusals, scan.singleRoundReview)\n + this.discountedSection(scan, neverRan)\n + this.neverRanSection(scan, neverRan)\n + this.footer(refused.length > 0, scan.singleRoundReview),\n );\n }\n\n /**\n * Say plainly how many REFUSED and how many never ran.\n *\n * The old headline said all of them \"have no passing verdict yet\", which is technically true of a refusal\n * and reads as though nobody had looked. It is the sentence that framed a decision as an omission.\n */\n private headline(scan: ChecklistScan, refused: readonly RequiredChecklist[], neverRan: readonly RequiredChecklist[]): string {\n const lines = [\n `⛔ NO PR — ${scan.outstanding.length} of ${scan.applicable.length} review checklist(s) that apply to this branch are not clear:`,\n ];\n if (refused.length > 0) {\n lines.push(` • ${refused.length} REFUSED — a reviewer ran, judged this change, and said no: ${this.instructions.names(refused)}`);\n }\n if (neverRan.length > 0) {\n lines.push(` • ${neverRan.length} never ran — no verdict has been written yet: ${this.instructions.names(neverRan)}`);\n }\n return lines.join('\\n') + this.skippedNote(scan) + '\\n\\n';\n }\n\n /**\n * The optional checklists nobody ran, stated OUT LOUD on the refusal.\n *\n * They are not why the PR is being refused and this block says so — but a message that lists only what\n * blocked reads as \"everything else was reviewed\", and here that is false: those reviews were declined,\n * not passed. The one moment a human is looking at the review state is the moment to be honest about\n * which reviews did not happen, and it is also the prompt an AI needs to offer them again if the human\n * has changed their mind now that something else came back red.\n */\n private skippedNote(scan: ChecklistScan): string {\n if (scan.optionalNotRun.length === 0) return '';\n return `\\n (Not blocking: ${scan.optionalNotRun.length} OPTIONAL checklist(s) were not run — `\n + `${this.instructions.names(scan.optionalNotRun)}. They do not have to run; re-run\\n`\n + ' pnpm wp-review-upsert-pr if you now want to offer them.)';\n }\n\n // Unreadable verdict files come FIRST. A reviewer that wrote its verdict in the removed `success` format\n // is otherwise indistinguishable from one that never ran, and the AI would go re-run a subagent instead\n // of correcting four characters of JSON.\n private unreadableSection(scan: ChecklistScan): string {\n if (scan.formatErrors.length === 0) return '';\n return `${scan.formatErrors.length} verdict file(s) are in an UNREADABLE format:\\n\\n`\n + scan.formatErrors.map((e: string): string => ` • ${e}`).join('\\n') + '\\n\\n';\n }\n\n /**\n * The refusals — SECOND, above anything that says to spawn a subagent, because a spawn instruction is the\n * one line an agent acts on first, and acting on it here IS the loop.\n */\n private refusedSection(refusals: readonly string[], singleRoundReview: boolean): string {\n if (refusals.length === 0) return '';\n if (singleRoundReview) {\n return '⛔ REFUSED — SINGLE-ROUND MODE. These reviewers ALREADY ANSWERED and MUST NOT be rerun.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n'\n + ` main_agent_instructions: ${SINGLE_ROUND_MAIN_AGENT_INSTRUCTIONS}\\n\\n`;\n }\n return '⛔ REFUSED — these reviewers ALREADY ANSWERED. Re-spawning one against unchanged code only buys\\n'\n + ' the same answer: fix what it found (or get a HUMAN to authorize an override), THEN review again.\\n\\n'\n + refusals.map((r: string): string => ` • ${r}`).join('\\n\\n') + '\\n\\n';\n }\n\n /**\n * Verdict files that EXIST but do not count (issue #863), each with why — printed before the spawn\n * list so the reader does not mistake them for reviewers that never ran, and so a hand-written verdict\n * is named as what it is. REJECTED: no `wp-write-review` provenance, or edited after submission — a\n * coordinator writing a reviewer's verdict lands here, and that is the forgery this gate exists to\n * refuse. STALE: the checklist's in-scope files changed since it was submitted.\n */\n private discountedSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n const owed = new Set(neverRan.map((r: RequiredChecklist): string => r.id));\n const discounted = scan.standings.filter((s: VerdictStanding): boolean => owed.has(s.checklistId)\n && (s.standing === STANDING_REJECTED || s.standing === STANDING_STALE));\n if (discounted.length === 0) return '';\n return '🚫 NOT COUNTED — these verdict files exist, but they are not a current review:\\n\\n'\n + discounted.map((s: VerdictStanding): string => ` • ${s.checklistId} — ${s.standing.toUpperCase()}: ${s.reason}`).join('\\n')\n + '\\n A reviewer SUBAGENT must submit a fresh verdict with pnpm wp-write-review. Do NOT write or copy the\\n'\n + ' file yourself: the bin refuses the coordinating agent, and this gate rejects a verdict it did not write.\\n\\n';\n }\n\n /**\n * The reviewers that genuinely never ran — LAST, and listing ONLY these. When there are none this block\n * is absent entirely, which is the whole point: the \"You MUST run these N reviewer subagent(s)\"\n * imperative must not appear at all on a run whose only problem is a refusal.\n */\n private neverRanSection(scan: ChecklistScan, neverRan: readonly RequiredChecklist[]): string {\n if (neverRan.length === 0) return '';\n return '❓ NO VERDICT YET — nothing that counts has been submitted for these, so they must actually be run:\\n\\n'\n + `${this.instructions.render(neverRan, scan.reviewPath, scan.context)}\\n\\n`;\n }\n\n /**\n * Retire ONE refused checklist's verdict and render the refusal that reports it.\n *\n * ORDER IS LOAD-BEARING. The verdict is resolved from the already-loaded results, so the finding is in\n * hand before the file moves; the move then happens; and only then is the message rendered, because it\n * names the archive path and must not claim a move that did not happen.\n *\n * The move is NON-FATAL. A finish that died after retiring a verdict would leave the AI with a red\n * verdict gone from the live path and no message saying where it went or why the PR was refused — a\n * silent gap, and the worst possible outcome for a feature whose entire purpose is a durable record. So a\n * failed move warns and the refusal is reported without an archive path (the file is then still live,\n * which the un-archived wording of `refusalError` describes correctly).\n */\n private retireAndReport(scan: ChecklistScan, req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, scan.results);\n if (scan.singleRoundReview) {\n const live = this.reviewJsonService.checklistResultPath(scan.reviewPath, req.id);\n return `Checklist \"${req.id}\" FAILED review (status:\"red\"). The reviewer wrote:\\n`\n + ` ${verdict.detail}\\n`\n + ` DO NOT RERUN this reviewer. After fixing every finding, edit ${live}.\\n`\n + ' Change its addressed red status to \"yellow\". Yellow is accepted by the gate. If you genuinely\\n'\n + ' disagree, leave it red and flag the human BEFORE posting the PR; red remains blocking.';\n }\n return this.reviewJsonService.refusalError(\n req, verdict, scan.reviewPath, this.archiveOrWarn(scan.reviewPath, req.id));\n }\n\n // The archive path, or '' when there was nothing to move or the move failed (see retireAndReport).\n private archiveOrWarn(reviewPath: string, checklistId: string): string {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: a failed archive must never swallow the refusal it belongs to\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return this.reviewJsonService.archiveChecklistResult(reviewPath, checklistId);\n } catch (err: unknown) {\n const error = toError(err);\n process.stderr.write(\n `⚠️ Could not retire the refused verdict for \"${checklistId}\" (non-fatal — the refusal is still `\n + `reported below): ${error.message}\\n`);\n return '';\n }\n }\n\n // Re-running stage 2 is normally optional. It stops being optional after a refusal, because the only way\n // past one is to CHANGE the code — which is exactly the condition that makes the extracted diff and every\n // reviewer briefing stale.\n private footer(anyRefused: boolean, singleRoundReview: boolean): string {\n if (anyRefused) {\n if (singleRoundReview) {\n return 'Do NOT run pnpm wp-review-upsert-pr and do NOT re-run a reviewer. Fix the findings, change\\n'\n + 'addressed red verdicts to yellow, then run: pnpm wp-finish-upsert-pr\\n'\n + 'If any red remains because you disagree, STOP and ask the human before posting the PR.';\n }\n return 'Then re-run: pnpm wp-review-upsert-pr (the code changed, so the extracted diff and the reviewer\\n'\n + 'briefings are stale), re-run the reviewer(s) above, and finally: pnpm wp-finish-upsert-pr';\n }\n return 'Then re-run: pnpm wp-finish-upsert-pr\\n'\n + '(Each reviewer\\'s generated instructions file is already written — re-running pnpm wp-review-upsert-pr\\n'\n + ' is only needed if the code changed since it ran.)';\n }\n}\n"]}
@@ -0,0 +1,90 @@
1
+ import { AtomicFile, ChecklistResult, ReviewJsonService } from '@webpieces/rules-config';
2
+ /** `harness` for a verdict submitted from a plain terminal — a HUMAN reviewer, with no AI harness at all. */
3
+ export declare const HARNESS_TERMINAL = "terminal";
4
+ /** A verdict exactly as `wp-write-review` accepts it — the five fields and nothing else. Data-only. */
5
+ export declare class SubmittedVerdict {
6
+ id: string;
7
+ status: string;
8
+ agent: string;
9
+ model: string;
10
+ output: string;
11
+ constructor(id: string, status: string, agent: string, model: string, output: string);
12
+ }
13
+ /**
14
+ * The record `wp-write-review` writes to `review-<id>.provenance.json`. Data-only; field names are the JSON
15
+ * keys, `_WHAT_THIS_IS` first so a reader learns what the file is before anything it might act on.
16
+ */
17
+ export declare class VerdictProvenance {
18
+ _WHAT_THIS_IS: string;
19
+ writer: string;
20
+ checklistId: string;
21
+ harness: string;
22
+ sessionId: string;
23
+ agentId: string;
24
+ agentType: string;
25
+ headSha: string;
26
+ scopeHash: string;
27
+ status: string;
28
+ verdictHash: string;
29
+ writtenAt: string;
30
+ constructor(checklistId: string, harness: string, sessionId: string, agentId: string, agentType: string, headSha: string, scopeHash: string);
31
+ }
32
+ /** A live verdict that stands: submitted through the bin and judged the in-scope diff as it is NOW. */
33
+ export declare const STANDING_CURRENT = "current";
34
+ /** Submitted through the bin, but the checklist's in-scope diff has changed since — it judged other code. */
35
+ export declare const STANDING_STALE = "stale";
36
+ /** No bin provenance, or edited after submission: not a reviewer's verdict at all. */
37
+ export declare const STANDING_REJECTED = "rejected";
38
+ /**
39
+ * How ONE existing verdict file stands against the branch as it is now. Data-only. Carried on the
40
+ * checklist scan so stage ② (which briefs) and stage ③ (which blocks) read one answer.
41
+ */
42
+ export declare class VerdictStanding {
43
+ checklistId: string;
44
+ standing: string;
45
+ status: string;
46
+ fromSha: string;
47
+ reason: string;
48
+ constructor(checklistId: string, standing: string, status: string, fromSha: string, reason: string);
49
+ }
50
+ /**
51
+ * Writes a submitted verdict WITH its provenance, and judges an existing verdict against it (issue #863).
52
+ *
53
+ * This is what closes the forgery the issue measured: a Codex coordinator wrote five `review-<id>.json`
54
+ * files itself and the gate accepted them, because nothing distinguished a reviewer's verdict from a file
55
+ * that merely had the right shape. Now a verdict counts only when `wp-write-review` wrote it — which it does
56
+ * only for a caller the harness identified as a subagent — and only while it still says exactly what was
57
+ * submitted.
58
+ *
59
+ * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.
60
+ */
61
+ export declare class VerdictProvenanceService {
62
+ private readonly reviewJsonService;
63
+ private readonly atomicFile;
64
+ constructor(reviewJsonService: ReviewJsonService, atomicFile: AtomicFile);
65
+ /** `review-<id>.provenance.json`, beside the verdict. */
66
+ provenancePath(reviewPath: string, checklistId: string): string;
67
+ /**
68
+ * sha256 over the five fields in a FIXED order, so formatting, key order and whitespace outside the
69
+ * values cannot move it — only a change to what the verdict SAYS can.
70
+ */
71
+ canonicalHash(verdict: SubmittedVerdict): string;
72
+ /** Write the verdict, then its provenance. Returns the verdict path. */
73
+ write(reviewPath: string, verdict: SubmittedVerdict, provenance: VerdictProvenance): string;
74
+ /** The provenance for one checklist, or null when there is none (or it is unreadable). */
75
+ read(reviewPath: string, checklistId: string): VerdictProvenance | null;
76
+ /**
77
+ * How one parsed verdict stands. `currentScopeHash` is this checklist's scope hash NOW ('' when it
78
+ * could not be computed, which never marks anything stale). `singleRound` is the machine's
79
+ * `singleRoundReview` opt-in, and it changes two things — both so that this check does not narrow what
80
+ * that experimental flag already promises:
81
+ * - scope never goes STALE: one round means one round, and its verdicts are the review record;
82
+ * - the one edit that mode tells the COORDINATOR to make — an addressed red changed to yellow in
83
+ * place — is accepted, and nothing else is.
84
+ */
85
+ assess(reviewPath: string, result: ChecklistResult, currentScopeHash: string, singleRound: boolean): VerdictStanding;
86
+ /** The first 8 characters of a sha, the way every banner line prints one. */
87
+ short(sha: string): string;
88
+ private matchesSubmission;
89
+ private str;
90
+ }