Files
archie/internal/logging/tasksink.go
T
sam 951ddbc9f4 feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
Closes the loop #451-#453 opened. archie-agent (#453) now publishes its
own logs to agentexec.SubjectForSystem(taskID) over NATS, and a task
log sink (#452) exists to persist them, but nothing on the daemon side
subscribed, demuxed, or wrote anything -- the messages had nowhere to
land.

- agentexec: SubjectSystemWildcard + TaskIDFromSystemSubject, the
  inverse of SubjectForSystem, for a daemon subscribing to every
  task's system subject with one wildcard subscription.
- logging: TaskRegistry manages one open TaskSink per running task
  attempt, mirroring every write onto the live dashboard Feed the same
  way a locally-written log would appear. Nil-receiver-safe, matching
  every other optional composition-wired Daemon field.
- daemon: Daemon.process opens a task's log sink for its own duration
  (covering both the sandboxed-container and in-process dispatch
  paths uniformly) and closes it on every return path.
- cmd/archied: constructs the registry, subscribes core NATS to
  SubjectSystemWildcard, and wires TaskLogs into both Daemon and
  webui.Server.
- webui: archiving a task now removes its log directory too, so
  archived tasks' logs don't accumulate forever. Documented as a
  known, accepted race: a task can reach terminal status (satisfying
  ArchiveTask's precondition) before process() itself returns and
  closes the sink, so a very late system-log write can race an
  archive's Remove. Not corrupting -- the write lands on a
  soon-to-be-unlinked inode and is discarded -- and not worth fixing
  here: it would mean tying Close to the store transition instead of
  to process()'s return, a larger change than this issue's scope.

Adversarial review (fresh subagent) found and fixed two real issues in
the first draft: a doc comment accidentally spliced between two
functions during an extraction meant to fix a lint regression, and a
genuine test gap on openTaskLog (added, using TaskRegistry.Write's own
true/false contract as the observable -- no Store/Forge/Trees fakes
needed, since openTaskLog only touches TaskLogs and Log).
2026-08-09 18:42:54 +10:00

72 lines
2.8 KiB
Go

package logging
import (
"fmt"
"log/slog"
"path/filepath"
"strconv"
)
// TaskLogDir returns the directory holding every attempt's log files for one
// task under baseDir (typically <state_dir>/logs/tasks).
func TaskLogDir(baseDir string, taskID int64) string {
return filepath.Join(baseDir, strconv.FormatInt(taskID, 10))
}
// TaskLogPath returns the log file path for one task attempt under baseDir.
// Each task gets its own subdirectory (TaskLogDir) 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(TaskLogDir(baseDir, taskID), 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() }