From c523def8523a3494779ebec221e955d4046b090f Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Fri, 20 Nov 2026 05:59:09 +0000 Subject: [PATCH] Route console diagnostics and stage progress through native reporting --- docs/roadmap/implementation.md | 11 ++ internal/app/artifact_catalog_command.go | 2 +- internal/app/catalog_execution_test.go | 4 +- internal/app/clean_command.go | 2 +- internal/app/command_dependencies.go | 2 + internal/app/command_reporting.go | 48 ++++++ internal/app/command_reporting_test.go | 173 +++++++++++++++++++++ internal/app/configuration_acquisition.go | 18 +++ internal/app/execution_command.go | 4 +- internal/app/lock_command.go | 2 +- internal/app/plan_command.go | 2 +- internal/app/restore_command.go | 2 +- internal/app/run_control_test.go | 4 +- internal/app/runner.go | 3 + internal/app/runner_runtime.go | 7 +- internal/app/runner_stage_execution.go | 17 +- internal/app/session_init_command.go | 2 +- internal/app/session_inspection_command.go | 2 +- internal/app/session_state_command.go | 2 +- internal/logging/logging.go | 21 +-- internal/logging/logging_test.go | 31 ---- internal/stage/reporting.go | 22 +++ internal/stage/stage.go | 4 +- 23 files changed, 309 insertions(+), 76 deletions(-) create mode 100644 internal/app/command_reporting.go create mode 100644 internal/app/command_reporting_test.go delete mode 100644 internal/logging/logging_test.go create mode 100644 internal/stage/reporting.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 79ed6cc..0e6d87d 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -684,6 +684,17 @@ case and representative process signal wiring without timing-based sleeps. ## Stage 17: Centralize native console diagnostics and stage progress +**Completed.** Replaced the runner's direct stderr logger with a small +Narratio-owned reporting interface adapted to the native invocation reporter. +Stage starts, durable completions, self-skips, and reuse emit Progress; selected +configuration, destinations, and reuse decisions emit Info, with native Warning +and Debug channels. Console delivery failures stay with native finalization and +do not interrupt checkpointing. Native visibility/boolean/repetition, report, +single-failure, downstream-capture isolation, runner/composition, focused race, +configuration/stage/artifact, build, and diff checks pass with Go 1.27.4. +Removed obsolete logger-construction tests in favor of real native invocation +coverage; captured downstream content is never replayed. + Read: CommandKit reporting/visibility contracts, `internal/logging`, `runner_runtime.go`, `runner_stage_execution.go`, and application print/log sites. diff --git a/internal/app/artifact_catalog_command.go b/internal/app/artifact_catalog_command.go index bc96f5a..c22e949 100644 --- a/internal/app/artifact_catalog_command.go +++ b/internal/app/artifact_catalog_command.go @@ -34,7 +34,7 @@ func artifactCatalogCommand(deps commandDependencies) commandkit.Command { Flags: []commandkit.Flag[configurationSelection]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.PartyFile, common.SecretsDir}, CheckInput: checkConfigurationSelection, Run: func(invocation commandkit.Invocation, input configurationSelection) commandkit.Outcome { - report, err := loadArtifactCatalogReport(invocation.Context, input, deps) + report, err := loadArtifactCatalogReport(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/catalog_execution_test.go b/internal/app/catalog_execution_test.go index 406ead5..552460c 100644 --- a/internal/app/catalog_execution_test.go +++ b/internal/app/catalog_execution_test.go @@ -4,8 +4,6 @@ import ( "bytes" "context" "encoding/json" - "io" - "log/slog" "os" "path/filepath" "reflect" @@ -98,7 +96,7 @@ scriptorium: runner := &scriptorium.FakeRunner{} summary, err := executePlan(context.Background(), cfg, plan, RunOptions{ SelectedArtifacts: []string{"character_note"}, - Env: &Env{Scriptorium: runner, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}, + Env: &Env{Scriptorium: runner}, }) if err != nil { t.Fatal(err) diff --git a/internal/app/clean_command.go b/internal/app/clean_command.go index 8ad645e..d3fbfc2 100644 --- a/internal/app/clean_command.go +++ b/internal/app/clean_command.go @@ -60,7 +60,7 @@ func cleanCommand(deps commandDependencies) commandkit.Command { Arguments: []commandkit.Argument[*cleanCommandInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity, omitted with --all."}, false, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).Selection.Session = value })}, CheckInput: checkCleanInput, Run: func(invocation commandkit.Invocation, input *cleanCommandInput) commandkit.Outcome { - report, err := cleanSelectedSession(invocation.Context, input, deps) + report, err := cleanSelectedSession(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/command_dependencies.go b/internal/app/command_dependencies.go index 1c481cd..aba9d28 100644 --- a/internal/app/command_dependencies.go +++ b/internal/app/command_dependencies.go @@ -6,10 +6,12 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/config" + "gitea.maximumdirect.net/eric/narratio/internal/logging" configkit "go.maximumdirect.net/configkit" ) type commandDependencies struct { + reporter logging.Reporter diagnostics io.Writer pipelineSearch *configkit.Search loadPipelineConfig func(string, config.PipelineLoadOptions) (*config.PipelineConfig, error) diff --git a/internal/app/command_reporting.go b/internal/app/command_reporting.go new file mode 100644 index 0000000..9621522 --- /dev/null +++ b/internal/app/command_reporting.go @@ -0,0 +1,48 @@ +package app + +import ( + "fmt" + "io" + + "go.maximumdirect.net/commandkit" +) + +// Native reporting retains its own delivery failures until invocation finalization. +// Console delivery failures must not interrupt domain work or checkpoint saves. +type nativeConsole struct{ reporter *commandkit.Reporter } + +func (r nativeConsole) Info(message string, fields ...any) { + _ = r.reporter.Info(message, consoleFields(fields)) +} +func (r nativeConsole) Warn(message string, fields ...any) { + _ = r.reporter.Warn(message, consoleFields(fields)) +} +func (r nativeConsole) Debug(message string, fields ...any) { + _ = r.reporter.Debug(message, consoleFields(fields)) +} +func (r nativeConsole) Progress(message string, fields ...any) { + _ = r.reporter.Progress(message, consoleFields(fields)) +} + +func consoleFields(fields []any) commandkit.Detail { + if len(fields) == 0 { + return nil + } + return func(w io.Writer) error { + for index := 0; index < len(fields); index += 2 { + value := any("") + if index+1 < len(fields) { + value = fields[index+1] + } + if _, err := fmt.Fprintf(w, "%v=%v\n", fields[index], value); err != nil { + return err + } + } + return nil + } +} + +func withCommandReporting(deps commandDependencies, invocation commandkit.Invocation) commandDependencies { + deps.reporter = nativeConsole{reporter: invocation.Reporter()} + return deps +} diff --git a/internal/app/command_reporting_test.go b/internal/app/command_reporting_test.go new file mode 100644 index 0000000..14f7851 --- /dev/null +++ b/internal/app/command_reporting_test.go @@ -0,0 +1,173 @@ +package app + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "gitea.maximumdirect.net/eric/narratio/internal/config" + "gitea.maximumdirect.net/eric/narratio/internal/manifest" + "gitea.maximumdirect.net/eric/narratio/internal/stage" + "go.maximumdirect.net/commandkit" +) + +type diagnosticStage struct { + result *stage.StageResult + err error +} + +func (s diagnosticStage) Name() string { return "prepare" } +func (s diagnosticStage) Run(_ context.Context, env *stage.Env, _ *manifest.Manifest) (*stage.StageResult, error) { + env.Info("stage context") + env.Warn("stage warning") + env.Debug("stage diagnostic") + return s.result, s.err +} + +func TestNativeConsoleVisibilityDoesNotChangeExecution(t *testing.T) { + for _, test := range []struct { + name string + flags []string + info, debug, progress, quiet bool + }{ + {name: "ordinary"}, + {name: "verbose", flags: []string{"--verbose"}, info: true}, + {name: "progress", flags: []string{"--progress"}, progress: true}, + {name: "verbose progress", flags: []string{"--verbose", "--progress"}, info: true, progress: true}, + {name: "quiet", flags: []string{"--debug", "--progress", "--quiet"}, quiet: true}, + {name: "debug", flags: []string{"--debug"}, info: true, debug: true, progress: true}, + {name: "debug without progress", flags: []string{"--debug", "--progress=false"}, info: true, debug: true}, + {name: "cleared debug", flags: []string{"--debug", "--debug=false"}}, + {name: "last progress value", flags: []string{"--progress=false", "--progress=true"}, progress: true}, + {name: "last mode", flags: []string{"--quiet", "--verbose"}, info: true}, + } { + t.Run(test.name, func(t *testing.T) { + pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) + logPath := filepath.Join(t.TempDir(), "captured.log") + const captured = "synthetic-private-downstream-output" + if err := os.WriteFile(logPath, []byte(captured), 0o600); err != nil { + t.Fatal(err) + } + var saved *RunSummary + app, err := newApplication(commandDependencies{}, func(ctx context.Context, cfg *config.Config, plan BoundedPlan, opts RunOptions) (*RunSummary, error) { + if len(plan.Names()) != 1 || plan.Names()[0] != "prepare" || opts.Force { + t.Fatal("console flags changed execution selection") + } + if cfg.Pipeline.Trim.Bounds.RenderDebug || (cfg.Pipeline.Scriptorium != nil && cfg.Pipeline.Scriptorium.RenderDebug) { + t.Fatal("console debug changed downstream capture") + } + var err error + saved, err = executeStages(ctx, cfg, []stage.Stage{diagnosticStage{result: &stage.StageResult{Logs: []string{logPath}}}}, opts) + return saved, err + }) + if err != nil { + t.Fatal(err) + } + args := []string{"run", "2026-05-03", "--stage", "prepare", "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--format", "json"} + args = append(args, test.flags...) + var out, diagnostic bytes.Buffer + outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic}) + if outcome.Status != 0 || saved == nil || !saved.Complete { + t.Fatalf("outcome=%#v diagnostics=%s", outcome, diagnostic.String()) + } + text := diagnostic.String() + for _, check := range []struct { + fragment string + want bool + }{{"stage context", test.info}, {"selected pipeline configuration", test.info}, {"stage warning", test.info}, {"stage diagnostic", test.debug}, {"manifest saved", test.debug}, {"starting stage", test.progress}, {"stage succeeded", test.progress}} { + if strings.Contains(text, check.fragment) != check.want { + t.Fatalf("visibility for %q = %v, want %v; diagnostics=%s", check.fragment, !check.want, check.want, text) + } + } + if strings.Contains(text+out.String(), captured) { + t.Fatal("replayed captured downstream output") + } + if test.quiet { + if out.Len() != 0 || diagnostic.Len() != 0 { + t.Fatal("quiet produced successful console output") + } + return + } + var report runReport + if err := json.Unmarshal(out.Bytes(), &report); err != nil { + t.Fatal(err) + } + if !report.Complete || len(report.StageResults) != 1 || report.StageResults[0].Outcome != "completed" { + t.Fatalf("report=%#v", report) + } + }) + } +} + +func TestNativeConsoleReportsSelfSkipReuseAndSingleFailure(t *testing.T) { + pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) + cause := errors.New("synthetic stage failure") + for _, test := range []struct { + name string + selected stage.Stage + flags []string + want string + status int + }{ + {name: "self skip", selected: diagnosticStage{result: &stage.StageResult{Disposition: stage.StageDispositionSkipped, SkipReason: "disabled"}}, flags: []string{"--progress"}, want: "stage skipped"}, + {name: "success", selected: diagnosticStage{}, flags: []string{"--progress"}, want: "stage succeeded"}, + {name: "reuse", selected: failingStage{name: "prepare", err: errors.New("must reuse")}, flags: []string{"--progress"}, want: "reusing stage"}, + {name: "failure", selected: diagnosticStage{err: cause}, flags: []string{"--force", "--progress"}, status: 1}, + {name: "quiet failure", selected: diagnosticStage{err: cause}, flags: []string{"--force", "--quiet"}, status: 1}, + } { + t.Run(test.name, func(t *testing.T) { + app, err := newApplication(commandDependencies{}, func(ctx context.Context, cfg *config.Config, _ BoundedPlan, opts RunOptions) (*RunSummary, error) { + return executeStages(ctx, cfg, []stage.Stage{test.selected}, opts) + }) + if err != nil { + t.Fatal(err) + } + args := []string{"run", "2026-05-03", "--stage", "prepare", "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--format", "json"} + var out, diagnostic bytes.Buffer + outcome := app.Execute(context.Background(), append(args, test.flags...), commandkit.Streams{Out: &out, Err: &diagnostic}) + if outcome.Status != test.status { + t.Fatalf("outcome=%#v diagnostics=%s", outcome, diagnostic.String()) + } + if test.status == 1 { + if strings.Count(diagnostic.String(), cause.Error()) != 1 { + t.Fatalf("failure presented repeatedly: %s", diagnostic.String()) + } + return + } + if !strings.Contains(diagnostic.String(), test.want) { + t.Fatalf("missing %q: %s", test.want, diagnostic.String()) + } + }) + } +} + +func TestNativeConsoleDeliveryFailureDoesNotInterruptCheckpointing(t *testing.T) { + pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) + writeErr := errors.New("diagnostic destination unavailable") + var saved *RunSummary + app, err := newApplication(commandDependencies{}, func(ctx context.Context, cfg *config.Config, _ BoundedPlan, opts RunOptions) (*RunSummary, error) { + var err error + saved, err = executeStages(ctx, cfg, []stage.Stage{diagnosticStage{}}, opts) + return saved, err + }) + if err != nil { + t.Fatal(err) + } + var out bytes.Buffer + outcome := app.Execute(context.Background(), []string{"run", "2026-05-03", "--stage", "prepare", "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--progress", "--format", "json"}, commandkit.Streams{Out: &out, Err: runReportWriteFunc(func([]byte) (int, error) { return 0, writeErr })}) + if outcome.Status != 1 || !errors.Is(outcome.Presentation.Diagnostics.WriteError, writeErr) || saved == nil || !saved.Complete { + t.Fatalf("outcome=%#v summary=%#v", outcome, saved) + } + durable, err := (&manifest.LocalStore{}).Load(context.Background(), saved.ManifestPath) + if err != nil { + t.Fatal(err) + } + if durable.Stages["prepare"].Status != manifest.StatusSucceeded { + t.Fatal("diagnostic delivery failure interrupted domain work") + } +} diff --git a/internal/app/configuration_acquisition.go b/internal/app/configuration_acquisition.go index b851b66..865ab57 100644 --- a/internal/app/configuration_acquisition.go +++ b/internal/app/configuration_acquisition.go @@ -87,6 +87,9 @@ func (a *configurationAcquisition) Pipeline(ctx context.Context) (*config.Pipeli return nil, err } a.pipeline, a.pipelinePath = cfg, path + if a.deps.reporter != nil { + a.deps.reporter.Info("selected pipeline configuration", "source", path, "overlay", a.selection.Overlay.Value) + } return cfg, nil } @@ -121,6 +124,9 @@ func (a *configurationAcquisition) Campaign(ctx context.Context) (*config.Campai return nil, &config.SessionIdentityError{Source: path, Field: "campaign_id", Expected: a.selection.Campaign.Value, Actual: config.CampaignID(cfg)} } a.campaign, a.campaignPath = cfg, path + if a.deps.reporter != nil { + a.deps.reporter.Info("selected campaign configuration", "campaign", config.CampaignID(cfg), "source", path) + } return cfg, nil } @@ -145,6 +151,9 @@ func (a *configurationAcquisition) Party(ctx context.Context) (*config.ResolvedP return nil, err } a.party = &party + if a.deps.reporter != nil { + a.deps.reporter.Info("selected party configuration", "source", party.Source.Path) + } return a.party, nil } @@ -174,6 +183,9 @@ func (a *configurationAcquisition) Session(ctx context.Context) (*config.Session return nil, err } a.session = &acquiredSession{Config: session, Path: path, Source: config.SessionSource{Source: "session_config", LocalPath: path}} + if a.deps.reporter != nil { + a.deps.reporter.Info("selected session configuration", "session", session.SessionID, "source", path) + } return session, nil } session, path, err := config.DiscoverSession(config.DefaultSessionConfigSearchPaths, opts) @@ -186,6 +198,9 @@ func (a *configurationAcquisition) Session(ctx context.Context) (*config.Session return nil, err } a.session = &acquiredSession{Config: session, Path: path, Source: config.SessionSource{Source: "session_config", LocalPath: path}} + if a.deps.reporter != nil { + a.deps.reporter.Info("selected session configuration", "session", session.SessionID, "source", path) + } return session, nil } if a.selection.Session.Value == "" { @@ -205,6 +220,9 @@ func (a *configurationAcquisition) Session(ctx context.Context) (*config.Session return nil, err } a.session = loaded + if a.deps.reporter != nil { + a.deps.reporter.Info("selected session configuration", "session", loaded.Config.SessionID, "source", loaded.Source.Source, "key", loaded.Source.S3Key) + } if err := ctx.Err(); err != nil { return nil, errors.Join(err, a.Close()) } diff --git a/internal/app/execution_command.go b/internal/app/execution_command.go index 02378d9..68cf0c9 100644 --- a/internal/app/execution_command.go +++ b/internal/app/execution_command.go @@ -69,7 +69,7 @@ func checkExecutionInput(input *executionInput) error { func executionCommand(name, summary string, regenerate bool, deps commandDependencies, executor pipelineExecutor) commandkit.Command { spec := executionCommandSpec(name, summary, regenerate) spec.Run = func(invocation commandkit.Invocation, input *executionInput) commandkit.Outcome { - report, err := executeSelectedPipeline(invocation.Context, input, deps, executor) + report, err := executeSelectedPipeline(invocation.Context, input, withCommandReporting(deps, invocation), executor) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } @@ -135,7 +135,7 @@ func executeSelectedPipeline(ctx context.Context, input *executionInput, deps co if err := ctx.Err(); err != nil { return nil, err } - summary, err := executor(ctx, cfg, input.plan, RunOptions{Force: input.Force.Value, SelectedArtifacts: selected, EffectiveArtifacts: effective}) + summary, err := executor(ctx, cfg, input.plan, RunOptions{Force: input.Force.Value, SelectedArtifacts: selected, EffectiveArtifacts: effective, Reporter: invocationDeps.reporter}) if summary == nil { if err == nil { err = fmt.Errorf("pipeline execution returned no run summary") diff --git a/internal/app/lock_command.go b/internal/app/lock_command.go index b1fb637..4f8b30e 100644 --- a/internal/app/lock_command.go +++ b/internal/app/lock_command.go @@ -63,7 +63,7 @@ func lockCommand(operation string, deps commandDependencies) commandkit.Command return nil }, Run: func(invocation commandkit.Invocation, input *lockCommandInput) commandkit.Outcome { - report, err := executeLockCommand(invocation.Context, input, operation, deps) + report, err := executeLockCommand(invocation.Context, input, operation, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/plan_command.go b/internal/app/plan_command.go index 9c309f4..360305e 100644 --- a/internal/app/plan_command.go +++ b/internal/app/plan_command.go @@ -59,7 +59,7 @@ func analysisPlanReport(summary *stage.AnalyzeResumeSummary) *plannedAnalysis { func sessionPlanCommand(deps commandDependencies) commandkit.Command { spec := executionCommandSpec("plan", "Preview session work without executing it.", false) spec.Run = func(invocation commandkit.Invocation, input *executionInput) commandkit.Outcome { - report, err := planSelectedPipeline(invocation.Context, input, deps) + report, err := planSelectedPipeline(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/restore_command.go b/internal/app/restore_command.go index a696092..da68349 100644 --- a/internal/app/restore_command.go +++ b/internal/app/restore_command.go @@ -170,7 +170,7 @@ func restoreCommand(deps commandDependencies) commandkit.Command { })}, CheckInput: func(input *restoreCommandInput) error { return checkConfigurationSelection(input.Selection) }, Run: func(invocation commandkit.Invocation, input *restoreCommandInput) commandkit.Outcome { - report, err := restoreSelectedSession(invocation.Context, input, deps) + report, err := restoreSelectedSession(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/run_control_test.go b/internal/app/run_control_test.go index 06637b9..ca96058 100644 --- a/internal/app/run_control_test.go +++ b/internal/app/run_control_test.go @@ -3,8 +3,6 @@ package app import ( "context" "fmt" - "io" - "log/slog" "path/filepath" "reflect" "strings" @@ -166,7 +164,7 @@ func TestPlannedStageModelMatchesStageExecution(t *testing.T) { cfg: cfg, opts: RunOptions{Force: test.force}, identity: invocationIdentity{RunID: "20260503T120000Z-a1b2c3d4", LocalWorkDir: workDir}, - env: &stage.Env{Config: cfg, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}, + env: &stage.Env{Config: cfg}, manifestStore: &manifest.LocalStore{}, manifestPath: filepath.Join(t.TempDir(), "manifest.json"), manifest: executed, diff --git a/internal/app/runner.go b/internal/app/runner.go index 5571427..b87c341 100644 --- a/internal/app/runner.go +++ b/internal/app/runner.go @@ -14,11 +14,13 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/artifactmodel" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" + "gitea.maximumdirect.net/eric/narratio/internal/logging" "gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/stage" ) type RunOptions struct { + Reporter logging.Reporter Force bool SelectedArtifacts []string EffectiveArtifacts artifacts.EffectiveArtifactSet @@ -87,6 +89,7 @@ func executePlanWithDependencies(ctx context.Context, cfg *config.Config, plan B return nil, err } + runtime.env.Info("selected run destinations", "session", runtime.identity.SessionID, "run", runtime.identity.RunID, "manifest", runtime.manifestPath, "workspace", runtime.identity.LocalWorkDir) for index, selected := range runtime.stages { if err := ctx.Err(); err != nil { return nil, err diff --git a/internal/app/runner_runtime.go b/internal/app/runner_runtime.go index 495cbb2..a308ac6 100644 --- a/internal/app/runner_runtime.go +++ b/internal/app/runner_runtime.go @@ -3,13 +3,10 @@ package app import ( "context" "fmt" - "log/slog" - "os" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/fileops" - "gitea.maximumdirect.net/eric/narratio/internal/logging" "gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/stage" ) @@ -95,8 +92,8 @@ func prepareInvocation(ctx context.Context, cfg *config.Config, plan BoundedPlan if env.ArtifactStore == nil { env.ArtifactStore = artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) } - if env.Logger == nil { - env.Logger = logging.NewLogger(os.Stderr, slog.LevelInfo) + if opts.Reporter != nil { + env.Reporter = opts.Reporter } normalizedOpts := opts diff --git a/internal/app/runner_stage_execution.go b/internal/app/runner_stage_execution.go index 9a6e8de..e65ac84 100644 --- a/internal/app/runner_stage_execution.go +++ b/internal/app/runner_stage_execution.go @@ -53,7 +53,7 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out if err := runtime.manifestStore.Save(runtime.ctx, runtime.manifestPath, m); err != nil { return outcome, fmt.Errorf("save manifest after resume validation for stage %q: %w", selected.Name(), err) } - env.Logger.Info("stage result is not resumable", "stage", selected.Name(), "reason", decision.selectedStaleReason) + env.Info("stage result is not resumable", "stage", selected.Name(), "reason", decision.selectedStaleReason) } } @@ -61,7 +61,8 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out return outcome, err } if decision.action == stageActionSkip { - env.Logger.Info("skipping stage", "stage", selected.Name(), "reason", "already_succeeded", "force", runtime.opts.Force) + env.Info("stage reuse decision", "stage", selected.Name(), "reason", "already_succeeded", "force", runtime.opts.Force) + env.Progress("reusing stage", "stage", selected.Name()) return stageExecutionOutcome{skipped: true, reused: true, reason: "already_succeeded"}, nil } if err := runtime.ensureRunWorkspaceFor(selected); err != nil { @@ -74,12 +75,12 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out if _, err := beginStageAttempt(m, selected.Name(), decision, startedAt); err != nil { return outcome, fmt.Errorf("invalidate dependents before forced stage %q: %w", selected.Name(), err) } - env.Logger.Info("starting stage", "stage", selected.Name()) + env.Progress("starting stage", "stage", selected.Name()) if err := runtime.manifestStore.Save(runtime.ctx, runtime.manifestPath, m); err != nil { operationErr := fmt.Errorf("save manifest before stage %q: %w", selected.Name(), err) return outcome, operationErr } - env.Logger.Debug("manifest saved", "stage", selected.Name(), "transition", "running", "path", runtime.manifestPath) + env.Debug("manifest saved", "stage", selected.Name(), "transition", "running", "path", runtime.manifestPath) if err := runtime.ctx.Err(); err != nil { return outcome, err @@ -100,8 +101,8 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out if err := runtime.manifestStore.Save(runtime.ctx, runtime.manifestPath, m); err != nil { return outcome, fmt.Errorf("save manifest after self-skip %q: %w", selected.Name(), err) } - env.Logger.Debug("manifest saved", "stage", selected.Name(), "transition", "skipped", "path", runtime.manifestPath) - env.Logger.Info("stage skipped", "stage", selected.Name(), "reason", result.SkipReason) + env.Debug("manifest saved", "stage", selected.Name(), "transition", "skipped", "path", runtime.manifestPath) + env.Progress("stage skipped", "stage", selected.Name(), "reason", result.SkipReason) outcome.skipped = true outcome.reason = result.SkipReason return outcome, nil @@ -116,7 +117,7 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out operationErr := fmt.Errorf("save manifest after stage %q: %w", selected.Name(), err) return outcome, operationErr } - env.Logger.Debug("manifest saved", "stage", selected.Name(), "transition", "succeeded", "path", runtime.manifestPath) - env.Logger.Info("stage succeeded", "stage", selected.Name()) + env.Debug("manifest saved", "stage", selected.Name(), "transition", "succeeded", "path", runtime.manifestPath) + env.Progress("stage succeeded", "stage", selected.Name()) return outcome, nil } diff --git a/internal/app/session_init_command.go b/internal/app/session_init_command.go index 516e062..e2dbeca 100644 --- a/internal/app/session_init_command.go +++ b/internal/app/session_init_command.go @@ -84,7 +84,7 @@ func sessionInitializationCommand(deps commandDependencies) commandkit.Command { })}, CheckInput: checkSessionInitializationInput, Run: func(invocation commandkit.Invocation, input *sessionInitializationInput) commandkit.Outcome { - report, err := initializeSession(invocation.Context, input, deps) + report, err := initializeSession(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/session_inspection_command.go b/internal/app/session_inspection_command.go index e45d475..d8c8eb8 100644 --- a/internal/app/session_inspection_command.go +++ b/internal/app/session_inspection_command.go @@ -46,7 +46,7 @@ func sessionInspectionSpec(name, summary string, remoteOption bool) commandkit.C func sessionValidationCommand(deps commandDependencies) commandkit.Command { spec := sessionInspectionSpec("validate", "Check session readiness without executing work.", false) spec.Run = func(invocation commandkit.Invocation, input *sessionInspectionInput) commandkit.Outcome { - report, err := validateSelectedSession(invocation.Context, input, deps) + report, err := validateSelectedSession(invocation.Context, input, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/app/session_state_command.go b/internal/app/session_state_command.go index 1fca96f..b45a348 100644 --- a/internal/app/session_state_command.go +++ b/internal/app/session_state_command.go @@ -74,7 +74,7 @@ type sessionPublishedOutput struct { func sessionStateCommand(name string, status bool, deps commandDependencies) commandkit.Command { spec := sessionInspectionSpec(name, "Inspect session state without changing it.", !status) spec.Run = func(invocation commandkit.Invocation, input *sessionInspectionInput) commandkit.Outcome { - report, err := inspectSelectedSessionState(invocation.Context, input, status, deps) + report, err := inspectSelectedSessionState(invocation.Context, input, status, withCommandReporting(deps, invocation)) if report != nil { err = errors.Join(err, invocation.Reporter().Report(commandkit.Report{Value: report})) } diff --git a/internal/logging/logging.go b/internal/logging/logging.go index 47dfd6e..dc937aa 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -1,17 +1,10 @@ package logging -import ( - "io" - "log/slog" - "os" -) - -// NewLogger creates a text slog logger. -func NewLogger(out io.Writer, level slog.Level) *slog.Logger { - if out == nil { - out = os.Stderr - } - - handler := slog.NewTextHandler(out, &slog.HandlerOptions{Level: level}) - return slog.New(handler) +// Reporter receives operation diagnostics and work progress. Implementations own +// delivery and visibility; reporting does not change domain execution policy. +type Reporter interface { + Info(message string, fields ...any) + Warn(message string, fields ...any) + Debug(message string, fields ...any) + Progress(message string, fields ...any) } diff --git a/internal/logging/logging_test.go b/internal/logging/logging_test.go deleted file mode 100644 index 2e3163c..0000000 --- a/internal/logging/logging_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package logging - -import ( - "bytes" - "log/slog" - "strings" - "testing" -) - -func TestNewLoggerWritesOutput(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(&buf, slog.LevelInfo) - - if logger == nil { - t.Fatal("logger is nil") - } - - logger.Info("hello", "component", "test") - out := buf.String() - if !strings.Contains(out, "hello") { - t.Fatalf("output = %q, want to contain message", out) - } -} - -func TestNewLoggerNilWriter(t *testing.T) { - logger := NewLogger(nil, slog.LevelInfo) - if logger == nil { - t.Fatal("logger is nil") - } - logger.Info("should not panic") -} diff --git a/internal/stage/reporting.go b/internal/stage/reporting.go new file mode 100644 index 0000000..6a34b3b --- /dev/null +++ b/internal/stage/reporting.go @@ -0,0 +1,22 @@ +package stage + +func (env *Env) Info(message string, fields ...any) { + if env != nil && env.Reporter != nil { + env.Reporter.Info(message, fields...) + } +} +func (env *Env) Warn(message string, fields ...any) { + if env != nil && env.Reporter != nil { + env.Reporter.Warn(message, fields...) + } +} +func (env *Env) Debug(message string, fields ...any) { + if env != nil && env.Reporter != nil { + env.Reporter.Debug(message, fields...) + } +} +func (env *Env) Progress(message string, fields ...any) { + if env != nil && env.Reporter != nil { + env.Reporter.Progress(message, fields...) + } +} diff --git a/internal/stage/stage.go b/internal/stage/stage.go index 9e3797a..1188811 100644 --- a/internal/stage/stage.go +++ b/internal/stage/stage.go @@ -2,7 +2,6 @@ package stage import ( "context" - "log/slog" "strings" "unicode/utf8" @@ -15,6 +14,7 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/adapters/whisperx" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" + "gitea.maximumdirect.net/eric/narratio/internal/logging" "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) @@ -25,7 +25,7 @@ type Env struct { EffectiveArtifacts artifacts.EffectiveArtifactSet ArtifactStore artifacts.Store ManifestStore manifest.Store - Logger *slog.Logger + Reporter logging.Reporter Force bool WhisperX whisperx.Client