obs

package
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package obs is the local observability layer: a structured event bus that feeds an append-only JSONL audit log and a local IPC host.

It exists because MCP stdio is a private channel between the AI client and jms: without it there is no independent, real-time, inspectable view of what the AI executed (DESIGN.md「可观测性」).

Index

Constants

View Source
const (
	// EnvAudit disables auditing when set to "off".
	EnvAudit = "JMS_AUDIT"
	// EnvAuditDir relocates the audit directory.
	EnvAuditDir = "JMS_AUDIT_DIR"
	// EnvAuditFull stores the untruncated output preview when set to "1".
	EnvAuditFull = "JMS_AUDIT_FULL"
	// EnvAuditPreviewBytes tunes the preview truncation limit.
	EnvAuditPreviewBytes = "JMS_AUDIT_PREVIEW_BYTES"
)

Environment switches (DESIGN.md「审计日志」).

View Source
const (
	// DefaultRingSize bounds the in-memory replay buffer.
	DefaultRingSize = 512
	// DefaultPreviewBytes truncates a captured output preview.
	DefaultPreviewBytes = 4096
)

Defaults.

View Source
const EnvAuditKeepDays = "JMS_AUDIT_KEEP_DAYS"

EnvAuditKeepDays is the retention window for the local audit files.

"0" disables pruning. Unset means "use the configuration file", and the configuration default is also 0: deleting audit records is not something a tool should start doing because nobody said otherwise.

Variables

View Source
var ErrInvalidKeepDays = errors.New("keep days must be at least 1")

ErrInvalidKeepDays reports a retention window that is not a positive number of days.

Functions

func AuditDirFrom added in v0.2.3

func AuditDirFrom(configured string) (string, error)

AuditDirFrom resolves the audit directory for a caller that computed a default: JMS_AUDIT_DIR wins, otherwise the configured value, otherwise the config directory's audit/ subdirectory.

It exists so the sink, the readers (`tail`, `log show`, `log prune`) and the retention check all agree. They used to disagree: the sink honoured JMS_AUDIT_DIR while the CLI's Runtime.AuditDir did not, so a relocated audit directory was written to one place and read from another.

func MarshalLine

func MarshalLine(e Event) ([]byte, error)

MarshalLine renders an event as one JSONL line, without a trailing newline.

It is the single place the on-disk encoding is decided, so the writer and any reader agree by construction.

func NewBusWithAudit

func NewBusWithAudit(ctx context.Context, opts AuditOptions) (*Bus, *AuditWriter, error)

NewBusWithAudit wires a bus to an audit writer when auditing is enabled.

JMS_AUDIT=off disables it; JMS_AUDIT_DIR relocates the directory; JMS_AUDIT_FULL=1 stores full output; JMS_AUDIT_PREVIEW_BYTES tunes the preview. An explicit AuditOptions field wins over its environment switch, so an injected test or a caller that already resolved the config does not have to unset the environment.

The returned bus is never nil, even when the writer is: a failed audit file still leaves IPC observation and `--last` replay working. On failure the error is returned together with the usable bus and a nil writer, leaving it to the caller to decide whether a missing audit log is fatal for the command it is about to run.

ctx is accepted for symmetry with the rest of the runtime and is unused: opening a file is synchronous, and the writer's lifetime ends at Close rather than at cancellation.

func NewBusWithLazyAudit added in v0.1.1

func NewBusWithLazyAudit(opts AuditOptions) (*Bus, *AuditSink, error)

NewBusWithLazyAudit wires a bus to a sink that opens its file on first event, and returns the bus plus that sink.

It is the CLI's variant of NewBusWithAudit: same environment switches and same non-blocking bus, but no empty audit file for a command that never recorded anything. The returned bus is never nil; the sink is nil when auditing is off, and the error reports an unusable audit location.

func ParseKeepDays added in v0.2.3

func ParseKeepDays(raw string) (int, error)

ParseKeepDays accepts an integer number of days, including "0" for "off".

It exists so the environment variable and the configuration file share one validation rule instead of each doing its own.

Types

type AuditOptions

type AuditOptions struct {
	// Dir is the audit directory; the empty value means <config_dir>/audit.
	Dir string
	// PreviewBytes truncates Preview; 0 means DefaultPreviewBytes.
	PreviewBytes int
	// Full disables truncation.
	Full bool
}

AuditOptions tunes an AuditWriter.

type AuditSink added in v0.1.1

type AuditSink struct {
	// contains filtered or unexported fields
}

AuditSink is a Subscriber that opens its per-pid file on the first event.

It exists for the CLI, where one Runtime is built for every invocation including read-only ones (`jms version`, `jms ls`): opening the file eagerly would leave an empty audit-*.jsonl behind for every command that never ran anything, and `jms tail` merges that whole directory. The directory is validated eagerly so a broken audit location is still reported before the command does its work, but no file is created until there is something to record.

func NewAuditSink added in v0.1.1

func NewAuditSink(opts AuditOptions) (*AuditSink, error)

NewAuditSink validates the audit location and returns a sink that will open its file on first use.

