{"modulePath":"github.com/c360studio/semstreams","version":"v1.0.0-beta.162","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package agenticloop\n\nPackage agenticloop provides the agentic loop orchestrator component. It manages the state machine for agentic loops, coordinating between model calls and tool executions while capturing execution trajectories.\n\nPackage agenticloop provides the loop orchestrator for the SemStreams agentic system.\n\n### Overview {#hdr-Overview}\n\nThe agentic-loop processor orchestrates autonomous agent execution by managing the lifecycle of agentic loops. It coordinates communication between the model processor (LLM calls) and tools processor (tool execution), tracks state through a 10-state machine, supports signal handling for user control, manages context memory with automatic compaction, and appends observed trajectory facts with separately stored full evidence.\n\nThis is the central component of the agentic system - it receives task requests, routes messages between model and tools, handles iteration limits, processes control signals, manages context memory, and publishes completion events.\n\n### Architecture {#hdr-Architecture}\n\nThe loop orchestrator sits at the center of the agentic component family:\n\n\t                  ┌─────────────────┐\n\tagent.task.*  ──▶ │                 │ ──▶ agent.request.*\n\t                  │  agentic-loop   │\n\tagent.response.\u003e◀─│   (this pkg)    │◀── agent.response.*\n\t                  │                 │\n\ttool.result.\u003e  ──▶│                 │ ──▶ tool.execute.*\n\t                  │                 │\n\tagent.signal.* ──▶│                 │ ──▶ agent.complete.*\n\t                  │                 │\n\t                  │                 │ ──▶ agent.context.compaction.*\n\t                  └────────┬────────┘\n\t                           │\n\t                  ┌────────┴────────┐\n\t                  │   NATS KV       │\n\t                  │  AGENT_LOOPS    │\n\t                  │  AGENT_TRAJ...  │\n\t                  └─────────────────┘\n\n### Message Flow {#hdr-Message_Flow}\n\nA typical loop execution follows this pattern:\n\n 1. External system publishes TaskMessage to agent.task.\\*\n 2. Loop creates LoopEntity, starts Trajectory, publishes AgentRequest to agent.request.\\*\n 3. agentic-model processes request, publishes AgentResponse to agent.response.\\*\n 4. Loop receives response: - If status=\"tool\\_call\": publishes ToolCall to tool.execute.\\* for each tool - If status=\"complete\": publishes completion to agent.complete.\\* - If status=\"error\": marks loop as failed\n 5. agentic-tools executes tools, publishes ToolResult to tool.result.\\*\n 6. Loop receives tool results, when all complete: increments iteration, sends next request\n 7. Cycle repeats until complete, failed, or max iterations reached\n\n### State Machine {#hdr-State_Machine}\n\nLoops progress through ten states defined in the agentic package:\n\n\texploring → planning → architecting → executing → reviewing → complete\n\t     ↑          ↑            ↑             ↑           ↑        ↘ failed\n\t     └──────────┴────────────┴─────────────┴───────────┘         ↘ cancelled\n\t                                                                  ↘ paused\n\t                                                                   ↘ awaiting_approval\n\nStates:\n\n  - exploring: Initial state, gathering information\n  - planning: Developing approach\n  - architecting: Designing solution\n  - executing: Implementing solution\n  - reviewing: Validating results\n  - complete: Successfully finished (terminal)\n  - failed: Failed due to error or max iterations (terminal)\n  - cancelled: Cancelled by user signal (terminal)\n  - paused: Paused by user signal, can resume\n  - awaiting\\_approval: Waiting for user approval\n\nStates are fluid checkpoints - the loop can transition backward (e.g., from executing back to exploring) to support agent rethinking. Only terminal states (complete, failed, cancelled) prevent further transitions.\n\nState transitions are managed by the LoopManager and persisted to NATS KV.\n\n### Signal Handling {#hdr-Signal_Handling}\n\nThe loop accepts control signals via the agent.signal.\\* input port:\n\n\tsignal := agentic.UserSignal{\n\t    SignalID:    \"sig_abc123\",\n\t    Type:        \"cancel\",  // cancel, pause, resume, approve, reject, feedback, retry\n\t    LoopID:      \"loop_456\",\n\t    UserID:      \"user_789\",\n\t    ChannelType: \"cli\",\n\t    ChannelID:   \"session_001\",\n\t    Timestamp:   time.Now(),\n\t}\n\nSignal types and their effects:\n\n  - cancel: Stop execution immediately, transition to cancelled state\n  - pause: Pause at next checkpoint, transition to paused state\n  - resume: Continue paused loop, restore previous state\n  - approve: Approve pending result, transition to complete\n  - reject: Reject with optional reason, transition to failed\n  - feedback: Add feedback without decision, no state change\n  - retry: Retry failed loop, transition to exploring\n\n### Context Management {#hdr-Context_Management}\n\nThe loop includes automatic context memory management to handle long-running conversations that approach model token limits.\n\nContext is organized into priority regions (lower priority evicted first):\n\n 1. tool\\_results (priority 1) - Tool execution results, GC'd by age\n 2. recent\\_history (priority 2) - Recent conversation messages\n 3. hydrated\\_context (priority 3) - Retrieved context from memory\n 4. compacted\\_history (priority 4) - Summarized old conversation\n 5. system\\_prompt (priority 5) - Never evicted\n\nConfiguration:\n\n\tcontext := agenticloop.ContextConfig{\n\t    Enabled:            true,\n\t    CompactThreshold:   0.60,  // Trigger compaction at 60% utilization\n\t    HeadroomTokens:     6400,  // Reserve tokens for new content\n\t}\n\nModel context limits are resolved from the unified model registry (component.Dependencies.ModelRegistry). If a model is not found in the registry, DefaultContextLimit (128000) is used as fallback.\n\nContext events are published to agent.context.compaction.\\*:\n\n  - compaction\\_starting: Context approaching limit, compaction starting\n  - compaction\\_complete: Compaction finished, includes tokens saved\n\n### Component Architecture {#hdr-Component_Architecture}\n\nThe package is organized into three main components:\n\n\\*\\*LoopManager\\*\\* - Manages loop entity lifecycle:\n\n\tmanager := NewLoopManager()\n\n\t// Create a loop\n\tloopID, err := manager.CreateLoop(\"task_123\", \"general\", \"gpt-4\", 20)\n\n\t// State transitions\n\terr = manager.TransitionLoop(loopID, agentic.LoopStateExecuting)\n\n\t// Iteration tracking\n\terr = manager.IncrementIteration(loopID)\n\n\t// Pending tool management\n\tmanager.AddPendingTool(loopID, \"call_001\")\n\tmanager.RemovePendingTool(loopID, \"call_001\")\n\tallDone := manager.AllToolsComplete(loopID)\n\n\t// Context management\n\tcm := manager.GetContextManager(loopID)\n\n\\*\\*Trajectory observations\\*\\* - The component keeps transient execution detail internally while a loop is active. It exposes no aggregate manager or read API. Durable reads come from bounded TrajectoryFactV1 observations; full TrajectoryEvidenceV1 bodies live in the configured registered Store.\n\n\\*\\*MessageHandler\\*\\* - Routes and processes messages:\n\n\thandler := NewMessageHandler(config)\n\n\t// Handle incoming task\n\tresult, err := handler.HandleTask(ctx, TaskMessage{\n\t    TaskID: \"task_123\",\n\t    Role:   \"general\",\n\t    Model:  \"gpt-4\",\n\t    Prompt: \"Analyze this code for bugs\",\n\t})\n\n\t// Handle model response\n\tresult, err = handler.HandleModelResponse(ctx, loopID, response)\n\n\t// Handle tool result\n\tresult, err = handler.HandleToolResult(ctx, loopID, toolResult)\n\n### Configuration {#hdr-Configuration}\n\nThe processor is configured via JSON:\n\n\t{\n\t    \"max_iterations\": 20,\n\t    \"timeout\": \"120s\",\n\t    \"stream_name\": \"AGENT\",\n\t    \"loops_bucket\": \"AGENT_LOOPS\",\n\t    \"trajectory_evidence_storage_instance\": \"objectstore\",\n\t    \"context\": {\n\t        \"enabled\": true,\n\t        \"compact_threshold\": 0.60,\n\t        \"headroom_tokens\": 6400,\n\t    },\n\t    \"ports\": {\n\t        \"inputs\": [...],\n\t        \"outputs\": [...]\n\t    }\n\t}\n\nConfiguration fields:\n\n  - max\\_iterations: Maximum loop iterations before failure (default: 20, range: 1-1000)\n  - timeout: Loop execution timeout as duration string (default: \"120s\")\n  - stream\\_name: JetStream stream name for agentic messages (default: \"AGENT\")\n  - loops\\_bucket: NATS KV bucket for loop state (default: \"AGENT\\_LOOPS\")\n  - trajectory\\_evidence\\_storage\\_instance: Registered Store instance for full evidence (default: \"objectstore\")\n  - consumer\\_name\\_suffix: Optional suffix for JetStream consumer names (for testing)\n  - context: Context management configuration (see ContextConfig)\n  - ports: Port configuration for inputs and outputs\n\n### Ports {#hdr-Ports}\n\nInput ports (JetStream consumers):\n\n  - agent.task: Task requests from external systems (subject: agent.task.\\*)\n  - agent.response: Model responses from agentic-model (subject: agent.response.\u003e)\n  - tool.result: Tool results from agentic-tools (subject: tool.result.\u003e)\n  - agent.signal: Control signals for loops (subject: agent.signal.\\*)\n  - trajectory\\_query: Observed fact queries (subject: agentic.query.trajectory)\n\nOutput ports (JetStream publishers):\n\n  - agent.request: Model requests to agentic-model (subject: agent.request.\\*)\n  - tool.execute: Tool execution requests to agentic-tools (subject: tool.execute.\\*)\n  - agent.complete: Loop completion events (subject: agent.complete.\\*)\n  - agent.context.compaction: Context compaction events (subject: agent.context.compaction.\\*)\n\nKV write ports:\n\n  - loops: Loop entity state (bucket: AGENT\\_LOOPS)\n  - trajectories: Immutable TrajectoryFactV1 observations (bucket: AGENT\\_TRAJECTORIES)\n\n### KV Storage {#hdr-KV_Storage}\n\nLoop state and observed trajectory facts are persisted to NATS KV:\n\n\\*\\*AGENT\\_LOOPS bucket\\*\\*: Stores LoopEntity as JSON, keyed by loop ID\n\n\t{\n\t    \"id\": \"loop_123\",\n\t    \"task_id\": \"task_456\",\n\t    \"state\": \"executing\",\n\t    \"role\": \"general\",\n\t    \"model\": \"gpt-4\",\n\t    \"iterations\": 3,\n\t    \"max_iterations\": 20,\n\t    \"parent_loop_id\": \"\",\n\t    \"pause_requested\": false,\n\t    \"user_id\": \"user_789\",\n\t    \"channel_type\": \"cli\",\n\t    \"channel_id\": \"session_001\"\n\t}\n\n\\*\\*COMPLETE\\_{loopID}\\*\\*: Written when a loop completes, for rules engine consumption\n\n\t{\n\t    \"loop_id\": \"loop_123\",\n\t    \"task_id\": \"task_456\",\n\t    \"outcome\": \"success\",\n\t    \"role\": \"architect\",\n\t    \"result\": \"Designed authentication system...\",\n\t    \"model\": \"gpt-4\",\n\t    \"iterations\": 3,\n\t    \"parent_loop\": \"\"\n\t}\n\n\\*\\*AGENT\\_TRAJECTORIES bucket\\*\\*: Stores immutable TrajectoryFactV1 JSON at v1.\\\u003cbase32-sha256(loop-id)\u003e.\\\u003cattempt-id\u003e. It uses history 1 and no TTL. Readers prefix-list visible facts, validate them, causally sort them, and report only coverage=\"observed\" plus observed totals.\n\n\t{\n\t    \"schema_version\": \"v1\",\n\t    \"loop_digest\": \"\u003csha256\u003e\",\n\t    \"attempt_id\": \"01J...\",\n\t    \"attempt_ordinal\": 3,\n\t    \"kind\": \"model.completed\",\n\t    \"causal_iteration\": 2,\n\t    \"causal_phase\": \"model_result\",\n\t    \"evidence_capture\": \"stored\",\n\t    \"evidence\": {\"storage_instance\":\"objectstore\", \"key\":\"trajectory-evidence/v1/sha256/\u003csha256\u003e\"}\n\t}\n\nFull prompts, messages, tool arguments/results, URLs, and raw errors live in content-addressed TrajectoryEvidenceV1 bodies borrowed through StoreRegistry.\n\n### Rules/Workflow Integration {#hdr-Rules_Workflow_Integration}\n\nThe loop integrates with the rules engine for orchestration:\n\n 1. On completion, writes COMPLETE\\_{loopID} key to KV\n 2. Rules engine watches COMPLETE\\_\\* keys\n 3. Rules can trigger follow-up actions (e.g., spawn editor when architect completes)\n\nArchitect/Editor pattern:\n\n 1. Task arrives with role=\"architect\"\n 2. Architect loop executes and produces a plan\n 3. On completion, COMPLETE\\_{loopID} written with role=\"architect\"\n 4. Rule matches COMPLETE\\_\\* where role=\"architect\"\n 5. Rule spawns new loop with role=\"editor\", parent\\_loop={loopID}\n 6. Editor receives architect's output as context\n\n### Quick Start {#hdr-Quick_Start}\n\nCreate and start the component:\n\n\tconfig := agenticloop.Config{\n\t    MaxIterations:      20,\n\t    Timeout:            \"120s\",\n\t    StreamName:         \"AGENT\",\n\t    LoopsBucket: \"AGENT_LOOPS\",\n\t    Context:    agenticloop.DefaultContextConfig(),\n\t}\n\n\trawConfig, _ := json.Marshal(config)\n\tcomp, err := agenticloop.NewComponent(rawConfig, deps)\n\n\tlc := comp.(component.LifecycleComponent)\n\tlc.Initialize()\n\tlc.Start(ctx)\n\tshutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer shutdownCancel()\n\t_ = lc.Stop(shutdownCtx)\n\nPublish a task:\n\n\ttask := agenticloop.TaskMessage{\n\t    TaskID: \"analyze_code\",\n\t    Role:   \"general\",\n\t    Model:  \"gpt-4\",\n\t    Prompt: \"Review main.go for security issues\",\n\t}\n\ttaskData, _ := json.Marshal(task)\n\tnatsClient.PublishToStream(ctx, \"agent.task.review\", taskData)\n\n### Thread Safety {#hdr-Thread_Safety}\n\nThe LoopManager, internal active-loop detail, and ContextManager are thread-safe, using RWMutex for concurrent access. Multiple goroutines can safely:\n\n  - Create and manage different loops concurrently\n  - Read loop state while other loops are being modified\n  - Track pending tools across concurrent tool executions\n  - Add messages to context regions\n\nThe Component itself is not designed for concurrent Start/Stop calls.\n\n### Error Handling {#hdr-Error_Handling}\n\nErrors are handled at multiple levels:\n\n  - Validation errors: Returned immediately from handlers\n  - State transition errors: Logged, loop may continue or fail depending on severity\n  - Max iterations: Loop transitions to failed state, not returned as error\n  - KV persistence errors: Logged but don't block message processing\n  - Context cancellation: Propagated up, handlers check ctx.Err() early\n\n### Observability {#hdr-Observability}\n\nThe component provides observability through:\n\n  - Structured logging (slog) for all significant events\n  - Append-only observed facts with full evidence stored by digest and returned by reference only\n  - Context events for memory management visibility\n  - Health status via Health() method\n  - Flow metrics via DataFlow() method\n\n### Testing {#hdr-Testing}\n\nFor testing, use the ConsumerNameSuffix config option to create unique JetStream consumer names per test:\n\n\tconfig := agenticloop.Config{\n\t    StreamName:         \"AGENT\",\n\t    ConsumerNameSuffix: \"test-\" + t.Name(),\n\t    // ...\n\t}\n\nThis prevents consumer name conflicts when running tests in parallel.\n\n### Limitations {#hdr-Limitations}\n\nCurrent limitations:\n\n  - No streaming support for partial responses\n  - Trajectory facts are internally bounded below 8 KiB; full evidence requires a registered Store\n  - No built-in retry for failed tool executions\n  - Context summarization requires LLM call (cost consideration)\n\n### See Also {#hdr-See_Also}\n\nRelated packages:\n\n  - agentic: Shared types (LoopEntity, AgentRequest, UserSignal, etc.)\n  - processor/agentic-model: LLM endpoint integration\n  - processor/agentic-tools: Tool execution framework\n  - processor/agentic-dispatch: User message routing\n  - processor/workflow: Multi-step orchestration\n\nPackage agenticloop — subject-mode tool-call governance dispatcher (ADR-039).\n\nThe dispatcher sits between the model's tool-call response and the loop's serial-dispatch fan-out. It implements three modes per ToolCallGovernanceConfig.Mode:\n\n  - disabled: pass-through. All calls return as approved without publishing. No governance gate active. (Beta.70 retired the beta.67+68 in-process ToolCallFilter wiring; subject-mode is now the sole governance path.)\n  - audit: publishes each proposed call to agent.toolcall.proposed.\\* but returns all calls as approved IMMEDIATELY. Verdicts that arrive later are recorded for observability only. Shadow mode for rule development.\n  - enforce: subscribes-then-publishes per ADR-039 race-fix option 3 (per-call waiter registration BEFORE publish), waits up to ToolCallGovernanceConfig.Timeout for a per-call verdict, and returns approved/rejected sets. Fail-closed on timeout.\n\n### Race-condition fix: subscribe before publish {#hdr-Race_condition_fix__subscribe_before_publish}\n\nJetStream consumer binding is async with publish. If the rule processor fires faster than the loop's verdict subscription binds, the verdict can be published to a subject with no subscribers, the loop times out, the call fails — same class as the natsclient handler-error payload convention bug.\n\nFix: the Component sets up a SINGLE wildcard subscription to \\`agent.toolcall.approved.\u003e\\` and \\`agent.toolcall.rejected.\u003e\\` at Start. The dispatcher REGISTERS per-call waiter channels in-process BEFORE publishing the proposed call. The wildcard subscription is bound before any task arrives, and the in-process waiter registration is synchronous with the publish call. Verdicts that arrive demux by call\\_id (trailing path segment) into the registered waiter channel.\n\n### Approved subject shape (ADR-039 open question 1) {#hdr-Approved_subject_shape__ADR_039_open_question_1_}\n\nImplementations consume verdict subjects of the shape \\`agent.toolcall.{approved,rejected}.\\\u003cloop\\_id\u003e.\\\u003ccall\\_id\u003e\\`. The call\\_id is the trailing path segment. Operators templating verdict subjects in their rule actions are expected to use \\`$message.loop\\_id.$message.call\\_id\\`; ADR-039 §\"Implementation\" lists this contract.\n\nPackage agenticloop — task in-flight visibility (gh#733).\n\nPackage agenticloop provides Prometheus metrics for agentic-loop component.\n\n## Constants\n\n```go\nconst (\n\tToolCallGovernanceModeDisabled = \"disabled\"\n\tToolCallGovernanceModeAudit    = \"audit\"\n\tToolCallGovernanceModeEnforce  = \"enforce\"\n)\n```\nTool-call governance mode constants. ADR-039.\n\nDisabled is the default — no publish to the proposed subject, direct dispatch. The in-process ToolCallFilter wiring beta.67+68 shipped was retired in beta.70; subject-mode is now the sole governance path.\n\nAudit publishes proposed tool calls to the proposed subject and dispatches IMMEDIATELY without waiting for a verdict — shadow mode for operators developing governance rules without blocking production tool-call flow. Verdicts that arrive later are counted for observability only.\n\nEnforce subscribes-then-publishes, waits up to ToolCallGovernance.Timeout for a per-call verdict, and dispatches on approve / fails on reject / fail-closed on timeout. The default 1s timeout is deliberately generous for beta.69 to surface real p99 latency before tightening in beta.70.\n\n```go\nconst (\n\t// InFlightUnknownNoConsumer — this deployment binds no agentic-loop consumer\n\t// for the requested subject. NOT \"nothing is in flight\": there may be work\n\t// on the stream that nobody here is answering for.\n\tInFlightUnknownNoConsumer = \"inflight_unknown_no_consumer\"\n\t// InFlightUnknownUnreadable — a consumer is bound but its outstanding-work\n\t// bookkeeping could not be read on this attempt.\n\tInFlightUnknownUnreadable = \"inflight_unknown_unreadable\"\n)\n```\nBounded reasons an in-flight answer is UNKNOWN.\n\n```go\nconst DefaultContextLimit = 128000\n```\nDefaultContextLimit is the fallback context window size when the model is unknown.\n\n```go\nconst DefaultDeployment = \"default\"\n```\nDefaultDeployment is the address token for a loop configured with no ConsumerNameSuffix.\n\n```go\nconst DefaultToolCallGovernanceTimeout = \"1s\"\n```\nDefaultToolCallGovernanceTimeout is the wait window for a per-call verdict in enforce mode before the dispatcher fails-closed (treats the absence of a verdict as a reject). 1s is generous for beta.69 to surface real p99 latency; tightens after measurement in beta.70 per ADR-039 §\"Observability\".\n\n```go\nconst InFlightQuerySubjectPrefix = \"agentic.query.inflight\"\n```\nInFlightQuerySubjectPrefix is the root of the in-flight request/reply subject. The full subject is deployment-addressed — see InFlightQuerySubjectFor.\n\n## Variables\n\n```go\nvar (\n\t// ErrInFlightUnknownNoConsumer — see InFlightUnknownNoConsumer.\n\tErrInFlightUnknownNoConsumer = \u0026errs.ClassifiedError{\n\t\tClass:   errs.ErrorTransient,\n\t\tCode:    InFlightUnknownNoConsumer,\n\t\tMessage: InFlightUnknownNoConsumer,\n\t}\n\t// ErrInFlightUnknownUnreadable — see InFlightUnknownUnreadable.\n\tErrInFlightUnknownUnreadable = \u0026errs.ClassifiedError{\n\t\tClass:   errs.ErrorTransient,\n\t\tCode:    InFlightUnknownUnreadable,\n\t\tMessage: InFlightUnknownUnreadable,\n\t}\n)\n```\nSentinels for the unknown reasons, matchable with errors.Is (ADR-060).\n\nThese exist so a caller branches on identity, never on message text. They also survive the request/reply wire: natsclient's ClassifyReply reconstructs the Code on the far side, so errors.Is resolves for an out-of-process caller exactly as it does in-process — which matters because out-of-process is the caller this query was shaped for.\n\n```go\nvar ErrGovernancePublishFailed = errors.New(\"governance publish failed\")\n```\nErrGovernancePublishFailed is returned by Propose only when the dispatcher is unable to make any forward progress at all — currently unused (per-call publish failures are recorded as per-call rejections). Reserved for a future architectural failure mode that short-circuits the entire batch.\n\n```go\nvar ErrMalformedTodoRecord = errors.New(\"malformed todo record\")\n```\nErrMalformedTodoRecord classifies a TodoReader failure caused by any invalid agent.todo.record triple. The reader returns no partial list with this error.\n\n```go\nvar ErrMaxIterationsReached = agentic.ErrMaxIterationsReached\n```\nErrMaxIterationsReached is the typed sentinel returned by HandleModelResponse when a loop's iteration counter has already met or exceeded its configured budget when the next model response arrives (gh#529). Component.handleResponseMessage matches it via errors.Is — never string matching — and maps it to the uniform loop-terminal failure reason \"max\\_iterations\", the same reason handleToolsComplete's tool-drain path already publishes when the budget is exhausted while tools are still in flight. Before this sentinel, the model-response path fell through to the generic \"handler\\_error\" reason, forcing reactive rules to string-match error text to detect budget exhaustion.\n\nAliases agentic.ErrMaxIterationsReached — LoopEntity.IncrementIteration (agentic/state.go) returns that same sentinel on the tool-drain path (handleToolsComplete below), and the import direction only works agentic → agenticloop, so this package re-exports the canonical value instead of declaring its own distinct error. Both detection paths therefore compare against the exact same sentinel via errors.Is.\n\n## Functions\n\n```go\nfunc BuildIterationBudgetMessage(iteration, maxIterations int) agentic.ChatMessage\n```\nBuildIterationBudgetMessage creates a system message informing the model of its iteration budget. Tone escalates as the budget is consumed: neutral at ≤50%, a nudge to wrap up at 51-75%, and urgent at \u003e75%.\n\n```go\nfunc BuildTodoStateMessage(todos []TodoState) agentic.ChatMessage\n```\nBuildTodoStateMessage formats the current todo list as a system message the agent sees at the top of its iteration. Empty list returns the zero ChatMessage (handler skips appending).\n\nFormat is compact and mirrors Claude Code's TodoWrite display: per-status marker + content, one per line. Operators reading the prompt see what the agent sees.\n\n```go\nfunc InFlightQuerySubjectFor(deployment string) string\n```\nInFlightQuerySubjectFor returns the subject that addresses ONE deployment's in-flight answer.\n\nThe subject must carry deployment identity. \\`SubscribeForRequests\\` uses a plain \\`conn.Subscribe\\`, so a single shared subject means every agentic-loop in the NATS account receives the request and replies, and the requester keeps whichever reply arrives first. That is a silently-wrong answer from an arbitrary deployment — precisely the permissive failure this API exists to remove.\n\n\\`deployment\\` is the loop's ConsumerNameSuffix, and that is the correct discriminator rather than a new invented one: the suffix already determines WHICH durable consumer exists. Two loops sharing a suffix bind the SAME consumer, so they necessarily report the same outstanding count and either may answer; two loops with different suffixes are different deployments and now occupy different subjects. The addressing therefore matches the thing actually being measured.\n\nThe empty suffix maps to DefaultDeployment for the same reason — loops with no suffix share one consumer and so share one answer.\n\nThis is a SELECTOR the operator configures on both sides, not a derived internal name: the caller states which deployment it is asking about, which is inherent to the question. It never has to know the consumer name, the stream, or the sanitizing rules.\n\n```go\nfunc NewComponent(rawConfig json.RawMessage, deps component.Dependencies) (component.Discoverable, error)\n```\nNewComponent creates a new agentic-loop component\n\n```go\nfunc Register(registry *component.Registry) error\n```\nRegister registers the agentic-loop component factory with the registry\n\n## Types\n\n```go\ntype ApprovalTimeoutCandidate struct {\n\tLoopID      string\n\tCallID      string\n\tToolName    string\n\tRequestedAt time.Time\n\tTimeout     time.Duration\n}\n```\nApprovalTimeoutCandidate captures the loop+call coordinates the approval-timeout sweeper needs to publish an auto-rejection. The sweeper builds an agentic.ApprovalResponse from these and feeds it through HandleApprovalResponse — same code path a real human rejection would take.\n\n```go\ntype CompactionResult struct {\n\tSummary       string\n\tEvictedTokens int\n\tNewTokens     int\n\tModel         string // model used for summarization (empty if stub fallback)\n}\n```\nCompactionResult contains the results of a compaction operation.\n\n```go\ntype Compactor struct {\n\t// contains filtered or unexported fields\n}\n```\nCompactor handles context compaction operations.\n\n```go\nfunc NewCompactor(config ContextConfig, opts ...CompactorOption) *Compactor\n```\nNewCompactor creates a new compactor. Variadic opts allow optional injection of a Summarizer and logger without breaking existing callers.\n\n```go\nfunc (c *Compactor) Compact(ctx context.Context, cm *ContextManager) (CompactionResult, error)\n```\nCompact performs compaction on the context manager. When a Summarizer is injected, it calls the LLM to generate a real summary. If the summarizer returns an error, it falls back to a stub summary and logs a warning.\n\n```go\nfunc (c *Compactor) ShouldCompact(cm *ContextManager) bool\n```\nShouldCompact delegates to the context manager's ShouldCompact.\n\n```go\ntype CompactorOption func(*Compactor)\n```\nCompactorOption is a functional option for configuring a Compactor.\n\n```go\nfunc WithCompactorLogger(l *slog.Logger) CompactorOption\n```\nWithCompactorLogger sets the logger used by the Compactor.\n\n```go\nfunc WithModelName(name string) CompactorOption\n```\nWithModelName sets the resolved model name reported in CompactionResult.\n\n```go\nfunc WithSummarizer(s Summarizer) CompactorOption\n```\nWithSummarizer injects an LLM-backed summarizer into the Compactor. When set, Compact() calls the summarizer instead of the stub fallback.\n\n```go\ntype Component struct {\n\t// contains filtered or unexported fields\n}\n```\nComponent implements the agentic-loop processor\n\n```go\nfunc (c *Component) ConfigSchema() component.ConfigSchema\n```\nConfigSchema returns the configuration schema\n\n```go\nfunc (c *Component) DataFlow() component.FlowMetrics\n```\nDataFlow returns current data flow metrics\n\n```go\nfunc (c *Component) Health() component.HealthStatus\n```\nHealth returns current health status\n\n```go\nfunc (c *Component) Initialize() error\n```\nInitialize prepares the component (no-op for this component)\n\n```go\nfunc (c *Component) InputPorts() []component.Port\n```\nInputPorts returns input port definitions\n\n```go\nfunc (c *Component) Meta() component.Metadata\n```\nMeta returns component metadata\n\n```go\nfunc (c *Component) OutputPorts() []component.Port\n```\nOutputPorts returns output port definitions\n\n```go\nfunc (c *Component) Start(ctx context.Context) (startErr error)\n```\nStart starts the component. The context is used for cancellation during startup operations.\n\n```go\nfunc (c *Component) Stop(ctx context.Context) error\n```\nStop stops the component within the given timeout.\n\n```go\ntype Config struct {\n\tMaxIterations                     int                      `json:\"max_iterations\" schema:\"type:int,description:Maximum number of iterations before loop terminates,default:20,min:1,max:1000,category:basic,required\"`\n\tTimeout                           string                   `json:\"timeout\" schema:\"type:string,description:Timeout duration for loop execution (e.g. 120s or 5m),default:120s,category:basic,required\"`\n\tStreamName                        string                   `json:\"stream_name\" schema:\"type:string,description:JetStream stream name,default:AGENT,category:advanced\"`\n\tConsumerNameSuffix                string                   `json:\"consumer_name_suffix\" schema:\"type:string,description:Suffix for consumer names,category:advanced\"`\n\tLoopsBucket                       string                   `json:\"loops_bucket\" schema:\"type:string,description:NATS KV bucket name for storing loop state,default:AGENT_LOOPS,category:advanced,required\"`\n\tToolResultMaxBytes                int                      `json:\"tool_result_max_bytes,omitempty\" schema:\"type:int,description:Maximum bytes for tool result content before truncation. 0 means no limit,default:32768,category:advanced\"`\n\tTrajectoryEvidenceStorageInstance string                   `json:\"trajectory_evidence_storage_instance,omitempty\" schema:\"type:string,description:Logical registered storage instance for full trajectory evidence,default:objectstore,category:advanced\"`\n\tApprovalTimeoutStr                string                   `json:\"approval_timeout,omitempty\" schema:\"type:string,description:Auto-reject pending approvals after this duration (e.g. 5m or 1h). Empty means wait indefinitely,category:advanced\"`\n\tConsumer                          ConsumerConfig           `json:\"consumer\" schema:\"type:object,description:JetStream consumer tuning for long-running ports (agent.task/agent.response/tool.result),category:advanced\"`\n\tContext                           ContextConfig            `json:\"context\" schema:\"type:object,description:Context window management. Model limits are resolved from the model registry,category:advanced\"`\n\tToolCallGovernance                ToolCallGovernanceConfig `json:\"tool_call_governance,omitempty\" schema:\"type:object,description:Subject-mode tool-call governance (ADR-039). Default mode=disabled is no-op (no governance gate),category:advanced\"`\n\t// SynthesizeTerminalOnCompletion enables the framework to synthesize a\n\t// decide(needs_clarification) when a loop completes without a terminal\n\t// tool call (#133). Cheap-model substrate recovery: when a small model\n\t// returns text-only at completion despite persona prose enforcing a\n\t// decide call, the framework stamps coordinator.next_action +\n\t// coordinator.decision.reason + coordinator.decision.synthetic=\"true\"\n\t// on the loop entity so existing recovery rules match. Default false\n\t// for back-compat — new deployments targeting cheap-model substrates\n\t// should opt in.\n\tSynthesizeTerminalOnCompletion bool                  `json:\"synthesize_terminal_on_completion,omitempty\" schema:\"type:bool,description:Synthesize decide(needs_clarification) when a loop completes without a terminal tool call (#133). Belt-and-suspenders recovery for cheap-model substrates where models occasionally return text-only at completion despite persona prose,default:false,category:advanced\"`\n\tPorts                          *component.PortConfig `json:\"ports,omitempty\" schema:\"type:ports,description:Port configuration for inputs and outputs,category:basic\"`\n}\n```\nConfig represents the configuration for the agentic-loop processor\n\n```go\nfunc DefaultConfig() Config\n```\nDefaultConfig returns the default configuration\n\n```go\nfunc (c Config) ApprovalTimeout() time.Duration\n```\nApprovalTimeout returns the parsed duration for ApprovalTimeoutStr. Returns zero (wait indefinitely) when unset or unparseable; the validation step is the safety net for malformed input.\n\n```go\nfunc (c Config) Validate() error\n```\nValidate validates the configuration\n\n```go\ntype ConsumerConfig struct {\n\tAckWait           string `json:\"ack_wait,omitempty\" schema:\"type:string,description:AckWait duration for long-running consumers (e.g. 90s or 5m),default:90s,category:advanced\"`\n\tHeartbeatInterval string `json:\"heartbeat_interval,omitempty\" schema:\"type:string,description:InProgress heartbeat interval (e.g. 60s or 2m). Must be less than ack_wait,default:60s,category:advanced\"`\n\tMaxDeliver        int    `json:\"max_deliver,omitempty\" schema:\"type:int,description:Maximum redelivery attempts for long-running consumers,default:2,min:1,max:10,category:advanced\"`\n}\n```\nConsumerConfig holds JetStream consumer tuning for long-running ports. Deployments with slow LLMs (local Ollama, constrained GPUs) should increase ack\\_wait and heartbeat\\_interval to prevent premature redelivery.\n\n```go\nfunc DefaultConsumerConfig() ConsumerConfig\n```\nDefaultConsumerConfig returns the default consumer configuration. These defaults match the original hardcoded values.\n\n```go\nfunc (c *ConsumerConfig) EnsureDefaults()\n```\nEnsureDefaults fills zero-valued fields with defaults.\n\n```go\nfunc (c ConsumerConfig) ParsedAckWait() time.Duration\n```\nParsedAckWait returns AckWait as a time.Duration. Caller must validate first.\n\n```go\nfunc (c ConsumerConfig) ParsedHeartbeatInterval() time.Duration\n```\nParsedHeartbeatInterval returns HeartbeatInterval as a time.Duration. Caller must validate first.\n\n```go\nfunc (c ConsumerConfig) Validate() error\n```\nValidate validates the consumer configuration.\n\n```go\ntype ContextConfig struct {\n\tEnabled          bool    `json:\"enabled\" description:\"Deprecated: context management is always enabled (required for Gemini compatibility)\"`\n\tCompactThreshold float64 `json:\"compact_threshold\" description:\"Utilization threshold (0.01-1.0) that triggers context compaction\"`\n\tHeadroomRatio    float64 `json:\"headroom_ratio\" description:\"Fraction of model context to reserve for responses (0.0-0.5). Takes precedence over headroom_tokens when the computed value is larger\"`\n\tHeadroomTokens   int     `json:\"headroom_tokens\" description:\"Minimum token headroom floor — ratio-based headroom never goes below this value\"`\n\t// Multi-agent context budget fields\n\tMaxBudgetTokens  int      `json:\"max_budget_tokens,omitempty\" description:\"Hard token limit for context budget (overrides model limits when set)\"`\n\tSliceOnBudget    bool     `json:\"slice_on_budget,omitempty\" description:\"Enable context slicing when budget is exceeded\"`\n\tPreserveEntities []string `json:\"preserve_entities,omitempty\" description:\"Entity IDs to always keep in context during slicing\"`\n\tEntityPriority   int      `json:\"entity_priority,omitempty\" description:\"Priority for entity context vs conversation (1-10, higher = more entity context)\"`\n}\n```\nContextConfig represents configuration for context memory management. Model context limits are resolved from the unified model registry (component.Dependencies.ModelRegistry).\n\n```go\nfunc DefaultContextConfig() ContextConfig\n```\nDefaultContextConfig returns the default context configuration\n\n```go\nfunc (c *ContextConfig) EnsureDefaults()\n```\nEnsureDefaults fills zero-valued fields with defaults. This is needed because json.Unmarshal overwrites nested structs even when the JSON contains zero values (e.g., \"compact\\_threshold\": 0).\n\n```go\nfunc (c ContextConfig) Validate() error\n```\nValidate validates the context configuration. Context management is always enabled; the Enabled field is deprecated.\n\n```go\ntype ContextManager struct {\n\t// contains filtered or unexported fields\n}\n```\nContextManager manages conversation context with memory optimization\n\n```go\nfunc NewContextManager(loopID, model string, config ContextConfig, opts ...ContextManagerOption) *ContextManager\n```\nNewContextManager creates a new context manager\n\n```go\nfunc (cm *ContextManager) AddGraphEntityContext(entityID string, content string) error\n```\nAddGraphEntityContext adds context from graph entities to the dedicated region\n\n```go\nfunc (cm *ContextManager) AddMessage(region RegionType, msg agentic.ChatMessage) error\n```\nAddMessage adds a message to a specific region\n\n```go\nfunc (cm *ContextManager) AdvanceIteration()\n```\nAdvanceIteration moves to the next iteration. Call this after processing each loop iteration to ensure proper age tracking for GC.\n\n```go\nfunc (cm *ContextManager) CheckBudget(budgetTokens int) (bool, int)\n```\nCheckBudget checks if current context is within the token budget. Returns (withinBudget, currentTokens).\n\n```go\nfunc (cm *ContextManager) ClearGraphEntities()\n```\nClearGraphEntities clears the graph entities region\n\n```go\nfunc (cm *ContextManager) GetContext() []agentic.ChatMessage\n```\nGetContext returns all messages in region priority order\n\n```go\nfunc (cm *ContextManager) GetGraphEntityTokens() int\n```\nGetGraphEntityTokens returns the total tokens in the graph entities region\n\n```go\nfunc (cm *ContextManager) GetRegionTokens(region RegionType) int\n```\nGetRegionTokens returns the total token count for a region\n\n```go\nfunc (cm *ContextManager) ModelLimit() int\n```\nModelLimit returns the resolved model context limit.\n\n```go\nfunc (cm *ContextManager) RepairToolPairs() int\n```\nRepairToolPairs is the public entry point for the tool-pair integrity audit. Locks cm.mu and delegates to repairToolPairsLocked.\n\nBeta.25 hoisted this from compaction-only (it was previously called only by SliceForBudget) to a general-purpose pre-request safety net. Beta.25 C1 wired synth-result emission at every known terminal-transition path (failLoop, max-iter, cancel signal, dispatch failure) so most orphan tool\\_calls get matched results before they ever reach context. RepairToolPairs is the belt-and- suspenders for cases the synth-result path missed:\n\n  - loops restored from KV with corrupt context written by an older binary version,\n  - any future failure path that adds an assistant tool\\_call to context without ensuring matched results,\n  - third-party state mutations (e.g., manual KV edits during debugging).\n\nReturns the number of messages removed; zero on the hot path (well-formed contexts iterate the recent-history slice once and return without allocations).\n\n```go\nfunc (cm *ContextManager) ShouldCompact() bool\n```\nShouldCompact returns true if compaction should be triggered\n\n```go\nfunc (cm *ContextManager) SliceForBudget(budget int, slice ContextSlice) error\n```\nSliceForBudget removes content to fit within the budget. Uses graph-aware slicing that preserves entity context when EntityPriority is set.\n\n```go\nfunc (cm *ContextManager) TotalTokens() int\n```\nTotalTokens returns the sum of all region tokens.\n\n```go\nfunc (cm *ContextManager) Utilization() float64\n```\nUtilization returns the current context utilization (0.0 to 1.0). Reserves headroom so compaction triggers before the model limit, leaving room for the response. Headroom is resolved as the greater of (HeadroomRatio \\* modelLimit) and HeadroomTokens (floor).\n\n```go\ntype ContextManagerOption func(*ContextManager)\n```\nContextManagerOption is a functional option for configuring ContextManager\n\n```go\nfunc WithLogger(logger *slog.Logger) ContextManagerOption\n```\nWithLogger sets the logger for the ContextManager\n\n```go\nfunc WithModelRegistry(reg model.RegistryReader) ContextManagerOption\n```\nWithModelRegistry provides registry-based model limit resolution\n\n```go\ntype ContextSlice struct {\n\tIncludeRegions   []RegionType // Regions to include\n\tExcludeRegions   []RegionType // Regions to exclude (takes precedence)\n\tPreserveEntities []string     // Entity IDs to always keep\n}\n```\nContextSlice defines which regions to include when slicing context\n\n```go\ntype DispatcherMetrics interface {\n\t// RecordGovernanceVerdict observes the wait duration and counts the\n\t// verdict. decision is \"approved\" | \"rejected\" | \"timeout\"; mode is\n\t// \"audit\" | \"enforce\".\n\tRecordGovernanceVerdict(decision, mode string, duration float64)\n\n\t// RecordGovernanceVerdictMissingWaiter signals that a verdict\n\t// arrived for a call_id without a registered waiter — points at\n\t// the subscribe-before-publish race regressing or a late arrival.\n\tRecordGovernanceVerdictMissingWaiter()\n}\n```\nDispatcherMetrics is the optional metrics-sink interface the dispatcher calls into for observability. The Component's \\*loopMetrics satisfies it; tests pass nil.\n\nKept narrow so the dispatcher stays free of Prometheus types and the metrics layer can evolve independently. Implementations should be non-blocking — the dispatcher is on the loop's hot path.\n\n```go\ntype DispatcherResult struct {\n\tApproved []agentic.ToolCall\n\tRejected []ToolCallRejection\n}\n```\nDispatcherResult is the verdict for a batch of proposed calls. Empty Rejected with full Approved is the disabled-mode/audit-mode steady state. Partial splits are produced by enforce mode.\n\n```go\ntype GovernanceDispatcher interface {\n\t// Propose submits a batch of tool calls for governance review.\n\t// Returns the approved/rejected split. Disabled mode passes\n\t// through; audit mode publishes-but-passes-through; enforce mode\n\t// waits up to the configured timeout per call and fails-closed on\n\t// timeout (treats absent verdict as a reject).\n\t//\n\t// loopID is the originating loop's bare UUID. parentLoopID is the\n\t// spawn-tree parent (empty for top-level loops). Both ride along\n\t// in the proposed payload so rule conditions can match across the\n\t// hierarchy from day one.\n\tPropose(ctx context.Context, loopID, parentLoopID string, calls []agentic.ToolCall) (DispatcherResult, error)\n\n\t// HandleVerdict feeds an inbound verdict to the dispatcher. The\n\t// Component's wildcard subscription handlers call this for every\n\t// verdict, after extracting the decision and call_id from the\n\t// payload via VerdictPayload.EffectiveCallID/EffectiveDecision.\n\t// The dispatcher demuxes by call_id to the appropriate waiter\n\t// channel. No-op when no waiter is registered for the call_id\n\t// (audit mode, late arrivals, verdicts for other components'\n\t// loops on a shared stream). Data is retained for audit logging\n\t// only — routing decisions are made from decision + callID.\n\tHandleVerdict(decision, callID string, data []byte)\n\n\t// Mode returns the configured mode for inspection. Useful for\n\t// observability gauges and conditional logging in the handler.\n\tMode() string\n}\n```\nGovernanceDispatcher abstracts the subject-mode tool-call governance flow. The Component holds one instance per loop component and delegates from handleToolCallResponse before the existing serial- dispatch. Verdict arrival from the JetStream subscription is fed in via HandleVerdict.\n\n```go\nfunc NewGovernanceDispatcher(cfg ToolCallGovernanceConfig, publisher VerdictPublisher, logger *slog.Logger, metrics DispatcherMetrics) GovernanceDispatcher\n```\nNewGovernanceDispatcher constructs the dispatcher matching the configured mode. Publisher may be nil in disabled mode (no publishes happen). Metrics may be nil — observability records are skipped when unset. The returned dispatcher's HandleVerdict is safe to call from JetStream consumer callbacks.\n\nThe dispatcher does NOT subscribe — the Component owns the wildcard JetStream subscription and routes verdicts through HandleVerdict. That keeps the consumer lifecycle (create / bind / cleanup-on-stop) in one place and lets the dispatcher stay free of NATS dependencies.\n\n```go\ntype HandlerResult struct {\n\tLoopID               string\n\tState                agentic.LoopState\n\tPublishedMessages    []PublishedMessage\n\tPendingTools         []string\n\tTrajectorySteps      []agentic.TrajectoryStep\n\tContextEvents        []agentic.ContextEvent\n\tRetryScheduled       bool\n\tMaxIterationsReached bool\n\t// Created is true only when HandleTask actually created a new loop.\n\t// False on the dedup short-circuit path (TaskMessage redelivered for\n\t// an already-active task). Component uses this to gate\n\t// recordLoopCreated so the active_loops gauge does not drift on\n\t// JetStream redelivery.\n\tCreated bool\n\t// CompletionState contains enriched completion data for KV persistence.\n\t// This is populated when a loop completes and is used by component.go\n\t// to write to the loops bucket with key pattern COMPLETE_{loopID}.\n\tCompletionState *agentic.LoopCompletedEvent\n\t// FailureState contains enriched failure data for graph emission.\n\t// Populated when a loop fails, mirrors CompletionState for the failure path.\n\tFailureState *agentic.LoopFailedEvent\n\t// SyntheticDecide is populated when handleCompleteResponse detects a\n\t// terminal-tool-less completion AND Config.SynthesizeTerminalOnCompletion\n\t// is true (#133). Component reads this and routes through graphWriter\n\t// to stamp coordinator.next_action=\"needs_clarification\",\n\t// coordinator.decision.reason=\"[synthetic-no-terminal] ...\", and\n\t// coordinator.decision.synthetic=\"true\" atomically on the loop entity.\n\t// Nil means either the loop terminated through a real decide call or\n\t// the synthesis opt-in is off; either way, no synthetic triples.\n\tSyntheticDecide *SyntheticDecideRequest\n\t// contains filtered or unexported fields\n}\n```\nHandlerResult contains the results of a handler operation\n\n```go\ntype InFlightRequest struct {\n\tSubject string `json:\"subject\"`\n}\n```\nInFlightRequest asks about one task subject.\n\n```go\ntype InFlightResponse struct {\n\tSubject string `json:\"subject\"`\n\t// Outstanding is NumPending + NumAckPending for the bound consumer — work\n\t// delivered-but-unacked plus work not yet delivered.\n\tOutstanding uint64 `json:\"outstanding\"`\n\t// InFlight is Outstanding \u003e 0, carried explicitly so the common caller\n\t// question does not require every caller to re-derive the same comparison.\n\tInFlight bool `json:\"inFlight\"`\n}\n```\nInFlightResponse is returned ONLY when the answer is known.\n\nThere is deliberately no \"unknown\" field and no zero-valued fallback: an unknown answer is an error, never a payload, so a caller cannot accidentally read absence of a measurement as a measurement of absence. See errUnknownInFlight.\n\n```go\ntype LLMSummarizer struct {\n\t// contains filtered or unexported fields\n}\n```\nLLMSummarizer implements Summarizer using a graph/llm.Client.\n\n```go\nfunc NewLLMSummarizer(client llm.Client, logger *slog.Logger) *LLMSummarizer\n```\nNewLLMSummarizer creates a summarizer backed by an LLM client.\n\n```go\nfunc (s *LLMSummarizer) Summarize(ctx context.Context, messages []agentic.ChatMessage, maxTokens int) (string, error)\n```\nSummarize calls the LLM to generate a summary of the conversation messages.\n\n```go\ntype LessonReader interface {\n\t// ReadLessons lists the matcher-relevant projection of every lesson record\n\t// under recordPrefix (the {org}.{platform}.agent.lesson.record 5-part\n\t// prefix). The caller filters/orders/bounds the result.\n\tReadLessons(ctx context.Context, recordPrefix string) ([]lessonmatch.Lesson, error)\n}\n```\nLessonReader is the narrow surface MessageHandler uses to fetch lesson candidates for brief-assembly injection (ADR-080 push delivery). It returns EVERY lesson-record entity's matcher-relevant projection — including status — and the caller's matcher (lessonmatch.Match) performs the active-only exclusion and scope filtering, so the exclusion lives in ONE place the future fusion facet reuses. Production satisfies it via a NATS prefix query against graph.ingest.query.prefix; tests substitute an in-memory implementation. A nil reader disables injection entirely (back-compat).\n\n```go\nfunc NewNATSLessonReader(client *natsclient.Client) LessonReader\n```\nNewNATSLessonReader builds a LessonReader backed by the graph.ingest.query.prefix NATS surface.\n\n```go\ntype LoopManager struct {\n\t// contains filtered or unexported fields\n}\n```\nLoopManager manages loop entity lifecycle and state\n\n```go\nfunc NewLoopManager(opts ...LoopManagerOption) *LoopManager\n```\nNewLoopManager creates a new LoopManager\n\n```go\nfunc NewLoopManagerWithConfig(contextConfig ContextConfig, opts ...LoopManagerOption) *LoopManager\n```\nNewLoopManagerWithConfig creates a new LoopManager with custom context config\n\n```go\nfunc (m *LoopManager) AddPendingTool(loopID, callID string) error\n```\nAddPendingTool adds a pending tool call to the loop\n\n```go\nfunc (m *LoopManager) AllToolsComplete(loopID string) bool\n```\nAllToolsComplete returns true if there are no pending tool calls\n\n```go\nfunc (m *LoopManager) CacheMetadata(loopID string, metadata map[string]any)\n```\nCacheMetadata stores domain context metadata for a loop (set once from task, reused for all tool calls). Makes a defensive copy to isolate from the caller's map.\n\n```go\nfunc (m *LoopManager) CacheRequestTimeout(loopID, timeout string)\n```\nCacheRequestTimeout stores the per-request timeout for a loop (from TaskMessage.Timeout). Reused for all continuation iterations so the task-level budget persists across LLM calls in the same loop.\n\n```go\nfunc (m *LoopManager) CacheResponseFormat(loopID string, rf *agentic.ResponseFormat)\n```\nCacheResponseFormat stores the per-task response\\_format for a loop (from TaskMessage.ResponseFormat). Reused for all continuation iterations so the structured-output constraint persists across LLM calls in the same loop. ADR-034.\n\n```go\nfunc (m *LoopManager) CacheTaskPrompt(loopID, prompt string)\n```\nCacheTaskPrompt stores the original task prompt for context recovery. If GC/repair leaves the context empty, this prompt is re-injected as a synthetic user message so the model always has contents to work with.\n\n```go\nfunc (m *LoopManager) CacheToolChoice(loopID string, tc *agentic.ToolChoice)\n```\nCacheToolChoice stores the tool choice strategy for a loop (set once from task, reused for all requests)\n\n```go\nfunc (m *LoopManager) CacheTools(loopID string, tools []agentic.ToolDefinition)\n```\nCacheTools stores tool definitions for a loop (discovered once, reused for all requests)\n\n```go\nfunc (m *LoopManager) CancelLoop(loopID, cancelledBy string) (agentic.LoopEntity, error)\n```\nCancelLoop atomically cancels a loop and populates completion data. Returns the updated entity for further processing, or an error if the loop cannot be cancelled (not found or already terminal).\n\n```go\nfunc (m *LoopManager) ClearQueuedTools(loopID string)\n```\nClearQueuedTools discards all queued tool calls (e.g., when StopLoop fires).\n\n```go\nfunc (m *LoopManager) CreateLoop(taskID, role, model string, maxIterations ...int) (string, error)\n```\nCreateLoop creates a new loop entity with a generated UUID\n\n```go\nfunc (m *LoopManager) CreateLoopWithID(loopID, taskID, role, model string, maxIterations ...int) (string, error)\n```\nCreateLoopWithID creates a new loop entity with a specific ID\n\n```go\nfunc (m *LoopManager) DeleteLoop(loopID string) error\n```\nDeleteLoop deletes a loop entity and all associated tracking data.\n\n```go\nfunc (m *LoopManager) DequeueToolCall(loopID string) (agentic.ToolCall, bool)\n```\nDequeueToolCall removes and returns the next queued tool call for dispatch.\n\n```go\nfunc (m *LoopManager) ExtractLoopIDFromRequest(requestID string) string\n```\nExtractLoopIDFromRequest extracts the loop ID from a structured request ID. Returns empty string if the ID is not in structured format.\n\n```go\nfunc (m *LoopManager) ExtractLoopIDFromToolCall(toolCallID string) string\n```\nExtractLoopIDFromToolCall extracts the loop ID from a structured tool call ID. Returns empty string if the ID is not in structured format.\n\n```go\nfunc (m *LoopManager) GenerateLoopID() string\n```\nGenerateLoopID returns an identity with the exact UUID semantics used by CreateLoop, without registering or persisting a loop. Intake uses this pure generator to preflight prospective lineage before loop creation.\n\n```go\nfunc (m *LoopManager) GenerateRequestID(loopID string) string\n```\nGenerateRequestID creates a structured request ID that embeds the loop ID. Format: loopID:req:shortUUID This allows recovery of loop ID from request ID if in-memory maps are lost.\n\n```go\nfunc (m *LoopManager) GenerateToolCallID(loopID string) string\n```\nGenerateToolCallID creates a structured tool call ID that embeds the loop ID. Format: loopID:tool:shortUUID This allows recovery of loop ID from tool call ID if in-memory maps are lost.\n\n```go\nfunc (m *LoopManager) GetAndClearToolResults(loopID string) []agentic.ToolResult\n```\nGetAndClearToolResults retrieves all accumulated tool results and clears them. Also evicts the CallID→loop routing entry for each drained result so a late re-delivery (NATS redelivery, executor retry) lands on an empty mapping at handleToolResultMessage and is dropped at the wire instead of leaking into the next turn's PendingToolResults — which would otherwise produce a duplicate tool message in the message array sent to the model.\n\nEviction effectiveness depends on GetLoopForToolCallWithRecovery NOT resolving an evicted CallID via ExtractLoopIDFromToolCall — true today because model-issued CallIDs (toolu\\_, call\\_) don't carry the structured {loopID}:tool:{short} form and GenerateToolCallID is not wired to dispatch. If structured CallIDs ever become the dispatch default, this needs an evicted-set check inside the recovery path or it silently regresses.\n\nMetadata maps (callIDToName, callIDToArguments, callIDToOrdinal, toolStartTimes) are preserved — buildToolMessages's empty-name fallback and the trajectory step builder still read them. They grow O(total-tool-calls-in-loop) and are cleaned up at DeleteLoop along with the rest of the loop's bookkeeping.\n\n```go\nfunc (m *LoopManager) GetCachedMetadata(loopID string) map[string]any\n```\nGetCachedMetadata retrieves the cached metadata for a loop\n\n```go\nfunc (m *LoopManager) GetCachedRequestTimeout(loopID string) string\n```\nGetCachedRequestTimeout retrieves the cached per-request timeout for a loop. Returns empty string when no task-level timeout was set.\n\n```go\nfunc (m *LoopManager) GetCachedResponseFormat(loopID string) *agentic.ResponseFormat\n```\nGetCachedResponseFormat retrieves the cached response\\_format for a loop. Returns nil when no task-level response\\_format was set, in which case AgentRequest.ResponseFormat stays nil and tool-calling behaviour is preserved.\n\n```go\nfunc (m *LoopManager) GetCachedToolChoice(loopID string) *agentic.ToolChoice\n```\nGetCachedToolChoice retrieves the cached tool choice for a loop\n\n```go\nfunc (m *LoopManager) GetCachedTools(loopID string) []agentic.ToolDefinition\n```\nGetCachedTools retrieves the cached tool definitions for a loop\n\n```go\nfunc (m *LoopManager) GetContextManager(loopID string) *ContextManager\n```\nGetContextManager retrieves the context manager for a loop\n\n```go\nfunc (m *LoopManager) GetCurrentIteration(loopID string) int\n```\nGetCurrentIteration returns the current iteration for a loop\n\n```go\nfunc (m *LoopManager) GetDepth(loopID string) (depth, maxDepth int, err error)\n```\nGetDepth returns the current depth and max depth for a loop\n\n```go\nfunc (m *LoopManager) GetLoop(loopID string) (agentic.LoopEntity, error)\n```\nGetLoop retrieves a loop entity by ID\n\n```go\nfunc (m *LoopManager) GetLoopForRequest(requestID string) (string, bool)\n```\nGetLoopForRequest retrieves the loop ID for a request ID\n\n```go\nfunc (m *LoopManager) GetLoopForRequestWithRecovery(requestID string) (string, bool)\n```\nGetLoopForRequestWithRecovery retrieves the loop ID for a request ID, attempting recovery from structured ID if not found in cache.\n\n```go\nfunc (m *LoopManager) GetLoopForToolCall(callID string) (string, bool)\n```\nGetLoopForToolCall retrieves the loop ID for a tool call ID\n\n```go\nfunc (m *LoopManager) GetLoopForToolCallWithRecovery(toolCallID string) (string, bool)\n```\nGetLoopForToolCallWithRecovery retrieves the loop ID for a tool call ID, attempting recovery from structured ID if not found in cache.\n\n```go\nfunc (m *LoopManager) GetPendingTools(loopID string) []string\n```\nGetPendingTools returns all pending tool calls for a loop\n\n```go\nfunc (m *LoopManager) GetRequestStart(requestID string) time.Time\n```\nGetRequestStart retrieves the start time for a model request.\n\n```go\nfunc (m *LoopManager) GetRole(loopID string) string\n```\nGetRole returns the role of a loop (LoopEntity.Role), or the empty string when the loop is unknown or roleless. Read-only counterpart used by dispatch to stamp the agent role onto outgoing ToolCall.Metadata (agentic.MetadataKeyAgentRole) so tool executors can DERIVE role attribution (e.g. emit\\_lesson's agent.lesson.observed-role) without the model supplying a spoofable identity argument. Returns \"\" rather than an error so the best-effort dispatch stamp stays branchless — an unknown loop and a roleless loop are indistinguishable to the consumer (both mean \"no role\"), and dispatch must never fail over it.\n\n```go\nfunc (m *LoopManager) GetRunID(loopID string) string\n```\nGetRunID returns the run anchor (bare run loop-id) for a loop, or the empty string when the loop is unknown or not part of a run (ADR-053 D7). Read-only counterpart to SetRunID; dispatch reads it to stamp the run anchor onto outgoing ToolCall.Metadata (issue #250). Returns \"\" rather than an error so the best-effort dispatch stamp stays branchless — an unknown loop and a runless loop are indistinguishable to the consumer (both mean \"no run anchor\"), and dispatch must never fail over it.\n\n```go\nfunc (m *LoopManager) GetTaskPrompt(loopID string) string\n```\nGetTaskPrompt retrieves the cached task prompt for a loop\n\n```go\nfunc (m *LoopManager) GetToolArguments(callID string) map[string]any\n```\nGetToolArguments retrieves a shallow copy of the arguments for a tool call ID.\n\n```go\nfunc (m *LoopManager) GetToolName(callID string) string\n```\nGetToolName retrieves the function name for a tool call ID.\n\n```go\nfunc (m *LoopManager) GetToolOrdinal(callID string) uint32\n```\nGetToolOrdinal returns the tool call's order in the model response.\n\n```go\nfunc (m *LoopManager) GetToolStart(callID string) time.Time\n```\nGetToolStart retrieves the start time for a tool call.\n\n```go\nfunc (m *LoopManager) HasActiveLoopForTask(taskID string) (string, bool)\n```\nHasActiveLoopForTask returns true if a non-terminal loop already exists for the given task ID. This prevents duplicate loop creation on JetStream redelivery.\n\n```go\nfunc (m *LoopManager) HasQueuedTools(loopID string) bool\n```\nHasQueuedTools returns true if there are tool calls waiting to be dispatched.\n\n```go\nfunc (m *LoopManager) IncrementIteration(loopID string) error\n```\nIncrementIteration increments the loop iteration counter\n\n```go\nfunc (m *LoopManager) IncrementTruncationRetry(loopID string) int\n```\nIncrementTruncationRetry bumps the within-loop truncation retry counter and returns the new value. Caller branches on the return to decide between \"first retry — compact and try again\" (==1) and \"already retried — fail loud\" (\u003e1). The counter is cleared by ResetTruncationRetry whenever the loop makes forward progress.\n\n```go\nfunc (m *LoopManager) IsTimedOut(loopID string) bool\n```\nIsTimedOut checks if a loop has exceeded its timeout\n\n```go\nfunc (m *LoopManager) QueueToolCalls(loopID string, calls []agentic.ToolCall)\n```\nQueueToolCalls stores tool calls to be dispatched serially after the current call completes.\n\n```go\nfunc (m *LoopManager) RemovePendingTool(loopID, callID string) error\n```\nRemovePendingTool removes a pending tool call from the loop\n\n```go\nfunc (m *LoopManager) ResetTruncationRetry(loopID string)\n```\nResetTruncationRetry clears the within-loop truncation retry counter. Called when the loop makes forward progress (a normal StatusComplete or StatusToolCall response arrives) so a future truncation can self-heal once.\n\n```go\nfunc (m *LoopManager) ResolveApprovalIfPending(loopID, callID string) (agentic.PendingApprovalState, bool, error)\n```\nResolveApprovalIfPending atomically transitions the loop out of LoopStateAwaitingApproval if and only if the supplied call\\_id matches the currently pinned PendingApproval. Returns a snapshot of the pending state (so the caller has the original tool name + arguments + trace context for re-dispatch) plus a bool indicating whether the resolve actually happened. A false return is the idempotent drop case: the loop is no longer awaiting approval, or the response targets a different call\\_id (typical when a duplicate UI click races with an automated reject scheduler).\n\nThis is the only path that should mutate PendingApproval + State out of awaiting\\_approval after BeginAwaitingApproval. The previous load → mutate → UpdateLoop pattern in HandleApprovalResponse let two concurrent responses both pass the awaiting-state check and both dispatch — for a safety feature, that double-execution risk is unacceptable.\n\n```go\nfunc (m *LoopManager) SetDepth(loopID string, depth, maxDepth int) error\n```\nSetDepth sets the depth tracking for a loop in the multi-agent hierarchy\n\n```go\nfunc (m *LoopManager) SetMetadata(loopID string, metadata map[string]any) error\n```\nSetMetadata sets domain context metadata on the loop entity.\n\n```go\nfunc (m *LoopManager) SetParentLoop(loopID, parentLoopID string) error\n```\nSetParentLoop sets the parent loop ID for tracking architect-\u003eeditor relationships\n\n```go\nfunc (m *LoopManager) SetParentLoopID(loopID, parentLoopID string) error\n```\nSetParentLoopID is an alias for SetParentLoop for consistency with TaskMessage field names\n\n```go\nfunc (m *LoopManager) SetRunID(loopID, runID string) error\n```\nSetRunID sets the run anchor (bare run loop-id) on the loop entity (ADR-053 D7). The run\\_id identifies which agent run this loop belongs to. Empty string is accepted to allow explicit clearing, though in practice it is only set when the TaskMessage carries a non-empty RunID.\n\n```go\nfunc (m *LoopManager) SetTimeout(loopID string, timeout time.Duration) error\n```\nSetTimeout sets the timeout for a loop\n\n```go\nfunc (m *LoopManager) SetUserContext(loopID, channelType, channelID, userID string) error\n```\nSetUserContext sets the user routing info for error notifications\n\n```go\nfunc (m *LoopManager) SetWorkflowContext(loopID, workflowSlug, workflowStep string) error\n```\nSetWorkflowContext sets the workflow slug and step for loops created by workflow commands\n\n```go\nfunc (m *LoopManager) SnapshotExpiredApprovals(now time.Time) []ApprovalTimeoutCandidate\n```\nSnapshotExpiredApprovals returns a snapshot of loops whose pending approval has timed out (RequestedAt + Timeout \\\u003c= now). Skips loops whose Timeout is zero (wait-indefinitely policy). Read-locked; the snapshot is taken under the lock and the lock released before return so callers can act on each candidate without holding the mutex.\n\nBeta.25 adds this for the orphan-tool-call recovery work. The approval-timeout timer was a deferred item from beta.19; closing it now ensures a stuck human-approval flow doesn't leave the gated tool\\_call orphaned indefinitely (mode f of orphan recovery).\n\n```go\nfunc (m *LoopManager) StoreToolResult(loopID string, result agentic.ToolResult) error\n```\nStoreToolResult stores a tool result in the loop entity for later retrieval\n\n```go\nfunc (m *LoopManager) TrackRequest(requestID, loopID string)\n```\nTrackRequest associates a request ID with a loop ID\n\n```go\nfunc (m *LoopManager) TrackRequestStart(requestID string)\n```\nTrackRequestStart records when a model request was sent.\n\n```go\nfunc (m *LoopManager) TrackToolArguments(callID string, args map[string]any)\n```\nTrackToolArguments associates a tool call ID with its arguments. This is used to populate the ToolArguments field on trajectory steps for audit.\n\n```go\nfunc (m *LoopManager) TrackToolCall(callID, loopID string)\n```\nTrackToolCall associates a tool call ID with a loop ID\n\n```go\nfunc (m *LoopManager) TrackToolName(callID, name string)\n```\nTrackToolName associates a tool call ID with its function name. This is used to populate the name field on tool result messages (required by Gemini).\n\n```go\nfunc (m *LoopManager) TrackToolOrdinal(callID string, ordinal uint32)\n```\nTrackToolOrdinal records the tool call's order in the model response.\n\n```go\nfunc (m *LoopManager) TrackToolStart(callID string)\n```\nTrackToolStart records when a tool call was dispatched for execution.\n\n```go\nfunc (m *LoopManager) TransitionLoop(loopID string, newState agentic.LoopState) error\n```\nTransitionLoop transitions a loop to a new state\n\n```go\nfunc (m *LoopManager) UpdateCompletion(loopID, outcome, result, errMsg string) error\n```\nUpdateCompletion updates a loop with completion data (outcome, result, error). This is called when a loop finishes to populate fields for SSE delivery via KV watch.\n\n```go\nfunc (m *LoopManager) UpdateLoop(entity agentic.LoopEntity) error\n```\nUpdateLoop updates an existing loop entity\n\n```go\ntype LoopManagerOption func(*LoopManager)\n```\nLoopManagerOption is a functional option for configuring LoopManager\n\n```go\nfunc WithLoopManagerLogger(logger *slog.Logger) LoopManagerOption\n```\nWithLoopManagerLogger sets the logger for the LoopManager and its context managers\n\n```go\nfunc WithLoopManagerModelRegistry(reg model.RegistryReader) LoopManagerOption\n```\nWithLoopManagerModelRegistry sets the model registry for context managers\n\n```go\ntype MessageHandler struct {\n\t// contains filtered or unexported fields\n}\n```\nMessageHandler handles incoming messages and coordinates loop execution\n\n```go\nfunc NewMessageHandler(config Config, loopManagerOpts ...LoopManagerOption) *MessageHandler\n```\nNewMessageHandler creates a new MessageHandler\n\n```go\nfunc (h *MessageHandler) BuildFailureEvent(loopID, reason, errorMsg string) (*agentic.LoopFailedEvent, error)\n```\nBuildFailureEvent creates a failure event (public wrapper for component.go).\n\n```go\nfunc (h *MessageHandler) BuildFailureMessages(loopID, reason, errorMsg string) (*agentic.LoopFailedEvent, []PublishedMessage, error)\n```\nBuildFailureMessages creates a failure event and serializes it for NATS publishing. Returns the event (for graph emission) and published messages (for reactive workflows).\n\n```go\nfunc (h *MessageHandler) CancelLoop(loopID, cancelledBy string) (agentic.LoopEntity, error)\n```\nCancelLoop atomically cancels a loop and populates completion data.\n\n```go\nfunc (h *MessageHandler) GetContextManager(loopID string) *ContextManager\n```\nGetContextManager returns the ContextManager for a given loop ID.\n\n```go\nfunc (h *MessageHandler) GetLoop(loopID string) (agentic.LoopEntity, error)\n```\nGetLoop retrieves a loop entity (for testing)\n\n```go\nfunc (h *MessageHandler) GovernanceDispatcher() GovernanceDispatcher\n```\nGovernanceDispatcher returns the installed dispatcher (or nil). Used by the Component's verdict subscription handlers to route inbound verdicts via HandleVerdict.\n\n```go\nfunc (h *MessageHandler) HandleApprovalResponse(ctx context.Context, response agentic.ApprovalResponse) (result HandlerResult, err error)\n```\nHandleApprovalResponse processes an ApprovalResponse for a loop awaiting human approval. Returns a HandlerResult populated with either a re-dispatched ToolCall (approve/modify) or a synthesised rejection ToolResult fed through the normal HandleToolResult path (reject). The component publishes any messages and persists the loop state.\n\nThe transition out of awaiting\\_approval happens atomically inside LoopManager.ResolveApprovalIfPending. Two concurrent responses (e.g., a human approve racing an automated reject scheduler) cannot both pass the awaiting check — exactly one wins; the loser sees ok= false and we treat it as a stale-response idempotent drop. This is load-bearing for the safety claim: a sensitive tool must not dispatch twice off two responses for the same call\\_id.\n\nOther mismatches (loop not found, response.Validate() fails) return a defensive log + non-error empty result so duplicate or stale UI clicks don't crash the loop.\n\n```go\nfunc (h *MessageHandler) HandleModelResponse(ctx context.Context, loopID string, response agentic.AgentResponse) (HandlerResult, error)\n```\nHandleModelResponse processes a model response\n\n```go\nfunc (h *MessageHandler) HandleTask(ctx context.Context, task TaskMessage) (HandlerResult, error)\n```\nHandleTask processes an incoming task message and creates a new loop\n\n```go\nfunc (h *MessageHandler) HandleToolResult(ctx context.Context, loopID string, toolResult agentic.ToolResult) (HandlerResult, error)\n```\nHandleToolResult processes a tool execution result\n\n```go\nfunc (h *MessageHandler) SetGovernanceDispatcher(d GovernanceDispatcher)\n```\nSetGovernanceDispatcher installs the subject-mode tool-call governance dispatcher (ADR-039). The dispatcher field is not synchronized once the JetStream consumer callbacks start reading it — the setter must be called between NewComponent and Start.\n\nNil clears any previously installed dispatcher (effectively reverting to disabled-mode pass-through). The Component wires this automatically in NewComponent based on Config.ToolCallGovernance.Mode; tests stub via this setter.\n\n```go\nfunc (h *MessageHandler) SetLessonReader(r LessonReader)\n```\nSetLessonReader installs the reader the handler uses to list active lesson-record entities for brief-assembly injection (ADR-080). Passing nil disables lesson injection — the assembled system prompt is left unchanged.\n\n```go\nfunc (h *MessageHandler) SetLogger(logger *slog.Logger)\n```\nSetLogger sets the logger for the handler\n\n```go\nfunc (h *MessageHandler) SetMetrics(m *loopMetrics)\n```\nSetMetrics installs the component metrics used to record brief-assembly observability (lesson matched-vs-included counts). Nil-safe.\n\n```go\nfunc (h *MessageHandler) SetPersonaFragments(src PersonaFragmentSource)\n```\nSetPersonaFragments installs a source for KV-backed persona overrides. On each task the handler calls src.Fragments(ctx) and UpsertAll's the result onto the registry before assembly — this is what makes runtime persona edits take effect on the next loop without a restart. Passing nil disables the per-task refresh; the registry is used as-is.\n\n```go\nfunc (h *MessageHandler) SetPlatform(p types.PlatformMeta)\n```\nSetPlatform installs the org/platform pair used to construct loop entity IDs for todo reads. The same identity is also used by other graph paths in this package (graph\\_writer); typically wired once from the same source at component boot.\n\n```go\nfunc (h *MessageHandler) SetPromptRegistry(r *prompt.Registry)\n```\nSetPromptRegistry installs the base fragment registry that composes the per-task system prompt. Passing nil clears the registry — callers get the legacy behaviour where buildInitialMessages emits only task.Context.Content + user prompt. The registry is expected to be preloaded with prompt.DefaultFragments. Product-supplied overrides (KV-backed personas) are merged at assembly time via the source passed to SetPersonaFragments.\n\n```go\nfunc (h *MessageHandler) SetSummarizer(s Summarizer, modelName string)\n```\nSetSummarizer injects an LLM-backed summarizer into the compactor. When set, context compaction generates real summaries instead of stubs. modelName is the resolved endpoint name reported in CompactionResult.\n\n```go\nfunc (h *MessageHandler) SetTodoReader(r TodoReader)\n```\nSetTodoReader installs the reader the handler uses to fetch each loop's write\\_todos list at iteration-build time (ADR-036 Stage 4). Passing nil disables the per-iteration todo block.\n\n```go\nfunc (h *MessageHandler) SetToolRegistry(r component.ToolRegistryReader)\n```\nSetToolRegistry installs the shared tool registry used by discoverTools. Production wiring lives in component.go via deps.ToolRegistry; tests use this to inject a per-test registry.\n\n```go\nfunc (h *MessageHandler) UpdateLoop(entity agentic.LoopEntity) error\n```\nUpdateLoop updates a loop entity\n\n```go\ntype PersonaFragmentSource interface {\n\tFragments(ctx context.Context) ([]prompt.Fragment, error)\n}\n```\nPersonaFragmentSource is the minimum surface the handler needs to pull KV-backed persona overrides at prompt-assembly time. persona.Manager satisfies it via its Fragments method; tests can stub with a trivial in-memory implementation. Kept as an interface here so the handler package doesn't carry a compile-time dependency on persona.\n\n```go\ntype ProposedToolCallPayload struct {\n\tLoopID       string         `json:\"loop_id\"`\n\tParentLoopID string         `json:\"parent_loop_id,omitempty\"`\n\tCallID       string         `json:\"call_id\"`\n\tToolName     string         `json:\"tool_name\"`\n\tCommand      string         `json:\"command,omitempty\"`\n\tURL          string         `json:\"url,omitempty\"`\n\tArguments    map[string]any `json:\"arguments,omitempty\"`\n}\n```\nProposedToolCallPayload is the wire shape published to agent.toolcall.proposed.\\\u003cloop\\_id\u003e in audit and enforce modes. Rules match on these field paths via \\`$message.\\\u003cfield\u003e\\` substitution.\n\nParentLoopID is nullable from day one (ADR-039) so rule conditions can match across loop hierarchies for sub-agent governance inheritance. Empty string means no parent.\n\n```go\ntype PublishedMessage struct {\n\tSubject string\n\tData    []byte\n}\n```\nPublishedMessage represents a message published to NATS\n\n```go\ntype RegionType string\n```\nRegionType defines the type of context region\n\n```go\nconst (\n\tRegionSystemPrompt     RegionType = \"system_prompt\"     // System prompt and instructions\n\tRegionCompactedHistory RegionType = \"compacted_history\" // Summarized old conversation\n\tRegionRecentHistory    RegionType = \"recent_history\"    // Recent uncompacted messages\n\tRegionToolResults      RegionType = \"tool_results\"      // Tool execution results\n\tRegionHydratedContext  RegionType = \"hydrated_context\"  // Retrieved context from memory\n\tRegionGraphEntities    RegionType = \"graph_entities\"    // Graph entity context (multi-agent)\n)\n```\nContext region types define different areas of the conversation context\n\n```go\ntype Summarizer interface {\n\t// Summarize generates a concise summary of the given conversation messages.\n\t// maxTokens limits the response length.\n\tSummarize(ctx context.Context, messages []agentic.ChatMessage, maxTokens int) (string, error)\n}\n```\nSummarizer abstracts the LLM call for context compaction.\n\n```go\ntype SyntheticDecideRequest struct {\n\tLoopID string\n\tReason string\n}\n```\nSyntheticDecideRequest carries the data needed for graphWriter to stamp the synthetic decide triples (#133). LoopID identifies the loop entity; Reason is the model's final text content, used as the coordinator.decision.reason payload (prefixed by graphWriter so the \"synthetic\" provenance is impossible to miss in operator dashboards).\n\n```go\ntype TaskMessage = agentic.TaskMessage\n```\nTaskMessage is an alias for agentic.TaskMessage for backward compatibility. This allows existing code to use agenticloop.TaskMessage without modification.\n\n```go\ntype TodoReader interface {\n\tReadTodos(ctx context.Context, loopEntityID string) ([]TodoState, error)\n}\n```\nTodoReader is the narrow surface MessageHandler uses to fetch the current todo list for a loop. Production satisfies it via a NATS adapter against graph.ingest.query.entity; tests substitute an in-memory implementation.\n\n```go\nfunc NewNATSTodoReader(client *natsclient.Client) TodoReader\n```\nNewNATSTodoReader builds a TodoReader backed by the graph.ingest.query.entity NATS surface.\n\n```go\ntype TodoState struct {\n\tID        string\n\tContent   string\n\tStatus    string\n\tPosition  int\n\tUpdatedAt string\n}\n```\nTodoState is the reconstructed logical shape of one todo item. Its storage encoding is private to TodoReader.\n\n```go\nfunc ReconstructTodos(triples []message.Triple) []TodoState\n```\nReconstructTodos rebuilds the ordered todo list from record triples. It preserves its historical helper signature for package callers; malformed storage returns no list. Production TodoReader uses the checked decoder below and returns the corresponding error.\n\n```go\ntype ToolCallGovernanceConfig struct {\n\t// Mode is one of \"disabled\", \"audit\", or \"enforce\". Default\n\t// \"disabled\" leaves no governance gate.\n\tMode string `json:\"mode,omitempty\" schema:\"type:string,description:Governance mode (disabled|audit|enforce). Default disabled means no governance gate,default:disabled,category:advanced\"`\n\n\t// Timeout is the per-call wait window in enforce mode before the\n\t// dispatcher fails-closed (rejects). Parsed as a Go duration string\n\t// (e.g. \"500ms\", \"2s\"). Ignored when Mode is \"disabled\" or \"audit\".\n\tTimeout string `json:\"timeout,omitempty\" schema:\"type:string,description:Per-call verdict wait window in enforce mode (e.g. 500ms or 2s). Default 1s,default:1s,category:advanced\"`\n}\n```\nToolCallGovernanceConfig configures subject-mode tool-call governance (ADR-039). When Mode is \"disabled\" (the default), tool calls dispatch directly with no governance gate. When Mode is \"audit\", every tool call is published to agent.toolcall.proposed.\\* but dispatch is NOT blocked — verdicts that arrive are logged/counted for observability. When Mode is \"enforce\", the loop publishes-then-waits for a per-call verdict on agent.toolcall.approved/rejected.\\* subjects, with Timeout as the fail-closed window.\n\nBeta.70 retired the in-process ToolCallFilter wiring that the beta.67+68 release shipped (per ADR-039 Phase 3); subject-mode is now the sole governance path.\n\n```go\nfunc DefaultToolCallGovernanceConfig() ToolCallGovernanceConfig\n```\nDefaultToolCallGovernanceConfig returns the default tool-call governance configuration: disabled mode (preserves pre-ADR-039 behavior) with the framework default Timeout for when an operator later flips to enforce.\n\n```go\nfunc (c *ToolCallGovernanceConfig) EnsureDefaults()\n```\nEnsureDefaults fills zero-valued fields with defaults. Called from Config-level defaulting at boot so an unset governance section has a stable Mode + Timeout instead of empty strings.\n\n```go\nfunc (c ToolCallGovernanceConfig) IsEnabled() bool\n```\nIsEnabled returns true when the governance flow is active (audit or enforce). Callers use this to skip publish setup work when governance is disabled.\n\n```go\nfunc (c ToolCallGovernanceConfig) IsEnforcing() bool\n```\nIsEnforcing returns true when verdicts gate dispatch. Callers use this to decide whether to wait for verdicts before dispatching.\n\n```go\nfunc (c ToolCallGovernanceConfig) ParsedTimeout() time.Duration\n```\nParsedTimeout returns the parsed Timeout duration. Falls back to the default when unset or unparseable; Validate is the safety net for malformed input.\n\n```go\nfunc (c ToolCallGovernanceConfig) Validate() error\n```\nValidate validates the tool-call governance configuration.\n\n```go\ntype ToolCallRejection struct {\n\tCall   agentic.ToolCall\n\tReason string\n}\n```\nToolCallRejection records why a tool call was denied by the governance dispatcher. The downstream serial-dispatch path consumes this to write per-call error results for the model to react to on its next iteration.\n\n```go\ntype VerdictPayload struct {\n\tDecision   string         `json:\"decision,omitempty\"`\n\tCallID     string         `json:\"call_id,omitempty\"`\n\tLoopID     string         `json:\"loop_id,omitempty\"`\n\tRuleID     string         `json:\"rule_id,omitempty\"`\n\tReason     string         `json:\"reason,omitempty\"`\n\tEntityID   string         `json:\"entity_id,omitempty\"`\n\tTimestamp  string         `json:\"timestamp,omitempty\"`\n\tProperties map[string]any `json:\"properties,omitempty\"`\n}\n```\nVerdictPayload is the wire shape inbound on agent.toolcall.{approved,rejected}.\\\u003cloop\\_id\u003e.\\\u003ccall\\_id\u003e. Produced by the rule engine's executeApprove action (top-level fields) OR by a rule \\`publish\\` action emitting a rejection (fields nested under Properties — the canonical ADR-039 reject pattern).\n\nBoth shapes are supported because the ADR's example rule uses \\`publish\\` + \\`deny\\` together for rejections (no extra \\`reject\\` action). EffectiveCallID and EffectiveDecision fall through the two shapes so callers don't write the same parsing code twice.\n\n```go\nfunc (v VerdictPayload) EffectiveCallID() string\n```\nEffectiveCallID returns the routing call\\_id from the payload, preferring the top-level CallID (approve-action shape) and falling back to Properties\\[\"call\\_id\"] (publish-action shape).\n\n```go\nfunc (v VerdictPayload) EffectiveDecision() string\n```\nEffectiveDecision returns the routing decision from the payload, preferring the top-level Decision (approve-action shape) and falling back to Properties\\[\"decision\"] (publish-action shape).\n\n```go\nfunc (v VerdictPayload) EffectiveReason() string\n```\nEffectiveReason returns the human-readable reason, with the same fall-through semantics as EffectiveCallID.\n\n```go\ntype VerdictPublisher interface {\n\tPublishToStream(ctx context.Context, subject string, data []byte) error\n}\n```\nVerdictPublisher is the minimum surface the governance dispatcher needs to publish proposed-call payloads. \\*natsclient.Client satisfies it via PublishToStream. Kept as an interface here so tests can stub the publish path without a real NATS connection.\n\n","path":"github.com/c360studio/semstreams/processor/agentic-loop","name":"agenticloop","synopsis":"Package agenticloop provides the agentic loop orchestrator component.","isRedistributable":true}
