Separate trim bounds and transcript acceptance
This commit is contained in:
@@ -7,11 +7,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/seriatim"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/contracts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
)
|
||||
@@ -70,281 +67,59 @@ func (trimStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*Stag
|
||||
return nil, fmt.Errorf("trim: resolve run-local trimmed output path: %w", err)
|
||||
}
|
||||
|
||||
logPaths := []string{}
|
||||
generatedConfigs := []string{}
|
||||
metadata := map[string]any{
|
||||
"stage": "trim",
|
||||
"trim_enabled": enabled,
|
||||
"normalized_transcript_path": normalizedPath,
|
||||
"normalized_transcript_source": normalizedSource,
|
||||
"run_trimmed_output_path": trimmedPath,
|
||||
"trimmed_output_path": canonicalTrimmedPath,
|
||||
"stage": "trim", "trim_enabled": enabled,
|
||||
"normalized_transcript_path": normalizedPath, "normalized_transcript_source": normalizedSource,
|
||||
"run_trimmed_output_path": trimmedPath, "trimmed_output_path": canonicalTrimmedPath,
|
||||
}
|
||||
|
||||
var bounds *trimBoundsResult
|
||||
var transcript *trimTranscriptResult
|
||||
if !enabled {
|
||||
if err := copyTranscript(env.ArtifactStore, normalizedPath, trimmedPath); err != nil {
|
||||
return nil, fmt.Errorf("trim: copy normalized transcript to trimmed output: %w", err)
|
||||
}
|
||||
if err := validateProcessedTranscriptOutput(trimmedPath); err != nil {
|
||||
return nil, fmt.Errorf("trim: copied trimmed transcript %q invalid: %w", trimmedPath, err)
|
||||
}
|
||||
materializedTrimmed, err := materializeRunLocalOutput(env.ArtifactStore, trimmedPath, canonicalTrimmedPath, artifacts.Ref{
|
||||
Kind: "transcript_final_trimmed",
|
||||
Category: "transcripts",
|
||||
SessionID: sessionID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: materialize canonical final trimmed transcript: %w", err)
|
||||
}
|
||||
metadata["trim_action"] = "copy_disabled"
|
||||
return &StageResult{
|
||||
Outputs: []artifacts.Ref{materializedTrimmed},
|
||||
Metadata: metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if env.Scriptorium == nil {
|
||||
return nil, fmt.Errorf("trim: scriptorium adapter is required when trim is enabled")
|
||||
}
|
||||
if env.Seriatim == nil {
|
||||
return nil, fmt.Errorf("trim: seriatim adapter is required when trim is enabled")
|
||||
}
|
||||
if env.Config.Pipeline.Scriptorium == nil {
|
||||
return nil, fmt.Errorf("trim: pipeline.scriptorium is required when trim is enabled")
|
||||
}
|
||||
|
||||
boundsCfg := trimCfg.Bounds
|
||||
canonicalBoundsOutputPath, err := resolveScriptoriumOutputPath(paths, boundsCfg.OutputPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: resolve bounds output path: %w", err)
|
||||
}
|
||||
boundsOutputPath, err := runLocalPathForCanonical(runLayout, paths, canonicalBoundsOutputPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: resolve run-local bounds output path: %w", err)
|
||||
}
|
||||
boundsStderrLogPath := filepath.Join(runLayout.LogsDir, "scriptorium.bounds.stderr.log")
|
||||
boundsGeneratedConfigPath := filepath.Join(runLayout.LogsDir, "scriptorium.bounds.generated.yml")
|
||||
requestContext, err := TrimScriptoriumContext(env.Config, sessionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: resolve bounds request: %w", err)
|
||||
}
|
||||
boundsTimeout := requestContext.Timeout
|
||||
|
||||
inputPaths := map[string]string{
|
||||
boundsCfg.TranscriptInputName: normalizedPath,
|
||||
}
|
||||
vars := requestContext.Vars
|
||||
|
||||
metadata["bounds_prompt_id"] = boundsCfg.PromptID
|
||||
metadata["bounds_profile_id"] = boundsCfg.ProfileID
|
||||
metadata["run_bounds_output_path"] = boundsOutputPath
|
||||
metadata["bounds_output_path"] = canonicalBoundsOutputPath
|
||||
metadata["bounds_timeout"] = boundsTimeout.String()
|
||||
metadata["bounds_input_name"] = boundsCfg.TranscriptInputName
|
||||
metadata["bounds_input_path"] = normalizedPath
|
||||
metadata["bounds_render_debug_enabled"] = boundsCfg.RenderDebug
|
||||
|
||||
renderOutputPath := ""
|
||||
if boundsCfg.RenderDebug {
|
||||
filename := filepath.Base(strings.TrimSpace(boundsCfg.RenderOutputPath))
|
||||
if filename == "." || filename == ".." || strings.ContainsAny(filename, `/\\`) {
|
||||
return nil, fmt.Errorf("trim: bounds render output must name a file")
|
||||
}
|
||||
renderOutputPath = filepath.Join(runLayout.DebugDir, filename)
|
||||
renderStderrLogPath := filepath.Join(runLayout.LogsDir, "scriptorium.bounds.render.stderr.log")
|
||||
renderGeneratedConfigPath := filepath.Join(runLayout.LogsDir, "scriptorium.bounds.render.generated.yml")
|
||||
|
||||
renderReq := scriptorium.RenderArtifactRequest{
|
||||
Binary: requestContext.Binary,
|
||||
ConfigPath: requestContext.ConfigPath,
|
||||
Credentials: requestContext.Credentials,
|
||||
PromptID: requestContext.PromptID,
|
||||
ProfileID: requestContext.ProfileID,
|
||||
InputPaths: inputPaths,
|
||||
Vars: vars,
|
||||
OutputPath: renderOutputPath,
|
||||
StderrLogPath: renderStderrLogPath,
|
||||
GeneratedConfigPath: renderGeneratedConfigPath,
|
||||
Timeout: boundsTimeout,
|
||||
}
|
||||
renderRes, renderErr := env.Scriptorium.RenderArtifact(ctx, renderReq)
|
||||
if renderErr != nil {
|
||||
return nil, fmt.Errorf("trim: scriptorium bounds render failed: %w", renderErr)
|
||||
}
|
||||
if renderRes.ValidationFailed {
|
||||
return nil, fmt.Errorf("trim: scriptorium bounds render returned validation_failed=true")
|
||||
}
|
||||
finalRenderOutputPath, err := authoritativeOutputPath(renderReq.OutputPath, renderRes.OutputPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: %w", err)
|
||||
}
|
||||
if err := requireNonEmptyFile(finalRenderOutputPath, "bounds render output"); err != nil {
|
||||
return nil, fmt.Errorf("trim: %w", err)
|
||||
}
|
||||
if err := validateJSONFile(finalRenderOutputPath); err != nil {
|
||||
return nil, fmt.Errorf("trim: bounds render diagnostics %q invalid json: %w", finalRenderOutputPath, err)
|
||||
}
|
||||
|
||||
logPaths = append(logPaths, renderStderrLogPath, finalRenderOutputPath)
|
||||
generatedConfigs = append(generatedConfigs, renderGeneratedConfigPath)
|
||||
metadata["bounds_render_output_path"] = finalRenderOutputPath
|
||||
metadata["bounds_render_stderr_log_path"] = renderStderrLogPath
|
||||
metadata["bounds_render_generated_config_path"] = renderGeneratedConfigPath
|
||||
metadata["bounds_render_adapter_exit_code"] = renderRes.ExitCode
|
||||
metadata["bounds_render_adapter_duration_ms"] = renderRes.Duration.Milliseconds()
|
||||
metadata["bounds_render_adapter_command_mode"] = renderRes.CommandMode
|
||||
if renderRes.Metadata != nil {
|
||||
metadata["bounds_render_adapter_metadata"] = renderRes.Metadata
|
||||
}
|
||||
}
|
||||
|
||||
boundsReq := scriptorium.RunArtifactRequest{
|
||||
Binary: requestContext.Binary,
|
||||
ConfigPath: requestContext.ConfigPath,
|
||||
Credentials: requestContext.Credentials,
|
||||
PromptID: requestContext.PromptID,
|
||||
ProfileID: requestContext.ProfileID,
|
||||
InputPaths: inputPaths,
|
||||
Vars: vars,
|
||||
OutputPath: boundsOutputPath,
|
||||
StderrLogPath: boundsStderrLogPath,
|
||||
GeneratedConfigPath: boundsGeneratedConfigPath,
|
||||
Timeout: boundsTimeout,
|
||||
}
|
||||
|
||||
boundsRes, boundsRunErr := env.Scriptorium.RunArtifact(ctx, boundsReq)
|
||||
if boundsRunErr != nil {
|
||||
if boundsRes.ValidationFailed {
|
||||
return nil, fmt.Errorf(
|
||||
"trim: scriptorium bounds validation failed (prompt_id=%q, output_path=%q, exit_code=%d, stderr_log=%q): %w",
|
||||
boundsReq.PromptID,
|
||||
boundsReq.OutputPath,
|
||||
boundsRes.ExitCode,
|
||||
coalesceString(boundsRes.StderrLogPath, boundsReq.StderrLogPath),
|
||||
boundsRunErr,
|
||||
)
|
||||
}
|
||||
return nil, fmt.Errorf("trim: scriptorium bounds generation failed: %w", boundsRunErr)
|
||||
}
|
||||
if boundsRes.ValidationFailed {
|
||||
return nil, fmt.Errorf("trim: scriptorium bounds run returned validation_failed=true")
|
||||
}
|
||||
|
||||
finalBoundsOutputPath, err := authoritativeOutputPath(boundsReq.OutputPath, boundsRes.OutputPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: %w", err)
|
||||
}
|
||||
if err := requireNonEmptyFile(finalBoundsOutputPath, "session bounds output"); err != nil {
|
||||
return nil, fmt.Errorf("trim: %w", err)
|
||||
}
|
||||
|
||||
boundsPayload, err := contracts.ParseSessionBoundsFile(finalBoundsOutputPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: parse bounds output %q: %w", finalBoundsOutputPath, err)
|
||||
}
|
||||
if err := contracts.ValidateSessionBoundsAgainstTranscript(boundsPayload, normalizedPath); err != nil {
|
||||
return nil, fmt.Errorf("trim: validate bounds output %q against transcript %q: %w", finalBoundsOutputPath, normalizedPath, err)
|
||||
}
|
||||
|
||||
keepSelector, copyUnchanged, err := contracts.BuildSeriatimKeepSelector(boundsPayload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: build keep selector from bounds output: %w", err)
|
||||
}
|
||||
trimAction := strings.ToLower(strings.TrimSpace(boundsPayload.TrimAction))
|
||||
if trimAction == "" {
|
||||
trimAction = "trim"
|
||||
}
|
||||
|
||||
logPaths = append(logPaths, boundsStderrLogPath)
|
||||
generatedConfigs = append(generatedConfigs, boundsGeneratedConfigPath)
|
||||
metadata["bounds_confidence"] = boundsPayload.Confidence
|
||||
metadata["trim_action"] = trimAction
|
||||
metadata["start_segment_id"] = boundsPayload.StartSegmentID
|
||||
metadata["end_segment_id"] = boundsPayload.EndSegmentID
|
||||
metadata["warnings"] = boundsPayload.Warnings
|
||||
metadata["keep_selector"] = keepSelector
|
||||
metadata["run_bounds_output_path"] = finalBoundsOutputPath
|
||||
metadata["bounds_stderr_log_path"] = boundsStderrLogPath
|
||||
metadata["bounds_generated_config_path"] = boundsGeneratedConfigPath
|
||||
metadata["bounds_adapter_exit_code"] = boundsRes.ExitCode
|
||||
metadata["bounds_adapter_duration_ms"] = boundsRes.Duration.Milliseconds()
|
||||
metadata["bounds_adapter_command_mode"] = boundsRes.CommandMode
|
||||
metadata["bounds_adapter_prompt_id"] = boundsRes.PromptID
|
||||
metadata["bounds_adapter_profile_id"] = boundsRes.ProfileID
|
||||
metadata["bounds_adapter_output_path"] = boundsRes.OutputPath
|
||||
metadata["bounds_adapter_generated_config"] = boundsRes.GeneratedConfigPath
|
||||
metadata["bounds_adapter_stderr_log_path"] = boundsRes.StderrLogPath
|
||||
if boundsRes.Metadata != nil {
|
||||
metadata["bounds_adapter_metadata"] = boundsRes.Metadata
|
||||
}
|
||||
|
||||
if copyUnchanged {
|
||||
if err := copyTranscript(env.ArtifactStore, normalizedPath, trimmedPath); err != nil {
|
||||
return nil, fmt.Errorf("trim: copy normalized transcript to trimmed output: %w", err)
|
||||
}
|
||||
} else {
|
||||
trimStdoutLogPath := filepath.Join(runLayout.LogsDir, "seriatim.trim.stdout.log")
|
||||
trimStderrLogPath := filepath.Join(runLayout.LogsDir, "seriatim.trim.stderr.log")
|
||||
trimGeneratedConfigPath := filepath.Join(runLayout.LogsDir, "seriatim.trim.generated.yml")
|
||||
trimTimeout, err := resolveSeriatimStageTimeout(env.Config.Pipeline.Seriatim.Timeout)
|
||||
if env.Scriptorium == nil {
|
||||
return nil, fmt.Errorf("trim: scriptorium adapter is required when trim is enabled")
|
||||
}
|
||||
if env.Seriatim == nil {
|
||||
return nil, fmt.Errorf("trim: seriatim adapter is required when trim is enabled")
|
||||
}
|
||||
if env.Config.Pipeline.Scriptorium == nil {
|
||||
return nil, fmt.Errorf("trim: pipeline.scriptorium is required when trim is enabled")
|
||||
}
|
||||
generated, err := generateTrimBounds(ctx, env, paths, runLayout, sessionID, normalizedPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: resolve seriatim timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
trimReq := seriatim.TrimRequest{
|
||||
Binary: env.Config.Pipeline.Seriatim.Binary,
|
||||
InputTranscriptPath: normalizedPath,
|
||||
OutputTrimmedPath: trimmedPath,
|
||||
KeepSelector: keepSelector,
|
||||
StdoutLogPath: trimStdoutLogPath,
|
||||
StderrLogPath: trimStderrLogPath,
|
||||
GeneratedConfigPath: trimGeneratedConfigPath,
|
||||
Timeout: trimTimeout,
|
||||
generated, err = selectTrimBounds(generated, normalizedPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
trimRes, trimErr := env.Seriatim.Trim(ctx, trimReq)
|
||||
if trimErr != nil {
|
||||
return nil, fmt.Errorf("trim: seriatim trim failed: %w", trimErr)
|
||||
}
|
||||
logPaths = append(logPaths, trimStdoutLogPath, trimStderrLogPath)
|
||||
generatedConfigs = append(generatedConfigs, trimGeneratedConfigPath)
|
||||
metadata["seriatim_trim_stdout_log_path"] = trimStdoutLogPath
|
||||
metadata["seriatim_trim_stderr_log_path"] = trimStderrLogPath
|
||||
metadata["seriatim_trim_generated_config_path"] = trimGeneratedConfigPath
|
||||
metadata["seriatim_trim_exit_code"] = trimRes.ExitCode
|
||||
metadata["seriatim_trim_duration_ms"] = trimRes.Duration.Milliseconds()
|
||||
metadata["seriatim_trim_invoked_binary"] = trimRes.InvokedBinary
|
||||
metadata["seriatim_trim_keep_selector"] = trimRes.KeepSelector
|
||||
if trimRes.Metadata != nil {
|
||||
metadata["seriatim_trim_metadata"] = trimRes.Metadata
|
||||
bounds = &generated
|
||||
transcript, err = runTrimTranscript(ctx, env, runLayout, normalizedPath, trimmedPath, bounds.selector, bounds.copyUnchanged)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := validateProcessedTranscriptOutput(trimmedPath); err != nil {
|
||||
return nil, fmt.Errorf("trim: trimmed transcript %q invalid: %w", trimmedPath, err)
|
||||
}
|
||||
|
||||
materializedTrimmed, err := materializeRunLocalOutput(env.ArtifactStore, trimmedPath, canonicalTrimmedPath, artifacts.Ref{
|
||||
Kind: "transcript_final_trimmed",
|
||||
Category: "transcripts",
|
||||
SessionID: sessionID,
|
||||
})
|
||||
trimmed, err := acceptTrimTranscript(env, sessionID, trimmedPath, canonicalTrimmedPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: materialize canonical final trimmed transcript: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
materializedBounds, err := materializeRunLocalOutput(env.ArtifactStore, finalBoundsOutputPath, canonicalBoundsOutputPath, artifacts.Ref{
|
||||
Kind: "session_bounds",
|
||||
Category: "artifacts",
|
||||
SessionID: sessionID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: materialize canonical session bounds: %w", err)
|
||||
result := &StageResult{Outputs: []artifacts.Ref{trimmed}, Metadata: metadata}
|
||||
if bounds != nil {
|
||||
materialized, err := materializeRunLocalOutput(env.ArtifactStore, bounds.outputPath, bounds.canonicalPath, artifacts.Ref{Kind: "session_bounds", Category: "artifacts", SessionID: sessionID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trim: materialize canonical session bounds: %w", err)
|
||||
}
|
||||
result.Outputs = append(result.Outputs, materialized)
|
||||
result.Logs, result.GeneratedConfigs = bounds.appendDiagnostics(metadata)
|
||||
logs, configs := transcript.appendDiagnostics(metadata)
|
||||
result.Logs = append(result.Logs, logs...)
|
||||
result.GeneratedConfigs = append(result.GeneratedConfigs, configs...)
|
||||
}
|
||||
|
||||
return &StageResult{
|
||||
Outputs: []artifacts.Ref{materializedTrimmed, materializedBounds},
|
||||
Logs: logPaths,
|
||||
GeneratedConfigs: generatedConfigs,
|
||||
Metadata: metadata,
|
||||
}, nil
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func resolveTrimmedOutputPath(paths artifacts.SessionPaths, cfg *config.TrimConfig) (string, error) {
|
||||
|
||||
Reference in New Issue
Block a user