It honours the same environment switches as NewBusWithAudit: JMS_AUDIT=off disables auditing, JMS_AUDIT_DIR relocates the directory, JMS_AUDIT_FULL=1 stores full output and JMS_AUDIT_PREVIEW_BYTES tunes the preview. It returns (nil, nil) when auditing is off.

func (*AuditSink) Close added in v0.1.1

func (s *AuditSink) Close() error

Close flushes and closes the file, reporting any failure.

It is terminal and idempotent: every later call reports the first outcome, and a publish that arrives afterwards is dropped rather than reopening a file no one would close.

func (*AuditSink) Path added in v0.1.1

func (s *AuditSink) Path() string

Path returns the file path, or "" when it was never opened.

func (*AuditSink) Prepare added in v0.1.1

func (s *AuditSink) Prepare() error

Prepare creates the audit directory and verifies it is usable.

The long-lived host calls it at startup so a misconfigured audit location is reported before any tool call runs, rather than being discovered when the first event tries to land. One-shot commands skip it: their failure is reported by Close, after the work they were asked to do.

func (*AuditSink) Publish added in v0.1.1

func (s *AuditSink) Publish(e Event)

Publish implements Subscriber, opening the file on the first event.

A publish that arrives after Close is dropped: Close is terminal, and reopening here would leave a file no one closes.

type AuditWriter

type AuditWriter struct {
	// contains filtered or unexported fields
}

AuditWriter appends events as JSONL, one file per process.

Per-pid files avoid the Windows lock contention of several MCP instances appending to one file (DESIGN.md「审计日志」).

func NewAuditWriter

func NewAuditWriter(opts AuditOptions) (*AuditWriter, error)

NewAuditWriter opens the per-pid JSONL file.

The directory and the file are created 0600/0700 on Unix.

func (*AuditWriter) Close

func (w *AuditWriter) Close() error

Close flushes and closes the file.

It is idempotent: every call reports the same outcome as the first one, and later calls never touch the closed file. A write failure recorded by Publish is returned here, because a Subscriber has nowhere else to report it. It is safe on a nil writer, which is what NewBusWithAudit returns when auditing is disabled.

func (*AuditWriter) Path

func (w *AuditWriter) Path() string

Path returns the file path.

It returns "" for a nil writer (auditing disabled), so callers can print it without a nil check.

func (*AuditWriter) Publish

func (w *AuditWriter) Publish(e Event)

Publish implements Subscriber.

The writer owns the per-pid file, so it stamps its own pid on every line: a record whose pid contradicts the file name would make `jms tail`'s per-file attribution wrong. A write failure cannot be reported to the publisher, so it is remembered and returned by Close.

type Bus

type Bus struct {
	// contains filtered or unexported fields
}

Bus is a non-blocking event bus with a bounded replay ring.

A nil *Bus is usable and discards everything: callers carry an optional bus and "nil disables publication" is part of their contract (mcpserver.Options, cli.Runtime).

func NewBus

func NewBus(ringSize int) *Bus

NewBus returns an empty bus with a ring of size ringSize (0 means DefaultRingSize).

func (*Bus) Drain added in v0.1.1

func (b *Bus) Drain(timeout time.Duration) bool

Drain waits until every queued event has been handed to its subscriber.

It exists for the short-lived process: delivery is asynchronous by design, so a command that returns immediately after publishing would otherwise let os.Exit drop the very record of what it did. It reports false when the timeout expires first, which is the only outcome a stuck subscriber can produce; the caller decides whether that is worth reporting.

A nil bus drains instantly: nothing was ever queued.

func (*Bus) Dropped

func (b *Bus) Dropped() int64

Dropped reports how many deliveries were skipped.

func (*Bus) Last

func (b *Bus) Last(n int) []Event

Last returns up to n most recent events, oldest first.

func (*Bus) Publish

func (b *Bus) Publish(e Event)

Publish delivers e to every subscriber and records it in the ring.

A subscriber that blocks is skipped and counted: the execution path must never stall on a slow observer. Delivery is asynchronous, so a subscriber may observe an event after Publish has returned.

func (*Bus) Subscribe

func (b *Bus) Subscribe(s Subscriber)

Subscribe registers a subscriber.

Every call registers a delivery stream, so subscribing the same value twice delivers twice. Subscribers are identified for Unsubscribe by their interface value (see Unsubscribe).

A delivery goroutine drains each registration until Unsubscribe removes it. A Bus is therefore process-scoped, like the pools it feeds: a caller that registers a short-lived subscriber must unsubscribe it to release that goroutine.

func (*Bus) Unsubscribe

func (b *Bus) Unsubscribe(s Subscriber)

Unsubscribe removes every registration of s.

Events already queued for s are still delivered: they were published before the unsubscribe. No event published after Unsubscribe returns reaches s.

Subscribers are compared by their interface value: pointer-shaped subscribers are matched by identity. A SubscriberFunc is matched by its code pointer, because Go panics when an interface holding a function type is compared — two closures built from the same function literal are indistinguishable, so register a pointer-typed subscriber when that matters.

