2026-11-11 04:29:18 +00:00
package runner
import (
"context"
2026-11-16 14:42:24 +00:00
"errors"
2026-11-11 04:29:18 +00:00
"fmt"
2026-11-11 12:28:42 +00:00
"slices"
2026-11-11 04:29:18 +00:00
2026-11-17 04:22:20 +00:00
"gitea.maximumdirect.net/eric/audita/v3/internal/core/jsonnumber"
2026-11-11 04:29:18 +00:00
"gitea.maximumdirect.net/eric/audita/v3/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v3/internal/framework/proposal_generation"
"gitea.maximumdirect.net/eric/audita/v3/internal/framework/proposals"
"gitea.maximumdirect.net/eric/audita/v3/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v3/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v3/internal/framework/validators"
)
2026-11-11 12:31:08 +00:00
// RepairAttempt holds optional debug evidence for one semantic request.
2026-11-11 04:29:18 +00:00
type RepairAttempt struct {
2026-11-16 03:43:29 +00:00
Artifacts structuredoutput . InteractionArtifacts
2026-11-11 04:29:18 +00:00
Revision * proposals . EnrichedCorrectionProposal
Decisions [ ] ValidatorDecisionRecord
FailureReason outcomes . ReasonCode
}
2026-11-11 12:31:08 +00:00
// RepairOutcome summarizes the branch and carries its lineage when debug is enabled.
2026-11-11 04:29:18 +00:00
type RepairOutcome struct {
ProposalIndex int
2026-11-11 12:31:08 +00:00
AttemptCount int
2026-11-11 04:29:18 +00:00
Outcome string
2026-11-11 12:31:08 +00:00
Attempts [ ] RepairAttempt
2026-11-11 04:29:18 +00:00
Original proposals . EnrichedCorrectionProposal
Final proposals . EnrichedCorrectionProposal
}
func actionable ( index int , rejected [ ] ValidatorRejectedChange ) bool {
found := false
for _ , decision := range rejected {
if decision . ProposalIndex != index {
continue
}
if decision . ReasonCode == validators . ReasonNoEffect {
return false
}
if decision . Disposition != validators . DispositionUnavailable {
found = true
}
}
return found
}
// repairCandidates branches each rejected proposal from the same section exchange.
func repairCandidates ( ctx context . Context , input validateSectionCandidatesInput , references [ ] int , initial validateSectionCandidatesResult , promptID string ) ( validateSectionCandidatesResult , [ ] RepairOutcome , error ) {
2026-11-16 14:36:07 +00:00
if input . Spec . Settings . LLM . CorrectionRepairAttempts <= 0 || len ( initial . rejected ) == 0 {
2026-11-11 04:29:18 +00:00
return initial , nil , nil
}
2026-11-11 17:42:30 +00:00
if input . Section == nil {
input . Section = validators . NewSectionLookup ( input . WorkingTranscript )
}
2026-11-11 12:28:42 +00:00
initialFindings := make ( map [ int ] [ ] ValidatorRejectedChange )
for _ , decision := range initial . rejected {
initialFindings [ decision . ProposalIndex ] = append ( initialFindings [ decision . ProposalIndex ] , decision )
}
superseded := make ( map [ int ] bool )
2026-11-11 04:29:18 +00:00
var branches [ ] RepairOutcome
2026-11-11 12:28:42 +00:00
finish := func ( err error ) ( validateSectionCandidatesResult , [ ] RepairOutcome , error ) {
if len ( superseded ) > 0 {
initial . filtered = slices . DeleteFunc ( initial . filtered , func ( item outcomes . FilteredProposal ) bool {
return superseded [ item . ProposalIndex ]
} )
}
return initial , branches , err
}
2026-11-11 04:29:18 +00:00
for position , original := range input . SectionEnriched {
2026-11-11 12:28:42 +00:00
rejected := initialFindings [ original . ProposalIndex ]
if ! actionable ( original . ProposalIndex , rejected ) {
2026-11-11 04:29:18 +00:00
continue
}
2026-11-16 14:36:07 +00:00
localRef := 0
if position < len ( references ) {
localRef = references [ position ]
} else if pos , ok := input . Section . Position ( original . TargetSegmentID ) ; ok {
localRef = pos + 1
2026-11-11 12:31:08 +00:00
}
2026-11-16 14:36:07 +00:00
result , err := runRepairBranch ( ctx , repairBranchInput {
validation : input ,
original : original ,
proposalRef : position + 1 ,
segmentRef : localRef ,
rejected : rejected ,
promptID : promptID ,
} )
branches = append ( branches , result . outcome )
initial . operations = append ( initial . operations , result . operations ... )
if result . approved != nil {
initial . approved = append ( initial . approved , * result . approved )
superseded [ original . ProposalIndex ] = true
}
if err != nil {
2026-11-11 12:28:42 +00:00
return finish ( err )
2026-11-11 04:29:18 +00:00
}
2026-11-16 14:36:07 +00:00
}
return finish ( nil )
}
type repairBranchInput struct {
validation validateSectionCandidatesInput
original proposals . EnrichedCorrectionProposal
proposalRef int
segmentRef int
rejected [ ] ValidatorRejectedChange
promptID string
}
type repairBranchResult struct {
outcome RepairOutcome
operations [ ] outcomes . Operation
approved * proposals . EnrichedCorrectionProposal
}
func runRepairBranch ( ctx context . Context , branchInput repairBranchInput ) ( repairBranchResult , error ) {
input , original := branchInput . validation , branchInput . original
result := repairBranchResult { outcome : RepairOutcome { ProposalIndex : original . ProposalIndex , Outcome : "interrupted" } }
branch := & result . outcome
debug := input . Interactions != nil
if debug {
branch . Original , branch . Final = original , original
}
if err := ctx . Err ( ) ; err != nil {
return result , err
}
if input . Spec . RepairCoordinator == nil || input . Exchange == nil || branchInput . promptID == "" {
return result , & structuredoutput . Failure { Class : outcomes . FailureFatal , Reason : outcomes . ReasonSetupFailure , Message : "correction repair exchange or setup is unavailable" }
}
section := 0
if input . SectionIndex != nil {
section = * input . SectionIndex
}
localRef := branchInput . segmentRef
proposalRef := branchInput . proposalRef
promptID := branchInput . promptID
current := original
findings := repairFindings ( original . ProposalIndex , branchInput . rejected )
2026-11-17 04:29:02 +00:00
var history repairHistory
2026-11-16 14:36:07 +00:00
buildRequest := func ( ) ( * structuredoutput . Request , error ) {
request := proposal_generation . RepairRequest {
ProposalRef : proposalRef ,
2026-11-17 04:22:20 +00:00
Correction : proposal_generation . StructuredCorrectionProposal { SegmentReference : jsonnumber . Integer ( localRef ) , OriginalText : current . OriginalText , CorrectedText : current . CorrectedText } ,
2026-11-16 14:36:07 +00:00
Findings : findings ,
2026-11-11 04:29:18 +00:00
}
2026-11-16 14:36:07 +00:00
if pos , ok := input . Section . Position ( current . TargetSegmentID ) ; ok {
segment := & input . WorkingTranscript . Segments [ pos ]
request . OriginalSegmentText = & segment . Text
preview := proposals . PreviewProposalForSegment ( segment , current . CorrectionProposal , input . Policy )
if preview . Applicable {
request . CorrectedSegmentText = & preview . CorrectedSegmentText
2026-11-11 04:29:18 +00:00
}
}
2026-11-16 14:36:07 +00:00
payload , err := request . JSON ( )
if err != nil {
return nil , err
2026-11-15 01:25:55 +00:00
}
2026-11-16 14:36:07 +00:00
proposalIndex , attemptNumber := original . ProposalIndex , branch . AttemptCount + 1
2026-11-16 15:08:02 +00:00
return & structuredoutput . Request { PromptID : promptID , Variables : map [ string ] string { "RepairRequestJSON" : payload } , Schema : responseschema . CorrectionRepairKey , CaptureDiagnostics : debug , Context : structuredoutput . DiagnosticContext { StageIndex : & input . Spec . Index , StageID : input . Spec . ID , Role : "correction_repair" , ModuleKey : input . Spec . ModuleKey , ModuleInstance : input . Spec . InstanceName , SectionIndex : input . SectionIndex , ProposalIndex : & proposalIndex , RepairAttempt : & attemptNumber } } , nil
2026-11-16 14:36:07 +00:00
}
exhausted , coordinationErr := input . Spec . RepairCoordinator . Coordinate ( ctx , input . Exchange , input . Spec . Settings . LLM . CorrectionRepairAttempts , func ( ctx context . Context , turn structuredoutput . Turn ) ( * structuredoutput . Request , error ) {
if turn . Response == nil {
return buildRequest ( )
2026-11-15 01:25:55 +00:00
}
2026-11-16 14:36:07 +00:00
completion , callErr := turn . Response , turn . Err
proposalIndex , attemptNumber := original . ProposalIndex , branch . AttemptCount + 1
var response proposal_generation . RepairResponse
2026-11-15 01:25:55 +00:00
2026-11-16 14:36:07 +00:00
operation := outcomes . Operation {
Reference : outcomes . Reference {
StageIndex : & input . Spec . Index , StageID : input . Spec . ID , ModuleKey : input . Spec . ModuleKey ,
ModuleInstance : input . Spec . InstanceName , SectionIndex : section , Kind : outcomes . OperationCorrectionRepair ,
ProposalIndex : & proposalIndex , RepairAttempt : & attemptNumber ,
} ,
Counts : completion . Execution , ProposalIndices : [ ] int { proposalIndex } ,
}
finishAttempt := func ( err error , revision * proposals . EnrichedCorrectionProposal , validated validateSectionCandidatesResult ) {
branch . AttemptCount ++
result . operations = append ( result . operations , operation )
if ! debug {
return
2026-11-11 04:37:52 +00:00
}
2026-11-16 14:36:07 +00:00
record := RepairAttempt { Decisions : validated . decisions , FailureReason : operation . FailureReason }
if revision != nil {
snapshot := * revision
record . Revision = & snapshot
2026-11-11 04:29:18 +00:00
}
2026-11-16 14:53:14 +00:00
feedback := findings
2026-11-17 04:29:02 +00:00
prepared := history . retain ( completion . Prepared )
prompt , finalContent := completion . Prompt , completion . FinalContent
2026-11-16 14:53:14 +00:00
record . Artifacts , _ = structuredoutput . WriteIndexedInteraction ( input . Interactions , func ( offset int , resolvePath func ( string ) string ) structuredoutput . Interaction {
index := proposalIndex + offset
name := fmt . Sprintf ( "%s:section-%04d:proposal-%04d:attempt-%04d:repair" , input . Spec . InstanceName , section , index , attemptNumber )
var failure any
if err != nil {
failure = map [ string ] string { "error" : err . Error ( ) }
}
var correction * proposals . EnrichedCorrectionProposal
if record . Revision != nil {
snapshot := * record . Revision
snapshot . ProposalIndex = index
correction = & snapshot
}
decisions := slices . Clone ( validated . decisions )
for i := range decisions {
decisions [ i ] . ProposalIndex += offset
decisions [ i ] . DiagnosticArtifactPath = resolvePath ( decisions [ i ] . DiagnosticArtifactPath )
}
rejections := slices . Clone ( validated . rejected )
for i := range rejections {
rejections [ i ] . ProposalIndex += offset
}
return structuredoutput . Interaction {
Name : name ,
Context : structuredoutput . DiagnosticContext { StageIndex : & input . Spec . Index , StageID : input . Spec . ID , Role : "correction_repair" , ModuleKey : input . Spec . ModuleKey , ModuleInstance : input . Spec . InstanceName , SectionIndex : input . SectionIndex , ProposalIndex : & index , RepairAttempt : & attemptNumber } ,
2026-11-17 04:29:02 +00:00
RequestMetadata : map [ string ] any { "stage_index" : input . Spec . Index , "stage_id" : input . Spec . ID , "proposal_index" : index , "repair_attempt" : attemptNumber , "prompt_id" : promptID , "prompt" : prompt , "feedback" : feedback } ,
RequestPayload : prepared ,
ResponsePayload : map [ string ] any { "decoded" : response , "final_content" : finalContent , "revision" : correction , "decisions" : decisions , "rejections" : rejections } ,
2026-11-16 14:53:14 +00:00
ErrorPayload : failure ,
}
2026-11-16 14:36:07 +00:00
} )
branch . Attempts = append ( branch . Attempts , record )
}
if callErr != nil {
structuredoutput . RecordFailure ( & operation , callErr )
finishAttempt ( callErr , nil , validateSectionCandidatesResult { } )
if operation . FailureClass == outcomes . FailureRecoverable {
branch . Outcome = "unavailable"
2026-11-15 01:25:55 +00:00
return nil , nil
2026-11-11 04:29:18 +00:00
}
2026-11-16 14:36:07 +00:00
return nil , callErr
}
var err error
response , err = proposal_generation . DecodeRepairResponse ( completion . Content , proposalRef )
if err != nil {
structuredoutput . RecordFailure ( & operation , err )
finishAttempt ( err , nil , validateSectionCandidatesResult { } )
2026-11-11 04:29:18 +00:00
branch . Outcome = "unavailable"
2026-11-15 01:25:55 +00:00
return nil , nil
2026-11-11 04:29:18 +00:00
}
2026-11-16 14:36:07 +00:00
operation . Succeeded = true
operation . RecoveryReasons = outcomes . ExecutionRecoveries ( operation . Counts )
if response . Decision . Action == "withdraw" {
finishAttempt ( nil , nil , validateSectionCandidatesResult { } )
branch . Outcome = "withdrawn"
return nil , nil
2026-11-15 01:25:55 +00:00
}
2026-11-16 14:36:07 +00:00
revision := response . Decision . Correction
2026-11-17 04:22:20 +00:00
localRef = int ( revision . SegmentReference )
2026-11-16 14:36:07 +00:00
current = original
current . CorrectionProposal = proposals . CorrectionProposal { TargetSegmentID : proposals . SegmentIDAtReference ( input . WorkingTranscript , localRef ) , OriginalText : revision . OriginalText , CorrectedText : revision . CorrectedText }
if debug {
branch . Final = current
}
next := input
next . RepairProposalIndex , next . RepairAttempt = & proposalIndex , & attemptNumber
next . SectionEnriched = [ ] proposals . EnrichedCorrectionProposal { current }
validated , validationErr := validateSectionCandidates ( ctx , next )
if len ( validated . filtered ) > 0 {
// Each repair response contains only one proposal.
operation . Filtered = validated . filtered [ : 1 ]
operation . RecoveryReasons = append ( operation . RecoveryReasons , outcomes . RecoveryProposalsFiltered )
}
for i := range validated . operations {
validated . operations [ i ] . Reference . ProposalIndex = & proposalIndex
validated . operations [ i ] . Reference . RepairAttempt = & attemptNumber
}
approved := validationErr == nil && len ( validated . approved ) == 1
if approved {
operation . RecoveryReasons = append ( operation . RecoveryReasons , outcomes . RecoveryCorrectionRevised )
}
result . operations = append ( result . operations , validated . operations ... )
finishAttempt ( validationErr , & current , validated )
if validationErr != nil {
return nil , validationErr
}
if approved {
branch . Outcome = "approved"
2026-11-17 04:34:31 +00:00
revision := validated . approved [ 0 ]
result . approved = & revision
2026-11-16 14:36:07 +00:00
return nil , nil
}
if actionable ( original . ProposalIndex , validated . rejected ) {
findings = repairFindings ( original . ProposalIndex , validated . rejected )
return buildRequest ( )
}
branch . Outcome = "unavailable"
for _ , d := range validated . rejected {
if d . Disposition != validators . DispositionUnavailable {
branch . Outcome = "rejected"
return nil , nil
}
}
return nil , nil
} )
if coordinationErr != nil {
branch . Outcome = "interrupted"
result . approved = nil
2026-11-16 14:42:24 +00:00
var failure * ExecutionFailure
if ! errors . As ( coordinationErr , & failure ) {
ref := failureReference ( input . Spec , input . SectionIndex , outcomes . OperationCorrectionRepair )
ref . ProposalIndex = & original . ProposalIndex
coordinationErr = locateFailure ( coordinationErr , "correction_repair" , ref , input . SectionIndex != nil , result . operations )
}
2026-11-16 14:36:07 +00:00
} else if exhausted {
branch . Outcome = "exhausted"
2026-11-11 04:29:18 +00:00
}
2026-11-16 14:36:07 +00:00
return result , coordinationErr
2026-11-11 04:29:18 +00:00
}