audit-tools 0.55.15 → 0.55.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/dist/audit/cli/auditStep.d.ts.map +1 -1
  2. package/dist/audit/cli/auditStep.js +4 -3
  3. package/dist/audit/cli/auditStep.js.map +1 -1
  4. package/dist/audit/cli/charterComparisonPrompt.d.ts.map +1 -1
  5. package/dist/audit/cli/charterComparisonPrompt.js +8 -1
  6. package/dist/audit/cli/charterComparisonPrompt.js.map +1 -1
  7. package/dist/audit/cli/conceptualDispatch.d.ts.map +1 -1
  8. package/dist/audit/cli/conceptualDispatch.js +9 -5
  9. package/dist/audit/cli/conceptualDispatch.js.map +1 -1
  10. package/dist/audit/cli/confirmIntentStep.d.ts.map +1 -1
  11. package/dist/audit/cli/confirmIntentStep.js +0 -1
  12. package/dist/audit/cli/confirmIntentStep.js.map +1 -1
  13. package/dist/audit/cli/dispatch/hostHandoff.d.ts +86 -1
  14. package/dist/audit/cli/dispatch/hostHandoff.d.ts.map +1 -1
  15. package/dist/audit/cli/dispatch/hostHandoff.js +460 -161
  16. package/dist/audit/cli/dispatch/hostHandoff.js.map +1 -1
  17. package/dist/audit/cli/fanoutLanes.d.ts +1 -1
  18. package/dist/audit/cli/fanoutLanes.d.ts.map +1 -1
  19. package/dist/audit/cli/fanoutLanes.js +4 -2
  20. package/dist/audit/cli/fanoutLanes.js.map +1 -1
  21. package/dist/audit/cli/nextStepCommand.d.ts.map +1 -1
  22. package/dist/audit/cli/nextStepCommand.js +17 -15
  23. package/dist/audit/cli/nextStepCommand.js.map +1 -1
  24. package/dist/audit/cli/nextStepHelpers.d.ts.map +1 -1
  25. package/dist/audit/cli/nextStepHelpers.js +4 -3
  26. package/dist/audit/cli/nextStepHelpers.js.map +1 -1
  27. package/dist/audit/cli/prompts.d.ts +2 -0
  28. package/dist/audit/cli/prompts.d.ts.map +1 -1
  29. package/dist/audit/cli/prompts.js +12 -1
  30. package/dist/audit/cli/prompts.js.map +1 -1
  31. package/dist/audit/cli/semanticReviewStep.d.ts.map +1 -1
  32. package/dist/audit/cli/semanticReviewStep.js +71 -6
  33. package/dist/audit/cli/semanticReviewStep.js.map +1 -1
  34. package/dist/audit/cli/submitCommand.d.ts +26 -0
  35. package/dist/audit/cli/submitCommand.d.ts.map +1 -0
  36. package/dist/audit/cli/submitCommand.js +79 -0
  37. package/dist/audit/cli/submitCommand.js.map +1 -0
  38. package/dist/audit/cli/validateResultsCommand.d.ts +11 -0
  39. package/dist/audit/cli/validateResultsCommand.d.ts.map +1 -1
  40. package/dist/audit/cli/validateResultsCommand.js +56 -4
  41. package/dist/audit/cli/validateResultsCommand.js.map +1 -1
  42. package/dist/audit/cli.d.ts.map +1 -1
  43. package/dist/audit/cli.js +4 -1
  44. package/dist/audit/cli.js.map +1 -1
  45. package/dist/audit/contracts/findingContractPrompt.d.ts +229 -0
  46. package/dist/audit/contracts/findingContractPrompt.d.ts.map +1 -1
  47. package/dist/audit/contracts/findingContractPrompt.js +31 -20
  48. package/dist/audit/contracts/findingContractPrompt.js.map +1 -1
  49. package/dist/audit/decompose/buildStructureDecomposition.d.ts +11 -5
  50. package/dist/audit/decompose/buildStructureDecomposition.d.ts.map +1 -1
  51. package/dist/audit/decompose/buildStructureDecomposition.js +17 -8
  52. package/dist/audit/decompose/buildStructureDecomposition.js.map +1 -1
  53. package/dist/audit/extractors/designAssessment.d.ts.map +1 -1
  54. package/dist/audit/extractors/designAssessment.js.map +1 -1
  55. package/dist/audit/extractors/graph.d.ts +1 -1
  56. package/dist/audit/extractors/graph.js +1 -1
  57. package/dist/audit/extractors/graphSignals.d.ts +8 -0
  58. package/dist/audit/extractors/graphSignals.d.ts.map +1 -1
  59. package/dist/audit/extractors/graphSignals.js +12 -1
  60. package/dist/audit/extractors/graphSignals.js.map +1 -1
  61. package/dist/audit/extractors/pathPatterns.d.ts +3 -0
  62. package/dist/audit/extractors/pathPatterns.d.ts.map +1 -1
  63. package/dist/audit/extractors/pathPatterns.js +9 -4
  64. package/dist/audit/extractors/pathPatterns.js.map +1 -1
  65. package/dist/audit/extractors/surfaces.d.ts.map +1 -1
  66. package/dist/audit/extractors/surfaces.js +6 -1
  67. package/dist/audit/extractors/surfaces.js.map +1 -1
  68. package/dist/audit/io/runArtifacts.d.ts +6 -0
  69. package/dist/audit/io/runArtifacts.d.ts.map +1 -1
  70. package/dist/audit/io/runArtifacts.js +9 -0
  71. package/dist/audit/io/runArtifacts.js.map +1 -1
  72. package/dist/audit/orchestrator/advance.d.ts.map +1 -1
  73. package/dist/audit/orchestrator/advance.js +3 -0
  74. package/dist/audit/orchestrator/advance.js.map +1 -1
  75. package/dist/audit/orchestrator/architectureDiscovery.d.ts +9 -0
  76. package/dist/audit/orchestrator/architectureDiscovery.d.ts.map +1 -1
  77. package/dist/audit/orchestrator/architectureDiscovery.js +11 -1
  78. package/dist/audit/orchestrator/architectureDiscovery.js.map +1 -1
  79. package/dist/audit/orchestrator/charterPackets.d.ts +36 -7
  80. package/dist/audit/orchestrator/charterPackets.d.ts.map +1 -1
  81. package/dist/audit/orchestrator/charterPackets.js +88 -21
  82. package/dist/audit/orchestrator/charterPackets.js.map +1 -1
  83. package/dist/audit/orchestrator/dependencyMap.d.ts.map +1 -1
  84. package/dist/audit/orchestrator/dependencyMap.js +16 -13
  85. package/dist/audit/orchestrator/dependencyMap.js.map +1 -1
  86. package/dist/audit/orchestrator/dependencySlices.d.ts.map +1 -1
  87. package/dist/audit/orchestrator/dependencySlices.js +26 -11
  88. package/dist/audit/orchestrator/dependencySlices.js.map +1 -1
  89. package/dist/audit/orchestrator/designReviewPrompt.d.ts.map +1 -1
  90. package/dist/audit/orchestrator/designReviewPrompt.js +38 -6
  91. package/dist/audit/orchestrator/designReviewPrompt.js.map +1 -1
  92. package/dist/audit/orchestrator/intentCheckpointExecutor.d.ts.map +1 -1
  93. package/dist/audit/orchestrator/intentCheckpointExecutor.js +3 -2
  94. package/dist/audit/orchestrator/intentCheckpointExecutor.js.map +1 -1
  95. package/dist/audit/orchestrator/state.js +1 -1
  96. package/dist/audit/orchestrator/state.js.map +1 -1
  97. package/dist/audit/orchestrator/systemicChallengeExecutor.d.ts +9 -0
  98. package/dist/audit/orchestrator/systemicChallengeExecutor.d.ts.map +1 -1
  99. package/dist/audit/orchestrator/systemicChallengeExecutor.js +12 -2
  100. package/dist/audit/orchestrator/systemicChallengeExecutor.js.map +1 -1
  101. package/dist/audit/orchestrator/unitBuilder.d.ts.map +1 -1
  102. package/dist/audit/orchestrator/unitBuilder.js +29 -8
  103. package/dist/audit/orchestrator/unitBuilder.js.map +1 -1
  104. package/dist/audit/reporting/criticalFlowFallbackPrompt.d.ts +6 -0
  105. package/dist/audit/reporting/criticalFlowFallbackPrompt.d.ts.map +1 -1
  106. package/dist/audit/reporting/criticalFlowFallbackPrompt.js +55 -34
  107. package/dist/audit/reporting/criticalFlowFallbackPrompt.js.map +1 -1
  108. package/dist/audit/systemic/reviewFileMap.d.ts +92 -45
  109. package/dist/audit/systemic/reviewFileMap.d.ts.map +1 -1
  110. package/dist/audit/systemic/reviewFileMap.js +171 -94
  111. package/dist/audit/systemic/reviewFileMap.js.map +1 -1
  112. package/dist/audit/systemic/secondOrderAdversaryPrompt.d.ts +15 -6
  113. package/dist/audit/systemic/secondOrderAdversaryPrompt.d.ts.map +1 -1
  114. package/dist/audit/systemic/secondOrderAdversaryPrompt.js +119 -36
  115. package/dist/audit/systemic/secondOrderAdversaryPrompt.js.map +1 -1
  116. package/dist/audit/types/designAssessment.d.ts +11 -0
  117. package/dist/audit/types/designAssessment.d.ts.map +1 -1
  118. package/dist/audit/types/designAssessment.js +23 -1
  119. package/dist/audit/types/designAssessment.js.map +1 -1
  120. package/dist/remediate/index.d.ts.map +1 -1
  121. package/dist/remediate/index.js +44 -0
  122. package/dist/remediate/index.js.map +1 -1
  123. package/dist/remediate/steps/dispatch/hostHandoff.d.ts +29 -0
  124. package/dist/remediate/steps/dispatch/hostHandoff.d.ts.map +1 -1
  125. package/dist/remediate/steps/dispatch/hostHandoff.js +63 -4
  126. package/dist/remediate/steps/dispatch/hostHandoff.js.map +1 -1
  127. package/dist/remediate/steps/submitResult.d.ts +13 -0
  128. package/dist/remediate/steps/submitResult.d.ts.map +1 -0
  129. package/dist/remediate/steps/submitResult.js +24 -0
  130. package/dist/remediate/steps/submitResult.js.map +1 -0
  131. package/dist/shared/decompose/charterExtraction.d.ts +117 -17
  132. package/dist/shared/decompose/charterExtraction.d.ts.map +1 -1
  133. package/dist/shared/decompose/charterExtraction.js +27 -3
  134. package/dist/shared/decompose/charterExtraction.js.map +1 -1
  135. package/dist/shared/decompose/systemicChallenge.d.ts.map +1 -1
  136. package/dist/shared/decompose/systemicChallenge.js +4 -1
  137. package/dist/shared/decompose/systemicChallenge.js.map +1 -1
  138. package/dist/shared/index.d.ts +2 -2
  139. package/dist/shared/index.d.ts.map +1 -1
  140. package/dist/shared/index.js +2 -2
  141. package/dist/shared/index.js.map +1 -1
  142. package/dist/shared/mcp/submitServer.d.ts +26 -0
  143. package/dist/shared/mcp/submitServer.d.ts.map +1 -0
  144. package/dist/shared/mcp/submitServer.js +74 -0
  145. package/dist/shared/mcp/submitServer.js.map +1 -0
  146. package/dist/shared/submission/hostHandoffCore.d.ts +10 -0
  147. package/dist/shared/submission/hostHandoffCore.d.ts.map +1 -1
  148. package/dist/shared/submission/hostHandoffCore.js +19 -0
  149. package/dist/shared/submission/hostHandoffCore.js.map +1 -1
  150. package/dist/shared/submission/submissionClassifier.d.ts +7 -0
  151. package/dist/shared/submission/submissionClassifier.d.ts.map +1 -1
  152. package/dist/shared/submission/submissionClassifier.js +9 -0
  153. package/dist/shared/submission/submissionClassifier.js.map +1 -1
  154. package/dist/shared/submission/submissionScan.d.ts +7 -0
  155. package/dist/shared/submission/submissionScan.d.ts.map +1 -1
  156. package/dist/shared/submission/submissionScan.js +6 -2
  157. package/dist/shared/submission/submissionScan.js.map +1 -1
  158. package/package.json +2 -1
  159. package/scripts/audit/postinstall.mjs +21 -7
  160. package/scripts/remediate/postinstall.mjs +44 -1
  161. package/scripts/shared/install-host-assets.mjs +134 -1
  162. package/wrapper/audit-code-wrapper-lib.mjs +9 -46