type Event

type Event struct {
	TS          time.Time `json:"ts"`
	PID         int       `json:"pid"`
	Actor       string    `json:"actor,omitempty"`
	Kind        Kind      `json:"kind"`
	Server      string    `json:"server,omitempty"`
	Asset       string    `json:"asset,omitempty"`
	Backend     string    `json:"backend,omitempty"`
	Endpoint    string    `json:"endpoint,omitempty"`
	Command     string    `json:"command,omitempty"`
	ExitCode    *int      `json:"exit_code,omitempty"`
	DurationMS  int64     `json:"duration_ms,omitempty"`
	OutputBytes int       `json:"output_bytes,omitempty"`
	Preview     string    `json:"preview,omitempty"`
	Pool        string    `json:"pool,omitempty"`
	IdleMS      int64     `json:"idle_ms,omitempty"`
	Reason      string    `json:"reason,omitempty"`
	Error       string    `json:"error,omitempty"`

	// Path and Status describe one management-API call (MIFA-73). Path is
	// the request path without the query string; Params carries the query
	// with credential-looking values masked, so a parameter such as
	// password=... never reaches the log.
	Path   string `json:"path,omitempty"`
	Params string `json:"params,omitempty"`
	Status int    `json:"status,omitempty"`
}

Event is one audit record. The JSON shape is the on-disk contract.

func ReadEvents added in v0.2.2

func ReadEvents(dir string) ([]Event, error)

ReadEvents reads every audit file in dir and returns the events ordered by timestamp.

The MCP surface uses this to expose the local audit stream the way `jms log show` does. `jms tail` keeps its own incremental reader because following a file needs byte offsets, which this whole-directory read does not track; both parse the same on-disk format, and this one is the reference for it.

A missing directory is not an error: it means nothing has been recorded yet.

type Kind

type Kind string

Kind enumerates the audit event types (DESIGN.md「审计日志」).

const (
	KindExecStart      Kind = "exec.start"
	KindExecEnd        Kind = "exec.end"
	KindPoolCold       Kind = "pool.cold"
	KindPoolHit        Kind = "pool.hit"
	KindPoolEvict      Kind = "pool.evict"
	KindPoolReap       Kind = "pool.reap"
	KindSessionLogin   Kind = "session.login"
	KindSessionRelogin Kind = "session.relogin"
	KindEndpointSelect Kind = "endpoint.select"
	KindError          Kind = "error"

	// management-API kinds (MIFA-73). They record one REST call rather
	// than one terminal session.
	//
	//   api.read    a management read succeeded or failed on the server
	//   api.write   a management write was attempted and its outcome
	//   api.denied  a call was refused locally, before any request
	KindAPIRead   Kind = "api.read"
	KindAPIWrite  Kind = "api.write"
	KindAPIDenied Kind = "api.denied"
)

Event kinds.

type PruneResult added in v0.2.3

type PruneResult struct {
	// Deleted is how many files were (or would be) removed.
	Deleted int
	// Kept is how many files are inside the window.
	Kept int
	// Skipped is how many file names could not be dated and were left alone.
	Skipped int
	// FreedBytes is the size of the removed files.
	FreedBytes int64
	// Cutoff is the oldest date still kept, at local midnight.
	Cutoff time.Time
	// DryRun reports whether anything was actually removed.
	DryRun bool
}

PruneResult describes one prune run.

func PruneAuditFiles added in v0.2.3

func PruneAuditFiles(dir string, keepDays int, now time.Time, dryRun bool) (PruneResult, error)

PruneAuditFiles removes audit files older than keepDays.

The age is read from the FILE NAME, not the modification time. A copied or restored directory resets mtime, and a prune that trusted mtime would then keep files that are years past the window — the direction of that mistake is "keeps too much", which nobody notices until the directory is huge.

Files whose names cannot be dated are skipped rather than deleted: an unexpected name is a reason to look, not a reason to remove.

A missing directory is not an error; it means nothing has been recorded yet.

func PruneIfDue added in v0.2.3

func PruneIfDue(dir string, keepDays int, now time.Time, dryRun bool) (PruneResult, bool, error)

PruneIfDue runs PruneAuditFiles at most once per interval.

A stamp file records the last run, so the long-lived MCP host and the short-lived CLI both prune without turning a directory scan into a per-command cost. A stamp that cannot be read or written is not fatal: pruning is housekeeping, and it must never be the reason a command fails.

func (PruneResult) String added in v0.2.3

func (r PruneResult) String() string

String renders a one-line summary for logs and command output.

type Subscriber

type Subscriber interface {
	// Publish delivers one event. It must not block indefinitely.
	Publish(Event)
}

Subscriber receives events. A slow subscriber must never block the publisher (DESIGN.md「可观测性」).

type SubscriberFunc

type SubscriberFunc func(Event)

SubscriberFunc adapts a function to Subscriber.

func (SubscriberFunc) Publish

func (f SubscriberFunc) Publish(e Event)

Publish calls f.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL