Add native Audita preflight

This commit is contained in:
2026-11-27 16:39:43 +00:00
parent 5bafae048e
commit 2db2554d1e
4 changed files with 191 additions and 1 deletions

View File

@@ -0,0 +1,70 @@
package audita
import (
"context"
_ "embed"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess"
)
//go:embed synthetic-transcript.json
var syntheticTranscript []byte
// PreflightResult records the native invocation outcome.
type PreflightResult struct {
ExitCode int
Duration time.Duration
}
// Preflight checks actual processing settings with a synthetic transcript and native smoke checks.
func (r *SubprocessRunner) Preflight(ctx context.Context, req PolishRequest) (PreflightResult, error) {
if r == nil {
return PreflightResult{}, fmt.Errorf("audita subprocess runner is nil")
}
if strings.TrimSpace(req.OutputProcessedPath) == "" {
return PreflightResult{}, fmt.Errorf("audita output processed path is required")
}
for i, path := range req.GlossaryFiles {
if strings.TrimSpace(path) == "" {
return PreflightResult{}, fmt.Errorf("audita glossary file at index %d is empty", i)
}
}
dir, err := os.MkdirTemp("", "narratio-audita-preflight-")
if err != nil {
return PreflightResult{}, fmt.Errorf("create audita preflight directory: %w", err)
}
defer os.RemoveAll(dir)
req.MergedTranscriptPath = filepath.Join(dir, "transcript.json")
req.StdoutLogPath = filepath.Join(dir, "stdout.log")
req.StderrLogPath = filepath.Join(dir, "stderr.log")
req.GeneratedConfigPath = filepath.Join(dir, "invocation.yml")
if err := os.WriteFile(req.MergedTranscriptPath, syntheticTranscript, 0600); err != nil {
return PreflightResult{}, fmt.Errorf("write synthetic transcript: %w", err)
}
args := r.buildArgs("preflight", req)
env, names, err := subprocess.CredentialEnvironment(r.cfg.Credentials)
if err != nil {
return PreflightResult{}, fmt.Errorf("audita credentials: %w", err)
}
if err := r.writeInvocationConfig(req, args, names); err != nil {
return PreflightResult{}, fmt.Errorf("write preflight invocation: %w", err)
}
run := r.run
if run == nil {
run = subprocess.Run
}
out, err := run(ctx, subprocess.RunRequest{Executable: r.cfg.Binary, Args: args, Timeout: r.cfg.Timeout, EnvOverrides: env, SensitiveEnvNames: names, DiagnosticOwner: "audita preflight", StdoutLogPath: req.StdoutLogPath, StderrLogPath: req.StderrLogPath})
result := PreflightResult{ExitCode: out.ExitCode, Duration: out.Duration}
if err != nil {
return result, fmt.Errorf("audita preflight failed: %w", err)
}
if out.ExitCode != 0 {
return result, fmt.Errorf("audita preflight failed with exit code %d", out.ExitCode)
}
return result, nil
}

View File