@@ -3,9 +3,9 @@ import { ActiveReviewRunSchema } from "../../contracts/wrapperResponse.js";
3
3
  import { sourceTreeInstruction } from "../../io/runSnapshot.js";
4
4
  import { CURRENT_TASK_FILENAME } from "../../supervisor/operatorHandoff.js";
5
5
  import { mkdir } from "node:fs/promises";
6
- import { join } from "node:path";
6
+ import { join, relative, resolve } from "node:path";
7
7
  import { lensDefinition } from "../../types.js";
8
- import { createMemoizedSourceReader, enumerateTrackedFilePaths, deriveLaneDemand, appendSubmissionEvent, assertSubmissionRunId, SUBMISSION_LEDGER_EVENT_CONTRACT_VERSION, bindingIdentity, compareCodeUnits, contentSha256, firstDuplicateIdentity, hasExactKeys, hostHandoffResultPath, identityFailureDiagnostic, isFileMissingError, isJsonParseError, isRecord, isSha256, LaneDemandSchema, parseAllWorkloadItems, parseWorkloadEnvelope, bindWorkerPrompt, deriveResultId, workerPromptBindingHolds, enrichMissingSubmissionIssues, readTrailingSubmissionRefusals, readJsonFile, repoRelativePath, requireNonEmptyString, resolveContainedPath, resolveHostHandoffPaths, resultMapIdentity, scanBoundSubmission, siblingLockPath, sameStrings, stableStringify, groundFinding, withFileLock, writeBlockedStepContract, writeJsonFile, } from "audit-tools/shared";
8
+ import { createMemoizedSourceReader, enumerateTrackedFilePaths, deriveLaneDemand, appendSubmissionEvent, assertSubmissionRunId, SUBMISSION_LEDGER_EVENT_CONTRACT_VERSION, bindingIdentity, compareCodeUnits, contentSha256, firstDuplicateIdentity, hasExactKeys, hostHandoffResultPath, workerPromptPath, identityFailureDiagnostic, isFileMissingError, isJsonParseError, isRecord, isSha256, LaneDemandSchema, parseAllWorkloadItems, parseWorkloadEnvelope, bindWorkerPrompt, deriveResultId, workerPromptBindingHolds, enrichMissingSubmissionIssues, readTrailingSubmissionRefusals, readJsonFile, repoRelativePath, requireNonEmptyString, resolveContainedPath, resolveHostHandoffPaths, resultMapIdentity, scanBoundSubmission, siblingLockPath, sameStrings, stableStringify, groundFinding, withFileLock, writeBlockedStepContract, writeTextFile, writeJsonFile, toPosixPath, } from "audit-tools/shared";
9
9
  import { findingContractPromptLines } from "../../contracts/findingContractPrompt.js";
10
10
  import { WORKER_REFUSED_FINDING_VERDICTS, WORKER_REFUSED_LOCATION_FIELDS, WorkerFindingSchema, } from "../../contracts/workerSchemas.js";
11
11
  import { AuditResultSchema, AuditTaskSchema, } from "../../types.js";
@@ -14,7 +14,7 @@ import { validateOneAuditResult, formatAuditResultIssues,
14
14
  // `validateVerification` build their allowed set through the same function, so
15
15
  // they cannot disagree about which `file_paths` entries are inside the packet.
16
16
  verificationAllowedPaths, normalizeCoveragePath, } from "../../validation/auditResults.js";
