Learning Loop
The self-improving pipeline that turns completed sessions and tool calls into memory facts, session summaries, and promotable skill drafts.
6 min read
The Learning Loop is Anvio's opt-in, self-improving layer, implemented in @anvio/learning (packages/learning/src). It runs after a session completes or after a tool call succeeds, and produces three kinds of output: memory facts, a session summary, and — when a repeatable pattern is detected — a skill draft that can be promoted into a real, installed skill.
Nothing here is magic prompt engineering — every stage has a rule-based fallback that runs even with no model configured, and an LLM-enhanced path that runs when one is.
Pipeline
Trigger points
| Trigger | Method | Fires on |
|---|---|---|
| Session completed | LearningEngine.onSessionCompleted() | AGENT_RUN_COMPLETED — from the worker, a detached run, anvio chat, or an inline anvio run |
| Tool call succeeded | LearningEngine.onToolUseCompleted() | Each successful ToolGateway.call() — this is the "runtime tool learning" (Phase L6) path |
Both methods check the soul's evolution setting first (see Souls & Soul Gate):
// packages/learning/src/index.ts
async onSessionCompleted(input: SessionLearningInput): Promise<SessionLearningResult> {
const evolution = input.soul?.spec.evolution;
if (evolution && !evolution.allowAutoUpdate) {
return { memoryNudge: { factsStored: 0, facts: [] }, skipped: 'soul evolution disabled' };
}
// ...
}If allowAutoUpdate is false, the entire loop is skipped for that soul — no facts, no summary, no draft.
Stage 1 — Memory nudge (fact extraction)
MemoryNudgeEngine.extractFacts() (packages/learning/src/memory-nudge.ts) scans user messages with four regex patterns:
const FACT_PATTERNS = [
/user prefers (.+)/i,
/remember that (.+)/i,
/always (.+) when/i,
/never (.+) unless/i,
];It also captures any user message under 200 characters that contains the word "prefer". Every match is stored via MemoryProvider.store() as a fact-type memory entry, scoped to sessionId and userId. This is deliberately simple and deterministic — no LLM call, no ambiguity about what got stored.
Stage 2 — Session summary
SessionSummarizer.summarizeAndStore() (packages/learning/src/session-summarizer.ts) tries an LLM summary first, falling back to a rule-based one:
- LLM path (
summarizeWithLlm): only runs if a real model provider is configured (isUsableModelProviderrejects themockprovider). Sends the last 10 messages with a strict system prompt asking for{"summary": "2-4 sentences..."}JSON, and parses the result defensively (handles fenced code blocks, trailing text) viaparseLlmJson. - Rule-based fallback (
summarizeWithRules): takes the last 3 user messages (first 120 chars each) as "Topics", plus the last assistant reply (first 280 chars) as "Last outcome". No API key required.
The result is stored as a summary-type memory entry. SessionSummaryJob.summarizeStaleSessions() (packages/learning/src/session-summary-job.ts) is the batch variant used by the session-memory-summarize automation (see Automation Engine) — it skips sessions that aren't completed, have fewer than 2 messages, or already have a summary entry.
Stage 3 — Skill draft proposal
SkillEvolutionSummarizer (packages/learning/src/skill-evolution-summarizer.ts) has two entry points:
fromSession()— requires a real last user message ≥ 40 characters and a last assistant reply. Prompts an LLM to decideshouldCreate: booleanplustopic,instructions,description,tags. IfshouldCreateisfalse, the pipeline stops here for this session — no draft is written. If no usable model provider is configured, it falls back to a rule-based proposal built directly from the last exchange.fromToolUse()— same shape, triggered per successful tool call (outcomemust be ≥ 20 characters). This is the Phase L6 "runtime tool learning" path: the agent can learn a reusable tool-usage pattern mid-session, not just at session end.
Both system prompts are explicit about being selective:
"Set
shouldCreate=falsewhen there is no clear repeatable pattern, preference, or workflow worth saving."
This matters: the learning loop is designed to avoid flooding your skill catalog with one-off, low-value drafts.
Stage 4 — Writing the draft
SkillEvolutionWriter.proposeDraft() (packages/learning/src/skill-evolution.ts) writes a new SkillDefinition to workspace/skills/_drafts/{slug}-draft-{timestamp}.md:
const definition = parseSkillDefinition({
apiVersion: 'anvio.io/v1',
kind: 'Skill',
metadata: { slug, version: '0.1.0', catalog: 'private' },
spec: {
name: input.topic,
description: input.description ?? `Draft skill from session ${input.sessionId} (${input.agentId})`,
instructions: `${input.instructions}\n\n## Source excerpt\n${input.sourceExcerpt}`,
tags: input.tags ?? ['draft', 'learning-loop'],
// permissions, toolRequirements, contextRequirements start empty
},
});Drafts are always rendered as Markdown (frontmatter + instructions body), regardless of how they were proposed — matching the skill-file format described in Skills.
Stage 5 — Promotion
Promotion behavior depends on the soul's evolution.requireApproval:
onSessionCompleted() always leaves the draft in _drafts/ — even with requireApproval: false. A human (or automation) runs anvio learning promote <draft-slug> to move it into workspace/skills/.
onToolUseCompleted() checks requireApproval: if it's false or unset (the schema default), the draft is promoted immediately in the same call via promoteDraft(). If requireApproval: true, the draft is left for manual promotion.
SkillEvolutionWriter.promoteDraft(slug, targetDir) looks for {slug}, {slug}.md, {slug}.yaml, {slug}.yml in _drafts/, strips the -draft-{timestamp} suffix from the filename, converts YAML drafts to the Markdown skill format if needed, and writes the result into workspace/skills/{base}.md.
anvio learning drafts # list pending drafts in workspace/skills/_drafts/
anvio learning promote <draft-slug> # promote one into workspace/skills/
anvio learning summarize-sessions # batch-run stale session summarizationLLM requirements
The LLM-enhanced paths (session summary, skill proposal) need a configured, non-mock model provider — typically ANTHROPIC_API_KEY set, or another real provider configured. The platform passes whichever provider is configured (Anthropic preferred, otherwise the first non-mock provider) into LearningEngine's constructor options. Without one, every stage still runs — just via its rule-based fallback. See Runtimes & Models Overview for provider configuration.
Enabling / disabling
Learning is controlled per-soul via the evolution block in SOUL.md (see Souls & Soul Gate):
spec:
evolution:
allowAutoUpdate: true # false = learning loop skipped entirely for this soul
requireApproval: false # false = tool-use skill drafts auto-promote; true = manual onlyRelated components at a glance
| Component | File | Role |
|---|---|---|
| Memory nudge | packages/learning/src/memory-nudge.ts | Regex fact extraction from user messages |
| Session summarizer | packages/learning/src/session-summarizer.ts | LLM summary with rule-based fallback |
| Session summary job | packages/learning/src/session-summary-job.ts | Batch summarization of stale sessions |
| Skill evolution summarizer | packages/learning/src/skill-evolution-summarizer.ts | LLM proposal (shouldCreate) from session or tool use |
| Skill evolution writer | packages/learning/src/skill-evolution.ts | Writes/lists/promotes drafts in workspace/skills/_drafts/ |
| Learning engine | packages/learning/src/index.ts | Orchestrates all of the above, gated by soul evolution settings |
Honcho sync (an optional external memory backend mentioned alongside the learning loop in the source docs) lives in @anvio/memory, not @anvio/learning — it's a memory provider concern, not part of this pipeline. See the memory provider documentation for filesystem vs Honcho vs other backends.
Related
Skills
The file format skill drafts are written in and promoted into.
Souls & Soul Gate
The evolution settings that gate this entire pipeline.
Automation Engine
The 'learning' automation action type that batch-runs session summarization.
Runtimes & Models
Configuring a real model provider for the LLM-enhanced paths.
Last updated on
Souls & Soul Gate
SOUL.md is an agent's durable identity and its harness policy gate — both parsed from the same Markdown file, never invented.
Agent-to-Agent Integration
How Anvio implements Google's A2A Protocol v1.0 — expose your agents to external A2A clients, and delegate tasks to external A2A agents from within Anvio.