@@ -0,0 +1,113 @@
package audita
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess"
configkit "go.maximumdirect.net/configkit"
)
func TestPreflightUsesNativeProcessingSettingsAndCleansTemporaryInputs(t *testing.T) {
key := auditaTestSecret(t, "NARRATIO_PREFLIGHT_TEST_KEY", "synthetic-secret")
runner := auditaTestRunner(t, SubprocessRunnerConfig{Credentials: []configkit.Secret{key}, Debug: true, ConfigPath: "config.yml", Overlay: "testing", ProposalProfile: "proposal", ValidationProfile: "validation", OutputSchema: "audita-v1"})
req := auditaTestRequest(t)
req.ReportDir = filepath.Join(t.TempDir(), "reports")
req.WorkDir = filepath.Join(t.TempDir(), "debug")
originalStdout := req.StdoutLogPath
if err := os.WriteFile(originalStdout, []byte("prior"), 0600); err != nil {
t.Fatal(err)
}
var captured subprocess.RunRequest
var tempDir string
runner.run = func(_ context.Context, r subprocess.RunRequest) (subprocess.RunResult, error) {
captured = r
tempDir = filepath.Dir(r.StdoutLogPath)
data, err := os.ReadFile(filepath.Join(tempDir, "transcript.json"))
if err != nil {
t.Fatal(err)
}
var transcript struct {
Segments []map[string]any `json:"segments"`
}
if err := json.Unmarshal(data, &transcript); err != nil || len(transcript.Segments) < 2 {
t.Fatalf("fixture: %s %v", data, err)
}
if r.StdoutLogPath == originalStdout || r.StderrLogPath == req.StderrLogPath {
t.Fatal("overwrote processing diagnostics")
}
if r.EnvOverrides["NARRATIO_PREFLIGHT_TEST_KEY"] != "synthetic-secret" || !reflect.DeepEqual(r.SensitiveEnvNames, []string{"NARRATIO_PREFLIGHT_TEST_KEY"}) {
t.Fatal("credential forwarding lost")
}
return subprocess.RunResult{}, nil
}
result, err := runner.Preflight(context.Background(), req)
if err != nil || result.ExitCode != 0 {
t.Fatalf("preflight: %+v %v", result, err)
}
args := runner.buildArgs("process", req)
if captured.Args[0] != "preflight" || !reflect.DeepEqual(captured.Args[2:], args[2:]) {
t.Fatalf("settings differ: %v vs %v", captured.Args, args)
}
if strings.Contains(strings.Join(captured.Args, " "), "--smoke=false") {
t.Fatal("smoke disabled")
}
if _, err := os.Stat(tempDir); !os.IsNotExist(err) {
t.Fatalf("temporary directory remains: %v", err)
}
prior, err := os.ReadFile(originalStdout)
if err != nil || string(prior) != "prior" {
t.Fatalf("prior diagnostics changed: %q %v", prior, err)
}
}
func TestPreflightPreservesFailureAndRedactsDiagnostics(t *testing.T) {
const name = "NARRATIO_PREFLIGHT_SECRET"
secret := auditaTestSecret(t, name, "synthetic-private-value")
binary := filepath.Join(t.TempDir(), "helper")
writeAuditaTestFile(t, binary, "#!/bin/sh\nprintf 'provider rejected %s\\n' \"$"+name+"\" >&2\nexit 2\n")
if err := os.Chmod(binary, 0700); err != nil {
t.Fatal(err)
}
runner := auditaTestRunner(t, SubprocessRunnerConfig{Binary: binary, Credentials: []configkit.Secret{secret}})
result, err := runner.Preflight(context.Background(), auditaTestRequest(t))
if err == nil || result.ExitCode != 2 || !strings.Contains(err.Error(), "provider rejected") || strings.Contains(err.Error(), "synthetic-private-value") {
t.Fatalf("failure: %+v %v", result, err)
}
}
func TestPreflightCancellationPreservesCause(t *testing.T) {
runner := auditaTestRunner(t, SubprocessRunnerConfig{})
runner.run = func(ctx context.Context, _ subprocess.RunRequest) (subprocess.RunResult, error) {
return subprocess.RunResult{Canceled: true}, ctx.Err()
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := runner.Preflight(ctx, auditaTestRequest(t))
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancellation: %v", err)
}
}
func TestPreflightCleansTemporaryFilesOnFailure(t *testing.T) {
runner := auditaTestRunner(t, SubprocessRunnerConfig{})
failure := errors.New("synthetic provider failure")
var tempDir string
runner.run = func(_ context.Context, r subprocess.RunRequest) (subprocess.RunResult, error) {
tempDir = filepath.Dir(r.StderrLogPath)
return subprocess.RunResult{ExitCode: 1}, failure
}
_, err := runner.Preflight(context.Background(), auditaTestRequest(t))
if !errors.Is(err, failure) {
t.Fatalf("cause lost: %v", err)
}
if _, err := os.Stat(tempDir); !os.IsNotExist(err) {
t.Fatalf("temporary directory remains: %v", err)
}
}

View File

@@ -0,0 +1 @@
{"segments":[{"id":1,"speaker":"Speaker A","start":0,"end":2.1,"text":"We meet by the old harbor before dawn."},{"id":2,"speaker":"Speaker B","start":2.4,"end":4.6,"text":"I will keep watch while the others arrive."},{"id":3,"speaker":"Speaker A","start":4.9,"end":7.2,"text":"Then we can follow the road together."}]}