17
- import { reviewWaveClosedPath } from "../../io/runArtifacts.js";
17
+ import { hostCoherenceGroupsPath, reviewWaveClosedPath } from "../../io/runArtifacts.js";
18
18
  // The lane token itself is single-sourced where the steward lane is minted:
19
19
  // `LENS_VERIFICATION_TAG` (`orchestrator/selectiveDeepening/shared.ts`). Every
20
20
  // reader compiles against that one declaration, so a rename moves them together
@@ -22,6 +22,8 @@ import { reviewWaveClosedPath } from "../../io/runArtifacts.js";
22
22
  // is what a hand-copied literal here produced, twice (this boundary and the
23
23
  // audit-results validator).
24
24
  import { LENS_VERIFICATION_TAG, } from "../../orchestrator/selectiveDeepening/shared.js";
25
+ import { buildTaskAffinityGraph } from "../../orchestrator/taskAffinityGraph.js";
26
+ import { buildTaskCoherencePartition } from "../../orchestrator/partitionTaskGraph.js";
25
27
  // v1alpha2 (the emitted-lane demand ranking): each work item's `metadata`
26
28
  // carries the shared `demand` ranking (size / complexity / risk) beside its
27
29
  // token estimate, in place of the retired `{complexity, risk}` pair whose
@@ -44,7 +46,17 @@ import { LENS_VERIFICATION_TAG, } from "../../orchestrator/selectiveDeepening/sh
44
46
  // the result template, its identity values filled in by the tool, and the
45
47
  // prompt digest covers the text ABOVE that template. A v1alpha3 document refuses
46
48
  // closed as stale — the same `next-step` re-prepares it.
47
- const WORKLOAD_CONTRACT_VERSION = "audit-host-workload/v1alpha4";
49
+ //
50
+ // v1alpha5 (the 0.55.15 self-audit): the prompt and its result template name
51
+ // the result path ABSOLUTE, so the persisted template a work item is checked
52
+ // against changed shape. A v1alpha4 document refuses closed as stale — the same
53
+ // `next-step` re-prepares it.
54
+ //
55
+ // v1alpha6 (decision 5 of the 2026-11-06 dogfood audit): each fact stated once.
56
+ // The template no longer names the path (line 2 of the body does), and its
57
+ // wording depends on the lane, so the persisted template changed shape again. A
58
+ // v1alpha5 document refuses closed as stale — the same `next-step` re-prepares it.
59
+ const WORKLOAD_CONTRACT_VERSION = "audit-host-workload/v1alpha6";
48
60
  const RESULT_MAP_CONTRACT_VERSION = "audit-host-result-map/v1alpha1";
49
61
  const RESULT_CONTRACT_VERSION = "audit-host-result/v1alpha1";
50
62
  /**
@@ -362,11 +374,13 @@ function isVerificationLane(tags) {
362
374
  return tags?.includes(LENS_VERIFICATION_TAG) ?? false;
363
375
  }
364
376
  /**
365
- * The result template every audit worker prompt ends with. The tool fills the
366
- * identity values; the worker fills `file_coverage` and `findings`. The digest
367
- * it states is the digest of the prompt text ABOVE it (see `bindWorkerPrompt`).
377
+ * The tail every work-item prompt ends with. The destination is NOT repeated
378
+ * here: line 2 of the body states it, once (decision 5, cut C1). The base lane's
379
+ * key set is stated by the template itself ("Keep exactly these keys", cut C2);
380
+ * the steward lane adds `verification`, so its body keeps the result-contract
381
+ * line and its tail does not claim an exact key set.
368
382
  */
