@tangle-network/agent-eval 0.139.3 → 0.140.1
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.
- package/CHANGELOG.md +22 -0
- package/dist/analyst/index.d.ts +15 -13
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +6 -6
- package/dist/{benchmark-DDVdWcwA.d.ts → benchmark-DxaZfy0w.d.ts} +3 -3
- package/dist/{benchmark-DDVdWcwA.d.ts.map → benchmark-DxaZfy0w.d.ts.map} +1 -1
- package/dist/{benchmark-command-xvi2liH7.js → benchmark-command-Bo_hkhQf.js} +54 -33
- package/dist/benchmark-command-Bo_hkhQf.js.map +1 -0
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +1 -1
- package/dist/{benchmarks-zxhy1QV3.js → benchmarks-HwoBE32G.js} +4 -4
- package/dist/{benchmarks-zxhy1QV3.js.map → benchmarks-HwoBE32G.js.map} +1 -1
- package/dist/campaign/index.d.ts +5 -5
- package/dist/campaign/index.js +3 -3
- package/dist/{campaign-DrS6_hLd.js → campaign-BzjYNYVZ.js} +5 -5
- package/dist/{campaign-DrS6_hLd.js.map → campaign-BzjYNYVZ.js.map} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{client-BohnDFBq.d.ts → client-BoqGxEqx.d.ts} +4 -4
- package/dist/{client-BohnDFBq.d.ts.map → client-BoqGxEqx.d.ts.map} +1 -1
- package/dist/{completion-verifier-IPoP4fQO.d.ts → completion-verifier-D15NHYSk.d.ts} +5 -5
- package/dist/{completion-verifier-IPoP4fQO.d.ts.map → completion-verifier-D15NHYSk.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +6 -6
- package/dist/control.d.ts +2 -2
- package/dist/{cost-ledger-CZ9diLxY.js → cost-ledger-DMFxsLKr.js} +22 -8
- package/dist/cost-ledger-DMFxsLKr.js.map +1 -0
- package/dist/{cost-ledger-DKgyIWRj.d.ts → cost-ledger-FuQvHxPm.d.ts} +8 -2
- package/dist/{cost-ledger-DKgyIWRj.d.ts.map → cost-ledger-FuQvHxPm.d.ts.map} +1 -1
- package/dist/{default-registry-BgJJItGr.js → default-registry-BOiBXNFh.js} +4 -4
- package/dist/{default-registry-BgJJItGr.js.map → default-registry-BOiBXNFh.js.map} +1 -1
- package/dist/{default-registry-B8vf7Rmf.d.ts → default-registry-Ci7wAAR8.d.ts} +5 -5
- package/dist/{default-registry-B8vf7Rmf.d.ts.map → default-registry-Ci7wAAR8.d.ts.map} +1 -1
- package/dist/{dspy-rlm-engine-DTkVyDX-.js → dspy-rlm-engine-Bkak4nzo.js} +11 -4
- package/dist/dspy-rlm-engine-Bkak4nzo.js.map +1 -0
- package/dist/{eval-campaign-BmptJj50.js → eval-campaign-YdkpWWoT.js} +2 -2
- package/dist/{eval-campaign-BmptJj50.js.map → eval-campaign-YdkpWWoT.js.map} +1 -1
- package/dist/{exact-types-MaaFcllV.d.ts → exact-types-B0lJV3tu.d.ts} +2 -2
- package/dist/{exact-types-MaaFcllV.d.ts.map → exact-types-B0lJV3tu.d.ts.map} +1 -1
- package/dist/{external-optimizer-contracts-BrxY2Sli.d.ts → external-optimizer-contracts-nb7c_WAR.d.ts} +12 -2
- package/dist/{external-optimizer-contracts-BrxY2Sli.d.ts.map → external-optimizer-contracts-nb7c_WAR.d.ts.map} +1 -1
- package/dist/{extract-usage-DZs601Va.js → extract-usage-C5vMw-0R.js} +2 -2
- package/dist/{extract-usage-DZs601Va.js.map → extract-usage-C5vMw-0R.js.map} +1 -1
- package/dist/{feedback-trajectory-BJUWOkJM.d.ts → feedback-trajectory-BCHqzLh3.d.ts} +3 -3
- package/dist/{feedback-trajectory-BJUWOkJM.d.ts.map → feedback-trajectory-BCHqzLh3.d.ts.map} +1 -1
- package/dist/fuzz.d.ts +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/hosted/index.d.ts +3 -3
- package/dist/{index-B798zyGh.d.ts → index-BKjcUH13.d.ts} +39 -3
- package/dist/index-BKjcUH13.d.ts.map +1 -0
- package/dist/{index-_66rVpwN.d.ts → index-CKI1CXTL.d.ts} +5 -5
- package/dist/{index-_66rVpwN.d.ts.map → index-CKI1CXTL.d.ts.map} +1 -1
- package/dist/{index-CWOPCJiw.d.ts → index-D2enbqA0.d.ts} +2 -2
- package/dist/{index-CWOPCJiw.d.ts.map → index-D2enbqA0.d.ts.map} +1 -1
- package/dist/{index-BTm_P9aC.d.ts → index-DCP4I2Qx.d.ts} +10 -10
- package/dist/{index-BTm_P9aC.d.ts.map → index-DCP4I2Qx.d.ts.map} +1 -1
- package/dist/{index-CtR1xh4V.d.ts → index-DFLVtPZ9.d.ts} +3 -3
- package/dist/{index-CtR1xh4V.d.ts.map → index-DFLVtPZ9.d.ts.map} +1 -1
- package/dist/index.d.ts +24 -24
- package/dist/index.js +15 -15
- package/dist/{insight-report-Bu5Wi9tG.d.ts → insight-report-Bh_8ksel.d.ts} +4 -4
- package/dist/{insight-report-Bu5Wi9tG.d.ts.map → insight-report-Bh_8ksel.d.ts.map} +1 -1
- package/dist/{integrity-COTh3DTH.d.ts → integrity-DRXobPEs.d.ts} +2 -2
- package/dist/{integrity-COTh3DTH.d.ts.map → integrity-DRXobPEs.d.ts.map} +1 -1
- package/dist/{integrity-CCXTftiL.js → integrity-hruKe6oe.js} +104 -12
- package/dist/integrity-hruKe6oe.js.map +1 -0
- package/dist/{kind-factory-CFxA0JQX.js → kind-factory-DB7nIs35.js} +2 -2
- package/dist/{kind-factory-CFxA0JQX.js.map → kind-factory-DB7nIs35.js.map} +1 -1
- package/dist/{llm-client-bkztEfIx.js → llm-client-B3WXSH5Y.js} +2 -2
- package/dist/{llm-client-bkztEfIx.js.map → llm-client-B3WXSH5Y.js.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{release-report-fZarvIm-.d.ts → release-report-B_bQOHM-.d.ts} +3 -3
- package/dist/{release-report-fZarvIm-.d.ts.map → release-report-B_bQOHM-.d.ts.map} +1 -1
- package/dist/{replay-DjG4IG60.d.ts → replay-BqTgoioO.d.ts} +6 -6
- package/dist/{replay-DjG4IG60.d.ts.map → replay-BqTgoioO.d.ts.map} +1 -1
- package/dist/{replay-SA4OB7O7.js → replay-k2MsOmv5.js} +4 -4
- package/dist/{replay-SA4OB7O7.js.map → replay-k2MsOmv5.js.map} +1 -1
- package/dist/reporting.d.ts +4 -4
- package/dist/{researcher-BxhtGfKa.d.ts → researcher-C6lzl-rP.d.ts} +5 -5
- package/dist/{researcher-BxhtGfKa.d.ts.map → researcher-C6lzl-rP.d.ts.map} +1 -1
- package/dist/{reward-hacking-CqSLiV51.d.ts → reward-hacking-CEVVmy3h.d.ts} +2 -2
- package/dist/{reward-hacking-CqSLiV51.d.ts.map → reward-hacking-CEVVmy3h.d.ts.map} +1 -1
- package/dist/rl.d.ts +5 -5
- package/dist/rl.js +1 -1
- package/dist/rollout/index.d.ts +1 -1
- package/dist/{rubric-predictive-validity-DQBQj6uV.d.ts → rubric-predictive-validity-C2CthIfY.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-DQBQj6uV.d.ts.map → rubric-predictive-validity-C2CthIfY.d.ts.map} +1 -1
- package/dist/{run-evidence-C4RcRQT5.d.ts → run-evidence-8Ou28QSa.d.ts} +3 -3
- package/dist/{run-evidence-C4RcRQT5.d.ts.map → run-evidence-8Ou28QSa.d.ts.map} +1 -1
- package/dist/{run-record-CztDMXVF.d.ts → run-record-Tb3TTtUn.d.ts} +2 -2
- package/dist/{run-record-CztDMXVF.d.ts.map → run-record-Tb3TTtUn.d.ts.map} +1 -1
- package/dist/{semantic-concept-judge-BuIJ9IfB.js → semantic-concept-judge-DJQtFr95.js} +3 -3
- package/dist/{semantic-concept-judge-BuIJ9IfB.js.map → semantic-concept-judge-DJQtFr95.js.map} +1 -1
- package/dist/{server-DaCpLfi0.js → server-Cu4M3NSO.js} +3 -3
- package/dist/{server-DaCpLfi0.js.map → server-Cu4M3NSO.js.map} +1 -1
- package/dist/{single-run-lock-BTTtPZ9N.js → single-run-lock-CiQThJxB.js} +22 -12
- package/dist/single-run-lock-CiQThJxB.js.map +1 -0
- package/dist/{skill-usage-B-BFS8M2.d.ts → skill-usage-CVVnoIx-.d.ts} +26 -10
- package/dist/skill-usage-CVVnoIx-.d.ts.map +1 -0
- package/dist/{skillopt-optimization-method-BbGnCC53.js → skillopt-optimization-method-CSBQ8Qma.js} +4 -4
- package/dist/{skillopt-optimization-method-BbGnCC53.js.map → skillopt-optimization-method-CSBQ8Qma.js.map} +1 -1
- package/dist/{skillopt-optimization-method-_s0Tub7Y.d.ts → skillopt-optimization-method-D1dqGzzH.d.ts} +11 -11
- package/dist/{skillopt-optimization-method-_s0Tub7Y.d.ts.map → skillopt-optimization-method-D1dqGzzH.d.ts.map} +1 -1
- package/dist/{statistics-B5d0Zd-z.d.ts → statistics-B4u_CiFd.d.ts} +2 -2
- package/dist/{statistics-B5d0Zd-z.d.ts.map → statistics-B4u_CiFd.d.ts.map} +1 -1
- package/dist/{store-otlp-DX4fGIcf.js → store-otlp-vRByAR6h.js} +2 -2
- package/dist/{store-otlp-DX4fGIcf.js.map → store-otlp-vRByAR6h.js.map} +1 -1
- package/dist/{summary-report-Cg7BifAM.d.ts → summary-report-o3eJ3gxG.d.ts} +3 -3
- package/dist/{summary-report-Cg7BifAM.d.ts.map → summary-report-o3eJ3gxG.d.ts.map} +1 -1
- package/dist/supervisor-run/index.d.ts +2 -2
- package/dist/supervisor-run/index.js +2 -2
- package/dist/{supervisor-run-D6A5oQw-.js → supervisor-run-BEns49Nx.js} +2 -2
- package/dist/supervisor-run-BEns49Nx.js.map +1 -0
- package/dist/{tool-groups-CdYq22lX.d.ts → tool-groups-DVQTy9lq.d.ts} +8 -8
- package/dist/{tool-groups-CdYq22lX.d.ts.map → tool-groups-DVQTy9lq.d.ts.map} +1 -1
- package/dist/traces.d.ts +6 -6
- package/dist/traces.js +4 -4
- package/dist/{types-uPrS6mD-.d.ts → types-BjMFz88h.d.ts} +2 -2
- package/dist/{types-uPrS6mD-.d.ts.map → types-BjMFz88h.d.ts.map} +1 -1
- package/dist/{types-DoEYskCd.d.ts → types-D3jh6F98.d.ts} +4 -4
- package/dist/{types-DoEYskCd.d.ts.map → types-D3jh6F98.d.ts.map} +1 -1
- package/dist/{types-BBFNHxSK.d.ts → types-Dk7PB7vh.d.ts} +5 -5
- package/dist/{types-BBFNHxSK.d.ts.map → types-Dk7PB7vh.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/package.json +1 -1
- package/dist/benchmark-command-xvi2liH7.js.map +0 -1
- package/dist/cost-ledger-CZ9diLxY.js.map +0 -1
- package/dist/dspy-rlm-engine-DTkVyDX-.js.map +0 -1
- package/dist/index-B798zyGh.d.ts.map +0 -1
- package/dist/integrity-CCXTftiL.js.map +0 -1
- package/dist/single-run-lock-BTTtPZ9N.js.map +0 -1
- package/dist/skill-usage-B-BFS8M2.d.ts.map +0 -1
- package/dist/supervisor-run-D6A5oQw-.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cost-ledger-CZ9diLxY.js","names":[],"sources":["../src/cost-ledger.ts"],"sourcesContent":["import { z } from 'zod'\nimport { ValidationError } from './errors'\nimport { estimateCost, isModelPriced, resolveModelPricing } from './metrics'\n\nexport type CostChannel = 'agent' | 'judge' | 'verifier' | 'analyst' | 'driver' | (string & {})\n\n/** How a USD amount was obtained. */\nexport type CostProvenance =\n | { kind: 'observed'; usd: number }\n | { kind: 'estimated'; usd: number }\n | { kind: 'uncaptured'; usd: null }\n\nexport interface CostUsage {\n inputTokens: number\n /** Includes reasoning tokens when the provider bills them as output. */\n outputTokens: number\n /** Reasoning-token subset of outputTokens, when reported. */\n reasoningTokens?: number\n /** Prompt tokens served from a provider cache. */\n cachedTokens?: number\n /** Prompt tokens written into a provider cache. */\n cacheWriteTokens?: number\n}\n\ninterface CostCallBase {\n callId: string\n channel: CostChannel\n phase: string\n actor: string\n model: string\n maximumCostUsd?: number\n tags?: Record<string, string>\n timestamp: number\n}\n\nexport interface PendingCostCall extends CostCallBase {\n status: 'pending'\n}\n\nexport interface PendingCostCallView extends PendingCostCall {\n state: 'active' | 'late' | 'interrupted'\n}\n\nexport interface CostReceipt extends CostCallBase, CostUsage {\n status: 'settled'\n costUsd: number\n costUnknown: boolean\n usageUnknown?: boolean\n /** Rates used to estimate cost locally. Absent when cost is provider-reported or unknown. */\n pricing?: {\n inputUsdPerThousand: number\n cachedInputUsdPerThousand?: number\n cacheWriteUsdPerThousand?: number\n outputUsdPerThousand: number\n }\n /** Cost reported by the provider, not a local token-price calculation. */\n actualCostUsd?: number\n /** Known non-provider amount supplied by an external executor. */\n estimatedCostUsd?: number\n /** Why the call failed. `'paid-call-failed'` is the ledger's own value for\n * recovery settles; a reconciling caller may record its own reason. */\n error?: string\n}\n\nexport type CostLedgerRecord = PendingCostCall | CostReceipt\n\nexport interface CostReceiptInput extends CostUsage {\n model: string\n /** Caller-supplied rates for a local estimate when the provider does not report billed cost. */\n customTokenPricing?: CustomTokenPricing\n actualCostUsd?: number\n /** A known estimate from an external executor that cannot provide token pricing. */\n estimatedCostUsd?: number\n costUnknown?: boolean\n usageUnknown?: boolean\n}\n\n/** Per-million token rates for a model or endpoint not covered by package pricing. */\nexport interface CustomTokenPricing {\n /** Non-cached input tokens. */\n inputUsdPerMillion: number\n /** Cache-read tokens. Falls back to the normal input rate when omitted. */\n cachedInputUsdPerMillion?: number\n /** Cache-creation or cache-write tokens. Falls back to the normal input rate when omitted. */\n cacheWriteUsdPerMillion?: number\n outputUsdPerMillion: number\n}\n\nexport type MaximumCharge =\n | { externallyEnforcedMaximumUsd: number }\n | ({\n customTokenPricing: CustomTokenPricing\n } & Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>)\n | ({ model: string } & CostUsage)\n\nexport interface RunPaidCallInput<T> {\n callId?: string\n channel: CostChannel\n phase: string\n actor: string\n /** Used before a provider receipt exists and on failures without one. */\n model?: string\n tags?: Record<string, string>\n signal?: AbortSignal\n /** Provider-enforced dollar maximum, or maximum token usage with known pricing. Required when capped. */\n maximumCharge?: MaximumCharge\n /** `callId` can be forwarded as the provider's idempotency key. */\n execute(signal: AbortSignal, callId: string): Promise<T>\n receipt(value: T): CostReceiptInput\n receiptFromError?(error: Error): CostReceiptInput | undefined\n}\n\nexport type PaidCallResult<T> =\n | { succeeded: true; callId: string; value: T; receipt: CostReceipt }\n | { succeeded: false; callId?: string; error: Error; receipt?: CostReceipt }\n\nexport interface ChannelRollup {\n channel: CostChannel\n calls: number\n inputTokens: number\n outputTokens: number\n reasoningTokens?: number\n cachedTokens: number\n cacheWriteTokens?: number\n costUsd: number\n unpricedCalls: number\n unknownUsageCalls: number\n}\n\nexport interface CostLedgerSummary {\n totalCalls: number\n pendingCalls: number\n unresolvedCalls: number\n reservedCostUsd: number\n inputTokens: number\n outputTokens: number\n reasoningTokens?: number\n cachedTokens: number\n cacheWriteTokens?: number\n totalCostUsd: number\n costProvenance: CostProvenance\n byChannel: ChannelRollup[]\n unpricedModels: string[]\n fullyPriced: boolean\n usageComplete: boolean\n accountingComplete: boolean\n incompleteReasons: string[]\n}\n\nexport interface CostLedgerFilter {\n channel?: CostChannel\n phase?: string\n tags?: Record<string, string>\n}\n\nexport interface CostLedgerWaitOptions {\n /** Maximum time to wait for active provider calls. Default 5 seconds. */\n timeoutMs?: number\n /** Wait only for calls matching this attribution filter. */\n filter?: CostLedgerFilter\n}\n\n/** Append-only storage. `append` must atomically reject stale revisions. */\nexport interface CostLedgerPersistence {\n read(): { revision: string; events: string }\n append(expectedRevision: string, event: string): string | undefined\n}\n\nexport interface CostLedgerOptions {\n costCeilingUsd?: number\n persistence?: CostLedgerPersistence\n /** Import already-settled receipts without admitting new paid work. */\n receipts?: readonly CostReceipt[]\n}\n\nexport class CostCeilingReachedError extends ValidationError {\n constructor(\n ceilingUsd: number,\n committedUsd: number,\n requestedUsd: number,\n phase: string,\n actor: string,\n ) {\n super(\n `CostLedger: reserving ${requestedUsd} for '${actor}' during '${phase}' would exceed ceiling ${ceilingUsd} with ${committedUsd} already committed`,\n )\n }\n}\n\nexport class CostAccountingIncompleteError extends ValidationError {}\n\nexport class CostReservationExceededError extends ValidationError {\n constructor(actor: string, actualUsd: number, maximumUsd: number) {\n super(\n `CostLedger: '${actor}' charged ${actualUsd}, exceeding its enforced maximum ${maximumUsd}`,\n )\n }\n}\n\nexport class CostCallConflictError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(\n message: string,\n options: { callId?: string; receipt?: CostReceipt; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.callId = options.callId\n this.receipt = options.receipt ? cloneReceipt(options.receipt) : undefined\n }\n}\n\nexport class CostLedgerPersistenceError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(cause: unknown, callId?: string, receipt?: CostReceipt) {\n super(\n `CostLedger: failed to persist${callId ? ` call '${callId}'` : ''}: ${toError(cause).message}`,\n { cause },\n )\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n }\n}\n\nexport class CostReceiptCaptureError extends ValidationError {\n readonly callId: string\n readonly receipt?: CostReceipt\n readonly receiptError: Error\n\n constructor(callId: string, cause: unknown, receiptError: unknown, receipt?: CostReceipt) {\n super(`CostLedger: could not capture the provider receipt for call '${callId}'`, { cause })\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n this.receiptError = toError(receiptError)\n }\n}\n\ninterface PendingCostCallEvent {\n version: 1\n record: PendingCostCall\n}\n\ninterface SettledCostCallEvent {\n version: 2\n record: CostReceipt\n}\n\ninterface CompletedTasksEvent {\n version: 1\n completedTasks: number\n}\n\ninterface CostLimitEvent {\n version: 1\n costCeilingUsd: number\n}\n\ntype CostCallEvent = PendingCostCallEvent | SettledCostCallEvent\ntype CostLedgerEvent = CostCallEvent | CompletedTasksEvent | CostLimitEvent\n\n/** Run-wide paid-call admission, durable call state, receipts, and summaries. */\nexport class CostLedger {\n private readonly records = new Map<string, CostLedgerRecord>()\n private readonly activeCallIds = new Set<string>()\n private readonly lateCallIds = new Set<string>()\n private readonly idleWaiters = new Set<() => void>()\n private completedTasks = 0\n private revision = 'memory'\n private costLimitPersisted = false\n readonly costCeilingUsd?: number\n private readonly persistence?: CostLedgerPersistence\n\n constructor(input?: number | CostLedgerOptions) {\n const options = typeof input === 'number' ? { costCeilingUsd: input } : (input ?? {})\n this.persistence = options.persistence\n if (options.costCeilingUsd !== undefined) {\n assertNonNegative(options.costCeilingUsd, 'costCeilingUsd')\n }\n\n let persistedCostCeilingUsd: number | undefined\n if (this.persistence) {\n let stored: ReturnType<CostLedgerPersistence['read']>\n try {\n stored = this.persistence.read()\n } catch (cause) {\n throw new CostLedgerPersistenceError(cause)\n }\n assertString(stored.revision, 'persistence revision')\n this.revision = stored.revision\n const restored = parseEvents(stored.events)\n for (const record of restored.records) this.records.set(record.callId, record)\n this.completedTasks = restored.completedTasks\n persistedCostCeilingUsd = restored.costCeilingUsd\n }\n\n if (\n options.costCeilingUsd !== undefined &&\n persistedCostCeilingUsd !== undefined &&\n options.costCeilingUsd !== persistedCostCeilingUsd\n ) {\n throw new ValidationError(\n `CostLedger: requested cost ceiling ${options.costCeilingUsd} does not match persisted ceiling ${persistedCostCeilingUsd}`,\n )\n }\n this.costCeilingUsd = persistedCostCeilingUsd ?? options.costCeilingUsd\n this.costLimitPersisted =\n !this.persistence ||\n this.costCeilingUsd === undefined ||\n persistedCostCeilingUsd !== undefined\n\n if (\n this.costCeilingUsd !== undefined &&\n [...this.records.values()].some(\n (record) => record.status === 'pending' && record.maximumCostUsd === undefined,\n )\n ) {\n throw new ValidationError('CostLedger: capped event log contains an unbounded pending call')\n }\n\n if (options.receipts?.length) {\n const imported = options.receipts.map((receipt, index) =>\n parseImportedReceipt(receipt, `imported receipt ${index + 1}`),\n )\n this.ensureCostLimitPersisted()\n for (const receipt of imported) this.appendRecord(receipt)\n }\n }\n\n async runPaidCall<T>(input: RunPaidCallInput<T>): Promise<PaidCallResult<T>> {\n let callId: string | undefined\n let pending: PendingCostCall | undefined\n try {\n callId = resolveCallId(input.callId)\n validateAttribution(input)\n if (input.signal?.aborted) {\n return { succeeded: false, callId, error: abortError(input.signal) }\n }\n this.ensureCostLimitPersisted(callId)\n\n const maximumCostUsd = this.resolveMaximum(input.maximumCharge)\n const existing = this.records.get(callId)\n if (existing) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(\n existing.status === 'pending'\n ? `CostLedger: callId '${callId}' is unresolved and must be reconciled before retry`\n : `CostLedger: callId '${callId}' already exists`,\n { callId },\n ),\n }\n }\n\n if (!pending) {\n while (true) {\n if (this.records.has(callId)) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(`CostLedger: callId '${callId}' already exists`),\n }\n }\n const summary = this.summary()\n if (summary.unresolvedCalls > 0) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: ${summary.unresolvedCalls} unresolved call(s) must be reconciled before new paid work`,\n ),\n }\n }\n if (this.costCeilingUsd === undefined) break\n if (this.hasIncompleteSettledCall()) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: accounting is incomplete; refusing paid call '${input.actor}' during '${input.phase}'`,\n ),\n }\n }\n if (summary.totalCostUsd + maximumCostUsd! > this.costCeilingUsd) {\n return {\n succeeded: false,\n callId,\n error: new CostCeilingReachedError(\n this.costCeilingUsd,\n summary.totalCostUsd,\n maximumCostUsd!,\n input.phase,\n input.actor,\n ),\n }\n }\n if (\n summary.totalCostUsd + summary.reservedCostUsd + maximumCostUsd! <=\n this.costCeilingUsd\n ) {\n break\n }\n await this.waitForReservationRelease(input.signal)\n }\n\n pending = {\n status: 'pending',\n callId,\n channel: input.channel,\n phase: input.phase,\n actor: input.actor,\n model: pendingModel(input),\n ...(maximumCostUsd === undefined ? {} : { maximumCostUsd }),\n ...(input.tags ? { tags: { ...input.tags } } : {}),\n timestamp: Date.now(),\n }\n this.appendRecord(pending)\n this.activeCallIds.add(callId)\n }\n } catch (error) {\n return { succeeded: false, ...(callId ? { callId } : {}), error: toError(error) }\n }\n\n try {\n return await this.execute(input, pending)\n } catch (error) {\n return { succeeded: false, callId: pending.callId, error: toError(error) }\n } finally {\n if (!this.lateCallIds.has(pending.callId)) this.releaseActiveCall(pending.callId)\n }\n }\n\n /** Wait until every call started by this ledger has produced a durable outcome. */\n async waitForIdle(options: CostLedgerWaitOptions = {}): Promise<boolean> {\n const hasActiveMatch = (): boolean =>\n [...this.activeCallIds].some((callId) => {\n const record = this.records.get(callId)\n return record !== undefined && matches(record, options.filter)\n })\n if (!hasActiveMatch()) return true\n const timeoutMs = options.timeoutMs ?? 5_000\n assertTimeout(timeoutMs, 'waitForIdle.timeoutMs')\n return new Promise<boolean>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const finish = (settled: boolean): void => {\n this.idleWaiters.delete(onIdle)\n if (timer !== undefined) clearTimeout(timer)\n resolve(settled)\n }\n const onIdle = (): void => {\n if (!hasActiveMatch()) finish(true)\n }\n this.idleWaiters.add(onIdle)\n timer = setTimeout(() => finish(false), timeoutMs)\n onIdle()\n })\n }\n\n /** Settle a call left pending by a crashed process after reconciling with the provider. */\n reconcile(\n callId: string,\n observed: CostReceiptInput,\n options: { failed?: boolean; error?: string } = {},\n ): CostReceipt {\n const pending = [...this.records.values()].find(\n (record): record is PendingCostCall =>\n record.callId === callId && record.status === 'pending',\n )\n if (!pending) throw new CostCallConflictError(`CostLedger: no pending call '${callId}'`)\n if (this.activeCallIds.has(callId)) {\n throw new CostCallConflictError(`CostLedger: call '${callId}' is still active`)\n }\n this.ensureCostLimitPersisted(callId)\n return this.commitReceipt(\n pending,\n observed,\n options.failed === true || options.error !== undefined,\n options.error,\n )\n }\n\n list(filter?: CostLedgerFilter): CostReceipt[] {\n return [...this.records.values()]\n .filter((record): record is CostReceipt => record.status === 'settled')\n .filter((receipt) => matches(receipt, filter))\n .map(cloneReceipt)\n }\n\n /** Read pending calls without exposing mutable ledger state. */\n listPending(filter?: CostLedgerFilter): PendingCostCallView[] {\n return [...this.records.values()]\n .filter((record): record is PendingCostCall => record.status === 'pending')\n .filter((record) => matches(record, filter))\n .map((record) => ({\n ...clonePendingCall(record),\n state: this.lateCallIds.has(record.callId)\n ? 'late'\n : this.activeCallIds.has(record.callId)\n ? 'active'\n : 'interrupted',\n }))\n }\n\n summary(filter?: CostLedgerFilter): CostLedgerSummary {\n const records = [...this.records.values()].filter((record) => matches(record, filter))\n const pending = records.filter(\n (record): record is PendingCostCall => record.status === 'pending',\n )\n const receipts = records.filter((record): record is CostReceipt => record.status === 'settled')\n const byChannel = new Map<string, ChannelRollup>()\n const unpriced = new Set<string>()\n const incompleteReasons: string[] = pending.map(\n (record) => `call '${record.callId}' for '${record.actor}' is pending`,\n )\n let inputTokens = 0\n let outputTokens = 0\n let reasoningTokens = 0\n let cachedTokens = 0\n let cacheWriteTokens = 0\n let totalCostUsd = 0\n\n for (const receipt of receipts) {\n inputTokens += receipt.inputTokens\n outputTokens += receipt.outputTokens\n reasoningTokens += receipt.reasoningTokens ?? 0\n cachedTokens += receipt.cachedTokens ?? 0\n cacheWriteTokens += receipt.cacheWriteTokens ?? 0\n totalCostUsd += receipt.costUsd\n if (receipt.costUnknown) {\n unpriced.add(receipt.model)\n incompleteReasons.push(\n receipt.error ?? `cost unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.usageUnknown) {\n incompleteReasons.push(\n `token usage unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n incompleteReasons.push(\n `'${receipt.actor}' charged ${receipt.costUsd}, exceeding its enforced maximum ${receipt.maximumCostUsd}`,\n )\n }\n const rollup = byChannel.get(receipt.channel) ?? emptyRollup(receipt.channel)\n rollup.calls += 1\n rollup.inputTokens += receipt.inputTokens\n rollup.outputTokens += receipt.outputTokens\n rollup.reasoningTokens = (rollup.reasoningTokens ?? 0) + (receipt.reasoningTokens ?? 0)\n rollup.cachedTokens += receipt.cachedTokens ?? 0\n rollup.cacheWriteTokens = (rollup.cacheWriteTokens ?? 0) + (receipt.cacheWriteTokens ?? 0)\n rollup.costUsd += receipt.costUsd\n if (receipt.costUnknown) rollup.unpricedCalls += 1\n if (receipt.usageUnknown) rollup.unknownUsageCalls += 1\n byChannel.set(receipt.channel, rollup)\n }\n\n return {\n totalCalls: receipts.length,\n pendingCalls: pending.length,\n unresolvedCalls: pending.filter(\n (record) => !this.activeCallIds.has(record.callId) || this.lateCallIds.has(record.callId),\n ).length,\n reservedCostUsd: pending.reduce((sum, record) => sum + (record.maximumCostUsd ?? 0), 0),\n inputTokens,\n outputTokens,\n reasoningTokens,\n cachedTokens,\n cacheWriteTokens,\n totalCostUsd,\n costProvenance:\n pending.length > 0 || receipts.some((receipt) => receipt.costUnknown)\n ? { kind: 'uncaptured', usd: null }\n : receipts.every((receipt) => receipt.actualCostUsd !== undefined)\n ? { kind: 'observed', usd: totalCostUsd }\n : { kind: 'estimated', usd: totalCostUsd },\n byChannel: [...byChannel.values()].sort((a, b) => a.channel.localeCompare(b.channel)),\n unpricedModels: [...unpriced].sort(),\n fullyPriced: unpriced.size === 0,\n usageComplete: pending.length === 0 && receipts.every((receipt) => !receipt.usageUnknown),\n accountingComplete: incompleteReasons.length === 0,\n incompleteReasons: [...new Set(incompleteReasons)],\n }\n }\n\n markCompleted(count = 1): void {\n if (!Number.isInteger(count) || count < 0) {\n throw new ValidationError(\n `CostLedger.markCompleted: count must be a non-negative integer, got ${count}`,\n )\n }\n if (count === 0) return\n this.ensureCostLimitPersisted()\n this.appendEvent({ version: 1, completedTasks: count })\n this.completedTasks += count\n }\n\n costPerCompletedTask(): number | null {\n return this.completedTasks === 0 ? null : this.summary().totalCostUsd / this.completedTasks\n }\n\n private async execute<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n ): Promise<PaidCallResult<T>> {\n const signal = input.signal ?? new AbortController().signal\n if (signal.aborted) {\n return this.commitOutcome(pending, abortError(signal), {\n model: pending.model,\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: 0,\n })\n }\n\n const operation = Promise.resolve().then(() => input.execute(signal, pending.callId))\n const settled = await settle(operation, signal)\n if (settled.kind === 'aborted') {\n this.lateCallIds.add(pending.callId)\n this.captureLateOutcome(input, pending, operation)\n return paidFailure(pending.callId, abortError(signal))\n }\n if (settled.kind === 'error') {\n let observed: CostReceiptInput | undefined\n try {\n observed = input.receiptFromError?.(settled.error)\n } catch (receiptError) {\n return this.captureFailure(pending, settled.error, receiptError)\n }\n return this.commitOutcome(pending, settled.error, observed ?? unknownReceipt(pending.model))\n }\n\n try {\n const receipt = this.commitReceipt(pending, input.receipt(settled.value))\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n return paidFailure(\n pending.callId,\n new CostReservationExceededError(pending.actor, receipt.costUsd, receipt.maximumCostUsd),\n receipt,\n )\n }\n return { succeeded: true, callId: pending.callId, value: settled.value, receipt }\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, receiptError, receiptError)\n }\n }\n\n private captureLateOutcome<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n operation: Promise<T>,\n ): void {\n void operation\n .then(\n (value) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n try {\n this.commitReceipt(pending, input.receipt(value))\n } catch {\n // A failed durable settlement leaves the reservation pending and blocks new paid work.\n }\n },\n (cause) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n const error = toError(cause)\n try {\n const observed = input.receiptFromError?.(error)\n this.commitReceipt(pending, observed ?? unknownReceipt(pending.model), true)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return\n }\n this.captureFailure(pending, error, receiptError)\n }\n },\n )\n .finally(() => {\n this.lateCallIds.delete(pending.callId)\n this.releaseActiveCall(pending.callId)\n })\n }\n\n private releaseActiveCall(callId: string): void {\n this.activeCallIds.delete(callId)\n for (const resolve of [...this.idleWaiters]) resolve()\n }\n\n private async waitForReservationRelease(signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw abortError(signal)\n await new Promise<void>((resolve, reject) => {\n let finished = false\n const finish = (error?: Error): void => {\n if (finished) return\n finished = true\n this.idleWaiters.delete(onRelease)\n signal?.removeEventListener('abort', onAbort)\n if (error) reject(error)\n else resolve()\n }\n const onRelease = (): void => finish()\n const onAbort = (): void => finish(abortError(signal!))\n this.idleWaiters.add(onRelease)\n signal?.addEventListener('abort', onAbort, { once: true })\n if (this.activeCallIds.size === 0) onRelease()\n })\n }\n\n private commitOutcome<T>(\n pending: PendingCostCall,\n error: Error,\n observed: CostReceiptInput,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, observed, true)\n return paidFailure(pending.callId, error, receipt)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, error, receiptError)\n }\n }\n\n private captureFailure<T>(\n pending: PendingCostCall,\n cause: unknown,\n receiptError: unknown,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, unknownReceipt(pending.model), true)\n return paidFailure(\n pending.callId,\n new CostReceiptCaptureError(pending.callId, cause, receiptError, receipt),\n receipt,\n )\n } catch (error) {\n const typed = error instanceof Error ? error : toError(error)\n return paidFailure(pending.callId, typed)\n }\n }\n\n private commitReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n ): CostReceipt {\n const receipt = buildReceipt(pending, observed, failed, error)\n if (this.records.get(pending.callId)?.status !== 'pending') {\n throw new CostCallConflictError(`CostLedger: call '${pending.callId}' is not pending`)\n }\n this.appendRecord(receipt)\n return cloneReceipt(receipt)\n }\n\n private resolveMaximum(maximum: MaximumCharge | undefined): number | undefined {\n if (!maximum) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n 'CostLedger: capped paid calls require a hard maximumCharge before execution',\n )\n }\n return undefined\n }\n if ('externallyEnforcedMaximumUsd' in maximum) {\n assertNonNegative(\n maximum.externallyEnforcedMaximumUsd,\n 'maximumCharge.externallyEnforcedMaximumUsd',\n )\n return maximum.externallyEnforcedMaximumUsd\n }\n if ('customTokenPricing' in maximum) {\n return costForTokenPricing(maximum.customTokenPricing, maximum)\n }\n const priced = costForUsage(maximum.model, maximum)\n if (priced.costUnknown) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n `CostLedger: cannot reserve unpriced model '${maximum.model}' in a capped run`,\n )\n }\n return undefined\n }\n return priced.costUsd\n }\n\n private hasIncompleteSettledCall(): boolean {\n return [...this.records.values()].some(\n (record) =>\n record.status === 'settled' &&\n (record.costUnknown ||\n record.usageUnknown ||\n (record.maximumCostUsd !== undefined && record.costUsd > record.maximumCostUsd)),\n )\n }\n\n private appendRecord(record: CostLedgerRecord): void {\n const callId = record.callId\n const receipt = record.status === 'settled' ? record : undefined\n validateTransition(this.records, record)\n const event: CostCallEvent =\n record.status === 'settled'\n ? { version: 2, record: cloneReceipt(record) }\n : { version: 1, record: clonePendingCall(record) }\n this.appendEvent(event, callId, receipt)\n this.records.set(callId, cloneRecord(record))\n }\n\n private ensureCostLimitPersisted(callId?: string): void {\n if (this.costLimitPersisted || this.costCeilingUsd === undefined) return\n this.appendEvent({ version: 1, costCeilingUsd: this.costCeilingUsd }, callId)\n this.costLimitPersisted = true\n }\n\n private appendEvent(event: CostLedgerEvent, callId?: string, receipt?: CostReceipt): void {\n try {\n if (this.persistence) {\n const nextRevision = this.persistence.append(this.revision, `${JSON.stringify(event)}\\n`)\n if (nextRevision === undefined) {\n throw new CostCallConflictError(\n `CostLedger: persisted revision changed while writing call '${callId}'`,\n { callId, receipt },\n )\n }\n assertString(nextRevision, 'persistence revision')\n this.revision = nextRevision\n }\n } catch (cause) {\n if (cause instanceof CostCallConflictError) throw cause\n throw new CostLedgerPersistenceError(cause, callId, receipt)\n }\n }\n}\n\n/** Public callback surface for a shared cost ledger.\n *\n * Declaration bundles may expose this type through multiple package subpaths.\n * Keeping callback contracts structural lets those subpaths compose while the\n * concrete {@link CostLedger} retains its private durable state.\n */\nexport type CostLedgerHandle = Pick<\n CostLedger,\n Exclude<keyof CostLedger, 'listPending' | 'waitForIdle'>\n> &\n Partial<Pick<CostLedger, 'listPending' | 'waitForIdle'>>\n\n/** Return the canonical pricing-table key, or null when the model is unpriced. */\nexport function modelPriceKey(model: string): string | null {\n return isModelPriced(model) ? model : null\n}\n\nexport interface CostResult {\n costUsd: number\n costUnknown: boolean\n}\n\nexport function costForUsage(model: string, usage: CostUsage): CostResult {\n assertUsage(usage)\n if (!resolveModelPricing(model)) return { costUsd: 0, costUnknown: true }\n return {\n costUsd: estimateCost(\n usage.inputTokens + (usage.cachedTokens ?? 0) + (usage.cacheWriteTokens ?? 0),\n usage.outputTokens,\n model,\n ),\n costUnknown: false,\n }\n}\n\n/** Price token counts with caller-supplied per-million rates. */\nexport function costForTokenPricing(\n pricing: CustomTokenPricing,\n usage: Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>,\n): number {\n assertTokenCount(usage.inputTokens, 'usage.inputTokens')\n assertTokenCount(usage.outputTokens, 'usage.outputTokens')\n if (usage.cachedTokens !== undefined) {\n assertTokenCount(usage.cachedTokens, 'usage.cachedTokens')\n }\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'usage.cacheWriteTokens')\n }\n assertNonNegative(pricing.inputUsdPerMillion, 'pricing.inputUsdPerMillion')\n if (pricing.cachedInputUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cachedInputUsdPerMillion, 'pricing.cachedInputUsdPerMillion')\n }\n if (pricing.cacheWriteUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cacheWriteUsdPerMillion, 'pricing.cacheWriteUsdPerMillion')\n }\n assertNonNegative(pricing.outputUsdPerMillion, 'pricing.outputUsdPerMillion')\n const cachedInputRate = pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion\n const cacheWriteRate = pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion\n return (\n (usage.inputTokens / 1_000_000) * pricing.inputUsdPerMillion +\n ((usage.cachedTokens ?? 0) / 1_000_000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1_000_000) * cacheWriteRate +\n (usage.outputTokens / 1_000_000) * pricing.outputUsdPerMillion\n )\n}\n\ntype Settled<T> =\n | { kind: 'value'; value: T }\n | { kind: 'error'; error: Error }\n | { kind: 'aborted' }\n\nasync function settle<T>(promise: Promise<T>, signal: AbortSignal): Promise<Settled<T>> {\n return await new Promise((resolve) => {\n let done = false\n const finish = (value: Settled<T>): void => {\n if (done) return\n done = true\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n }\n const onAbort = () => finish({ kind: 'aborted' })\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) onAbort()\n promise.then(\n (value) => finish({ kind: 'value', value }),\n (error) => finish({ kind: 'error', error: toError(error) }),\n )\n })\n}\n\nfunction buildReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n): CostReceipt {\n assertUsage(observed)\n assertString(observed.model, 'receipt.model')\n const suppliedAmounts = [\n observed.actualCostUsd,\n observed.estimatedCostUsd,\n observed.customTokenPricing,\n ].filter((value) => value !== undefined)\n if (suppliedAmounts.length > 1) {\n throw new ValidationError(\n 'CostLedger: a receipt can have only one of actualCostUsd, estimatedCostUsd, or customTokenPricing',\n )\n }\n const customPricingSnapshot =\n observed.customTokenPricing === undefined\n ? undefined\n : pricingSnapshot(observed.customTokenPricing)\n const estimated = customPricingSnapshot\n ? {\n costUsd: costFromPricing(observed, customPricingSnapshot),\n costUnknown: false,\n }\n : costForUsage(observed.model, observed)\n const hasActual = observed.actualCostUsd !== undefined\n const hasExternalEstimate = observed.estimatedCostUsd !== undefined\n if (hasActual && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both actualCostUsd and costUnknown=true',\n )\n }\n if (hasActual) assertNonNegative(observed.actualCostUsd!, 'actualCostUsd')\n if (hasExternalEstimate) assertNonNegative(observed.estimatedCostUsd!, 'estimatedCostUsd')\n if (hasExternalEstimate && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both estimatedCostUsd and costUnknown=true',\n )\n }\n const usageUnknown = observed.usageUnknown === true\n const costUnknown =\n observed.costUnknown === true ||\n (!hasActual && !hasExternalEstimate && (usageUnknown || estimated.costUnknown))\n const resolvedModelPricing =\n !customPricingSnapshot && !hasActual && !hasExternalEstimate && !costUnknown\n ? resolveModelPricing(observed.model)\n : null\n const receiptPricing =\n !hasActual && !hasExternalEstimate && !costUnknown\n ? (customPricingSnapshot ??\n (resolvedModelPricing\n ? {\n inputUsdPerThousand: resolvedModelPricing.input,\n outputUsdPerThousand: resolvedModelPricing.output,\n }\n : undefined))\n : undefined\n return parseReceipt(\n {\n status: 'settled',\n callId: pending.callId,\n channel: pending.channel,\n phase: pending.phase,\n actor: pending.actor,\n model: observed.model,\n inputTokens: observed.inputTokens,\n outputTokens: observed.outputTokens,\n ...(observed.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: observed.reasoningTokens }),\n ...(observed.cachedTokens === undefined ? {} : { cachedTokens: observed.cachedTokens }),\n ...(observed.cacheWriteTokens === undefined\n ? {}\n : { cacheWriteTokens: observed.cacheWriteTokens }),\n costUsd: costUnknown\n ? 0\n : hasActual\n ? observed.actualCostUsd!\n : hasExternalEstimate\n ? observed.estimatedCostUsd!\n : estimated.costUsd,\n costUnknown,\n usageUnknown,\n ...(receiptPricing ? { pricing: receiptPricing } : {}),\n ...(hasActual ? { actualCostUsd: observed.actualCostUsd } : {}),\n ...(hasExternalEstimate ? { estimatedCostUsd: observed.estimatedCostUsd } : {}),\n ...(pending.maximumCostUsd === undefined ? {} : { maximumCostUsd: pending.maximumCostUsd }),\n ...(failed ? { error: error ?? 'paid-call-failed' } : {}),\n ...(pending.tags ? { tags: { ...pending.tags } } : {}),\n timestamp: pending.timestamp,\n },\n 'provider receipt',\n )\n}\n\nconst NonEmptyString = z.string().refine((value) => value.trim().length > 0, 'must be non-empty')\nconst TokenCount = z.number().int().nonnegative().finite()\nconst NonNegative = z.number().nonnegative().finite()\nconst Tags = z.record(NonEmptyString, z.string())\nconst CostPricingSchema = z.strictObject({\n inputUsdPerThousand: NonNegative,\n cachedInputUsdPerThousand: NonNegative.optional(),\n cacheWriteUsdPerThousand: NonNegative.optional(),\n outputUsdPerThousand: NonNegative,\n})\nconst CostCallBaseShape = {\n callId: NonEmptyString,\n channel: NonEmptyString,\n phase: NonEmptyString,\n actor: NonEmptyString,\n model: NonEmptyString,\n maximumCostUsd: NonNegative.optional(),\n tags: Tags.optional(),\n timestamp: NonNegative,\n}\nconst PendingCostCallSchema = z.strictObject({\n status: z.literal('pending'),\n ...CostCallBaseShape,\n})\nconst CostReceiptBaseShape = {\n status: z.literal('settled'),\n ...CostCallBaseShape,\n inputTokens: TokenCount,\n outputTokens: TokenCount,\n cachedTokens: TokenCount.optional(),\n costUsd: NonNegative,\n costUnknown: z.boolean(),\n usageUnknown: z.boolean().default(false),\n pricing: CostPricingSchema.optional(),\n actualCostUsd: NonNegative.optional(),\n estimatedCostUsd: NonNegative.optional(),\n error: NonEmptyString.optional(),\n}\nconst CostReceiptSchema = z\n .strictObject({\n ...CostReceiptBaseShape,\n reasoningTokens: TokenCount.optional(),\n cacheWriteTokens: TokenCount.optional(),\n })\n .superRefine((receipt, ctx) => validateCostReceipt(receipt, ctx))\n\nfunction validateCostReceipt(\n receipt: CostUsage & {\n costUsd: number\n costUnknown: boolean\n usageUnknown: boolean\n pricing?: NonNullable<CostReceipt['pricing']>\n actualCostUsd?: number\n estimatedCostUsd?: number\n },\n ctx: z.RefinementCtx,\n): void {\n if (receipt.reasoningTokens !== undefined && receipt.reasoningTokens > receipt.outputTokens) {\n ctx.addIssue({ code: 'custom', message: 'reasoningTokens must not exceed outputTokens' })\n }\n\n if (receipt.actualCostUsd !== undefined && receipt.estimatedCostUsd !== undefined) {\n ctx.addIssue({\n code: 'custom',\n message: 'actual and external estimated costs cannot both be present',\n })\n }\n\n if (receipt.actualCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.actualCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.estimatedCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.estimatedCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must not include token pricing' })\n }\n return\n }\n\n if (receipt.costUnknown) {\n if (receipt.costUsd !== 0) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must have costUsd 0' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.usageUnknown) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires known usage' })\n }\n if (!receipt.pricing) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires a pricing snapshot' })\n return\n }\n\n const expected = costFromPricing(receipt, receipt.pricing)\n if (!costAmountsMatch(receipt.costUsd, expected)) {\n ctx.addIssue({\n code: 'custom',\n message: `estimated cost ${receipt.costUsd} does not match pricing snapshot ${expected}`,\n })\n }\n}\n\nfunction costAmountsMatch(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right))\n return Math.abs(left - right) <= Number.EPSILON * scale * 8\n}\n\nconst CostLedgerEventSchema = z.union([\n z.strictObject({\n version: z.literal(1),\n record: PendingCostCallSchema,\n }),\n z.strictObject({\n version: z.literal(2),\n record: CostReceiptSchema,\n }),\n z.strictObject({\n version: z.literal(1),\n completedTasks: TokenCount,\n }),\n z.strictObject({\n version: z.literal(1),\n costCeilingUsd: NonNegative,\n }),\n])\n\nfunction parseEvents(serialized: string): {\n records: CostLedgerRecord[]\n completedTasks: number\n costCeilingUsd?: number\n} {\n const records = new Map<string, CostLedgerRecord>()\n let completedTasks = 0\n let costCeilingUsd: number | undefined\n let lineNumber = 0\n try {\n for (const line of completeJournalPrefix(serialized).split('\\n')) {\n if (!line.trim()) continue\n lineNumber += 1\n const event = CostLedgerEventSchema.parse(JSON.parse(line)) as CostLedgerEvent\n if ('record' in event) {\n const record = event.record\n validateTransition(records, record)\n records.set(record.callId, cloneRecord(record))\n } else if ('completedTasks' in event) {\n completedTasks += event.completedTasks\n if (!Number.isSafeInteger(completedTasks)) {\n throw new ValidationError('CostLedger: completed task count exceeds safe integer range')\n }\n } else {\n if (costCeilingUsd !== undefined) {\n throw new ValidationError('CostLedger: duplicate persisted cost ceiling')\n }\n costCeilingUsd = event.costCeilingUsd\n }\n }\n return {\n records: [...records.values()],\n completedTasks,\n ...(costCeilingUsd === undefined ? {} : { costCeilingUsd }),\n }\n } catch (cause) {\n throw new ValidationError(\n `CostLedger: invalid persisted event ${lineNumber || 1}: ${validationMessage(cause)}`,\n { cause },\n )\n }\n}\n\nfunction completeJournalPrefix(serialized: string): string {\n if (!serialized || serialized.endsWith('\\n')) return serialized\n const finalNewline = serialized.lastIndexOf('\\n')\n const tail = serialized.slice(finalNewline + 1)\n try {\n JSON.parse(tail)\n } catch {\n return finalNewline < 0 ? '' : serialized.slice(0, finalNewline + 1)\n }\n throw new ValidationError(\n 'CostLedger: complete final persisted event is missing its newline terminator',\n )\n}\n\nfunction validateTransition(\n records: ReadonlyMap<string, CostLedgerRecord>,\n record: CostLedgerRecord,\n): void {\n const current = records.get(record.callId)\n if (!current) return\n if (record.status === 'pending' || current.status === 'settled') {\n throw new CostCallConflictError(`CostLedger: duplicate callId '${record.callId}'`)\n }\n if (!sameAttribution(current, record)) {\n throw new ValidationError(`CostLedger: receipt attribution changed for call '${record.callId}'`)\n }\n}\n\nfunction sameAttribution(before: CostCallBase, after: CostCallBase): boolean {\n return (\n before.channel === after.channel &&\n before.phase === after.phase &&\n before.actor === after.actor &&\n before.maximumCostUsd === after.maximumCostUsd &&\n before.timestamp === after.timestamp &&\n sameTags(before.tags, after.tags)\n )\n}\n\nfunction sameTags(\n left: Readonly<Record<string, string>> | undefined,\n right: Readonly<Record<string, string>> | undefined,\n): boolean {\n const leftEntries = Object.entries(left ?? {}).sort(([a], [b]) => a.localeCompare(b))\n const rightEntries = Object.entries(right ?? {}).sort(([a], [b]) => a.localeCompare(b))\n return JSON.stringify(leftEntries) === JSON.stringify(rightEntries)\n}\n\nfunction parseReceipt(value: unknown, path: string): CostReceipt {\n try {\n return CostReceiptSchema.parse(value) as CostReceipt\n } catch (cause) {\n throw new ValidationError(`CostLedger: invalid ${path}: ${validationMessage(cause)}`, { cause })\n }\n}\n\nfunction parseImportedReceipt(value: unknown, path: string): CostReceipt {\n if (typeof value !== 'object' || value === null) return parseReceipt(value, path)\n const candidate = { ...value } as Record<string, unknown>\n if (\n candidate.status === 'settled' &&\n candidate.actualCostUsd === undefined &&\n candidate.estimatedCostUsd === undefined &&\n candidate.costUnknown === false &&\n candidate.pricing === undefined &&\n typeof candidate.model === 'string'\n ) {\n const pricing = resolveModelPricing(candidate.model)\n if (pricing) {\n candidate.pricing = {\n inputUsdPerThousand: pricing.input,\n outputUsdPerThousand: pricing.output,\n }\n }\n }\n return parseReceipt(candidate, path)\n}\n\nfunction validateAttribution(\n input: Pick<RunPaidCallInput<unknown>, 'channel' | 'phase' | 'actor' | 'model' | 'tags'>,\n): void {\n assertString(input.channel, 'channel')\n assertString(input.phase, 'phase')\n assertString(input.actor, 'actor')\n if (input.model !== undefined) assertString(input.model, 'model')\n if (input.tags !== undefined) {\n const parsed = Tags.safeParse(input.tags)\n if (!parsed.success)\n throw new ValidationError(`CostLedger: invalid tags: ${parsed.error.message}`)\n }\n}\n\nfunction matches(record: CostCallBase, filter: CostLedgerFilter | undefined): boolean {\n if (!filter) return true\n if (filter.channel !== undefined && record.channel !== filter.channel) return false\n if (filter.phase !== undefined && record.phase !== filter.phase) return false\n return Object.entries(filter.tags ?? {}).every(([key, value]) => record.tags?.[key] === value)\n}\n\nfunction cloneRecord(record: CostLedgerRecord): CostLedgerRecord {\n if (record.status === 'settled') return cloneReceipt(record)\n return clonePendingCall(record)\n}\n\nfunction clonePendingCall(record: PendingCostCall): PendingCostCall {\n const { tags, ...rest } = record\n return { ...rest, ...(tags ? { tags: { ...tags } } : {}) }\n}\n\nfunction cloneReceipt(receipt: CostReceipt): CostReceipt {\n const { pricing, tags, ...rest } = receipt\n return {\n ...rest,\n ...(tags ? { tags: { ...tags } } : {}),\n ...(pricing ? { pricing: { ...pricing } } : {}),\n }\n}\n\nfunction costFromPricing(usage: CostUsage, pricing: NonNullable<CostReceipt['pricing']>): number {\n const cachedInputRate = pricing.cachedInputUsdPerThousand ?? pricing.inputUsdPerThousand\n const cacheWriteRate = pricing.cacheWriteUsdPerThousand ?? pricing.inputUsdPerThousand\n return (\n (usage.inputTokens / 1000) * pricing.inputUsdPerThousand +\n ((usage.cachedTokens ?? 0) / 1000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1000) * cacheWriteRate +\n (usage.outputTokens / 1000) * pricing.outputUsdPerThousand\n )\n}\n\nfunction pricingSnapshot(pricing: CustomTokenPricing): NonNullable<CostReceipt['pricing']> {\n costForTokenPricing(pricing, { inputTokens: 0, outputTokens: 0 })\n return {\n inputUsdPerThousand: pricing.inputUsdPerMillion / 1000,\n ...(pricing.cachedInputUsdPerMillion === undefined\n ? {}\n : { cachedInputUsdPerThousand: pricing.cachedInputUsdPerMillion / 1000 }),\n ...(pricing.cacheWriteUsdPerMillion === undefined\n ? {}\n : { cacheWriteUsdPerThousand: pricing.cacheWriteUsdPerMillion / 1000 }),\n outputUsdPerThousand: pricing.outputUsdPerMillion / 1000,\n }\n}\n\nfunction emptyRollup(channel: CostChannel): ChannelRollup {\n return {\n channel,\n calls: 0,\n inputTokens: 0,\n outputTokens: 0,\n reasoningTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n costUsd: 0,\n unpricedCalls: 0,\n unknownUsageCalls: 0,\n }\n}\n\nfunction pendingModel(input: RunPaidCallInput<unknown>): string {\n if (input.model) return input.model\n if (input.maximumCharge && 'model' in input.maximumCharge) return input.maximumCharge.model\n return 'unknown'\n}\n\nfunction unknownReceipt(model: string): CostReceiptInput {\n return { model, inputTokens: 0, outputTokens: 0, costUnknown: true, usageUnknown: true }\n}\n\nfunction resolveCallId(input: string | undefined): string {\n if (input !== undefined) {\n assertString(input, 'callId')\n return input\n }\n if (typeof globalThis.crypto?.randomUUID !== 'function') {\n throw new ValidationError('CostLedger: crypto.randomUUID is required when callId is omitted')\n }\n return globalThis.crypto.randomUUID()\n}\n\nfunction abortError(signal: AbortSignal): Error {\n const reason = (signal as { reason?: unknown }).reason\n if (reason instanceof Error) return reason\n const error = new Error('CostLedger: paid call aborted')\n error.name = 'AbortError'\n return error\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\nfunction paidFailure<T>(callId: string, error: Error, receipt?: CostReceipt): PaidCallResult<T> {\n return {\n succeeded: false,\n callId,\n error,\n ...(receipt ? { receipt: cloneReceipt(receipt) } : {}),\n }\n}\n\nfunction validationMessage(cause: unknown): string {\n return cause instanceof z.ZodError ? z.prettifyError(cause) : toError(cause).message\n}\n\nfunction assertUsage(usage: CostUsage): void {\n assertTokenCount(usage.inputTokens, 'inputTokens')\n assertTokenCount(usage.outputTokens, 'outputTokens')\n if (usage.reasoningTokens !== undefined) {\n assertTokenCount(usage.reasoningTokens, 'reasoningTokens')\n if (usage.reasoningTokens > usage.outputTokens) {\n throw new ValidationError('CostLedger: reasoningTokens must not exceed outputTokens')\n }\n }\n if (usage.cachedTokens !== undefined) assertTokenCount(usage.cachedTokens, 'cachedTokens')\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'cacheWriteTokens')\n }\n}\n\nfunction assertTokenCount(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative integer, got ${String(value)}`,\n )\n }\n}\n\nfunction assertNonNegative(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative finite number, got ${String(value)}`,\n )\n }\n}\n\nfunction assertTimeout(value: unknown, name: string): asserts value is number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value < 0 ||\n value > 2_147_483_647\n ) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative safe integer no greater than 2147483647, got ${String(value)}`,\n )\n }\n}\n\nfunction assertString(value: unknown, name: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`CostLedger: ${name} must be a non-empty string`)\n }\n}\n"],"mappings":";;;;AA+KA,IAAa,0BAAb,cAA6C,gBAAgB;CAC3D,YACE,YACA,cACA,cACA,OACA,OACA;EACA,MACE,yBAAyB,aAAa,QAAQ,MAAM,YAAY,MAAM,yBAAyB,WAAW,QAAQ,aAAa,mBACjI;CACF;AACF;AAEA,IAAa,gCAAb,cAAmD,gBAAgB,CAAC;AAEpE,IAAa,+BAAb,cAAkD,gBAAgB;CAChE,YAAY,OAAe,WAAm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KAAK,uCAAuC,OAAO,KAAK,GACzE;AAEJ;AAEA,SAAS,kBAAkB,OAAgB,MAAuC;CAChF,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAClE,MAAM,IAAI,gBACR,eAAe,KAAK,6CAA6C,OAAO,KAAK,GAC/E;AAEJ;AAEA,SAAS,cAAc,OAAgB,MAAuC;CAC5E,IACE,OAAO,UAAU,YACjB,CAAC,OAAO,cAAc,KAAK,KAC3B,QAAQ,KACR,QAAQ,YAER,MAAM,IAAI,gBACR,eAAe,KAAK,uEAAuE,OAAO,KAAK,GACzG;AAEJ;AAEA,SAAS,aAAa,OAAgB,MAAuC;CAC3E,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW,GACvD,MAAM,IAAI,gBAAgB,eAAe,KAAK,4BAA4B;AAE9E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dspy-rlm-engine-DTkVyDX-.js","names":["isRecord"],"sources":["../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { closeServer, listenLocal, sendJson } from '../campaign/external-optimizer-http'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\nconst MAX_REQUEST_BYTES = 1_000_000\nconst MAX_RESPONSE_BYTES = 4_000_000\n\nexport interface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > MAX_RESPONSE_BYTES) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction readJson(request: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_REQUEST_BYTES) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import {\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { resolveModelPricing } from '../metrics'\nimport type { TraceAnalysisEngine, TraceAnalysisEngineResult } from './engine'\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { startTraceToolCallback } from './trace-tool-callback'\n\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\nconst DEFAULT_MODEL_OUTPUT_TOKENS = 4_096\nconst DEFAULT_MAX_COST_USD = 1\nconst MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '1.0.0'\n\nexport interface DspyRlmTraceEngineOptions {\n baseUrl: string\n apiKey: string\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: 4096. */\n maxOutputTokens?: number\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_MODEL_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new TypeError('DSPy RLM timeoutMs must be a positive safe integer')\n }\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n\n const runner = sanitizedRunner(options.runner)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n base_url: options.baseUrl,\n model: options.model,\n api_key_provided: true,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n timeout_ms: timeoutMs,\n max_request_bytes: MAX_MODEL_REQUEST_BYTES,\n max_response_bytes: MAX_MODEL_RESPONSE_BYTES,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n upstreamBaseUrl: options.baseUrl,\n upstreamApiKey: options.apiKey,\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: request.limits.maxIterations + request.limits.maxLlmCalls + 1,\n maxRequestBytes: MAX_MODEL_REQUEST_BYTES,\n maxResponseBytes: MAX_MODEL_RESPONSE_BYTES,\n maxOutputTokensPerRequest: maxOutputTokens,\n requestTimeoutMs: timeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n },\n ...(runner ? { runner } : {}),\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n if (!Array.isArray(value.findings)) {\n throw new Error('DSPy RLM bridge findings must be an array')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. Rejected\n // rows are logged per row and counted in runtime.rejectedFindings.\n let rejectedFindings = 0\n const findings: RawAnalystFinding[] = []\n value.findings.forEach((finding, index) => {\n const parsed = RawAnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n rejectedFindings += 1\n onRejectedFinding(\n index,\n parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; '),\n )\n return\n }\n findings.push(parsed.data)\n })\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['baseUrl', options.baseUrl],\n ['apiKey', options.apiKey],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a non-empty string`)\n }\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";;;;;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;;AAU3B,eAAsB,uBAAuB,MAId;CAC7B,IAAI,CAAC,OAAO,cAAc,KAAK,QAAQ,KAAK,KAAK,YAAY,GAC3D,MAAM,IAAI,UAAU,8DAA8D;CAEpF,KAAK,QAAQ,eAAe;CAC5B,MAAM,SAAS,IAAI,IAAI,KAAK,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;CAClE,IAAI,OAAO,SAAS,KAAK,MAAM,QAC7B,MAAM,IAAI,MAAM,mDAAmD;CAGrE,MAAM,QAAQ,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC5C,IAAI,QAAQ;CACZ,IAAI,YAAY;CAChB,IAAI;CACJ,MAAM,oCAAoB,IAAI,IAAqB;CACnD,MAAM,iCAAiB,IAAI,IAAmB;CAC9C,MAAM,SAAS,cAAc,SAAS,aAAa;EACjD,IAAI,CAAC,WAAW;GACd,eAAe,UAAU,KAAK,EAAE,OAAO,iCAAiC,CAAC;GACzE;EACF;EACA,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,qBAA2B;GAC/B,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB;EACA,kBAAkB,IAAI,UAAU;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AC3C,MAAM,IAAI,UAAU,YAAY,KAAK,4BAA4B;AAGvE;AAEA,SAAS,gBAAgB,OAAmC;CAC1D,MAAM,UAAU,oBAAoB,KAAK;CACzC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,iCAAiC,MAAM,6CACzC;CAEF,OAAO;EACL,oBAAoB,QAAQ,QAAQ;EACpC,qBAAqB,QAAQ,SAAS;CACxC;AACF;AAEA,SAAS,gBACP,QAC4C;CAC5C,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EACL,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;EACpD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,MAAM,EAAE,KAAK,4BAA4B,OAAO,GAAG,EAAE,IAAI,CAAC;CACvE;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-B798zyGh.d.ts","names":[],"sources":["../src/supervisor-run/source-facts.ts","../src/supervisor-run/analyze.ts","../src/supervisor-run/claude-code-reader.ts","../src/supervisor-run/integrity-types.ts","../src/supervisor-run/integrity.ts","../src/supervisor-run/loops-reader.ts","../src/supervisor-run/render.ts","../src/supervisor-run/rollout-nodes.ts"],"mappings":";;;UAqBU;EACR;EACA;EACA;EACA;;EAEA;;UAGQ;EACR,QAAQ;EACR;;UAgFe;;EAEf;EACA;EACA;EACA;EACA,MAAM;EACN;;EAEA;EACA;;UAGe;EACf;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA,OAAO;;EAEP;;UAGe;;EAEf;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;EACA;;EAEA;;EAEA;EACA;EACA;EACA;EACA,eAAe;EACf,uBAAuB;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C7X3C,4BAA4B,GAAG;iBAgC/B,4BAA4B,GAAG;iBAwK/B,+BACd,QAAQ,qBACR;;;UCtLe;;WAEN;;WAEA,QAAQ;;WAER;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;WACA;WACA;WACA;WACA;;WAEA;;;;;;;iBAwBK,0BACd,KAAK,sBACL,OAAM,2BACL"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"integrity-CCXTftiL.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/source-facts.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 are malformed',\n detail: `${facts.journalInvalidRows} non-object or invalid JSON row(s) and ${malformedSpawns.length} malformed spawn row(s) were excluded from structural conclusions.`,\n evidence: [\n evidence('journal/malformed-json-rows/count', facts.journalInvalidRows),\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 or reject malformed journal rows before using the run for structural analysis.',\n metadata: {\n assessment: 'unavailable',\n malformed_json_rows: facts.journalInvalidRows,\n malformed_spawn_rows: malformedSpawns.length,\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","import type { SupervisorRunNodeRole, SupervisorRunSources } from './types'\n\n// ---------------------------------------------------------------------------\n// Journal shapes — structurally parsed. The journal is the contract, not the type.\n// ---------------------------------------------------------------------------\n\ninterface JournalEvent {\n kind?: unknown\n id?: unknown\n parent?: unknown\n label?: unknown\n role?: unknown\n status?: unknown\n verdict?: unknown\n reason?: unknown\n seq?: unknown\n at?: unknown\n spend?: unknown\n spent?: unknown\n}\n\ninterface Tokens {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n /** False when the event carried no cache counters at all — not \"zero cached\". */\n hasCache: boolean\n}\n\ninterface SpendLike {\n tokens: Tokens\n usd: number\n}\n\nexport function asRecord(v: unknown): Record<string, unknown> {\n return typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {}\n}\n\nfunction num(v: unknown): number {\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n}\n\nfunction readSpend(v: unknown): SpendLike {\n const rec = asRecord(v)\n const tok = asRecord(rec.tokens)\n const cacheRead = tok.cacheRead ?? tok.cache_read\n const cacheWrite = tok.cacheWrite ?? tok.cache_write\n return {\n tokens: {\n input: num(tok.input),\n output: num(tok.output),\n cacheRead: num(cacheRead),\n cacheWrite: num(cacheWrite),\n hasCache: cacheRead !== undefined || cacheWrite !== undefined,\n },\n usd: num(rec.usd),\n }\n}\n\nexport function parseJsonl(text: string | null): Record<string, unknown>[] {\n return parseJsonlWithDiagnostics(text).rows\n}\n\ninterface ParsedJsonl {\n readonly rows: Record<string, unknown>[]\n readonly invalidRows: number\n}\n\nfunction parseJsonlWithDiagnostics(text: string | null): ParsedJsonl {\n if (text === null) return { rows: [], invalidRows: 0 }\n const out: Record<string, unknown>[] = []\n let invalidRows = 0\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed: unknown = JSON.parse(trimmed)\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n out.push(parsed as Record<string, unknown>)\n } else {\n invalidRows += 1\n }\n } catch {\n invalidRows += 1\n }\n }\n return { rows: out, invalidRows }\n}\n\nexport function parseJson(text: string | null): Record<string, unknown> | null {\n if (text === null) return null\n try {\n const parsed: unknown = JSON.parse(text)\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\nfunction ms(at: unknown): number | null {\n if (typeof at !== 'string') return null\n const t = Date.parse(at)\n return Number.isFinite(t) ? t : null\n}\n\n// ---------------------------------------------------------------------------\n// The supervision tree, as parsed from the journal event stream.\n// ---------------------------------------------------------------------------\n\nexport interface SpawnRow {\n /** Zero-based row among parsed journal objects. */\n sourceRow: number\n id: string\n parent: string | null\n label: string\n role: SupervisorRunNodeRole\n at: number | null\n /** False when identity, parentage, label, or role was malformed. */\n valid: boolean\n invalidFields: readonly string[]\n}\n\nexport interface CloseRow {\n id: string\n kind: 'settled' | 'cancelled'\n status: string | null\n /** String verdict from legacy journals, or valid/invalid for a structured verdict. */\n verdict: string | null\n /** Structured verdict validity, when recorded. */\n valid: boolean | null\n /** Structured verdict score, preserved without boolean coercion. */\n score: number | null\n /** The verdict exactly as the journal carried it. */\n rawVerdict: unknown | null\n at: number | null\n spend: SpendLike\n /** False when the close event carried no spend object — not \"spent nothing\". */\n hasSpend: boolean\n}\n\nexport interface WorkerLogFacts {\n /** Position in `SupervisorRunSources.workers`, retained for exact evidence paths. */\n sourceIndex: number\n workerId: string | null\n label: string\n /** `false` means the artifact was missing; a captured empty artifact is `true`. */\n inboxCaptured: boolean\n eventsCaptured: boolean\n inboxInvalidRows: number\n eventsInvalidRows: number\n started: number | null\n /** True once a `finished` event was seen — independent of whether its `at` parsed. */\n finished: boolean\n finishedAt: number | null\n passed: boolean | null\n /** Numeric score exactly as the finished event recorded it. */\n score: number | null\n /** `patchBytes` as reported by the finished event (not the patch file's size). */\n finishedPatchBytes: number | null\n evidenceBytes: number\n /** Unique queued request ids, or null when exact accounting is unavailable. */\n steersQueued: number | null\n /** Unique matched request ids acknowledged as delivered, or null when unavailable. */\n steersDelivered: number | null\n steersQueuedUnavailable: string | null\n steersDeliveredUnavailable: string | null\n questions: number\n steerRequests: SteerRequestFact[]\n steerAcknowledgements: SteerAcknowledgementFact[]\n}\n\nexport interface SteerRequestFact {\n /** Durable inbox request id; null when the row did not retain one. */\n requestId: string | null\n row: number\n}\n\nexport interface SteerAcknowledgementFact {\n /** Worker event request id; null when the event cannot be correlated. */\n requestId: string | null\n /** `null` means the acknowledgement omitted delivery status. */\n delivered: boolean | null\n row: number\n}\n\n/**\n * The tree + timeline the report is computed from, exposed because the rollout-row\n * minter needs exactly the same parse (one parser, two consumers).\n */\nexport interface SupervisorTreeFacts {\n readonly rootId: string | null\n readonly spawns: readonly SpawnRow[]\n readonly closes: readonly CloseRow[]\n readonly workerSpawns: readonly SpawnRow[]\n readonly workerCloses: readonly CloseRow[]\n readonly brain: {\n tokensIn: number\n tokensOut: number\n cacheRead: number\n cacheWrite: number\n /** False when no metered event carried cache counters — not \"nothing cached\". */\n hasCache: boolean\n usd: number\n meteredCount: number\n }\n readonly workerLogs: ReadonlyMap<string, WorkerLogFacts>\n /** Every worker source row, including duplicate identities that a map cannot retain. */\n readonly workerLogRows: readonly WorkerLogFacts[]\n /** Non-empty journal lines that were not JSON objects. */\n readonly journalInvalidRows: number\n /** Parsed once with the journal and worker artifacts. */\n readonly state: Record<string, unknown> | null\n readonly startedAt: number | null\n readonly completedAt: number | null\n}\n\ninterface VerdictFacts {\n label: string | null\n valid: boolean | null\n score: number | null\n raw: unknown | null\n}\n\nfunction readVerdict(v: unknown): VerdictFacts {\n if (typeof v === 'string') return { label: v, valid: null, score: null, raw: v }\n if (typeof v !== 'object' || v === null) {\n return { label: null, valid: null, score: null, raw: null }\n }\n const rec = v as Record<string, unknown>\n const valid = typeof rec.valid === 'boolean' ? rec.valid : null\n return {\n label: valid === null ? null : valid ? 'valid' : 'invalid',\n valid,\n score: typeof rec.score === 'number' && Number.isFinite(rec.score) ? rec.score : null,\n raw: v,\n }\n}\n\nexport function workerSourceKey(\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n): string {\n return worker.workerId ?? worker.label\n}\n\nexport function parseSupervisorTree(src: SupervisorRunSources): SupervisorTreeFacts {\n const parsedJournal = parseJsonlWithDiagnostics(src.journal)\n const events = parsedJournal.rows\n const state = parseJson(src.state)\n\n const spawns: SpawnRow[] = []\n const closes: CloseRow[] = []\n let brainIn = 0\n let brainOut = 0\n let brainCacheRead = 0\n let brainCacheWrite = 0\n let brainHasCache = false\n let brainUsd = 0\n let meteredCount = 0\n let rootId: string | null = null\n for (const [sourceRow, ev] of (events as JournalEvent[]).entries()) {\n const kind = typeof ev.kind === 'string' ? ev.kind : ''\n const id = typeof ev.id === 'string' ? ev.id : ''\n if (kind === 'spawned') {\n const parent = typeof ev.parent === 'string' && ev.parent.length > 0 ? ev.parent : null\n const label = typeof ev.label === 'string' ? ev.label : ''\n const invalidFields: string[] = []\n if (id.length === 0) invalidFields.push('id')\n const parentOmittedForFirstRoot = ev.parent === undefined && rootId === null\n if (\n ev.parent !== null &&\n !parentOmittedForFirstRoot &&\n !(typeof ev.parent === 'string' && ev.parent.length > 0)\n ) {\n invalidFields.push('parent')\n }\n if (label.length === 0) invalidFields.push('label')\n if (ev.role !== undefined && ev.role !== 'supervisor' && ev.role !== 'worker') {\n invalidFields.push('role')\n }\n const role: SupervisorRunNodeRole =\n ev.role === 'supervisor' || ev.role === 'worker'\n ? ev.role\n : parent === null\n ? 'supervisor'\n : 'worker'\n const valid = invalidFields.length === 0\n if (valid && parent === null && rootId === null) rootId = id\n spawns.push({\n sourceRow,\n id,\n parent,\n label,\n role,\n at: ms(ev.at),\n valid,\n invalidFields,\n })\n } else if (kind === 'settled') {\n const verdict = readVerdict(ev.verdict)\n closes.push({\n id,\n kind: 'settled',\n status: typeof ev.status === 'string' ? ev.status : null,\n verdict: verdict.label,\n valid: verdict.valid,\n score: verdict.score,\n rawVerdict: verdict.raw,\n at: ms(ev.at),\n spend: readSpend(ev.spent),\n hasSpend: asRecord(ev.spent).tokens !== undefined,\n })\n } else if (kind === 'cancelled') {\n closes.push({\n id,\n kind: 'cancelled',\n status: 'cancelled',\n verdict: typeof ev.reason === 'string' ? ev.reason : null,\n valid: null,\n score: null,\n rawVerdict: typeof ev.reason === 'string' ? ev.reason : null,\n at: ms(ev.at),\n spend: {\n tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, hasCache: false },\n usd: 0,\n },\n hasSpend: false,\n })\n } else if (kind === 'metered') {\n const s = readSpend(ev.spend)\n brainIn += s.tokens.input\n brainOut += s.tokens.output\n brainCacheRead += s.tokens.cacheRead\n brainCacheWrite += s.tokens.cacheWrite\n brainHasCache = brainHasCache || s.tokens.hasCache\n brainUsd += s.usd\n meteredCount += 1\n }\n }\n\n const workerSpawns = spawns.filter((s) => s.valid && s.id !== rootId)\n const workerIds = new Set(workerSpawns.map((s) => s.id))\n const workerCloses = closes.filter((c) => workerIds.has(c.id))\n\n const workerLogs = new Map<string, WorkerLogFacts>()\n const workerLogRows: WorkerLogFacts[] = []\n for (const [sourceIndex, w] of (src.workers ?? []).entries()) {\n const facts: WorkerLogFacts = {\n sourceIndex,\n workerId: w.workerId ?? null,\n label: w.label,\n inboxCaptured: w.inbox !== null,\n eventsCaptured: w.events !== null,\n inboxInvalidRows: 0,\n eventsInvalidRows: 0,\n started: null,\n finished: false,\n finishedAt: null,\n passed: null,\n score: null,\n finishedPatchBytes: null,\n evidenceBytes: 0,\n steersQueued: null,\n steersDelivered: null,\n steersQueuedUnavailable: null,\n steersDeliveredUnavailable: null,\n questions: 0,\n steerRequests: [],\n steerAcknowledgements: [],\n }\n const parsedInbox = parseJsonlWithDiagnostics(w.inbox)\n const parsedEvents = parseJsonlWithDiagnostics(w.events)\n facts.inboxInvalidRows = parsedInbox.invalidRows\n facts.eventsInvalidRows = parsedEvents.invalidRows\n for (const [row, req] of parsedInbox.rows.entries()) {\n if (typeof req.message !== 'string' || req.message.trim().length === 0) continue\n facts.steerRequests.push({\n requestId: typeof req.id === 'string' && req.id.length > 0 ? req.id : null,\n row,\n })\n }\n for (const [row, ev] of parsedEvents.rows.entries()) {\n const kind = ev.kind\n if (kind === 'message') {\n if (ev.direction === 'up') {\n facts.questions += 1\n continue\n }\n facts.steerAcknowledgements.push({\n requestId:\n typeof ev.requestId === 'string' && ev.requestId.length > 0 ? ev.requestId : null,\n delivered: typeof ev.delivered === 'boolean' ? ev.delivered : null,\n row,\n })\n } else if (kind === 'started') {\n facts.started = ms(ev.at)\n } else if (kind === 'finished') {\n facts.finished = true\n facts.finishedAt = ms(ev.at)\n facts.passed = typeof ev.passed === 'boolean' ? ev.passed : null\n facts.score = typeof ev.score === 'number' && Number.isFinite(ev.score) ? ev.score : null\n facts.finishedPatchBytes = typeof ev.patchBytes === 'number' ? ev.patchBytes : null\n facts.evidenceBytes = typeof ev.evidence === 'string' ? ev.evidence.length : 0\n }\n }\n const requestsById = new Map<string, number>()\n for (const request of facts.steerRequests) {\n if (request.requestId === null) continue\n requestsById.set(request.requestId, (requestsById.get(request.requestId) ?? 0) + 1)\n }\n const acknowledgementsById = new Map<string, SteerAcknowledgementFact[]>()\n for (const acknowledgement of facts.steerAcknowledgements) {\n if (acknowledgement.requestId === null) continue\n const matches = acknowledgementsById.get(acknowledgement.requestId) ?? []\n matches.push(acknowledgement)\n acknowledgementsById.set(acknowledgement.requestId, matches)\n }\n const queueProblems: string[] = []\n if (!facts.inboxCaptured) queueProblems.push('inbox absent')\n if (!facts.eventsCaptured) queueProblems.push('events absent')\n if (facts.inboxInvalidRows > 0) queueProblems.push('inbox contains malformed rows')\n if (facts.eventsInvalidRows > 0) queueProblems.push('events contain malformed rows')\n if (facts.steerRequests.some((request) => request.requestId === null)) {\n queueProblems.push('queued request id missing')\n }\n if ([...requestsById.values()].some((count) => count > 1)) {\n queueProblems.push('queued request id duplicated')\n }\n if (facts.steerAcknowledgements.some((acknowledgement) => acknowledgement.requestId === null)) {\n queueProblems.push('acknowledgement request id missing')\n }\n if ([...acknowledgementsById.keys()].some((id) => !requestsById.has(id))) {\n queueProblems.push('acknowledgement has no queued request')\n }\n if (queueProblems.length === 0) {\n facts.steersQueued = requestsById.size\n } else {\n facts.steersQueuedUnavailable = [...new Set(queueProblems)].join('; ')\n }\n\n const deliveryProblems = [...queueProblems]\n if ([...acknowledgementsById.values()].some((rows) => rows.length > 1)) {\n deliveryProblems.push('acknowledgement request id duplicated')\n }\n if (facts.steerAcknowledgements.some((acknowledgement) => acknowledgement.delivered === null)) {\n deliveryProblems.push('acknowledgement delivery status missing')\n }\n if (deliveryProblems.length === 0) {\n facts.steersDelivered = [...requestsById.keys()].filter((id) => {\n const acknowledgement = acknowledgementsById.get(id)\n return acknowledgement?.length === 1 && acknowledgement[0]?.delivered === true\n }).length\n } else {\n facts.steersDeliveredUnavailable = [...new Set(deliveryProblems)].join('; ')\n }\n workerLogRows.push(facts)\n workerLogs.set(workerSourceKey(w), facts)\n }\n\n const startedAt = ms(state?.startedAt) ?? spawns[0]?.at ?? null\n const completedAt =\n ms(state?.completedAt) ??\n [...spawns.map((s) => s.at), ...closes.map((c) => c.at)].reduce<number | null>(\n (acc, t) => (t === null ? acc : acc === null ? t : Math.max(acc, t)),\n null,\n )\n\n return {\n rootId,\n spawns,\n closes,\n workerSpawns,\n workerCloses,\n brain: {\n tokensIn: brainIn,\n tokensOut: brainOut,\n cacheRead: brainCacheRead,\n cacheWrite: brainCacheWrite,\n hasCache: brainHasCache,\n usd: brainUsd,\n meteredCount,\n },\n workerLogs,\n workerLogRows,\n journalInvalidRows: parsedJournal.invalidRows,\n state,\n startedAt,\n completedAt,\n }\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 type {\n SupervisorRunSources,\n SupervisorRunTree,\n SupervisorRunTreeGap,\n 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 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} malformed journal row(s) were 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\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 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: typeof state?.status === 'string' ? state.status : null,\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 },\n is_completed: state?.status === 'completed',\n is_truncated: false,\n error: 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 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 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 },\n is_completed: close?.kind === 'settled',\n is_truncated: close?.kind === 'cancelled',\n error: close?.kind === 'cancelled' ? (close.verdict ?? 'cancelled') : 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,kBAC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