diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 53900f969..3030ed54d 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -29,13 +29,17 @@ See `docs/architecture/organisation.md` for the target structure and | `internal/config/` | Config types only — loading lives in `infrastructure/configuration` | | `internal/daemon/` | Resident loop: poll, enqueue, claim, route, process, reconcile | | `internal/domain/workflow/` | Engine: stage lists, routing, shared steps, workflow definitions | +| `internal/domain/workflow/task/` | Task-execution vocabulary (`Task`, statuses, mid-run `Store`, `Definition`) importable without the engine | +| `internal/domain/messaging/` | Canonical messages plus the chat wire contracts (`ChatContract`, sessions, turns, streaming) shared by gateway, channels, webui, and archie-ui | +| `internal/channels/status/` | Operator-facing channel lifecycle ledger (`State`/`Descriptor`/`Status`/`Manager`); the plugin contract stays in `internal/channels` | | `internal/domain/workintake/`| `TaskEnvelope`, routing `Kind`, label vocabulary, task subjects | | `internal/agentexec/` | Worker-local stage protocol and ai-sdk loop runner | | `internal/forge/` | Forge interface: GitHub and Gitea implementations | | `internal/forge/webhook/` | Optional forge webhook receiver: GitHub issue events → `workintake.TaskEnvelope`, same publish path as polling | | `internal/webhookguard/` | Cross-cutting inbound-webhook mechanics: HMAC verification, per-source rate limiting | | `internal/worktree/` | Git operations: clone, branch, commit, push, diff, cleanup | -| `internal/store/` | Task store interface and SQLite implementation; RPC clients proxy it | +| `internal/store/` | Task/capture/mapping/binding SQLite implementation; producer-owned contract interfaces live in `internal/domain/storecontract` (aliases kept here) | +| `internal/domain/storecontract/` | Producer-owned State Store read contracts consumed by webui, intake, and the gRPC adapters (state-store-contract rev. 2d) | | `internal/events/` | In-process event bus: publish/subscribe for observability | | `internal/infrastructure/` | Config loading, eventbus transport, model catalog | | `internal/webui/` | Shared dashboard HTTP layer served by the archie-ui process | diff --git a/docs/prds/state-store-contract.md b/docs/prds/state-store-contract.md index 80695956f..31298c0d9 100644 --- a/docs/prds/state-store-contract.md +++ b/docs/prds/state-store-contract.md @@ -88,6 +88,16 @@ Phase 2 acceptance criterion and the architecture's rules simultaneously satisfi > producer-owned interfaces may move to the same infrastructure package (or an approved > contract location) when the store implementation relocates. Agents must not treat > `internal/store` as the final infrastructure boundary. +> +> **REV. 2d (archie-core-8cda.5.6): the producer-owned interfaces HAVE moved to an approved +> contract location** — `internal/domain/storecontract` (package `storecontract`), ahead of the +> store implementation's own relocation. The UI Service deletion gate required the archie-ui +> process to hold the contracts without linking `internal/store`'s SQL implementation, and +> `internal/contracts/` itself is ruled out: that tree is the `buf generate` output and +> `tools/proto.sh check` deletes hand-written files there. `internal/store` keeps type aliases +> (`type TaskStore = storecontract.TaskStore`, the sentinel `var`s, the value types) so +> daemon-side callers are unaffected; the sentinel message strings are unchanged and remain +> the wire contract (§4). --- diff --git a/docs/prds/ui-service-boundary.md b/docs/prds/ui-service-boundary.md index abf7bdebc..8feff83e6 100644 --- a/docs/prds/ui-service-boundary.md +++ b/docs/prds/ui-service-boundary.md @@ -205,6 +205,35 @@ yet satisfy this boundary. This document is the ratified target; the implementation child must prove each migration gate before claiming Phase 3 complete. +### Deletion gate: SATISFIED (archie-core-8cda.5.6, rev. 2) + +The objective gate now holds. `go list -deps ./cmd/archie-ui` links **zero** +banned packages: no `modernc.org/sqlite`, no `internal/store`, `internal/gateway`, +`internal/channels`, `internal/memory`, `internal/secret`, `internal/agentexec`, +`internal/tools`, `internal/skill`, `internal/yaegiutil`, `internal/domain/curator`, +or the workflow engine (`internal/domain/workflow`). How the runtime handles were +severed, each at the producer: + +- **Store contracts** moved to `internal/domain/storecontract` (producer-owned + read contracts, state-store-contract rev. 2d); `internal/store` keeps aliases. +- **Chat contracts** moved to `internal/domain/messaging`; `internal/gateway` + keeps aliases. The UI process holds `ChatContract`, `SessionStore`, turn and + stream types without linking the gateway runtime or its SQLite session store. +- **Webui-owned views** replaced concrete runtime handles on `webui.Server`: + channel lifecycle via `internal/channels/status`, memory via a `MemoryStatus` + interface, curators via a `CuratorStatus` interface, and the skill catalogue + via a `SkillCatalog` interface — each supplied by a daemon-side adapter at + bootstrap, each degrading to an empty page when unwired. +- **`config.SecretRef`** moved into `internal/config` (it is config vocabulary); + `internal/secret` keeps an alias and resolves through `Registry.Resolve`. +- **Task vocabulary** (`Task`, `Store`, `Definition`, status constants) split + into `internal/domain/workflow/task`; the pipeline engine stays in package + `workflow`, which keeps aliases. The UI process links the vocabulary only. + +Remaining for Phase 3 closure: the architecture tests asserting the absence of +`config.Holder`, concrete store/gateway runtime types, and direct SQLite imports +in the UI service, plus the end-to-end smoke suite over real processes. + ## Non-goals and open work This ratification does not define a new domain model, move the dashboard's diff --git a/internal/app/archied/binding_cipher.go b/internal/app/archied/binding_cipher.go index 0da77d9c4..b5fc1f465 100644 --- a/internal/app/archied/binding_cipher.go +++ b/internal/app/archied/binding_cipher.go @@ -17,7 +17,7 @@ func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (store if cfg.Bindings.EncryptionKey == (secret.SecretRef{}) { return nil, nil } - active, err := cfg.Bindings.EncryptionKey.Resolve(secrets) + active, err := secrets.Resolve(cfg.Bindings.EncryptionKey) if err != nil { return nil, fmt.Errorf("resolve bindings encryption_key: %w", err) } @@ -28,7 +28,7 @@ func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (store previous := make([]string, 0, len(cfg.Bindings.PreviousEncryptionKeys)) for _, ref := range cfg.Bindings.PreviousEncryptionKeys { - v, err := ref.Resolve(secrets) + v, err := secrets.Resolve(ref) if err != nil { return nil, fmt.Errorf("resolve bindings previous_encryption_key: %w", err) } diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index d917b4680..788af0170 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -24,18 +24,18 @@ import ( "github.com/samcharles93/ai-sdk/runtime" - channelruntime "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/channels/email" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/channels/webhook" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/eda/module" "github.com/samcharles93/archie-core/internal/domain/eda/playbook" domainembedding "github.com/samcharles93/archie-core/internal/domain/embedding" domainmemory "github.com/samcharles93/archie-core/internal/domain/memory" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild" "github.com/samcharles93/archie-core/internal/domain/workintake" @@ -99,7 +99,7 @@ type boot struct { playbooks *playbook.Store - st storev1.TaskStore + st storecontract.TaskStore // stateStore is the State Store contract adapter every daemon and gateway // store consumer depends on. It is ALWAYS the remote *staterpc.Client // dialed to the standalone archie-state-store gRPC service at @@ -108,7 +108,7 @@ type boot struct { // by openStateStoreAdapter, which requires [services.state].target to be // set. The b.st field remains solely for the standalone archie-state-store // binary, which owns the single SQLite file. - stateStore storev1.TaskStore + stateStore storecontract.TaskStore // stateStoreGrants issues per-task, scoped State Store credentials for // agent containers (daemon.StateStoreGrantIssuer), wrapping the same // *staterpc.Client as stateStore. Nil when the State Store adapter isn't @@ -123,7 +123,7 @@ type boot struct { bus *events.Bus restartTelegram func() error - channelManager *channelruntime.Manager + channelManager *status.Manager web *webui.Server natsClient *nats.Client @@ -378,7 +378,7 @@ func (b *boot) setupObservability(ctx context.Context) { if (cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "") && len(cfg.Chat.Telegram.AllowedUserIDs) == 0 { telegramDetail = "Token set, but the allowlist is empty -- the bot answers nobody." } - b.channelManager = channelruntime.NewManager([]channelruntime.Descriptor{ + b.channelManager = status.NewManager([]status.Descriptor{ {ID: "telegram", Name: "Telegram", Configured: cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "", ReloadSupported: cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "", Detail: telegramDetail}, {ID: "email", Name: "Email", Configured: cfg.Chat.Email.ListenAddr != ""}, {ID: "webhook", Name: "Webhook gateway", Configured: cfg.Chat.WebhookAddr != ""}, @@ -389,7 +389,7 @@ func (b *boot) setupObservability(ctx context.Context) { Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature), }) } - b.web = &webui.Server{Log: log.With("component", "webui"), Cfg: config.NewHolder(cfg), Channels: b.channelManager} + b.web = &webui.Server{Log: log.With("component", "webui"), Cfg: config.NewHolder(cfg), Channels: b.channelManager, Skills: skillCatalogAdapter{config.NewHolder(cfg)}} // The watchdog leaves its verdict in a file on this host, so the daemon // reads it and publishes the outcome as an event; the dashboard renders // what it receives, wherever it runs (archie-core-8cda.5.4). @@ -895,7 +895,7 @@ func (b *boot) setupMemory() error { // The dashboard is built before memory exists, so it is wired in here // rather than at construction. if b.web != nil { - b.web.Memory = memManager + b.web.Memory = memoryUIAdapter{memManager} } if err := memManager.Initialize("daemon"); err != nil { @@ -1181,7 +1181,7 @@ func (b *boot) registerMinimaxTool(cfg config.Config, log *slog.Logger) { return } - apiKey, err := cfg.Tools.Minimax.APIKey.Resolve(b.secrets) + apiKey, err := b.secrets.Resolve(cfg.Tools.Minimax.APIKey) if err != nil { log.Warn("minimax video generation enabled but the API key failed to resolve; tool not registered", "err", err) return @@ -1223,15 +1223,15 @@ func (b *boot) buildDaemon() { ContainerPool: b.containerPool, Guardrails: b.guardrails, ToolRegistry: b.toolReg, - Curators: b.curatorRegistry, Identities: b.identityRunners, TaskLogs: b.taskLogs, AgentStatus: b.agentStatus, } // Curator observability (archie-core-1786637489932-6): GET // /api/curators reads registered names, health and recent activity - // straight off the live registry the daemon already holds. - b.web.Curators = b.curatorRegistry + // off the live registry the daemon already holds, narrowed to the + // webui's own view type. + b.web.Curators = curatorsUIAdapter{b.curatorRegistry} // web and the daemon must share ONE Holder: a reload swaps d.Cfg and // the dashboard reads the running config from the same snapshot. The // webui Holder seeded in the literal above is replaced here; after @@ -1241,16 +1241,16 @@ func (b *boot) buildDaemon() { // Consumer mapping/binding surfaces resolve from b.stateStore (the State // Store contract adapter): local by default, remote *staterpc.Client when // [services.state].target is set. See docs/prds/state-store-contract.md §10. - if ms, ok := b.stateStore.(storev1.MappingStore); ok { + if ms, ok := b.stateStore.(storecontract.MappingStore); ok { b.d.Mappings = ms } - if bs, ok := b.stateStore.(storev1.BindingStore); ok { + if bs, ok := b.stateStore.(storecontract.BindingStore); ok { b.d.Bindings = bs } - if bd, ok := b.stateStore.(storev1.BindingDispatcher); ok { + if bd, ok := b.stateStore.(storecontract.BindingDispatcher); ok { b.d.BindingDispatcher = bd } - if btc, ok := b.stateStore.(storev1.BindingTaskCreator); ok { + if btc, ok := b.stateStore.(storecontract.BindingTaskCreator); ok { b.d.BindingTaskCreator = btc } b.setupForgeWebhook() @@ -1288,7 +1288,7 @@ func (b *boot) setupForgeWebhook() { log.Error("forge webhook disabled: multi-identity deployments are not supported yet (each identity's own poll loop is unaffected)") return } - secretValue, err := cfg.Forge.WebhookSecret.Resolve(b.secrets) + secretValue, err := b.secrets.Resolve(cfg.Forge.WebhookSecret) if err != nil || secretValue == "" { log.Error("forge webhook disabled: secret unavailable", "engine", cfg.Forge.WebhookSecret.Engine, "key", cfg.Forge.WebhookSecret.Key, "err", err) @@ -1340,7 +1340,7 @@ func (b *boot) publishConfig(ctx context.Context, cfg config.Config, provenance // propagated: it must never fail the reload or dashboard write that produced // the new configuration, both of which have already taken effect. func (b *boot) publishConfigSnapshot(ctx context.Context) { - snapshots, ok := b.stateStore.(storev1.ConfigSnapshotStore) + snapshots, ok := b.stateStore.(storecontract.ConfigSnapshotStore) if !ok || b.web == nil { return } @@ -1362,7 +1362,7 @@ func (b *boot) publishConfigSnapshot(ctx context.Context) { b.log.Warn("config snapshot not published", "err", err) return } - err = snapshots.PutConfigSnapshot(ctx, storev1.ConfigSnapshot{ + err = snapshots.PutConfigSnapshot(ctx, storecontract.ConfigSnapshot{ Schema: webui.ConfigViewSchema, Document: document, PublishedAt: time.Now().UTC(), diff --git a/internal/app/archied/channel_lifecycle_test.go b/internal/app/archied/channel_lifecycle_test.go index e093da5a3..6231de658 100644 --- a/internal/app/archied/channel_lifecycle_test.go +++ b/internal/app/archied/channel_lifecycle_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - channelruntime "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/webui" @@ -42,7 +42,7 @@ func TestConfiguredNetworkGatewaysBecomeRunning(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = st.Close() }) - manager := channelruntime.NewManager([]channelruntime.Descriptor{{ + manager := status.NewManager([]status.Descriptor{{ ID: test.id, Name: test.name, Configured: true, }}) b := &boot{ @@ -66,13 +66,13 @@ func TestConfiguredNetworkGatewaysBecomeRunning(t *testing.T) { deadline := time.Now().Add(250 * time.Millisecond) for time.Now().Before(deadline) { - if got := manager.Snapshot()[0].State; got == channelruntime.StateRunning { + if got := manager.Snapshot()[0].State; got == status.StateRunning { return } time.Sleep(time.Millisecond) } t.Fatalf("channel state = %q, want %q after successful startup", - manager.Snapshot()[0].State, channelruntime.StateRunning) + manager.Snapshot()[0].State, status.StateRunning) }) } } diff --git a/internal/app/archied/curator_ui.go b/internal/app/archied/curator_ui.go new file mode 100644 index 000000000..0bb30e38b --- /dev/null +++ b/internal/app/archied/curator_ui.go @@ -0,0 +1,50 @@ +package archied + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/curator" + "github.com/samcharles93/archie-core/internal/webui" +) + +// curatorsUIAdapter narrows the running curator registry to the webui-owned +// CuratorStatus view. The webui deliberately does not link the curator +// pass-engine contract (archie-core-8cda.5.6), so the process that owns the +// registry supplies this adapter at bootstrap. It converts health and +// activity records to their wire views; it never hands the UI a live +// engine. +type curatorsUIAdapter struct{ r *curator.Registry } + +var _ webui.CuratorStatus = curatorsUIAdapter{} + +func (a curatorsUIAdapter) Names() []string { return a.r.Names() } + +func (a curatorsUIAdapter) Health(ctx context.Context) map[string]webui.CuratorHealthView { + health := a.r.Health(ctx) + views := make(map[string]webui.CuratorHealthView, len(health)) + for name, h := range health { + views[name] = webui.CuratorHealthView{Status: string(h.Status), Message: h.Message} + } + return views +} + +func (a curatorsUIAdapter) Activity(name string) (webui.CuratorActivity, bool) { + activity, ok := a.r.Activity(name) + if !ok { + return webui.CuratorActivity{}, false + } + view := webui.CuratorActivity{ + LastRunAt: activity.LastRunAt, + LastRunActions: activity.LastRunActions, + Recent: make([]webui.CuratorActionView, 0, len(activity.Recent)), + } + for _, a2 := range activity.Recent { + view.Recent = append(view.Recent, webui.CuratorActionView{ + At: a2.At, + Type: a2.Type, + Detail: a2.Detail, + Reason: a2.Reason, + }) + } + return view, true +} diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 729076b37..2104e455f 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -29,9 +29,9 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/domain/curator" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -269,7 +269,7 @@ func resolveForge(cfg config.Forge, secrets *secret.Registry, log *slog.Logger) if configuration.ForgeDisabled(cfg.Type) { return forge.NewNoop(log), "" } - token, err := cfg.Token.Resolve(secrets) + token, err := secrets.Resolve(cfg.Token) if err != nil || token == "" { log.Warn("forge disabled: token unavailable", "forge_type", cfg.Type, @@ -287,7 +287,7 @@ func resolveForge(cfg config.Forge, secrets *secret.Registry, log *slog.Logger) return client, token } -func openProductionTaskStore(ctx context.Context, path string, opts ...store.OpenOption) (storev1.TaskStore, error) { +func openProductionTaskStore(ctx context.Context, path string, opts ...store.OpenOption) (storecontract.TaskStore, error) { return store.Open(ctx, path, opts...) } @@ -304,7 +304,7 @@ func configDBPath(configuredPath string) string { return configuredPath + "-config.sqlite" } -func manualRequeueTask(ctx context.Context, st storev1.TaskStore, taskID int64) error { +func manualRequeueTask(ctx context.Context, st storecontract.TaskStore, taskID int64) error { task, err := st.TaskByID(ctx, taskID) if err != nil { return err @@ -517,7 +517,7 @@ func recordBootOverlayError(p *atomic.Pointer[string], log *slog.Logger, err err // The insert deliberately outlives ctx: this loop ends when the bus closes, // which is part of shutdown, and the last events of a run are exactly the // ones an operator wants to read afterwards. -func persistEvents(ctx context.Context, sink *events.Sub, st storev1.TaskStore, log *slog.Logger) { +func persistEvents(ctx context.Context, sink *events.Sub, st storecontract.TaskStore, log *slog.Logger) { ctx = context.WithoutCancel(ctx) for e := range sink.C { if e.ID != 0 { diff --git a/internal/app/archied/memory_ui.go b/internal/app/archied/memory_ui.go new file mode 100644 index 000000000..0622c0997 --- /dev/null +++ b/internal/app/archied/memory_ui.go @@ -0,0 +1,41 @@ +package archied + +import ( + "github.com/samcharles93/archie-core/internal/memory" + "github.com/samcharles93/archie-core/internal/webui" +) + +// memoryUIAdapter narrows the running memory runtime to the webui-owned +// MemoryStatus view. The webui deliberately does not link the memory +// package (archie-core-8cda.5.6), so the process that owns the runtime +// supplies this adapter at bootstrap. It renders names, readiness, and the +// tool vocabulary by name; it never hands the UI a live tool. +type memoryUIAdapter struct{ m *memory.Manager } + +var _ webui.MemoryStatus = memoryUIAdapter{} + +func (a memoryUIAdapter) Builtin() webui.MemoryProviderHandle { + return memoryProviderUIAdapter{a.m.Builtin()} +} + +func (a memoryUIAdapter) External() webui.MemoryProviderHandle { + return memoryProviderUIAdapter{a.m.External()} +} + +// memoryProviderUIAdapter converts one provider's runtime tool entries into +// the webui's name/description view. A nil provider renders as absent. +type memoryProviderUIAdapter struct{ p memory.MemoryProvider } + +func (a memoryProviderUIAdapter) Name() string { return a.p.Name() } +func (a memoryProviderUIAdapter) IsAvailable() bool { return a.p.IsAvailable() } +func (a memoryProviderUIAdapter) ToolViews() []webui.MemoryToolView { + if a.p == nil { + return nil + } + schemas := a.p.GetToolSchemas() + views := make([]webui.MemoryToolView, 0, len(schemas)) + for _, t := range schemas { + views = append(views, webui.MemoryToolView{Name: t.Name, Description: t.Description}) + } + return views +} diff --git a/internal/app/archied/provider_secrets.go b/internal/app/archied/provider_secrets.go index 9a4bea4c3..90e643a22 100644 --- a/internal/app/archied/provider_secrets.go +++ b/internal/app/archied/provider_secrets.go @@ -53,7 +53,7 @@ func resolveProviderMap(scope string, providers map[string]config.Provider, regi if provider.APIKey == (secret.SecretRef{}) { continue } - value, err := provider.APIKey.Resolve(registry) + value, err := registry.Resolve(provider.APIKey) if err != nil { return fmt.Errorf("provider %q: %w", id, err) } diff --git a/internal/app/archied/readiness.go b/internal/app/archied/readiness.go index 9dce30475..9c495d213 100644 --- a/internal/app/archied/readiness.go +++ b/internal/app/archied/readiness.go @@ -12,7 +12,7 @@ import ( "strings" "time" - channelruntime "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" @@ -42,7 +42,7 @@ func (b *boot) setupReadinessProbes() { // channelStates projects a channel lifecycle snapshot into the readiness // probe's view, so the probe does not depend on the channels package's // concrete type. -func channelStates(m *channelruntime.Manager) []readiness.ChannelState { +func channelStates(m *status.Manager) []readiness.ChannelState { if m == nil { return nil } diff --git a/internal/app/archied/readiness_test.go b/internal/app/archied/readiness_test.go index f64eefa0e..8cb2dada7 100644 --- a/internal/app/archied/readiness_test.go +++ b/internal/app/archied/readiness_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - channelruntime "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/store" @@ -33,7 +33,7 @@ func TestDiskProbePath_FallsBackToCwd(t *testing.T) { } func TestChannelStates_ProjectsSnapshot(t *testing.T) { - m := channelruntime.NewManager([]channelruntime.Descriptor{ + m := status.NewManager([]status.Descriptor{ {ID: "telegram", Name: "Telegram", Configured: true}, {ID: "email", Name: "Email", Configured: false}, }) @@ -95,7 +95,7 @@ func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) { st: st, web: &webui.Server{ Cfg: config.NewHolder(cfg), - Channels: channelruntime.NewManager([]channelruntime.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}), + Channels: status.NewManager([]status.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}), Chat: &webui.ChatService{ Contract: &gateway.LocalChatAdapter{ Router: &gateway.Router{}, diff --git a/internal/app/archied/skill_ui.go b/internal/app/archied/skill_ui.go new file mode 100644 index 000000000..82366da9d --- /dev/null +++ b/internal/app/archied/skill_ui.go @@ -0,0 +1,54 @@ +package archied + +import ( + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/skill" + "github.com/samcharles93/archie-core/internal/webui" +) + +// skillCatalogAdapter serves the webui's skill catalogue view from the +// runtime cataloguer. The webui deliberately does not link internal/skill +// (archie-core-8cda.5.6), so the process that owns the config and the +// runtime supplies this adapter at bootstrap. +type skillCatalogAdapter struct{ cfg *config.Holder } + +var _ webui.SkillCatalog = skillCatalogAdapter{} + +// Skills discovers and renders the catalogue: project, explicitly shared, +// and user-global skills; earlier roots win when names collide. A discovery +// failure renders as an empty catalogue -- the page answers "what can +// Archie do" from whatever loaded, never a failed dashboard. +func (a skillCatalogAdapter) Skills() []webui.SkillView { + cfg := a.cfg.Get() + roots := skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir) + catalog, err := skill.CatalogRoots(roots...) + if err != nil { + return []webui.SkillView{} + } + views := make([]webui.SkillView, 0, len(catalog)) + for _, entry := range catalog { + views = append(views, webui.SkillView{ + Name: entry.Name, + Description: entry.Description, + Workflow: entry.Workflow, + Source: skillSource(entry.Root, cfg.WorkDir, cfg.SkillsDir), + }) + } + return views +} + +// skillSource labels where a skill was loaded from. +// +// sharedDir is checked first: when it equals workDir the roots collapse to one +// entry, and matching workDir first labelled every shared skill as a project +// skill. +func skillSource(root, workDir, sharedDir string) string { + switch root { + case sharedDir: + return "shared skills" + case workDir: + return "project skills" + default: + return "user-global skills" + } +} diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 3cff36505..e91969a5c 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -20,8 +20,8 @@ import ( "google.golang.org/grpc" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/store" @@ -120,28 +120,28 @@ func (b *boot) openStateStore(ctx context.Context) error { } // stateStoreDeps assembles the store surfaces the StateStore service fronts. -// b.st is the narrow storev1.TaskStore; the wide *store.Store also implements +// b.st is the narrow storecontract.TaskStore; the wide *store.Store also implements // the capture/mapping/binding surfaces, so each is asserted here (the same // pattern the daemon's wireWebStoreSurfaces uses) and a store that lacks one // degrades that group rather than aborting boot. func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants} - if cs, ok := b.st.(storev1.CaptureStore); ok { + if cs, ok := b.st.(storecontract.CaptureStore); ok { deps.Captures = cs } - if ms, ok := b.st.(storev1.MappingStore); ok { + if ms, ok := b.st.(storecontract.MappingStore); ok { deps.Mappings = ms } - if bs, ok := b.st.(storev1.BindingStore); ok { + if bs, ok := b.st.(storecontract.BindingStore); ok { deps.Bindings = bs } - if bd, ok := b.st.(storev1.BindingDispatcher); ok { + if bd, ok := b.st.(storecontract.BindingDispatcher); ok { deps.BindingDispatcher = bd } - if btc, ok := b.st.(storev1.BindingTaskCreator); ok { + if btc, ok := b.st.(storecontract.BindingTaskCreator); ok { deps.BindingTaskCreator = btc } - if css, ok := b.st.(storev1.ConfigSnapshotStore); ok { + if css, ok := b.st.(storecontract.ConfigSnapshotStore); ok { deps.ConfigSnapshots = css } return deps diff --git a/internal/app/archied/telegram_setup.go b/internal/app/archied/telegram_setup.go index 7cbf6405b..c77017764 100644 --- a/internal/app/archied/telegram_setup.go +++ b/internal/app/archied/telegram_setup.go @@ -13,11 +13,11 @@ import ( "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" - channelruntime "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/channels/telegram" "github.com/samcharles93/archie-core/internal/config" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/daemon" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" @@ -38,7 +38,7 @@ type telegramSetup struct { Cfg *config.Holder CfgPath string OverlayPath string - St storev1.TaskStore + St storecontract.TaskStore LLM *runtime.Runtime ChatModels gateway.ModelManager ToolReg *tools.Registry @@ -59,7 +59,7 @@ type telegramSetup struct { // disables turn events (tests, minimal setups). Bus *events.Bus Log *slog.Logger - ChannelManager *channelruntime.Manager + ChannelManager *status.Manager // AgentStatus is the composition root's shared tracker for the most // recently observed archie-agent version (see daemon.AgentStatus). // Nil disables the agent component of RunningVersions. @@ -69,7 +69,7 @@ type telegramSetup struct { func resolveTelegramToken(cfg config.TelegramConfig, registry *secret.Registry) (string, error) { if cfg.Token != (secret.SecretRef{}) { - return cfg.Token.Resolve(registry) + return registry.Resolve(cfg.Token) } if cfg.TokenEnv == "" { return "", nil diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go index 46fb38fe4..47de3e8a6 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -5,10 +5,10 @@ import ( "log/slog" "time" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/captureintake" "github.com/samcharles93/archie-core/internal/webhookguard" "github.com/samcharles93/archie-core/internal/webui" @@ -20,8 +20,8 @@ import ( type deps struct { Options Options Log *slog.Logger - Store storev1.TaskStore - Chat gateway.ChatContract + Store storecontract.TaskStore + Chat messaging.ChatContract Health *health.Registry } @@ -61,17 +61,17 @@ func compose(d deps) *webui.Server { TrustForwardedHeaders: d.Options.trustForwardedHeaders(), Health: d.Health, } - if snapshots, ok := d.Store.(storev1.ConfigSnapshotStore); ok { + if snapshots, ok := d.Store.(storecontract.ConfigSnapshotStore); ok { srv.ConfigSource = webui.RemoteConfigView(snapshots) } // Mappings and bindings are ratified State Store contracts, and the same // client already carries them: withholding them would degrade two pages // that have an owner, which is a different thing from the intake surfaces // below. - if mappings, ok := d.Store.(storev1.MappingStore); ok { + if mappings, ok := d.Store.(storecontract.MappingStore); ok { srv.Mappings = mappings } - if bindings, ok := d.Store.(storev1.BindingStore); ok { + if bindings, ok := d.Store.(storecontract.BindingStore); ok { srv.Bindings = bindings } if d.Chat != nil { @@ -88,8 +88,8 @@ func compose(d deps) *webui.Server { // implement one degrades that half with a warning rather than aborting the // process, mirroring the daemon's own adapter selection. func wireCaptureSurfaces(d deps, srv *webui.Server) { - captures, hasCaptures := d.Store.(storev1.CaptureStore) - bindings, hasBindings := d.Store.(storev1.BindingDispatcher) + captures, hasCaptures := d.Store.(storecontract.CaptureStore) + bindings, hasBindings := d.Store.(storecontract.BindingDispatcher) if !hasCaptures { d.Log.Warn("capture storage unavailable: state store does not implement CaptureStore") return diff --git a/internal/app/archieui/readiness.go b/internal/app/archieui/readiness.go index f7d2c67aa..386a60e94 100644 --- a/internal/app/archieui/readiness.go +++ b/internal/app/archieui/readiness.go @@ -3,9 +3,9 @@ package archieui import ( "context" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/health" - "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" ) @@ -17,7 +17,7 @@ import ( // // The component names match the daemon dashboard's, so the readiness view // reads the same whichever process serves it. -func newReadinessRegistry(o Options, tasks storev1.TaskStore, chat gateway.ChatContract) *health.Registry { +func newReadinessRegistry(o Options, tasks storecontract.TaskStore, chat messaging.ChatContract) *health.Registry { return health.NewRegistry( readiness.NewContractProbe("state_db", o.DependencyTimeout, func(ctx context.Context) error { _, err := tasks.StatusCounts(ctx) diff --git a/internal/channels/manager.go b/internal/channels/status/status.go similarity index 84% rename from internal/channels/manager.go rename to internal/channels/status/status.go index fda93fb72..5518951c1 100644 --- a/internal/channels/manager.go +++ b/internal/channels/status/status.go @@ -1,4 +1,10 @@ -package channels +// 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 (archie-core-8cda.5.6). +package status import "sync" diff --git a/internal/channels/manager_test.go b/internal/channels/status/status_test.go similarity index 97% rename from internal/channels/manager_test.go rename to internal/channels/status/status_test.go index e65e7fcec..52e048f5c 100644 --- a/internal/channels/manager_test.go +++ b/internal/channels/status/status_test.go @@ -1,4 +1,4 @@ -package channels +package status import "testing" diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go index a773089c0..2e27e76e8 100644 --- a/internal/channels/telegram/live.go +++ b/internal/channels/telegram/live.go @@ -338,8 +338,8 @@ func (l *liveReply) ToolCall(event gateway.ToolCallEvent) { // Render the completed result as a compact fenced block. Do not append the // raw/JSON-shaped parameters: they are noisy, can expose secrets, and were // the source of unreadable schema placeholders in Telegram. - line := event.RenderToolCall() - key := event.FailureKey() + line := gateway.RenderToolCall(event) + key := gateway.FailureKey(event) l.mu.Lock() if index, ok := l.failureLines[key]; key != "" && ok { diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go index 7c0b15df0..a33561e9f 100644 --- a/internal/config/clone_test.go +++ b/internal/config/clone_test.go @@ -2,8 +2,6 @@ package config import ( "testing" - - "github.com/samcharles93/archie-core/internal/secret" ) // TestConfigCloneDeepCopiesReferenceFields pins that Clone returns a @@ -29,7 +27,7 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}}, LegacyAgent: LegacyAgent{Env: []string{"HOME"}}, Extra: map[string]any{"custom": 1}, - Bindings: BindingsConfig{PreviousEncryptionKeys: []secret.SecretRef{{Engine: "env", Key: "K0"}}}, + Bindings: BindingsConfig{PreviousEncryptionKeys: []SecretRef{{Engine: "env", Key: "K0"}}}, } got := orig.Clone() @@ -46,7 +44,7 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { got.Chat.Telegram.AllowedUserIDs[0] = 99 got.LegacyAgent.Env[0] = "changed" got.Extra["custom"] = 2 - got.Bindings.PreviousEncryptionKeys[0] = secret.SecretRef{Engine: "env", Key: "changed"} + got.Bindings.PreviousEncryptionKeys[0] = SecretRef{Engine: "env", Key: "changed"} *got.Tools.WebFetch.Enabled = false if orig.Models["builder"] != "m" { diff --git a/internal/config/config.go b/internal/config/config.go index 1ed54ede5..3a3a99f8c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,8 +21,6 @@ import ( "net" "strings" "time" - - "github.com/samcharles93/archie-core/internal/secret" ) // Duration is a time.Duration that unmarshals from TOML strings ("60s"). @@ -178,10 +176,10 @@ type Budgets struct { // Provider configures one LLM provider for the runtime catalog. type Provider struct { - Class string `toml:"class" yaml:"class" json:"class"` - APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"` - APIKey secret.SecretRef `toml:"api_key" yaml:"api_key" json:"-"` - BaseURL string `toml:"base_url" yaml:"base_url" json:"base_url"` + Class string `toml:"class" yaml:"class" json:"class"` + APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"` + APIKey SecretRef `toml:"api_key" yaml:"api_key" json:"-"` + BaseURL string `toml:"base_url" yaml:"base_url" json:"base_url"` } // LegacyAgent decodes the removed [agent] section so existing operator files @@ -204,10 +202,10 @@ const ( // Forge configures the code forge integration. type Forge struct { - Type string `toml:"type" yaml:"type"` - Host string `toml:"host" yaml:"host"` - Token secret.SecretRef `toml:"token" yaml:"token"` - TokenEnv string `toml:"token_env" yaml:"token_env"` + Type string `toml:"type" yaml:"type"` + Host string `toml:"host" yaml:"host"` + Token SecretRef `toml:"token" yaml:"token"` + TokenEnv string `toml:"token_env" yaml:"token_env"` // Intake selects how forge issues become work: "poll" (default), // "webhook", or "both". Webhook intake reacts to forge events the moment // they arrive instead of up to poll_interval later. @@ -215,7 +213,7 @@ type Forge struct { // WebhookSecret is the shared secret used to verify GitHub webhook // signatures (X-Hub-Signature-256). Required when Intake is "webhook" or // "both". - WebhookSecret secret.SecretRef `toml:"webhook_secret" yaml:"webhook_secret"` + WebhookSecret SecretRef `toml:"webhook_secret" yaml:"webhook_secret"` // WebhookAddr is the host:port the webhook receiver listens on. Required // when Intake is "webhook" or "both". WebhookAddr string `toml:"webhook_addr" yaml:"webhook_addr"` @@ -302,11 +300,11 @@ type ImageConfig struct { // provider spends real API credits per call and must never activate from // the mere presence of a key. type ImageHostedProvider struct { - Enabled bool `toml:"enabled" yaml:"enabled" json:"enabled"` - Class string `toml:"class" yaml:"class" json:"class"` - APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"` - APIKey secret.SecretRef `toml:"api_key" yaml:"api_key" json:"-"` - BaseURL string `toml:"base_url" yaml:"base_url" json:"base_url,omitempty"` + Enabled bool `toml:"enabled" yaml:"enabled" json:"enabled"` + Class string `toml:"class" yaml:"class" json:"class"` + APIKeyEnv string `toml:"api_key_env" yaml:"api_key_env" json:"api_key_env"` + APIKey SecretRef `toml:"api_key" yaml:"api_key" json:"-"` + BaseURL string `toml:"base_url" yaml:"base_url" json:"base_url,omitempty"` } // ImageLocalProvider configures one local GPU image recipe. Enabled @@ -405,7 +403,7 @@ type MinimaxConfig struct { Enabled bool `toml:"enabled" yaml:"enabled" json:"enabled"` // APIKey authenticates against the MiniMax API. - APIKey secret.SecretRef `toml:"api_key" yaml:"api_key" json:"-"` + APIKey SecretRef `toml:"api_key" yaml:"api_key" json:"-"` // BaseURL overrides the API host. Empty uses the client's built-in // default. Exists for a proxy or a self-hosted-compatible endpoint, @@ -661,7 +659,7 @@ func (c Config) Clone() Config { c.Chat.Telegram.AllowedUserIDs = append([]int64(nil), c.Chat.Telegram.AllowedUserIDs...) c.Chat.Telegram.UpdateCheckCommand = append([]string(nil), c.Chat.Telegram.UpdateCheckCommand...) c.Chat.Telegram.UpdateInstallCommand = append([]string(nil), c.Chat.Telegram.UpdateInstallCommand...) - c.Bindings.PreviousEncryptionKeys = append([]secret.SecretRef(nil), c.Bindings.PreviousEncryptionKeys...) + c.Bindings.PreviousEncryptionKeys = append([]SecretRef(nil), c.Bindings.PreviousEncryptionKeys...) c.Tools.MCPServers = cloneMCPServers(c.Tools.MCPServers) c.Memory.ProviderConfig = maps.Clone(c.Memory.ProviderConfig) if c.Tools.WebFetch.Enabled != nil { @@ -788,11 +786,11 @@ type BindingsConfig struct { // Resolved through the secret registry (engine + key) at startup; the // resolved material must be 32 bytes of high-entropy randomness. // A nil/empty ref disables encryption and keeps current behaviour. - EncryptionKey secret.SecretRef `toml:"encryption_key" yaml:"encryption_key"` + EncryptionKey SecretRef `toml:"encryption_key" yaml:"encryption_key"` // PreviousEncryptionKeys retains older key material so rows sealed // under a previous rotation still decrypt. Each is resolved the same // way as EncryptionKey; entries are decrypt-only. - PreviousEncryptionKeys []secret.SecretRef `toml:"previous_encryption_keys" yaml:"previous_encryption_keys"` + PreviousEncryptionKeys []SecretRef `toml:"previous_encryption_keys" yaml:"previous_encryption_keys"` } // ContainerConfig configures Docker sandbox execution of archie-agent. @@ -928,7 +926,7 @@ type TelegramConfig struct { AllowedUserIDs []int64 `toml:"allowed_user_ids" yaml:"allowed_user_ids"` // Token references the bot token through the configured secret engine. // It takes precedence over TokenEnv when both are set. - Token secret.SecretRef `toml:"token" yaml:"token"` + Token SecretRef `toml:"token" yaml:"token"` // TokenEnv names the env var holding the bot token from @BotFather. // Empty disables the Telegram channel. TokenEnv string `toml:"token_env" yaml:"token_env"` diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 7c4fc43b8..9d59fc9f8 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -8,8 +8,6 @@ import ( "time" "github.com/BurntSushi/toml" - - "github.com/samcharles93/archie-core/internal/secret" ) func TestTaskConfigToConfigRoundTrip(t *testing.T) { @@ -21,7 +19,7 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) { Budgets: Budgets{MaxSteps: 12, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3}, Dispatch: Dispatch{Trigger: "label", AckReaction: "eyes", Labels: map[string]string{"working": "bot:working"}}, Notify: Notify{Webhook: "https://notify.example.test/hook"}, - Forge: Forge{Type: "github", Host: "https://forge.example.test", Token: secret.SecretRef{Engine: "env", Key: "TOP_SECRET"}}, + Forge: Forge{Type: "github", Host: "https://forge.example.test", Token: SecretRef{Engine: "env", Key: "TOP_SECRET"}}, } got := cfg.ForTask().ToConfig() @@ -43,7 +41,7 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) { if got.Forge.Host != cfg.Forge.Host { t.Fatalf("Forge.Host = %q, want %q", got.Forge.Host, cfg.Forge.Host) } - if got.Forge.Token != (secret.SecretRef{}) { + if got.Forge.Token != (SecretRef{}) { t.Fatalf("Forge.Token = %#v, want zero value (never carried by TaskConfig)", got.Forge.Token) } } @@ -107,7 +105,7 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) { Forge: Forge{ Type: "github", Host: "https://forge.example.test", - Token: secret.SecretRef{Engine: "env", Key: "TOP_SECRET_FORGE_TOKEN"}, + Token: SecretRef{Engine: "env", Key: "TOP_SECRET_FORGE_TOKEN"}, }, Providers: map[string]Provider{ "secret": {APIKeyEnv: "TOP_SECRET_PROVIDER_TOKEN"}, diff --git a/internal/config/secret_ref.go b/internal/config/secret_ref.go new file mode 100644 index 000000000..cb9368cc0 --- /dev/null +++ b/internal/config/secret_ref.go @@ -0,0 +1,24 @@ +package config + +// SecretRef references a secret stored in a named engine. Legacy environment +// variable fields remain supported where required for backwards compatibility. +// +// Format in TOML/YAML: +// +// [forge] +// token = {engine = "env", key = "GITEA_TOKEN"} +// +// [providers.deepseek] +// api_key = {engine = "bws", key = "DEEPSEEK_API_KEY"} +// +// The zero value (empty engine, empty key) resolves to "" with no error, +// for config fields where the secret is optional (e.g. an unconfigured +// channel token). +// +// It lives here rather than in internal/secret so the archie-ui process can +// render config projections without linking the secret runtime +// (archie-core-8cda.5.6). +type SecretRef struct { + Engine string `toml:"engine" yaml:"engine" json:"engine"` + Key string `toml:"key" yaml:"key" json:"key"` +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index b258e3004..650235543 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -17,10 +17,10 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/mapping" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/eventbus" @@ -100,26 +100,26 @@ type Daemon struct { // remote archie-state-store service; it is always the configured // [services.state].target after the in-process serving path is deleted. ConnectedStateStore StateStoreEndpoint - Store storev1.TaskStore + Store storecontract.TaskStore // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). // Used by the binding dispatch loop to resolve capture bodies against // the mapping a binding names. Optional: nil disables the binding // dispatch loop (legacy behaviour). - Mappings storev1.MappingStore + Mappings storecontract.MappingStore // Bindings persists playbook bindings (docs/prds/playbook-binding.md). // Optional: nil disables the binding dispatch loop (legacy behaviour). - Bindings storev1.BindingStore + Bindings storecontract.BindingStore // BindingDispatcher is the dispatch-time helper surface for bindings: // list undispatched captures, look up armed bindings by source for the // matcher, and write the at-most-once dedup ledger row. Split from // BindingStore to keep the CRUD interface under the interfacebloat // limit. Optional: nil disables the dispatch loop. - BindingDispatcher storev1.BindingDispatcher + BindingDispatcher storecontract.BindingDispatcher // BindingTaskCreator enqueues a task triggered by a binding. Split // off TaskLifecycle so the lifecycle surface stays narrow and the // dispatch loop does not acquire the full task-creation contract. // Optional: nil disables the dispatch loop. - BindingTaskCreator storev1.BindingTaskCreator + BindingTaskCreator storecontract.BindingTaskCreator Forge forge.Forge Trees *worktree.Manager Bus *events.Bus @@ -517,7 +517,7 @@ const bindingDispatchBatchLimit = 100 // // The binding_dispatches ledger is the at-most-once guarantee across // cycles and daemon restarts: RecordDispatch returns -// storev1.ErrAlreadyDispatched on a duplicate (binding_id, capture_id) +// storecontract.ErrAlreadyDispatched on a duplicate (binding_id, capture_id) // pair, and dispatchOneBinding treats that as a normal "another cycle // raced us" outcome rather than an error. // @@ -580,7 +580,7 @@ func (d *Daemon) dispatchBindings(ctx context.Context) { // repo (when exactly one is configured); binding.Owner/Repo is a // follow-up so multi-repo deployments don't have to live with the // ambiguity. -func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storev1.CapturedEvent) { +func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent) { if d.Mappings == nil { d.Log.Warn("binding dispatch: mapping store unavailable", "binding", b.ID) return @@ -623,7 +623,7 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st } if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, task.ID); err != nil { - if errors.Is(err, storev1.ErrAlreadyDispatched) { + if errors.Is(err, storecontract.ErrAlreadyDispatched) { // Another cycle or daemon instance raced us and already // recorded the dispatch. The duplicate task remains // queued (delete-on-races is its own can of worms), @@ -664,7 +664,7 @@ func hasBlockingFailure(fields []mapping.Field, failures []mapping.Failure) bool // resolved, one "key=value" pair per line. Empty maps still produce // a body that records the source capture id so the workflow has // provenance to hand back to the operator. -func renderBindingBody(values map[string]any, c storev1.CapturedEvent) string { +func renderBindingBody(values map[string]any, c storecontract.CapturedEvent) string { if len(values) == 0 { return fmt.Sprintf("(no fields resolved from capture %d)", c.ID) } @@ -1283,7 +1283,7 @@ func (d *Daemon) acquireTaskContainer( // that survives cancellation while preserving values. // // The transition remains guarded from StatusRunning: if the worker already -// recorded a terminal state over storerpc, storev1.ErrStaleTransition is returned +// recorded a terminal state over storerpc, storecontract.ErrStaleTransition is returned // and ignored. Unexpected store errors are logged as warnings. func (d *Daemon) parkRunningTask(ctx context.Context, taskID int64, reason string) { if d.Store == nil { @@ -1293,7 +1293,7 @@ func (d *Daemon) parkRunningTask(ctx context.Context, taskID int64, reason strin defer cancel() if err := d.Store.Transition(writeCtx, taskID, workflow.StatusRunning, workflow.StatusParked, reason); err != nil { - if !errors.Is(err, storev1.ErrStaleTransition) { + if !errors.Is(err, storecontract.ErrStaleTransition) { d.Log.Warn("terminal park transition failed", "task", taskID, "reason", reason, "err", err) } } diff --git a/internal/domain/messaging/chat_contract.go b/internal/domain/messaging/chat_contract.go new file mode 100644 index 000000000..3937ae900 --- /dev/null +++ b/internal/domain/messaging/chat_contract.go @@ -0,0 +1,46 @@ +package messaging + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/taskstate" +) + +// ChatContract is the conversational boundary consumed by channel frontends. +// Results are snapshots: callers must not rely on shared object identity. +// It moved here from internal/gateway (archie-core-8cda.5.6) so the webui +// and archie-ui processes can hold the contract without linking the gateway +// runtime (and, transitively, its SQLite session store). +type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade + Snapshot(context.Context) (ChatSnapshot, error) + GetSession(context.Context, string) (SessionContext, bool, error) + RecentMessages(context.Context, string, int) ([]Message, error) + RecentTurns(context.Context, string, int) ([]TurnRecord, error) + Route(context.Context, Inbound) (ChatReply, error) + // Stream emits started, delta/tool/media, then done or error, in order. + // Callers must drain the stream or cancel the context. Cancellation closes it. + Stream(context.Context, Inbound) (<-chan ChatEvent, error) + Cancel(context.Context, string) (ChatCancellation, error) + SetPersona(context.Context, string, string) (bool, error) + ChatTaskActionContract +} + +// ChatTaskActionContract is the operator task mutation capability exposed by +// the Gateway. It is separate so read/turn consumers do not need to model it. +type ChatTaskActionContract interface { + // ApplyTaskAction applies an action on behalf of a chat identity, which + // may only act on its own tasks. + ApplyTaskAction(context.Context, string, int64, taskstate.Action) (TaskActionResult, error) + // ApplyOperatorTaskAction applies an action on behalf of an authenticated + // dashboard operator, who acts across identities. It is a separate method + // rather than an empty identity because "" is a real identity in a + // single-identity deployment (see chatTaskProfiles in the daemon). + ApplyOperatorTaskAction(context.Context, int64, taskstate.Action) (TaskActionResult, error) +} + +// TaskActionResult is what task_action returns. +type TaskActionResult struct { + TaskID int64 `json:"task_id"` + Action string `json:"action"` + Message string `json:"message"` +} diff --git a/internal/domain/messaging/chat_stream.go b/internal/domain/messaging/chat_stream.go new file mode 100644 index 000000000..14d46f256 --- /dev/null +++ b/internal/domain/messaging/chat_stream.go @@ -0,0 +1,45 @@ +package messaging + +// ChatSnapshot is what Snapshot returns: the full chat state a dashboard +// renders in one read. +type ChatSnapshot struct { + Sessions []SessionContext + Models []string + ModelsByProvider map[string][]string + Providers []string + ActiveModel string + ActiveProvider string + Personas []string + ActivePersonas map[string]string + RestartAvailable bool + CancellationAvailable bool + PersonasAvailable bool +} + +// ChatReply is the blocking reply from Route. +type ChatReply struct { + Text string + SessionID string +} + +// ChatCancellation is what Cancel returns. +type ChatCancellation struct { + Cancelled bool + Dropped int +} + +// ChatEvent contains values only; Text holds the error message for error events. +type ChatEvent struct { + Kind string + Text string + SessionID string + Tool ToolCallEvent + Media MediaEvent +} + +// DashboardNavigateResult is what dashboard_navigate returns. The web UI +// renders it as a clickable chip that routes the operator to the page. +type DashboardNavigateResult struct { + Path string `json:"path"` + Label string `json:"label"` +} diff --git a/internal/domain/messaging/commands.go b/internal/domain/messaging/commands.go new file mode 100644 index 000000000..f75c5d499 --- /dev/null +++ b/internal/domain/messaging/commands.go @@ -0,0 +1,64 @@ +package messaging + +// localCommands is the executable gateway-local command list. It lives here +// beside CommandSpec so adapter-published help surfaces cannot drift from +// the executable router surface. +var localCommands = []string{ + "/status", "/tasks", "/model", "/spawn", + "/approve", "/cancel", "/start", + "/new", "/reset", "/topic", "/retry", "/undo", + "/title", "/branch", "/fork", "/compress", "/compact", + "/whoami", "/profile", "/sessions", "/resume", "/delete", "/agents", + "/personality", "/help", "/version", "/update", "/restart", +} + +// CommandSpec describes a local command for adapter-provided discovery. +type CommandSpec struct { + Command string `json:"command"` + Description string `json:"description"` + Usage string `json:"usage"` +} + +var localCommandSpecs = []CommandSpec{ + {Command: "/status", Description: "Show daemon health", Usage: "/status"}, + {Command: "/tasks", Description: "Show running and parked work", Usage: "/tasks"}, + {Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"}, + {Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn "}, + {Command: "/approve", Description: "Approve a waiting task", Usage: "/approve <task-id>"}, + {Command: "/cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel <task-id>"}, + {Command: "/start", Description: "Confirm that Archie is running", Usage: "/start"}, + {Command: "/new", Description: "Start a fresh conversation", Usage: "/new [title]"}, + {Command: "/reset", Description: "Alias for /new", Usage: "/reset [title]"}, + {Command: "/topic", Description: "List or switch conversation topics", Usage: "/topic [session-id]"}, + {Command: "/retry", Description: "Replay the last message", Usage: "/retry"}, + {Command: "/undo", Description: "Remove recent messages", Usage: "/undo [N]"}, + {Command: "/title", Description: "Show or set the conversation title", Usage: "/title [name]"}, + {Command: "/branch", Description: "Create a child conversation", Usage: "/branch [name]"}, + {Command: "/fork", Description: "Alias for /branch", Usage: "/fork [name]"}, + {Command: "/compress", Description: "Compress conversation context", Usage: "/compress [options]"}, + {Command: "/compact", Description: "Alias for /compress", Usage: "/compact [options]"}, + {Command: "/whoami", Description: "Show the active identity and model", Usage: "/whoami"}, + {Command: "/profile", Description: "Show the active identity profile", Usage: "/profile"}, + {Command: "/sessions", Description: "List this channel's conversations", Usage: "/sessions"}, + {Command: "/resume", Description: "Switch to a conversation", Usage: "/resume <session-id>"}, + {Command: "/delete", Description: "Delete a conversation and its history", Usage: "/delete <session-id>"}, + {Command: "/agents", Description: "List tasks currently being worked", Usage: "/agents"}, + {Command: "/personality", Description: "Choose a communication style", Usage: "/personality [name]"}, + {Command: "/help", Description: "See what Archie can do", Usage: "/help"}, + {Command: "/version", Description: "Show installed Archie versions", Usage: "/version"}, + {Command: "/update", Description: "Check for Archie updates", Usage: "/update"}, + {Command: "/restart", Description: "Reload the chat adapter", Usage: "/restart"}, +} + +// LocalCommands returns the command names Route answers from local state. +// Gateways use this to verify that their published command surfaces match +// the executable router surface. +func LocalCommands() []string { + return append([]string(nil), localCommands...) +} + +// LocalCommandSpecs returns a copy safe for adapters to enrich with their +// optional capabilities. +func LocalCommandSpecs() []CommandSpec { + return append([]CommandSpec(nil), localCommandSpecs...) +} diff --git a/internal/domain/messaging/inbound.go b/internal/domain/messaging/inbound.go new file mode 100644 index 000000000..16aca807b --- /dev/null +++ b/internal/domain/messaging/inbound.go @@ -0,0 +1,62 @@ +package messaging + +import ( + "context" + "time" +) + +// Inbound is a message arriving from a channel together with the +// transport context that is not part of the canonical record. +// +// Message is the record itself, exactly as it will be persisted. Channels +// construct it directly: ConversationID addresses the chat (a Telegram +// chat ID and topic thread, an email recipient, a webhook path), Sender is +// the channel-native attribution, and Role is always RoleUser -- +// a channel only ever carries what a person said. ID is left empty for a +// newly received message so the store derives one from SourceID, and +// honoured when set, which is what lets a read-modify-write of a history +// keep its identities rather than minting new ones. +type Inbound struct { + Message Message + // Page is the dashboard route the operator is on when they sent + // this message. Transport-only: it reaches the system prompt and + // is never persisted. Empty for non-web channels. + Page string +} + +// SpawnRequest is a chat-originated task creation request. Repo and +// Workflow are optional -- empty means "the daemon's configured +// default for this identity". +type SpawnRequest struct { + Title string + Body string // operator instructions carried into the admitted task + Repo string // "owner/name"; empty = identity's default repo + Workflow string // empty = daemon's default workflow routing + Identity string // the identity spawning this task; propagated from Router.Identity +} + +// TaskCreator creates a native (non-forge-backed) task from a chat +// command. The daemon supplies an implementation backed by the store. +// When nil on a Router, /spawn returns "not configured". CreateTask +// must return the task's real, durable database ID -- never a +// synthetic or fabricated value. +type TaskCreator interface { + CreateTask(ctx context.Context, req SpawnRequest) (taskID int64, err error) +} + +// DangerousCommandAuthority is the sandbox-owned authority for operations +// that can destroy process or filesystem state. Adapters only request and +// present approval; they never implement these operations themselves. +type DangerousCommandAuthority interface { + StopProcess(context.Context, string) error + Rollback(context.Context, int) (string, error) + ListCheckpoints(context.Context) ([]CheckpointInfo, error) +} + +// CheckpointInfo describes a saved sandbox filesystem checkpoint. +type CheckpointInfo struct { + Number int + Timestamp time.Time + Label string + Size string +} diff --git a/internal/domain/messaging/media.go b/internal/domain/messaging/media.go new file mode 100644 index 000000000..8a4d8b89d --- /dev/null +++ b/internal/domain/messaging/media.go @@ -0,0 +1,53 @@ +package messaging + +// MediaAttachment describes a file attached to a message. Platform-agnostic; +// platform-specific fields live in Raw. +// +// Numeric fields use pointers so that zero is distinguishable from +// "unknown" across a JSON round-trip: a 0-byte file is valid and +// different from a file whose size was never set. +type MediaAttachment struct { + // Type is "image", "video", "audio", or "document". + Type string `json:"type"` + + // FileID is the platform-assigned identifier for download APIs. + FileID string `json:"file_id"` + + // URL is a direct download URL when available. May be empty for + // platforms that require a download API call. + URL string `json:"url,omitempty"` + + // Path is a local filesystem path on the host that produced the + // attachment. It is the alternative to URL for outbound delivery: a + // URL is fetched by the platform, a Path is uploaded by us. A file the + // agent wrote has no URL and never gets one -- publishing it would + // trade a delivery problem for a hosting and access-control one -- so + // senders that support upload must read this. + // + // Exactly one of URL and Path is meaningful for an outbound send. + Path string `json:"path,omitempty"` + + // MIMEType is the content type (e.g. "image/png", "audio/ogg"). + MIMEType string `json:"mime_type,omitempty"` + + // FileName is the original file name when known. + FileName string `json:"file_name,omitempty"` + + // FileSize is the attachment size in bytes. nil means unknown. + FileSize *int64 `json:"file_size,omitempty"` + + // Width is the pixel width for images and video. nil means unknown + // or not applicable. + Width *int `json:"width,omitempty"` + + // Height is the pixel height for images and video. nil means unknown + // or not applicable. + Height *int `json:"height,omitempty"` + + // Duration is the play time in seconds for audio and video. + Duration *int `json:"duration,omitempty"` + + // Raw carries platform-specific fields the common vocabulary does not + // cover, so adapters never need a second attachment type. + Raw map[string]any `json:"raw,omitempty"` +} diff --git a/internal/domain/messaging/session_store.go b/internal/domain/messaging/session_store.go new file mode 100644 index 000000000..d38b99ad5 --- /dev/null +++ b/internal/domain/messaging/session_store.go @@ -0,0 +1,154 @@ +package messaging + +import ( + "context" + "time" +) + +// SessionSource identifies the platform, bot identity, and conversation a +// gateway session belongs to. It is the composite natural key for session +// lookup. +type SessionSource struct { + // Platform is the adapter name ("telegram", "discord", "web"). + Platform string `json:"platform"` + + // BotUser is the bot identity serving this session (e.g. "archie", + // "winter"). Distinct bot identities on the same platform and channel + // produce distinct sessions. + BotUser string `json:"bot_user"` + + // ChannelID is the platform conversation identifier (chat ID, channel + // name, DM thread). + ChannelID string `json:"channel_id"` + + // ThreadID identifies the topic thread within the conversation, for + // platforms that support threading (Telegram supergroup topics, + // Slack threads, Discord forum posts). Empty for flat chats and the + // General topic. When non-empty, distinct threads within the same + // channel produce distinct sessions. + ThreadID string `json:"thread_id,omitempty"` +} + +// SessionContext holds the full metadata for an active gateway session. +// The session store is the persistence layer; callers treat SessionContext +// as a value object. +type SessionContext struct { + // SessionID is the unique session identifier (UUID). + SessionID string `json:"session_id"` + + // Source identifies the platform, bot, and conversation. + Source SessionSource `json:"source"` + + // Title is an optional human-readable name for the session, set + // via /title. Empty until set. + Title string `json:"title,omitempty"` + + // ParentSessionID is the session this one was branched from, set + // by /branch or /fork. Empty for root sessions. + ParentSessionID string `json:"parent_session_id,omitempty"` + + // BranchName is the name given when branching, set via + // /branch <name>. Empty for root sessions. + BranchName string `json:"branch_name,omitempty"` + + // CreatedAt is when the session was first established. + CreatedAt time.Time `json:"created_at"` + + // LastActiveAt is the timestamp of the most recent message or event + // on this session. Updated by Touch. + LastActiveAt time.Time `json:"last_active_at"` +} + +// SessionStore persists gateway session metadata and conversation history. +// Each session tracks one platform, bot, and channel combination. +// +// Message history is stored and loaded as canonical Message records +// (archie-core-d9dv). Session lifecycle records stay SessionContext: +// a session's UUID key, platform/bot/title/branch metadata, and the fact +// that several sessions share one channel/thread have no lossless home in +// Conversation, whose composite identity is only +// {ChannelID, ThreadID} and whose canonical Agent/user/binding ownership is +// still open (see docs/architecture/migration-decisions.md section 2). +// Conversation-keying the sessions is tracked as follow-up work once that +// ownership settles. +type SessionStore interface { + SessionLifecycle + MessageHistory +} + +// SessionLifecycle manages session CRUD and listing. +type SessionLifecycle interface { + // Save inserts or replaces a session. + Save(ctx context.Context, s SessionContext) error + // Get returns a session by ID, or nil when it does not exist. + Get(ctx context.Context, sessionID string) (*SessionContext, error) + // GetByChannel returns matching sessions newest first. + GetByChannel(ctx context.Context, platform, channelID string) ([]SessionContext, error) + // Delete removes a session. Deleting an absent session is a no-op. + Delete(ctx context.Context, sessionID string) error + // Touch marks a session active at the current time. + Touch(ctx context.Context, sessionID string) error + // List returns all sessions newest first. + List(ctx context.Context) ([]SessionContext, error) +} + +// MessageHistory manages conversation messages within a session. Messages +// are canonical Message records, the same type channel adapters hand the +// Router, so nothing converts on the way in or out. +type MessageHistory interface { + // SaveMessage appends one message with a strictly increasing timestamp. + SaveMessage(ctx context.Context, sessionID string, msg Message) error + // RecentMessages returns the most recent messages in chronological order. + RecentMessages(ctx context.Context, sessionID string, n int) ([]Message, error) + // DeleteRecentMessages removes up to n messages and returns the count. + DeleteRecentMessages(ctx context.Context, sessionID string, n int) (deleted int, err error) + // MessageCount returns the number of stored messages in a session. + MessageCount(ctx context.Context, sessionID string) (int, error) + // SaveMessages appends messages used to inherit branch history. + SaveMessages(ctx context.Context, sessionID string, msgs []Message) error + // ReplaceMessages writes replacements before deleting superseded messages. + // Records absent from both inputs remain untouched. + ReplaceMessages(ctx context.Context, sessionID string, msgs []Message, superseded []string) error + // SearchMessages searches the session's full history. + SearchMessages(ctx context.Context, sessionID string, q MessageQuery) (MessagePage, error) + // Close releases the database. + Close() error +} + +// MessageQuery is one page request against a session's message history. Limit +// is clamped to MaxMessagePageSize and Offset is never negative. +type MessageQuery struct { + Query string + Limit int + // Offset is the number of ranked matches to skip. + Offset int +} + +// MessagePage is one page of search results. +type MessagePage struct { + // Messages are ordered by relevance. + Messages []Message + // NextOffset is meaningful only when HasMore is true. + NextOffset int + HasMore bool + // Truncated is retained in the transport contract and is always false for + // SQLite because it can count the complete result set. + Truncated bool +} + +// Page-size bounds for MessageQuery. +const ( + DefaultMessagePageSize = 50 + MaxMessagePageSize = 500 + MaxMessageSearchQueryBytes = 4096 + MaxMessageSearchQueryTerms = 64 +) + +// RoleForSender classifies a message sender: a message sent by the +// session's bot is the assistant's, anything else is the user's. +func RoleForSender(sender, botUser string) Role { + if sender == botUser { + return RoleAssistant + } + return RoleUser +} diff --git a/internal/domain/messaging/stream.go b/internal/domain/messaging/stream.go new file mode 100644 index 000000000..0f4702ad9 --- /dev/null +++ b/internal/domain/messaging/stream.go @@ -0,0 +1,89 @@ +package messaging + +import "strings" + +// ToolCallEvent reports one completed tool invocation within a turn. It +// carries the raw outcome rather than rendered text: presentation (emoji, +// layout, whether to show it at all) belongs to the channel adapter. +type ToolCallEvent struct { + // ID correlates the completed result with the model's invocation. + ID string + // Name is the tool the model invoked. + Name string + // Parameters is a bounded, redacted JSON summary of the invocation input. + // It is safe for channel adapters to render directly. + Parameters string + // Output is what the tool returned, verbatim. + Output string + // Err is non-empty when the tool failed, in which case Output is + // unreliable and usually empty. + Err string +} + +// MediaEvent reports one media attachment produced during a turn, so a +// channel can deliver it (e.g. through its media sender capability) in the +// same ordered pass as the text and tool activity that surrounded it. +type MediaEvent struct { + // ToolName is the tool call that produced the attachment. + ToolName string + // Attachment is the media to deliver. + Attachment MediaAttachment +} + +// TurnStream receives a turn's output as it is produced. +// +// It replaces the plain delta callback so a channel can render tool activity +// in the same ordered pass as the text: both arrive on the generating +// goroutine, in the order the model produced them. Implementations must not +// block -- a slow renderer stalls generation -- and must be safe to call +// from that goroutine only. +// +// Callers that render text alone use DeltaFunc rather than implementing this. +type TurnStream interface { + // Delta appends the next fragment of assistant text. + Delta(text string) + // ToolCall reports a tool invocation that has finished executing. + ToolCall(event ToolCallEvent) + // Media reports a media attachment a tool call produced during the + // turn. A channel that cannot deliver it inline is expected to fall + // back to rendering the attachment's URL as text instead of dropping + // it silently. + Media(event MediaEvent) +} + +// toolSummaryMaxRunes bounds a rendered tool summary. +const toolSummaryMaxRunes = 80 + +// Summary reduces the outcome to a single short line suitable for an inline +// status entry. It never returns an empty string: a tool that returned +// nothing still ran, and a blank summary would read as a rendering fault. +func (e ToolCallEvent) Summary() string { + if line := firstNonEmptyLine(e.Err); line != "" { + return "failed: " + truncateRunes(line, toolSummaryMaxRunes) + } + if line := firstNonEmptyLine(e.Output); line != "" { + return truncateRunes(line, toolSummaryMaxRunes) + } + return "done" +} + +// firstNonEmptyLine returns the first non-empty line of s, trimmed. +func firstNonEmptyLine(s string) string { + for line := range strings.SplitSeq(s, "\n") { + if trimmed := strings.TrimSpace(line); trimmed != "" { + return trimmed + } + } + return "" +} + +// truncateRunes shortens s to at most maxRunes runes, marking the cut with an +// ellipsis. Counting runes rather than bytes keeps multi-byte text from being +// cut mid-character. +func truncateRunes(s string, maxRunes int) string { + runes := []rune(s) + if len(runes) <= maxRunes { + return s + } + return string(runes[:maxRunes]) + "…" +} diff --git a/internal/domain/messaging/turn.go b/internal/domain/messaging/turn.go new file mode 100644 index 000000000..a46a81150 --- /dev/null +++ b/internal/domain/messaging/turn.go @@ -0,0 +1,39 @@ +package messaging + +import "time" + +// TurnStatus is the durable lifecycle state of one chat generation. +type TurnStatus string + +const ( + TurnStatusAccepted TurnStatus = "accepted" + TurnStatusRunning TurnStatus = "running" + TurnStatusPartial TurnStatus = "partial" + TurnStatusCompleted TurnStatus = "completed" + TurnStatusFailed TurnStatus = "failed" + TurnStatusCancelled TurnStatus = "cancelled" +) + +// TurnRecord is the durable identity and outcome projection for one chat +// generation. ResponseText is retained so a completed duplicate can replay +// without depending on the bounded model-context history window. ToolCalls +// is retained for the same reason and saved in the same call as +// ResponseText, so a completed-duplicate replay (NATS redelivery, restart +// RecoverTurns redelivery) can narrate the tool activity that produced the +// answer instead of showing a tool-less duplicate beside the original. +type TurnRecord struct { + TurnID string + SessionID string + SourceID string + Status TurnStatus + Attempt int + OwnerID string + InputMessageID string + AssistantMessageID string + PartialText string + ResponseText string + ToolCalls []ToolCallEvent + Error string + CreatedAt time.Time + UpdatedAt time.Time +} diff --git a/internal/contracts/store/v1/contracts.go b/internal/domain/storecontract/storecontract.go similarity index 86% rename from internal/contracts/store/v1/contracts.go rename to internal/domain/storecontract/storecontract.go index a7f0af6e7..85f9dd3a2 100644 --- a/internal/contracts/store/v1/contracts.go +++ b/internal/domain/storecontract/storecontract.go @@ -1,19 +1,19 @@ -// Package storev1 is the ratified State Store contract as its consumers -// reference it: the producer-owned daemon/webui/intake store surfaces -// (docs/prds/state-store-contract.md §1, §2). It carries no persistence -- -// *store.Store (SQLite, transitional location) and *staterpc.Client (the -// remote adapter) both satisfy these interfaces -- so a process that only -// holds the contracts, such as the archie-ui dashboard process, can reference -// them without linking the SQL implementation. +// Package storecontract is the ratified State Store contract as its +// consumers reference it: the producer-owned daemon/webui/intake store +// surfaces (docs/prds/state-store-contract.md §1, §2). It carries no +// persistence -- *store.Store (SQLite, transitional location) and +// *staterpc.Client (the remote adapter) both satisfy these interfaces -- +// so a process that only holds the contracts, such as the archie-ui +// dashboard process, can reference them without linking the SQL +// implementation. // -// The package is hand-written, unlike its proto-generated siblings under -// internal/contracts/{gateway,state}/v1: the gRPC fronting service -// (statev1.StateStoreService) is generated, but these Go consumer facades -// predate it and stay narrow (<= 8 methods except the TaskStore composite) -// per the same document. Relocated from internal/store by the UI Service -// deletion gate (archie-core-8cda.5.6); internal/store keeps type aliases so -// daemon-side callers are unaffected. -package storev1 +// It is hand-written and lives in the domain layer (which owns required +// contracts), NOT under internal/contracts: that tree is the buf generate +// output and is wiped and regenerated by tools/proto.sh, which would +// delete a hand-written file there (archie-core-8cda.5.6). Relocated from +// internal/store by the UI Service deletion gate; internal/store keeps +// type aliases so daemon-side callers are unaffected. +package storecontract import ( "context" @@ -22,7 +22,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" - "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" ) @@ -42,11 +42,11 @@ type TaskStore interface { // poll, chat spawn, drain loop) do not acquire a binding-specific shape. type TaskLifecycle interface { EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error) - EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string) (*workflow.Task, error) - ClaimNext(ctx context.Context) (*workflow.Task, error) - ClaimByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) + EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string) (*task.Task, error) + ClaimNext(ctx context.Context) (*task.Task, error) + ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) Transition(ctx context.Context, taskID int64, from, to, detail string) error - Update(ctx context.Context, t *workflow.Task) error + Update(ctx context.Context, t *task.Task) error Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error RecoverStale(ctx context.Context) (int64, error) } @@ -66,11 +66,11 @@ type TaskRetryer interface { // TaskQueries groups read-only task accessors. type TaskQueries interface { - TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) - TaskByID(ctx context.Context, taskID int64) (*workflow.Task, error) - OpenPRs(ctx context.Context) ([]workflow.Task, error) + TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) + TaskByID(ctx context.Context, taskID int64) (*task.Task, error) + OpenPRs(ctx context.Context) ([]task.Task, error) ClearTerminalTasks(ctx context.Context) (int64, error) - Tasks(ctx context.Context, limit int) ([]workflow.Task, error) + Tasks(ctx context.Context, limit int) ([]task.Task, error) StatusCounts(ctx context.Context) (map[string]int, error) IncrementRetryCount(ctx context.Context, taskID int64) error } @@ -158,7 +158,7 @@ type BindingDispatcher interface { // keeps the lifecycle surface narrow (8 methods, the interfacebloat limit) // and keeps the binding-specific shape on the binding interfaces. type BindingTaskCreator interface { - EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*workflow.Task, error) + EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*task.Task, error) } // CapturedEvent is one unbound inbound webhook capture: no workflow binding, diff --git a/internal/domain/workflow/task.go b/internal/domain/workflow/task/task.go similarity index 81% rename from internal/domain/workflow/task.go rename to internal/domain/workflow/task/task.go index 5f43b1b2f..f7ae17bd8 100644 --- a/internal/domain/workflow/task.go +++ b/internal/domain/workflow/task/task.go @@ -1,4 +1,11 @@ -package workflow +// Package task is the task-execution vocabulary of the workflow domain: +// the Task record, its lifecycle statuses, and the narrow Store contract +// workflow stages call mid-run. It split out of package workflow +// (archie-core-8cda.5.6) so the UI process can hold the vocabulary without +// linking the pipeline engine there -- which drags in agentexec, skill and +// tools. package workflow keeps aliases, so daemon-side callers are +// unaffected. +package task import ( "context" @@ -101,3 +108,16 @@ type Store interface { Transition(ctx context.Context, taskID int64, from, to, detail string) error InsertEvent(ctx context.Context, e events.Event) (int64, error) } + +// Definition is the operator-safe snapshot of an executable workflow. It +// contains only identity and stage order, never executable function values. +// It lives with the task vocabulary (not with the engine in package +// workflow) for the same reason this package exists: dashboards render +// Definitions without linking the engine. +type Definition struct { + ID string `json:"id"` + Name string `json:"name"` + Origin string `json:"origin"` + Enabled bool `json:"enabled"` + Stages []string `json:"stages"` +} diff --git a/internal/domain/workflow/task_aliases.go b/internal/domain/workflow/task_aliases.go new file mode 100644 index 000000000..6b0ae18c9 --- /dev/null +++ b/internal/domain/workflow/task_aliases.go @@ -0,0 +1,39 @@ +// Task-vocabulary aliases. The Task record, its statuses, the mid-run +// Store contract, and Definition moved to internal/domain/workflow/task +// (archie-core-8cda.5.6) so the UI process can hold the vocabulary without +// linking this package's pipeline engine (which imports agentexec, skill +// and tools). package workflow keeps these aliases, so daemon-side callers +// are unaffected. +package workflow + +import "github.com/samcharles93/archie-core/internal/domain/workflow/task" + +type ( + // Task is the task-execution record the workflow domain operates on. + Task = task.Task + // Store is the narrow, consumer-owned subset of the State Store + // contract that workflow stages call mid-run. + Store = task.Store + // Definition is the operator-safe snapshot of an executable workflow. + Definition = task.Definition +) + +// Task lifecycle statuses. Defined in internal/taskstate; these names are +// the workflow domain's public spelling. +const ( + StatusQueued = task.StatusQueued + StatusRunning = task.StatusRunning + StatusWaitingHuman = task.StatusWaitingHuman + StatusPROpen = task.StatusPROpen + StatusMerged = task.StatusMerged + StatusParked = task.StatusParked + StatusDead = task.StatusDead + StatusRejected = task.StatusRejected + StatusClosedWontDo = task.StatusClosedWontDo +) + +// Task.Source values. +const ( + SourceForge = task.SourceForge + SourceChat = task.SourceChat +) diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index de743adda..92cc1e92f 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -211,16 +211,6 @@ type Workflow struct { // Registry maps workflow names to definitions. type Registry map[string]Workflow -// Definition is the operator-safe snapshot of an executable workflow. It -// contains only identity and stage order, never executable function values. -type Definition struct { - ID string `json:"id"` - Name string `json:"name"` - Origin string `json:"origin"` - Enabled bool `json:"enabled"` - Stages []string `json:"stages"` -} - // Definitions snapshots a registry deterministically so installed workflows // remain visible even when they have not produced persisted run statistics. func Definitions(reg Registry) []Definition { diff --git a/internal/gateway/chat_contract.go b/internal/gateway/chat_contract.go index 914615ded..fa0ed3c2c 100644 --- a/internal/gateway/chat_contract.go +++ b/internal/gateway/chat_contract.go @@ -1,70 +1 @@ package gateway - -import ( - "context" - - "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/taskstate" -) - -// ChatContract is the conversational boundary consumed by channel frontends. -// Results are snapshots: callers must not rely on shared object identity. -type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade - Snapshot(context.Context) (ChatSnapshot, error) - GetSession(context.Context, string) (SessionContext, bool, error) - RecentMessages(context.Context, string, int) ([]messaging.Message, error) - RecentTurns(context.Context, string, int) ([]TurnRecord, error) - Route(context.Context, Inbound) (ChatReply, error) - // Stream emits started, delta/tool/media, then done or error, in order. - // Callers must drain the stream or cancel the context. Cancellation closes it. - Stream(context.Context, Inbound) (<-chan ChatEvent, error) - Cancel(context.Context, string) (ChatCancellation, error) - SetPersona(context.Context, string, string) (bool, error) - ChatTaskActionContract -} - -// ChatTaskActionContract is the operator task mutation capability exposed by -// the Gateway. It is separate so read/turn consumers do not need to model it. -type ChatTaskActionContract interface { - // ApplyTaskAction applies an action on behalf of a chat identity, which - // may only act on its own tasks. - ApplyTaskAction(context.Context, string, int64, taskstate.Action) (TaskActionResult, error) - // ApplyOperatorTaskAction applies an action on behalf of an authenticated - // dashboard operator, who acts across identities. It is a separate method - // rather than an empty identity because "" is a real identity in a - // single-identity deployment (see chatTaskProfiles in the daemon). - ApplyOperatorTaskAction(context.Context, int64, taskstate.Action) (TaskActionResult, error) -} - -type ChatSnapshot struct { - Sessions []SessionContext - Models []string - ModelsByProvider map[string][]string - Providers []string - ActiveModel string - ActiveProvider string - Personas []string - ActivePersonas map[string]string - RestartAvailable bool - CancellationAvailable bool - PersonasAvailable bool -} - -type ChatReply struct { - Text string - SessionID string -} - -type ChatCancellation struct { - Cancelled bool - Dropped int -} - -// ChatEvent contains values only; Text holds the error message for error events. -type ChatEvent struct { - Kind string - Text string - SessionID string - Tool ToolCallEvent - Media MediaEvent -} diff --git a/internal/gateway/chat_contract_aliases.go b/internal/gateway/chat_contract_aliases.go new file mode 100644 index 000000000..7c33f2bd5 --- /dev/null +++ b/internal/gateway/chat_contract_aliases.go @@ -0,0 +1,97 @@ +// Wire-contract aliases. The chat contract types moved to +// internal/domain/messaging (archie-core-8cda.5.6) so the webui and +// archie-ui processes can hold the contract without linking the gateway +// runtime (and, transitively, its SQLite session store). internal/gateway +// keeps these aliases so daemon-side callers and channel adapters are +// unaffected. +package gateway + +import "github.com/samcharles93/archie-core/internal/domain/messaging" + +type ( + // ChatContract is the conversational boundary consumed by channel frontends. + ChatContract = messaging.ChatContract + // ChatTaskActionContract is the operator task mutation capability. + ChatTaskActionContract = messaging.ChatTaskActionContract + // Inbound is a message arriving from a channel. + Inbound = messaging.Inbound + // SpawnRequest is a chat-originated task creation request. + SpawnRequest = messaging.SpawnRequest + // TaskCreator creates a native task from a chat command. + TaskCreator = messaging.TaskCreator + // ChatSnapshot is the full chat state a dashboard renders in one read. + ChatSnapshot = messaging.ChatSnapshot + // ChatReply is the blocking reply from Route. + ChatReply = messaging.ChatReply + // ChatCancellation is what Cancel returns. + ChatCancellation = messaging.ChatCancellation + // ChatEvent is one streamed chat event. + ChatEvent = messaging.ChatEvent + // ToolCallEvent reports one completed tool invocation within a turn. + ToolCallEvent = messaging.ToolCallEvent + // MediaEvent reports one media attachment produced during a turn. + MediaEvent = messaging.MediaEvent + // MediaAttachment describes a file attached to a message. + MediaAttachment = messaging.MediaAttachment + // TurnStream receives a turn's output as it is produced. + TurnStream = messaging.TurnStream + // TurnStatus is the durable lifecycle state of one chat generation. + TurnStatus = messaging.TurnStatus + // TurnRecord is the durable identity and outcome projection for one chat generation. + TurnRecord = messaging.TurnRecord + // SessionSource identifies the platform, bot identity, and conversation a session belongs to. + SessionSource = messaging.SessionSource + // SessionContext holds the full metadata for an active gateway session. + SessionContext = messaging.SessionContext + // SessionStore persists gateway session metadata and conversation history. + SessionStore = messaging.SessionStore + // SessionLifecycle manages session CRUD and listing. + SessionLifecycle = messaging.SessionLifecycle + // MessageHistory manages conversation messages within a session. + MessageHistory = messaging.MessageHistory + // MessageQuery is one page request against a session's message history. + MessageQuery = messaging.MessageQuery + // MessagePage is one page of search results. + MessagePage = messaging.MessagePage + // CommandSpec describes a local command for adapter-provided discovery. + CommandSpec = messaging.CommandSpec + // DangerousCommandAuthority is the sandbox-owned authority for destructive operations. + DangerousCommandAuthority = messaging.DangerousCommandAuthority + // CheckpointInfo describes a saved sandbox filesystem checkpoint. + CheckpointInfo = messaging.CheckpointInfo + // TaskActionResult is what task_action returns. + TaskActionResult = messaging.TaskActionResult + // DashboardNavigateResult is what dashboard_navigate returns. + DashboardNavigateResult = messaging.DashboardNavigateResult +) + +// Turn lifecycle states. +const ( + TurnStatusAccepted = messaging.TurnStatusAccepted + TurnStatusRunning = messaging.TurnStatusRunning + TurnStatusPartial = messaging.TurnStatusPartial + TurnStatusCompleted = messaging.TurnStatusCompleted + TurnStatusFailed = messaging.TurnStatusFailed + TurnStatusCancelled = messaging.TurnStatusCancelled +) + +// Page-size bounds for MessageQuery. +const ( + DefaultMessagePageSize = messaging.DefaultMessagePageSize + MaxMessagePageSize = messaging.MaxMessagePageSize + MaxMessageSearchQueryBytes = messaging.MaxMessageSearchQueryBytes + MaxMessageSearchQueryTerms = messaging.MaxMessageSearchQueryTerms +) + +// LocalCommands returns the command names Route answers from local state. +func LocalCommands() []string { return messaging.LocalCommands() } + +// LocalCommandSpecs returns a copy safe for adapters to enrich with their +// optional capabilities. +func LocalCommandSpecs() []CommandSpec { return messaging.LocalCommandSpecs() } + +// RoleForSender classifies a message sender: a message sent by the +// session's bot is the assistant's, anything else is the user's. +func RoleForSender(sender, botUser string) messaging.Role { + return messaging.RoleForSender(sender, botUser) +} diff --git a/internal/gateway/dangerous.go b/internal/gateway/dangerous.go index a30c0b83d..fa0ed3c2c 100644 --- a/internal/gateway/dangerous.go +++ b/internal/gateway/dangerous.go @@ -1,23 +1 @@ package gateway - -import ( - "context" - "time" -) - -// DangerousCommandAuthority is the sandbox-owned authority for operations -// that can destroy process or filesystem state. Adapters only request and -// present approval; they never implement these operations themselves. -type DangerousCommandAuthority interface { - StopProcess(context.Context, string) error - Rollback(context.Context, int) (string, error) - ListCheckpoints(context.Context) ([]CheckpointInfo, error) -} - -// CheckpointInfo describes a saved sandbox filesystem checkpoint. -type CheckpointInfo struct { - Number int - Timestamp time.Time - Label string - Size string -} diff --git a/internal/gateway/dashboard_tools.go b/internal/gateway/dashboard_tools.go index 4b0bf8a93..d48932cd0 100644 --- a/internal/gateway/dashboard_tools.go +++ b/internal/gateway/dashboard_tools.go @@ -69,13 +69,6 @@ func pageIndexTool() (tools.ToolEntry, bool) { return entry, true } -// DashboardNavigateResult is what dashboard_navigate returns. The web UI -// renders it as a clickable chip that routes the operator to the page. -type DashboardNavigateResult struct { - Path string `json:"path"` - Label string `json:"label"` -} - // dashboardNavigateTool resolves a page path and returns the navigation the UI // can follow. It validates against the registry and refuses an unknown route // rather than guessing, so a chip is only ever produced for a real page. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9a3714936..2d2f65adb 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -25,25 +25,6 @@ import ( "github.com/samcharles93/archie-core/internal/taskstate" ) -// Inbound is a message arriving from a channel together with the -// transport context that is not part of the canonical record. -// -// Message is the record itself, exactly as it will be persisted. Channels -// construct it directly: ConversationID addresses the chat (a Telegram -// chat ID and topic thread, an email recipient, a webhook path), Sender is -// the channel-native attribution, and Role is always messaging.RoleUser -- -// a channel only ever carries what a person said. ID is left empty for a -// newly received message so the store derives one from SourceID, and -// honoured when set, which is what lets a read-modify-write of a history -// keep its identities rather than minting new ones. -type Inbound struct { - Message messaging.Message - // Page is the dashboard route the operator is on when they sent - // this message. Transport-only: it reaches the system prompt and - // is never persisted. Empty for non-web channels. - Page string -} - // Lifecycle receives adapter-owned startup facts. Callbacks are optional. // Starting is reported before each launch attempt; Running is reported only // after the adapter's external delivery boundary is ready. @@ -163,26 +144,6 @@ type DangerousApprover interface { Decide(context.Context, string, string) (string, error) } -// SpawnRequest is a chat-originated task creation request. Repo and -// Workflow are optional -- empty means "the daemon's configured -// default for this identity". -type SpawnRequest struct { - Title string - Body string // operator instructions carried into the admitted task - Repo string // "owner/name"; empty = identity's default repo - Workflow string // empty = daemon's default workflow routing - Identity string // the identity spawning this task; propagated from Router.Identity -} - -// TaskCreator creates a native (non-forge-backed) task from a chat -// command. The daemon supplies an implementation backed by the store. -// When nil on a Router, /spawn returns "not configured". CreateTask -// must return the task's real, durable database ID -- never a -// synthetic or fabricated value. -type TaskCreator interface { - CreateTask(ctx context.Context, req SpawnRequest) (taskID int64, err error) -} - // TaskController approves or cancels a chat-originated task. Both // methods must enforce authorization (identity must own the task) and // valid state transitions; see gateway.tasks.go's StoreTaskController @@ -499,72 +460,10 @@ func (r *Router) RouteStream(ctx context.Context, in Inbound, stream TurnStream) return reply, err } -var localCommands = []string{ - "/status", "/tasks", "/model", "/spawn", "/approve", "/cancel", - "/start", - "/new", "/reset", "/topic", "/retry", "/undo", - "/title", "/branch", "/fork", "/compress", "/compact", - "/whoami", "/profile", "/sessions", "/resume", "/delete", "/agents", - "/personality", "/help", "/version", "/update", "/restart", -} - -// CommandSpec describes a local command for adapter-provided discovery. -// Keeping this beside the executable command list prevents help surfaces from -// drifting when a command is added or removed. -type CommandSpec struct { - Command string `json:"command"` - Description string `json:"description"` - Usage string `json:"usage"` -} - -var localCommandSpecs = []CommandSpec{ - {Command: "/status", Description: "Show daemon health", Usage: "/status"}, - {Command: "/tasks", Description: "Show running and parked work", Usage: "/tasks"}, - {Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"}, - {Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn <title>"}, - {Command: "/approve", Description: "Approve a waiting task", Usage: "/approve <task-id>"}, - {Command: "/cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel <task-id>"}, - {Command: "/start", Description: "Confirm that Archie is running", Usage: "/start"}, - {Command: "/new", Description: "Start a fresh conversation", Usage: "/new [title]"}, - {Command: "/reset", Description: "Alias for /new", Usage: "/reset [title]"}, - {Command: "/topic", Description: "List or switch conversation topics", Usage: "/topic [session-id]"}, - {Command: "/retry", Description: "Replay the last message", Usage: "/retry"}, - {Command: "/undo", Description: "Remove recent messages", Usage: "/undo [N]"}, - {Command: "/title", Description: "Show or set the conversation title", Usage: "/title [name]"}, - {Command: "/branch", Description: "Create a child conversation", Usage: "/branch [name]"}, - {Command: "/fork", Description: "Alias for /branch", Usage: "/fork [name]"}, - {Command: "/compress", Description: "Compress conversation context", Usage: "/compress [options]"}, - {Command: "/compact", Description: "Alias for /compress", Usage: "/compact [options]"}, - {Command: "/whoami", Description: "Show the active identity and model", Usage: "/whoami"}, - {Command: "/profile", Description: "Show the active identity profile", Usage: "/profile"}, - {Command: "/sessions", Description: "List this channel's conversations", Usage: "/sessions"}, - {Command: "/resume", Description: "Switch to a conversation", Usage: "/resume <session-id>"}, - {Command: "/delete", Description: "Delete a conversation and its history", Usage: "/delete <session-id>"}, - {Command: "/agents", Description: "List tasks currently being worked", Usage: "/agents"}, - {Command: "/personality", Description: "Choose a communication style", Usage: "/personality [name]"}, - {Command: "/help", Description: "See what Archie can do", Usage: "/help"}, - {Command: "/version", Description: "Show installed Archie versions", Usage: "/version"}, - {Command: "/update", Description: "Check for Archie updates", Usage: "/update"}, - {Command: "/restart", Description: "Reload the chat adapter", Usage: "/restart"}, -} - -// LocalCommands returns the command names Route answers from local state. -// Gateways use this to verify that their published command surfaces match -// the executable router surface. -func LocalCommands() []string { - return slices.Clone(localCommands) -} - -// LocalCommandSpecs returns a copy safe for adapters to enrich with their -// optional capabilities. -func LocalCommandSpecs() []CommandSpec { - return slices.Clone(localCommandSpecs) -} - // isLocalCommand reports whether cmd is answered from local state by // Route rather than handed to the LLM. func isLocalCommand(cmd string) bool { - return slices.Contains(localCommands, cmd) + return slices.Contains(messaging.LocalCommands(), cmd) } // parseCmd extracts the command name from text, stripping an optional diff --git a/internal/gateway/messageevent.go b/internal/gateway/messageevent.go index 544d6e749..7ff995286 100644 --- a/internal/gateway/messageevent.go +++ b/internal/gateway/messageevent.go @@ -1,52 +1,5 @@ package gateway -// MediaAttachment describes a file attached to a message. Platform-agnostic; -// platform-specific fields live in Raw. -// -// Numeric fields use pointers so that zero is distinguishable from -// "unknown" across a JSON round-trip: a 0-byte file is valid and -// different from a file whose size was never set. -type MediaAttachment struct { - // Type is "image", "video", "audio", or "document". - Type string `json:"type"` - - // FileID is the platform-assigned identifier for download APIs. - FileID string `json:"file_id"` - - // URL is a direct download URL when available. May be empty for - // platforms that require a download API call. - URL string `json:"url,omitempty"` - - // Path is a local filesystem path on the host that produced the - // attachment. It is the alternative to URL for outbound delivery: a - // URL is fetched by the platform, a Path is uploaded by us. A file the - // agent wrote has no URL and never gets one -- publishing it would - // trade a delivery problem for a hosting and access-control one -- so - // senders that support upload must read this. - // - // Exactly one of URL and Path is meaningful for an outbound send. - Path string `json:"path,omitempty"` - - // MIMEType is the content type (e.g. "image/png", "audio/ogg"). - MIMEType string `json:"mime_type,omitempty"` - - // FileName is the original file name when known. - FileName string `json:"file_name,omitempty"` - - // FileSize is the attachment size in bytes. nil means unknown. - FileSize *int64 `json:"file_size,omitempty"` - - // Width is the pixel width for images and video. nil means unknown - // or not applicable. - Width *int `json:"width,omitempty"` - - // Height is the pixel height for images and video. - Height *int `json:"height,omitempty"` - - // Duration is the play time in seconds for audio and video. - Duration *int `json:"duration,omitempty"` -} - // MessageEvent is the rich message model for all gateway channels. It // carries the platform detail an adapter needs beyond the persisted // record, and keeps the Text() and FromID() helpers for callers that only diff --git a/internal/gateway/messaging_convert.go b/internal/gateway/messaging_convert.go index 6b2718959..525099adb 100644 --- a/internal/gateway/messaging_convert.go +++ b/internal/gateway/messaging_convert.go @@ -1,9 +1,5 @@ package gateway -import ( - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - // This file holds the one piece of the old channel-facing Message that // outlived it: the role derivation. // @@ -19,15 +15,3 @@ import ( // instead of adding a field to the proto -- see // internal/infrastructure/gatewayrpc. Because both derive from the same // session, they agree. - -// RoleForSender reports the role of a message written by sender in a -// session whose bot identity is botUser. It is the comparison this package -// already makes elsewhere (compressTurnHistory, messagesToCompressed, -// PriorReply, and the sessioncurator adapter): a message sent by the -// session's bot is the assistant's, anything else is the user's. -func RoleForSender(sender, botUser string) messaging.Role { - if sender == botUser { - return messaging.RoleAssistant - } - return messaging.RoleUser -} diff --git a/internal/gateway/session.go b/internal/gateway/session.go index ad943c71a..fa0ed3c2c 100644 --- a/internal/gateway/session.go +++ b/internal/gateway/session.go @@ -1,57 +1 @@ package gateway - -import "time" - -// SessionSource identifies the platform, bot identity, and conversation a -// gateway session belongs to. It is the composite natural key for session -// lookup. -type SessionSource struct { - // Platform is the adapter name ("telegram", "discord", "web"). - Platform string `json:"platform"` - - // BotUser is the bot identity serving this session (e.g. "archie", - // "winter"). Distinct bot identities on the same platform and channel - // produce distinct sessions. - BotUser string `json:"bot_user"` - - // ChannelID is the platform conversation identifier (chat ID, channel - // name, DM thread). - ChannelID string `json:"channel_id"` - - // ThreadID identifies the topic thread within the conversation, for - // platforms that support threading (Telegram supergroup topics, - // Slack threads, Discord forum posts). Empty for flat chats and the - // General topic. When non-empty, distinct threads within the same - // channel produce distinct sessions. - ThreadID string `json:"thread_id,omitempty"` -} - -// SessionContext holds the full metadata for an active gateway session. -// SessionStore is the persistence layer; callers treat SessionContext as -// a value object. -type SessionContext struct { - // SessionID is the unique session identifier (UUID). - SessionID string `json:"session_id"` - - // Source identifies the platform, bot, and conversation. - Source SessionSource `json:"source"` - - // Title is an optional human-readable name for the session, set - // via /title. Empty until set. - Title string `json:"title,omitempty"` - - // ParentSessionID is the session this one was branched from, set - // by /branch or /fork. Empty for root sessions. - ParentSessionID string `json:"parent_session_id,omitempty"` - - // BranchName is the name given when branching, set via - // /branch <name>. Empty for root sessions. - BranchName string `json:"branch_name,omitempty"` - - // CreatedAt is when the session was first established. - CreatedAt time.Time `json:"created_at"` - - // LastActiveAt is the timestamp of the most recent message or event - // on this session. Updated by Touch. - LastActiveAt time.Time `json:"last_active_at"` -} diff --git a/internal/gateway/session_store.go b/internal/gateway/session_store.go index 198ac5f3a..96e690ac2 100644 --- a/internal/gateway/session_store.go +++ b/internal/gateway/session_store.go @@ -1,7 +1,6 @@ package gateway import ( - "context" "encoding/binary" "strings" "time" @@ -11,91 +10,6 @@ import ( "github.com/samcharles93/archie-core/internal/domain/messaging" ) -// SessionStore persists gateway session metadata and conversation history. -// Each session tracks one platform, bot, and channel combination. -// -// Message history is stored and loaded as canonical messaging.Message -// records (archie-core-d9dv). Session lifecycle records stay SessionContext: -// a session's UUID key, platform/bot/title/branch metadata, and the fact -// that several sessions share one channel/thread have no lossless home in -// messaging.Conversation, whose composite identity is only -// {ChannelID, ThreadID} and whose canonical Agent/user/binding ownership is -// still open (see docs/architecture/migration-decisions.md section 2). -// Conversation-keying the sessions is tracked as follow-up work once that -// ownership settles. -type SessionStore interface { - SessionLifecycle - MessageHistory -} - -// SessionLifecycle manages session CRUD and listing. -type SessionLifecycle interface { - // Save inserts or replaces a session. - Save(ctx context.Context, s SessionContext) error - // Get returns a session by ID, or nil when it does not exist. - Get(ctx context.Context, sessionID string) (*SessionContext, error) - // GetByChannel returns matching sessions newest first. - GetByChannel(ctx context.Context, platform, channelID string) ([]SessionContext, error) - // Delete removes a session. Deleting an absent session is a no-op. - Delete(ctx context.Context, sessionID string) error - // Touch marks a session active at the current time. - Touch(ctx context.Context, sessionID string) error - // List returns all sessions newest first. - List(ctx context.Context) ([]SessionContext, error) -} - -// MessageHistory manages conversation messages within a session. Messages -// are canonical messaging.Message records, the same type channel adapters -// hand the Router, so nothing converts on the way in or out. -type MessageHistory interface { - // SaveMessage appends one message with a strictly increasing timestamp. - SaveMessage(ctx context.Context, sessionID string, msg messaging.Message) error - // RecentMessages returns the most recent messages in chronological order. - RecentMessages(ctx context.Context, sessionID string, n int) ([]messaging.Message, error) - // DeleteRecentMessages removes up to n messages and returns the count. - DeleteRecentMessages(ctx context.Context, sessionID string, n int) (deleted int, err error) - // MessageCount returns the number of stored messages in a session. - MessageCount(ctx context.Context, sessionID string) (int, error) - // SaveMessages appends messages used to inherit branch history. - SaveMessages(ctx context.Context, sessionID string, msgs []messaging.Message) error - // ReplaceMessages writes replacements before deleting superseded messages. - // Records absent from both inputs remain untouched. - ReplaceMessages(ctx context.Context, sessionID string, msgs []messaging.Message, superseded []string) error - // SearchMessages searches the session's full history. - SearchMessages(ctx context.Context, sessionID string, q MessageQuery) (MessagePage, error) - // Close releases the database. - Close() error -} - -// MessageQuery is one page request against a session's message history. Limit -// is clamped to MaxMessagePageSize and Offset is never negative. -type MessageQuery struct { - Query string - Limit int - // Offset is the number of ranked matches to skip. - Offset int -} - -// MessagePage is one page of search results. -type MessagePage struct { - // Messages are ordered by relevance. - Messages []messaging.Message - // NextOffset is meaningful only when HasMore is true. - NextOffset int - HasMore bool - // Truncated is retained in the transport contract and is always false for - // SQLite because it can count the complete result set. - Truncated bool -} - -// Page-size bounds for MessageQuery. -const ( - DefaultMessagePageSize = 50 - MaxMessagePageSize = 500 - MaxMessageSearchQueryBytes = 4096 - MaxMessageSearchQueryTerms = 64 -) - // NewSessionStoreMemory returns an in-memory SQLite SessionStore for tests. func NewSessionStoreMemory() SessionStore { store, err := NewSQLiteSessionStoreMemory() diff --git a/internal/gateway/stream.go b/internal/gateway/stream.go index c331ab8f3..db499a170 100644 --- a/internal/gateway/stream.go +++ b/internal/gateway/stream.go @@ -16,43 +16,15 @@ const ( redactedParameterValue = "[redacted]" ) -// ToolCallEvent reports one completed tool invocation within a turn. It -// carries the raw outcome rather than rendered text: presentation (emoji, -// layout, whether to show it at all) belongs to the channel adapter. -type ToolCallEvent struct { - // ID correlates the completed result with the model's invocation. - ID string - // Name is the tool the model invoked. - Name string - // Parameters is a bounded, redacted JSON summary of the invocation input. - // It is safe for channel adapters to render directly. - Parameters string - // Output is what the tool returned, verbatim. - Output string - // Err is non-empty when the tool failed, in which case Output is - // unreliable and usually empty. - Err string -} - -// Summary reduces the outcome to a single short line suitable for an inline -// status entry. It never returns an empty string: a tool that returned -// nothing still ran, and a blank summary would read as a rendering fault. -func (e ToolCallEvent) Summary() string { - if line := firstNonEmptyLine(e.Err); line != "" { - return "failed: " + truncateRunes(line, toolSummaryMaxRunes) - } - if line := firstNonEmptyLine(e.Output); line != "" { - return truncateRunes(line, toolSummaryMaxRunes) - } - return "done" -} - // RenderToolCall returns the channel-neutral compact representation used by // chat surfaces. Parameters are intentionally omitted: JSON/schema-shaped // inputs are noisy, often contain secrets, and are not useful progress text. // Results are reduced semantically instead of clipped blindly: file contents, // listings and structured envelopes are described, never echoed. -func (e ToolCallEvent) RenderToolCall() string { +// RenderToolCall returns the channel-neutral compact representation used by +// chat surfaces. (A function rather than a method because ToolCallEvent is a +// messaging alias: see chat_contract_aliases.go.) +func RenderToolCall(e ToolCallEvent) string { if limit, ok := legacyTurnBudgetLimit(e.Err); ok { return toolProgressBlock("tools", "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit)) } @@ -66,7 +38,10 @@ func (e ToolCallEvent) RenderToolCall() string { // retries. Legacy aggregate-output-limit errors deliberately share one key // across tool names: they are one obsolete turn-level condition, not five // independently useful failures. -func (e ToolCallEvent) FailureKey() string { +// FailureKey identifies equivalent failures for channel adapters that +// collapse retries. (A function rather than a method because ToolCallEvent +// is a messaging alias: see chat_contract_aliases.go.) +func FailureKey(e ToolCallEvent) string { if _, ok := legacyTurnBudgetLimit(e.Err); ok { return "legacy-turn-output-limit" } @@ -240,37 +215,6 @@ func truncateRunesWithinLimit(s string, limit int) string { return string(runes[:limit-1]) + "…" } -// MediaEvent reports one media attachment produced during a turn, so a -// channel can deliver it (e.g. through gateway.MediaSender) in the same -// ordered pass as the text and tool activity that surrounded it. -type MediaEvent struct { - // ToolName is the tool call that produced the attachment. - ToolName string - // Attachment is the media to deliver. - Attachment MediaAttachment -} - -// TurnStream receives a turn's output as it is produced. -// -// It replaces the plain delta callback so a channel can render tool activity -// in the same ordered pass as the text: both arrive on the generating -// goroutine, in the order the model produced them. Implementations must not -// block -- a slow renderer stalls generation -- and must be safe to call -// from that goroutine only. -// -// Callers that render text alone use DeltaFunc rather than implementing this. -type TurnStream interface { - // Delta appends the next fragment of assistant text. - Delta(text string) - // ToolCall reports a tool invocation that has finished executing. - ToolCall(event ToolCallEvent) - // Media reports a media attachment a tool call produced during the - // turn. A channel that cannot deliver it inline (see - // gateway.CapabilitiesOf) is expected to fall back to rendering the - // attachment's URL as text instead of dropping it silently. - Media(event MediaEvent) -} - // DeltaFunc adapts a plain text-delta callback to TurnStream for callers that // render text only. Tool events are discarded. A nil DeltaFunc is inert, so // DeltaFunc(nil) is a usable "stream nothing" sink. diff --git a/internal/gateway/task_tools.go b/internal/gateway/task_tools.go index 880d8d72c..b07a7bc68 100644 --- a/internal/gateway/task_tools.go +++ b/internal/gateway/task_tools.go @@ -68,13 +68,6 @@ type TaskSpawnResult struct { Message string `json:"message"` } -// TaskActionResult is what task_action returns. -type TaskActionResult struct { - TaskID int64 `json:"task_id"` - Action string `json:"action"` - Message string `json:"message"` -} - // ChatTaskActor is the mutation surface task_action needs. It mirrors the // ChatTaskLister pattern: gateway states what it needs and the daemon // supplies an adapter over the store and runtime, so this package keeps its diff --git a/internal/gateway/tool_render_test.go b/internal/gateway/tool_render_test.go index 224db611e..0cdc89362 100644 --- a/internal/gateway/tool_render_test.go +++ b/internal/gateway/tool_render_test.go @@ -6,7 +6,7 @@ import ( ) func TestToolCallEventRenderToolCallUsesCompactSafeOutput(t *testing.T) { - got := (ToolCallEvent{Name: "shell", Parameters: `{"command":"{schema placeholder}"}`, Output: "line one\nline two"}).RenderToolCall() + got := RenderToolCall(ToolCallEvent{Name: "shell", Parameters: `{"command":"{schema placeholder}"}`, Output: "line one\nline two"}) if strings.Contains(got, "schema placeholder") || strings.Contains(got, "Parameters") { t.Fatalf("render leaked input/schema noise: %q", got) } @@ -17,7 +17,7 @@ func TestToolCallEventRenderToolCallUsesCompactSafeOutput(t *testing.T) { func TestToolCallEventRenderToolCallShowsUsefulPreviewWithoutDumpingSource(t *testing.T) { source := "package agentexec\n\nimport (\n \"context\"\n)\n\ntype AgentRequestMessage struct {\n Workflow string\n}\n" - got := (ToolCallEvent{Name: "read", Output: source}).RenderToolCall() + got := RenderToolCall(ToolCallEvent{Name: "read", Output: source}) if strings.Contains(got, "type AgentRequestMessage") || strings.Contains(got, "content hidden") { t.Fatalf("read preview should show a short lead-in, not dump or hide everything: %q", got) } @@ -26,7 +26,7 @@ func TestToolCallEventRenderToolCallShowsUsefulPreviewWithoutDumpingSource(t *te } listing := "/home/sam/projects/archie-core\n/home/sam/projects/archie-core/internal/gateway\n/home/sam/go/pkg/mod/github.com/samcharles93/ai-sdk@v0.1.21/prompt/prompt.go\n" - got = (ToolCallEvent{Name: "find", Output: listing}).RenderToolCall() + got = RenderToolCall(ToolCallEvent{Name: "find", Output: listing}) if strings.Contains(got, "listing hidden") || strings.Contains(got, "/pkg/mod/") { t.Fatalf("find preview should show a short local path, not hide or dump module cache: %q", got) } @@ -36,14 +36,14 @@ func TestToolCallEventRenderToolCallShowsUsefulPreviewWithoutDumpingSource(t *te } func TestToolCallEventRenderToolCallBoundsOutputAndPreservesFailure(t *testing.T) { - got := (ToolCallEvent{Name: "read", Output: strings.Repeat("x", 2000)}).RenderToolCall() + got := RenderToolCall(ToolCallEvent{Name: "read", Output: strings.Repeat("x", 2000)}) if len([]rune(got)) > 520 { t.Fatalf("render has %d runes, want bounded output", len([]rune(got))) } if strings.Contains(got, strings.Repeat("x", 200)) { t.Fatalf("oversized contents were not bounded: %q", got) } - failed := (ToolCallEvent{Name: "shell", Output: "ignored", Err: "command_exit: exit status 2"}).RenderToolCall() + failed := RenderToolCall(ToolCallEvent{Name: "shell", Output: "ignored", Err: "command_exit: exit status 2"}) if failed != "🔧 shell — failed\n```text\ncommand_exit: exit status 2\n```" { t.Fatalf("failure render = %q", failed) } @@ -52,10 +52,10 @@ func TestToolCallEventRenderToolCallBoundsOutputAndPreservesFailure(t *testing.T func TestToolCallEventFailureKeyCollapsesLegacyTurnBudget(t *testing.T) { first := ToolCallEvent{Name: "read", Err: "tool read: turn budget exceeded (200000 chars)"} second := ToolCallEvent{Name: "shell", Err: "tool shell: turn budget exceeded (200000 chars)"} - if first.FailureKey() == "" || first.FailureKey() != second.FailureKey() { - t.Fatalf("legacy output-limit failures should share one key: %q vs %q", first.FailureKey(), second.FailureKey()) + if FailureKey(first) == "" || FailureKey(first) != FailureKey(second) { + t.Fatalf("legacy output-limit failures should share one key: %q vs %q", FailureKey(first), FailureKey(second)) } - if first.RenderToolCall() != "🔧 tools — stopped\n```text\ntool-output limit reached (200000 chars); further results suppressed\n```" { - t.Fatalf("legacy output-limit render = %q", first.RenderToolCall()) + if RenderToolCall(first) != "🔧 tools — stopped\n```text\ntool-output limit reached (200000 chars); further results suppressed\n```" { + t.Fatalf("legacy output-limit render = %q", RenderToolCall(first)) } } diff --git a/internal/gateway/turn_ledger.go b/internal/gateway/turn_ledger.go index 04a131f53..ba4fad5f0 100644 --- a/internal/gateway/turn_ledger.go +++ b/internal/gateway/turn_ledger.go @@ -4,23 +4,10 @@ import ( "context" "errors" "strings" - "time" "github.com/google/uuid" ) -// TurnStatus is the durable lifecycle state of one chat generation. -type TurnStatus string - -const ( - TurnStatusAccepted TurnStatus = "accepted" - TurnStatusRunning TurnStatus = "running" - TurnStatusPartial TurnStatus = "partial" - TurnStatusCompleted TurnStatus = "completed" - TurnStatusFailed TurnStatus = "failed" - TurnStatusCancelled TurnStatus = "cancelled" -) - // TurnClaim describes what happened when a caller claimed a durable turn. type TurnClaim string @@ -37,30 +24,6 @@ var ErrTurnInProgress = errors.New("chat turn already in progress") // newer attempt of the same durable turn. var ErrTurnOwnershipLost = errors.New("chat turn ownership lost") -// TurnRecord is the durable identity and outcome projection for one chat -// generation. ResponseText is retained so a completed duplicate can replay -// without depending on the bounded model-context history window. ToolCalls -// is retained for the same reason and saved in the same call as -// ResponseText, so a completed-duplicate replay (NATS redelivery, restart -// RecoverTurns redelivery) can narrate the tool activity that produced the -// answer instead of showing a tool-less duplicate beside the original. -type TurnRecord struct { - TurnID string - SessionID string - SourceID string - Status TurnStatus - Attempt int - OwnerID string - InputMessageID string - AssistantMessageID string - PartialText string - ResponseText string - ToolCalls []ToolCallEvent - Error string - CreatedAt time.Time - UpdatedAt time.Time -} - // TurnLedger persists chat-turn identity and lifecycle independently from the // conversation message history. Session stores implement it as an optional // capability so existing narrow test stores remain source-compatible. diff --git a/internal/infrastructure/captureintake/receiver.go b/internal/infrastructure/captureintake/receiver.go index 24a247418..cae93b7b5 100644 --- a/internal/infrastructure/captureintake/receiver.go +++ b/internal/infrastructure/captureintake/receiver.go @@ -22,8 +22,8 @@ import ( "net/http" "time" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/webhookguard" ) @@ -37,7 +37,7 @@ type Receiver struct { // Captures persists what arrives. Nil answers 503 rather than failing // the process it is mounted in: capture is a precondition for the // no-code playbook epic, not a hard dependency of the daemon. - Captures storev1.CaptureStore + Captures storecontract.CaptureStore // Limiter is the per-remote-address token bucket applied before a body // is read. Nil disables rate limiting, which composition never does in // production. @@ -45,7 +45,7 @@ type Receiver struct { // Bindings resolves the armed binding whose secret authenticates a // source. Nil disables per-source HMAC verification and every event // records as authenticated=false. - Bindings storev1.BindingDispatcher + Bindings storecontract.BindingDispatcher // Retention and MaxEvents are passed straight to InsertCapture's // prune-on-write bounds. See config.CaptureConfig. Retention time.Duration @@ -135,7 +135,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { redactedBody = body } - c := storev1.CapturedEvent{ + c := storecontract.CapturedEvent{ ReceivedAt: time.Now().UTC(), Source: source, RemoteAddr: r.RemoteAddr, diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 1ba322d00..396eb038c 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -7,7 +7,6 @@ import ( "time" "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/secret" ) // Defaults applied to absent input. Named so a reader can find the value @@ -221,7 +220,7 @@ func applyForgeDefaults(cfg *config.Config) { cfg.Forge.Host = defaultForgeHost } if cfg.Forge.Token.Engine == "" && cfg.Forge.Token.Key == "" && cfg.Forge.TokenEnv != "" { - cfg.Forge.Token = secret.SecretRef{Engine: "env", Key: cfg.Forge.TokenEnv} + cfg.Forge.Token = config.SecretRef{Engine: "env", Key: cfg.Forge.TokenEnv} } if cfg.Forge.Intake == "" { cfg.Forge.Intake = config.ForgeIntakePoll diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index e47e8cf15..5e833b4ea 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/secret" ) // Recognised enum values, named so validation and its error message cannot @@ -108,7 +107,7 @@ func validateImage(cfg *config.Config) error { if p.Class == "" { return fmt.Errorf("%w: image.hosted.%s.class is required when enabled", ErrInvalidInput, name) } - if p.APIKeyEnv == "" && p.APIKey == (secret.SecretRef{}) { + if p.APIKeyEnv == "" && p.APIKey == (config.SecretRef{}) { return fmt.Errorf("%w: image.hosted.%s requires api_key_env or api_key when enabled", ErrInvalidInput, name) } } @@ -222,7 +221,7 @@ func validateForgeIntake(cfg *config.Config) error { return fmt.Errorf("%w: forge.intake %q (want %s)", ErrInvalidInput, cfg.Forge.Intake, list(forgeIntakes)) } if intake == config.ForgeIntakeWebhook || intake == config.ForgeIntakeBoth { - if cfg.Forge.WebhookSecret == (secret.SecretRef{}) { + if cfg.Forge.WebhookSecret == (config.SecretRef{}) { return fmt.Errorf("%w: forge.webhook_secret is required when forge.intake is %q", ErrInvalidInput, intake) } if cfg.Forge.WebhookAddr == "" { @@ -265,7 +264,7 @@ func validateIdentities(identities []config.IdentityConfig) error { if !oneOf(id.Forge.Type, forgeTypes) { return fmt.Errorf("%w: identities[%d].forge.type %q (want %s)", ErrInvalidInput, i, id.Forge.Type, list(forgeTypes)) } - if !ForgeDisabled(id.Forge.Type) && id.Forge.Token == (secret.SecretRef{}) { + if !ForgeDisabled(id.Forge.Type) && id.Forge.Token == (config.SecretRef{}) { return fmt.Errorf("%w: identities[%d].forge.token is required (each identity needs its own secret reference; unlike the top-level [forge], there is no default)", ErrInvalidInput, i) } if err := validateRepos(id.Repos); err != nil { diff --git a/internal/infrastructure/gatewayrpc/client.go b/internal/infrastructure/gatewayrpc/client.go index 8e77b930a..f66988820 100644 --- a/internal/infrastructure/gatewayrpc/client.go +++ b/internal/infrastructure/gatewayrpc/client.go @@ -10,13 +10,12 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/taskstate" ) -var _ gateway.ChatContract = (*Client)(nil) +var _ messaging.ChatContract = (*Client)(nil) -// Client implements gateway.ChatContract over the chat service. The proto +// Client implements messaging.ChatContract over the chat service. The proto // is unchanged by the messaging migration, so history crosses without its // role and is re-addressed from the owning session on arrival; StoreClient // serves the SessionStore view over the same RPCs. @@ -26,18 +25,18 @@ func NewClient(conn grpc.ClientConnInterface) *Client { return &Client{client: pb.NewChatServiceClient(conn)} } -func (c *Client) Snapshot(ctx context.Context) (gateway.ChatSnapshot, error) { +func (c *Client) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) { v, err := c.client.Snapshot(ctx, &pb.SnapshotRequest{}) if err != nil { - return gateway.ChatSnapshot{}, err + return messaging.ChatSnapshot{}, err } return snapshotValue(v), nil } -func (c *Client) GetSession(ctx context.Context, id string) (gateway.SessionContext, bool, error) { +func (c *Client) GetSession(ctx context.Context, id string) (messaging.SessionContext, bool, error) { v, err := c.client.GetSession(ctx, &pb.GetSessionRequest{SessionId: id}) if err != nil { - return gateway.SessionContext{}, false, err + return messaging.SessionContext{}, false, err } return sessionValue(v.Session), v.Found, nil } @@ -50,7 +49,7 @@ func (c *Client) RecentMessages(ctx context.Context, id string, n int) ([]messag return addressRecords(ctx, c.client, id, v.Messages) } -func (c *Client) RecentTurns(ctx context.Context, id string, n int) ([]gateway.TurnRecord, error) { +func (c *Client) RecentTurns(ctx context.Context, id string, n int) ([]messaging.TurnRecord, error) { v, err := c.client.RecentTurns(ctx, &pb.RecentTurnsRequest{SessionId: id, Limit: int64(n)}) if err != nil { return nil, err @@ -58,20 +57,20 @@ func (c *Client) RecentTurns(ctx context.Context, id string, n int) ([]gateway.T return mapValues(v.Turns, turnValue), nil } -func (c *Client) Route(ctx context.Context, in gateway.Inbound) (gateway.ChatReply, error) { +func (c *Client) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) { v, err := c.client.Route(ctx, &pb.RouteRequest{Message: inboundProto(in)}) if err != nil { - return gateway.ChatReply{}, err + return messaging.ChatReply{}, err } - return gateway.ChatReply{Text: v.Text, SessionID: v.SessionId}, nil + return messaging.ChatReply{Text: v.Text, SessionID: v.SessionId}, nil } -func (c *Client) Cancel(ctx context.Context, id string) (gateway.ChatCancellation, error) { +func (c *Client) Cancel(ctx context.Context, id string) (messaging.ChatCancellation, error) { v, err := c.client.Cancel(ctx, &pb.CancelRequest{SessionId: id}) if err != nil { - return gateway.ChatCancellation{}, err + return messaging.ChatCancellation{}, err } - return gateway.ChatCancellation{Cancelled: v.Cancelled, Dropped: int(v.Dropped)}, nil + return messaging.ChatCancellation{Cancelled: v.Cancelled, Dropped: int(v.Dropped)}, nil } func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error) { @@ -82,28 +81,28 @@ func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error) return v.Found, nil } -func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) { +func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) { v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{Identity: identity, TaskId: taskID, Action: string(action)}) if err != nil { - return gateway.TaskActionResult{}, taskActionError(err) + return messaging.TaskActionResult{}, taskActionError(err) } - return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil + return messaging.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil } -func (c *Client) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) { +func (c *Client) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) { v, err := c.client.ApplyOperatorTaskAction(ctx, &pb.ApplyOperatorTaskActionRequest{TaskId: taskID, Action: string(action)}) if err != nil { - return gateway.TaskActionResult{}, taskActionError(err) + return messaging.TaskActionResult{}, taskActionError(err) } - return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil + return messaging.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil } -func (c *Client) Stream(ctx context.Context, in gateway.Inbound) (<-chan gateway.ChatEvent, error) { +func (c *Client) Stream(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) { stream, err := c.client.Stream(ctx, &pb.StreamRequest{Message: inboundProto(in)}) if err != nil { return nil, err } - out := make(chan gateway.ChatEvent) + out := make(chan messaging.ChatEvent) go func() { defer close(out) for { @@ -111,9 +110,9 @@ func (c *Client) Stream(ctx context.Context, in gateway.Inbound) (<-chan gateway if errors.Is(err, io.EOF) { return } - var event gateway.ChatEvent + var event messaging.ChatEvent if err != nil { - event = gateway.ChatEvent{Kind: "error", Text: err.Error()} + event = messaging.ChatEvent{Kind: "error", Text: err.Error()} } else { event = eventValue(v) } diff --git a/internal/infrastructure/gatewayrpc/server.go b/internal/infrastructure/gatewayrpc/server.go index f548c1630..e57fc6511 100644 --- a/internal/infrastructure/gatewayrpc/server.go +++ b/internal/infrastructure/gatewayrpc/server.go @@ -9,25 +9,24 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/taskstate" ) type server struct { pb.UnimplementedChatServiceServer - chat gateway.ChatContract - sessions gateway.SessionStore + chat messaging.ChatContract + sessions messaging.SessionStore } -func RegisterServer(registrar grpc.ServiceRegistrar, chat gateway.ChatContract, sessions ...gateway.SessionStore) { - var ss gateway.SessionStore +func RegisterServer(registrar grpc.ServiceRegistrar, chat messaging.ChatContract, sessions ...messaging.SessionStore) { + var ss messaging.SessionStore if len(sessions) > 0 { ss = sessions[0] } pb.RegisterChatServiceServer(registrar, &server{chat: chat, sessions: ss}) } -func (s *server) sessionStore() (gateway.SessionStore, error) { +func (s *server) sessionStore() (messaging.SessionStore, error) { if s.sessions == nil { return nil, status.Error(codes.Unavailable, "session store unavailable") } @@ -150,9 +149,9 @@ func (s *server) ListSessions(ctx context.Context, _ *pb.ListSessionsRequest) (* // storedMessages converts wire messages to canonical records, deriving // roles from the owning session's bot identity (see -// gateway.RoleForSender). The wire carries no role; both sides derive from +// messaging.RoleForSender). The wire carries no role; both sides derive from // the same session, so they agree. -func (s *server) storedMessages(ctx context.Context, ss gateway.SessionStore, sessionID string, msgs []*pb.Message) ([]messaging.Message, error) { +func (s *server) storedMessages(ctx context.Context, ss messaging.SessionStore, sessionID string, msgs []*pb.Message) ([]messaging.Message, error) { var botUser string if sc, err := ss.Get(ctx, sessionID); err != nil { return nil, err @@ -162,7 +161,7 @@ func (s *server) storedMessages(ctx context.Context, ss gateway.SessionStore, se out := make([]messaging.Message, 0, len(msgs)) for _, m := range msgs { stored := storedValue(m) - stored.Role = gateway.RoleForSender(stored.Sender, botUser) + stored.Role = messaging.RoleForSender(stored.Sender, botUser) out = append(out, stored) } return out, nil @@ -227,7 +226,7 @@ func (s *server) SearchMessages(ctx context.Context, r *pb.SearchMessagesRequest if e != nil { return nil, e } - v, e := ss.SearchMessages(ctx, r.SessionId, gateway.MessageQuery{Query: r.Query, Limit: int(r.Limit), Offset: int(r.Offset)}) + v, e := ss.SearchMessages(ctx, r.SessionId, messaging.MessageQuery{Query: r.Query, Limit: int(r.Limit), Offset: int(r.Offset)}) return &pb.SearchMessagesResponse{Messages: mapValues(v.Messages, storedProto), NextOffset: int64(v.NextOffset), HasMore: v.HasMore, Truncated: v.Truncated}, e } diff --git a/internal/infrastructure/gatewayrpc/store_client.go b/internal/infrastructure/gatewayrpc/store_client.go index 57aef28bc..f58279bc6 100644 --- a/internal/infrastructure/gatewayrpc/store_client.go +++ b/internal/infrastructure/gatewayrpc/store_client.go @@ -7,12 +7,11 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/gateway" ) -var _ gateway.SessionStore = (*StoreClient)(nil) +var _ messaging.SessionStore = (*StoreClient)(nil) -// StoreClient implements gateway.SessionStore over the chat service's +// 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. // @@ -26,7 +25,7 @@ func NewStoreClient(conn grpc.ClientConnInterface) *StoreClient { return &StoreClient{client: pb.NewChatServiceClient(conn)} } -func (c *StoreClient) Get(ctx context.Context, id string) (*gateway.SessionContext, error) { +func (c *StoreClient) Get(ctx context.Context, id string) (*messaging.SessionContext, error) { v, err := c.client.GetSession(ctx, &pb.GetSessionRequest{SessionId: id}) if err != nil { return nil, err @@ -38,12 +37,12 @@ func (c *StoreClient) Get(ctx context.Context, id string) (*gateway.SessionConte return &s, nil } -func (c *StoreClient) Save(ctx context.Context, s gateway.SessionContext) error { +func (c *StoreClient) Save(ctx context.Context, s messaging.SessionContext) error { _, e := c.client.SaveSession(ctx, &pb.SaveSessionRequest{Session: sessionProto(s)}) return e } -func (c *StoreClient) GetByChannel(ctx context.Context, p, ch string) ([]gateway.SessionContext, error) { +func (c *StoreClient) GetByChannel(ctx context.Context, p, ch string) ([]messaging.SessionContext, error) { v, e := c.client.GetSessionsByChannel(ctx, &pb.GetSessionsByChannelRequest{Platform: p, ChannelId: ch}) if e != nil { return nil, e @@ -61,7 +60,7 @@ func (c *StoreClient) Touch(ctx context.Context, id string) error { return e } -func (c *StoreClient) List(ctx context.Context) ([]gateway.SessionContext, error) { +func (c *StoreClient) List(ctx context.Context) ([]messaging.SessionContext, error) { v, e := c.client.ListSessions(ctx, &pb.ListSessionsRequest{}) if e != nil { return nil, e @@ -105,16 +104,16 @@ func (c *StoreClient) RecentMessages(ctx context.Context, id string, n int) ([]m return addressRecords(ctx, c.client, id, v.Messages) } -func (c *StoreClient) SearchMessages(ctx context.Context, id string, q gateway.MessageQuery) (gateway.MessagePage, error) { +func (c *StoreClient) SearchMessages(ctx context.Context, id string, q messaging.MessageQuery) (messaging.MessagePage, error) { v, e := c.client.SearchMessages(ctx, &pb.SearchMessagesRequest{SessionId: id, Query: q.Query, Limit: int64(q.Limit), Offset: int64(q.Offset)}) if e != nil { - return gateway.MessagePage{}, e + return messaging.MessagePage{}, e } msgs, err := addressRecords(ctx, c.client, id, v.Messages) if err != nil { - return gateway.MessagePage{}, err + return messaging.MessagePage{}, err } - return gateway.MessagePage{Messages: msgs, NextOffset: int(v.NextOffset), HasMore: v.HasMore, Truncated: v.Truncated}, nil + return messaging.MessagePage{Messages: msgs, NextOffset: int(v.NextOffset), HasMore: v.HasMore, Truncated: v.Truncated}, nil } func (c *StoreClient) Close() error { return nil } @@ -139,7 +138,7 @@ func addressRecords(ctx context.Context, client pb.ChatServiceClient, id string, for _, m := range msgs { stored := storedValue(m) stored.ConversationID = conv - stored.Role = gateway.RoleForSender(stored.Sender, botUser) + stored.Role = messaging.RoleForSender(stored.Sender, botUser) out = append(out, stored) } return out, nil diff --git a/internal/infrastructure/gatewayrpc/task_action_errors.go b/internal/infrastructure/gatewayrpc/task_action_errors.go index 07b4d658e..3678ba1e1 100644 --- a/internal/infrastructure/gatewayrpc/task_action_errors.go +++ b/internal/infrastructure/gatewayrpc/task_action_errors.go @@ -6,7 +6,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/taskactions" ) @@ -22,7 +22,7 @@ var taskActionCodes = []struct { }{ {code: codes.NotFound, err: taskactions.ErrNotFound}, {code: codes.FailedPrecondition, err: taskactions.ErrConflict}, - {code: codes.Aborted, err: storev1.ErrStaleTransition}, + {code: codes.Aborted, err: storecontract.ErrStaleTransition}, {code: codes.Unavailable, err: taskactions.ErrUnavailable}, } diff --git a/internal/infrastructure/gatewayrpc/values.go b/internal/infrastructure/gatewayrpc/values.go index a5a34ce2f..a86a42a6b 100644 --- a/internal/infrastructure/gatewayrpc/values.go +++ b/internal/infrastructure/gatewayrpc/values.go @@ -7,7 +7,6 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/gateway" ) func timestamp(t time.Time) *timestamppb.Timestamp { @@ -26,7 +25,7 @@ func timeValue(t *timestamppb.Timestamp) time.Time { // storedProto renders a canonical record in its wire shape. The role stays // off the wire: each side derives it from the owning session's bot identity -// (see gateway.RoleForSender), so pb.Message needs no role field. +// (see messaging.RoleForSender), so pb.Message needs no role field. func storedProto(m messaging.Message) *pb.Message { return &pb.Message{ MessageId: string(m.ID), @@ -58,7 +57,7 @@ func storedValue(v *pb.Message) messaging.Message { // inboundProto renders a channel message and its transport context in wire // shape. Page rides along; the record's role does not, for the reason // storedProto gives. -func inboundProto(v gateway.Inbound) *pb.Message { +func inboundProto(v messaging.Inbound) *pb.Message { m := storedProto(v.Message) m.Page = v.Page return m @@ -68,16 +67,16 @@ func inboundProto(v gateway.Inbound) *pb.Message { // RoleUser without consulting the session: this is a message a channel // frontend is delivering on a person's behalf, which is the only kind of // message Route and Stream accept. -func inboundValue(v *pb.Message) gateway.Inbound { +func inboundValue(v *pb.Message) messaging.Inbound { if v == nil { - return gateway.Inbound{} + return messaging.Inbound{} } msg := storedValue(v) msg.Role = messaging.RoleUser - return gateway.Inbound{Message: msg, Page: v.Page} + return messaging.Inbound{Message: msg, Page: v.Page} } -func toolProto(v gateway.ToolCallEvent) *pb.ToolCall { +func toolProto(v messaging.ToolCallEvent) *pb.ToolCall { return &pb.ToolCall{ Id: v.ID, Name: v.Name, @@ -87,11 +86,11 @@ func toolProto(v gateway.ToolCallEvent) *pb.ToolCall { } } -func toolValue(v *pb.ToolCall) gateway.ToolCallEvent { +func toolValue(v *pb.ToolCall) messaging.ToolCallEvent { if v == nil { - return gateway.ToolCallEvent{} + return messaging.ToolCallEvent{} } - return gateway.ToolCallEvent{ + return messaging.ToolCallEvent{ ID: v.Id, Name: v.Name, Parameters: v.Parameters, @@ -100,7 +99,7 @@ func toolValue(v *pb.ToolCall) gateway.ToolCallEvent { } } -func turnProto(v gateway.TurnRecord) *pb.Turn { +func turnProto(v messaging.TurnRecord) *pb.Turn { return &pb.Turn{ TurnId: v.TurnID, SessionId: v.SessionID, @@ -115,11 +114,11 @@ func turnProto(v gateway.TurnRecord) *pb.Turn { } } -func turnValue(v *pb.Turn) gateway.TurnRecord { +func turnValue(v *pb.Turn) messaging.TurnRecord { if v == nil { - return gateway.TurnRecord{} + return messaging.TurnRecord{} } - return gateway.TurnRecord{ + return messaging.TurnRecord{ TurnID: v.TurnId, SessionID: v.SessionId, SourceID: v.SourceId, @@ -129,7 +128,7 @@ func turnValue(v *pb.Turn) gateway.TurnRecord { PartialText: v.PartialText, ResponseText: v.ResponseText, Error: v.Error, CreatedAt: timeValue(v.CreatedAt), - UpdatedAt: timeValue(v.UpdatedAt), Status: gateway.TurnStatus(v.Status), Attempt: int(v.Attempt), ToolCalls: mapValues(v.ToolCalls, toolValue), + UpdatedAt: timeValue(v.UpdatedAt), Status: messaging.TurnStatus(v.Status), Attempt: int(v.Attempt), ToolCalls: mapValues(v.ToolCalls, toolValue), } } @@ -144,15 +143,15 @@ func mapValues[A, B any](in []A, f func(A) B) []B { return out } -func sessionProto(v gateway.SessionContext) *pb.Session { +func sessionProto(v messaging.SessionContext) *pb.Session { return &pb.Session{SessionId: v.SessionID, Platform: v.Source.Platform, BotUser: v.Source.BotUser, ChannelId: v.Source.ChannelID, ThreadId: v.Source.ThreadID, Title: v.Title, ParentSessionId: v.ParentSessionID, BranchName: v.BranchName, CreatedAt: timestamp(v.CreatedAt), LastActiveAt: timestamp(v.LastActiveAt)} } -func sessionValue(v *pb.Session) gateway.SessionContext { +func sessionValue(v *pb.Session) messaging.SessionContext { if v == nil { - return gateway.SessionContext{} + return messaging.SessionContext{} } - return gateway.SessionContext{SessionID: v.SessionId, Source: gateway.SessionSource{Platform: v.Platform, BotUser: v.BotUser, ChannelID: v.ChannelId, ThreadID: v.ThreadId}, Title: v.Title, ParentSessionID: v.ParentSessionId, BranchName: v.BranchName, CreatedAt: timeValue(v.CreatedAt), LastActiveAt: timeValue(v.LastActiveAt)} + return messaging.SessionContext{SessionID: v.SessionId, Source: messaging.SessionSource{Platform: v.Platform, BotUser: v.BotUser, ChannelID: v.ChannelId, ThreadID: v.ThreadId}, Title: v.Title, ParentSessionID: v.ParentSessionId, BranchName: v.BranchName, CreatedAt: timeValue(v.CreatedAt), LastActiveAt: timeValue(v.LastActiveAt)} } func int64Pointer(v *int) *int64 { @@ -171,27 +170,27 @@ func intPointer(v *int64) *int { return &n } -func mediaProto(v gateway.MediaEvent) *pb.Media { +func mediaProto(v messaging.MediaEvent) *pb.Media { a := v.Attachment return &pb.Media{ToolName: v.ToolName, Type: a.Type, FileId: a.FileID, Url: a.URL, Path: a.Path, MimeType: a.MIMEType, FileName: a.FileName, FileSize: a.FileSize, Width: int64Pointer(a.Width), Height: int64Pointer(a.Height), Duration: int64Pointer(a.Duration)} } -func mediaValue(v *pb.Media) gateway.MediaEvent { +func mediaValue(v *pb.Media) messaging.MediaEvent { if v == nil { - return gateway.MediaEvent{} + return messaging.MediaEvent{} } - return gateway.MediaEvent{ToolName: v.ToolName, Attachment: gateway.MediaAttachment{Type: v.Type, FileID: v.FileId, URL: v.Url, Path: v.Path, MIMEType: v.MimeType, FileName: v.FileName, FileSize: v.FileSize, Width: intPointer(v.Width), Height: intPointer(v.Height), Duration: intPointer(v.Duration)}} + return messaging.MediaEvent{ToolName: v.ToolName, Attachment: messaging.MediaAttachment{Type: v.Type, FileID: v.FileId, URL: v.Url, Path: v.Path, MIMEType: v.MimeType, FileName: v.FileName, FileSize: v.FileSize, Width: intPointer(v.Width), Height: intPointer(v.Height), Duration: intPointer(v.Duration)}} } -func eventProto(v gateway.ChatEvent) *pb.StreamResponse { +func eventProto(v messaging.ChatEvent) *pb.StreamResponse { return &pb.StreamResponse{Kind: v.Kind, Text: v.Text, SessionId: v.SessionID, Tool: toolProto(v.Tool), Media: mediaProto(v.Media)} } -func eventValue(v *pb.StreamResponse) gateway.ChatEvent { - return gateway.ChatEvent{Kind: v.Kind, Text: v.Text, SessionID: v.SessionId, Tool: toolValue(v.Tool), Media: mediaValue(v.Media)} +func eventValue(v *pb.StreamResponse) messaging.ChatEvent { + return messaging.ChatEvent{Kind: v.Kind, Text: v.Text, SessionID: v.SessionId, Tool: toolValue(v.Tool), Media: mediaValue(v.Media)} } -func snapshotProto(v gateway.ChatSnapshot) *pb.SnapshotResponse { +func snapshotProto(v messaging.ChatSnapshot) *pb.SnapshotResponse { groups := make(map[string]*pb.StringList, len(v.ModelsByProvider)) for k, list := range v.ModelsByProvider { groups[k] = &pb.StringList{Values: list} @@ -199,10 +198,10 @@ func snapshotProto(v gateway.ChatSnapshot) *pb.SnapshotResponse { return &pb.SnapshotResponse{Sessions: mapValues(v.Sessions, sessionProto), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable} } -func snapshotValue(v *pb.SnapshotResponse) gateway.ChatSnapshot { +func snapshotValue(v *pb.SnapshotResponse) messaging.ChatSnapshot { groups := make(map[string][]string, len(v.ModelsByProvider)) for k, list := range v.ModelsByProvider { groups[k] = list.GetValues() } - return gateway.ChatSnapshot{Sessions: mapValues(v.Sessions, sessionValue), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable} + return messaging.ChatSnapshot{Sessions: mapValues(v.Sessions, sessionValue), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable} } diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 00a3a5cfd..a61d33c88 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -9,17 +9,17 @@ import ( "google.golang.org/grpc" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" - "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" ) // Client is the single remote adapter wrapping one StateStoreServiceClient, // asserted against whichever narrow Go interfaces its caller needs -- exactly -// as gatewayrpc.Client asserts both gateway.ChatContract and -// gateway.SessionStore. See docs/prds/state-store-contract.md §2. +// as gatewayrpc.Client asserts both messaging.ChatContract and +// messaging.SessionStore. See docs/prds/state-store-contract.md §2. type Client struct { client pb.StateStoreServiceClient } @@ -34,14 +34,14 @@ func NewClient(conn grpc.ClientConnInterface) *Client { func (c *Client) Close() error { return nil } var ( - _ workflow.Store = (*Client)(nil) - _ storev1.TaskStore = (*Client)(nil) - _ storev1.CaptureStore = (*Client)(nil) - _ storev1.MappingStore = (*Client)(nil) - _ storev1.BindingStore = (*Client)(nil) - _ storev1.BindingDispatcher = (*Client)(nil) - _ storev1.BindingTaskCreator = (*Client)(nil) - _ storev1.ConfigSnapshotStore = (*Client)(nil) + _ task.Store = (*Client)(nil) + _ storecontract.TaskStore = (*Client)(nil) + _ storecontract.CaptureStore = (*Client)(nil) + _ storecontract.MappingStore = (*Client)(nil) + _ storecontract.BindingStore = (*Client)(nil) + _ storecontract.BindingDispatcher = (*Client)(nil) + _ storecontract.BindingTaskCreator = (*Client)(nil) + _ storecontract.ConfigSnapshotStore = (*Client)(nil) ) // Lifecycle @@ -54,7 +54,7 @@ func (c *Client) EnqueueIssue(ctx context.Context, owner, repo string, number in return r.Inserted, nil } -func (c *Client) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string) (*workflow.Task, error) { +func (c *Client) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string) (*task.Task, error) { r, err := c.client.EnqueueChatTask(ctx, &pb.EnqueueChatTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity}) if err != nil { return nil, unmapError(err) @@ -62,7 +62,7 @@ func (c *Client) EnqueueChatTask(ctx context.Context, owner, repo, title, body, return taskValue(r.Task), nil } -func (c *Client) ClaimNext(ctx context.Context) (*workflow.Task, error) { +func (c *Client) ClaimNext(ctx context.Context) (*task.Task, error) { r, err := c.client.ClaimNext(ctx, &pb.ClaimNextRequest{}) if err != nil { return nil, unmapError(err) @@ -73,7 +73,7 @@ func (c *Client) ClaimNext(ctx context.Context) (*workflow.Task, error) { return taskValue(r.Task), nil } -func (c *Client) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) { +func (c *Client) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) { r, err := c.client.ClaimByIssue(ctx, &pb.ClaimByIssueRequest{Owner: owner, Repo: repo, Number: int64(number)}) if err != nil { return nil, unmapError(err) @@ -89,7 +89,7 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail return unmapError(err) } -func (c *Client) Update(ctx context.Context, t *workflow.Task) error { +func (c *Client) Update(ctx context.Context, t *task.Task) error { _, err := c.client.Update(ctx, &pb.UpdateRequest{Task: taskProto(t)}) return unmapError(err) } @@ -124,7 +124,7 @@ func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf str // Queries -func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) { +func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) { r, err := c.client.TaskByIssue(ctx, &pb.TaskByIssueRequest{Owner: owner, Repo: repo, Number: int64(number)}) if err != nil { return nil, unmapError(err) @@ -135,7 +135,7 @@ func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int return taskValue(r.Task), nil } -func (c *Client) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, error) { +func (c *Client) TaskByID(ctx context.Context, taskID int64) (*task.Task, error) { r, err := c.client.TaskByID(ctx, &pb.TaskByIDRequest{TaskId: taskID}) if err != nil { return nil, unmapError(err) @@ -146,7 +146,7 @@ func (c *Client) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, er return taskValue(r.Task), nil } -func (c *Client) OpenPRs(ctx context.Context) ([]workflow.Task, error) { +func (c *Client) OpenPRs(ctx context.Context) ([]task.Task, error) { r, err := c.client.OpenPRs(ctx, &pb.OpenPRsRequest{}) if err != nil { return nil, unmapError(err) @@ -162,7 +162,7 @@ func (c *Client) ClearTerminalTasks(ctx context.Context) (int64, error) { return r.Count, nil } -func (c *Client) Tasks(ctx context.Context, limit int) ([]workflow.Task, error) { +func (c *Client) Tasks(ctx context.Context, limit int) ([]task.Task, error) { r, err := c.client.Tasks(ctx, &pb.TasksRequest{Limit: int64(limit)}) if err != nil { return nil, unmapError(err) @@ -213,7 +213,7 @@ func (c *Client) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, return mapValues(r.Events, eventValue), nil } -func (c *Client) WorkflowStats(ctx context.Context) ([]storev1.WorkflowStat, error) { +func (c *Client) WorkflowStats(ctx context.Context) ([]storecontract.WorkflowStat, error) { r, err := c.client.WorkflowStats(ctx, &pb.WorkflowStatsRequest{}) if err != nil { return nil, unmapError(err) @@ -221,7 +221,7 @@ func (c *Client) WorkflowStats(ctx context.Context) ([]storev1.WorkflowStat, err return mapValues(r.Stats, workflowStatValue), nil } -func (c *Client) StageStats(ctx context.Context) ([]storev1.StageStat, error) { +func (c *Client) StageStats(ctx context.Context) ([]storecontract.StageStat, error) { r, err := c.client.StageStats(ctx, &pb.StageStatsRequest{}) if err != nil { return nil, unmapError(err) @@ -229,7 +229,7 @@ func (c *Client) StageStats(ctx context.Context) ([]storev1.StageStat, error) { return mapValues(r.Stats, stageStatValue), nil } -func (c *Client) TokensByDay(ctx context.Context, days int) ([]storev1.DayTokens, error) { +func (c *Client) TokensByDay(ctx context.Context, days int) ([]storecontract.DayTokens, error) { r, err := c.client.TokensByDay(ctx, &pb.TokensByDayRequest{Days: int64(days)}) if err != nil { return nil, unmapError(err) @@ -239,7 +239,7 @@ func (c *Client) TokensByDay(ctx context.Context, days int) ([]storev1.DayTokens // Capture -func (c *Client) InsertCapture(ctx context.Context, ce storev1.CapturedEvent, retention time.Duration, maxEvents int) (int64, error) { +func (c *Client) InsertCapture(ctx context.Context, ce storecontract.CapturedEvent, retention time.Duration, maxEvents int) (int64, error) { r, err := c.client.InsertCapture(ctx, &pb.InsertCaptureRequest{Capture: capturedEventProto(ce), RetentionSeconds: int64(retention.Seconds()), MaxEvents: int64(maxEvents)}) if err != nil { return 0, unmapError(err) @@ -253,7 +253,7 @@ func (c *Client) InsertCapture(ctx context.Context, ce storev1.CapturedEvent, re // PutConfigSnapshot publishes the dashboard's configuration projection. The // server admits it on the administrative token only; a task-scoped grant // cannot reach it (see TaskGrants). -func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot storev1.ConfigSnapshot) error { +func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot storecontract.ConfigSnapshot) error { _, err := c.client.PutConfigSnapshot(ctx, &pb.PutConfigSnapshotRequest{Snapshot: configSnapshotProto(snapshot)}) if err != nil { return unmapError(err) @@ -263,23 +263,23 @@ func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot storev1.ConfigS // ConfigSnapshot reads the published projection. found is false, with a nil // error, before a daemon has published one. -func (c *Client) ConfigSnapshot(ctx context.Context) (storev1.ConfigSnapshot, bool, error) { +func (c *Client) ConfigSnapshot(ctx context.Context) (storecontract.ConfigSnapshot, bool, error) { reply, err := c.client.GetConfigSnapshot(ctx, &pb.GetConfigSnapshotRequest{}) if err != nil { - return storev1.ConfigSnapshot{}, false, unmapError(err) + return storecontract.ConfigSnapshot{}, false, unmapError(err) } if !reply.Found { - return storev1.ConfigSnapshot{}, false, nil + return storecontract.ConfigSnapshot{}, false, nil } return configSnapshotValue(reply.Snapshot), true, nil } -func (c *Client) ListCaptures(ctx context.Context, limit int) ([]storev1.CapturedEvent, error) { +func (c *Client) ListCaptures(ctx context.Context, limit int) ([]storecontract.CapturedEvent, error) { stream, err := c.client.StreamCaptures(ctx, &pb.StreamCapturesRequest{Limit: int64(limit)}) if err != nil { return nil, unmapError(err) } - var captures []storev1.CapturedEvent + var captures []storecontract.CapturedEvent for { r, err := stream.Recv() if errors.Is(err, io.EOF) { @@ -394,12 +394,12 @@ func (c *Client) RecordDispatch(ctx context.Context, bindingID, bindingVersion, // ListUndispatchedCaptures calls StreamUndispatchedCaptures; see ListCaptures // above. -func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storev1.CapturedEvent, error) { +func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) { stream, err := c.client.StreamUndispatchedCaptures(ctx, &pb.StreamUndispatchedCapturesRequest{Sources: sources, Limit: int64(limit)}) if err != nil { return nil, unmapError(err) } - var captures []storev1.CapturedEvent + var captures []storecontract.CapturedEvent for { r, err := stream.Recv() if errors.Is(err, io.EOF) { @@ -414,7 +414,7 @@ func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, // BindingTaskCreator -func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*workflow.Task, error) { +func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*task.Task, error) { r, err := c.client.EnqueueBindingTask(ctx, &pb.EnqueueBindingTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, BindingId: bindingID, BindingVersion: int64(bindingVersion)}) if err != nil { return nil, unmapError(err) @@ -422,11 +422,11 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod return taskValue(r.Task), nil } -func derefTasks(in []*pb.Task) []workflow.Task { +func derefTasks(in []*pb.Task) []task.Task { if in == nil { return nil } - out := make([]workflow.Task, len(in)) + out := make([]task.Task, len(in)) for i, t := range in { out[i] = *taskValue(t) } diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index f4834d54f..6fda9cff4 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -14,9 +14,9 @@ import ( "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" + "github.com/samcharles93/archie-core/internal/domain/storecontract" ) // Unavailable-capability errors, mirroring gatewayrpc's missing-session-store @@ -40,13 +40,13 @@ func timeSeconds(s int64) time.Duration { return time.Duration(s) * time.Second // nil Mappings/Bindings/BindingDispatcher/BindingTaskCreator as "disabled". type Deps struct { Grants *TaskGrants - Tasks storev1.TaskStore - Captures storev1.CaptureStore - ConfigSnapshots storev1.ConfigSnapshotStore - Mappings storev1.MappingStore - Bindings storev1.BindingStore - BindingDispatcher storev1.BindingDispatcher - BindingTaskCreator storev1.BindingTaskCreator + Tasks storecontract.TaskStore + Captures storecontract.CaptureStore + ConfigSnapshots storecontract.ConfigSnapshotStore + Mappings storecontract.MappingStore + Bindings storecontract.BindingStore + BindingDispatcher storecontract.BindingDispatcher + BindingTaskCreator storecontract.BindingTaskCreator Log *slog.Logger } @@ -277,14 +277,14 @@ func (s *server) TokensByDay(ctx context.Context, r *pb.TokensByDayRequest) (*pb // Capture -func (s *server) capture() (storev1.CaptureStore, error) { +func (s *server) capture() (storecontract.CaptureStore, error) { if s.deps.Captures == nil { return nil, errCaptureUnavailable } return s.deps.Captures, nil } -func (s *server) configSnapshots() (storev1.ConfigSnapshotStore, error) { +func (s *server) configSnapshots() (storecontract.ConfigSnapshotStore, error) { if s.deps.ConfigSnapshots == nil { return nil, errConfigSnapshotsUnavailable } @@ -364,7 +364,7 @@ func (s *server) StreamCaptures(r *pb.StreamCapturesRequest, stream pb.StateStor // Mapping -func (s *server) mapping() (storev1.MappingStore, error) { +func (s *server) mapping() (storecontract.MappingStore, error) { if s.deps.Mappings == nil { return nil, errMappingUnavailable } @@ -431,7 +431,7 @@ func (s *server) DeleteMapping(ctx context.Context, r *pb.DeleteMappingRequest) // Binding -func (s *server) binding() (storev1.BindingStore, error) { +func (s *server) binding() (storecontract.BindingStore, error) { if s.deps.Bindings == nil { return nil, errBindingUnavailable } diff --git a/internal/infrastructure/staterpc/task_grants.go b/internal/infrastructure/staterpc/task_grants.go index fa806def1..4e7147165 100644 --- a/internal/infrastructure/staterpc/task_grants.go +++ b/internal/infrastructure/staterpc/task_grants.go @@ -15,7 +15,7 @@ import ( "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" - "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) // TaskGrants lives in the State Store process. Restart invalidates all worker @@ -91,7 +91,7 @@ func (g *TaskGrants) taskFor(token string) int64 { } // authorizesTaskScopedCall reports whether req -- a call to one of the three -// workflow.Store RPCs a task grant may ever authorize -- targets taskID. +// task.Store RPCs a task grant may ever authorize -- targets taskID. // Every other RPC (including RegisterTaskGrant/RevokeTaskGrant themselves) // falls through to false: a task grant can only ever narrow, never expand. func authorizesTaskScopedCall(fullMethod string, req any, taskID int64) bool { @@ -202,7 +202,7 @@ type GrantIssuer struct { Client *Client } -func (g *GrantIssuer) Issue(task *workflow.Task) (string, func(), error) { +func (g *GrantIssuer) Issue(task *task.Task) (string, func(), error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() token, err := g.Client.RegisterTaskGrant(ctx, task.ID, defaultGrantLifetime) diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index bb32a8522..6c3fa3332 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -12,10 +12,10 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" - "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" ) @@ -44,7 +44,7 @@ func mapValues[A, B any](in []A, f func(A) B) []B { return out } -func taskProto(t *workflow.Task) *pb.Task { //nolint:dupl // mirror-image field-by-field proto<->domain mapping; taskValue below reverses every assignment, so line-level duplication is unavoidable without reflection +func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-field proto<->domain mapping; taskValue below reverses every assignment, so line-level duplication is unavoidable without reflection if t == nil { return nil } @@ -60,11 +60,11 @@ func taskProto(t *workflow.Task) *pb.Task { //nolint:dupl // mirror-image field- } } -func taskValue(t *pb.Task) *workflow.Task { //nolint:dupl // see taskProto above +func taskValue(t *pb.Task) *task.Task { //nolint:dupl // see taskProto above if t == nil { return nil } - return &workflow.Task{ + return &task.Task{ ID: t.Id, Owner: t.Owner, Repo: t.Repo, IssueNumber: int(t.IssueNumber), Title: t.Title, Body: t.Body, Labels: t.Labels, Status: t.Status, Workflow: t.Workflow, Stage: t.Stage, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes, @@ -119,7 +119,7 @@ func eventValue(e *pb.Event) events.Event { } } -func capturedEventProto(c storev1.CapturedEvent) *pb.CapturedEvent { +func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent { return &pb.CapturedEvent{ Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source, RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers, @@ -127,11 +127,11 @@ func capturedEventProto(c storev1.CapturedEvent) *pb.CapturedEvent { } } -func capturedEventValue(c *pb.CapturedEvent) storev1.CapturedEvent { +func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent { if c == nil { - return storev1.CapturedEvent{} + return storecontract.CapturedEvent{} } - return storev1.CapturedEvent{ + return storecontract.CapturedEvent{ ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source, RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers, Body: c.Body, Authenticated: c.Authenticated, @@ -193,7 +193,7 @@ func bindingValue(b *pb.Binding) binding.Binding { } } -func workflowStatProto(w storev1.WorkflowStat) *pb.WorkflowStat { +func workflowStatProto(w storecontract.WorkflowStat) *pb.WorkflowStat { return &pb.WorkflowStat{ Workflow: w.Workflow, Runs: int64(w.Runs), Merged: int64(w.Merged), PrOpen: int64(w.PROpen), Parked: int64(w.Parked), AvgTokens: int64(w.AvgTokens), @@ -201,37 +201,37 @@ func workflowStatProto(w storev1.WorkflowStat) *pb.WorkflowStat { } } -func workflowStatValue(w *pb.WorkflowStat) storev1.WorkflowStat { +func workflowStatValue(w *pb.WorkflowStat) storecontract.WorkflowStat { if w == nil { - return storev1.WorkflowStat{} + return storecontract.WorkflowStat{} } - return storev1.WorkflowStat{ + return storecontract.WorkflowStat{ Workflow: w.Workflow, Runs: int(w.Runs), Merged: int(w.Merged), PROpen: int(w.PrOpen), Parked: int(w.Parked), AvgTokens: int(w.AvgTokens), AvgSteps: w.AvgSteps, TotalToken: int(w.TotalTokens), } } -func stageStatProto(s storev1.StageStat) *pb.StageStat { +func stageStatProto(s storecontract.StageStat) *pb.StageStat { return &pb.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int64(s.Runs), AvgMs: int64(s.AvgMs), Errors: int64(s.Errors)} } -func stageStatValue(s *pb.StageStat) storev1.StageStat { +func stageStatValue(s *pb.StageStat) storecontract.StageStat { if s == nil { - return storev1.StageStat{} + return storecontract.StageStat{} } - return storev1.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int(s.Runs), AvgMs: int(s.AvgMs), Errors: int(s.Errors)} + return storecontract.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int(s.Runs), AvgMs: int(s.AvgMs), Errors: int(s.Errors)} } -func dayTokensProto(d storev1.DayTokens) *pb.DayTokens { +func dayTokensProto(d storecontract.DayTokens) *pb.DayTokens { return &pb.DayTokens{Day: d.Day, Tokens: int64(d.Tokens)} } -func dayTokensValue(d *pb.DayTokens) storev1.DayTokens { +func dayTokensValue(d *pb.DayTokens) storecontract.DayTokens { if d == nil { - return storev1.DayTokens{} + return storecontract.DayTokens{} } - return storev1.DayTokens{Day: d.Day, Tokens: int(d.Tokens)} + return storecontract.DayTokens{Day: d.Day, Tokens: int(d.Tokens)} } // Canonical public phrases for sentinel errors (rev. 2c §7). These strings @@ -271,17 +271,17 @@ func mapError(err error) error { return status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error()) } switch { - case errors.Is(err, storev1.ErrStaleTransition): + case errors.Is(err, storecontract.ErrStaleTransition): return status.Error(codes.FailedPrecondition, msgStaleTransition) - case errors.Is(err, storev1.ErrBindingNotFound): + case errors.Is(err, storecontract.ErrBindingNotFound): return status.Error(codes.NotFound, msgBindingNotFound) - case errors.Is(err, storev1.ErrMappingNotFound): + case errors.Is(err, storecontract.ErrMappingNotFound): return status.Error(codes.NotFound, msgMappingNotFound) - case errors.Is(err, storev1.ErrBindingOverlap): + case errors.Is(err, storecontract.ErrBindingOverlap): return status.Error(codes.FailedPrecondition, msgBindingOverlap) - case errors.Is(err, storev1.ErrBindingTransition): + case errors.Is(err, storecontract.ErrBindingTransition): return status.Error(codes.FailedPrecondition, msgBindingTransition) - case errors.Is(err, storev1.ErrAlreadyDispatched): + case errors.Is(err, storecontract.ErrAlreadyDispatched): return status.Error(codes.AlreadyExists, msgAlreadyDispatched) default: return status.Error(codes.Internal, msgInternal) @@ -289,7 +289,7 @@ func mapError(err error) error { } // unmapError rehydrates a gRPC status error back to the store sentinel it -// came from, so a caller's errors.Is(err, storev1.ErrX) keeps working across +// came from, so a caller's errors.Is(err, storecontract.ErrX) keeps working across // the wire. A non-status error (e.g. a transport failure) is returned // unchanged. // @@ -317,22 +317,22 @@ func unmapError(err error) error { case codes.FailedPrecondition: switch st.Message() { case msgStaleTransition: - return storev1.ErrStaleTransition + return storecontract.ErrStaleTransition case msgBindingOverlap: - return storev1.ErrBindingOverlap + return storecontract.ErrBindingOverlap case msgBindingTransition: - return storev1.ErrBindingTransition + return storecontract.ErrBindingTransition } case codes.NotFound: switch st.Message() { case msgBindingNotFound: - return storev1.ErrBindingNotFound + return storecontract.ErrBindingNotFound case msgMappingNotFound: - return storev1.ErrMappingNotFound + return storecontract.ErrMappingNotFound } case codes.AlreadyExists: if st.Message() == msgAlreadyDispatched { - return storev1.ErrAlreadyDispatched + return storecontract.ErrAlreadyDispatched } } return fmt.Errorf("state store: %s: %w", st.Message(), err) @@ -341,7 +341,7 @@ func unmapError(err error) error { // configSnapshotProto and configSnapshotValue carry the dashboard's // configuration projection. document crosses as bytes, unread by either side // of this hop: the store holds it and the page renders it. -func configSnapshotProto(snapshot storev1.ConfigSnapshot) *pb.ConfigSnapshot { +func configSnapshotProto(snapshot storecontract.ConfigSnapshot) *pb.ConfigSnapshot { return &pb.ConfigSnapshot{ Schema: snapshot.Schema, Document: snapshot.Document, @@ -349,11 +349,11 @@ func configSnapshotProto(snapshot storev1.ConfigSnapshot) *pb.ConfigSnapshot { } } -func configSnapshotValue(snapshot *pb.ConfigSnapshot) storev1.ConfigSnapshot { +func configSnapshotValue(snapshot *pb.ConfigSnapshot) storecontract.ConfigSnapshot { if snapshot == nil { - return storev1.ConfigSnapshot{} + return storecontract.ConfigSnapshot{} } - return storev1.ConfigSnapshot{ + return storecontract.ConfigSnapshot{ Schema: snapshot.Schema, Document: snapshot.Document, PublishedAt: timeValue(snapshot.PublishedAt), diff --git a/internal/infrastructure/taskactions/rpc.go b/internal/infrastructure/taskactions/rpc.go index 14d8db540..d5c9602fa 100644 --- a/internal/infrastructure/taskactions/rpc.go +++ b/internal/infrastructure/taskactions/rpc.go @@ -10,7 +10,7 @@ import ( "github.com/nats-io/nats.go" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/natsrpc" @@ -49,7 +49,7 @@ var actionErrorKinds = []struct { }{ {kind: "not_found", err: taskactions.ErrNotFound}, {kind: "conflict", err: taskactions.ErrConflict}, - {kind: "stale_transition", err: storev1.ErrStaleTransition}, + {kind: "stale_transition", err: storecontract.ErrStaleTransition}, {kind: "unavailable", err: taskactions.ErrUnavailable}, } diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go index 334cbb2d1..b144c8a78 100644 --- a/internal/infrastructure/taskactions/store.go +++ b/internal/infrastructure/taskactions/store.go @@ -5,11 +5,11 @@ import ( "context" "github.com/samcharles93/archie-core/internal/config" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/taskactions" ) -type Store struct{ storev1.TaskStore } +type Store struct{ storecontract.TaskStore } func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error) { t, err := s.TaskStore.TaskByID(ctx, id) diff --git a/internal/secret/engine.go b/internal/secret/engine.go index 82dc04d86..8324170ab 100644 --- a/internal/secret/engine.go +++ b/internal/secret/engine.go @@ -100,8 +100,13 @@ func (r *Registry) Getenv(key string) string { return "" } -// Resolve resolves a SecretRef through the registered engine. +// Resolve resolves a SecretRef through the registered engine. The zero +// value (engine and key both empty) resolves to "" with no error -- the +// zero value means "not configured". func (r *Registry) Resolve(ref SecretRef) (string, error) { + if ref.Engine == "" && ref.Key == "" { + return "", nil + } e, ok := r.Get(ref.Engine) if !ok { return "", fmt.Errorf("secret engine %q not registered", ref.Engine) diff --git a/internal/secret/secret.go b/internal/secret/secret.go index abbccd29b..2123c4aba 100644 --- a/internal/secret/secret.go +++ b/internal/secret/secret.go @@ -1,30 +1,8 @@ package secret -// SecretRef references a secret stored in a named engine. Legacy environment -// variable fields remain supported where required for backwards compatibility. -// -// Format in TOML/YAML: -// -// [forge] -// token = {engine = "env", key = "GITEA_TOKEN"} -// -// [providers.deepseek] -// api_key = {engine = "bws", key = "DEEPSEEK_API_KEY"} -// -// The zero value (empty engine, empty key) resolves to "" with no error, -// for config fields where the secret is optional (e.g. an unconfigured -// channel token). -type SecretRef struct { - Engine string `toml:"engine" yaml:"engine" json:"engine"` - Key string `toml:"key" yaml:"key" json:"key"` -} +import "github.com/samcharles93/archie-core/internal/config" -// Resolve resolves this reference through reg. Returns "" with no error -// when the reference is empty (engine and key both empty — the zero -// value means "not configured"). -func (s SecretRef) Resolve(reg *Registry) (string, error) { - if s.Engine == "" && s.Key == "" { - return "", nil - } - return reg.Resolve(s) -} +// SecretRef moved to internal/config (archie-core-8cda.5.6): the type is +// config vocabulary, and config cannot import this package (the UI process +// renders config projections but never resolves a secret). +type SecretRef = config.SecretRef diff --git a/internal/secret/secret_test.go b/internal/secret/secret_test.go index 36311e2fd..43e2398a9 100644 --- a/internal/secret/secret_test.go +++ b/internal/secret/secret_test.go @@ -38,7 +38,7 @@ func TestEnvEngineResolveMissing(t *testing.T) { func TestSecretRefZeroValue(t *testing.T) { r := NewRegistry() var s SecretRef - v, err := s.Resolve(r) + v, err := r.Resolve(s) if err != nil { t.Error(err) } diff --git a/internal/store/interface.go b/internal/store/interface.go index 597b79df9..c4a77a86e 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -11,40 +11,40 @@ package store import ( - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" ) -// Aliases: the daemon/webui/intake store surfaces moved to storev1. The +// Aliases: the daemon/webui/intake store surfaces moved to storecontract. The // message strings of the sentinel errors are the wire contract (see // storev1's var block); the aliases change nothing observable. type ( - TaskStore = storev1.TaskStore - TaskLifecycle = storev1.TaskLifecycle - TaskArchiver = storev1.TaskArchiver - TaskRetryer = storev1.TaskRetryer - TaskQueries = storev1.TaskQueries - TaskEvents = storev1.TaskEvents - CaptureStore = storev1.CaptureStore - ConfigSnapshotStore = storev1.ConfigSnapshotStore - MappingStore = storev1.MappingStore - BindingStore = storev1.BindingStore - BindingDispatcher = storev1.BindingDispatcher - BindingTaskCreator = storev1.BindingTaskCreator - CapturedEvent = storev1.CapturedEvent - ConfigSnapshot = storev1.ConfigSnapshot - WorkflowStat = storev1.WorkflowStat - StageStat = storev1.StageStat - DayTokens = storev1.DayTokens + TaskStore = storecontract.TaskStore + TaskLifecycle = storecontract.TaskLifecycle + TaskArchiver = storecontract.TaskArchiver + TaskRetryer = storecontract.TaskRetryer + TaskQueries = storecontract.TaskQueries + TaskEvents = storecontract.TaskEvents + CaptureStore = storecontract.CaptureStore + ConfigSnapshotStore = storecontract.ConfigSnapshotStore + MappingStore = storecontract.MappingStore + BindingStore = storecontract.BindingStore + BindingDispatcher = storecontract.BindingDispatcher + BindingTaskCreator = storecontract.BindingTaskCreator + CapturedEvent = storecontract.CapturedEvent + ConfigSnapshot = storecontract.ConfigSnapshot + WorkflowStat = storecontract.WorkflowStat + StageStat = storecontract.StageStat + DayTokens = storecontract.DayTokens ) var ( - ErrStaleTransition = storev1.ErrStaleTransition - ErrBindingNotFound = storev1.ErrBindingNotFound - ErrBindingOverlap = storev1.ErrBindingOverlap - ErrBindingTransition = storev1.ErrBindingTransition - ErrAlreadyDispatched = storev1.ErrAlreadyDispatched - ErrMappingNotFound = storev1.ErrMappingNotFound + ErrStaleTransition = storecontract.ErrStaleTransition + ErrBindingNotFound = storecontract.ErrBindingNotFound + ErrBindingOverlap = storecontract.ErrBindingOverlap + ErrBindingTransition = storecontract.ErrBindingTransition + ErrAlreadyDispatched = storecontract.ErrAlreadyDispatched + ErrMappingNotFound = storecontract.ErrMappingNotFound ) // Compile-time check: *Store satisfies TaskStore. diff --git a/internal/webui/api_binding.go b/internal/webui/api_binding.go index dabbb391b..d43cbe8bf 100644 --- a/internal/webui/api_binding.go +++ b/internal/webui/api_binding.go @@ -6,8 +6,8 @@ import ( "net/http" "strconv" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" + "github.com/samcharles93/archie-core/internal/domain/storecontract" ) // bindingRequest is the wire shape POST /api/bindings and @@ -72,7 +72,7 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) { } id, err := s.Bindings.InsertBinding(r.Context(), b) if err != nil { - if errors.Is(err, storev1.ErrBindingOverlap) { + if errors.Is(err, storecontract.ErrBindingOverlap) { http.Error(w, "binding source overlaps an existing binding", http.StatusConflict) return } @@ -150,9 +150,9 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) { } if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil { switch { - case errors.Is(err, storev1.ErrBindingNotFound): + case errors.Is(err, storecontract.ErrBindingNotFound): http.Error(w, "binding not found", http.StatusNotFound) - case errors.Is(err, storev1.ErrBindingOverlap): + case errors.Is(err, storecontract.ErrBindingOverlap): http.Error(w, "binding source overlaps an existing binding", http.StatusConflict) default: s.Log.Error("update binding", "err", err, "id", id) @@ -181,7 +181,7 @@ func (s *Server) handleBindingDelete(w http.ResponseWriter, r *http.Request) { return } if err := s.Bindings.DeleteBinding(r.Context(), id); err != nil { - if errors.Is(err, storev1.ErrBindingNotFound) { + if errors.Is(err, storecontract.ErrBindingNotFound) { http.Error(w, "binding not found", http.StatusNotFound) return } @@ -204,11 +204,11 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) { } if err := s.Bindings.ApproveBinding(r.Context(), id); err != nil { switch { - case errors.Is(err, storev1.ErrBindingNotFound): + case errors.Is(err, storecontract.ErrBindingNotFound): http.Error(w, "binding not found", http.StatusNotFound) - case errors.Is(err, storev1.ErrBindingTransition): + case errors.Is(err, storecontract.ErrBindingTransition): http.Error(w, "binding cannot be approved from its current state", http.StatusConflict) - case errors.Is(err, storev1.ErrBindingOverlap): + case errors.Is(err, storecontract.ErrBindingOverlap): http.Error(w, "binding source overlaps an existing binding", http.StatusConflict) default: s.Log.Error("approve binding", "err", err, "id", id) diff --git a/internal/webui/api_capabilities.go b/internal/webui/api_capabilities.go index 1991d0579..968839d48 100644 --- a/internal/webui/api_capabilities.go +++ b/internal/webui/api_capabilities.go @@ -22,7 +22,7 @@ func (s *Server) handleCapabilities(w http.ResponseWriter, _ *http.Request) { "sections": map[string]bool{ "chat": s.Chat != nil && s.Chat.Contract != nil, "logs": s.LogFeed != nil, - "skills": s.Cfg != nil, + "skills": s.Skills != nil, "memory": s.Memory != nil, "curators": s.Curators != nil, "channels": s.Channels != nil || s.Cfg != nil, diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index 5ebadf110..6f8fb0901 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -13,7 +13,6 @@ import ( "github.com/google/uuid" "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/releaseupdate" ) @@ -21,7 +20,7 @@ import ( // Handlers depend on the Gateway-owned contract and never retain Gateway // implementation objects. type ChatService struct { - Contract gateway.ChatContract + Contract messaging.ChatContract Updates ChatUpdateService Dangerous *DangerousService updateMu sync.Mutex @@ -73,11 +72,11 @@ type chatUpdateRequest struct { } type chatTurnView struct { - TurnID string `json:"turn_id"` - AssistantMessageID string `json:"assistant_message_id,omitempty"` - Status gateway.TurnStatus `json:"status"` - Error string `json:"error,omitempty"` - ToolCalls []chatToolView `json:"tool_calls,omitempty"` + TurnID string `json:"turn_id"` + AssistantMessageID string `json:"assistant_message_id,omitempty"` + Status messaging.TurnStatus `json:"status"` + Error string `json:"error,omitempty"` + ToolCalls []chatToolView `json:"tool_calls,omitempty"` } type chatToolView struct { @@ -127,7 +126,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - out := make([]gateway.SessionContext, 0, len(snapshot.Sessions)) + out := make([]messaging.SessionContext, 0, len(snapshot.Sessions)) active := make(map[string]string) for _, session := range snapshot.Sessions { if session.Source.Platform == "web" { @@ -152,14 +151,14 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) { }) } -func chatCommandSpecs(chat *ChatService) []gateway.CommandSpec { - specs := gateway.LocalCommandSpecs() +func chatCommandSpecs(chat *ChatService) []messaging.CommandSpec { + specs := messaging.LocalCommandSpecs() if chat.Dangerous != nil { specs = append( specs, - gateway.CommandSpec{Command: "/rollback", Description: "Request approval to restore a filesystem checkpoint", Usage: "/rollback [number]"}, - gateway.CommandSpec{Command: "/stop", Description: "Request approval to terminate a background process", Usage: "/stop <process-name>"}, - gateway.CommandSpec{Command: "/deny", Description: "Deny a pending dangerous action", Usage: "/deny <action-id>"}, + messaging.CommandSpec{Command: "/rollback", Description: "Request approval to restore a filesystem checkpoint", Usage: "/rollback [number]"}, + messaging.CommandSpec{Command: "/stop", Description: "Request approval to terminate a background process", Usage: "/stop <process-name>"}, + messaging.CommandSpec{Command: "/deny", Description: "Deny a pending dangerous action", Usage: "/deny <action-id>"}, ) } return specs @@ -233,16 +232,16 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) { writeJSON(w, views) } -func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (gateway.Inbound, bool) { +func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) { var req chatMessageRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid chat message", http.StatusBadRequest) - return gateway.Inbound{}, false + return messaging.Inbound{}, false } req.Text = strings.TrimSpace(req.Text) if req.Text == "" || req.ChannelID == "" { http.Error(w, "text and channel_id are required", http.StatusBadRequest) - return gateway.Inbound{}, false + return messaging.Inbound{}, false } if req.SourceID == "" { req.SourceID = newChatSourceID() @@ -250,7 +249,7 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (gate // The browser has no threading, so the conversation is the channel // alone. Page is the route the operator is looking at, and stays out // of the record. - return gateway.Inbound{ + return messaging.Inbound{ Message: messaging.Message{ SourceID: req.SourceID, ConversationID: messaging.ConversationID{ChannelID: req.ChannelID}, @@ -303,7 +302,7 @@ type chatStreamEvent struct { Label string `json:"label,omitempty"` } -// chatStreamSink adapts the stream writer to gateway.TurnStream so text and +// chatStreamSink adapts the stream writer to messaging.TurnStream so text and // tool activity reach the browser through one ordered path. // // showToolCalls gates ToolCall the same way Telegram's liveReply gates its @@ -322,13 +321,13 @@ func (s chatStreamSink) Delta(text string) { s.write(chatStreamEvent{Type: "delta", Text: text}) } -func (s chatStreamSink) ToolCall(event gateway.ToolCallEvent) { +func (s chatStreamSink) ToolCall(event messaging.ToolCallEvent) { // A dashboard_navigate call is an explicit point-the-operator-there // result, not tool narration, so it renders a clickable chip even when // ShowToolCalls is off. Parse the resolved path/label from the tool's // JSON result and emit a dedicated navigate frame. if event.Name == "dashboard_navigate" && event.Err == "" { - var result gateway.DashboardNavigateResult + var result messaging.DashboardNavigateResult if err := json.Unmarshal([]byte(event.Output), &result); err == nil && result.Path != "" { s.write(chatStreamEvent{ Type: "navigate", @@ -364,7 +363,7 @@ func (s chatStreamSink) ToolCall(event gateway.ToolCallEvent) { // path, silence here meant the model announced a file it had sent and // nothing arrived -- the precise defect send_file was built to end, // reappearing on the channel that cannot deliver. -func (s chatStreamSink) Media(event gateway.MediaEvent) { +func (s chatStreamSink) Media(event messaging.MediaEvent) { att := event.Attachment switch { case att.URL != "": diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 73e316265..2d5191ffd 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -10,11 +10,10 @@ import ( "strconv" "strings" - "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" - "github.com/samcharles93/archie-core/internal/secret" ) // Sentinel errors for handleConfigUpdate status classification. The @@ -82,7 +81,7 @@ func (s *Server) handleChannelReload(w http.ResponseWriter, r *http.Request) { http.Error(w, "channel reload unavailable", http.StatusNotImplemented) return } - var status *channels.Status + var status *status.Status for _, candidate := range s.Channels.Snapshot() { if candidate.ID == id { status = &candidate @@ -100,7 +99,7 @@ func (s *Server) handleChannelReload(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{"ok": true, "channel": id}) } -func channelViewFromStatus(status channels.Status) ChannelView { +func channelViewFromStatus(status status.Status) ChannelView { view := ChannelView{ ID: status.ID, Name: status.Name, Configured: status.Configured, Detail: status.Detail, State: string(status.State), ReloadSupported: status.ReloadSupported, @@ -119,20 +118,20 @@ func channelViewFromStatus(status channels.Status) ChannelView { return view } -func channelStateDetail(state channels.State, configured bool) string { +func channelStateDetail(state status.State, configured bool) string { if !configured { return "Not configured." } switch state { - case channels.StateConfigured: + case status.StateConfigured: return "Configured; waiting for the daemon to start it." - case channels.StateStarting: + case status.StateStarting: return "Starting." - case channels.StateRunning: + case status.StateRunning: return "Running." - case channels.StateDegraded: + case status.StateDegraded: return "Running with a degraded capability." - case channels.StateFailed: + case status.StateFailed: return "Failed to start." default: return "Stopped." @@ -140,7 +139,7 @@ func channelStateDetail(state channels.State, configured bool) string { } func telegramChannelView(t config.TelegramConfig) ChannelView { - configured := t.Token != (secret.SecretRef{}) || strings.TrimSpace(t.TokenEnv) != "" + configured := t.Token != (config.SecretRef{}) || strings.TrimSpace(t.TokenEnv) != "" detail := "Not configured." if configured { n := len(t.AllowedUserIDs) @@ -159,7 +158,7 @@ func telegramChannelView(t config.TelegramConfig) ChannelView { Configured: configured, Detail: detail, Description: "Talk to Archie and approve its work from your phone.", - State: string(channels.StateConfigured), + State: string(status.StateConfigured), ReloadSupported: true, } } @@ -198,9 +197,9 @@ func emailChannelView(e config.EmailConfig) ChannelView { func staticChannelState(configured bool) string { if configured { - return string(channels.StateConfigured) + return string(status.StateConfigured) } - return string(channels.StateStopped) + return string(status.StateStopped) } // ConfigView is the read-only, secret-free projection of config.Config @@ -319,7 +318,7 @@ type WebView struct { // // This handler builds ConfigView field by field from an explicit allowlist // rather than marshalling config.Config and stripping fields afterward: -// config.Config carries secret.SecretRef values (forge tokens, provider API +// config.Config carries config.SecretRef values (forge tokens, provider API // keys) and there is no way to guarantee a strip-after-marshal approach // keeps working as fields are added to Config in the future. An allowlist // fails safe -- a new secret field added upstream is simply absent here @@ -359,7 +358,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { // LocalConfigView builds the projection from the configuration this process // holds. It is what the daemon serves and, byte for byte, what it publishes -// for the UI process to render (see storev1.ConfigSnapshot). +// for the UI process to render (see storecontract.ConfigSnapshot). // // Every value here is read from one config snapshot taken up front: under the // Holder a reload swaps the whole value, which is what a read-only view @@ -437,7 +436,7 @@ func (s *Server) LocalConfigView(ctx context.Context) (ConfigView, bool, error) // RemoteConfigView reads the projection the configuration owner published. // The reading process cannot edit it: it has no update path, and the page is // told so rather than offering a control that would 503. -func RemoteConfigView(snapshots storev1.ConfigSnapshotStore) ConfigViewSource { +func RemoteConfigView(snapshots storecontract.ConfigSnapshotStore) ConfigViewSource { return func(ctx context.Context) (ConfigView, bool, error) { snapshot, found, err := snapshots.ConfigSnapshot(ctx) if err != nil || !found { diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index f310907f0..317f654a7 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -9,11 +9,9 @@ import ( "strings" "testing" - "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/logging" - "github.com/samcharles93/archie-core/internal/memory" "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/store" ) @@ -595,7 +593,7 @@ func TestHandleChannelsNilConfig(t *testing.T) { func TestHandleChannelsUsesRuntimeManager(t *testing.T) { srv := newTestServer(t) srv.Cfg = configWithFakeSecrets() - srv.Channels = channels.NewManager([]channels.Descriptor{{ + srv.Channels = status.NewManager([]status.Descriptor{{ ID: "telegram", Name: "Telegram", Configured: true, ReloadSupported: true, }}) srv.Channels.MarkFailed("telegram", "token rejected") @@ -729,8 +727,9 @@ func TestCapabilitiesReportWhatThisProcessCanServe(t *testing.T) { wired := newTestServer(t) wired.Cfg = config.NewHolder(config.Config{}) wired.LogFeed = logging.NewFeed(10) - wired.Memory = &memory.Manager{} - wired.Curators = &curator.Registry{} + wired.Memory = stubMemory{} + wired.Curators = stubCurators{} + wired.Skills = stubSkillCatalog{} got := get(wired) for _, section := range []string{"logs", "memory", "curators", "skills", "channels"} { if !got[section] { @@ -738,3 +737,31 @@ func TestCapabilitiesReportWhatThisProcessCanServe(t *testing.T) { } } } + +// stubMemory satisfies the webui-owned MemoryStatus view for tests. +type stubMemory struct{} + +func (stubMemory) Builtin() MemoryProviderHandle { return stubMemoryProvider{} } +func (stubMemory) External() MemoryProviderHandle { return nil } + +type stubMemoryProvider struct{} + +func (stubMemoryProvider) Name() string { return "builtin" } +func (stubMemoryProvider) IsAvailable() bool { return true } +func (stubMemoryProvider) ToolViews() []MemoryToolView { + return []MemoryToolView{{Name: "remember", Description: "store a fact"}} +} + +// stubCurators satisfies the webui-owned CuratorStatus view for tests. +type stubCurators struct{} + +func (stubCurators) Names() []string { return []string{"wired"} } +func (stubCurators) Health(_ context.Context) map[string]CuratorHealthView { + return map[string]CuratorHealthView{"wired": {Status: "healthy"}} +} +func (stubCurators) Activity(string) (CuratorActivity, bool) { return CuratorActivity{}, false } + +// stubSkillCatalog satisfies the webui-owned SkillCatalog view for tests. +type stubSkillCatalog struct{} + +func (stubSkillCatalog) Skills() []SkillView { return []SkillView{{Name: "demo"}} } diff --git a/internal/webui/api_curators.go b/internal/webui/api_curators.go index 3e207ca60..818dd8b6d 100644 --- a/internal/webui/api_curators.go +++ b/internal/webui/api_curators.go @@ -1,6 +1,7 @@ package webui import ( + "context" "net/http" "time" ) @@ -14,8 +15,29 @@ type CuratorActionView struct { Reason string `json:"reason"` } +// CuratorStatus is the webui-owned surface over the running curator +// registry: the names, point-in-time health, and recent activity the +// dashboard's curator view renders. It is deliberately narrower than the +// registry itself -- whose engine contract drags in the agent toolchain -- +// so the UI process holds the view without linking it +// (archie-core-8cda.5.6). Whoever owns the registry supplies an adapter at +// bootstrap. +type CuratorStatus interface { + Names() []string + Health(ctx context.Context) map[string]CuratorHealthView + Activity(name string) (CuratorActivity, bool) +} + +// CuratorActivity is one curator's recent run history, as the webui +// renders it. +type CuratorActivity struct { + LastRunAt time.Time + LastRunActions int + Recent []CuratorActionView +} + // CuratorView is one registered curator's observable state: identity, -// health, and recent activity. Backed by curator.Registry -- see +// health, and recent activity. Backed by CuratorStatus -- see // handleCurators. type CuratorView struct { Name string `json:"name"` @@ -55,7 +77,7 @@ func (s *Server) handleCurators(w http.ResponseWriter, r *http.Request) { view := CuratorView{ Name: name, Health: CuratorHealthView{ - Status: string(h.Status), + Status: h.Status, Message: h.Message, }, RecentActions: []CuratorActionView{}, diff --git a/internal/webui/api_curators_test.go b/internal/webui/api_curators_test.go index 1590aa875..558923727 100644 --- a/internal/webui/api_curators_test.go +++ b/internal/webui/api_curators_test.go @@ -66,7 +66,7 @@ func TestHandleCuratorsReportsNamesHealthAndActivity(t *testing.T) { }) srv := newTestServer(t) - srv.Curators = registry + srv.Curators = curatorStatusAdapter{registry} w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/curators", nil)) @@ -113,7 +113,7 @@ func TestHandleCuratorsReportsRegisteredCuratorWithNoActivityYet(t *testing.T) { } srv := newTestServer(t) - srv.Curators = registry + srv.Curators = curatorStatusAdapter{registry} w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/curators", nil)) @@ -142,3 +142,36 @@ func TestHandleCuratorsReportsRegisteredCuratorWithNoActivityYet(t *testing.T) { t.Fatalf("response leaks zero-value time.Time: %s", body) } } + +// curatorStatusAdapter adapts the real registry to the webui-owned +// CuratorStatus view, mirroring the daemon's bootstrap adapter. +type curatorStatusAdapter struct{ r *curator.Registry } + +func (a curatorStatusAdapter) Names() []string { return a.r.Names() } + +func (a curatorStatusAdapter) Health(ctx context.Context) map[string]CuratorHealthView { + health := a.r.Health(ctx) + views := make(map[string]CuratorHealthView, len(health)) + for name, h := range health { + views[name] = CuratorHealthView{Status: string(h.Status), Message: h.Message} + } + return views +} + +func (a curatorStatusAdapter) Activity(name string) (CuratorActivity, bool) { + activity, ok := a.r.Activity(name) + if !ok { + return CuratorActivity{}, false + } + view := CuratorActivity{ + LastRunAt: activity.LastRunAt, + LastRunActions: activity.LastRunActions, + Recent: make([]CuratorActionView, 0, len(activity.Recent)), + } + for _, a2 := range activity.Recent { + view.Recent = append(view.Recent, CuratorActionView{ + At: a2.At, Type: a2.Type, Detail: a2.Detail, Reason: a2.Reason, + }) + } + return view, true +} diff --git a/internal/webui/api_mapping.go b/internal/webui/api_mapping.go index 54c943055..5d5d2b070 100644 --- a/internal/webui/api_mapping.go +++ b/internal/webui/api_mapping.go @@ -7,8 +7,8 @@ import ( "net/http" "strconv" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/mapping" + "github.com/samcharles93/archie-core/internal/domain/storecontract" ) // mappingRequest is the wire shape POST /api/mappings and @@ -109,7 +109,7 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) { return } if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil { - if errors.Is(err, storev1.ErrMappingNotFound) { + if errors.Is(err, storecontract.ErrMappingNotFound) { http.Error(w, "mapping not found", http.StatusNotFound) return } @@ -137,7 +137,7 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) { return } if err := s.Mappings.DeleteMapping(r.Context(), id); err != nil { - if errors.Is(err, storev1.ErrMappingNotFound) { + if errors.Is(err, storecontract.ErrMappingNotFound) { http.Error(w, "mapping not found", http.StatusNotFound) return } @@ -192,7 +192,7 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) { // exactly one reader, the dashboard list view, so a by-ID lookup was never // needed until preview), so this scans the newest window rather than // adding a new store method for a single low-volume caller. -func (s *Server) captureByID(ctx context.Context, id int64) (*storev1.CapturedEvent, error) { +func (s *Server) captureByID(ctx context.Context, id int64) (*storecontract.CapturedEvent, error) { captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents)) if err != nil { return nil, err diff --git a/internal/webui/api_memory.go b/internal/webui/api_memory.go index 85a39eef3..61a0db241 100644 --- a/internal/webui/api_memory.go +++ b/internal/webui/api_memory.go @@ -1,10 +1,26 @@ package webui -import ( - "net/http" +import "net/http" - "github.com/samcharles93/archie-core/internal/memory" -) +// MemoryProviderHandle is the webui-owned view source for one memory +// provider: the memory page renders a name, a readiness flag, and the +// provider's tool vocabulary by name. It is deliberately narrower than +// memory.MemoryProvider -- whose GetToolSchemas returns runtime tool +// entries -- so the UI process holds the view without linking the memory +// runtime (and, transitively, the agent toolchain). Whoever owns the +// memory runtime supplies adapters at bootstrap (archie-core-8cda.5.6). +type MemoryProviderHandle interface { + Name() string + IsAvailable() bool + ToolViews() []MemoryToolView +} + +// MemoryStatus is the webui-owned surface over the running memory runtime: +// the two providers the memory page renders, by role. +type MemoryStatus interface { + Builtin() MemoryProviderHandle + External() MemoryProviderHandle +} // MemoryProviderView describes one memory provider for the dashboard. type MemoryProviderView struct { @@ -48,18 +64,13 @@ func (s *Server) handleMemory(w http.ResponseWriter, r *http.Request) { writeJSON(w, map[string]any{"providers": views, "enabled": true}) } -func providerView(p memory.MemoryProvider, role string) MemoryProviderView { +func providerView(p MemoryProviderHandle, role string) MemoryProviderView { view := MemoryProviderView{ Name: p.Name(), Role: role, Available: p.IsAvailable(), Tools: []MemoryToolView{}, } - for _, t := range p.GetToolSchemas() { - view.Tools = append(view.Tools, MemoryToolView{ - Name: t.Name, - Description: t.Description, - }) - } + view.Tools = append(view.Tools, p.ToolViews()...) return view } diff --git a/internal/webui/api_setup.go b/internal/webui/api_setup.go index 04771659e..c201b9d30 100644 --- a/internal/webui/api_setup.go +++ b/internal/webui/api_setup.go @@ -4,7 +4,7 @@ import ( "net/http" "strings" - "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/config" ) // SetupStep is one item in the dashboard's getting-started checklist. @@ -79,6 +79,6 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { // one is the honest signal here. func (s *Server) hasChannel() bool { cfg := s.Cfg.Get() - return cfg.Chat.Telegram.Token != (secret.SecretRef{}) || strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" || + return cfg.Chat.Telegram.Token != (config.SecretRef{}) || strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" || strings.TrimSpace(cfg.Chat.WebhookAddr) != "" } diff --git a/internal/webui/api_skills.go b/internal/webui/api_skills.go index 4d8f8c5cc..bea376fff 100644 --- a/internal/webui/api_skills.go +++ b/internal/webui/api_skills.go @@ -1,10 +1,6 @@ package webui -import ( - "net/http" - - "github.com/samcharles93/archie-core/internal/skill" -) +import "net/http" // SkillView is one catalogued skill as shown on the dashboard's Skills page: // what it does, in plain language, and where it was discovered. @@ -15,55 +11,23 @@ type SkillView struct { Source string `json:"source"` } +// SkillCatalog is the webui-owned source of the dashboard's skill +// catalogue. It is deliberately a view over already-discovered entries, not +// the discovery machinery: the cataloguer (internal/skill) drags the agent +// toolchain in, and the UI process must not link it (archie-core-8cda.5.6). +// Whoever owns the runtime -- the daemon, via its config -- supplies an +// adapter at bootstrap; an unwired catalog degrades to an empty page. +type SkillCatalog interface { + Skills() []SkillView +} + // handleSkills reports the skill catalogue -- what Archie can actually do, // beyond what is in the source. It answers the same question a fresh // operator would ask by reading internal/skill/, without the reading. -// -// The catalogue layers project, explicitly shared, and user-global skills. -// Earlier roots win when names collide. Missing roots are legitimate and -// produce an empty or partial catalogue rather than a failed dashboard. func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) { - if s.Cfg == nil { + if s.Skills == nil { writeJSON(w, map[string]any{"skills": []SkillView{}}) return } - - cfg := s.Cfg.Get() - roots := skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir) - catalog, err := skill.CatalogRoots(roots...) - if err != nil { - http.Error(w, "failed to read skill catalogue: "+err.Error(), http.StatusInternalServerError) - return - } - - views := make([]SkillView, 0, len(catalog)) - for _, entry := range catalog { - views = append(views, SkillView{ - Name: entry.Name, - Description: entry.Description, - Workflow: entry.Workflow, - Source: skillSource(entry.Root, cfg.WorkDir, cfg.SkillsDir), - }) - } - - // Each skill already carries its own Source, which is what the page - // renders. A top-level dir/dirs pair had no consumer and implied the - // catalog came from one place when it is merged from several. - writeJSON(w, map[string]any{"skills": views}) -} - -// skillSource labels where a skill was loaded from. -// -// sharedDir is checked first: when it equals workDir the roots collapse to one -// entry, and matching workDir first labelled every shared skill as a project -// skill. -func skillSource(root, workDir, sharedDir string) string { - switch root { - case sharedDir: - return "shared skills" - case workDir: - return "project skills" - default: - return "user-global skills" - } + writeJSON(w, map[string]any{"skills": s.Skills.Skills()}) } diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 13b402064..ae0ce0f30 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -13,9 +13,9 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/config" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/taskactions" - "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -63,14 +63,14 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) { } type taskView struct { - workflow.Task + task.Task Actions []taskstate.Action `json:"actions"` RepoURL string `json:"repo_url,omitempty"` IssueURL string `json:"issue_url,omitempty"` PRURL string `json:"pr_url,omitempty"` } -func (s *Server) taskURLs(task workflow.Task) (repoURL, issueURL, prURL string) { +func (s *Server) taskURLs(task task.Task) (repoURL, issueURL, prURL string) { if s.Cfg == nil { return "", "", "" } @@ -92,7 +92,7 @@ func (s *Server) taskURLs(task workflow.Task) (repoURL, issueURL, prURL string) return repoURL, issueURL, prURL } -func forgeConfigForTask(cfg config.Config, task workflow.Task) config.Forge { +func forgeConfigForTask(cfg config.Config, task task.Task) config.Forge { for _, identity := range cfg.Identities { if task.Identity != "" && identity.Name == task.Identity { return identity.Forge @@ -152,7 +152,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { switch { case errors.Is(err, taskactions.ErrNotFound): http.Error(w, "task not found", http.StatusNotFound) - case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storev1.ErrStaleTransition): + case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storecontract.ErrStaleTransition): http.Error(w, err.Error(), http.StatusConflict) case errors.Is(err, taskactions.ErrUnavailable): http.Error(w, err.Error(), http.StatusServiceUnavailable) diff --git a/internal/webui/api_workflows.go b/internal/webui/api_workflows.go index 7e4c09111..2ef20f651 100644 --- a/internal/webui/api_workflows.go +++ b/internal/webui/api_workflows.go @@ -7,8 +7,8 @@ import ( "net/http" "strings" + "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/gateway" ) // handleWorkflows returns per-workflow and per-stage statistics: run counts, @@ -78,7 +78,7 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { http.Error(w, "workflow is not enabled", http.StatusConflict) return } - taskID, err := s.WorkRequests.CreateTask(r.Context(), gateway.SpawnRequest{ + taskID, err := s.WorkRequests.CreateTask(r.Context(), messaging.SpawnRequest{ Identity: request.Identity, Repo: request.Repository, Workflow: request.Workflow, Title: request.Title, Body: request.Instructions, }) diff --git a/internal/webui/dangerous.go b/internal/webui/dangerous.go index 441de5fdf..211646d63 100644 --- a/internal/webui/dangerous.go +++ b/internal/webui/dangerous.go @@ -10,7 +10,7 @@ import ( "github.com/google/uuid" - "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/domain/messaging" ) const ( @@ -22,7 +22,7 @@ const ( // interactive approval workflow. It intentionally has no host process or // filesystem access of its own. type DangerousService struct { - Authority gateway.DangerousCommandAuthority + Authority messaging.DangerousCommandAuthority mu sync.Mutex actions map[string]dangerousAction @@ -44,7 +44,7 @@ type DangerousActionView struct { ExpiresAt time.Time `json:"expires_at"` } -func NewDangerousService(authority gateway.DangerousCommandAuthority) *DangerousService { +func NewDangerousService(authority messaging.DangerousCommandAuthority) *DangerousService { return &DangerousService{ Authority: authority, actions: make(map[string]dangerousAction), @@ -59,7 +59,7 @@ func (s *DangerousService) enabled() error { return nil } -func (s *DangerousService) Checkpoints(ctx context.Context) ([]gateway.CheckpointInfo, error) { +func (s *DangerousService) Checkpoints(ctx context.Context) ([]messaging.CheckpointInfo, error) { if err := s.enabled(); err != nil { return nil, err } diff --git a/internal/webui/server.go b/internal/webui/server.go index c87033dac..23b3a5d1a 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -16,21 +16,19 @@ import ( "sync" "sync/atomic" - "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" - "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/health" - "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/logging" - "github.com/samcharles93/archie-core/internal/memory" "github.com/samcharles93/archie-core/ui" ) type Server struct { - Store storev1.TaskStore + Store storecontract.TaskStore Log *slog.Logger // Cfg backs the setup checklist and configuration views. Optional: the @@ -52,10 +50,10 @@ type Server struct { ConfigSource ConfigViewSource // Workflows is the executable registry snapshot supplied by composition. - Workflows []workflow.Definition + Workflows []task.Definition // WorkRequests admits dashboard requests through the same task-creation // boundary used by chat; it never invokes a workflow runner directly. - WorkRequests gateway.TaskCreator + WorkRequests messaging.TaskCreator // LogFeed is the daemon diagnostic stream. It is separate from Events, // which contains persisted task lifecycle activity only. LogFeed *logging.Feed @@ -108,7 +106,7 @@ type Server struct { // Channels reports actual adapter lifecycle, independently of configuration // presence. Nil preserves the configuration-only fallback for tests and // minimal embedding. - Channels *channels.Manager + Channels *status.Manager // ReloadChannel invokes a channel-specific reload seam. Only adapters that // explicitly support reload are wired here; nil means reload is unavailable. @@ -116,13 +114,16 @@ type Server struct { // Memory backs the memory view. Optional: the section reports memory as // unavailable rather than failing when it is nil. - Memory *memory.Manager + Memory MemoryStatus + // Skills is the webui-owned skill catalogue view; nil degrades + // /api/skills to an empty page. + Skills SkillCatalog // Curators is the daemon's live curator registry (epic archie-core-yp9). // Backs GET /api/curators: registered names, per-curator health, and // recent activity (archie-core-1786637489932-6). Optional: nil reports // an empty curator list rather than failing the dashboard. - Curators *curator.Registry + Curators CuratorStatus // Chat exposes the Gateway's wire-safe conversational contract. Optional: // the dashboard simply omits chat when it is nil. @@ -146,7 +147,7 @@ type Server struct { // GET /api/captures list and the mapping preview's by-ID scan // (docs/prds/event-capture-storage.md). Optional: nil makes the list // answer {"enabled": false} rather than the dashboard failing to start. - Captures storev1.CaptureStore + Captures storecontract.CaptureStore // CaptureMaxEvents is the operator's configured [capture] max_events, // used to bound captureByID's scan window (api_mapping.go). // CaptureIntake is the write half's mount. @@ -167,13 +168,13 @@ type Server struct { // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). // Optional: nil makes every /api/mappings route answer 503 rather than // the dashboard failing to start. - Mappings storev1.MappingStore + Mappings storecontract.MappingStore // Bindings persists playbook bindings: matcher + mapping + workflow // triples that turn a captured webhook into an archie task // (docs/prds/webhook-intake-security.md). Optional: nil makes every // /api/bindings route answer 503 rather than the dashboard failing to start. - Bindings storev1.BindingStore + Bindings storecontract.BindingStore // TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard- // initiated update use the same post-restart notification route as a diff --git a/internal/webui/sse.go b/internal/webui/sse.go index 134afb053..5acc24388 100644 --- a/internal/webui/sse.go +++ b/internal/webui/sse.go @@ -7,7 +7,7 @@ import ( "net/http" "strconv" - storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" ) @@ -89,7 +89,7 @@ func (s *Server) registerSSEConn() (chan events.Event, func()) { // running "since" watermark that deduplicates the backlog against live // broadcasts covering the same event. type sseStream struct { - store storev1.TaskStore + store storecontract.TaskStore log *slog.Logger w http.ResponseWriter fl http.Flusher @@ -98,7 +98,7 @@ type sseStream struct { // newSSEStream builds a stream over w, reporting false if w cannot be // flushed incrementally -- SSE does not work without that. -func newSSEStream(st storev1.TaskStore, log *slog.Logger, w http.ResponseWriter, since int64) (*sseStream, bool) { +func newSSEStream(st storecontract.TaskStore, log *slog.Logger, w http.ResponseWriter, since int64) (*sseStream, bool) { fl, ok := w.(http.Flusher) if !ok { return nil, false