369
- function renderResultTemplate(runId, workItemId, resultPath, promptDigest) {
383
+ function renderResultTemplate(runId, workItemId, promptDigest, verificationLane) {
370
384
  const template = {
371
385
  contract_version: RESULT_CONTRACT_VERSION,
372
386
  result_id: deriveResultId(workItemId, promptDigest),
@@ -377,7 +391,9 @@ function renderResultTemplate(runId, workItemId, resultPath, promptDigest) {
377
391
  findings: [],
378
392
  };
379
393
  return [
380
- `When you finish, write this JSON to \`${resultPath}\`. Keep the five identity values as they are. Fill in \`file_coverage\` and \`findings\`:`,
394
+ verificationLane
395
+ ? "When you finish, submit this JSON as line 2 says. Keep the five identity values as they are. Fill in `file_coverage` and `findings`:"
396
+ : "When you finish, submit this JSON as line 2 says. Keep exactly these keys, and keep the five identity values as they are. Fill in `file_coverage` and `findings`:",
381
397
  "```json",
382
398
  JSON.stringify(template, null, 2),
383
399
  "```",
@@ -402,23 +418,13 @@ function lensGuidanceLines(lens) {
402
418
  `Do not report under this lens: ${definition.do_not_report}`,
403
419
  ];
404
420
  }
405
- function buildPrompt(task, resultPath, workloadPath, sourceRoot) {
421
+ function buildPrompt(task, destination, workloadPath, sourceRoot) {
406
422
  // A `"selective"` lane's file list is NOT inlined. Its assignment is the whole
407
423
  // surface its lens was applied to, which runs to hundreds of files on a real
408
424
  // run, so inlining it would make the prompt mostly a path list and the prompt
409
425
  // DIGEST a function of the surface's size. The list and its per-file metrics
410
426
  // ride the workload the tool already writes, and the prompt names where.
411
427
  const selective = task.coverage_policy === "selective";
412
- const assignment = stableStringify({
413
- ...(selective
414
- ? { surface_file_count: task.file_paths.length }
415
- : { file_line_counts: task.file_line_counts, files: task.file_paths }),
416
- lens: task.lens,
417
- pass_id: task.pass_id,
418
- rationale: task.rationale,
419
- task_id: task.task_id,
420
- unit_id: task.unit_id,
421
- });
422
428
  // LANE-AWARE, because the two lanes' contracts genuinely differ: the steward
423
429
  // lane is INSTRUCTED (by its task rationale) to return verification metadata,
424
430
  // and the base lane is not. Rendering one envelope sentence for both would
@@ -427,16 +433,35 @@ function buildPrompt(task, resultPath, workloadPath, sourceRoot) {
427
433
  // demands. The ask and the envelope are the same fact, so they are stated
428
434
  // from the same predicate.
429
435
  const verificationLane = isVerificationLane(task.tags);
436
+ // Each fact once (decision 5): `file_line_counts` already names every file
437
+ // (cut C3), and the base lane's reader uses neither `task_id` (the template's
438
+ // `work_item_id`) nor `pass_id` (`pass:<lens>`) (cut C4). The steward keeps
439
+ // both: each of its `verification.followup_tasks` entries must carry them.
440
+ const assignment = stableStringify({
441
+ ...(selective
442
+ ? { surface_file_count: task.file_paths.length }
443
+ : { file_line_counts: task.file_line_counts }),
444
+ lens: task.lens,
445
+ ...(verificationLane ? { pass_id: task.pass_id, task_id: task.task_id } : {}),
446
+ rationale: task.rationale,
447
+ unit_id: task.unit_id,
448
+ });
430
449
  return [
431
450
  "Perform the bounded semantic audit work item below.",
432
451
  // THE DESTINATION FIRST, on its own line. It used to be one field inside a
433
452
  // single long JSON blob, which buries the one fact a reader must not have to
434
453
  // search for: a result written anywhere else is never ingested.
435
- `Write one JSON object to this exact path: ${resultPath}`,
454
+ // ABSOLUTE (`workerPromptPath`): the worker's working directory is the
455
+ // host's choice, so no path here may depend on it.
456
+ destination,
436
457
  // WHERE TO READ, stated rather than left to the host's working directory:
437
458
  // the run audits a frozen snapshot, and the live tree may have moved since
438
459
  // the run started. Line counts and cited text are checked against this tree.
439
460
  sourceTreeInstruction(sourceRoot),
461
+ // WHAT ELSE TO WRITE: nothing. Workers in the self-audit wrote scratch
462
+ // files to the OS temp directory and stalled on the permission prompt each
463
+ // one raised; the work needs no file but the result.
464
+ "Write no other file: no scratch, temporary or helper file anywhere. Both paths above are absolute and do not depend on your working directory.",
440
465
  // LANE-AWARE, because "review every listed file" is true of the base lane
441
466
  // and false of a steward under selective coverage — whose whole task is to
442
467
  // decide what is worth opening.
@@ -453,23 +478,41 @@ function buildPrompt(task, resultPath, workloadPath, sourceRoot) {
453
478
  assignment,
454
479
  "```",
455
480
  ...lensGuidanceLines(task.lens),
456
- verificationLane
457
- // `verification` is REQUIRED on this lane, and the prompt states ONE rule.
458
- // It used to say "exactly … and verification" and then call the field
459
- // optional, which is a contradiction a reader cannot obey both halves of.
460
- // Required is the honest reading: a steward returns `findings: []`, so a
461
- // steward with no `verification` carries no answer at all and is
462
- // indistinguishable from a lane that failed.
463
- ? "Result contract: audit-host-result/v1alpha1 with exactly result_id, run_id, work_item_id, prompt_sha256, file_coverage, findings, and verification in addition to contract_version. On this lane verification is REQUIRED."
464
- : "Result contract: audit-host-result/v1alpha1 with exactly result_id, run_id, work_item_id, prompt_sha256, file_coverage, and findings in addition to contract_version.",
481
+ // `verification` is REQUIRED on the steward lane, and the prompt states ONE
482
+ // rule. It used to say "exactly … and verification" and then call the field
483
+ // optional, which is a contradiction a reader cannot obey both halves of.
484
+ // Required is the honest reading: a steward returns `findings: []`, so a
485
+ // steward with no `verification` carries no answer at all and is
486
+ // indistinguishable from a lane that failed. The base lane has no such
487
+ // line: its template states the exact key set (decision 5, cut C2).
488
+ ...(verificationLane
489
+ ? ["Result contract: audit-host-result/v1alpha1 with exactly result_id, run_id, work_item_id, prompt_sha256, file_coverage, findings, and verification in addition to contract_version. On this lane verification is REQUIRED."]
490
+ : []),
465
491
  "Each file_coverage entry must contain exactly path, reviewed_lines, and total_lines.",
466
492
  // The finding contract is CARRIED, not referenced: it is rendered from the
467
493
  // very schema ingestion enforces, so a host never has to remember or fetch it.
468
494
  ...findingContractPromptLines(),
469
- "Do not supply a `grounding` field on any finding — grounding is computed by the tool at ingest by re-reading your cited quoted_text from disk, and a supplied one rejects the whole submission.",
495
+ "Never supply a `grounding` field: the tool computes it at ingest from your quoted_text.",
470
496
  ...(verificationLane ? verificationContractPromptLines() : []),
497
+ // Stated ONCE, last, so it covers every rule above it (decision 5, cut C7).
498
+ "A result that breaks any rule above is rejected whole.",
471
499
  ].join("\n");
472
500
  }
501
+ /**
502
+ * Line 2 of every work-item prompt: how the result reaches the tool, and the one
503
+ * statement of the absolute destination (owner decision, 2026-11-07). The
504
+ * submit tool comes first because it checks the result before it writes it, and
505
+ * it needs the root and the work-item id, so the line states both. The file path
506
+ * stays as the fallback for a host without the tool. A shell is excluded by
507
+ * name: the dogfood audit lost a backslash in a quoted span that way.
508
+ */
509
+ function destinationLine(root, workItemId, resultPath) {
510
+ return (`Submit one JSON object with the submit_result tool (root: ${workerPromptPath(root, ".")}, work_item_id: ${workItemId}). ` +
511
+ `If you do not have that tool, write the object with a file-write tool to this exact absolute path: ${workerPromptPath(root, resultPath)}. ` +
512
+ "Do not write it through a shell.");
513
+ }
514
+ /** The first line of the steward's verification contract; only a steward body holds it. */
515
+ const VERIFICATION_CONTRACT_LEAD = "This work item is a LENS STEWARD VERIFICATION task, so it must also carry a `verification` object.";
473
516
  /**
474
517
  * The `verification` contract rendered into a steward-lane work item's prompt.
475
518
  *
@@ -482,7 +525,7 @@ function buildPrompt(task, resultPath, workloadPath, sourceRoot) {
482
525
  */
483
526
  function verificationContractPromptLines() {
484
527
  return [
485
- "This work item is a LENS STEWARD VERIFICATION task, so it must also carry a `verification` object.",
528
+ VERIFICATION_CONTRACT_LEAD,
486
529
  `verification must contain exactly ${VERIFICATION_CONTRACT_KEYS.join(", ")} — all ${String(VERIFICATION_CONTRACT_KEYS.length)}, with no extra key: verified and needs_followup are booleans, concerns, coverage_concerns and confidence_concerns are arrays of non-empty strings (a genuine "nothing to report" is an empty array, not an omitted field), selection_rationale is a non-empty string, and followup_tasks is an array of objects.`,
487
530
  "verification.selection_rationale states how you chose which surface files to open and which to leave: name the signals you followed and say what you decided was not worth opening. A file you did not open is not a coverage failure, but an unexplained choice is.",
488
531
  `Each verification.followup_tasks entry must contain exactly ${VERIFICATION_FOLLOWUP_KEYS.join(", ")} — all ${String(VERIFICATION_FOLLOWUP_KEYS.length)}, with no extra key: file_paths is a non-empty array of non-empty repo-relative strings, each naming a file on THIS work item's assigned surface (scope.files) — a file you did not open is still on the surface and may be named; lens must be the lens of THIS task; task_id, unit_id, pass_id and rationale must be non-empty strings.`,
@@ -636,7 +679,7 @@ function buildWorkItem(paths, task) {
636
679
  const resultPath = resultPathFor(paths, task.task_id);
637
680
  // The SAME path the caller writes the workload to, so a selective lane is told
638
681
  // where its surface actually is rather than where it is expected to be.
639
- const prompt = bindWorkerPrompt(buildPrompt(task, resultPath, paths.workloadPath, boundarySourceRoot(paths)), (digest) => renderResultTemplate(paths.runId, task.task_id, resultPath, digest));
682
+ const prompt = bindWorkerPrompt(buildPrompt(task, destinationLine(paths.root, task.task_id, resultPath), paths.workloadPath, boundarySourceRoot(paths)), (digest) => renderResultTemplate(paths.runId, task.task_id, digest, isVerificationLane(task.tags)));
640
683
  return {
641
684
  id: task.task_id,
642
685
  lens: task.lens,
@@ -805,11 +848,20 @@ export async function prepareAuditHostHandoff(params) {
805
848
  await writeAcceptedResults(paths, accepted);
806
849
  await writeJsonFile(paths.workloadPath, workload);
807
850
  await writeJsonFile(paths.resultMapPath, resultMap);
851
+ const coherenceGroups = {
852
+ contract_version: COHERENCE_GROUPS_CONTRACT_VERSION,
853
+ run_id: params.runId,
854
+ groups: coherenceGroupsFor(allWorkItems, params.coherenceGroups),
855
+ };
856
+ const coherenceGroupsPath = hostCoherenceGroupsPath(params.artifactsDir, params.runId);
857
+ await writeJsonFile(coherenceGroupsPath, coherenceGroups);
808
858
  return {
809
859
  workload,
810
860
  result_map: resultMap,
811
861
  workload_path: paths.workloadPath,
812
862
  result_map_path: paths.resultMapPath,
863
+ coherence_groups: coherenceGroups,
864
+ coherence_groups_path: coherenceGroupsPath,
813
865
  };
814
866
  });
815
867
  }
@@ -825,7 +877,7 @@ export async function prepareAuditHostHandoff(params) {
825
877
  function isSurfaceFileMetrics(value) {
826
878
  return AuditTaskSchema.shape.file_metrics.safeParse(value).success;
827
879
  }
828
- function parseWorkItem(value, runId) {
880
+ function parseWorkItem(value, runId, root) {
829
881
  // `file_metrics` is the ONE optional scope key: a selective (steward) lane
830
882
  // carries it, every complete lane omits it. It is added to the expected set
831
883
  // only when the document supplies it, exactly as the result envelope treats
@@ -854,7 +906,18 @@ function parseWorkItem(value, runId) {
854
906
  !hasExactKeys(value.prompt, ["sha256", "text"]) ||
855
907
  !isSha256(value.prompt.sha256) ||
856
908
  typeof value.prompt.text !== "string" ||
857
- !workerPromptBindingHolds({ text: value.prompt.text, sha256: value.prompt.sha256 }, (digest) => renderResultTemplate(runId, value.id, value.result_path, digest)) ||
909
+ !workerPromptBindingHolds({ text: value.prompt.text, sha256: value.prompt.sha256 },
910
+ // The lane is read from the digest-bound BODY: only a steward body states
911
+ // the verification contract, and the body cannot change without the digest.
912
+ (digest) => renderResultTemplate(runId, value.id, digest,
913
+ // A WHOLE line: a rationale is free text inside the assignment JSON, so a
914
+ // substring match would let it flip the lane.
915
+ value.prompt.text.split("\n").includes(VERIFICATION_CONTRACT_LEAD))) ||
916
+ // Line 2 states the absolute destination under the root the workload was
917
+ // prepared at. Re-derived under the CURRENT root, a root that really moved
918
+ // no longer matches, and the workload is refused as stale (see
919
+ // `workerPromptPath`) rather than sending readers to the old tree.
920
+ value.prompt.text.split("\n")[1] !== destinationLine(root, value.id, value.result_path) ||
858
921
  !isRecord(value.scope) ||
859
922
  !hasExactKeys(value.scope, [
860
923
  "files",
@@ -942,7 +1005,7 @@ class StaleAuditHostTaskBindingsError extends Error {
942
1005
  this.name = "StaleAuditHostTaskBindingsError";
943
1006
  }
944
1007
  }
945
- function parseWorkload(value, runId) {
1008
+ function parseWorkload(value, runId, root) {
946
1009
  // Envelope + all-items parsing is the CORE's scaffolding; the audit draw
947
1010
  // selects only its own contract version and item parser.
948
1011
  const envelope = parseWorkloadEnvelope(value, {
@@ -962,7 +1025,7 @@ function parseWorkload(value, runId) {
962
1025
  }
963
1026
  throw bindingFailure("workload_binding", "Invalid audit host workload");
964
1027
  }
965
- const workItems = parseAllWorkloadItems(envelope.rawItems, (raw) => parseWorkItem(raw, runId));
1028
+ const workItems = parseAllWorkloadItems(envelope.rawItems, (raw) => parseWorkItem(raw, runId, root));
966
1029
  if (workItems === null) {
967
1030
  throw bindingFailure("workload_binding", "Invalid audit host work item");
968
1031
  }
@@ -1086,33 +1149,43 @@ function validateHandoffBinding(paths, workload, resultMap, taskBindings) {
1086
1149
  }
1087
1150
  return items;
1088
1151
  }
1089
- /** Snapshot current publication under its existing lock; release before planning. */
1090
- export async function readPublishedAuditTaskIds(params) {
1152
+ /**
1153
+ * The run the current-review-run pointer names, or `undefined` when there is
1154
+ * no usable pointer. The pointer schema accepts strings; only the existing
1155
+ * run-id grammar may authorize a directory segment, so an unusable pointer is
1156
+ * not publication.
1157
+ */
1158
+ async function readActiveRunId(artifactsDir) {
1091
1159
  let run;
1092
1160
  try {
1093
- run = ActiveReviewRunSchema.safeParse(await readJsonFile(join(params.artifactsDir, "dispatch", CURRENT_TASK_FILENAME)));
1161
+ run = ActiveReviewRunSchema.safeParse(await readJsonFile(join(artifactsDir, "dispatch", CURRENT_TASK_FILENAME)));
1094
1162
  }
1095
1163
  catch (error) {
1096
1164
  if (isFileMissingError(error) || isJsonParseError(error))
1097
- return new Set();
1165
+ return undefined;
1098
1166
  throw error;
1099
1167
  }
1100
1168
  if (!run.success)
1101
- return new Set();
1102
- // The pointer schema accepts strings; only the existing run-id grammar may
1103
- // authorize a directory segment. An unusable pointer is not publication.
1169
+ return undefined;
1104
1170
  try {
1105
1171
  assertSubmissionRunId(run.data.run_id);
1106
1172
  }
1107
1173
  catch {
1108
- return new Set();
1174
+ return undefined;
1109
1175
  }
1110
- const paths = resolveBoundaryPaths({ root: params.root, sourceRoot: params.sourceRoot, artifactsDir: params.artifactsDir, runId: run.data.run_id });
1176
+ return run.data.run_id;
1177
+ }
1178
+ /** Snapshot current publication under its existing lock; release before planning. */
1179
+ export async function readPublishedAuditTaskIds(params) {
1180
+ const runId = await readActiveRunId(params.artifactsDir);
1181
+ if (runId === undefined)
1182
+ return new Set();
1183
+ const paths = resolveBoundaryPaths({ root: params.root, sourceRoot: params.sourceRoot, artifactsDir: params.artifactsDir, runId });
1111
1184
  return withAcceptedResultsLock(paths, params.logger, async () => {
1112
1185
  let items;
1113
1186
  let bindings;
1114
1187
  try {
1115
- const workload = parseWorkload(await readJsonFile(paths.workloadPath), paths.runId);
1188
+ const workload = parseWorkload(await readJsonFile(paths.workloadPath), paths.runId, paths.root);
1116
1189
  const resultMap = parseResultMap(await readJsonFile(paths.resultMapPath), paths.runId);
1117
1190
  bindings = parseTaskBindings(await readJsonFile(paths.taskBindingsPath), paths.runId);
1118
1191
  items = validateHandoffBinding(paths, workload, resultMap, bindings);
@@ -1462,6 +1535,325 @@ function evictInvalidatedEntries(loaded, params) {
1462
1535
  });
1463
1536
  return { kept: { ...loaded, entries: kept }, issues };
1464
1537
  }
1538
+ /**
1539
+ * The ONE judgment of one bound submission: read it at its bound path, parse
1540
+ * the envelope against its binding, convert it, ground its cited text, and put
1541
+ * it through the per-result validator. Ingestion ACCEPTS on `ok`; the
1542
+ * read-only check ({@link checkAuditHostResult}) only reports — so a host that
1543
+ * checks a result before ingestion is told exactly what ingestion would say.
1544
+ */
1545
+ async function judgeAuditHostSubmission(params) {
1546
+ const { paths, entry, item, binding } = params;
1547
+ const outcome = await scanBoundSubmission({
1548
+ root: paths.root,
1549
+ artifactsDir: paths.artifactsDir,
1550
+ workItemId: entry.work_item_id,
1551
+ resultPath: entry.result_path,
1552
+ parse: (value) => {
1553
+ const parsed = parseHostResult(value, paths.runId, item, binding);
1554
+ return parsed.ok ? { ok: true, parsed: parsed.result } : parsed;
1555
+ },
1556
+ resultId: (result) => result.result_id,
1557
+ seen: params.seen,
1558
+ messages: auditScanMessages(entry.work_item_id),
1559
+ source: params.source,
1560
+ });
1561
+ if (!outcome.ok)
1562
+ return { ok: false, issue: outcome.issue };
1563
+ const result = outcome.parsed;
1564
+ const converted = toAuditResult(result, binding);
1565
+ if (!converted.ok) {
1566
+ return {
1567
+ ok: false,
1568
+ issue: {
1569
+ code: "submission_contract_invalid",
1570
+ check: "result_schema",
1571
+ message: `work item '${entry.work_item_id}' submitted a result that does not convert to ` +
1572
+ `an AuditResult: ${converted.detail}`,
1573
+ work_item_id: entry.work_item_id,
1574
+ result_path: entry.result_path,
1575
+ },
1576
+ };
1577
+ }
1578
+ // S7 quote-and-verify: the tool re-reads each cited span from disk, stamps
1579
+ // the verdict, and writes each entry's line numbers from where its quote
1580
+ // occurs. It NEVER rejects — a quote that is absent or occurs more than
1581
+ // once rides through as `ungrounded` and synthesis surfaces it under
1582
+ // "Ungrounded Findings (not confirmed)"; refusing here would discard the
1583
+ // whole submission over one bad citation. It mutates the CONVERTED copy
1584
+ // only: `result` stays the host's submission, which `result_sha256` hashes.
1585
+ // It runs BEFORE validation, so the derived span meets the same coverage
1586
+ // rule here that the downstream batch gate applies: a span that rule would
1587
+ // refuse is refused while the item can still be resubmitted, never
1588
+ // accepted and then replayed into a failing gate on every later step.
1589
+ for (const finding of converted.auditResult.findings) {
1590
+ await groundFinding(boundarySourceRoot(paths), finding, params.readSource, await params.knownPaths());
1591
+ }
1592
+ // VALIDATE BEFORE ACCEPT. The conversion above proves only the envelope
1593
+ // contract (`FindingSchema` admits an evidence-less finding); these are the
1594
+ // per-result rules the downstream batch gate applies, applied HERE so an
1595
+ // error-severity issue never reaches the accepted pair. A rejected item is
1596
+ // simply never in the ledger, so the corrected file at the same bound path
1597
+ // is re-read on the next fold — acceptance used to be terminal instead, and
1598
+ // a failed batch gate then wedged the run permanently.
1599
+ //
1600
+ // Orphans (task pruned by a re-plan) pass through UNVALIDATED with the same
1601
+ // stderr notice the batch gate uses — never newly rejected: refusing one
1602
+ // here would strand it outside the append-only ledger entirely.
1603
+ if (!params.activeTaskIds.has(entry.work_item_id)) {
1604
+ process.stderr.write(`audit host-handoff ingest: result for '${entry.work_item_id}' is not in the ` +
1605
+ `active task manifest (orphaned by re-planning); retained in the accepted pair ` +
1606
+ `but skipped at the validation gate\n`);
1607
+ return { ok: true, result, auditResult: converted.auditResult, warnings: [] };
1608
+ }
1609
+ const validationIssues = validateOneAuditResult(converted.auditResult, [...params.auditTasks], {
1610
+ lineIndex: params.lineIndex,
1611
+ });
1612
+ const errors = validationIssues.filter((issue) => issue.severity === "error");
1613
+ if (errors.length > 0) {
1614
+ return {
1615
+ ok: false,
1616
+ issue: {
1617
+ code: "result_validation_failed",
1618
+ check: "result_validation",
1619
+ message: `work item '${entry.work_item_id}' failed audit-results validation ` +
1620
+ `(${errors.length} error(s)); fix the result file at its bound path and call next-step again: ` +
1621
+ formatAuditResultIssues(errors),
1622
+ work_item_id: entry.work_item_id,
1623
+ result_path: entry.result_path,
1624
+ },
1625
+ };
1626
+ }
1627
+ // Warnings are NOT rejections: an accepted result never refused anything,
1628
+ // so a warning must never reach the rejection-classified issue list — the
1629
+ // ONE ledger recorder would otherwise record kind:'rejected' for a result
1630
+ // that was accepted, manufacturing a repair story that never happened.
1631
+ // They ride the separate advisory channel instead (rendered for the
1632
+ // operator; never counted as a submission that could not be accepted).
1633
+ const warnings = validationIssues
1634
+ .filter((issue) => issue.severity === "warning")
1635
+ .map((warning) => ({
1636
+ work_item_id: entry.work_item_id,
1637
+ result_path: entry.result_path,
1638
+ message: `${warning.message} (${warning.field})`,
1639
+ }));
1640
+ return { ok: true, result, auditResult: converted.auditResult, warnings };
1641
+ }
1642
+ /**
1643
+ * The run's published binding set — workload, result map, task bindings — read
1644
+ * and cross-checked, or the CLASSIFIED refusal ingestion reports for it. One
1645
+ * reader for both doors, so the read-only check refuses a stale or corrupt set
1646
+ * exactly as ingestion does, never as a stack. Infrastructure failures stay
1647
+ * strict.
1648
+ */
1649
+ async function readHandoffBindingSet(paths) {
1650
+ try {
1651
+ const workload = parseWorkload(await readJsonFile(paths.workloadPath), paths.runId, paths.root);
1652
+ const resultMap = parseResultMap(await readJsonFile(paths.resultMapPath), paths.runId);
1653
+ const taskBindings = parseTaskBindings(await readJsonFile(paths.taskBindingsPath), paths.runId);
1654
+ const items = validateHandoffBinding(paths, workload, resultMap, taskBindings);
1655
+ return { ok: true, resultMap, taskBindings, items };
1656
+ }
1657
+ catch (error) {
1658
+ if (error instanceof StaleAuditHostWorkloadError ||
1659
+ error instanceof StaleAuditHostTaskBindingsError ||
1660
+ error instanceof AuditHostBindingError)
1661
+ return { ok: false, refusal: error };
1662
+ if (isJsonParseError(error)) {
1663
+ return { ok: false, refusal: new AuditHostBindingError("workload_binding", error.message) };
1664
+ }
1665
+ throw error;
1666
+ }
1667
+ }
1668
+ /**
1669
+ * Judge one host result file by the rules ingestion applies, WITHOUT accepting
1670
+ * it: nothing is written, no lock is held, the ledger is only read. The run is
1671
+ * named by where the file lives (`<artifacts>/runs/<run id>/host-results/…`),
1672
+ * and the file must be the bound result path of one of that run's work items.
1673
+ */
1674
+ export async function checkAuditHostResult(params) {
1675
+ const absolute = resolve(params.resultPath);
1676
+ const segments = toPosixPath(relative(resolve(params.artifactsDir, "runs"), absolute)).split("/");
1677
+ if (segments.length !== 3 || segments[1] !== "host-results" || segments[0] === "..") {
1678
+ throw new Error(`${toPosixPath(absolute)} is not a bound host result path. A semantic-review result is written at the ` +
1679
+ "`result_path` its work item binds in the published host-workload.json, under " +
1680
+ `${toPosixPath(join(resolve(params.artifactsDir), "runs", "<run id>", "host-results"))}/; ` +
1681
+ "write it there and validate that file.");
1682
+ }
1683
+ const runId = segments[0];
1684
+ const paths = resolveBoundaryPaths({
1685
+ root: params.root,
1686
+ sourceRoot: params.sourceRoot,
1687
+ artifactsDir: params.artifactsDir,
1688
+ runId,
1689
+ });
1690
+ let bindingSet;
1691
+ try {
1692
+ bindingSet = await readHandoffBindingSet(paths);
1693
+ }
1694
+ catch (error) {
1695
+ if (!isFileMissingError(error))
1696
+ throw error;
1697
+ throw new Error(`run ${runId} has no published workload (${toPosixPath(paths.workloadPath)} is missing); ` +
1698
+ "run next-step to publish one, then write each result at the result_path it binds.");
1699
+ }
1700
+ if (!bindingSet.ok) {
1701
+ // The SAME classified refusal ingestion reports for this binding set.
1702
+ return {
1703
+ run_id: runId,
1704
+ already_accepted: false,
1705
+ issues: [{ code: bindingSet.refusal.code, check: bindingSet.refusal.check, message: bindingSet.refusal.message }],
1706
+ validation_warnings: [],
1707
+ };
1708
+ }
1709
+ const entry = bindingSet.resultMap.entries.find((candidate) => resolve(paths.root, candidate.result_path) === absolute);
1710
+ if (entry === undefined) {
1711
+ throw new Error(`${toPosixPath(absolute)} is not the bound result path of any work item in run ${runId}. ` +
1712
+ `Each work item in ${toPosixPath(paths.workloadPath)} names its own result_path; write the result there and validate that file.`);
1713
+ }
1714
+ const judged = await judgeBoundEntry({ ...params, paths, bindingSet, entry });
1715
+ return checkReport(runId, entry, judged);
1716
+ }
1717
+ /**
1718
+ * The judgment both doors share once a run's binding set and one of its entries
1719
+ * are resolved: the ledger read, the duplicate predicate, and the ONE
1720
+ * submission judgment. `source` carries `submit`'s in-memory document.
1721
+ */
1722
+ async function judgeBoundEntry(params) {
1723
+ const { paths, bindingSet, entry } = params;
1724
+ const item = bindingSet.items.get(entry.work_item_id);
1725
+ const binding = bindingSet.taskBindings.get(entry.work_item_id);
1726
+ if (item === undefined || binding === undefined) {
1727
+ throw new Error(`work item '${entry.work_item_id}' has a result path in run ${paths.runId} but no work item or task binding; ` +
1728
+ "run next-step to publish a current workload.");
1729
+ }
1730
+ const accepted = await loadAcceptedResults(paths.acceptedLedgerPath, paths.runId);
1731
+ const alreadyAccepted = accepted.entries.some((candidate) => bindingIdentity(candidate) === bindingIdentity(entry));
1732
+ // An accepted binding's own id is not a duplicate of itself: the check judges
1733
+ // the bytes, and says separately that ingestion will not re-read them.
1734
+ const otherIds = new Set(accepted.entries
1735
+ .filter((candidate) => candidate.work_item_id !== entry.work_item_id)
1736
+ .map((candidate) => candidate.result_id));
1737
+ let knownPaths;
1738
+ const judged = await judgeAuditHostSubmission({
1739
+ paths,
1740
+ entry,
1741
+ item,
1742
+ binding,
1743
+ seen: (resultId) => otherIds.has(resultId),
1744
+ activeTaskIds: new Set(params.auditTasks.map((task) => task.task_id)),
1745
+ auditTasks: params.auditTasks,
1746
+ lineIndex: params.lineIndex,
1747
+ readSource: createMemoizedSourceReader(),
1748
+ knownPaths: async () => (knownPaths ??= await enumerateTrackedFilePaths(boundarySourceRoot(paths))),
1749
+ source: params.source,
1750
+ });
1751
+ return { alreadyAccepted, judged };
1752
+ }
1753
+ function checkReport(runId, entry, { alreadyAccepted, judged }) {
1754
+ return {
1755
+ run_id: runId,
1756
+ work_item_id: entry.work_item_id,
1757
+ result_path: entry.result_path,
1758
+ already_accepted: alreadyAccepted,
1759
+ issues: judged.ok ? [] : [judged.issue],
1760
+ validation_warnings: judged.ok ? judged.warnings : [],
1761
+ };
1762
+ }
1763
+ /**
1764
+ * Judge a submitted result for one work item of the CURRENT run and, only when
1765
+ * ingestion would accept it, write it atomically to that item's bound result
1766
+ * path (decision 4, 2026-11-06). The reader never names a path: the tool
1767
+ * derives it from the work-item id. A refused result writes nothing, and the
1768
+ * report carries the same refusal ingestion would give, so the reader fixes
1769
+ * the document and submits again. No lock is held: the write is the one a
1770
+ * reader made before, and the next-step fold still ingests the file under the
1771
+ * artifact-tree lock. Bindings are read on every call, never cached, so an item
1772
+ * a re-plan retired fails with the classified refusal.
1773
+ */
1774
+ export async function submitAuditHostResult(params) {
1775
+ const runId = await readActiveRunId(params.artifactsDir);
1776
+ if (runId === undefined) {
1777
+ throw new Error("no audit run has published a workload (the current-review-run pointer is missing or unusable); " +
1778
+ "run next-step to publish one, then submit each result by its work-item id.");
1779
+ }
1780
+ const paths = resolveBoundaryPaths({
1781
+ root: params.root,
1782
+ sourceRoot: params.sourceRoot,
1783
+ artifactsDir: params.artifactsDir,
1784
+ runId,
1785
+ });
1786
+ const bindingSet = await readHandoffBindingSet(paths);
1787
+ if (!bindingSet.ok) {
1788
+ return {
1789
+ run_id: runId,
1790
+ already_accepted: false,
1791
+ issues: [{ code: bindingSet.refusal.code, check: bindingSet.refusal.check, message: bindingSet.refusal.message }],
1792
+ validation_warnings: [],
1793
+ };
1794
+ }
1795
+ const entry = bindingSet.resultMap.entries.find((candidate) => candidate.work_item_id === params.workItemId);
1796
+ if (entry === undefined) {
1797
+ throw new Error(`'${params.workItemId}' is not a work item of the current run ${runId}. ` +
1798
+ `Submit with the work-item id your prompt names; the run's items are listed in ${toPosixPath(paths.workloadPath)}.`);
1799
+ }
1800
+ const judgment = await judgeBoundEntry({ ...params, paths, bindingSet, entry });
1801
+ if (judgment.alreadyAccepted) {
1802
+ throw new Error(`work item '${entry.work_item_id}' is already accepted in run ${runId}, and ingestion does not read an accepted result again. ` +
1803
+ `To replace it, run \`audit-code unaccept-results --work-item ${entry.work_item_id}\` first, then submit again.`);
1804
+ }
1805
+ if (judgment.judged.ok) {
1806
+ await writeTextFile(resolveContainedPath(paths.root, entry.result_path, `result path for ${entry.work_item_id}`), params.source);
1807
+ }
1808
+ return checkReport(runId, entry, judgment);
1809
+ }
1810
+ /** The set-level scheduling facts beside a published workload. */
1811
+ const COHERENCE_GROUPS_CONTRACT_VERSION = "audit-host-coherence-groups/v1alpha1";
1812
+ /**
1813
+ * The groups to publish: the caller's, which must partition EXACTLY the
1814
+ * published items (a group naming an unpublished item, or an item in no group,
1815
+ * would describe a different publish), or one singleton per item.
1816
+ */
1817
+ function coherenceGroupsFor(items, supplied) {
1818
+ if (supplied === undefined) {
1819
+ return items.map((item) => ({
1820
+ id: item.id,
1821
+ work_item_ids: [item.id],
1822
+ token_estimate: item.metadata.token_estimate,
1823
+ }));
1824
+ }
1825
+ const members = supplied.flatMap((group) => group.work_item_ids).sort(compareCodeUnits);
1826
+ const published = items.map((item) => item.id);
1827
+ if (stableStringify(members) !== stableStringify(published)) {
1828
+ throw new Error("audit host coherence groups do not partition the published work items exactly");
1829
+ }
1830
+ return supplied;
1831
+ }
1832
+ /**
1833
+ * Content-coherence groups over the work items a wave PUBLISHES: the shared
1834
+ * task-draw partition (`buildTaskCoherencePartition`) of the affinity graph
1835
+ * built from exactly those tasks. Items in one group share files, a unit, a
1836
+ * flow, a directory or graph adjacency, so one lane taking them together reads
1837
+ * each file once.
1838
+ *
1839
+ * SET-LEVEL, deliberately, and never a field on a work item: a group is a
1840
+ * property of the whole published set, so on an item it would rewrite that
1841
+ * item whenever a peer is added or accepted — and an unchanged published item
1842
+ * must re-publish byte-identical. Metadata only: order, grouping and
1843
+ * parallelism stay the host's choice.
1844
+ */
1845
+ export function buildAuditHostCoherenceGroups(tasks, graphBundle) {
1846
+ const partition = tasks.length === 0
1847
+ ? { packets: [] }
1848
+ : buildTaskCoherencePartition(buildTaskAffinityGraph(tasks, graphBundle === undefined ? {} : { graphBundle }));
1849
+ const groups = partition.packets
1850
+ .map((packet) => {
1851
+ const ids = [...packet.task_ids].sort(compareCodeUnits);
1852
+ return { id: ids[0], work_item_ids: ids, token_estimate: packet.token_estimate };
1853
+ })
1854
+ .sort((left, right) => compareCodeUnits(left.id, right.id));
1855
+ return groups;
1856
+ }
1465
1857
  export async function ingestAuditHostResults(params) {
1466
1858
  const paths = resolveBoundaryPaths(params);
1467
1859
  return withAcceptedResultsLock(paths, params.logger, async (loaded) => {
@@ -1497,27 +1889,10 @@ export async function ingestAuditHostResults(params) {
1497
1889
  raw_issues: [...evictionIssues(), error],
1498
1890
  validation_warnings: [],
1499
1891
  });
1500
- let workload;
1501
- let resultMap;
1502
- let taskBindings;
1503
- let items;
1504
- try {
1505
- workload = parseWorkload(await readJsonFile(paths.workloadPath), params.runId);
1506
- resultMap = parseResultMap(await readJsonFile(paths.resultMapPath), params.runId);
1507
- taskBindings = parseTaskBindings(await readJsonFile(paths.taskBindingsPath), params.runId);
1508
- items = validateHandoffBinding(paths, workload, resultMap, taskBindings);
1509
- }
1510
- catch (error) {
1511
- if (error instanceof StaleAuditHostWorkloadError ||
1512
- error instanceof StaleAuditHostTaskBindingsError ||
1513
- error instanceof AuditHostBindingError)
1514
- return stale(error);
1515
- if (isJsonParseError(error)) {
1516
- return stale(new AuditHostBindingError("workload_binding", error.message));
1517
- }
1518
- // Infrastructure failures and corrupt accepted ledgers remain strict.
1519
- throw error;
1520
- }
1892
+ const bindingSet = await readHandoffBindingSet(paths);
1893
+ if (!bindingSet.ok)
1894
+ return stale(bindingSet.refusal);
1895
+ const { resultMap, taskBindings, items } = bindingSet;
1521
1896
  const acceptedBindings = new Set(accepted.entries.map(bindingIdentity));
1522
1897
  const resultIds = new Set(accepted.entries.map((entry) => entry.result_id));
1523
1898
  const additions = [];
@@ -1535,102 +1910,26 @@ export async function ingestAuditHostResults(params) {
1535
1910
  const binding = taskBindings.get(entry.work_item_id);
1536
1911
  if (item === undefined || binding === undefined)
1537
1912
  continue;
1538
- const outcome = await scanBoundSubmission({
1539
- root: paths.root,
1540
- artifactsDir: paths.artifactsDir,
1541
- workItemId: entry.work_item_id,
1542
- resultPath: entry.result_path,
1543
- parse: (value) => {
1544
- const parsed = parseHostResult(value, params.runId, item, binding);
1545
- return parsed.ok ? { ok: true, parsed: parsed.result } : parsed;
1546
- },
1547
- resultId: (result) => result.result_id,
1548
- // CHECK only. The id is consumed further down, after conversion,
1549
- // validation and grounding — a result refused there must stay re-submittable.
1913
+ const judged = await judgeAuditHostSubmission({
1914
+ paths,
1915
+ entry,
1916
+ item,
1917
+ binding,
1918
+ // CHECK only. The id is consumed below, after the judgment — a result
1919
+ // refused there must stay re-submittable.
1550
1920
  seen: (resultId) => resultIds.has(resultId),
1551
- messages: auditScanMessages(entry.work_item_id),
1921
+ activeTaskIds,
1922
+ auditTasks: params.auditTasks,
1923
+ lineIndex: params.lineIndex,
1924
+ readSource,
1925
+ knownPaths: async () => (knownPaths ??= await enumerateTrackedFilePaths(boundarySourceRoot(paths))),
1552
1926
  });
1553
- if (!outcome.ok) {
1554
- issues.push(outcome.issue);
1555
- continue;
1556
- }
1557
- const result = outcome.parsed;
1558
- const converted = toAuditResult(result, binding);
1559
- if (!converted.ok) {
1560
- issues.push({
1561
- code: "submission_contract_invalid",
1562
- check: "result_schema",
1563
- message: `work item '${entry.work_item_id}' submitted a result that does not convert to ` +
1564
- `an AuditResult: ${converted.detail}`,
1565
- work_item_id: entry.work_item_id,
1566
- result_path: entry.result_path,
1567
- });
1927
+ if (!judged.ok) {
1928
+ issues.push(judged.issue);
1568
1929
  continue;
1569
1930
  }
1570
- // S7 quote-and-verify: the tool re-reads each cited span from disk, stamps
1571
- // the verdict, and writes each entry's line numbers from where its quote
1572
- // occurs. It NEVER rejects — a quote that is absent or occurs more than
1573
- // once rides through as `ungrounded` and synthesis surfaces it under
1574
- // "Ungrounded Findings (not confirmed)"; refusing here would discard the
1575
- // whole submission over one bad citation. It mutates the CONVERTED copy
1576
- // only: `result` stays the host's submission, which `result_sha256` hashes.
1577
- // It runs BEFORE validation, so the derived span meets the same coverage
1578
- // rule here that the downstream batch gate applies: a span that rule would
1579
- // refuse is refused while the item can still be resubmitted, never
1580
- // accepted and then replayed into a failing gate on every later step.
1581
- for (const finding of converted.auditResult.findings) {
1582
- knownPaths ??= await enumerateTrackedFilePaths(boundarySourceRoot(paths));
1583
- await groundFinding(boundarySourceRoot(paths), finding, readSource, knownPaths);
1584
- }
1585
- // VALIDATE BEFORE ACCEPT. The conversion above proves only the envelope
1586
- // contract (`FindingSchema` admits an evidence-less finding); these are the
1587
- // per-result rules the downstream batch gate applies, applied HERE so an
1588
- // error-severity issue never reaches the accepted pair. A rejected item is
1589
- // simply never in the ledger, so the corrected file at the same bound path
1590
- // is re-read on the next fold — acceptance used to be terminal instead, and
1591
- // a failed batch gate then wedged the run permanently.
1592
- //
1593
- // Orphans (task pruned by a re-plan) pass through UNVALIDATED with the same
1594
- // stderr notice the batch gate uses — never newly rejected: refusing one
1595
- // here would strand it outside the append-only ledger entirely.
1596
- if (!activeTaskIds.has(entry.work_item_id)) {
1597
- process.stderr.write(`audit host-handoff ingest: result for '${entry.work_item_id}' is not in the ` +
1598
- `active task manifest (orphaned by re-planning); retained in the accepted pair ` +
1599
- `but skipped at the validation gate\n`);
1600
- }
1601
- else {
1602
- const validationIssues = validateOneAuditResult(converted.auditResult, [
1603
- ...params.auditTasks,
1604
- ], {
1605
- lineIndex: params.lineIndex,
1606
- });
1607
- const errors = validationIssues.filter((issue) => issue.severity === "error");
1608
- if (errors.length > 0) {
1609
- issues.push({
1610
- code: "result_validation_failed",
1611
- check: "result_validation",
1612
- message: `work item '${entry.work_item_id}' failed audit-results validation ` +
1613
- `(${errors.length} error(s)); fix the result file at its bound path and call next-step again: ` +
1614
- formatAuditResultIssues(errors),
1615
- work_item_id: entry.work_item_id,
1616
- result_path: entry.result_path,
1617
- });
1618
- continue;
1619
- }
1620
- // Warnings are NOT rejections: an accepted result never refused anything,
1621
- // so a warning must never reach the rejection-classified issue list — the
1622
- // ONE ledger recorder would otherwise record kind:'rejected' for a result
1623
- // that was accepted, manufacturing a repair story that never happened.
1624
- // They ride the separate advisory channel instead (rendered for the
1625
- // operator; never counted as a submission that could not be accepted).
1626
- validation_warnings.push(...validationIssues
1627
- .filter((issue) => issue.severity === "warning")
1628
- .map((warning) => ({
1629
- work_item_id: entry.work_item_id,
1630
- result_path: entry.result_path,
1631
- message: `${warning.message} (${warning.field})`,
1632
- })));
1633
- }
1931
+ validation_warnings.push(...judged.warnings);
1932
+ const { result, auditResult } = judged;
1634
1933
  resultIds.add(result.result_id);
1635
1934
  // construction-site: AuditResult
1636
1935
  // construction-site: Finding (the `findings` array; `lens` defaults from the enclosing contract, already spread in)
@@ -1641,7 +1940,7 @@ export async function ingestAuditHostResults(params) {
1641
1940
  result_id: result.result_id,
1642
1941
  result_sha256: contentSha256(result),
1643
1942
  result,
1644
- audit_result: converted.auditResult,
1943
+ audit_result: auditResult,
1645
1944
  });
1646
1945
  }
1647
1946
  // Binding reads, validation and this accepted pair write share ONE hold.