diff --git a/internal/app/controlplane/channel_settings.go b/internal/app/controlplane/channel_settings.go index 903b021d7..e808c5a3a 100644 --- a/internal/app/controlplane/channel_settings.go +++ b/internal/app/controlplane/channel_settings.go @@ -8,12 +8,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) -// The channel-settings DOCUMENT lives in internal/infrastructure/controlplanerpc, -// beside the client that projects it, so a process that only reads stored -// settings does not link this package's store-backed server and workflow engine. -// These aliases keep the store-backed side reading the same -// types by the same names it always used, so there is one definition of the -// document rather than a copy on each side of the boundary. +// Aliases for the channel-settings document defined in controlplanerpc. type ( channelSettings = controlplanerpc.ChannelSettings telegramSettings = controlplanerpc.TelegramSettings @@ -51,12 +46,7 @@ func validateChannels(input []byte) error { }) } -// normalizeChannels canonicalizes the stored document: decoding into the shape -// above and re-encoding writes the snake_case keys and the string duration, -// dropping the Go-cased keys an earlier revision stored. A document that still -// carries them converges the next time it is written; reads tolerate them -// meanwhile (emailSettings, rateLimitSettings), so nothing has to be re-saved -// before it can be read again. +// normalizeChannels re-encodes the stored document with snake_case keys. func normalizeChannels(input []byte) ([]byte, error) { var settings channelSettings if err := json.Unmarshal(input, &settings); err != nil { diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index a2a312e31..44d5663f9 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -16,17 +16,8 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) -// Client is the control-plane client for every resource that does not resolve -// a workflow step type: catalog, history, settings, personas, schedules. It -// carries no step vocabulary, so a process that never reads or writes a -// workflow definition -- archie-messaging, which only loads channel settings, -// and archie-gateway, which reads catalog, runtime settings and personas -- -// needs no provider set and cannot be failed by one. -// Client is the control-plane client a process that serves the store uses. It -// embeds the Messaging Service's client -- the generic resource read path and -// the channel-settings projection -- and adds the resource-specific reads and -// watches, which need the workflow and scheduling engines that such a process -// already links. +// Client reads and watches control-plane resources. It embeds the Messaging +// Service's client and adds resource-specific reads. type Client struct { *controlplanerpc.Client rpc pb.ControlPlaneServiceClient @@ -43,11 +34,7 @@ func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { } // WorkflowDefinitionsClient reads and replaces the workflow-definitions -// resource, the one control-plane surface whose stored values name workflow -// step types. Resolving those names needs the step vocabulary the process -// registered at its composition root, so the vocabulary is a constructor -// dependency of this surface and of no other: a caller that cannot reach -// workflow definitions cannot ask for one. +// resource, resolving step types against the given vocabulary. type WorkflowDefinitionsClient struct { rpc pb.ControlPlaneServiceClient steps workflow.StepRegistry @@ -78,13 +65,8 @@ func (c *WorkflowDefinitionsClient) WorkflowDefinitions(ctx context.Context) (wo return definitions, response.Resource.Version, err } -// ReplaceWorkflowDefinitions replaces the collection. Passing -// workflow.ShippedDefinitions() restores all shipped definitions while keeping -// the previous override in resource history. -// -// No production process calls it today: the daemon's only consumer of this -// surface reads (internal/daemon's WorkflowDefinitions interface), so this half -// is reached by tests until a writer exists. +// ReplaceWorkflowDefinitions replaces the collection, keeping the previous +// value in history. func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Context, definitions workflow.WorkflowDefinitionCollection, expectedVersion int64, actor, source, requestID string) (int64, error) { value, err := encodeWorkflowDefinitions(definitions, c.steps) if err != nil { @@ -134,23 +116,14 @@ func (c *Client) WatchWorkflowExecutionSettings(ctx context.Context, afterVersio func(err error) AppliedSettings { return AppliedSettings{Err: err} }), nil } -// AppliedResource carries a watched resource's version only, without its -// document. The kinds applied with it are applied by re-running the whole -// layering, which reads every kind back from the store, so the document the -// stream carries would be decoded and then thrown away; a stored value this -// build cannot read is reported by the layering that refuses it (with -// last-known-good kept), not by the watch. +// AppliedResource is a watched resource's version, without its document. type AppliedResource struct { Version int64 Err error } -// WatchResource streams version updates for any resource kind without -// decoding the document. It is the shape the runtime-resource watches read: -// keepWatch reconnects on it exactly as it does on a -// typed stream, and the resume point still moves past a document the client -// refused to decode -- the store answered with that version, and resuming -// before it would re-offer it on every reconnect. +// WatchResource streams version updates for a resource kind without decoding +// documents. func (c *Client) WatchResource(ctx context.Context, kind string, afterVersion int64) (<-chan AppliedResource, error) { stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, kind, afterVersion)) if err != nil { @@ -224,13 +197,7 @@ func watchUpdates[T any]( return out } -// sendUpdate hands update to the reader of one Watch stream, reporting false -// when ctx ended first. A reader leaves without draining what is left for it: -// the watch that reads these streams returns on cancellation, so a bare send -// parks this producer -- and the stream it holds -- for the rest of the -// process's life, one goroutine and one channel per kind at every exit. That -// coupling is load-bearing: the reader's prompt shutdown rests on this side -// stopping on the same context, and neither half is safe alone. +// sendUpdate sends update to out, returning false if ctx ends first. func sendUpdate[T any](ctx context.Context, out chan<- T, update T) bool { select { case out <- update: diff --git a/internal/app/controlplane/container_settings.go b/internal/app/controlplane/container_settings.go index d7856488c..4bd1fadb4 100644 --- a/internal/app/controlplane/container_settings.go +++ b/internal/app/controlplane/container_settings.go @@ -9,17 +9,8 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) -// containerRuntimePolicies is the container-runtime-policies resource document. -// Its shape IS the contract the Web UI edits, so it is defined here with -// explicit snake_case json tags and never handed the internal config.ContainerConfig -// directly: that struct's tags belong to the TOML file format, and when it was -// the document, encoding/json fell back to its Go field names -- "Image", -// "MaxConcurrency", "LegacyEnabled" -- the only Go-cased resource left in the -// registry. The two durations are config.Duration, which -// already writes the string the file accepts; the leak was the keys only. -// -// Profiles is deliberately not a field here: config.ContainerConfig.Profiles is -// json:"-", so this document never carries it either. +// containerRuntimePolicies is the container-runtime-policies document, with +// snake_case JSON keys. type containerRuntimePolicies struct { Image string `json:"image"` MaxConcurrency int `json:"max_concurrency"` @@ -37,11 +28,8 @@ type agentProfile struct { Tools []string `json:"tools,omitempty"` } -// legacyContainerKeys are the Go field names encoding/json fell back to while -// the document was the internal config struct. The decoder's case-insensitive -// fallback compares whole keys, so "MaxConcurrency" never matches -// "max_concurrency"; every store written before the reshape holds these keys, -// so reading them is deliberate and everything else stays strict. +// legacyContainerKeys maps Go-cased keys from older stored documents to +// their current names. var legacyContainerKeys = map[string]string{ "Image": "image", "MaxConcurrency": "max_concurrency", "MaxUptime": "max_uptime", "VolumeTTL": "volume_ttl", "PullPolicy": "pull_policy", "Network": "network", @@ -69,11 +57,7 @@ func (p *containerRuntimePolicies) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &raw); err != nil { return err } - // "LegacyEnabled" decoded the removed containers.enabled switch during the - // window in which this resource existed, and stores written then hold it. - // It has no counterpart in the current shape -- it never had a runtime - // consumer -- so it is dropped rather than renamed: the strict decode would - // otherwise refuse a document every deployment of that window stores. + // LegacyEnabled has no current field; drop it. delete(raw, "LegacyEnabled") // "profiles"/"Profiles" carried config.ContainerConfig.Profiles before it // moved to its own resource, AgentProfileKind; a document stored under @@ -131,12 +115,8 @@ func validateContainers(input []byte) error { }) } -// normalizeContainerPolicies canonicalizes the stored document: decoding into -// the shape above and re-encoding writes the snake_case keys, dropping the -// Go-cased keys an earlier revision stored. A document that still carries them -// converges the next time it is written; reads tolerate them meanwhile -// (containerRuntimePolicies), so nothing has to be re-saved before it can be -// read again. +// normalizeContainerPolicies re-encodes the stored document with snake_case +// keys. func normalizeContainerPolicies(input []byte) ([]byte, error) { var policies containerRuntimePolicies if err := json.Unmarshal(input, &policies); err != nil { diff --git a/internal/app/controlplane/credential_bindings.go b/internal/app/controlplane/credential_bindings.go index 85c1e2064..c23449bc0 100644 --- a/internal/app/controlplane/credential_bindings.go +++ b/internal/app/controlplane/credential_bindings.go @@ -2,12 +2,8 @@ package controlplane import "github.com/samcharles93/archie-core/internal/config" -// CredentialBindingsKind is the control-plane resource mapping a Kit -// credential@1 service name to an org secret -// It exists so a binding applies without a restart, the same reason -// AgentProfileKind is its own resource: [containers].credentials in -// config.toml is only its seed, and kitrun.Launcher reads the live -// control-plane document on every launch, never a value captured at boot. +// CredentialBindingsKind is the resource mapping Kit credential service +// names to org secrets. Applied live on each launch. const CredentialBindingsKind = "credential-bindings" // credentialBinding is one config.CredentialBinding as the document writes diff --git a/internal/app/controlplane/operational_settings.go b/internal/app/controlplane/operational_settings.go index a42ef45e0..14d736b9e 100644 --- a/internal/app/controlplane/operational_settings.go +++ b/internal/app/controlplane/operational_settings.go @@ -20,13 +20,7 @@ const ( type schedulingPolicy struct { PollInterval string `json:"poll_interval"` MaxRetries int `json:"max_retries"` - // Label is the trigger-matching label the stored dispatch pairs with. - // It is a pointer, not a string, so a policy stored before the field - // existed decodes nil and leaves the file document's label in force when - // it is layered (runtime_config.go) -- the same absence-means-inherited - // shape a kind with no stored value has. Writes are stricter: the pairing - // rule below refuses a label-requiring trigger with no label, so the - // store can never bless the half of a pairing boot then refuses. + // Label is the dispatch trigger label. Nil keeps the file's label. Label *string `json:"label,omitempty"` Dispatch config.Dispatch `json:"dispatch"` } @@ -45,13 +39,8 @@ func operationalDefinitions() []Definition { {Kind: SchedulingPolicyKind, Title: "Scheduling policy", ApplyMode: "live", Document: schedulingPolicy{}, Seed: func(cfg config.Config) any { return schedulingPolicy{PollInterval: cfg.PollInterval.Std().String(), MaxRetries: cfg.MaxRetries, Label: &cfg.Label, Dispatch: cfg.Dispatch} }, Validate: validateScheduling}, - // ApplyMode is live: the daemon diffs the stored MCP server set against - // the running providers -- connecting added servers, disconnecting - // removed ones and reconnecting changed ones while leaving unchanged - // servers untouched -- and rebuilds the web_fetch and minimax entries. - // A changed server whose new engine fails to start - // is rolled back to the old one, so the refusal is reported rather than - // leaving the server down. + // Live: changed MCP servers are reconnected, rolling back to the old engine + // if the new one fails to start. {Kind: ToolSettingsKind, Title: "Tool and MCP settings", ApplyMode: "live", Document: toolSettings{}, Seed: seedTools, Validate: validateTools}, // ApplyMode is live for additions: a stored directory change re-layers live // and the daemon's reconciliation loads new and changed files without a @@ -60,41 +49,13 @@ func operationalDefinitions() []Definition { {Kind: PluginSettingsKind, Title: "Plugin settings", ApplyMode: "live", Document: pluginSettings{}, Seed: func(cfg config.Config) any { return pluginSettings{cfg.PluginDir, cfg.ModuleDir, cfg.SecretEngineDir, cfg.SkillsDir} }, Validate: validatePluginSettings}, - // ApplyMode is live: the container pool reads the published config on - // every acquire (image, pull policy, network, max uptime, concurrency - // cap) and the daemon resizes its running dispatcher after the publish, - // so neither a deferred container nor a queued task needs a restart. - // RegistryAuth is file-owned and never part of - // this document, so it stays a boot-resolved value. + // Live: the container pool reads these on every acquire and the dispatcher + // is resized on publish. {Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "live", Document: containerRuntimePolicies{}, Seed: seedContainerPolicies, Validate: validateContainers, Normalize: normalizeContainerPolicies}, } } -// validatePluginSettings accepts every value, deliberately. -// -// Two candidate rules were considered and are refused: -// -// - That the directory must exist. Every consumer reads a missing directory as -// an empty one by design: plugin.LoadDir and secret.Registry.LoadDir return -// no entries and no error on os.IsNotExist, loadModules skips a kind whose -// file is absent, and playbook.Load returns an empty store. The no-error half -// is pinned by internal/secret's TestLoadDirNonexistent. An existence rule -// would turn each of those deliberate no-ops into a refused startup. -// - That the path must be absolute, or that skills_dir must sit under -// plugin_dir. No directory setting in this repository is validated for shape -// (work_dir, state_dir, chat.workspace, the routing and playbook paths and an -// MCP server's work_dir are all free-form), so a rule for these four alone -// would be arbitrary. It would also fail closed in the wrong place: a stored -// document is layered over the file and the boot path validates the result, -// so a rule added here refuses to start a daemon whose only problem is a -// value the store already holds. -// -// A "~/..." value is not the missing rule either: it is a path-expansion -// concern, handled where the file is read (configuration.applyGeneralDefaults), -// not a reason to refuse the document. -// -// It stays a real function rather than an inline no-op so that a rule, if one is -// ever settled, has one obvious home. +// validatePluginSettings accepts every value. func validatePluginSettings(input []byte) error { return validateAs(input, func(pluginSettings) error { return nil }) } @@ -125,13 +86,7 @@ func validateScheduling(input []byte) error { if !configuration.DispatchTriggerValid(policy.Dispatch.Trigger) { return fmt.Errorf("dispatch.trigger %q is not a discovery rule the daemon can poll with", policy.Dispatch.Trigger) } - // The pairing rule the file layer's validateDispatch enforces on the - // effective document, judged here on the data the resource carries: - // RuntimeConfig layers this label over the file's (an absent field - // leaves the file's label in force, which is what legacy policies - // decode with), so a stored label-requiring trigger with no label was - // a value the store blessed and boot refused -- the two-layer - // disagreement the parity test refuses to allow. + // A label-requiring trigger needs a label. if workintake.RequiresLabel(policy.Dispatch.Trigger) && (policy.Label == nil || *policy.Label == "") { return fmt.Errorf("label is required when dispatch.trigger is %q (an empty label matches every open issue)", policy.Dispatch.Trigger) } diff --git a/internal/app/controlplane/registry.go b/internal/app/controlplane/registry.go index 7b09a92c6..edba49ec2 100644 --- a/internal/app/controlplane/registry.go +++ b/internal/app/controlplane/registry.go @@ -18,11 +18,8 @@ import ( type Definition struct { Kind string Title string - // Document is a zero value of the resource's document type. The descriptor's - // JSON Schema is derived from it (see schemaJSON) rather than written out - // here, so the schema cannot drift from the document it describes. Nil means - // the definition names no document, which is why bareObjectSchema still - // exists as a fallback. + // Document is a zero value of the resource's document type; the JSON Schema + // is derived from it. Nil means no document. Document any ApplyMode string Seed func(config.Config) any @@ -75,50 +72,16 @@ type SeedSkip struct { Err error } -// The audit identity every seed writes under. It is a constant rather than a -// literal at each call site because a later boot reads it back: it is how a -// stored value is told apart from one an operator replaced (seedWroteNewest), -// and a writer whose identity its own reader cannot name cannot make that -// distinction at all. +// seedActor is the audit identity seeds write under. const ( seedActor = "system:migration" seedSource = "legacy-config" ) -// ImportConfig brings every control-plane resource up to date with the value -// this build seeds for it, and reports the version each kind is left at. -// -// For a kind the store does not hold, that is the seed itself. For a kind it -// does hold, the stored value wins and the seed writes nothing -- with one -// exception, because the two ways a kind gets its content are not symmetric: -// -// - A kind derived from the file config is seeded once and then owned by the -// store. Editing config.toml does not reach a database that holds a value -// for it, which is the whole point of the file being only a seed. -// - A kind whose document the build ships (the ones that set Definition.Defaults, -// the same set the catalog offers as "restore shipped") is not derived from -// operator input at all, so a stored copy is a copy of an older build's -// document and nothing else. A value like that is brought up to date, or a -// State Store upgraded under a running deployment keeps serving the previous -// release's document forever. For workflow-definitions that is not a stale -// setting but an outage: the collection validates as one document, so a -// stored step type this build no longer has fails every task's pin, whatever -// workflow the task names. -// -// A refreshed kind keeps its history: the value it replaced stays a revision in -// resource_history. What is replaced is only the seed's own work -- a -// definition set an operator replaced is theirs and is left alone, on the boot -// that finds it and on every boot after. -// -// A seed the resource's own validator refuses is SKIPPED and returned in -// skipped, not fatal. Nothing is written for that kind, so it stays ABSENT and -// the file document's value stays the one in effect (Client.RuntimeConfig -// leaves an absent kind alone), with the fix still in the file. The seed is -// retried on the next start of this process, so correcting config.toml re-seeds -// it. Fail closed belongs to the process that uses the value: -// boot.runtimeConfig validates the effective document and refuses to start -// archied with a value it cannot run with, which is what keeps an invalid value -// from taking effect silently. +// ImportConfig seeds every resource the store does not hold and returns the +// version each kind is left at. A stored value is kept, except a shipped +// document the seed itself wrote, which is refreshed. A seed its validator +// refuses is skipped and returned in skipped. func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[string]int64, []SeedSkip, error) { versions := make(map[string]int64, len(s.ordered)) var skipped []SeedSkip @@ -147,11 +110,8 @@ func (r *seedRefusal) Error() string { return r.err.Error() } func (r *seedRefusal) Unwrap() error { return r.err } -// seedKind seeds one kind if the store holds nothing for it, refreshes a -// shipped document the seed itself wrote, and otherwise leaves the stored value -// alone, returning the version the kind is left at. A *seedRefusal means the -// value this build derived is not one the resource's validator accepts, and -// nothing was written. +// seedKind seeds, refreshes or leaves one kind and returns its version. A +// *seedRefusal means the seed failed validation and nothing was written. func (s *Server) seedKind(ctx context.Context, definition Definition, cfg config.Config) (int64, error) { stored, storedErr := s.store.Resource(ctx, storecontract.DefaultOrgID, definition.Kind) absent := errors.Is(storedErr, storecontract.ErrResourceNotFound) @@ -160,13 +120,7 @@ func (s *Server) seedKind(ctx context.Context, definition Definition, cfg config } value, err := definition.seededValue(cfg) if err != nil { - // Skipped and reported, not fatal: nothing is written, so the kind - // stays absent and the file document's value is the one in effect, - // while the process that would RUN the value still fails closed on - // it (boot.runtimeConfig validates the effective document). - // seededValue wraps a seed's encode and validation failures together, - // which is why both take this path: the alternative is a second seed - // implementation here to tell them apart. + // Skipped, not fatal. return 0, &seedRefusal{err: err} } if !absent && bytes.Equal(stored.Value, value) { @@ -206,12 +160,8 @@ func expectedVersion(stored storecontract.Resource, absent bool) int64 { return stored.Version } -// shippedValueIsStale reports whether a stored value is the build's to replace: -// the kind ships a document of its own (Defaults is set exactly for those, and -// a file-derived seed never overwrites a stored value) and the revision the -// seed itself wrote is the newest one. A newer revision carrying any other -// identity is an operator's replacement, and an operator's replacement is not -// the seed's to undo. +// shippedValueIsStale reports whether the newest stored revision of a +// shipped document was written by the seed. func (s *Server) shippedValueIsStale(ctx context.Context, definition Definition) (bool, error) { if definition.Defaults == nil { return false, nil @@ -233,25 +183,14 @@ func (s *Server) seedWroteNewest(ctx context.Context, kind string) (bool, error) return history[0].Actor == seedActor && history[0].Source == seedSource, nil } -// seedRequestID is the idempotency key a seed writes under. It is derived from -// the value rather than from the kind alone, because the key is spent the -// moment it is in the ledger (resource_history's UNIQUE (kind, request_id), and -// PutResource answers a known key from that ledger): a key derived from the -// kind makes every later value a replay of the first one ever written, which is -// how a document that changed in the build never reached a database the seed -// had already written. Deriving it from the value keeps the write idempotent -- -// the same document twice is still one revision -- without making the second -// document impossible. +// seedRequestID is a seed write's idempotency key, derived from the kind and +// value. func seedRequestID(kind string, value []byte) string { sum := sha256.Sum256(value) return "import:" + kind + ":" + hex.EncodeToString(sum[:]) } -// seededValue is the value the State Store writes for a kind it does not hold -// yet: the definition's seed derived from cfg, run through the same Decode a -// write applies. ImportConfig stores it; the offline config layering reads it -// for the same reason, so "what the daemon sees for a kind that was never -// stored" is one value rather than two. +// seededValue is the value written for a kind the store does not hold. func (d Definition) seededValue(cfg config.Config) ([]byte, error) { value, err := json.Marshal(d.Seed(cfg)) if err != nil { @@ -286,18 +225,8 @@ func (s *Server) Owns(kind string) bool { return ok } -// ValidateStored decodes every stored resource with the definition that owns -// it, using the same Decode the write path applies, and reports how many -// resources it checked. Errors name the kind and the revision it was stored at, -// which is what an operator needs to roll the value back. -// -// It is the write path's own check, not boot's: boot refuses on -// configuration.Validate over the stored values layered onto the file config, -// and the two disagree in both directions (this one rejects unknown fields -// boot's decode ignores, while only boot checks dispatch.trigger and a positive -// poll interval). A caller answering "would the daemon start" therefore needs -// StoredRuntimeConfig and configuration.Validate as well -- see -// validateStore in internal/app/archied/state_store_recovery.go. +// ValidateStored decodes every stored resource with its definition and +// returns how many it checked. Errors name the kind and revision. func (s *Server) ValidateStored(ctx context.Context) (int, error) { checked := 0 var failures []error diff --git a/internal/app/controlplane/review_settings.go b/internal/app/controlplane/review_settings.go index 14917efc4..1cbfce31c 100644 --- a/internal/app/controlplane/review_settings.go +++ b/internal/app/controlplane/review_settings.go @@ -28,11 +28,7 @@ func reviewSettingsDefinition() Definition { } } -// validateReviewSettings accepts every value, deliberately: both dials are free -// booleans with no cross-field rule, and a stored value reaches its consumers -// through the same layered cfg.Review boot validates. It stays a real function -// rather than an inline no-op so a rule, if one is ever settled, has one -// obvious home (validatePluginSettings is the precedent). +// validateReviewSettings accepts every value. func validateReviewSettings(input []byte) error { return validateAs(input, func(reviewSettings) error { return nil }) } diff --git a/internal/app/controlplane/runtime_config.go b/internal/app/controlplane/runtime_config.go index ae8be4baf..c685b120e 100644 --- a/internal/app/controlplane/runtime_config.go +++ b/internal/app/controlplane/runtime_config.go @@ -12,28 +12,11 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) -// resourceReader is the one read the layering performs: a resource kind's value -// and the version it came from, or nothing at all when the store holds no value -// for that kind. The gRPC client and the in-process server both provide it, so -// "what the database covers in the running config" has exactly one -// implementation. The offline validate runs the same code as boot, which is the -// only way its verdict can be boot's verdict. -// -// found is false only for the reader that dials a live State Store: a kind with -// no stored value leaves the file document's value in effect instead of failing -// the process, which is the state a seed ImportConfig refused leaves behind -// (controlplane.Server.ImportConfig skips it) and the state of a database the -// migration has not reached yet. storeReader never reports absent -- it answers -// with the seed the State Store would write -- so the offline verdict stays -// boot's. +// resourceReader returns a resource kind's value and version; found is false +// when the store holds none. -// RuntimeConfig applies restart-scoped database resources over bootstrap -// configuration. Values intentionally absent from a control-plane projection, -// such as secret-bearing MCP headers and channel update commands, remain -// bootstrap-owned. -// -// It also returns the version of each kind it read, so the process that -// layers them in can report which version it is running +// RuntimeConfig layers stored resources over base and returns each kind's +// version. func (c *Client) RuntimeConfig(ctx context.Context, base config.Config) (config.Config, map[string]int64, error) { return runtimeConfigFrom(ctx, c, base) } @@ -41,16 +24,8 @@ func (c *Client) RuntimeConfig(ctx context.Context, base config.Config) (config. // RuntimeChatConfig layers the stored channel settings over the file document's // chat section. -// StoredRuntimeConfig is RuntimeConfig's layering over the store this server -// owns, for a caller holding the database file rather than a connection to it. -// Boot layers the stored settings onto the file config and then runs -// configuration.Validate, so an offline check of that database has to make the -// same first move with the same implementation; called with the config the -// daemon would load, the result is the document boot decides on. -// -// A kind the store does not hold is read as the seed the State Store would -// write for it from base (see storeReader.query), because that store seeds -// every kind before it serves. +// StoredRuntimeConfig is RuntimeConfig over this server's own store. Kinds +// not stored are read as their seed. func (s *Server) StoredRuntimeConfig(ctx context.Context, base config.Config) (config.Config, map[string]int64, error) { seeds, err := s.seededValues(base) if err != nil { @@ -59,11 +34,8 @@ func (s *Server) StoredRuntimeConfig(ctx context.Context, base config.Config) (c return runtimeConfigFrom(ctx, storeReader{resources: s.store, seeds: seeds}, base) } -// storeReader reads the server's own store. It mirrors what the gRPC read -// answers -- a kind that is stored is the value and version it holds -- with -// one difference: a kind the store does not hold yet is the value the State -// Store seeds for it, since the daemon dials a store that has already run -// ImportConfig over the same config. +// storeReader reads this server's store, returning the seed for kinds it +// does not hold. type storeReader struct { resources ResourceStore seeds map[string][]byte @@ -112,12 +84,7 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade }); err != nil { return config.Config{}, nil, err } - // The stored role assignments own cfg.Models once the store carries a - // value, the way the provider layer above owns cfg.Providers: a role - // removed from the store is gone from the layered document too. The - // runtime-resource watches re-layer over an already-layered base, - // so json.Unmarshal's map merge here would - // resurrect a role the store deleted every time any watched kind changed. + // Stored role assignments replace cfg.Models outright. if err := layerResource(ctx, reader, versions, ModelRoleAssignmentsKind, func(value []byte) error { var roles map[string]string if err := json.Unmarshal(value, &roles); err != nil { @@ -146,12 +113,7 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade return err } out.PollInterval, out.MaxRetries, out.Dispatch = config.Duration(interval), policy.MaxRetries, policy.Dispatch - // The label pairs with the trigger and layers with it: once the store - // carries one, it owns it, and the file can no longer drop the label a - // stored label-requiring trigger depends on. A policy stored before - // the field existed -- the nil the seed never produces -- leaves the - // file document's label in force, and boot's gate judges the pairing - // either way. + // A stored label replaces the file's. if policy.Label != nil { out.Label = *policy.Label } @@ -191,13 +153,8 @@ func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceR } servers := make([]config.MCPServer, 0, len(settings.MCPServers)) for _, server := range settings.MCPServers { - // This assignment replaces cfg.Tools wholesale, so every field the - // stored resource does not carry has to be taken back from the file - // or the operator's file value is dropped. Headers have always been - // file-owned; ParallelToolCalls joins them when the store predates - // the field, because a nil pointer means "no stored decision", not - // "false". A server with no file entry has nothing to inherit and - // gets the zero value. + // cfg.Tools is replaced wholesale, so keep file-owned fields: headers, and + // ParallelToolCalls when not stored. parallelToolCalls := fileParallelToolCalls[server.Name] if server.ParallelToolCalls != nil { parallelToolCalls = *server.ParallelToolCalls @@ -235,16 +192,7 @@ func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceR if err := json.Unmarshal(value, &policies); err != nil { return err } - // Profiles survives this assignment untouched: containerRuntimePolicies - // carries no Profiles field at all (it is AgentProfileKind's document - // now), and settings() never sets it, so whatever the AgentProfileKind - // layering step below assigns is what's left standing regardless of - // which of the two runs first. - // - // RegistryAuth is the same shape of file-owned field, with no resource of - // its own to restore it later the way CredentialBindingsKind restores - // Credentials: the document cannot carry a secret reference, so it has to - // survive this assignment or the daemon pulls anonymously again. + // Keep the file-owned Profiles and RegistryAuth across the replacement. profiles := out.Containers.Profiles registryAuth := out.Containers.RegistryAuth out.Containers = policies.settings() @@ -254,11 +202,7 @@ func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceR }); err != nil { return config.Config{}, nil, err } - // AgentProfileKind is a separate resource from ContainerRuntimePoliciesKind - // (config.ContainerConfig.Profiles is json:"-") so a Kit profile applies - // without a restart: a stored value replaces the file's outright rather - // than merging into it, the same reason ModelRoleAssignmentsKind above - // reassigns out.Models wholesale instead of decoding into the existing map. + // Stored profiles replace the file's outright. if err := layerResource(ctx, reader, versions, AgentProfileKind, func(value []byte) error { var profiles map[string]agentProfile if err := json.Unmarshal(value, &profiles); err != nil { @@ -284,14 +228,8 @@ func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceR return out, versions, nil } -// layerResource decodes a resource and records the version it came from, so the -// layering ends up holding the version of every kind it applied. -// -// A kind with no stored value is not an error and records no version: the file -// document's value stays in effect. That is the state a seed the resource -// validator refused leaves behind (controlplane.Server.ImportConfig skips it), -// and failing here instead would stop the process with a database-named error -// that editing config.toml cannot clear. +// layerResource decodes a stored resource and records its version. A kind +// with no stored value is skipped. func layerResource(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, kind string, decode func([]byte) error) error { version, found, err := reader.Query(ctx, kind, decode) if err != nil { diff --git a/internal/app/controlplane/schema.go b/internal/app/controlplane/schema.go index 58d2bf30c..9599b42c7 100644 --- a/internal/app/controlplane/schema.go +++ b/internal/app/controlplane/schema.go @@ -20,14 +20,7 @@ var timeType = reflect.TypeFor[time.Time]() // standard duration for arithmetic. var stdDuration = reflect.TypeOf((*interface{ Std() time.Duration })(nil)).Elem() -// durationLike reports whether t is a duration type that writes itself as the -// string time.ParseDuration reads, rather than as its nanosecond count. -// -// It asks the type rather than listing the ones that exist, because a list goes -// stale the moment a fourth duration type appears and the failure is silent in -// the worst direction: the field derives as an integer and a client renders a -// number box for a duration. That is exactly what the enumerated version of this -// function did to scheduling.Duration when the schedules interval became one. +// durationLike reports whether t marshals as a duration string. func durationLike(t reflect.Type) bool { if !t.Implements(stdDuration) { return false @@ -36,24 +29,8 @@ func durationLike(t reflect.Type) bool { return err == nil && len(encoded) > 0 && encoded[0] == '"' } -// schemaJSON renders the JSON Schema a resource descriptor advertises, derived -// from the document type the definition owns rather than written out beside it. -// -// Derivation is the point. A hand-written schema beside a struct drifts the -// moment a field is added, and nothing catches it, because the document and its -// schema are never compared -- which is exactly how twelve descriptors came to -// advertise `{"type":"object"}` and no field metadata at all. -// -// It describes structure only: keys, types, and the `format`, `title` and `doc` -// annotations a field declares in its own tags. It deliberately emits no prose -// of its own. Field descriptions already have one home in this tree -// (internal/webui/config_schema.go, keyed by dotted config path), and a second -// would be two places to keep the same fact true. -// -// `required` is never emitted. An empty string is a legitimate value for nearly -// every field here -- a blank workspace, a disabled rate limit -- so calling most -// fields required would invite a client to enforce something the document does -// not mean. +// schemaJSON derives a resource's JSON Schema from its document type: keys, +// types and tag annotations. It never emits required. func schemaJSON(document any) string { if document == nil { return bareObjectSchema diff --git a/internal/app/controlplane/tool_settings.go b/internal/app/controlplane/tool_settings.go index 0cd23b8f4..aa7de7376 100644 --- a/internal/app/controlplane/tool_settings.go +++ b/internal/app/controlplane/tool_settings.go @@ -23,13 +23,7 @@ type mcpServerSettings struct { URL string `json:"url,omitempty"` SSEEndpoint string `json:"sse_endpoint,omitempty"` MessageEndpoint string `json:"message_endpoint,omitempty"` - // ParallelToolCalls is a pointer, not a bool, for the same reason - // schedulingPolicy.Label is: a resource seeded before this field existed - // carries no key for it, and the layering replaces cfg.Tools wholesale, so - // absence has to mean "leave the file document's value in force" rather - // than "false". A plain bool cannot tell the two apart, which made the - // file's parallel_tool_calls inert on every store that predates the field - // -- the stores that cannot be re-seeded. + // ParallelToolCalls is nil when not stored, keeping the file's value. ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` HeadersConfigured bool `json:"headers_configured"` } diff --git a/internal/app/controlplane/workflow_definitions.go b/internal/app/controlplane/workflow_definitions.go index 25dc3aa86..6959b0b38 100644 --- a/internal/app/controlplane/workflow_definitions.go +++ b/internal/app/controlplane/workflow_definitions.go @@ -11,15 +11,7 @@ import ( const WorkflowDefinitionsKind = "workflow-definitions" -// stepRegistry is this package's single resolution site for the workflow step -// vocabulary, and the guard on the manager it must be handed. The manager is -// built at the composition root (infrastructure/workflowsteps.NewManager) and -// injected, so the State Store server -- the validating side -- and the -// workflow-definitions client both resolve the vocabulary that composition -// root registered. Agreement is within one build: the State Store and -// archie-agent are separately deployed binaries, so a State Store built from -// newer source than the agent it dispatches to can still disagree, and only a -// matching deploy fixes that. +// stepRegistry returns the step vocabulary from the injected manager. func stepRegistry(steps *workflow.Manager) (workflow.StepRegistry, error) { if steps == nil { return nil, errors.New("control plane: no workflow step vocabulary: the composition root must register the provider set (infrastructure/workflowsteps.NewManager) before the first resolution") diff --git a/internal/app/controlplane/workflow_projector.go b/internal/app/controlplane/workflow_projector.go index 8b41356f6..5e8fed1fc 100644 --- a/internal/app/controlplane/workflow_projector.go +++ b/internal/app/controlplane/workflow_projector.go @@ -22,16 +22,9 @@ const projectionActor = "archie-state-store" // refuses the projection. const projectWriteAttempts = 3 -// WorkflowProjector carries an installed package's workflow contributions -// into the org's workflow-definitions resource, the same document an operator -// edits on the dashboard. The readers the -// daemon holds read that resource per dispatch, so a projected workflow is -// usable at the next dispatch and a withdrawn one stops dispatching, without -// restarting processes. -// -// Apply merges: a contributed id that belongs to an operator or to another -// package is refused (storepkg.ErrContributionCollision), never silently -// replaced. +// WorkflowProjector merges an installed package's workflows into the org's +// workflow-definitions resource. Ids owned by an operator or another package +// are refused. type WorkflowProjector struct { store ResourceStore ledger storepkg.ProjectionLedger diff --git a/internal/app/controlplane/workflow_settings.go b/internal/app/controlplane/workflow_settings.go index 772bae9b2..7b55b5e50 100644 --- a/internal/app/controlplane/workflow_settings.go +++ b/internal/app/controlplane/workflow_settings.go @@ -27,11 +27,8 @@ type executionSettingsDocument struct { MaxTaskRuntimeSeconds *int64 `json:"max_task_runtime_seconds" title:"Max task runtime seconds" doc:"Limit for a whole task run; the task is parked when it passes. 0 disables it."` } -// ImportWorkflowExecutionSettings preserves the focused bootstrap API for callers -// that do not own the complete legacy configuration document. It is the same -// producer rule as ImportConfig, at this narrower entry point: a kind the store -// holds is left alone, and a kind it does not hold is seeded under the one seed -// identity (see seedActor and seedRequestID). +// ImportWorkflowExecutionSettings seeds the workflow execution settings when +// the store does not hold them. func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings workflow.ExecutionSettings) (int64, error) { resource, err := s.store.Resource(ctx, storecontract.DefaultOrgID, WorkflowExecutionSettingsKind) if err == nil { diff --git a/internal/domain/messaging/approval.go b/internal/domain/messaging/approval.go index ea7f9b48a..df204b7d4 100644 --- a/internal/domain/messaging/approval.go +++ b/internal/domain/messaging/approval.go @@ -49,11 +49,8 @@ func ApprovalFromContext(ctx context.Context) ApprovalRequester { return a } -// ApproverOf returns sender's ApprovalRequester only when sender reports the -// Approval capability. Like ClarifierOf and PickerOf, the capability wins -// over the method set: a sender that renders approvals but denies the -// capability is treated as unable to, and one that claims it without -// implementing the interface degrades instead of panicking. +// ApproverOf returns sender's ApprovalRequester when it reports the +// Approval capability and implements the interface. func ApproverOf(sender any) (ApprovalRequester, bool) { if !CapabilitiesOf(sender).Approval { return nil, false diff --git a/internal/domain/messaging/chat_contract.go b/internal/domain/messaging/chat_contract.go index 4fedb5996..3fa758b22 100644 --- a/internal/domain/messaging/chat_contract.go +++ b/internal/domain/messaging/chat_contract.go @@ -7,11 +7,8 @@ import ( "github.com/samcharles93/archie-core/internal/taskstate" ) -// ChatContract is the conversational boundary consumed by channel frontends. -// Results are snapshots: callers must not rely on shared object identity. -// It moved here from internal/gateway so the webui -// and archie-ui processes can hold the contract without linking the gateway -// runtime (and, transitively, its SQLite session store). +// ChatContract is the chat boundary channel frontends call. Results are +// snapshots. type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade Snapshot(context.Context) (ChatSnapshot, error) GetSession(context.Context, string) (SessionContext, bool, error) @@ -34,15 +31,9 @@ type ChatTaskActionContract interface { // payload; the chat surface has no instruction or selection syntax, so it // is the zero value there. ApplyTaskAction(context.Context, string, int64, taskstate.Action, taskactions.ActionPayload) (TaskActionResult, error) - // ApplyOperatorTaskAction applies an action on behalf of an authenticated - // dashboard caller, who acts across identities. The actor is who the - // credential resolved to, or the zero Actor when the caller presented - // nothing archie could verify -- which is recorded unattributed rather than - // credited to a human. It is a separate method rather than an empty identity - // because "" is a real identity in a single-identity deployment (see - // chatTaskProfiles in the daemon). res carries the review gate answer - // payload: the operator's finding selection for approve, and the - // instructions a rereview requires. + // ApplyOperatorTaskAction applies an action for an authenticated dashboard + // operator acting across identities. A zero actor is recorded unattributed. + // res carries the review gate answer. ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload) (TaskActionResult, error) } diff --git a/internal/domain/messaging/ephemeral.go b/internal/domain/messaging/ephemeral.go index 970b7fc94..b2377bb4d 100644 --- a/internal/domain/messaging/ephemeral.go +++ b/internal/domain/messaging/ephemeral.go @@ -5,37 +5,21 @@ import ( "time" ) -// EphemeralReply is a reply the sender delivers and then retracts once its -// TTL elapses. It is for status and progress placeholders ("thinking…", -// "running tool X…") that are only meaningful while a turn is in flight and -// should not linger in the chat history after they are superseded. -// -// TTL is measured from the moment the send succeeds. A non-positive TTL -// means the reply is not retracted, which keeps a normal message and an -// ephemeral one with no lifetime on the same path. +// EphemeralReply is a reply deleted after TTL from a successful send. A +// non-positive TTL is never deleted. type EphemeralReply struct { Event MessageEvent TTL time.Duration } -// MessageDeleter is the optional interface a sender implements to remove a -// message it previously sent. It is the delete counterpart of MediaSender, -// discovered the same way: callers read Capabilities().Delete first so a -// platform without delete support is never probed with a doomed call. -// -// DeleteMessage is addressed by the MessageEvent the send returned, so its -// ID must be the platform identifier for the message to remove. A sender -// that cannot name that identifier must not report the Delete capability. +// MessageDeleter deletes a message the sender sent, addressed by the +// MessageEvent the send returned. type MessageDeleter interface { DeleteMessage(ctx context.Context, event MessageEvent) error } -// DeleterOf returns sender's MessageDeleter only when sender reports the -// Delete capability. A sender that implements the interface but reports -// Delete:false is treated as unable to delete -- the capability is the -// contract, not the method set -- and one that reports Delete:true without -// implementing the interface is treated the same way, so a mis-reporting -// adapter degrades instead of panicking. +// DeleterOf returns sender's MessageDeleter when it reports the Delete +// capability and implements the interface. func DeleterOf(sender any) (MessageDeleter, bool) { if !CapabilitiesOf(sender).Delete { return nil, false diff --git a/internal/domain/messaging/inbound.go b/internal/domain/messaging/inbound.go index 882fe1ac3..7c4de8ff2 100644 --- a/internal/domain/messaging/inbound.go +++ b/internal/domain/messaging/inbound.go @@ -5,58 +5,24 @@ import ( "time" ) -// Inbound is a message arriving from a channel together with the -// transport context that is not part of the canonical record. -// -// Message is the record itself, exactly as it will be persisted. Channels -// construct it directly: ConversationID addresses the chat (a Telegram -// chat ID and topic thread, an email recipient, a webhook path), Sender is -// the channel-native attribution, and Role is always RoleUser -- -// a channel only ever carries what a person said. ID is left empty for a -// newly received message so the store derives one from SourceID, and -// honoured when set, which is what lets a read-modify-write of a history -// keep its identities rather than minting new ones. +// Inbound is a received message plus transport context that is not +// persisted. Message.Role is always RoleUser; an empty ID is derived from +// SourceID. type Inbound struct { Message Message // Page is the dashboard route the operator is on when they sent // this message. Transport-only: it reaches the system prompt and // is never persisted. Empty for non-web channels. Page string - // BudgetKey is what the Gateway charges this message against in its - // inbound rate limiter (internal/ratelimit), for a channel whose - // Message.SenderID is empty because it carries no per-person - // identity but still has a stable, operator-controlled source to - // budget -- a webhook's configured route path, today. It is - // deliberately not SenderID: SenderID means "this is who sent it", - // and several consumers (internal/app/archied/chat_identity.go, - // sessioncurator) read it as a person, so a route path in that field - // becomes a user identity. BudgetKey is transport-only and never - // persisted, exactly like Page. Empty means the message is not - // rate limited, which is correct for a source with no stable key of - // its own (the dashboard). + // BudgetKey is the rate-limit key for a channel with no per-person sender, + // such as a webhook route. Not persisted. Empty means not limited. BudgetKey string - // Platform is the channel that carried this message ("telegram", - // "email", "webhook", "web"), named by the frontend that owns that - // channel. It is how the Gateway learns which channel it is serving: - // one Router serves all of them, so its own name is "web" even for a - // Telegram turn, which made SessionSource.Platform -- the first - // component of the session natural key -- a constant, and left the - // per-user identity policy unreachable with a real channel name. - // Transport-only and never persisted: the session - // record keeps the platform. Empty means the sender did not name its - // channel, and the Gateway falls back to its own name. + // Platform is the channel that carried the message. Not persisted. Empty + // falls back to the gateway's name. Platform string - // Media carries files the sender attached to this message (photos, - // documents, voice, video) with their in-process bytes already - // downloaded. Like Page and BudgetKey it is transport-only: it never - // crosses a persistence boundary, and the stored Message records the - // attachment as a short textual note in its Text instead, because - // download URLs expire and raw media bytes must not silently inflate - // the transcript store. It does cross the inbound request to the - // Gateway process that runs the turn -- that process has no platform - // credential, so the bytes have no other way to reach the model. nil - // for a text-only message. + // Media are the message's attachments with their bytes. Sent to the Gateway + // but never persisted. Media []MediaAttachment } @@ -75,11 +41,8 @@ type SpawnRequest struct { Identity string // the identity spawning this task; propagated from Router.Identity } -// TaskCreator creates a native (non-forge-backed) task from a chat -// command. The daemon supplies an implementation backed by the store. -// When nil on a Router, /spawn returns "not configured". CreateTask -// must return the task's real, durable database ID -- never a -// synthetic or fabricated value. +// TaskCreator creates a chat task and returns its database ID. Nil makes +// /spawn report "not configured". type TaskCreator interface { CreateTask(ctx context.Context, req SpawnRequest) (taskID int64, err error) } diff --git a/internal/domain/messaging/interactive.go b/internal/domain/messaging/interactive.go index a937b1fc8..bb4fec284 100644 --- a/internal/domain/messaging/interactive.go +++ b/internal/domain/messaging/interactive.go @@ -8,11 +8,8 @@ import ( "strings" ) -// InteractiveChoice is one selectable option offered by a clarify or picker -// prompt. ID is the value carried back to the caller; Label is what the -// human sees. An adapter that renders a choice must return the option as it -// was given (ID preserved), never a Label the human typed: callers correlate -// on ID. +// InteractiveChoice is one option in a clarify or picker prompt. Callers +// match on ID. type InteractiveChoice struct { ID string Label string @@ -71,12 +68,8 @@ var ( ErrTextFallbackNotConfigured = errors.New("interactive: text fallback is missing Send or Reply") ) -// ClarifierOf returns sender's ClarifyRequester only when sender reports the -// Clarify capability. A sender that implements the interface but reports -// Clarify:false is treated as unable to clarify -- the capability is the -// contract, not the method set -- and one that reports Clarify:true without -// implementing the interface is treated the same way, so a mis-reporting -// adapter degrades instead of panicking. It mirrors DeleterOf. +// ClarifierOf returns sender's ClarifyRequester when it reports the Clarify +// capability and implements the interface. func ClarifierOf(sender any) (ClarifyRequester, bool) { if !CapabilitiesOf(sender).Clarify { return nil, false @@ -96,11 +89,8 @@ func PickerOf(sender any) (PickerRequester, bool) { return picker, ok } -// Interactive bundles the human-interaction requesters a channel adapter can -// carry for one turn, resolved once from its capability report. The zero value -// carries nothing, which is what a turn whose channel cannot ask a question -// sees; the gateway turn reads it to decide whether to offer a question tool -// at all rather than one that always fails. +// Interactive holds the interaction requesters a channel supports for one +// turn. The zero value supports none. type Interactive struct { Clarifier ClarifyRequester Picker PickerRequester @@ -193,14 +183,8 @@ func ParsePickerReply(req PickerRequest, reply string) (InteractiveChoice, bool) return InteractiveChoice{}, false } -// TextFallback renders clarify and picker prompts as plain text and reads the -// human's typed reply. It is the degrade path for a channel with no native -// question or selection UI, and the behaviour an adapter claims when it -// reports Clarify/Picker without native widgets: the interaction still -// happens, it just costs a typed answer instead of a tap. -// -// Send delivers one prompt; Reply blocks for the next human text. Both are -// injected so the fallback carries no transport of its own. +// TextFallback asks clarify and picker questions as plain text and reads the +// typed reply. type TextFallback struct { Send func(ctx context.Context, text string) error Reply func(ctx context.Context) (string, error) diff --git a/internal/domain/messaging/media.go b/internal/domain/messaging/media.go index d2bcbbaa3..fcf46677a 100644 --- a/internal/domain/messaging/media.go +++ b/internal/domain/messaging/media.go @@ -1,21 +1,10 @@ package messaging -// MaxInboundAttachmentBytes is the transport ceiling for an attachment a -// channel frontend carries across the inbound wire to the process that runs -// the turn. It is a ceiling, not a policy: a frontend may refuse earlier -// (Telegram's Bot API caps getFile at 20 MB), and anything larger must -// degrade to a notice instead of failing the request that carries it. -// The Gateway's gRPC receive limit is sized from this value, so a maximal -// attachment is accepted rather than rejected as an oversized message. +// MaxInboundAttachmentBytes is the largest attachment carried to the Gateway. const MaxInboundAttachmentBytes = 20 << 20 -// Type values. MediaTypeVoice is speech the sender recorded -- a Telegram -// voice note -- as distinct from MediaTypeAudio, a music or generic audio -// file. The distinction is what tells the model-owning turn runner to -// transcribe a speech attachment before the turn: a voice note's bytes reach -// the Gateway, which owns the provider credential, but the Gateway must not -// spend a transcription call on a forwarded song. The remaining values are -// what they say. +// Media types. MediaTypeVoice is recorded speech, which is transcribed; +// MediaTypeAudio is other audio. const ( MediaTypeImage = "image" MediaTypeVideo = "video" @@ -24,12 +13,8 @@ const ( MediaTypeVoice = "voice" ) -// MediaAttachment describes a file attached to a message. Platform-agnostic; -// platform-specific fields live in Raw. -// -// Numeric fields use pointers so that zero is distinguishable from -// "unknown" across a JSON round-trip: a 0-byte file is valid and -// different from a file whose size was never set. +// MediaAttachment describes a file attached to a message. Pointer fields +// distinguish zero from unknown. type MediaAttachment struct { // Type is "image", "video", "audio", "voice", or "document". Type string `json:"type"` @@ -41,14 +26,8 @@ type MediaAttachment struct { // platforms that require a download API call. URL string `json:"url,omitempty"` - // Path is a local filesystem path on the host that produced the - // attachment. It is the alternative to URL for outbound delivery: a - // URL is fetched by the platform, a Path is uploaded by us. A file the - // agent wrote has no URL and never gets one -- publishing it would - // trade a delivery problem for a hosting and access-control one -- so - // senders that support upload must read this. - // - // Exactly one of URL and Path is meaningful for an outbound send. + // Path is a local file to upload. Exactly one of URL and Path is used for an + // outbound send. Path string `json:"path,omitempty"` // MIMEType is the content type (e.g. "image/png", "audio/ogg"). @@ -75,12 +54,7 @@ type MediaAttachment struct { // cover, so adapters never need a second attachment type. Raw map[string]any `json:"raw,omitempty"` - // Data carries the attachment bytes in-process. An inbound path sets - // it after downloading the file; outbound senders never set it and - // read Path or URL instead. It crosses the wire in one direction only: - // the inbound request from a channel frontend to the Gateway process - // that runs the turn, because that process never holds the platform - // credential. It is never persisted, and the stored-history and - // outbound-event directions strip it. + // Data holds the attachment bytes in-process on the inbound path. Never + // persisted. Data []byte `json:"data,omitempty"` } diff --git a/internal/domain/messaging/media_sender.go b/internal/domain/messaging/media_sender.go index a6e285878..cfd26f088 100644 --- a/internal/domain/messaging/media_sender.go +++ b/internal/domain/messaging/media_sender.go @@ -15,17 +15,10 @@ type SendResult struct { // implements. type AdapterCapabilities struct { Media bool - // Delete reports whether the sender can remove a message it - // previously sent (MessageDeleter), which is what lets an - // EphemeralReply be retracted once its TTL elapses. A sender that - // cannot delete still delivers ephemeral replies, it just leaves them - // in place. + // Delete reports whether the sender can delete messages it sent. Delete bool - // Clarify reports whether the sender can pose a clarifying question and - // carry the human's answer back (ClarifyRequester). The capability is - // about carrying the interaction, not about native widgets: an adapter - // with no button UI fulfils it through the text fallback rather than - // reporting false and stranding the question. + // Clarify reports whether the sender can ask a question and return the + // answer. Clarify bool // Picker reports whether the sender can present a single-choice // selection and carry the chosen option back (PickerRequester), on the diff --git a/internal/domain/messaging/message.go b/internal/domain/messaging/message.go index ad7b5206f..08937b60f 100644 --- a/internal/domain/messaging/message.go +++ b/internal/domain/messaging/message.go @@ -1,10 +1,5 @@ -// Package messaging owns canonical Messages, Conversations, branches, -// channel and source correlation, and typed tool-call/tool-result message -// variants. -// -// Migrating internal/gateway/'s session, compression, approval, and branch -// logic onto these types is deliberately out of scope here — see that section -// for why, and bd for the tracked follow-up work. +// Package messaging defines messages, conversations and the chat contracts +// channels and the gateway share. package messaging import "time" @@ -40,14 +35,8 @@ const ( RoleSystem Role = "system" ) -// Conversation is a single thread of Messages within a channel, optionally -// forked from another Conversation. -// -// Parent and child transcript isolation is exact: a fork sees the parent's -// history up to ForkMessageID, and appends to its own independent -// continuation. Nothing appended to the child is visible to the parent, and -// nothing appended to the parent after the fork point is visible to the -// child. +// Conversation is a thread of Messages in a channel, optionally forked from +// another at ForkMessageID. Fork and parent histories are isolated. type Conversation struct { ID ConversationID @@ -76,39 +65,18 @@ type Message struct { // upstream identity. SourceID string - // Sender is the channel-native display attribution (e.g. a Telegram - // username) recorded when the message was written. Like SourceID it - // is external correlation metadata, never the canonical identity: the - // canonical Role field is authoritative in-process. At the gateway wire - // boundary (internal/infrastructure/gatewayrpc) Role is deliberately - // dropped and rebuilt from Sender via RoleForSender, so Sender is also - // preserved for that reconstruction and for history search and - // transcript rendering. + // Sender is the channel-native display name of the author. Role is rebuilt + // from it at the gateway wire boundary. Sender string - // SenderID is the channel-native stable identifier for the party that - // sent this message (e.g. a Telegram numeric user ID or an SMTP from - // address), distinct from Sender's human-readable display form. Empty - // when the channel has no stable per-person identity to offer -- which - // includes a webhook, whose configured route path is a source rather - // than a person and travels in the transport-only Inbound.BudgetKey - // instead. Used to key - // per-identity inbound controls and to derive a memory participant, so - // a non-person value here becomes a user identity to every consumer - // that reads it. + // SenderID is the channel-native stable ID of the person who sent the + // message, or empty when there is none. SenderID string Role Role Text string - // Media carries attachment metadata for messages that arrived with a - // file (photo, document, video, audio): the platform attachment id, its - // name, type, and size, so the transcript records what was sent as - // data rather than as prose. The attachment bytes and any embedded - // Data field are deliberately NOT persisted -- they are turn-scoped -- - // so this is the metadata a later reader (search, transcript, a - // re-look capability) can act on, including re-fetching through - // FileID where the platform allows it. + // Media is the message's attachment metadata, without bytes. Media []MediaAttachment `json:"media,omitempty"` // ToolCall and ToolResult are populated instead of Text for their diff --git a/internal/domain/messaging/session_store.go b/internal/domain/messaging/session_store.go index 6385cb143..8eb167676 100644 --- a/internal/domain/messaging/session_store.go +++ b/internal/domain/messaging/session_store.go @@ -21,11 +21,8 @@ type SessionSource struct { // name, DM thread). ChannelID string `json:"channel_id"` - // ThreadID identifies the topic thread within the conversation, for - // platforms that support threading (Telegram supergroup topics, - // Slack threads, Discord forum posts). Empty for flat chats and the - // General topic. When non-empty, distinct threads within the same - // channel produce distinct sessions. + // ThreadID identifies a topic thread; distinct threads get distinct sessions. + // Empty for flat chats. ThreadID string `json:"thread_id,omitempty"` } @@ -59,18 +56,7 @@ type SessionContext struct { LastActiveAt time.Time `json:"last_active_at"` } -// SessionStore persists gateway session metadata and conversation history. -// Each session tracks one platform, bot, and channel combination. -// -// Message history is stored and loaded as canonical Message records. -// Session lifecycle records stay SessionContext: -// a session's UUID key, platform/bot/title/branch metadata, and the fact -// that several sessions share one channel/thread have no lossless home in -// Conversation, whose composite identity is only -// {ChannelID, ThreadID} and whose canonical Agent/user/binding ownership is -// still open. -// Conversation-keying the sessions is tracked as follow-up work once that -// ownership settles. +// SessionStore persists chat sessions and their message history. type SessionStore interface { SessionLifecycle MessageHistory diff --git a/internal/domain/messaging/stream.go b/internal/domain/messaging/stream.go index 8f9258f1a..b519cb269 100644 --- a/internal/domain/messaging/stream.go +++ b/internal/domain/messaging/stream.go @@ -34,15 +34,8 @@ type MediaEvent struct { Attachment MediaAttachment } -// TurnStream receives a turn's output as it is produced. -// -// It replaces the plain delta callback so a channel can render tool activity -// in the same ordered pass as the text: both arrive on the generating -// goroutine, in the order the model produced them. Implementations must not -// block -- a slow renderer stalls generation -- and must be safe to call -// from that goroutine only. -// -// Callers that render text alone use DeltaFunc rather than implementing this. +// TurnStream receives a turn's text and tool activity in order, on the +// generating goroutine. Implementations must not block. type TurnStream interface { // Delta appends the next fragment of assistant text. Delta(text string) diff --git a/internal/domain/messaging/tool_render.go b/internal/domain/messaging/tool_render.go index c5eb8fd05..b8d36b7f4 100644 --- a/internal/domain/messaging/tool_render.go +++ b/internal/domain/messaging/tool_render.go @@ -42,16 +42,7 @@ func FailureKey(e ToolCallEvent) string { return "success\x00" + strings.TrimSpace(e.Name) + "\x00" + toolPreview(e.Name, e.Output) } -// ToolPreviewSeparator joins a tool's header to its preview. The preview is -// always one line (every toolPreview path summarises to one), so it belongs -// on the header line rather than in a block of its own: Telegram renders a -// fenced block as a full code widget, and the block parser puts a spacer -// paragraph before every block, so fencing one line cost four rendered -// elements to show a word count. -// -// Keeping the preview on the line also means a fence marker in the output can -// never reach column zero, which is why the preview is passed through -// verbatim instead of having its backticks substituted away. +// ToolPreviewSeparator joins a tool line's header and its one-line preview. const ToolPreviewSeparator = " · " func toolProgressBlock(name, emoji, status, preview string) string { diff --git a/internal/domain/messaging/transcribe.go b/internal/domain/messaging/transcribe.go index 053335f60..2803b98b8 100644 --- a/internal/domain/messaging/transcribe.go +++ b/internal/domain/messaging/transcribe.go @@ -6,23 +6,11 @@ import ( "strings" ) -// ErrTranscriptionUnavailable reports that the transcription capability -// cannot serve right now: no role configured, an unknown or unsupported -// provider, or a credential that could not be resolved. Infrastructure -// implementations wrap it so a caller can degrade -- keep the media note -- -// instead of failing the turn. +// ErrTranscriptionUnavailable reports that transcription is not configured +// or cannot run. var ErrTranscriptionUnavailable = errors.New("transcription capability unavailable") -// Transcriber turns recorded audio into text. It is a channel-neutral, -// call-scoped capability: the messaging media layer defines what a -// transcription is, and each frontend supplies the bytes its platform -// produced. Implementations live in internal/infrastructure/transcription; -// the domain never imports one. -// -// The same shape as image.Provider and embedding.Client: no Lifecycle, -// because "can the capability serve right now" is exactly what a returned -// error already communicates, and a missing capability must degrade rather -// than fail the turn it arrived on. +// Transcriber turns recorded audio into text. type Transcriber interface { // Transcribe returns the transcript of audio, which must be non-empty. // A failure is an error, never a panic; any error means the caller keeps @@ -36,11 +24,8 @@ type Transcriber interface { // transcript from something the sender typed. const TranscriptionProvenance = "[voice transcription]" -// TranscribedText renders a transcript as the text an inbound voice note -// contributes to the turn, keeping any caption the sender attached after the -// transcript. An empty transcript still yields the provenance marker, so the -// agent knows audio arrived rather than silently treating the message as -// empty. +// TranscribedText returns the transcript with a provenance marker, followed +// by any caption. func TranscribedText(transcript, caption string) string { parts := []string{TranscriptionProvenance} if t := strings.TrimSpace(transcript); t != "" { @@ -52,21 +37,8 @@ func TranscribedText(transcript, caption string) string { return strings.Join(parts, "\n") } -// TranscribedMessageText renders the text a transcribed speech attachment -// contributes to a message, preserving any caption the sender attached. -// -// messageText is the inbound text a channel frontend rendered for an -// attachment: the media note alone, or the note followed by the sender's -// caption on the next line. The note is a bracketed, self-describing -// placeholder (see internal/channels/telegram's turnMessageText); it is -// replaced by the provenance marker and transcript, and anything after it -// survives as the caption. Text that carries no recognisable note is treated -// as a caption in full, so nothing the sender wrote is dropped. -// -// The transcription happens on the model-owning side of the Messaging -// boundary, which receives the audio bytes but not the caption as a separate -// field; this is the function that turns the frontend's rendered text into -// the transcript the turn is recorded with. +// TranscribedMessageText replaces the media note in messageText with the +// transcript, keeping any caption after it. func TranscribedMessageText(messageText, transcript string) string { note, caption, _ := strings.Cut(messageText, "\n") if !isMediaNote(note) { diff --git a/internal/domain/messaging/turn.go b/internal/domain/messaging/turn.go index a46a81150..a54fbc205 100644 --- a/internal/domain/messaging/turn.go +++ b/internal/domain/messaging/turn.go @@ -14,13 +14,8 @@ const ( TurnStatusCancelled TurnStatus = "cancelled" ) -// TurnRecord is the durable identity and outcome projection for one chat -// generation. ResponseText is retained so a completed duplicate can replay -// without depending on the bounded model-context history window. ToolCalls -// is retained for the same reason and saved in the same call as -// ResponseText, so a completed-duplicate replay (NATS redelivery, restart -// RecoverTurns redelivery) can narrate the tool activity that produced the -// answer instead of showing a tool-less duplicate beside the original. +// TurnRecord is one chat generation's identity and outcome. ResponseText and +// ToolCalls are kept so a duplicate can be replayed. type TurnRecord struct { TurnID string SessionID string diff --git a/internal/domain/messaging/turns.go b/internal/domain/messaging/turns.go index cf7267966..41e378ecf 100644 --- a/internal/domain/messaging/turns.go +++ b/internal/domain/messaging/turns.go @@ -7,25 +7,9 @@ import ( "sync" ) -// Turns serialises chat turns per session and keeps the running turn -// cancellable. -// -// Channel event loops are typically single-threaded -- go-telegram/bot, -// for one, runs a single worker that calls handlers synchronously. Running -// a turn on that goroutine blocks delivery of every subsequent update, -// including the command meant to stop it: /stop would sit unread in the -// update channel until the turn it was meant to kill had already finished. -// -// Submitting to Turns hands the work to a per-session goroutine and returns -// immediately, so the event loop stays free and control commands are always -// serviceable. Ordering is preserved by the lane being serial, not by the -// event loop being blocked. -// -// Queues are unbounded and never shed. A dropped message is a silent -// failure that surfaces much later as an agent that ignored something, -// which costs far more to diagnose than the memory a backlog occupies. -// [Turns.Stop] is the way a backlog is cleared -- deliberately, by the -// person who created it. +// Turns runs chat turns serially per session on their own goroutines, so +// the channel's event loop stays free, and keeps the running turn +// cancellable. Queues are unbounded. type Turns struct { log *slog.Logger @@ -33,26 +17,14 @@ type Turns struct { lanes map[string]*lane } -// queued is one pending turn: the work, already bound to its own -// cancellable context, and the cancel that releases it. -// -// The context is derived when the turn is submitted rather than when it -// starts running, which means a turn has a live cancel handle for its whole -// time in the backlog. Stop can therefore cancel queued turns rather than -// merely dropping them, and each turn stays tied to the caller that asked -// for it -- it dies when that caller's context does. +// queued is one pending turn with its own cancellable context. type queued struct { run func() cancel context.CancelFunc } -// lane is one session's serial worker. -// -// A single mutex guards the backlog, the running turn's cancel, and whether -// a worker is live, so that Stop observes them together. Splitting them -// would leave a window where a turn finishes between the backlog being -// cleared and the cancel being called, letting a queued turn start after a -// stop. +// lane is one session's serial worker; one mutex guards its backlog, running +// cancel and liveness. type lane struct { mu sync.Mutex pending []queued @@ -70,11 +42,8 @@ func NewTurns(log *slog.Logger) *Turns { return &Turns{log: log, lanes: make(map[string]*lane)} } -// Submit schedules run for the given session and returns without waiting -// for it. run receives a context derived from ctx that [Turns.Stop] can -// cancel. -// -// Submit never blocks and never rejects: messages queue. +// Submit queues run for session and returns. run's context is cancelled by +// Stop. func (t *Turns) Submit(ctx context.Context, session string, run func(context.Context)) { turnCtx, cancel := context.WithCancel(ctx) @@ -102,13 +71,8 @@ func (t *Turns) Submit(ctx context.Context, session string, run func(context.Con } } -// Stop cancels the session's running turn and discards everything queued -// behind it. It reports whether a turn was actually cancelled and how many -// queued turns were dropped. -// -// Dropping the queue is intentional. "Stop" means stop, not "stop this one -// and immediately begin the next thing I said" -- starting the queued turn -// would look to the sender exactly like the stop had failed. +// Stop cancels the session's running turn and drops its queue, reporting +// whether a turn was cancelled and how many were dropped. func (t *Turns) Stop(session string) (cancelled bool, dropped int) { l := t.lane(session) if l == nil { @@ -200,14 +164,8 @@ func (t *Turns) retire(session string, l *lane) bool { return true } -// begin pops the oldest queued turn and publishes its cancel in the same -// critical section. It reports false when the backlog is empty; the owning -// Turns then retires the worker and map entry under both locks. -// -// The pop and the publish must happen together. Were the turn popped first -// and its cancel published after, a Stop landing in between would see an -// empty backlog and no running turn, report that nothing was happening, and -// let the turn it should have killed start regardless. +// begin pops the oldest queued turn and publishes its cancel atomically. It +// reports false when the backlog is empty. func (l *lane) begin() (queued, bool) { l.mu.Lock() defer l.mu.Unlock() @@ -228,13 +186,7 @@ func (l *lane) begin() (queued, bool) { return next, true } -// runOne executes one turn, always retracting its cancel afterwards so a -// later Stop cannot cancel an already-finished turn. -// -// Panics are contained here rather than by the channel's own recovery -// middleware: that middleware wraps the event-loop goroutine, and the turn -// no longer runs on it. Without this, one bad turn would take the lane's -// goroutine down and the session would silently stop answering forever. +// runOne runs one turn, recovering panics, and clears its cancel afterwards. func (l *lane) runOne(next queued, log *slog.Logger) { defer next.cancel() diff --git a/internal/logging/feed.go b/internal/logging/feed.go index 3da8e3aa0..9b0d849c1 100644 --- a/internal/logging/feed.go +++ b/internal/logging/feed.go @@ -99,12 +99,7 @@ func (h *FeedHandler) Handle(ctx context.Context, record slog.Record) error { return h.next.Handle(ctx, record) } -// WithAttrs bakes the current group prefix into each new attr's key -// immediately, rather than storing it raw and re-deriving the key at -// Handle-time from whatever the group chain has grown to by then. Deferring -// it would nest an attr under a group added by a *later* WithGroup call it -// was never actually inside -- slog's contract is that WithGroup affects -// only attrs added afterwards. +// WithAttrs prefixes attrs with the current group chain now. func (h *FeedHandler) WithAttrs(attrs []slog.Attr) slog.Handler { clone := *h clone.attrs = append(append([]slog.Attr(nil), h.attrs...), PrefixAttrs(attrs, h.groups)...) @@ -119,14 +114,8 @@ func (h *FeedHandler) WithGroup(name string) slog.Handler { return &clone } -// PrefixAttrs renames each attr's key with the given dotted group chain, so -// it carries its grouping with it regardless of what the chain grows to -// later. Call this from a slog.Handler's WithAttrs, never from Handle: a -// record's own attrs are always evaluated at the current group nesting, so -// they're flattened with the live chain instead (see FlattenAttrs). -// Exported for the same reason as FlattenAttrs: more than one handler needs -// to get slog's group-nesting contract right (FeedHandler here, and -// agentexec's system-log handler). +// PrefixAttrs prefixes each attr's key with the group chain. For use in +// WithAttrs. func PrefixAttrs(attrs []slog.Attr, groups []string) []slog.Attr { if len(groups) == 0 { return attrs @@ -144,13 +133,8 @@ func PrefixAttrs(attrs []slog.Attr, groups []string) []slog.Attr { return out } -// FlattenAttrs merges base (handler-bound attrs from WithAttrs, already -// keyed with whatever group chain was active when each was added -- see -// prefixAttrs) with a record's own attrs, grouped under the chain currently -// active at Handle-time, into the single flat map Entry.Fields expects on -// decode. Exported because more than one slog.Handler needs to produce -// Entry-shaped output from a slog.Record: FeedHandler here, and agentexec's -// system-log handler shipping a task's own logs. +// FlattenAttrs merges base with a record's attrs under the current group +// chain into a flat map. func FlattenAttrs(record slog.Record, base []slog.Attr, groups []string) map[string]any { fields := map[string]any{} for _, attr := range base { @@ -176,14 +160,7 @@ func addAttr(fields map[string]any, groups []string, attr slog.Attr) { fields[key] = attrValue(attr.Value) } -// attrValue resolves a slog attr to what Entry.Fields should hold on the -// wire. Both consumers of FlattenAttrs (SystemLogHandler, FeedHandler) -// json.Marshal Entry.Fields directly rather than through slog's own JSON -// handler, so an `error` value must be resolved to its message string here: -// encoding/json has no Error()-aware special case, and the concrete types -// behind almost every Go error (errors.errorString, fmt.wrapError, ...) hold -// only unexported fields, which marshal to `{}` and silently discard the -// message. +// attrValue resolves an attr for JSON encoding; errors become their message. func attrValue(v slog.Value) any { if v.Kind() == slog.KindAny { if err, ok := v.Any().(error); ok && !isNilError(err) { @@ -193,13 +170,7 @@ func attrValue(v slog.Value) any { return v.Any() } -// isNilError reports whether err is nil in the way that matters before -// calling Error(): a plain nil interface, or the classic Go footgun where a -// non-nil interface wraps a nil concrete pointer (var e *T; var err error = -// e -- err != nil is true). A logging package's whole job is to never be the -// thing that crashes the process, so this checks for both rather than -// trusting every Error() method in this module and its dependencies to -// tolerate a nil receiver. +// isNilError reports whether err is nil or a nil pointer in an interface. func isNilError(err error) bool { if err == nil { return true diff --git a/internal/logging/logging.go b/internal/logging/logging.go index 4e38d31c8..14d37ffe9 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -1,9 +1,4 @@ -// Package logging builds archied's logger. -// -// archied previously wrote only to stderr, so under systemd journald held the -// sole copy and running by hand left nothing at all. A file sink gives a -// durable record independent of the supervisor, and is what lets the dashboard -// show anything from before it connected. +// Package logging builds archied's logger and reads its JSON log files. package logging import ( @@ -42,12 +37,8 @@ const ( DefaultKeep = 5 ) -// New builds a logger and returns it with a closer for any file sink. The -// closer is a no-op when only stderr is in use. -// -// A file that cannot be opened is reported but never fatal: losing the -// durable copy is worse than losing the daemon, but not by enough to refuse -// to start. +// New builds a logger and a closer for its file sink. A file that cannot be +// opened is reported, not fatal. func New(opts Options) (*slog.Logger, io.Closer, error) { level := parseLevel(opts.Level) handlerOpts := &slog.HandlerOptions{Level: level} @@ -90,10 +81,6 @@ func parseLevel(s string) slog.Level { } // rotatingFile is a size-rotating io.WriteCloser. -// -// Deliberately hand-rolled rather than pulling in a rotation dependency: the -// requirement is one file, a size cap and a retention count, and that is -// materially less code than auditing and tracking a third-party module. type rotatingFile struct { path string maxSize int64 @@ -157,15 +144,8 @@ func (r *rotatingFile) Write(p []byte) (int, error) { return n, err } -// rotate renames the live file to .1, shifting existing generations down and -// discarding anything past keep, then opens a fresh file at path. -// -// The live descriptor is kept open across the renames -- POSIX rename only -// changes a directory entry, not what an open file descriptor points at -- -// so if the rename or the reopen below fails, r.f still refers to a -// perfectly writable file (the original, or the just-rotated one) and the -// caller's write is never lost. Closing the old descriptor only happens -// once the new one is confirmed open. +// rotate shifts path to path.1, dropping generations past keep, and opens a +// new file. The old descriptor stays usable until the new one opens. func (r *rotatingFile) rotate() error { // Oldest first, so each rename lands on a free slot. _ = os.Remove(fmt.Sprintf("%s.%d", r.path, r.keep)) diff --git a/internal/logging/reader.go b/internal/logging/reader.go index 6c1c0303e..1d614a0db 100644 --- a/internal/logging/reader.go +++ b/internal/logging/reader.go @@ -14,11 +14,6 @@ import ( ) // Entry is one decoded log line. -// -// Reading lives here rather than in the dashboard because this package owns -// the on-disk format. If the handler shape or field names change, the reader -// changes with them in the same file, and no consumer has to know slog wrote -// JSON with a "msg" key. type Entry struct { ID int64 `json:"id,omitempty"` Time time.Time `json:"time"` @@ -38,14 +33,8 @@ type Query struct { Levels []string // Component matches the "component" field exactly. Empty means any. Component string - // Stage matches the entry's own "stage" field exactly (case-insensitive). - // Empty means any. - // - // Only entries a stage tagged carry that field. Agent and tool output is - // logged by the runtime that produced it and carries no stage, so a stage - // filter NARROWS the file rather than covering it: the caller is obliged to - // say that, because an honest-looking filter over a partial field is worse - // than no filter. An entry with no stage never matches. + // Stage matches the entry's "stage" field, case-insensitively. Empty + // matches any. Entries without a stage never match. Stage string // Contains matches the message or any field value, case-insensitively. Contains string @@ -77,13 +66,7 @@ type Result struct { Truncated bool `json:"truncated"` // File is the path read, for the UI to show where this came from. File string `json:"file"` - // Found reports whether the file existed. False with a nil error is not a - // failure: a caller asking for a log that has no file yet, or one whose - // attempt produced no output, must be told that rather than shown an empty - // page indistinguishable from a log that is genuinely empty. This is also - // what separates "there is no log for this attempt" from "this process - // cannot read logs at all" -- two conditions that a reader has to report - // differently because only the second is a configuration matter. + // Found reports whether the log file exists. Found bool `json:"found"` } @@ -96,11 +79,7 @@ type TaskLogPage struct { Components []string `json:"components"` } -// ErrTaskLogsUnavailable reports that this process cannot read task logs at -// all -- no reader is configured here. It is deliberately not the same answer -// as "this attempt has no log" (Result.Found = false): a caller that conflates -// them tells an operator task logging is switched off when it is not, which is -// the bug this error exists to prevent. +// ErrTaskLogsUnavailable reports that this process cannot read task logs. var ErrTaskLogsUnavailable = errors.New("logging: task log reader unavailable") // taskLogChunkBytes bounds one write a TaskLogContent makes, so a reader that @@ -108,11 +87,8 @@ var ErrTaskLogsUnavailable = errors.New("logging: task log reader unavailable") // io.Copy would otherwise hand it reads of its own choosing. const taskLogChunkBytes = 256 << 10 -// TaskLog reads one task attempt's persisted log from this registry. A nil -// registry (task logging not configured for this process) reports -// ErrTaskLogsUnavailable, never an empty page: a process that cannot read logs -// must say so rather than implicate the attempt. Safe to call on a nil -// receiver, like every other method here. +// TaskLog reads one task attempt's log. A nil registry returns +// ErrTaskLogsUnavailable. func (r *TaskRegistry) TaskLog(_ context.Context, taskID int64, attempt int, q Query) (TaskLogPage, error) { if r == nil { return TaskLogPage{}, ErrTaskLogsUnavailable @@ -134,15 +110,8 @@ func (r *TaskRegistry) TaskLog(_ context.Context, taskID int64, attempt int, q Q return page, nil } -// TaskLogContent writes one task attempt's log to w exactly as it is on disk, -// for a caller that wants the file rather than a decoded page. found is false, -// with a nil error, when the attempt has no log file -- a normal state for an -// attempt that produced no output, and not an error. A nil registry reports -// ErrTaskLogsUnavailable, matching TaskLog. -// -// The content is streamed rather than returned as one slice because a log file -// is unbounded input (it rotates at DefaultMaxSizeMB), and a caller moving it -// across a transport with a message-size limit needs it in pieces. +// TaskLogContent streams one attempt's raw log to w. found is false when +// there is no file. A nil registry returns ErrTaskLogsUnavailable. func (r *TaskRegistry) TaskLogContent(_ context.Context, taskID int64, attempt int, w io.Writer) (bool, error) { if r == nil { return false, ErrTaskLogsUnavailable @@ -161,14 +130,8 @@ func (r *TaskRegistry) TaskLogContent(_ context.Context, taskID int64, attempt i return true, nil } -// PageResult is what a single forward-paged call returns. -// -// Cursor is the byte offset within path at which the next page should -// resume -- pass it back as Page's cursor argument. A Cursor equal to -// or past the file's current size means there is nothing more to read. -// MoreAvailable is true iff the scan saw at least one matching entry it -// did not return because Limit was already satisfied; it does NOT imply -// the file has been read to the end (combine with Truncated). +// PageResult is one forward page. Pass Cursor back to continue. +// MoreAvailable reports matches beyond Limit. type PageResult struct { Entries []Entry `json:"entries"` Truncated bool `json:"truncated"` @@ -221,17 +184,7 @@ func readWindow(path string) (w logWindow, found bool, err error) { } w.data = make([]byte, size) - // ReadAt, never Read: io.ReaderAt guarantees it either fills the - // buffer or returns a non-nil error, whereas Read may legally return - // fewer bytes with a nil error. A silent short read here would leave - // the tail of the buffer as zero bytes, which decode rejects -- so - // the NEWEST entries would vanish from every result while the call - // still reported success. That is the worst possible failure for a - // log reader, and it is the one Read invites. - // - // Guarded on len>0 because a zero-length ReadAt at end-of-file is - // permitted to return io.EOF, and an empty log is a valid empty - // result rather than an error. + // ReadAt fills the buffer or errors; skip it for an empty window. if len(w.data) > 0 { if _, err := f.ReadAt(w.data, w.start); err != nil { return logWindow{}, false, fmt.Errorf("logging: read %s: %w", path, err) @@ -240,34 +193,9 @@ func readWindow(path string) (w logWindow, found bool, err error) { return w, true, nil } -// readLines walks every JSONL line in path within the scan window -// (tail-most maxScanBytes), invoking step with each decoded entry that -// matches q and the file offset just past the line's terminating '\n'. -// It returns whether the scan hit maxScanBytes before EOF (so older -// matching entries exist that were not examined) and the file offset -// the caller should use as its next-page Cursor. -// -// cursor=0 begins at the scan window's start (same as Tail); a cursor -// past the scan window's start resumes partway through. A cursor at or -// past EOF returns ok=false without invoking step -- either the caller -// has read everything, or the file shrank under rotation. -// -// SCAN WINDOW IS A HARD CEILING, and it bounds pagination too. For a -// file larger than maxScanBytes the oldest bytes are never examined by -// ANY call, no matter how the caller pages: every call re-derives the -// window from the CURRENT file size, and the cursor is clamped up into -// it. Paging therefore walks the window exhaustively and stops; it does -// not walk backwards into history. truncated=true is the signal that -// this happened, and it is the caller's job to surface that rather than -// implying the log was read whole. Rotated generations -// (.1, .2, ...) are separate files this function never opens. -// -// Implementation: the window is read into memory in one Read, then -// walked by exact slice offsets. Offsets into a single contiguous -// buffer are trivially correct, which an incremental reader over the -// file is not: bufio.Reader buffers ahead, so its underlying file -// position runs up to one buffer past its logical position and cannot -// be used to derive a cursor. +// readLines calls step for each matching entry in the last maxScanBytes of +// path, with the offset after its line. It returns whether the window +// excluded older data and the next cursor. Older data is never read. func readLines(path string, q Query, cursor int64, step func(e Entry, endOff int64) bool) (truncated bool, cursorOut int64, ok bool, err error) { w, found, err := readWindow(path) if err != nil || !found { @@ -290,21 +218,10 @@ func readLines(path string, q Query, cursor int64, step func(e Entry, endOff int return truncated, cursor, false, nil } - // The caller's cursor is a file offset. Convert to an offset within - // `data` (which begins at windowStart). The clamp above guarantees - // cursor >= windowStart, so this cannot go negative; min() only - // guards against a caller-supplied cursor inside the window but past - // its end, which the EOF check above does not catch when the file is - // larger than maxScanBytes. + // Convert the file cursor to an offset in data. cursorInWindow := min(cursor-windowStart, int64(len(data))) - // When the caller resumes at the very start of the scan window, the - // first line may have been truncated by the size-cap seek. Drop - // bytes up to and including the first '\\n' so the caller never sees - // a partial first entry. If there is no '\\n' at all, the file (or - // the visible window) is one giant unterminated line: report it as - // truncated (already true) and stop -- there is nothing for the - // caller to page through. + // Skip a partial first line at the window start. if cursor == windowStart && truncated { idx := bytes.IndexByte(data, '\n') if idx < 0 { @@ -316,28 +233,9 @@ func readLines(path string, q Query, cursor int64, step func(e Entry, endOff int return truncated, walkWindow(data, windowStart, cursorInWindow, q, step), true, nil } -// walkWindow invokes step for each entry in data at or after the -// in-buffer offset from that decodes and matches q, and returns the FILE -// offset at which the next page should resume. -// -// step receives the file offset just past the line it was given, and -// returns false to stop the walk; walkWindow then returns the cursor -// exactly there. A line that fails to decode is skipped rather than -// ending the walk -- a log may carry subprocess output that does not -// share our format. -// -// NOTE: a `false` return from step does NOT mean "no more matches". It -// means "you have enough for this page; stop here so you can return to -// the caller." The next call, started from the cursor walkWindow -// returns, will revisit the file offset step saw and continue walking. -// The caller is responsible for distinguishing the two outcomes via -// the limit it passed. -// -// The returned cursor is the FILE offset of the first byte after the -// last line walked, regardless of whether step stopped the walk early -// or the buffer was exhausted. Cursor values are in the same coordinate -// system across calls (file offset), so passing one straight back into -// the next Page call resumes the walk cleanly. +// walkWindow calls step for each matching entry from offset from, skipping +// undecodable lines, and returns the file offset to resume at. step returns +// false to stop. func walkWindow(data []byte, windowStart, from int64, q Query, step func(e Entry, endOff int64) bool) int64 { pos := from for pos < int64(len(data)) { @@ -366,17 +264,9 @@ func walkWindow(data []byte, windowStart, from int64, q Query, step func(e Entry return windowStart + pos } -// Tail returns the most recent entries in path matching q. -// -// Entries are returned oldest-first so the UI can append newer ones from the -// live stream without reordering. A missing file is not an error: file logging -// is optional, and an empty result with a clear File value lets the caller say -// so rather than showing a failure. -// -// Tail preserves the legacy ring-buffer semantics: when more than Limit -// matching entries exist within the scan window, the OLDEST matches are -// dropped and Truncated is set. Page is the forward-paged alternative -- -// callers that want every entry reachable should use Page, not Tail. +// Tail returns the most recent matching entries in path, oldest first. A +// missing file is not an error. Past Limit, older matches are dropped and +// Truncated is set. func Tail(path string, q Query) (Result, error) { res := Result{Entries: []Entry{}, File: path} limit := q.Limit @@ -387,11 +277,7 @@ func Tail(path string, q Query) (Result, error) { limit = MaxTailLines } - // found is read before readLines so an absent file is reported as such - // rather than only as an empty entry list -- see Result.Found. It is a - // Stat rather than a second readWindow: readLines reads the whole scan - // window, and doing that twice per Tail call would double the cost of - // every log view for one boolean. + // Stat for Found without reading the window twice. if strings.TrimSpace(path) != "" { if _, err := os.Stat(path); err == nil { res.Found = true @@ -413,11 +299,7 @@ func Tail(path string, q Query) (Result, error) { return Result{}, err } if !ok { - // A "nothing to read" early return (file > maxScanBytes with no - // terminator in the window) is still Truncated: the scan cap - // fired. Preserve that signal even though we have no entries to - // surface -- the caller must know that older matching entries - // exist beyond what we examined. + // Truncated stays set even with no entries. res.Truncated = truncated return res, nil } @@ -426,26 +308,9 @@ func Tail(path string, q Query) (Result, error) { return res, nil } -// Page walks path forward from cursor, returning up to Limit matching -// entries (clamped to MaxTailLines). A cursor of 0 starts at the -// beginning of the scanned window, exactly as Tail does. -// -// The returned Cursor is the byte offset at which the next call should -// resume; pass it back unchanged. When the file has been read to EOF -// within maxScanBytes, Cursor equals the file's size and MoreAvailable -// is false. Truncated is true when the scan cap fired before EOF, -// meaning older matching entries exist that were never examined -- the -// caller must decide whether to walk the rotation history or surface -// the gap. -// -// A cursor that points past the file's current size returns an empty -// page with MoreAvailable=false: rotation may have shrunk the file, and -// the next page is whatever the file now contains. -// -// Cursor=0 with a file larger than maxScanBytes begins at the first -// complete line AFTER the size-cap seek, exactly as Tail does -- -// identical output to Tail under the same query when Limit is large -// enough to hold everything. +// Page returns up to Limit matching entries from cursor, and the cursor to +// resume at. Truncated means older entries were not examined. A cursor past +// the end returns an empty page. func Page(path string, q Query, cursor int64) (PageResult, error) { res := PageResult{Entries: []Entry{}, File: path} limit := q.Limit @@ -487,16 +352,8 @@ func Page(path string, q Query, cursor int64) (PageResult, error) { for i, m := range matches { res.Entries[i] = m.entry } - // The cursor must resume AFTER the last entry this page returned, so - // the next call does not re-walk the same entries. When the walk - // stopped because the limit was reached (MoreAvailable), that resume - // point is the end of the last matching line. When the walk ran the - // whole buffer to completion (no more matches), the cursor is the - // walk's own end offset -- which can sit past trailing lines that - // failed the filter or failed to decode, and must, otherwise the next - // call would re-walk those trailing bytes forever. The two values - // differ only in the MoreAvailable=false case, which is exactly the - // case where the doc comment promises "Cursor equals the file's size". + // Resume after the last returned entry when the page filled, else at the end + // of the walk. if res.MoreAvailable { res.Cursor = matches[len(matches)-1].endOff } else { @@ -535,18 +392,8 @@ func decode(line []byte) (Entry, bool) { return entry, true } -// withinTimeBounds reports whether t satisfies q's Since/Until bounds. -// Both bounds are inclusive, and an unset (zero) bound is no bound. -// -// An entry whose timestamp did not parse -- missing, non-string, or -// malformed "time", all of which leave decode's Entry.Time zero rather -// than dropping the record -- cannot be placed in a range, so ANY -// time-bounded query excludes it. That check is explicit rather than -// implied, because the two comparisons are not symmetric about the zero -// time on their own: zero.Before(since) is true so Since would drop such -// entries, while zero.After(until) is false so Until would silently keep -// them, and "errors before noon" would come back carrying records with -// no known time at all. +// withinTimeBounds reports whether t is within q's inclusive Since/Until +// bounds. An entry with no parsed time fails any bound. func (q Query) withinTimeBounds(t time.Time) bool { if q.Since.IsZero() && q.Until.IsZero() { return true diff --git a/internal/logging/registry.go b/internal/logging/registry.go index 62619e38f..402b2aa8f 100644 --- a/internal/logging/registry.go +++ b/internal/logging/registry.go @@ -8,25 +8,11 @@ import ( "time" ) -// receivedAtField is the record field carrying the receipt time of a -// remotely-shipped entry, alongside the entry's own event time in Time. -// Shipping and arriving are different moments -- a container's records cross -// NATS and can land in a burst, so a log that files them under arrival time -// cannot say when anything actually happened. Keeping both lets a reader -// measure delivery latency without losing the event's own timeline. +// receivedAtField records when a shipped entry was received. const receivedAtField = "received_at" -// TaskRegistry manages one open log destination per currently-running task -// attempt, shared between whatever starts and ends a task's run (Open, -// Close) and whatever receives that task's remotely-shipped log records -// (Write) -- in the daemon, two different goroutines: task dispatch, and -// the NATS system-log subscription handler. -// -// The zero value is not usable; construct with NewTaskRegistry. A nil -// *TaskRegistry is safe to call every method on and always behaves as -// "task logging is not configured" -- the same "optional, nil means -// disabled" convention every other composition-wired field in Daemon -// follows, so callers never need a separate nil check before using one. +// TaskRegistry holds one open log sink per running task attempt. Construct +// with NewTaskRegistry; every method is safe on nil, meaning disabled. type TaskRegistry struct { baseDir string feed *Feed @@ -90,21 +76,9 @@ func (r *TaskRegistry) Close(taskID int64) error { return entry.sink.Close() } -// Write appends one remotely-shipped entry to taskID's open sink, mirroring -// it into the live dashboard feed the same way a locally-written log would -// be. The entry keeps the event time it was shipped with; the moment this -// process received it is recorded separately as the received_at field. -// Arrival time is never substituted for event time -- stamping on arrival is -// exactly what makes a run's timing unrecoverable. -// Reports false for a task with no open sink -- not an error: a system -// log message is fire-and-forget best effort, and a late or duplicate -// delivery after the task finished (or one this daemon instance never -// dispatched) is expected, not exceptional. -// -// ctx is the caller's, used for the handler's own attribute extraction. It is -// not consulted for cancellation: a park is recorded at exactly the moment a -// run's context has been cancelled, and that entry is the one an operator most -// needs to read. +// Write appends a shipped entry to taskID's open sink and the live feed, +// keeping its event time and recording received_at. It returns false when no +// sink is open. ctx cancellation is ignored. func (r *TaskRegistry) Write(ctx context.Context, taskID int64, entry Entry) bool { if r == nil { return false @@ -119,12 +93,7 @@ func (r *TaskRegistry) Write(ctx context.Context, taskID int64, entry Entry) boo var level slog.Level _ = level.UnmarshalText([]byte(entry.Level)) // unparseable falls back to Info, slog.Level's zero value - // File the record under the time the event happened, not the time this - // process received it. A run's records arrive in whatever bursts the - // transport produces, so stamping them on arrival collapses a - // multi-minute run onto a few milliseconds and makes its timing - // unrecoverable. An entry carrying no time of its own (the field is - // optional) is stamped now, so a line is never filed under the zero time. + // Use the entry's own time, or now if it has none. received := time.Now() happened := entry.Time if happened.IsZero() { @@ -137,11 +106,7 @@ func (r *TaskRegistry) Write(ctx context.Context, taskID int64, entry Entry) boo } attrs = append(attrs, slog.Time(receivedAtField, received)) - // slog.Logger.LogAttrs always stamps time.Now() and cannot be handed a - // record, so build the record here and dispatch it through the same - // handler the logger holds. The Enabled check is the logger's -- calling - // the handler directly skips it, which would write an entry below the - // sink's level to the file while the feed, gated separately, dropped it. + // Build the record directly to keep its time, checking Enabled first. record := slog.NewRecord(happened, level, entry.Message, 0) record.AddAttrs(attrs...) handler := got.logger.Handler() @@ -152,11 +117,7 @@ func (r *TaskRegistry) Write(ctx context.Context, taskID int64, entry Entry) boo return true } -// Path returns the on-disk path for one task attempt's log file under this -// registry's baseDir, for callers that only need to read a task's history -// (the API handler, chat tools) rather than write to it. Safe to call on a -// nil registry -- returns "" the same way every write method reports "task -// logging is not configured" on a nil receiver. +// Path returns one attempt's log file path, or "" on a nil registry. func (r *TaskRegistry) Path(taskID int64, attempt int) string { if r == nil { return "" @@ -164,11 +125,7 @@ func (r *TaskRegistry) Path(taskID int64, attempt int) string { return TaskLogPath(r.baseDir, taskID, attempt) } -// Remove deletes taskID's entire log directory -- every attempt, every -// rotated generation -- so task logs don't accumulate forever once a task -// is archived. Safe to call whether or not a sink is currently open (Close -// first regardless: this only removes files, it does not stop writes to an -// open sink) and whether or not the directory exists at all. +// Remove deletes taskID's whole log directory. func (r *TaskRegistry) Remove(taskID int64) error { if r == nil { return nil diff --git a/internal/logging/tasksink.go b/internal/logging/tasksink.go index 6a16c9a7f..f01ca3bd7 100644 --- a/internal/logging/tasksink.go +++ b/internal/logging/tasksink.go @@ -43,17 +43,8 @@ type TaskSink struct { 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. +// NewTaskSink opens the rotating JSONL sink for one task attempt. Unlike New, +// it returns an error when the file cannot be opened. 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)