Use prepared glossaries for transcript polishing

This commit is contained in:
2026-11-27 16:38:10 +00:00
parent 16e28b25a2
commit 5bafae048e
6 changed files with 198 additions and 41 deletions

View File

@@ -9,6 +9,7 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
@@ -57,33 +58,25 @@ func (polishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*St
return nil, fmt.Errorf("polish: merged transcript %q invalid: %w", mergedPath, err)
}
glossaryPath := filepath.Join(paths.InputsDir, "glossary.yml")
if err := requireFile(glossaryPath, "glossary.yml"); err != nil {
return nil, fmt.Errorf("polish: %w", err)
}
canonicalProcessedPath := filepath.Join(paths.TranscriptsDir, "polished.json")
processedPath, err := runLocalPathForCanonical(runLayout, paths, canonicalProcessedPath)
if err != nil {
return nil, fmt.Errorf("polish: resolve run-local processed transcript path: %w", err)
return nil, fmt.Errorf("polish: resolve output: %w", err)
}
stdoutPath := filepath.Join(paths.LogsDir, "audita.stdout.log")
stderrPath := filepath.Join(paths.LogsDir, "audita.stderr.log")
generatedConfigPath := filepath.Join(paths.ConfigDir, "audita.generated.yml")
if !runLayout.Enabled {
processedPath = filepath.Join(paths.Root, "scratch", "polish", "polished.json")
}
logs := paths.LogsDir
debug := filepath.Join(paths.Root, "debug", "polish")
if runLayout.Enabled {
stdoutPath = filepath.Join(runLayout.LogsDir, "audita.stdout.log")
stderrPath = filepath.Join(runLayout.LogsDir, "audita.stderr.log")
generatedConfigPath = filepath.Join(runLayout.ConfigDir, "audita.generated.yml")
logs = runLayout.LogsDir
debug = filepath.Join(runLayout.Root, "debug")
}
req := audita.PolishRequest{
GeneratedConfigPath: generatedConfigPath,
MergedTranscriptPath: mergedPath,
OutputProcessedPath: processedPath,
GlossaryFiles: []string{glossaryPath},
StdoutLogPath: stdoutPath,
StderrLogPath: stderrPath,
req, evidence, err := BuildPolishRequest(paths, m, mergedPath, processedPath, logs, debug)
if err != nil {
return nil, fmt.Errorf("polish: %w", err)
}
stdoutPath, stderrPath, generatedConfigPath := req.StdoutLogPath, req.StderrLogPath, req.GeneratedConfigPath
res, err := env.Audita.Run(ctx, req)
if err != nil {
@@ -91,6 +84,9 @@ func (polishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*St
filepath.Dir(processedPath), stdoutPath, stderrPath, err)
}
if res.ExitCode != 0 {
return nil, fmt.Errorf("polish: audita exited with status %d", res.ExitCode)
}
finalProcessedPath, err := authoritativeOutputPath(processedPath, res.ProcessedTranscriptPath)
if err != nil {
return nil, fmt.Errorf("polish: %w", err)
@@ -108,7 +104,7 @@ func (polishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*St
if report.returned == "" {
continue
}
expected := filepath.Join(filepath.Dir(processedPath), report.name)
expected := filepath.Join(req.ReportDir, report.name)
path, err := authoritativeOutputPath(expected, report.returned)
if err != nil {
return nil, fmt.Errorf("polish: report %s: %w", report.name, err)
@@ -116,6 +112,9 @@ func (polishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*St
if err := requireRegularReadableFile(path, "audita report"); err != nil {
return nil, fmt.Errorf("polish: %w", err)
}
if _, err := fileops.ReadFileBounded(path, audita.MaxReportOutputBytes); err != nil {
return nil, fmt.Errorf("polish: read audita report %q: %w", path, err)
}
reportPaths = append(reportPaths, path)
reportMetadata[report.name] = path
}
@@ -133,7 +132,8 @@ func (polishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*St
"stage": "polish",
"merged_transcript_path": mergedPath,
"merged_transcript_source": source,
"glossary_path": glossaryPath,
"glossary_files": req.GlossaryFiles,
"glossary_evidence": evidence,
"run_output_path": finalProcessedPath,
"output_path": canonicalProcessedPath,
"overlay": env.Config.Pipeline.Audita.Overlay,

View File

@@ -0,0 +1,57 @@
package stage
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"path/filepath"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
// BuildPolishRequest resolves prepared vocabulary and selects intended destinations.
// Callers provide the transcript, allowing readiness checks to use a synthetic input.
func BuildPolishRequest(paths artifacts.SessionPaths, m *manifest.Manifest, transcript, output, logs, debug string) (audita.PolishRequest, string, error) {
files, evidence, err := polishGlossaryEvidence(paths, m)
if err != nil {
return audita.PolishRequest{}, "", err
}
for _, dir := range []string{filepath.Dir(output), logs, debug} {
if err := fileops.EnsureWorkspaceDirectory(dir); err != nil {
return audita.PolishRequest{}, "", err
}
}
return audita.PolishRequest{MergedTranscriptPath: transcript, OutputProcessedPath: output, GlossaryFiles: files,
ReportDir: logs, WorkDir: debug, StdoutLogPath: filepath.Join(logs, "audita.stdout.log"),
StderrLogPath: filepath.Join(logs, "audita.stderr.log"), GeneratedConfigPath: filepath.Join(logs, "audita.generated.yml")}, evidence, nil
}
func polishGlossaryEvidence(paths artifacts.SessionPaths, m *manifest.Manifest) ([]string, string, error) {
var files []string
var evidence []struct {
Source, Checksum string
Size int64
}
for _, descriptor := range artifactpolicy.GlossaryInputSources() {
identity, err := artifacts.ResolvePreparedInput(paths, m, descriptor.SourceID)
if err != nil {
return nil, "", fmt.Errorf("prepared glossary %s is unavailable or invalid; run prepare: %w", descriptor.SourceID, err)
}
files = append(files, identity.Path)
evidence = append(evidence, struct {
Source, Checksum string
Size int64
}{identity.SourceID, identity.Checksum, identity.Size})
}
data, err := json.Marshal(evidence)
if err != nil {
return nil, "", err
}
digest := sha256.Sum256(data)
return files, hex.EncodeToString(digest[:]), nil
}

View File

@@ -0,0 +1,29 @@
package stage
import (
"context"
"fmt"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func (polishStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Manifest) (ResumeValidation, error) {
if err := ctx.Err(); err != nil {
return ResumeValidation{}, err
}
if env == nil || env.Config == nil || env.Config.Session == nil || env.Config.Pipeline == nil {
return ResumeValidation{}, fmt.Errorf("polish resume: resolved configuration is required")
}
if m == nil || m.Stages["polish"] == nil {
return NonResumable("polish input evidence is missing; rerun polish"), nil
}
_, current, err := polishGlossaryEvidence(sessionPathsForEnv(env, m.SessionID), m)
if err != nil {
return NonResumable("prepared glossaries are unavailable or invalid; run prepare"), nil
}
previous, ok := m.Stages["polish"].Metadata["glossary_evidence"].(string)
if !ok || previous != current {
return NonResumable("polish glossary inputs changed; rerun polish"), nil
}
return Resumable(), nil
}

View File

@@ -11,6 +11,7 @@ import (
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
@@ -29,7 +30,6 @@ func TestPolishStagePolishesMergedTranscriptAndRecordsMetadata(t *testing.T) {
mergedPath := filepath.Join(paths.TranscriptsDir, "base.json")
writeFile(t, mergedPath, `{"segments":[]}`)
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, mergedPath)
fake := &audita.FakeRunner{}
@@ -49,7 +49,7 @@ func TestPolishStagePolishesMergedTranscriptAndRecordsMetadata(t *testing.T) {
if req.MergedTranscriptPath != mergedPath {
t.Fatalf("merged path = %q, want %q", req.MergedTranscriptPath, mergedPath)
}
if len(req.GlossaryFiles) != 1 || req.GlossaryFiles[0] != filepath.Join(paths.InputsDir, "glossary.yml") {
if len(req.GlossaryFiles) != 4 || req.GlossaryFiles[0] != filepath.Join(paths.InputsDir, "glossaries", "party.yml") {
t.Fatalf("glossary paths = %q", req.GlossaryFiles)
}
if len(result.Outputs) != 1 {
@@ -62,7 +62,7 @@ func TestPolishStagePolishesMergedTranscriptAndRecordsMetadata(t *testing.T) {
t.Fatalf("logs = %#v, want stdout, stderr, and three reports", result.Logs)
}
for _, name := range []string{"errors.yml", "recoveries.yml", "report.md"} {
path := filepath.Join(filepath.Dir(req.OutputProcessedPath), name)
path := filepath.Join(req.ReportDir, name)
if !slices.Contains(result.Logs, path) {
t.Fatalf("report %q missing from diagnostics: %#v", path, result.Logs)
}
@@ -87,7 +87,6 @@ func TestPolishStageRejectsIncidentalMergedTranscriptPath(t *testing.T) {
paths := sessionPathsForEnv(env, m.SessionID)
mergedPath := filepath.Join(paths.TranscriptsDir, "base.json")
writeFile(t, mergedPath, `{"segments":[]}`)
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
fake := &audita.FakeRunner{}
env.Audita = fake
@@ -103,8 +102,6 @@ func TestPolishStageRejectsIncidentalMergedTranscriptPath(t *testing.T) {
func TestPolishStageFailsWhenMergedTranscriptMissing(t *testing.T) {
env, m := setupPolishEnv(t)
paths := sessionPathsForEnv(env, m.SessionID)
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
env.Audita = &audita.FakeRunner{}
_, err := (polishStage{}).Run(context.Background(), env, m)
@@ -121,7 +118,6 @@ func TestPolishStageFailsWhenMergedTranscriptInvalidJSON(t *testing.T) {
paths := sessionPathsForEnv(env, m.SessionID)
writeFile(t, filepath.Join(paths.TranscriptsDir, "base.json"), "not-json")
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, filepath.Join(paths.TranscriptsDir, "base.json"))
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
env.Audita = &audita.FakeRunner{}
_, err := (polishStage{}).Run(context.Background(), env, m)
@@ -138,13 +134,14 @@ func TestPolishStageFailsWhenGlossaryMissing(t *testing.T) {
paths := sessionPathsForEnv(env, m.SessionID)
writeFile(t, filepath.Join(paths.TranscriptsDir, "base.json"), `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, filepath.Join(paths.TranscriptsDir, "base.json"))
m.Inputs = nil
env.Audita = &audita.FakeRunner{}
_, err := (polishStage{}).Run(context.Background(), env, m)
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "glossary.yml") {
if !strings.Contains(err.Error(), "run prepare") {
t.Fatalf("error = %q", err.Error())
}
}
@@ -154,7 +151,6 @@ func TestPolishStageFailsWhenAdapterFails(t *testing.T) {
paths := sessionPathsForEnv(env, m.SessionID)
writeFile(t, filepath.Join(paths.TranscriptsDir, "base.json"), `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, filepath.Join(paths.TranscriptsDir, "base.json"))
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
env.Audita = &audita.FakeRunner{Err: errors.New("audita failed")}
_, err := (polishStage{}).Run(context.Background(), env, m)
@@ -175,7 +171,6 @@ func TestPolishStageDoesNotPromoteTranscriptAfterAdapterFailure(t *testing.T) {
mergedPath := filepath.Join(paths.TranscriptsDir, "base.json")
writeFile(t, mergedPath, `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, mergedPath)
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
failure := errors.New("audita exited after output")
var runOutput string
env.Audita = polishRunnerFunc(func(_ context.Context, req audita.PolishRequest) (audita.PolishResult, error) {
@@ -205,7 +200,6 @@ func TestPolishStageRejectsRedirectedReportPath(t *testing.T) {
mergedPath := filepath.Join(paths.TranscriptsDir, "base.json")
writeFile(t, mergedPath, `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, mergedPath)
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
redirected := filepath.Join(t.TempDir(), "errors.yml")
writeFile(t, redirected, "status: completed\n")
env.Audita = &audita.FakeRunner{Result: audita.PolishResult{Reports: audita.ReportBundle{ErrorsPath: redirected}}}
@@ -223,7 +217,6 @@ func TestPolishStageFailsWhenProcessedOutputInvalid(t *testing.T) {
paths := sessionPathsForEnv(env, m.SessionID)
writeFile(t, filepath.Join(paths.TranscriptsDir, "base.json"), `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, filepath.Join(paths.TranscriptsDir, "base.json"))
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
badPath := filepath.Join(paths.TranscriptsDir, "processed.invalid.json")
writeFile(t, badPath, `{"schema":"audita.processed.v1","segments":"wrong-type"}`)
env.Audita = &audita.FakeRunner{Result: audita.PolishResult{ProcessedTranscriptPath: badPath}}
@@ -245,7 +238,6 @@ func TestPolishStageUsesRunLocalPathsAndMaterializesCanonical(t *testing.T) {
paths := sessionPathsForEnv(env, m.SessionID)
writeFile(t, filepath.Join(paths.TranscriptsDir, "base.json"), `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, filepath.Join(paths.TranscriptsDir, "base.json"))
writeFile(t, filepath.Join(paths.InputsDir, "glossary.yml"), "terms: []\n")
fake := &audita.FakeRunner{}
env.Audita = fake
@@ -260,6 +252,10 @@ func TestPolishStageUsesRunLocalPathsAndMaterializesCanonical(t *testing.T) {
if !strings.Contains(req.OutputProcessedPath, filepath.Join("runs", m.RunID, "polish", "outputs")) {
t.Fatalf("run output path = %q, want run-local path", req.OutputProcessedPath)
}
wantLogs := filepath.Join(paths.RunsDir, m.RunID, "polish", "logs")
if req.ReportDir != wantLogs || filepath.Dir(req.GeneratedConfigPath) != wantLogs || req.WorkDir != filepath.Join(paths.RunsDir, m.RunID, "polish", "debug") {
t.Fatalf("diagnostic paths: %+v", req)
}
if len(result.Outputs) == 0 {
t.Fatalf("outputs = %#v, want materialized outputs", result.Outputs)
}
@@ -292,6 +288,7 @@ func setupPolishEnv(t *testing.T) (*Env, *manifest.Manifest) {
},
},
Session: &config.SessionConfig{
Campaign: "sample-campaign",
SessionID: "2026-05-03",
Inputs: config.SessionInputsConfig{
GlossaryFile: new("./glossary.yml"),
@@ -303,8 +300,75 @@ func setupPolishEnv(t *testing.T) (*Env, *manifest.Manifest) {
if _, err := store.EnsureLayoutFor("sample-campaign", "2026-05-03"); err != nil {
t.Fatalf("EnsureLayout() error = %v", err)
}
return &Env{
Config: cfg,
ArtifactStore: store,
}, manifest.New("2026-05-03", time.Now().UTC())
env := &Env{Config: cfg, ArtifactStore: store}
m := manifest.New("2026-05-03", time.Now().UTC())
paths := sessionPathsForEnv(env, m.SessionID)
for _, desc := range artifactpolicy.GlossaryInputSources() {
path := filepath.Join(paths.InputsDir, desc.Filename)
writeFile(t, path, "synthetic: {entries: []}\n")
checksum, err := store.Checksum(path)
if err != nil {
t.Fatal(err)
}
m.Inputs = append(m.Inputs, manifest.InputRecord{Kind: desc.ManifestKind, Path: path, Checksum: checksum})
}
return env, m
}
func TestPolishResumeRequiresMatchingPreparedGlossaries(t *testing.T) {
env, m := setupPolishEnv(t)
paths := sessionPathsForEnv(env, m.SessionID)
merged := filepath.Join(paths.TranscriptsDir, "base.json")
writeFile(t, merged, `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, merged)
env.Audita = &audita.FakeRunner{}
result, err := (polishStage{}).Run(context.Background(), env, m)
if err != nil {
t.Fatal(err)
}
m.MarkStageSucceeded("polish", time.Now().UTC(), nil)
m.Stages["polish"].Metadata = result.Metadata
state, err := (polishStage{}).ValidateResume(context.Background(), env, m)
if err != nil || !state.Resumable {
t.Fatalf("reuse: %+v %v", state, err)
}
file := filepath.Join(paths.InputsDir, "glossaries", "campaign.yml")
writeFile(t, file, "campaign: {entries: [{id: a, name: A, category: place}]}\n")
state, err = (polishStage{}).ValidateResume(context.Background(), env, m)
if err != nil || state.Resumable {
t.Fatalf("changed: %+v %v", state, err)
}
checksum, err := env.ArtifactStore.Checksum(file)
if err != nil {
t.Fatal(err)
}
for i := range m.Inputs {
if m.Inputs[i].Kind == "glossary_campaign" {
m.Inputs[i].Checksum = checksum
}
}
state, err = (polishStage{}).ValidateResume(context.Background(), env, m)
if err != nil || state.Resumable {
t.Fatalf("new valid evidence reused old polish: %+v %v", state, err)
}
}
func TestPolishRejectsNonzeroOutcomeWithoutPromotingOutput(t *testing.T) {
env, m := setupPolishEnv(t)
m.Campaign = "sample-campaign"
m.RunID = "20260518T010203Z-abcdef12"
paths := sessionPathsForEnv(env, m.SessionID)
merged := filepath.Join(paths.TranscriptsDir, "base.json")
writeFile(t, merged, `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, merged)
env.Audita = polishRunnerFunc(func(_ context.Context, req audita.PolishRequest) (audita.PolishResult, error) {
writeFile(t, req.OutputProcessedPath, `{"segments":[]}`)
return audita.PolishResult{ProcessedTranscriptPath: req.OutputProcessedPath, ExitCode: 1}, nil
})
if _, err := (polishStage{}).Run(context.Background(), env, m); err == nil {
t.Fatal("nonzero outcome accepted")
}
if _, err := os.Stat(filepath.Join(paths.TranscriptsDir, "polished.json")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("nonzero output promoted: %v", err)
}
}

View File

@@ -10,7 +10,7 @@ import (
)
const (
polishSemanticConfigVersion = 2
polishSemanticConfigVersion = 3
normalizeSemanticConfigVersion = 1
trimSemanticConfigVersion = 1
renderSemanticConfigVersion = 1