diff --git a/configtemplate.go b/configtemplate.go index 6e4714a8c..e512332d2 100644 --- a/configtemplate.go +++ b/configtemplate.go @@ -1,12 +1,5 @@ -// Package configtemplate embeds config.example.toml so archied setup can -// generate a first-run config.toml from the exact file operators already -// read as documentation, instead of a second copy that can drift from it. -// -// It lives at the module root, rather than under internal/, because embed -// patterns cannot reach outside the directory of the .go file that declares -// them, and config.example.toml is kept at the root where it is easy to -// find and hand-edit. (Written without the directive prefix on purpose: -// staticcheck reads "// go:embed" in prose as a malformed directive.) +// Package configtemplate embeds config.example.toml for archied setup. It +// sits at the module root because embed cannot reach parent directories. package configtemplate import _ "embed" diff --git a/internal/app/archieplaybooks/lint.go b/internal/app/archieplaybooks/lint.go index d2327f99d..e29014922 100644 --- a/internal/app/archieplaybooks/lint.go +++ b/internal/app/archieplaybooks/lint.go @@ -1,11 +1,5 @@ -// Package archieplaybooks is the application composition for the standalone -// playbook-validation CLI (cmd/archie-playbooks). It owns the lint mode's -// orchestration: collect the configured directories, run the domain -// validators, and shape the outcome for human consumption. The rules live in -// internal/domain/workflow (routing binding files) and -// internal/domain/eda/playbook (EDA playbooks) -- this package only calls the -// loaders the daemon runs and formats results; there is deliberately no -// second validation path here. +// Package archieplaybooks implements the archie-playbooks CLI, using the +// daemon's own playbook loaders. package archieplaybooks import ( @@ -24,16 +18,8 @@ type Result struct { Findings []string } -// Lint validates one or more playbook directories against the domain -// loaders and reports every collision / malformed file / invalid binding as -// a finding. It returns exit code 0 on a clean set, 1 when any finding is -// reported. Directories and single-file fields share one validation source: -// -// workflow.LoadPlaybookDirs -// -// which already applies the same rules LoadKindWorkflowsYAML and -// LoadLabelWorkflowsYAML do, per file and across files -- so the linter can -// never disagree with the daemon's startup validation. +// Lint validates playbook directories with workflow.LoadPlaybookDirs and +// reports every finding. It returns 0 when clean, 1 otherwise. func Lint(dirs []string, stderr io.Writer) Result { var findings []string diff --git a/internal/app/archieplaybooks/serve.go b/internal/app/archieplaybooks/serve.go index 1cd5b4427..152ed3669 100644 --- a/internal/app/archieplaybooks/serve.go +++ b/internal/app/archieplaybooks/serve.go @@ -17,11 +17,9 @@ import ( "gopkg.in/yaml.v3" ) -// Serve runs the language server over rwc until the client disconnects or -// ctx ends. It publishes diagnostics when a playbook file is opened or saved, -// by linting the file's saved directory with the loader the daemon runs for -// it: the whole directory, because a collision is a cross-file finding. -// Unsaved edits are not validated. +// Serve runs the language server over rwc until the client disconnects or ctx +// ends, publishing diagnostics for the saved directory when a playbook is +// opened or saved. func Serve(ctx context.Context, rwc io.ReadWriteCloser) error { s := &server{exited: make(chan struct{})} _, conn, client := protocol.NewServer(ctx, s, jsonrpc2.NewStream(rwc)) diff --git a/internal/channels/email/email.go b/internal/channels/email/email.go index 1ff75c853..52ebd9c85 100644 --- a/internal/channels/email/email.go +++ b/internal/channels/email/email.go @@ -1,8 +1,4 @@ -// Package email implements gateway.Gateway for inbound email via SMTP. -// A lightweight SMTP server receives emails on a configurable port -// (intended for localhost use behind a mail relay like Postfix). -// Inbound messages are routed through the gateway for LLM processing; -// replies are sent via SMTP relay to the original sender. +// Package email receives email over SMTP and replies through an SMTP relay. package email import ( diff --git a/internal/channels/ephemeral.go b/internal/channels/ephemeral.go index aee18f14f..4de11cd79 100644 --- a/internal/channels/ephemeral.go +++ b/internal/channels/ephemeral.go @@ -20,12 +20,8 @@ const defaultEphemeralDeleteTimeout = 30 * time.Second // of that message is then skipped rather than attempted blindly. type SendFunc func(ctx context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error) -// EphemeralSender delivers EphemeralReplies and retracts them after their TTL. -// -// The retraction runs on its own goroutine, so a TTL that has not elapsed -// never holds the turn that sent the reply. after is injected so the TTL -// fires in tests without sleeping; nil selects time.After, which is the -// production shape. +// EphemeralSender sends EphemeralReplies and deletes them after their TTL. +// after defaults to time.After. type EphemeralSender struct { after func(time.Duration) <-chan time.Time timeout time.Duration @@ -48,15 +44,9 @@ func NewEphemeralSender(log *slog.Logger, after func(time.Duration) <-chan time. } } -// Send delivers reply.Event through send. When sender reports the Delete -// capability, the delivered message is retracted once reply.TTL elapses; -// otherwise the reply is left in place and the fact is logged once, at debug -// level. A platform that cannot delete must never fail the turn, so the -// degrade returns the send's outcome rather than an error. -// -// A send error is returned unchanged and no retraction is scheduled: there -// is no message to remove. A non-positive TTL or a send that reported no -// message identifier also schedules nothing. +// Send delivers reply.Event and schedules its deletion after reply.TTL when +// sender supports Delete. A send error is returned; nothing is scheduled +// without a message ID or a positive TTL. func (e *EphemeralSender) Send(ctx context.Context, sender any, reply messaging.EphemeralReply, send SendFunc) (messaging.MessageEvent, error) { sent, err := send(ctx, reply.Event) if err != nil { diff --git a/internal/channels/status/status.go b/internal/channels/status/status.go index 2b97466a1..587bdd4bd 100644 --- a/internal/channels/status/status.go +++ b/internal/channels/status/status.go @@ -1,9 +1,5 @@ -// Package status is the operator-facing channel lifecycle ledger: the -// State/Descriptor/Status vocabulary and the Manager that owns runtime -// facts for the dashboard and readiness surfaces. It lives beside the -// channels package rather than inside it so UI-process code can hold the -// types without linking the plugin contract there -- which references the -// gateway runtime. +// Package status tracks channel lifecycle state for the dashboard and +// readiness. package status import "sync" diff --git a/internal/channels/webhook/webhook.go b/internal/channels/webhook/webhook.go index ff6415fbf..189db4269 100644 --- a/internal/channels/webhook/webhook.go +++ b/internal/channels/webhook/webhook.go @@ -194,12 +194,7 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc { return } - // A rate-limited delivery was dropped before reaching the LLM, not - // completed: it must not be echoed back as a successful "origin" reply - // (chat prose, meant for a human) or 202'd as accepted (indistinguishable - // from a delivered event, so the source would never retry it). 429 lets - // the source back off and retry, the way internal/webhookguard.RateLimiter's - // other callers already respond. + // A rate-limited delivery answers 429 so the source retries. if reply.RateLimited { http.Error(w, "rate limited", http.StatusTooManyRequests) return diff --git a/internal/domain/access/access.go b/internal/domain/access/access.go index 050c46f1e..0ff63ee76 100644 --- a/internal/domain/access/access.go +++ b/internal/domain/access/access.go @@ -1,20 +1,9 @@ -// Package access owns the policy schema, the action vocabulary, how -// principals and resources are turned into policy entities, and the -// Authorizer contract. +// Package access defines the policy schema, the action vocabulary, policy +// entities and the Authorizer contract. The chain is // -// The policy chain is +// instance ─▶ org ─▶ workspace ─▶ object // -// instance ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object -// -// and the Cedar implementation lives in internal/infrastructure/access; -// internal/app wires it. Exactly two places call the Authorizer: the -// dashboard and API request path, and dispatch. Every other service verifies -// a credential and never evaluates policy. -// -// The chain's "identity + workflow" level is expressed with object policies: -// an identity or a workflow is one of the objects a policy can attach to -// (event source, secret, identity, binding, workflow), so the stored levels -// are instance, org, workspace and object. +// The Cedar engine is in internal/infrastructure/access. package access import ( @@ -109,12 +98,9 @@ const ( KindEventIngest ResourceKind = "event" ) -// Policy is one stored policy document. Its Text is Cedar policy language -// (one policy: an effect, a principal/action/resource scope and conditions). -// -// The scope fields say where the policy attaches. LevelInstance policies -// carry none; LevelOrg carries OrgID; LevelWorkspace adds WorkspaceID; -// LevelObject adds ObjectKind and ObjectID. +// Policy is one stored Cedar policy. LevelInstance has no scope; LevelOrg sets +// OrgID; LevelWorkspace adds WorkspaceID; LevelObject adds ObjectKind and +// ObjectID. type Policy struct { ID string `json:"id"` Level Level `json:"level"` diff --git a/internal/domain/access/authorizer.go b/internal/domain/access/authorizer.go index 2fedaac13..a2b805a0f 100644 --- a/internal/domain/access/authorizer.go +++ b/internal/domain/access/authorizer.go @@ -5,14 +5,8 @@ package access import "context" -// Authorizer evaluates the policy chain for one request. Exactly two places -// call it: the dashboard and -// API request path, and dispatch. The implementation is the Cedar engine in -// internal/infrastructure/access. -// -// Authorize never fails open: a stored policy the engine cannot parse makes -// its level deny everything and the decision carries the error; an invalid -// instance policy is a boot failure, not a denial the request path sees. +// Authorizer evaluates the policy chain for a request. It never fails open: +// an unparsable stored policy denies its whole level. type Authorizer interface { // Authorize evaluates instance, org, workspace and object policies for // the request. A request is allowed only if every level with policies @@ -21,11 +15,7 @@ type Authorizer interface { Authorize(p Principal, a Action, r Resource, c Context) Decision } -// Validator checks one policy against the current schema: Cedar syntax plus -// the entity vocabulary this package defines. A policy naming an unknown -// entity type, action or attribute is refused. Every stored policy is -// checked again when archie starts (the engine's construction reports the -// invalid ones). +// Validator checks a policy's Cedar syntax and entity vocabulary. type Validator interface { Validate(p Policy) error } diff --git a/internal/domain/access/request.go b/internal/domain/access/request.go index a2ea1ff13..73997e0f0 100644 --- a/internal/domain/access/request.go +++ b/internal/domain/access/request.go @@ -1,8 +1,3 @@ -// The entities a decision is made about. The domain owns their shape and the -// Cedar vocabulary they are built from (the schema); the engine in -// internal/infrastructure/access turns them into engine entities. This file -// carries no Cedar dependency: the vocabulary is plain constants so the -// domain never links the engine. package access import ( diff --git a/internal/domain/access/roles.go b/internal/domain/access/roles.go index 1543affd1..654f80059 100644 --- a/internal/domain/access/roles.go +++ b/internal/domain/access/roles.go @@ -1,10 +1,3 @@ -// The shipped policies: the four org roles every org carries, and the -// cross-org forbid the engine always enforces -// -// The role policies are Cedar policy text because that is what the engine -// evaluates. They live in the domain so the store seeds them, the reset -// command restores them, and the engine ships the same words regardless of -// which process builds it. package access import "github.com/samcharles93/archie-core/internal/domain/org" diff --git a/internal/domain/agent/soul.go b/internal/domain/agent/soul.go index 8596bd3a1..d4057a0da 100644 --- a/internal/domain/agent/soul.go +++ b/internal/domain/agent/soul.go @@ -2,16 +2,8 @@ package agent import "strings" -// DefaultSoul is the starter SOUL document this build ships. -// -// It is deliberately independent of ShippedPersonas: the persona catalogue is -// a style axis that is being retired, while the starter SOUL is the fallback -// identity a user edits. Deleting personas must not delete the fallback. -// -// The document is plain Markdown and becomes the identity slot of the system -// prompt, XML-escaped beneath the invariant sections. It owns the agent's -// name, register and warmth only; it cannot change the rules, tools or runtime -// metadata, so keep it to identity prose. +// DefaultSoul is the starter SOUL document: the agent's identity prose in the +// system prompt. const DefaultSoul = `# Archie You are Archie, a capable coding and project assistant. Be direct without being @@ -21,23 +13,12 @@ verified. Do not impersonate another assistant, provider, or vendor. ` // ShippedSoul returns the SOUL document this build ships. -// -// Exactly one body is shipped, so the seeder recognises only this text as -// untouched scaffolding. A build that supersedes it adds the old body next to -// this one together with the in-place upgrade that consumes it; a branch that -// rewrites a file for matching a template no build ever shipped has no -// producer and must not be kept ahead of one. func ShippedSoul() string { return DefaultSoul } -// SoulMatchesShipped reports whether content is the same body as shipped, once -// transport noise is normalised away. -// -// Comparison is on normalised content, so a CRLF checkout or an editor that -// left trailing whitespace still matches the template it came from. Only a -// body that is identical to a shipped document after that normalisation is -// eligible for replacement; any other difference is treated as user intent. +// SoulMatchesShipped reports whether content equals shipped after line-ending +// and trailing-whitespace normalisation. func SoulMatchesShipped(content, shipped string) bool { return normalizeSoul(content) == normalizeSoul(shipped) } diff --git a/internal/domain/applystatus/applystatus.go b/internal/domain/applystatus/applystatus.go index 1b0cb5c30..2f7e91ce3 100644 --- a/internal/domain/applystatus/applystatus.go +++ b/internal/domain/applystatus/applystatus.go @@ -55,14 +55,8 @@ type Reporter struct { applied map[string]storecontract.ApplyStatus } -// New returns a Reporter for one process, or nil when there is no store to -// report to or the composition is a process that applies nothing, such as the -// State Store itself. -// -// A name Processes() does not list is refused rather than reported: the reader -// renders the names it knows, so an invented one would vanish from the page -// exactly as a process that never started does. Failing here makes a new -// process declare itself in one place. +// New returns a Reporter for process, or nil when there is no store or the +// process applies nothing. Unknown process names are refused. func New(process string, store storecontract.ApplyStatusStore, log *slog.Logger) *Reporter { if store == nil || process == "" { return nil @@ -80,12 +74,8 @@ func New(process string, store storecontract.ApplyStatusStore, log *slog.Logger) } } -// Report records that this process applied version of kind, or failed to. -// A failure leaves the recorded version alone: an edit this process rejected -// does not change which version is live in it. -// -// Best-effort by construction. The configuration a report describes has -// already been applied, so a failed report is logged and never returned. +// Report records that this process applied version of kind, or failed to. A +// failure keeps the previous version. Errors are logged. func (r *Reporter) Report(ctx context.Context, kind string, version int64, applyErr error) { if r == nil { return @@ -107,11 +97,7 @@ func (r *Reporter) Report(ctx context.Context, kind string, version int64, apply r.write(ctx, status) } -// AppliedVersion returns the version last recorded for kind, or 0 when this -// process has reported none. A caller that reports an outcome rather than an -// application -- the plugin directory reconciliation, which reports against -// the plugin-settings version the process is already running -- reads it so a -// clean pass does not reset the version to zero. +// AppliedVersion returns the last version recorded for kind, or 0. func (r *Reporter) AppliedVersion(kind string) int64 { if r == nil { return 0 diff --git a/internal/domain/binding/binding.go b/internal/domain/binding/binding.go index 379180423..24f1013b8 100644 --- a/internal/domain/binding/binding.go +++ b/internal/domain/binding/binding.go @@ -11,11 +11,8 @@ import ( "github.com/samcharles93/archie-core/internal/domain/org" ) -// Status is the binding lifecycle state. Mirrors telegram's -// dangerousAction / pendingApproval shape: a binding is created -// pending_approval, armed is the only state that evaluates against incoming -// events, any edit drops armed back to pending_approval, and only an -// explicit Approve call moves pending_approval -> armed. +// Status is a binding's state. New bindings are pending_approval; only armed +// bindings dispatch; any edit returns to pending_approval; Approve arms. type Status string const ( @@ -23,25 +20,13 @@ const ( StatusArmed Status = "armed" ) -// Matcher decides which captured events a binding applies to. Source is -// the only dimension today -- the path segment the sender POSTs to -// (e.g. "sentry"). Extend with additional predicates if a use case -// demands it; the storage column is plain TEXT so widening is -// non-breaking. +// Matcher selects the captures a binding applies to, by source path segment. type Matcher struct { Source string `json:"source"` } -// Binding is the runtime-editable entity that ties a matcher, a payload -// mapping, and a workflow together. Bindings live in the store, not in -// config.toml, so operators can author them from the dashboard while the -// daemon runs. Any number of bindings may share a source: each one applies to -// the event type its mapping belongs to. -// -// Version is bumped on every UpdateBinding so a later edit cannot -// silently rewrite the historical provenance of a task that already -// fired. Signing belongs to the source the matcher names, not to the -// binding (internal/domain/source). +// Binding ties a source matcher, a payload mapping and a workflow together. +// Version increments on every update. type Binding struct { ID string `json:"id"` Name string `json:"name"` @@ -51,12 +36,7 @@ type Binding struct { // (CompileFilter). An event it excludes is not dispatched. Filter string `json:"filter,omitempty"` Workflow string `json:"workflow"` - // Owner and Repo pin a binding to a specific configured repo, so a - // multi-repo deployment can dispatch correctly. Both empty means "no - // pin" -- resolveBindingRepo falls back to the single-configured-repo - // behaviour that predates this field. Setting only one is invalid - // (Validate rejects it): a pin is a complete owner/repo pair or not a - // pin at all, never a half-guess. + // Owner and Repo pin the binding to a repo. Both or neither must be set. Owner string `json:"owner,omitempty"` Repo string `json:"repo,omitempty"` // RepoParam names the mapped parameter holding "owner/name" when the diff --git a/internal/domain/binding/inputs.go b/internal/domain/binding/inputs.go index 2dc941d00..37914efcd 100644 --- a/internal/domain/binding/inputs.go +++ b/internal/domain/binding/inputs.go @@ -23,11 +23,9 @@ func (s InputSource) validate(name string) error { return nil } -// CheckWorkflow checks the binding against the workflow it targets and the -// mapping it reads, as the binding is saved: every assigned input is declared, -// every required input is assigned, a parameter exists and its type feeds the -// input's, a constant has the input's type, and the repository agrees with the -// workflow's repository mode. +// CheckWorkflow validates the binding against its workflow and mapping: +// inputs declared and assigned with matching types, and a compatible +// repository. func (b Binding) CheckWorkflow(w task.WorkflowInterface, fields []mapping.Field) error { byName := make(map[string]mapping.Field, len(fields)) for _, f := range fields { diff --git a/internal/domain/curator/activity.go b/internal/domain/curator/activity.go index c105e76b4..44f423367 100644 --- a/internal/domain/curator/activity.go +++ b/internal/domain/curator/activity.go @@ -21,12 +21,7 @@ type Activity struct { Recent []Action } -// activityTracker records recent curator activity in memory, fed directly -// from the runtime's own emit point (Runtime.emitRun) rather than by -// re-subscribing to the event bus -- the runtime already has the pass -// result in hand, and EventSink is fire-and-forget with no replay. Activity -// resets on daemon restart, same as every other piece of runtime state the -// curator family holds only in memory. +// activityTracker records recent curator activity in memory. type activityTracker struct { mu sync.Mutex data map[string]*Activity diff --git a/internal/domain/curator/contract.go b/internal/domain/curator/contract.go index e8c364518..645f77e10 100644 --- a/internal/domain/curator/contract.go +++ b/internal/domain/curator/contract.go @@ -1,13 +1,5 @@ -// Package curator is the curator engine family: long-running agent loops -// that reason over memory and perform small maintenance tasks, rather than -// one hardcoded background job.. -// -// A curator is defined by a declared shape (check-in interval, tool set, -// attached memory engine), runs persistently while there is input, and backs -// off to a cooldown when idle. The family follows the strict plugin engine -// rule: a typed contract (CuratorEngine), an owning registry (Registry) with -// start/health/stop and shutdown ordering, and narrow typed host access -// (Registrar) — a curator never receives the daemon or an untyped hook map. +// Package curator runs curators: long-running agent loops that maintain +// memory, each with a declared interval, tool set and memory engine. package curator import ( diff --git a/internal/domain/curator/definition.go b/internal/domain/curator/definition.go index 1ed78e4a9..486a28a0a 100644 --- a/internal/domain/curator/definition.go +++ b/internal/domain/curator/definition.go @@ -1,10 +1,6 @@ package curator -// Definition is a curator definition as data: the declared Manifest plus -// the identity, lifecycle flag, and free-form instructions the manifest -// cannot express. One generic engine (DefinitionEngine) interprets any -// definition -- there is deliberately no catalogue of curator "types" and -// no second authority beside the existing registry. +// Definition is a curator defined as data, run by DefinitionEngine. type Definition struct { // Name is the registry key. Name string diff --git a/internal/domain/curator/registrar.go b/internal/domain/curator/registrar.go index 442d7bfe7..932b989cd 100644 --- a/internal/domain/curator/registrar.go +++ b/internal/domain/curator/registrar.go @@ -9,11 +9,8 @@ import ( "github.com/samcharles93/archie-core/internal/tools" ) -// Registrar is the narrow typed host access a curator receives at -// registration. Only the services the curator's declared shape requires are -// ever populated in the view the registry binds (see Registry.filter); the -// daemon itself is never part of it. Fields are typed contracts declared -// here — this package never names who implements them. +// Registrar is the host access a curator receives, limited to what its +// manifest declares. type Registrar struct { // Log is the curator-scoped diagnostic logger. It is optional so domain // tests and embedders can construct a registrar without a logging sink. @@ -32,14 +29,8 @@ type Registrar struct { // Skills is the skill-maintenance capability. Bound when the curator // declares Skills. Skills SkillStore - // MemoryEngines resolves a named memory engine, for a curator that - // declared Manifest.MemoryEngine. Bound - // only when declared. Like Tools, resolution is by name at call time, - // not a value pre-fetched at Bind: a curator calls - // MemoryEngines.Get(its own Manifest().MemoryEngine), the same trust - // model ToolBuilder.Build(ctx, declared) already uses -- the caller is - // trusted to pass its own declared identifier, not handed a - // pre-scoped instance. + // MemoryEngines resolves a memory engine by name. Bound only when the + // manifest declares one. MemoryEngines MemoryEngineSource // Conversations is read-only recent conversation history, for a curator // that declared Manifest.Conversations. Bound only when declared. @@ -155,11 +146,7 @@ type SessionSummary struct { type ConversationMessage struct { Role string // "user" or "assistant" Content string - // SenderID is the channel-native stable identifier of the party that - // sent the message (see messaging.Message.SenderID). Empty for an - // assistant message, and for a channel that carries no per-sender - // identity. A curator derives a session's participant from the - // user-role messages that carry one. + // SenderID is the sender's channel-native ID, empty for assistant messages. SenderID string At time.Time } diff --git a/internal/domain/curator/registry.go b/internal/domain/curator/registry.go index 5d25ca087..7e495f0ff 100644 --- a/internal/domain/curator/registry.go +++ b/internal/domain/curator/registry.go @@ -32,11 +32,8 @@ type curatorStatus struct { startErr error } -// Registry is the curator family owner: it controls registration and -// discovery, lifecycle (start/health/stop), shutdown ordering, and failure -// isolation. A curator failure — a rejected registration, a failing Start, a -// blocking Stop, even a panicking Bind — affects only that curator and is -// reported, never fatal to the daemon or to other curators. +// Registry owns curator registration and lifecycle. A curator's failure +// affects only that curator. type Registry struct { mu sync.Mutex host Registrar @@ -66,11 +63,7 @@ func NewRegistry(host Registrar) *Registry { } } -// RecordActivity records one pass's outcome for the named curator so it is -// inspectable at runtime: last run time, action count, and recent actions -// with their reasons. Called by the runtime at the same point it emits the -// curator_run/curator_action events (Runtime.emitRun), so the two views -// never disagree. +// RecordActivity records one pass's outcome for the named curator. func (r *Registry) RecordActivity(name string, at time.Time, actions []Action) { r.activity.record(name, at, actions) } @@ -81,11 +74,8 @@ func (r *Registry) Activity(name string) (Activity, bool) { return r.activity.snapshot(name) } -// Register validates the curator's declared shape against the registrar and -// adds it, binding the curator to a host view filtered to its declared -// capabilities. Registration fails on nil engines, invalid manifests, -// duplicate names, a declared capability with no host service behind it, or -// a panicking Bind — and a failure affects only that curator. +// Register validates the curator's manifest and binds it to a filtered host +// view. Failures affect only that curator. func (r *Registry) Register(c CuratorEngine) error { if isNilEngine(c) { return errors.New("curator: nil engine") @@ -271,11 +261,8 @@ func healthSafely(ctx context.Context, c CuratorEngine) (h Health) { return c.Health(ctx) } -// Stop stops every started curator in reverse registration order. Curators -// whose Start failed are skipped; the call is bounded by ctx — a curator -// that ignores cancellation cannot hang the daemon's shutdown beyond the -// caller's deadline, and its error is joined into the result. Stopping a -// registry that never started is a no-op. +// Stop stops started curators in reverse order, bounded by ctx, and joins +// their errors. func (r *Registry) Stop(ctx context.Context) error { r.mu.Lock() if r.state == stateIdle || r.state == stateStopped { diff --git a/internal/domain/curator/runtime.go b/internal/domain/curator/runtime.go index 1f3bc8c69..96a574b9d 100644 --- a/internal/domain/curator/runtime.go +++ b/internal/domain/curator/runtime.go @@ -32,16 +32,8 @@ type RuntimeConfig struct { MaxConcurrentPasses int } -// Runtime runs the registered curators' loops: one goroutine per curator, -// timing driven by the registry's clock (fake-clock testable), waking on -// best-effort nudges (the trigger decision belongs to the curator's Check), -// with per-pass timeouts, panic recovery, and bounded shutdown. -// -// Curators are peers, never dependencies: nothing a curator does — a -// blocking pass, a panic, a burst of nudges — can block a chat turn, an -// agent run, or the daemon. Wake events are accelerations; the trigger is a -// deterministic state read at pass time, so a dropped -// nudge only delays a run to the next check-in. +// Runtime runs one loop per registered curator, with per-pass timeouts and +// panic recovery. Wake events are best-effort. type Runtime struct { registry *Registry cfg RuntimeConfig @@ -127,11 +119,8 @@ func (rt *Runtime) Nudge(curator string) { } } -// Stop cancels every loop, waits for in-flight passes to unwind (bounded by -// ctx), then stops the curators' lifecycle in reverse registration order. -// A pass that ignores cancellation cannot hang shutdown beyond ctx: Stop -// returns ctx.Err once the deadline passes. Stopping a runtime that never -// started is a no-op. +// Stop cancels every loop, waits for passes to finish within ctx, then stops +// the curators in reverse order. func (rt *Runtime) Stop(ctx context.Context) error { rt.mu.Lock() if !rt.started { diff --git a/internal/domain/curator/wake.go b/internal/domain/curator/wake.go index 1638fcfbd..0f322f213 100644 --- a/internal/domain/curator/wake.go +++ b/internal/domain/curator/wake.go @@ -7,15 +7,8 @@ import ( "github.com/samcharles93/archie-core/internal/events" ) -// WakeOnPrimaryInput forwards primary-input events from the in-process bus -// to the runtime as best-effort nudges. Only the kinds in -// inputKinds wake curators — the trigger-accounting invariant: curator- -// produced activity (curator_run, curator_action, curator_error, and any -// future derived-write kind) never appears on this path, so a curator's own -// output cannot feed its own trigger. The subscription is bounded and the -// bus drops on overflow, so a slow curator can never backpressure the chat -// publisher; a dropped event only delays a run to the next check-in. The -// forwarder runs until ctx is cancelled or the bus closes. +// WakeOnPrimaryInput nudges the runtime for each bus event of inputKinds +// until ctx ends or the bus closes. Dropped events only delay a run. func WakeOnPrimaryInput(ctx context.Context, bus *events.Bus, rt *Runtime, inputKinds ...string) { sub := bus.Subscribe(defaultWakeBuffer) go func() { diff --git a/internal/domain/drain/drain.go b/internal/domain/drain/drain.go index 412ad1fad..56fac1a20 100644 --- a/internal/domain/drain/drain.go +++ b/internal/domain/drain/drain.go @@ -1,24 +1,9 @@ -// Package drain owns the decision logic for external drain requests. -// -// A drain is an operator-initiated request for the daemon to stop accepting -// new work and shut itself down gracefully. It arrives out-of-band through a -// marker file (an external trigger such as a maintenance window or a rolling -// deploy writes it) rather than a signal, because a marker survives the phase -// in which the process is between restarts and can be validated against the -// *current* instantiation. -// -// The single source of confusion this package rules out is the stale marker: a -// drain request written before the daemon last restarted must never drain the -// daemon that came up afterwards. That is handled by pairing each marker with -// an instantiation epoch (the OS boot id plus PID 1's start time) and only -// honouring a marker whose epoch matches the current one. +// Package drain decides whether a drain marker file applies to the running +// daemon. A marker is honoured only when its epoch matches the current one. package drain -// Epoch identifies one instantiation of the daemon's process tree. It -// combines the OS boot id with PID 1's start time (in clock ticks since -// boot). Two Epochs are equal only when both parts match, so a marker written -// before a reboot or before a PID 1 restart within the same boot is never -// mistaken for one written against the current instantiation. +// Epoch identifies one boot of the process tree: the OS boot id and PID 1's +// start time. type Epoch struct { // BootID is the content of /proc/sys/kernel/random/boot_id, a UUID that // changes on every boot. @@ -83,13 +68,8 @@ func (d Decision) String() string { } } -// Decide returns the drain decision for marker against current. -// -// A nil marker means no request (DecisionNone). An empty current epoch means -// the OS identity facts could not be established, so the request is treated as -// stale -- a daemon that cannot prove the marker is live must not shut itself -// down on it. Only a marker whose epoch exactly matches a non-empty current -// epoch is honoured. +// Decide returns the decision for marker. Nil means none; an empty current +// epoch or a mismatched marker is stale. func Decide(current Epoch, marker *Marker) Decision { if marker == nil { return DecisionNone diff --git a/internal/domain/eda/expr/expr.go b/internal/domain/eda/expr/expr.go index efa1e7334..2c2366742 100644 --- a/internal/domain/eda/expr/expr.go +++ b/internal/domain/eda/expr/expr.go @@ -1,21 +1,5 @@ -// Package expr is the CEL expression environment for the EDA playbook engine: -// one mechanism for both an action's `when` condition and its `args` values, -// per eda-playbook-engine.md's resolved open question 1 (CEL decision). -// -// The environment declares two context roots -- `event` (the triggering -// event's decoded payload, kept dyn by J4) and `actions` (prior actions' -// results keyed by the action's declared id) -- and applies a cost limit to -// every program. `actions` is not a global map: its shape depends on the ids -// one playbook declares and the kind each id runs, so NewEnv takes the -// declared ids and their Go Result struct types and builds a per-playbook -// object type (multi-action-playbooks.md, D3). The playbook loader compiles -// every `when` and `args` value here, so load-time rejection and runtime -// evaluation cannot disagree; the standalone lint command covers the flat -// kind/label binding files, not rich EDA playbook documents. -// -// CEL is non-Turing-complete, side-effect-free, and panic-free by design. -// Anything the schema does not accept is a returned error here -- the -// reject-at-load philosophy of the parent design doc. +// Package expr is the CEL environment for EDA playbook `when` and `args` +// expressions, with an `event` root and a per-playbook typed `actions` root. package expr import ( @@ -33,12 +17,8 @@ import ( // resolved doc: tunable, start here; linter and daemon share the same value). const DefaultCostLimit = 100_000 -// DeclaredResult is one prior action's result the environment exposes to a -// later expression. ID is the action's declared id, read as -// `actions..result.`; Type is the reflect.Type of that action -// kind's Go Result struct. `module.ModuleRegistry.DecodeResult` is the site -// that converts Invoke's flat result map back into this struct before a later -// expression reads it. +// DeclaredResult is a prior action's id and Result type, read as +// actions..result.. type DeclaredResult struct { ID string Type reflect.Type @@ -49,14 +29,7 @@ type DeclaredResult struct { // its fields are never read. type probeResult struct{} -// IsCELFieldName reports whether id can be written as `actions.` in a CEL -// expression. It is the authoritative check the playbook loader uses for a -// module action id, replacing a regex approximation of CEL's token rules: it -// compiles a probe expression against a one-field environment declaring the -// id, so the CEL parser and checker decide. CEL keywords (`in`, `true`, -// `false`, `null`) and any other spelling with no field-selection form return -// false; a valid CEL identifier such as `Build` returns true (the loader adds -// its own lowercase policy on top). +// IsCELFieldName reports whether id can be written as actions. in CEL. func IsCELFieldName(id string) bool { if id == "" { return false @@ -76,17 +49,9 @@ type Env struct { // Context is what an expression may read at dispatch time. Both roots are // read-only from the expression's perspective; CEL enforces this. type Context struct { - // Event is the triggering event's decoded payload (webhook body, forge - // issue, schedule tick). Declared dyn because its shape is unknown by - // design (schema-by-example); field-level typing is follow-up work once - // multi-action playbooks exist (per-kind generated Result structs - // declared as CEL types). + // Event is the triggering event's payload, typed dyn. Event map[string]any - // Actions holds prior actions' results keyed by the action's id as - // declared in the playbook. Each id maps to the per-id wrapper - // `{"result": }` built by - // `module.ModuleRegistry.DecodeResult`, so a later expression reads - // `actions..result.`. + // Actions holds prior actions' results by id as {"result": }. Actions map[string]map[string]any } @@ -118,11 +83,8 @@ func NewEnv(declared ...DeclaredResult) *Env { return &Env{celEnv: celEnv, costLimit: DefaultCostLimit} } -// newResultRegistry registers every declared Result reflect.Type with CEL's -// native type system, using lower-cased Go field names so `Written` is read -// as `written`. The registry is both the provider (for the Result struct -// fields) and the adapter (so a Go Result struct value inside the eval map -// adapts to those same fields). +// newResultRegistry registers the declared Result types with lower-cased +// field names. func newResultRegistry(declared []DeclaredResult) (*types.Registry, error) { items := make([]any, 0, len(declared)+1) items = append(items, types.ParseStructField(lowerFieldName)) @@ -138,11 +100,7 @@ func lowerFieldName(f reflect.StructField) string { return strings.ToLower(f.Name) } -// nativeResultTypeName is the CEL type name cel-go's native type system -// assigns to a reflect.Type (simple package alias + struct name), e.g. -// `log.Result`. It must match the name the native registry registers, because -// the per-id wrapper's `result` field is typed by that name and its fields -// are resolved through the native registry. +// nativeResultTypeName returns the CEL name for a Go type, e.g. log.Result. func nativeResultTypeName(t reflect.Type) string { if t.Kind() == reflect.Pointer { t = t.Elem() @@ -154,11 +112,7 @@ func nativeResultTypeName(t reflect.Type) string { return pkg + "." + t.Name() } -// The `actions` root object type name and the per-id wrapper type namespace. -// Per-id names must live in a reserved namespace (eda.action.): naming a -// wrapper `actions.` makes the checker parse `actions.` as a type -// reference rather than a field selection, which then fails with "type ... -// does not support field selection". +// Type names for the actions root and per-id wrappers. const ( actionsTypeName = "actions" actionTypePrefix = "eda.action." @@ -261,11 +215,8 @@ func (p *actionResultProvider) NewValue(structType string, fields map[string]ref return p.base.NewValue(structType, fields) } -// Compile parses and type-checks a playbook expression string against the -// declared context. A syntax error, an unknown root (anything other than -// event/actions), a dynamic `actions` read, or a field typo on a declared -// result is a returned error -- never a panic. The returned Program is safe -// to evaluate concurrently (CEL programs are stateless once compiled). +// Compile parses and type-checks an expression. Programs are safe for +// concurrent use. func (e *Env) Compile(src string) (*Program, error) { ast, issues := e.celEnv.Compile(src) if issues != nil && issues.Err() != nil { @@ -279,21 +230,8 @@ func (e *Env) Compile(src string) (*Program, error) { return &Program{prg: prg, actionIDs: ids, resolvable: resolvable, outType: ast.OutputType()}, nil } -// actionReferences walks the checked AST once and classifies every read of -// the `actions` context root as either a statically-resolvable action id or -// not. A root read is an identifier the checker typed as the `actions` -// object: matching on type rather than name keeps a comprehension variable -// that happens to be called `actions` out of the count. Each root read -// consumes exactly one such identifier, so -// -// resolvable = (identCount == staticCount) -// -// where staticCount is the root reads that are a field selection. The -// checker already rejects every other non-static read (a dynamic index, -// `in`, `size`, an undeclared id); the spelling it accepts is a bare -// `actions` value, which compiles but cannot be pinned to an action id at -// load. This walk exists to reject that spelling; the ids return is -// informational. The ids are sorted and de-duplicated. +// actionReferences returns the sorted action ids the expression reads and +// whether every read of `actions` is a field selection. func actionReferences(ast *cel.Ast) ([]string, bool) { if ast == nil || ast.NativeRep() == nil { return nil, true @@ -368,15 +306,8 @@ func celScalar(t reflect.Type) (*cel.Type, bool) { } } -// ActionReferences reports the action ids the expression reads from the -// `actions` context root (sorted, de-duplicated) and whether every `actions` -// read could be statically resolved to one of those ids. ids is empty when -// the expression reads no prior-action result; resolvable is false when the -// expression reads `actions` in any form that cannot be pinned to a prior -// action id at load. Under the per-playbook object type the checker already -// rejects every dynamic `actions` read, so the only form that still reaches -// here unresolved is a bare `actions` value read; the playbook loader rejects -// that rather than evaluating it as a runtime miss. +// ActionReferences returns the action ids the expression reads and whether +// each `actions` read resolves to an id. func (p *Program) ActionReferences() (ids []string, resolvable bool) { if p == nil { return nil, true @@ -384,12 +315,7 @@ func (p *Program) ActionReferences() (ids []string, resolvable bool) { return p.actionIDs, p.resolvable } -// Eval evaluates the program against a dispatch-time context. A missing -// field, a wrong type against a dyn value, or an exceeded cost limit is a -// returned error. CEL's own evaluation recovers panics internally (verified -// in cel-go's program.go: Eval wraps evaluation in recover), and its -// returned values implement ref.Val -- unwrapped here to the native Go value -// the caller expects. +// Eval evaluates the program and returns the native Go value. func (e *Env) Eval(prg *Program, ctx Context) (any, error) { data := map[string]any{ "event": ctx.Event, diff --git a/internal/domain/eda/module/log/log.go b/internal/domain/eda/module/log/log.go index 38c4dff57..2f4c9fcf4 100644 --- a/internal/domain/eda/module/log/log.go +++ b/internal/domain/eda/module/log/log.go @@ -1,11 +1,4 @@ -// Package log is the schema source for the "log" Module action kind -- the -// side-effect-free proof-of-concept kind for the Module position. A Yaegi -// module implementing this kind exports a fixed function name against these -// generated types; the operator's file is the implementation, this package is -// the contract. -// -// This is the hand-written schema. logextract (generated by `go generate`) -// turns it into the Yaegi symbol table the interpreter uses. +// Package log defines the "log" module kind's Args and Result. package log // SchemaVersion is independent of a playbook's own workflow_version, per diff --git a/internal/domain/eda/module/module.go b/internal/domain/eda/module/module.go index 2257a3d55..d71d6d7f6 100644 --- a/internal/domain/eda/module/module.go +++ b/internal/domain/eda/module/module.go @@ -1,15 +1,5 @@ -// Package module is the Module position of the EDA playbook engine: operator- -// installed, in-process, daemon-privileged action implementations, interpreted -// via Yaegi (same trust tier as PluginDir and SecretEngineDir -- NOT -// repository-supplied task code). -// -// Each module kind has a fixed signature and generated symbol table: load the -// installed source, resolve its typed entrypoint, then call it through the -// panic-safe interpreter boundary. -// -// Each action kind is its own tiny package with its own generated contract -// (internal/domain/eda/module/), and the registry's internal storage is -// the only place type erasure appears. +// Package module loads and invokes EDA module actions, Yaegi-interpreted Go +// files with a fixed entrypoint per kind. package module import ( @@ -90,12 +80,7 @@ func (r *ModuleRegistry) Len() int { return len(r.kinds) } -// KindSchema reports the hand-written Args and Result struct types for a -// known kind. A kind is known when it has a registered contract in this -// package's built-in registry (the log kind is the shipped kind), independent -// of whether a module instance is currently loaded from a module directory. -// It is the narrow schema source the playbook loader consumes to type-check -// an action playbook's args and result references at load. +// KindSchema returns a known kind's Args and Result types. func (r *ModuleRegistry) KindSchema(kind string) (reflect.Type, reflect.Type, bool) { k, ok := registry[kind] if !ok { @@ -104,11 +89,7 @@ func (r *ModuleRegistry) KindSchema(kind string) (reflect.Type, reflect.Type, bo return k.argsType, k.resultType, true } -// Register discovers /.go, interprets it against the kind's -// generated symbols, resolves its fixed export, and stores the invoker. -// A missing file, an unreadable file, a resolve failure, or an unknown kind -// is a reported error -- the daemon aborts startup on a broken module -// directory per the established routing-file pattern. +// Register loads /.go and resolves its entrypoint. func (r *ModuleRegistry) Register(kind, dir string) error { k, ok := registry[kind] if !ok { @@ -211,11 +192,7 @@ func decodeLogArgs(rawArgs map[string]any) (log.Args, error) { return args, nil } -// Invoke calls the registered kind with rawArgs and returns the marshaled -// result. An unregistered kind is a reported error. Invoke is deliberately -// schema-agnostic: it returns the flat map[string]any the kind produces and -// does not re-apply the Result schema. DecodeResult is the single conversion -// site that re-applies it for the typed CEL environment. +// Invoke calls kind with rawArgs and returns its result map. func (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]any, error) { inv, ok := r.kinds[kind] if !ok { @@ -228,14 +205,8 @@ func (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[st return res, nil } -// DecodeResult converts Invoke's flat result map into the kind's registered -// Result struct. Invoke stays schema-agnostic and returns map[string]any; this -// method is the one place the Result schema is re-applied so the value a later -// CEL expression reads is the same Go struct the expression environment typed -// (`actions..result.`). The map is keyed by the lower-cased Go -// field name, the same spelling expr registers as the CEL field name. An -// unknown field, an absent declared field, or a value that is not already the -// field's type is a reported error. +// DecodeResult converts Invoke's result map into the kind's Result struct. +// Unknown, missing or mistyped fields are errors. func (r *ModuleRegistry) DecodeResult(kind string, raw map[string]any) (any, error) { k, ok := registry[kind] if !ok { @@ -244,13 +215,8 @@ func (r *ModuleRegistry) DecodeResult(kind string, raw map[string]any) (any, err return decodeResultStruct(kind, k.resultType, raw) } -// decodeResultStruct marshals raw into a new value of the kind's Result -// struct type, keyed by the lower-cased Go field name -- the same spelling -// expr registers as the CEL field name. Every declared field must be present -// and every value must already carry that field's type: a missing field would -// read as the zero value, and a conversion would change the value's -// representation, so both are reported rather than becoming a quietly wrong -// value in a later expression. +// decodeResultStruct builds a Result value from raw. Every field must be +// present with the exact type. func decodeResultStruct(kind string, t reflect.Type, raw map[string]any) (any, error) { if t == nil { return nil, fmt.Errorf("module %s: result schema is not set", kind) diff --git a/internal/domain/embedding/contract.go b/internal/domain/embedding/contract.go index 66adc5920..3e7ceaf60 100644 --- a/internal/domain/embedding/contract.go +++ b/internal/domain/embedding/contract.go @@ -1,12 +1,4 @@ -// Package embedding is the embedding capability: a narrow typed boundary for -// turning text into vectors, so consumers never depend on a specific provider -// SDK. -// -// Unlike curator and memory (internal/domain/curator, internal/domain/ -// memory), a Client has no Lifecycle: it is call-scoped, not long-running, -// the same reasoning internal/domain/image's Provider contract already -// uses -- "is this usable right now" is exactly what Embed returning -// ErrUnavailable already communicates. +// Package embedding defines the text embedding contract. package embedding import ( @@ -17,12 +9,8 @@ import ( // Sentinel errors every implementation wraps with fmt.Errorf("%w: ...", ...) // so callers can errors.Is regardless of backend. var ( - // ErrUnavailable means the capability cannot serve right now: no role - // is configured, the provider is unknown, or its credential could not - // be resolved. Per the credential-missing-degrades-not-fatal rule - // (AGENTS.md), this must never prevent the daemon from starting or - // fail an unrelated chat turn -- a caller must degrade (skip the - // content, fall back to free exploration) instead. + // ErrUnavailable means embedding is not configured or cannot run; callers + // degrade. ErrUnavailable = errors.New("embedding capability unavailable") // ErrEmptyInput means Embed was called with no texts. ErrEmptyInput = errors.New("embedding request has no input text") @@ -33,11 +21,6 @@ type Vector []float32 // Client is the narrow typed contract every embedding backend implements. type Client interface { - // Embed returns one Vector per entry in texts, in the same order. - // Network calls must carry a timeout; a failure is returned as an - // error, never a panic. Callers must treat any non-nil error as - // "skip this batch," matching image.Provider's ErrUnavailable - // convention -- an embedding failure must never crash or fail an - // unrelated caller. + // Embed returns one Vector per text, in order. Embed(ctx context.Context, texts []string) ([]Vector, error) } diff --git a/internal/domain/eventtype/eventtype.go b/internal/domain/eventtype/eventtype.go index 9d6a81cb2..155b12786 100644 --- a/internal/domain/eventtype/eventtype.go +++ b/internal/domain/eventtype/eventtype.go @@ -1,9 +1,6 @@ -// Package eventtype owns event types: named kinds of event from one source, -// each defined by a match rule over headers and payload. It infers a structural -// signature per capture, groups a source's captures into proposed types, -// evaluates rules, and refuses two types on one source whose rules can match -// the same event. An event that matches no type is unidentified and is never -// dispatched. +// Package eventtype defines event types: match rules over a source's headers +// and payload. It infers signatures, proposes types and refuses overlapping +// types on one source. package eventtype import ( @@ -134,11 +131,9 @@ func payloadHolds(root any, p PayloadCondition) bool { return false } -// Overlaps reports whether some event could satisfy both rules. Two rules are -// disjoint only when they demand different values of one header, or different -// values at one payload path outside any array; anything else is treated as -// overlapping, which errs towards refusing a save rather than towards an event -// two types both claim. +// Overlaps reports whether an event could satisfy both rules. Rules are +// disjoint only when they require different values for one header or a +// non-array payload path. func Overlaps(a, b Rule) bool { for _, ha := range a.Headers { for _, hb := range b.Headers { diff --git a/internal/domain/eventtype/propose.go b/internal/domain/eventtype/propose.go index 29dd32ec5..4153fecf4 100644 --- a/internal/domain/eventtype/propose.go +++ b/internal/domain/eventtype/propose.go @@ -68,11 +68,8 @@ func Propose(captures []Capture) []Proposal { return out } -// separatingRule demands the group's discriminator headers, then, for each -// sibling those do not already rule out, the presence of the first path the -// group has and the sibling lacks. A group whose paths are a subset of a -// sibling's cannot be separated by presence alone; saving it as proposed is -// then refused as an overlap, and the operator edits the rule. +// separatingRule requires the group's discriminator headers, plus a path +// present in the group but absent from each remaining sibling. func separatingRule(g Signature, siblings []Signature) Rule { rule := Rule{Headers: headerConditions(g.Headers)} paths := slices.Sorted(maps.Keys(g.Paths)) diff --git a/internal/domain/harnesssecret/harnesssecret.go b/internal/domain/harnesssecret/harnesssecret.go index f3166f41b..79be1b14b 100644 --- a/internal/domain/harnesssecret/harnesssecret.go +++ b/internal/domain/harnesssecret/harnesssecret.go @@ -1,8 +1,5 @@ -// Package harnesssecret is the OAuth token set a credential binding's service -// holds for one org. The setup terminal writes the first capture; the egress -// proxy overwrites it on every token refresh. It is never a Kit-declared value -// and never resolved through the config secret registry the way an API-key -// binding's SecretRef is -- it is state archie itself captures and mutates. +// Package harnesssecret defines a credential binding's OAuth token set for +// one org. package harnesssecret import ( diff --git a/internal/domain/health/health.go b/internal/domain/health/health.go index 97b877b8e..5b1b7674a 100644 --- a/internal/domain/health/health.go +++ b/internal/domain/health/health.go @@ -1,18 +1,5 @@ -// Package health is the readiness-probe contract for archie's operator -// surfaces. It defines the probe shape (Name + Check), the resulting -// Status vocabulary, and a Registry that runs a fixed set of probes and -// aggregates their results into one report. -// -// Concrete probe implementations live in internal/infrastructure/health; -// composition root wiring lives in internal/app/archied. This package owns -// only the contract and the aggregation rule, so a new subsystem probe never -// has to touch the HTTP surface or the composition root. -// -// The vocabulary is deliberately tiny: a probe is either `ok` (ready for -// work) or `degraded` (not ready -- failed, or a required subsystem report it -// cannot serve). There is no "unknown"; a probe that cannot run must say so -// loudly by reporting degraded, because a readiness consumer treats anything -// other than `ok` as a reason to stop routing work. +// Package health defines readiness probes and aggregates their results. A +// probe is ok or degraded. package health import "context" diff --git a/internal/domain/identity/credential.go b/internal/domain/identity/credential.go index 2576292cd..bfdbc7bfc 100644 --- a/internal/domain/identity/credential.go +++ b/internal/domain/identity/credential.go @@ -62,11 +62,7 @@ type LoginFlow interface { Exchange(ctx context.Context, code, codeVerifier string) (ProviderSession, error) } -// SubjectResolver resolves a verified provider subject to the identity bound to -// it. It is deliberately narrower than Repository: authenticating a request -// needs to resolve a subject, not to administer identities, so a consumer that -// only authenticates does not take a dependency on the whole identity CRUD -// surface. +// SubjectResolver resolves a provider subject to its bound identity. type SubjectResolver interface { // ResolveSubject returns the identity a provider subject is bound to. It is // the second binding beside the legacy-name alias: a name archie was @@ -101,11 +97,7 @@ var ( ErrIdentityInactive = errors.New("identity may not act") ) -// Authenticate resolves a presented credential to the identity that may act. -// -// The order is deliberate: the credential is verified by the provider's own -// keys before anything it contains is used, so no field of an unverified token -// can select an identity. +// Authenticate verifies rawToken, then resolves it to an identity. func Authenticate(ctx context.Context, subjects SubjectResolver, verifier Verifier, rawToken string) (Identity, Credential, error) { if strings.TrimSpace(rawToken) == "" { return Identity{}, Credential{}, ErrNoCredential @@ -124,14 +116,8 @@ func Authenticate(ctx context.Context, subjects SubjectResolver, verifier Verifi return value, credential, nil } -// Resolve turns an already-verified credential into the identity that may act. -// -// It is the single place the binding and lifecycle rules are applied, so a path -// that verified a credential itself -- the login callback exchanging an -// authorization code -- cannot reach a different verdict from the path that -// verified a presented token. A suspended identity is refused here even though -// its credential verified, because suspension is archie's decision and must not -// depend on the provider withdrawing a token. +// Resolve maps a verified credential to its identity, refusing suspended +// identities. func Resolve(ctx context.Context, subjects SubjectResolver, credential Credential) (Identity, error) { if err := credential.Subject.Validate(); err != nil { return Identity{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) diff --git a/internal/domain/identity/identity.go b/internal/domain/identity/identity.go index 5dd89b0ed..c766d3751 100644 --- a/internal/domain/identity/identity.go +++ b/internal/domain/identity/identity.go @@ -95,21 +95,12 @@ func New(id IdentityID, kind Kind, displayName string) (Identity, error) { return value, nil } -// FromLegacyName builds the bot identity a configured name denotes -- the -// identity a [[identities]] entry, or the single bot_user, seeds. It is the -// one place a configuration name becomes an identity, so the file path that -// seeds and the store path that creates cannot disagree: both derive through -// New, and therefore through ValidDisplayName. +// FromLegacyName builds the bot identity for a configured name. func FromLegacyName(legacyName string) (Identity, error) { return New(StableID(legacyName), KindBot, legacyName) } -// ValidDisplayName reports whether name can be an identity display name: the -// non-empty-after-trimming rule Validate applies. A configuration loader that -// seeds an identity from a name calls this so the values it accepts and the -// values the store accepts are the same set, rather than two rules on one -// string (a whitespace-only name passed the loader's empty-string test and -// then failed here). +// ValidDisplayName reports whether name is non-empty after trimming. func ValidDisplayName(name string) bool { return strings.TrimSpace(name) != "" } func (i Identity) Validate() error { diff --git a/internal/domain/image/contract.go b/internal/domain/image/contract.go index 69e9a8499..6525f7b51 100644 --- a/internal/domain/image/contract.go +++ b/internal/domain/image/contract.go @@ -1,13 +1,4 @@ -// Package image is the image generation capability family: a provider-neutral -// boundary for hosted (gpt-image-2-class) and local GPU backends, so /image -// routing can target either without depending on provider-specific types. -// -// Unlike curator and memory (internal/domain/curator, -// internal/domain/memory), a Provider has no Lifecycle: it is call-scoped, -// not long-running. There is nothing to Start, and "is this usable right -// now" is exactly what Generate/Edit returning ErrUnavailable already -// communicates — a separate Health poll would duplicate that. This package -// defines the contract only; no provider implementation lives here. +// Package image defines the image generation provider contract. package image import ( diff --git a/internal/domain/mapping/mapping.go b/internal/domain/mapping/mapping.go index e108ee4c7..287b473c0 100644 --- a/internal/domain/mapping/mapping.go +++ b/internal/domain/mapping/mapping.go @@ -150,12 +150,8 @@ func Resolve(fields []Field, payload []byte) (values map[string]any, failures [] return values, failures } -// pathSegment is a map key (Key set, Index == -1), an array index -// (Index >= 0, Key empty), or Invalid -- a bracket segment whose contents -// were not a plain non-negative integer (e.g. "items[abc]"). walk always -// fails an Invalid segment rather than silently dropping it and matching a -// shorter, unintended path -- a malformed path must read as ReasonMissing, -// never as a different path succeeding by accident. +// pathSegment is a map key, an array index, or Invalid. walk always fails on +// Invalid. type pathSegment struct { Key string Index int diff --git a/internal/domain/memory/contract.go b/internal/domain/memory/contract.go index 117c6c3d0..0fc821832 100644 --- a/internal/domain/memory/contract.go +++ b/internal/domain/memory/contract.go @@ -1,21 +1,5 @@ -// Package memory is the memory engine family: the authoritative store for -// durable observations, addressed by typed scope. -// -// One engine, four scopes. A caller names the scopes it may read or write -// (Scope, Subject) and the engine applies no policy of its own: an engine -// that enforced access would need to know about channels, sessions and -// bindings, and every backend would reimplement it. Isolation then falls out -// mechanically, because ScopeAgent{a} and ScopeAgent{b} are different -// storage keys. -// -// The family follows the strict plugin engine rule: a typed contract -// (MemoryEngine) with real domain operations (create, read, update, delete, -// revisions — not just Name/Version), an owning registry (Registry) with -// start/health/stop and shutdown ordering, and narrow typed host access -// (Registrar) — an engine never receives the daemon or an untyped hook map. -// -// This package owns the contract and the family's policy that is independent of -// any backend (the content scanner). +// Package memory defines the memory engine contract: durable records in +// typed scopes, plus the content scanner. Engines apply no access policy. package memory import ( @@ -82,11 +66,7 @@ const ( ScopeAgentUser ScopeKind = "agent-user" ) -// AgentID and IdentityID are opaque. This package never resolves them, -// canonicalises them, or invents one from a channel: resolution happens -// where the channel's native identity is in hand (the gateway turn path), -// because a channel's sender id is not necessarily a person -- treating one -// as a person would give a URL an identity. +// AgentID and IdentityID are opaque. type ( AgentID string IdentityID string @@ -133,14 +113,8 @@ func (s Scope) Validate() error { return nil } -// Key returns the scope's canonical storage key. Each component is -// length-prefixed, so two different scopes can never share a key even when -// an id embeds the separator byte — which matters because AgentID and -// IdentityID are opaque and come from channels this package does not -// control. -// -// An invalid scope returns "", which a storage key can never legitimately -// be: callers must Validate first. Every engine path does. +// Key returns the scope's length-prefixed storage key, or "" for an invalid +// scope. func (s Scope) Key() string { switch s.Kind { case ScopeGlobal: @@ -179,12 +153,8 @@ type Subject struct { UserID IdentityID } -// Scopes returns the scopes a read for this subject names, narrowest first: -// agent-user, agent, user, then global last, because global is the only -// scope every subject shares. -// -// The read path hands exactly this set to the engine and the engine unions -// nothing beyond it. +// Scopes returns the subject's readable scopes, narrowest first: agent-user, +// agent, user, global. func (s Subject) Scopes() []Scope { return append(s.WritableScopes(), Scope{Kind: ScopeGlobal}) } @@ -206,13 +176,8 @@ func (s Subject) WritableScopes() []Scope { return scopes } -// Store is the real domain operations every memory backend implements. -// Split out from MemoryEngine so the two concerns (storage vs. -// identity/lifecycle) stay separately named and independently testable. -// -// Every method that touches one record takes the record's Scope: a record id -// alone does not locate a scope, and an engine that had to search for one -// would be reimplementing the caller's addressing. +// Store is a memory backend's record operations. Each takes the record's +// Scope. type Store interface { // Create records one new memory and returns the stored Record, // including the identifier Get/Update/Forget/Revisions later need. diff --git a/internal/domain/memory/registrar.go b/internal/domain/memory/registrar.go index e835d2699..62f054657 100644 --- a/internal/domain/memory/registrar.go +++ b/internal/domain/memory/registrar.go @@ -10,21 +10,12 @@ import ( // never names who implements them, and the daemon itself is never part of // it. type Registrar struct { - // Events publishes engine activity (writes, forgets, failures) for - // observability. Implementations must be non-blocking and bounded (drop - // on overflow), matching the curator family's EventSink contract, so an - // engine can never apply backpressure to a chat turn or the daemon. - // Always bound. + // Events receives engine activity. Must not block. Events EventSink // Clock is injectable time. Always bound; nil at construction is // replaced with the system clock. Clock Clock - // Log is the engine-scoped diagnostic logger, optional so domain tests - // and embedders can construct a registrar without a logging sink (the - // curator family's Registrar carries the same field for the same - // reason). An engine emits here what it cannot emit as an event: the - // content scanner's warn level, which allows the write and is expected - // to leave a record of what it saw. + // Log is the engine's logger. Optional. Log *slog.Logger } diff --git a/internal/domain/memory/registry.go b/internal/domain/memory/registry.go index 27834e3ae..75a04dd27 100644 --- a/internal/domain/memory/registry.go +++ b/internal/domain/memory/registry.go @@ -31,11 +31,8 @@ type engineStatus struct { startErr error } -// Registry is the memory family owner: it controls registration and -// discovery, lifecycle (start/health/stop), shutdown ordering, and failure -// isolation. An engine failure — a rejected registration, a failing Start, a -// blocking Stop, even a panicking Bind — affects only that engine and is -// reported, never fatal to the daemon or to other engines. +// Registry owns memory engine registration and lifecycle. An engine's +// failure affects only that engine. type Registry struct { mu sync.Mutex host Registrar @@ -183,11 +180,8 @@ func healthSafely(ctx context.Context, e MemoryEngine) (h Health) { return e.Health(ctx) } -// Stop stops every started engine in reverse registration order. Engines -// whose Start failed are skipped; the call is bounded by ctx — an engine -// that ignores cancellation cannot hang the daemon's shutdown beyond the -// caller's deadline, and its error is joined into the result. Stopping a -// registry that never started is a no-op. +// Stop stops started engines in reverse order, bounded by ctx, and joins +// their errors. func (r *Registry) Stop(ctx context.Context) error { r.mu.Lock() if r.state == stateIdle || r.state == stateStopped { diff --git a/internal/domain/memory/scanner.go b/internal/domain/memory/scanner.go index ca53cc4dc..57864109a 100644 --- a/internal/domain/memory/scanner.go +++ b/internal/domain/memory/scanner.go @@ -47,12 +47,6 @@ type DefaultScanner struct{} // Compile-time check: DefaultScanner implements Scanner. var _ Scanner = (*DefaultScanner)(nil) -// ── Patterns ──────────────────────────────────────────────────────────── -// -// These patterns are compiled once at init time. They are intentionally -// broad to catch common variants without being so broad that they -// produce false positives on normal memory content. - var ( promptInjectionPatterns = []*regexp.Regexp{ // Override / ignore previous instructions diff --git a/internal/domain/sampling/contract.go b/internal/domain/sampling/contract.go index 99d9e58ee..f249cb0a4 100644 --- a/internal/domain/sampling/contract.go +++ b/internal/domain/sampling/contract.go @@ -9,11 +9,7 @@ import ( "time" ) -// Candidate is one item eligible for sampling. It is deliberately narrow: -// an opaque identifier, the timestamp the timestamp-based strategies score -// against, and an open Metadata bag for whatever a future strategy needs -// (e.g. the embedding-backed surprisal strategy's vector) without widening -// this struct for every strategy that comes after wave 1. +// Candidate is an item eligible for sampling. type Candidate struct { ID string At time.Time @@ -29,11 +25,8 @@ type Request struct { Seed int64 } -// Sampler selects a subset of candidates to spend a curator pass's agentic -// budget on. Every implementation -- the four in this package and the -// future embedding-backed surprisal strategy -- must be -// deterministic given the same candidates and Request: same inputs, same -// output, every time. That is what makes a pass reproducible and testable. +// Sampler selects candidates for a curator pass. Implementations must be +// deterministic. type Sampler interface { // Name identifies the strategy for logging/attribution (e.g. // "recency", "random", "all", "staleness", later "surprisal"). diff --git a/internal/domain/sampling/recency.go b/internal/domain/sampling/recency.go index ef803489d..6ddcee088 100644 --- a/internal/domain/sampling/recency.go +++ b/internal/domain/sampling/recency.go @@ -19,11 +19,7 @@ func (recencySampler) Sample(_ context.Context, candidates []Candidate, req Requ return sorted[:effectiveCap(req.Cap, len(sorted))], nil } -// sortByTime returns a stably-sorted copy of candidates, never mutating the -// input. newestFirst true sorts descending by At (recency); false sorts -// ascending (staleness). A stable sort keeps ties in input order, which is -// what makes both strategies deterministic when candidates share a -// timestamp. +// sortByTime returns a stably sorted copy of candidates by At. func sortByTime(candidates []Candidate, newestFirst bool) []Candidate { sorted := append([]Candidate(nil), candidates...) slices.SortStableFunc(sorted, func(a, b Candidate) int { diff --git a/internal/domain/sampling/staleness.go b/internal/domain/sampling/staleness.go index 5cdffbf60..f96733906 100644 --- a/internal/domain/sampling/staleness.go +++ b/internal/domain/sampling/staleness.go @@ -2,11 +2,7 @@ package sampling import "context" -// stalenessSampler is the "staleness proxy" strategy: prefers content that -// hasn't been touched/reviewed in the longest time, i.e. the smallest -// Candidate.At first. It is a cheap proxy only -- callers decide what -// timestamp At holds (created, updated, or last-reviewed); this is never -// the embedding-based surprisal calculation. +// stalenessSampler prefers the oldest Candidate.At. type stalenessSampler struct{} // NewStaleness builds the "staleness" strategy. diff --git a/internal/domain/scheduling/contract.go b/internal/domain/scheduling/contract.go index da42a8a35..d9a8c8ff8 100644 --- a/internal/domain/scheduling/contract.go +++ b/internal/domain/scheduling/contract.go @@ -1,15 +1,5 @@ -// Package scheduling is the ticker engine: the timing half of archied's -// cron/scheduling capability. -// It owns one job and one job only — deciding *when* a scheduled job runs, -// and with what concurrency — and nothing about where jobs are stored, how -// they are authored, or how their output is delivered. -// -// The split is deliberate. A job store (file-backed, cross-process locked) -// and a delivery router are separate issues in that epic; this package -// declares the two contracts it needs from them (JobSource, Runner) and -// names no implementation. That is what lets the timing behaviour — pool -// semantics, overlap suppression, per-run timeouts, bounded shutdown — be -// tested against a fake clock with no store, no NATS and no model. +// Package scheduling decides when scheduled jobs run and with what +// concurrency. Storage and delivery are behind JobSource and Runner. package scheduling import ( @@ -78,11 +68,7 @@ func (j Job) Validate() error { return j.Pool.Validate() } -// JobSource yields the jobs eligible to run at a given instant. The engine -// calls Due once per tick and treats it as authoritative: it applies no -// schedule arithmetic of its own, so a source is free to implement cron -// expressions, fixed intervals or catch-up windows without the engine -// changing. +// JobSource returns the jobs due at an instant. type JobSource interface { Due(ctx context.Context, now time.Time) ([]Job, error) } diff --git a/internal/domain/scheduling/cron.go b/internal/domain/scheduling/cron.go index 0daeba0d7..592a4f98f 100644 --- a/internal/domain/scheduling/cron.go +++ b/internal/domain/scheduling/cron.go @@ -36,11 +36,8 @@ var cronMacros = map[string]string{ "@hourly": "0 * * * *", } -// parseCronSpec parses the project's cron dialect: five space-separated -// fields (minute, hour, day of month, month, day of week) each a wildcard, -// value, range, step (*/n or a-b/n) or comma list of those, or one of the -// @yearly, @annually, @monthly, @weekly, @daily, @midnight and @hourly -// macros. Any failure wraps ErrInvalidSpec. +// parseCronSpec parses a five-field cron expression or an @ macro. Errors +// wrap ErrInvalidSpec. func parseCronSpec(expr string) (*cronSpec, error) { spec, err := parseCron(expr) if err != nil { diff --git a/internal/domain/scheduling/jobspec.go b/internal/domain/scheduling/jobspec.go index 1a5da4d52..0464d9c81 100644 --- a/internal/domain/scheduling/jobspec.go +++ b/internal/domain/scheduling/jobspec.go @@ -5,16 +5,8 @@ import ( "time" ) -// Kind values for JobSpec.Kind: the discriminator that decides which delivery -// runner handles a job. -// -// They live beside the field that carries them because they are part of the -// schedules vocabulary an operator writes into the schedules document, a strict -// decoder reads back, and a build that never heard of a kind must reject loudly -// rather than deliver the wrong way. Which runner serves a kind is not this -// package's business: the router in internal/infrastructure/crondelivery owns -// that mapping, which is why an unrecognised kind is stored verbatim rather -// than refused at write time. +// Job kinds, selecting the delivery runner. Unknown kinds are stored as-is +// and refused by the router. const ( // KindChat delivers the job's Payload.Text as a chat message through the // deployment's channel. It is the default: an empty Kind means KindChat, @@ -44,12 +36,7 @@ type JobSpec struct { // Detail is a human-readable label rendered on events. Detail string `json:"detail,omitempty"` - // Kind selects which delivery runner handles this job. Empty means - // KindChat, so a job written before this field existed keeps - // delivering as a chat message. This package does not interpret the - // value: an unrecognised kind is stored verbatim and refused by the - // delivery router, which is the one place the mapping from kind to - // runner lives. + // Kind selects the delivery runner. Empty means KindChat. Kind string `json:"kind,omitempty"` // Schedule decides when this job is due. See schedule.go for the diff --git a/internal/domain/scheduling/schedule.go b/internal/domain/scheduling/schedule.go index b4547b82d..c4b1031b2 100644 --- a/internal/domain/scheduling/schedule.go +++ b/internal/domain/scheduling/schedule.go @@ -6,16 +6,8 @@ import ( "time" ) -// Duration is a schedule interval as the document writes it: the human string -// time.ParseDuration reads, never a nanosecond count. It reads the count too, -// because every schedule stored before this shape existed carries one -- both in -// the control plane's schedules resource and in this package's own jobs table, -// which persists the spec as JSON. -// -// The type is deliberately local, as config.Duration is for the file document -// and channelDuration is in internal/app/controlplane: each document owns its own -// wire form, and what is actually worth unifying later is the legacy-count -// tolerance rather than the tag shape. +// Duration is a schedule interval written as a duration string. It also +// reads a nanosecond count. type Duration time.Duration func (d Duration) MarshalJSON() ([]byte, error) { @@ -77,21 +69,15 @@ type Schedule struct { Start time.Time `json:"start"` } -// Schedule kinds the store recognises. Interval and Cron have full -// next-run arithmetic; Once is accepted at Create / fires at Due exactly -// once, but has no next-run arithmetic for MarkRun (one-shot by -// definition). MarkRun on a kind this build does not implement returns -// ErrScheduleUnsupported rather than silently advancing next_run. +// Schedule kinds. MarkRun on an unsupported kind returns +// ErrScheduleUnsupported. const ( // ScheduleInterval fires every Interval after the last successful run // (or after Start, if never run). The simplest recurring schedule. ScheduleInterval = "interval" - // ScheduleCron fires at the next moment matching a 5-field cron - // expression (or one of the @ macros) after the last successful - // run, computed in the zone of that run time. The dialect (cron.go) - // ANDs day-of-month with day-of-week instead of Vixie cron's OR: "0 0 1 * 1" means only Monday the 1st, - // not "the 1st or any Monday". + // ScheduleCron fires at the next cron match after the last run, in that + // run's zone. Day-of-month and day-of-week are ANDed. ScheduleCron = "cron" // ScheduleOnce fires once at the configured At time. Subsequent @@ -133,11 +119,8 @@ func (s Schedule) resolve() Schedule { return s } -// firstRun returns when the job should fire the very first time it has -// never run before. For Interval, it is Start + Interval (or now + Interval -// when Start is zero, so a freshly-created job with no Start still has a -// finite next-run). For Once, it is At. For Cron, it is the first matching -// minute strictly after Start (or after now when Start is zero). +// firstRun returns a never-run job's first fire time: Start (or now) plus +// Interval, At for Once, or the first cron match after Start (or now). func (s Schedule) firstRun(now time.Time) (time.Time, error) { switch s.resolve().Kind { case ScheduleInterval: @@ -171,11 +154,8 @@ func (s Schedule) firstRun(now time.Time) (time.Time, error) { // the parser's field ranges cannot reject — exhausts the scan. const cronHorizon = 5 * 365 * 24 * time.Hour -// nextCronRun returns the first wall-clock minute in the location of from -// at which sched is due, strictly after the minute containing from — the -// minute that just fired is never its own successor. Whole months and -// hours that cannot match are skipped, so even a sparse expression costs -// a handful of iterations per year scanned. +// nextCronRun returns the first minute after from's minute, in from's +// location, at which sched is due. func nextCronRun(sched *cronSpec, from time.Time) (time.Time, error) { t := from.Truncate(time.Minute).Add(time.Minute) for limit := from.Add(cronHorizon); t.Before(limit); { @@ -201,11 +181,8 @@ func (s Schedule) NextRun(lastRun time.Time) (time.Time, error) { return s.nextR func (s Schedule) Resolved() Schedule { return s.resolve() } -// nextRun returns when the job should fire after a successful run at -// lastRun. It is the engine-side counterpart to firstRun: every MarkRun -// advances next_run through this function. Interval and Cron are fully -// implemented; Once deliberately fails (there is no recurring next run) -// so a silently-wrong value cannot reach the ticker. +// nextRun returns the next fire time after a successful run at lastRun. Once +// returns an error. func (s Schedule) nextRun(lastRun time.Time) (time.Time, error) { switch s.resolve().Kind { case ScheduleInterval: diff --git a/internal/domain/scheduling/ticker.go b/internal/domain/scheduling/ticker.go index 690c405eb..0fc5e65d0 100644 --- a/internal/domain/scheduling/ticker.go +++ b/internal/domain/scheduling/ticker.go @@ -97,20 +97,9 @@ func (c EngineConfig) withDefaults() EngineConfig { return c } -// Engine is the ticker engine: one loop that asks the source what is due at -// each tick and dispatches each due job to the pool it declares. -// -// Two invariants make the timing safe to reason about: -// -// - A job never overlaps itself. While a run is queued or in flight, later -// ticks reporting the same ID are skipped, not stacked. A job slower than -// the tick interval therefore runs back-to-back, never fanned out. -// - The pools do not interfere. A blocked sequential job cannot delay a -// parallel one, and a saturated parallel cap cannot delay the sequential -// worker — they are separate dispatch paths sharing only the tick. -// -// Every failure is contained: a source error, a job error, a job panic and a -// job timeout are each reported as an event and leave the loop running. +// Engine asks the source what is due each tick and dispatches each job to +// its pool. A job never overlaps itself, and the sequential and parallel +// pools are independent. Errors, panics and timeouts are reported as events. type Engine struct { source JobSource runner Runner @@ -160,14 +149,8 @@ func (e *Engine) MaxParallel() int { return e.cfg.MaxParallel } // JobTimeout reports the resolved per-run timeout. func (e *Engine) JobTimeout() time.Duration { return e.cfg.JobTimeout } -// Start launches the tick loop and the sequential worker. -// -// An engine is single-use: starting one that is already started, or that has -// been stopped, is an error. Restarting is refused rather than supported -// because Stop leaves the dropped sequential backlog and the claims of runs -// it did not wait for behind — a restarted engine would re-run stale queued -// jobs and permanently suppress the jobs still marked claimed. Build a new -// engine instead; it is a struct, not a resource. +// Start launches the tick loop and the sequential worker. An engine can be +// started only once. func (e *Engine) Start(ctx context.Context) error { e.mu.Lock() defer e.mu.Unlock() @@ -194,11 +177,8 @@ func (e *Engine) Start(ctx context.Context) error { return nil } -// Stop halts ticking, drops any queued-but-unstarted runs, and waits for -// in-flight runs to finish, bounded by ctx. If ctx expires first, in-flight -// runs are cancelled and ctx's error is returned — a Runner that ignores -// cancellation can still outlive Stop, which is why the deadline is the -// caller's to set. Stopping an engine that never started is a no-op. +// Stop halts ticking, drops queued runs and waits for running ones within +// ctx, then cancels them. Stopping an unstarted engine is a no-op. func (e *Engine) Stop(ctx context.Context) error { e.mu.Lock() if !e.started { diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index c60f29d8c..5aef6dbfb 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -68,14 +68,8 @@ type ActionPayload struct { RetryMode taskstate.RetryMode } -// Actor is the identity that performed an action, and the principal whose -// authority permitted it. -// -// The two are separate fields because an agent acting under a person's standing -// approval is not the same fact as a person acting: a record that collapsed -// them would answer "who approved this" with the wrong identity. An empty -// Principal means UNATTRIBUTED -- no authority was recorded, which is a -// different fact from the actor authorising itself. +// Actor is who performed an action and the principal whose authority allowed +// it. An empty Principal means unattributed. type Actor struct { Identity identity.IdentityID Kind identity.Kind @@ -183,12 +177,8 @@ type Store interface { RespondReviewGate(context.Context, int64, string, string, bool, int) error ArchiveTask(context.Context, int64, string, events.Event) (int64, error) InsertEvent(context.Context, events.Event) (int64, error) - // CancelExecution is the one cancel path: - // the store - // records the cancellation -- every non-terminal step of the current - // attempt plus the execution's own move to `to` -- in one transaction. - // The service then cancels the in-memory context that was delivering the - // run; a worker's next step write fails ErrStaleTransition and stops. + // CancelExecution cancels the execution and its open steps in one + // transaction. CancelExecution(context.Context, int64, string, string) ([]int64, error) } @@ -206,18 +196,9 @@ type Service struct { Warn func(string, ...any) } -// Apply scopes chat requests to an identity. A nil scope denotes a caller -// authenticated across identities, which is the dashboard's own credential; -// scope limits which task a chat identity may act on, and never says who acted. -// -// The actor is not derived from scope: scope is which tasks a caller may touch, -// actor is who touched one, and the two are only equal by coincidence. -// -// res is the per-action payload (ActionPayload): the operator's instruction -// and finding selection for approve and rereview, the worktree mode for -// retry, and empty for every other action and for the chat surfaces that -// carry no such syntax. Both the dashboard and chat reach the same apply, so -// one operator intent cannot be recorded as two different decisions. +// Apply runs action on task id. A nil scope is a dashboard caller acting +// across identities; otherwise scope limits which tasks may be acted on. res +// is the action's payload. func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64, action taskstate.Action, res ActionPayload) error { task, err := s.Store.TaskByID(ctx, id) if err != nil { @@ -288,16 +269,9 @@ func (s Service) apply(ctx context.Context, task *Task, actor Actor, action task } } -// applyApprove is the one approval path, for both the review gate and the -// human-decision waits that predate it. -// -// A task carrying a gate offer gets the answer recorded on that offer in the -// guarded response write: the resumed run posts the recorded review filtered by -// the operator's selection, which is the only way "post the findings the -// operator selected" can mean the findings they saw. A task with no gate has no -// review to answer, so the approval is the plain release of waiting work; it -// requeues under the workflow the wait names -- which feasibility sets to -// implement before it waits -- never a name this handler hardcodes. +// applyApprove approves a waiting task. With a gate offer it records the +// answer on the offer; otherwise it requeues under the workflow the wait +// names. func (s Service) applyApprove(ctx context.Context, task *Task, actor Actor, o outcome, res ActionPayload) (outcome, error) { o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved") gate, ok := workflowtask.DecodeReviewGate(task.ReviewGate) @@ -318,11 +292,8 @@ func (s Service) applyApprove(ctx context.Context, task *Task, actor Actor, o ou return o, nil } -// applyRereview records the operator's instructions and requeues the review -// phases. It is refused, as a conflict, for a task with no gate offer and for -// one at the cap: in both cases the task stays waiting and nothing is written. -// The offer's findings are cleared, because the resumed run recomputes them; -// the instructions are what reach the recomputation. +// applyRereview records the operator's instructions and requeues the review. +// It conflicts when there is no gate offer or the cap is reached. func (s Service) applyRereview(ctx context.Context, task *Task, actor Actor, o outcome, res ActionPayload) (outcome, error) { gate, ok := workflowtask.DecodeReviewGate(task.ReviewGate) if !ok || !gate.Offered() { diff --git a/internal/domain/workintake/dispatch.go b/internal/domain/workintake/dispatch.go index c4b1c992a..494811718 100644 --- a/internal/domain/workintake/dispatch.go +++ b/internal/domain/workintake/dispatch.go @@ -1,12 +1,5 @@ package workintake -// This file is the single definition of what a dispatch trigger means: which -// triggers match on a label, and whether a concrete issue (its labels and -// assignees) is eligible work under a trigger. The daemon's poller and the -// forge webhook intake both consult it, so the two cannot drift -- the -// empty-label guard here is the one that previously regressed (3209a1f: an -// empty label matches every open issue via the forge API). - import ( "slices" "strings" @@ -40,11 +33,7 @@ func containsLabel(labels []string, needle string) bool { return slices.Contains(labels, needle) } -// containsAssignee matches logins case-insensitively: GitHub usernames are -// unique case-insensitively, and AssignedIssues' server-side assignee filter -// matches the same way -- an exact-case comparison here would silently miss -// what the poller finds whenever the configured bot_user's case differs from -// the login GitHub reports on the event. +// containsAssignee matches logins case-insensitively. func containsAssignee(assignees []string, botUser string) bool { return slices.ContainsFunc(assignees, func(a string) bool { return strings.EqualFold(a, botUser) diff --git a/internal/domain/workintake/envelope.go b/internal/domain/workintake/envelope.go index 9e1f03c64..a869dc8d2 100644 --- a/internal/domain/workintake/envelope.go +++ b/internal/domain/workintake/envelope.go @@ -1,14 +1,5 @@ -// Package workintake owns the promotion of a discovered external issue into -// durable, workflow-backed work. -// -// It owns the vocabulary of that promotion -- the task envelope, its routing -// kind, and the subjects it is addressed to -- because the domain that defines -// a message's meaning owns its schema. These previously lived in the NATS -// package, which made the transport responsible for knowing what a unit of work -// was -// -// This package names no broker. It produces and consumes bytes; carrying -// them is internal/eventbus's job. +// Package workintake turns discovered issues into task envelopes and defines +// their routing kinds and subjects. package workintake import ( @@ -107,12 +98,8 @@ func (t TaskEnvelope) Ref() string { return t.Owner + "/" + t.Repo + "#" + strconv.Itoa(t.Number) } -// IdempotencyKey identifies this issue for delivery deduplication, so -// rediscovering it on a later poll does not enqueue the same work twice. The -// key is org/identity/owner/repo/number: the poller and the webhook receiver -// resolve the org and identity before publishing, so the same issue delivered -// both ways still gives one key, and the State Store's task uniqueness uses the -// same fields. This method is the one place that shape is produced. +// IdempotencyKey identifies this issue for dedup: +// org/identity/owner/repo/number. func (t TaskEnvelope) IdempotencyKey() string { return dedupKeyPrefix + string(t.org()) + "/" + t.Identity + "/" + t.Owner + "/" + t.Repo + "/" + strconv.Itoa(t.Number) diff --git a/internal/domain/workintake/subjects.go b/internal/domain/workintake/subjects.go index bf4c816a1..fff3c2d54 100644 --- a/internal/domain/workintake/subjects.go +++ b/internal/domain/workintake/subjects.go @@ -18,12 +18,7 @@ const ( SubjectTaskWildcard = "archie.task.>" ) -// SubjectReactionWildcard matches every reaction subject under archie.reaction. -// Reactions are producer-only fan-out events -// delivered on a separate -// LimitsPolicy stream, so every registered consumer sees every matching event -// -- unlike the work-queue ARCHIE_TASKS stream, where one consumer claims each -// message. +// SubjectReactionWildcard matches every reaction subject. const SubjectReactionWildcard = "archie.reaction.>" // ErrUnknownKind reports a kind with no subject. Routing it to the default @@ -31,12 +26,6 @@ const SubjectReactionWildcard = "archie.reaction.>" var ErrUnknownKind = errors.New("workintake: unknown task kind") // Kind is the routing category an issue's labels select. -// -// It is the single axis both the workflow registry and the task subjects -// route on. The label table was once written twice -- a switch in -// workflow.Route and a subject lookup in the NATS package -- so adding a -// label meant remembering both, and the transport had to know what a forge -// label was. type Kind string const ( @@ -95,11 +84,7 @@ func KindForLabels(labels []string) Kind { return KindDefault } -// KindsForLabels returns every recognised kind in label order. -// -// Workflow routing needs the full ordered set rather than just the first: -// when a task is labelled "bug,feature" and no "tdd" workflow is registered, -// it must still fall through to "feasibility" rather than to the default. +// KindsForLabels returns every recognised kind, in label order. func KindsForLabels(labels []string) []Kind { var kinds []Kind for _, label := range labels { @@ -110,18 +95,7 @@ func KindsForLabels(labels []string) []Kind { return kinds } -// labelValue reduces a forge label to the value labelKinds is keyed on. -// -// Forges namespace labels by convention ("type::feature", "priority::medium") -// and the namespace is the issue tracker's own taxonomy, not part of the -// routing vocabulary, so the value after the last "::" is what identifies a -// kind. Matching the bare string alone meant a repo that namespaces its -// labels -- which this one does -- never matched any kind, and every task -// fell through kind routing to the content-aware fallback in Route. -// -// The namespace itself is deliberately not checked: a closed three-value -// vocabulary (bug, feature, bootstrap) is specific enough that a label ending -// in one of them means that kind whatever the tracker files it under. +// labelValue returns the part of a label after its last "::". func labelValue(label string) string { trimmed := strings.TrimSpace(label) if i := strings.LastIndex(trimmed, "::"); i >= 0 { diff --git a/internal/eventbus/doc.go b/internal/eventbus/doc.go index 78844da04..f6994df70 100644 --- a/internal/eventbus/doc.go +++ b/internal/eventbus/doc.go @@ -1,20 +1,3 @@ -// Package eventbus is the broker-neutral messaging contract. -// -// It defines only the messaging behaviour Archie requires: publication, -// subscription, request/reply, and delivery outcomes. It names no broker. -// NATS subjects, JetStream configuration, consumer groups, acknowledgement -// mechanics, reconnection and serialization live in -// internal/infrastructure/eventbus/nats, which implements these interfaces. -// -// # The bus does not own message meaning -// -// This package deliberately transports opaque payloads. Message schemas -// belong to the domain that defines them -- work intake owns its task -// envelope, agent execution owns its request and response types -- and each -// domain owns the subjects it addresses. A previous version of the NATS -// package exported a TaskEnvelope type and a PublishTask method, which made -// the transport responsible for knowing what a unit of work was. -// -// Subjects are plain strings here. Constraining their syntax would encode one -// broker's addressing rules into the contract. +// Package eventbus is the broker-neutral messaging contract. Payloads are +// opaque and subjects are plain strings. package eventbus diff --git a/internal/eventbus/eventbus.go b/internal/eventbus/eventbus.go index 005b3633b..8e0f5c749 100644 --- a/internal/eventbus/eventbus.go +++ b/internal/eventbus/eventbus.go @@ -45,13 +45,8 @@ type Publisher interface { // Publish sends payload to subject. Publish(ctx context.Context, subject string, payload []byte) error - // PublishUnique sends payload to subject carrying an idempotency key. - // Republishing the same key within the implementation's deduplication - // window is suppressed. - // - // This is a required semantic rather than a broker detail: work intake - // rediscovers the same issue on every poll, so at-least-once delivery - // without deduplication would enqueue it repeatedly. + // PublishUnique publishes payload with an idempotency key; repeats within + // the dedup window are dropped. PublishUnique(ctx context.Context, subject, idempotencyKey string, payload []byte) error } diff --git a/internal/events/events.go b/internal/events/events.go index 6a2c1ff26..6ce53f5ec 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -15,12 +15,8 @@ const ( KindTaskQueued = "task_queued" KindStageStart = "stage_start" KindStageFinish = "stage_finish" // data: duration_ms, error - // KindAgentFinish carries the stage's token economics as well as its - // outcome: tokens is the run total (agentexec.Result.TokensUsed) and the - // prompt/completion/cached/cache_creation breakdown is the provider's own - // accounting, forwarded verbatim for evaluation. The breakdown is absent - // on events persisted before it was carried across the agent boundary, so - // consumers must treat each field as optional rather than zero. + // KindAgentFinish carries the stage outcome and token usage. The breakdown + // fields are optional. KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model, prompt_tokens, completion_tokens, cached_tokens, cache_creation_tokens // KindToolCall marks one completed tool invocation during an agent stage // run. Only emitted for runners that execute in the same process as their @@ -37,26 +33,14 @@ const ( // seeing, because it explains why a task changed course. KindHumanApproved = "human_approved" KindHumanRejected = "human_rejected" - // KindAgentApproved and KindAgentRejected record that an agent performed - // the action. They exist because the event kind describes the ACTOR: an - // agent approving under a person's standing authority is not a human - // approval, and recording it as one asserts something false. The authority - // it acted under is PrincipalID, which is a separate fact. + // KindAgentApproved and KindAgentRejected record an agent's action. KindAgentApproved = "agent_approved" KindAgentRejected = "agent_rejected" - // KindTaskApproved and KindTaskRejected record an approval or rejection that - // archie cannot attribute to anyone: the request carried no identity archie - // could verify. They are task-level events that claim nothing about the - // actor, which is the honest record -- a human's approval and an agent's are - // recorded as human_* and agent_* respectively. + // KindTaskApproved and KindTaskRejected record an unattributed approval or + // rejection. KindTaskApproved = "task_approved" KindTaskRejected = "task_rejected" - // KindHumanRereviewed, KindAgentRereviewed and KindTaskRereviewed record - // the operator asking the review gate for a re-review. The answer is - // neither an approval nor a rejection, and recording it as either would - // make the timeline claim a verdict the operator did not give. They follow - // the same actor/agent/task attribution split as the approved and rejected - // trios above. + // Re-review requests, by human, agent or unattributed. KindHumanRereviewed = "human_rereviewed" KindAgentRereviewed = "agent_rereviewed" KindTaskRereviewed = "task_rereviewed" @@ -71,24 +55,13 @@ const ( KindWorkRequestSubmitted = "work_request_submitted" KindLog = "log" // data: level, msg - // KindChangesCaptured records the change one attempt produced, read off - // the worktree at the moment it was committed or pushed, plus a final - // capture once OpenPR knows the number. It is durable - // provenance, not a live view: the worktree is deleted on merge, close - // and no-PR terminal states, and a retry resets the branch onto its base, - // so nothing can re-derive this after the fact. data: schema - // (ChangesCapturedSchema), owner, repo, base, branch, head_sha, base_sha, - // pr_number, captured_after, files[], totals, truncated. + // KindChangesCaptured records one attempt's change at commit or push time. + // data: schema, owner, repo, base, branch, head_sha, base_sha, pr_number, + // captured_after, files[], totals, truncated. KindChangesCaptured = "changes_captured" - // KindConfigCaptured records the effective configuration one attempt ran - // under, captured where it is materialised for the dispatch. It is durable - // by requirement, not convenience: the published configuration snapshot is - // the CURRENT configuration and is replaced on every publish, so it cannot - // answer what a run that finished last week was configured with. This is - // the only record of that. data: schema (ConfigCapturedSchema) and document - // (the JSON encoding of the dispatch's config.TaskConfig, non-secret by - // construction and by test). + // KindConfigCaptured records the configuration one attempt ran with. data: + // schema and document (the dispatch's config.TaskConfig as JSON). KindConfigCaptured = "config_captured" // Curator family activity. Curator runs ride @@ -98,11 +71,8 @@ const ( KindCuratorAction = "curator_action" // data: curator, type, detail, reason KindCuratorError = "curator_error" // data: curator, phase, err - // Scheduled-job activity from the ticker engine - // (internal/domain/scheduling). A scheduled run has no task and no chat - // turn behind it, so without these a job that fired, stalled or failed - // is invisible everywhere. data: job, pool, duration_ms (run) and job, - // pool, phase, err (error). + // Scheduled job activity. data: job, pool, duration_ms (run); job, pool, + // phase, err (error). KindJobRun = "job_run" KindJobError = "job_error" @@ -112,12 +82,8 @@ const ( // trigger. data: session, channel. KindTurnCompleted = "turn_completed" - // EDA edit activity (bindings and mappings on the captures store). Each - // successful write on the State Store's binding and mapping tables emits one - // event through the same task-DB path capture arrival uses, so a - // dashboard edit is visible on the activity stream without a manual - // refresh. data: id (the edited record), action (create, update, - // approve, delete). + // Binding and mapping edits. data: id, action (create, update, approve, + // delete). KindBindingChanged = "binding_changed" KindMappingChanged = "mapping_changed" @@ -136,11 +102,8 @@ const ( // one; a wait:false callee reports on its own run. KindWorkflowCallFinished = "workflow_call_finished" - // KindUpdateReport carries the phase-2 outcome of a dashboard-initiated - // update -- whether the restarted daemon came back up healthy and on - // the version it claimed, relayed once on the boot that finds the - // pending report left by the update watchdog. - // data: health_check, rolled_back, confirmed, drift, unverified. + // KindUpdateReport is a dashboard update's post-restart outcome. data: + // health_check, rolled_back, confirmed, drift, unverified. KindUpdateReport = "update_report" ) @@ -167,19 +130,9 @@ type Event struct { Issue int `json:"issue,omitempty"` Workflow string `json:"workflow,omitempty"` Stage string `json:"stage,omitempty"` - // Attempt attributes the event to one run of the task. Zero means - // UNATTRIBUTED, not "attempt zero": every row written before this field - // existed, and the deliberately task-agnostic producers, carry 0. A - // reader must report those as unattributable rather than presenting them - // as a first run. The tag is deliberately not omitempty so that - // unattributed and absent stay distinguishable on the wire and in the - // array the dashboard renders. + // Attempt is the task attempt; 0 means unattributed. Attempt int `json:"attempt"` - // ActorID is the identity that performed the action this event records, - // derived from the credential the request presented. Empty means the event - // has no actor: the producers that are task-agnostic or pre-date this field - // make no claim about who acted, and a reader must report that rather than - // assume a human did. + // ActorID is the identity that acted; empty means no actor is claimed. ActorID string `json:"actor_id,omitempty"` // ActorKind is the acting identity's kind, kept beside ActorID so a reader // can tell an agent's action from a person's without resolving the identity diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 25d7fa14e..eb59813a3 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -149,12 +149,7 @@ type Review struct { // inline comments are flat under a review, so it is 0 there. type ReviewComment struct { ID int64 - // ReviewID is the review this comment belongs to. It is what lets a - // comment be collected into its review's remediation unit instead of - // starting one of its own (pr-review-remediation.md decision 5); a - // standalone comment carries 0. GitHub carries it on the comment; - // Gitea's flat comment list is walked per review, so the mapping comes - // from the walk. + // ReviewID is the review this comment belongs to; 0 for a standalone comment. ReviewID int64 Author string Body string @@ -164,13 +159,7 @@ type ReviewComment struct { CreatedAt time.Time } -// PullRequestReviewReader reads review activity on an existing PR. Forge -// implementations that cannot read reviews (the noop forge) do not implement -// it; callers type-assert and refuse when the capability is absent. -// -// sinceID is the dedup cursor: only entries with ID > sinceID are returned, -// so a poller and a webhook delivery of the same comment collapse on the same -// ID (the TaskEnvelope.IdempotencyKey pattern applied to reviews). +// PullRequestReviewReader reads review activity on a PR newer than sinceID. type PullRequestReviewReader interface { ListReviews(ctx context.Context, owner, repo string, number int, sinceID int64) ([]Review, error) ListReviewComments(ctx context.Context, owner, repo string, number int, sinceID int64) ([]ReviewComment, error) @@ -189,34 +178,15 @@ type InlineReviewComment struct { Body string } -// ReviewCommentWriter posts line-anchored review comments on an open pull -// request. Forge implementations that cannot (the noop forge) do not implement -// it; callers type-assert and degrade to the PR-body list rather than faking it. -// -// The set travels in one call because that is Gitea's native shape (a single -// COMMENT-state review carrying many comments); GitHub loops internally. Each -// implementation reads the pull request's current head itself and anchors the -// comments to it, but only after checking it against reviewedHeadSHA -- the -// revision the caller's line numbers were measured on. A line number that -// outlives its revision does not fail loudly at the forge: it attaches to -// whatever is on that line now, so the set is refused once the head has moved. -// An empty reviewedHeadSHA means the caller could not measure one, and posts -// unanchored by revision rather than dropping every finding. +// ReviewCommentWriter posts line-anchored review comments on a PR, refusing +// when the head has moved past reviewedHeadSHA. Empty reviewedHeadSHA skips +// the check. type ReviewCommentWriter interface { CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []InlineReviewComment) error } -// reviewHeadDrift is the rule ReviewCommentWriter's implementations share: a -// line-anchored comment set may be posted only while the pull request's head is -// still the revision those line numbers were measured on. It returns nil when -// there is nothing to refuse, including when the caller could not measure a -// revision at all (reviewedHeadSHA == "") -- posting unverified is the -// pre-existing behaviour, and is strictly better than dropping every finding. -// -// The check lives here rather than in each implementation because the danger is -// identical on both: GitHub and Gitea accept a line number against the current -// head and anchor it to whatever now occupies that line, so a stale anchor does -// not fail loudly -- it misinforms. +// reviewHeadDrift returns an error when head is no longer reviewedHeadSHA. +// Empty reviewedHeadSHA returns nil. func reviewHeadDrift(owner, repo string, number int, head, reviewedHeadSHA string) error { if reviewedHeadSHA == "" || strings.EqualFold(head, reviewedHeadSHA) { return nil diff --git a/internal/forge/gitea.go b/internal/forge/gitea.go index 3eef869c5..d6af0a796 100644 --- a/internal/forge/gitea.go +++ b/internal/forge/gitea.go @@ -268,22 +268,8 @@ func (c *GiteaClient) ReplyToReview(ctx context.Context, owner, repo string, num return nil } -// CreateReviewComments posts the line-anchored comments as one COMMENT-state -// review, anchored to the pull request's head revision. -// -// Gitea has no standalone inline-comment call: inline comments are carried by a -// submitted review, so a single review is both the native shape and the fewest -// round trips. It is also all-or-nothing -- one comment Gitea refuses fails the -// whole request, and the review carries nothing -- where GitHub's loop keeps the -// comments it could post. The PR-body findings list is the fallback in either -// case. -// -// The head SHA is read here rather than taken from the caller: it is what Gitea -// anchors the review to, and the caller that produced the line numbers (a -// workflow stage running in archie-agent) holds no forge credentials to read it -// with. reviewedHeadSHA is the revision those line numbers were measured on, and -// the review is refused outright if the head has moved past it -- see -// reviewHeadDrift. +// CreateReviewComments posts the comments as one COMMENT review on the PR's +// head, refused if the head moved past reviewedHeadSHA. func (c *GiteaClient) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []InlineReviewComment) error { pr, err := c.GetPullRequest(ctx, owner, repo, number) if err != nil { diff --git a/internal/forge/github.go b/internal/forge/github.go index a2f6c3d88..ce60c0c37 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -202,11 +202,8 @@ func (c *GitHubClient) GetPullRequestDiff(ctx context.Context, owner, repo strin return diff, nil } -// GetRepoArchive fetches a gzipped tar archive of the repository at ref. -// GetArchiveLink only resolves the download's final location; the archive's -// bytes still have to be fetched with a plain, unauthenticated GET (the URL -// GitHub redirects to is a pre-signed storage link, not a GitHub API -// endpoint), so no forge token is attached to this second request. +// GetRepoArchive downloads a gzipped tar of the repository at ref. The +// download URL is pre-signed, so no token is sent. func (c *GitHubClient) GetRepoArchive(ctx context.Context, owner, repo, ref string) (io.ReadCloser, error) { url, _, err := c.gh.Repositories.GetArchiveLink(ctx, owner, repo, github.Tarball, &github.RepositoryContentGetOptions{Ref: ref}, 5) if err != nil { @@ -301,19 +298,9 @@ func (c *GitHubClient) ReplyToReview(ctx context.Context, owner, repo string, nu return nil } -// CreateReviewComments posts line-anchored review comments, one GitHub call per -// comment, anchored to the RIGHT (new) side of the pull request's head revision. -// -// The head SHA is read here rather than taken from the caller: it is what the -// comments are anchored to, and the caller that produced the line numbers (a -// workflow stage running in archie-agent) holds no forge credentials to read it -// with. reviewedHeadSHA is the revision those line numbers were measured on, and -// the set is refused outright if the head has moved past it -- see -// reviewHeadDrift. -// -// A comment GitHub refuses -- a line that falls outside the diff, a file the -// push renamed -- does not abandon the rest. The failures are joined and -// returned, so one unanchorable finding cannot silently drop the others. +// CreateReviewComments posts each comment on the PR head's new side, refused +// if the head moved past reviewedHeadSHA. Failures are joined; the rest are +// still posted. func (c *GitHubClient) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []InlineReviewComment) error { head, err := c.reviewHeadSHA(ctx, owner, repo, number) if err != nil { @@ -370,13 +357,6 @@ func (c *GitHubClient) LinkBranch(ctx context.Context, owner, repo string, issue return nil } -// State labels mirror the task lifecycle onto the forge so archie's -// status is visible at a glance. SQLite remains the source of truth; -// labels are the human-facing projection -- and removing the parked -// label is the forge-native retry trigger. -// Label strings are configured via [dispatch.labels]; these are the -// built-in defaults used as a fallback when config is absent. - // stateLabelColors maps label name → colour for on-demand creation. var stateLabelColors = map[string]string{ "archie:queued": "bfd4f2", // grey-blue diff --git a/internal/forge/webhook/receiver.go b/internal/forge/webhook/receiver.go index aeef70449..f4fec404e 100644 --- a/internal/forge/webhook/receiver.go +++ b/internal/forge/webhook/receiver.go @@ -1,33 +1,6 @@ -// Package webhook implements the GitHub forge webhook receiver: an HTTP -// endpoint that verifies a GitHub webhook's HMAC signature, decodes the -// "issues" event, and publishes a matched issue as a workintake.TaskEnvelope. -// -// It is forge intake, distinct from internal/channels/webhook (the chat -// channel): that package routes inbound text through the gateway for LLM -// processing; this one decodes a GitHub payload into the same TaskEnvelope -// the poller produces and hands it to the same publish path, so a labelled or -// assigned issue becomes work the moment it happens rather than up to -// poll_interval later. -// -// GitHub's webhook must be configured with "Content type: application/json" -// (the UI default). The alternate application/x-www-form-urlencoded delivery -// is not decoded here and is rejected as a bad payload. -// -// Idempotency is not this package's job: it decodes into the same TaskEnvelope -// and calls the same publish path the poller uses, so PublishUnique's dedup -// (keyed on TaskEnvelope.IdempotencyKey) covers both sources for free. What -// this package does own is making a wedged or non-delivering receiver -// observable: a GET to the listen address (GitHub only ever POSTs) returns -// Status, tracking authenticated deliveries and successful publishes separately -// so an operator can tell "receiver is up but nothing is arriving" apart from -// "repo has no issue activity." -// -// The GET/Status route is deliberately unauthenticated, on the same -// internet-facing listener GitHub POSTs signed payloads to: it reveals -// counters and timestamps only, never repo data, issue content, or the -// webhook secret, so treating it as a public liveness probe (the same -// tradeoff an unauthenticated /healthz makes) is an acceptable exchange for -// not requiring a second credential just to check if the receiver is alive. +// Package webhook receives GitHub issue and review webhooks, verifies their +// HMAC and publishes them through the poller's publish path. Only +// application/json payloads are accepted. A GET returns delivery Status. package webhook import ( @@ -54,12 +27,7 @@ const maxBodyBytes = 1 << 20 // 1 MiB // (*daemon.Daemon).PublishTask, the same enqueue path the poller uses. type PublishFunc func(ctx context.Context, task workintake.TaskEnvelope) error -// ReactionPublishFunc delivers one decoded review reaction to the reaction -// stream (pr-review-remediation.md decision 2's webhook producer). The -// composition root wires it to PublishUnique against the envelope's reaction -// subject, so a webhook delivery and a poll record of the same review dedup -// on the envelope's source-independent key. The reaction path carries no -// dispatch predicate: eligibility is the consumer's owned-PR lookup. +// ReactionPublishFunc publishes one review reaction. type ReactionPublishFunc func(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error // reactionRateLimit bounds reaction deliveries per remote source per window @@ -118,12 +86,8 @@ func New(secret, trigger, label, botUser string, publish PublishFunc, reactionPu } } -// Status reports the receiver's delivery activity so an operator can tell a -// wedged or non-delivering receiver apart from a repo with no issue -// activity: Deliveries counts every authenticated, -// parseable webhook -- proof GitHub reached this process at all -- while -// Publishes counts only what the dispatch predicate turned into work. -// LastReceivedAt is nil until the first authenticated delivery arrives. +// Status counts authenticated deliveries and published tasks. +// LastReceivedAt is nil before the first delivery. type Status struct { StartedAt time.Time `json:"started_at"` LastReceivedAt *time.Time `json:"last_received_at"` diff --git a/internal/forgerpc/forgerpc.go b/internal/forgerpc/forgerpc.go index 6e9d05080..9e0d1420a 100644 --- a/internal/forgerpc/forgerpc.go +++ b/internal/forgerpc/forgerpc.go @@ -1,25 +1,5 @@ -// Package forgerpc lets archie-agent call the forge methods workflow stages -// invoke mid-run -- CloseIssue, CreatePR, LinkBranch, CreateReviewComments, -// Comment and ReplyToReview, the workflow.Forger set -- over core NATS -// request/reply, instead of the agent -// container holding a live forge API token. archied remains the sole holder of -// forge credentials and the sole caller of forge.Forge. -// -// The rest of forge.Forge (issue polling, invitations, reactions, PR-state -// reconciliation) is used exclusively by the daemon's own poll/reconcile -// loops, never from inside a workflow stage, so there is nothing for -// archie-agent to call. -// -// The server also still answers Comment and SetStateLabel. No current agent -// calls them; the handlers exist so an older archie-agent image keeps working -// against a newer daemon. The compatibility is one-directional: a NEW agent -// against an OLD daemon has no LinkBranch handler to reach, and the request -// times out, so an image skew that way parks tasks. Note it in release notes -// rather than assuming either side can lag. -// -// CreateReviewComments is the one method whose absence does NOT park a task: the -// stage that calls it is best-effort by design, so the same new-agent/old-daemon -// skew costs the inline comments and leaves the PR-body findings list intact. +// Package forgerpc lets archie-agent call the workflow.Forger methods over +// NATS request/reply, so only archied holds forge credentials. package forgerpc import ( @@ -48,12 +28,8 @@ const ( SubjectReplyToReview = "archie.forge.reply_to_review" ) -// SubjectFor returns the subject for base, scoped to identity when set. -// An empty identity uses the root subject, which is how single-identity -// deployments and agent images that predate identity routing behave. The -// daemon registers one server per identity on these scoped subjects so a -// container-mode task owned by a non-root identity has its RPC calls -// served by that identity's own forge client, not the root's. +// SubjectFor returns base scoped to identity, or base when identity is +// empty. func SubjectFor(identity, base string) string { if identity == "" { return base @@ -100,21 +76,11 @@ type SetStateLabelRequest struct { KnownLabels []string } -// CreateReviewCommentsRequest carries one review's worth of line-anchored -// comments. The payload mirrors workflow.ReviewComment rather than reusing it: -// the wire shape is a contract between two processes that can be at different -// versions, so it is stated here instead of inherited from a type that may be -// renamed or reshaped for reasons that never crossed the wire. +// CreateReviewCommentsRequest is one review's line-anchored comments. type CreateReviewCommentsRequest struct { Owner, Repo string Number int - // ReviewedHeadSHA is the revision the comments' line numbers were measured - // on, which the worker records when it opens the pull request. It is - // additive on the wire: a worker that predates it omits the field and the - // server posts unverified (the pre-existing behaviour) rather than refusing - // every set, and a server that predates it ignores the field. Neither - // direction breaks, and neither silently mints a revision that was never - // measured. + // ReviewedHeadSHA is the revision the line numbers were measured on. ReviewedHeadSHA string Comments []InlineReviewCommentPayload } @@ -270,11 +236,6 @@ func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Ti func (c *Client) subject(base string) string { return SubjectFor(c.Identity, base) } -// Comment and SetStateLabel are not in workflow.Forger, so no current agent -// calls them. They stay as the client half of handlers kept for image skew -// (see the package doc) -- and as the only way to exercise those handlers -// end to end, which is why removing them would leave the compatibility path -// untested rather than merely unused. func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) { req := CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body} resp, err := natsrpc.Call[CommentResponse](ctx, c.rpc(), c.subject(SubjectComment), req) @@ -324,13 +285,8 @@ func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number i _, _ = natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectSetStateLabel), req) } -// CreateReviewComments posts the review's line-anchored findings on the pull -// request. It is the one proxied method a workflow stage treats as best-effort, -// which is why it is also the one whose failure cannot park a task. -// -// reviewedHeadSHA travels with the call so the daemon -- the only side holding -// forge credentials, and so the only side that can read a pull request's head -- -// can refuse a set whose line numbers describe a revision the PR has left. +// CreateReviewComments posts line-anchored comments on the PR through the +// daemon. func (c *Client) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []workflow.ReviewComment) error { payload := make([]InlineReviewCommentPayload, 0, len(comments)) for _, cm := range comments { diff --git a/internal/infrastructure/access/engine.go b/internal/infrastructure/access/engine.go index 584ffd955..bbdfee9df 100644 --- a/internal/infrastructure/access/engine.go +++ b/internal/infrastructure/access/engine.go @@ -1,14 +1,6 @@ -// Package access implements internal/domain/access's Authorizer with -// github.com/cedar-policy/cedar-go. The engine owns policy parsing and -// validation against the shipped Cedar schema, and the chain evaluation: -// instance ▶ org ▶ workspace ▶ object, where a level with policies must -// permit, a forbid at any level wins, and with no permit the request is -// denied. -// -// The cross-org forbid is enforced here, structurally, before any Cedar -// runs: a principal never reaches a resource outside its org. It is not a -// stored policy, so it cannot be edited away or removed by -// `archied access reset`. +// Package access implements the Authorizer with cedar-go. Levels are +// evaluated instance, org, workspace, object: a level with policies must +// permit and any forbid wins. Cross-org access is always denied. package access import ( @@ -24,12 +16,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/org" ) -// schemaText is the Cedar schema the engine validates every policy against. -// It names the entity vocabulary internal/domain/access defines: an -// Identity principal carrying its org and effective role, the org and -// workspace parents, one Object entity per record, and one Action per -// action. Context carries the event's signature result, the address it came -// from, and the run and step of an agent's request. +// schemaText is the Cedar schema policies are validated against. const schemaText = `namespace Archie { entity Identity in [Org] = {"org": String, "role": String}; entity Org; @@ -98,11 +85,9 @@ var ( _ access.Validator = (*Engine)(nil) ) -// New builds an engine over one snapshot of the stored policies. An invalid -// instance policy is a boot failure: it returns (nil, err) and archie stops -// serving until the policy is fixed. An invalid org, workspace or object -// policy becomes a Problem and makes its level deny everything -- the other -// levels still serve, and the health surface reports the problem by name. +// New builds an engine from the stored policies. An invalid instance policy +// is an error; an invalid policy at another level makes that level deny +// everything. func New(policies []access.Policy) (*Engine, error) { e := &Engine{ orgs: map[org.OrgID]*levelSet{}, diff --git a/internal/infrastructure/access/entities.go b/internal/infrastructure/access/entities.go index e79bcbfef..1885d1eff 100644 --- a/internal/infrastructure/access/entities.go +++ b/internal/infrastructure/access/entities.go @@ -12,11 +12,8 @@ import ( "github.com/samcharles93/archie-core/internal/domain/access" ) -// buildRequest turns the assembled request into the engine's shape. The -// context record carries only the fields that were set: a policy testing a -// field the caller did not supply cannot match, which is the fail-closed -// reading of "context: the event's signature result, the address it came -// from, the time, and the run and step when the principal is an agent". +// buildRequest converts a request for Cedar, including only the context +// fields that were set. func buildRequest(p access.Principal, a access.Action, r access.Resource, c access.Context) types.Request { record := types.RecordMap{} if c.Signature != "" { @@ -48,11 +45,7 @@ func buildRequest(p access.Principal, a access.Action, r access.Resource, c acce } } -// buildEntities assembles the entity graph policies may walk: the principal -// (its org and effective role), the resource (its kind, org, workspace, -// owner and state), and the org and workspace parents the resource hangs -// from. A policy naming a parent the request does not supply simply does -// not match. +// buildEntities builds the principal, resource and parent entities. func buildEntities(p access.Principal, r access.Resource) cedar.EntityMap { resOrg := r.Org if resOrg == "" { diff --git a/internal/infrastructure/agentgit/safety.go b/internal/infrastructure/agentgit/safety.go index 1e17d6fbe..06f7b3871 100644 --- a/internal/infrastructure/agentgit/safety.go +++ b/internal/infrastructure/agentgit/safety.go @@ -22,29 +22,8 @@ func MarkSafe(ctx context.Context, mountDir string, log *slog.Logger) bool { return markSafe(ctx, mountDir, runGit, log) } -// markSafe adds mountDir to git's global safe.directory list. -// -// The daemon bind-mounts the task worktree into the container from the host, -// so the directory is owned by a UID the container user is not. Git refuses to -// operate in a repository it does not own ("detected dubious ownership"), and -// the Go toolchain shells out to git for VCS stamping during build/test/vet -- -// so without this every gate fails before the agent does any real work. -// -// Best-effort by design: git may be absent from a minimal image, and an agent -// working a repo with no gate commands never needs it. A failure is logged and -// the agent continues. Returns true only when git accepted the configuration. -// -// The guard is existence, not mount-ness: os.Stat confirms mountDir exists and -// is a directory, which prevents a misconfigured archie-agent from writing to -// the operator's own ~/.gitconfig for a workspace path that was never mounted. -// Mandatory task boot metadata independently rejects non-task workers before -// they subscribe. This check does not detect a -// stale directory that happens to exist at the same path without actually -// being a bind mount -- a real mount check would need platform-specific -// parsing (e.g. /proc/self/mountinfo on Linux) that this deliberately does -// without. The failure mode is inert: git only rejects operations in a -// directory that both exists at this path and is a real repository, and -// safe.directory entries for a stale non-repo path do nothing. +// markSafe adds mountDir to git's global safe.directory when it is an +// existing directory. Failures are logged. Returns true on success. func markSafe(ctx context.Context, mountDir string, run gitRunner, log *slog.Logger) bool { info, err := os.Stat(mountDir) if err != nil || !info.IsDir() { diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index e427cffcb..8036828c5 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -48,11 +48,7 @@ type sdkSubscription interface { // worker has no JetStream consumer. type Transport struct { conn *natsio.Conn - // state is the long-lived State Store contract client and closeState its - // connection cleanup. Store() dials nothing per call; it wraps this one - // client with the per-call timeout each caller supplies. Connect refuses - // to construct a Transport without one (the legacy NATS storerpc path is - // deleted), so it is never nil in a real worker. + // state is the State Store client; closeState closes its connection. state *staterpc.Client closeState func() @@ -60,11 +56,7 @@ type Transport struct { flush func(time.Duration) error } -// Connect establishes the worker's core-NATS connection and, when -// Config.StateStoreURL is set, a long-lived gRPC connection to the State -// Store. A non-loopback -// StateStoreURL with no token fails closed rather than dialing an -// unauthenticated remote store. +// Connect opens the worker's NATS connection and its State Store connection. func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, error) { if log == nil { log = slog.New(slog.DiscardHandler) @@ -132,23 +124,13 @@ type RemoteTrees interface { Push(ctx context.Context) error } -// The top-level forgerpc and worktreerpc packages remain legacy infrastructure -// with an open final destination. This adapter is their single worker -// composition point until that broader migration is approved. The State Store -// is the exception: it is a gRPC contract (staterpc), and this adapter's -// Store() returns that client directly. - // Forger constructs the identity-scoped forge RPC client. func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forger { return &forgerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity} } -// Store constructs the workflow store RPC client over the long-lived State -// Store client. Each call is bounded -// by timeout when the caller's context carries no deadline of its own. The -// legacy NATS storerpc path is deleted; a transport without a -// State Store client cannot reach Store() because Connect refused to build -// one. +// Store returns the State Store client, bounding each call by timeout when +// ctx has no deadline. func (t *Transport) Store(timeout time.Duration) workflow.Store { return deadlineStore{Store: t.state, timeout: timeout} } diff --git a/internal/infrastructure/bindingcipher/cipher.go b/internal/infrastructure/bindingcipher/cipher.go index 50b201859..b8b9904df 100644 --- a/internal/infrastructure/bindingcipher/cipher.go +++ b/internal/infrastructure/bindingcipher/cipher.go @@ -33,11 +33,7 @@ type Domain struct { } var ( - // BindingDomain seals binding.Binding.Secret and source webhook - // secrets -- the original domain this package was built for. It is - // deliberately NOT row-bound: these are random HMAC keys, never used - // as lookup keys, so cross-row relocation within the domain is not a - // meaningful attack. + // BindingDomain seals binding and source webhook secrets. Not row-bound. BindingDomain = Domain{marker: "arcie-binding", aad: []byte("arcie-binding-secret")} // HarnessSecretDomain seals harness OAuth token sets // -- its own @@ -69,22 +65,16 @@ type BindingCipher interface { DecryptDomain(d Domain, envelope string) (string, error) } -// bindingCipher is the AES-256-GCM BindingCipher. Keys are derived as -// SHA-256(resolved material) -- 32 bytes of high-entropy input re-shaped to a -// 256-bit key, so no passphrase-stretching KDF (Argon2id) is required. The -// active key seals new writes; previous keys are retained for decryption only -// during rotation. +// bindingCipher is AES-256-GCM with keys SHA-256(material). The active key +// seals; previous keys only decrypt. type bindingCipher struct { activeKey []byte activeFingerprint string keys map[string][]byte // fingerprint(hex[:16]) → 32-byte AES key } -// NewBindingCipher builds a bindingCipher over the active key material and any -// previous (decrypt-only) material. Key identity is intrinsic to the material -// (the SHA-256 fingerprint), so rotation needs no manual key IDs. It is a pure -// constructor: it never reads the secret registry, which the composition root -// owns. +// NewBindingCipher builds a cipher over the active and previous key +// material. Keys are identified by fingerprint. func NewBindingCipher(active string, previous []string) (*bindingCipher, error) { if active == "" { return nil, errors.New("store: binding cipher requires a non-empty active key") @@ -138,11 +128,8 @@ func (c *bindingCipher) EncryptDomain(d Domain, plaintext string) (string, error c.activeFingerprint, base64.RawURLEncoding.EncodeToString(payload)), nil } -// DecryptDomain parses an envelope sealed under d, looks up the key by its -// embedded fingerprint, and returns the plaintext. A fingerprint not present -// in the keyring (an old key dropped from config), or an envelope sealed -// under a different domain's marker/AAD, fails rather than returning -// garbage. +// DecryptDomain decrypts an envelope sealed under d. An unknown key or wrong +// domain is an error. func (c *bindingCipher) DecryptDomain(d Domain, envelope string) (string, error) { parts := strings.SplitN(envelope, ":", 4) if len(parts) != 4 || parts[0] != d.marker || parts[1] != bindingEnvelopeVersion { diff --git a/internal/infrastructure/captureintake/receiver.go b/internal/infrastructure/captureintake/receiver.go index df78d3885..4fa976f14 100644 --- a/internal/infrastructure/captureintake/receiver.go +++ b/internal/infrastructure/captureintake/receiver.go @@ -1,15 +1,5 @@ -// Package captureintake is the HTTP receiver for inbound webhooks archie has -// no binding for yet: it persists what arrives so an operator can inspect it -// and build one. -// -// It belongs to the process that owns work intake, not to the dashboard that -// displays captures. It served from the dashboard's listener while the two -// shared a process; the split gives the read to the dashboard, over the State -// Store, and keeps the write here. From the cutover -// change in the same bead it is a persistence shim over the State Store -// contract mounted by the UI process -- the only dashboard listener left -- -// while the daemon's binding-dispatch loop consumes captures from the same -// store: the HTTP front door moved without moving work intake. +// Package captureintake receives and stores inbound webhooks for inspection +// and binding dispatch. package captureintake import ( @@ -70,12 +60,9 @@ func (rc *Receiver) Register(mux *http.ServeMux) { mux.HandleFunc(Path, rc.ServeHTTP) } -// ServeHTTP accepts an inbound webhook POST and persists it. On a signed -// source only a valid HMAC under the source's secret marks the event -// authenticated; on an approved unsigned source every event is marked -// unsigned. Anything else is still captured and visible in the inspector, -// but is neither, so the dispatch loop's check (binding.Matcher.Matches over -// CapturedEvent.Dispatchable) never starts a task from it. +// ServeHTTP stores an inbound webhook. A valid HMAC on a signed source marks +// it authenticated; an approved unsigned source marks it unsigned; other +// events are stored but never dispatch. func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { if rc.Captures == nil { http.Error(w, "capture not configured", http.StatusServiceUnavailable) @@ -83,14 +70,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { } path := r.PathValue("source") - // webhookguard.RateLimiter's bucket map assumes a bounded, operator- - // registered key space (see its doc comment) -- it is never evicted, and - // a fresh key starts with a full burst allowance. source is an - // unregistered, attacker-chosen URL segment by design (this endpoint - // exists to capture senders archie has no registration for yet), so - // keying on it would let a single attacker rotate a new "source" on - // every request to bypass the limit entirely and grow the bucket map - // without bound. Remote address is the bounded identity available here. + // Rate limit by remote address; the source segment is attacker-chosen. if rc.Limiter != nil && !rc.Limiter.Allow(remoteAddrHost(r)) { http.Error(w, "rate limit exceeded", http.StatusTooManyRequests) return @@ -169,11 +149,9 @@ func (rc *Receiver) resolveSource(r *http.Request, path string) *source.Source { return src } -// verify decides how an event on src may dispatch. An approved unsigned -// source marks it unsigned. Otherwise a valid HMAC under the source's secret -// authenticates it: X-Hub-Signature-256 first, X-Signature-256 as fallback. -// A source with no secret yet authenticates nothing, since an empty key is -// one anybody can sign with. +// verify reports how an event on src may dispatch: unsigned for an approved +// unsigned source, else authenticated by a valid X-Hub-Signature-256 or +// X-Signature-256. A source with no secret authenticates nothing. func verify(src *source.Source, h http.Header, body []byte) (authenticated, unsigned bool) { switch { case src == nil: diff --git a/internal/infrastructure/configuration/tomlwrite/tomlwrite.go b/internal/infrastructure/configuration/tomlwrite/tomlwrite.go index 0ac8eecc3..91a416fc2 100644 --- a/internal/infrastructure/configuration/tomlwrite/tomlwrite.go +++ b/internal/infrastructure/configuration/tomlwrite/tomlwrite.go @@ -1,33 +1,7 @@ -// Package tomlwrite patches specific keys in a TOML document without -// disturbing anything else in it -- including comments, blank lines, and -// key order. -// -// # Why not decode/re-marshal -// -// BurntSushi/toml does not round-trip comments: a Decode followed by an Encode -// reproduces the data but discards every comment. config.example.toml carries -// substantial documentation as inline comments that operators are meant to read -// and hand-edit, and archied setup must be able to write into that same file -- -// and be re-run later to change one value -- without deleting it. A full -// re-marshal was rejected for that reason. -// -// # The chosen strategy -// -// Apply treats the document as text and edits only the lines a caller -// names. For each requested key it looks, in order, for: an active -// "key = value" line in the target table (replace the value, keep any -// trailing inline comment); a commented-out "# key = value" line in the -// target table (uncomment the table header and the line, then replace the -// value); or, failing both, a place to add the key (the end of the -// table's existing content, or a brand new table appended at the end of -// the document). Every line Apply was not asked to touch is copied through -// unchanged, byte for byte. -// -// It only understands single-line scalar and inline-table values (strings, -// numbers, booleans, `{ engine = "...", key = "..." }` secret refs), which -// covers everything archied setup writes. Multi-line arrays and -// [[array-of-tables]] entries are not targets for Apply; other code paths (e.g. -// adding a [[repos]] entry) must not use it. +// Package tomlwrite edits keys in a TOML document as text, leaving comments, +// blank lines and order untouched. Apply replaces an active key, uncomments +// a commented one, or appends it to its table. Only single-line values are +// supported. package tomlwrite import ( @@ -38,13 +12,8 @@ import ( "strings" ) -// Edit is one key = value change to make within a TOML document. -// -// Table is the dotted path to the table the key lives in ("" for the -// document root, "forge", "providers.openai", "chat.telegram", ...). Value -// is the exact TOML literal to write -- callers are responsible for -// quoting it themselves; see [String] and [Ref] for the two shapes archied -// setup needs. +// Edit sets one key in a TOML table. Table is a dotted path ("" for the +// root). Value is a literal TOML value; see String and Ref. type Edit struct { Table string Key string @@ -71,11 +40,7 @@ var ( commentedKeyRe = regexp.MustCompile(`^(\s*)#\s?([A-Za-z0-9_.]+)(\s*=\s*)(.*)$`) ) -// Generate applies edits to template and returns the result: a config a -// human can read and hand-edit afterwards, since it is the documented -// template with only the requested values filled in. archied setup calls -// this on first run, with configtemplate.Example as template, and calls -// Apply directly against the existing file on every later run. +// Generate applies edits to template. func Generate(template []byte, edits []Edit) ([]byte, error) { return Apply(template, edits) } diff --git a/internal/infrastructure/controlplanerpc/client.go b/internal/infrastructure/controlplanerpc/client.go index 95baea6f7..e844ac6f7 100644 --- a/internal/infrastructure/controlplanerpc/client.go +++ b/internal/infrastructure/controlplanerpc/client.go @@ -1,8 +1,5 @@ -// Package controlplanerpc is the Messaging Service side of the control-plane -// contract: the generic resource client, the channel-settings document it -// projects, and the wire sentinels both sides match on. It exists so a service -// that only reads stored settings does not link the store-backed server, the -// workflow engine or the SQLite driver. +// Package controlplanerpc is the control-plane resource client and the +// channel-settings document. package controlplanerpc import ( @@ -45,13 +42,6 @@ func NewClient(conn grpc.ClientConnInterface) *Client { func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { return &Client{rpc: 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. - // ResourceReader is the read side of the control-plane client: one resource // query per kind. The store-backed server implements it too, which is why the // layering functions here are shared with internal/app/controlplane. @@ -110,15 +100,6 @@ func RuntimeChatConfigFrom(ctx context.Context, reader ResourceReader, base conf return out, version, 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. - // ClientError maps a gRPC status onto the wire sentinels both sides match on. // It is exported because the store-backed server's own client methods need the // same mapping, and a second copy would be a second contract. diff --git a/internal/infrastructure/controlplanerpc/request.go b/internal/infrastructure/controlplanerpc/request.go index 3c8c492bb..a043223d9 100644 --- a/internal/infrastructure/controlplanerpc/request.go +++ b/internal/infrastructure/controlplanerpc/request.go @@ -7,12 +7,8 @@ import ( "github.com/samcharles93/archie-core/internal/domain/org" ) -// Every control-plane request acts in one org's copy of a resource. The org -// travels on the request context (org.WithOrg), attached once by whatever -// established the caller's principal, and these constructors are the one place -// it is read back: a call site cannot send the wrong org, and a new call site -// cannot forget it. org.OrgFromContext yields the default org when the context -// carries none, so a process with no principal still acts where it always did. +// Requests carry the org from the context (org.WithOrg), defaulting to the +// default org. // QueryRequest builds a resource query for the caller's org. func QueryRequest(ctx context.Context, kind string) *pb.QueryRequest { diff --git a/internal/infrastructure/controlplanerpc/vocabulary.go b/internal/infrastructure/controlplanerpc/vocabulary.go index a2782c588..2c7a1e747 100644 --- a/internal/infrastructure/controlplanerpc/vocabulary.go +++ b/internal/infrastructure/controlplanerpc/vocabulary.go @@ -9,13 +9,8 @@ import ( "github.com/samcharles93/archie-core/internal/config" ) -// ChannelSettings is the Channel settings resource document. Its shape IS the -// contract the Web UI edits, so every nested object here is defined by this -// file with explicit snake_case json tags and never handed an internal config -// struct. Encoding/json falls back to Go field names when a tag is absent, -// which is how "Window", "MaxRequests", "ListenAddr" and "RelayAddr" reached -// operators in the first place -- a shape belonging to TOML, not to this -// document. +// ChannelSettings is the channel-settings resource document, with +// snake_case JSON keys. type ChannelSettings struct { Operator string `json:"operator"` ShowToolCalls bool `json:"show_tool_calls"` @@ -88,11 +83,8 @@ func (r *RateLimitSettings) UnmarshalJSON(data []byte) error { return nil } -// DecodeRenamingLegacyKeys decodes an object into v after renaming each key in -// legacy to the spelling v documents, and stays strict about everything else. -// The strictness is the point: dropping unknown keys would let a typo -// ("windows") read as "unset" and silently disable the setting, which is the -// class of failure this shape exists to end. +// DecodeRenamingLegacyKeys decodes data into v after renaming legacy keys. +// Unknown keys are errors. func DecodeRenamingLegacyKeys(data []byte, legacy map[string]string, v any) error { var raw map[string]json.RawMessage if err := json.Unmarshal(data, &raw); err != nil { @@ -117,11 +109,8 @@ func DecodeRenamingLegacyKeys(data []byte, legacy map[string]string, v any) erro return decoder.Decode(v) } -// ChannelDuration is a duration as this document writes it: the human string -// the file accepts ("1m0s", the same spelling config.Duration emits), never a -// nanosecond count. It still reads the count, because every document written -// before this shape existed carries one, and reading both forms is what lets -// those documents keep working without being re-saved. +// ChannelDuration is written as a duration string; it also reads a +// nanosecond count. type ChannelDuration time.Duration // Std is the standard-library duration, for arithmetic and for the marker diff --git a/internal/infrastructure/crondelivery/contract.go b/internal/infrastructure/crondelivery/contract.go index a65b2dc31..12065650a 100644 --- a/internal/infrastructure/crondelivery/contract.go +++ b/internal/infrastructure/crondelivery/contract.go @@ -1,25 +1,5 @@ -// Package crondelivery is the delivery half of archied's cron/scheduling -// capability: it turns a due job into an effect. -// -// The domain's ticker engine (internal/domain/scheduling) decides *when* a job -// runs and hands over a scheduling.Job — identity and dispatch policy, nothing -// more. This package owns what happens next, and it is the only place that -// knows a job store exists. The engine sees one Runner (the Router); the -// deliveries it dispatches to are a mapping this package holds. -// -// Three surfaces: -// -// - ChatCourier sends a job's payload text to a chat. -// - WorkflowTask submits a job as a unit of work. -// - Router picks between them per job kind, and is the single Runner the -// engine is given. -// -// No implementation here talks to a channel, a broker or a forge. Each takes -// the effect it needs as an injected function or narrow interface, so which -// chat transport carries a message — and which intake path receives a task — -// stays the deployment's decision (the wiring slice composes the real ones), -// not the cron's. That is also what keeps this package testable without a -// network. +// Package crondelivery delivers due scheduled jobs: ChatCourier sends a chat +// message, WorkflowTask submits work, and Router picks one per job kind. package crondelivery import ( @@ -31,29 +11,14 @@ import ( "github.com/samcharles93/archie-core/internal/domain/scheduling" ) -// SpecLookup resolves a job id to its persisted spec. -// -// It is declared here (consumer-owned) rather than imported from the document's -// owner as a concrete type so this package depends on the one method it uses. -// scheduleResourceStore in internal/app/archied satisfies it as written, so a -// deployment passes that in. +// SpecLookup resolves a job id to its stored spec. type SpecLookup interface { // Get returns the job and whether it was found; the error is reserved // for I/O failures, matching scheduleResourceStore.Get. Get(ctx context.Context, id string) (scheduling.JobSpec, bool, error) } -// RunRecorder advances a job's schedule once a run has completed. It is -// declared here (consumer-owned) for the same reason SpecLookup is, and -// scheduleResourceStore satisfies it as written. -// -// MarkRun is the only step that moves a job's NextRun, so a store whose Due -// keeps reporting an already-completed job keeps handing it back on every -// tick: an interval job fires once per tick instead of once per interval. The -// record is written only for a successful run, matching the store's own -// contract that an interval or cron schedule fires "after the last successful -// run" -- a failed run retries at the tick rate rather than silently skipping -// its slot. +// RunRecorder advances a job's schedule after a successful run. type RunRecorder interface { // MarkRun records that id ran at runAt and advances NextRun to the // schedule's next firing. @@ -69,23 +34,10 @@ type RouterStore interface { RunRecorder } -// Courier sends one chat message. It is the whole outbound surface this -// package needs, and it is injected: the concrete channel client lives in the -// deployment, so an operator switching transports changes nothing here. That -// is how "the channel choice stays the operator's, not the cron's" is enforced -// — by construction, there is no channel to choose from here. -// -// An implementation must honour ctx: the engine bounds every run with a -// timeout and cancels on shutdown, and a courier that blocks through -// cancellation keeps the run in flight past the engine's own deadline. +// Courier sends one chat message. It must honour ctx. type Courier func(ctx context.Context, chatID, text string) error -// TaskSubmitter submits one unit of work to the work-intake path. -// -// identity is the submitting job's id; title and body are the job's detail and -// payload. It is narrow on purpose: the concrete publisher builds the -// work-intake envelope, because the envelope carries owner/repo/number fields -// only the deployment can know. This package carries no forge vocabulary. +// TaskSubmitter submits one unit of work. type TaskSubmitter interface { Submit(ctx context.Context, identity, title, body string) error } diff --git a/internal/infrastructure/crondelivery/router.go b/internal/infrastructure/crondelivery/router.go index fc73da673..664584c01 100644 --- a/internal/infrastructure/crondelivery/router.go +++ b/internal/infrastructure/crondelivery/router.go @@ -11,39 +11,21 @@ import ( "github.com/samcharles93/archie-core/internal/events" ) -// phaseDispatch names the step that failed on a KindJobError the Router emits. -// -// It is restated as a literal rather than referenced, because the engine's -// equivalent constant is unexported (internal/domain/scheduling's -// phaseDispatch). "dispatch" is a wire value on the event stream and this -// package must match it, so it is pinned here by value. +// phaseDispatch is the phase reported for a dispatch refusal; it matches the +// scheduling engine's value. const phaseDispatch = "dispatch" -// Router is the single Runner the engine is given. It resolves a due job's -// kind from its persisted spec and hands the job to that kind's runner, -// keeping the engine unaware that more than one delivery exists. Once a run -// has succeeded it also records the run, which is what moves a recurring job's -// NextRun. -// -// An unknown kind is refused, not failed. It is reported on the event stream -// as KindJobError with phase "dispatch" — naming the gate, so an operator can -// distinguish a misconfigured job from a broken one — and Run returns nil. -// Returning an error instead would have the engine emit it as a failed *run* -// (phase "run"), conflating the two, and would leave the job looking like it -// tried and broke on every tick. +// Router runs a due job with the runner for its kind and records successful +// runs. An unknown kind is reported as a dispatch KindJobError and Run +// returns nil. type Router struct { specs RouterStore runners map[string]scheduling.Runner sink scheduling.Sink } -// NewRouter builds the router over a spec lookup, its kind-to-runner mapping, -// and the sink its dispatch refusals are reported on. A nil sink disables -// emission — the router still refuses, it is just unobservable, the same -// tolerance the engine has for its own nil sink. -// -// An empty kind resolves to scheduling.KindChat, so a deployment only needs a -// mapping for the kinds it actually uses. +// NewRouter builds a router over specs and runners. A nil sink disables +// events. An empty kind is KindChat. func NewRouter(specs RouterStore, runners map[string]scheduling.Runner, sink scheduling.Sink) (*Router, error) { if specs == nil { return nil, errors.New("crondelivery: spec lookup must not be nil") @@ -79,16 +61,8 @@ func (r *Router) Run(ctx context.Context, job scheduling.Job) error { return r.recordRun(ctx, job) } -// recordRun advances the job's schedule after a successful run. Without it the -// store has no record that the job ran, so its NextRun stays in the past and -// Due reports the job again on every tick: a job scheduled hourly fires once -// per tick instead. -// -// A schedule kind with no recurring next run -- a one-shot -- reports -// scheduling.ErrScheduleUnsupported, which is the job's definition rather than a -// run failure, so it is swallowed. Anything else is returned: the run happened -// but the bookkeeping did not, and hiding that would leave the job silently -// re-firing. +// recordRun advances the job's schedule after a successful run. +// ErrScheduleUnsupported (a one-shot) is ignored. func (r *Router) recordRun(ctx context.Context, job scheduling.Job) error { if err := r.specs.MarkRun(ctx, job.ID, time.Now()); err != nil && !errors.Is(err, scheduling.ErrScheduleUnsupported) { return fmt.Errorf("crondelivery: record run of job %q: %w", job.ID, err) diff --git a/internal/infrastructure/crondelivery/runner.go b/internal/infrastructure/crondelivery/runner.go index b491511ac..ef72ee58c 100644 --- a/internal/infrastructure/crondelivery/runner.go +++ b/internal/infrastructure/crondelivery/runner.go @@ -29,12 +29,7 @@ func NewChatCourier(specs SpecLookup, courier Courier) (*ChatCourier, error) { return &ChatCourier{specs: specs, courier: courier}, nil } -// Run hydrates the job's spec and sends its payload text to its target chat. -// -// The pre-check matters as much as the error wrap: a cancelled run must produce -// no side effect, because the engine cancels on shutdown and a message sent -// after that is one nobody asked for. The courier's own ctx handling covers -// cancellation that arrives mid-send. +// Run sends the job's payload to its chat. A cancelled ctx sends nothing. func (c *ChatCourier) Run(ctx context.Context, job scheduling.Job) error { if err := ctx.Err(); err != nil { return err @@ -69,11 +64,7 @@ func NewWorkflowTask(specs SpecLookup, submitter TaskSubmitter) (*WorkflowTask, return &WorkflowTask{specs: specs, submitter: submitter}, nil } -// Run hydrates the job's spec and submits it as work. -// -// The title falls back to the job id when Detail is empty: a submitted task is -// how a human finds the job that created it, and an untitled one is -// unfindable. +// Run submits the job as work, titled by Detail or the job id. func (w *WorkflowTask) Run(ctx context.Context, job scheduling.Job) error { if err := ctx.Err(); err != nil { return err diff --git a/internal/infrastructure/drain/drain.go b/internal/infrastructure/drain/drain.go index 6b198f49d..d85b9f4ca 100644 --- a/internal/infrastructure/drain/drain.go +++ b/internal/infrastructure/drain/drain.go @@ -1,10 +1,5 @@ -// Package drain is the infrastructure implementation of drain-request -// detection. It reads the external marker file from disk and the OS identity -// facts that make up the current instantiation epoch, then hands the verdict -// to the domain's Decide function. -// -// It only reads. Deciding (and any shutdown consequence) belongs to the caller, -// so the daemon never drains itself from this package. +// Package drain reads the drain marker file and the current epoch and asks +// domain drain.Decide for a verdict. package drain import ( @@ -62,11 +57,8 @@ func readPid1Start() (int64, error) { return parseProcStat(string(data)) } -// parseProcStat extracts PID 1's start time (field 22, starttime) from the -// textual /proc/[pid]/stat record. The comm field (field 2) is wrapped in -// parentheses and may itself contain spaces or parentheses, so the record is -// split after the last closing parenthesis and field 22 is the 20th token -// there (post-paren token 0 is field 3, the state). +// parseProcStat returns field 22 (starttime) of a /proc/[pid]/stat record, +// parsing after the last ')'. func parseProcStat(stat string) (int64, error) { paren := strings.LastIndexByte(stat, ')') if paren < 0 { @@ -107,14 +99,8 @@ func New(markerPath string, epoch func() (drain.Epoch, error)) *Reader { return &Reader{path: markerPath, epoch: epoch} } -// Check returns the drain decision for the marker at the reader's path against -// the current epoch. -// -// A missing marker returns DecisionNone. The returned error is informational -- -// it exists so a caller can log why a request was not honoured -- but the -// decision is authoritative and always fails closed on an unrecoverable read -// (permission error, malformed JSON, unreadable epoch) so a broken marker can -// never drain the daemon. +// Check returns the drain decision for the marker. A missing marker is +// DecisionNone; any read failure is reported and never drains. func (r *Reader) Check() (drain.Decision, error) { data, err := os.ReadFile(r.path) if errors.Is(err, os.ErrNotExist) { diff --git a/internal/infrastructure/egress/credentials.go b/internal/infrastructure/egress/credentials.go index 5a9b840c0..ebeeeab70 100644 --- a/internal/infrastructure/egress/credentials.go +++ b/internal/infrastructure/egress/credentials.go @@ -14,13 +14,8 @@ import ( // it can tell a credential is wired without ever holding it. const Sentinel = "archie-proxy-managed" -// CredentialKind is how one run carries a credential service. The org's -// binding decides it, never the Kit's declaration: the sandbox kit spec lets -// one credential@1 declare apiKey and oauth together, meaning "whichever the -// host has bound" (docker/claude-code-kit declares both for anthropic, codex -// for openai). A service absent from a session's bound kinds is not carried -// at all, which is what refuses a required credential and skips an optional -// one. +// CredentialKind is how a run carries a credential service, decided by the +// org's binding. An absent service is not carried. type CredentialKind string const ( diff --git a/internal/infrastructure/egress/oauth.go b/internal/infrastructure/egress/oauth.go index dfd5e82e1..986330499 100644 --- a/internal/infrastructure/egress/oauth.go +++ b/internal/infrastructure/egress/oauth.go @@ -153,12 +153,9 @@ func (p *Proxy) injectOAuth(ctx context.Context, s *Session, r *http.Request, ho return nil } -// interceptOAuth handles one request to a granted rule's token endpoint -// whole. A refresh carrying the sentinel refresh token goes upstream with -// the stored real one; a login code exchange carries none and passes as -// sent. A successful response is captured to the store and reaches the -// container with sentinels in place of the real tokens, so a refreshed -// token is never returned to it. +// interceptOAuth proxies a token endpoint request, swapping the sentinel +// refresh token for the stored one. Successful responses are stored and +// returned to the container with sentinels. func (p *Proxy) interceptOAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, s *Session, rule oauthRule, scheme, target string) { body, err := io.ReadAll(io.LimitReader(r.Body, maxTokenExchange)) if err != nil { diff --git a/internal/infrastructure/egress/proxy.go b/internal/infrastructure/egress/proxy.go index e39fd7cc6..862abafc2 100644 --- a/internal/infrastructure/egress/proxy.go +++ b/internal/infrastructure/egress/proxy.go @@ -80,12 +80,9 @@ type SessionOptions struct { Run string Org string Network *spec.PhasedNetwork - // Credentials is what the Kit's descriptor declares; Bound is how the run - // actually carries them, each service the run credential names mapped to - // the kind the org's binding gave it. Declared and bound are two separate - // facts, and neither widens the other: a rule may only fire for a service - // the run carries as that same kind, and a service the run carries not at - // all resolves as unbound whichever rule asks. + // Credentials are what the Kit declares; Bound maps each service the run + // carries to its kind. A rule fires only for a service bound with the same + // kind. Credentials []spec.CredentialCapability Bound map[string]CredentialKind } diff --git a/internal/infrastructure/embedding/embedding.go b/internal/infrastructure/embedding/embedding.go index e10f3ad62..7d90241b2 100644 --- a/internal/infrastructure/embedding/embedding.go +++ b/internal/infrastructure/embedding/embedding.go @@ -41,18 +41,9 @@ type Options struct { Timeout time.Duration } -// New builds an embedding client from cfg.Models[Role] and the matching -// cfg.Providers entry. It reports (nil, false) rather than an error when -// the capability is not usable right now -- no role configured, an unknown -// provider, an unsupported provider class, or a missing/blank credential -// -- per the credential-missing-degrades-not-fatal rule (AGENTS.md): -// callers must skip the capability, never fail daemon startup or an -// unrelated call, over this. -// -// cfg.Providers is expected to already have secret refs resolved to -// APIKeyEnv (see internal/app/archied/provider_secrets.go's -// resolveProviderSecrets), the same precondition agentexec.NewRuntime -// relies on for chat models. +// New builds an embedding client from cfg.Models[Role] and its provider. It +// returns (nil, false) when unavailable. Provider secrets must already be +// resolved. func New(cfg config.Config, opts Options) (domainembedding.Client, bool) { getenv := opts.Getenv if getenv == nil { @@ -103,12 +94,8 @@ func parseModelRef(ref string) (providerID, modelID string, ok bool) { return providerID, modelID, true } -// newSDKProvider constructs the ai-sdk embed.Provider for a config class. -// Only classes matching config.Provider's shape (APIKey/BaseURL, no -// provider-specific extra fields) are supported -- azure's Deployment -// requirement, for example, has no field to source it from yet, so an -// "azure" class degrades like any other unsupported class rather than -// gaining a special-cased partial wiring. +// newSDKProvider builds the ai-sdk embed provider for class. Unsupported +// classes, including azure, return an error. func newSDKProvider(class, apiKey, baseURL string, httpClient *http.Client) (sdkembed.Provider, error) { switch class { case "openai", "openai-compatible": diff --git a/internal/infrastructure/gatewayrpc/auth.go b/internal/infrastructure/gatewayrpc/auth.go index 2e3a18013..f6ec9d252 100644 --- a/internal/infrastructure/gatewayrpc/auth.go +++ b/internal/infrastructure/gatewayrpc/auth.go @@ -17,13 +17,8 @@ import ( // token lifecycle. const tokenMetadataKey = "gateway-token" -// TargetIsLoopback reports whether addr's host is a loopback address. Both -// literal loopback IPs (127.0.0.1, ::1) and the "localhost" hostname count; -// everything else (including the wildcard 0.0.0.0 and DNS names) is treated -// as network-reachable and therefore non-loopback. It applies to a listen -// address and a dial target alike -- the same host decides both. It mirrors -// staterpc.TargetIsLoopback; the two transports keep their own copy so -// neither adapter imports the other. +// TargetIsLoopback reports whether addr's host is a loopback IP or +// "localhost". func TargetIsLoopback(addr string) (bool, error) { host, _, err := net.SplitHostPort(addr) if err != nil { diff --git a/internal/infrastructure/gatewayrpc/dial.go b/internal/infrastructure/gatewayrpc/dial.go index 8092bd9e7..0ee42b1f4 100644 --- a/internal/infrastructure/gatewayrpc/dial.go +++ b/internal/infrastructure/gatewayrpc/dial.go @@ -8,15 +8,9 @@ import ( "google.golang.org/grpc/credentials/insecure" ) -// Dial returns a chat contract client for target, the standalone -// archie-gateway process, applying the transport security boundary: a -// loopback target dials insecure with no credential, while a non-loopback -// target requires a Bearer [REDACTED] and fails closed without one. The returned -// cleanup closes the connection. -// -// The rule lives here rather than in a composition root so the server side -// (which decides whether to install the token interceptors) and every client -// that dials it share one implementation. It mirrors staterpc.Dial. +// Dial returns a Gateway chat client for target. A loopback target dials +// insecure; any other target requires a token. The cleanup closes the +// connection. func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) { target = strings.TrimSpace(target) if target == "" { diff --git a/internal/infrastructure/gatewayrpc/store_client.go b/internal/infrastructure/gatewayrpc/store_client.go index f58279bc6..cd4923405 100644 --- a/internal/infrastructure/gatewayrpc/store_client.go +++ b/internal/infrastructure/gatewayrpc/store_client.go @@ -11,14 +11,8 @@ import ( var _ messaging.SessionStore = (*StoreClient)(nil) -// StoreClient implements messaging.SessionStore over the chat service's -// session-store RPCs. It is separate from Client (the ChatContract view) -// because the two contracts serve different reads over the same messages. -// -// Role does not cross the wire (the proto is unchanged by the messaging -// migration). Both sides derive it from the owning session instead -- the -// server on write, this client on read -- so they agree without a proto -// change. +// StoreClient implements messaging.SessionStore over the Gateway's session +// RPCs. Role is derived from the session. type StoreClient struct{ client pb.ChatServiceClient } func NewStoreClient(conn grpc.ClientConnInterface) *StoreClient { diff --git a/internal/infrastructure/gatewayrpc/task_action_errors.go b/internal/infrastructure/gatewayrpc/task_action_errors.go index 3678ba1e1..3ee8930a9 100644 --- a/internal/infrastructure/gatewayrpc/task_action_errors.go +++ b/internal/infrastructure/gatewayrpc/task_action_errors.go @@ -10,12 +10,8 @@ import ( "github.com/samcharles93/archie-core/internal/domain/taskactions" ) -// taskActionCodes pairs each sentinel the daemon's action service reports -// with the gRPC code that carries it. The dashboard picks its HTTP status by -// matching these (404, 409, 503), and gRPC transports a code and a string, -// not a Go error, so the class travels as the code and is restored on -// arrival. Adding a sentinel a caller matches on without adding it here -// silently degrades that case to a 500. +// taskActionCodes maps task-action sentinels to the gRPC codes that carry +// them. var taskActionCodes = []struct { code codes.Code err error diff --git a/internal/infrastructure/gatewayrpc/values.go b/internal/infrastructure/gatewayrpc/values.go index a12af125c..3f088ac17 100644 --- a/internal/infrastructure/gatewayrpc/values.go +++ b/internal/infrastructure/gatewayrpc/values.go @@ -177,12 +177,7 @@ func intPointer(v *int64) *int { return &n } -// attachmentProtoList renders a message's attachments in wire shape for the -// stored-history and outbound-event directions. Data is deliberately -// unmapped: those directions must not carry a turn's bytes, and a persisted -// record strips them too. An attachment with no fields beyond Data would -// produce an empty wire message, which is still the honest encoding of -// "metadata was stripped", and never happens for a real attachment. +// attachmentProtoList converts attachments without their Data. func attachmentProtoList(media []messaging.MediaAttachment) []*pb.Media { if len(media) == 0 { return nil @@ -197,11 +192,7 @@ func attachmentValueList(list []*pb.Media) []messaging.MediaAttachment { return mapValues(list, attachmentValue) } -// inboundAttachmentProtoList renders a turn's attachments for the inbound -// request. Unlike the stored direction, Data rides along: the channel -// frontend downloads the file, but the Gateway process that runs the turn -// never holds the platform credential, so the bytes have no other way to -// reach the model. +// inboundAttachmentProtoList converts attachments including their Data. func inboundAttachmentProtoList(media []messaging.MediaAttachment) []*pb.Media { if len(media) == 0 { return nil diff --git a/internal/infrastructure/kit/credential_file.go b/internal/infrastructure/kit/credential_file.go index 2b9fa9a89..58cb3de39 100644 --- a/internal/infrastructure/kit/credential_file.go +++ b/internal/infrastructure/kit/credential_file.go @@ -9,11 +9,7 @@ import ( "github.com/docker/sandbox-kit-spec/v3/spec" ) -// Credential-file placeholders, the vocabulary the Kit spec's -// credentialFile.structure declares. A leaf may reference the token -// sentinels as a whole value or inside a larger string; ExpiresAt (a number) -// and Scopes (an array) may only be the whole value, and PrimaryApiKey's -// enclosing key is dropped rather than substituted. +// Credential-file placeholders. const ( accessPlaceholder = "{{.AccessToken}}" refreshPlaceholder = "{{.RefreshToken}}" @@ -28,11 +24,8 @@ const ( credentialFileMode = "0600" ) -// renderCredentialFile renders c's oauth.credentialFile: the declared structure -// with the Kit's sentinels substituted for the token placeholders, the stored -// token set's scopes for {{.Scopes}} and its expiry for {{.ExpiresAt}}, encoded -// in the declared format. facts is the only thing the renderer receives about -// the stored token set, so a real token cannot reach the file. +// renderCredentialFile renders c's oauth credential file with sentinels for +// tokens and the stored scopes and expiry. func renderCredentialFile(c spec.CredentialCapability, facts OAuthFacts) (string, error) { cf := c.OAuth.CredentialFile var sentinels spec.Sentinels @@ -64,11 +57,7 @@ func substitutePlaceholders(v any, sentinels spec.Sentinels, scopes []string, ex case map[string]any: out := make(map[string]any, len(t)) for k, e := range t { - // {{.PrimaryApiKey}}'s spec case is that its ENCLOSING KEY is omitted - // when no key is captured. archie resolves a service key only to fill - // the egress grant and the container holds egress.Sentinel, so there - // is never a key to render here: drop the key, never empty it (absent - // and empty are different bugs). Do not "fix" this into a value. + // No key is ever captured, so drop the enclosing key. if s, ok := e.(string); ok && s == primaryKeyPlaceholder { continue } diff --git a/internal/infrastructure/kit/kit.go b/internal/infrastructure/kit/kit.go index f4ac4865d..eef6417e9 100644 --- a/internal/infrastructure/kit/kit.go +++ b/internal/infrastructure/kit/kit.go @@ -1,8 +1,5 @@ -// Package kit decides whether archie can run a harness packaged as Kit v3 -// images, and what it runs with. Descriptor grammar, validation and -// composition belong to the Kit spec package; this package owns only the -// runtime's half of the contract: which capability types archie implements, -// and the refusals that keep the host's guarantees intact. +// Package kit decides whether archie can run a Kit v3 harness and with what +// capabilities. package kit import ( @@ -151,12 +148,8 @@ func FromMerge(merged *spec.MergeResult) (*Plan, error) { return plan, nil } -// ValidateNeeds rejects a Plan that cannot meet what the workflow's stages -// declared they need: a -// gate that may retry needs the Kit's agent-sessions resume verb, because -// archie resumes the session with the gate's output rather than starting -// over. gateRetries is zero for a workflow with no gated stage, which no -// Kit composition can fail to meet. +// ValidateNeeds rejects a Plan without a resume verb when the gate may +// retry. func ValidateNeeds(plan *Plan, gateRetries int) error { if gateRetries > 0 && (plan.Sessions == nil || len(plan.Sessions.Resume) == 0) { return fmt.Errorf("needs.gate_retries is %d, but the kit declares no %s resume verb to retry with", gateRetries, typeAgentSessions) diff --git a/internal/infrastructure/kit/launch.go b/internal/infrastructure/kit/launch.go index 4b10a2edf..128b45fed 100644 --- a/internal/infrastructure/kit/launch.go +++ b/internal/infrastructure/kit/launch.go @@ -59,12 +59,8 @@ type LaunchParams struct { Execution string ProxyToken string CAPath string - // Bound keys each credential service this run carries to the kind the - // org's binding gave it (egress.CredentialKind). A service absent from - // this map is unbound: its mode variable says none, it renders no - // credential file, and the proxy refuses (required) or skips (optional) - // any request needing it. The map carries kinds, never values -- the real - // secret stays on the host. + // Bound maps each credential service the run carries to its kind. Values + // never leave the host. Bound map[string]egress.CredentialKind // OAuth is the non-secret facts of each bound OAuth credential's stored // token set, keyed by service, that a Kit's credentialFile renders: the @@ -162,11 +158,8 @@ func Assemble(p *Plan, img ImageConfig, params LaunchParams) (Launch, error) { return l, nil } -// credentialFiles renders the credential file of every OAuth-bound -// credential whose Kit declares one: the path and structure the Kit names, -// with the stored token set's scopes and expiry. A service bound as an API -// key renders none -- its Kit may carry the OAuth declaration too, but this -// run has no token set to put in the file. +// credentialFiles renders the credential file for each OAuth-bound +// credential that declares one. func credentialFiles(creds []spec.CredentialCapability, bound map[string]egress.CredentialKind, oauth map[string]OAuthFacts) ([]spec.File, error) { var files []spec.File for _, c := range creds { @@ -182,11 +175,8 @@ func credentialFiles(creds []spec.CredentialCapability, bound map[string]egress. return files, nil } -// contextFiles materializes agent-context@1: the workload's profile file -// beside the workspace, never in it, carrying an index of each Kit's body. -// A staged body is pointed at where the image holds it; an inline one is -// written to its own file beside the profile. The profile never inlines a -// Kit's text, so stacking Kits does not grow what the agent always loads. +// contextFiles writes agent-context@1: a profile file beside the workspace +// indexing each Kit's body. func contextFiles(p *Plan) ([]spec.File, error) { ac, err := spec.AgentContextOf(p.Capabilities) if err != nil || ac == nil || ac.Filename == "" { diff --git a/internal/infrastructure/kitrun/launcher.go b/internal/infrastructure/kitrun/launcher.go index 136bff16b..3b3e6a58e 100644 --- a/internal/infrastructure/kitrun/launcher.go +++ b/internal/infrastructure/kitrun/launcher.go @@ -61,13 +61,8 @@ type Launcher struct { // Kit container: the worker's own binary and the egress CA. AgentBinary string CAFile string - // Config is read fresh on every Launch, never captured once at - // construction: credential bindings are their own live control-plane - // resource (controlplane.CredentialBindingsKind), so a binding added or - // changed after this daemon started must take effect on the very next - // dispatch, the same way an agent profile already does. A nil Secrets or - // Grants degrades every credential to unbound rather than panicking: a - // daemon with no Kit profile configured wires neither. + // Config is read on every Launch. Nil Secrets or Grants leave every + // credential unbound. Config *config.Holder Secrets SecretResolver Grants Grants @@ -91,11 +86,8 @@ type Request struct { Adapter string WorkDir string WorkerEnv []string - // GateRetries is the workflow's declared gate-retry budget - // (task.WorkflowNeeds.GateRetries); zero means no stage gates its - // result. A composition with no agent-sessions resume verb cannot meet - // a positive one, and Launch refuses it rather than starting a - // container no gate failure could ever resume. + // GateRetries is the workflow's gate-retry budget. Launch refuses a positive + // budget without a resume verb. GateRetries int // Org and GrantedServices are the dispatching identity's own facts. A Kit // credential resolves only where these agree with a configured @@ -181,23 +173,10 @@ func (l *Launcher) Launch(ctx context.Context, req Request) (*Run, error) { return run, nil } -// resolveCredentials computes the run's granted secrets -- the intersection -// of what the Kit composition declares, what config.CredentialBinding -// entries exist, and what the dispatching identity is granted and belongs -// to -- and resolves each to a real value. granted is the run/service -> -// value map for Grants.Grant; kinds is the service -> bound-kind map -// kit.Assemble renders the container's credential state from. A service -// failing any part of the intersection, or whose binding's secret does not -// resolve, is simply absent from both: it stays unbound, exactly as if -// credential@1 named a service nobody configured. -// -// The binding decides the kind, not the Kit's declaration: the sandbox kit -// spec lets one credential declare apiKey and oauth together, meaning -// "whichever the host has bound" (docker/claude-code-kit declares both for -// anthropic). A binding naming a secret is therefore this run's API key even -// when the Kit also declares OAuth, and a binding naming none is the org's -// stored OAuth token set, carried with no value because the proxy reads the -// tokens itself. +// resolveCredentials resolves the run's credentials: services declared by +// the Kit, bound in config, and granted to the identity's org. granted maps +// run/service to value; kinds maps service to bound kind. A binding with a +// secret is an API key; one without is the org's OAuth token set. func (l *Launcher) resolveCredentials(req Request, creds []spec.CredentialCapability) (granted map[string]string, kinds map[string]egress.CredentialKind) { granted = map[string]string{} kinds = map[string]egress.CredentialKind{} @@ -217,11 +196,7 @@ func (l *Launcher) resolveCredentials(req Request, creds []spec.CredentialCapabi bindings := config.ContainerConfig{Credentials: current}.BoundCredentials(req.Org, req.GrantedServices, declared) for service, binding := range bindings { if binding.Secret == (config.SecretRef{}) { - // The binding names no secret of its own. Only a Kit declaring - // OAuth gives the service a meaning then -- the org's captured - // token set. Anything else has nothing to carry and stays - // unbound, rather than resolving to an empty value the proxy - // would present as a credential. + // No secret: only OAuth gives the service a value. if !oauth[service] { continue } @@ -242,11 +217,8 @@ func (l *Launcher) resolveCredentials(req Request, creds []spec.CredentialCapabi return granted, kinds } -// oauthFacts reads the stored token set's scopes and expiry for each -// OAuth-bound credential whose Kit renders a credential file. The store is -// read only for a service this run bound as OAuth, and only those facts -// leave here: the tokens stay behind, so the renderer has no way to write -// one. +// oauthFacts reads the stored scopes and expiry for each OAuth-bound +// credential with a credential file. func (l *Launcher) oauthFacts(ctx context.Context, org string, creds []spec.CredentialCapability, kinds map[string]egress.CredentialKind) (map[string]kit.OAuthFacts, error) { facts := map[string]kit.OAuthFacts{} for _, c := range creds { diff --git a/internal/infrastructure/memory/builtin/store.go b/internal/infrastructure/memory/builtin/store.go index ed6920899..224f1676c 100644 --- a/internal/infrastructure/memory/builtin/store.go +++ b/internal/infrastructure/memory/builtin/store.go @@ -1,8 +1,5 @@ -// Package builtin implements the built-in, file-backed MemoryProvider. It -// persists agent memory to MEMORY.md and USER.md as plain markdown, using -// "## " headers to delimit named sections. Content within a section is -// organized into blank-line-separated blocks; add/replace/remove act on -// those blocks and on substrings within them. +// Package builtin is a file-backed markdown memory store: "## " sections of +// blank-line-separated blocks. package builtin import ( diff --git a/internal/infrastructure/modelcatalog/catalog.go b/internal/infrastructure/modelcatalog/catalog.go index fc3be3cc4..6c97e9e75 100644 --- a/internal/infrastructure/modelcatalog/catalog.go +++ b/internal/infrastructure/modelcatalog/catalog.go @@ -1,10 +1,3 @@ -// Adapted from /work/apps/tau/internal/providers/snapshot/gen/main.go at -// b41dda42ef869cc919044ff4f23d7b568531c3f5. -// -// Deliberate mutations: -// - runtime startup fetch and disk fallback replace build-time generation; -// - every models.dev provider is eligible rather than a Tau-owned allowlist; -// - usable providers are derived from live environment and Archie overrides. package modelcatalog import ( diff --git a/internal/infrastructure/oidc/flow.go b/internal/infrastructure/oidc/flow.go index ad57100ab..a4a73df4d 100644 --- a/internal/infrastructure/oidc/flow.go +++ b/internal/infrastructure/oidc/flow.go @@ -58,14 +58,8 @@ func NewFlow(ctx context.Context, cfg Config, clientID, clientSecret, redirectUR }, nil } -// AuthCodeURL returns the provider URL to send a browser to, and the PKCE -// verifier the callback must present with the code. -// -// The audience is requested HERE, at the authorization endpoint, and not only at -// the token endpoint: a provider that returns the audience empty otherwise mints -// a token this dashboard must refuse, and the refusal looks like a signing fault -// rather than a missing request parameter. The verifier is generated by the -// library, not by archie. +// AuthCodeURL returns the provider URL to send a browser to, with the +// audience requested, and the PKCE verifier. func (f *Flow) AuthCodeURL(state string) (string, string) { codeVerifier := oauth2.GenerateVerifier() url := f.oauth.AuthCodeURL(state, diff --git a/internal/infrastructure/oidc/oidc.go b/internal/infrastructure/oidc/oidc.go index bb4a0f49b..1370c3626 100644 --- a/internal/infrastructure/oidc/oidc.go +++ b/internal/infrastructure/oidc/oidc.go @@ -77,13 +77,8 @@ func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Creden }, nil } -// subjectFor derives the caller a token asserts. -// -// A person's token carries sub, the provider's stable identifier for that person. -// A machine's token carries no sub at all and identifies its caller by client_id, -// so a machine identity is keyed on the client and one identity exists per client -// registration. A token asserting neither identifies nobody and is refused rather -// than being accepted as an anonymous caller. +// subjectFor returns the token's subject: sub for a person, client_id for a +// machine. A token with neither is refused. func subjectFor(issuer, subject, clientID string) (identity.Subject, error) { switch { case strings.TrimSpace(subject) != "": diff --git a/internal/infrastructure/prsource/archive.go b/internal/infrastructure/prsource/archive.go index 66c5a0991..ac39a6576 100644 --- a/internal/infrastructure/prsource/archive.go +++ b/internal/infrastructure/prsource/archive.go @@ -12,14 +12,8 @@ import ( "strings" ) -// extractTarGz extracts a gzipped tar stream into destDir, stripping a single -// common leading path component when every entry shares one (the wrapper -// directory GitHub's and Gitea's repository archives both add, named after the -// repo and ref -- e.g. "acme-widget-deadbeef/"). A.git entry is never written: -// PRSource's isolation contract requires the pipeline to read a.git-free -// snapshot, and a malicious PR's own tarball is exactly the input this cannot -// trust, so an entry escaping destDir via ".." or an absolute path is refused -// rather than silently written outside it. +// extractTarGz extracts a .tar.gz into destDir, stripping a common top-level +// directory. It skips .git and refuses paths escaping destDir. func extractTarGz(r io.Reader, destDir string) error { gz, err := gzip.NewReader(r) if err != nil { @@ -73,11 +67,7 @@ func planExtraction(tr *tar.Reader) (prefix string, entries []tarEntry, err erro top, _, hasSlash := strings.Cut(name, "/") switch { case !hasSlash && hdr.Typeflag != tar.TypeDir: - // A bare top-level file (no directory component at all) proves - // there is no single wrapper directory containing everything. A - // bare top-level *directory* entry is not this evidence -- it is - // exactly the wrapper directory's own header, which real - // archives include alongside the files nested under it. + // A top-level file means there is no wrapper directory. commonPrefix = "" first = false case first: @@ -99,11 +89,8 @@ func planExtraction(tr *tar.Reader) (prefix string, entries []tarEntry, err erro return commonPrefix, entries, nil } -// writeEntry writes one archive entry under destDir, with prefix (if any) -// stripped from its name. destDir is the absolute destination directory -// resolved by extractTarGz. Directories, regular files, and nothing else -// are written: a symlink or device entry from an untrusted PR archive is -// skipped rather than followed. +// writeEntry writes one directory or regular file under destDir; other +// entry types are skipped. func writeEntry(destDir, prefix string, e tarEntry) error { name := path.Clean(filepath.ToSlash(e.header.Name)) if name == "." || name == prefix { diff --git a/internal/infrastructure/prsource/mount.go b/internal/infrastructure/prsource/mount.go index 5b82a4d0d..7e44df8ef 100644 --- a/internal/infrastructure/prsource/mount.go +++ b/internal/infrastructure/prsource/mount.go @@ -17,21 +17,12 @@ import ( // package's reader cannot drift into two different paths. const PrefetchDirName = ".archie-pr-review" -// MountSource implements workflow.PRSource by reading data the daemon -// already fetched and wrote to disk before the container started, instead of -// calling the forge itself. This is how the sandboxed pipeline gets pull -// request data with no forge credential ever entering the container: the -// daemon (which holds the credential) runs Source (this package's -// HTTP-backed implementation) against baseDir before handing the container -// off, and the pipeline's Stage.Run bodies read the result through -// MountSource instead. -// -// baseDir holds three artifacts, all written by prefetchTo (the daemon-side -// counterpart, in internal/daemon): +// MountSource implements workflow.PRSource from data the daemon prefetched +// into baseDir: // // metadata.json -- {"title", "body", "head_sha"} -// diff.patch -- the raw unified diff -// snapshot/ -- the extracted repository tree at head_sha +// diff.patch -- the unified diff +// snapshot/ -- the repository tree at head_sha type MountSource struct { baseDir string } @@ -81,11 +72,8 @@ func (s *MountSource) Diff(_ context.Context, _, _ string, _ int) (string, error return string(data), nil } -// Snapshot copies the prefetched snapshot tree into destDir and returns the -// head SHA it was measured against. This is a local filesystem copy inside -// the same container -- no network call, no credential -- since the daemon -// already extracted the archive into baseDir/snapshot before the container -// started. +// Snapshot copies the prefetched snapshot into destDir and returns its head +// SHA. func (s *MountSource) Snapshot(_ context.Context, _, _ string, _ int, destDir string) (string, error) { m, err := s.readMetadata() if err != nil { diff --git a/internal/infrastructure/prsource/prsource.go b/internal/infrastructure/prsource/prsource.go index 444eb5bbf..4608aa12f 100644 --- a/internal/infrastructure/prsource/prsource.go +++ b/internal/infrastructure/prsource/prsource.go @@ -1,14 +1,5 @@ -// Package prsource implements workflow.PRSource: fetching an arbitrary -// external pull request's metadata, diff and a read-only snapshot of its -// head, for the pr-review pipeline. It is -// the PR-under-review counterpart to worktree.Manager's use as the task's -// own Trees: that path only ever reaches the task's own worktree, never a -// third-party PR being reviewed. -// -// Every call goes over the forge's HTTP API -- never a git-shell checkout. The -// pipeline's Stage.Run bodies execute inside the sandboxed archie-agent -// process, which holds no forge credential and no git-level credential either; -// a git clone would need one. +// Package prsource fetches a pull request's metadata, diff and head snapshot +// over the forge HTTP API. package prsource import ( @@ -19,11 +10,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow" ) -// PullRequest is the pull request fields Metadata, Diff and Snapshot need: -// title, body, and the head commit SHA the diff's line numbers and the -// snapshot are both measured against. It mirrors forge.PullRequest's shape -// so callers can pass that type directly without this package importing -// internal/forge. +// PullRequest is the PR's title, body and head SHA. type PullRequest struct { Title string Body string diff --git a/internal/infrastructure/readiness/probes.go b/internal/infrastructure/readiness/probes.go index 0b1b0f9af..3eb1614c3 100644 --- a/internal/infrastructure/readiness/probes.go +++ b/internal/infrastructure/readiness/probes.go @@ -1,13 +1,4 @@ -// Package readiness implements the readiness probes declared by -// internal/domain/health. Each probe is a thin adapter over a real subsystem -// dependency: it answers with a live, current result rather than a constant, -// so an operator calling /health/detailed sees the daemon's true state. -// -// The probes are deliberately dependency-light and injectable. Each takes -// the narrowest useful shape -- an interface it defines, a function, or a -// value -- so a probe never reaches into the daemon or a broad registry for -// its inputs. Composition root wiring (internal/app/archied) builds the -// concrete values and assembles the domain Registry. +// Package readiness implements the health probes. package readiness import ( @@ -59,11 +50,8 @@ func (p *StoreProbe) Check(ctx context.Context) health.Result { // --- remote contract --- -// ContractProbe reports whether a service this process consumes over the wire -// answers a cheap call within a bounded timeout. It is the readiness signal -// available to a process that depends on a service it does not own: the probe -// consumes the dependency's own result and never inspects its manager, registry -// or database. +// ContractProbe checks that a remote service answers a cheap call within a +// timeout. type ContractProbe struct { ProbeName string Timeout time.Duration @@ -210,16 +198,8 @@ func NewDiskProbeTargets(targets []DiskTarget) *DiskProbe { func (p *DiskProbe) Name() string { return "disk" } -// reduceTargets collapses the configured targets to one per path: the first -// target seen for a path wins its position, and the result keeps the strictest -// requirement any target placed on that path. -// -// Position is what makes this necessary rather than using a plain set. With -// root, an optional /var, then a required data path that resolves to /var, the -// optional /var is the target that survives dedup -- and its optional rules -// then apply to a path the daemon requires, so a vanished required path is -// skipped as "optional absent" and the probe reports OK. Choosing the required -// target (and its name) keeps the failure visible and correctly attributed. +// reduceTargets keeps one target per path, in first-seen position, with the +// strictest requirement for that path. func reduceTargets(targets []DiskTarget) []DiskTarget { index := make(map[string]int, len(targets)) out := make([]DiskTarget, 0, len(targets)) diff --git a/internal/infrastructure/sessioncurator/adapter.go b/internal/infrastructure/sessioncurator/adapter.go index 2ed60a0a9..08b012e22 100644 --- a/internal/infrastructure/sessioncurator/adapter.go +++ b/internal/infrastructure/sessioncurator/adapter.go @@ -21,14 +21,8 @@ type Adapter struct { agentID string } -// NewAdapter builds an Adapter that reports agentID as the agent owning -// every session it returns, so the curator addresses agent-user memory to -// the same agent a chat turn reads it back from (the composition's -// configured bot user, the value gateway.TurnRunnerConfig.BotUser carries). -// A session record's own Source.BotUser is deliberately not used for this: -// it is the router's session-resolution match key, and empty in a -// single-identity deployment. Roles come from the canonical records the -// store returns, so no bot identity is needed to derive them. +// NewAdapter returns an Adapter that reports agentID as every session's +// agent. func NewAdapter(store gateway.SessionStore, agentID string) *Adapter { return &Adapter{store: store, agentID: agentID} } diff --git a/internal/infrastructure/sessioncurator/sessioncurator.go b/internal/infrastructure/sessioncurator/sessioncurator.go index af2b8d35c..1f003447a 100644 --- a/internal/infrastructure/sessioncurator/sessioncurator.go +++ b/internal/infrastructure/sessioncurator/sessioncurator.go @@ -18,13 +18,8 @@ const Name = "session-memory" // written. const ActionExtracted = "memory.extracted" -// ActionSkipped records a session the pass could not address, so nothing was -// written for it. The reason names what was missing: an agent id (the -// deployment's bot user, empty when the composition resolved none), how many -// distinct senders were found (zero for a dashboard or webhook session, more -// than one for a group chat), and how many user messages carried no sender at -// all -- unknown provenance rules a session out on its own, beside any number -// of identified senders. +// ActionSkipped records a session that could not be attributed, with the +// reason. const ActionSkipped = "memory.skipped" // DefaultInterval is the check-in cadence used when nothing more @@ -130,13 +125,9 @@ func effectiveSince(since, now time.Time) time.Time { return since } -// reviewOne extracts observations from one session's recent messages and -// writes them through engine as agent-user memory for the session's single -// participant. Returns nil (no Action) when nothing was extracted -- -// matching the skill curator's "a pass with nothing to report is not an -// error" -- or when the session carries no messages at all. A session the -// pass cannot address -- no agent, or no single participant -- is skipped -// with an Action saying why. +// reviewOne extracts observations from one session and writes them as +// agent-user memory for its single participant. It returns nil when nothing +// was extracted, or a skip action when the session cannot be attributed. func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngine, sess curator.SessionSummary) (*curator.Action, error) { msgs, err := c.host.Conversations.Messages(ctx, sess.ID, messageTailSize) if err != nil { @@ -146,17 +137,7 @@ func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngin return nil, nil } - // Resolve the address before spending a model call: an unaddressable - // session has nowhere to write, so there is nothing a model response - // could add. ScopeAgentUser is addressed by both ids, and a guess would - // file one person's facts under another's. - // - // An empty agent id is the composition having resolved no bot user for - // this deployment -- the session's own record cannot supply one (see - // Adapter). The engine would refuse the scope, which is the right - // refusal for a write with no address: what is wrong is writing it at - // all, so the skip belongs here, at the point the scope is produced, and - // not as a Pass error that abandons every other session's work. + // Skip sessions without an agent before calling the model. if sess.AgentID == "" { return &curator.Action{ At: c.host.Clock.Now(), @@ -197,12 +178,7 @@ func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngin facts = facts[:maxObservationsPerSession] } - // Agent-user is the only defensible home for a derived fact about a - // person: agent scope would leak user A's facts to user B through the - // same agent, user scope would pool them across agents, and the session - // id this used to write stops meaning anything when the session ends. - // ScopeAgentUser is also what a later chat turn reads back, which is - // the whole point of writing these at all. + // Write to agent-user scope, which chat turns read back. scope := domainmemory.Scope{ Kind: domainmemory.ScopeAgentUser, Agent: domainmemory.AgentID(sess.AgentID), @@ -229,18 +205,9 @@ func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngin }, nil } -// sessionParticipant returns the one participant a session's memory may be -// attributed to, or -- when there is none -- the reason there isn't. -// -// Only user-role messages carry a person: an assistant message carries the -// bot, so it can never manufacture a participant. -// -// A user-role message with an empty SenderID is part of the excerpt the -// model reads but names nobody, so the session is unattributable outright, -// even beside exactly one identified sender. The alternative -- skipping it -// and attributing the rest -- would credit whoever that sender is with -// facts drawn from content of unknown provenance, which is the isolation -// failure the agent-user scope exists to prevent. +// sessionParticipant returns the session's single user-role sender, or why +// there is none. Any user message without a sender makes the session +// unattributable. func sessionParticipant(msgs []curator.ConversationMessage) (participant, reason string) { senders := make(map[string]struct{}) unidentified := 0 diff --git a/internal/infrastructure/skillcurator/skillcurator.go b/internal/infrastructure/skillcurator/skillcurator.go index 5eaf0d8fc..b695f0aab 100644 --- a/internal/infrastructure/skillcurator/skillcurator.go +++ b/internal/infrastructure/skillcurator/skillcurator.go @@ -88,12 +88,8 @@ func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassR return curator.PassResult{Actions: actions}, nil } -// reviewOne classifies a single skill and, for a normalizable one, -// writes the cleaned content back. It never returns more than one -// Action: a parse failure and a missing field can't both be reported for -// the same skill in the same pass (a Frontmatter that failed to parse -// has no fields to check), and a normalization is reported once even -// though it may have fixed multiple lines. +// reviewOne classifies one skill and writes back a normalized version when +// possible. It returns at most one Action. func (c *Curator) reviewOne(ctx context.Context, name string) ([]curator.Action, error) { sk, err := c.host.Skills.Read(ctx, name) if err != nil { diff --git a/internal/infrastructure/skillcurator/store.go b/internal/infrastructure/skillcurator/store.go index e7e99d5f2..c27a4a8ef 100644 --- a/internal/infrastructure/skillcurator/store.go +++ b/internal/infrastructure/skillcurator/store.go @@ -21,11 +21,7 @@ const skillsDir = ".agents/skills" // its own directory under skillsDir. const skillFile = "SKILL.md" -// Store implements curator.SkillStore over one root directory's. -// agents/skills/*/SKILL.md files. List and Read never parse frontmatter -// themselves beyond a best-effort Description: a per-skill parse failure is the -// curator's problem to report as an Action, not this store's problem to abort -// on. +// Store implements curator.SkillStore over root's */SKILL.md files. type Store struct { root string } @@ -43,13 +39,8 @@ func (s *Store) skillPath(name string) string { return filepath.Join(s.skillsPath(), name, skillFile) } -// List returns every skill directory under root, in directory order. A -// directory with no SKILL.md is skipped -- consistent with internal/skill's -// Catalog, which treats an unreadable or absent SKILL.md as "no skill here" -// rather than an error -- and a missing -// skills directory returns an empty list, not an error, matching -// internal/skill's discovery convention (missing directory is not an -// error). +// List returns every skill directory with a SKILL.md. A missing directory +// returns an empty list. func (s *Store) List(_ context.Context) ([]curator.SkillRef, error) { entries, err := os.ReadDir(s.skillsPath()) if os.IsNotExist(err) { @@ -73,12 +64,8 @@ func (s *Store) List(_ context.Context) ([]curator.SkillRef, error) { return refs, nil } -// Read returns the named skill's raw SKILL.md content. Description is a -// best-effort frontmatter read: empty on a parse failure, which Read -// does not treat as an error -- Pass is what decides a parse failure is -// worth reporting, and it needs the raw Content to do so via its own -// skill.Parse call regardless of whether this convenience field could be -// populated. +// Read returns the skill's raw SKILL.md. Description is empty when the +// frontmatter does not parse. func (s *Store) Read(_ context.Context, name string) (curator.Skill, error) { path := s.skillPath(name) data, err := os.ReadFile(path) @@ -92,11 +79,7 @@ func (s *Store) Read(_ context.Context, name string) (curator.Skill, error) { return sk, nil } -// Write persists s.Content to the named skill's SKILL.md. The skill's -// directory must already exist -- Write curates an existing skill, it -// does not create a new one, which is a bigger decision (naming, -// directory layout, an author writing the rest of the frontmatter) that -// this store does not make. +// Write overwrites an existing skill's SKILL.md. func (s *Store) Write(_ context.Context, sk curator.Skill) error { dir := filepath.Join(s.skillsPath(), sk.Name) if info, err := os.Stat(dir); err != nil || !info.IsDir() { diff --git a/internal/infrastructure/taskactions/rpc.go b/internal/infrastructure/taskactions/rpc.go index 285088ca6..bc7a2c662 100644 --- a/internal/infrastructure/taskactions/rpc.go +++ b/internal/infrastructure/taskactions/rpc.go @@ -23,24 +23,15 @@ import ( // execution; the standalone Gateway never mutates the task store directly. const actionSubject = "archie.gateway.task-action" -// Identity is a pointer because its absence is meaningful: nil is a -// caller authenticated across identities, which the daemon's service -// distinguishes from any named identity, empty included. It is a SCOPE -- which -// tasks the caller may touch -- and never an actor. -// -// Actor carries who performed the action and whose authority permitted it, as -// resolved by the caller that verified the credential. Its absence is meaningful: -// an absent actor records an unattributed action, never a human's. +// actionRequest is a task action request. A nil Identity is a caller acting +// across identities. A nil Actor records an unattributed action. type actionRequest struct { Identity *string `json:"identity"` TaskID int64 `json:"task_id"` Action taskstate.Action `json:"action"` Actor *actorPayload `json:"actor,omitempty"` - // Instructions and Findings are the review gate answer payload - // (taskactions.ActionPayload). They are empty for every action but - // approve and rereview, and for chat surfaces, which carry no selection - // syntax. RetryMode is the worktree choice a retry carries; empty means - // the explicit default, refresh_onto_base. + // Instructions and Findings answer the review gate. RetryMode is the retry's + // worktree mode; empty means refresh_onto_base. Instructions string `json:"instructions,omitempty"` Findings []string `json:"findings,omitempty"` RetryMode taskstate.RetryMode `json:"retry_mode,omitempty"` @@ -114,12 +105,8 @@ func actionErrorFor(kind string, err error) error { return err } -// Register exposes only identity-scoped operator actions on the daemon. The -// daemon retains execution cancellation, retry policy, forge closure and event -// ownership; the Gateway's client reaches this responder over NATS. -// Handlers run with context.Background() (the storerpc convention): the -// daemon's lifecycle ctx is not request-scoped, and a cancelled boot ctx must -// not poison later requests. +// Register serves identity-scoped task actions over NATS. Handlers use +// context.Background(). func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (func(), error) { return natsrpc.RegisterAll(nc, []natsrpc.Registration{{ Subject: actionSubject, diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go index 707b4f7d8..49dff8394 100644 --- a/internal/infrastructure/taskactions/store.go +++ b/internal/infrastructure/taskactions/store.go @@ -20,11 +20,7 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil } -// CancelExecution delegates to the store's one cancel path. -// Both adapters -- the -// PostgreSQL store and the remote gRPC client -- implement it; the type -// assertion failing would be a composition bug, so it is named rather than -// panicked over. +// CancelExecution delegates to the store. func (s Store) CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error) { canceller, ok := s.TaskStore.(storecontract.ExecutionCanceller) if !ok { @@ -33,11 +29,7 @@ func (s Store) CancelExecution(ctx context.Context, taskID int64, reason, to str return canceller.CancelExecution(ctx, taskID, reason, to) } -// RespondReviewGate delegates to the store's guarded response write. Both -// adapters -- the PostgreSQL store and the remote gRPC client -- implement it -// (internal/domain/storecontract.ReviewGateResponder); the type assertion -// failing would be a composition bug, so it is named rather than panicked -// over, exactly like CancelExecution above. +// RespondReviewGate delegates to the store. func (s Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error { responder, ok := s.TaskStore.(storecontract.ReviewGateResponder) if !ok { @@ -52,11 +44,7 @@ func MaxRetries(cfg *config.Holder) func(*taskactions.Task) int { return 0 } c := cfg.Get() - // A multi-identity deployment declares its repositories under - // [[identities.repos]] and has no global [[repos]] at all, so the - // task's owning identity is the only place a per-repo override can - // live. Without this lookup the override is never matched and the - // task dies at the global cap instead of the configured one. + // In multi-identity deployments, repos live under the task's identity. if t.Identity != "" { for _, identity := range c.Identities { if identity.Name != t.Identity { diff --git a/internal/infrastructure/terminalprompt/terminalprompt.go b/internal/infrastructure/terminalprompt/terminalprompt.go index 64e3171db..009179893 100644 --- a/internal/infrastructure/terminalprompt/terminalprompt.go +++ b/internal/infrastructure/terminalprompt/terminalprompt.go @@ -1,9 +1,4 @@ -// Package terminalprompt is the real, TTY-backed implementation of the -// prompt surface archied setup needs (see internal/infrastructure/ -// configuration/setup.Prompter, which this package satisfies structurally -// -- it does not import that package, so there is no infrastructure -> -// infrastructure edge for what is, structurally, just an interface -// satisfaction). +// Package terminalprompt implements setup's Prompter on a TTY. package terminalprompt import ( @@ -26,21 +21,11 @@ type Terminal struct { out io.Writer r *bufio.Reader - // readSecret reads one line from the given fd without echoing it. It is - // a seam so tests can exercise ReadSecret's prompt/cancellation - // behaviour over a pipe -- term.ReadPassword itself only works on a - // real TTY fd, which New already requires for production use, so this - // field is never swapped outside a test. + // readSecret reads a line without echo. readSecret func(fd int) ([]byte, error) } -// New returns a Terminal reading from in and writing prompts to out. in -// must be a real terminal: setup's non-interactive failure requirement -// ("a non-TTY invocation without sufficient input fails with a clear -// message rather than writing a partial config") is enforced here, at -// construction, rather than by falling back to a degraded read mode that -// would silently accept piped or redirected input and produce a config -// nobody typed. +// New returns a Terminal on in, which must be a terminal. func New(in *os.File, out io.Writer) (*Terminal, error) { if !term.IsTerminal(int(in.Fd())) { return nil, fmt.Errorf( @@ -57,11 +42,8 @@ func New(in *os.File, out io.Writer) (*Terminal, error) { }, nil } -// readLine runs a blocking read in a goroutine and races it against -// ctx.Done(). On cancellation the read is abandoned: the goroutine leaks -// until the abandoned read itself returns (real input or EOF), which is -// accepted because a cancelled setup command is expected to exit shortly -// after via its own signal handling, taking the leaked goroutine with it. +// readLine reads a line, returning early if ctx ends; the read goroutine +// then finishes on its own. func (t *Terminal) readLine(ctx context.Context) (string, error) { type result struct { line string diff --git a/internal/infrastructure/toolbuilder/toolbuilder.go b/internal/infrastructure/toolbuilder/toolbuilder.go index e09a214f8..18b336908 100644 --- a/internal/infrastructure/toolbuilder/toolbuilder.go +++ b/internal/infrastructure/toolbuilder/toolbuilder.go @@ -1,8 +1,5 @@ -// Package toolbuilder resolves a curator's declared tool names from the -// daemon's process-wide tool registry (internal/tools.Registry). It is the -// implementation of curator.ToolBuilder: resolution returns exactly the -// declared set, never a broader registry, and a declared name with no -// implementation fails the build rather than silently returning fewer tools. +// Package toolbuilder resolves a curator's declared tools from the tool +// registry. An unknown name is an error. package toolbuilder import ( diff --git a/internal/infrastructure/transcription/transcription.go b/internal/infrastructure/transcription/transcription.go index 83dcb0116..94a0529da 100644 --- a/internal/infrastructure/transcription/transcription.go +++ b/internal/infrastructure/transcription/transcription.go @@ -42,12 +42,8 @@ type Options struct { Timeout time.Duration } -// New builds a transcription client from models[Role] and the matching -// providers entry. It reports (nil, false) rather than an error when the -// capability is not usable right now -- no role configured, an unknown -// provider, an unsupported provider class, or a missing/blank credential -- -// per the credential-missing-degrades-not-fatal rule (AGENTS.md): callers -// keep the media note, never fail the turn or daemon startup, over this. +// New builds a transcription client from models[Role] and its provider, or +// returns (nil, false) when unavailable. func New(models map[string]string, providers map[string]config.Provider, opts Options) (messaging.Transcriber, bool) { getenv := opts.Getenv if getenv == nil { @@ -77,11 +73,8 @@ func New(models map[string]string, providers map[string]config.Provider, opts Op return &client{client: sdktranscribe.NewClient(sdkProvider), model: modelID}, true } -// resolveCredential returns the provider's key and whether the provider may -// be used. A provider that names neither an env var nor a secret reference is -// permitted with an empty key: a self-hosted OpenAI-compatible backend is -// unauthenticated, and the provider constructor rejects an empty key for the -// hosted classes that require one. +// resolveCredential returns the provider's key and whether it may be used. +// A provider with no credential is allowed with an empty key. func resolveCredential(provider config.Provider, getenv func(string) string, resolveSecret func(config.SecretRef) (string, error)) (string, bool) { switch { case provider.APIKeyEnv != "": diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index cda181bf5..1be075605 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -1,15 +1,5 @@ -// Package workflowsteps is the compiled-in workflow step-type provider set: -// the one place a step type is bundled into the Archie binaries that resolve -// one, so no such binary can keep a provider set of its own. -// -// Two composition roots register it, both of them roots that resolve a step -// type: archied's RunStateStore (the State Store's validating side) and -// archied's daemon root (openDaemonWorkflowDefinitions, the executing side's -// workflow-definitions client, alongside agentworker's -// productionWorkerDependencies). Sharing one package is what keeps them -// registering the same vocabulary. Processes that resolve no step type do not -// import it and register nothing: archie-gateway, archie-messaging, -// archie-playbooks and archie-ui. +// Package workflowsteps is the compiled-in set of workflow step-type +// providers, registered by every process that resolves step types. package workflowsteps import ( @@ -20,11 +10,8 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow" ) -// shippedStages is the provider that contributes every stage of the shipped -// workflows (bootstrap, implement, tdd, feasibility, triage, remediate) as a -// workflow step type. It is what makes the shipped vocabulary arrive by -// registration rather than by the manager implying it, so the vocabulary a -// process resolves is always the vocabulary a provider set claimed. +// shippedStages provides every stage of the shipped workflows as a step +// type. type shippedStages struct{} func (shippedStages) Name() string { return "shipped" } @@ -38,16 +25,7 @@ func (shippedStages) StepTypes() []workflow.StepType { return stepTypes } -// repoHooks is the provider that contributes the step types replacing the -// repository-authored hooks that were deleted with the interpreted workflow -// engine -- .archie/gate.go, whose rules now arrive as settings on -// workflow.DiffRulesStepName instead of as Go read out of the worktree being -// worked on. -// -// It is a provider of its own rather than part of shippedStages, which is -// scoped to the stages of the shipped workflows: a repository's migration target -// is not part of any shipped workflow, and a root that bundles one set should be -// able to tell which set a step type came from. +// repoHooks provides the gate.diff-rules step type. type repoHooks struct{} func (repoHooks) Name() string { return "repo-hooks" } @@ -78,29 +56,12 @@ func (commandSteps) StepTypes() []workflow.StepType { return []workflow.StepType{workflow.CommandRunStepType()} } -// Providers returns the provider set the roots that resolve a workflow step -// type register at their composition root, before the first resolution: it is -// what NewManager registers, and what the roots' guards read to hold a -// registered vocabulary to the set it came from. A step type added here becomes -// reachable from the validating side and the executing side at once. -// -// The set is a compiled-in constant rather than a directory scan: a step type -// is a Go factory, and no bridge has been built from the Yaegi-interpreted -// plugins internal/plugin loads to workflow.StepFactory -- those plugins -// satisfy plugin.Plugin's metadata contract only. Such a bridge is possible: -// internal/secret/secretextract wraps an interpreted Engine into the typed -// contract secret.Registry.LoadDir registers (internal/app/archied/ -// provider_secrets.go). Until one exists for step types, adding a step type -// means adding a provider here. +// Providers returns the step-type providers to register. func Providers() []workflow.StepTypeProvider { return []workflow.StepTypeProvider{shippedStages{}, repoHooks{}, eventSteps{}, commandSteps{}} } -// NewManager builds this process's workflow step-type manager by registering -// the provider set. Every call constructs an independent manager: there is no -// package-level registry and nothing registers at init(), so building the -// vocabulary twice in one process — as `-count=2` does — cannot collide with -// the first build. +// NewManager returns a new manager with Providers registered. func NewManager() (*workflow.Manager, error) { manager := workflow.NewManager() for _, provider := range Providers() { diff --git a/internal/installtype/installtype.go b/internal/installtype/installtype.go index 4aeaf82fe..9d1843d92 100644 --- a/internal/installtype/installtype.go +++ b/internal/installtype/installtype.go @@ -1,15 +1,5 @@ -// Package installtype identifies how the running binary was distributed, so -// code that must never guess at deployment shape -- most notably the -// self-update dispatcher -- can fail closed instead of assuming. -// -// The install type is decided once, at release-build time, and baked into -// the binary. It is deliberately never detected at runtime by probing the -// environment (checking for a container marker file, a systemd env var, -// and so on): those signals are guessable and can be present for reasons -// that have nothing to do with how the binary would actually be updated. A -// binary that was never stamped by the release pipeline (a local -// `go build`, for instance) reports Unknown, and callers that would -// otherwise silently guess must instead refuse. +// Package installtype reports how the binary was distributed, stamped at +// build time. Unstamped builds report Unknown. package installtype // Unknown is what Type reports when a build was never stamped. diff --git a/internal/natsrpc/natsrpc.go b/internal/natsrpc/natsrpc.go index f286d4904..69cd28063 100644 --- a/internal/natsrpc/natsrpc.go +++ b/internal/natsrpc/natsrpc.go @@ -1,9 +1,5 @@ -// Package natsrpc holds the request/reply plumbing shared by -// archie-core's core-NATS RPC surfaces (worktreerpc, forgerpc, -// taskactions): a timeout-bounded client call, multi-subject server -// registration with rollback on partial failure, and a JSON error -// envelope so handlers don't each reimplement "marshal error, log -// encode/respond failures." +// Package natsrpc is shared core NATS request/reply plumbing: client calls, +// server registration and a JSON error envelope. package natsrpc import ( @@ -89,15 +85,8 @@ type Registration struct { Handler nats.MsgHandler } -// RegisterAll subscribes every registration on nc and waits for the server -// to acknowledge them. If any step fails, every subscription made so far is -// unsubscribed before returning the error -- a server never ends up -// half-registered. The returned func unsubscribes all of them. -// -// The flush is what makes a successful return meaningful. Subscribe only -// queues the SUB frame on the client, so without it a caller that registers -// and immediately requests can beat its own subscription to the server and -// get nats.ErrNoResponders from a responder that is, by then, listening. +// RegisterAll subscribes every registration and flushes, unsubscribing all +// of them on any failure. The returned func unsubscribes all. func RegisterAll(nc *nats.Conn, regs []Registration) (unsubscribe func(), err error) { subs := make([]*nats.Subscription, 0, len(regs)) unsubscribeAll := func() { @@ -123,11 +112,7 @@ func RegisterAll(nc *nats.Conn, regs []Registration) (unsubscribe func(), err er return unsubscribeAll, nil } -// Respond marshals v and replies to msg, logging (rather than -// returning) any encode or transport failure -- a handler has no -// meaningful way to retry or propagate a respond failure to its caller. -// pkg prefixes the log message (e.g. "forgerpc") to identify the -// surface a failure came from. +// Respond marshals v and replies to msg, logging any failure. func Respond(msg *nats.Msg, log *slog.Logger, pkg string, v any) { data, err := json.Marshal(v) if err != nil { diff --git a/internal/pairing/atomic.go b/internal/pairing/atomic.go index 5e7077842..ba4853436 100644 --- a/internal/pairing/atomic.go +++ b/internal/pairing/atomic.go @@ -6,13 +6,8 @@ import ( "path/filepath" ) -// writeFileAtomic writes data to path by writing to a temporary file in -// the same directory and renaming it into place. A rename within the -// same filesystem is atomic, so a reader never observes a partially -// written file, and a crash mid-write leaves the original file (or no -// file) intact rather than a corrupt one. The file is created with mode -// 0600 -- pairing state (codes, approvals, rate-limit history) is -// sensitive and must not be group/world readable. +// writeFileAtomic writes data to path, mode 0600, through a temp file and +// rename. func writeFileAtomic(path string, data []byte) error { dir := filepath.Dir(path) tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") diff --git a/internal/pairing/store.go b/internal/pairing/store.go index fb084f246..6b418d3df 100644 --- a/internal/pairing/store.go +++ b/internal/pairing/store.go @@ -54,11 +54,8 @@ type userLimit struct { LastRequestAt time.Time `json:"last_request_at"` Failures int `json:"failures"` LockedUntil time.Time `json:"locked_until"` - // LockoutCount is how many times in a row this user has been locked - // out without an intervening successful VerifyCode. It escalates - // the lockout duration on repeat offenses and resets to 0 on - // success, so a one-time mistake isn't punished as hard as a - // sustained brute-force attempt. + // LockoutCount counts consecutive lockouts, escalating the lockout duration; + // reset on success. LockoutCount int `json:"lockout_count"` } @@ -79,12 +76,8 @@ func lockoutDuration(lockoutCount int) time.Duration { return d } -// Store is a file-backed pairing authorization store, scoped to a single -// platform (create one Store per platform, each pointed at its own -// directory -- see New). It tracks outstanding pairing codes, approved -// users, and per-user rate-limit/lockout state, persisting all three to -// pending.json, approved.json, and rate_limits.json under its directory -// after every mutation. +// Store is a file-backed pairing store for one platform: pending codes, +// approved users and rate limits. type Store struct { dir string now func() time.Time @@ -122,11 +115,8 @@ func New(dir string) (*Store, error) { return s, nil } -// RequestCode generates and stores a new pairing code for userID, -// returning the plaintext code (the only time it is ever available in -// plaintext -- only its salted hash is persisted). Fails with -// ErrLockedOut, ErrRateLimited, or ErrQuotaExceeded per the package's -// tuning constants. +// RequestCode creates and returns a pairing code for userID; only its hash +// is stored. func (s *Store) RequestCode(userID string) (string, error) { s.mu.Lock() defer s.mu.Unlock() @@ -166,11 +156,8 @@ func (s *Store) RequestCode(userID string) (string, error) { return code, nil } -// VerifyCode checks code against userID's pending pairing code. On -// success, userID moves to the approved set, its pending code is -// consumed (cannot be reused), and its failure count resets. On a wrong -// code, the failure count increments and, at MaxFailures, the user is -// locked out for LockoutDuration. +// VerifyCode checks code for userID. Success approves the user and consumes +// the code; a failure counts toward lockout. func (s *Store) VerifyCode(userID, code string) (bool, error) { s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/ratelimit/limiter.go b/internal/ratelimit/limiter.go index 32b566548..efc308160 100644 --- a/internal/ratelimit/limiter.go +++ b/internal/ratelimit/limiter.go @@ -1,11 +1,5 @@ -// Package ratelimit provides a sliding-window request limiter, keyed by -// platform and user, for gating inbound gateway traffic per identity -// rather than globally. -// -// A limiter's per-key map is unbounded until something calls EvictStale: -// long-lived instances should have it driven on a ticker so entries whose -// hits have all aged out of the window are removed instead of accumulating -// for the life of the process. +// Package ratelimit is a sliding-window limiter keyed by platform and user. +// Call EvictStale periodically. package ratelimit import ( @@ -73,19 +67,8 @@ func (l *Limiter) Allow(platform, userID string) bool { return true } -// EvictStale removes per-key entries whose hits have all aged out of the -// sliding window — an entry with no hit strictly within the last window is -// deleted, and entries that hold no hits at all (possible when maxRequests -// is zero) are always removed. It reports how many entries were removed. -// -// Eviction is behaviour-preserving by construction: the cutoff is Allow's -// own pruning cutoff (now - window), so a removed key would have -// contributed zero hits to its next Allow, which would lazily recreate it -// — sweeping can never grant fresh budget. -// -// The limiter runs no background sweeper; a long-lived limiter should have -// EvictStale driven on a ticker (e.g. once per window), as the daemon -// drives storage expiry. +// EvictStale removes keys with no hits in the current window and returns +// how many it removed. func (l *Limiter) EvictStale() int { l.mu.Lock() defer l.mu.Unlock() diff --git a/internal/sdnotify/sdnotify.go b/internal/sdnotify/sdnotify.go index a8d438894..e19dee045 100644 --- a/internal/sdnotify/sdnotify.go +++ b/internal/sdnotify/sdnotify.go @@ -1,33 +1,6 @@ -// Package sdnotify implements systemd's sd_notify(3) protocol: one READY=1 when -// a process starts serving, and a WATCHDOG=1 heartbeat while the loop it stands -// for is demonstrably still making progress. -// -// The protocol is three environment variables and one datagram per state, so -// this package speaks it directly instead of taking a module dependency: the -// whole client is net.DialUnix plus a Write. Nothing here is fatal -- a process -// with no NOTIFY_SOCKET (a plain terminal, Docker, a user unit without -// WatchdogSec) sends nothing and serves exactly as before, and a socket that -// cannot be written to is logged and ignored. -// -// It lives outside a composition package because a process that must announce -// itself cannot import another process's composition -- archied and -// archie-messaging are two processes that announce, and only one of them can -// own archied's boot -// -// What stays with the caller is everything that is the caller's: which marker -// counts as progress, how long its loop may go without a pass, and the point -// at which it considers itself serving. -// -// The heartbeat is deliberately not a bare ticker. A ticker fires whether or -// not the loop it stands for is alive, so it would keep systemd satisfied while -// the event loop was wedged -- the exact failure the watchdog exists to catch. -// The sampler instead reads the caller's own progress marker through Progress -// and withholds the heartbeat once that marker is older than the cadence -// Cadence reports. While passes keep beginning, beats flow at half of -// WatchdogSec; a loop blocked inside a pass stops being reported as alive. -// -// Consuming the states is the unit's business: READY=1 needs Type=notify, and -// the heartbeat needs WatchdogSec. +// Package sdnotify sends systemd sd_notify READY=1 and WATCHDOG=1 messages. +// Heartbeats stop when the caller's progress marker goes stale. Without +// NOTIFY_SOCKET nothing is sent. package sdnotify import ( @@ -91,11 +64,8 @@ func (n Notifier) Send(state string) { } } -// sendNotify writes one state datagram to a unixgram socket. sd_notify(3) is -// one datagram per state, so each send dials afresh: a manager restart recreates -// its socket, and a connection cached across one would fail every send after it. -// A leading '@' names the Linux abstract namespace, which user managers use; -// net.UnixAddr takes that syntax verbatim. +// sendNotify sends one datagram to the notify socket; '@' means the +// abstract namespace. func sendNotify(addr, state string) error { conn, err := net.DialUnix("unixgram", nil, &net.UnixAddr{Name: addr, Net: "unixgram"}) if err != nil { @@ -108,22 +78,13 @@ func sendNotify(addr, state string) error { return nil } -// Ready sends READY=1 to the socket named in the process environment. It is -// the one call a composing package needs to declare itself serving, and it -// belongs at the moment the process already says so: the daemon's run loop -// (next to its own health surface), and the serve steps of archie-gateway, -// archie-state-store and archie-messaging, which have readiness of their own -// and would otherwise hang a Type=notify unit until TimeoutStartSec while -// perfectly healthy. +// Ready sends READY=1. func Ready(log *slog.Logger) { New(os.Getenv, log).Send(ReadyState) } -// Heartbeat reads systemd's watchdog contract and returns the heartbeat -// cadence, which is half of WatchdogSec. ok is false when systemd asked for no -// watchdog, and also when it asked for one from a different process: -// WATCHDOG_PID names the process whose beats count, so a unit watching another -// process must not have this one beating on its behalf. +// Heartbeat returns half of WatchdogSec. ok is false when no watchdog is +// requested or WATCHDOG_PID is another process. func Heartbeat(getenv func(string) string, pid int, log *slog.Logger) (time.Duration, bool) { raw := getenv(WatchdogUsecEnv) if raw == "" { diff --git a/internal/servicediscovery/doc.go b/internal/servicediscovery/doc.go index e347d1bc6..2929aadce 100644 --- a/internal/servicediscovery/doc.go +++ b/internal/servicediscovery/doc.go @@ -1,30 +1,5 @@ -// Package servicediscovery is the broker-neutral service registry contract. -// -// It defines only the shape archie-core needs to discover and watch the -// services of its decomposed fleet: a way to resolve a named service to its -// live endpoints, and a way to watch that membership change over time. It names -// no registry. A NATS JetStream KV implementation lives in -// internal/infrastructure/servicediscovery/nats; the Kubernetes-native primary -// is the sibling that serves the same contract. -// -// # NotInstalled is not Down -// -// The single most important semantic in this package is the distinction -// between a service that was never installed and a service that is installed -// but currently has no healthy endpoint. -// -// - [ErrNotInstalled] reports that a service has never been installed. It -// is a distinct outcome, not a failure. An optional service (Curator -// today, others later) that is not present must resolve to "absent", -// never "broken": callers match it with errors.Is and treat it as "this -// capability is disabled", not "this capability is unhealthy". -// - A service that IS installed but has zero healthy endpoints right now is -// a normal, non-error outcome. [ServiceRegistry.Resolve] returns a -// possibly-empty slice with a nil error; [ServiceRegistry.Watch] returns -// a live channel that simply does not emit until an endpoint joins. -// -// This is why a registry implementation must model presence separately from -// liveness. The NATS implementation keeps a durable "installed" marker that -// never expires, distinct from expiring heartbeat keys: the marker's presence -// means NotInstalled=false, while heartbeat expiry is Down/Unhealthy. +// Package servicediscovery is the broker-neutral service registry contract: +// resolve a service's live endpoints and watch membership changes. A service +// never installed returns ErrNotInstalled; an installed service with no live +// endpoints returns no endpoints and no error. package servicediscovery diff --git a/internal/servicediscovery/servicediscovery.go b/internal/servicediscovery/servicediscovery.go index 4545fb6a7..a91ae8f58 100644 --- a/internal/servicediscovery/servicediscovery.go +++ b/internal/servicediscovery/servicediscovery.go @@ -5,21 +5,13 @@ import ( "errors" ) -// ErrNotInstalled reports that a service has never been installed. It is -// distinct from a service that is installed but currently has no healthy -// endpoint: that case is an empty, non-error result, not ErrNotInstalled. -// Implementations of [ServiceRegistry.Resolve] and [ServiceRegistry.Watch] -// return it (wrapped, matched with errors.Is) when a service's "installed" -// marker is absent. Callers match it and treat the capability as disabled. +// ErrNotInstalled reports that a service was never installed. Callers treat +// the capability as disabled. var ErrNotInstalled = errors.New("servicediscovery: service not installed") // Endpoint is one resolved instance of a service. type Endpoint struct { - // Service is the logical name the endpoint was registered under. It is - // redundant within the scope of a single Resolve/Watch call, but it makes - // the value self-describing and directly usable by a consumer that reads - // raw registry records (e.g. a custom gRPC resolver) rather than going - // through ServiceRegistry. + // Service is the name the endpoint registered under. Service string `json:"service,omitempty"` // ID distinguishes multiple instances of the same service. It is the @@ -72,17 +64,11 @@ type Event struct { // It models network endpoints only. In-process services do not register here; // application composition selects local adapters independently of discovery. type ServiceRegistry interface { - // Resolve returns the current healthy endpoints for service. It returns - // [ErrNotInstalled] if service has never been installed. If service is - // installed but currently has no healthy endpoint, it returns a - // possibly-empty slice with a nil error -- callers distinguish that from - // NotInstalled to avoid treating an optional, disabled service as broken. + // Resolve returns service's live endpoints, possibly none, or + // ErrNotInstalled. Resolve(ctx context.Context, service string) ([]Endpoint, error) - // Watch returns a channel that emits [Join] and [Leave] events as service's - // membership changes, until ctx is cancelled. It returns [ErrNotInstalled] - // if service has never been installed at the time of the call. A service - // that is installed but currently has no healthy endpoint returns a live - // channel that simply does not emit until an endpoint joins. + // Watch emits Join and Leave events for service until ctx ends, or returns + // ErrNotInstalled. Watch(ctx context.Context, service string) (<-chan Event, error) } diff --git a/internal/skill/plugin.go b/internal/skill/plugin.go index 9d4312f23..2249556a0 100644 --- a/internal/skill/plugin.go +++ b/internal/skill/plugin.go @@ -37,14 +37,9 @@ func (p *Plugin) Run(input string) (string, error) { return fn(input), nil } -// LoadPlugins loads plugins. -// -// When allowed is non-empty, only the listed filenames are loaded in -// declared order -- the plugins/ prefix is stripped before matching. -// A listed file that does not exist on disk is an error. -// -// When allowed is nil or empty, all *.go files in the plugins/ directory -// are globbed alphabetically (backward-compatible fallback). +// LoadPlugins loads a skill's plugins: the allowed files in order, or every +// *.go file in plugins/ alphabetically when allowed is empty. A listed file +// that is missing is an error. func LoadPlugins(dir, skillName string, allowed []string) ([]Plugin, error) { pluginsDir := filepath.Join(dir, skillsDir, skillName, "plugins") entries, err := os.ReadDir(pluginsDir) diff --git a/internal/skill/tooldef.go b/internal/skill/tooldef.go index 660caf125..dec4e9c19 100644 --- a/internal/skill/tooldef.go +++ b/internal/skill/tooldef.go @@ -7,14 +7,8 @@ import ( "github.com/samcharles93/archie-core/internal/tools" ) -// ActivateTool bridges a skill catalog into a single tools.ToolEntry a -// chat turn's agent loop can offer the model: one tool named -// "skill_activate", not one per skill -- this is the same progressive -// disclosure Catalog/LoadBody already implement (Tier 1 catalog entries -// cost ~100 tokens each and are always in context via the tool schema; -// Tier 2 full bodies are loaded only when the model actually activates a -// skill). Returns nil when catalog is empty, so an empty skills -// directory doesn't add a dead tool to the set. +// ActivateTool returns a single skill_activate tool over catalog, or nil when +// the catalog is empty. func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry { if len(catalog) == 0 { return nil diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 115e767c8..cc384ab19 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -1,32 +1,14 @@ -// Package storage defines the pluggable storage backend interface for agent -// container execution. The Docker backend (DockerBackend) is the MVP -// implementation -- no NFS/SMB/S3 yet, just Docker volumes + bind mounts. -// -// /data/ volume layout (implemented): +// Package storage provides the mounts for agent containers. // // /data/ -// worktree/ -- bind mount of host worktree -// .git/task.json -- boot-time brief (WriteTaskJSON). Under .git so -// the agent's own commit cannot sweep it onto the -// task branch: go-git's Add ignores .gitignore. -// repo/ -- per-repo persistent volume (optional, on request) -// session.jsonl -- agent session transcript, appended per stage -// memory.jsonl -- cross-session project memory -// plugins/ -- daemon-staged bundled plugins +// worktree/ bind mount of the host worktree +// .git/task.json task brief +// repo/ optional per-repo persistent volume // cache/ -// go/ -- GOMODCACHE (shared across all tasks) -// node/ -- npm cache (shared) -// pnpm/ -- pnpm store (shared) -// deno/ -- Deno module cache (shared) -// bun/ -- Bun package cache (shared) -// pip/ -- pip cache (shared) -// cargo/ -- Rust cargo cache (shared) -// mcp-npm/ -- npm cache for npx-launched per-task MCP -// servers (shared, mounted regardless of the -// task repo's ecosystem -- see MCPNPMCacheMountDir) +// go/ node/ pnpm/ deno/ bun/ pip/ cargo/ shared ecosystem caches +// mcp-npm/ npm cache for npx MCP servers, always mounted // -// Cache volumes are named Docker volumes created once and shared across all -// tasks. They are never deleted -- the daemon operator manages them. +// Cache volumes are shared across tasks and never deleted. package storage import ( @@ -95,15 +77,8 @@ func AppendJSONLine(path string, value any) error { return nil } -// ReadJSONLines decodes each line of the JSONL file at path as a T, calling -// fn for each. A path that does not exist yet is not an error -- no log -// written and an empty log mean the same thing to a caller -- so fn is -// simply never called. A malformed line, or an error fn itself returns, -// stops the scan and is returned wrapped. -// -// This is AppendJSONLine's read-side counterpart, kept in the package that -// owns the format: see organisation.md's "a package owns its own format end -// to end." +// ReadJSONLines calls fn for each JSON line in path. A missing file is not +// an error; a bad line or an fn error stops the scan. func ReadJSONLines[T any](path string, fn func(T) error) error { f, err := os.Open(path) if errors.Is(err, os.ErrNotExist) { @@ -174,13 +149,8 @@ const ( PluginsDir = PersistentMountDir + "/plugins" ) -// MCPNPMCacheMountDir is the fixed container path where the npm package -// cache for npx-launched per-task MCP servers is mounted. Unlike the -// ecosystem caches below, this is mounted on every task container -// regardless of the task repo's language: per-task MCP servers come from -// daemon-wide config (config.MCPServer), not from anything specific to the -// checked-out repo, so an npx-based server needs the cache warm whether the -// task is a Go repo, a Python repo, or anything else. +// MCPNPMCacheMountDir is where the npm cache for npx MCP servers is mounted +// on every task container. const MCPNPMCacheMountDir = "/data/cache/mcp-npm" // Backend prepares container storage. Each container runtime backend @@ -204,12 +174,7 @@ type cacheVolume struct { MountPath string // container destination path } -// alwaysOnCacheVolumes are shared cache volumes mounted on every task -// container regardless of the task repo's ecosystem, because what they -// cache isn't tied to the repo being worked on. The npx package cache for -// per-task MCP servers is the only current instance: MCP servers are -// daemon-wide config, not per-repo, so an npx-based one needs a warm cache -// no matter which repo the task happens to be against. +// alwaysOnCacheVolumes are mounted on every task container. var alwaysOnCacheVolumes = []cacheVolume{ {Name: "archie-cache-mcp-npm", MountPath: MCPNPMCacheMountDir}, } @@ -242,11 +207,8 @@ var cacheVolumesByEcosystem = map[string][]cacheVolume{ }, } -// cacheMounts returns the cache mount specs for an ecosystem -- the -// always-on volumes plus any matched by ecosystem -- sorted by destination -// path for deterministic container configuration. Ecosystem is -// case-insensitive -- "Python" and "python" are equivalent. An unknown or -// empty ecosystem still returns the always-on volumes. +// cacheMounts returns the always-on mounts plus the ecosystem's, sorted by +// destination. Ecosystem is case-insensitive. func cacheMounts(ecosystem string) []Mount { vols := append([]cacheVolume(nil), alwaysOnCacheVolumes...) vols = append(vols, cacheVolumesByEcosystem[strings.ToLower(ecosystem)]...) @@ -298,14 +260,8 @@ func NewDockerBackend(cli *client.Client) *DockerBackend { return &DockerBackend{cli: cli} } -// ensureVolume creates a Docker volume if it doesn't already exist. -// It is idempotent: concurrent callers racing to create the same volume -// will not see an error -- "already exists" is treated as success. -// -// When d.cli is nil (unit tests), ensureVolume returns nil without -// creating a volume. The returned mounts will fail at container create -// time if Docker cannot find the volume. Production code always sets -// cli via NewDockerBackend. +// ensureVolume creates a Docker volume unless it exists. A nil client does +// nothing. func (d *DockerBackend) ensureVolume(ctx context.Context, name string, labels map[string]string) error { if d.cli == nil { return nil // nil client for testing -- volumes must be pre-created @@ -338,11 +294,8 @@ func repoVolumeName(owner, repo string) string { return fmt.Sprintf("archie-repo-%s-%s", owner, repo) } -// Setup returns the mount list for a task container. Mounts are ordered: -// 1. /data/worktree bind mount (always first) -// 2. /data/repo volume mount (only when PersistentStorage is true) -// 3. cache volume mounts: the always-on volumes plus /data/cache/ -// (sorted together by destination) +// Setup returns a task container's mounts: the worktree, the repo volume +// when PersistentStorage is set, then the caches. func (d *DockerBackend) Setup(ctx context.Context, task TaskRef) ([]Mount, error) { mounts := []Mount{ { diff --git a/internal/taskrun/taskrun.go b/internal/taskrun/taskrun.go index e7e9a5ab9..d688b390d 100644 --- a/internal/taskrun/taskrun.go +++ b/internal/taskrun/taskrun.go @@ -1,9 +1,5 @@ -// Package taskrun defines the wire format for handing an entire task off -// from archied to archie-agent in one NATS round trip. -// archie-agent runs workflow.Route and workflow.Run itself; archied's role -// shrinks to worktree prepare, container acquire/release, and answering -// the forgerpc/worktreerpc calls archie-agent proxies back. Agent store -// calls go over gRPC to the State Store, not through this NATS handoff. +// Package taskrun defines the request and response for handing a whole task +// from archied to archie-agent over NATS. package taskrun import ( @@ -15,11 +11,8 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow" ) -// Request carries everything archie-agent needs to run a task's entire -// workflow itself: the task row (already claimed by archied), the repo's -// gate/ecosystem config, a non-secret config snapshot, and LLM provider -// config (API keys are injected into the container's environment -// separately -- Providers only carries class/env-var-name/base-URL). +// Request is everything archie-agent needs to run a task's workflow. API +// keys reach the container as environment variables, not here. type Request struct { Task *workflow.Task `json:"task"` Repo config.Repo `json:"repo"` @@ -29,12 +22,8 @@ type Request struct { // transports, discover tools, and register them locally. Absent/empty // means no MCP servers (backward compatible). MCPServers []config.MCPServer `json:"mcp_servers,omitempty"` - // KindWorkflows and LabelWorkflows carry the resolved kind/label -> - // workflow-name bindings the daemon loaded from WorkflowRoutingFile, - // WorkflowLabelsFile and PlaybookDirs. workflow.Route runs in the - // archie-agent process, not the daemon, so these resolved values must - // cross the process boundary here; nil means use the built-in defaults - // (backward compatible). + // KindWorkflows and LabelWorkflows are the daemon's loaded routing bindings. + // Nil means defaults. KindWorkflows workflow.KindWorkflows `json:"kind_workflows,omitempty"` LabelWorkflows workflow.LabelWorkflows `json:"label_workflows,omitempty"` // WorktreeGrant is an opaque, per-dispatch capability authorizing the @@ -76,13 +65,8 @@ type Response struct { Task *workflow.Task `json:"task"` Status string `json:"status"` Error string `json:"error,omitempty"` - // AgentVersion and AgentInstallType report the build of archie-agent - // that actually ran this task -- self-reported by the worker, not the - // version archied's release pipeline expected to be running. Every - // archie-agent process is task-scoped and ephemeral, so this response - // is the only channel the daemon has to observe what is really in - // service; see daemon.AgentStatus. Empty AgentVersion means an - // unstamped build ("dev") or a worker older than this field. + // AgentVersion and AgentInstallType are the build of archie-agent that ran + // the task. Empty AgentVersion means an unstamped build. AgentVersion string `json:"agent_version,omitempty"` AgentInstallType string `json:"agent_install_type,omitempty"` } diff --git a/internal/taskstate/taskstate.go b/internal/taskstate/taskstate.go index 1c924214f..9af19e9a4 100644 --- a/internal/taskstate/taskstate.go +++ b/internal/taskstate/taskstate.go @@ -1,18 +1,5 @@ -// Package taskstate owns the task lifecycle vocabulary and the rules for -// operator-initiated actions on a task. -// -// It exists because those rules had two implementations. The dashboard and -// chat both offer approve and reject, and they had drifted: rejecting from -// the dashboard left a task ClosedWontDo, cancelling the same task from chat -// left it Rejected. Two operators looking at the same queue saw different -// states for the same decision, and Rejected -- which the PR reconciler uses -// for "the pull request was closed without merging" -- no longer meant one -// thing. -// -// internal/gateway deliberately does not import the task store, so it kept a -// hand-synced copy of the status strings with a comment asking future editors -// to keep them aligned. That is the same defect one level down. This package -// has no dependencies, so both can import it and the copy can go. +// Package taskstate defines task statuses and which operator actions each +// allows. It has no dependencies. package taskstate import ( @@ -75,13 +62,8 @@ func Terminal(status string) bool { } } -// Actions returns the ordered controls valid for status. Callers receive a -// fresh slice so presentation code cannot mutate the lifecycle table. -// -// Reject is deliberately present in every non-terminal state: an operator can -// refuse work no matter where it currently sits, and the refusal always lands -// in the terminal Declined state. Terminal states are already resolved, so -// they only expose archive. +// Actions returns the actions valid for status, as a new slice. Reject is +// available in every non-terminal state; terminal states offer archive. func Actions(status string) []Action { var actions []Action switch status { @@ -124,11 +106,7 @@ func CheckAction(status string, action Action) error { return fmt.Errorf("action %q is not available while task is %s", action, status) } -// CheckApprove reports whether a task in this status can be approved. -// -// Approval releases work that is waiting on a human decision, so it is only -// meaningful from WaitingHuman. Approving anything else would either restart -// finished work or race a task that is already running. +// CheckApprove allows approval only from WaitingHuman. func CheckApprove(status string) error { if status != WaitingHuman { return fmt.Errorf("task is %s, not awaiting approval", status) @@ -136,11 +114,7 @@ func CheckApprove(status string) error { return nil } -// CheckRetry reports whether a task in this status can be retried. -// -// Only a parked task can be retried: parking is how archie says "this failed -// in a way a human might fix". A dead task has spent its retries and needs -// the cap raised or the work re-filed, not another attempt. +// CheckRetry allows retry only from Parked. func CheckRetry(status string) error { if status != Parked { return fmt.Errorf("task is %s, not parked", status) @@ -148,12 +122,8 @@ func CheckRetry(status string) error { return nil } -// RetryMode is the operator's worktree choice for the next dispatch of a -// retried task. It is a dispatch directive: the daemon resolves it to the -// commit the worktree is prepared at, never infers it from the workflow. -// -// The values are persisted on the task row (tasks.retry_mode) and cross the -// wire, so they are part of the on-disk format: renaming one is a migration. +// RetryMode is the worktree mode for a retried task's next dispatch. Stored +// on the task row. type RetryMode string const ( @@ -178,11 +148,8 @@ func NormalizeRetryMode(mode string) RetryMode { return RetryRefreshOntoBase } -// ResolveRetryMode validates a retry mode arriving from a caller. Unlike -// stored data, a wire value that names no mode is rejected rather than -// defaulted: silently reading a typo as "refresh onto base" would reset a task -// the operator asked to continue. The empty string is accepted and means the -// explicit default, RetryRefreshOntoBase. +// ResolveRetryMode validates a retry mode; "" means RetryRefreshOntoBase and +// unknown values are rejected. func ResolveRetryMode(mode string) (RetryMode, bool) { switch RetryMode(mode) { case "", RetryRefreshOntoBase: @@ -216,12 +183,7 @@ func RetryModes() []RetryModeMeta { } } -// CheckDecline reports whether a task in this status can be declined. -// -// The legacy chat command expresses cancel, stop, reject and abandon as one -// operation. Because Reject is now offered in every non-terminal state, that -// command is available everywhere a task is still live; unknown and terminal -// states fail closed instead of permitting an arbitrary transition. +// CheckDecline allows declining any non-terminal task. func CheckDecline(status string) error { for _, action := range Actions(status) { switch action { diff --git a/internal/taskstate/transitions.go b/internal/taskstate/transitions.go index f936a72df..d18fd3a3c 100644 --- a/internal/taskstate/transitions.go +++ b/internal/taskstate/transitions.go @@ -6,17 +6,7 @@ import ( "slices" ) -// StepStatus is the lifecycle of a StepExecution -- one stage run, or one agent -// call a stage makes, inside a WorkflowExecution. -// It is part of the on-disk -// format, like the execution statuses above. -// -// It is a distinct type from those statuses even though the two vocabularies -// share the word "running": an execution status says what the task is doing, -// a step status says what one stage is doing, and the two move through -// different tables. One shared string type would let either status be passed -// where the other belongs, which is the mistake the separate tables exist to -// catch. +// StepStatus is a step execution's status. Stored. type StepStatus string const ( @@ -28,14 +18,8 @@ const ( StepInterrupted StepStatus = "interrupted" ) -// executionTransitions is the WorkflowExecution table: the complete set of -// legal status moves, held as data so no writer carries its own conditional -// copy of the rules. -// -// Terminal statuses appear as empty rows rather than being absent, so the -// table is total over the vocabulary: a status that is missing here is -// unroutable, and the difference between "goes nowhere" and "nobody wrote a -// row" stays visible. +// executionTransitions lists every legal execution status move. Terminal +// statuses have empty rows. var executionTransitions = map[string][]string{ Queued: {Running, Declined}, Running: {Queued, WaitingHuman, PROpen, Completed, Parked, Declined}, @@ -86,13 +70,8 @@ func StepTerminal(status StepStatus) bool { } } -// CheckStepStart reports whether a StepExecution may enter StepRunning under -// the execution it belongs to. -// -// A step only runs while its execution is running, and never under a parent -// that has already finished: work a terminal parent had going was cancelled or -// interrupted when it finished, so a step starting afterwards would be recorded -// against a decision that has already been taken. +// CheckStepStart allows a step to start only while its execution is running +// and its parent has not finished. func CheckStepStart(executionStatus string, parentTerminal bool) error { if executionStatus != Running { return fmt.Errorf("step cannot start while its execution is %s", executionStatus) diff --git a/internal/tools/classification.go b/internal/tools/classification.go index 31d25a75d..d70c8cd9e 100644 --- a/internal/tools/classification.go +++ b/internal/tools/classification.go @@ -17,14 +17,7 @@ const ( // serialization, checkpointing, and stricter guardrail monitoring. ClassMutating - // RequiresApproval marks a tool that must not execute without a human - // consent decision. The dispatch layer blocks the call until an - // ApprovalRequester resolves it (approve, permanently approve, or deny). - // - // It is independent of ClassMutating: writing a file is mutating but - // not necessarily gated (the agent loop's own path enforcement handles - // that), while deleting a session is gated because it is irreversible - // on a path the model controls. + // RequiresApproval marks a tool that needs human approval before each call. RequiresApproval ) diff --git a/internal/tools/command/hardline.go b/internal/tools/command/hardline.go index 5dd152c93..5364aea70 100644 --- a/internal/tools/command/hardline.go +++ b/internal/tools/command/hardline.go @@ -27,19 +27,9 @@ func (b *Blocked) Error() string { return fmt.Sprintf("refused (%s): %s: %q", b.Rule, b.Reason, b.Segment) } -// Hardline checks a command line against the rules that hold regardless of -// configuration, approval, or operator instruction. -// -// This is deliberately a floor and not a security boundary. Anything with a -// shell has countless ways around a pattern list, and pretending otherwise -// would be worse than not having one. What it does buy is that the failure -// modes with no recovery -- the ones where you cannot intervene afterwards -// because the machine, the filesystem, or the gateway itself is gone -- are -// not reachable by an ordinary mistake. -// -// Two rules exist specifically to keep intervention possible: an agent must -// not be able to stop the daemon that hosts /stop, nor start a second one -// outside the supervisor's control. +// Hardline rejects command lines that would be unrecoverable: destroying the +// system, or stopping or duplicating the daemon. It is a floor, not a +// security boundary. func Hardline(line string) error { return hardline(line, 0) } @@ -72,13 +62,7 @@ func hardline(line string, depth int) error { return nil } -// checkSegment applies every rule to one command invocation, then follows -// the segment into any command it merely wraps. -// -// Without that second step the rules are trivially defeated, and not only -// by someone trying: `bash -c "rm -rf /"` is a shape models produce -// unprompted, and `xargs rm -rf /` reads as ordinary shell. In both cases -// the dangerous command is an argument, so nothing above sees it. +// checkSegment applies every rule to one command and to any command it wraps. func checkSegment(seg Segment, depth int) error { for _, rule := range rules { if reason, hit := rule.check(seg); hit { @@ -139,11 +123,8 @@ var wrappers = map[string]bool{ "setsid": true, "unbuffer": true, "script": true, } -// unwrap returns the command a wrapper invokes. -// -// Flags, environment assignments, and bare numbers are skipped, the last -// because several wrappers take a leading value -- `timeout 30 rm -rf /` -// and `nice -n 10 rm -rf /` both have to resolve to the rm. +// unwrap returns the command a wrapper runs, skipping flags, env assignments +// and numbers. func unwrap(seg Segment) (Segment, bool) { if !wrappers[baseName(seg.Name)] { return Segment{}, false @@ -203,12 +184,7 @@ var criticalPaths = map[string]bool{ "/proc": true, "/sys": true, "/dev": true, } -// checkRecursiveDelete refuses a recursive rm whose target is a critical -// path. A recursive delete elsewhere is ordinary work and is allowed. -// -// The command is resolved through baseName so that /bin/rm and rm are judged -// alike, matching every sibling rule: comparing the raw segment name let -// /bin/rm -rf / through while blocking rm -rf /. +// checkRecursiveDelete refuses a recursive rm of a critical path. func checkRecursiveDelete(seg Segment) (string, bool) { if baseName(seg.Name) != "rm" { return "", false @@ -375,11 +351,7 @@ func checkSudoStdin(seg Segment) (string, bool) { // to intervene. var daemonNames = map[string]bool{"archied": true, "archie-agent": true} -// checkSelfTermination refuses killing the daemon that hosts the gateway. -// -// /stop, approvals, and every other control run inside archied. An agent -// that can stop it can put itself beyond reach, and the only remaining -// recourse is physical access to the host. +// checkSelfTermination refuses killing archied. func checkSelfTermination(seg Segment) (string, bool) { base := baseName(seg.Name) @@ -411,11 +383,7 @@ func checkSelfTermination(seg Segment) (string, bool) { return "", false } -// checkDaemonLaunch refuses starting another daemon. -// -// A second archied outside the supervisor competes for the same Telegram -// updates and the same queues, and nothing is tracking it -- so it cannot -// be restarted, reconfigured, or stopped through any of the usual paths. +// checkDaemonLaunch refuses starting another archied. func checkDaemonLaunch(seg Segment) (string, bool) { name := baseName(seg.Name) if name == "nohup" || name == "setsid" { diff --git a/internal/tools/command/parse.go b/internal/tools/command/parse.go index 8232b7abc..8c29451e2 100644 --- a/internal/tools/command/parse.go +++ b/internal/tools/command/parse.go @@ -1,15 +1,5 @@ -// Package command inspects shell command lines before they are executed. -// -// It exists because a substring search over a command line is wrong in both -// directions. `git commit -m "revert the rm -rf change"` is harmless and -// would be blocked; `echo x; rm -rf /` is not and, with a naive anchor on -// the start of the line, would be allowed. Deciding either way requires -// knowing where a command actually begins, which means parsing quoting and -// separators rather than pattern-matching the raw text. -// -// Tool execution owns command constraints. -// When internal/policy's evaluation API lands, [Hardline] becomes an -// evaluator registered there; the rules themselves stay here. +// Package command parses shell command lines into individual commands and +// checks them with Hardline. package command import "strings" @@ -34,13 +24,8 @@ type Segment struct { ElevationArgs []string } -// Split breaks a command line into the individual commands within it. -// -// Separators are only honoured outside quotes, which is what keeps a -// quoted argument from being read as a new command: in -// `echo "a; rm -rf /"` the semicolon is data, so the whole line is one -// segment whose command is echo. Command substitutions and subshells do -// start new commands, so `$(rm -rf /)` and `(rm -rf /)` are seen. +// Split returns the commands in line. Separators count only outside quotes; +// command substitutions and subshells start new commands. func Split(line string) []Segment { var ( segments []Segment diff --git a/internal/tools/disclosure.go b/internal/tools/disclosure.go index 210b15372..c98676161 100644 --- a/internal/tools/disclosure.go +++ b/internal/tools/disclosure.go @@ -160,12 +160,7 @@ func bridgeCallHandler(reg *Registry) Handler { } } -// BridgeTools returns the three bridge tool entries for progressive -// disclosure: tool_search, tool_describe, and tool_call. The returned -// entries are pre-configured with handlers wired to the given registry. -// -// These tools are classified as idempotent (read-only) since they do -// not directly modify state. +// BridgeTools returns tool_search, tool_describe and tool_call over reg. func BridgeTools(reg *Registry) []ToolEntry { return []ToolEntry{ { @@ -228,13 +223,8 @@ func BridgeTools(reg *Registry) []ToolEntry { } } -// ComposeForTurn builds a per-turn Registry that combines the base registry's -// tools, the per-turn extra tools, and the three bridge tools. The returned -// registry is detached from the process-wide registry: extra tools are -// per-gateway identity-bound (see agentexec.BuildToolSetFrom) and must never be -// registered globally, so composing them into a turn-local registry is the only -// way the bridge handlers (which enumerate reg.All) can discover and invoke -// them. +// ComposeForTurn returns a new registry with reg's tools, extra and the +// bridge tools. func ComposeForTurn(reg *Registry, extra []ToolEntry) (*Registry, error) { composed := NewRegistry() if reg != nil { diff --git a/internal/tools/guardrail.go b/internal/tools/guardrail.go index 635230064..978c4295c 100644 --- a/internal/tools/guardrail.go +++ b/internal/tools/guardrail.go @@ -94,11 +94,8 @@ func (d GuardrailDecision) String() string { } } -// GuardrailEngine tracks per-session and per-turn tool call outcomes and -// evaluates them against a [ToolCallGuardrailConfig] to decide whether to -// allow, warn, or hard-stop. -// -// All methods are safe for concurrent use. +// GuardrailEngine tracks tool call outcomes and decides allow, warn or stop. +// Safe for concurrent use. type GuardrailEngine struct { config ToolCallGuardrailConfig diff --git a/internal/tools/limit.go b/internal/tools/limit.go index 14a87999b..04ea9487a 100644 --- a/internal/tools/limit.go +++ b/internal/tools/limit.go @@ -1,10 +1,7 @@ package tools -// ListLimit resolves a limit value from a tool input map, falling back to -// def for anything absent or non-positive and clamping to at most max. -// -// JSON numbers decode as float64, but a model that emits an integer through -// a different provider path can arrive as int, so both are accepted. +// ListLimit returns input["limit"], defaulting to def and clamped to +// maxLimit. Accepts float64 and int. func ListLimit(input map[string]any, def, maxLimit int) int { var limit int switch v := input["limit"].(type) { diff --git a/internal/tools/minimax/minimax.go b/internal/tools/minimax/minimax.go index 40eab8cbe..cf3c49a37 100644 --- a/internal/tools/minimax/minimax.go +++ b/internal/tools/minimax/minimax.go @@ -1,12 +1,5 @@ -// Package minimax generates video through MiniMax's video-generation API: -// https://platform.minimax.io/docs/api-reference/video-generation-v2-create -// -// Generation is asynchronous on MiniMax's side (submit a job, poll for a -// result), but archied's tool subsystem has no async-tool flow control (see -// tools.ToolEntry.IsAsync's doc comment), so GenerateAndWait blocks the -// calling goroutine -- a tool call, not the model's own generating -// goroutine -- submitting and polling until the job reaches a terminal -// status or MaxWait elapses. +// Package minimax generates video with the MiniMax API. GenerateAndWait +// submits a job and polls until it finishes or MaxWait elapses. package minimax import ( diff --git a/internal/tools/minimax/tool.go b/internal/tools/minimax/tool.go index a7fcc9e3f..1300c0fbf 100644 --- a/internal/tools/minimax/tool.go +++ b/internal/tools/minimax/tool.go @@ -11,14 +11,7 @@ import ( // ToolName is the registry name of the video-generation tool. const ToolName = "generate_video" -// Tool builds the registry entry for cfg, or nil when disabled -- the -// same "withdraw entirely rather than advertise a broken capability" -// reasoning webfetch.Tool documents. -// -// Classified ClassMutating, not RequiresApproval: it creates a hosted -// resource and spends real API credits, which is a mutating action, but -// gating every call behind human approval would make the tool unusable -// for its purpose. Revisit if usage shows this needs a spend guard. +// Tool returns the generate_video tool, or nil when disabled. func Tool(cfg Config) *tools.ToolEntry { if !cfg.Enabled { return nil diff --git a/internal/tools/multimodal.go b/internal/tools/multimodal.go index 6ce5317d2..46d92f381 100644 --- a/internal/tools/multimodal.go +++ b/internal/tools/multimodal.go @@ -1,11 +1,7 @@ package tools -// MultimodalResult wraps a tool result that includes non-text content -// (images, audio, video, documents). Summary is the text fed back into -// the model's context; the actual media is written to files under -// SubdirHint rather than inlined as base64, since inlining media into -// the context window would bloat token usage for content the model -// cannot directly consume anyway. +// MultimodalResult is a tool result with media written to files; Summary is +// what the model sees. type MultimodalResult struct { // IsMultimodal is always true for this type; present so a JSON // consumer can distinguish a MultimodalResult from a plain string @@ -22,15 +18,8 @@ type MultimodalResult struct { // Files lists the full paths written under SubdirHint, in the order // the source content blocks appeared. Files []string `json:"files,omitempty"` - // URLs lists media to deliver to the user's channel. Each ref carries - // either a remote URL -- a generation API's result, for example, - // which has nowhere to go in Files because nothing was downloaded -- - // or a local Path the channel uploads. - // - // The field used to mean remote-hosted media only; it now means "media - // this result wants delivered", because a locally produced file has no - // URL and exposing one for it was rejected. The JSON name is unchanged - // so existing producers keep working. + // URLs lists media to deliver to the channel, each a remote URL or a local + // Path. URLs []MediaRef `json:"urls,omitempty"` } diff --git a/internal/tools/provider/builtin/provider.go b/internal/tools/provider/builtin/provider.go index 74e731af0..dcba840ca 100644 --- a/internal/tools/provider/builtin/provider.go +++ b/internal/tools/provider/builtin/provider.go @@ -1,11 +1,5 @@ -// Package builtin adapts the lifted tau file and shell tools to the typed -// tool-provider family. -// -// The tools themselves live in internal/tools/builtin, copied from tau with -// provenance headers. This package is the seam: it translates tau's tool -// shape (a JSON-schema struct plus an Executor taking raw JSON and a UI -// bridge) into archie's tools.ToolEntry, so the ai-sdk runtime's existing -// tool loop can call them without either side knowing about the other. +// Package builtin exposes the internal/tools/builtin file and shell tools as +// a tool provider. package builtin import ( @@ -37,12 +31,8 @@ type Provider struct { registry *toolsbuiltin.Registry } -// New creates a provider rooted at workspace. An empty workspace is a -// configuration error, reported by Start rather than silently defaulting to -// the daemon's own working directory. -// -// unrestricted lets the file tools reach absolute paths outside workspace; -// relative paths still resolve against it either way. +// New returns a provider rooted at workspace. unrestricted lets file tools +// reach absolute paths outside it. func New(workspace string, unrestricted bool) *Provider { return &Provider{workspace: workspace, unrestricted: unrestricted} } @@ -125,13 +115,8 @@ func toEntry(tool toolsbuiltin.Tool) (tools.ToolEntry, error) { }, nil } -// handlerFor adapts a tau Executor to an archie Handler. -// -// Two shape differences are bridged here. Archie hands the handler decoded -// arguments while tau's executor takes raw JSON, and tau's executor reports -// a tool-level failure in Result.IsError rather than as an error. The -// latter is surfaced as a real error so the runtime's own failure handling -// and the guardrail engine both see it. +// handlerFor adapts a builtin tool to a Handler, returning tool failures as +// errors. func handlerFor(tool toolsbuiltin.Tool) tools.Handler { return func(ctx context.Context, input map[string]any) (any, error) { if err := screen(tool.Schema.Name, input); err != nil { @@ -164,13 +149,7 @@ func handlerFor(tool toolsbuiltin.Tool) tools.Handler { } } -// screen applies the always-on command rules before a tool runs. -// -// This lives in the adapter rather than in the lifted shell tool so that -// the copied files stay diffable against tau, and so the rules are archie's -// to change. It is a floor, not a sandbox: anything with a shell has ways -// around a rule list, and the point is only that the failures with no -// recovery are not reachable by an ordinary mistake. +// screen applies command.Hardline to shell commands. func screen(name string, input map[string]any) error { if name != "shell" { return nil @@ -182,12 +161,7 @@ func screen(name string, input map[string]any) error { return nil } -// classify tags each tool so the guardrail engine and result-limit enforcement -// can reason about it. This is categorisation, not a jail: it describes -// what a tool does and does not gate whether it may run. -// -// shell is classified mutating because it can be, not because it always -// is -- the classification cannot inspect the command. +// classify returns a tool's classification. func classify(name string) tools.ToolClassification { switch name { case "read", "grep", "find": diff --git a/internal/tools/provider/mcp/provider.go b/internal/tools/provider/mcp/provider.go index e6bf3b1a4..a73b4978e 100644 --- a/internal/tools/provider/mcp/provider.go +++ b/internal/tools/provider/mcp/provider.go @@ -245,19 +245,12 @@ func (p *Provider) handlerFor(client *protocol.Client, originalName string) tool } } -// maxMediaBlockBase64Bytes caps the base64-encoded size of a single media -// content block before it is decoded and written to disk. An MCP server is -// a semi-trusted external process; without a cap, one misbehaving or -// malicious response could force the daemon to allocate and persist an -// unbounded amount of data. ~48MiB decoded (base64 is ~4/3 the size of the -// decoded payload). +// maxMediaBlockBase64Bytes caps one media block's base64 size. const maxMediaBlockBase64Bytes = 64 << 20 // 64MiB -// writeMultimodalResult decodes and writes each media block to disk under -// p.mediaDir///, returning an envelope whose URLs -// carry the local files for the channel to upload. Malformed base64 data -// is a hard error -- the server sent a content block it claimed was media -// but wasn't decodable. +// writeMultimodalResult writes each media block under +// mediaDir/// and returns a result naming the files. Bad base64 +// is an error. func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []protocol.ContentBlock) (tools.MultimodalResult, error) { result := tools.MultimodalResult{IsMultimodal: true, Summary: summaryText} root, err := p.mediaRoot() @@ -265,12 +258,7 @@ func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []p return tools.MultimodalResult{}, err } - // toolName is server-supplied (it comes from the MCP server's own - // tools/list response, not from caller-controlled input) and is used - // to build a filesystem path below. Never trust it: a malicious server - // could otherwise advertise a tool name like "../../etc/cron.d/x" to - // escape the media root. Reject any path separator or "." component - // outright rather than trying to sanitize it into something safe. + // The tool name comes from the server; refuse path traversal. if err := rejectPathTraversal(toolName); err != nil { return tools.MultimodalResult{}, fmt.Errorf("MCP tool name %q is not safe as a path component: %w", toolName, err) } @@ -321,11 +309,7 @@ func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []p return result, nil } -// mediaRoot returns the provider's media directory, creating it under the -// system temp directory on first use. Providers are long-lived relative to -// a turn (the daemon keeps them for its whole lifetime; a task worker keeps -// them for the task), so a lazily created root keeps text-only servers from -// creating directories they never need. +// mediaRoot returns the media directory, creating it on first use. func (p *Provider) mediaRoot() (string, error) { p.mu.Lock() defer p.mu.Unlock() @@ -388,12 +372,8 @@ func extensionForMimeType(mimeType string) string { } } -// mediaTypeForMimeType maps an MCP media MIME type onto the four-value -// vocabulary gateway.MediaAttachment.Type uses. Only the photo formats the -// Telegram photo endpoint accepts are classified "image": image/svg+xml and -// image/tiff are images that a photo endpoint rejects outright, so they fall -// through to "document" and still arrive as a file, mirroring -// sendfile.MediaType's photo-format list. +// mediaTypeForMimeType maps a MIME type to image, video, audio or document. +// Only photo formats count as image. func mediaTypeForMimeType(mimeType string) string { switch mimeType { case "image/png", "image/jpeg", "image/gif", "image/webp": diff --git a/internal/tools/provider/provider.go b/internal/tools/provider/provider.go index d2ab2851b..f7fe39386 100644 --- a/internal/tools/provider/provider.go +++ b/internal/tools/provider/provider.go @@ -116,13 +116,8 @@ func prepareRegistration(engine Engine, optional bool) (registration, error) { return registration{engine: engine, manifest: cloneManifest(manifest), optional: optional}, nil } -// RegisterOptional adds an engine the daemon can run without. -// -// An optional provider that fails to start or discover is logged, excluded -// from the running set, and does not roll the family back or stop the daemon. -// Required/optional is a deployment decision, not a property of the code, so -// it is stated by the registrar rather than declared in the engine's own -// manifest. +// RegisterOptional adds a provider whose failure is logged and excluded +// rather than fatal. func (r *Registry) RegisterOptional(engine Engine) error { return r.register(engine, true) } @@ -328,12 +323,8 @@ func (r *Registry) setFailed(running []runningProvider) { r.mu.Unlock() } -// startProvider starts, discovers, and indexes one provider. -// -// A required provider's failure rolls back previously-started providers and -// returns a joined error. An optional provider's failure stops only itself -// and returns the cause, leaving the family running -- Start decides which, -// since only the registrar knows whether the daemon needs this provider. +// startProvider starts and indexes one provider. A required failure rolls +// back the started providers; an optional one stops only itself. func (r *Registry) startProvider(ctx context.Context, reg registration, started []runningProvider) (runningProvider, error) { id := reg.manifest.ID diff --git a/internal/tools/provider/running.go b/internal/tools/provider/running.go index 30120337b..ccfa53f55 100644 --- a/internal/tools/provider/running.go +++ b/internal/tools/provider/running.go @@ -51,11 +51,8 @@ func (r *Registry) RunningIDs() []string { return ids } -// Add starts one provider while the family is running, indexing its tools as -// one batch. The provider is isolated: a failed start unregisters it again and -// leaves every other provider running, the plugin engine rule for a provider -// pulled in at runtime. On a registry that has not started, Add registers the -// provider and Start picks it up with the rest. +// Add starts a provider while the registry runs. A failed start removes it. +// Before Start, it only registers. func (r *Registry) Add(ctx context.Context, engine Engine) error { r.opMu.Lock() defer r.opMu.Unlock() @@ -153,12 +150,9 @@ func (r *Registry) Remove(ctx context.Context, id string) error { return nil } -// Replace swaps the provider whose manifest id matches for a new engine while -// the family is running. The old provider is stopped and the new one started; -// when the new start fails the old one is restarted, so a refused replacement -// leaves the running set as it was. A provider registered but not yet running -// is started. On a registry that has not started, Replace swaps the -// registration only and Start picks the replacement up with the rest. +// Replace swaps the running provider with the same id for engine, restoring +// the old one if the new one fails. Before Start, it only swaps the +// registration. func (r *Registry) Replace(ctx context.Context, engine Engine) error { r.opMu.Lock() defer r.opMu.Unlock() diff --git a/internal/tools/sendfile/tool.go b/internal/tools/sendfile/tool.go index e99bd377f..cc1fad58d 100644 --- a/internal/tools/sendfile/tool.go +++ b/internal/tools/sendfile/tool.go @@ -1,20 +1,5 @@ -// Package sendfile provides the send_file tool: it delivers a file that -// exists on the daemon host to the chat the turn is running in. -// -// It exists because the agent could produce a file -- a log dump, a -// transcript, a screenshot -- and had no way to hand it over. The media -// path it did have was fetch-by-URL, which only ever worked for remotely -// hosted assets, so a local path was accepted and silently delivered -// nothing. Exposing a public URL for local files was rejected: it trades a -// missing feature for a hosting and access-control problem. -// -// The tool does not send anything itself. It validates the file under the -// same path policy the read tool applies and returns a -// tools.MultimodalResult naming it, which the turn's channel delivers by -// upload. That keeps the tool free of any channel binding -- the tool -// registry is process-wide, while a chat is per-turn -- and makes every -// failure it CAN detect (unreadable, absent, refused by confinement, too -// large) a tool error the model sees, rather than a silent non-delivery. +// Package sendfile provides send_file: it validates a host file under the +// read tool's path policy and returns it for the turn's channel to upload. package sendfile import ( @@ -33,17 +18,7 @@ import ( // ToolName is the registry name of the file-delivery tool. const ToolName = "send_file" -// Upload ceilings, in bytes. These are the Telegram Bot API's, the -// tightest among the channels that can deliver at all; checking them here -// means an oversized file fails as a tool error the model can report -// instead of as a delivery failure it never sees. The channel enforces its -// own limits regardless -- this is an early, visible check, not the -// authority. -// -// Images have their own, much lower ceiling. Applying MaxUploadBytes to -// every type made the early check useless for exactly the type that needed -// it: a 20 MB screenshot passed here, was reported to the model as sent, -// and was then rejected by a layer the model cannot see. +// Upload limits in bytes, matching the Telegram Bot API. const ( MaxUploadBytes int64 = 50 * 1024 * 1024 MaxImageUploadBytes int64 = 10 * 1024 * 1024 @@ -60,13 +35,8 @@ func uploadLimit(mediaType string) int64 { return MaxUploadBytes } -// Tool builds the registry entry rooted at workspace. Relative paths -// resolve against it, and confinement (when enabled) is measured from it, -// exactly as for the read tool. -// -// Returns nil when workspace is empty: with no root there is no policy to -// apply, and a tool that reads arbitrary host files into an outbound -// message is not something to enable by defaulting. +// Tool returns send_file rooted at workspace, or nil when workspace is +// empty. func Tool(workspace string) *tools.ToolEntry { if workspace == "" { return nil @@ -156,11 +126,7 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) { }, nil } -// photoFormats are the image types a chat platform will accept through its -// photo endpoint. Membership is by exact media type rather than an -// "image/" prefix: image/svg+xml and image/tiff are images that a photo -// endpoint rejects outright, so treating the whole prefix as photo-safe -// turned a deliverable file into a failed send. As documents they arrive. +// photoFormats are the image types photo endpoints accept. var photoFormats = map[string]bool{ "image/jpeg": true, "image/png": true, @@ -168,12 +134,8 @@ var photoFormats = map[string]bool{ "image/webp": true, } -// MediaType maps a filename onto the four-value media vocabulary -// gateway.MediaAttachment.Type uses. -// -// Anything unrecognised is a document, which is the only kind that carries -// arbitrary bytes: guessing "image" wrongly makes the platform reject the -// send, while sending an image as a document still delivers the file. +// MediaType maps a filename to image, video, audio or document; unknown is +// document. func MediaType(path string) string { mt, _, _ := strings.Cut(mime.TypeByExtension(strings.ToLower(filepath.Ext(path))), ";") mt = strings.TrimSpace(mt) diff --git a/internal/tools/toolentry.go b/internal/tools/toolentry.go index 83e752fd7..5e02557f2 100644 --- a/internal/tools/toolentry.go +++ b/internal/tools/toolentry.go @@ -31,12 +31,7 @@ type CheckFn func() bool // override means the schema is static. type SchemaOverrideFn func(schema JSONSchema) JSONSchema -// ToolEntry is the foundational data type for the tools subsystem. Every -// tool -- built-in, MCP server, plugin-provided, or dynamically registered -// -// -- is represented by a ToolEntry. Fields with `json:"-"` tags are -// -// runtime-only (not serialized). +// ToolEntry describes one tool. Fields tagged json:"-" are runtime-only. type ToolEntry struct { // Name uniquely identifies this tool (e.g. "read_file", "write_file", // "mcp.github.search_repos"). Must be non-empty. @@ -85,15 +80,8 @@ type ToolEntry struct { // "🌐"). Single character or short sequence. May be empty. Emoji string `json:"emoji,omitempty"` - // BuildApprovalDescription is called with the decoded tool inputs to - // build the human-facing prompt shown when approval is required. When - // nil (the default), the tool's Description is used verbatim. - // - // The returned string should identify the specific resource being acted - // on so the human knows what they are consenting to. A prompt that says - // only "Delete a session" is not adequate; "Delete session 'Refactor - // auth' (abc12345)" is. This runs before the handler, so only the raw - // input is available — it cannot resolve references or look up titles. + // BuildApprovalDescription builds the approval prompt from the tool input. + // Nil uses Description. It should name the specific resource affected. BuildApprovalDescription func(input map[string]any) string `json:"-"` // MaxResultSizeChars caps this tool's result size in characters. diff --git a/internal/tools/webfetch/webfetch.go b/internal/tools/webfetch/webfetch.go index 19a0fb88d..40111a9cc 100644 --- a/internal/tools/webfetch/webfetch.go +++ b/internal/tools/webfetch/webfetch.go @@ -1,13 +1,5 @@ -// Package webfetch retrieves a URL on the model's behalf and returns readable -// text. -// -// The interesting part is not the fetch, it is the refusals. archied runs on a -// host where the Docker API, NATS and its own dashboard answer on private -// addresses, and the URL it is asked to fetch arrives in chat -- an untrusted -// path, since a forge issue body or an inbound email can end up quoted into a -// turn. So the address is vetted at dial time rather than by inspecting the -// URL: a name that looks public can resolve to a private address, and only the -// resolved address tells the truth. +// Package webfetch fetches a URL for the model and returns readable text, +// refusing private and local addresses at dial time. package webfetch import ( @@ -213,12 +205,8 @@ func unwrapFetchError(err error) error { return err } -// dialContext resolves the host and refuses addresses the daemon must not be -// talked into reaching, then dials a vetted address directly. -// -// Vetting here rather than on the URL is the whole point: between a pre-flight -// check and the connection, a name can resolve to something else. Dialing the -// address that was actually approved closes that window. +// dialContext resolves host, refuses forbidden addresses and dials the vetted +// address. func (c *Client) dialContext(ctx context.Context, network, addr string) (net.Conn, error) { host, port, err := net.SplitHostPort(addr) if err != nil { diff --git a/internal/webhookguard/doc.go b/internal/webhookguard/doc.go index 3e5de0b11..457c1d2f1 100644 --- a/internal/webhookguard/doc.go +++ b/internal/webhookguard/doc.go @@ -1,8 +1,3 @@ -// Package webhookguard provides storage-agnostic mechanics for vetting -// inbound webhook-shaped HTTP requests before anything trusts them: -// signature verification, per-source rate limiting, and payload redaction. -// -// It owns none of a caller's vocabulary -- not what a "source" is, not how a -// captured event is stored, not what a binding's approval state means. Those -// stay with the packages that own that state. +// Package webhookguard verifies, rate-limits and redacts inbound webhook +// requests. package webhookguard diff --git a/internal/webhookguard/hmac.go b/internal/webhookguard/hmac.go index 0233bb34a..c9f5a2e0d 100644 --- a/internal/webhookguard/hmac.go +++ b/internal/webhookguard/hmac.go @@ -7,13 +7,8 @@ import ( "strings" ) -// VerifyHMAC checks a SHA-256 HMAC signature against body using secret, -// accepting a signature with or without the "sha256=" prefix GitHub and -// similar senders use. The digest is hex, which is case-insensitive by -// convention and by sender taste, so an uppercase signature verifies rather -// than masquerading as a wrong secret. An empty signature is never valid, even -// against an empty secret -- the absence of a signature must never be mistaken -// for one that happens to match. +// VerifyHMAC checks a hex SHA-256 HMAC of body, with or without a "sha256=" +// prefix, case-insensitively. An empty signature never verifies. func VerifyHMAC(body []byte, signature, secret string) bool { if signature == "" { return false diff --git a/internal/webhookguard/ratelimit.go b/internal/webhookguard/ratelimit.go index 80cdbcaf5..8fa693006 100644 --- a/internal/webhookguard/ratelimit.go +++ b/internal/webhookguard/ratelimit.go @@ -5,13 +5,7 @@ import ( "time" ) -// RateLimiter caps request volume per source using a token bucket per source -// ID. Source IDs are assumed to come from a registered, operator- controlled -// set, not from unbounded attacker-supplied request data -- the bucket map is -// not itself bounded, because the key space is bounded by registration. -// -// A rejected request must be surfaced as an observable rejection by the caller -// (HTTP 429), never silently dropped. +// RateLimiter is a per-source token bucket. Sources must be a bounded set. type RateLimiter struct { mu sync.Mutex rate float64 // tokens added per second diff --git a/internal/webhookguard/redact.go b/internal/webhookguard/redact.go index a15b6efc5..60382ba3a 100644 --- a/internal/webhookguard/redact.go +++ b/internal/webhookguard/redact.go @@ -10,14 +10,7 @@ import ( // redactedValue replaces a value whose key (or shape) looks sensitive. const redactedValue = "[redacted]" -// SensitiveKeyMarkers is the key-name heuristic shared by both redaction -// paths -- webhook-capture redaction here and chat-transcript -// summarization in internal/gateway/stream.go's sensitiveParameterKey -- -// so they agree on what counts as sensitive. It is intentionally -// conservative: a value whose key matches is redacted wholesale, so a marker -// that is too broad (e.g. bare "key" or "auth", which would match "Key: 42" -// or "author") would destroy the schema-by-example mapping use case the -// captured payload exists to serve. +// SensitiveKeyMarkers are key substrings whose values are redacted. var SensitiveKeyMarkers = []string{ "token", "secret", "password", "passwd", "pwd", "passphrase", "api_key", "apikey", "api_secret", "client_secret", "private_key", "secret_key", @@ -31,24 +24,8 @@ var SensitiveKeyMarkers = []string{ // when a sender puts it under a key the name heuristic misses. var jwtTokenRe = regexp.MustCompile(`^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$`) -// RedactPayload replaces values under sensitive-looking JSON keys with a -// redaction marker and returns the re-encoded payload, for capturing an -// inbound webhook body before persisting it. -// -// This intentionally does NOT reuse internal/gateway/stream.go's -// SummarizeToolParameters shape unchanged: that function replaces every string -// value regardless of key, which produces a bounded one-line summary for a chat -// transcript. A captured webhook payload exists to be inspected and mapped -// field-by-field -- redacting every string would make that impossible. Only a -// value whose key matches the marker list, or whose value is an unambiguous -// secret shape, is touched; everything else is returned exactly as decoded. -// -// A key match redacts its entire value, including a nested object or array -// -- "credentials": {"host": ..., "user": ...} is wholesale replaced, not -// recursed into, matching the intent of the key name. -// -// This is best-effort, not a guarantee: a sender that names a secret field -// something the heuristic misses is still captured with its secret. +// RedactPayload replaces values under sensitive keys, or with secret-shaped +// values, with a marker and returns the re-encoded JSON. Best-effort. func RedactPayload(payload []byte) ([]byte, error) { var value any decoder := json.NewDecoder(strings.NewReader(string(payload))) diff --git a/internal/worktreerpc/worktreerpc.go b/internal/worktreerpc/worktreerpc.go index 6abf3a621..0fe870df7 100644 --- a/internal/worktreerpc/worktreerpc.go +++ b/internal/worktreerpc/worktreerpc.go @@ -1,12 +1,5 @@ -// Package worktreerpc lets archie-agent request publication of the task branch -// over core NATS request/reply without holding the forge credential itself. -// archied has already prepared the bind-mounted worktree before the container -// starts. Publication is authorized by an opaque per-dispatch grant; sandbox -// input never selects a host path, repository, or branch. -// -// CommitAll/Diff/ChangedFiles/ChangedLines are purely local git -// operations against the already-mounted worktree and don't need the -// credential, so they run directly inside archie-agent. +// Package worktreerpc lets archie-agent ask archied to push the task branch +// over NATS, authorized by a per-dispatch grant. package worktreerpc import ( @@ -31,12 +24,8 @@ const ( SubjectPush = "archie.worktree.push" ) -// SubjectFor returns the subject for base, scoped to identity when set. -// An empty identity uses the root subject (single-identity deployments and -// agent images that predate identity routing). The daemon registers one -// server per identity on these scoped subjects so a container-mode task -// owned by a non-root identity has its push/prepare calls served by that -// identity's own worktree manager (its own credential and workdir). +// SubjectFor returns base scoped to identity, or base when identity is +// empty. func SubjectFor(identity, base string) string { if identity == "" { return base @@ -117,12 +106,7 @@ type Server struct { Timeout time.Duration } -// handlerContext returns the context a single request runs under. -// -// NATS request/reply carries no deadline from the caller, and the work -// now runs in-process through go-git rather than as a killable child -// process, so the server has to impose its own bound. Without one an -// unresponsive forge holds this handler's goroutine forever. +// handlerContext returns a context bounded by s.Timeout. func (s *Server) handlerContext() (context.Context, context.CancelFunc) { timeout := s.Timeout if timeout <= 0 { diff --git a/tools/newsgen/main.go b/tools/newsgen/main.go index 9e1691472..d17366729 100644 --- a/tools/newsgen/main.go +++ b/tools/newsgen/main.go @@ -1,18 +1,5 @@ -// Command newsgen derives every published release fact from CHANGELOG.md. -// -// CHANGELOG.md is the release process's frozen notes: tools/release.sh -// --prepare writes a section, the maintainer edits it, and --tag refuses to tag -// a version without its section. Tags are deliberately not a source, because CI -// and deployment check out shallow and a site build has no tags to read. -// -// Generated and committed artifacts: -// -// docs/news/releases.json the canonical, host-neutral fact set -// docs/news/redirects.json the retired per-component URLs, mapped to pages -// -// `newsgen check` reproduces the output in memory and fails when the committed -// files differ, which keeps a changelog edit from landing without updating the -// artifacts consumed by the external documentation site. +// Command newsgen generates docs/news/releases.json and redirects.json from +// CHANGELOG.md. `newsgen check` fails when the committed files are stale. package main import ( diff --git a/ui/embed.go b/ui/embed.go index 6e6975af4..87c6fce15 100644 --- a/ui/embed.go +++ b/ui/embed.go @@ -1,13 +1,7 @@ //go:build !no_ui -// Package ui embeds archied's built dashboard. It carries no behaviour -- -// internal/webui owns serving and the HTTP API -- so that the frontend build -// artefact stays a separate concern from the server that hands it out. -// -// dist/ is committed deliberately. Without it `go build`, `go install` and -// the CI gate would each need a Node toolchain present merely to compile the -// daemon, which is a poor trade for a project whose quality gate is -// `task check`. Rebuild it with `task ui`. +// Package ui embeds the built dashboard in dist/, which is committed. Rebuild +// with `task ui`. package ui import (