package audita import ( "context" "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "time" "gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess" "gitea.maximumdirect.net/eric/narratio/internal/fileops" configkit "go.maximumdirect.net/configkit" ) // MaxProcessedOutputBytes bounds Audita's processed-transcript JSON result. const MaxProcessedOutputBytes int64 = 64 * 1024 * 1024 // MaxReportOutputBytes bounds each optional Audita report. const MaxReportOutputBytes int64 = 16 * 1024 * 1024 // SubprocessRunnerConfig defines deterministic settings for Audita CLI execution. type SubprocessRunnerConfig struct { Binary string Timeout time.Duration Credentials []configkit.Secret Debug bool Overlay string ProposalProfile string ValidationProfile string TranscriptDescription string ConfigPath string OutputSchema string } // SubprocessRunner invokes Audita via subprocess. type SubprocessRunner struct { cfg SubprocessRunnerConfig run func(context.Context, subprocess.RunRequest) (subprocess.RunResult, error) } // NewSubprocessRunner constructs a validated Audita subprocess runner. func NewSubprocessRunner(cfg SubprocessRunnerConfig) (*SubprocessRunner, error) { if strings.TrimSpace(cfg.Binary) == "" { return nil, fmt.Errorf("audita binary is required") } if cfg.Timeout <= 0 { return nil, fmt.Errorf("audita timeout must be > 0") } switch strings.TrimSpace(cfg.OutputSchema) { case "", "bare-segments", "audita-v1": default: return nil, fmt.Errorf("audita output schema must be one of: bare-segments, audita-v1") } cfg.Binary = strings.TrimSpace(cfg.Binary) cfg.Credentials = append([]configkit.Secret(nil), cfg.Credentials...) return &SubprocessRunner{cfg: cfg, run: subprocess.Run}, nil } // Run executes Audita process and validates its corrected transcript. func (r *SubprocessRunner) Run(ctx context.Context, req PolishRequest) (PolishResult, error) { if r == nil { return PolishResult{}, fmt.Errorf("audita subprocess runner is nil") } for _, field := range []struct{ name, value string }{ {"merged transcript path", req.MergedTranscriptPath}, {"output processed path", req.OutputProcessedPath}, } { if strings.TrimSpace(field.value) == "" { return PolishResult{}, fmt.Errorf("audita %s is required", field.name) } } for i, path := range req.GlossaryFiles { if strings.TrimSpace(path) == "" { return PolishResult{}, fmt.Errorf("audita glossary file at index %d is empty", i) } } args := r.buildArgs("process", req) env, names, err := subprocess.CredentialEnvironment(r.cfg.Credentials) if err != nil { return PolishResult{}, fmt.Errorf("audita credentials: %w", err) } if req.GeneratedConfigPath != "" { if err := r.writeInvocationConfig(req, args, names); err != nil { return PolishResult{}, fmt.Errorf("write audita invocation config %q: %w", req.GeneratedConfigPath, err) } } run := r.run if run == nil { run = subprocess.Run } runRes, runErr := run(ctx, subprocess.RunRequest{ Executable: r.cfg.Binary, Args: args, Timeout: r.cfg.Timeout, EnvOverrides: env, SensitiveEnvNames: names, DiagnosticOwner: "audita", StdoutLogPath: req.StdoutLogPath, StderrLogPath: req.StderrLogPath, }) result := r.result(req, names, runRes) if runErr != nil { result.Reports, _ = discoverReports(reportDirectory(req)) return result, fmt.Errorf("run audita process (binary=%q, output_dir=%q, stdout_log=%q, stderr_log=%q): %w", r.cfg.Binary, filepath.Dir(req.OutputProcessedPath), req.StdoutLogPath, req.StderrLogPath, runErr) } if err := validateProcessedOutput(req.OutputProcessedPath); err != nil { result.Reports, _ = discoverReports(reportDirectory(req)) return result, fmt.Errorf("validate audita processed output %q: %w", req.OutputProcessedPath, err) } reports, err := discoverReports(reportDirectory(req)) if err != nil { return result, err } result.Reports = reports return result, nil } func (r *SubprocessRunner) result(req PolishRequest, names []string, runRes subprocess.RunResult) PolishResult { return PolishResult{ ProcessedTranscriptPath: req.OutputProcessedPath, StdoutLogPath: req.StdoutLogPath, StderrLogPath: req.StderrLogPath, GeneratedConfigPath: req.GeneratedConfigPath, ExitCode: runRes.ExitCode, Duration: runRes.Duration, InvokedBinary: r.cfg.Binary, Metadata: map[string]any{ "adapter": "audita_subprocess", "glossary_files": req.GlossaryFiles, "report_dir": req.ReportDir, "work_dir": req.WorkDir, "debug": r.cfg.Debug, "overlay": r.cfg.Overlay, "proposal_profile": r.cfg.ProposalProfile, "validation_profile": r.cfg.ValidationProfile, "transcript_description": r.cfg.TranscriptDescription, "config_path": r.cfg.ConfigPath, "output_schema": r.cfg.OutputSchema, "credential_names": names, }, } } func (r *SubprocessRunner) buildArgs(command string, req PolishRequest) []string { args := []string{command, req.MergedTranscriptPath, "--output", req.OutputProcessedPath} for _, path := range req.GlossaryFiles { args = append(args, "--glossary-file", path) } for _, setting := range []struct{ flag, value string }{ {"--config", r.cfg.ConfigPath}, {"--overlay", r.cfg.Overlay}, {"--proposal-profile", r.cfg.ProposalProfile}, {"--validation-profile", r.cfg.ValidationProfile}, {"--transcript-description", r.cfg.TranscriptDescription}, {"--output-schema", r.cfg.OutputSchema}, {"--report-dir", req.ReportDir}, {"--work-dir", req.WorkDir}, } { if setting.value != "" { args = append(args, setting.flag, setting.value) } } if r.cfg.Debug { args = append(args, "--debug") } return args } func (r *SubprocessRunner) writeInvocationConfig(req PolishRequest, args, names []string) error { return writeGeneratedYAML(req.GeneratedConfigPath, map[string]any{ "schema": "audita.generated.v3", "binary": r.cfg.Binary, "args": args, "timeout": r.cfg.Timeout.String(), "glossary_files": req.GlossaryFiles, "report_dir": req.ReportDir, "work_dir": req.WorkDir, "debug": r.cfg.Debug, "overlay": r.cfg.Overlay, "proposal_profile": r.cfg.ProposalProfile, "validation_profile": r.cfg.ValidationProfile, "transcript_description": r.cfg.TranscriptDescription, "config_path": r.cfg.ConfigPath, "output_schema": r.cfg.OutputSchema, "merged_transcript_path": req.MergedTranscriptPath, "output_path": req.OutputProcessedPath, "credential_names": names, }) } func reportDirectory(req PolishRequest) string { if req.ReportDir != "" { return req.ReportDir } return filepath.Dir(req.OutputProcessedPath) } func discoverReports(reportDir string) (ReportBundle, error) { var reports ReportBundle for _, report := range []struct { name string dest *string }{ {"errors.yml", &reports.ErrorsPath}, {"recoveries.yml", &reports.RecoveriesPath}, {"report.md", &reports.OverviewPath}, } { path := filepath.Join(reportDir, report.name) info, err := os.Lstat(path) if errors.Is(err, os.ErrNotExist) { continue } if err != nil { return reports, fmt.Errorf("inspect audita report %q: %w", path, err) } if !info.Mode().IsRegular() { return reports, fmt.Errorf("audita report %q is not a regular file", path) } if _, err := fileops.ReadFileBounded(path, MaxReportOutputBytes); err != nil { return reports, fmt.Errorf("audita report %q exceeds or cannot be read within %d-byte limit: %w", path, MaxReportOutputBytes, err) } *report.dest = path } return reports, nil } func validateProcessedOutput(path string) error { data, err := fileops.ReadFileBounded(path, MaxProcessedOutputBytes) if err != nil { return fmt.Errorf("audita processed transcript result exceeds or cannot be read within %d-byte limit: %w", MaxProcessedOutputBytes, err) } var payload map[string]any if err := json.Unmarshal(data, &payload); err != nil { return fmt.Errorf("parse json: %w", err) } segments, ok := payload["segments"] if !ok { return fmt.Errorf("top-level segments is required") } if _, ok := segments.([]any); !ok { return fmt.Errorf("top-level segments must be an array") } return nil }