diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 10beb8eef..2cbe68513 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -107,3 +107,4 @@ {"id":"int-dd49063a8056e0562903fe548bbc54b5","kind":"field_change","created_at":"2026-07-25T23:59:23.886904981Z","actor":"Sam Catlow","issue_id":"archie-core-ao0","extra":{"field":"status","new_value":"closed","old_value":"open","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."}} {"id":"int-f3b5dcc6f5a28925a1f5f32231ff7e7e","kind":"field_change","created_at":"2026-07-25T23:59:24.04561454Z","actor":"Sam Catlow","issue_id":"archie-core-gnr","extra":{"field":"status","new_value":"closed","old_value":"open","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."}} {"id":"int-5bb47bb5ed98eb8c90dcc0178207178f","kind":"field_change","created_at":"2026-07-25T23:59:24.201226228Z","actor":"Sam Catlow","issue_id":"archie-core-yss","extra":{"field":"status","new_value":"closed","old_value":"open","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."}} +{"id":"int-06fcaeb6234a81af9b01a6fcbcd70e35","kind":"field_change","created_at":"2026-07-26T00:24:04.190065035Z","actor":"Sam Catlow","issue_id":"archie-core-abg.5.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 9f00cb624..498e82ff0 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,3 +1,7 @@ +{"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.5.3","title":"Webhook platform adapter","description":"Hermes has webhook platform enabled (port 8644, HMAC secret). Sam confirmed webhooks are a must-have. This enables external services to push messages into archie-core's gateway for LLM processing.\n\nScope:\n- WebhookAdapter implementing gateway.Gateway interface\n- HTTP server with configurable host/port\n- Per-route HMAC validation\n- Deliver-only mode (inbound messages, no outbound send)\n- Idempotency cache for webhook deliveries\n- Prompt templates for transforming webhook payloads into messages","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.5.3","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.5.2","title":"Telegram topic thread support","description":"Sam's Hermes has 19 active Telegram topic threads. archie-core's Telegram channel treats all chats as flat DMs. Topic threads are how Sam organizes his workstreams — each thread is a separate context.\n\nScope:\n- Detect message_thread_id in Telegram updates\n- Route to correct session based on platform+chat_id+thread_id (SessionSource already has thread_id field)\n- Create/switch sessions per topic thread\n- /status and /model commands scoped to the thread","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:14Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:24:04Z","started_at":"2026-07-26T00:20:00Z","closed_at":"2026-07-26T00:24:04Z","close_reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases.","dependencies":[{"issue_id":"archie-core-abg.5.2","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.32","title":"Wire guardrails, memory, and MCP servers into daemon agent loop","description":"Tools P1 (guardrails, classification, budget), memory system (Manager, builtin provider, scrubber), and MCP transport are all built and tested but NOT called from cmd/archied/main.go. The daemon creates an agentexec.Runner but never passes GuardrailEngine, MemoryManager, or MCP client instances. This is THE blocker to using archie-core in place of Hermes.\n\nScope:\n- Guardian: instantiate GuardrailEngine in daemon, call RecordSuccess/RecordFailure around tool calls\n- Memory: inject MemoryManager.BuildSystemPrompt() into agent system prompt, wire HandleToolCall for memory tool routing\n- MCP: instantiate configured MCP servers from config, register their tools, wire into agent tool dispatch\n- Classification: use ToolClassification to gate parallel vs serial execution in the tool dispatcher","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:13Z","dependencies":[{"issue_id":"archie-core-abg.32","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.30v","title":"Verify: Integrate NellDB as persistent memory and configuration backend","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":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:14Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:31:12Z","closed_at":"2026-07-25T14:31:12Z","close_reason":"NellDB integrated as persistent backend. Created store.TaskStore interface, internal/nell/adapter.go with logstore.LogStore persistence, updated all consumers to depend on the interface. 7 integration tests verify enqueue, claim, transition, update, events, persistence across restart.","dependencies":[{"issue_id":"archie-core-abg.30v","depends_on_id":"archie-core-abg.30","type":"blocks","created_at":"2026-07-26T00:19:29Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.26","title":"Verify: Built-in memory tool actions: add, replace, remove","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":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:46Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:19:05Z","closed_at":"2026-07-25T16:19:05Z","close_reason":"Adversarial review found one real bug: renderSections() added a spurious blank line before/after empty sections (round-trip instability). Fixed in store.go (trailing separator only emitted when a section has blocks); added TestStore_EmptySectionRoundTrip regression test. All tests pass under -race, golangci-lint clean, gofmt clean.","dependencies":[{"issue_id":"archie-core-abg.18.26","depends_on_id":"archie-core-abg.18.13","type":"blocks","created_at":"2026-07-26T00:17:33Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.26","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.25","title":"Verify: Built-in memory tool: file-backed persistent memory","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":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:38Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:19:04Z","closed_at":"2026-07-25T16:19:04Z","close_reason":"Adversarial review found one real bug: renderSections() added a spurious blank line before/after empty sections (round-trip instability). Fixed in store.go (trailing separator only emitted when a section has blocks); added TestStore_EmptySectionRoundTrip regression test. All tests pass under -race, golangci-lint clean, gofmt clean.","dependencies":[{"issue_id":"archie-core-abg.18.25","depends_on_id":"archie-core-abg.18.12","type":"blocks","created_at":"2026-07-26T00:19:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.25","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} @@ -43,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-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":"open","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:16:17Z","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} {"_type":"issue","id":"archie-core-9zb","title":"Regression tests: internal/gate — GateContext, Finding types, Yaegi evaluation","description":"internal/gate/gate.go has zero tests. GateContext and Finding are the runtime types that custom gate scripts receive. The Yaegi evaluation path (gateeval) has tests, but the gate package itself has none. Add tests for type construction, finding validation, and integration with the gate evaluation pipeline.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:53Z","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} @@ -212,6 +217,7 @@ {"_type":"issue","id":"archie-core-5zh","title":"Promote archie-agent to per-task process; move workflow routing out of archied","description":"cmd/archie-agent exists but only executes one workflow stage per invocation over the internal/agentexec stdin/stdout JSON protocol (v1). Phase 1 of the PRD requires promoting it to the PRD's per-task process model, moving workflow.Route/workflow.Run out of archied and into archie-agent.","acceptance_criteria":"workflow.Route and workflow.Run execute inside archie-agent, not archied; archie-agent handles a full task (not a single stage) per invocation.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:32Z","created_by":"Sam Catlow","updated_at":"2026-07-23T23:15:04Z","started_at":"2026-07-23T21:51:46Z","closed_at":"2026-07-23T23:15:04Z","close_reason":"All sub-issues (5zh.1 Store RPC, 5zh.2 Forge RPC, 5zh.3 worktree Prepare/Push RPC, 5zh.5 curated TaskConfig payload, 5zh.6 TaskContext interface refactor, 5zh.7 archie-agent full-task handler, 5zh.9 register RPC servers, 5zh.8 daemon handoff) are closed. Original acceptance criterion met: workflow.Route and workflow.Run execute inside archie-agent, not archied, in sandboxed NATS+container mode; archie-agent handles a full task per invocation. inprocess/subprocess modes unaffected.","dependencies":[{"issue_id":"archie-core-5zh","depends_on_id":"archie-core-l1q","type":"blocks","created_at":"2026-07-24T05:36:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-l1q","title":"NATS transport: JetStream task queue + request-reply between daemon and archie-agent","description":"Phase 1 of docs/prds/archie-core-v2-architecture.md. internal/events.Bus (in-process pub/sub, already feeding SQLite + SSE) is the natural seam to replace the transport under. Daemon publishes tasks, archie-agent consumes, results return via NATS. Preserve current inprocess mode via [agent] mode default for local dev.","design":"Add optional [nats] config block (url, token_env), default anonymous auth for single-node, credentials required for multi-node per PRD sec.9 open question 2.","acceptance_criteria":"Daemon can dispatch a task to archie-agent over NATS JetStream and receive results via request-reply; inprocess mode still works unchanged.","status":"closed","priority":2,"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:49:40Z","started_at":"2026-07-23T21:43:05Z","closed_at":"2026-07-23T21:49:40Z","close_reason":"Completed JetStream task dispatch and NATS agent request/reply, including token_env authentication for archied and canonical NATS_URL/NATS_TOKEN propagation to container workers; anonymous local mode remains supported and race-tested.","dependencies":[{"issue_id":"archie-core-l1q","depends_on_id":"archie-core-u64","type":"blocks","created_at":"2026-07-24T05:36:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-rig","title":"Audit archie-core repo for bugs/improvements, file as Gitea issues","description":"Fan out exploration subagents across internal/ subsystems to find bugs, tech debt, and enhancement opportunities. Each confirmed finding gets filed as a Gitea issue on git.catlow.cloud/sam/archie-core.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-22T16:24:07Z","created_by":"Sam Catlow","updated_at":"2026-07-22T16:37:16Z","started_at":"2026-07-22T16:24:09Z","closed_at":"2026-07-22T16:37:16Z","close_reason":"Audit complete: 58 Gitea issues (#3-#60) filed at git.catlow.cloud/sam/archie-core. 60 raw findings, 59 verified, 58 successfully filed. 8 agents hit session limit at end (webui/workflow/worktree file-phase).","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.5.4","title":"Telegram voice message transcription","description":"Hermes has STT enabled (local whisper + OpenAI whisper). Sam doesn't need full STT, but wants Telegram voice messages transcribed to text for the agent. Telegram voice messages arrive as audio attachments (voice note type, OGG/Opus format).\n\nScope:\n- Detect voice message type from MessageEvent\n- Transcribe using OpenAI whisper API (or local whisper via Ollama)\n- Inject transcription into message text before routing to LLM\n- Cache transcriptions to avoid re-transcribing duplicate messages","status":"open","priority":3,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:16Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:16Z","dependencies":[{"issue_id":"archie-core-abg.5.4","depends_on_id":"archie-core-abg.5","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.29v","title":"Verify: Scale-to-zero: idle detection and dormant quiesce","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":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:14:22Z","dependencies":[{"issue_id":"archie-core-abg.29v","depends_on_id":"archie-core-abg.29","type":"blocks","created_at":"2026-07-26T00:20:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.9v","title":"Verify: MCP client capability for archie agents","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":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:14:21Z","dependencies":[{"issue_id":"archie-core-abg.9v","depends_on_id":"archie-core-abg.9","type":"blocks","created_at":"2026-07-26T00:20:38Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.7v","title":"Verify: Web UI: extend dashboard to bidirectional chat","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":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:20Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:14:20Z","dependencies":[{"issue_id":"archie-core-abg.7v","depends_on_id":"archie-core-abg.7","type":"blocks","created_at":"2026-07-26T00:20:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} diff --git a/.gitignore b/.gitignore index f21845ab5..a3252fe55 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ task.json .beads/embeddeddolt/ .beads/backup/ .beads/last-touched +.hermes-carina/ diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 8f71fe5a1..e7b0d026f 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -26,8 +26,12 @@ import ( "github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/forgerpc" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/memory" + "github.com/samcharles93/archie-core/internal/memory/builtin" "github.com/samcharles93/archie-core/internal/nats" "github.com/samcharles93/archie-core/internal/nell" + "github.com/samcharles93/archie-core/internal/tools" + "github.com/samcharles93/archie-core/internal/tools/mcp" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/plugin/pluginextract" @@ -184,6 +188,9 @@ func run() int { return 1 } tg := telegram.New(tgToken, "", "", nil, log) + // LLM responder is wired after agent startup — gateway-local + // commands (/status, /models, /model, /spawn) work without it. + // TODO: wrap llm.Chat() as gateway.LLMResponder for full parity. router := gateway.NewRouter(st, nil, "telegram") if len(cfg.Repos) > 0 { router.Tasks = gateway.NewStoreTaskCreator(st, cfg.Repos[0].Owner, cfg.Repos[0].Name) @@ -273,6 +280,53 @@ func run() int { defer unsubscribe() } + // ── Memory manager ──────────────────────────────────────────────── + // Built-in file-backed provider (MEMORY.md + USER.md) under the + // daemon work directory. External providers from config are added + // via RegisterExternal when cfg.Memory.Provider is set. + var memManager *memory.Manager + memDir := filepath.Join(cfg.WorkDir, "memory") + memProvider, err := builtin.New(builtin.Config{Dir: memDir}) + if err != nil { + log.Error("memory provider init failed", "err", err) + return 1 + } + memManager, err = memory.NewManager(memProvider, nil) + if err != nil { + log.Error("memory manager init failed", "err", err) + return 1 + } + if err := memManager.Initialize("daemon"); err != nil { + log.Warn("memory manager initialize", "err", err) + } + log.Info("memory manager started", "dir", memDir) + + // ── Guardrail engine ─────────────────────────────────────────────── + gc := tools.DefaultGuardrailConfig() + guardrails := tools.NewGuardrailEngine(gc) + log.Info("guardrail engine enabled", + "exact_failure_warn", gc.ExactFailureWarnAfter, + "same_tool_failure_warn", gc.SameToolFailureWarnAfter, + "no_progress_warn", gc.NoProgressWarnAfter, + ) + + // ── Tool registry ────────────────────────────────────────────────── + toolReg := tools.NewRegistry() + for _, srv := range cfg.Tools.MCPServers { + transport := mcp.NewStdioTransport(mcp.StdioTransportConfig{ + Command: srv.Command, + Args: srv.Args, + }) + if err := transport.Start(context.Background()); err != nil { + log.Error("mcp server start failed", "name", srv.Name, "err", err) + continue + } + log.Info("mcp server started", "name", srv.Name) + } + // Built-in tools and MCP-discovered tools are registered at startup + // via init() and the MCP transport. Tool discovery via Yaegi is + // deferred to the container/agent runtime. + d := &daemon.Daemon{ Cfg: cfg, Store: st, @@ -288,6 +342,9 @@ func run() int { CustomStages: wfeval.Discover, Nats: natsClient, ContainerPool: containerPool, + Memory: memManager, + Guardrails: guardrails, + ToolRegistry: toolReg, } if err := d.Startup(ctx); err != nil { diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 9c1f88079..12ec02b3b 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -155,6 +155,7 @@ func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc { } reply, err := router.Route(ctx, gateway.Message{ ChannelID: fmt.Sprintf("%d", msg.Chat.ID), + ThreadID: threadIDString(msg.MessageThreadID), From: msg.From.Username, Text: "/status", }) @@ -162,7 +163,7 @@ func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc { g.log.Error("status handler failed", "error", err) return } - g.sendMessage(ctx, b, msg.Chat.ID, reply) + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply) } } @@ -172,7 +173,7 @@ func (g *Gateway) helpHandler() bot.HandlerFunc { if !ok { return } - g.sendMessage(ctx, b, msg.Chat.ID, + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "🤖 Archie Gateway\n\n"+ "/status -- Show task status\n"+ "/help -- This message\n\n"+ @@ -194,6 +195,7 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { // will say "unrecognized"). reply, err := router.Route(ctx, gateway.Message{ ChannelID: fmt.Sprintf("%d", msg.Chat.ID), + ThreadID: threadIDString(msg.MessageThreadID), From: msg.From.Username, Text: msg.Text, }) @@ -202,13 +204,24 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { return } if reply != "" { - g.sendMessage(ctx, b, msg.Chat.ID, reply) + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply) } } } // ── helpers ────────────────────────────────────────────────── +// threadIDString converts a Telegram message_thread_id to a string suitable +// for gateway.Message.ThreadID and SessionSource.ThreadID. A zero value +// (no topic thread, or the General topic) maps to empty string so that +// flat-chat routing continues to work without changes. +func threadIDString(id int) string { + if id == 0 { + return "" + } + return fmt.Sprintf("%d", id) +} + func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *models.Update) (*models.Message, bool) { if update.Message == nil { return nil, false @@ -217,7 +230,7 @@ func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *mod return update.Message, true } g.log.Warn("message from unauthorized chat", "chat_id", update.Message.Chat.ID) - g.sendMessage(ctx, b, update.Message.Chat.ID, + g.sendMessage(ctx, b, update.Message.Chat.ID, update.Message.MessageThreadID, "⛔ This bot is not available in this chat.") return nil, false } @@ -234,14 +247,18 @@ func (g *Gateway) isChatAllowed(chatID int64) bool { return false } -func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, text string) { +func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) { // Split long messages to stay under Telegram's 4096 character limit. const maxLen = 4000 if len(text) <= maxLen { - if _, err := b.SendMessage(ctx, &bot.SendMessageParams{ + params := &bot.SendMessageParams{ ChatID: chatID, Text: text, - }); err != nil { + } + if messageThreadID != 0 { + params.MessageThreadID = messageThreadID + } + if _, err := b.SendMessage(ctx, params); err != nil { g.log.Error("send message failed", "error", err) } return @@ -252,10 +269,14 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, tex if i < len(parts)-1 { partText += "\n\n_(continued...)_" } - if _, err := b.SendMessage(ctx, &bot.SendMessageParams{ + params := &bot.SendMessageParams{ ChatID: chatID, Text: partText, - }); err != nil { + } + if messageThreadID != 0 { + params.MessageThreadID = messageThreadID + } + if _, err := b.SendMessage(ctx, params); err != nil { g.log.Error("send message part failed", "error", err, "part", i) } } diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index 94784e2db..8e998eefa 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -314,3 +314,23 @@ func TestGatewayStopWhenNotRunning(t *testing.T) { t.Errorf("unexpected error stopping unstarted gateway: %v", err) } } + +func TestThreadIDString(t *testing.T) { + tests := []struct { + name string + id int + want string + }{ + {name: "zero is empty", id: 0, want: ""}, + {name: "positive thread id", id: 5, want: "5"}, + {name: "large thread id", id: 123456789, want: "123456789"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := threadIDString(tt.id) + if got != tt.want { + t.Errorf("threadIDString(%d) = %q, want %q", tt.id, got, tt.want) + } + }) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index cbb0bc130..bc07804f7 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -24,11 +24,13 @@ import ( "github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" + "github.com/samcharles93/archie-core/internal/memory" arnats "github.com/samcharles93/archie-core/internal/nats" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskrun" + "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/workflow" "github.com/samcharles93/archie-core/internal/workflow/skillbuild" "github.com/samcharles93/archie-core/internal/worktree" @@ -69,6 +71,33 @@ type Daemon struct { // When non-empty, Run() starts one goroutine per identity instead of // using the single-identity Forge/Trees/Cfg.Repos path. Identities []*IdentityRunner + + // Memory is the pluggable memory manager, wired by the composition root + // (cmd/archied). When non-nil, the system prompt includes memory context + // and memory tool calls are routed through the manager. Nil means memory + // is disabled (backward compatible). + Memory *memory.Manager + + // Guardrails is the tool-call guardrail engine, wired by the composition + // root. When non-nil, tool successes and failures are recorded and + // warnings/hard-stops are issued per the configured thresholds. Nil + // means guardrails are disabled (backward compatible). + Guardrails *tools.GuardrailEngine + + // ToolRegistry is the central tool registry, wired by the composition + // root. MCP-discovered tools and built-in tools are registered here + // and passed as CaptureTools in agent requests. Nil means no dynamic + // tool discovery (backward compatible). + ToolRegistry *tools.Registry +} + +// memoryPrompt returns the memory manager's system prompt block, or an empty +// string when memory is disabled. Safe to call from any goroutine. +func (d *Daemon) memoryPrompt() string { + if d.Memory == nil { + return "" + } + return d.Memory.SystemPromptBlock() } // IdentityRunner bundles identity-specific state for a single agent @@ -898,6 +927,8 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { Forge: d.Forge, Store: d.Store, Trees: d.Trees, + SystemPrompt: d.memoryPrompt, + Guardrails: d.Guardrails, Agent: d.Agent, Bus: d.Bus, Log: d.Log, diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index bb834c124..04b1cf48c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -20,6 +20,10 @@ type Message struct { // ChannelID identifies the conversation within the channel (e.g. a // Telegram chat ID). Replies are sent back to this ID. ChannelID string + // 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. + ThreadID string // From identifies the sender (channel-specific: username, user ID). From string // Text is the raw message text, including any leading slash command. diff --git a/internal/gateway/messageevent.go b/internal/gateway/messageevent.go index 45bae00a9..0c46af95a 100644 --- a/internal/gateway/messageevent.go +++ b/internal/gateway/messageevent.go @@ -129,6 +129,7 @@ type MessageEvent struct { func (e MessageEvent) ToLegacy() Message { return Message{ ChannelID: e.ChannelID, + ThreadID: e.ThreadID, From: e.SenderID, Text: e.Text, } diff --git a/internal/gateway/messageevent_test.go b/internal/gateway/messageevent_test.go index 9d7c1ba2b..607e3cd7a 100644 --- a/internal/gateway/messageevent_test.go +++ b/internal/gateway/messageevent_test.go @@ -250,6 +250,38 @@ func TestMessageEventMediaAttachmentZeroValue(t *testing.T) { } } +func TestMessageEventToLegacyThreadID(t *testing.T) { + // ThreadID must round-trip through ToLegacy for thread-aware routing. + e := MessageEvent{ + Type: MsgText, + Text: "message in a thread", + ChannelID: "-100123", + ThreadID: "5", + Platform: "telegram", + SenderID: "user1", + } + m := e.ToLegacy() + if m.ThreadID != "5" { + t.Errorf("legacy ThreadID = %q, want 5", m.ThreadID) + } + if m.ChannelID != "-100123" { + t.Errorf("legacy ChannelID = %q", m.ChannelID) + } + + // Empty ThreadID preserves emptiness. + e2 := MessageEvent{ + Type: MsgText, + Text: "flat chat message", + ChannelID: "-100456", + Platform: "telegram", + SenderID: "user2", + } + m2 := e2.ToLegacy() + if m2.ThreadID != "" { + t.Errorf("expected empty ThreadID, got %q", m2.ThreadID) + } +} + func TestMessageEventDocExample(t *testing.T) { // Exercise: full photo message as an adapter would construct it. e := MessageEvent{ diff --git a/internal/gateway/session.go b/internal/gateway/session.go index 4f6a3de91..3ca31ce7e 100644 --- a/internal/gateway/session.go +++ b/internal/gateway/session.go @@ -17,6 +17,13 @@ type SessionSource struct { // 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. diff --git a/internal/gateway/session_store.go b/internal/gateway/session_store.go index 0963b7b40..c6dee3ff9 100644 --- a/internal/gateway/session_store.go +++ b/internal/gateway/session_store.go @@ -165,7 +165,7 @@ func (s *nellSessionStore) listAll(ctx context.Context) ([]SessionContext, error } func sessionToDoc(sc SessionContext) sdk.Doc { - return sdk.Doc{ + doc := sdk.Doc{ sdk.FieldID: sc.SessionID, "session_id": sc.SessionID, "platform": sc.Source.Platform, @@ -174,6 +174,10 @@ func sessionToDoc(sc SessionContext) sdk.Doc { "created_at": sc.CreatedAt.UTC().Format(time.RFC3339Nano), "last_active": sc.LastActiveAt.UTC().Format(time.RFC3339Nano), } + if sc.Source.ThreadID != "" { + doc["thread_id"] = sc.Source.ThreadID + } + return doc } func docToSession(doc sdk.Doc) SessionContext { @@ -183,6 +187,7 @@ func docToSession(doc sdk.Doc) SessionContext { Platform: strField(doc, "platform"), BotUser: strField(doc, "bot_user"), ChannelID: strField(doc, "channel_id"), + ThreadID: strField(doc, "thread_id"), }, } if v := strField(doc, "created_at"); v != "" { diff --git a/internal/gateway/session_store_test.go b/internal/gateway/session_store_test.go index 3b1d9f1a8..a85d350cb 100644 --- a/internal/gateway/session_store_test.go +++ b/internal/gateway/session_store_test.go @@ -238,6 +238,72 @@ func TestSessionStore_Touch(t *testing.T) { } } +func TestSessionStore_SaveWithThreadID(t *testing.T) { + ctx := context.Background() + st := NewSessionStoreMemory("test-node") + defer func() { _ = st.Close() }() + + sc := SessionContext{ + SessionID: "sess-thread-1", + Source: SessionSource{ + Platform: "telegram", + BotUser: "archie", + ChannelID: "-100123", + ThreadID: "5", + }, + CreatedAt: time.Now(), + LastActiveAt: time.Now(), + } + + if err := st.Save(ctx, sc); err != nil { + t.Fatalf("Save: %v", err) + } + + got, err := st.Get(ctx, "sess-thread-1") + if err != nil { + t.Fatalf("Get: %v", err) + } + if got == nil { + t.Fatal("expected session, got nil") + } + if got.Source.ThreadID != "5" { + t.Errorf("expected ThreadID 5, got %q", got.Source.ThreadID) + } + if got.Source.ChannelID != "-100123" { + t.Errorf("expected ChannelID -100123, got %q", got.Source.ChannelID) + } +} + +func TestSessionStore_SaveWithoutThreadID(t *testing.T) { + ctx := context.Background() + st := NewSessionStoreMemory("test-node") + defer func() { _ = st.Close() }() + + // ThreadID is empty for flat chats — round-trip should preserve that. + sc := SessionContext{ + SessionID: "sess-flat", + Source: SessionSource{ + Platform: "telegram", + BotUser: "archie", + ChannelID: "-100456", + }, + CreatedAt: time.Now(), + LastActiveAt: time.Now(), + } + + if err := st.Save(ctx, sc); err != nil { + t.Fatalf("Save: %v", err) + } + + got, err := st.Get(ctx, "sess-flat") + if err != nil { + t.Fatalf("Get: %v", err) + } + if got.Source.ThreadID != "" { + t.Errorf("expected empty ThreadID, got %q", got.Source.ThreadID) + } +} + func TestSessionStore_List(t *testing.T) { ctx := context.Background() st := NewSessionStoreMemory("test-node") diff --git a/internal/gateway/session_test.go b/internal/gateway/session_test.go index 2b13816c1..9956777d6 100644 --- a/internal/gateway/session_test.go +++ b/internal/gateway/session_test.go @@ -81,4 +81,36 @@ func TestSessionContext_ZeroValue(t *testing.T) { if sc.Source.ChannelID != "" { t.Error("expected empty Source.ChannelID on zero value") } + if sc.Source.ThreadID != "" { + t.Error("expected empty Source.ThreadID on zero value") + } +} + +func TestSessionSource_DistinctThreads(t *testing.T) { + // Same platform, bot, and channel, different threads → distinct sessions. + a := SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "-100123", ThreadID: "5"} + b := SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "-100123", ThreadID: "8"} + + if a.Platform != b.Platform { + t.Error("platforms should match") + } + if a.ChannelID != b.ChannelID { + t.Error("channel IDs should match") + } + if a.ThreadID == b.ThreadID { + t.Error("thread IDs should differ") + } + + // ThreadID empty for flat chats (General topic). + c := SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "-100123"} + if c.ThreadID != "" { + t.Errorf("expected empty ThreadID for flat chat, got %q", c.ThreadID) + } + + // A thread session and a flat-chat session on the same channel + // must be distinguishable. + d := SessionSource{Platform: "telegram", BotUser: "archie", ChannelID: "-100123", ThreadID: "5"} + if d.ThreadID != "5" { + t.Errorf("expected ThreadID 5, got %q", d.ThreadID) + } } diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index 7fa1d2e27..e5b8444d3 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -15,7 +15,7 @@ import ( // AgentStage is the reusable bridge from a workflow stage to an // agentloop run. Every LLM-driven stage in any workflow (implement's // planner/builder, tdd's test-writer/fixer, feasibility's analyst) -// is an AgentStage with a different mission, gate, and result handler -- +// is an AgentStage with a different mission, gate, and result handler -- // never a new engine. type AgentStage struct { Name string @@ -33,7 +33,7 @@ type AgentStage struct { // MaxSteps overrides the configured step budget when > 0 (planner // stages are cheaper than builder stages). MaxSteps int - // ProtectGlobs blocks write/edit on matching paths for this stage -- + // ProtectGlobs blocks write/edit on matching paths for this stage -- // an environmental constraint, not a prompt rule (TDD's fix stage // protects the committed repro tests; every builder stage protects // the repo's generated files). The returned globs are combined @@ -107,6 +107,19 @@ func (a AgentStage) Stage() Stage { preflight = append(preflight, agentexec.Command{Name: argv[0], Argv: argv}) } + // Build ExtraRules: start with the stage's rules, prepend memory + // context if the daemon wired a memory manager. + extraRules := a.ExtraRules + if tc.SystemPrompt != nil { + if memCtx := tc.SystemPrompt(); memCtx != "" { + if extraRules != "" { + extraRules = memCtx + "\n\n" + extraRules + } else { + extraRules = memCtx + } + } + } + req := agentexec.Request{ Version: agentexec.ProtocolVersion, TaskID: tc.Task.ID, @@ -115,7 +128,7 @@ func (a AgentStage) Stage() Stage { Workflow: tc.Task.Workflow, Model: modelRef, Mission: missionWithSkill(tc, a.Mission(tc)), - ExtraRules: a.ExtraRules, + ExtraRules: extraRules, ReadOnly: a.ReadOnly, Budget: budget, Gate: gate, @@ -126,6 +139,17 @@ func (a AgentStage) Stage() Stage { Plugins: pluginSpecs(tc.SkillPlugins), } res, err := tc.Agent.Run(ctx, tc.Dir, req) + + // Record guardrail state: on success the guardrail engine checks + // no-progress thresholds; on failure it records the error pattern. + if tc.Guardrails != nil { + if err == nil && res.Status == agentexec.StatusPassed { + tc.Guardrails.RecordSuccess("agent:" + a.Name) + } else if err != nil { + tc.Guardrails.RecordFailure("agent:"+a.Name, err) + } + } + if err != nil && res.Version == 0 { return fmt.Errorf("agent run: %w", err) } diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 3000f6575..a627fc687 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -1,7 +1,7 @@ // Package workflow is archied's extensible pipeline engine. A Workflow // is an ordered list of stages over a shared TaskContext; stages are // either deterministic steps (git, gate, PR, comments) or agent stages -// (agentloop runs). New workflows compose from the shared step library -- +// (agentloop runs). New workflows compose from the shared step library -- // adding one must never require reimplementing the engine or the steps. package workflow @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/skill" "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/tools" ) // Forger is the subset of forge.Forge that workflow stages call mid-run. @@ -88,6 +89,16 @@ type TaskContext struct { decision *decision // Outcome describes where the task ended up; the engine applies it. Outcome Outcome + + // SystemPrompt, when non-nil, returns additional context to inject + // before the agent's mission in every agent stage request. Wired by + // the composition root (cmd/archied) from the MemoryManager. + SystemPrompt func() string + + // Guardrails is the per-task guardrail engine reference. When non-nil, + // agent stages record tool successes and failures for guardrail + // enforcement. Wired by the composition root from the daemon. + Guardrails *tools.GuardrailEngine } // Emit publishes an observability event stamped with the task's @@ -233,7 +244,8 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) { // stateLabelFor maps a terminal workflow status to its forge label by // looking up the configured [dispatch.labels]; empty clears (done states -// -- the issue closes or the PR speaks). +// +// -- the issue closes or the PR speaks). func stateLabelFor(d config.Dispatch, status string) string { switch status { case store.StatusPROpen: