@snappedly-tools/shipyard 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +24 -14
  2. package/dist/MountConfig-K5ILnfht.d.ts +26 -0
  3. package/dist/{MountConfig-BHnKnA4h.d.ts → SandboxProvider-oUAwYlWm.d.ts} +1 -26
  4. package/dist/{chunk-L6PX5QTU.js → chunk-57EEKW3R.js} +57 -55
  5. package/dist/chunk-57EEKW3R.js.map +1 -0
  6. package/dist/{chunk-JI3HDDMS.js → chunk-HXSZM52J.js} +3 -3
  7. package/dist/{chunk-JI3HDDMS.js.map → chunk-HXSZM52J.js.map} +1 -1
  8. package/dist/{chunk-44I2BL6E.js → chunk-JZUBT4WG.js} +20 -4
  9. package/dist/chunk-JZUBT4WG.js.map +1 -0
  10. package/dist/chunk-NQRFVKCU.js +1840 -0
  11. package/dist/chunk-NQRFVKCU.js.map +1 -0
  12. package/dist/chunk-Z5C4LHVP.js +137 -0
  13. package/dist/chunk-Z5C4LHVP.js.map +1 -0
  14. package/dist/createSandbox-DmbnWAZv.d.ts +739 -0
  15. package/dist/index.d.ts +7 -2534
  16. package/dist/index.js +216 -7269
  17. package/dist/index.js.map +1 -1
  18. package/dist/integrations/github.d.ts +52 -0
  19. package/dist/integrations/github.js +1049 -0
  20. package/dist/integrations/github.js.map +1 -0
  21. package/dist/integrations/releases.d.ts +136 -0
  22. package/dist/integrations/releases.js +500 -0
  23. package/dist/integrations/releases.js.map +1 -0
  24. package/dist/main.js +641 -383
  25. package/dist/main.js.map +1 -1
  26. package/dist/publication-BPoy_M9M.d.ts +1200 -0
  27. package/dist/sandboxes/docker.d.ts +2 -1
  28. package/dist/sandboxes/docker.js +2 -2
  29. package/dist/templates/parallel-planner/main.mts +11 -7
  30. package/dist/templates/parallel-planner/setup.sh +1 -0
  31. package/dist/templates/parallel-planner-with-review/main.mts +11 -7
  32. package/dist/templates/parallel-planner-with-review/setup.sh +1 -0
  33. package/dist/templates/sequential-reviewer/main.mts +7 -3
  34. package/dist/templates/sequential-reviewer/setup.sh +1 -0
  35. package/dist/templates/shared/setup.sh +1 -0
  36. package/dist/templates/simple-loop/main.mts +7 -3
  37. package/dist/templates/simple-loop/setup.sh +1 -0
  38. package/dist/workflow/coordinator/migrations/002_workflow_phase_records.sql +11 -0
  39. package/dist/workflow/coordinator/migrations/003_phase_record_schema_version.sql +6 -0
  40. package/dist/workflow.d.ts +472 -0
  41. package/dist/workflow.js +4345 -0
  42. package/dist/workflow.js.map +1 -0
  43. package/package.json +13 -1
  44. package/dist/chunk-44I2BL6E.js.map +0 -1
  45. package/dist/chunk-L6PX5QTU.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/workflow/shared.ts","../src/workflow/contracts/index.ts","../src/workflow/handoff/index.ts","../src/workflow/phase-storage.ts","../src/workflow/triage/persistence.ts","../src/workflow/triage/reconciliation.ts","../src/workflow/triage/index.ts"],"names":["allRequiredChecksPassed","stringArray","sha256","createHash","sourceFingerprint","sourceKey","existing","timestamp","record"],"mappings":";;;;;AAOO,IAAM,gBAAA,GAAmB,CAC9B,IAAA,EACA,KAAA,KAEA,KAAK,UAAA,KAAe,KAAA,CAAM,UAAA,IAC1B,IAAA,CAAK,MAAA,KAAW,KAAA,CAAM,MAAA,IACtB,IAAA,CAAK,SAAS,KAAA,CAAM;AAEf,IAAM,YAAA,GAAe,CAC1B,IAAA,EACA,KAAA,KACY,IAAA,CAAK,WAAW,KAAA,CAAM,MAAA,IAAU,IAAA,CAAK,GAAA,KAAQ,KAAA,CAAM;AAE1D,IAAM,iBAAA,GAAoB,CAAC,OAAA,KAChC,OAAA,CAAQ,QAAA,KAAa,WACpB,OAAA,CAAQ,WAAA,KAAgB,MAAA,IAAU,OAAA,CAAQ,WAAA,KAAgB,UAAA;AAEtD,IAAM,kBAAA,GAAqB,CAChC,MAAA,KAEA,MAAA,CAAO,OAAO,MAAA,CAAO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,EAAQ,QAAA,EAAU,QAAQ,CAAA,EAAG;AAC1D,MAAA,OAAO,gBAAA,CAAiB,QAAQ,MAAM,CAAA;AAAA,IACxC;AAAA,EACF;AACA,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAAA,kBAAA,EAAqB,OAAO,UAAU,CAAA,MAAA,EAAS,OAAO,MAAM,CAAA,gBAAA,EAAmB,oCAAoC,CAAC,CAAA,oBAAA;AAAA,GACtH;AACF","file":"chunk-NQRFVKCU.js","sourcesContent":["import type {\n Finding,\n RepositoryPolicy,\n RevisionReference,\n WorkIdentity,\n} from \"./contracts/index.js\";\n\nexport const sameWorkIdentity = (\n left: WorkIdentity,\n right: WorkIdentity,\n): boolean =>\n left.repository === right.repository &&\n left.itemId === right.itemId &&\n left.kind === right.kind;\n\nexport const sameRevision = (\n left: RevisionReference,\n right: RevisionReference,\n): boolean => left.branch === right.branch && left.sha === right.sha;\n\nexport const isBlockingFinding = (finding: Finding): boolean =>\n finding.severity !== \"info\" &&\n (finding.disposition === \"open\" || finding.disposition === \"deferred\");\n\nexport const requiredCheckNames = (\n policy: RepositoryPolicy,\n): readonly string[] =>\n policy.checks.filter((check) => check.required).map((check) => check.name);\n\nexport const deepFreeze = <T>(value: T): T => {\n if (typeof value !== \"object\" || value === null) return value;\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreeze(child);\n }\n return Object.freeze(value);\n};\n","import { createHash } from \"node:crypto\";\nimport { isBlockingFinding } from \"../shared.js\";\n\nexport const WORKFLOW_CONTRACT_VERSION = 1 as const;\n\nexport type WorkItemKind = \"planning-spec\" | \"executable-issue\" | \"pr-repair\";\n\nexport type RiskLevel = \"low\" | \"medium\" | \"high\" | \"critical\";\n\nexport type WorkRisk = RiskLevel | \"unknown\";\n\nexport type WorkScope = \"small\" | \"substantial\" | \"unknown\";\n\nexport type WorkflowPhase =\n | \"triage\"\n | \"implementation\"\n | \"checking\"\n | \"review\"\n | \"repair\"\n | \"handoff\"\n | \"merge\"\n | \"release-verification\";\n\nexport type LifecycleState =\n | \"queued\"\n | \"waiting-info\"\n | \"authorized\"\n | \"implementing\"\n | \"checking\"\n | \"reviewing\"\n | \"repairing\"\n | \"human-review\"\n | \"merged\"\n | \"release-verifying\"\n | \"completed\"\n | \"failed\"\n | \"blocked\"\n | \"cancelled\";\n\nexport type PhaseOutcome =\n | \"completed\"\n | \"needs-info\"\n | \"blocked\"\n | \"failed\"\n | \"cancelled\";\n\nexport type CheckStatus =\n | \"passed\"\n | \"failed\"\n | \"incomplete\"\n | \"blocked\"\n | \"unknown\";\n\nexport type FindingSeverity = \"info\" | \"low\" | \"medium\" | \"high\" | \"critical\";\n\nexport type ReviewAxis = \"standards\" | \"spec\" | \"interface\";\n\nexport type FindingDisposition =\n | \"open\"\n | \"fixed\"\n | \"rejected\"\n | \"accepted\"\n | \"deferred\";\n\nexport interface WorkIdentity {\n readonly repository: string;\n readonly itemId: string;\n readonly kind: WorkItemKind;\n}\n\nexport interface SourceReference {\n readonly provider: \"github\" | \"slack\" | \"manual\";\n readonly repository: string;\n readonly itemId: string;\n readonly url?: string;\n /** Original content is retained durably but must not be echoed to an unauthorized destination. */\n readonly originalBody: string;\n readonly author?: string;\n}\n\nexport interface RevisionReference {\n readonly branch: string;\n readonly sha: string;\n}\n\nexport interface Authorization {\n readonly status: \"pending\" | \"approved\" | \"withdrawn\";\n readonly actor?: string;\n readonly actorRole?: \"maintainer\" | \"owner\" | \"policy\";\n readonly approvedAt?: string;\n}\n\nexport interface VerificationPlan {\n readonly checks: readonly string[];\n readonly artifacts: readonly string[];\n}\n\nexport interface WorkBrief {\n readonly contractVersion: typeof WORKFLOW_CONTRACT_VERSION;\n readonly id: string;\n readonly revision: number;\n readonly hash: string;\n readonly identity: WorkIdentity;\n readonly source: SourceReference;\n readonly problem: string;\n readonly evidence: readonly string[];\n readonly acceptanceCriteria: readonly string[];\n readonly exclusions: readonly string[];\n readonly risk: WorkRisk;\n readonly scope?: WorkScope;\n readonly verification: VerificationPlan;\n readonly unresolvedQuestions: readonly string[];\n readonly authorization: Authorization;\n readonly base: RevisionReference;\n readonly policyRevision: string;\n readonly skillRevision: string;\n readonly createdAt: string;\n}\n\nexport interface CheckCommand {\n readonly name: string;\n readonly command: string;\n readonly required: boolean;\n}\n\nexport interface PhaseBudget {\n readonly maxAttempts: number;\n readonly timeoutSeconds: number;\n}\n\nexport type AgentRole = \"routine\" | \"strong\";\n\nexport interface AgentModelRoles {\n readonly routine: string;\n readonly strong: string;\n}\n\nexport type WorkerPolicy = {\n readonly provider: string;\n readonly sandbox: string;\n readonly skillRevision: string;\n} & (\n | { readonly model: string; readonly models?: never }\n | { readonly model?: never; readonly models: AgentModelRoles }\n);\n\nexport interface AgentSelection {\n readonly provider: string;\n readonly model: string;\n readonly role: AgentRole;\n}\n\nexport interface RepositoryPolicy {\n readonly contractVersion: typeof WORKFLOW_CONTRACT_VERSION;\n readonly repository: string;\n readonly revision: string;\n readonly baseBranch: string;\n readonly issueClosure:\n | \"merge-and-ci\"\n | \"staging-verification\"\n | \"production-verification\";\n readonly authorization: {\n readonly required: boolean;\n readonly allowedActors: readonly (\"maintainer\" | \"owner\" | \"policy\")[];\n readonly autoStartRisk: readonly RiskLevel[];\n };\n readonly worker: WorkerPolicy;\n readonly checks: readonly CheckCommand[];\n readonly phaseBudgets: Readonly<Record<WorkflowPhase, PhaseBudget>>;\n readonly repairBudget: {\n readonly maxBatches: number;\n readonly maxFollowUps: number;\n };\n}\n\n/** Whether a brief carries an authorization accepted by this repository policy. */\nexport const isAuthorizationAllowed = (\n brief: Pick<WorkBrief, \"authorization\">,\n policy: Pick<RepositoryPolicy, \"authorization\">,\n): boolean =>\n brief.authorization.status === \"approved\" &&\n brief.authorization.actor !== undefined &&\n brief.authorization.actor.trim().length > 0 &&\n brief.authorization.approvedAt !== undefined &&\n brief.authorization.approvedAt.trim().length > 0 &&\n brief.authorization.actorRole !== undefined &&\n policy.authorization.allowedActors.includes(brief.authorization.actorRole);\n\nexport interface CheckEvidence {\n readonly name: string;\n readonly command: string;\n readonly status: CheckStatus;\n readonly summary: string;\n /** Candidate identity for checks that are used as a lifecycle gate. */\n readonly baseSha?: string;\n readonly headSha?: string;\n readonly briefHash?: string;\n readonly startedAt?: string;\n readonly completedAt?: string;\n readonly exitCode?: number;\n readonly artifactRefs?: readonly string[];\n}\n\nexport interface Finding {\n readonly id: string;\n readonly severity: FindingSeverity;\n readonly axis: ReviewAxis;\n readonly disposition: FindingDisposition;\n readonly title: string;\n readonly evidence: string;\n readonly location?: string;\n readonly requirement?: string;\n readonly verification?: string;\n}\n\nexport interface ReviewEvidence {\n readonly outcome:\n | \"passed\"\n | \"actionable-findings\"\n | \"incomplete\"\n | \"blocked\"\n | \"failed\";\n readonly axes: readonly ReviewAxis[];\n readonly findings: readonly Finding[];\n readonly headSha: string;\n readonly baseSha?: string;\n readonly briefHash: string;\n}\n\nexport interface PhaseResult {\n readonly contractVersion: typeof WORKFLOW_CONTRACT_VERSION;\n readonly assignmentId: string;\n readonly phase: WorkflowPhase;\n readonly outcome: PhaseOutcome;\n readonly identity: WorkIdentity;\n /** Brief revision executed by this phase. */\n readonly briefHash: string;\n readonly base?: RevisionReference;\n readonly head?: RevisionReference;\n readonly summary: string;\n readonly evidence: readonly string[];\n readonly checks: readonly CheckEvidence[];\n readonly commits: readonly string[];\n readonly artifacts: readonly string[];\n readonly questions: readonly string[];\n readonly findings: readonly Finding[];\n /** Review axes explicitly completed, including axes with no findings. */\n readonly reviewAxes?: readonly ReviewAxis[];\n readonly completedAt: string;\n}\n\nexport interface Assignment {\n readonly contractVersion: typeof WORKFLOW_CONTRACT_VERSION;\n readonly id: string;\n readonly phase: WorkflowPhase;\n readonly attempt: number;\n readonly identity: WorkIdentity;\n readonly briefId: string;\n readonly briefRevision: number;\n readonly briefHash: string;\n readonly policyRevision: string;\n readonly skillRevision: string;\n /** Missing only on assignments persisted before role model selection shipped. */\n readonly agentSelection?: AgentSelection;\n readonly base: RevisionReference;\n readonly head?: RevisionReference;\n readonly createdAt: string;\n}\n\nexport interface TransitionContext {\n readonly kind: WorkItemKind;\n readonly authorization: Authorization[\"status\"];\n readonly checks?: readonly CheckEvidence[];\n /** Required check names from the repository policy. */\n readonly requiredCheckNames?: readonly string[];\n /** Exact candidate identity required for lifecycle-gating check evidence. */\n readonly checkCandidate?: {\n readonly baseSha: string;\n readonly headSha: string;\n readonly briefHash: string;\n };\n readonly review?: ReviewEvidence;\n readonly currentHeadSha?: string;\n readonly assignedHeadSha?: string;\n}\n\nexport class ContractValidationError extends Error {\n readonly issues: readonly string[];\n\n constructor(message: string, issues: readonly string[] = []) {\n super(message);\n this.name = \"ContractValidationError\";\n this.issues = issues.length > 0 ? issues : [message];\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst nonEmptyString = (value: unknown, path: string): string => {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new ContractValidationError(`${path} must be a non-empty string`);\n }\n return value;\n};\n\nconst optionalString = (value: unknown, path: string): string | undefined => {\n if (value === undefined) return undefined;\n return nonEmptyString(value, path);\n};\n\nconst enumValue = <T extends string>(\n value: unknown,\n values: readonly T[],\n path: string,\n): T => {\n if (typeof value !== \"string\" || !values.includes(value as T)) {\n throw new ContractValidationError(\n `${path} must be one of: ${values.join(\", \")}`,\n );\n }\n return value as T;\n};\n\nconst stringArray = (value: unknown, path: string): string[] => {\n if (!Array.isArray(value)) {\n throw new ContractValidationError(`${path} must be an array`);\n }\n return value.map((entry, index) =>\n nonEmptyString(entry, `${path}[${index}]`),\n );\n};\n\nconst enumArray = <T extends string>(\n value: unknown,\n values: readonly T[],\n path: string,\n): T[] =>\n stringArray(value, path).map((entry, index) =>\n enumValue(entry, values, `${path}[${index}]`),\n );\n\nconst positiveInteger = (value: unknown, path: string): number => {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n throw new ContractValidationError(`${path} must be a positive integer`);\n }\n return value;\n};\n\nconst nonNegativeInteger = (value: unknown, path: string): number => {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n throw new ContractValidationError(`${path} must be a non-negative integer`);\n }\n return value;\n};\n\nconst contractVersion = (value: unknown): typeof WORKFLOW_CONTRACT_VERSION => {\n if (value !== WORKFLOW_CONTRACT_VERSION) {\n throw new ContractValidationError(\n `Unsupported workflow contract version: ${String(value)}`,\n );\n }\n return WORKFLOW_CONTRACT_VERSION;\n};\n\nconst parseIdentity = (value: unknown, path = \"identity\"): WorkIdentity => {\n if (!isRecord(value)) {\n throw new ContractValidationError(`${path} must be an object`);\n }\n return {\n repository: nonEmptyString(value.repository, `${path}.repository`),\n itemId: nonEmptyString(value.itemId, `${path}.itemId`),\n kind: enumValue(\n value.kind,\n [\"planning-spec\", \"executable-issue\", \"pr-repair\"],\n `${path}.kind`,\n ),\n };\n};\n\nconst parseRevision = (value: unknown, path: string): RevisionReference => {\n if (!isRecord(value)) {\n throw new ContractValidationError(`${path} must be an object`);\n }\n return {\n branch: nonEmptyString(value.branch, `${path}.branch`),\n sha: nonEmptyString(value.sha, `${path}.sha`),\n };\n};\n\nconst parseAuthorization = (value: unknown): Authorization => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"authorization must be an object\");\n }\n const result: Authorization = {\n status: enumValue(\n value.status,\n [\"pending\", \"approved\", \"withdrawn\"],\n \"authorization.status\",\n ),\n actor: optionalString(value.actor, \"authorization.actor\"),\n actorRole:\n value.actorRole === undefined\n ? undefined\n : enumValue(\n value.actorRole,\n [\"maintainer\", \"owner\", \"policy\"] as const,\n \"authorization.actorRole\",\n ),\n approvedAt: optionalString(value.approvedAt, \"authorization.approvedAt\"),\n };\n if (result.status === \"approved\" && (!result.actor || !result.approvedAt)) {\n throw new ContractValidationError(\n \"approved authorization requires actor and approvedAt\",\n );\n }\n return result;\n};\n\nconst parseSource = (value: unknown): SourceReference => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"source must be an object\");\n }\n return {\n provider: enumValue(\n value.provider,\n [\"github\", \"slack\", \"manual\"],\n \"source.provider\",\n ),\n repository: nonEmptyString(value.repository, \"source.repository\"),\n itemId: nonEmptyString(value.itemId, \"source.itemId\"),\n url: optionalString(value.url, \"source.url\"),\n originalBody: nonEmptyString(value.originalBody, \"source.originalBody\"),\n author: optionalString(value.author, \"source.author\"),\n };\n};\n\nconst parseVerification = (value: unknown): VerificationPlan => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"verification must be an object\");\n }\n return {\n checks: stringArray(value.checks, \"verification.checks\"),\n artifacts: stringArray(value.artifacts, \"verification.artifacts\"),\n };\n};\n\nconst briefHashInput = (brief: Omit<WorkBrief, \"hash\">): string =>\n canonicalJson(brief);\n\nconst canonicalJson = (value: unknown): string => {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => canonicalJson(entry)).join(\",\")}]`;\n }\n if (isRecord(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n};\n\nconst sha256 = (value: string): string =>\n createHash(\"sha256\").update(value).digest(\"hex\");\n\nexport type CreateWorkBriefInput = Omit<\n WorkBrief,\n \"contractVersion\" | \"id\" | \"revision\" | \"hash\"\n> & {\n readonly id?: string;\n readonly revision?: number;\n /** Accepted for callers carrying a previously materialized brief; always recomputed. */\n readonly hash?: string;\n readonly contractVersion?: typeof WORKFLOW_CONTRACT_VERSION;\n};\n\nexport const createWorkBrief = (input: CreateWorkBriefInput): WorkBrief => {\n const withoutHash: Omit<WorkBrief, \"hash\"> = {\n contractVersion: WORKFLOW_CONTRACT_VERSION,\n id:\n input.id ??\n `${input.identity.repository}:${input.identity.kind}:${input.identity.itemId}`,\n revision: input.revision ?? 1,\n identity: parseIdentity(input.identity),\n source: parseSource(input.source),\n problem: nonEmptyString(input.problem, \"problem\"),\n evidence: stringArray(input.evidence, \"evidence\"),\n acceptanceCriteria: stringArray(\n input.acceptanceCriteria,\n \"acceptanceCriteria\",\n ),\n exclusions: stringArray(input.exclusions, \"exclusions\"),\n risk: enumValue(\n input.risk,\n [\"low\", \"medium\", \"high\", \"critical\", \"unknown\"],\n \"risk\",\n ),\n ...(input.scope === undefined\n ? {}\n : {\n scope: enumValue<WorkScope>(\n input.scope,\n [\"small\", \"substantial\", \"unknown\"],\n \"scope\",\n ),\n }),\n verification: parseVerification(input.verification),\n unresolvedQuestions: stringArray(\n input.unresolvedQuestions,\n \"unresolvedQuestions\",\n ),\n authorization: parseAuthorization(input.authorization),\n base: parseRevision(input.base, \"base\"),\n policyRevision: nonEmptyString(input.policyRevision, \"policyRevision\"),\n skillRevision: nonEmptyString(input.skillRevision, \"skillRevision\"),\n createdAt: nonEmptyString(input.createdAt, \"createdAt\"),\n };\n if (\n withoutHash.identity.repository !== withoutHash.source.repository ||\n withoutHash.identity.itemId !== withoutHash.source.itemId\n ) {\n throw new ContractValidationError(\n \"work brief source must identify the same repository and item as its identity\",\n );\n }\n const brief: WorkBrief = {\n ...withoutHash,\n hash: sha256(briefHashInput(withoutHash)),\n };\n return parseWorkBrief(brief);\n};\n\nexport const parseWorkBrief = (value: unknown): WorkBrief => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"work brief must be an object\");\n }\n const parsedWithoutHash: Omit<WorkBrief, \"hash\"> = {\n contractVersion: contractVersion(value.contractVersion),\n id: nonEmptyString(value.id, \"id\"),\n revision: positiveInteger(value.revision, \"revision\"),\n identity: parseIdentity(value.identity),\n source: parseSource(value.source),\n problem: nonEmptyString(value.problem, \"problem\"),\n evidence: stringArray(value.evidence, \"evidence\"),\n acceptanceCriteria: stringArray(\n value.acceptanceCriteria,\n \"acceptanceCriteria\",\n ),\n exclusions: stringArray(value.exclusions, \"exclusions\"),\n risk: enumValue(\n value.risk,\n [\"low\", \"medium\", \"high\", \"critical\", \"unknown\"],\n \"risk\",\n ),\n ...(value.scope === undefined\n ? {}\n : {\n scope: enumValue<WorkScope>(\n value.scope,\n [\"small\", \"substantial\", \"unknown\"],\n \"scope\",\n ),\n }),\n verification: parseVerification(value.verification),\n unresolvedQuestions: stringArray(\n value.unresolvedQuestions,\n \"unresolvedQuestions\",\n ),\n authorization: parseAuthorization(value.authorization),\n base: parseRevision(value.base, \"base\"),\n policyRevision: nonEmptyString(value.policyRevision, \"policyRevision\"),\n skillRevision: nonEmptyString(value.skillRevision, \"skillRevision\"),\n createdAt: nonEmptyString(value.createdAt, \"createdAt\"),\n };\n const hash = nonEmptyString(value.hash, \"hash\");\n if (\n parsedWithoutHash.identity.repository !==\n parsedWithoutHash.source.repository ||\n parsedWithoutHash.identity.itemId !== parsedWithoutHash.source.itemId\n ) {\n throw new ContractValidationError(\n \"work brief source must identify the same repository and item as its identity\",\n );\n }\n const expectedHash = sha256(briefHashInput(parsedWithoutHash));\n if (hash !== expectedHash) {\n throw new ContractValidationError(\"work brief hash does not match content\");\n }\n return { ...parsedWithoutHash, hash };\n};\n\nconst parsePhaseBudget = (value: unknown, path: string): PhaseBudget => {\n if (!isRecord(value)) {\n throw new ContractValidationError(`${path} must be an object`);\n }\n return {\n maxAttempts: positiveInteger(value.maxAttempts, `${path}.maxAttempts`),\n timeoutSeconds: positiveInteger(\n value.timeoutSeconds,\n `${path}.timeoutSeconds`,\n ),\n };\n};\n\nconst workflowPhases: readonly WorkflowPhase[] = [\n \"triage\",\n \"implementation\",\n \"checking\",\n \"review\",\n \"repair\",\n \"handoff\",\n \"merge\",\n \"release-verification\",\n];\n\nexport type CreateRepositoryPolicyInput = Omit<\n RepositoryPolicy,\n \"contractVersion\"\n>;\n\nexport const parseRepositoryPolicy = (value: unknown): RepositoryPolicy => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"repository policy must be an object\");\n }\n if (!isRecord(value.authorization)) {\n throw new ContractValidationError(\"policy.authorization must be an object\");\n }\n if (!isRecord(value.worker)) {\n throw new ContractValidationError(\"policy.worker must be an object\");\n }\n const workerModels =\n value.worker.models === undefined\n ? undefined\n : (() => {\n if (value.worker.model !== undefined) {\n throw new ContractValidationError(\n \"policy.worker.model cannot be combined with policy.worker.models\",\n );\n }\n if (!isRecord(value.worker.models)) {\n throw new ContractValidationError(\n \"policy.worker.models must be an object\",\n );\n }\n return {\n routine: nonEmptyString(\n value.worker.models.routine,\n \"policy.worker.models.routine\",\n ),\n strong: nonEmptyString(\n value.worker.models.strong,\n \"policy.worker.models.strong\",\n ),\n };\n })();\n if (!Array.isArray(value.checks)) {\n throw new ContractValidationError(\"policy.checks must be an array\");\n }\n const phaseBudgetRecord = value.phaseBudgets;\n if (!isRecord(phaseBudgetRecord)) {\n throw new ContractValidationError(\"policy.phaseBudgets must be an object\");\n }\n if (!isRecord(value.repairBudget)) {\n throw new ContractValidationError(\"policy.repairBudget must be an object\");\n }\n const phaseBudgets = Object.fromEntries(\n workflowPhases.map((phase) => {\n if (!(phase in phaseBudgetRecord)) {\n throw new ContractValidationError(\n `policy.phaseBudgets.${phase} is required`,\n );\n }\n return [\n phase,\n parsePhaseBudget(\n phaseBudgetRecord[phase],\n `policy.phaseBudgets.${phase}`,\n ),\n ];\n }),\n ) as Record<WorkflowPhase, PhaseBudget>;\n const checks = value.checks.map((check, index) => {\n if (!isRecord(check)) {\n throw new ContractValidationError(\n `policy.checks[${index}] must be an object`,\n );\n }\n return {\n name: nonEmptyString(check.name, `policy.checks[${index}].name`),\n command: nonEmptyString(check.command, `policy.checks[${index}].command`),\n required:\n typeof check.required === \"boolean\"\n ? check.required\n : (() => {\n throw new ContractValidationError(\n `policy.checks[${index}].required must be a boolean`,\n );\n })(),\n };\n });\n const allowedActors = stringArray(\n value.authorization.allowedActors,\n \"policy.authorization.allowedActors\",\n ).map((actor) =>\n enumValue(\n actor,\n [\"maintainer\", \"owner\", \"policy\"] as const,\n \"policy.authorization.allowedActors\",\n ),\n );\n const autoStartRisk = stringArray(\n value.authorization.autoStartRisk,\n \"policy.authorization.autoStartRisk\",\n ).map((risk) =>\n enumValue(\n risk,\n [\"low\", \"medium\", \"high\", \"critical\"] as const,\n \"policy.authorization.autoStartRisk\",\n ),\n );\n const required = value.authorization.required;\n if (typeof required !== \"boolean\") {\n throw new ContractValidationError(\n \"policy.authorization.required must be a boolean\",\n );\n }\n const maxBatches = positiveInteger(\n value.repairBudget.maxBatches,\n \"policy.repairBudget.maxBatches\",\n );\n const maxFollowUps = nonNegativeInteger(\n value.repairBudget.maxFollowUps,\n \"policy.repairBudget.maxFollowUps\",\n );\n return {\n contractVersion: contractVersion(value.contractVersion),\n repository: nonEmptyString(value.repository, \"policy.repository\"),\n revision: nonEmptyString(value.revision, \"policy.revision\"),\n baseBranch: nonEmptyString(value.baseBranch, \"policy.baseBranch\"),\n issueClosure: enumValue(\n value.issueClosure,\n [\n \"merge-and-ci\",\n \"staging-verification\",\n \"production-verification\",\n ] as const,\n \"policy.issueClosure\",\n ),\n authorization: { required, allowedActors, autoStartRisk },\n worker: {\n provider: nonEmptyString(value.worker.provider, \"policy.worker.provider\"),\n ...(workerModels === undefined\n ? { model: nonEmptyString(value.worker.model, \"policy.worker.model\") }\n : { models: workerModels }),\n sandbox: nonEmptyString(value.worker.sandbox, \"policy.worker.sandbox\"),\n skillRevision: nonEmptyString(\n value.worker.skillRevision,\n \"policy.worker.skillRevision\",\n ),\n },\n checks,\n phaseBudgets,\n repairBudget: { maxBatches, maxFollowUps },\n };\n};\n\nexport const createRepositoryPolicy = (\n input: CreateRepositoryPolicyInput,\n): RepositoryPolicy =>\n parseRepositoryPolicy({\n contractVersion: WORKFLOW_CONTRACT_VERSION,\n ...input,\n });\n\nexport const resolveAgentSelection = (\n policy: Pick<RepositoryPolicy, \"worker\">,\n phase: WorkflowPhase,\n risk?: WorkRisk,\n scope?: WorkScope,\n): AgentSelection => {\n const role: AgentRole =\n phase === \"review\" && !(risk === \"low\" && scope === \"small\")\n ? \"strong\"\n : \"routine\";\n const worker = policy.worker;\n const modelPath = worker.models\n ? `policy.worker.models.${role}`\n : \"policy.worker.model\";\n return Object.freeze({\n provider: nonEmptyString(worker.provider, \"policy.worker.provider\"),\n model: nonEmptyString(worker.models?.[role] ?? worker.model, modelPath),\n role,\n });\n};\n\nexport const parseCheckEvidence = (value: unknown): CheckEvidence => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"check evidence must be an object\");\n }\n const status = enumValue(\n value.status,\n [\"passed\", \"failed\", \"incomplete\", \"blocked\", \"unknown\"],\n \"check.status\",\n );\n const summary = nonEmptyString(value.summary, \"check.summary\");\n const exitCode =\n value.exitCode === undefined\n ? undefined\n : nonNegativeInteger(value.exitCode, \"check.exitCode\");\n return {\n name: nonEmptyString(value.name, \"check.name\"),\n command: nonEmptyString(value.command, \"check.command\"),\n status,\n summary,\n baseSha: optionalString(value.baseSha, \"check.baseSha\"),\n headSha: optionalString(value.headSha, \"check.headSha\"),\n briefHash: optionalString(value.briefHash, \"check.briefHash\"),\n startedAt: optionalString(value.startedAt, \"check.startedAt\"),\n completedAt: optionalString(value.completedAt, \"check.completedAt\"),\n exitCode,\n artifactRefs:\n value.artifactRefs === undefined\n ? undefined\n : stringArray(value.artifactRefs, \"check.artifactRefs\"),\n };\n};\n\nconst allowedTransitions: Readonly<\n Record<LifecycleState, readonly LifecycleState[]>\n> = {\n queued: [\"waiting-info\", \"authorized\", \"cancelled\", \"blocked\", \"failed\"],\n \"waiting-info\": [\"queued\", \"authorized\", \"cancelled\"],\n authorized: [\"implementing\", \"waiting-info\", \"cancelled\", \"blocked\"],\n implementing: [\"checking\", \"waiting-info\", \"blocked\", \"failed\", \"cancelled\"],\n checking: [\"reviewing\", \"repairing\", \"blocked\", \"failed\", \"cancelled\"],\n reviewing: [\"repairing\", \"human-review\", \"blocked\", \"failed\", \"cancelled\"],\n repairing: [\"checking\", \"reviewing\", \"blocked\", \"failed\", \"cancelled\"],\n \"human-review\": [\"merged\", \"repairing\", \"blocked\", \"cancelled\"],\n merged: [\"release-verifying\", \"completed\", \"failed\", \"blocked\"],\n \"release-verifying\": [\"completed\", \"failed\", \"blocked\"],\n completed: [],\n failed: [],\n blocked: [],\n cancelled: [],\n};\n\nconst allRequiredChecksPassed = (\n context: Pick<\n TransitionContext,\n \"checks\" | \"requiredCheckNames\" | \"checkCandidate\"\n >,\n): boolean => {\n const checks = context.checks;\n if (checks === undefined) return false;\n if (context.requiredCheckNames === undefined) {\n return (\n checks.length > 0 && checks.every((check) => check.status === \"passed\")\n );\n }\n if (\n context.requiredCheckNames.length > 0 &&\n context.checkCandidate === undefined\n ) {\n return false;\n }\n return context.requiredCheckNames.every((name) =>\n checks.some(\n (check) =>\n check.name === name &&\n check.status === \"passed\" &&\n (context.checkCandidate === undefined ||\n (check.baseSha === context.checkCandidate.baseSha &&\n check.headSha === context.checkCandidate.headSha &&\n check.briefHash === context.checkCandidate.briefHash)),\n ),\n );\n};\n\nexport const requireTransition = (\n from: LifecycleState,\n to: LifecycleState,\n context: TransitionContext,\n): void => {\n if (!allowedTransitions[from].includes(to)) {\n throw new ContractValidationError(\n `Transition from ${from} to ${to} is not allowed`,\n );\n }\n if (to === \"implementing\") {\n if (context.kind !== \"executable-issue\") {\n throw new ContractValidationError(\n \"Only an executable issue may enter implementation; planning spec and PR repair are separate flows\",\n );\n }\n if (context.authorization !== \"approved\") {\n throw new ContractValidationError(\n \"Implementation requires approved authorization\",\n );\n }\n }\n if (to === \"reviewing\" && !allRequiredChecksPassed(context)) {\n const unknown = context.checks?.find((check) => check.status === \"unknown\");\n throw new ContractValidationError(\n unknown\n ? `Cannot review while check ${unknown.name} is unknown`\n : \"Cannot review until all required checks pass\",\n );\n }\n if (to === \"human-review\") {\n if (!allRequiredChecksPassed(context)) {\n throw new ContractValidationError(\n \"Human review requires a complete set of passing checks\",\n );\n }\n if (\n context.review?.outcome !== \"passed\" ||\n context.review.axes.length === 0 ||\n context.review.findings.some(isBlockingFinding)\n ) {\n throw new ContractValidationError(\n \"Human review requires every review axis to pass and blocking findings to be disposed\",\n );\n }\n if (\n context.currentHeadSha !== undefined &&\n context.assignedHeadSha !== undefined &&\n context.currentHeadSha !== context.assignedHeadSha\n ) {\n throw new ContractValidationError(\n \"Human review evidence is stale for the current candidate head\",\n );\n }\n }\n};\n\nexport interface CreateAssignmentInput {\n readonly id: string;\n readonly phase: WorkflowPhase;\n readonly brief: WorkBrief;\n readonly policy: RepositoryPolicy;\n readonly attempt: number;\n readonly head?: RevisionReference;\n readonly createdAt: string;\n}\n\nexport const createAssignment = (input: CreateAssignmentInput): Assignment => {\n const brief = parseWorkBrief(input.brief);\n if (brief.identity.kind === \"planning-spec\") {\n throw new ContractValidationError(\n \"A planning spec cannot receive an execution assignment\",\n );\n }\n if (\n input.phase === \"implementation\" &&\n brief.identity.kind !== \"executable-issue\"\n ) {\n throw new ContractValidationError(\n \"PR repair work must use the repair phase; planning spec cannot be implemented\",\n );\n }\n if (\n input.phase === \"implementation\" &&\n !isAuthorizationAllowed(brief, input.policy)\n ) {\n throw new ContractValidationError(\n \"Implementation assignments require approved authorization\",\n );\n }\n if (input.policy.repository !== brief.identity.repository) {\n throw new ContractValidationError(\n \"Assignment policy repository does not match work identity\",\n );\n }\n if (\n [\"checking\", \"review\", \"handoff\", \"merge\"].includes(input.phase) &&\n input.head === undefined\n ) {\n throw new ContractValidationError(\n `${input.phase} assignments require an immutable candidate head`,\n );\n }\n const assignment: Assignment = {\n contractVersion: WORKFLOW_CONTRACT_VERSION,\n id: nonEmptyString(input.id, \"assignment.id\"),\n phase: input.phase,\n attempt: positiveInteger(input.attempt, \"assignment.attempt\"),\n identity: brief.identity,\n briefId: brief.id,\n briefRevision: brief.revision,\n briefHash: brief.hash,\n policyRevision: input.policy.revision,\n skillRevision: brief.skillRevision,\n agentSelection: resolveAgentSelection(\n input.policy,\n input.phase,\n brief.risk,\n brief.scope,\n ),\n base: brief.base,\n head: input.head,\n createdAt: nonEmptyString(input.createdAt, \"assignment.createdAt\"),\n };\n return Object.freeze(assignment);\n};\n\nexport const parsePhaseResult = (value: unknown): PhaseResult => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"phase result must be an object\");\n }\n contractVersion(value.contractVersion);\n const outcome = enumValue(\n value.outcome,\n [\"completed\", \"needs-info\", \"blocked\", \"failed\", \"cancelled\"],\n \"phase result.outcome\",\n );\n const evidence = stringArray(value.evidence, \"phase result.evidence\");\n const commits = stringArray(value.commits, \"phase result.commits\");\n if (\n outcome === \"completed\" &&\n evidence.length === 0 &&\n commits.length === 0\n ) {\n throw new ContractValidationError(\n \"A completed phase requires evidence; zero commits alone cannot mean success\",\n );\n }\n const checksValue = value.checks;\n if (!Array.isArray(checksValue)) {\n throw new ContractValidationError(\"phase result.checks must be an array\");\n }\n const checks = checksValue.map(parseCheckEvidence);\n return {\n contractVersion: WORKFLOW_CONTRACT_VERSION,\n assignmentId: nonEmptyString(\n value.assignmentId,\n \"phase result.assignmentId\",\n ),\n phase: enumValue(\n value.phase,\n [\n \"triage\",\n \"implementation\",\n \"checking\",\n \"review\",\n \"repair\",\n \"handoff\",\n \"merge\",\n \"release-verification\",\n ],\n \"phase result.phase\",\n ),\n outcome,\n identity: parseIdentity(value.identity, \"phase result.identity\"),\n briefHash: nonEmptyString(value.briefHash, \"phase result.briefHash\"),\n base:\n value.base === undefined\n ? undefined\n : parseRevision(value.base, \"phase result.base\"),\n head:\n value.head === undefined\n ? undefined\n : parseRevision(value.head, \"phase result.head\"),\n summary: nonEmptyString(value.summary, \"phase result.summary\"),\n evidence,\n checks,\n commits,\n artifacts: stringArray(value.artifacts, \"phase result.artifacts\"),\n questions: stringArray(value.questions, \"phase result.questions\"),\n findings: Array.isArray(value.findings)\n ? value.findings.map(parseFinding)\n : (() => {\n throw new ContractValidationError(\n \"phase result.findings must be an array\",\n );\n })(),\n reviewAxes:\n value.reviewAxes === undefined\n ? undefined\n : enumArray(\n value.reviewAxes,\n [\"standards\", \"spec\", \"interface\"],\n \"phase result.reviewAxes\",\n ),\n completedAt: nonEmptyString(value.completedAt, \"phase result.completedAt\"),\n };\n};\n\nconst parseFinding = (value: unknown): Finding => {\n if (!isRecord(value)) {\n throw new ContractValidationError(\"finding must be an object\");\n }\n return {\n id: nonEmptyString(value.id, \"finding.id\"),\n severity: enumValue(\n value.severity,\n [\"info\", \"low\", \"medium\", \"high\", \"critical\"],\n \"finding.severity\",\n ),\n axis: enumValue(\n value.axis,\n [\"standards\", \"spec\", \"interface\"],\n \"finding.axis\",\n ),\n disposition: enumValue(\n value.disposition,\n [\"open\", \"fixed\", \"rejected\", \"accepted\", \"deferred\"],\n \"finding.disposition\",\n ),\n title: nonEmptyString(value.title, \"finding.title\"),\n evidence: nonEmptyString(value.evidence, \"finding.evidence\"),\n location: optionalString(value.location, \"finding.location\"),\n requirement: optionalString(value.requirement, \"finding.requirement\"),\n verification: optionalString(value.verification, \"finding.verification\"),\n };\n};\n","import {\n isAuthorizationAllowed,\n parseRepositoryPolicy,\n parseWorkBrief,\n type CheckEvidence,\n type Finding,\n type RepositoryPolicy,\n type RevisionReference,\n type ReviewAxis,\n type ReviewEvidence,\n type WorkBrief,\n} from \"../contracts/index.js\";\nimport type { WorkflowJob } from \"../coordinator/index.js\";\nimport {\n isBlockingFinding,\n requiredCheckNames,\n sameRevision,\n} from \"../shared.js\";\n\nexport interface HandoffCandidate {\n readonly base: RevisionReference;\n readonly head: RevisionReference;\n readonly briefHash: string;\n}\n\nexport interface BranchProtectionState {\n readonly enforced: boolean;\n readonly humanApprovalRequired: boolean;\n /** Fresh provider evidence; caller-supplied booleans alone are not a merge gate. */\n readonly provider: \"github\";\n readonly verifiedAt: string;\n}\n\nexport interface HumanApproval {\n readonly actor: string;\n readonly actorRole: \"owner\" | \"maintainer\";\n readonly approvedAt: string;\n readonly baseSha: string;\n readonly headSha: string;\n readonly briefHash: string;\n}\n\nexport interface HandoffReadinessInput {\n readonly job: WorkflowJob;\n readonly candidate: HandoffCandidate;\n readonly checks: readonly CheckEvidence[];\n readonly review: ReviewEvidence;\n readonly requiredAxes?: readonly ReviewAxis[];\n readonly branchProtection?: BranchProtectionState;\n readonly humanApproval?: HumanApproval;\n readonly now?: () => string;\n readonly freshnessWindowSeconds?: number;\n}\n\nexport interface HandoffPacket {\n readonly sourceIssue: string;\n readonly pullRequest?: string;\n readonly candidate: HandoffCandidate;\n readonly briefRevision: number;\n readonly briefHash: string;\n readonly change: string;\n readonly risk: WorkBrief[\"risk\"];\n readonly acceptanceCriteria: readonly string[];\n readonly acceptanceEvidence: readonly string[];\n readonly checks: readonly CheckEvidence[];\n readonly reviewAxes: readonly ReviewAxis[];\n readonly findings: readonly Finding[];\n readonly limitations: readonly string[];\n}\n\nexport type HandoffOutcome =\n | \"blocked\"\n | \"ready-for-review\"\n | \"review-requested\"\n /** Retained for source-item triage; PR handoff uses ready-for-review. */\n | \"ready-for-human\"\n | \"repair-needed\"\n | \"rejected\"\n | \"abandoned\"\n | \"merge-ready\"\n | \"merged\"\n | \"open\";\n\nexport interface HandoffReadinessResult {\n readonly outcome:\n | \"blocked\"\n | \"ready-for-review\"\n | \"review-requested\"\n | \"merge-ready\";\n readonly readyForReview: boolean;\n readonly reviewRequested: boolean;\n readonly readyForHuman: boolean;\n readonly mergeReady: boolean;\n readonly reasons: readonly string[];\n readonly packet: HandoffPacket;\n}\n\nexport interface HumanHandoffPublisher {\n requestReview(input: {\n readonly packet: HandoffPacket;\n readonly pullRequestNumber: number;\n }): Promise<void>;\n}\n\nexport interface PrepareHandoffOptions extends HandoffReadinessInput {\n readonly sourceIssueNumber: number;\n readonly pullRequestNumber: number;\n readonly publisher?: HumanHandoffPublisher;\n readonly readCurrent?: () => Promise<HandoffCandidate>;\n}\n\nexport interface HumanReviewDecisionInput {\n readonly decision:\n | \"approved\"\n | \"changes-requested\"\n | \"rejected\"\n | \"abandoned\";\n readonly reason?: string;\n}\n\nexport interface HumanReviewDecision {\n readonly outcome: Extract<\n HandoffOutcome,\n \"merge-ready\" | \"repair-needed\" | \"rejected\" | \"abandoned\"\n >;\n readonly reason?: string;\n}\n\nexport interface HumanReviewRoundTripOptions {\n readonly candidate: HandoffCandidate;\n readonly pullRequestNumber: number;\n readonly decision: HumanReviewDecisionInput;\n /** Re-reads the PR head and brief before applying the human decision. */\n readonly readCurrent: () => Promise<HandoffCandidate>;\n /** Keeps a requested-changes repair on the existing PR branch. */\n readonly requestRepair: (input: {\n readonly candidate: HandoffCandidate;\n readonly pullRequestNumber: number;\n readonly reason: string;\n }) => Promise<void>;\n}\n\nexport interface HumanReviewRoundTripResult {\n readonly outcome:\n | \"blocked\"\n | Extract<\n HandoffOutcome,\n \"merge-ready\" | \"repair-needed\" | \"rejected\" | \"abandoned\"\n >;\n readonly reason?: string;\n readonly candidate: HandoffCandidate;\n readonly pullRequestNumber: number;\n}\n\nexport interface MergeTransport {\n mergeProtected(input: {\n readonly pullRequestNumber: number;\n readonly headSha: string;\n readonly baseBranch: string;\n }): Promise<{ readonly mergedSha: string }>;\n}\n\nexport interface MergeCandidateOptions extends Omit<\n HandoffReadinessInput,\n \"branchProtection\"\n> {\n readonly pullRequestNumber: number;\n readonly humanApproval: HumanApproval;\n /** Re-reads the PR, branch and brief identity immediately before merging. */\n readonly readCurrent: () => Promise<HandoffCandidate>;\n /** Fetches fresh provider evidence immediately before a protected merge. */\n readonly readBranchProtection: () => Promise<BranchProtectionState>;\n readonly transport: MergeTransport;\n}\n\nexport interface MergeResult {\n readonly outcome: \"blocked\" | \"merged\";\n readonly reason?: string;\n readonly mergedSha?: string;\n}\n\nexport interface CompletionInput {\n readonly policy: RepositoryPolicy;\n readonly mergedSha: string;\n readonly candidate: HandoffCandidate;\n readonly checks: readonly CheckEvidence[];\n}\n\nexport interface CompletionResult {\n readonly outcome: \"completed\" | \"open\";\n readonly reason?: string;\n readonly mergedSha: string;\n readonly checks: readonly CheckEvidence[];\n}\n\nexport interface SourceIssueCloser {\n closeIssue(input: {\n readonly issueNumber: number;\n readonly mergedSha: string;\n readonly checks: readonly CheckEvidence[];\n }): Promise<void>;\n}\n\nexport interface CloseSourceIssueOptions extends CompletionInput {\n readonly sourceIssueNumber: number;\n readonly closer: SourceIssueCloser;\n}\n\nexport interface SourceIssueClosureResult extends CompletionResult {\n readonly closed: boolean;\n}\n\nconst defaultAxes: readonly ReviewAxis[] = [\"standards\", \"spec\"];\n\nconst isFreshTimestamp = (\n value: string,\n now: string,\n freshnessWindowSeconds: number,\n): boolean => {\n const timestamp = Date.parse(value);\n const current = Date.parse(now);\n return (\n Number.isFinite(timestamp) &&\n Number.isFinite(current) &&\n timestamp <= current &&\n current - timestamp <= freshnessWindowSeconds * 1000\n );\n};\n\nconst implementationEvidence = (\n job: WorkflowJob,\n candidate: HandoffCandidate,\n): readonly string[] =>\n [...job.phaseResults]\n .reverse()\n .find(\n (result) =>\n result.outcome === \"completed\" &&\n (result.phase === \"implementation\" || result.phase === \"repair\") &&\n result.base !== undefined &&\n result.head !== undefined &&\n sameRevision(result.base, candidate.base) &&\n sameRevision(result.head, candidate.head) &&\n result.briefHash === candidate.briefHash,\n )?.evidence ?? [];\n\nconst allRequiredChecksPassed = (\n policy: RepositoryPolicy,\n checks: readonly CheckEvidence[],\n expected?: {\n readonly baseSha?: string;\n readonly headSha: string;\n readonly briefHash?: string;\n },\n): string[] => {\n const reasons: string[] = [];\n for (const name of requiredCheckNames(policy)) {\n const named = checks.filter((candidate) => candidate.name === name);\n if (named.length === 0) {\n reasons.push(`Required check is missing: ${name}`);\n continue;\n }\n const check =\n expected === undefined\n ? named[0]\n : named.find(\n (candidate) =>\n candidate.headSha === expected.headSha &&\n (expected.baseSha === undefined ||\n candidate.baseSha === expected.baseSha) &&\n (expected.briefHash === undefined ||\n candidate.briefHash === expected.briefHash),\n );\n if (check === undefined) {\n reasons.push(\n `Required check is stale for the current candidate: ${name}`,\n );\n } else if (check.status !== \"passed\") {\n reasons.push(`Required check ${name} is ${check.status}`);\n }\n }\n return reasons;\n};\n\nconst candidateReasons = (\n job: WorkflowJob,\n candidate: HandoffCandidate,\n review: ReviewEvidence,\n requiredAxes: readonly ReviewAxis[],\n): string[] => {\n const reasons: string[] = [];\n let brief: WorkBrief;\n try {\n brief = parseWorkBrief(job.brief);\n } catch {\n return [\"Workflow brief is malformed\"];\n }\n if (brief.identity.kind !== \"executable-issue\") {\n reasons.push(\"Only executable issues may reach human PR handoff\");\n }\n if (!isAuthorizationAllowed(brief, job.policy)) {\n reasons.push(\"Implementation authorization is not approved\");\n }\n if (brief.identity.repository !== job.policy.repository) {\n reasons.push(\"Workflow policy repository does not match the brief\");\n }\n if (job.control !== \"active\") reasons.push(`Workflow job is ${job.control}`);\n if (!sameRevision(brief.base, candidate.base)) {\n reasons.push(\"Candidate base does not match the brief base\");\n }\n if (review.baseSha !== candidate.base.sha) {\n reasons.push(\"Review evidence is bound to a different base revision\");\n }\n if (review.headSha !== candidate.head.sha) {\n reasons.push(\"Review evidence is bound to a different candidate head\");\n }\n if (\n review.briefHash !== candidate.briefHash ||\n review.briefHash !== brief.hash\n ) {\n reasons.push(\"Review evidence is bound to a different brief revision\");\n }\n const implementationHead = [...job.phaseResults]\n .reverse()\n .find(\n (result) =>\n result.phase === \"implementation\" || result.phase === \"repair\",\n )?.head;\n if (\n implementationHead !== undefined &&\n !sameRevision(implementationHead, candidate.head)\n ) {\n reasons.push(\"Candidate head does not match the implementation result\");\n }\n if (review.outcome !== \"passed\") {\n reasons.push(`Independent review outcome is ${review.outcome}`);\n }\n if (\n implementationEvidence(job, candidate).length <\n brief.acceptanceCriteria.length\n ) {\n reasons.push(\"Implementation acceptance evidence is missing\");\n }\n for (const axis of requiredAxes) {\n if (!review.axes.includes(axis))\n reasons.push(`Review axis is missing: ${axis}`);\n }\n for (const finding of review.findings) {\n if (isBlockingFinding(finding)) {\n reasons.push(`Blocking finding remains: ${finding.id}`);\n }\n }\n return reasons;\n};\n\nconst packetFor = (\n input: HandoffReadinessInput,\n brief: WorkBrief,\n): HandoffPacket => ({\n sourceIssue: `#${brief.identity.itemId}`,\n candidate: input.candidate,\n briefRevision: brief.revision,\n briefHash: brief.hash,\n change: brief.problem,\n risk: brief.risk,\n acceptanceCriteria: brief.acceptanceCriteria,\n acceptanceEvidence: implementationEvidence(input.job, input.candidate),\n checks: input.checks,\n reviewAxes: input.review.axes,\n findings: input.review.findings,\n limitations: [\n ...brief.exclusions,\n ...brief.unresolvedQuestions.map((question) => `Unresolved: ${question}`),\n ],\n});\n\nconst approvalMatches = (\n candidate: HandoffCandidate,\n brief: WorkBrief,\n policy: RepositoryPolicy,\n approval: HumanApproval | undefined,\n): boolean =>\n approval !== undefined &&\n approval.actor.trim().length > 0 &&\n approval.approvedAt.trim().length > 0 &&\n policy.authorization.allowedActors.includes(approval.actorRole) &&\n approval.baseSha === candidate.base.sha &&\n approval.headSha === candidate.head.sha &&\n approval.briefHash === brief.hash;\n\nexport const evaluateHandoffReadiness = (\n input: HandoffReadinessInput,\n): HandoffReadinessResult => {\n const brief = parseWorkBrief(input.job.brief);\n const policy = parseRepositoryPolicy(input.job.policy);\n const requiredAxes = [\n ...new Set([...defaultAxes, ...(input.requiredAxes ?? [])]),\n ] as ReviewAxis[];\n const reasons = [\n ...candidateReasons(input.job, input.candidate, input.review, requiredAxes),\n ...allRequiredChecksPassed(policy, input.checks, {\n baseSha: input.candidate.base.sha,\n headSha: input.candidate.head.sha,\n briefHash: input.candidate.briefHash,\n }),\n ];\n const packet: HandoffPacket = {\n ...packetFor(input, brief),\n pullRequest: undefined,\n };\n const readyForHuman = reasons.length === 0;\n const protection = input.branchProtection;\n const freshnessWindowSeconds = input.freshnessWindowSeconds ?? 300;\n const freshMergeEvidence =\n Number.isFinite(freshnessWindowSeconds) &&\n freshnessWindowSeconds > 0 &&\n protection?.provider === \"github\" &&\n isFreshTimestamp(\n protection.verifiedAt,\n input.now?.() ?? new Date().toISOString(),\n freshnessWindowSeconds,\n ) &&\n input.humanApproval !== undefined &&\n isFreshTimestamp(\n input.humanApproval.approvedAt,\n input.now?.() ?? new Date().toISOString(),\n freshnessWindowSeconds,\n );\n const mergeReady =\n readyForHuman &&\n protection?.enforced === true &&\n protection.humanApprovalRequired === true &&\n freshMergeEvidence &&\n approvalMatches(input.candidate, brief, policy, input.humanApproval);\n if (!readyForHuman) {\n return {\n outcome: \"blocked\",\n readyForReview: false,\n reviewRequested: false,\n readyForHuman: false,\n mergeReady: false,\n reasons,\n packet,\n };\n }\n return {\n outcome: mergeReady ? \"merge-ready\" : \"ready-for-review\",\n readyForReview: true,\n reviewRequested: false,\n readyForHuman: true,\n mergeReady,\n reasons,\n packet,\n };\n};\n\nexport const prepareHumanHandoff = async (\n input: PrepareHandoffOptions,\n): Promise<HandoffReadinessResult> => {\n if (input.readCurrent !== undefined) {\n let current: HandoffCandidate;\n try {\n current = await input.readCurrent();\n } catch (error) {\n const brief = parseWorkBrief(input.job.brief);\n return {\n outcome: \"blocked\",\n readyForReview: false,\n reviewRequested: false,\n readyForHuman: false,\n mergeReady: false,\n reasons: [\n `Could not validate the current candidate: ${error instanceof Error ? error.message : String(error)}`,\n ],\n packet: {\n ...packetFor(input, brief),\n pullRequest: `#${input.pullRequestNumber}`,\n },\n };\n }\n if (\n !sameRevision(current.base, input.candidate.base) ||\n !sameRevision(current.head, input.candidate.head) ||\n current.briefHash !== input.candidate.briefHash\n ) {\n const brief = parseWorkBrief(input.job.brief);\n return {\n outcome: \"blocked\",\n readyForReview: false,\n reviewRequested: false,\n readyForHuman: false,\n mergeReady: false,\n reasons: [\"Candidate changed before human handoff\"],\n packet: {\n ...packetFor(input, brief),\n pullRequest: `#${input.pullRequestNumber}`,\n },\n };\n }\n }\n const readiness = evaluateHandoffReadiness(input);\n const packet = {\n ...readiness.packet,\n pullRequest: `#${input.pullRequestNumber}`,\n };\n let result: HandoffReadinessResult = { ...readiness, packet };\n if (result.readyForHuman && input.publisher !== undefined) {\n try {\n await input.publisher.requestReview({\n packet,\n pullRequestNumber: input.pullRequestNumber,\n });\n result = {\n ...result,\n outcome: \"review-requested\",\n reviewRequested: true,\n };\n } catch (error) {\n result = {\n ...result,\n outcome: \"blocked\",\n readyForReview: false,\n reviewRequested: false,\n readyForHuman: false,\n reasons: [\n `Could not request human review: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n }\n return result;\n};\n\nexport const resolveHumanReviewDecision = (\n input: HumanReviewDecisionInput,\n): HumanReviewDecision => {\n switch (input.decision) {\n case \"approved\":\n return { outcome: \"merge-ready\", reason: input.reason };\n case \"changes-requested\":\n return {\n outcome: \"repair-needed\",\n reason: input.reason ?? \"Human review requested changes\",\n };\n case \"rejected\":\n return {\n outcome: \"rejected\",\n reason: input.reason ?? \"Human review rejected the candidate\",\n };\n case \"abandoned\":\n return {\n outcome: \"abandoned\",\n reason: input.reason ?? \"Pull request was abandoned\",\n };\n }\n};\n\nexport const processHumanReviewDecision = async (\n input: HumanReviewRoundTripOptions,\n): Promise<HumanReviewRoundTripResult> => {\n let current: HandoffCandidate;\n try {\n current = await input.readCurrent();\n } catch (error) {\n return {\n outcome: \"blocked\",\n reason: `Could not validate the current candidate: ${error instanceof Error ? error.message : String(error)}`,\n candidate: input.candidate,\n pullRequestNumber: input.pullRequestNumber,\n };\n }\n if (\n !sameRevision(current.base, input.candidate.base) ||\n !sameRevision(current.head, input.candidate.head) ||\n current.briefHash !== input.candidate.briefHash\n ) {\n return {\n outcome: \"blocked\",\n reason: \"Human review decision is stale for the current candidate\",\n candidate: input.candidate,\n pullRequestNumber: input.pullRequestNumber,\n };\n }\n\n const decision = resolveHumanReviewDecision(input.decision);\n if (decision.outcome === \"repair-needed\") {\n try {\n await input.requestRepair({\n candidate: input.candidate,\n pullRequestNumber: input.pullRequestNumber,\n reason: decision.reason ?? \"Human review requested changes\",\n });\n } catch (error) {\n return {\n outcome: \"blocked\",\n reason: `Could not schedule the requested repair: ${error instanceof Error ? error.message : String(error)}`,\n candidate: input.candidate,\n pullRequestNumber: input.pullRequestNumber,\n };\n }\n }\n return {\n ...decision,\n candidate: input.candidate,\n pullRequestNumber: input.pullRequestNumber,\n };\n};\n\nexport const mergeProtectedCandidate = async (\n input: MergeCandidateOptions,\n): Promise<MergeResult> => {\n const brief = parseWorkBrief(input.job.brief);\n const policy = parseRepositoryPolicy(input.job.policy);\n let current: HandoffCandidate;\n try {\n current = await input.readCurrent();\n } catch (error) {\n return {\n outcome: \"blocked\",\n reason: `Could not validate the current candidate: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n if (\n !sameRevision(current.base, input.candidate.base) ||\n !sameRevision(current.head, input.candidate.head) ||\n current.briefHash !== input.candidate.briefHash\n ) {\n return {\n outcome: \"blocked\",\n reason: \"current candidate changed before protected merge\",\n };\n }\n const freshnessWindowSeconds = input.freshnessWindowSeconds ?? 300;\n if (!Number.isFinite(freshnessWindowSeconds) || freshnessWindowSeconds <= 0) {\n return {\n outcome: \"blocked\",\n reason: \"Freshness window must be a positive number of seconds\",\n };\n }\n let branchProtection: BranchProtectionState;\n try {\n branchProtection = await input.readBranchProtection();\n } catch (error) {\n return {\n outcome: \"blocked\",\n reason: `Could not verify branch protection: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n const readiness = evaluateHandoffReadiness({\n ...input,\n branchProtection,\n });\n if (!readiness.readyForHuman) {\n return { outcome: \"blocked\", reason: readiness.reasons.join(\"; \") };\n }\n if (!branchProtection.enforced) {\n return {\n outcome: \"blocked\",\n reason: \"Branch protection is not proven enforced\",\n };\n }\n if (!branchProtection.humanApprovalRequired) {\n return {\n outcome: \"blocked\",\n reason: \"Human approval gate is not configured\",\n };\n }\n if (\n branchProtection.provider !== \"github\" ||\n !isFreshTimestamp(\n branchProtection.verifiedAt,\n input.now?.() ?? new Date().toISOString(),\n freshnessWindowSeconds,\n )\n ) {\n return {\n outcome: \"blocked\",\n reason: \"Branch protection evidence is not freshly verified\",\n };\n }\n if (\n !isFreshTimestamp(\n input.humanApproval.approvedAt,\n input.now?.() ?? new Date().toISOString(),\n freshnessWindowSeconds,\n )\n ) {\n return {\n outcome: \"blocked\",\n reason: \"Human approval evidence is not fresh\",\n };\n }\n if (!approvalMatches(input.candidate, brief, policy, input.humanApproval)) {\n return {\n outcome: \"blocked\",\n reason: \"Human approval does not match the exact candidate\",\n };\n }\n try {\n const merged = await input.transport.mergeProtected({\n pullRequestNumber: input.pullRequestNumber,\n headSha: input.candidate.head.sha,\n baseBranch: policy.baseBranch,\n });\n return { outcome: \"merged\", mergedSha: merged.mergedSha };\n } catch (error) {\n return {\n outcome: \"blocked\",\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n};\n\nexport const completeSourceIssue = (\n input: CompletionInput,\n): CompletionResult => {\n const policy = parseRepositoryPolicy(input.policy);\n if (input.mergedSha.trim().length === 0) {\n return {\n outcome: \"open\",\n reason: \"Merged revision is missing\",\n mergedSha: input.mergedSha,\n checks: input.checks,\n };\n }\n if (policy.issueClosure !== \"merge-and-ci\") {\n return {\n outcome: \"open\",\n reason: \"Source issue remains open until release verification\",\n mergedSha: input.mergedSha,\n checks: input.checks,\n };\n }\n const checkReasons = allRequiredChecksPassed(policy, input.checks, {\n headSha: input.mergedSha,\n });\n if (checkReasons.length > 0) {\n return {\n outcome: \"open\",\n reason: checkReasons.join(\"; \"),\n mergedSha: input.mergedSha,\n checks: input.checks,\n };\n }\n return {\n outcome: \"completed\",\n mergedSha: input.mergedSha,\n checks: input.checks,\n };\n};\n\nexport const closeSourceIssue = async (\n input: CloseSourceIssueOptions,\n): Promise<SourceIssueClosureResult> => {\n const completion = completeSourceIssue(input);\n if (completion.outcome === \"open\") {\n return { ...completion, closed: false };\n }\n try {\n await input.closer.closeIssue({\n issueNumber: input.sourceIssueNumber,\n mergedSha: input.mergedSha,\n checks: input.checks,\n });\n return { ...completion, closed: true };\n } catch (error) {\n return {\n ...completion,\n outcome: \"open\",\n closed: false,\n reason: `Could not close source issue: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n};\n","import type { PostgresQueryClient } from \"./coordinator/postgres-storage.js\";\n\nexport type WorkflowPhaseRecordKind = \"triage\" | \"repair-batch\";\n\n/** Persistence shared by workflow phases whose records do not belong in the coordinator ledger. */\nexport interface WorkflowPhaseRecordStore {\n get(kind: WorkflowPhaseRecordKind, key: string): Promise<unknown | undefined>;\n save(\n kind: \"repair-batch\",\n key: string,\n record: unknown,\n updatedAt: string,\n ): Promise<void>;\n compareAndSaveTriage(\n key: string,\n expectedRevision: number | undefined,\n record: unknown,\n updatedAt: string,\n ): Promise<boolean>;\n}\n\nexport interface PostgresWorkflowPhaseRecordStoreOptions {\n readonly client: PostgresQueryClient;\n}\n\n/** Stores resumable triage and repair records in the coordinator database. */\nexport class PostgresWorkflowPhaseRecordStore implements WorkflowPhaseRecordStore {\n private readonly client: PostgresQueryClient;\n\n constructor(options: PostgresWorkflowPhaseRecordStoreOptions) {\n this.client = options.client;\n }\n\n async get(\n kind: WorkflowPhaseRecordKind,\n key: string,\n ): Promise<unknown | undefined> {\n const result = await this.client.query<{\n record: unknown;\n schema_version: unknown;\n }>(\n `SELECT record, schema_version\n FROM shipyard_workflow_phase_records\n WHERE namespace = $1 AND record_key = $2`,\n [kind, encodeURIComponent(key)],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n if (Number(row.schema_version) !== 1) {\n throw new Error(\n `Unsupported ${kind} record schema version: ${String(row.schema_version)}`,\n );\n }\n if (typeof row.record === \"string\")\n return JSON.parse(row.record) as unknown;\n return row.record;\n }\n\n async save(\n kind: \"repair-batch\",\n key: string,\n record: unknown,\n updatedAt: string,\n ): Promise<void> {\n await this.client.query(\n `INSERT INTO shipyard_workflow_phase_records\n (namespace, record_key, schema_version, record, updated_at)\n VALUES ($1, $2, 1, $3::jsonb, $4::timestamptz)\n ON CONFLICT (namespace, record_key) DO UPDATE SET\n schema_version = EXCLUDED.schema_version,\n record = EXCLUDED.record,\n updated_at = EXCLUDED.updated_at`,\n [kind, encodeURIComponent(key), JSON.stringify(record), updatedAt],\n );\n }\n\n async compareAndSaveTriage(\n key: string,\n expectedRevision: number | undefined,\n record: unknown,\n updatedAt: string,\n ): Promise<boolean> {\n const encodedKey = encodeURIComponent(key);\n const result =\n expectedRevision === undefined\n ? await this.client.query<{ record_key: string }>(\n `INSERT INTO shipyard_workflow_phase_records\n (namespace, record_key, schema_version, record, updated_at)\n VALUES ('triage', $1, 1, $2::jsonb, $3::timestamptz)\n ON CONFLICT (namespace, record_key) DO NOTHING\n RETURNING record_key`,\n [encodedKey, JSON.stringify(record), updatedAt],\n )\n : await this.client.query<{ record_key: string }>(\n `UPDATE shipyard_workflow_phase_records\n SET schema_version = 1, record = $3::jsonb, updated_at = $4::timestamptz\n WHERE namespace = 'triage'\n AND record_key = $1\n AND record->>'revision' = $2\n RETURNING record_key`,\n [\n encodedKey,\n String(expectedRevision),\n JSON.stringify(record),\n updatedAt,\n ],\n );\n return result.rows.length > 0;\n }\n}\n","import { createHash } from \"node:crypto\";\nimport {\n parseWorkBrief,\n type RiskLevel,\n type WorkBrief,\n type WorkItemKind,\n} from \"../contracts/index.js\";\nimport type {\n ClarificationReply,\n TriageAssessment,\n TriageCategory,\n TriageOutcome,\n TriageRecord,\n TriageSource,\n} from \"./index.js\";\n\nconst nonEmpty = (value: unknown, path: string): string => {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`${path} must be a non-empty string`);\n }\n return value.trim();\n};\n\nconst optionalNonEmpty = (value: unknown, path: string): string | undefined =>\n value === undefined ? undefined : nonEmpty(value, path);\n\nconst isCategory = (value: unknown): value is TriageCategory =>\n typeof value === \"string\" &&\n [\n \"bug\",\n \"enhancement\",\n \"support\",\n \"duplicate\",\n \"sensitive\",\n \"non-actionable\",\n ].includes(value);\n\nconst isRisk = (value: unknown): value is RiskLevel =>\n typeof value === \"string\" &&\n [\"low\", \"medium\", \"high\", \"critical\"].includes(value);\n\nconst stringArray = (value: unknown, path: string): string[] => {\n if (!Array.isArray(value)) throw new Error(`${path} must be an array`);\n return value.map((entry, index) => nonEmpty(entry, `${path}[${index}]`));\n};\n\nconst sha256 = (value: string): string =>\n createHash(\"sha256\").update(value).digest(\"hex\");\n\nexport const sourceKind = (source: TriageSource): WorkItemKind =>\n source.kind ?? \"executable-issue\";\n\nexport const sourceKey = (source: TriageSource): string =>\n [source.repository, source.itemId, sourceKind(source)].join(\"\\u0000\");\n\nexport const sourceFingerprint = (source: TriageSource): string =>\n sha256(\n JSON.stringify({\n provider: source.provider,\n repository: source.repository,\n itemId: source.itemId,\n title: source.title,\n body: source.body,\n author: source.author ?? \"\",\n url: source.url ?? \"\",\n updatedAt: source.updatedAt,\n kind: sourceKind(source),\n labels: [...(source.labels ?? [])].sort(),\n }),\n );\n\nexport const sourceTimestampOrder = (\n candidateUpdatedAt: string,\n storedUpdatedAt: string,\n): \"older\" | \"same\" | \"newer\" | \"unknown\" => {\n const candidateTime = Date.parse(candidateUpdatedAt);\n const storedTime = Date.parse(storedUpdatedAt);\n if (!Number.isFinite(candidateTime) || !Number.isFinite(storedTime)) {\n return \"unknown\";\n }\n return candidateTime < storedTime\n ? \"older\"\n : candidateTime > storedTime\n ? \"newer\"\n : \"same\";\n};\n\nconst storedObject = (\n value: unknown,\n path: string,\n): Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`${path} must be an object`);\n }\n return value as Record<string, unknown>;\n};\n\nconst parseStoredSource = (value: unknown): TriageSource => {\n const source = storedObject(value, \"triage.source\");\n const provider = source.provider;\n if (provider !== \"github\" && provider !== \"slack\" && provider !== \"manual\") {\n throw new Error(\"triage.source.provider is invalid\");\n }\n const allowedKinds: readonly WorkItemKind[] = [\n \"planning-spec\",\n \"executable-issue\",\n \"pr-repair\",\n ];\n const kind = source.kind ?? \"executable-issue\";\n if (\n typeof kind !== \"string\" ||\n !allowedKinds.includes(kind as WorkItemKind)\n ) {\n throw new Error(\"triage.source.kind is invalid\");\n }\n if (typeof source.body !== \"string\") {\n throw new Error(\"triage.source.body must be a string\");\n }\n if (source.labels !== undefined && !Array.isArray(source.labels)) {\n throw new Error(\"triage.source.labels must be an array\");\n }\n return normalizeSource({\n provider,\n repository: nonEmpty(source.repository, \"triage.source.repository\"),\n itemId: nonEmpty(source.itemId, \"triage.source.itemId\"),\n title: nonEmpty(source.title, \"triage.source.title\"),\n body: source.body,\n author: optionalNonEmpty(source.author, \"triage.source.author\"),\n url: optionalNonEmpty(source.url, \"triage.source.url\"),\n updatedAt: nonEmpty(source.updatedAt, \"triage.source.updatedAt\"),\n kind: kind as WorkItemKind,\n labels: stringArray(source.labels ?? [], \"triage.source.labels\"),\n });\n};\n\nconst parseClarificationReply = (\n value: unknown,\n path: string,\n): ClarificationReply => {\n const reply = storedObject(value, path);\n if (typeof reply.body !== \"string\") {\n throw new Error(`${path}.body must be a string`);\n }\n return {\n id: nonEmpty(reply.id, `${path}.id`),\n body: reply.body,\n author: optionalNonEmpty(reply.author, `${path}.author`),\n updatedAt: nonEmpty(reply.updatedAt, `${path}.updatedAt`),\n };\n};\n\nexport const normalizeClarificationReply = (\n reply: ClarificationReply,\n): ClarificationReply => parseClarificationReply(reply, \"clarificationReply\");\n\nexport const parseTriageRecord = (value: unknown): TriageRecord => {\n const record = storedObject(value, \"triage record\");\n const source = parseStoredSource(record.source);\n const assessment = normalizeAssessment(record.assessment);\n const outcome = record.outcome;\n const outcomes: readonly TriageOutcome[] = [\n \"completed\",\n \"needs-info\",\n \"duplicate\",\n \"sensitive\",\n \"non-actionable\",\n \"blocked\",\n \"failed\",\n ];\n if (\n typeof outcome !== \"string\" ||\n !outcomes.includes(outcome as TriageOutcome)\n ) {\n throw new Error(\"triage.outcome is invalid\");\n }\n if (!isCategory(record.category))\n throw new Error(\"triage.category is invalid\");\n const revision = record.revision;\n if (\n typeof revision !== \"number\" ||\n !Number.isSafeInteger(revision) ||\n revision < 1\n ) {\n throw new Error(\"triage.revision must be a positive integer\");\n }\n const parsedBrief =\n record.brief === undefined ? undefined : parseWorkBrief(record.brief);\n const clarificationIds = stringArray(\n record.clarificationIds,\n \"triage.clarificationIds\",\n );\n const pendingClarificationReplies =\n record.pendingClarificationReplies === undefined\n ? []\n : (() => {\n if (!Array.isArray(record.pendingClarificationReplies)) {\n throw new Error(\n \"triage.pendingClarificationReplies must be an array\",\n );\n }\n return record.pendingClarificationReplies.map((reply, index) =>\n parseClarificationReply(\n reply,\n `triage.pendingClarificationReplies[${index}]`,\n ),\n );\n })();\n const sourceConflict =\n record.sourceConflict === undefined\n ? undefined\n : (() => {\n const conflict = storedObject(\n record.sourceConflict,\n \"triage.sourceConflict\",\n );\n const fingerprint = nonEmpty(\n conflict.fingerprint,\n \"triage.sourceConflict.fingerprint\",\n );\n if (!/^[0-9a-f]{64}$/.test(fingerprint)) {\n throw new Error(\"triage.sourceConflict.fingerprint is invalid\");\n }\n return {\n fingerprint,\n updatedAt: nonEmpty(\n conflict.updatedAt,\n \"triage.sourceConflict.updatedAt\",\n ),\n };\n })();\n const pendingIds = pendingClarificationReplies.map(({ id }) => id);\n if (\n new Set(pendingIds).size !== pendingIds.length ||\n pendingIds.some((id) => clarificationIds.includes(id))\n ) {\n throw new Error(\"Stored triage clarification replies are not unique\");\n }\n const parsed: TriageRecord = {\n id: nonEmpty(record.id, \"triage.id\"),\n sourceKey: nonEmpty(record.sourceKey, \"triage.sourceKey\"),\n source,\n sourceUpdatedAt: nonEmpty(record.sourceUpdatedAt, \"triage.sourceUpdatedAt\"),\n sourceFingerprint: nonEmpty(\n record.sourceFingerprint,\n \"triage.sourceFingerprint\",\n ),\n revision,\n category: record.category,\n outcome: outcome as TriageOutcome,\n assessment,\n brief: parsedBrief,\n questions: stringArray(record.questions, \"triage.questions\"),\n clarificationIds,\n ...(pendingClarificationReplies.length === 0\n ? {}\n : { pendingClarificationReplies }),\n ...(sourceConflict === undefined ? {} : { sourceConflict }),\n duplicateOf: optionalNonEmpty(record.duplicateOf, \"triage.duplicateOf\"),\n publicMessage: nonEmpty(record.publicMessage, \"triage.publicMessage\"),\n createdAt: nonEmpty(record.createdAt, \"triage.createdAt\"),\n updatedAt: nonEmpty(record.updatedAt, \"triage.updatedAt\"),\n };\n if (parsed.sourceKey !== sourceKey(source)) {\n throw new Error(\"Stored triage source key does not match its source\");\n }\n if (parsed.sourceUpdatedAt !== source.updatedAt) {\n throw new Error(\"Stored triage source timestamp does not match its source\");\n }\n if (parsed.sourceFingerprint !== sourceFingerprint(source)) {\n throw new Error(\"Stored triage fingerprint does not match its source\");\n }\n if (parsed.category !== assessment.category) {\n throw new Error(\"Stored triage category does not match its assessment\");\n }\n if (\n sourceConflict !== undefined &&\n (parsed.outcome !== \"blocked\" ||\n parsedBrief !== undefined ||\n sourceConflict.fingerprint === parsed.sourceFingerprint)\n ) {\n throw new Error(\"Stored triage source conflict is inconsistent\");\n }\n if (\n parsedBrief !== undefined &&\n (parsedBrief.revision !== revision ||\n parsedBrief.identity.repository !== source.repository ||\n parsedBrief.identity.itemId !== source.itemId ||\n parsedBrief.identity.kind !== sourceKind(source))\n ) {\n throw new Error(\"Stored triage brief does not match its source revision\");\n }\n return parsed;\n};\n\nexport const normalizeSource = (source: TriageSource): TriageSource => ({\n ...source,\n repository: nonEmpty(source.repository, \"source.repository\"),\n itemId: nonEmpty(source.itemId, \"source.itemId\"),\n title: nonEmpty(source.title, \"source.title\"),\n body: typeof source.body === \"string\" ? source.body : \"\",\n author: optionalNonEmpty(source.author, \"source.author\"),\n url: optionalNonEmpty(source.url, \"source.url\"),\n updatedAt: nonEmpty(source.updatedAt, \"source.updatedAt\"),\n kind: sourceKind(source),\n labels: [...(source.labels ?? [])].map((label, index) =>\n nonEmpty(label, `source.labels[${index}]`),\n ),\n});\n\nexport const normalizeAssessment = (value: unknown): TriageAssessment => {\n const assessment = storedObject(value, \"assessment\");\n if (!isCategory(assessment.category))\n throw new Error(\"assessment.category is invalid\");\n if (!isRisk(assessment.risk)) throw new Error(\"assessment.risk is invalid\");\n if (typeof assessment.requirementsConfirmed !== \"boolean\") {\n throw new Error(\"assessment.requirementsConfirmed must be a boolean\");\n }\n const duplicateOf = optionalNonEmpty(\n assessment.duplicateOf,\n \"assessment.duplicateOf\",\n );\n const sensitiveReason = optionalNonEmpty(\n assessment.sensitiveReason,\n \"assessment.sensitiveReason\",\n );\n return {\n category: assessment.category,\n evidence: stringArray(assessment.evidence, \"assessment.evidence\"),\n relevantFiles: stringArray(\n assessment.relevantFiles,\n \"assessment.relevantFiles\",\n ),\n acceptanceCriteria: stringArray(\n assessment.acceptanceCriteria,\n \"assessment.acceptanceCriteria\",\n ),\n exclusions: stringArray(assessment.exclusions, \"assessment.exclusions\"),\n risk: assessment.risk,\n verification: stringArray(\n assessment.verification,\n \"assessment.verification\",\n ),\n unresolvedQuestions: stringArray(\n assessment.unresolvedQuestions,\n \"assessment.unresolvedQuestions\",\n ),\n requirementsConfirmed: assessment.requirementsConfirmed,\n duplicateOf,\n sensitiveReason,\n };\n};\n","import type {\n ClarificationReply,\n TriageRecord,\n TriageSource,\n TriageSourceConflict,\n} from \"./index.js\";\nimport { sourceTimestampOrder } from \"./persistence.js\";\n\ntype Reconciliation =\n | { readonly kind: \"unchanged\"; readonly record: TriageRecord }\n | {\n readonly kind: \"source-conflict\";\n readonly existing: TriageRecord;\n readonly sourceConflict: TriageSourceConflict;\n readonly pendingReplies: readonly ClarificationReply[];\n }\n | {\n readonly kind: \"investigate\";\n readonly source: TriageSource;\n readonly sourceFingerprint: string;\n readonly pendingReplies: readonly ClarificationReply[];\n };\n\nexport const reconcileTriageSource = (input: {\n readonly source: TriageSource;\n readonly sourceFingerprint: string;\n readonly existing?: TriageRecord;\n readonly incomingReply?: ClarificationReply;\n}): Reconciliation => {\n const { source, sourceFingerprint, existing, incomingReply } = input;\n const timestampOrder =\n existing === undefined\n ? \"newer\"\n : sourceTimestampOrder(source.updatedAt, existing.sourceUpdatedAt);\n const sourceChanged =\n existing !== undefined && existing.sourceFingerprint !== sourceFingerprint;\n const sourceTimestampAmbiguous =\n sourceChanged && timestampOrder !== \"older\" && timestampOrder !== \"newer\";\n const replyAlreadyApplied =\n incomingReply !== undefined &&\n (existing?.clarificationIds.includes(incomingReply.id) ?? false);\n const storedReplies = existing?.pendingClarificationReplies ?? [];\n const pendingIds = new Set(storedReplies.map(({ id }) => id));\n const newReply =\n incomingReply !== undefined &&\n !replyAlreadyApplied &&\n !pendingIds.has(incomingReply.id)\n ? incomingReply\n : undefined;\n const pendingReplies =\n newReply === undefined ? [...storedReplies] : [...storedReplies, newReply];\n const priorConflictIsUnresolved =\n existing?.sourceConflict !== undefined && timestampOrder !== \"newer\";\n\n if (\n existing !== undefined &&\n (sourceTimestampAmbiguous || priorConflictIsUnresolved)\n ) {\n const sourceConflict = sourceTimestampAmbiguous\n ? { fingerprint: sourceFingerprint, updatedAt: source.updatedAt }\n : existing.sourceConflict!;\n if (\n existing.sourceConflict?.fingerprint === sourceConflict.fingerprint &&\n existing.outcome === \"blocked\" &&\n existing.brief === undefined &&\n newReply === undefined\n ) {\n return { kind: \"unchanged\", record: existing };\n }\n return {\n kind: \"source-conflict\",\n existing,\n sourceConflict,\n pendingReplies,\n };\n }\n\n // Older snapshots cannot replace current content. Their new replies can\n // still be applied to the saved source below.\n const storedSnapshotWins =\n existing !== undefined &&\n (existing.sourceFingerprint === sourceFingerprint ||\n timestampOrder !== \"newer\");\n const currentSource = storedSnapshotWins ? existing.source : source;\n const currentFingerprint = storedSnapshotWins\n ? existing.sourceFingerprint\n : sourceFingerprint;\n if (\n existing !== undefined &&\n pendingReplies.length === 0 &&\n existing.sourceFingerprint === currentFingerprint\n ) {\n return { kind: \"unchanged\", record: existing };\n }\n return {\n kind: \"investigate\",\n source: currentSource,\n sourceFingerprint: currentFingerprint,\n pendingReplies,\n };\n};\n","import {\n createWorkBrief,\n isAuthorizationAllowed,\n type RepositoryPolicy,\n type RiskLevel,\n type RevisionReference,\n type WorkBrief,\n type WorkItemKind,\n} from \"../contracts/index.js\";\nimport type { PostgresQueryClient } from \"../coordinator/postgres-storage.js\";\nimport { PostgresWorkflowPhaseRecordStore } from \"../phase-storage.js\";\nimport {\n normalizeAssessment,\n normalizeClarificationReply,\n normalizeSource,\n parseTriageRecord,\n sourceFingerprint,\n sourceKey,\n sourceKind,\n} from \"./persistence.js\";\nimport { reconcileTriageSource } from \"./reconciliation.js\";\n\nexport type TriageCategory =\n | \"bug\"\n | \"enhancement\"\n | \"support\"\n | \"duplicate\"\n | \"sensitive\"\n | \"non-actionable\";\n\nexport type TriageOutcome =\n | \"completed\"\n | \"needs-info\"\n | \"duplicate\"\n | \"sensitive\"\n | \"non-actionable\"\n | \"blocked\"\n | \"failed\";\n\nexport interface TriageSource {\n readonly provider: \"github\" | \"slack\" | \"manual\";\n readonly repository: string;\n readonly itemId: string;\n readonly title: string;\n readonly body: string;\n readonly author?: string;\n readonly url?: string;\n readonly updatedAt: string;\n readonly kind?: WorkItemKind;\n readonly labels?: readonly string[];\n}\n\nexport interface ClarificationReply {\n readonly id: string;\n readonly body: string;\n readonly author?: string;\n readonly updatedAt: string;\n}\n\nexport interface TriageSourceConflict {\n readonly fingerprint: string;\n readonly updatedAt: string;\n}\n\nexport interface TriageAssessment {\n readonly category: TriageCategory;\n readonly evidence: readonly string[];\n readonly relevantFiles: readonly string[];\n readonly acceptanceCriteria: readonly string[];\n readonly exclusions: readonly string[];\n readonly risk: RiskLevel;\n readonly verification: readonly string[];\n readonly unresolvedQuestions: readonly string[];\n readonly requirementsConfirmed: boolean;\n readonly duplicateOf?: string;\n readonly sensitiveReason?: string;\n}\n\nexport interface TriageInvestigationRequest {\n readonly source: TriageSource;\n readonly policy: RepositoryPolicy;\n readonly base: RevisionReference;\n readonly previous?: TriageRecord;\n readonly clarificationReply?: ClarificationReply;\n}\n\nexport type TriageInvestigator =\n | ((request: TriageInvestigationRequest) => Promise<TriageAssessment>)\n | {\n investigate(\n request: TriageInvestigationRequest,\n ): Promise<TriageAssessment>;\n };\n\nexport interface TriageRecord {\n readonly id: string;\n readonly sourceKey: string;\n /** Retained for durable investigation and resumption; never used as public output. */\n readonly source: TriageSource;\n readonly sourceUpdatedAt: string;\n readonly sourceFingerprint: string;\n readonly revision: number;\n readonly category: TriageCategory;\n readonly outcome: TriageOutcome;\n readonly assessment: TriageAssessment;\n readonly brief?: WorkBrief;\n readonly questions: readonly string[];\n readonly clarificationIds: readonly string[];\n readonly pendingClarificationReplies?: readonly ClarificationReply[];\n readonly sourceConflict?: TriageSourceConflict;\n readonly duplicateOf?: string;\n readonly publicMessage: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport interface TriageStore {\n get(\n sourceKey: string,\n ): TriageRecord | undefined | Promise<TriageRecord | undefined>;\n /**\n * Atomically save only when the stored revision still matches the read\n * revision. Custom stores must implement this as one compare-and-save.\n */\n compareAndSave(\n record: TriageRecord,\n expectedRevision: number | undefined,\n ): boolean | Promise<boolean>;\n}\n\nexport class InMemoryTriageStore implements TriageStore {\n private readonly records = new Map<string, TriageRecord>();\n\n get(sourceKey: string): TriageRecord | undefined {\n const record = this.records.get(sourceKey);\n return record === undefined ? undefined : clone(record);\n }\n\n compareAndSave(\n record: TriageRecord,\n expectedRevision: number | undefined,\n ): boolean {\n const current = this.records.get(record.sourceKey);\n if (current?.revision !== expectedRevision) return false;\n this.records.set(record.sourceKey, clone(record));\n return true;\n }\n}\n\nexport interface PostgresTriageStoreOptions {\n readonly client: PostgresQueryClient;\n}\n\n/** Durable triage records backed by the coordinator's PostgreSQL database. */\nexport class PostgresTriageStore implements TriageStore {\n private readonly records: PostgresWorkflowPhaseRecordStore;\n\n constructor(options: PostgresTriageStoreOptions) {\n this.records = new PostgresWorkflowPhaseRecordStore(options);\n }\n\n async get(sourceKey: string): Promise<TriageRecord | undefined> {\n const record = await this.records.get(\"triage\", sourceKey);\n return record === undefined ? undefined : parseTriageRecord(record);\n }\n\n compareAndSave(\n record: TriageRecord,\n expectedRevision: number | undefined,\n ): Promise<boolean> {\n return this.records.compareAndSaveTriage(\n record.sourceKey,\n expectedRevision,\n record,\n record.updatedAt,\n );\n }\n}\n\nexport interface RunTriageOptions {\n readonly source: TriageSource;\n readonly policy: RepositoryPolicy;\n readonly base: RevisionReference;\n readonly store: TriageStore;\n readonly investigator?: TriageInvestigator;\n readonly clarificationReply?: ClarificationReply;\n readonly now?: () => string;\n}\n\nexport interface TriageResult {\n readonly outcome: TriageOutcome;\n readonly category: TriageCategory;\n readonly brief?: WorkBrief;\n readonly questions: readonly string[];\n readonly publicMessage: string;\n readonly record: TriageRecord;\n readonly implementationEligible: boolean;\n}\n\nconst defaultNow = (): string => new Date().toISOString();\nconst clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;\nconst MAX_TRIAGE_WRITE_CONFLICT_RETRIES = 5;\n\nconst safeDuplicateId = (value: string | undefined): string | undefined => {\n if (\n value === undefined ||\n !/^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,79}$/.test(value)\n ) {\n return undefined;\n }\n return value;\n};\n\nconst defaultInvestigator: TriageInvestigator = {\n async investigate({ source }): Promise<TriageAssessment> {\n const text = `${source.title}\\n${source.body}`.toLowerCase();\n const labels = new Set(\n (source.labels ?? []).map((label) => label.toLowerCase()),\n );\n const duplicateMatch = text.match(\n /(?:duplicate|dupe)(?: of|:|#)\\s*([\\w./:-]+)/i,\n );\n const category: TriageCategory =\n labels.has(\"sensitive\") ||\n /\\b(secret|token|password|credential|security report)\\b/.test(text)\n ? \"sensitive\"\n : labels.has(\"duplicate\") || duplicateMatch !== null\n ? \"duplicate\"\n : labels.has(\"support\") ||\n /\\?|\\b(how do i|support|question)\\b/.test(text)\n ? \"support\"\n : labels.has(\"bug\") ||\n /\\b(bug|fix|error|crash|broken|fail(?:ed|ure)?)\\b/.test(text)\n ? \"bug\"\n : \"enhancement\";\n const highRisk =\n /\\b(auth|billing|payment|migration|destructive|security)\\b/.test(text);\n const hasExplicitRequirements =\n /\\b(acceptance|expected|should|must|given|when|then)\\b/.test(text) &&\n source.body.trim().length > 0;\n return {\n category,\n evidence: [\n \"Classification derived from the submitted title, body, and labels.\",\n ],\n relevantFiles: [],\n acceptanceCriteria: hasExplicitRequirements\n ? [\"Implement only the explicitly described behavior.\"]\n : [],\n exclusions: [\n \"Do not expand scope beyond the retained source and confirmed answers.\",\n ],\n risk: highRisk ? \"high\" : \"low\",\n verification: [],\n unresolvedQuestions: hasExplicitRequirements\n ? []\n : [\n \"What observable behavior should change, and how will it be accepted?\",\n ],\n requirementsConfirmed: hasExplicitRequirements,\n duplicateOf: safeDuplicateId(duplicateMatch?.[1]),\n };\n },\n};\n\nconst investigate = (\n investigator: TriageInvestigator,\n request: TriageInvestigationRequest,\n): Promise<TriageAssessment> =>\n typeof investigator === \"function\"\n ? investigator(request)\n : investigator.investigate(request);\n\nconst canAutoAuthorize = (\n source: TriageSource,\n assessment: TriageAssessment,\n policy: RepositoryPolicy,\n): boolean =>\n sourceKind(source) === \"executable-issue\" &&\n !policy.authorization.required &&\n policy.authorization.allowedActors.includes(\"policy\") &&\n policy.authorization.autoStartRisk.includes(assessment.risk) &&\n assessment.requirementsConfirmed &&\n assessment.unresolvedQuestions.length === 0 &&\n assessment.acceptanceCriteria.length > 0 &&\n assessment.category !== \"support\" &&\n assessment.category !== \"duplicate\" &&\n assessment.category !== \"sensitive\" &&\n assessment.category !== \"non-actionable\";\n\nconst outcomeForAssessment = (\n source: TriageSource,\n assessment: TriageAssessment,\n): TriageOutcome => {\n const category = assessment.category;\n const questions = assessment.unresolvedQuestions;\n if (sourceKind(source) !== \"executable-issue\") return \"blocked\";\n if (category === \"duplicate\") return \"duplicate\";\n if (category === \"sensitive\") return \"sensitive\";\n if (category === \"non-actionable\") return \"non-actionable\";\n return !assessment.requirementsConfirmed ||\n questions.length > 0 ||\n assessment.acceptanceCriteria.length === 0\n ? \"needs-info\"\n : \"completed\";\n};\n\nconst sourceConflictMessage = (hasPendingReplies: boolean): string =>\n hasPendingReplies\n ? \"Triage is blocked because the source update cannot be ordered against the saved revision; the clarification reply is saved and will be applied after the source is refreshed.\"\n : \"Triage is blocked because the source update cannot be ordered against the saved revision; refresh the source before triage can continue.\";\n\nconst publicMessage = (\n outcome: TriageOutcome,\n category: TriageCategory,\n questions: readonly string[],\n duplicateId?: string,\n): string => {\n switch (outcome) {\n case \"needs-info\":\n return `Triage needs clarification (${questions.length} question${questions.length === 1 ? \"\" : \"s\"}); the work item remains paused.`;\n case \"duplicate\":\n return duplicateId === undefined\n ? \"Triage routed this report as a duplicate for maintainer review.\"\n : `Triage routed this report as a duplicate of #${duplicateId}.`;\n case \"sensitive\":\n return \"Triage routed this report to the private security channel; sensitive details are not reproduced here.\";\n case \"non-actionable\":\n return \"Triage routed this report for maintainer disposition.\";\n case \"blocked\":\n return \"Triage recorded the work item but ordinary implementation dispatch is blocked for this item type.\";\n case \"failed\":\n return \"Triage could not complete; a maintainer must inspect the failure without relying on source text in public output.\";\n case \"completed\":\n return category === \"support\"\n ? \"Triage recorded this support request for a maintainer response.\"\n : \"Triage completed; implementation authorization remains a separate policy decision.\";\n }\n};\n\nconst makeBrief = (\n source: TriageSource,\n assessment: TriageAssessment,\n policy: RepositoryPolicy,\n base: RevisionReference,\n revision: number,\n createdAt: string,\n): WorkBrief => {\n const originalBody =\n source.body.trim().length > 0 ? source.body : \"(empty source body)\";\n const authorization = canAutoAuthorize(source, assessment, policy)\n ? {\n status: \"approved\" as const,\n actor: \"policy\",\n actorRole: \"policy\" as const,\n approvedAt: createdAt,\n }\n : { status: \"pending\" as const };\n return createWorkBrief({\n id: `${source.repository}:${sourceKind(source)}:${source.itemId}`,\n revision,\n identity: {\n repository: source.repository,\n itemId: source.itemId,\n kind: sourceKind(source),\n },\n source: {\n provider: source.provider,\n repository: source.repository,\n itemId: source.itemId,\n url: source.url,\n originalBody,\n author: source.author,\n },\n problem: source.title,\n evidence: assessment.evidence,\n acceptanceCriteria: assessment.acceptanceCriteria,\n exclusions: assessment.exclusions,\n risk: assessment.risk,\n verification: {\n checks: assessment.verification,\n artifacts: assessment.relevantFiles,\n },\n unresolvedQuestions: assessment.unresolvedQuestions,\n authorization,\n base,\n policyRevision: policy.revision,\n skillRevision: policy.worker.skillRevision,\n createdAt,\n });\n};\n\nconst resultFromRecord = (\n record: TriageRecord,\n policy: RepositoryPolicy,\n): TriageResult => ({\n outcome: record.outcome,\n category: record.category,\n brief: record.brief,\n questions: record.questions,\n publicMessage: record.publicMessage,\n record,\n implementationEligible:\n record.outcome === \"completed\" &&\n record.category !== \"support\" &&\n record.brief?.identity.kind === \"executable-issue\" &&\n record.brief !== undefined &&\n record.brief.policyRevision === policy.revision &&\n isAuthorizationAllowed(record.brief, policy),\n});\n\nexport const runTriage = async ({\n source: rawSource,\n policy,\n base,\n store,\n investigator = defaultInvestigator,\n clarificationReply,\n now = defaultNow,\n}: RunTriageOptions): Promise<TriageResult> => {\n const source = normalizeSource(rawSource);\n if (source.repository !== policy.repository) {\n throw new Error(\"source.repository must match policy.repository\");\n }\n const incomingReply =\n clarificationReply === undefined\n ? undefined\n : normalizeClarificationReply(clarificationReply);\n const key = sourceKey(source);\n const fingerprint = sourceFingerprint(source);\n for (\n let conflictAttempt = 0;\n conflictAttempt <= MAX_TRIAGE_WRITE_CONFLICT_RETRIES;\n conflictAttempt += 1\n ) {\n const existing = await store.get(key);\n const reconciliation = reconcileTriageSource({\n source,\n sourceFingerprint: fingerprint,\n existing,\n incomingReply,\n });\n if (reconciliation.kind === \"unchanged\") {\n return resultFromRecord(reconciliation.record, policy);\n }\n if (reconciliation.kind === \"source-conflict\") {\n const { existing, sourceConflict, pendingReplies } = reconciliation;\n const timestamp = now();\n const record: TriageRecord = {\n id: existing.id,\n sourceKey: key,\n source: existing.source,\n sourceUpdatedAt: existing.sourceUpdatedAt,\n sourceFingerprint: existing.sourceFingerprint,\n revision: existing.revision + 1,\n category: existing.category,\n outcome: \"blocked\",\n assessment: existing.assessment,\n questions: [],\n clarificationIds: existing.clarificationIds,\n ...(pendingReplies.length === 0\n ? {}\n : { pendingClarificationReplies: pendingReplies }),\n sourceConflict,\n publicMessage: sourceConflictMessage(pendingReplies.length > 0),\n duplicateOf: existing.duplicateOf,\n createdAt: existing.createdAt,\n updatedAt: timestamp,\n };\n if (await store.compareAndSave(record, existing.revision)) {\n return resultFromRecord(record, policy);\n }\n continue;\n }\n const {\n source: currentSource,\n sourceFingerprint: currentFingerprint,\n pendingReplies: currentPendingReplies,\n } = reconciliation;\n\n const timestamp = now();\n let assessment: TriageAssessment | undefined;\n try {\n let previous = existing;\n if (currentPendingReplies.length === 0) {\n assessment = normalizeAssessment(\n await investigate(investigator, {\n source: currentSource,\n policy,\n base,\n previous,\n }),\n );\n } else {\n for (const [index, reply] of currentPendingReplies.entries()) {\n assessment = normalizeAssessment(\n await investigate(investigator, {\n source: currentSource,\n policy,\n base,\n previous,\n clarificationReply: reply,\n }),\n );\n const processedReplyIds = currentPendingReplies\n .slice(0, index + 1)\n .map(({ id }) => id);\n const remainingReplies = currentPendingReplies.slice(index + 1);\n const previousOutcome = outcomeForAssessment(\n currentSource,\n assessment,\n );\n const previousCategory = assessment.category;\n const previousDuplicateId = safeDuplicateId(assessment.duplicateOf);\n previous = {\n id:\n existing?.id ??\n `${currentSource.repository}:${sourceKind(currentSource)}:${currentSource.itemId}`,\n sourceKey: key,\n source: currentSource,\n sourceUpdatedAt: currentSource.updatedAt,\n sourceFingerprint: currentFingerprint,\n revision: existing?.revision ?? 1,\n category: previousCategory,\n outcome: previousOutcome,\n assessment,\n questions: assessment.unresolvedQuestions,\n clarificationIds: [\n ...(existing?.clarificationIds ?? []),\n ...processedReplyIds,\n ],\n ...(remainingReplies.length === 0\n ? {}\n : { pendingClarificationReplies: remainingReplies }),\n duplicateOf: previousDuplicateId,\n publicMessage: publicMessage(\n previousOutcome,\n previousCategory,\n assessment.unresolvedQuestions,\n previousDuplicateId,\n ),\n createdAt: existing?.createdAt ?? timestamp,\n updatedAt: timestamp,\n };\n }\n }\n } catch {\n const failedAssessment: TriageAssessment = {\n category: \"non-actionable\",\n evidence: [\n \"The investigator did not return a usable structured assessment.\",\n ],\n relevantFiles: [],\n acceptanceCriteria: [],\n exclusions: [\n \"No implementation may start from an incomplete assessment.\",\n ],\n risk: \"high\",\n verification: [],\n unresolvedQuestions: [],\n requirementsConfirmed: false,\n };\n const record: TriageRecord = {\n id:\n existing?.id ??\n `${currentSource.repository}:${sourceKind(currentSource)}:${currentSource.itemId}`,\n sourceKey: key,\n source: currentSource,\n sourceUpdatedAt: currentSource.updatedAt,\n sourceFingerprint: currentFingerprint,\n revision: existing === undefined ? 1 : existing.revision + 1,\n category: failedAssessment.category,\n outcome: \"failed\",\n assessment: failedAssessment,\n questions: [],\n clarificationIds: existing?.clarificationIds ?? [],\n ...(currentPendingReplies.length === 0\n ? {}\n : { pendingClarificationReplies: currentPendingReplies }),\n publicMessage: publicMessage(\"failed\", failedAssessment.category, []),\n createdAt: existing?.createdAt ?? timestamp,\n updatedAt: timestamp,\n };\n if (await store.compareAndSave(record, existing?.revision)) {\n return resultFromRecord(record, policy);\n }\n continue;\n }\n\n if (assessment === undefined) {\n throw new Error(\"Triage investigator returned no assessment\");\n }\n const questions = assessment.unresolvedQuestions;\n const category = assessment.category;\n const duplicateId = safeDuplicateId(assessment.duplicateOf);\n const outcome = outcomeForAssessment(currentSource, assessment);\n const nextRevision = existing === undefined ? 1 : existing.revision + 1;\n const brief = makeBrief(\n currentSource,\n assessment,\n policy,\n base,\n nextRevision,\n existing?.createdAt ?? timestamp,\n );\n const record: TriageRecord = {\n id: existing?.id ?? brief.id,\n sourceKey: key,\n source: currentSource,\n sourceUpdatedAt: currentSource.updatedAt,\n sourceFingerprint: currentFingerprint,\n revision: nextRevision,\n category,\n outcome,\n assessment,\n brief,\n questions,\n clarificationIds: [\n ...(existing?.clarificationIds ?? []),\n ...currentPendingReplies.map(({ id }) => id),\n ],\n duplicateOf: duplicateId,\n publicMessage: publicMessage(outcome, category, questions, duplicateId),\n createdAt: existing?.createdAt ?? timestamp,\n updatedAt: timestamp,\n };\n if (await store.compareAndSave(record, existing?.revision)) {\n return resultFromRecord(record, policy);\n }\n }\n throw new Error(\n `Triage record for ${source.repository} item ${source.itemId} changed during ${MAX_TRIAGE_WRITE_CONFLICT_RETRIES + 1} consecutive updates`,\n );\n};\n\nexport { defaultInvestigator as defaultTriageInvestigator };\n"]}
@@ -0,0 +1,137 @@
1
+ // src/Output.ts
2
+ var Output = {
3
+ /**
4
+ * Declare an object-typed structured output extracted from an XML tag in
5
+ * the agent's stdout. The tag contents are JSON-parsed (with fence-aware
6
+ * unwrapping) and validated against the provided Standard Schema validator.
7
+ *
8
+ * Set `maxRetries` to have `run()` automatically resume the failed session
9
+ * and ask the agent to re-emit corrected output when extraction or
10
+ * validation fails. Default: `0` (no retries).
11
+ */
12
+ object: (opts) => ({
13
+ _tag: "object",
14
+ tag: opts.tag,
15
+ schema: opts.schema,
16
+ maxRetries: opts.maxRetries
17
+ }),
18
+ /**
19
+ * Declare a string-typed structured output extracted from an XML tag in
20
+ * the agent's stdout. The tag contents are whitespace-trimmed and returned
21
+ * as a plain string — no JSON parsing, no schema validation.
22
+ *
23
+ * Set `maxRetries` to have `run()` automatically resume the failed session
24
+ * and ask the agent to re-emit corrected output when extraction fails.
25
+ * Default: `0` (no retries).
26
+ */
27
+ string: (opts) => ({
28
+ _tag: "string",
29
+ tag: opts.tag,
30
+ maxRetries: opts.maxRetries
31
+ })
32
+ };
33
+ var StructuredOutputError = class extends Error {
34
+ tag;
35
+ rawMatched;
36
+ cause;
37
+ commits;
38
+ branch;
39
+ preservedWorktreePath;
40
+ /** Session ID of the iteration that produced the bad output, when available. */
41
+ sessionId;
42
+ /** Host path to the captured session JSONL, when the session was captured. */
43
+ sessionFilePath;
44
+ constructor(message, options) {
45
+ super(message);
46
+ this.name = "StructuredOutputError";
47
+ this.tag = options.tag;
48
+ this.rawMatched = options.rawMatched;
49
+ this.cause = options.cause;
50
+ this.commits = options.commits;
51
+ this.branch = options.branch;
52
+ this.preservedWorktreePath = options.preservedWorktreePath;
53
+ this.sessionId = options.sessionId;
54
+ this.sessionFilePath = options.sessionFilePath;
55
+ }
56
+ };
57
+
58
+ // src/extractStructuredOutput.ts
59
+ var extractStructuredOutput = async (stdout, definition, context) => {
60
+ if (definition._tag === "object") {
61
+ return extractObject(
62
+ stdout,
63
+ definition,
64
+ context
65
+ );
66
+ }
67
+ return extractString(stdout, definition, context);
68
+ };
69
+ var extractObject = async (stdout, definition, context) => {
70
+ const raw = findLastTagContent(stdout, definition.tag);
71
+ if (raw === void 0) {
72
+ throw new StructuredOutputError(
73
+ `Structured output tag <${definition.tag}> not found in agent output`,
74
+ { tag: definition.tag, rawMatched: void 0, ...context }
75
+ );
76
+ }
77
+ const unwrapped = unwrapFences(raw.trim());
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(unwrapped);
81
+ } catch (cause) {
82
+ throw new StructuredOutputError(
83
+ `Structured output tag <${definition.tag}> contains invalid JSON`,
84
+ { tag: definition.tag, rawMatched: raw, cause, ...context }
85
+ );
86
+ }
87
+ const result = await definition.schema["~standard"].validate(parsed);
88
+ if (result.issues) {
89
+ throw new StructuredOutputError(
90
+ `Structured output tag <${definition.tag}> failed schema validation`,
91
+ {
92
+ tag: definition.tag,
93
+ rawMatched: raw,
94
+ cause: result.issues,
95
+ ...context
96
+ }
97
+ );
98
+ }
99
+ return result.value;
100
+ };
101
+ var extractString = (stdout, definition, context) => {
102
+ const raw = findLastTagContent(stdout, definition.tag);
103
+ if (raw === void 0) {
104
+ throw new StructuredOutputError(
105
+ `Structured output tag <${definition.tag}> not found in agent output`,
106
+ { tag: definition.tag, rawMatched: void 0, ...context }
107
+ );
108
+ }
109
+ return raw.trim();
110
+ };
111
+ var findLastTagContent = (text, tag) => {
112
+ const openTag = `<${tag}>`;
113
+ const closeTag = `</${tag}>`;
114
+ let lastContent;
115
+ let searchFrom = 0;
116
+ while (true) {
117
+ const openIdx = text.indexOf(openTag, searchFrom);
118
+ if (openIdx === -1) break;
119
+ const contentStart = openIdx + openTag.length;
120
+ const closeIdx = text.indexOf(closeTag, contentStart);
121
+ if (closeIdx === -1) break;
122
+ lastContent = text.slice(contentStart, closeIdx);
123
+ searchFrom = closeIdx + closeTag.length;
124
+ }
125
+ return lastContent;
126
+ };
127
+ var unwrapFences = (text) => {
128
+ const fenceMatch = text.match(/^```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/);
129
+ if (fenceMatch) {
130
+ return fenceMatch[1].trim();
131
+ }
132
+ return text;
133
+ };
134
+
135
+ export { Output, StructuredOutputError, extractStructuredOutput };
136
+ //# sourceMappingURL=chunk-Z5C4LHVP.js.map
137
+ //# sourceMappingURL=chunk-Z5C4LHVP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Output.ts","../src/extractStructuredOutput.ts"],"names":[],"mappings":";AAkEO,IAAM,MAAA,GAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUpB,MAAA,EAAQ,CAAkC,IAAA,MAI2B;AAAA,IACnE,IAAA,EAAM,QAAA;AAAA,IACN,KAAK,IAAA,CAAK,GAAA;AAAA,IACV,QAAQ,IAAA,CAAK,MAAA;AAAA,IAIb,YAAY,IAAA,CAAK;AAAA,GACnB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAA,EAAQ,CAAC,IAAA,MAGsB;AAAA,IAC7B,IAAA,EAAM,QAAA;AAAA,IACN,KAAK,IAAA,CAAK,GAAA;AAAA,IACV,YAAY,IAAA,CAAK;AAAA,GACnB;AACF;AAiDO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EACtC,GAAA;AAAA,EACA,UAAA;AAAA,EACS,KAAA;AAAA,EACT,OAAA;AAAA,EACA,MAAA;AAAA,EACA,qBAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,eAAA;AAAA,EAET,WAAA,CAAY,SAAiB,OAAA,EAAuC;AAClE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AACZ,IAAA,IAAA,CAAK,MAAM,OAAA,CAAQ,GAAA;AACnB,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAC1B,IAAA,IAAA,CAAK,QAAQ,OAAA,CAAQ,KAAA;AACrB,IAAA,IAAA,CAAK,UAAU,O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IAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,UAAU,CAAA;AAChD,IAAA,IAAI,YAAY,EAAA,EAAI;AAEpB,IAAA,MAAM,YAAA,GAAe,UAAU,OAAA,CAAQ,MAAA;AACvC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,QAAA,EAAU,YAAY,CAAA;AACpD,IAAA,IAAI,aAAa,EAAA,EAAI;AAErB,IAAA,WAAA,GAAc,IAAA,CAAK,KAAA,CAAM,YAAA,EAAc,QAAQ,CAAA;AAC/C,IAAA,UAAA,GAAa,WAAW,QAAA,CAAS,MAAA;AAAA,EACnC;AAEA,EAAA,OAAO,WAAA;AACT,CAAA;AAeA,IAAM,YAAA,GAAe,CAAC,IAAA,KAAyB;AAE7C,EAAA,MAAM,UAAA,GAAa,IAAA,CAAK,KAAA,CAAM,0CAA0C,CAAA;AACxE,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,OAAO,UAAA,CAAW,CAAC,CAAA,CAAG,IAAA,EAAK;AAAA,EAC7B;AACA,EAAA,OAAO,IAAA;AACT,CAAA","file":"chunk-Z5C4LHVP.js","sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// ---------------------------------------------------------------------------\n// Output definition types (branded values for run() overload discrimination)\n// ---------------------------------------------------------------------------\n\n/** Branded output definition for `Output.object({ tag, schema })`. */\nexport interface OutputObjectDefinition<T> {\n readonly _tag: \"object\";\n readonly tag: string;\n readonly schema: StandardSchemaV1<unknown, T>;\n /**\n * Maximum number of additional attempts after the first if structured output\n * extraction or validation fails. Each retry resumes the failed run's agent\n * session and feeds back a token-efficient description of the error so the\n * agent can re-emit a corrected tag. Default: `0` (no retries).\n *\n * Retries require the agent provider to support session resumption (i.e.\n * `provider.sessionStorage` is populated — Codex or Claude Code). `run()`\n * fails at entry with a clear error when retries are requested but the\n * provider cannot resume.\n */\n readonly maxRetries?: number;\n}\n\n/** Branded output definition for `Output.string({ tag })`. */\nexport interface OutputStringDefinition {\n readonly _tag: \"string\";\n readonly tag: string;\n /**\n * Maximum number of additional attempts after the first if structured output\n * extraction fails. Each retry resumes the failed run's agent session and\n * feeds back a token-efficient description of the error so the agent can\n * re-emit a corrected tag. Default: `0` (no retries).\n *\n * Retries require the agent provider to support session resumption (i.e.\n * `provider.sessionStorage` is populated — Codex or Claude Code). `run()`\n * fails at entry with a clear error when retries are requested but the\n * provider cannot resume.\n */\n readonly maxRetries?: number;\n}\n\n/** Union of all output definition shapes accepted by `run()`. */\nexport type OutputDefinition =\n | OutputObjectDefinition<any>\n | OutputStringDefinition;\n\n// ---------------------------------------------------------------------------\n// Output namespace — public API\n// ---------------------------------------------------------------------------\n\n/**\n * Helpers for declaring structured output on `run()`.\n *\n * ```ts\n * import { Output, run } from \"@snappedly-tools/shipyard\";\n * import { z } from \"zod\";\n *\n * const result = await run({\n * output: Output.object({ tag: \"result\", schema: z.object({ answer: z.number() }) }),\n * // ...\n * });\n * console.log(result.output.answer); // typed as number\n * ```\n */\nexport const Output = {\n /**\n * Declare an object-typed structured output extracted from an XML tag in\n * the agent's stdout. The tag contents are JSON-parsed (with fence-aware\n * unwrapping) and validated against the provided Standard Schema validator.\n *\n * Set `maxRetries` to have `run()` automatically resume the failed session\n * and ask the agent to re-emit corrected output when extraction or\n * validation fails. Default: `0` (no retries).\n */\n object: <Schema extends StandardSchemaV1>(opts: {\n tag: string;\n schema: Schema;\n maxRetries?: number;\n }): OutputObjectDefinition<StandardSchemaV1.InferOutput<Schema>> => ({\n _tag: \"object\",\n tag: opts.tag,\n schema: opts.schema as StandardSchemaV1<\n unknown,\n StandardSchemaV1.InferOutput<Schema>\n >,\n maxRetries: opts.maxRetries,\n }),\n\n /**\n * Declare a string-typed structured output extracted from an XML tag in\n * the agent's stdout. The tag contents are whitespace-trimmed and returned\n * as a plain string — no JSON parsing, no schema validation.\n *\n * Set `maxRetries` to have `run()` automatically resume the failed session\n * and ask the agent to re-emit corrected output when extraction fails.\n * Default: `0` (no retries).\n */\n string: (opts: {\n tag: string;\n maxRetries?: number;\n }): OutputStringDefinition => ({\n _tag: \"string\",\n tag: opts.tag,\n maxRetries: opts.maxRetries,\n }),\n} as const;\n\n// ---------------------------------------------------------------------------\n// StructuredOutputError\n// ---------------------------------------------------------------------------\n\nexport interface StructuredOutputErrorOptions {\n readonly tag: string;\n readonly rawMatched: string | undefined;\n readonly cause?: unknown;\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n readonly sessionId?: string;\n readonly sessionFilePath?: string;\n}\n\n/**\n * Thrown by `run()` when structured output extraction or validation fails.\n *\n * Possible failure modes:\n * - The configured XML tag was not found in stdout (`rawMatched` is `undefined`).\n * - The tag contents failed `JSON.parse` (`cause` carries the parse error).\n * - The parsed JSON failed schema validation (`cause` carries the Standard Schema issues).\n *\n * The error carries `commits`, `branch`, and optionally `preservedWorktreePath`\n * so callers can decide recovery without losing the run's side effects.\n *\n * It also carries `sessionId` (and `sessionFilePath` when the session was\n * captured to the host) of the iteration that produced the bad output, so a\n * caller can resume that same session and ask the agent to re-emit corrected\n * output:\n *\n * ```ts\n * try {\n * return await run({ ...opts, output });\n * } catch (e) {\n * if (e instanceof StructuredOutputError && e.sessionId) {\n * return await run({\n * ...opts,\n * output,\n * resumeSession: e.sessionId,\n * prompt: feedback(e),\n * });\n * }\n * throw e;\n * }\n * ```\n */\nexport class StructuredOutputError extends Error {\n readonly tag: string;\n readonly rawMatched: string | undefined;\n override readonly cause: unknown;\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n /** Session ID of the iteration that produced the bad output, when available. */\n readonly sessionId?: string;\n /** Host path to the captured session JSONL, when the session was captured. */\n readonly sessionFilePath?: string;\n\n constructor(message: string, options: StructuredOutputErrorOptions) {\n super(message);\n this.name = \"StructuredOutputError\";\n this.tag = options.tag;\n this.rawMatched = options.rawMatched;\n this.cause = options.cause;\n this.commits = options.commits;\n this.branch = options.branch;\n this.preservedWorktreePath = options.preservedWorktreePath;\n this.sessionId = options.sessionId;\n this.sessionFilePath = options.sessionFilePath;\n }\n}\n","import {\n StructuredOutputError,\n type OutputDefinition,\n type OutputObjectDefinition,\n type OutputStringDefinition,\n} from \"./Output.js\";\n\ninterface ExtractionContext {\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n readonly sessionId?: string;\n readonly sessionFilePath?: string;\n}\n\n/**\n * Extract and validate structured output from the agent's stdout.\n *\n * - Finds the **last** occurrence of `<tag>...</tag>` in stdout.\n * - For `Output.object`: unwraps optional Markdown fences, JSON-parses,\n * and validates against the Standard Schema.\n * - For `Output.string`: trims whitespace only.\n *\n * Throws `StructuredOutputError` on missing tag, invalid JSON, or schema failure.\n */\nexport const extractStructuredOutput = async <T>(\n stdout: string,\n definition: OutputDefinition,\n context: ExtractionContext,\n): Promise<T> => {\n if (definition._tag === \"object\") {\n return extractObject(\n stdout,\n definition as OutputObjectDefinition<T>,\n context,\n );\n }\n return extractString(stdout, definition, context) as T;\n};\n\n// ---------------------------------------------------------------------------\n// Object extraction\n// ---------------------------------------------------------------------------\n\nconst extractObject = async <T>(\n stdout: string,\n definition: OutputObjectDefinition<T>,\n context: ExtractionContext,\n): Promise<T> => {\n const raw = findLastTagContent(stdout, definition.tag);\n\n if (raw === undefined) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> not found in agent output`,\n { tag: definition.tag, rawMatched: undefined, ...context },\n );\n }\n\n // Fence-aware unwrap + JSON parse\n const unwrapped = unwrapFences(raw.trim());\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(unwrapped);\n } catch (cause) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> contains invalid JSON`,\n { tag: definition.tag, rawMatched: raw, cause, ...context },\n );\n }\n\n // Standard Schema validation\n const result = await definition.schema[\"~standard\"].validate(parsed);\n\n if (result.issues) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> failed schema validation`,\n {\n tag: definition.tag,\n rawMatched: raw,\n cause: result.issues,\n ...context,\n },\n );\n }\n\n return result.value;\n};\n\n// ---------------------------------------------------------------------------\n// String extraction\n// ---------------------------------------------------------------------------\n\nconst extractString = (\n stdout: string,\n definition: OutputStringDefinition,\n context: ExtractionContext,\n): string => {\n const raw = findLastTagContent(stdout, definition.tag);\n\n if (raw === undefined) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> not found in agent output`,\n { tag: definition.tag, rawMatched: undefined, ...context },\n );\n }\n\n return raw.trim();\n};\n\n// ---------------------------------------------------------------------------\n// Tag extraction — last match wins\n// ---------------------------------------------------------------------------\n\n/**\n * Find the content between the **last** `<tag>` and `</tag>` pair in text.\n * Returns `undefined` if the tag is not found.\n */\nconst findLastTagContent = (text: string, tag: string): string | undefined => {\n const openTag = `<${tag}>`;\n const closeTag = `</${tag}>`;\n\n let lastContent: string | undefined;\n let searchFrom = 0;\n\n while (true) {\n const openIdx = text.indexOf(openTag, searchFrom);\n if (openIdx === -1) break;\n\n const contentStart = openIdx + openTag.length;\n const closeIdx = text.indexOf(closeTag, contentStart);\n if (closeIdx === -1) break;\n\n lastContent = text.slice(contentStart, closeIdx);\n searchFrom = closeIdx + closeTag.length;\n }\n\n return lastContent;\n};\n\n// ---------------------------------------------------------------------------\n// Fence-aware unwrap (object mode only)\n// ---------------------------------------------------------------------------\n\n/**\n * Strip an optional Markdown code fence from text.\n *\n * Recognises:\n * - ` ```json\\n...\\n``` `\n * - ` ```\\n...\\n``` `\n *\n * If no fence is detected, returns the input unchanged (already trimmed by caller).\n */\nconst unwrapFences = (text: string): string => {\n // Match ```json ... ``` or ``` ... ``` (with optional language hint)\n const fenceMatch = text.match(/^```(?:json)?\\s*\\n([\\s\\S]*?)\\n\\s*```\\s*$/);\n if (fenceMatch) {\n return fenceMatch[1]!.trim();\n }\n return text;\n};\n"]}