From 86d3071f391452a29da87ad302215da9a6810edf Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 9 Aug 2026 16:23:24 +1000 Subject: [PATCH 1/2] fix(workflow): carry gate output into the baseline park error StageBaselineGate captured a failing gate command's full output but discarded it: a 200-char clip went into a Warn log, and the terminal error carried only res.Status. A park reason like "go build ./... fails ... (status: failed)" gave no way to see the actual compiler error, and the container that had it is already gone (AutoRemove). Now the park error carries a bounded tail of the real output (tail, not head, since a failing test's explanation is at the end after pages of "ok" lines), rune-safe so it can't emit invalid UTF-8 into a persisted park reason. The three existing byte bounds in this stage (log line, agent mission, park error) are named and documented as independently sized rather than left as bare numbers. Also adds docs/architecture/observability.md, the design doc for the larger task-observability epic (#450) this fix is the first step of. --- docs/architecture/observability.md | 158 +++++++++++++++++++++ internal/domain/workflow/implement.go | 27 +++- internal/domain/workflow/implement_test.go | 81 +++++++++++ internal/domain/workflow/workflow.go | 22 +++ 4 files changed, 284 insertions(+), 4 deletions(-) create mode 100644 docs/architecture/observability.md diff --git a/docs/architecture/observability.md b/docs/architecture/observability.md new file mode 100644 index 000000000..21b5d6b0a --- /dev/null +++ b/docs/architecture/observability.md @@ -0,0 +1,158 @@ +# Task Observability + +**Status:** Approved, not yet implemented +**Date:** 2026-08-09 + +## Problem + +archied's own daemon logging (`internal/logging/`) is solid: a rotating file +sink, a live `Feed` the dashboard subscribes to, and a reader the `/api/logs` +endpoint serves from. None of that reaches inside a task. + +A task's actual work happens in an `archie-agent` container, dispatched over +NATS (`[agent] mode = "nats"` is the only supported mode; the in-process +runner exists for tests and is being migrated away — see +[Decision: no new functionality on non-NATS transports](#decision-no-new-functionality-on-non-nats-transports)). +Four things currently destroy the evidence of what that container did: + +1. **`cmd/archie-agent/main.go`** logs to `os.Stderr` only + (`log := slog.New(slog.NewJSONHandler(os.Stderr, nil))`). Nothing captures + it outside the container. +2. **`internal/container/pool.go`** creates every task container with + `AutoRemove: true`. The container — and its stderr — is gone at exit, + success or failure alike. +3. **`internal/domain/workflow/implement.go`, `StageBaselineGate`** captures + `go build`/`go vet`/`go test` output via `cmd.CombinedOutput()`, then + clips it to 200 characters into a `Warn` log line and discards the rest. + The eventual park reason is built from `res.Status` alone — the actual + compiler error is never persisted anywhere a human or Archie's own chat + tools can read it back. +4. **`agentexec.Result`** (`internal/agentexec/protocol.go`) carries only + `Summary`/`Detail` — no step-by-step transcript (tool calls, durations, + errors). There is no transcript to recover even in principle. +5. **`agentexec.SubjectForSystem`** is documented as the return channel for + exactly this — *"log dumps, health, and PII warnings... the daemon reads + these for observability and never forwards them"* — but has no publisher + and no consumer anywhere in the codebase except a subject-format + assertion in `nats_test.go`. The designed return path was never wired. + +The practical consequence: a task parks with +`stage baseline: baseline red -- go build ./... fails and builder could not +auto-fix (status: parked)` and there is no way — not from the dashboard, not +from Telegram chat, not by SSH'ing into the deployment host — to see *why* +`go build` failed. The container that knew is already gone. + +This matters beyond debugging convenience: the deployment model +(`CLAUDE.md` "Deployment model") is a systemd daemon plus ephemeral Docker +containers that may run unattended for weeks between operator logins, and is +intended to be usable by people other than the original operator. A system +that is only debuggable by an operator who happens to be watching `docker ps` +in real time does not meet that bar. + +## Decision: NATS is the only transport this feature targets + +`[agent] mode = "nats"` is the supported deployment; the agent image must +already be able to reach NATS in every deployment, because it is the *only* +channel carrying stage results back to the daemon — if it can't reach NATS, +the task cannot complete regardless of logging. The in-process runner +(`agentexec.InProcessRunner`) exists for tests and is being migrated away. +New functionality is NOT added to it or to any non-NATS path. A container +that dies before establishing a NATS connection is a distinct, narrower +failure (connectivity/config) from the one this document addresses (a +connected container's own output being unrecoverable), and is out of scope +here. + +## Design + +The key property: **logs leave the container while it is alive**, so its +death at `AutoRemove` no longer matters. Persistence happens in the daemon +process, which already owns durable state. + +### Sink: extend `internal/logging`, not a new package + +`internal/logging` already owns its on-disk format end to end per +`organisation.md` ("a package owns its own format end to end"). Add a +task-scoped writer producing the same `logging.Entry` JSONL shape at +`/logs/tasks//attempt-.jsonl`. `logging.Tail`, +`logging.Query`, and `logging.Components` operate on this unchanged; +`internal/webui/api_logs.go` stays transport-only, as it does today. + +### Agent side: make the designed subject real + +`cmd/archie-agent/main.go` replaces the stderr-only `slog.Handler` with one +that tees to stderr (kept for container-level operator debugging when a +shell is attached) and publishes each record to +`agentexec.SubjectForSystem(taskID)`, which already exists for this purpose +and already has zero consumers to conflict with. The agent already holds its +NATS client and task ID (`bootTaskID`, read from +`/.git/task.json` per the container/pool.go trap documented in +`CLAUDE.md`). Publishing is fire-and-forget with a bounded local buffer: log +shipping must never block or fail the run it is reporting on. + +### Daemon side + +Subscribe `agentexec.SubjectAgentWildcard` ("archie.agent.>") for the +`.system` suffix once at startup (app-layer wiring — this composes the +domain's log sink with the infrastructure NATS subscription, so it lives in +`internal/app/`, not in `internal/domain/workflow` or `internal/nats` +directly). Demux by task ID, append to that task's sink, and also publish +into the existing `logging.Feed` so live task output appears on the +dashboard exactly like daemon output does today. + +### Gate output: stop discarding it + +`StageBaselineGate` and the equivalent TDD-stage gate runs write full +`cmd.CombinedOutput()` to the task's sink under a `gate` component, and put a +bounded tail (~2KB, not 200 bytes) into the park reason. This is the cheapest +fix and independently valuable — it alone would have made the `go build` +failure diagnosable without any NATS plumbing. + +### Transcript + +Step-level events (tool name, argument digest, duration, error) are emitted +as log entries on the same NATS system subject rather than added as new +fields on `agentexec.Result`. This keeps the wire protocol +(`internal/agentexec/protocol.go`) stable and the transcript lands in the +sink automatically, with no separate delivery path to keep consistent. + +### Retention + +Reuse the existing rotation (`MaxSizeMB`/`Keep`) semantics per task +directory. Prune a task's log directory when `nell.ArchiveTask` +(`internal/nell/adapter.go`) archives it, so task logs share the task's own +lifecycle rather than accumulating independently. + +### Surfaces + +- `/api/tasks/{id}/logs`, built on `logging.Reader` the same way + `/api/logs` is today. +- A chat tool so Archie can answer "why did task 4 park?" directly from + Telegram or the webui chat — this is the surface that actually matters + for the deployment model in `CLAUDE.md`, where an operator may not be + looking at a dashboard at all. + +## Dependency direction + +`internal/logging` remains cross-cutting per `organisation.md` — it imports +no domain, infrastructure, or app package, so extending it to be task-scoped +does not change its classification. The workflow domain writes through an +interface it declares (a `TaskLogSink` or equivalent, not a direct +`internal/logging` import into `internal/domain/workflow`, unless +`internal/logging` is judged to already be an acceptable cross-cutting +dependency for a domain package — confirm against `organisation.md`'s +concrete rule before writing the interface). `internal/app` wires the NATS +subscription to the sink; `internal/agentexec` and `internal/nats` supply +the transport underneath. + +## Sequencing + +1. Gate-output capture (~30 lines, no NATS changes) — fixes the immediate + symptom that prompted this document. +2. Task log sink in `internal/logging`. +3. Agent-side publisher on `SubjectForSystem`. +4. Daemon-side subscriber + `logging.Feed` integration + retention on + archive. +5. `/api/tasks/{id}/logs` + chat tool. + +Tracked as GitHub epic/subtasks per the issue list linked from this +document's PR. diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go index 4b7cd6bcc..18f308c5d 100644 --- a/internal/domain/workflow/implement.go +++ b/internal/domain/workflow/implement.go @@ -9,6 +9,25 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" ) +// Bounds on how much of a failing gate command's output rides along at each +// point in this stage. They serve different purposes and are sized +// independently, not derived from one another: +// - baselineWarnLogBytes is a daemon log line -- kept short so one baseline +// failure doesn't dominate the log around it. +// - baselineMissionBytes is what the builder agent sees -- generous, since +// it needs enough context to actually diagnose the failure. +// - baselineParkOutputBytes is what a human (or Archie's own chat tools) +// sees in the park reason when the builder couldn't fix it. It used to +// be zero: the returned error carried only a status string, so a park +// reason like "go build ./... fails ... (status: failed)" gave no way to +// see the actual compiler error. It stays comfortably under the store's +// own park-reason cap (see internal/store's Task.ParkReason clip). +const ( + baselineWarnLogBytes = 200 + baselineMissionBytes = 3000 + baselineParkOutputBytes = 2048 +) + // StageBaselineGate verifies the repo's gate is green at the base commit. // If the gate is red due to pre-existing failures, the builder attempts to // fix them via TDD before proceeding. Only parks if the builder cannot fix @@ -27,7 +46,7 @@ func StageBaselineGate() Stage { } tc.Log.Warn("baseline red -- auto-fixing pre-existing gate failure", "cmd", strings.Join(argv, " "), - "err", clip(string(out), 200)) + "err", clip(string(out), baselineWarnLogBytes)) // Run builder to fix the failure via TDD. mission := fmt.Sprintf( @@ -41,7 +60,7 @@ func StageBaselineGate() Stage { "5. Repeat until the gate `%s` passes for all packages\n\n"+ "Gate output:\n%s\n\n"+ "When the gate passes, call finish with status \"passed\".", - strings.Join(argv, " "), tc.Repo.FullName(), strings.Join(argv, " "), clip(string(out), 3000), + strings.Join(argv, " "), tc.Repo.FullName(), strings.Join(argv, " "), clip(string(out), baselineMissionBytes), ) modelRef := tc.Cfg.Models["builder"] @@ -67,8 +86,8 @@ func StageBaselineGate() Stage { return fmt.Errorf("baseline-fix agent run: %w", agentErr) } if res.Status != agentexec.StatusPassed { - return fmt.Errorf("baseline red -- %s fails and builder could not auto-fix (status: %s)", - strings.Join(argv, " "), res.Status) + return fmt.Errorf("baseline red -- %s fails and builder could not auto-fix (status: %s)\n\ngate output:\n%s", + strings.Join(argv, " "), res.Status, clipTail(string(out), baselineParkOutputBytes)) } // Commit the baseline fix. diff --git a/internal/domain/workflow/implement_test.go b/internal/domain/workflow/implement_test.go index 2bb358eb6..44bf691bb 100644 --- a/internal/domain/workflow/implement_test.go +++ b/internal/domain/workflow/implement_test.go @@ -3,8 +3,14 @@ package workflow import ( "context" "errors" + "log/slog" + "os" + "path/filepath" + "strconv" + "strings" "testing" + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/store" @@ -155,6 +161,81 @@ func TestStageCommitPushDoesNotUseSyntheticIssueForChatNoOp(t *testing.T) { } } +// alwaysFailingRunner reports the gate as unfixable, so StageBaselineGate +// falls through to its terminal error without needing a real agent loop. +var alwaysFailingRunner = agentRunnerFunc(func(context.Context, string, agentexec.Request) (agentexec.Result, error) { + return agentexec.Result{Status: "failed"}, nil +}) + +// TestStageBaselineGateParkErrorCarriesGateOutput guards against the gate's +// real failure output being thrown away. StageBaselineGate used to build the +// park error from res.Status alone -- the actual compiler/test error was +// never in it at all, so a park reason like "go build ./... fails ... +// (status: failed)" gave no way to see why. It also guards the direction and +// size of the bound: baselineParkOutputBytes keeps the *tail* of the output +// (where a test runner's failure detail lives, after pages of "ok" lines), +// not the head, and must actually truncate rather than always including +// everything regardless of the constant's value. +func TestStageBaselineGateParkErrorCarriesGateOutput(t *testing.T) { + tests := []struct { + name string + script string // shell body; markers must appear only in output, never in argv + wantContains []string + wantNotContain []string + }{ + { + name: "short output is included in full", + script: "echo shortmarker", + wantContains: []string{"shortmarker"}, + }, + { + name: "long output is bounded to the tail", + // filler comfortably exceeds baselineParkOutputBytes so the + // head marker falls outside the kept window and the tail + // marker falls inside it. + script: "echo headmarker; " + + "head -c " + strconv.Itoa(baselineParkOutputBytes*2) + " /dev/zero | tr '\\0' 'y'; " + + "echo; echo tailmarker", + wantContains: []string{"tailmarker"}, + wantNotContain: []string{"headmarker"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "gate.sh") + if err := os.WriteFile(script, []byte("#!/bin/sh\n"+tt.script+"\nexit 1\n"), 0o755); err != nil { + t.Fatal(err) + } + + tc := &TaskContext{ + Task: &store.Task{ID: 1, Owner: "o", Repo: "r"}, + Repo: config.Repo{Gate: [][]string{{"sh", script}}}, + Cfg: config.Config{}, + Agent: alwaysFailingRunner, + Dir: dir, + Log: slog.New(slog.DiscardHandler), + } + + err := StageBaselineGate().Run(context.Background(), tc) + if err == nil { + t.Fatal("expected an error when the baseline gate is unfixable") + } + for _, want := range tt.wantContains { + if !strings.Contains(err.Error(), want) { + t.Errorf("park error missing %q: %v", want, err) + } + } + for _, notWant := range tt.wantNotContain { + if strings.Contains(err.Error(), notWant) { + t.Errorf("park error contains %q, want truncated away: %v", notWant, err) + } + } + }) + } +} + // LinkBranch is cosmetic: it puts the branch in the issue's sidebar on Gitea // and does nothing at all on GitHub. Failing the stage on it meant the pull // request -- the entire point of the run -- was never opened, and the task diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 937eb7426..e1354bc92 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -11,6 +11,7 @@ import ( "log/slog" "sort" "time" + "unicode/utf8" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" @@ -285,3 +286,24 @@ func clip(s string, n int) string { } return s[:n] + "\n…(truncated)" } + +// clipTail keeps the last n bytes of s, breaking on a rune boundary so a +// multi-byte character straddling the cut point isn't split into invalid +// UTF-8 -- this return value can be persisted (e.g. into a task's park +// reason), not just logged, so mangled bytes would survive past this call. +// +// Head-clipping (clip, above) is right when the useful part comes first, +// such as a compiler error. It is wrong for command output where the +// explanation is at the end, such as a test runner's "--- FAIL" block after +// pages of "ok" lines -- clip would keep exactly the part that doesn't say +// why it failed. +func clipTail(s string, n int) string { + if len(s) <= n { + return s + } + cut := len(s) - n + for cut < len(s) && !utf8.RuneStart(s[cut]) { + cut++ + } + return "…(truncated)\n" + s[cut:] +} From a7f33fcb032664f3d2c97c42818a380a2c6f9004 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 9 Aug 2026 16:32:52 +1000 Subject: [PATCH 2/2] feat(logging): add a per-task log sink Part of #452 (task-observability epic #450). A task's real work happens in an ephemeral archie-agent container; currently nothing persists what it logs once the container exits (AutoRemove: true). Adds TaskSink: a per-task, per-attempt JSONL log destination sharing the exact on-disk format the daemon-wide logger already writes (see Entry/Tail/Query/Components in reader.go), so a task's history is readable with the same reader rather than a second format to keep in sync. Backed by the existing rotatingFile, so it gets the same size-based rotation and retention as the daemon-wide log for free. Deliberately does not fall back to stderr on open failure the way the daemon-wide New does: that fallback exists because losing the daemon over a broken log path is worse than losing the durable copy, and there is no equivalent daemon-level fallback for one task's log. This lands only the sink primitive and its own tests. Wiring an agent-side publisher and a daemon-side NATS consumer into it is tracked separately in #453 and #454. --- internal/logging/tasksink.go | 65 ++++++++++ internal/logging/tasksink_test.go | 190 ++++++++++++++++++++++++++++++ 2 files changed, 255 insertions(+) create mode 100644 internal/logging/tasksink.go create mode 100644 internal/logging/tasksink_test.go diff --git a/internal/logging/tasksink.go b/internal/logging/tasksink.go new file mode 100644 index 000000000..eee7cb98e --- /dev/null +++ b/internal/logging/tasksink.go @@ -0,0 +1,65 @@ +package logging + +import ( + "fmt" + "log/slog" + "path/filepath" + "strconv" +) + +// TaskLogPath returns the log file path for one task attempt under baseDir +// (typically /logs/tasks). Each task gets its own subdirectory so +// an attempt's rotated generations (attempt-N.jsonl.1, .2, ...) stay grouped +// with that task rather than interleaved with every other task's. +func TaskLogPath(baseDir string, taskID int64, attempt int) string { + return filepath.Join(baseDir, strconv.FormatInt(taskID, 10), fmt.Sprintf("attempt-%d.jsonl", attempt)) +} + +// TaskSinkOptions configures a per-task log sink. The zero value selects the +// same defaults as the daemon-wide log: DefaultMaxSizeMB, DefaultKeep, and +// info level. +type TaskSinkOptions struct { + // MaxSizeMB rotates the file once it exceeds this size. Zero selects + // DefaultMaxSizeMB. + MaxSizeMB int + // Keep is how many rotated files to retain. Zero selects DefaultKeep. + Keep int + // Level is "debug", "info", "warn" or "error". Empty selects info. + Level string +} + +// TaskSink is a per-task, per-attempt log destination. It writes the same +// on-disk JSONL shape as the daemon-wide log (see Entry, Tail, Query, +// Components), so a task's history is readable with the same reader -- +// there is deliberately no second log format to keep in sync. +type TaskSink struct { + logger *slog.Logger + file *rotatingFile +} + +// NewTaskSink opens the JSONL sink for one task attempt under baseDir, +// creating its directory if needed, with the same size-based rotation as +// the daemon-wide log. +// +// Unlike New (the daemon-wide logger), a task sink that fails to open +// returns the error rather than falling back to stderr: New degrades +// because losing the daemon over a broken log path is worse than losing the +// durable copy, but there is no equivalent daemon-level fallback for one +// task's log -- the caller (a workflow stage, or the daemon's NATS log +// consumer) is better placed to decide what a missing sink means for that +// task than this package is. +func NewTaskSink(baseDir string, taskID int64, attempt int, opts TaskSinkOptions) (*TaskSink, error) { + path := TaskLogPath(baseDir, taskID, attempt) + w, err := newRotatingFile(path, opts.MaxSizeMB, opts.Keep) + if err != nil { + return nil, fmt.Errorf("logging: open task sink %s: %w", path, err) + } + handler := slog.NewJSONHandler(w, &slog.HandlerOptions{Level: parseLevel(opts.Level)}) + return &TaskSink{logger: slog.New(handler), file: w}, nil +} + +// Logger returns the slog.Logger writing to this sink. +func (s *TaskSink) Logger() *slog.Logger { return s.logger } + +// Close closes the underlying file. +func (s *TaskSink) Close() error { return s.file.Close() } diff --git a/internal/logging/tasksink_test.go b/internal/logging/tasksink_test.go new file mode 100644 index 000000000..d5b18c488 --- /dev/null +++ b/internal/logging/tasksink_test.go @@ -0,0 +1,190 @@ +package logging + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestTaskLogPath(t *testing.T) { + tests := []struct { + name string + baseDir string + taskID int64 + attempt int + want string + }{ + {"first attempt", "/var/log/archie/tasks", 42, 1, "/var/log/archie/tasks/42/attempt-1.jsonl"}, + {"later attempt", "/var/log/archie/tasks", 42, 3, "/var/log/archie/tasks/42/attempt-3.jsonl"}, + {"different task", "/var/log/archie/tasks", 7, 1, "/var/log/archie/tasks/7/attempt-1.jsonl"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := TaskLogPath(tt.baseDir, tt.taskID, tt.attempt) + want := filepath.FromSlash(tt.want) + if got != want { + t.Errorf("TaskLogPath(%q, %d, %d) = %q, want %q", tt.baseDir, tt.taskID, tt.attempt, got, want) + } + }) + } +} + +// TestNewTaskSinkWritesEntriesReadableByTail pins that a task sink's on-disk +// format is exactly what Tail/Query/Components already know how to parse -- +// a task's log history must be readable with the same reader the daemon-wide +// log uses, not a second incompatible format. +func TestNewTaskSinkWritesEntriesReadableByTail(t *testing.T) { + baseDir := t.TempDir() + + sink, err := NewTaskSink(baseDir, 42, 1, TaskSinkOptions{}) + if err != nil { + t.Fatalf("NewTaskSink: %v", err) + } + sink.Logger().Warn("gate failed", "component", "gate", "cmd", "go build ./...") + if err := sink.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + path := TaskLogPath(baseDir, 42, 1) + result, err := Tail(path, Query{}) + if err != nil { + t.Fatalf("Tail: %v", err) + } + if len(result.Entries) != 1 { + t.Fatalf("got %d entries, want 1: %+v", len(result.Entries), result.Entries) + } + entry := result.Entries[0] + if entry.Message != "gate failed" { + t.Errorf("Message = %q, want %q", entry.Message, "gate failed") + } + if entry.Level != "WARN" { + t.Errorf("Level = %q, want WARN", entry.Level) + } + if got := entry.Fields["component"]; got != "gate" { + t.Errorf("Fields[component] = %v, want gate", got) + } +} + +func TestNewTaskSinkCreatesNestedTaskDirectory(t *testing.T) { + baseDir := t.TempDir() + + sink, err := NewTaskSink(baseDir, 99, 1, TaskSinkOptions{}) + if err != nil { + t.Fatalf("NewTaskSink: %v", err) + } + t.Cleanup(func() { _ = sink.Close() }) + + if _, err := os.Stat(TaskLogPath(baseDir, 99, 1)); err != nil { + t.Errorf("task log file not created: %v", err) + } +} + +// TestNewTaskSinkHonoursRotationOptions confirms TaskSinkOptions.MaxSizeMB +// and .Keep both actually reach the underlying rotatingFile, not just +// MaxSizeMB. Writing enough to rotate past DefaultKeep (5) generations while +// asking for Keep: 2 is deliberate: if Keep were silently dropped and +// defaulted, generation .3 would still exist and this test would catch it -- +// a smaller write volume that only ever produces 1-2 rotations would pass +// whether or not Keep was wired through at all. Rotation ordering itself +// (which generation holds what) is already covered by TestRotation; this +// only checks that TaskSink forwards both options. +func TestNewTaskSinkHonoursRotationOptions(t *testing.T) { + baseDir := t.TempDir() + + sink, err := NewTaskSink(baseDir, 1, 1, TaskSinkOptions{MaxSizeMB: 1, Keep: 2}) + if err != nil { + t.Fatalf("NewTaskSink: %v", err) + } + line := strings.Repeat("x", 64*1024) + for range 200 { // ~12MB against a 1MB cap: well past DefaultKeep (5) generations. + sink.Logger().Info(line) + } + if err := sink.Close(); err != nil { + t.Fatal(err) + } + + path := TaskLogPath(baseDir, 1, 1) + for i := 1; i <= 2; i++ { + if _, err := os.Stat(fmt.Sprintf("%s.%d", path, i)); err != nil { + t.Errorf("rotated file .%d missing, want rotation to have engaged: %v", i, err) + } + } + if _, err := os.Stat(path + ".3"); err == nil { + t.Error("generation .3 exists, want retention capped at Keep=2 (not the default of 5, " + + "which .3 surviving would indicate Keep was dropped)") + } +} + +func TestNewTaskSinkLevelFiltersEntries(t *testing.T) { + baseDir := t.TempDir() + + sink, err := NewTaskSink(baseDir, 1, 1, TaskSinkOptions{Level: "warn"}) + if err != nil { + t.Fatalf("NewTaskSink: %v", err) + } + sink.Logger().Info("info-line") + sink.Logger().Warn("warn-line") + if err := sink.Close(); err != nil { + t.Fatal(err) + } + + body, err := os.ReadFile(TaskLogPath(baseDir, 1, 1)) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(body), "info-line") { + t.Error("info-line present, want it filtered at warn level") + } + if !strings.Contains(string(body), "warn-line") { + t.Error("warn-line missing") + } +} + +// TestNewTaskSinkRejectsUnusableDirectory confirms a task sink surfaces the +// error instead of quietly falling back -- unlike the daemon-wide New, which +// intentionally degrades to stderr because losing the daemon over a log path +// is worse than losing the durable copy. A task sink has no such tradeoff: +// there is no equivalent fallback destination for one task's log, so a task +// sink that fails to open should fail loudly and let the caller decide. +func TestNewTaskSinkRejectsUnusableDirectory(t *testing.T) { + blocker := filepath.Join(t.TempDir(), "not-a-dir") + if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + + _, err := NewTaskSink(blocker, 1, 1, TaskSinkOptions{}) + if err == nil { + t.Error("NewTaskSink returned nil error for an unusable base directory") + } +} + +func TestTaskSinkOutputIsValidJSONLines(t *testing.T) { + baseDir := t.TempDir() + sink, err := NewTaskSink(baseDir, 1, 1, TaskSinkOptions{}) + if err != nil { + t.Fatalf("NewTaskSink: %v", err) + } + sink.Logger().Info("one") + sink.Logger().Info("two") + if err := sink.Close(); err != nil { + t.Fatal(err) + } + + body, err := os.ReadFile(TaskLogPath(baseDir, 1, 1)) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(body)), "\n") + if len(lines) != 2 { + t.Fatalf("got %d lines, want 2", len(lines)) + } + for _, line := range lines { + var raw map[string]any + if err := json.Unmarshal([]byte(line), &raw); err != nil { + t.Errorf("line is not JSON: %v (%q)", err, line) + } + } +}