@tangle-network/agent-eval 0.174.0 → 0.176.0

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 (128) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/http.d.ts +1 -1
  4. package/dist/agent-profile-cell-0gSi5ffD.js +374 -0
  5. package/dist/agent-profile-cell-0gSi5ffD.js.map +1 -0
  6. package/dist/analyst/index.d.ts +3 -3
  7. package/dist/analyst/index.js +4 -4
  8. package/dist/{benchmark-command-mZIlR-ra.js → benchmark-command-yPqjcZnC.js} +7 -7
  9. package/dist/{benchmark-command-mZIlR-ra.js.map → benchmark-command-yPqjcZnC.js.map} +1 -1
  10. package/dist/benchmarks/index.d.ts +1 -1
  11. package/dist/benchmarks/index.js +3 -3
  12. package/dist/campaign/index.d.ts +3 -3
  13. package/dist/campaign/index.js +9 -9
  14. package/dist/{campaign-BzMSCejE.js → campaign-85igdlgG.js} +12 -12
  15. package/dist/{campaign-BzMSCejE.js.map → campaign-85igdlgG.js.map} +1 -1
  16. package/dist/campaign-evidence-D8DBLqLI.js +2083 -0
  17. package/dist/campaign-evidence-D8DBLqLI.js.map +1 -0
  18. package/dist/{opencode-sqlite-eK6HW6dr.js → claude-jsonl-CxZZrDJ3.js} +9 -149
  19. package/dist/claude-jsonl-CxZZrDJ3.js.map +1 -0
  20. package/dist/cli.js +9 -2
  21. package/dist/cli.js.map +1 -1
  22. package/dist/contract/index.d.ts +4 -4
  23. package/dist/contract/index.js +9 -9
  24. package/dist/{default-registry-CrAp0pYq.js → default-registry-DBqVI4pq.js} +2 -2
  25. package/dist/{default-registry-CrAp0pYq.js.map → default-registry-DBqVI4pq.js.map} +1 -1
  26. package/dist/{define-agent-eval-V1jQyCDR.d.ts → define-agent-eval-CCbl8k2E.d.ts} +11 -4
  27. package/dist/define-agent-eval-CCbl8k2E.d.ts.map +1 -0
  28. package/dist/{define-agent-eval-ox5McL6e.js → define-agent-eval-DEMsu5eA.js} +54 -36
  29. package/dist/define-agent-eval-DEMsu5eA.js.map +1 -0
  30. package/dist/{dspy-rlm-engine-Caz2pl4L.js → dspy-rlm-engine-DqjER2sV.js} +2 -2
  31. package/dist/{dspy-rlm-engine-Caz2pl4L.js.map → dspy-rlm-engine-DqjER2sV.js.map} +1 -1
  32. package/dist/{eval-campaign-BeAjdhzC.js → eval-campaign-Cs-7MiCs.js} +4 -5
  33. package/dist/{eval-campaign-BeAjdhzC.js.map → eval-campaign-Cs-7MiCs.js.map} +1 -1
  34. package/dist/experiment/index.d.ts +3 -68
  35. package/dist/experiment/index.d.ts.map +1 -1
  36. package/dist/experiment/index.js +6 -128
  37. package/dist/experiment/index.js.map +1 -1
  38. package/dist/{attestation-XSUpbc4o.js → experiment-tracker-BKEumQug.js} +2 -96
  39. package/dist/experiment-tracker-BKEumQug.js.map +1 -0
  40. package/dist/{attestation-c1QvaBdX.d.ts → experiment-tracker-CNwqCZFD.d.ts} +2 -78
  41. package/dist/experiment-tracker-CNwqCZFD.d.ts.map +1 -0
  42. package/dist/{external-optimizer-process-CxnFL1hd.js → external-optimizer-process-Dlz8YxrT.js} +3 -3
  43. package/dist/{external-optimizer-process-CxnFL1hd.js.map → external-optimizer-process-Dlz8YxrT.js.map} +1 -1
  44. package/dist/{external-optimizer-subprocess-CQi27uEI.js → external-optimizer-subprocess-q3VzlGAO.js} +2 -2
  45. package/dist/{external-optimizer-subprocess-CQi27uEI.js.map → external-optimizer-subprocess-q3VzlGAO.js.map} +1 -1
  46. package/dist/{index-Bn-nlnSV.d.ts → index-BAAiSF3_.d.ts} +2 -2
  47. package/dist/{index-Bn-nlnSV.d.ts.map → index-BAAiSF3_.d.ts.map} +1 -1
  48. package/dist/{index-DKXuBPXf.d.ts → index-Bg6OT2Dd.d.ts} +23 -10
  49. package/dist/{index-DKXuBPXf.d.ts.map → index-Bg6OT2Dd.d.ts.map} +1 -1
  50. package/dist/{index-BTrx5s8m.d.ts → index-DBkcm_9H.d.ts} +4 -4
  51. package/dist/{index-BTrx5s8m.d.ts.map → index-DBkcm_9H.d.ts.map} +1 -1
  52. package/dist/{index-D-UdhAmg.d.ts → index-u0d1Jp4F.d.ts} +4 -2
  53. package/dist/{index-D-UdhAmg.d.ts.map → index-u0d1Jp4F.d.ts.map} +1 -1
  54. package/dist/index.d.ts +5 -5
  55. package/dist/index.js +15 -16
  56. package/dist/index.js.map +1 -1
  57. package/dist/{integrity-BWywb34E.js → integrity-DsHWCebQ.js} +11 -435
  58. package/dist/integrity-DsHWCebQ.js.map +1 -0
  59. package/dist/ledger-core/index.d.ts +2 -2
  60. package/dist/ledger-core/index.js +2 -2
  61. package/dist/{ledger-core-PIfjCbKn.js → ledger-core-Cs9f7385.js} +60 -47
  62. package/dist/{ledger-core-PIfjCbKn.js.map → ledger-core-Cs9f7385.js.map} +1 -1
  63. package/dist/{llm-judge-DmNaBrXB.js → llm-judge-DliimmRb.js} +994 -1517
  64. package/dist/llm-judge-DliimmRb.js.map +1 -0
  65. package/dist/{mint-vWOdD8Ae.js → mint-Cc1_zwRQ.js} +2 -2
  66. package/dist/{mint-vWOdD8Ae.js.map → mint-Cc1_zwRQ.js.map} +1 -1
  67. package/dist/openapi.json +1 -1
  68. package/dist/opencode-sqlite-CNw3vubS.js +145 -0
  69. package/dist/opencode-sqlite-CNw3vubS.js.map +1 -0
  70. package/dist/{produced-state-B8mw6zj9.js → produced-state-DrMqa2HD.js} +3 -2
  71. package/dist/{produced-state-B8mw6zj9.js.map → produced-state-DrMqa2HD.js.map} +1 -1
  72. package/dist/profile-cell.js +1 -268
  73. package/dist/{promotion-policy-LY9mVQ7W.js → promotion-policy-DWOm70gx.js} +2 -2
  74. package/dist/{promotion-policy-LY9mVQ7W.js.map → promotion-policy-DWOm70gx.js.map} +1 -1
  75. package/dist/{release-confidence-BsGEg_xg.js → release-confidence-BcGCclTB.js} +2 -2
  76. package/dist/{release-confidence-BsGEg_xg.js.map → release-confidence-BcGCclTB.js.map} +1 -1
  77. package/dist/report-command-DKlXfU5r.js +1528 -0
  78. package/dist/report-command-DKlXfU5r.js.map +1 -0
  79. package/dist/reporting.js +2 -2
  80. package/dist/{reward-hacking-CKW4teig.js → reward-hacking-D0XwhVWE.js} +2 -215
  81. package/dist/reward-hacking-D0XwhVWE.js.map +1 -0
  82. package/dist/rl.js +5 -4
  83. package/dist/rl.js.map +1 -1
  84. package/dist/rollout/index.js +4 -3
  85. package/dist/{rollout-C-znbbYg.js → rollout-DmoJVqrF.js} +4 -3
  86. package/dist/{rollout-C-znbbYg.js.map → rollout-DmoJVqrF.js.map} +1 -1
  87. package/dist/run-record-CR63CpHK.js +216 -0
  88. package/dist/run-record-CR63CpHK.js.map +1 -0
  89. package/dist/{run-record-ZIsR9Fif.js → run-record-DQpSf7t-.js} +2 -2
  90. package/dist/{run-record-ZIsR9Fif.js.map → run-record-DQpSf7t-.js.map} +1 -1
  91. package/dist/{semantic-concept-judge-E3s_fEjB.js → semantic-concept-judge-Dw-f7TEs.js} +3 -3
  92. package/dist/{semantic-concept-judge-E3s_fEjB.js.map → semantic-concept-judge-Dw-f7TEs.js.map} +1 -1
  93. package/dist/{sequential-B51qAYE4.js → sequential-B5gXgcyp.js} +3 -3
  94. package/dist/{sequential-B51qAYE4.js.map → sequential-B5gXgcyp.js.map} +1 -1
  95. package/dist/{skillopt-optimization-method-f7399oGb.js → skillopt-optimization-method-CV7go7ex.js} +6 -749
  96. package/dist/skillopt-optimization-method-CV7go7ex.js.map +1 -0
  97. package/dist/{statistical-heldout-Cqb73yE9.d.ts → statistical-heldout-Z9NROFFS.d.ts} +156 -3
  98. package/dist/statistical-heldout-Z9NROFFS.d.ts.map +1 -0
  99. package/dist/{summary-report-Bgh8CpNK.js → summary-report-B16xy9Kd.js} +2 -2
  100. package/dist/{summary-report-Bgh8CpNK.js.map → summary-report-B16xy9Kd.js.map} +1 -1
  101. package/dist/supervisor-run/index.d.ts +71 -6
  102. package/dist/supervisor-run/index.d.ts.map +1 -1
  103. package/dist/supervisor-run/index.js +6 -1357
  104. package/dist/supervisor-run/index.js.map +1 -1
  105. package/dist/terminal-record-Ce9_UjRz.js +539 -0
  106. package/dist/terminal-record-Ce9_UjRz.js.map +1 -0
  107. package/dist/traces.js +1 -1
  108. package/dist/{types-CoPUTiXb.d.ts → types-vUdAx2Cj.d.ts} +65 -3
  109. package/dist/types-vUdAx2Cj.d.ts.map +1 -0
  110. package/docs/public-api.md +62 -39
  111. package/docs/search-history-receipts.md +48 -1
  112. package/package.json +1 -1
  113. package/dist/attestation-XSUpbc4o.js.map +0 -1
  114. package/dist/attestation-c1QvaBdX.d.ts.map +0 -1
  115. package/dist/define-agent-eval-V1jQyCDR.d.ts.map +0 -1
  116. package/dist/define-agent-eval-ox5McL6e.js.map +0 -1
  117. package/dist/integrity-BWywb34E.js.map +0 -1
  118. package/dist/llm-judge-DmNaBrXB.js.map +0 -1
  119. package/dist/opencode-sqlite-eK6HW6dr.js.map +0 -1
  120. package/dist/power-preflight-CFXm0Vjo.js +0 -502
  121. package/dist/power-preflight-CFXm0Vjo.js.map +0 -1
  122. package/dist/pre-registration-D94b7Of5.js +0 -110
  123. package/dist/pre-registration-D94b7Of5.js.map +0 -1
  124. package/dist/profile-cell.js.map +0 -1
  125. package/dist/reward-hacking-CKW4teig.js.map +0 -1
  126. package/dist/skillopt-optimization-method-f7399oGb.js.map +0 -1
  127. package/dist/statistical-heldout-Cqb73yE9.d.ts.map +0 -1
  128. package/dist/types-CoPUTiXb.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integrity-DsHWCebQ.js","names":[],"sources":["../src/supervisor-run/integrity-issues.ts","../src/supervisor-run/integrity-steer.ts","../src/supervisor-run/integrity-source.ts","../src/supervisor-run/integrity-tree.ts","../src/supervisor-run/integrity-types.ts","../src/supervisor-run/rollout-nodes.ts","../src/supervisor-run/integrity.ts"],"sourcesContent":["import type { SupervisorRunIntegrityEvidence, SupervisorRunIntegrityIssue } from './integrity-types'\n\nexport const MAX_EXAMPLES = 20\n\nexport function evidence(path: string, value: unknown): SupervisorRunIntegrityEvidence {\n return { path, value }\n}\n\nexport function issue(\n init: Omit<SupervisorRunIntegrityIssue, 'evidence'> & {\n evidence?: readonly SupervisorRunIntegrityEvidence[]\n },\n): SupervisorRunIntegrityIssue {\n return { ...init, evidence: init.evidence ?? [] }\n}\n","import { evidence, issue, MAX_EXAMPLES } from './integrity-issues'\nimport type { JoinedWorker } from './integrity-source'\nimport type { SupervisorRunIntegrityIssue } from './integrity-types'\n\nfunction idListDetail(ids: readonly string[]): string {\n const examples = ids\n .slice(0, MAX_EXAMPLES)\n .map((id) => JSON.stringify(id))\n .join(', ')\n return ids.length <= MAX_EXAMPLES\n ? examples\n : `${examples}, and ${ids.length - MAX_EXAMPLES} more`\n}\n\nexport function steerIssues(\n joined: JoinedWorker,\n rootCompleted: boolean,\n): SupervisorRunIntegrityIssue[] {\n const { facts } = joined\n const subject = facts.workerId ?? joined.spawn.id\n const prefix = `workers/${facts.sourceIndex}`\n const out: SupervisorRunIntegrityIssue[] = []\n if (\n !facts.inboxCaptured ||\n !facts.eventsCaptured ||\n facts.inboxInvalidRows > 0 ||\n facts.eventsInvalidRows > 0\n ) {\n const missing = [\n ...(facts.inboxCaptured ? [] : ['inbox']),\n ...(facts.eventsCaptured ? [] : ['events']),\n ]\n const malformed = [\n ...(facts.inboxInvalidRows > 0 ? [`inbox:${facts.inboxInvalidRows}`] : []),\n ...(facts.eventsInvalidRows > 0 ? [`events:${facts.eventsInvalidRows}`] : []),\n ]\n out.push(\n issue({\n code: 'worker-controls-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject,\n claim:\n 'Steer delivery integrity is unavailable for a worker with missing control artifacts',\n detail:\n missing.length > 0\n ? `${JSON.stringify(subject)} is missing ${missing.join(' and ')}.`\n : `${JSON.stringify(subject)} has malformed control rows (${malformed.join(', ')}).`,\n evidence: [\n ...missing.map((artifact) => evidence(`${prefix}/${artifact}`, null)),\n ...(facts.inboxInvalidRows > 0\n ? [evidence(`${prefix}/inbox/malformed-rows/count`, facts.inboxInvalidRows)]\n : []),\n ...(facts.eventsInvalidRows > 0\n ? [evidence(`${prefix}/events/malformed-rows/count`, facts.eventsInvalidRows)]\n : []),\n ],\n recommendedAction:\n 'Retain both control artifacts and repair malformed rows before correlating requests.',\n metadata: {\n assessment: 'unavailable',\n missing_artifacts: missing,\n malformed_rows: malformed,\n },\n }),\n )\n return out\n }\n\n const requestsById = new Map<string, typeof facts.steerRequests>()\n const unidentifiedRequests = facts.steerRequests.filter((request) => request.requestId === null)\n for (const request of facts.steerRequests) {\n if (request.requestId === null) continue\n const rows = requestsById.get(request.requestId) ?? []\n rows.push(request)\n requestsById.set(request.requestId, rows)\n }\n if (unidentifiedRequests.length > 0) {\n out.push(\n issue({\n code: 'steer-request-id-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject,\n claim: 'Some queued steer requests cannot be correlated because their ids are missing',\n detail: `${unidentifiedRequests.length} queued request(s) omit id.`,\n evidence: unidentifiedRequests\n .slice(0, MAX_EXAMPLES)\n .map((request) => evidence(`${prefix}/inbox/${request.row}/id`, null)),\n recommendedAction: 'Assign one stable request id before appending a steer to the inbox.',\n metadata: { assessment: 'unavailable', unavailable_count: unidentifiedRequests.length },\n }),\n )\n }\n const duplicateRequestIds = [...requestsById]\n .filter(([, rows]) => rows.length > 1)\n .map(([id]) => id)\n if (duplicateRequestIds.length > 0) {\n out.push(\n issue({\n code: 'duplicate-steer-request-id',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A worker inbox contains duplicate steer request ids',\n detail: `${duplicateRequestIds.length} duplicate id(s): ${idListDetail(duplicateRequestIds)}.`,\n evidence: [\n evidence(\n `${prefix}/inbox/duplicate-request-ids`,\n duplicateRequestIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction: 'Generate a unique request id for every queued steer.',\n }),\n )\n }\n\n const acknowledgementsById = new Map<string, typeof facts.steerAcknowledgements>()\n const unidentifiedAcks = facts.steerAcknowledgements.filter((ack) => ack.requestId === null)\n for (const ack of facts.steerAcknowledgements) {\n if (ack.requestId === null) continue\n const rows = acknowledgementsById.get(ack.requestId) ?? []\n rows.push(ack)\n acknowledgementsById.set(ack.requestId, rows)\n }\n if (unidentifiedAcks.length > 0) {\n out.push(\n issue({\n code: 'steer-ack-id-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject,\n claim: 'Some steer acknowledgements cannot be correlated because requestId is missing',\n detail: `${unidentifiedAcks.length} down-leg event(s) omit requestId.`,\n evidence: unidentifiedAcks\n .slice(0, MAX_EXAMPLES)\n .map((ack) => evidence(`${prefix}/events/${ack.row}/requestId`, null)),\n recommendedAction: 'Echo the queued request id on every worker acknowledgement.',\n metadata: { assessment: 'unavailable', unavailable_count: unidentifiedAcks.length },\n }),\n )\n }\n\n const unknownAckIds = [...acknowledgementsById.keys()].filter((id) => !requestsById.has(id))\n if (unknownAckIds.length > 0) {\n out.push(\n issue({\n code: 'unknown-steer-ack',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A worker acknowledged steer request ids absent from its captured inbox',\n detail: `${unknownAckIds.length} unknown id(s): ${idListDetail(unknownAckIds)}.`,\n evidence: [\n evidence(`${prefix}/events/unknown-request-ids`, unknownAckIds.slice(0, MAX_EXAMPLES)),\n ],\n recommendedAction:\n 'Reject acknowledgements whose request id was not queued for this worker.',\n }),\n )\n }\n\n const duplicateAckIds = [...acknowledgementsById]\n .filter(([, rows]) => rows.length > 1)\n .map(([id]) => id)\n if (duplicateAckIds.length > 0) {\n out.push(\n issue({\n code: 'duplicate-steer-ack',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A worker emitted duplicate acknowledgements for steer request ids',\n detail: `${duplicateAckIds.length} duplicated id(s): ${idListDetail(duplicateAckIds)}.`,\n evidence: [\n evidence(\n `${prefix}/events/duplicate-request-ids`,\n duplicateAckIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction: 'Make steer acknowledgement append idempotent by request id.',\n }),\n )\n }\n\n const missingAckIds = [...requestsById.keys()].filter((id) => !acknowledgementsById.has(id))\n if (rootCompleted && missingAckIds.length > 0) {\n out.push(\n issue({\n code: 'missing-steer-ack',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A completed supervisor run has queued steer requests without acknowledgements',\n detail: `${missingAckIds.length}/${requestsById.size} request id(s) are unacknowledged: ${idListDetail(missingAckIds)}.`,\n evidence: [\n evidence(\n `${prefix}/inbox/unacknowledged-request-ids`,\n missingAckIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction:\n 'Record one delivered or failed acknowledgement for every queued request id.',\n }),\n )\n }\n\n const statusUnavailableIds: string[] = []\n const notDeliveredIds: string[] = []\n for (const [id, acknowledgements] of acknowledgementsById) {\n if (!requestsById.has(id) || acknowledgements.length !== 1) continue\n const delivered = acknowledgements[0]?.delivered\n if (delivered === null || delivered === undefined) statusUnavailableIds.push(id)\n else if (!delivered) notDeliveredIds.push(id)\n }\n if (statusUnavailableIds.length > 0) {\n out.push(\n issue({\n code: 'steer-ack-status-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject,\n claim: 'Some steer acknowledgements omit delivery status',\n detail: `${statusUnavailableIds.length} id(s): ${idListDetail(statusUnavailableIds)}.`,\n evidence: [\n evidence(\n `${prefix}/events/status-unavailable-request-ids`,\n statusUnavailableIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction: 'Record delivered: true or delivered: false on each acknowledgement.',\n metadata: { assessment: 'unavailable', unavailable_count: statusUnavailableIds.length },\n }),\n )\n }\n if (notDeliveredIds.length > 0) {\n out.push(\n issue({\n code: 'steer-not-delivered',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'Queued steer requests were acknowledged but not delivered',\n detail: `${notDeliveredIds.length} id(s): ${idListDetail(notDeliveredIds)}.`,\n evidence: [\n evidence(\n `${prefix}/events/not-delivered-request-ids`,\n notDeliveredIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction:\n 'Retry or explicitly fail the control request instead of treating it as delivered.',\n }),\n )\n }\n return out\n}\n","import { evidence, issue, MAX_EXAMPLES } from './integrity-issues'\nimport { steerIssues } from './integrity-steer'\nimport type { SupervisorRunIntegrityIssue } from './integrity-types'\nimport type { SpawnRow, SupervisorTreeFacts, WorkerLogFacts } from './source-facts'\nimport type { SupervisorRunSources, SupervisorRunTree } from './types'\n\nfunction sourceIdentityIssues(facts: SupervisorTreeFacts): SupervisorRunIntegrityIssue[] {\n const out: SupervisorRunIntegrityIssue[] = []\n const malformedSpawns = facts.spawns.filter((spawn) => !spawn.valid)\n if (facts.journalInvalidRows > 0 || malformedSpawns.length > 0) {\n out.push(\n issue({\n code: 'source-row-malformed',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'journal-rows',\n claim: 'Some supervisor journal rows could not be interpreted',\n detail: `${facts.journalInvalidRows} of ${facts.journalRows} row(s) could not be interpreted (${facts.journalMalformedJsonRows} were not JSON objects) and ${malformedSpawns.length} malformed spawn row(s) were excluded from structural conclusions.`,\n evidence: [\n evidence('journal/uninterpretable-rows/count', facts.journalInvalidRows),\n evidence('journal/malformed-json-rows/count', facts.journalMalformedJsonRows),\n evidence('journal/rows/count', facts.journalRows),\n evidence('journal/dialect', facts.journalDialect),\n ...malformedSpawns\n .slice(0, MAX_EXAMPLES)\n .map((spawn) =>\n evidence(`journal/spawns/${spawn.sourceRow}/invalid-fields`, spawn.invalidFields),\n ),\n ],\n recommendedAction:\n 'Repair the rows, or teach the parser the shape they are in, before using the run for structural analysis. A row nobody can read must never be silently absent from the tree.',\n metadata: {\n assessment: 'unavailable',\n journal_rows: facts.journalRows,\n uninterpretable_rows: facts.journalInvalidRows,\n malformed_json_rows: facts.journalMalformedJsonRows,\n malformed_spawn_rows: malformedSpawns.length,\n journal_dialect: facts.journalDialect,\n },\n }),\n )\n }\n const unidentifiedSpawns = malformedSpawns.filter((spawn) => spawn.id.length === 0)\n const unidentifiedCloses = facts.closes.filter((close) => close.id.length === 0)\n if (unidentifiedSpawns.length + unidentifiedCloses.length > 0) {\n out.push(\n issue({\n code: 'source-event-identity-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'journal-event-identity',\n claim: 'Some supervisor journal events have no usable invocation id',\n detail: `${unidentifiedSpawns.length} spawn and ${unidentifiedCloses.length} terminal event(s) lack an id.`,\n evidence: [\n evidence('journal/unidentified-spawns/count', unidentifiedSpawns.length),\n evidence('journal/unidentified-terminals/count', unidentifiedCloses.length),\n ],\n recommendedAction: 'Reject or repair control events that omit their stable invocation id.',\n metadata: { assessment: 'unavailable', checks: ['journal-event-linkage'] },\n }),\n )\n }\n\n const spawnCounts = new Map<string, number>()\n for (const spawn of facts.spawns) {\n if (!spawn.valid || spawn.id.length === 0) continue\n spawnCounts.set(spawn.id, (spawnCounts.get(spawn.id) ?? 0) + 1)\n }\n for (const [id, count] of spawnCounts) {\n if (count < 2) continue\n out.push(\n issue({\n code: 'duplicate-spawn',\n area: 'control-integrity',\n severity: 'critical',\n subject: id,\n claim: 'An invocation has more than one spawned control event',\n detail: `${count} spawned events name invocation ${JSON.stringify(id)}.`,\n evidence: [evidence(`journal/spawn-count/${encodeURIComponent(id)}`, count)],\n recommendedAction: 'Make spawn event append idempotent.',\n }),\n )\n }\n\n const closeCounts = new Map<string, number>()\n for (const close of facts.closes) {\n if (close.id.length === 0) continue\n closeCounts.set(close.id, (closeCounts.get(close.id) ?? 0) + 1)\n }\n const uncertainSpawnIds = new Set(\n malformedSpawns.filter((spawn) => spawn.id.length > 0).map((spawn) => spawn.id),\n )\n if (unidentifiedSpawns.length === 0 && facts.journalInvalidRows === 0) {\n const orphanCloses = new Map<string, Array<(typeof facts.closes)[number]>>()\n for (const close of facts.closes) {\n if (close.id.length === 0 || spawnCounts.has(close.id) || uncertainSpawnIds.has(close.id)) {\n continue\n }\n const rows = orphanCloses.get(close.id) ?? []\n rows.push(close)\n orphanCloses.set(close.id, rows)\n }\n for (const [id, closes] of orphanCloses) {\n out.push(\n issue({\n code: 'orphan-terminal',\n area: 'control-integrity',\n severity: 'critical',\n subject: id,\n claim: 'A terminal control event names an invocation that was never spawned',\n detail: `${closes.length} terminal event(s) for ${JSON.stringify(id)} have no matching spawn.`,\n evidence: [\n evidence(`journal/closes/${encodeURIComponent(id)}/count`, closes.length),\n ...closes\n .slice(0, MAX_EXAMPLES)\n .map((close, index) =>\n evidence(`journal/closes/${encodeURIComponent(id)}/${index}`, close),\n ),\n ],\n recommendedAction: 'Retain the matching spawn event or reject the orphan terminal event.',\n }),\n )\n }\n }\n for (const [id, count] of closeCounts) {\n if (count < 2) continue\n out.push(\n issue({\n code: 'duplicate-terminal',\n area: 'control-integrity',\n severity: 'critical',\n subject: id,\n claim: 'An invocation has more than one terminal control event',\n detail: `${count} settled/cancelled events name invocation ${JSON.stringify(id)}.`,\n evidence: [evidence(`journal/terminal-count/${encodeURIComponent(id)}`, count)],\n recommendedAction: 'Make terminal event append idempotent.',\n }),\n )\n }\n return out\n}\n\nexport interface JoinedWorker {\n readonly spawn: SpawnRow\n readonly facts: WorkerLogFacts\n}\n\nfunction joinWorkerControls(facts: SupervisorTreeFacts): {\n joined: JoinedWorker[]\n issue: SupervisorRunIntegrityIssue | null\n} {\n const spawnsById = new Map<string, SpawnRow[]>()\n const spawnsByLabel = new Map<string, SpawnRow[]>()\n for (const spawn of facts.workerSpawns) {\n const ids = spawnsById.get(spawn.id) ?? []\n ids.push(spawn)\n spawnsById.set(spawn.id, ids)\n const labels = spawnsByLabel.get(spawn.label) ?? []\n labels.push(spawn)\n spawnsByLabel.set(spawn.label, labels)\n }\n const rowsWithoutIdByLabel = new Map<string, WorkerLogFacts[]>()\n for (const row of facts.workerLogRows) {\n if (row.workerId !== null && row.workerId.length > 0) continue\n const matches = rowsWithoutIdByLabel.get(row.label) ?? []\n matches.push(row)\n rowsWithoutIdByLabel.set(row.label, matches)\n }\n\n const rowsBySpawn = new Map<string, WorkerLogFacts[]>()\n const unmatchedRows: number[] = []\n const ambiguousRows: number[] = []\n for (const row of facts.workerLogRows) {\n const matches =\n row.workerId !== null && row.workerId.length > 0\n ? (spawnsById.get(row.workerId) ?? [])\n : (rowsWithoutIdByLabel.get(row.label)?.length ?? 0) === 1\n ? (spawnsByLabel.get(row.label) ?? [])\n : []\n if (matches.length === 0) {\n unmatchedRows.push(row.sourceIndex)\n continue\n }\n if (matches.length !== 1) {\n ambiguousRows.push(row.sourceIndex)\n continue\n }\n const spawn = matches[0] as SpawnRow\n const joined = rowsBySpawn.get(spawn.id) ?? []\n joined.push(row)\n rowsBySpawn.set(spawn.id, joined)\n }\n\n const joined: JoinedWorker[] = []\n const missingSpawnIds: string[] = []\n const duplicateSpawnIds: string[] = []\n for (const spawn of facts.workerSpawns) {\n if ((spawnsById.get(spawn.id)?.length ?? 0) !== 1) continue\n const rows = rowsBySpawn.get(spawn.id) ?? []\n if (rows.length === 0) missingSpawnIds.push(spawn.id)\n else if (rows.length > 1) duplicateSpawnIds.push(spawn.id)\n else joined.push({ spawn, facts: rows[0] as WorkerLogFacts })\n }\n\n if (\n missingSpawnIds.length === 0 &&\n duplicateSpawnIds.length === 0 &&\n unmatchedRows.length === 0 &&\n ambiguousRows.length === 0\n ) {\n return { joined, issue: null }\n }\n return {\n joined,\n issue: issue({\n code: 'worker-control-join-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'worker-control-join',\n claim: 'Worker control-log coverage does not match recorded child invocations',\n detail: `${missingSpawnIds.length} spawn(s) have no log, ${duplicateSpawnIds.length} have duplicate logs, ${unmatchedRows.length} log row(s) match no spawn, and ${ambiguousRows.length} row(s) are ambiguous.`,\n evidence: [\n evidence('workers/join/missing-spawn-ids', missingSpawnIds.slice(0, MAX_EXAMPLES)),\n evidence('workers/join/duplicate-spawn-ids', duplicateSpawnIds.slice(0, MAX_EXAMPLES)),\n evidence('workers/join/unmatched-source-rows', unmatchedRows.slice(0, MAX_EXAMPLES)),\n evidence('workers/join/ambiguous-source-rows', ambiguousRows.slice(0, MAX_EXAMPLES)),\n ],\n recommendedAction:\n 'Retain exactly one worker control row with workerId for every spawned invocation.',\n metadata: {\n assessment: 'unavailable',\n missing_count: missingSpawnIds.length,\n duplicate_count: duplicateSpawnIds.length,\n unmatched_count: unmatchedRows.length,\n ambiguous_count: ambiguousRows.length,\n },\n }),\n }\n}\n\nexport function sourceIssues(\n source: SupervisorRunSources,\n facts: SupervisorTreeFacts,\n tree: SupervisorRunTree,\n): SupervisorRunIntegrityIssue[] {\n const out = sourceIdentityIssues(facts)\n if (source.workers === null) {\n const reason = source.workersMissingReason ?? 'worker control-log store was not captured'\n out.push(\n issue({\n code: 'worker-controls-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'steer-delivery',\n claim:\n 'Steer delivery integrity is unavailable because worker control logs were not captured',\n detail: reason,\n evidence: [evidence('sources/workers', null)],\n recommendedAction: 'Retain each worker inbox and event stream.',\n metadata: { assessment: 'unavailable', reason },\n }),\n )\n return out\n }\n\n const joined = joinWorkerControls(facts)\n if (joined.issue !== null) out.push(joined.issue)\n const rootCompleted =\n tree.rootId !== null &&\n tree.nodes.filter((node) => node.rollout_id === tree.rootId).length === 1 &&\n tree.nodes.find((node) => node.rollout_id === tree.rootId)?.outcome.is_completed === true\n for (const row of joined.joined) out.push(...steerIssues(row, rootCompleted))\n return out\n}\n","import { validateRolloutLine } from '../rollout/schema'\nimport { evidence, issue, MAX_EXAMPLES } from './integrity-issues'\nimport type { SupervisorRunIntegrityEvidence, SupervisorRunIntegrityIssue } from './integrity-types'\nimport type { SupervisorRunTree } from './types'\n\ninterface NodeRecord {\n readonly index: number\n readonly raw: Record<string, unknown>\n readonly errors: readonly string[]\n readonly id: string | null\n readonly parent: string | null | undefined\n readonly runId: string | null\n readonly role: string | null\n readonly messages: readonly unknown[] | null\n readonly profileId: string | null\n readonly completed: boolean | null\n readonly terminal: boolean | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction parentValue(raw: Record<string, unknown>): string | null | undefined {\n if (raw.parent_rollout_id === null) return null\n return nonEmptyString(raw.parent_rollout_id) ?? undefined\n}\n\nfunction terminalValue(outcome: Record<string, unknown> | null): boolean | null {\n if (outcome === null) return null\n if (typeof outcome.is_completed !== 'boolean' || typeof outcome.is_truncated !== 'boolean') {\n return null\n }\n if (outcome.error !== null && typeof outcome.error !== 'string') return null\n return outcome.is_completed || outcome.is_truncated || outcome.error !== null\n}\n\nfunction nodeRecord(value: unknown, index: number): NodeRecord {\n const raw = isRecord(value) ? value : {}\n const policy = isRecord(raw.policy) ? raw.policy : null\n const outcome = isRecord(raw.outcome) ? raw.outcome : null\n return {\n index,\n raw,\n errors: validateRolloutLine(value),\n id: nonEmptyString(raw.rollout_id),\n parent: parentValue(raw),\n runId: nonEmptyString(raw.run_id),\n role: nonEmptyString(raw.role),\n messages: Array.isArray(raw.messages) ? raw.messages : null,\n profileId: policy === null ? null : nonEmptyString(policy.agent_profile_cell_id),\n completed:\n outcome !== null && typeof outcome.is_completed === 'boolean' ? outcome.is_completed : null,\n terminal: terminalValue(outcome),\n }\n}\n\nfunction metric(\n record: NodeRecord,\n keys: readonly string[],\n): { key: string; value: number } | null {\n const outcome = isRecord(record.raw.outcome) ? record.raw.outcome : null\n const metrics = outcome !== null && isRecord(outcome.metrics) ? outcome.metrics : null\n if (metrics === null) return null\n for (const key of keys) {\n const value = metrics[key]\n if (typeof value === 'number' && Number.isFinite(value)) return { key, value }\n }\n return null\n}\n\nfunction nodeEvidence(\n record: NodeRecord,\n path: string,\n value: unknown,\n): SupervisorRunIntegrityEvidence {\n const key = record.id ?? `index-${record.index}`\n return evidence(`nodes/${encodeURIComponent(key)}/${path}`, value)\n}\n\nfunction unavailableNodeChecks(record: NodeRecord): string[] {\n const checks: string[] = []\n if (record.id === null) checks.push('identity', 'root-membership', 'parent-link', 'cycle')\n if (record.parent === undefined) checks.push('parent-link', 'cycle')\n if (record.runId === null) checks.push('cross-run-parent')\n if (record.role === null) checks.push('root-role')\n if (!isRecord(record.raw.outcome)) checks.push('timing', 'terminal-state')\n return [...new Set(checks)]\n}\n\ninterface TreeIssueUncertainty {\n readonly unknownIdentityRows?: number\n readonly uncertainIds?: ReadonlySet<string>\n}\n\nexport function treeIssues(\n tree: SupervisorRunTree,\n uncertainty: TreeIssueUncertainty = {},\n): SupervisorRunIntegrityIssue[] {\n const out: SupervisorRunIntegrityIssue[] = []\n const records = (tree.nodes as readonly unknown[]).map(nodeRecord)\n const malformedSourceRows = tree.gaps\n .filter((gap) => gap.code === 'source-row-malformed')\n .reduce((count, gap) => count + (gap.count ?? 1), 0)\n\n for (const record of records) {\n if (record.errors.length === 0) continue\n out.push(\n issue({\n code: 'node-schema-invalid',\n area: 'capture-integrity',\n severity: 'high',\n subject: record.id ?? `node-${record.index}`,\n claim: 'A supervisor-tree node fails canonical rollout validation',\n detail: record.errors.join('; '),\n evidence: [evidence(`nodes/${record.index}/validation`, record.errors)],\n recommendedAction:\n 'Fix the producer so every node validates as the existing tangle.rollout.v1 shape before analysis.',\n metadata: { validation_errors: record.errors },\n }),\n )\n const unavailableChecks = unavailableNodeChecks(record)\n if (unavailableChecks.length === 0) continue\n out.push(\n issue({\n code: 'node-checks-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: record.id ?? `node-${record.index}`,\n claim: 'Some integrity checks are unavailable for a malformed supervisor-tree node',\n detail: `Unavailable checks: ${unavailableChecks.join(', ')}.`,\n evidence: [evidence(`nodes/${record.index}/unavailable-checks`, unavailableChecks)],\n recommendedAction:\n 'Retain the named identity and relationship fields with their canonical types.',\n metadata: { assessment: 'unavailable', checks: unavailableChecks },\n }),\n )\n }\n\n const byId = new Map<string, NodeRecord[]>()\n for (const record of records) {\n if (record.id === null) continue\n const matches = byId.get(record.id) ?? []\n matches.push(record)\n byId.set(record.id, matches)\n }\n\n for (const [rolloutId, matches] of byId) {\n if (matches.length < 2) continue\n out.push(\n issue({\n code: 'duplicate-rollout-id',\n area: 'control-integrity',\n severity: 'critical',\n subject: rolloutId,\n claim: 'A rollout id is duplicated within one supervisor tree',\n detail: `${matches.length} nodes claim rollout_id ${JSON.stringify(rolloutId)}, so references are ambiguous.`,\n evidence: [\n evidence(`duplicates/${encodeURIComponent(rolloutId)}/count`, matches.length),\n ...matches.slice(0, MAX_EXAMPLES).map((record) =>\n evidence(`nodes/${record.index}/identity`, {\n rollout_id: record.id,\n parent_rollout_id: record.parent,\n role: record.role,\n }),\n ),\n ],\n recommendedAction: 'Give every invocation one stable rollout id and regenerate the tree.',\n }),\n )\n }\n\n const unknownIdentityRows =\n records.filter((record) => record.id === null).length +\n Math.max(malformedSourceRows, uncertainty.unknownIdentityRows ?? 0)\n const unique = records.filter(\n (record): record is NodeRecord & { readonly id: string } =>\n record.id !== null && byId.get(record.id)?.length === 1,\n )\n\n let root: NodeRecord | undefined\n if (tree.rootId === null) {\n out.push(\n issue({\n code: 'root-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'tree-root',\n claim: 'The supervisor-tree root is unavailable',\n detail: `rootId is null while ${records.length} node row(s) were captured.`,\n evidence: [evidence('rootId', null)],\n recommendedAction: 'Capture the root spawned event and preserve its rollout id as rootId.',\n metadata: { assessment: 'unavailable', node_rows: records.length },\n }),\n )\n } else {\n const rootRows = byId.get(tree.rootId) ?? []\n if (rootRows.length === 1) {\n root = rootRows[0]\n } else if (rootRows.length === 0 && unknownIdentityRows > 0) {\n out.push(\n issue({\n code: 'node-checks-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: tree.rootId,\n claim: 'Root membership is unavailable because a malformed node lost its rollout id',\n detail: `${unknownIdentityRows} malformed node row(s) have no usable rollout_id, so absence of root ${JSON.stringify(tree.rootId)} cannot be established.`,\n evidence: [evidence('rootId', tree.rootId)],\n recommendedAction: 'Retain rollout_id even when another node field fails validation.',\n metadata: { assessment: 'unavailable', checks: ['root-membership'] },\n }),\n )\n } else if (rootRows.length === 0) {\n out.push(\n issue({\n code: 'declared-root-missing',\n area: 'control-integrity',\n severity: 'critical',\n subject: tree.rootId,\n claim: 'The declared supervisor-tree root has no matching invocation node',\n detail: `rootId ${JSON.stringify(tree.rootId)} is absent from ${records.length} node row(s).`,\n evidence: [evidence('rootId', tree.rootId)],\n recommendedAction: 'Restore the root rollout row or correct rootId.',\n }),\n )\n }\n }\n\n if (root !== undefined) {\n if (root.parent !== undefined && root.parent !== null) {\n out.push(\n issue({\n code: 'root-has-parent',\n area: 'control-integrity',\n severity: 'critical',\n subject: root.id ?? tree.rootId ?? 'tree-root',\n claim: 'The declared supervisor-tree root has a parent',\n detail: `Root points to parent ${JSON.stringify(root.parent)}.`,\n evidence: [nodeEvidence(root, 'parent_rollout_id', root.parent)],\n recommendedAction: 'Record the root with parent_rollout_id null.',\n }),\n )\n }\n if (root.role !== null && root.role !== 'supervisor') {\n out.push(\n issue({\n code: 'root-role-invalid',\n area: 'control-integrity',\n severity: 'high',\n subject: root.id ?? tree.rootId ?? 'tree-root',\n claim: 'The declared supervisor-tree root is not labeled as a supervisor',\n detail: `Root has role ${JSON.stringify(root.role)}.`,\n evidence: [nodeEvidence(root, 'role', root.role)],\n recommendedAction:\n 'Preserve the root invocation role as supervisor when minting rollout rows.',\n }),\n )\n }\n }\n\n for (const record of unique) {\n if (record.parent === undefined) continue\n if (record.parent === null) {\n if (record.id !== tree.rootId) {\n out.push(\n issue({\n code: 'detached-node',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'A non-root invocation is recorded as a detached parentless root',\n detail: `Node ${JSON.stringify(record.id)} is parentless while rootId is ${JSON.stringify(tree.rootId)}.`,\n evidence: [\n nodeEvidence(record, 'parent_rollout_id', null),\n evidence('rootId', tree.rootId),\n ],\n recommendedAction:\n 'Attach the invocation to its spawning parent or record a separate run.',\n }),\n )\n }\n continue\n }\n\n const parentRows = byId.get(record.parent) ?? []\n if (parentRows.length === 0) {\n if (unknownIdentityRows > 0 || uncertainty.uncertainIds?.has(record.parent) === true) {\n out.push(\n issue({\n code: 'node-checks-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: record.id,\n claim: 'Parent membership is unavailable because a malformed node lost its rollout id',\n detail:\n uncertainty.uncertainIds?.has(record.parent) === true\n ? `Parent ${JSON.stringify(record.parent)} appears only in a malformed source row, so its absence cannot be established.`\n : `Parent ${JSON.stringify(record.parent)} cannot be matched while ${unknownIdentityRows} row(s) have no usable rollout_id.`,\n evidence: [nodeEvidence(record, 'parent_rollout_id', record.parent)],\n recommendedAction: 'Retain rollout_id on every row before assessing detached children.',\n metadata: { assessment: 'unavailable', checks: ['parent-membership'] },\n }),\n )\n } else {\n out.push(\n issue({\n code: 'parent-missing',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'An invocation points to a parent absent from the supervisor tree',\n detail: `Node ${JSON.stringify(record.id)} names missing parent ${JSON.stringify(record.parent)}.`,\n evidence: [nodeEvidence(record, 'parent_rollout_id', record.parent)],\n recommendedAction: 'Retain the parent invocation or remove the dangling edge.',\n }),\n )\n }\n continue\n }\n if (parentRows.length !== 1) continue\n const parent = parentRows[0] as NodeRecord\n\n if (record.runId !== null && parent.runId !== null && record.runId !== parent.runId) {\n out.push(\n issue({\n code: 'cross-run-parent',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'A parent-child edge crosses supervisor-run identities',\n detail: `Child run_id ${JSON.stringify(record.runId)} differs from parent run_id ${JSON.stringify(parent.runId)}.`,\n evidence: [\n nodeEvidence(record, 'run_id', record.runId),\n nodeEvidence(parent, 'run_id', parent.runId),\n ],\n recommendedAction:\n 'Keep one run_id across a supervision tree or remove the cross-run edge.',\n }),\n )\n }\n\n const childStart = metric(record, ['spawned_at', 'started_at'])\n const parentStart = metric(parent, ['spawned_at', 'started_at'])\n if (childStart !== null && parentStart !== null && childStart.value < parentStart.value) {\n out.push(\n issue({\n code: 'child-before-parent',\n area: 'control-integrity',\n severity: 'high',\n subject: record.id,\n claim: 'A child invocation is timestamped before its parent started',\n detail: `Child ${childStart.key} ${childStart.value} precedes parent ${parentStart.key} ${parentStart.value}.`,\n evidence: [\n nodeEvidence(record, `outcome.metrics.${childStart.key}`, childStart.value),\n nodeEvidence(parent, `outcome.metrics.${parentStart.key}`, parentStart.value),\n ],\n recommendedAction: 'Use one ordered clock for spawn events or retain clock metadata.',\n }),\n )\n }\n\n const parentClose = metric(parent, ['settled_at', 'completed_at', 'finished_at'])\n if (childStart !== null && parentClose !== null && childStart.value > parentClose.value) {\n out.push(\n issue({\n code: 'child-after-parent-close',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'A child invocation is timestamped after its parent closed',\n detail: `Child ${childStart.key} ${childStart.value} follows parent ${parentClose.key} ${parentClose.value}.`,\n evidence: [\n nodeEvidence(record, `outcome.metrics.${childStart.key}`, childStart.value),\n nodeEvidence(parent, `outcome.metrics.${parentClose.key}`, parentClose.value),\n ],\n recommendedAction:\n 'Correct the causal timestamps or attach the child to its actual spawner.',\n }),\n )\n }\n }\n\n for (const record of unique) {\n const start = metric(record, ['spawned_at', 'started_at'])\n const close = metric(record, ['settled_at', 'completed_at', 'finished_at'])\n if (start === null || close === null || close.value >= start.value) continue\n out.push(\n issue({\n code: 'close-before-start',\n area: 'control-integrity',\n severity: 'high',\n subject: record.id,\n claim: 'An invocation is timestamped as closing before it started',\n detail: `${start.key} is ${start.value} and ${close.key} is ${close.value}.`,\n evidence: [\n nodeEvidence(record, `outcome.metrics.${start.key}`, start.value),\n nodeEvidence(record, `outcome.metrics.${close.key}`, close.value),\n ],\n recommendedAction: 'Correct the event ordering or retain clock-domain metadata.',\n }),\n )\n }\n\n const emittedCycles = new Set<string>()\n const resolved = new Set<string>()\n for (const start of unique) {\n if (resolved.has(start.id)) continue\n const path: string[] = []\n const positions = new Map<string, number>()\n let current: string | null = start.id\n while (current !== null) {\n if (resolved.has(current)) break\n const position = positions.get(current)\n if (position !== undefined) {\n const cycle = path.slice(position)\n const key = [...cycle].sort().join('\\u0000')\n if (!emittedCycles.has(key)) {\n emittedCycles.add(key)\n out.push(\n issue({\n code: 'parent-cycle',\n area: 'control-integrity',\n severity: 'critical',\n subject: [...cycle].sort()[0] ?? 'cycle',\n claim: 'The supervisor tree contains a parent cycle',\n detail: `${cycle.join(' -> ')} -> ${cycle[0]}`,\n evidence: cycle.slice(0, MAX_EXAMPLES).flatMap((id) => {\n const rows = byId.get(id)\n const record = rows?.length === 1 ? rows[0] : undefined\n return record === undefined\n ? []\n : [nodeEvidence(record, 'parent_rollout_id', record.parent)]\n }),\n recommendedAction:\n 'Correct parent ids at ingestion; a cyclic graph is not a run tree.',\n }),\n )\n }\n break\n }\n positions.set(current, path.length)\n path.push(current)\n const rows = byId.get(current)\n if (rows?.length !== 1) break\n const parent = rows[0]?.parent\n if (parent === undefined) break\n current = parent\n }\n for (const id of path) resolved.add(id)\n }\n\n if (root?.completed === true) {\n const missingTerminal = unique.filter(\n (record) => record.id !== root?.id && record.terminal === false,\n )\n if (missingTerminal.length > 0) {\n out.push(\n issue({\n code: 'child-terminal-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'child-terminal-outcomes',\n claim: 'A completed supervisor run has children with no captured terminal outcome',\n detail: `${missingTerminal.length}/${Math.max(0, unique.length - 1)} child node(s) are neither completed, truncated, nor errored.`,\n evidence: [\n evidence('children/missing-terminal/count', missingTerminal.length),\n ...missingTerminal\n .slice(0, MAX_EXAMPLES)\n .map((record) => nodeEvidence(record, 'outcome', record.raw.outcome)),\n ],\n recommendedAction: 'Retain each child settlement or cancellation event.',\n metadata: { assessment: 'unavailable', unavailable_count: missingTerminal.length },\n }),\n )\n }\n }\n\n const missingTranscripts = records.filter((record) => record.messages?.length === 0)\n if (missingTranscripts.length > 0) {\n out.push(\n issue({\n code: 'transcript-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'decision-transcripts',\n claim: 'Decision transcripts are unavailable for some supervisor-tree invocations',\n detail: `${missingTranscripts.length}/${records.length} node row(s) have messages: [].`,\n evidence: [\n evidence('capture/missing-transcripts/count', missingTranscripts.length),\n ...missingTranscripts\n .slice(0, MAX_EXAMPLES)\n .map((record) => nodeEvidence(record, 'messages', [])),\n ],\n recommendedAction: 'Hydrate canonical messages from the retained session transcript.',\n metadata: { assessment: 'unavailable', unavailable_count: missingTranscripts.length },\n }),\n )\n }\n\n const missingProfiles = records.filter((record) => record.profileId === null)\n if (missingProfiles.length > 0) {\n out.push(\n issue({\n code: 'profile-id-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'agent-profile-identity',\n claim:\n 'Canonical agent-profile identity is unavailable for some supervisor-tree invocations',\n detail: `${missingProfiles.length}/${records.length} node row(s) omit policy.agent_profile_cell_id.`,\n evidence: [\n evidence('capture/missing-agent-profile-cell-id/count', missingProfiles.length),\n ...missingProfiles\n .slice(0, MAX_EXAMPLES)\n .map((record) => nodeEvidence(record, 'policy.agent_profile_cell_id', null)),\n ],\n recommendedAction:\n 'Record policy.agent_profile_cell_id on every invocation at dispatch time.',\n metadata: { assessment: 'unavailable', unavailable_count: missingProfiles.length },\n }),\n )\n }\n\n return out\n}\n","import type { SupervisorRunTree } from './types'\n\nexport const SUPERVISOR_RUN_INTEGRITY_SCHEMA = 'tangle.supervisor-run-integrity@1'\n\nexport type SupervisorRunIntegritySeverity = 'critical' | 'high' | 'medium' | 'low' | 'info'\n\nexport type SupervisorRunSourceOnlyCheckCode =\n | 'journal-event-cardinality'\n | 'worker-control-join'\n | 'steer-ack-correlation'\n\nexport type SupervisorRunIntegrityIssueCode =\n | 'source-checks-unavailable'\n | 'node-schema-invalid'\n | 'node-checks-unavailable'\n | 'root-unavailable'\n | 'duplicate-rollout-id'\n | 'declared-root-missing'\n | 'root-has-parent'\n | 'root-role-invalid'\n | 'detached-node'\n | 'parent-missing'\n | 'cross-run-parent'\n | 'child-before-parent'\n | 'child-after-parent-close'\n | 'close-before-start'\n | 'parent-cycle'\n | 'child-terminal-unavailable'\n | 'transcript-unavailable'\n | 'profile-id-unavailable'\n | 'source-row-malformed'\n | 'source-event-identity-unavailable'\n | 'duplicate-spawn'\n | 'orphan-terminal'\n | 'duplicate-terminal'\n | 'worker-controls-unavailable'\n | 'worker-control-join-unavailable'\n | 'steer-request-id-unavailable'\n | 'steer-ack-id-unavailable'\n | 'steer-ack-status-unavailable'\n | 'duplicate-steer-request-id'\n | 'missing-steer-ack'\n | 'duplicate-steer-ack'\n | 'unknown-steer-ack'\n | 'steer-not-delivered'\n\nexport interface SupervisorRunIntegrityEvidence {\n readonly path: string\n readonly value: unknown\n}\n\nexport interface SupervisorRunIntegrityIssue {\n readonly code: SupervisorRunIntegrityIssueCode\n readonly area: 'control-integrity' | 'capture-integrity'\n readonly severity: SupervisorRunIntegritySeverity\n readonly subject: string\n readonly claim: string\n readonly detail: string\n readonly evidence: readonly SupervisorRunIntegrityEvidence[]\n readonly recommendedAction: string\n readonly metadata?: Readonly<Record<string, unknown>>\n}\n\nexport interface SupervisorRunIntegrityReport {\n readonly schema: typeof SUPERVISOR_RUN_INTEGRITY_SCHEMA\n readonly runRef: string\n readonly input: 'sources' | 'tree'\n readonly tree: SupervisorRunTree\n readonly issues: readonly SupervisorRunIntegrityIssue[]\n}\n\nexport interface SupervisorRunIntegrityOptions {\n /** Pins rollout provenance when source input must be projected into a tree. */\n readonly capturedAt?: string\n}\n","/**\n * The supervision tree as `tangle.rollout.v1` rows.\n *\n * A supervisor run IS a tree of rollouts, so its nodes are not a new shape:\n * the root becomes one `RolloutLine` with `role: 'supervisor'`, and every\n * spawned invocation keeps its explicit supervisor/worker role with\n * `parent_rollout_id` pointing at its spawner. The rows append to the same\n * ledger as solo-agent rollouts and join to them with the same keys.\n *\n * What the journal CANNOT supply is the transcript: a worker's messages live\n * in its harness store (opencode sqlite, Claude Code jsonl), which the\n * `src/rollout/readers/*` intake readers own. Rows minted here are therefore\n * GAP lines (`messages: []`, `provenance.gap` set) carrying identity,\n * structure, outcome and cost; hydrating them with messages is the readers'\n * job, keyed on `artifacts.transcript_ref`.\n *\n * Timing lives in `outcome.metrics` (`spawned_at` / `settled_at` / `wall_ms`)\n * rather than a schema field: `tangle.rollout.v1` describes ONE invocation,\n * and the inter-invocation event timeline — which is what waves, concurrency,\n * idle and utilization are computed from — is a property of the journal, not\n * of any single row. The analyzer reads that timeline; these rows carry the\n * per-node facts.\n */\n\nimport { unscreenedRewardFields } from '../rollout/reward'\nimport {\n isRolloutLine,\n ROLLOUT_SCHEMA,\n type RolloutLine,\n type RolloutSplit,\n} from '../rollout/schema'\nimport { asRecord, parseJson, parseSupervisorTree, type SupervisorTreeFacts } from './source-facts'\nimport { readTerminalRecord } from './terminal-record'\nimport {\n isUnavailable,\n type SupervisorRunSources,\n type SupervisorRunTree,\n type SupervisorRunTreeGap,\n type WorkerLogSource,\n} from './types'\n\nexport interface SupervisorRolloutOptions {\n /** Benchmark/suite id for `task.suite`. Defaults to `'supervisor-run'`. */\n readonly suite?: string\n /** `task.split`. Defaults to `'search'` (the trainable pool). */\n readonly split?: RolloutSplit\n /** Replicate index. Defaults to 0. */\n readonly rep?: number\n /** Sampling seed the campaign pinned. Defaults to null (not recorded). */\n readonly seed?: number | null\n /** `run_id` for every node. Defaults to the supervisor root id, else `runRef`. */\n readonly runId?: string\n /** Harness that drove the supervisor. */\n readonly supervisorHarness?: string | null\n /** Harness that drove the workers. */\n readonly workerHarness?: string | null\n /** Model the supervisor ran on. */\n readonly supervisorModel?: string | null\n /** Model the workers ran on. */\n readonly workerModel?: string | null\n readonly experimentId?: string | null\n readonly candidateId?: string | null\n readonly generation?: number | null\n readonly candidateIndex?: number | null\n /** Pins `provenance.captured_at`; defaults to now. */\n readonly capturedAt?: string\n}\n\nconst EMPTY_COST = {\n usd: null,\n tokens_in: null,\n tokens_out: null,\n tokens_reasoning: null,\n cache_read: null,\n cache_write: null,\n wall_s: null,\n} as const\n\nfunction hasWorkerId(\n worker: WorkerLogSource,\n): worker is WorkerLogSource & { readonly workerId: string } {\n return worker.workerId !== undefined\n}\n\n/**\n * Mint the supervision tree as rollout rows. Returns the rows plus the gaps\n * that made any of them incomplete — same unavailable-vs-zero discipline as\n * the report: a row with no transcript says WHY, it never pretends to be empty.\n */\nexport function supervisorRunRolloutLines(\n src: SupervisorRunSources,\n opts: SupervisorRolloutOptions = {},\n): SupervisorRunTree {\n return supervisorRunRolloutLinesFromFacts(src, parseSupervisorTree(src), opts)\n}\n\n/** Mint rollout rows from an already parsed source without reading its JSONL again. */\nexport function supervisorRunRolloutLinesFromFacts(\n src: SupervisorRunSources,\n tree: SupervisorTreeFacts,\n opts: SupervisorRolloutOptions = {},\n): SupervisorRunTree {\n const gaps: SupervisorRunTreeGap[] = []\n if (src.journal === null) {\n gaps.push({\n code: 'journal-unavailable',\n message: `${src.supRunDir === null ? 'no supervisor run dir' : 'journal absent'}; no nodes recoverable`,\n })\n return { rootId: null, nodes: [], gaps }\n }\n // `journalInvalidRows` covers rows the parser could not interpret at all, including JSON\n // objects in a shape it does not recognize — so a journal it read but understood none of\n // reports an explicit gap instead of an empty tree.\n const malformedSourceRows =\n tree.journalInvalidRows + tree.spawns.filter((spawn) => !spawn.valid).length\n if (malformedSourceRows > 0) {\n gaps.push({\n code: 'source-row-malformed',\n message: `${malformedSourceRows} of ${tree.journalRows} journal row(s) were unusable and excluded from the tree`,\n count: malformedSourceRows,\n })\n }\n\n const state = tree.state\n const result = parseJson(src.result)\n const judge = parseJson(src.judge)\n const stateResult = asRecord(state?.result)\n // One derivation with the analyzer, so the root row and the report never\n // disagree about which record the status came from.\n const terminal = readTerminalRecord({\n state,\n result,\n failure: src.failure === undefined ? undefined : parseJson(src.failure),\n })\n\n const rootId = tree.rootId\n const runId = opts.runId ?? rootId ?? src.runRef\n const suite = opts.suite ?? 'supervisor-run'\n const instanceId = src.instanceId ?? src.runRef\n const split: RolloutSplit = opts.split ?? 'search'\n const capturedAt = opts.capturedAt ?? new Date().toISOString()\n\n const base = {\n schema: ROLLOUT_SCHEMA,\n run_id: runId,\n experiment_id: opts.experimentId ?? null,\n candidate_id: opts.candidateId ?? null,\n generation: opts.generation ?? null,\n candidate_index: opts.candidateIndex ?? null,\n task: {\n suite,\n instance_id: instanceId,\n split,\n seed: opts.seed ?? null,\n rep: opts.rep ?? 0,\n },\n messages: [] as RolloutLine['messages'],\n tool_defs: [] as RolloutLine['tool_defs'],\n } satisfies Partial<RolloutLine> & Record<string, unknown>\n\n const nodes: RolloutLine[] = []\n\n // ── root: the supervisor invocation ────────────────────────────────────\n if (rootId !== null) {\n const rootSpawn = tree.spawns.find((spawn) => spawn.valid && spawn.id === rootId)\n const judgeResolved = typeof judge?.resolved === 'boolean' ? judge.resolved : null\n const judgeScore = typeof judge?.score === 'number' ? judge.score : null\n const reward = judgeScore ?? (judgeResolved === null ? null : judgeResolved ? 1 : 0)\n if (reward === null) {\n gaps.push({\n code: 'root-reward-unavailable',\n message: 'no judge verdict for this run',\n nodeId: rootId,\n })\n }\n const wallMs =\n tree.startedAt !== null && tree.completedAt !== null && tree.completedAt >= tree.startedAt\n ? tree.completedAt - tree.startedAt\n : null\n nodes.push({\n ...base,\n rollout_id: rootId,\n parent_rollout_id: null,\n role: rootSpawn?.role ?? 'supervisor',\n policy: {\n harness: opts.supervisorHarness ?? null,\n harness_version: null,\n model: opts.supervisorModel ?? null,\n provider: null,\n profile_commit: null,\n agent_profile_cell_id: rootSpawn?.profileDigest ?? null,\n sampling: null,\n },\n outcome: {\n // `reward` and `realness_gated` are written by one call, in the module\n // that owns the gate. This is the SECOND producer of rollout rewards —\n // the judge verdict in the supervision run dir, not `mintRolloutRows` —\n // and it wrote `reward` by hand while never stating the flag, so\n // `isLineRealnessGated` was structurally false for every supervisor and\n // worker row ever emitted here. `unscreenedRewardFields` is the honest\n // name for what this producer can claim: a supervision journal carries\n // no `RunRecord.outcome.realness`, so no authenticity gate has run on\n // this score, and `realness_gated: false` states that rather than\n // implying it by omission. These rows stay plain `RolloutLine`s, so a\n // caller feeding them to a training exporter must `assertMinted` first.\n ...unscreenedRewardFields(reward),\n reward_source: src.judgeSource,\n verdict: judge ?? null,\n metrics: {\n arm: src.arm,\n sup_status: isUnavailable(terminal.supStatus) ? null : terminal.supStatus,\n sup_verdict: typeof state?.verdict === 'string' ? state.verdict : null,\n delivered: typeof stateResult.delivered === 'boolean' ? stateResult.delivered : null,\n verify_pass: typeof result?.verify_pass === 'boolean' ? result.verify_pass : null,\n started_at: tree.startedAt,\n completed_at: tree.completedAt,\n workers_spawned: tree.workerSpawns.length,\n brain_metered_events: tree.brain.meteredCount,\n runtime: rootSpawn?.runtime ?? null,\n profile_digest: rootSpawn?.profileDigest ?? null,\n },\n is_completed: terminal.completed === true,\n is_truncated: false,\n // A recorded non-delivery names its cause: Runtime's no-winner reason,\n // else the recorded error's message. A run with no terminal record has\n // no error to report, and a delivered run has none.\n error:\n terminal.completed !== false\n ? null\n : !isUnavailable(terminal.supReason) && terminal.supReason !== null\n ? terminal.supReason\n : !isUnavailable(terminal.failure) && terminal.failure !== null\n ? (terminal.failure.message ?? terminal.failure.name)\n : null,\n realness_gated: false,\n },\n cost: {\n ...EMPTY_COST,\n usd:\n src.limits.spendUsd !== null\n ? null\n : typeof stateResult.spentUsd === 'number'\n ? stateResult.spentUsd\n : tree.brain.usd,\n tokens_in: src.limits.managerTokens === null ? tree.brain.tokensIn : null,\n tokens_out: src.limits.managerTokens === null ? tree.brain.tokensOut : null,\n cache_read:\n src.limits.managerTokens === null && tree.brain.hasCache ? tree.brain.cacheRead : null,\n cache_write:\n src.limits.managerTokens === null && tree.brain.hasCache ? tree.brain.cacheWrite : null,\n wall_s: wallMs === null ? null : wallMs / 1000,\n },\n artifacts: {\n patch_path: typeof result?.patchPath === 'string' ? result.patchPath : null,\n run_dir: src.supRunDir,\n transcript_ref:\n src.rootTranscriptRef !== undefined\n ? src.rootTranscriptRef\n : src.supRunDir === null\n ? null\n : `${src.supRunDir}/journal.jsonl`,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'backfill',\n gap: 'supervision journal carries structure and spend, not the brain transcript',\n },\n })\n } else {\n gaps.push({\n code: 'root-spawn-unavailable',\n message: 'no parentless spawned event in the journal',\n })\n }\n\n // ── workers: one node per spawn, keyed to its spawner ───────────────────\n const closeById = new Map(tree.closes.map((c) => [c.id, c]))\n const sourceById = new Map(\n (src.workers ?? []).filter(hasWorkerId).map((worker) => [worker.workerId, worker]),\n )\n const fallbackSourceByLabel = new Map(\n (src.workers ?? [])\n .filter((worker) => worker.workerId === undefined)\n .map((worker) => [worker.label, worker]),\n )\n // Stable ids are authoritative. Labels are a compatibility join for stores\n // that predate workerId and are only safe when the store keeps them unique.\n for (const spawn of tree.workerSpawns) {\n if (spawn.role === null) {\n gaps.push({\n code: 'node-role-unavailable',\n message: `child ${JSON.stringify(spawn.label)} has no explicit invocation role`,\n nodeId: spawn.id,\n })\n continue\n }\n const close = closeById.get(spawn.id) ?? null\n const workerSource = sourceById.get(spawn.id) ?? fallbackSourceByLabel.get(spawn.label) ?? null\n const facts =\n tree.workerLogs.get(workerSource?.workerId ?? workerSource?.label ?? spawn.label) ?? null\n const wallMs =\n facts?.started != null && facts.finishedAt != null ? facts.finishedAt - facts.started : null\n const score = close?.score ?? facts?.score ?? null\n const passed = close?.valid ?? facts?.passed ?? null\n const reward = score ?? (passed === null ? null : passed ? 1 : 0)\n if (reward === null) {\n gaps.push({\n code: 'child-reward-unavailable',\n message: `child ${JSON.stringify(spawn.label)} has no verify verdict`,\n nodeId: spawn.id,\n })\n }\n const isSupervisor = spawn.role === 'supervisor'\n nodes.push({\n ...base,\n rollout_id: spawn.id,\n parent_rollout_id: spawn.parent,\n role: spawn.role,\n policy: {\n harness: isSupervisor ? (opts.supervisorHarness ?? null) : (opts.workerHarness ?? null),\n harness_version: null,\n model: isSupervisor ? (opts.supervisorModel ?? null) : (opts.workerModel ?? null),\n provider: null,\n profile_commit: null,\n agent_profile_cell_id: spawn.profileDigest,\n sampling: null,\n },\n outcome: {\n // Same producer, same claim: a child reward is a self-verify verdict\n // from the journal that no realness gate has seen.\n ...unscreenedRewardFields(reward),\n reward_source:\n reward === null ? null : score === null ? 'worker-self-verify' : 'worker-verdict-score',\n verdict:\n close === null\n ? null\n : {\n kind: close.kind,\n status: close.status,\n verdict: close.rawVerdict,\n valid: close.valid,\n score: close.score,\n },\n metrics: {\n label: spawn.label,\n spawned_at: spawn.at,\n settled_at: close?.at ?? null,\n started_at: facts?.started ?? null,\n finished_at: facts?.finishedAt ?? null,\n wall_ms: wallMs,\n patch_bytes: workerSource?.patchBytes ?? facts?.finishedPatchBytes ?? null,\n evidence_bytes: facts?.evidenceBytes ?? null,\n steers_queued: facts?.steersQueued ?? null,\n steers_delivered: facts?.steersDelivered ?? null,\n questions: facts?.questions ?? null,\n runtime: spawn.runtime,\n profile_digest: spawn.profileDigest,\n },\n is_completed: close?.kind === 'settled' && close.status === 'done',\n is_truncated: close?.kind === 'cancelled',\n error:\n close?.kind === 'cancelled'\n ? (close.reason ?? 'cancelled')\n : close?.status === 'down'\n ? (close.reason ?? 'child down')\n : null,\n realness_gated: false,\n },\n // `close.spend` is only a measurement when the close event carried one;\n // a store that never priced this worker must leave null, not 0.\n cost: {\n ...EMPTY_COST,\n usd: src.limits.spendUsd !== null || !close?.hasSpend ? null : close.spend.usd,\n tokens_in: workerSource?.tokensIn ?? (close?.hasSpend ? close.spend.tokens.input : null),\n tokens_out: workerSource?.tokensOut ?? (close?.hasSpend ? close.spend.tokens.output : null),\n // Mirror the tokens_in/out journal fallback so a loops-shaped store whose\n // `settled` spend carries cache counters is not reported as null cache\n // beside real tokens. Gate on `hasCache` — a spend object without cache\n // counters must stay null, not a fabricated 0.\n cache_read:\n workerSource?.cacheRead ??\n (close?.hasSpend && close.spend.tokens.hasCache ? close.spend.tokens.cacheRead : null),\n cache_write:\n workerSource?.cacheWrite ??\n (close?.hasSpend && close.spend.tokens.hasCache ? close.spend.tokens.cacheWrite : null),\n wall_s: wallMs === null ? null : wallMs / 1000,\n },\n // A reader that knows where its worker artifacts live says so; only the\n // loops layout is derivable from `supRunDir`, so guessing it for another\n // store would mint rows pointing at paths that never existed.\n artifacts: {\n patch_path:\n workerSource?.patchPath !== undefined\n ? workerSource.patchPath\n : src.supRunDir === null\n ? null\n : `${src.supRunDir}/workers/${spawn.label}.patch`,\n run_dir: src.supRunDir,\n transcript_ref:\n workerSource?.transcriptRef !== undefined\n ? workerSource.transcriptRef\n : src.supRunDir === null\n ? null\n : `${src.supRunDir}/workers/${spawn.label}.ndjson`,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'backfill',\n gap:\n workerSource?.transcriptRef == null\n ? 'worker transcript lives in the harness session store — hydrate via src/rollout/readers'\n : 'worker transcript recorded by the harness; messages not inlined into this row',\n },\n })\n }\n\n const invalid = nodes.filter((n) => !isRolloutLine(n))\n if (invalid.length > 0) {\n gaps.push({\n code: 'node-schema-invalid',\n message: `${invalid.length} node(s) failed tangle.rollout.v1 validation`,\n count: invalid.length,\n })\n }\n return { rootId, nodes, gaps }\n}\n","import { evidence, issue } from './integrity-issues'\nimport { sourceIssues } from './integrity-source'\nimport { treeIssues } from './integrity-tree'\nimport {\n SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n type SupervisorRunIntegrityOptions,\n type SupervisorRunIntegrityReport,\n type SupervisorRunSourceOnlyCheckCode,\n} from './integrity-types'\nimport { supervisorRunRolloutLinesFromFacts } from './rollout-nodes'\nimport { parseSupervisorTree } from './source-facts'\nimport type { SupervisorRunSources, SupervisorRunTree } from './types'\n\nexport {\n SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n type SupervisorRunIntegrityEvidence,\n type SupervisorRunIntegrityIssue,\n type SupervisorRunIntegrityIssueCode,\n type SupervisorRunIntegrityOptions,\n type SupervisorRunIntegrityReport,\n type SupervisorRunIntegritySeverity,\n type SupervisorRunSourceOnlyCheckCode,\n} from './integrity-types'\n\nfunction isTree(input: SupervisorRunSources | SupervisorRunTree): input is SupervisorRunTree {\n return 'nodes' in input && Array.isArray(input.nodes)\n}\n\nfunction treeRunRef(tree: SupervisorRunTree): string {\n const runIds = [\n ...new Set(\n tree.nodes\n .map((node) => node.run_id)\n .filter((runId): runId is string => typeof runId === 'string' && runId.length > 0),\n ),\n ].sort()\n if (runIds.length === 1) return runIds[0]!\n if (runIds.length > 1) return `mixed-runs:${runIds.join(',')}`\n return tree.rootId ?? 'unidentified-tree'\n}\n\n/**\n * Run deterministic integrity checks over source bytes or an already minted tree.\n * Source input is parsed exactly once and reused by projection and source-only checks.\n */\nexport function analyzeSupervisorRunIntegrity(\n input: SupervisorRunSources | SupervisorRunTree,\n options: SupervisorRunIntegrityOptions = {},\n): SupervisorRunIntegrityReport {\n if (isTree(input)) {\n const sourceOnlyChecks: readonly SupervisorRunSourceOnlyCheckCode[] = [\n 'journal-event-cardinality',\n 'worker-control-join',\n 'steer-ack-correlation',\n ]\n return {\n schema: SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n runRef: treeRunRef(input),\n input: 'tree',\n tree: input,\n issues: [\n ...treeIssues(input),\n issue({\n code: 'source-checks-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'source-only-control-checks',\n claim: 'Source-only control checks are unavailable for SupervisorRunTree input',\n detail:\n 'Rollout rows do not retain journal event multiplicity or worker inbox and acknowledgement rows.',\n evidence: [evidence('input/source-only-checks', sourceOnlyChecks)],\n recommendedAction:\n 'Pass SupervisorRunSources when journal and worker control checks are required.',\n metadata: { assessment: 'unavailable', checks: sourceOnlyChecks },\n }),\n ],\n }\n }\n\n const facts = parseSupervisorTree(input)\n const tree = supervisorRunRolloutLinesFromFacts(input, facts, {\n capturedAt: options.capturedAt,\n })\n return {\n schema: SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n runRef: input.runRef,\n input: 'sources',\n tree,\n issues: [\n ...treeIssues(tree, {\n unknownIdentityRows:\n facts.journalInvalidRows +\n facts.spawns.filter((spawn) => !spawn.valid && spawn.id.length === 0).length,\n uncertainIds: new Set(\n facts.spawns\n .filter((spawn) => !spawn.valid && spawn.id.length > 0)\n .map((spawn) => spawn.id),\n ),\n }),\n ...sourceIssues(input, facts, tree),\n ],\n }\n}\n"],"mappings":";;;;AAIA,SAAgB,SAAS,MAAc,OAAgD;CACrF,OAAO;EAAE;EAAM;CAAM;AACvB;AAEA,SAAgB,MACd,MAG6B;CAC7B,OAAO;EAAE,GAAG;EAAM,UAAU,KAAK,YAAY,CAAC;CAAE;AAClD;;;ACVA,SAAS,aAAa,KAAgC;CACpD,MAAM,WAAW,IACd,MAAM,GAAA,EAAe,CAAC,CACtB,KAAK,OAAO,KAAK,UAAU,EAAE,CAAC,CAAC,CAC/B,KAAK,IAAI;CACZ,OAAO,IAAI,UAAA,KACP,WACA,GAAG,SAAS,QAAQ,IAAI,SAAA,GAAsB;AACpD;AAEA,SAAgB,YACd,QACA,eAC+B;CAC/B,MAAM,EAAE,UAAU;CAClB,MAAM,UAAU,MAAM,YAAY,OAAO,MAAM;CAC/C,MAAM,SAAS,WAAW,MAAM;CAChC,MAAM,MAAqC,CAAC;CAC5C,IACE,CAAC,MAAM,iBACP,CAAC,MAAM,kBACP,MAAM,mBAAmB,KACzB,MAAM,oBAAoB,GAC1B;EACA,MAAM,UAAU,CACd,GAAI,MAAM,gBAAgB,CAAC,IAAI,CAAC,OAAO,GACvC,GAAI,MAAM,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAC3C;EACA,MAAM,YAAY,CAChB,GAAI,MAAM,mBAAmB,IAAI,CAAC,SAAS,MAAM,kBAAkB,IAAI,CAAC,GACxE,GAAI,MAAM,oBAAoB,IAAI,CAAC,UAAU,MAAM,mBAAmB,IAAI,CAAC,CAC7E;EACA,IAAI,KACF,MAAM;GACJ,MAAM;GACN,MAAM;GACN,UAAU;GACV;GACA,OACE;GACF,QACE,QAAQ,SAAS,IACb,GAAG,KAAK,UAAU,OAAO,EAAE,cAAc,QAAQ,KAAK,OAAO,EAAE,KAC/D,GAA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,UAAU,CAAC,MAAM,SAAS,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC;GACxE,cAAc,IAAI,IAChB,MAAM,OACH,QAAQ,UAAU,CAAC,MAAM,SAAS,MAAM,GAAG,SAAS,CAAC,CAAC,CACtD,KAAK,UAAU,MAAM,EAAE,CAC5B;EACF,CAAC,GACD,GAAG,aAAa,OAAO,OAAO,IAAI,CACpC;CACF;AACF"}
@@ -1,3 +1,3 @@
1
- import { A as AtomicFileLockUnavailable, C as withLedgerFileLock, D as AtomicFileLockError, E as AtomicFileLockAcquisition, M as tryAcquireAtomicFileLock, O as AtomicFileLockOptions, S as tryWithLedgerFileLock, T as AtomicFileLock, _ as trustedHeadPathFor, a as LedgerChainFields, b as LedgerFileContext, c as LedgerJournalCodec, d as LedgerReplayResult, f as LedgerAnchoredEntry, g as readTrustedHeadFile, h as LedgerTrustedHeadSubject, i as LedgerAppendResult, j as probeAtomicFileLock, k as AtomicFileLockOwner, l as LedgerLineContext, m as LedgerTrustedHeadRemoval, n as FileLedgerJournalOptions, o as LedgerEntryOf, p as LedgerTrustedHead, r as LedgerAppendOptions, s as LedgerEventBase, t as FileLedgerJournal, u as LedgerProjector, v as verifyEntriesAgainstTrustedHead, w as writeLedgerFileAtomically, x as appendLedgerLine, y as FileLockResult } from "../index-D-UdhAmg.js";
1
+ import { A as AtomicFileLockOwner, C as tryWithLedgerFileLock, D as AtomicFileLockAcquisition, E as AtomicFileLock, M as probeAtomicFileLock, N as tryAcquireAtomicFileLock, O as AtomicFileLockError, S as appendLedgerLine, T as writeLedgerFileAtomically, _ as readTrustedHeadFile, a as LedgerChainFields, b as FileLockResult, c as LedgerJournalCodec, d as LedgerReplayResult, f as replayLedgerText, g as LedgerTrustedHeadSubject, h as LedgerTrustedHeadRemoval, i as LedgerAppendResult, j as AtomicFileLockUnavailable, k as AtomicFileLockOptions, l as LedgerLineContext, m as LedgerTrustedHead, n as FileLedgerJournalOptions, o as LedgerEntryOf, p as LedgerAnchoredEntry, r as LedgerAppendOptions, s as LedgerEventBase, t as FileLedgerJournal, u as LedgerProjector, v as trustedHeadPathFor, w as withLedgerFileLock, x as LedgerFileContext, y as verifyEntriesAgainstTrustedHead } from "../index-u0d1Jp4F.js";
2
2
  import { a as hashCanonical, i as canonicalString, n as LedgerCanonicalizationError, o as jsonDocument, r as LedgerHash, t as LEDGER_HASH_PATTERN } from "../canonical-CFpojCN5.js";
3
- export { type AtomicFileLock, type AtomicFileLockAcquisition, AtomicFileLockError, type AtomicFileLockOptions, type AtomicFileLockOwner, type AtomicFileLockUnavailable, FileLedgerJournal, type FileLedgerJournalOptions, type FileLockResult, LEDGER_HASH_PATTERN, type LedgerAnchoredEntry, type LedgerAppendOptions, type LedgerAppendResult, LedgerCanonicalizationError, type LedgerChainFields, type LedgerEntryOf, type LedgerEventBase, type LedgerFileContext, type LedgerHash, type LedgerJournalCodec, type LedgerLineContext, type LedgerProjector, type LedgerReplayResult, type LedgerTrustedHead, type LedgerTrustedHeadRemoval, type LedgerTrustedHeadSubject, appendLedgerLine, canonicalString, hashCanonical, jsonDocument, probeAtomicFileLock, readTrustedHeadFile, trustedHeadPathFor, tryAcquireAtomicFileLock, tryWithLedgerFileLock, verifyEntriesAgainstTrustedHead, withLedgerFileLock, writeLedgerFileAtomically };
3
+ export { type AtomicFileLock, type AtomicFileLockAcquisition, AtomicFileLockError, type AtomicFileLockOptions, type AtomicFileLockOwner, type AtomicFileLockUnavailable, FileLedgerJournal, type FileLedgerJournalOptions, type FileLockResult, LEDGER_HASH_PATTERN, type LedgerAnchoredEntry, type LedgerAppendOptions, type LedgerAppendResult, LedgerCanonicalizationError, type LedgerChainFields, type LedgerEntryOf, type LedgerEventBase, type LedgerFileContext, type LedgerHash, type LedgerJournalCodec, type LedgerLineContext, type LedgerProjector, type LedgerReplayResult, type LedgerTrustedHead, type LedgerTrustedHeadRemoval, type LedgerTrustedHeadSubject, appendLedgerLine, canonicalString, hashCanonical, jsonDocument, probeAtomicFileLock, readTrustedHeadFile, replayLedgerText, trustedHeadPathFor, tryAcquireAtomicFileLock, tryWithLedgerFileLock, verifyEntriesAgainstTrustedHead, withLedgerFileLock, writeLedgerFileAtomically };
@@ -1,3 +1,3 @@
1
1
  import { a as hashCanonical, n as LedgerCanonicalizationError, o as jsonDocument, r as canonicalString, t as LEDGER_HASH_PATTERN } from "../canonical-DPyQ_rpt.js";
2
- import { a as appendLedgerLine, c as writeLedgerFileAtomically, f as AtomicFileLockError, i as verifyEntriesAgainstTrustedHead, m as tryAcquireAtomicFileLock, n as readTrustedHeadFile, o as tryWithLedgerFileLock, p as probeAtomicFileLock, r as trustedHeadPathFor, s as withLedgerFileLock, t as FileLedgerJournal } from "../ledger-core-PIfjCbKn.js";
3
- export { AtomicFileLockError, FileLedgerJournal, LEDGER_HASH_PATTERN, LedgerCanonicalizationError, appendLedgerLine, canonicalString, hashCanonical, jsonDocument, probeAtomicFileLock, readTrustedHeadFile, trustedHeadPathFor, tryAcquireAtomicFileLock, tryWithLedgerFileLock, verifyEntriesAgainstTrustedHead, withLedgerFileLock, writeLedgerFileAtomically };
2
+ import { a as verifyEntriesAgainstTrustedHead, c as withLedgerFileLock, h as tryAcquireAtomicFileLock, i as trustedHeadPathFor, l as writeLedgerFileAtomically, m as probeAtomicFileLock, n as replayLedgerText, o as appendLedgerLine, p as AtomicFileLockError, r as readTrustedHeadFile, s as tryWithLedgerFileLock, t as FileLedgerJournal } from "../ledger-core-Cs9f7385.js";
3
+ export { AtomicFileLockError, FileLedgerJournal, LEDGER_HASH_PATTERN, LedgerCanonicalizationError, appendLedgerLine, canonicalString, hashCanonical, jsonDocument, probeAtomicFileLock, readTrustedHeadFile, replayLedgerText, trustedHeadPathFor, tryAcquireAtomicFileLock, tryWithLedgerFileLock, verifyEntriesAgainstTrustedHead, withLedgerFileLock, writeLedgerFileAtomically };
@@ -795,56 +795,69 @@ var FileLedgerJournal = class {
795
795
  }
796
796
  readEntries() {
797
797
  if (!existsSync(this.path)) return [];
798
- const text = readFileSync(this.path, "utf8");
799
- if (text.length === 0) return [];
800
- if (!text.endsWith("\n")) throw this.codec.integrityError(`${this.codec.subject} ${this.path} has a truncated final record (missing newline)`);
801
- const lines = text.slice(0, -1).split("\n");
802
- const entries = [];
803
- for (let index = 0; index < lines.length; index += 1) {
804
- const line = lines[index];
805
- if (line.length === 0) throw this.codec.integrityError(`${this.codec.subject} ${this.path} has a blank row at line ${index + 1}`);
806
- let raw;
807
- try {
808
- raw = JSON.parse(line);
809
- } catch (error) {
810
- throw this.codec.integrityError(`${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`, { cause: error });
811
- }
812
- const entry = this.codec.parseEntry(raw, {
813
- path: this.path,
814
- line: index + 1
815
- });
816
- let canonical;
817
- try {
818
- canonical = canonicalString(entry);
819
- } catch (error) {
820
- throw this.codec.integrityError(`${this.codec.subject} ${this.path} has a row with no canonical JSON form at line ${index + 1}`, { cause: error });
821
- }
822
- if (line !== canonical) throw this.codec.integrityError(`${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`);
823
- entries.push(entry);
824
- }
825
- return entries;
798
+ return parseLedgerText(readFileSync(this.path, "utf8"), this.path, this.codec);
826
799
  }
827
800
  project(entries) {
828
- const projector = this.codec.createProjector();
829
- const eventIds = /* @__PURE__ */ new Set();
830
- let expectedPrevious = null;
831
- for (let index = 0; index < entries.length; index += 1) {
832
- const entry = entries[index];
833
- this.codec.checkEntryHeader(entry, index);
834
- if (entry.sequence !== index) throw this.codec.integrityError(`entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`);
835
- if (entry.previousHash !== expectedPrevious) throw this.codec.integrityError(`entry ${entry.event.eventId} does not extend the previous hash`);
836
- const { entryHash: _entryHash, ...material } = entry;
837
- const expectedHash = hashCanonical(material);
838
- if (entry.entryHash !== expectedHash) throw this.codec.integrityError(`entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`);
839
- expectedPrevious = entry.entryHash;
840
- if (eventIds.has(entry.event.eventId)) throw this.codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`);
841
- eventIds.add(entry.event.eventId);
842
- projector.apply(entry, index);
843
- }
844
- return projector.finish(entries);
801
+ return projectLedgerEntries(entries, this.codec);
845
802
  }
846
803
  };
804
+ /** Verify and replay resolved immutable journal bytes without filesystem I/O. */
805
+ function replayLedgerText(text, path, codec) {
806
+ const entries = parseLedgerText(text, path, codec);
807
+ return {
808
+ entries,
809
+ projection: projectLedgerEntries(entries, codec)
810
+ };
811
+ }
812
+ function parseLedgerText(text, path, codec) {
813
+ if (text.length === 0) return [];
814
+ if (!text.endsWith("\n")) throw codec.integrityError(`${codec.subject} ${path} has a truncated final record (missing newline)`);
815
+ const lines = text.slice(0, -1).split("\n");
816
+ const entries = [];
817
+ for (let index = 0; index < lines.length; index += 1) {
818
+ const line = lines[index];
819
+ if (line.length === 0) throw codec.integrityError(`${codec.subject} ${path} has a blank row at line ${index + 1}`);
820
+ let raw;
821
+ try {
822
+ raw = JSON.parse(line);
823
+ } catch (error) {
824
+ throw codec.integrityError(`${codec.subject} ${path} has invalid JSON at line ${index + 1}`, { cause: error });
825
+ }
826
+ const entry = codec.parseEntry(raw, {
827
+ path,
828
+ line: index + 1
829
+ });
830
+ let canonical;
831
+ try {
832
+ canonical = canonicalString(entry);
833
+ } catch (error) {
834
+ throw codec.integrityError(`${codec.subject} ${path} has a row with no canonical JSON form at line ${index + 1}`, { cause: error });
835
+ }
836
+ if (line !== canonical) throw codec.integrityError(`${codec.subject} ${path} has non-canonical bytes at line ${index + 1}`);
837
+ entries.push(entry);
838
+ }
839
+ return entries;
840
+ }
841
+ function projectLedgerEntries(entries, codec) {
842
+ const projector = codec.createProjector();
843
+ const eventIds = /* @__PURE__ */ new Set();
844
+ let expectedPrevious = null;
845
+ for (let index = 0; index < entries.length; index += 1) {
846
+ const entry = entries[index];
847
+ codec.checkEntryHeader(entry, index);
848
+ if (entry.sequence !== index) throw codec.integrityError(`entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`);
849
+ if (entry.previousHash !== expectedPrevious) throw codec.integrityError(`entry ${entry.event.eventId} does not extend the previous hash`);
850
+ const { entryHash: _entryHash, ...material } = entry;
851
+ const expectedHash = hashCanonical(material);
852
+ if (entry.entryHash !== expectedHash) throw codec.integrityError(`entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`);
853
+ expectedPrevious = entry.entryHash;
854
+ if (eventIds.has(entry.event.eventId)) throw codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`);
855
+ eventIds.add(entry.event.eventId);
856
+ projector.apply(entry, index);
857
+ }
858
+ return projector.finish(entries);
859
+ }
847
860
  //#endregion
848
- export { appendLedgerLine as a, writeLedgerFileAtomically as c, mapConcurrentRange as d, AtomicFileLockError as f, verifyEntriesAgainstTrustedHead as i, Mutex as l, tryAcquireAtomicFileLock as m, readTrustedHeadFile as n, tryWithLedgerFileLock as o, probeAtomicFileLock as p, trustedHeadPathFor as r, withLedgerFileLock as s, FileLedgerJournal as t, mapConcurrent as u };
861
+ export { verifyEntriesAgainstTrustedHead as a, withLedgerFileLock as c, mapConcurrent as d, mapConcurrentRange as f, tryAcquireAtomicFileLock as h, trustedHeadPathFor as i, writeLedgerFileAtomically as l, probeAtomicFileLock as m, replayLedgerText as n, appendLedgerLine as o, AtomicFileLockError as p, readTrustedHeadFile as r, tryWithLedgerFileLock as s, FileLedgerJournal as t, Mutex as u };
849
862
 
850
- //# sourceMappingURL=ledger-core-PIfjCbKn.js.map
863
+ //# sourceMappingURL=ledger-core-Cs9f7385.js.map