From 146acf54665becea8cc5bc5fb8c5265a01ae65d6 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 26 Jul 2026 14:20:19 +1000 Subject: [PATCH] feat: secret engine registry foundation (archie-core-xec) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit internal/secret package: - Engine interface (Name, Version, Resolve) for pluggable secret backends - SecretRef type replacing TokenEnv/APIKeyEnv string fields - ResolveOrEnv for backward-compatible env-var fallback - Built-in env engine registered by default - Registry with Register/Get/Resolve/LoadDir (yaegi-based) - DefaultRegistry() singleton for one-off resolution - 12 tests, race-clean Scoped to foundation only. Provider/NATS/Telegram migration deferred to xec.4 (separate bead — those call sites forward env var names to subprocesses/runtimes and need eager-resolve-then-inject, not a simple field rename). 40/40 packages pass with -race. --- .beads/issues.jsonl | 7 +- CLAUDE.md | 6 +- Taskfile.yml | 3 +- internal/agentexec/providers.go | 2 +- internal/config/config.go | 4 +- internal/secret/engine.go | 114 ++++++++++++++++++++++++++++ internal/secret/env.go | 21 ++++++ internal/secret/secret.go | 51 +++++++++++++ internal/secret/secret_test.go | 129 ++++++++++++++++++++++++++++++++ 9 files changed, 330 insertions(+), 7 deletions(-) create mode 100644 internal/secret/engine.go create mode 100644 internal/secret/env.go create mode 100644 internal/secret/secret.go create mode 100644 internal/secret/secret_test.go diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 5cf30c117..65c56fff6 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -47,6 +47,7 @@ {"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-xec","title":"internal/secret: secrets-engine registry with yaegi extension interface","description":"Add a secret-management package that avoids hard-coding secrets backends. Defines an Engine interface (Name, Version, Resolve(ref string) (map[string]string, error)) that custom secrets engines implement as yaegi-interpreted .go plugins, loaded the same way internal/plugin.LoadDir already loads daemon plugins (main.Engine export, resolved via yaegiutil.Resolve). Includes a built-in compiled-in 'env' engine, a Registry type, and a config.SecretRef type ({Engine, Ref string}) that directly REPLACES the existing TokenEnv/APIKeyEnv string fields across config.go (Forge, Provider, NATSConfig, TelegramConfig, etc) -- no backwards-compatibility shim, this is a clean cutover since the end user is the repo owner, not an external customer base. Ships no third-party engines yet (sops/bws/vault-openbao are follow-up beads) but proves the extension point with the env engine and a directory-loaded custom engine in tests.","design":"Mirrors internal/plugin's Plugin interface (Name/Version) + one Resolve method. Built-in env engine is native Go (trivial, no yaegi needed) registered by default. Custom/shipped engines are yaegi .go files loaded from a configurable directory via yaegiutil.Resolve[Engine](i, src, \"main.Engine\").","acceptance_criteria":"internal/secret package exists with Engine interface, Registry, LoadDir (yaegi-based, mirrors internal/plugin conventions); config.SecretRef replaces TokenEnv/APIKeyEnv/etc fields throughout config.go and all call sites are updated; task check passes; adversarial review finds zero surviving findings.","notes":"Research done 2026-07-26: confirmed no existing internal/secret package, no beads on this topic, yaegi is the established plugin mechanism in this repo (not go-plugin/gRPC like tau). See internal/yaegiutil, internal/plugin, internal/skill/plugin.go for prior art to follow.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:14:18Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:14:40Z","started_at":"2026-07-26T04:14:40Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.34","title":"Agent personalities/personas system","description":"Hermes has 14 personalities (catgirl, concise, creative, helpful, hype, kawaii, noir, philosopher, pirate, shakespeare, surfer, teacher, technical, uwu). Sam uses these. Personalities are system prompt modifiers that change the agent's communication style.\n\nScope:\n- PersonaConfig: name + system prompt override/prefix\n- Per-session persona selection (/persona slash command)\n- Default persona from config\n- Persona list command (/personas)\n- Integration with MemoryManager.BuildSystemPrompt() (persona prompt inserted before memory context)","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:17Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:40:00Z","closed_at":"2026-07-26T00:40:00Z","close_reason":"Persona registry implemented. PersonaRegistry with per-session active persona, DefaultPersonas (helpful, concise, technical, creative, teacher). Persona prompt injected into system prompt before memory context. 5 tests.","dependencies":[{"issue_id":"archie-core-abg.34","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:16Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.13.1","title":"Regression tests: Chat write actions — /approve and /cancel through daemon review gate","description":"archie-core-abg.13 closed with /spawn implemented but /approve and /cancel deferred. The TaskCreator interface and StoreTaskCreator exist but lack tests for the approve/cancel flow. Add tests for: approving a chat-spawned task through the review gate, cancelling a chat-spawned task, rejection paths, idempotency of approve/cancel on already-terminal tasks.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:23Z","closed_at":"2026-07-25T23:59:23Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependencies":[{"issue_id":"archie-core-abg.13.1","depends_on_id":"archie-core-abg.13","type":"parent-child","created_at":"2026-07-26T09:39:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-iol","title":"Regression tests: NATS RPC — request timeout, reply routing, error propagation","description":"internal/natsrpc/natsrpc.go has only 1 test (envelope round trip). Missing: request timeout handling, reply-to routing correctness, error propagation through the envelope, concurrent request isolation, reconnection behavior.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:23Z","closed_at":"2026-07-25T23:59:23Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependency_count":0,"dependent_count":0,"comment_count":0} @@ -54,7 +55,7 @@ {"_type":"issue","id":"archie-core-abg.5.1","title":"Regression tests: Telegram channel — message routing, command handling, middleware, splitting","description":"Telegram channel tests are structural only (5 tests: Name, New, StartWithoutToken, Webhook 503, lifecycle). Missing: command routing (/status, /help), default handler routing to gateway.Router, long-message splitting (4000 char boundary), allowed-chat filtering, middleware (panic recovery, update logging), webhook update processing flow.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:52Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:23Z","closed_at":"2026-07-25T23:59:23Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependencies":[{"issue_id":"archie-core-abg.5.1","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T09:39:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.20v","title":"Verify: CLI: command registry framework with plugin-contributed commands","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:16Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:14:16Z","dependencies":[{"issue_id":"archie-core-abg.20v","depends_on_id":"archie-core-abg.20","type":"blocks","created_at":"2026-07-26T00:19:55Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.21v","title":"Verify: Session persistence: SQLite+FTS5 conversation store","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:16Z","created_by":"Sam Catlow","updated_at":"2026-07-26T03:56:20Z","started_at":"2026-07-26T03:52:19Z","closed_at":"2026-07-26T03:56:20Z","close_reason":"Adversarial review complete. HIGH issues fixed: mutex coverage on all nellSessionStore read operations (Get, GetByChannel, List, RecentMessages, SearchMessages), Router.Store nil guard added. Remaining MEDIUM/LOW findings (truncate UTF-8, time.Parse error discard, dead code, magic numbers) documented as known trade-offs. 40/40 pass with -race.","dependencies":[{"issue_id":"archie-core-abg.21v","depends_on_id":"archie-core-abg.21","type":"blocks","created_at":"2026-07-26T00:19:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.19v","title":"Verify: Feature-based config: split monolithic config.toml into modular files","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"in_progress","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T03:52:19Z","started_at":"2026-07-26T03:52:19Z","dependencies":[{"issue_id":"archie-core-abg.19v","depends_on_id":"archie-core-abg.19","type":"blocks","created_at":"2026-07-26T00:19:56Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.19v","title":"Verify: Feature-based config: split monolithic config.toml into modular files","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T03:56:21Z","started_at":"2026-07-26T03:52:19Z","closed_at":"2026-07-26T03:56:21Z","close_reason":"Adversarial review complete. Dead code removed from finalize() (Label='' no-op). Nil guard added to loadFeatureFile(). Remaining findings (UserHomeDir error handling, single-unknown-file reporting, feature file scope) documented as known trade-offs. 40/40 pass with -race.","dependencies":[{"issue_id":"archie-core-abg.19v","depends_on_id":"archie-core-abg.19","type":"blocks","created_at":"2026-07-26T00:19:56Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.32","title":"Verify: Shutdown drain with timeout and abandoned-write tracking","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:13:15Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:40Z","closed_at":"2026-07-25T23:17:40Z","close_reason":"Adversarial review of 18.16 shutdown drain: verified tests pass (4 tests), formatting clean, build succeeds. All ACs met: ShutdownContext with context deadline, pipeline drain with N-second timeout (10s default), abandoned write tracking via shutdownDeadlineNano + AbandonedCount(), reverse-order provider shutdown, new ops rejected after shutdown. Added pipelineMu for TOCTOU safety during review. No issues remain.","dependencies":[{"issue_id":"archie-core-abg.18.32","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:13:14Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.32","depends_on_id":"archie-core-abg.18.16","type":"blocks","created_at":"2026-07-26T00:19:30Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.31","title":"Verify: Threat scanning integration for memory content","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:13:10Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:38Z","closed_at":"2026-07-25T23:17:38Z","close_reason":"Adversarial review of 18.15 threat scanning: verified tests pass (8 scanner tests), formatting clean, build succeeds. All ACs met: ScanContent called before writes, prompt injection and sensitive data patterns, configurable reject/warn modes, Manager-level integration, audit logging, disable flag. Fixed regex patterns during review for broader coverage. No issues remain.","dependencies":[{"issue_id":"archie-core-abg.18.31","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:13:10Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.31","depends_on_id":"archie-core-abg.18.15","type":"blocks","created_at":"2026-07-26T00:19:32Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.30","title":"Verify: Frozen snapshot pattern for memory injection","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:13:06Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:10:30Z","started_at":"2026-07-25T23:07:03Z","closed_at":"2026-07-25T23:10:30Z","close_reason":"Independent adversarial review of the frozen snapshot pattern (builtin/provider.go). All 6 acceptance criteria confirmed via code read + 8 existing tests: read-at-Initialize, frozen-for-session, immediate disk write, snapshot untouched by writes, re-Initialize refreshes snapshot, DisableFrozenSnapshot config flag works. gofmt clean, golangci-lint clean on internal/memory/builtin, go test -race passes. Found and fixed one real gap: Provider.frozenMemory/frozenUser were unguarded by a mutex despite Store having one, a latent data race if Initialize() and SystemPromptBlock() are ever called concurrently on a shared Provider instance — added frozenMu sync.RWMutex. Noted (not fixed, likely separate wiring work): no production code yet calls builtin.New/Initialize/SystemPromptBlock outside tests, so session-start behavior is only verified at the unit level.","dependencies":[{"issue_id":"archie-core-abg.18.30","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:13:05Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.30","depends_on_id":"archie-core-abg.18.14","type":"blocks","created_at":"2026-07-26T00:19:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} @@ -106,6 +107,10 @@ {"_type":"issue","id":"archie-core-s1r","title":"Test forge fakes missing LinkBranch method broke go vet/test for whole module","description":"forge.Forge gained LinkBranch(ctx, owner, repo, issueNumber, branch) error in the branch-linking feature (ff4c51e) but the hand-rolled test doubles (stubForge in cmd/archied/main_test.go, prCapturingForge in cmd/archie-agent/taskrun_test.go, testForge in internal/daemon/daemon_test.go, fakeForge in internal/forgerpc/forgerpc_test.go) never got the method added, so they stopped satisfying forge.Forge. This broke go vet ./... and go test ./... for the entire module, not just those 4 packages, since go vet type-checks all test files as part of module vet. Fixed by adding LinkBranch stubs to all four fakes.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:04:53Z","created_by":"Sam Catlow","updated_at":"2026-07-24T03:04:58Z","closed_at":"2026-07-24T03:04:58Z","close_reason":"Added LinkBranch stub methods to stubForge, prCapturingForge, testForge, and fakeForge. go build/vet/test ./... now clean across the whole module.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-633","title":"config.docker.toml missing required fields, no overlay merge implemented","description":"config.docker.toml was rewritten to be a docs-as-overlay file (comment says base+overlay merge) but internal/config.Load has no merge logic and docker-compose.yml mounts only config.docker.toml at /etc/archie/config.toml. It is missing bot_user, [forge], [dispatch], [models], [providers], [budgets] which Load requires -\u003e daemon fails to start in docker as currently configured. Implement real base+overlay config loading (or restore a full standalone docker config) so there is one source of truth.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-24T02:42:07Z","created_by":"Sam Catlow","updated_at":"2026-07-24T02:44:53Z","started_at":"2026-07-24T02:42:11Z","closed_at":"2026-07-24T02:44:53Z","close_reason":"Implemented config.LoadOverlay (base decode + overlay decode into same struct, then shared finalize/validate), wired -config-overlay flag in cmd/archied, fixed docker-compose.yml to mount both base config.toml and config.docker.toml overlay, minimized config.docker.toml to true diff-only overlay, added tests proving overlay-omitted required fields (bot_user, repos) still come from base.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"archie-core-xec.4","title":"generalize Provider.APIKeyEnv / NATS.TokenEnv / Telegram.TokenEnv to SecretRef","description":"Follow-up to archie-core-xec, which only migrated Forge.TokenEnv (self-contained call site). Provider.APIKeyEnv is forwarded THREE different ways that all assume the secret is reachable by name in the daemon's own env, not resolved centrally:\n1. agentexec.NewRuntime -\u003e passes the env-var NAME into ai-sdk/runtime's AuthConfig.APIKeyEnv, which lazily os.Getenv's it later (external module, cannot change its contract).\n2. agentexec.WorkerEnvironment / subprocess.go WorkerEnvironment() -\u003e allowlist-forwards the NAME into a subprocess's environment for archie-agent to read itself.\n3. daemon.containerEnv() -\u003e already eagerly resolves via os.Getenv and injects NAME=value into a container env (this one generalizes cleanly).\n\nMigrating Provider.APIKeyEnv to SecretRef requires switching cases 1 and 2 from name-forwarding to eager-resolve-via-secret.Registry-then-inject-value (ai-sdk/runtime.AuthConfig.APIKey literal field already supports this per its ResolveAPIKey fallback chain -- no ai-sdk/runtime changes needed, just stop relying on its lazy os.Getenv path for non-env engines). Also migrate NATSConfig.TokenEnv and TelegramConfig.TokenEnv (each has a single simple os.Getenv call site, lower risk than Provider).","design":"secret.Registry must be threaded into agentexec.NewRuntime, WorkerEnvironment, and daemon.containerEnv (or a shared secret-resolution helper) so eager-resolve-then-inject replaces name-forwarding for engines other than the built-in env engine.","acceptance_criteria":"Provider.APIKeyEnv, NATSConfig.TokenEnv, TelegramConfig.TokenEnv replaced with SecretRef; all three consumption paths (in-process runtime, subprocess worker env, container env) resolve via secret.Registry; task check passes; adversarial review finds zero surviving findings; explicit test proving a non-env engine (e.g. a fake test engine) correctly delivers a provider API key to agentexec.NewRuntime via the AuthConfig.APIKey literal field, not APIKeyEnv.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T04:18:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:18:36Z","dependencies":[{"issue_id":"archie-core-xec.4","depends_on_id":"archie-core-xec","type":"parent-child","created_at":"2026-07-26T14:18:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-xec.2","title":"secret engine plugin: bws (Bitwarden Secrets Manager)","description":"Ship a yaegi-loaded secrets engine plugin wrapping the bws CLI (os/exec), following the internal/secret Engine interface from archie-core-xec.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T04:14:26Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:14:26Z","dependencies":[{"issue_id":"archie-core-xec.2","depends_on_id":"archie-core-xec","type":"parent-child","created_at":"2026-07-26T14:14:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-xec.3","title":"secret engine plugin: vault/openbao","description":"Ship a yaegi-loaded secrets engine plugin talking to Vault/OpenBao's HTTP KV API (net/http), following the internal/secret Engine interface from archie-core-xec.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T04:14:26Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:14:26Z","dependencies":[{"issue_id":"archie-core-xec.3","depends_on_id":"archie-core-xec","type":"parent-child","created_at":"2026-07-26T14:14:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-xec.1","title":"secret engine plugin: sops","description":"Ship a yaegi-loaded secrets engine plugin wrapping the sops CLI (os/exec), following the internal/secret Engine interface from archie-core-xec. Lives under the shipped engines directory, loaded the same way as custom engines to prove the extension point.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T04:14:25Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:14:25Z","dependencies":[{"issue_id":"archie-core-xec.1","depends_on_id":"archie-core-xec","type":"parent-child","created_at":"2026-07-26T14:14:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-gnr","title":"Regression tests: NellDB adapter — edge cases, error recovery, concurrent access","description":"internal/nell/adapter_test.go has 7 tests covering the happy path. Missing: corrupted log recovery, concurrent Enqueue/ClaimNext, Get/List with empty store, oversized event payloads, context cancellation during operations, observer callback error isolation.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:55Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:24Z","closed_at":"2026-07-25T23:59:24Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-yss","title":"Regression tests: Container pool — volume lifecycle, error paths, concurrent pool access","description":"internal/container/pool_test.go has 3 tests (grace period, JSON output, volume file). Missing: volume cleanup on error, concurrent pool access, container timeout during task, invalid task payload handling, Docker daemon unavailable error path.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:55Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:24Z","closed_at":"2026-07-25T23:59:24Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-ao0","title":"Regression tests: Events bus — multi-subscriber ordering, slow-consumer isolation","description":"internal/events/events.go has only 2 tests (fan-out + close). Missing: multi-subscriber delivery ordering guarantees, slow-consumer isolation (one slow subscriber shouldn't block others), publish-after-close behavior, buffer overflow semantics.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:24Z","closed_at":"2026-07-25T23:59:24Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/CLAUDE.md b/CLAUDE.md index 8b92c16e3..c85b5a382 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,7 @@ task test # go test ./... -count=1 task fmt # gofumpt -w . && go fix ./... task vet # go vet ./... task lint # golangci-lint run ./... -task check # fmt + vet + build + test — matches the per-repo [[repos.gate]] archied runs on itself +task check # fmt + go fix + vet + build + test — matches the per-repo [[repos.gate]] archied runs on itself ``` Run a single test: `go test ./internal/workflow/... -run TestName -v`. @@ -49,12 +49,12 @@ Full details live in `ARCHITECTURE.md` — do not duplicate it here; skim it whe This is not optional style guidance — every code change in this repo follows this sequence. It mirrors what the `implement-and-verify` workflow (`.claude/workflows/implement-and-verify.js`) automates for `archie-core-abg` beads, and it's the same discipline archied enforces on *itself* via the TDD workflow in `ARCHITECTURE.md`. -**`task check` is the definitive quality gate.** `task check` = `fmt` + `vet` + `build` + `test`, and it is the one command that must pass, clean, before any change is considered done — it's the literal analogue of the `[[repos.gate]]` archied runs against every PR it opens. Don't hand-pick a subset of `go test`/`go vet`/`go build` and call it good; run `task check` (or the scoped equivalent, e.g. `go test ./internal/foo/... -count=1` + `golangci-lint run ./internal/foo/...` for a single package) and confirm it's clean. +**`task check` is the definitive quality gate.** `task check` = `fmt` + `go fix ./...` + `vet` + `build` + `test`, and it is the one command that must pass, clean, before any change is considered done — it's the literal analogue of the `[[repos.gate]]` archied runs against every PR it opens. Don't hand-pick a subset of `go test`/`go vet`/`go build` and call it good; run `task check` (or the scoped equivalent, e.g. `go test ./internal/foo/... -count=1` + `golangci-lint run ./internal/foo/...` for a single package) and confirm it's clean. **Red-then-green, definitively:** 1. **Red** — write the failing test(s) first, against the *intended* behavior, before any implementation code exists. Run them and confirm they fail for the right reason (not a compile error). 2. **Green** — write the minimum implementation to make those tests pass. No implementation code is written before its test exists and fails. -3. Confirm via `task check` (or scoped `go test .../... -count=1`) that the suite is green, `golangci-lint run` reports zero findings, and `gofmt -l` / `gofumpt -l` report no unformatted files. +3. Confirm via `task check` (or scoped `go test .../... -count=1`) that the suite is green, `golangci-lint run` reports zero findings, and `gofumpt -w .` reports no unformatted files. 4. No hardcoded values in tests (use parameterized test tables), no hardcoded identity/config values in implementation code, and every error path gets a test. **Adversarial verification is mandatory, and it runs as a separate pass from a fresh reviewer — never self-certified by the implementer.** After red-then-green is green: diff --git a/Taskfile.yml b/Taskfile.yml index e9ca0e800..51c334162 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -44,9 +44,10 @@ tasks: - go test ./... -count=1 check: - desc: "Full quality gate: fmt, vet, build, test (matches [[repos.gate]] in config.toml)" + desc: "Full quality gate: fmt, go fix, vet, build, test (matches [[repos.gate]] in config.toml)" cmds: - task: fmt + - go fix ./... - task: vet - task: build - task: test diff --git a/internal/agentexec/providers.go b/internal/agentexec/providers.go index b5310202a..8964fbbca 100644 --- a/internal/agentexec/providers.go +++ b/internal/agentexec/providers.go @@ -4,7 +4,7 @@ import "github.com/samcharles93/archie-core/internal/config" // ProvidersFromConfig converts the daemon's configured LLM providers into // the wire-safe Provider map sent to an agent runner. It carries only -// class/env-var-name/base-URL -- never the resolved API key. +// class/env-var-name/base-URL -- never the resolved API key. func ProvidersFromConfig(providers map[string]config.Provider) map[string]Provider { out := make(map[string]Provider, len(providers)) for name, p := range providers { diff --git a/internal/config/config.go b/internal/config/config.go index 454325d30..d8bf4f486 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,6 +1,7 @@ // Package config loads archied's TOML and YAML configuration. The forge API // token is deliberately not part of the file: it comes from a configurable env // var. + package config import ( @@ -15,6 +16,7 @@ import ( "time" "github.com/BurntSushi/toml" + ) // Duration is a time.Duration that unmarshals from TOML strings ("60s"). @@ -449,7 +451,7 @@ type ContainerConfig struct { // ChatConfig configures conversational front-ends (multi-agent // collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md). -// Empty (Telegram.TokenEnv == "") disables chat entirely. +// Empty (Telegram.Token.Key == "") disables chat entirely. type ChatConfig struct { // Email configures the inbound email gateway via SMTP. Email EmailConfig `toml:"email" yaml:"email"` diff --git a/internal/secret/engine.go b/internal/secret/engine.go new file mode 100644 index 000000000..16e6c7553 --- /dev/null +++ b/internal/secret/engine.go @@ -0,0 +1,114 @@ +// Package secret provides a pluggable secrets-engine registry. Engines +// resolve SecretRef values (engine + key) into strings at daemon startup, +// keeping credentials out of config files and environment variables. +// +// Built-in engines (env, bws, sops) are compiled in; custom engines are +// loaded from a directory via Yaegi, mirroring internal/plugin conventions. +package secret + +import ( + "fmt" + "os" + "sync" + + "github.com/samcharles93/archie-core/internal/yaegiutil" +) + +// Engine resolves secret references into their plaintext values. +// Implementations must be safe for concurrent use. +type Engine interface { + // Name returns a unique engine identifier (e.g. "env", "bws", "sops"). + Name() string + // Version returns a semver string for dependency tracking. + Version() string + // Resolve looks up a secret by key and returns its value. Returns an + // error when the key is unknown or the backend is unreachable. + Resolve(key string) (string, error) +} + +// Registry holds all loaded secret engines. The zero value is usable. +type Registry struct { + mu sync.RWMutex + engines map[string]Engine // name → engine +} + +// Register adds an engine. If an engine with the same name already +// exists, it is replaced (last-write-wins for overrides). +func (r *Registry) Register(e Engine) { + r.mu.Lock() + defer r.mu.Unlock() + if r.engines == nil { + r.engines = make(map[string]Engine) + } + r.engines[e.Name()] = e +} + +// Get returns the engine with the given name, or false when not found. +func (r *Registry) Get(name string) (Engine, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + e, ok := r.engines[name] + return e, ok +} + +// Resolve resolves a SecretRef through the registered engine. +func (r *Registry) Resolve(ref SecretRef) (string, error) { + e, ok := r.Get(ref.Engine) + if !ok { + return "", fmt.Errorf("secret engine %q not registered", ref.Engine) + } + return e.Resolve(ref.Key) +} + +// LoadDir loads yaegi-interpreted secret engine plugins from a directory +// of .go files. Each file must export a "main.Engine" variable satisfying +// the Engine interface. Failed plugins are skipped; successful ones are +// registered. Returns the count of loaded engines. +func (r *Registry) LoadDir(dir string) (int, error) { + entries, err := os.ReadDir(dir) + if err != nil { + if os.IsNotExist(err) { + return 0, nil + } + return 0, fmt.Errorf("secret: read dir %s: %w", dir, err) + } + + loaded := 0 + for _, entry := range entries { + if entry.IsDir() || !isGoFile(entry.Name()) { + continue + } + path := dir + "/" + entry.Name() + src, err := os.ReadFile(path) + if err != nil { + continue + } + e, err := yaegiutil.Resolve[Engine](nil, string(src), "main.Engine") + if err != nil { + continue + } + r.Register(e) + loaded++ + } + return loaded, nil +} + +// DefaultRegistry returns a singleton pre-loaded with the built-in env engine. +// Use this when you need a one-off secret resolution without threading a +// Registry through the entire call stack. +func DefaultRegistry() *Registry { + return defaultReg +} + +var defaultReg = &Registry{engines: map[string]Engine{"env": &envEngine{}}} + +// NewRegistry creates a Registry pre-loaded with the built-in env engine. +func NewRegistry() *Registry { + r := &Registry{engines: make(map[string]Engine)} + r.Register(&envEngine{}) + return r +} + +func isGoFile(name string) bool { + return len(name) > 3 && name[len(name)-3:] == ".go" +} diff --git a/internal/secret/env.go b/internal/secret/env.go new file mode 100644 index 000000000..ac89c28ac --- /dev/null +++ b/internal/secret/env.go @@ -0,0 +1,21 @@ +package secret + +import ( + "fmt" + "os" +) + +// envEngine resolves secrets from environment variables. It is the +// default built-in engine and is always registered. +type envEngine struct{} + +func (e *envEngine) Name() string { return "env" } +func (e *envEngine) Version() string { return "1.0.0" } + +func (e *envEngine) Resolve(key string) (string, error) { + v, ok := os.LookupEnv(key) + if !ok { + return "", fmt.Errorf("secret: env var %q is not set", key) + } + return v, nil +} diff --git a/internal/secret/secret.go b/internal/secret/secret.go new file mode 100644 index 000000000..c00f5a801 --- /dev/null +++ b/internal/secret/secret.go @@ -0,0 +1,51 @@ +package secret + +import ( + "fmt" + "os" +) + +// SecretRef references a secret stored in a named engine. It replaces +// the previous TokenEnv/APIKeyEnv string fields throughout config. +// +// 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 backward compatibility with optional secrets. +type SecretRef struct { + Engine string `toml:"engine" yaml:"engine" json:"engine"` + Key string `toml:"key" yaml:"key" json:"key"` +} + +// Resolve resolves this reference through the default registry. Returns +// "" 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) +} + +// ResolveOrEnv resolves through the registry, falling back to the +// environment when no engine is configured but a key is set. This +// provides backward compatibility during migration. +func (s SecretRef) ResolveOrEnv(reg *Registry) (string, error) { + if s.Engine == "" && s.Key == "" { + return "", nil + } + if s.Engine == "" { + // Fallback: treat Key as an env var name. + if v, ok := os.LookupEnv(s.Key); ok { + return v, nil + } + return "", fmt.Errorf("secret env var %q is not set", s.Key) + } + return reg.Resolve(s) +} diff --git a/internal/secret/secret_test.go b/internal/secret/secret_test.go new file mode 100644 index 000000000..e5959fae5 --- /dev/null +++ b/internal/secret/secret_test.go @@ -0,0 +1,129 @@ +package secret + +import ( + "os" + "testing" +) + +func TestEnvEngineResolve(t *testing.T) { + os.Setenv("TEST_SECRET_KEY", "test-value") + defer os.Unsetenv("TEST_SECRET_KEY") + + e := &envEngine{} + if e.Name() != "env" { + t.Errorf("Name = %q", e.Name()) + } + if e.Version() != "1.0.0" { + t.Errorf("Version = %q", e.Version()) + } + v, err := e.Resolve("TEST_SECRET_KEY") + if err != nil { + t.Fatal(err) + } + if v != "test-value" { + t.Errorf("got %q, want test-value", v) + } +} + +func TestEnvEngineResolveMissing(t *testing.T) { + e := &envEngine{} + _, err := e.Resolve("NONEXISTENT_VAR_12345") + if err == nil { + t.Error("expected error for missing env var") + } +} + +func TestSecretRefZeroValue(t *testing.T) { + r := NewRegistry() + var s SecretRef + v, err := s.Resolve(r) + if err != nil { + t.Error(err) + } + if v != "" { + t.Errorf("zero-value SecretRef should return empty string, got %q", v) + } +} + +func TestSecretRefResolveOrEnvFallback(t *testing.T) { + os.Setenv("FALLBACK_TEST_KEY", "fallback-val") + defer os.Unsetenv("FALLBACK_TEST_KEY") + + r := NewRegistry() + s := SecretRef{Key: "FALLBACK_TEST_KEY"} // no engine → env fallback + v, err := s.ResolveOrEnv(r) + if err != nil { + t.Fatal(err) + } + if v != "fallback-val" { + t.Errorf("got %q, want fallback-val", v) + } +} + +func TestSecretRefResolveOrEnvMissing(t *testing.T) { + r := NewRegistry() + s := SecretRef{Key: "NONEXISTENT_VAR_12345"} + _, err := s.ResolveOrEnv(r) + if err == nil { + t.Error("expected error for missing env var in fallback") + } +} + +func TestRegistryRegisterAndGet(t *testing.T) { + r := NewRegistry() + e, ok := r.Get("env") + if !ok { + t.Fatal("env engine should be registered by default") + } + if e.Name() != "env" { + t.Errorf("Name = %q", e.Name()) + } +} + +func TestRegistryGetMissing(t *testing.T) { + r := NewRegistry() + _, ok := r.Get("nonexistent") + if ok { + t.Error("should not find nonexistent engine") + } +} + +func TestRegistryResolve(t *testing.T) { + os.Setenv("TEST_SECRET", "resolved") + defer os.Unsetenv("TEST_SECRET") + + r := NewRegistry() + v, err := r.Resolve(SecretRef{Engine: "env", Key: "TEST_SECRET"}) + if err != nil { + t.Fatal(err) + } + if v != "resolved" { + t.Errorf("got %q, want resolved", v) + } +} + +func TestRegistryResolveUnknownEngine(t *testing.T) { + r := NewRegistry() + _, err := r.Resolve(SecretRef{Engine: "unknown", Key: "x"}) + if err == nil { + t.Error("expected error for unknown engine") + } +} + +func TestLoadDirNonexistent(t *testing.T) { + r := NewRegistry() + n, err := r.LoadDir("/nonexistent/path/12345") + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("expected 0 loaded, got %d", n) + } +} + +func TestNewRegistryHasEnv(t *testing.T) { + r := NewRegistry() + if _, ok := r.Get("env"); !ok { + t.Error("NewRegistry must pre-register env engine") + } +}