@fro.bot/systematic 3.18.3 → 3.18.5

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.
@@ -2,6 +2,7 @@
2
2
  // biome-ignore-all assist/source/organizeImports: generated bundle
3
3
  // Generated by scripts/generate-ce-review-validator.ts; do not edit by hand.
4
4
  // Run `bun run ce-review-validator:build` to regenerate.
5
+ // source-digest: d8c9763e3ace0919dbdc8994665795ed8666be392c40e526f2807b0c2fb17eae
5
6
  var __defProp = Object.defineProperty
6
7
  var __returnValue = (v) => v
7
8
  function __exportSetter(name, newValue) {
@@ -172,7 +173,7 @@ function resolveReviewArtifactPath(input, cwd, options = {}) {
172
173
  return { ok: true, path: canonicalTarget }
173
174
  }
174
175
 
175
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/util.js
176
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/util.js
176
177
  function getEnumValues(entries) {
177
178
  const numericValues = Object.values(entries).filter(
178
179
  (v) => typeof v === 'number',
@@ -667,9 +668,6 @@ function members(proto, table) {
667
668
  Object.defineProperty(proto, key, { ...desc, enumerable: false })
668
669
  else defineBound(proto, key, desc.value)
669
670
  }
670
- for (const sym of Object.getOwnPropertySymbols(table)) {
671
- defineBound(proto, sym, table[sym])
672
- }
673
671
  }
674
672
  function own(inst, key, value, enumerable = true) {
675
673
  Object.defineProperty(inst, key, {
@@ -796,7 +794,7 @@ function constantCatch(value) {
796
794
  return fn
797
795
  }
798
796
 
799
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/core.js
797
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/core.js
800
798
  var _a
801
799
  var _zodDesc = { value: undefined, enumerable: false }
802
800
  var _E = 'captureStackTrace' in Error ? Error : null
@@ -838,8 +836,7 @@ function $constructor(name, initializer, proto, params) {
838
836
  } finally {
839
837
  _zodDesc.value = undefined
840
838
  }
841
- }
842
- if (inst._zod.traits.has(name)) {
839
+ } else if (inst._zod.traits.has(name)) {
843
840
  return
844
841
  }
845
842
  inst._zod.traits.add(name)
@@ -911,7 +908,7 @@ function config(newConfig) {
911
908
  if (newConfig) Object.assign(globalConfig, newConfig)
912
909
  return globalConfig
913
910
  }
914
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/errors.js
911
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/errors.js
915
912
  function _getMessage() {
916
913
  const internals = this._zod
917
914
  internals.message ??
@@ -1048,7 +1045,7 @@ function formatError(error, mapper = (issue) => issue.message) {
1048
1045
  return fieldErrors
1049
1046
  }
1050
1047
 
1051
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/parse.js
1048
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/parse.js
1052
1049
  function finalizeParams(callee, params) {
1053
1050
  return { callee: params?.callee ?? callee, Err: params?.Err }
1054
1051
  }
@@ -1210,7 +1207,7 @@ var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
1210
1207
  var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
1211
1208
  return _safeParseAsync(_Err)(schema, value, _ctx)
1212
1209
  }
1213
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/regexes.js
1210
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/regexes.js
1214
1211
  var cuid = /^[cC][0-9a-z]{6,}$/
1215
1212
  var cuid2 = /^[0-9a-z]+$/
1216
1213
  var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/
@@ -1287,7 +1284,7 @@ var boolean = /^(?:true|false)$/i
1287
1284
  var lowercase = /^[^A-Z]*$/
1288
1285
  var uppercase = /^[^a-z]*$/
1289
1286
 
1290
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/checks.js
1287
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/checks.js
1291
1288
  var $ZodCheck = /* @__PURE__ */ $constructor('$ZodCheck', (inst, def) => {
1292
1289
  var _a
1293
1290
  inst._zod ?? (inst._zod = {})
@@ -1667,7 +1664,7 @@ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor(
1667
1664
  },
1668
1665
  )
1669
1666
 
1670
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/doc.js
1667
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/doc.js
1671
1668
  class Doc {
1672
1669
  constructor(args = [], closed = {}) {
1673
1670
  this.content = []
@@ -1718,14 +1715,14 @@ ${content.join(`
1718
1715
  }
1719
1716
  }
1720
1717
 
1721
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/versions.js
1718
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/versions.js
1722
1719
  var version = {
1723
1720
  major: 4,
1724
1721
  minor: 6,
1725
- patch: 2,
1722
+ patch: 4,
1726
1723
  }
1727
1724
 
1728
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/schemas.js
1725
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/schemas.js
1729
1726
  var $ZodType = /* @__PURE__ */ $constructor(
1730
1727
  '$ZodType',
1731
1728
  (inst, def) => {
@@ -1914,6 +1911,22 @@ var $ZodEmail = /* @__PURE__ */ $constructor('$ZodEmail', (inst, def) => {
1914
1911
  })
1915
1912
  var URL_BAD_FORMAT = 1
1916
1913
  var URL_UNPARSEABLE = 2
1914
+ function canParseURL(input) {
1915
+ try {
1916
+ if (typeof URL !== 'undefined' && typeof URL.canParse === 'function')
1917
+ return URL.canParse(input)
1918
+ new URL(input)
1919
+ return true
1920
+ } catch {
1921
+ return false
1922
+ }
1923
+ }
1924
+ function validateURL(trimmed, def) {
1925
+ if (!('normalize' in def) && !('hostname' in def) && !('protocol' in def)) {
1926
+ return canParseURL(trimmed) || URL_UNPARSEABLE
1927
+ }
1928
+ return parseURLObject(trimmed, def)
1929
+ }
1917
1930
  function parseURLObject(trimmed, def) {
1918
1931
  if (
1919
1932
  !def.normalize &&
@@ -1923,6 +1936,11 @@ function parseURLObject(trimmed, def) {
1923
1936
  return URL_BAD_FORMAT
1924
1937
  }
1925
1938
  try {
1939
+ if (typeof URL !== 'undefined') {
1940
+ const URLStatic = URL
1941
+ if (typeof URLStatic.parse === 'function')
1942
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE
1943
+ }
1926
1944
  return new URL(trimmed)
1927
1945
  } catch {
1928
1946
  return URL_UNPARSEABLE
@@ -1947,7 +1965,7 @@ var $ZodURL = /* @__PURE__ */ $constructor('$ZodURL', (inst, def) => {
1947
1965
  inst._zod.check = (payload) => {
1948
1966
  try {
1949
1967
  const trimmed = payload.value.trim()
1950
- const url = parseURLObject(trimmed, def)
1968
+ const url = validateURL(trimmed, def)
1951
1969
  if (url === URL_BAD_FORMAT) {
1952
1970
  payload.issues.push({
1953
1971
  code: 'invalid_format',
@@ -1969,6 +1987,10 @@ var $ZodURL = /* @__PURE__ */ $constructor('$ZodURL', (inst, def) => {
1969
1987
  })
1970
1988
  return
1971
1989
  }
1990
+ if (url === true) {
1991
+ payload.value = stripTabAndNewline(trimmed)
1992
+ return
1993
+ }
1972
1994
  if (def.hostname && !urlHostnameOk(url, def.hostname)) {
1973
1995
  payload.issues.push({
1974
1996
  code: 'invalid_format',
@@ -2068,12 +2090,7 @@ var $ZodIPv4 = /* @__PURE__ */ $constructor('$ZodIPv4', (inst, def) => {
2068
2090
  var ipv6Alphabet = /^[0-9a-fA-F:.]+$/
2069
2091
  function isValidIPv6(value) {
2070
2092
  if (!ipv6Alphabet.test(value)) return false
2071
- try {
2072
- new URL(`http://[${value}]`)
2073
- return true
2074
- } catch {
2075
- return false
2076
- }
2093
+ return canParseURL(`http://[${value}]`)
2077
2094
  }
2078
2095
  var $ZodIPv6 = /* @__PURE__ */ $constructor('$ZodIPv6', (inst, def) => {
2079
2096
  def.pattern ?? (def.pattern = ipv6)
@@ -3292,85 +3309,7 @@ function handleRefineResult(result, payload, input, inst) {
3292
3309
  payload.issues.push(issue(_iss))
3293
3310
  }
3294
3311
  }
3295
- function handlePropertiesResult(result, payload, key) {
3296
- if (result.issues.length) {
3297
- payload.issues.push(...prefixIssues(key, result.issues))
3298
- }
3299
- }
3300
- var $ZodProperties = /* @__PURE__ */ $constructor(
3301
- '$ZodProperties',
3302
- (inst, def) => {
3303
- $ZodType.init(inst, def)
3304
- $ZodCheck.init(inst, def)
3305
- const memo = globalConfig.memoizer
3306
- memo?.attach(inst)
3307
- let entries
3308
- const runShape = (payload, ctx) => {
3309
- entries ??
3310
- (entries = Reflect.ownKeys(def.shape).map((key) => [
3311
- key,
3312
- def.shape[key],
3313
- ]))
3314
- const input = payload.value
3315
- let proms
3316
- for (const [key, schema] of entries) {
3317
- const result = schema._zod.run({ value: input[key], issues: [] }, ctx)
3318
- if (result instanceof Promise) {
3319
- proms ?? (proms = [])
3320
- proms.push(
3321
- result.then((result) =>
3322
- handlePropertiesResult(result, payload, key),
3323
- ),
3324
- )
3325
- } else {
3326
- handlePropertiesResult(result, payload, key)
3327
- }
3328
- }
3329
- if (proms)
3330
- return Promise.all(proms).then(() => {
3331
- return
3332
- })
3333
- return
3334
- }
3335
- inst._zod.parse = (payload, ctx) => {
3336
- const input = payload.value
3337
- if (
3338
- input === null ||
3339
- (typeof input !== 'object' && typeof input !== 'function')
3340
- ) {
3341
- payload.issues.push({
3342
- expected: 'object',
3343
- code: 'invalid_type',
3344
- input,
3345
- inst,
3346
- })
3347
- return payload
3348
- }
3349
- if (ctx.direction === 'backward') ctx = { ...ctx, direction: 'forward' }
3350
- if (memo) memo.alloc(inst, payload, input, ctx)
3351
- const result = runShape(payload, ctx)
3352
- return result instanceof Promise ? result.then(() => payload) : payload
3353
- }
3354
- inst._zod.check = (payload) => {
3355
- if (payload.value == null) {
3356
- payload.issues.push({
3357
- expected: 'object',
3358
- code: 'invalid_type',
3359
- input: payload.value,
3360
- inst,
3361
- })
3362
- return
3363
- }
3364
- return runShape(payload, {})
3365
- }
3366
- },
3367
- {
3368
- *[Symbol.iterator]() {
3369
- yield this
3370
- },
3371
- },
3372
- )
3373
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/memoizer.js
3312
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/memoizer.js
3374
3313
  class $ZodCyclicError extends Error {
3375
3314
  constructor() {
3376
3315
  super(`Cannot parse a reference cycle that closes through a transform`)
@@ -3380,9 +3319,7 @@ class $ZodCyclicError extends Error {
3380
3319
  var STATE = '~memo'
3381
3320
  var NO_ISSUES = []
3382
3321
  function isRef(value) {
3383
- return (
3384
- value !== null && (typeof value === 'object' || typeof value === 'function')
3385
- )
3322
+ return value !== null && typeof value === 'object'
3386
3323
  }
3387
3324
  function cloneIssues(issues) {
3388
3325
  return issues.map((iss) =>
@@ -3431,9 +3368,6 @@ function isRecursive(inst, stack, resolve) {
3431
3368
  check(def.catchall)
3432
3369
  break
3433
3370
  }
3434
- case 'properties':
3435
- merge(shape(def.shape, false))
3436
- break
3437
3371
  case 'array':
3438
3372
  check(def.element)
3439
3373
  break
@@ -3632,7 +3566,7 @@ function isBackEdge(ctx, value) {
3632
3566
  const backEdges = ctx[STATE]?.backEdges
3633
3567
  return backEdges !== undefined && isRef(value) && backEdges.has(value)
3634
3568
  }
3635
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/locales/en.js
3569
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/locales/en.js
3636
3570
  var error = () => {
3637
3571
  const Sizable = {
3638
3572
  string: { unit: 'characters', verb: 'to have' },
@@ -3672,6 +3606,7 @@ var error = () => {
3672
3606
  base64url: 'base64url-encoded string',
3673
3607
  json_string: 'JSON string',
3674
3608
  e164: 'E.164 number',
3609
+ currency_code: 'currency code',
3675
3610
  credit_card: 'credit card number',
3676
3611
  iban: 'IBAN',
3677
3612
  jwt: 'JWT',
@@ -3761,7 +3696,7 @@ function en_default() {
3761
3696
  localeError: error(),
3762
3697
  }
3763
3698
  }
3764
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/registries.js
3699
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/registries.js
3765
3700
  var _a2
3766
3701
  class $ZodRegistry {
3767
3702
  constructor() {
@@ -3809,12 +3744,15 @@ function registry() {
3809
3744
  ;(_a2 = globalThis).__zod_globalRegistry ??
3810
3745
  (_a2.__zod_globalRegistry = registry())
3811
3746
  var globalRegistry = globalThis.__zod_globalRegistry
3812
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/api.js
3747
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/api.js
3748
+ function snapshotChecks(def) {
3749
+ if (def.checks) def.checks = [...def.checks]
3750
+ return def
3751
+ }
3813
3752
  function _string(Class, params) {
3814
- return new Class({
3815
- type: 'string',
3816
- ...normalizeParams(params),
3817
- })
3753
+ return new Class(
3754
+ snapshotChecks({ type: 'string', ...normalizeParams(params) }),
3755
+ )
3818
3756
  }
3819
3757
  function _email(Class, params) {
3820
3758
  return new Class({
@@ -4054,11 +3992,9 @@ function _isoDuration(Class, params) {
4054
3992
  })
4055
3993
  }
4056
3994
  function _number(Class, params) {
4057
- return new Class({
4058
- type: 'number',
4059
- checks: [],
4060
- ...normalizeParams(params),
4061
- })
3995
+ return new Class(
3996
+ snapshotChecks({ type: 'number', checks: [], ...normalizeParams(params) }),
3997
+ )
4062
3998
  }
4063
3999
  function _int(Class, params) {
4064
4000
  return new Class({
@@ -4257,7 +4193,7 @@ function _check(fn, params) {
4257
4193
  ch._zod.check = fn
4258
4194
  return ch
4259
4195
  }
4260
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/to-json-schema.js
4196
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/to-json-schema.js
4261
4197
  function assignProps(target, ...sources) {
4262
4198
  for (const source of sources) {
4263
4199
  for (const key of Reflect.ownKeys(source)) {
@@ -4812,7 +4748,7 @@ var createStandardJSONSchemaMethod =
4812
4748
  extractDefs(ctx, schema)
4813
4749
  return finalize(ctx, schema)
4814
4750
  }
4815
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/core/json-schema-processors.js
4751
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/core/json-schema-processors.js
4816
4752
  var narrowMin = (agg, key, value) => {
4817
4753
  if (agg[key] === undefined || value > agg[key]) agg[key] = value
4818
4754
  }
@@ -5136,19 +5072,19 @@ var objectProcessor = (schema, ctx, _json, params) => {
5136
5072
  }),
5137
5073
  )
5138
5074
  }
5139
- const allKeys = new Set(Object.keys(shape))
5140
- const requiredKeys = new Set(
5141
- [...allKeys].filter((key) => {
5142
- const field = def.shape[key]
5143
- if (ctx.io === 'input') {
5144
- return inputOptin(field) === undefined
5145
- } else {
5146
- return field._zod.optout === undefined
5147
- }
5148
- }),
5149
- )
5150
- if (requiredKeys.size > 0) {
5151
- json.required = Array.from(requiredKeys)
5075
+ const requiredKeys = []
5076
+ for (const key of Object.keys(shape)) {
5077
+ const field = def.shape[key]
5078
+ if (
5079
+ ctx.io === 'input'
5080
+ ? inputOptin(field) === undefined
5081
+ : field._zod.optout === undefined
5082
+ ) {
5083
+ requiredKeys.push(key)
5084
+ }
5085
+ }
5086
+ if (requiredKeys.length > 0) {
5087
+ json.required = requiredKeys
5152
5088
  }
5153
5089
  if (def.catchall?._zod.def.type === 'never') {
5154
5090
  json.additionalProperties = false
@@ -5302,7 +5238,7 @@ var optionalProcessor = (schema, ctx, _json, params) => {
5302
5238
  const seen = ctx.seen.get(schema)
5303
5239
  seen.ref = def.innerType
5304
5240
  }
5305
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/classic/errors.js
5241
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/classic/errors.js
5306
5242
  var _installedErrorProtos = /* @__PURE__ */ new WeakSet([
5307
5243
  Object.prototype,
5308
5244
  Error.prototype,
@@ -5366,7 +5302,7 @@ var ZodRealError = /* @__PURE__ */ $constructor(
5366
5302
  },
5367
5303
  )
5368
5304
 
5369
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/classic/parse.js
5305
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/classic/parse.js
5370
5306
  var parse2 = /* @__PURE__ */ _parse(ZodRealError)
5371
5307
  var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError)
5372
5308
  var safeParse = /* @__PURE__ */ _safeParse(ZodRealError)
@@ -5380,7 +5316,7 @@ var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError)
5380
5316
  var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError)
5381
5317
  var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError)
5382
5318
 
5383
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/classic/schemas.js
5319
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/classic/schemas.js
5384
5320
  function _ensureDefaultLocale() {
5385
5321
  if (!globalConfig.localeError) config(en_default())
5386
5322
  }
@@ -6349,7 +6285,7 @@ function refine(fn, _params = {}) {
6349
6285
  function superRefine(fn, params) {
6350
6286
  return _superRefine(fn, params)
6351
6287
  }
6352
- // node_modules/.bun/zod@4.6.2/node_modules/zod/v4/classic/iso.js
6288
+ // node_modules/.bun/zod@4.6.4/node_modules/zod/v4/classic/iso.js
6353
6289
  var exports_iso = {}
6354
6290
  __export(exports_iso, {
6355
6291
  ZodISODate: () => ZodISODate,
@@ -6400,7 +6336,6 @@ var REVIEW_ARTIFACT_CUSTOM_MESSAGES = [
6400
6336
  'provenance.agreement_credit must not contain duplicate reviewers',
6401
6337
  'provenance.agreement_credit must not overlap provenance.submitters',
6402
6338
  'provenance.agreement_credit requires an eligible returned persona with admitted evidence',
6403
- 'satisfied risk coverage must cite a validated finding on the lost persona selection surface',
6404
6339
  'satisfied risk coverage must cite an admitted ledger row owned by another persona',
6405
6340
  ]
6406
6341
  var boundedText = (maxLength) => string2().min(1).max(maxLength).regex(/\S/)
@@ -6840,24 +6775,6 @@ var ReviewArtifactSchema = object({
6840
6775
  return
6841
6776
  }
6842
6777
  if (owner === coverage.persona) {
6843
- ctx.addIssue({
6844
- code: 'custom',
6845
- path: ['risk_coverage', coverageIndex, 'input_finding_id'],
6846
- message: REVIEW_ARTIFACT_CUSTOM_MESSAGES[19],
6847
- })
6848
- return
6849
- }
6850
- const lostDispatch = artifact.dispatches.find(
6851
- (dispatch) => dispatch.persona === coverage.persona,
6852
- )
6853
- const surface = lostDispatch?.selection_surface ?? []
6854
- const covered = artifact.findings.some(
6855
- (finding) =>
6856
- finding.input_finding_ids.includes(citedId) &&
6857
- finding.validated !== false &&
6858
- surface.includes(finding.file),
6859
- )
6860
- if (!covered) {
6861
6778
  ctx.addIssue({
6862
6779
  code: 'custom',
6863
6780
  path: ['risk_coverage', coverageIndex, 'input_finding_id'],
@@ -7018,6 +6935,351 @@ function runClaudeCodeValidator(options) {
7018
6935
  if (false) {
7019
6936
  }
7020
6937
 
6938
+ // src/lib/review-pipeline.ts
6939
+ import path2 from 'node:path'
6940
+
6941
+ // src/lib/review-pipeline-contract.ts
6942
+ var boundedText2 = (maxLength) => string2().min(1).max(maxLength).regex(/\S/)
6943
+ var PipelineInputIdSchema = boundedText2(MAX_INPUT_ID_LENGTH)
6944
+ var PipelineReasonSchema = boundedText2(MAX_REASON_LENGTH)
6945
+ var RejectedSummaryDispatchOutcomeSchema2 = DispatchOutcomeSchema.exclude([
6946
+ 'validation_unavailable',
6947
+ ])
6948
+ var AdmittedScreenDispositionSchema = DispositionSchema.exclude(['rejected'])
6949
+ var ScreenInputSchema = object({
6950
+ raw_return: SubAgentReturnSchema,
6951
+ expected_reviewer: SubAgentReturnSchema.shape.reviewer,
6952
+ invoking_harness: HarnessSchema,
6953
+ }).strict()
6954
+ var AdmittedScreenFindingSchema = ParentFindingSchema.extend({
6955
+ input_id: PipelineInputIdSchema,
6956
+ disposition: AdmittedScreenDispositionSchema,
6957
+ }).strict()
6958
+ var ScreenRejectedSummarySchema = object({
6959
+ dispatch_outcome: RejectedSummaryDispatchOutcomeSchema2,
6960
+ rejected_finding_count: number2().int().positive().max(MAX_FINDINGS),
6961
+ rejected_severities: array(SeveritySchema).max(MAX_FINDINGS),
6962
+ reason: PipelineReasonSchema,
6963
+ })
6964
+ .strict()
6965
+ .superRefine((summary, ctx) => {
6966
+ if (summary.rejected_severities.length !== summary.rejected_finding_count) {
6967
+ ctx.addIssue({
6968
+ code: 'custom',
6969
+ path: ['rejected_severities'],
6970
+ message: 'severity count must match rejected finding count',
6971
+ })
6972
+ }
6973
+ })
6974
+ var ScreenOutputSchema = object({
6975
+ dispatch_outcome: DispatchOutcomeSchema,
6976
+ admitted_findings: array(AdmittedScreenFindingSchema).max(MAX_FINDINGS),
6977
+ rejected_summary: ScreenRejectedSummarySchema.optional(),
6978
+ residual_risks: SubAgentReturnSchema.shape.residual_risks,
6979
+ testing_gaps: SubAgentReturnSchema.shape.testing_gaps,
6980
+ harness: HarnessSchema,
6981
+ }).strict()
6982
+ var ScreenResultSchema = object({
6983
+ reviewer: SubAgentReturnSchema.shape.reviewer,
6984
+ result: ScreenOutputSchema,
6985
+ }).strict()
6986
+ var SelectedDispatchSchema = object({
6987
+ persona: SubAgentReturnSchema.shape.reviewer,
6988
+ dispatch_outcome: DispatchOutcomeSchema,
6989
+ selection_surface: array(RepoRelativePathSchema).max(MAX_FINDINGS).optional(),
6990
+ selection_reason: PipelineReasonSchema.optional(),
6991
+ }).strict()
6992
+ var PrepareInputSchema = object({
6993
+ screen_results: array(ScreenResultSchema).max(MAX_PERSONAS),
6994
+ selected_dispatches: array(SelectedDispatchSchema).max(MAX_PERSONAS),
6995
+ }).strict()
6996
+ var ConfidenceDispositionSchema = object({
6997
+ input_id: PipelineInputIdSchema,
6998
+ disposition: DispositionSchema.extract(['surviving', 'suppressed']),
6999
+ confidence: ParentFindingSchema.shape.confidence,
7000
+ reason: PipelineReasonSchema.optional(),
7001
+ }).strict()
7002
+ var CandidateGroupMemberSchema = object({
7003
+ input_id: PipelineInputIdSchema,
7004
+ line: ParentFindingSchema.shape.line,
7005
+ }).strict()
7006
+ var CandidateGroupSchema = object({
7007
+ file: RepoRelativePathSchema,
7008
+ members: array(CandidateGroupMemberSchema).min(2).max(MAX_FINDINGS),
7009
+ }).strict()
7010
+ var SurvivingAdmittedFindingSchema = ParentFindingSchema.extend({
7011
+ input_id: PipelineInputIdSchema,
7012
+ reviewer: SubAgentReturnSchema.shape.reviewer,
7013
+ }).strict()
7014
+ var PrepareOutputSchema = object({
7015
+ confidence_dispositions: array(ConfidenceDispositionSchema).max(
7016
+ MAX_FINDINGS * MAX_PERSONAS,
7017
+ ),
7018
+ coverage_union: array(RepoRelativePathSchema).max(
7019
+ MAX_FINDINGS * MAX_PERSONAS,
7020
+ ),
7021
+ singletons: array(PipelineInputIdSchema).max(MAX_FINDINGS * MAX_PERSONAS),
7022
+ candidate_groups: array(CandidateGroupSchema).max(MAX_FINDINGS),
7023
+ surviving_findings: array(SurvivingAdmittedFindingSchema).max(
7024
+ MAX_FINDINGS * MAX_PERSONAS,
7025
+ ),
7026
+ }).strict()
7027
+ var PER_FINDING_BYTE_ASSUMPTION = 8192
7028
+ var AGGREGATE_BYTE_CAP_HEADROOM = 65536
7029
+ var AGGREGATE_STDIN_BYTE_CAP =
7030
+ MAX_PERSONAS * MAX_FINDINGS * PER_FINDING_BYTE_ASSUMPTION +
7031
+ AGGREGATE_BYTE_CAP_HEADROOM
7032
+ var AutofixClassRouteSchema = ParentFindingSchema.shape.autofix_class
7033
+ var OwnerRouteSchema = ParentFindingSchema.shape.owner
7034
+ var AUTOFIX_CLASS_NARROWS_TO = {
7035
+ safe_auto: ['safe_auto', 'gated_auto', 'manual', 'advisory'],
7036
+ gated_auto: ['gated_auto', 'manual', 'advisory'],
7037
+ manual: ['manual', 'advisory'],
7038
+ advisory: ['advisory'],
7039
+ }
7040
+ var OWNER_NARROWS_TO = {
7041
+ 'review-fixer': ['review-fixer', 'downstream-resolver', 'human', 'release'],
7042
+ 'downstream-resolver': ['downstream-resolver', 'release'],
7043
+ human: ['human', 'release'],
7044
+ release: ['release'],
7045
+ }
7046
+ var REQUIRES_VERIFICATION_NARROWS_TO = {
7047
+ false: ['false', 'true'],
7048
+ true: ['true'],
7049
+ }
7050
+ var ROUTE_REFUSAL_TABLE = {
7051
+ autofix_class: AUTOFIX_CLASS_NARROWS_TO,
7052
+ owner: OWNER_NARROWS_TO,
7053
+ requires_verification: REQUIRES_VERIFICATION_NARROWS_TO,
7054
+ }
7055
+ var isRouteTransitionAllowed = (from, to) => {
7056
+ const autofixAllowed = ROUTE_REFUSAL_TABLE.autofix_class[
7057
+ from.autofix_class
7058
+ ].includes(to.autofix_class)
7059
+ const ownerAllowed = ROUTE_REFUSAL_TABLE.owner[from.owner].includes(to.owner)
7060
+ const fromVerification = from.requires_verification ? 'true' : 'false'
7061
+ const toVerification = to.requires_verification ? 'true' : 'false'
7062
+ const verificationAllowed =
7063
+ ROUTE_REFUSAL_TABLE.requires_verification[fromVerification].includes(
7064
+ toVerification,
7065
+ )
7066
+ return autofixAllowed && ownerAllowed && verificationAllowed
7067
+ }
7068
+ var AgreementCreditSchema = SubAgentReturnSchema.shape.reviewer
7069
+ var DisagreementFactsSchema = array(PipelineReasonSchema).max(MAX_FINDINGS)
7070
+ var ProposedRouteSchema = object({
7071
+ autofix_class: AutofixClassRouteSchema,
7072
+ owner: OwnerRouteSchema,
7073
+ requires_verification: ParentFindingSchema.shape.requires_verification,
7074
+ }).strict()
7075
+ var MergedDecisionSchema = object({
7076
+ decision_id: PipelineInputIdSchema,
7077
+ disposition: literal('merged'),
7078
+ input_finding_ids: array(PipelineInputIdSchema).min(2).max(MAX_FINDINGS),
7079
+ title: ParentFindingSchema.shape.title,
7080
+ why_it_matters: ParentFindingSchema.shape.why_it_matters,
7081
+ evidence: ParentFindingSchema.shape.evidence,
7082
+ suggested_fix: ParentFindingSchema.shape.suggested_fix,
7083
+ line: ParentFindingSchema.shape.line,
7084
+ disagreement_facts: DisagreementFactsSchema.optional(),
7085
+ eligible_agreement_credit: array(AgreementCreditSchema)
7086
+ .max(MAX_PERSONAS)
7087
+ .optional(),
7088
+ proposed_route: ProposedRouteSchema.optional(),
7089
+ route_narrowing_reason: PipelineReasonSchema.optional(),
7090
+ }).strict()
7091
+ var DeclinedDecisionSchema = object({
7092
+ decision_id: PipelineInputIdSchema,
7093
+ disposition: literal('declined'),
7094
+ input_finding_id: PipelineInputIdSchema,
7095
+ declined_reason: PipelineReasonSchema,
7096
+ disagreement_facts: DisagreementFactsSchema.optional(),
7097
+ proposed_route: ProposedRouteSchema.optional(),
7098
+ route_narrowing_reason: PipelineReasonSchema.optional(),
7099
+ }).strict()
7100
+ var MergeDecisionSchema = discriminatedUnion('disposition', [
7101
+ MergedDecisionSchema,
7102
+ DeclinedDecisionSchema,
7103
+ ])
7104
+ var AdjudicationEnvelopeSchema = object({
7105
+ decisions: array(MergeDecisionSchema).max(MAX_FINDINGS),
7106
+ })
7107
+ .strict()
7108
+ .superRefine((envelope, ctx) => {
7109
+ const seenDecisionIds = new Set()
7110
+ const seenInputIds = new Set()
7111
+ envelope.decisions.forEach((decision, decisionIndex) => {
7112
+ if (seenDecisionIds.has(decision.decision_id)) {
7113
+ ctx.addIssue({
7114
+ code: 'custom',
7115
+ path: ['decisions', decisionIndex, 'decision_id'],
7116
+ message: 'duplicate decision ID',
7117
+ })
7118
+ }
7119
+ seenDecisionIds.add(decision.decision_id)
7120
+ if (decision.proposed_route && !decision.route_narrowing_reason) {
7121
+ ctx.addIssue({
7122
+ code: 'custom',
7123
+ path: ['decisions', decisionIndex, 'route_narrowing_reason'],
7124
+ message:
7125
+ 'route_narrowing_reason is required when proposed_route is present',
7126
+ })
7127
+ }
7128
+ if (decision.disposition === 'merged') {
7129
+ decision.input_finding_ids.forEach((inputId, inputIndex) => {
7130
+ if (seenInputIds.has(inputId)) {
7131
+ ctx.addIssue({
7132
+ code: 'custom',
7133
+ path: [
7134
+ 'decisions',
7135
+ decisionIndex,
7136
+ 'input_finding_ids',
7137
+ inputIndex,
7138
+ ],
7139
+ message: 'input finding ID already claimed by another decision',
7140
+ })
7141
+ }
7142
+ seenInputIds.add(inputId)
7143
+ })
7144
+ return
7145
+ }
7146
+ if (seenInputIds.has(decision.input_finding_id)) {
7147
+ ctx.addIssue({
7148
+ code: 'custom',
7149
+ path: ['decisions', decisionIndex, 'input_finding_id'],
7150
+ message: 'input finding ID already claimed by another decision',
7151
+ })
7152
+ }
7153
+ seenInputIds.add(decision.input_finding_id)
7154
+ })
7155
+ })
7156
+ var MergeInputSchema = object({
7157
+ prepared: PrepareOutputSchema,
7158
+ adjudication: AdjudicationEnvelopeSchema,
7159
+ }).strict()
7160
+ var ValidatorRequestSchema = object({
7161
+ finding_id: PipelineInputIdSchema,
7162
+ file: RepoRelativePathSchema,
7163
+ line: ParentFindingSchema.shape.line,
7164
+ }).strict()
7165
+ var MergedFindingSchema = object({
7166
+ finding_id: PipelineInputIdSchema,
7167
+ file: RepoRelativePathSchema,
7168
+ title: ParentFindingSchema.shape.title,
7169
+ why_it_matters: ParentFindingSchema.shape.why_it_matters,
7170
+ line: ParentFindingSchema.shape.line,
7171
+ autofix_class: ParentFindingSchema.shape.autofix_class,
7172
+ owner: ParentFindingSchema.shape.owner,
7173
+ requires_verification: ParentFindingSchema.shape.requires_verification,
7174
+ evidence: ParentFindingSchema.shape.evidence,
7175
+ suggested_fix: ParentFindingSchema.shape.suggested_fix,
7176
+ input_finding_ids: array(PipelineInputIdSchema).min(1).max(MAX_FINDINGS),
7177
+ agreement_credit: array(AgreementCreditSchema).max(MAX_PERSONAS).optional(),
7178
+ severity: ParentFindingSchema.shape.severity,
7179
+ confidence: ParentFindingSchema.shape.confidence,
7180
+ pre_existing: ParentFindingSchema.shape.pre_existing,
7181
+ fingerprint: ProvenanceSchema.shape.fingerprint,
7182
+ submitters: ProvenanceSchema.shape.submitters,
7183
+ }).strict()
7184
+ var MergeOutputSchema = object({
7185
+ merged_findings: array(MergedFindingSchema).max(MAX_FINDINGS),
7186
+ validator_requests: array(ValidatorRequestSchema).max(MAX_FINDINGS),
7187
+ disagreement_facts: DisagreementFactsSchema,
7188
+ }).strict()
7189
+ var ValidatorLifecycleResultSchema = discriminatedUnion('outcome', [
7190
+ object({ outcome: literal('true') }).strict(),
7191
+ object({ outcome: literal('false'), reason: PipelineReasonSchema }).strict(),
7192
+ object({ outcome: literal('failed'), reason: PipelineReasonSchema }).strict(),
7193
+ object({
7194
+ outcome: literal('unavailable'),
7195
+ reason: PipelineReasonSchema,
7196
+ }).strict(),
7197
+ ])
7198
+ var ValidatorLifecycleRecordSchema = object({
7199
+ finding_id: PipelineInputIdSchema,
7200
+ result: ValidatorLifecycleResultSchema,
7201
+ }).strict()
7202
+ var ValidatorLifecycleResultsSchema = array(ValidatorLifecycleRecordSchema).max(
7203
+ MAX_FINDINGS,
7204
+ )
7205
+ var PlanAssessmentResultSchema = object({
7206
+ kind: _enum(['explicit_unmet_requirement', 'inferred_gap']),
7207
+ description: PipelineReasonSchema,
7208
+ }).strict()
7209
+ var PlanAssessmentEnvelopeSchema = object({
7210
+ verdict: ReviewArtifactSchema.shape.verdict,
7211
+ results: array(PlanAssessmentResultSchema).max(MAX_FINDINGS),
7212
+ }).strict()
7213
+ var ParentRunModeSchema = _enum([
7214
+ ...ReviewArtifactSchema.shape.mode.options,
7215
+ 'report-only',
7216
+ ])
7217
+ var ParentRunMetadataSchema = object({
7218
+ run_id: ReviewArtifactSchema.shape.run_id,
7219
+ mode: ParentRunModeSchema,
7220
+ harness: ReviewArtifactSchema.shape.harness,
7221
+ branch: ReviewArtifactSchema.shape.branch,
7222
+ head_sha: ReviewArtifactSchema.shape.head_sha,
7223
+ selected_dispatches: array(SelectedDispatchSchema).max(MAX_PERSONAS),
7224
+ timestamps: object({
7225
+ started_at: ReviewArtifactSchema.shape.completed_at,
7226
+ completed_at: ReviewArtifactSchema.shape.completed_at,
7227
+ }).strict(),
7228
+ validation: ReviewArtifactSchema.shape.validation.unwrap(),
7229
+ applied_fixes: ReviewArtifactSchema.shape.applied_fixes,
7230
+ }).strict()
7231
+ var FinalizeInputSchema = object({
7232
+ merge: MergeOutputSchema,
7233
+ prepared: PrepareOutputSchema,
7234
+ screen_results: PrepareInputSchema.shape.screen_results,
7235
+ dispatch_records: array(SelectedDispatchSchema).max(MAX_PERSONAS),
7236
+ validator_lifecycle_results: ValidatorLifecycleResultsSchema,
7237
+ plan_assessment: PlanAssessmentEnvelopeSchema,
7238
+ parent_run_metadata: ParentRunMetadataSchema,
7239
+ }).strict()
7240
+ var FinalizedInputDispositionSchema = object({
7241
+ input_id: PipelineInputIdSchema,
7242
+ disposition: DispositionSchema.extract([
7243
+ 'suppressed',
7244
+ 'filtered',
7245
+ 'merged',
7246
+ 'surviving',
7247
+ ]),
7248
+ reason: PipelineReasonSchema.optional(),
7249
+ }).strict()
7250
+ var ReportQueueEntrySchema = object({
7251
+ finding_id: PipelineInputIdSchema,
7252
+ unconfirmed: boolean2(),
7253
+ }).strict()
7254
+ var ReportQueuesSchema = object({
7255
+ fixer: array(ReportQueueEntrySchema).max(MAX_FINDINGS),
7256
+ residual: array(ReportQueueEntrySchema).max(MAX_FINDINGS),
7257
+ report_only: array(ReportQueueEntrySchema).max(MAX_FINDINGS),
7258
+ }).strict()
7259
+ var ReportProjectionSchema = object({
7260
+ verdict: ReviewArtifactSchema.shape.verdict,
7261
+ findings: ReviewArtifactSchema.shape.findings,
7262
+ applied_fixes: ReviewArtifactSchema.shape.applied_fixes,
7263
+ residual_actionable_work: ReviewArtifactSchema.shape.residual_actionable_work,
7264
+ advisory_outputs: ReviewArtifactSchema.shape.advisory_outputs,
7265
+ coverage: ReviewArtifactSchema.shape.coverage,
7266
+ input_dispositions: array(FinalizedInputDispositionSchema).max(
7267
+ MAX_FINDINGS * MAX_PERSONAS,
7268
+ ),
7269
+ disposition_counts: ReviewArtifactSchema.shape.disposition_counts,
7270
+ queues: ReportQueuesSchema,
7271
+ pre_existing_findings: array(ReportQueueEntrySchema).max(MAX_FINDINGS),
7272
+ risk_coverage: ReviewArtifactSchema.shape.risk_coverage,
7273
+ }).strict()
7274
+ var FinalizeOutputSchema = discriminatedUnion('kind', [
7275
+ object({
7276
+ kind: literal('writing'),
7277
+ artifact: ReviewArtifactSchema,
7278
+ report: ReportProjectionSchema,
7279
+ }).strict(),
7280
+ ReportProjectionSchema.extend({ kind: literal('report_only') }).strict(),
7281
+ ])
7282
+
7021
7283
  // src/lib/review-return-validator.ts
7022
7284
  import fs2 from 'node:fs'
7023
7285
  var VALIDATE_REVIEW_RETURN_USAGE = 'Usage: systematic validate-review-return'
@@ -7074,11 +7336,11 @@ function readChunkWithRetry(fd, buffer, toRead, readChunk) {
7074
7336
  }
7075
7337
  }
7076
7338
  }
7077
- function readBoundedStdin(fd, readChunk) {
7339
+ function readBoundedStdin(fd, readChunk, maxBytes = MAX_REVIEW_RETURN_BYTES) {
7078
7340
  const chunks = []
7079
7341
  let total = 0
7080
7342
  while (true) {
7081
- const remaining = MAX_REVIEW_RETURN_BYTES + 1 - total
7343
+ const remaining = maxBytes + 1 - total
7082
7344
  if (remaining <= 0) return { status: 'oversized' }
7083
7345
  const toRead = Math.min(READ_CHUNK_BYTES, remaining)
7084
7346
  const buffer = Buffer.allocUnsafe(toRead)
@@ -7087,7 +7349,7 @@ function readBoundedStdin(fd, readChunk) {
7087
7349
  if (read.bytesRead <= 0) break
7088
7350
  total += read.bytesRead
7089
7351
  chunks.push(buffer.subarray(0, read.bytesRead))
7090
- if (total > MAX_REVIEW_RETURN_BYTES) return { status: 'oversized' }
7352
+ if (total > maxBytes) return { status: 'oversized' }
7091
7353
  }
7092
7354
  return { buffer: Buffer.concat(chunks, total), status: 'ok' }
7093
7355
  }
@@ -7150,48 +7412,2940 @@ function runReviewReturnValidator(options) {
7150
7412
  return 1
7151
7413
  }
7152
7414
 
7153
- // src/ce-review-validator.ts
7154
- var CE_REVIEW_VALIDATOR_USAGE =
7155
- 'Usage: node validate-review.mjs <return|artifact> [...]'
7156
- function runCeReviewValidator(options) {
7157
- const outputSink = options.outputSink ?? ((message) => console.log(message))
7158
- const errorSink = options.errorSink ?? ((message) => console.error(message))
7159
- const subcommand = options.argv[0]
7160
- if (subcommand === 'return') {
7161
- return runReviewReturnValidator({
7162
- argv: ['systematic', 'validate-review-return', ...options.argv.slice(1)],
7163
- isTTY: options.isTTY,
7164
- readChunk: options.readChunk,
7165
- outputSink,
7166
- errorSink,
7167
- })
7415
+ // src/lib/review-pipeline.ts
7416
+ function normalizeRepoRelativePath(filePath) {
7417
+ return path2.posix.normalize(filePath.replaceAll('\\', '/'))
7418
+ }
7419
+ var JSON_ROOT_PATH = '$'
7420
+ var RECOGNIZED_SEVERITIES = ['P0', 'P1', 'P2', 'P3']
7421
+ function classifyRejectedSeverity(value) {
7422
+ return typeof value === 'string' && RECOGNIZED_SEVERITIES.includes(value)
7423
+ ? value
7424
+ : 'unknown'
7425
+ }
7426
+ function extractRejectedSeverities(rawValue) {
7427
+ if (typeof rawValue !== 'object' || rawValue === null) return
7428
+ const findings = rawValue.findings
7429
+ if (!Array.isArray(findings)) return
7430
+ if (findings.length > MAX_FINDINGS) return
7431
+ return findings.map((finding) =>
7432
+ typeof finding === 'object' && finding !== null
7433
+ ? classifyRejectedSeverity(finding.severity)
7434
+ : 'unknown',
7435
+ )
7436
+ }
7437
+ function formatDiagnostic(persona, fieldPath, reason) {
7438
+ const jsonPath =
7439
+ typeof fieldPath === 'string'
7440
+ ? fieldPath
7441
+ : formatReviewArtifactIssuePath(fieldPath)
7442
+ return `Rejected persona ${persona} return: field ${jsonPath} failed ${reason}.`
7443
+ }
7444
+ function truncateReason(reason) {
7445
+ if (reason.length <= MAX_REASON_LENGTH) return reason
7446
+ return reason.slice(0, MAX_REASON_LENGTH)
7447
+ }
7448
+ function parseRawReturn(rawReturn) {
7449
+ if (typeof rawReturn !== 'string') return { ok: true, value: rawReturn }
7450
+ try {
7451
+ return { ok: true, value: JSON.parse(rawReturn) }
7452
+ } catch {
7453
+ return { ok: false }
7454
+ }
7455
+ }
7456
+ function wholePayloadRejection(
7457
+ persona,
7458
+ fieldPath,
7459
+ reason,
7460
+ rejectedSeverities,
7461
+ harness,
7462
+ ) {
7463
+ const rejectedFindingCount = rejectedSeverities?.length ?? 0
7464
+ return ScreenOutputSchema.parse({
7465
+ admitted_findings: [],
7466
+ dispatch_outcome: 'malformed',
7467
+ ...(rejectedFindingCount > 0
7468
+ ? {
7469
+ rejected_summary: {
7470
+ dispatch_outcome: 'malformed',
7471
+ reason: truncateReason(
7472
+ formatDiagnostic(persona, fieldPath, reason),
7473
+ ),
7474
+ rejected_finding_count: rejectedFindingCount,
7475
+ rejected_severities: rejectedSeverities,
7476
+ },
7477
+ }
7478
+ : {}),
7479
+ residual_risks: [],
7480
+ testing_gaps: [],
7481
+ harness,
7482
+ })
7483
+ }
7484
+ function screenReviewReturn(input) {
7485
+ const persona = input.expected_reviewer
7486
+ const harness = input.invoking_harness
7487
+ const parsed = parseRawReturn(input.raw_return)
7488
+ if (!parsed.ok) {
7489
+ return wholePayloadRejection(
7490
+ persona,
7491
+ JSON_ROOT_PATH,
7492
+ 'malformed JSON',
7493
+ undefined,
7494
+ harness,
7495
+ )
7168
7496
  }
7169
- if (subcommand === 'artifact') {
7170
- return runClaudeCodeValidator({
7171
- argv: options.argv.slice(1),
7172
- cwd: options.cwd,
7173
- outputSink,
7174
- errorSink,
7175
- })
7497
+ const validation = validateReviewReturnValue(parsed.value)
7498
+ if (!validation.ok) {
7499
+ const fieldPath = validation.issues[0]?.path ?? JSON_ROOT_PATH
7500
+ return wholePayloadRejection(
7501
+ persona,
7502
+ fieldPath,
7503
+ 'schema validation',
7504
+ extractRejectedSeverities(parsed.value),
7505
+ harness,
7506
+ )
7507
+ }
7508
+ const raw = SubAgentReturnSchema.parse(parsed.value)
7509
+ if (raw.reviewer !== persona) {
7510
+ return wholePayloadRejection(
7511
+ persona,
7512
+ 'reviewer',
7513
+ 'schema validation',
7514
+ raw.findings.map((finding) => finding.severity),
7515
+ harness,
7516
+ )
7176
7517
  }
7177
- errorSink(CE_REVIEW_VALIDATOR_USAGE)
7178
- return 2
7518
+ const admittedFindings = raw.findings.map((finding, originalIndex) => ({
7519
+ ...finding,
7520
+ disposition: 'surviving',
7521
+ input_id: `${persona}#${originalIndex}`,
7522
+ }))
7523
+ const dispatchOutcome = raw.findings.length === 0 ? 'empty' : 'findings'
7524
+ return ScreenOutputSchema.parse({
7525
+ admitted_findings: admittedFindings,
7526
+ dispatch_outcome: dispatchOutcome,
7527
+ residual_risks: raw.residual_risks,
7528
+ testing_gaps: raw.testing_gaps,
7529
+ harness,
7530
+ })
7179
7531
  }
7180
- function resolveRealPath(candidate) {
7181
- if (candidate === undefined) return
7532
+ var STANDARD_CONFIDENCE_FLOOR = 0.6
7533
+ var P0_CONFIDENCE_FLOOR = 0.5
7534
+ var CONFIDENCE_GATE_SUPPRESSED_REASON = 'confidence below gate threshold'
7535
+ function rejectPrepare(path, reason) {
7536
+ return { ok: false, rejection: { path, reason } }
7537
+ }
7538
+ function compareStrings(a, b) {
7539
+ if (a < b) return -1
7540
+ if (a > b) return 1
7541
+ return 0
7542
+ }
7543
+ function payloadByteLength(rawInput) {
7544
+ if (typeof rawInput === 'string') return Buffer.byteLength(rawInput, 'utf8')
7182
7545
  try {
7183
- return fs3.realpathSync(candidate)
7546
+ return Buffer.byteLength(JSON.stringify(rawInput), 'utf8')
7184
7547
  } catch {
7185
7548
  return
7186
7549
  }
7187
7550
  }
7188
- var entryPath = resolveRealPath(process.argv[1])
7189
- var modulePath = resolveRealPath(fileURLToPath(import.meta.url))
7190
- var isMainModule =
7191
- entryPath !== undefined &&
7192
- modulePath !== undefined &&
7193
- entryPath === modulePath
7194
- if (isMainModule) {
7195
- process.exitCode = runCeReviewValidator({ argv: process.argv.slice(2) })
7551
+ function survivesConfidenceGate(finding) {
7552
+ if (finding.confidence >= STANDARD_CONFIDENCE_FLOOR) return true
7553
+ return finding.severity === 'P0' && finding.confidence >= P0_CONFIDENCE_FLOOR
7554
+ }
7555
+ function validatePrepareStructure(screenResults, selectedDispatches) {
7556
+ const seenPersonas = new Set()
7557
+ for (const [index, entry] of screenResults.entries()) {
7558
+ if (seenPersonas.has(entry.reviewer)) {
7559
+ return {
7560
+ path: formatReviewArtifactIssuePath([
7561
+ 'screen_results',
7562
+ index,
7563
+ 'reviewer',
7564
+ ]),
7565
+ reason: 'duplicate persona outcome',
7566
+ }
7567
+ }
7568
+ seenPersonas.add(entry.reviewer)
7569
+ }
7570
+ const seenInputIds = new Set()
7571
+ for (const [screenIndex, entry] of screenResults.entries()) {
7572
+ for (const [
7573
+ findingIndex,
7574
+ finding,
7575
+ ] of entry.result.admitted_findings.entries()) {
7576
+ if (seenInputIds.has(finding.input_id)) {
7577
+ return {
7578
+ path: formatReviewArtifactIssuePath([
7579
+ 'screen_results',
7580
+ screenIndex,
7581
+ 'result',
7582
+ 'admitted_findings',
7583
+ findingIndex,
7584
+ 'input_id',
7585
+ ]),
7586
+ reason: 'duplicate input id',
7587
+ }
7588
+ }
7589
+ seenInputIds.add(finding.input_id)
7590
+ }
7591
+ }
7592
+ const selectedPersonas = new Set(
7593
+ selectedDispatches.map((dispatch) => dispatch.persona),
7594
+ )
7595
+ for (const [index, entry] of screenResults.entries()) {
7596
+ if (!selectedPersonas.has(entry.reviewer)) {
7597
+ return {
7598
+ path: formatReviewArtifactIssuePath([
7599
+ 'screen_results',
7600
+ index,
7601
+ 'reviewer',
7602
+ ]),
7603
+ reason: 'unselected persona screen result',
7604
+ }
7605
+ }
7606
+ }
7607
+ const screenedPersonas = new Set(screenResults.map((entry) => entry.reviewer))
7608
+ for (const [index, dispatch] of selectedDispatches.entries()) {
7609
+ if (!screenedPersonas.has(dispatch.persona)) {
7610
+ return {
7611
+ path: formatReviewArtifactIssuePath([
7612
+ 'selected_dispatches',
7613
+ index,
7614
+ 'persona',
7615
+ ]),
7616
+ reason: 'missing screen result for selected dispatch',
7617
+ }
7618
+ }
7619
+ }
7620
+ return
7621
+ }
7622
+ function applyConfidenceGate(screenResults) {
7623
+ const confidenceDispositions = []
7624
+ const survivors = []
7625
+ const survivingFindings = []
7626
+ for (const entry of screenResults) {
7627
+ for (const finding of entry.result.admitted_findings) {
7628
+ if (survivesConfidenceGate(finding)) {
7629
+ confidenceDispositions.push({
7630
+ input_id: finding.input_id,
7631
+ disposition: 'surviving',
7632
+ confidence: finding.confidence,
7633
+ })
7634
+ survivors.push({
7635
+ inputId: finding.input_id,
7636
+ persona: entry.reviewer,
7637
+ normalizedFile: normalizeRepoRelativePath(finding.file),
7638
+ line: finding.line,
7639
+ })
7640
+ survivingFindings.push({
7641
+ ...finding,
7642
+ reviewer: entry.reviewer,
7643
+ })
7644
+ } else {
7645
+ confidenceDispositions.push({
7646
+ input_id: finding.input_id,
7647
+ disposition: 'suppressed',
7648
+ confidence: finding.confidence,
7649
+ reason: CONFIDENCE_GATE_SUPPRESSED_REASON,
7650
+ })
7651
+ }
7652
+ }
7653
+ }
7654
+ confidenceDispositions.sort((a, b) => compareStrings(a.input_id, b.input_id))
7655
+ survivingFindings.sort((a, b) => compareStrings(a.input_id, b.input_id))
7656
+ return { confidenceDispositions, survivors, survivingFindings }
7657
+ }
7658
+ function computeCoverageUnion(selectedDispatches) {
7659
+ const coverageSet = new Set()
7660
+ for (const dispatch of selectedDispatches) {
7661
+ for (const surface of dispatch.selection_surface ?? []) {
7662
+ coverageSet.add(surface)
7663
+ }
7664
+ }
7665
+ return [...coverageSet].sort(compareStrings)
7666
+ }
7667
+ function groupCandidates(survivors) {
7668
+ const groupsByFile = new Map()
7669
+ for (const survivor of survivors) {
7670
+ const bucket = groupsByFile.get(survivor.normalizedFile)
7671
+ if (bucket) {
7672
+ bucket.push(survivor)
7673
+ } else {
7674
+ groupsByFile.set(survivor.normalizedFile, [survivor])
7675
+ }
7676
+ }
7677
+ const candidateGroups = []
7678
+ const singletonIds = []
7679
+ for (const [file, members] of groupsByFile) {
7680
+ const distinctPersonas = new Set(members.map((member) => member.persona))
7681
+ if (distinctPersonas.size >= 2) {
7682
+ const sortedMembers = [...members].sort((a, b) => {
7683
+ if (a.line !== b.line) return a.line - b.line
7684
+ return compareStrings(a.inputId, b.inputId)
7685
+ })
7686
+ candidateGroups.push({
7687
+ file,
7688
+ members: sortedMembers.map((member) => ({
7689
+ input_id: member.inputId,
7690
+ line: member.line,
7691
+ })),
7692
+ })
7693
+ } else {
7694
+ for (const member of members) {
7695
+ singletonIds.push(member.inputId)
7696
+ }
7697
+ }
7698
+ }
7699
+ candidateGroups.sort((a, b) => compareStrings(a.file, b.file))
7700
+ singletonIds.sort(compareStrings)
7701
+ return { candidateGroups, singletonIds }
7702
+ }
7703
+ function prepareReviewCandidates(input) {
7704
+ const byteLength = payloadByteLength(input.raw_input)
7705
+ if (byteLength !== undefined && byteLength > AGGREGATE_STDIN_BYTE_CAP) {
7706
+ return rejectPrepare(JSON_ROOT_PATH, 'aggregate payload exceeds byte cap')
7707
+ }
7708
+ const parsed = parseRawReturn(input.raw_input)
7709
+ if (!parsed.ok) {
7710
+ return rejectPrepare(JSON_ROOT_PATH, 'malformed JSON')
7711
+ }
7712
+ const validation = PrepareInputSchema.safeParse(parsed.value)
7713
+ if (!validation.success) {
7714
+ const issue = validation.error.issues[0]
7715
+ const issuePath = issue
7716
+ ? formatReviewArtifactIssuePath(issue.path)
7717
+ : JSON_ROOT_PATH
7718
+ return rejectPrepare(issuePath, 'schema validation')
7719
+ }
7720
+ const {
7721
+ screen_results: screenResults,
7722
+ selected_dispatches: selectedDispatches,
7723
+ } = validation.data
7724
+ const structuralViolation = validatePrepareStructure(
7725
+ screenResults,
7726
+ selectedDispatches,
7727
+ )
7728
+ if (structuralViolation) {
7729
+ return rejectPrepare(structuralViolation.path, structuralViolation.reason)
7730
+ }
7731
+ const { confidenceDispositions, survivors, survivingFindings } =
7732
+ applyConfidenceGate(screenResults)
7733
+ const coverageUnion = computeCoverageUnion(selectedDispatches)
7734
+ const { candidateGroups, singletonIds } = groupCandidates(survivors)
7735
+ const output = PrepareOutputSchema.parse({
7736
+ candidate_groups: candidateGroups,
7737
+ confidence_dispositions: confidenceDispositions,
7738
+ coverage_union: coverageUnion,
7739
+ singletons: singletonIds,
7740
+ surviving_findings: survivingFindings,
7741
+ })
7742
+ return { ok: true, value: output }
7743
+ }
7744
+ function rejectAdjudication(path, reason) {
7745
+ return { ok: false, rejection: { path, reason } }
7746
+ }
7747
+ function citedInputIds(decision) {
7748
+ return decision.disposition === 'merged'
7749
+ ? decision.input_finding_ids
7750
+ : [decision.input_finding_id]
7751
+ }
7752
+ function citationPath(decision, decisionIndex, citedIndex) {
7753
+ return decision.disposition === 'merged'
7754
+ ? formatReviewArtifactIssuePath([
7755
+ 'decisions',
7756
+ decisionIndex,
7757
+ 'input_finding_ids',
7758
+ citedIndex,
7759
+ ])
7760
+ : formatReviewArtifactIssuePath([
7761
+ 'decisions',
7762
+ decisionIndex,
7763
+ 'input_finding_id',
7764
+ ])
7765
+ }
7766
+ function buildCandidateIndex(candidateGroups) {
7767
+ const groupIndexByInputId = new Map()
7768
+ candidateGroups.forEach((group, groupIndex) => {
7769
+ for (const member of group.members) {
7770
+ groupIndexByInputId.set(member.input_id, groupIndex)
7771
+ }
7772
+ })
7773
+ return { groupIndexByInputId }
7774
+ }
7775
+ function buildSuppressedSet(confidenceDispositions) {
7776
+ const suppressed = new Set()
7777
+ for (const disposition of confidenceDispositions) {
7778
+ if (disposition.disposition === 'suppressed') {
7779
+ suppressed.add(disposition.input_id)
7780
+ }
7781
+ }
7782
+ return suppressed
7783
+ }
7784
+ function validateCitations(decisions, index, suppressed) {
7785
+ const seen = new Set()
7786
+ for (const [decisionIndex, decision] of decisions.entries()) {
7787
+ for (const [citedIndex, inputId] of citedInputIds(decision).entries()) {
7788
+ const path = citationPath(decision, decisionIndex, citedIndex)
7789
+ if (suppressed.has(inputId)) {
7790
+ return { path, reason: 'suppressed input id' }
7791
+ }
7792
+ if (!index.groupIndexByInputId.has(inputId)) {
7793
+ return { path, reason: 'unknown input id' }
7794
+ }
7795
+ if (seen.has(inputId)) {
7796
+ return { path, reason: 'duplicate input id citation' }
7797
+ }
7798
+ seen.add(inputId)
7799
+ }
7800
+ }
7801
+ return
7802
+ }
7803
+ function validateNoOmissions(candidateGroups, citedIds) {
7804
+ for (const [groupIndex, group] of candidateGroups.entries()) {
7805
+ for (const [memberIndex, member] of group.members.entries()) {
7806
+ if (!citedIds.has(member.input_id)) {
7807
+ return {
7808
+ path: formatReviewArtifactIssuePath([
7809
+ 'candidate_groups',
7810
+ groupIndex,
7811
+ 'members',
7812
+ memberIndex,
7813
+ 'input_id',
7814
+ ]),
7815
+ reason: 'omitted eligible input id',
7816
+ }
7817
+ }
7818
+ }
7819
+ }
7820
+ return
7821
+ }
7822
+ function collectCitedIds(decisions) {
7823
+ const cited = new Set()
7824
+ for (const decision of decisions) {
7825
+ for (const inputId of citedInputIds(decision)) cited.add(inputId)
7826
+ }
7827
+ return cited
7828
+ }
7829
+ function validateMergedDecisionConsistency(
7830
+ decision,
7831
+ decisionIndex,
7832
+ index,
7833
+ candidateGroups,
7834
+ ) {
7835
+ const ids = decision.input_finding_ids
7836
+ const firstId = ids[0]
7837
+ if (firstId === undefined) return
7838
+ const expectedGroupIndex = index.groupIndexByInputId.get(firstId)
7839
+ if (expectedGroupIndex === undefined) return
7840
+ for (const [citedIndex, inputId] of ids.entries()) {
7841
+ const groupIndex = index.groupIndexByInputId.get(inputId)
7842
+ if (groupIndex !== expectedGroupIndex) {
7843
+ return {
7844
+ path: formatReviewArtifactIssuePath([
7845
+ 'decisions',
7846
+ decisionIndex,
7847
+ 'input_finding_ids',
7848
+ citedIndex,
7849
+ ]),
7850
+ reason: 'cross-group input id citation',
7851
+ }
7852
+ }
7853
+ }
7854
+ const group = candidateGroups[expectedGroupIndex]
7855
+ if (group && !group.members.some((member) => member.line === decision.line)) {
7856
+ return {
7857
+ path: formatReviewArtifactIssuePath(['decisions', decisionIndex, 'line']),
7858
+ reason: 'representative line mismatch',
7859
+ }
7860
+ }
7861
+ return
7862
+ }
7863
+ function validateMergedDecisions(decisions, index, candidateGroups) {
7864
+ for (const [decisionIndex, decision] of decisions.entries()) {
7865
+ if (decision.disposition !== 'merged') continue
7866
+ const violation = validateMergedDecisionConsistency(
7867
+ decision,
7868
+ decisionIndex,
7869
+ index,
7870
+ candidateGroups,
7871
+ )
7872
+ if (violation) return violation
7873
+ }
7874
+ return
7875
+ }
7876
+ function resolveDecisionFile(decision, index, candidateGroups) {
7877
+ const firstId = citedInputIds(decision)[0]
7878
+ if (firstId === undefined) return
7879
+ const groupIndex = index.groupIndexByInputId.get(firstId)
7880
+ if (groupIndex === undefined) return
7881
+ return candidateGroups[groupIndex]?.file
7882
+ }
7883
+ function buildValidatedPartition(
7884
+ decisions,
7885
+ index,
7886
+ candidateGroups,
7887
+ singletons,
7888
+ ) {
7889
+ const merged = []
7890
+ const declined = []
7891
+ for (const decision of decisions) {
7892
+ const file = resolveDecisionFile(decision, index, candidateGroups) ?? ''
7893
+ if (decision.disposition === 'merged') {
7894
+ merged.push({ decision, file })
7895
+ } else {
7896
+ declined.push({ decision, file })
7897
+ }
7898
+ }
7899
+ merged.sort((a, b) =>
7900
+ compareStrings(a.decision.decision_id, b.decision.decision_id),
7901
+ )
7902
+ declined.sort((a, b) =>
7903
+ compareStrings(a.decision.decision_id, b.decision.decision_id),
7904
+ )
7905
+ return {
7906
+ merged,
7907
+ declined,
7908
+ singletons: [...singletons].sort(compareStrings),
7909
+ }
7910
+ }
7911
+ function validateAdjudication(prepared, decisions) {
7912
+ if (prepared.candidate_groups.length === 0) {
7913
+ if (decisions.length > 0) {
7914
+ return rejectAdjudication(
7915
+ formatReviewArtifactIssuePath(['decisions']),
7916
+ 'unexpected decisions for empty candidate set',
7917
+ )
7918
+ }
7919
+ return {
7920
+ ok: true,
7921
+ value: buildValidatedPartition(
7922
+ decisions,
7923
+ buildCandidateIndex([]),
7924
+ [],
7925
+ prepared.singletons,
7926
+ ),
7927
+ }
7928
+ }
7929
+ const index = buildCandidateIndex(prepared.candidate_groups)
7930
+ const suppressed = buildSuppressedSet(prepared.confidence_dispositions)
7931
+ const citationViolation = validateCitations(decisions, index, suppressed)
7932
+ if (citationViolation) {
7933
+ return { ok: false, rejection: citationViolation }
7934
+ }
7935
+ const citedIds = collectCitedIds(decisions)
7936
+ const omissionViolation = validateNoOmissions(
7937
+ prepared.candidate_groups,
7938
+ citedIds,
7939
+ )
7940
+ if (omissionViolation) {
7941
+ return { ok: false, rejection: omissionViolation }
7942
+ }
7943
+ const mergedViolation = validateMergedDecisions(
7944
+ decisions,
7945
+ index,
7946
+ prepared.candidate_groups,
7947
+ )
7948
+ if (mergedViolation) {
7949
+ return { ok: false, rejection: mergedViolation }
7950
+ }
7951
+ return {
7952
+ ok: true,
7953
+ value: buildValidatedPartition(
7954
+ decisions,
7955
+ index,
7956
+ prepared.candidate_groups,
7957
+ prepared.singletons,
7958
+ ),
7959
+ }
7960
+ }
7961
+ function rejectMergedFinding(path, reason) {
7962
+ return { ok: false, rejection: { path, reason } }
7963
+ }
7964
+ var SEVERITY_RANK = {
7965
+ P0: 0,
7966
+ P1: 1,
7967
+ P2: 2,
7968
+ P3: 3,
7969
+ }
7970
+ function deriveSeverity(contributing) {
7971
+ return contributing.reduce(
7972
+ (highest, finding) =>
7973
+ SEVERITY_RANK[finding.severity] < SEVERITY_RANK[highest]
7974
+ ? finding.severity
7975
+ : highest,
7976
+ contributing[0].severity,
7977
+ )
7978
+ }
7979
+ function deriveSubmitters(contributing) {
7980
+ return [...new Set(contributing.map((finding) => finding.reviewer))].sort(
7981
+ compareStrings,
7982
+ )
7983
+ }
7984
+ function deriveAgreementCredit(claimed, submitters, returnedReviewers) {
7985
+ if (!claimed || claimed.length === 0) return { ok: true, value: [] }
7986
+ const credited = new Set()
7987
+ for (const [index, reviewer] of claimed.entries()) {
7988
+ const path = formatReviewArtifactIssuePath([
7989
+ 'eligible_agreement_credit',
7990
+ index,
7991
+ ])
7992
+ if (credited.has(reviewer)) {
7993
+ return rejectMergedFinding(path, 'duplicate agreement credit reviewer')
7994
+ }
7995
+ if (submitters.has(reviewer)) {
7996
+ return rejectMergedFinding(
7997
+ path,
7998
+ 'agreement credit reviewer already a submitter',
7999
+ )
8000
+ }
8001
+ if (!returnedReviewers.has(reviewer)) {
8002
+ return rejectMergedFinding(
8003
+ path,
8004
+ 'agreement credit reviewer did not return',
8005
+ )
8006
+ }
8007
+ credited.add(reviewer)
8008
+ }
8009
+ return { ok: true, value: [...credited].sort(compareStrings) }
8010
+ }
8011
+ var CONFIDENCE_AGREEMENT_BOOST = 0.1
8012
+ var MAX_CONFIDENCE = 1
8013
+ function deriveConfidence(contributing, distinctReviewerCount) {
8014
+ const highest = contributing.reduce(
8015
+ (max, finding) => Math.max(max, finding.confidence),
8016
+ contributing[0].confidence,
8017
+ )
8018
+ if (distinctReviewerCount < 2) return highest
8019
+ const boosted = Math.round((highest + CONFIDENCE_AGREEMENT_BOOST) * 100) / 100
8020
+ return Math.min(MAX_CONFIDENCE, boosted)
8021
+ }
8022
+ function derivePreExisting(contributing) {
8023
+ return contributing.every((finding) => finding.pre_existing)
8024
+ }
8025
+ function deriveFingerprint(normalizedFile, representativeLine, severity) {
8026
+ return `${normalizedFile}:${representativeLine}:${severity}`
8027
+ }
8028
+ function meetOverNarrowsTo(narrowsTo, values) {
8029
+ const domain = Object.keys(narrowsTo)
8030
+ const validCandidates = domain.filter((candidate) =>
8031
+ values.every((value) => narrowsTo[value].includes(candidate)),
8032
+ )
8033
+ return validCandidates.find((candidate) =>
8034
+ validCandidates.every((other) => narrowsTo[candidate].includes(other)),
8035
+ )
8036
+ }
8037
+ function deriveRouteMeet(contributing) {
8038
+ const autofixClasses = contributing.map((finding) => finding.autofix_class)
8039
+ const owners = contributing.map((finding) => finding.owner)
8040
+ const verifications = contributing.map((finding) =>
8041
+ finding.requires_verification ? 'true' : 'false',
8042
+ )
8043
+ return {
8044
+ autofix_class:
8045
+ meetOverNarrowsTo(ROUTE_REFUSAL_TABLE.autofix_class, autofixClasses) ??
8046
+ 'advisory',
8047
+ owner: meetOverNarrowsTo(ROUTE_REFUSAL_TABLE.owner, owners) ?? 'release',
8048
+ requires_verification:
8049
+ (meetOverNarrowsTo(
8050
+ ROUTE_REFUSAL_TABLE.requires_verification,
8051
+ verifications,
8052
+ ) ?? 'true') === 'true',
8053
+ }
8054
+ }
8055
+ function deriveRoute(contributing, decision) {
8056
+ const meet = deriveRouteMeet(contributing)
8057
+ if (!decision.proposed_route) return { ok: true, value: meet }
8058
+ if (!decision.route_narrowing_reason) {
8059
+ return rejectMergedFinding(
8060
+ formatReviewArtifactIssuePath(['route_narrowing_reason']),
8061
+ 'route narrowing missing reason',
8062
+ )
8063
+ }
8064
+ if (!isRouteTransitionAllowed(meet, decision.proposed_route)) {
8065
+ return rejectMergedFinding(
8066
+ formatReviewArtifactIssuePath(['proposed_route']),
8067
+ 'route widening',
8068
+ )
8069
+ }
8070
+ return { ok: true, value: decision.proposed_route }
8071
+ }
8072
+ function deriveMergedFindingFields(input) {
8073
+ const submitters = deriveSubmitters(input.contributing)
8074
+ const submitterSet = new Set(submitters)
8075
+ const returnedReviewerSet = new Set(input.returned_reviewers)
8076
+ const agreementCreditResult = deriveAgreementCredit(
8077
+ input.decision.eligible_agreement_credit,
8078
+ submitterSet,
8079
+ returnedReviewerSet,
8080
+ )
8081
+ if (!agreementCreditResult.ok) return agreementCreditResult
8082
+ const routeResult = deriveRoute(input.contributing, input.decision)
8083
+ if (!routeResult.ok) return routeResult
8084
+ const severity = deriveSeverity(input.contributing)
8085
+ const distinctReviewerCount =
8086
+ submitters.length + agreementCreditResult.value.length
8087
+ const confidence = deriveConfidence(input.contributing, distinctReviewerCount)
8088
+ const preExisting = derivePreExisting(input.contributing)
8089
+ const normalizedFile = normalizeRepoRelativePath(input.contributing[0].file)
8090
+ const fingerprint = deriveFingerprint(
8091
+ normalizedFile,
8092
+ input.decision.line,
8093
+ severity,
8094
+ )
8095
+ return {
8096
+ ok: true,
8097
+ value: {
8098
+ severity,
8099
+ submitters,
8100
+ confidence,
8101
+ agreement_credit: agreementCreditResult.value,
8102
+ pre_existing: preExisting,
8103
+ fingerprint,
8104
+ route: routeResult.value,
8105
+ },
8106
+ }
8107
+ }
8108
+ function reviewerFromInputId(inputId) {
8109
+ const separatorIndex = inputId.indexOf('#')
8110
+ return separatorIndex === -1 ? inputId : inputId.slice(0, separatorIndex)
8111
+ }
8112
+ function deriveReturnedReviewers(prepared) {
8113
+ const reviewers = new Set()
8114
+ for (const finding of prepared.surviving_findings) {
8115
+ reviewers.add(finding.reviewer)
8116
+ }
8117
+ for (const disposition of prepared.confidence_dispositions) {
8118
+ if (disposition.disposition === 'suppressed') {
8119
+ reviewers.add(reviewerFromInputId(disposition.input_id))
8120
+ }
8121
+ }
8122
+ return [...reviewers]
8123
+ }
8124
+ function buildSurvivingFindingIndex(prepared) {
8125
+ return new Map(
8126
+ prepared.surviving_findings.map((finding) => [finding.input_id, finding]),
8127
+ )
8128
+ }
8129
+ function requireSurvivingFinding(index, inputId) {
8130
+ const finding = index.get(inputId)
8131
+ if (!finding) {
8132
+ throw new Error(
8133
+ `applyReviewAdjudication: no surviving finding for input ID ${inputId}`,
8134
+ )
8135
+ }
8136
+ return finding
8137
+ }
8138
+ function toContributingTuple(findings) {
8139
+ const [first, second, ...rest] = findings
8140
+ if (!first || !second) {
8141
+ throw new Error(
8142
+ 'applyReviewAdjudication: contributing findings require at least two entries',
8143
+ )
8144
+ }
8145
+ return [first, second, ...rest]
8146
+ }
8147
+ function assemblyFromDerivation(base, derived) {
8148
+ return {
8149
+ ...base,
8150
+ agreement_credit:
8151
+ derived.agreement_credit.length > 0
8152
+ ? derived.agreement_credit
8153
+ : undefined,
8154
+ severity: derived.severity,
8155
+ confidence: derived.confidence,
8156
+ pre_existing: derived.pre_existing,
8157
+ fingerprint: derived.fingerprint,
8158
+ submitters: derived.submitters,
8159
+ autofix_class: derived.route.autofix_class,
8160
+ owner: derived.route.owner,
8161
+ requires_verification: derived.route.requires_verification,
8162
+ }
8163
+ }
8164
+ function assembleMergedGroupFinding(group, survivingIndex, returnedReviewers) {
8165
+ const decision = group.decision
8166
+ const sortedInputIds = [...decision.input_finding_ids].sort(compareStrings)
8167
+ const contributing = toContributingTuple(
8168
+ sortedInputIds.map((inputId) =>
8169
+ requireSurvivingFinding(survivingIndex, inputId),
8170
+ ),
8171
+ )
8172
+ const derived = deriveMergedFindingFields({
8173
+ contributing,
8174
+ decision: {
8175
+ line: decision.line,
8176
+ eligible_agreement_credit: decision.eligible_agreement_credit,
8177
+ proposed_route: decision.proposed_route,
8178
+ route_narrowing_reason: decision.route_narrowing_reason,
8179
+ },
8180
+ returned_reviewers: returnedReviewers,
8181
+ })
8182
+ if (!derived.ok) return derived
8183
+ return {
8184
+ ok: true,
8185
+ value: assemblyFromDerivation(
8186
+ {
8187
+ finding_id: decision.decision_id,
8188
+ file: group.file,
8189
+ title: decision.title,
8190
+ why_it_matters: decision.why_it_matters,
8191
+ line: decision.line,
8192
+ evidence: decision.evidence,
8193
+ suggested_fix: decision.suggested_fix,
8194
+ input_finding_ids: sortedInputIds,
8195
+ },
8196
+ derived.value,
8197
+ ),
8198
+ }
8199
+ }
8200
+ function assembleSingletonFinding(
8201
+ findingId,
8202
+ finding,
8203
+ decisionFields,
8204
+ returnedReviewers,
8205
+ ) {
8206
+ const contributing = [finding, finding]
8207
+ const derived = deriveMergedFindingFields({
8208
+ contributing,
8209
+ decision: {
8210
+ line: finding.line,
8211
+ proposed_route: decisionFields.proposed_route,
8212
+ route_narrowing_reason: decisionFields.route_narrowing_reason,
8213
+ },
8214
+ returned_reviewers: returnedReviewers,
8215
+ })
8216
+ if (!derived.ok) return derived
8217
+ return {
8218
+ ok: true,
8219
+ value: assemblyFromDerivation(
8220
+ {
8221
+ finding_id: findingId,
8222
+ file: normalizeRepoRelativePath(finding.file),
8223
+ title: finding.title,
8224
+ why_it_matters: finding.why_it_matters,
8225
+ line: finding.line,
8226
+ evidence: finding.evidence,
8227
+ suggested_fix: finding.suggested_fix,
8228
+ input_finding_ids: [finding.input_id],
8229
+ },
8230
+ derived.value,
8231
+ ),
8232
+ }
8233
+ }
8234
+ function compareMergedFindingAssembly(a, b) {
8235
+ const severityDelta = SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]
8236
+ if (severityDelta !== 0) return severityDelta
8237
+ if (a.confidence !== b.confidence) return b.confidence - a.confidence
8238
+ const pathDelta = compareStrings(a.file, b.file)
8239
+ if (pathDelta !== 0) return pathDelta
8240
+ if (a.line !== b.line) return a.line - b.line
8241
+ const fingerprintDelta = compareStrings(a.fingerprint, b.fingerprint)
8242
+ if (fingerprintDelta !== 0) return fingerprintDelta
8243
+ return compareStrings(a.finding_id, b.finding_id)
8244
+ }
8245
+ function requiresValidatorRequest(assembly) {
8246
+ return (
8247
+ assembly.severity === 'P0' ||
8248
+ assembly.severity === 'P1' ||
8249
+ assembly.requires_verification
8250
+ )
8251
+ }
8252
+ function toMergedFindingWireShape(assembly) {
8253
+ return {
8254
+ finding_id: assembly.finding_id,
8255
+ file: assembly.file,
8256
+ title: assembly.title,
8257
+ why_it_matters: assembly.why_it_matters,
8258
+ line: assembly.line,
8259
+ autofix_class: assembly.autofix_class,
8260
+ owner: assembly.owner,
8261
+ requires_verification: assembly.requires_verification,
8262
+ evidence: assembly.evidence,
8263
+ suggested_fix: assembly.suggested_fix,
8264
+ input_finding_ids: [...assembly.input_finding_ids],
8265
+ severity: assembly.severity,
8266
+ confidence: assembly.confidence,
8267
+ pre_existing: assembly.pre_existing,
8268
+ fingerprint: assembly.fingerprint,
8269
+ submitters: [...assembly.submitters],
8270
+ ...(assembly.agreement_credit
8271
+ ? { agreement_credit: [...assembly.agreement_credit] }
8272
+ : {}),
8273
+ }
8274
+ }
8275
+ function mergeFindingIdCollisionReason(first, second) {
8276
+ if (first === second) {
8277
+ if (first === 'merged group') return 'duplicate merged group decision id'
8278
+ if (first === 'declined decision') return 'duplicate declined decision id'
8279
+ return 'duplicate passthrough singleton input id'
8280
+ }
8281
+ const pair = [first, second].sort(compareStrings).join('|')
8282
+ if (pair === 'declined decision|merged group') {
8283
+ return 'declined decision id collides with merged group decision id'
8284
+ }
8285
+ if (pair === 'declined decision|passthrough singleton') {
8286
+ return 'declined decision id collides with passthrough singleton input id'
8287
+ }
8288
+ return 'passthrough singleton input id collides with merged group decision id'
8289
+ }
8290
+ function checkNoDuplicateAssembledFindingIds(origins) {
8291
+ const seen = new Map()
8292
+ for (const [index, entry] of origins.entries()) {
8293
+ const priorOrigin = seen.get(entry.finding_id)
8294
+ if (priorOrigin !== undefined) {
8295
+ return {
8296
+ path: formatReviewArtifactIssuePath([
8297
+ 'merge_assembly',
8298
+ index,
8299
+ 'finding_id',
8300
+ ]),
8301
+ reason: mergeFindingIdCollisionReason(priorOrigin, entry.origin),
8302
+ }
8303
+ }
8304
+ seen.set(entry.finding_id, entry.origin)
8305
+ }
8306
+ return
8307
+ }
8308
+ function applyReviewAdjudication(input) {
8309
+ const validated = validateAdjudication(input.prepared, input.decisions)
8310
+ if (!validated.ok) return validated
8311
+ const survivingIndex = buildSurvivingFindingIndex(input.prepared)
8312
+ const returnedReviewers = deriveReturnedReviewers(input.prepared)
8313
+ const assemblies = []
8314
+ const assemblyOrigins = []
8315
+ const disagreementFacts = []
8316
+ for (const group of validated.value.merged) {
8317
+ const result = assembleMergedGroupFinding(
8318
+ group,
8319
+ survivingIndex,
8320
+ returnedReviewers,
8321
+ )
8322
+ if (!result.ok) return result
8323
+ assemblies.push(result.value)
8324
+ assemblyOrigins.push({
8325
+ finding_id: result.value.finding_id,
8326
+ origin: 'merged group',
8327
+ })
8328
+ if (group.decision.disagreement_facts) {
8329
+ disagreementFacts.push(...group.decision.disagreement_facts)
8330
+ }
8331
+ }
8332
+ for (const singleton of validated.value.declined) {
8333
+ const finding = requireSurvivingFinding(
8334
+ survivingIndex,
8335
+ singleton.decision.input_finding_id,
8336
+ )
8337
+ const result = assembleSingletonFinding(
8338
+ singleton.decision.decision_id,
8339
+ finding,
8340
+ {
8341
+ proposed_route: singleton.decision.proposed_route,
8342
+ route_narrowing_reason: singleton.decision.route_narrowing_reason,
8343
+ },
8344
+ returnedReviewers,
8345
+ )
8346
+ if (!result.ok) return result
8347
+ assemblies.push(result.value)
8348
+ assemblyOrigins.push({
8349
+ finding_id: result.value.finding_id,
8350
+ origin: 'declined decision',
8351
+ })
8352
+ disagreementFacts.push(singleton.decision.declined_reason)
8353
+ if (singleton.decision.disagreement_facts) {
8354
+ disagreementFacts.push(...singleton.decision.disagreement_facts)
8355
+ }
8356
+ }
8357
+ for (const inputId of validated.value.singletons) {
8358
+ const finding = requireSurvivingFinding(survivingIndex, inputId)
8359
+ const result = assembleSingletonFinding(
8360
+ inputId,
8361
+ finding,
8362
+ {},
8363
+ returnedReviewers,
8364
+ )
8365
+ if (!result.ok) return result
8366
+ assemblies.push(result.value)
8367
+ assemblyOrigins.push({
8368
+ finding_id: result.value.finding_id,
8369
+ origin: 'passthrough singleton',
8370
+ })
8371
+ }
8372
+ const collision = checkNoDuplicateAssembledFindingIds(assemblyOrigins)
8373
+ if (collision) return { ok: false, rejection: collision }
8374
+ assemblies.sort(compareMergedFindingAssembly)
8375
+ disagreementFacts.sort(compareStrings)
8376
+ const mergedFindings = assemblies.map(toMergedFindingWireShape)
8377
+ const validatorRequests = assemblies
8378
+ .filter(requiresValidatorRequest)
8379
+ .map((assembly) => ({
8380
+ finding_id: assembly.finding_id,
8381
+ file: assembly.file,
8382
+ line: assembly.line,
8383
+ }))
8384
+ return {
8385
+ ok: true,
8386
+ value: MergeOutputSchema.parse({
8387
+ merged_findings: mergedFindings,
8388
+ validator_requests: validatorRequests,
8389
+ disagreement_facts: disagreementFacts,
8390
+ }),
8391
+ }
8392
+ }
8393
+ function rejectReconcile(path, reason) {
8394
+ return { ok: false, rejection: { path, reason } }
8395
+ }
8396
+ function indexLifecycleResults(results, requestedIds) {
8397
+ const resultsByFindingId = new Map()
8398
+ for (const [index, record] of results.entries()) {
8399
+ const path = formatReviewArtifactIssuePath([
8400
+ 'validator_lifecycle_results',
8401
+ index,
8402
+ 'finding_id',
8403
+ ])
8404
+ if (resultsByFindingId.has(record.finding_id)) {
8405
+ return rejectReconcile(path, 'duplicate validator result')
8406
+ }
8407
+ if (!requestedIds.has(record.finding_id)) {
8408
+ return rejectReconcile(path, 'unrequested validator result')
8409
+ }
8410
+ resultsByFindingId.set(record.finding_id, record.result)
8411
+ }
8412
+ return { ok: true, value: resultsByFindingId }
8413
+ }
8414
+ function validateNoMissingResults(validatorRequests, resultsByFindingId) {
8415
+ for (const [index, request] of validatorRequests.entries()) {
8416
+ if (!resultsByFindingId.has(request.finding_id)) {
8417
+ return {
8418
+ path: formatReviewArtifactIssuePath([
8419
+ 'validator_requests',
8420
+ index,
8421
+ 'finding_id',
8422
+ ]),
8423
+ reason: 'missing validator result',
8424
+ }
8425
+ }
8426
+ }
8427
+ return
8428
+ }
8429
+ function classifyFinding(finding, result) {
8430
+ if (!result) return { finding: { ...finding }, filtered: false }
8431
+ if (result.outcome === 'true') {
8432
+ return { finding: { ...finding, validated: true }, filtered: false }
8433
+ }
8434
+ if (result.outcome === 'false') {
8435
+ return {
8436
+ finding: {
8437
+ ...finding,
8438
+ validated: false,
8439
+ validation_reason: result.reason,
8440
+ },
8441
+ filtered: true,
8442
+ }
8443
+ }
8444
+ return {
8445
+ finding: { ...finding },
8446
+ filtered: false,
8447
+ failure: {
8448
+ finding_id: finding.finding_id,
8449
+ outcome: result.outcome,
8450
+ reason: result.reason,
8451
+ },
8452
+ }
8453
+ }
8454
+ function reconcileValidatorResults(input) {
8455
+ const requestedIds = new Set(
8456
+ input.merge.validator_requests.map((request) => request.finding_id),
8457
+ )
8458
+ const indexed = indexLifecycleResults(
8459
+ input.validator_lifecycle_results,
8460
+ requestedIds,
8461
+ )
8462
+ if (!indexed.ok) return indexed
8463
+ const missingViolation = validateNoMissingResults(
8464
+ input.merge.validator_requests,
8465
+ indexed.value,
8466
+ )
8467
+ if (missingViolation) return { ok: false, rejection: missingViolation }
8468
+ const findings = []
8469
+ const filteredFindingIds = new Set()
8470
+ const filteredInputIds = new Set()
8471
+ const lifecycleFailures = []
8472
+ for (const finding of input.merge.merged_findings) {
8473
+ const classified = classifyFinding(
8474
+ finding,
8475
+ indexed.value.get(finding.finding_id),
8476
+ )
8477
+ findings.push(classified.finding)
8478
+ if (classified.filtered) {
8479
+ filteredFindingIds.add(finding.finding_id)
8480
+ for (const inputId of finding.input_finding_ids) {
8481
+ filteredInputIds.add(inputId)
8482
+ }
8483
+ }
8484
+ if (classified.failure) lifecycleFailures.push(classified.failure)
8485
+ }
8486
+ lifecycleFailures.sort((a, b) => compareStrings(a.finding_id, b.finding_id))
8487
+ return {
8488
+ ok: true,
8489
+ value: {
8490
+ findings,
8491
+ filtered_finding_ids: [...filteredFindingIds].sort(compareStrings),
8492
+ filtered_input_ids: [...filteredInputIds].sort(compareStrings),
8493
+ lifecycle_failures: lifecycleFailures,
8494
+ degraded: lifecycleFailures.length > 0,
8495
+ },
8496
+ }
8497
+ }
8498
+ function rejectFinalizeContext(path, reason) {
8499
+ return { ok: false, rejection: { path, reason } }
8500
+ }
8501
+ function normalizeSelectionSurface(surface) {
8502
+ if (surface === undefined) return
8503
+ return [...surface].map(normalizeRepoRelativePath).sort(compareStrings)
8504
+ }
8505
+ function selectionSurfaceHasDuplicates(surface) {
8506
+ if (surface === undefined) return false
8507
+ const normalized = surface.map(normalizeRepoRelativePath)
8508
+ return new Set(normalized).size !== normalized.length
8509
+ }
8510
+ function dispatchRecordsEqual(a, b) {
8511
+ return (
8512
+ a.persona === b.persona &&
8513
+ a.dispatch_outcome === b.dispatch_outcome &&
8514
+ JSON.stringify(normalizeSelectionSurface(a.selection_surface) ?? []) ===
8515
+ JSON.stringify(normalizeSelectionSurface(b.selection_surface) ?? []) &&
8516
+ a.selection_reason === b.selection_reason
8517
+ )
8518
+ }
8519
+ var FINALIZE_CONTEXT_LOSS_DISPATCH_OUTCOMES = new Set([
8520
+ 'malformed',
8521
+ 'never_returned',
8522
+ 'validation_unavailable',
8523
+ ])
8524
+ var FINALIZE_CONTEXT_LOSS_SEVERITIES = new Set(['P0', 'P1', 'unknown'])
8525
+ function checkNoDuplicateMergedFindingIds(mergedFindings) {
8526
+ const seenFindingIds = new Set()
8527
+ for (const [index, finding] of mergedFindings.entries()) {
8528
+ if (seenFindingIds.has(finding.finding_id)) {
8529
+ return rejectFinalizeContext(
8530
+ formatReviewArtifactIssuePath([
8531
+ 'merge',
8532
+ 'merged_findings',
8533
+ index,
8534
+ 'finding_id',
8535
+ ]),
8536
+ 'duplicate merged finding ID',
8537
+ )
8538
+ }
8539
+ seenFindingIds.add(finding.finding_id)
8540
+ }
8541
+ return { ok: true, value: seenFindingIds }
8542
+ }
8543
+ function checkSurvivorPartition(
8544
+ mergedFindings,
8545
+ survivingFindings,
8546
+ survivingIndex,
8547
+ ) {
8548
+ const coveredInputIds = new Set()
8549
+ const contributingByFindingId = new Map()
8550
+ for (const [findingIndex, finding] of mergedFindings.entries()) {
8551
+ const sortedIds = [...finding.input_finding_ids].sort(compareStrings)
8552
+ const resolved = []
8553
+ for (const [idIndex, inputId] of sortedIds.entries()) {
8554
+ const survivor = survivingIndex.get(inputId)
8555
+ if (!survivor) {
8556
+ return rejectFinalizeContext(
8557
+ formatReviewArtifactIssuePath([
8558
+ 'merge',
8559
+ 'merged_findings',
8560
+ findingIndex,
8561
+ 'input_finding_ids',
8562
+ idIndex,
8563
+ ]),
8564
+ 'merged finding references unknown survivor',
8565
+ )
8566
+ }
8567
+ if (coveredInputIds.has(inputId)) {
8568
+ return rejectFinalizeContext(
8569
+ formatReviewArtifactIssuePath([
8570
+ 'merge',
8571
+ 'merged_findings',
8572
+ findingIndex,
8573
+ 'input_finding_ids',
8574
+ idIndex,
8575
+ ]),
8576
+ 'survivor claimed by multiple merged findings',
8577
+ )
8578
+ }
8579
+ resolved.push(survivor)
8580
+ coveredInputIds.add(inputId)
8581
+ }
8582
+ contributingByFindingId.set(finding.finding_id, resolved)
8583
+ }
8584
+ for (const [survivorIndex, survivor] of survivingFindings.entries()) {
8585
+ if (!coveredInputIds.has(survivor.input_id)) {
8586
+ return rejectFinalizeContext(
8587
+ formatReviewArtifactIssuePath([
8588
+ 'prepared',
8589
+ 'surviving_findings',
8590
+ survivorIndex,
8591
+ 'input_id',
8592
+ ]),
8593
+ 'survivor missing from merge inputs',
8594
+ )
8595
+ }
8596
+ }
8597
+ return { ok: true, value: contributingByFindingId }
8598
+ }
8599
+ function validatorRequestMismatches(request, findingById, expectedFindingIds) {
8600
+ const finding = findingById.get(request.finding_id)
8601
+ return (
8602
+ !finding ||
8603
+ !expectedFindingIds.has(request.finding_id) ||
8604
+ request.file !== finding.file ||
8605
+ request.line !== finding.line
8606
+ )
8607
+ }
8608
+ function checkValidatorRequestsResolve(validatorRequests, mergedFindings) {
8609
+ const findingById = new Map(
8610
+ mergedFindings.map((finding) => [finding.finding_id, finding]),
8611
+ )
8612
+ const expectedFindingIds = new Set(
8613
+ mergedFindings
8614
+ .filter((finding) => requiresValidatorRequest(finding))
8615
+ .map((finding) => finding.finding_id),
8616
+ )
8617
+ const seenFindingIds = new Set()
8618
+ for (const [index, request] of validatorRequests.entries()) {
8619
+ const path = formatReviewArtifactIssuePath([
8620
+ 'merge',
8621
+ 'validator_requests',
8622
+ index,
8623
+ 'finding_id',
8624
+ ])
8625
+ if (
8626
+ seenFindingIds.has(request.finding_id) ||
8627
+ validatorRequestMismatches(request, findingById, expectedFindingIds)
8628
+ ) {
8629
+ return {
8630
+ path,
8631
+ reason: 'validator request references unknown merged finding',
8632
+ }
8633
+ }
8634
+ seenFindingIds.add(request.finding_id)
8635
+ }
8636
+ if (seenFindingIds.size !== expectedFindingIds.size) {
8637
+ return {
8638
+ path: formatReviewArtifactIssuePath(['merge', 'validator_requests']),
8639
+ reason: 'validator request references unknown merged finding',
8640
+ }
8641
+ }
8642
+ return
8643
+ }
8644
+ function checkDispatchRecordsJoin(dispatchRecords, selectedDispatches) {
8645
+ if (dispatchRecords.length !== selectedDispatches.length) {
8646
+ return rejectFinalizeContext(
8647
+ formatReviewArtifactIssuePath(['dispatch_records']),
8648
+ 'dispatch record mismatch',
8649
+ )
8650
+ }
8651
+ const selectedByPersona = new Map(
8652
+ selectedDispatches.map((dispatch) => [dispatch.persona, dispatch]),
8653
+ )
8654
+ if (selectedByPersona.size !== selectedDispatches.length) {
8655
+ return rejectFinalizeContext(
8656
+ formatReviewArtifactIssuePath([
8657
+ 'parent_run_metadata',
8658
+ 'selected_dispatches',
8659
+ ]),
8660
+ 'dispatch record mismatch',
8661
+ )
8662
+ }
8663
+ const seenPersonas = new Set()
8664
+ for (const [index, record] of dispatchRecords.entries()) {
8665
+ const selected = selectedByPersona.get(record.persona)
8666
+ if (seenPersonas.has(record.persona) || !selected) {
8667
+ return rejectFinalizeContext(
8668
+ formatReviewArtifactIssuePath(['dispatch_records', index]),
8669
+ 'dispatch record mismatch',
8670
+ )
8671
+ }
8672
+ if (
8673
+ selectionSurfaceHasDuplicates(record.selection_surface) ||
8674
+ selectionSurfaceHasDuplicates(selected.selection_surface)
8675
+ ) {
8676
+ return rejectFinalizeContext(
8677
+ formatReviewArtifactIssuePath([
8678
+ 'dispatch_records',
8679
+ index,
8680
+ 'selection_surface',
8681
+ ]),
8682
+ 'duplicate selection surface entry',
8683
+ )
8684
+ }
8685
+ if (!dispatchRecordsEqual(record, selected)) {
8686
+ return rejectFinalizeContext(
8687
+ formatReviewArtifactIssuePath(['dispatch_records', index]),
8688
+ 'dispatch record mismatch',
8689
+ )
8690
+ }
8691
+ seenPersonas.add(record.persona)
8692
+ }
8693
+ return { ok: true, value: selectedByPersona }
8694
+ }
8695
+ var SCREEN_RESULT_EXEMPT_DISPATCH_OUTCOMES = new Set([
8696
+ 'validation_unavailable',
8697
+ 'never_returned',
8698
+ ])
8699
+ function checkScreenResultsJoin(
8700
+ screenResults,
8701
+ dispatchRecords,
8702
+ selectedByPersona,
8703
+ ) {
8704
+ const screenByReviewer = new Map()
8705
+ for (const [index, result] of screenResults.entries()) {
8706
+ if (
8707
+ screenByReviewer.has(result.reviewer) ||
8708
+ !selectedByPersona.has(result.reviewer)
8709
+ ) {
8710
+ return rejectFinalizeContext(
8711
+ formatReviewArtifactIssuePath(['screen_results', index, 'reviewer']),
8712
+ 'unexpected screen result for persona',
8713
+ )
8714
+ }
8715
+ screenByReviewer.set(result.reviewer, result)
8716
+ }
8717
+ for (const [index, record] of dispatchRecords.entries()) {
8718
+ const screenResult = screenByReviewer.get(record.persona)
8719
+ if (!screenResult) {
8720
+ if (SCREEN_RESULT_EXEMPT_DISPATCH_OUTCOMES.has(record.dispatch_outcome)) {
8721
+ continue
8722
+ }
8723
+ return rejectFinalizeContext(
8724
+ formatReviewArtifactIssuePath(['dispatch_records', index, 'persona']),
8725
+ 'screen result missing for selected persona',
8726
+ )
8727
+ }
8728
+ if (screenResult.result.dispatch_outcome !== record.dispatch_outcome) {
8729
+ return rejectFinalizeContext(
8730
+ formatReviewArtifactIssuePath([
8731
+ 'dispatch_records',
8732
+ index,
8733
+ 'dispatch_outcome',
8734
+ ]),
8735
+ 'screen result outcome does not match dispatch record',
8736
+ )
8737
+ }
8738
+ }
8739
+ return { ok: true, value: screenByReviewer }
8740
+ }
8741
+ function mergedFindingFileDiverges(finding, contributingSurvivors) {
8742
+ const normalizedFindingFile = normalizeRepoRelativePath(finding.file)
8743
+ return contributingSurvivors.some(
8744
+ (survivor) =>
8745
+ normalizeRepoRelativePath(survivor.file) !== normalizedFindingFile,
8746
+ )
8747
+ }
8748
+ function mergedFindingLineDiverges(finding, contributingSurvivors) {
8749
+ return !contributingSurvivors.some(
8750
+ (survivor) => survivor.line === finding.line,
8751
+ )
8752
+ }
8753
+ function eligibleAgreementCreditClaim(finding) {
8754
+ return finding.input_finding_ids.length >= 2
8755
+ ? finding.agreement_credit
8756
+ : undefined
8757
+ }
8758
+ function mergedFindingDivergesFromDerivation(
8759
+ finding,
8760
+ contributingByFindingId,
8761
+ returnedReviewers,
8762
+ ) {
8763
+ const resolved = contributingByFindingId.get(finding.finding_id) ?? []
8764
+ const contributing = toContributingTuple(
8765
+ resolved.length >= 2 ? resolved : [...resolved, ...resolved],
8766
+ )
8767
+ const derivation = deriveMergedFindingFields({
8768
+ contributing,
8769
+ decision: {
8770
+ line: finding.line,
8771
+ eligible_agreement_credit: eligibleAgreementCreditClaim(finding),
8772
+ proposed_route: {
8773
+ autofix_class: finding.autofix_class,
8774
+ owner: finding.owner,
8775
+ requires_verification: finding.requires_verification,
8776
+ },
8777
+ route_narrowing_reason: 'carried route verification',
8778
+ },
8779
+ returned_reviewers: returnedReviewers,
8780
+ })
8781
+ return (
8782
+ mergedFindingFileDiverges(finding, resolved) ||
8783
+ mergedFindingLineDiverges(finding, resolved) ||
8784
+ !derivation.ok ||
8785
+ derivation.value.severity !== finding.severity ||
8786
+ derivation.value.confidence !== finding.confidence ||
8787
+ derivation.value.pre_existing !== finding.pre_existing ||
8788
+ derivation.value.fingerprint !== finding.fingerprint ||
8789
+ JSON.stringify(derivation.value.submitters) !==
8790
+ JSON.stringify(finding.submitters) ||
8791
+ JSON.stringify(derivation.value.agreement_credit) !==
8792
+ JSON.stringify(finding.agreement_credit ?? []) ||
8793
+ derivation.value.route.autofix_class !== finding.autofix_class ||
8794
+ derivation.value.route.owner !== finding.owner ||
8795
+ derivation.value.route.requires_verification !==
8796
+ finding.requires_verification
8797
+ )
8798
+ }
8799
+ function checkMergedFindingsMatchDerivation(
8800
+ mergedFindings,
8801
+ contributingByFindingId,
8802
+ returnedReviewers,
8803
+ ) {
8804
+ for (const [index, finding] of mergedFindings.entries()) {
8805
+ if (
8806
+ mergedFindingDivergesFromDerivation(
8807
+ finding,
8808
+ contributingByFindingId,
8809
+ returnedReviewers,
8810
+ )
8811
+ ) {
8812
+ return {
8813
+ path: formatReviewArtifactIssuePath([
8814
+ 'merge',
8815
+ 'merged_findings',
8816
+ index,
8817
+ ]),
8818
+ reason: 'merged finding fields diverge from derivation',
8819
+ }
8820
+ }
8821
+ }
8822
+ return
8823
+ }
8824
+ function checkNoDuplicateConfidenceDispositions(confidenceDispositions) {
8825
+ const seen = new Set()
8826
+ for (const [index, entry] of confidenceDispositions.entries()) {
8827
+ if (seen.has(entry.input_id)) {
8828
+ return {
8829
+ path: formatReviewArtifactIssuePath([
8830
+ 'prepared',
8831
+ 'confidence_dispositions',
8832
+ index,
8833
+ 'input_id',
8834
+ ]),
8835
+ reason: 'duplicate confidence disposition',
8836
+ }
8837
+ }
8838
+ seen.add(entry.input_id)
8839
+ }
8840
+ return
8841
+ }
8842
+ function checkConfidenceDispositionsResolveScreenedFindings(
8843
+ prepared,
8844
+ screenResults,
8845
+ ) {
8846
+ const screenedCounts = new Map()
8847
+ const screenedByInputId = new Map()
8848
+ for (const result of screenResults) {
8849
+ for (const finding of result.result.admitted_findings) {
8850
+ screenedCounts.set(
8851
+ finding.input_id,
8852
+ (screenedCounts.get(finding.input_id) ?? 0) + 1,
8853
+ )
8854
+ screenedByInputId.set(finding.input_id, {
8855
+ reviewer: result.reviewer,
8856
+ confidence: finding.confidence,
8857
+ file: finding.file,
8858
+ line: finding.line,
8859
+ severity: finding.severity,
8860
+ })
8861
+ }
8862
+ }
8863
+ for (const [
8864
+ index,
8865
+ disposition,
8866
+ ] of prepared.confidence_dispositions.entries()) {
8867
+ if (screenedCounts.get(disposition.input_id) !== 1) {
8868
+ return {
8869
+ path: formatReviewArtifactIssuePath([
8870
+ 'prepared',
8871
+ 'confidence_dispositions',
8872
+ index,
8873
+ 'input_id',
8874
+ ]),
8875
+ reason: 'confidence disposition references unscreened finding',
8876
+ }
8877
+ }
8878
+ }
8879
+ for (const [index, survivor] of prepared.surviving_findings.entries()) {
8880
+ const screened = screenedByInputId.get(survivor.input_id)
8881
+ if (screened === undefined) {
8882
+ return {
8883
+ path: formatReviewArtifactIssuePath([
8884
+ 'prepared',
8885
+ 'surviving_findings',
8886
+ index,
8887
+ 'input_id',
8888
+ ]),
8889
+ reason: 'surviving finding references unscreened input',
8890
+ }
8891
+ }
8892
+ if (
8893
+ screened.reviewer !== survivor.reviewer ||
8894
+ screened.confidence !== survivor.confidence ||
8895
+ normalizeRepoRelativePath(screened.file) !==
8896
+ normalizeRepoRelativePath(survivor.file) ||
8897
+ screened.line !== survivor.line ||
8898
+ screened.severity !== survivor.severity
8899
+ ) {
8900
+ return {
8901
+ path: formatReviewArtifactIssuePath([
8902
+ 'prepared',
8903
+ 'surviving_findings',
8904
+ index,
8905
+ ]),
8906
+ reason: 'surviving finding diverges from its screened finding',
8907
+ }
8908
+ }
8909
+ }
8910
+ return
8911
+ }
8912
+ function findUnavailableCitedReviewer(
8913
+ finding,
8914
+ findingIndex,
8915
+ survivingIndex,
8916
+ dispatchByPersona,
8917
+ ) {
8918
+ const citedReviewers = new Set()
8919
+ for (const [idIndex, inputId] of finding.input_finding_ids.entries()) {
8920
+ const survivor = survivingIndex.get(inputId)
8921
+ if (!survivor) continue
8922
+ citedReviewers.add(survivor.reviewer)
8923
+ if (
8924
+ dispatchByPersona.get(survivor.reviewer)?.dispatch_outcome ===
8925
+ 'validation_unavailable'
8926
+ ) {
8927
+ return {
8928
+ citedReviewers,
8929
+ rejection: {
8930
+ path: formatReviewArtifactIssuePath([
8931
+ 'merge',
8932
+ 'merged_findings',
8933
+ findingIndex,
8934
+ 'input_finding_ids',
8935
+ idIndex,
8936
+ ]),
8937
+ reason: 'merged finding cites input from unavailable reviewer',
8938
+ },
8939
+ }
8940
+ }
8941
+ }
8942
+ return { citedReviewers }
8943
+ }
8944
+ function findUnsupportedSubmitter(finding, findingIndex, citedReviewers) {
8945
+ for (const [submitterIndex, submitter] of finding.submitters.entries()) {
8946
+ if (!citedReviewers.has(submitter)) {
8947
+ return {
8948
+ path: formatReviewArtifactIssuePath([
8949
+ 'merge',
8950
+ 'merged_findings',
8951
+ findingIndex,
8952
+ 'submitters',
8953
+ submitterIndex,
8954
+ ]),
8955
+ reason: 'merged finding submitter not a cited reviewer',
8956
+ }
8957
+ }
8958
+ }
8959
+ return
8960
+ }
8961
+ function findOverlappingAgreementCredit(finding, findingIndex) {
8962
+ const submitterSet = new Set(finding.submitters)
8963
+ const agreementCredit = finding.agreement_credit ?? []
8964
+ for (const [creditIndex, credit] of agreementCredit.entries()) {
8965
+ if (submitterSet.has(credit)) {
8966
+ return {
8967
+ path: formatReviewArtifactIssuePath([
8968
+ 'merge',
8969
+ 'merged_findings',
8970
+ findingIndex,
8971
+ 'agreement_credit',
8972
+ creditIndex,
8973
+ ]),
8974
+ reason: 'merged finding agreement credit overlaps submitters',
8975
+ }
8976
+ }
8977
+ }
8978
+ return
8979
+ }
8980
+ function checkMergedFindingProvenance(
8981
+ mergedFindings,
8982
+ survivingIndex,
8983
+ dispatchByPersona,
8984
+ ) {
8985
+ for (const [findingIndex, finding] of mergedFindings.entries()) {
8986
+ const unavailable = findUnavailableCitedReviewer(
8987
+ finding,
8988
+ findingIndex,
8989
+ survivingIndex,
8990
+ dispatchByPersona,
8991
+ )
8992
+ if (unavailable.rejection) return unavailable.rejection
8993
+ const unsupportedSubmitter = findUnsupportedSubmitter(
8994
+ finding,
8995
+ findingIndex,
8996
+ unavailable.citedReviewers,
8997
+ )
8998
+ if (unsupportedSubmitter) return unsupportedSubmitter
8999
+ const overlappingCredit = findOverlappingAgreementCredit(
9000
+ finding,
9001
+ findingIndex,
9002
+ )
9003
+ if (overlappingCredit) return overlappingCredit
9004
+ }
9005
+ return
9006
+ }
9007
+ function deriveRejectedPayloadWeights(screenResults) {
9008
+ const sorted = [...screenResults].sort((a, b) =>
9009
+ compareStrings(a.reviewer, b.reviewer),
9010
+ )
9011
+ const weights = []
9012
+ for (const result of sorted) {
9013
+ const summary = result.result.rejected_summary
9014
+ if (summary) {
9015
+ weights.push({ rejected_finding_count: summary.rejected_finding_count })
9016
+ }
9017
+ }
9018
+ return weights
9019
+ }
9020
+ function deriveLostRiskCriticalPersonas(dispatchRecords, screenByReviewer) {
9021
+ const riskCriticalPersonas = new Set(RISK_CRITICAL_PERSONAS)
9022
+ const lostPersonas = []
9023
+ for (const record of dispatchRecords) {
9024
+ if (!riskCriticalPersonas.has(record.persona)) continue
9025
+ const selectionSurface = record.selection_surface ?? []
9026
+ if (FINALIZE_CONTEXT_LOSS_DISPATCH_OUTCOMES.has(record.dispatch_outcome)) {
9027
+ lostPersonas.push({
9028
+ persona: record.persona,
9029
+ selection_surface: selectionSurface,
9030
+ })
9031
+ continue
9032
+ }
9033
+ const rejectedSeverities =
9034
+ screenByReviewer.get(record.persona)?.result.rejected_summary
9035
+ ?.rejected_severities ?? []
9036
+ if (
9037
+ rejectedSeverities.some((severity) =>
9038
+ FINALIZE_CONTEXT_LOSS_SEVERITIES.has(severity),
9039
+ )
9040
+ ) {
9041
+ lostPersonas.push({
9042
+ persona: record.persona,
9043
+ selection_surface: selectionSurface,
9044
+ })
9045
+ }
9046
+ }
9047
+ return [...lostPersonas].sort((a, b) => compareStrings(a.persona, b.persona))
9048
+ }
9049
+ function deriveFinalizeContext(input) {
9050
+ if (input.parent_run_metadata.validation.status !== 'not_attempted') {
9051
+ return rejectFinalizeContext(
9052
+ formatReviewArtifactIssuePath([
9053
+ 'parent_run_metadata',
9054
+ 'validation',
9055
+ 'status',
9056
+ ]),
9057
+ 'validation must be not_attempted at finalize',
9058
+ )
9059
+ }
9060
+ const findingIds = checkNoDuplicateMergedFindingIds(
9061
+ input.merge.merged_findings,
9062
+ )
9063
+ if (!findingIds.ok) return findingIds
9064
+ const survivingIndex = buildSurvivingFindingIndex(input.prepared)
9065
+ const partition = checkSurvivorPartition(
9066
+ input.merge.merged_findings,
9067
+ input.prepared.surviving_findings,
9068
+ survivingIndex,
9069
+ )
9070
+ if (!partition.ok) return partition
9071
+ const requestViolation = checkValidatorRequestsResolve(
9072
+ input.merge.validator_requests,
9073
+ input.merge.merged_findings,
9074
+ )
9075
+ if (requestViolation) return { ok: false, rejection: requestViolation }
9076
+ const dispatchJoin = checkDispatchRecordsJoin(
9077
+ input.dispatch_records,
9078
+ input.parent_run_metadata.selected_dispatches,
9079
+ )
9080
+ if (!dispatchJoin.ok) return dispatchJoin
9081
+ const screenJoin = checkScreenResultsJoin(
9082
+ input.screen_results,
9083
+ input.dispatch_records,
9084
+ dispatchJoin.value,
9085
+ )
9086
+ if (!screenJoin.ok) return screenJoin
9087
+ const returnedReviewers = deriveReturnedReviewers(input.prepared)
9088
+ const derivationViolation = checkMergedFindingsMatchDerivation(
9089
+ input.merge.merged_findings,
9090
+ partition.value,
9091
+ returnedReviewers,
9092
+ )
9093
+ if (derivationViolation) return { ok: false, rejection: derivationViolation }
9094
+ const duplicateDispositionViolation = checkNoDuplicateConfidenceDispositions(
9095
+ input.prepared.confidence_dispositions,
9096
+ )
9097
+ if (duplicateDispositionViolation) {
9098
+ return { ok: false, rejection: duplicateDispositionViolation }
9099
+ }
9100
+ const dispositionJoinViolation =
9101
+ checkConfidenceDispositionsResolveScreenedFindings(
9102
+ input.prepared,
9103
+ input.screen_results,
9104
+ )
9105
+ if (dispositionJoinViolation) {
9106
+ return { ok: false, rejection: dispositionJoinViolation }
9107
+ }
9108
+ const provenanceViolation = checkMergedFindingProvenance(
9109
+ input.merge.merged_findings,
9110
+ survivingIndex,
9111
+ dispatchJoin.value,
9112
+ )
9113
+ if (provenanceViolation) return { ok: false, rejection: provenanceViolation }
9114
+ return {
9115
+ ok: true,
9116
+ value: {
9117
+ rejected_payloads: deriveRejectedPayloadWeights(input.screen_results),
9118
+ lost_risk_critical_personas: deriveLostRiskCriticalPersonas(
9119
+ input.dispatch_records,
9120
+ screenJoin.value,
9121
+ ),
9122
+ },
9123
+ }
9124
+ }
9125
+ function deriveInputDispositions(
9126
+ prepared,
9127
+ reconciled,
9128
+ reviewerIndex,
9129
+ unavailablePersonas,
9130
+ ) {
9131
+ const filteredInputIds = new Set(reconciled.filtered_input_ids)
9132
+ const findingByInputId = new Map()
9133
+ for (const finding of reconciled.findings) {
9134
+ for (const inputId of finding.input_finding_ids) {
9135
+ findingByInputId.set(inputId, finding)
9136
+ }
9137
+ }
9138
+ const dispositions = []
9139
+ for (const [index, entry] of prepared.confidence_dispositions.entries()) {
9140
+ const reviewer = reviewerIndex.get(entry.input_id)
9141
+ if (reviewer !== undefined && unavailablePersonas.has(reviewer)) continue
9142
+ if (entry.disposition === 'suppressed') {
9143
+ dispositions.push({
9144
+ input_id: entry.input_id,
9145
+ disposition: 'suppressed',
9146
+ reason: entry.reason,
9147
+ })
9148
+ continue
9149
+ }
9150
+ if (filteredInputIds.has(entry.input_id)) {
9151
+ dispositions.push({ input_id: entry.input_id, disposition: 'filtered' })
9152
+ continue
9153
+ }
9154
+ const finding = findingByInputId.get(entry.input_id)
9155
+ if (finding === undefined) {
9156
+ return {
9157
+ ok: false,
9158
+ rejection: {
9159
+ path: formatReviewArtifactIssuePath([
9160
+ 'prepared',
9161
+ 'confidence_dispositions',
9162
+ index,
9163
+ 'input_id',
9164
+ ]),
9165
+ reason: 'survivor missing from merged findings',
9166
+ },
9167
+ }
9168
+ }
9169
+ const isMerged = finding.input_finding_ids.length > 1
9170
+ dispositions.push({
9171
+ input_id: entry.input_id,
9172
+ disposition: isMerged ? 'merged' : 'surviving',
9173
+ })
9174
+ }
9175
+ return {
9176
+ ok: true,
9177
+ value: [...dispositions].sort((a, b) =>
9178
+ compareStrings(a.input_id, b.input_id),
9179
+ ),
9180
+ }
9181
+ }
9182
+ function computeDispositionCounts(inputDispositions, rejectedPayloads) {
9183
+ let surviving = 0
9184
+ let merged = 0
9185
+ let suppressed = 0
9186
+ let filtered = 0
9187
+ for (const entry of inputDispositions) {
9188
+ if (entry.disposition === 'surviving') surviving += 1
9189
+ else if (entry.disposition === 'merged') merged += 1
9190
+ else if (entry.disposition === 'suppressed') suppressed += 1
9191
+ else filtered += 1
9192
+ }
9193
+ const rejected = rejectedPayloads.reduce(
9194
+ (total, payload) => total + payload.rejected_finding_count,
9195
+ 0,
9196
+ )
9197
+ return { surviving, merged, suppressed, filtered, rejected }
9198
+ }
9199
+ function routeForOwner(owner) {
9200
+ if (owner === 'review-fixer') return 'fixer'
9201
+ if (owner === 'release') return 'report_only'
9202
+ return 'residual'
9203
+ }
9204
+ function partitionFindings(reconciled) {
9205
+ const filteredFindingIds = new Set(reconciled.filtered_finding_ids)
9206
+ const unconfirmedFindingIds = new Set(
9207
+ reconciled.lifecycle_failures.map((failure) => failure.finding_id),
9208
+ )
9209
+ const preExistingFindings = []
9210
+ const newFindings = []
9211
+ const fixer = []
9212
+ const residual = []
9213
+ const reportOnly = []
9214
+ for (const finding of reconciled.findings) {
9215
+ if (filteredFindingIds.has(finding.finding_id)) continue
9216
+ const unconfirmed = unconfirmedFindingIds.has(finding.finding_id)
9217
+ const entry = { finding_id: finding.finding_id, unconfirmed }
9218
+ if (finding.pre_existing) {
9219
+ preExistingFindings.push(entry)
9220
+ continue
9221
+ }
9222
+ newFindings.push(entry)
9223
+ if (unconfirmed) continue
9224
+ const route = routeForOwner(finding.owner)
9225
+ if (route === 'fixer') fixer.push(entry)
9226
+ else if (route === 'residual') residual.push(entry)
9227
+ else reportOnly.push(entry)
9228
+ }
9229
+ const byFindingId = (a, b) => compareStrings(a.finding_id, b.finding_id)
9230
+ return {
9231
+ preExistingFindings: [...preExistingFindings].sort(byFindingId),
9232
+ newFindings: [...newFindings].sort(byFindingId),
9233
+ queues: {
9234
+ fixer: [...fixer].sort(byFindingId),
9235
+ residual: [...residual].sort(byFindingId),
9236
+ report_only: [...reportOnly].sort(byFindingId),
9237
+ },
9238
+ }
9239
+ }
9240
+ function finalizeReviewDispositions(input) {
9241
+ const reviewerIndex = buildAdmittedReviewerIndex(
9242
+ input.prepared,
9243
+ input.screen_results,
9244
+ )
9245
+ const unavailablePersonas = buildValidationUnavailablePersonas(
9246
+ input.dispatch_records,
9247
+ )
9248
+ const inputDispositionsResult = deriveInputDispositions(
9249
+ input.prepared,
9250
+ input.reconciled,
9251
+ reviewerIndex,
9252
+ unavailablePersonas,
9253
+ )
9254
+ if (!inputDispositionsResult.ok) return inputDispositionsResult
9255
+ const dispositionCounts = computeDispositionCounts(
9256
+ inputDispositionsResult.value,
9257
+ input.rejected_payloads,
9258
+ )
9259
+ const { preExistingFindings, newFindings, queues } = partitionFindings(
9260
+ input.reconciled,
9261
+ )
9262
+ return {
9263
+ ok: true,
9264
+ value: {
9265
+ input_dispositions: inputDispositionsResult.value,
9266
+ disposition_counts: dispositionCounts,
9267
+ pre_existing_findings: preExistingFindings,
9268
+ new_findings: newFindings,
9269
+ queues,
9270
+ },
9271
+ }
9272
+ }
9273
+ function buildSurvivingReviewerIndex(prepared) {
9274
+ const index = new Map()
9275
+ for (const finding of prepared.surviving_findings) {
9276
+ index.set(finding.input_id, finding.reviewer)
9277
+ }
9278
+ return index
9279
+ }
9280
+ function buildRequestedUncertainFindingIds(reconciled) {
9281
+ return new Set(
9282
+ reconciled.lifecycle_failures.map((failure) => failure.finding_id),
9283
+ )
9284
+ }
9285
+ function findingOwners(finding, survivingReviewerIndex) {
9286
+ const owners = new Set()
9287
+ for (const inputId of finding.input_finding_ids) {
9288
+ const reviewer = survivingReviewerIndex.get(inputId)
9289
+ if (reviewer !== undefined) owners.add(reviewer)
9290
+ }
9291
+ return owners
9292
+ }
9293
+ function isValidationBandEligible(finding, requestedUncertainFindingIds) {
9294
+ if (finding.validated === true) return true
9295
+ if (finding.validated === false) return false
9296
+ return !requestedUncertainFindingIds.has(finding.finding_id)
9297
+ }
9298
+ function isEligibleRiskCoverageCandidate(
9299
+ finding,
9300
+ lostPersona,
9301
+ normalizedSurface,
9302
+ survivingReviewerIndex,
9303
+ requestedUncertainFindingIds,
9304
+ ) {
9305
+ if (finding.validated === false) return false
9306
+ if (!normalizedSurface.has(normalizeRepoRelativePath(finding.file))) {
9307
+ return false
9308
+ }
9309
+ const owners = findingOwners(finding, survivingReviewerIndex)
9310
+ const hasCrossPersonaOwner = [...owners].some(
9311
+ (owner) => owner !== lostPersona,
9312
+ )
9313
+ if (!hasCrossPersonaOwner) return false
9314
+ return isValidationBandEligible(finding, requestedUncertainFindingIds)
9315
+ }
9316
+ function citedInputIdForLostPersona(
9317
+ finding,
9318
+ lostPersona,
9319
+ survivingReviewerIndex,
9320
+ ) {
9321
+ const crossPersonaInputIds = finding.input_finding_ids.filter((inputId) => {
9322
+ const reviewer = survivingReviewerIndex.get(inputId)
9323
+ return reviewer !== undefined && reviewer !== lostPersona
9324
+ })
9325
+ if (crossPersonaInputIds.length === 0) return
9326
+ return [...crossPersonaInputIds].sort(compareStrings)[0]
9327
+ }
9328
+ function deriveCoverageForLostPersona(
9329
+ lostPersona,
9330
+ reconciled,
9331
+ survivingReviewerIndex,
9332
+ requestedUncertainFindingIds,
9333
+ ) {
9334
+ const normalizedSurface = new Set(
9335
+ lostPersona.selection_surface.map(normalizeRepoRelativePath),
9336
+ )
9337
+ const eligible = reconciled.findings
9338
+ .filter((finding) =>
9339
+ isEligibleRiskCoverageCandidate(
9340
+ finding,
9341
+ lostPersona.persona,
9342
+ normalizedSurface,
9343
+ survivingReviewerIndex,
9344
+ requestedUncertainFindingIds,
9345
+ ),
9346
+ )
9347
+ .sort(compareMergedFindingAssembly)
9348
+ for (const candidate of eligible) {
9349
+ const citedInputId = citedInputIdForLostPersona(
9350
+ candidate,
9351
+ lostPersona.persona,
9352
+ survivingReviewerIndex,
9353
+ )
9354
+ if (citedInputId !== undefined) {
9355
+ return {
9356
+ persona: lostPersona.persona,
9357
+ satisfied: true,
9358
+ finding_id: candidate.finding_id,
9359
+ input_finding_id: citedInputId,
9360
+ }
9361
+ }
9362
+ }
9363
+ return { persona: lostPersona.persona, satisfied: false }
9364
+ }
9365
+ function deriveRiskCoverage(input) {
9366
+ const survivingReviewerIndex = buildSurvivingReviewerIndex(input.prepared)
9367
+ const requestedUncertainFindingIds = buildRequestedUncertainFindingIds(
9368
+ input.reconciled,
9369
+ )
9370
+ return input.lost_risk_critical_personas
9371
+ .map((lostPersona) =>
9372
+ deriveCoverageForLostPersona(
9373
+ lostPersona,
9374
+ input.reconciled,
9375
+ survivingReviewerIndex,
9376
+ requestedUncertainFindingIds,
9377
+ ),
9378
+ )
9379
+ .sort((a, b) => compareStrings(a.persona, b.persona))
9380
+ }
9381
+ function routePlanAssessment(input) {
9382
+ const residualActionableWork = []
9383
+ const advisoryOutputs = []
9384
+ for (const result of input.results) {
9385
+ if (result.kind === 'explicit_unmet_requirement') {
9386
+ residualActionableWork.push(result.description)
9387
+ } else {
9388
+ advisoryOutputs.push(result.description)
9389
+ }
9390
+ }
9391
+ residualActionableWork.sort(compareStrings)
9392
+ advisoryOutputs.sort(compareStrings)
9393
+ return {
9394
+ residual_actionable_work: residualActionableWork,
9395
+ advisory_outputs: advisoryOutputs,
9396
+ gated_by_explicit_unmet_requirement: residualActionableWork.length > 0,
9397
+ }
9398
+ }
9399
+ function deriveVerdict(planAssessment, riskCoverage, reconciled) {
9400
+ const blockingReasons = []
9401
+ for (const description of planAssessment.residual_actionable_work) {
9402
+ blockingReasons.push({
9403
+ kind: 'explicit_unmet_plan_requirement',
9404
+ description,
9405
+ })
9406
+ }
9407
+ for (const coverage of riskCoverage) {
9408
+ if (!coverage.satisfied) {
9409
+ blockingReasons.push({
9410
+ kind: 'unsatisfied_risk_coverage',
9411
+ persona: coverage.persona,
9412
+ })
9413
+ }
9414
+ }
9415
+ for (const failure of reconciled.lifecycle_failures) {
9416
+ blockingReasons.push({
9417
+ kind: 'degraded_validator_lifecycle',
9418
+ finding_id: failure.finding_id,
9419
+ outcome: failure.outcome,
9420
+ })
9421
+ }
9422
+ return {
9423
+ clean: blockingReasons.length === 0,
9424
+ blocking_reasons: blockingReasons,
9425
+ }
9426
+ }
9427
+ function runReviewPipeline(input) {
9428
+ const reconciled = reconcileValidatorResults({
9429
+ merge: input.merge,
9430
+ validator_lifecycle_results: input.validator_lifecycle_results,
9431
+ })
9432
+ if (!reconciled.ok) return reconciled
9433
+ const finalized = finalizeReviewDispositions({
9434
+ prepared: input.prepared,
9435
+ reconciled: reconciled.value,
9436
+ rejected_payloads: input.rejected_payloads,
9437
+ screen_results: input.screen_results,
9438
+ dispatch_records: input.dispatch_records,
9439
+ })
9440
+ if (!finalized.ok) return finalized
9441
+ const riskCoverage = deriveRiskCoverage({
9442
+ lost_risk_critical_personas: input.lost_risk_critical_personas,
9443
+ prepared: input.prepared,
9444
+ reconciled: reconciled.value,
9445
+ })
9446
+ const planAssessment = routePlanAssessment(input.plan_assessment)
9447
+ const verdict = deriveVerdict(planAssessment, riskCoverage, reconciled.value)
9448
+ return {
9449
+ ok: true,
9450
+ value: {
9451
+ reconciled: reconciled.value,
9452
+ finalized: finalized.value,
9453
+ risk_coverage: riskCoverage,
9454
+ plan_assessment: planAssessment,
9455
+ verdict,
9456
+ },
9457
+ }
9458
+ }
9459
+ var LEDGER_ADMITTED_REASON =
9460
+ 'This input finding passed synthesis and was carried into the run.'
9461
+ var LEDGER_FILTERED_FALLBACK_REASON =
9462
+ 'A validator disproved the synthesized finding this input contributed to.'
9463
+ function buildAdmittedReviewerIndex(prepared, screenResults) {
9464
+ const index = new Map()
9465
+ for (const finding of prepared.surviving_findings) {
9466
+ index.set(finding.input_id, finding.reviewer)
9467
+ }
9468
+ for (const result of screenResults) {
9469
+ for (const finding of result.result.admitted_findings) {
9470
+ if (!index.has(finding.input_id)) {
9471
+ index.set(finding.input_id, result.reviewer)
9472
+ }
9473
+ }
9474
+ }
9475
+ return index
9476
+ }
9477
+ function buildConfidenceReasonIndex(prepared) {
9478
+ const index = new Map()
9479
+ for (const entry of prepared.confidence_dispositions) {
9480
+ if (entry.disposition === 'suppressed' && entry.reason !== undefined) {
9481
+ index.set(entry.input_id, entry.reason)
9482
+ }
9483
+ }
9484
+ return index
9485
+ }
9486
+ function buildFilteredReasonIndex(reconciled) {
9487
+ const index = new Map()
9488
+ for (const finding of reconciled.findings) {
9489
+ if (
9490
+ finding.validated !== false ||
9491
+ finding.validation_reason === undefined
9492
+ ) {
9493
+ continue
9494
+ }
9495
+ for (const inputId of finding.input_finding_ids) {
9496
+ index.set(inputId, finding.validation_reason)
9497
+ }
9498
+ }
9499
+ return index
9500
+ }
9501
+ function buildValidationUnavailablePersonas(dispatchRecords) {
9502
+ return new Set(
9503
+ dispatchRecords
9504
+ .filter((record) => record.dispatch_outcome === 'validation_unavailable')
9505
+ .map((record) => record.persona),
9506
+ )
9507
+ }
9508
+ function admittedLedgerReason(
9509
+ inputId,
9510
+ disposition,
9511
+ confidenceReasons,
9512
+ filteredReasons,
9513
+ ) {
9514
+ if (disposition === 'suppressed') {
9515
+ return confidenceReasons.get(inputId) ?? CONFIDENCE_GATE_SUPPRESSED_REASON
9516
+ }
9517
+ if (disposition === 'filtered') {
9518
+ return filteredReasons.get(inputId) ?? LEDGER_FILTERED_FALLBACK_REASON
9519
+ }
9520
+ return LEDGER_ADMITTED_REASON
9521
+ }
9522
+ function buildAdmittedLedgerRows(input, unavailablePersonas) {
9523
+ const reviewerIndex = buildAdmittedReviewerIndex(
9524
+ input.prepared,
9525
+ input.screen_results,
9526
+ )
9527
+ const dispositionIndex = new Map(
9528
+ input.finalized.input_dispositions.map((entry) => [entry.input_id, entry]),
9529
+ )
9530
+ const confidenceReasons = buildConfidenceReasonIndex(input.prepared)
9531
+ const filteredReasons = buildFilteredReasonIndex(input.reconciled)
9532
+ const rows = []
9533
+ for (const entry of input.prepared.confidence_dispositions) {
9534
+ const reviewer = reviewerIndex.get(entry.input_id)
9535
+ if (reviewer === undefined) {
9536
+ throw new Error(
9537
+ 'buildInputLedger: confidence disposition has no resolvable reviewer',
9538
+ )
9539
+ }
9540
+ if (unavailablePersonas.has(reviewer)) continue
9541
+ const finalDisposition = dispositionIndex.get(entry.input_id)?.disposition
9542
+ if (finalDisposition === undefined) continue
9543
+ rows.push({
9544
+ record_type: 'admitted',
9545
+ input_id: entry.input_id,
9546
+ reviewer,
9547
+ confidence: entry.confidence,
9548
+ disposition: finalDisposition,
9549
+ reason: admittedLedgerReason(
9550
+ entry.input_id,
9551
+ finalDisposition,
9552
+ confidenceReasons,
9553
+ filteredReasons,
9554
+ ),
9555
+ })
9556
+ }
9557
+ return [...rows].sort((a, b) => compareStrings(a.input_id, b.input_id))
9558
+ }
9559
+ function buildRejectedLedgerRows(screenResults, unavailablePersonas) {
9560
+ const rows = []
9561
+ for (const result of screenResults) {
9562
+ if (unavailablePersonas.has(result.reviewer)) continue
9563
+ const summary = result.result.rejected_summary
9564
+ if (!summary) continue
9565
+ rows.push({
9566
+ record_type: 'rejected_summary',
9567
+ reviewer: result.reviewer,
9568
+ dispatch_outcome: summary.dispatch_outcome,
9569
+ rejected_finding_count: summary.rejected_finding_count,
9570
+ rejected_severities: summary.rejected_severities,
9571
+ disposition: 'rejected',
9572
+ reason: summary.reason,
9573
+ })
9574
+ }
9575
+ return [...rows].sort((a, b) => compareStrings(a.reviewer, b.reviewer))
9576
+ }
9577
+ function buildInputLedger(input) {
9578
+ const unavailablePersonas = buildValidationUnavailablePersonas(
9579
+ input.dispatch_records,
9580
+ )
9581
+ return [
9582
+ ...buildAdmittedLedgerRows(input, unavailablePersonas),
9583
+ ...buildRejectedLedgerRows(input.screen_results, unavailablePersonas),
9584
+ ]
9585
+ }
9586
+ function dedupeSortedStrings(values) {
9587
+ return [...new Set(values)].sort(compareStrings)
9588
+ }
9589
+ function checkCoverageArrayBound(field, values) {
9590
+ if (values.length <= MAX_PERSONAS) return
9591
+ return {
9592
+ path: formatReviewArtifactIssuePath(['coverage', field]),
9593
+ reason: 'coverage array exceeds bound',
9594
+ }
9595
+ }
9596
+ function buildReviewCoverage(input) {
9597
+ const residualRisks = dedupeSortedStrings(
9598
+ input.screen_results.flatMap((result) => result.result.residual_risks),
9599
+ )
9600
+ const testingGaps = dedupeSortedStrings(
9601
+ input.screen_results.flatMap((result) => result.result.testing_gaps),
9602
+ )
9603
+ const failedReviewers = dedupeSortedStrings(
9604
+ input.dispatch_records
9605
+ .filter((record) =>
9606
+ FINALIZE_CONTEXT_LOSS_DISPATCH_OUTCOMES.has(record.dispatch_outcome),
9607
+ )
9608
+ .map((record) => record.persona),
9609
+ )
9610
+ const validatorFailures = input.reconciled.lifecycle_failures.map(
9611
+ (failure) => failure.reason,
9612
+ )
9613
+ const intentUncertainty = [...input.merge.disagreement_facts]
9614
+ const bounded = [
9615
+ ['residual_risks', residualRisks],
9616
+ ['testing_gaps', testingGaps],
9617
+ ['failed_reviewers', failedReviewers],
9618
+ ['validator_failures', validatorFailures],
9619
+ ['intent_uncertainty', intentUncertainty],
9620
+ ]
9621
+ for (const [field, values] of bounded) {
9622
+ const violation = checkCoverageArrayBound(field, values)
9623
+ if (violation) return { ok: false, rejection: violation }
9624
+ }
9625
+ return {
9626
+ ok: true,
9627
+ value: {
9628
+ reviewers: input.dispatch_records.length,
9629
+ validators: input.validator_lifecycle_results.length,
9630
+ residual_risks: residualRisks,
9631
+ testing_gaps: testingGaps,
9632
+ failed_reviewers: failedReviewers,
9633
+ validator_failures: validatorFailures,
9634
+ intent_uncertainty: intentUncertainty,
9635
+ },
9636
+ }
9637
+ }
9638
+ function projectOneSynthesizedFinding(finding) {
9639
+ return {
9640
+ title: finding.title,
9641
+ severity: finding.severity,
9642
+ file: finding.file,
9643
+ line: finding.line,
9644
+ why_it_matters: finding.why_it_matters,
9645
+ autofix_class: finding.autofix_class,
9646
+ owner: finding.owner,
9647
+ requires_verification: finding.requires_verification,
9648
+ confidence: finding.confidence,
9649
+ evidence: finding.evidence,
9650
+ pre_existing: finding.pre_existing,
9651
+ ...(finding.suggested_fix !== undefined
9652
+ ? { suggested_fix: finding.suggested_fix }
9653
+ : {}),
9654
+ ...(finding.validated !== undefined
9655
+ ? { validated: finding.validated }
9656
+ : {}),
9657
+ ...(finding.validation_reason !== undefined
9658
+ ? { validation_reason: finding.validation_reason }
9659
+ : {}),
9660
+ input_finding_ids: finding.input_finding_ids,
9661
+ provenance: {
9662
+ fingerprint: finding.fingerprint,
9663
+ submitters: finding.submitters,
9664
+ agreement_credit: finding.agreement_credit ?? [],
9665
+ },
9666
+ }
9667
+ }
9668
+ function projectSynthesizedFindings(input) {
9669
+ return input.findings.map((finding) => projectOneSynthesizedFinding(finding))
9670
+ }
9671
+ var ARTIFACT_NON_CLEAN_VERDICT =
9672
+ 'Review did not reach a clean verdict; see blocking reasons and coverage for detail.'
9673
+ function deriveArtifactRunStatus(
9674
+ reconciledDegraded,
9675
+ dispatchRecords,
9676
+ lostRiskCriticalPersonas,
9677
+ ) {
9678
+ if (reconciledDegraded) return 'degraded'
9679
+ if (lostRiskCriticalPersonas.length > 0) return 'degraded'
9680
+ const hasFailedReviewer = dispatchRecords.some((record) =>
9681
+ FINALIZE_CONTEXT_LOSS_DISPATCH_OUTCOMES.has(record.dispatch_outcome),
9682
+ )
9683
+ return hasFailedReviewer ? 'degraded' : 'completed'
9684
+ }
9685
+ function deriveArtifactVerdictText(
9686
+ planAssessmentVerdict,
9687
+ runVerdict,
9688
+ runStatus,
9689
+ ) {
9690
+ if (runVerdict.clean && runStatus === 'completed') {
9691
+ return planAssessmentVerdict
9692
+ }
9693
+ return ARTIFACT_NON_CLEAN_VERDICT
9694
+ }
9695
+ function buildScreenResultIndex(screenResults) {
9696
+ const index = new Map()
9697
+ for (const result of screenResults) {
9698
+ index.set(result.reviewer, result)
9699
+ }
9700
+ return index
9701
+ }
9702
+ function buildDispatchEntry(record, screenByReviewer) {
9703
+ const screenResult = screenByReviewer.get(record.persona)
9704
+ const inputFindingCount =
9705
+ record.dispatch_outcome === 'validation_unavailable'
9706
+ ? 0
9707
+ : (screenResult?.result.admitted_findings.length ?? 0)
9708
+ const rejectionReason = screenResult?.result.rejected_summary?.reason
9709
+ const selectionSurface = record.selection_surface
9710
+ const selectionReason = record.selection_reason
9711
+ return {
9712
+ persona: record.persona,
9713
+ dispatch_outcome: record.dispatch_outcome,
9714
+ input_finding_count: inputFindingCount,
9715
+ ...(rejectionReason !== undefined
9716
+ ? { rejection_reason: rejectionReason }
9717
+ : {}),
9718
+ ...(selectionSurface !== undefined && selectionSurface.length > 0
9719
+ ? { selection_surface: selectionSurface }
9720
+ : {}),
9721
+ ...(selectionReason !== undefined
9722
+ ? { selection_reason: selectionReason }
9723
+ : {}),
9724
+ }
9725
+ }
9726
+ function buildArtifactDispatches(dispatchRecords, screenByReviewer) {
9727
+ return [...dispatchRecords]
9728
+ .map((record) => buildDispatchEntry(record, screenByReviewer))
9729
+ .sort((a, b) => compareStrings(a.persona, b.persona))
9730
+ }
9731
+ function checkRiskCoverageSemantics(artifactCandidate) {
9732
+ const coverage = artifactCandidate.risk_coverage
9733
+ if (coverage === undefined) return { ok: true }
9734
+ for (const [coverageIndex, entry] of coverage.entries()) {
9735
+ if (!entry.satisfied || entry.input_finding_id === undefined) continue
9736
+ const citedId = entry.input_finding_id
9737
+ const dispatch = artifactCandidate.dispatches.find(
9738
+ (record) => record.persona === entry.persona,
9739
+ )
9740
+ const normalizedSurface = new Set(
9741
+ (dispatch?.selection_surface ?? []).map(normalizeRepoRelativePath),
9742
+ )
9743
+ const covered = artifactCandidate.findings.some((finding) => {
9744
+ if (!finding.input_finding_ids.includes(citedId)) return false
9745
+ const inValidationBand =
9746
+ finding.severity === 'P0' ||
9747
+ finding.severity === 'P1' ||
9748
+ finding.requires_verification
9749
+ const validationSatisfied = inValidationBand
9750
+ ? finding.validated === true
9751
+ : finding.validated !== false
9752
+ if (!validationSatisfied) return false
9753
+ return normalizedSurface.has(normalizeRepoRelativePath(finding.file))
9754
+ })
9755
+ if (!covered) {
9756
+ return {
9757
+ ok: false,
9758
+ rejection: {
9759
+ path: formatReviewArtifactIssuePath([
9760
+ 'risk_coverage',
9761
+ coverageIndex,
9762
+ 'input_finding_id',
9763
+ ]),
9764
+ reason:
9765
+ 'satisfied risk coverage must cite a validated finding on the lost persona selection surface',
9766
+ },
9767
+ }
9768
+ }
9769
+ }
9770
+ return { ok: true }
9771
+ }
9772
+ function checkDispositionCountsReconcileLedger(dispositionCounts, ledger) {
9773
+ const admittedLedgerRowCount = ledger.filter(
9774
+ (row) => row.record_type === 'admitted',
9775
+ ).length
9776
+ const dispositionAdmittedSum =
9777
+ dispositionCounts.surviving +
9778
+ dispositionCounts.merged +
9779
+ dispositionCounts.suppressed +
9780
+ dispositionCounts.filtered
9781
+ if (dispositionAdmittedSum !== admittedLedgerRowCount) {
9782
+ return {
9783
+ ok: false,
9784
+ rejection: {
9785
+ path: formatReviewArtifactIssuePath(['disposition_counts']),
9786
+ reason:
9787
+ 'disposition counts do not reconcile with the admitted input ledger',
9788
+ },
9789
+ }
9790
+ }
9791
+ return { ok: true }
9792
+ }
9793
+ function projectRiskCoverage(riskCoverage) {
9794
+ if (riskCoverage.length === 0) return
9795
+ return riskCoverage.map((entry) => ({
9796
+ persona: entry.persona,
9797
+ satisfied: entry.satisfied,
9798
+ ...(entry.input_finding_id !== undefined
9799
+ ? { input_finding_id: entry.input_finding_id }
9800
+ : {}),
9801
+ }))
9802
+ }
9803
+ function buildReportProjection(
9804
+ verdictText,
9805
+ findings,
9806
+ appliedFixes,
9807
+ pipelineOutput,
9808
+ coverage,
9809
+ riskCoverage,
9810
+ ) {
9811
+ return {
9812
+ verdict: verdictText,
9813
+ findings,
9814
+ applied_fixes: appliedFixes,
9815
+ residual_actionable_work:
9816
+ pipelineOutput.plan_assessment.residual_actionable_work,
9817
+ advisory_outputs: pipelineOutput.plan_assessment.advisory_outputs,
9818
+ coverage,
9819
+ input_dispositions: pipelineOutput.finalized.input_dispositions,
9820
+ disposition_counts: pipelineOutput.finalized.disposition_counts,
9821
+ queues: pipelineOutput.finalized.queues,
9822
+ pre_existing_findings: pipelineOutput.finalized.pre_existing_findings,
9823
+ ...(riskCoverage !== undefined ? { risk_coverage: riskCoverage } : {}),
9824
+ }
9825
+ }
9826
+ function parseFinalizeOutput(output) {
9827
+ const parsed = FinalizeOutputSchema.safeParse(output)
9828
+ if (!parsed.success) {
9829
+ const issue = parsed.error.issues[0]
9830
+ return {
9831
+ ok: false,
9832
+ rejection: {
9833
+ path: issue
9834
+ ? formatReviewArtifactIssuePath(issue.path)
9835
+ : JSON_ROOT_PATH,
9836
+ reason: 'finalize output failed schema validation',
9837
+ },
9838
+ }
9839
+ }
9840
+ return { ok: true, value: parsed.data }
9841
+ }
9842
+ function finalizeReview(input) {
9843
+ const context = deriveFinalizeContext({
9844
+ merge: input.merge,
9845
+ prepared: input.prepared,
9846
+ screen_results: input.screen_results,
9847
+ dispatch_records: input.dispatch_records,
9848
+ parent_run_metadata: {
9849
+ selected_dispatches: input.parent_run_metadata.selected_dispatches,
9850
+ validation: input.parent_run_metadata.validation,
9851
+ },
9852
+ })
9853
+ if (!context.ok) return context
9854
+ const pipeline = runReviewPipeline({
9855
+ merge: input.merge,
9856
+ validator_lifecycle_results: input.validator_lifecycle_results,
9857
+ prepared: input.prepared,
9858
+ rejected_payloads: context.value.rejected_payloads,
9859
+ lost_risk_critical_personas: context.value.lost_risk_critical_personas,
9860
+ plan_assessment: input.plan_assessment,
9861
+ screen_results: input.screen_results,
9862
+ dispatch_records: input.dispatch_records,
9863
+ })
9864
+ if (!pipeline.ok) return pipeline
9865
+ const coverage = buildReviewCoverage({
9866
+ dispatch_records: input.dispatch_records,
9867
+ validator_lifecycle_results: input.validator_lifecycle_results,
9868
+ screen_results: input.screen_results,
9869
+ reconciled: pipeline.value.reconciled,
9870
+ merge: input.merge,
9871
+ })
9872
+ if (!coverage.ok) return coverage
9873
+ const findings = projectSynthesizedFindings({
9874
+ findings: pipeline.value.reconciled.findings,
9875
+ })
9876
+ const runStatus = deriveArtifactRunStatus(
9877
+ pipeline.value.reconciled.degraded,
9878
+ input.dispatch_records,
9879
+ context.value.lost_risk_critical_personas,
9880
+ )
9881
+ const verdictText = deriveArtifactVerdictText(
9882
+ input.plan_assessment.verdict,
9883
+ pipeline.value.verdict,
9884
+ runStatus,
9885
+ )
9886
+ const screenByReviewer = buildScreenResultIndex(input.screen_results)
9887
+ const dispatches = buildArtifactDispatches(
9888
+ input.dispatch_records,
9889
+ screenByReviewer,
9890
+ )
9891
+ const riskCoverage = projectRiskCoverage(pipeline.value.risk_coverage)
9892
+ const riskCoverageSemantics = checkRiskCoverageSemantics({
9893
+ dispatches,
9894
+ findings,
9895
+ risk_coverage: riskCoverage,
9896
+ })
9897
+ if (!riskCoverageSemantics.ok) return riskCoverageSemantics
9898
+ const report = buildReportProjection(
9899
+ verdictText,
9900
+ findings,
9901
+ input.parent_run_metadata.applied_fixes,
9902
+ pipeline.value,
9903
+ coverage.value,
9904
+ riskCoverage,
9905
+ )
9906
+ if (input.parent_run_metadata.mode === 'report-only') {
9907
+ return parseFinalizeOutput({ kind: 'report_only', ...report })
9908
+ }
9909
+ const ledger = buildInputLedger({
9910
+ prepared: input.prepared,
9911
+ screen_results: input.screen_results,
9912
+ dispatch_records: input.dispatch_records,
9913
+ finalized: pipeline.value.finalized,
9914
+ reconciled: pipeline.value.reconciled,
9915
+ })
9916
+ const dispositionReconciliation = checkDispositionCountsReconcileLedger(
9917
+ pipeline.value.finalized.disposition_counts,
9918
+ ledger,
9919
+ )
9920
+ if (!dispositionReconciliation.ok) return dispositionReconciliation
9921
+ const artifact = {
9922
+ schema_version: 1,
9923
+ run_id: input.parent_run_metadata.run_id,
9924
+ branch: input.parent_run_metadata.branch,
9925
+ head_sha: input.parent_run_metadata.head_sha,
9926
+ mode: input.parent_run_metadata.mode,
9927
+ harness: input.parent_run_metadata.harness,
9928
+ run_status: runStatus,
9929
+ verdict: verdictText,
9930
+ completed_at: input.parent_run_metadata.timestamps.completed_at,
9931
+ dispatches,
9932
+ input_findings: ledger,
9933
+ findings,
9934
+ disposition_counts: pipeline.value.finalized.disposition_counts,
9935
+ applied_fixes: input.parent_run_metadata.applied_fixes,
9936
+ residual_actionable_work:
9937
+ pipeline.value.plan_assessment.residual_actionable_work,
9938
+ advisory_outputs: pipeline.value.plan_assessment.advisory_outputs,
9939
+ coverage: coverage.value,
9940
+ validation: input.parent_run_metadata.validation,
9941
+ ...(riskCoverage !== undefined ? { risk_coverage: riskCoverage } : {}),
9942
+ }
9943
+ const parsedArtifact = ReviewArtifactSchema.safeParse(artifact)
9944
+ if (!parsedArtifact.success) {
9945
+ const issue = parsedArtifact.error.issues[0]
9946
+ return {
9947
+ ok: false,
9948
+ rejection: {
9949
+ path: issue
9950
+ ? formatReviewArtifactIssuePath(issue.path)
9951
+ : JSON_ROOT_PATH,
9952
+ reason: 'artifact failed schema validation',
9953
+ },
9954
+ }
9955
+ }
9956
+ return parseFinalizeOutput({
9957
+ kind: 'writing',
9958
+ artifact: parsedArtifact.data,
9959
+ report,
9960
+ })
9961
+ }
9962
+
9963
+ // src/ce-review-validator.ts
9964
+ var CE_REVIEW_VALIDATOR_USAGE =
9965
+ 'Usage: node validate-review.mjs <return|artifact|screen|prepare|merge|finalize> [...]'
9966
+ var CE_REVIEW_SCREEN_USAGE =
9967
+ 'Usage: node validate-review.mjs screen --reviewer <name> --harness <opencode|pi|claude-code>'
9968
+ var CE_REVIEW_SCREEN_STDIN_TTY_MESSAGE =
9969
+ 'screen reads one raw reviewer return from stdin; interactive input is not supported'
9970
+ var CE_REVIEW_SCREEN_STDIN_READ_FAILED_MESSAGE =
9971
+ 'screen could not read the reviewer return from stdin'
9972
+ var CE_REVIEW_SCREEN_STDIN_OVERSIZED_MESSAGE =
9973
+ 'screen input exceeds the 1 MiB limit'
9974
+ var CE_REVIEW_SCREEN_STDIN_INVALID_UTF8_MESSAGE =
9975
+ 'screen input is not valid UTF-8'
9976
+ var CE_REVIEW_SCREEN_STDIN_EMPTY_MESSAGE = 'screen received empty stdin'
9977
+ var CE_REVIEW_SCREEN_REJECTED_MESSAGE = 'screen rejected the reviewer return'
9978
+ var CE_REVIEW_SCREEN_INTERNAL_ERROR_MESSAGE =
9979
+ 'ce-review-validator: internal error'
9980
+ var CE_REVIEW_PREPARE_USAGE = 'Usage: node validate-review.mjs prepare'
9981
+ var CE_REVIEW_PREPARE_STDIN_TTY_MESSAGE =
9982
+ 'prepare reads one aggregate JSON envelope from stdin; interactive input is not supported'
9983
+ var CE_REVIEW_PREPARE_STDIN_READ_FAILED_MESSAGE =
9984
+ 'prepare could not read the aggregate envelope from stdin'
9985
+ var CE_REVIEW_PREPARE_STDIN_OVERSIZED_MESSAGE =
9986
+ 'prepare input exceeds the aggregate byte cap'
9987
+ var CE_REVIEW_PREPARE_STDIN_INVALID_UTF8_MESSAGE =
9988
+ 'prepare input is not valid UTF-8'
9989
+ var CE_REVIEW_PREPARE_STDIN_EMPTY_MESSAGE = 'prepare received empty stdin'
9990
+ var CE_REVIEW_PREPARE_REJECTED_MESSAGE =
9991
+ 'prepare rejected the aggregate envelope'
9992
+ var CE_REVIEW_MERGE_USAGE = 'Usage: node validate-review.mjs merge'
9993
+ var CE_REVIEW_MERGE_STDIN_TTY_MESSAGE =
9994
+ 'merge reads one aggregate JSON envelope from stdin; interactive input is not supported'
9995
+ var CE_REVIEW_MERGE_STDIN_READ_FAILED_MESSAGE =
9996
+ 'merge could not read the aggregate envelope from stdin'
9997
+ var CE_REVIEW_MERGE_STDIN_OVERSIZED_MESSAGE =
9998
+ 'merge input exceeds the aggregate byte cap'
9999
+ var CE_REVIEW_MERGE_STDIN_INVALID_UTF8_MESSAGE =
10000
+ 'merge input is not valid UTF-8'
10001
+ var CE_REVIEW_MERGE_STDIN_EMPTY_MESSAGE = 'merge received empty stdin'
10002
+ var CE_REVIEW_MERGE_REJECTED_MESSAGE = 'merge rejected the aggregate envelope'
10003
+ var CE_REVIEW_FINALIZE_USAGE = 'Usage: node validate-review.mjs finalize'
10004
+ var CE_REVIEW_FINALIZE_STDIN_TTY_MESSAGE =
10005
+ 'finalize reads one aggregate JSON envelope from stdin; interactive input is not supported'
10006
+ var CE_REVIEW_FINALIZE_STDIN_READ_FAILED_MESSAGE =
10007
+ 'finalize could not read the aggregate envelope from stdin'
10008
+ var CE_REVIEW_FINALIZE_STDIN_OVERSIZED_MESSAGE =
10009
+ 'finalize input exceeds the aggregate byte cap'
10010
+ var CE_REVIEW_FINALIZE_STDIN_INVALID_UTF8_MESSAGE =
10011
+ 'finalize input is not valid UTF-8'
10012
+ var CE_REVIEW_FINALIZE_STDIN_EMPTY_MESSAGE = 'finalize received empty stdin'
10013
+ var CE_REVIEW_FINALIZE_REJECTED_MESSAGE =
10014
+ 'finalize rejected the aggregate envelope'
10015
+ var SCREEN_FLAGS = ['--reviewer', '--harness']
10016
+ function isScreenFlag(token) {
10017
+ return SCREEN_FLAGS.includes(token)
10018
+ }
10019
+ function parseScreenFlags(argv) {
10020
+ const values = new Map()
10021
+ let index = 0
10022
+ while (index < argv.length) {
10023
+ const token = argv[index]
10024
+ if (token === undefined) break
10025
+ if (!isScreenFlag(token)) return { ok: false }
10026
+ if (values.has(token)) return { ok: false }
10027
+ const value = argv[index + 1]
10028
+ if (value === undefined || value.startsWith('--')) return { ok: false }
10029
+ values.set(token, value)
10030
+ index += 2
10031
+ }
10032
+ const reviewer = values.get('--reviewer')
10033
+ const rawHarness = values.get('--harness')
10034
+ if (reviewer === undefined || rawHarness === undefined) return { ok: false }
10035
+ const harnessParse = HarnessSchema.safeParse(rawHarness)
10036
+ if (!harnessParse.success) return { ok: false }
10037
+ const harness = harnessParse.data
10038
+ if (!ScreenInputSchema.shape.expected_reviewer.safeParse(reviewer).success) {
10039
+ return { ok: false }
10040
+ }
10041
+ return { harness, ok: true, reviewer }
10042
+ }
10043
+ function formatAggregateRejectionMessage(rejectedMessage, rejection) {
10044
+ return `${rejectedMessage}: ${rejection.reason} at ${rejection.path}`
10045
+ }
10046
+ function runScreenSubcommand(options, outputSink, errorSink) {
10047
+ const flags = parseScreenFlags(options.argv.slice(1))
10048
+ if (!flags.ok) {
10049
+ errorSink(CE_REVIEW_SCREEN_USAGE)
10050
+ return 2
10051
+ }
10052
+ const fd = 0
10053
+ const isTTY = options.isTTY ?? process.stdin.isTTY === true
10054
+ if (isTTY) {
10055
+ errorSink(CE_REVIEW_SCREEN_STDIN_TTY_MESSAGE)
10056
+ return 2
10057
+ }
10058
+ const read = readBoundedStdin(fd, options.readChunk ?? defaultReadChunk)
10059
+ if (read.status === 'read-error') {
10060
+ errorSink(CE_REVIEW_SCREEN_STDIN_READ_FAILED_MESSAGE)
10061
+ return 2
10062
+ }
10063
+ if (read.status === 'oversized') {
10064
+ errorSink(CE_REVIEW_SCREEN_STDIN_OVERSIZED_MESSAGE)
10065
+ return 1
10066
+ }
10067
+ let text
10068
+ try {
10069
+ text = new TextDecoder('utf-8', { fatal: true }).decode(read.buffer)
10070
+ } catch {
10071
+ errorSink(CE_REVIEW_SCREEN_STDIN_INVALID_UTF8_MESSAGE)
10072
+ return 1
10073
+ }
10074
+ if (text.trim() === '') {
10075
+ errorSink(CE_REVIEW_SCREEN_STDIN_EMPTY_MESSAGE)
10076
+ return 2
10077
+ }
10078
+ const result = screenReviewReturn({
10079
+ expected_reviewer: flags.reviewer,
10080
+ invoking_harness: flags.harness,
10081
+ raw_return: text,
10082
+ })
10083
+ if (result.dispatch_outcome === 'malformed') {
10084
+ errorSink(
10085
+ result.rejected_summary?.reason ?? CE_REVIEW_SCREEN_REJECTED_MESSAGE,
10086
+ )
10087
+ return 1
10088
+ }
10089
+ outputSink(JSON.stringify(result))
10090
+ return 0
10091
+ }
10092
+ function runPrepareSubcommand(options, outputSink, errorSink) {
10093
+ if (options.argv.slice(1).length > 0) {
10094
+ errorSink(CE_REVIEW_PREPARE_USAGE)
10095
+ return 2
10096
+ }
10097
+ const fd = 0
10098
+ const isTTY = options.isTTY ?? process.stdin.isTTY === true
10099
+ if (isTTY) {
10100
+ errorSink(CE_REVIEW_PREPARE_STDIN_TTY_MESSAGE)
10101
+ return 2
10102
+ }
10103
+ const read = readBoundedStdin(
10104
+ fd,
10105
+ options.readChunk ?? defaultReadChunk,
10106
+ AGGREGATE_STDIN_BYTE_CAP,
10107
+ )
10108
+ if (read.status === 'read-error') {
10109
+ errorSink(CE_REVIEW_PREPARE_STDIN_READ_FAILED_MESSAGE)
10110
+ return 2
10111
+ }
10112
+ if (read.status === 'oversized') {
10113
+ errorSink(CE_REVIEW_PREPARE_STDIN_OVERSIZED_MESSAGE)
10114
+ return 1
10115
+ }
10116
+ let text
10117
+ try {
10118
+ text = new TextDecoder('utf-8', { fatal: true }).decode(read.buffer)
10119
+ } catch {
10120
+ errorSink(CE_REVIEW_PREPARE_STDIN_INVALID_UTF8_MESSAGE)
10121
+ return 1
10122
+ }
10123
+ if (text.trim() === '') {
10124
+ errorSink(CE_REVIEW_PREPARE_STDIN_EMPTY_MESSAGE)
10125
+ return 2
10126
+ }
10127
+ const result = prepareReviewCandidates({ raw_input: text })
10128
+ if (!result.ok) {
10129
+ errorSink(
10130
+ formatAggregateRejectionMessage(
10131
+ CE_REVIEW_PREPARE_REJECTED_MESSAGE,
10132
+ result.rejection,
10133
+ ),
10134
+ )
10135
+ return 1
10136
+ }
10137
+ outputSink(JSON.stringify(result.value))
10138
+ return 0
10139
+ }
10140
+ function runAggregateStdinSubcommand(options, outputSink, errorSink, spec) {
10141
+ if (options.argv.slice(1).length > 0) {
10142
+ errorSink(spec.usage)
10143
+ return 2
10144
+ }
10145
+ const fd = 0
10146
+ const isTTY = options.isTTY ?? process.stdin.isTTY === true
10147
+ if (isTTY) {
10148
+ errorSink(spec.ttyMessage)
10149
+ return 2
10150
+ }
10151
+ const read = readBoundedStdin(
10152
+ fd,
10153
+ options.readChunk ?? defaultReadChunk,
10154
+ AGGREGATE_STDIN_BYTE_CAP,
10155
+ )
10156
+ if (read.status === 'read-error') {
10157
+ errorSink(spec.readFailedMessage)
10158
+ return 2
10159
+ }
10160
+ if (read.status === 'oversized') {
10161
+ errorSink(spec.oversizedMessage)
10162
+ return 1
10163
+ }
10164
+ let text
10165
+ try {
10166
+ text = new TextDecoder('utf-8', { fatal: true }).decode(read.buffer)
10167
+ } catch {
10168
+ errorSink(spec.invalidUtf8Message)
10169
+ return 1
10170
+ }
10171
+ if (text.trim() === '') {
10172
+ errorSink(spec.emptyMessage)
10173
+ return 2
10174
+ }
10175
+ let value
10176
+ try {
10177
+ value = JSON.parse(text)
10178
+ } catch {
10179
+ errorSink(spec.rejectedMessage)
10180
+ return 1
10181
+ }
10182
+ const parsed = spec.schema.safeParse(value)
10183
+ if (!parsed.success) {
10184
+ const issue = parsed.error.issues[0]
10185
+ errorSink(
10186
+ issue
10187
+ ? formatAggregateRejectionMessage(spec.rejectedMessage, {
10188
+ path: formatReviewArtifactIssuePath(issue.path),
10189
+ reason: issue.code,
10190
+ })
10191
+ : spec.rejectedMessage,
10192
+ )
10193
+ return 1
10194
+ }
10195
+ const result = spec.execute(parsed.data)
10196
+ if (!result.ok) {
10197
+ errorSink(
10198
+ formatAggregateRejectionMessage(spec.rejectedMessage, result.rejection),
10199
+ )
10200
+ return 1
10201
+ }
10202
+ outputSink(JSON.stringify(result.value))
10203
+ return 0
10204
+ }
10205
+ function runMergeSubcommand(options, outputSink, errorSink) {
10206
+ return runAggregateStdinSubcommand(options, outputSink, errorSink, {
10207
+ emptyMessage: CE_REVIEW_MERGE_STDIN_EMPTY_MESSAGE,
10208
+ execute: (input) =>
10209
+ applyReviewAdjudication({
10210
+ prepared: input.prepared,
10211
+ decisions: input.adjudication.decisions,
10212
+ }),
10213
+ invalidUtf8Message: CE_REVIEW_MERGE_STDIN_INVALID_UTF8_MESSAGE,
10214
+ oversizedMessage: CE_REVIEW_MERGE_STDIN_OVERSIZED_MESSAGE,
10215
+ readFailedMessage: CE_REVIEW_MERGE_STDIN_READ_FAILED_MESSAGE,
10216
+ rejectedMessage: CE_REVIEW_MERGE_REJECTED_MESSAGE,
10217
+ schema: MergeInputSchema,
10218
+ ttyMessage: CE_REVIEW_MERGE_STDIN_TTY_MESSAGE,
10219
+ usage: CE_REVIEW_MERGE_USAGE,
10220
+ })
10221
+ }
10222
+ function runFinalizeSubcommand(options, outputSink, errorSink) {
10223
+ return runAggregateStdinSubcommand(options, outputSink, errorSink, {
10224
+ emptyMessage: CE_REVIEW_FINALIZE_STDIN_EMPTY_MESSAGE,
10225
+ execute: (input) => finalizeReview(input),
10226
+ invalidUtf8Message: CE_REVIEW_FINALIZE_STDIN_INVALID_UTF8_MESSAGE,
10227
+ oversizedMessage: CE_REVIEW_FINALIZE_STDIN_OVERSIZED_MESSAGE,
10228
+ readFailedMessage: CE_REVIEW_FINALIZE_STDIN_READ_FAILED_MESSAGE,
10229
+ rejectedMessage: CE_REVIEW_FINALIZE_REJECTED_MESSAGE,
10230
+ schema: FinalizeInputSchema,
10231
+ ttyMessage: CE_REVIEW_FINALIZE_STDIN_TTY_MESSAGE,
10232
+ usage: CE_REVIEW_FINALIZE_USAGE,
10233
+ })
10234
+ }
10235
+ var processExceptionBoundaryInstalled = false
10236
+ var activeInvocation = {
10237
+ errorSink: (message) => console.error(message),
10238
+ phase: 'unknown',
10239
+ }
10240
+ function formatInternalErrorMessage(phase) {
10241
+ return `ce-review-validator: internal error in ${phase}`
10242
+ }
10243
+ function installProcessExceptionBoundary() {
10244
+ if (processExceptionBoundaryInstalled) return
10245
+ processExceptionBoundaryInstalled = true
10246
+ const handleFatal = () => {
10247
+ activeInvocation.errorSink(
10248
+ formatInternalErrorMessage(activeInvocation.phase),
10249
+ )
10250
+ process.exitCode = 1
10251
+ }
10252
+ process.on('unhandledRejection', handleFatal)
10253
+ process.on('uncaughtException', handleFatal)
10254
+ }
10255
+ function runCeReviewValidator(options) {
10256
+ const outputSink = options.outputSink ?? ((message) => console.log(message))
10257
+ const errorSink = options.errorSink ?? ((message) => console.error(message))
10258
+ const subcommand = options.argv[0]
10259
+ activeInvocation = { errorSink, phase: subcommand ?? 'unknown' }
10260
+ installProcessExceptionBoundary()
10261
+ try {
10262
+ if (subcommand === 'return') {
10263
+ return runReviewReturnValidator({
10264
+ argv: [
10265
+ 'systematic',
10266
+ 'validate-review-return',
10267
+ ...options.argv.slice(1),
10268
+ ],
10269
+ isTTY: options.isTTY,
10270
+ readChunk: options.readChunk,
10271
+ outputSink,
10272
+ errorSink,
10273
+ })
10274
+ }
10275
+ if (subcommand === 'artifact') {
10276
+ return runClaudeCodeValidator({
10277
+ argv: options.argv.slice(1),
10278
+ cwd: options.cwd,
10279
+ outputSink,
10280
+ errorSink,
10281
+ })
10282
+ }
10283
+ if (subcommand === 'screen') {
10284
+ return runScreenSubcommand(options, outputSink, errorSink)
10285
+ }
10286
+ if (subcommand === 'prepare') {
10287
+ return runPrepareSubcommand(options, outputSink, errorSink)
10288
+ }
10289
+ if (subcommand === 'merge') {
10290
+ return runMergeSubcommand(options, outputSink, errorSink)
10291
+ }
10292
+ if (subcommand === 'finalize') {
10293
+ return runFinalizeSubcommand(options, outputSink, errorSink)
10294
+ }
10295
+ errorSink(CE_REVIEW_VALIDATOR_USAGE)
10296
+ return 2
10297
+ } catch {
10298
+ errorSink(formatInternalErrorMessage(activeInvocation.phase))
10299
+ return 1
10300
+ }
10301
+ }
10302
+ function resolveRealPath(candidate) {
10303
+ if (candidate === undefined) return
10304
+ try {
10305
+ return fs3.realpathSync(candidate)
10306
+ } catch {
10307
+ return
10308
+ }
10309
+ }
10310
+ var entryPath = resolveRealPath(process.argv[1])
10311
+ var modulePath = resolveRealPath(fileURLToPath(import.meta.url))
10312
+ var isMainModule =
10313
+ entryPath !== undefined &&
10314
+ modulePath !== undefined &&
10315
+ entryPath === modulePath
10316
+ if (isMainModule) {
10317
+ process.exitCode = runCeReviewValidator({ argv: process.argv.slice(2) })
10318
+ }
10319
+ export {
10320
+ CE_REVIEW_FINALIZE_REJECTED_MESSAGE,
10321
+ CE_REVIEW_FINALIZE_STDIN_EMPTY_MESSAGE,
10322
+ CE_REVIEW_FINALIZE_STDIN_INVALID_UTF8_MESSAGE,
10323
+ CE_REVIEW_FINALIZE_STDIN_OVERSIZED_MESSAGE,
10324
+ CE_REVIEW_FINALIZE_STDIN_READ_FAILED_MESSAGE,
10325
+ CE_REVIEW_FINALIZE_STDIN_TTY_MESSAGE,
10326
+ CE_REVIEW_FINALIZE_USAGE,
10327
+ CE_REVIEW_MERGE_REJECTED_MESSAGE,
10328
+ CE_REVIEW_MERGE_STDIN_EMPTY_MESSAGE,
10329
+ CE_REVIEW_MERGE_STDIN_INVALID_UTF8_MESSAGE,
10330
+ CE_REVIEW_MERGE_STDIN_OVERSIZED_MESSAGE,
10331
+ CE_REVIEW_MERGE_STDIN_READ_FAILED_MESSAGE,
10332
+ CE_REVIEW_MERGE_STDIN_TTY_MESSAGE,
10333
+ CE_REVIEW_MERGE_USAGE,
10334
+ CE_REVIEW_PREPARE_REJECTED_MESSAGE,
10335
+ CE_REVIEW_PREPARE_STDIN_EMPTY_MESSAGE,
10336
+ CE_REVIEW_PREPARE_STDIN_INVALID_UTF8_MESSAGE,
10337
+ CE_REVIEW_PREPARE_STDIN_OVERSIZED_MESSAGE,
10338
+ CE_REVIEW_PREPARE_STDIN_READ_FAILED_MESSAGE,
10339
+ CE_REVIEW_PREPARE_STDIN_TTY_MESSAGE,
10340
+ CE_REVIEW_PREPARE_USAGE,
10341
+ CE_REVIEW_SCREEN_INTERNAL_ERROR_MESSAGE,
10342
+ CE_REVIEW_SCREEN_REJECTED_MESSAGE,
10343
+ CE_REVIEW_SCREEN_STDIN_EMPTY_MESSAGE,
10344
+ CE_REVIEW_SCREEN_STDIN_INVALID_UTF8_MESSAGE,
10345
+ CE_REVIEW_SCREEN_STDIN_OVERSIZED_MESSAGE,
10346
+ CE_REVIEW_SCREEN_STDIN_READ_FAILED_MESSAGE,
10347
+ CE_REVIEW_SCREEN_STDIN_TTY_MESSAGE,
10348
+ CE_REVIEW_SCREEN_USAGE,
10349
+ CE_REVIEW_VALIDATOR_USAGE,
10350
+ runCeReviewValidator,
7196
10351
  }
7197
- export { CE_REVIEW_VALIDATOR_USAGE, runCeReviewValidator }