ares

module
v0.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: Apache-2.0

README

           _____  ______  _____ 
     /\   |  __ \|  ____|/ ____|
    /  \  | |__) | |__  | (___  
   / /\ \ |  _  /|  __|  \___ \ 
  / ____ \| | \ \| |____ ____) |
 /_/    \_\_|  \_\______|_____/ 

Go CI Chaos CI codecov

Status — be precise about what you are getting

Area State
Kernel / task fabric / SDK exercised end-to-end and regression-locked; not a hardened runtime
GA evolution + patch pipeline runs end-to-end; evolution.objective defaults to strategy, so runtime patches need objective=runtime|both and runtime_patches.allow_live=true; the apply gate is installed and both loops share the NSGA-II dimension scoring
AKG (Adaptive Knowledge Graph) API frozen (0.3.4), schema versioned, tiered retrieval opt-in

AKG is the first attempt to build a knowledge graph without relying on LLMs (rule-based relation extraction, BM25-style lexical + vector hybrid search, deterministic quality scoring — no generative AI in the extraction loop) and it is the least finished part of the system. The Honest limits section below lists what this README knows it cannot yet claim; read it before trusting any number or capability here.


Why "ARES"?

ARES — Agent Operating System (AgentOS): runtime, kernel & GA evolution.

  • Name origin — Ares, the Greek god of war: the ares arena chaos scenarios literally pit candidates against faults and survival tests.
  • What the letters stood for — originally Agent Runtime & Evolution System: a runtime kernel plus a GA that evolves it (genomes, crossover, mutation; ares evolution).
  • What it is now — since v0.3.0 the kernel was promoted to an Agent Operating System (AgentOS): scheduling, synchronization, IPC, resource enforcement, lifecycle management and recovery. Evolution didn't disappear — it became a first-class subsystem of the OS (evidence-driven GA, evolving in production without restarts).

Agents are autonomous cognitive processes, not functions invoked by an orchestrator. They independently create work, communicate as peers, maintain private cognitive state, and may spawn other agents. The ARES Kernel provides scheduling, synchronization, IPC, resource enforcement, lifecycle management, and recovery.

Agents decide. The Kernel enforces. Agent death is an execution failure, not a task failure.

In practice: tasks are durable and outlive their executors (lease + epoch fencing + checkpoint + event-sourced recovery); execution is scheduled in cooperative semantic quanta (reason → tool → observe → checkpoint → yield); and scheduling policies — capability matching, load, confidence, priority — evolve in production without restarts. Built in Go with a unified SDK, DAG workflow, chaos engineering, and MCP support.

Quick Start

package main

import (
    "context"
    "fmt"

    "github.com/Timwood0x10/ares/api"
)

func main() {
    rt := api.MustNew() // reads ./ares.yaml (the single config entry point); use api.New(opts...) for fine-grained config
    defer rt.Close()

    agent := rt.NewAgent("assistant", api.WithInstruction("You are helpful."))
    result, _ := agent.Run(context.Background(), "hello")
    fmt.Println(result.Output)
}

Install the CLI:

go install github.com/Timwood0x10/ares/cmd/ares@latest
ares doctor
ares run -c ares.yaml "What is Go?"     # one command, human output, zero config flags

One interface, two faces — all configuration lives in ares.yaml (the single config entry point; there are no config flags). The same kernel (scheduler / DAG / GA / memory) is reachable in-process (above) or over HTTP when you run ares serve for non-Go callers:

ares init myproj && cd myproj   # generates ares.yaml incl. a security.api_key
ares serve &                    # boots the full AgentOS kernel from ares.yaml

# submit — the external one-interface entry: {"query": "..."} is enough
curl -sS -X POST localhost:8080/api/tasks \
  -H "Authorization: Bearer <security.api_key from ares.yaml>" \
  -H 'Content-Type: application/json' \
  -d '{"query":"analyze yesterday'"'"'s incidents"}'
# → 202 {"task_id":"...","status":"submitted"}
# bearer = security.api_key (dedicated HTTP credential, generated by ares init);
# when unset it falls back to llm.api_key. With NEITHER set (e.g. ollama,
# which needs no llm.api_key) the write gate answers 401 — deny-by-default,
# loopback included — so set security.api_key before serving.
# capability defaults to server.default_capability — NOTE: audit-only, the
# Submitter normalizes execution to the single L2 capability ares/plan

# read the result — GET /api/tasks/{task_id} (TaskView slim fields + result
# = the session answer on the L2 path; error carries the failure cause on
# FAILED)
curl -sS -H "Authorization: Bearer <security.api_key from ares.yaml>" \
  localhost:8080/api/tasks/<task_id>

# optional: POST /api/tasks?wait=<dur> blocks until the result resolves
# (empty value uses tasks.wait_timeout, default 60s; an explicit value over
# the 300s cap is REJECTED with 400, a configured default over it is clamped;
# expiry still answers 202 with the current state)

The HTTP layer is a thin adapter over the internal submitter — no scheduling logic lives there. server.default_capability and tasks.wait_timeout are set in ares.yaml like everything else.

Or assemble from a YAML config in code — one option loads everything:

rt := api.NewRuntime(api.WithConfig("ares.yaml")) // LLM / memory / distillation / evolution / tools, all from one file
defer rt.Close()

📖 Config guide: see config.yaml Guide (EN) / config.yaml 配置指南 (中文) for the full reference — LLM, distillation, GA evolution, knowledge, tools, and chaos-related switches.

Or run examples directly:

git clone https://github.com/Timwood0x10/ares
cd ares
make quickstart        # go run examples/01-quickstart
make examples          # build all examples

Features

Feature Description
Unified SDK Single api.MustNew() API for LLM, tools, memory, evolution; api.NewRuntime(api.WithConfig("ares.yaml")) for config-driven assembly
System Runtime lifecycle kernel Orchestrator reverse-topological start/stop + component snapshot observability + Degraded on missing deps; serve / start / SDK share one kernel
Evidence persistence evidence.PostgresStore accumulates GA feedback across restarts (the in-memory store resets on restart); opt-in + fail-loud via both serve and SDK
Runtime Evolution Genome + Diff Engine + Coordinator evolve DAG, scheduler, planner, recovery in production
Strategy GA Population-based strategy optimization — NSGA-II multi-objective, steady-state, uniform/two-point/segment crossover, 6 mutation types
Evidence-Driven Every runtime event (flight, chaos, fitness) feeds into evolution decisions
DAG Workflow Dynamic graphs with conditional branching and recovery
Chaos Resilient Fault injection, failover, survival testing, self-healing
Memory Session context, task distillation, vector similarity search
Durable archive & retention Per-stream event-round archive (concurrent streams never overwrite each other's rounds) + scheduled TTL purge across sessions / knowledge / conversations / secrets
AKG LLM-free knowledge graph — rule-based extraction + hybrid retrieval + quality gate
Candidate release pipeline (0.3.0) CandidatePipeline: candidate → 3-gate validation (static / evidence / regression) → release gate → SetStable; gate 3 uses LLMArenaScorer + BatchScorer (batched/merged requests) for LLM-driven retained-case regression, with FailoverClient multi-provider chains (openai / openrouter / anthropic / ollama) auto-switching
MCP Ready Connect any Model Context Protocol server for tools and data
Multi-Agent Capability-based agent registration (RegisterAgent) + task dispatch (Submit) with peer IPC and recovery
Observability OpenTelemetry traces, structured logs, Prometheus metrics

Tenancy Model

Single-tenant by default; per-request tenant scoping when you opt in. There is no config switch — the tenant_id field is the switch, at request granularity.

Mode Trigger Behavior
Default (single-tenant) Submit without tenant_id Everything runs under the default tenant — tasks, planner-grown nodes, ask_agent sessions, distilled facts and knowledge recall. Behavior is identical to a system with no tenant concept.
Opt-in (tenant-scoped) Submit with tenant_id (POST /api/tasks, POST /api/graphs, or payload["tenant_id"] on SDK submissions) That request and its derived work executes under that tenant; the experience/distillation store isolates per tenant column, the knowledge side isolates per namespace (see boundaries below).

How it holds together:

  • The tenant rides the task's checkpoint envelope (schema v5) through the scheduler's asynchronous execution, is restored into the quantum's context (tenantctx), and stamps downstream — grown tool/answer nodes, collaboration sessions, distillation. Empty means "no tenant known"; every consumer falls back to default.
  • Anti-forgery is Kernel-enforced: an LLM-supplied tenant_id in tool arguments, create_task payloads or ask_agent payloads is overwritten by the executing context's tenant (the same contract Origin follows). The system never generates a non-default tenant on its own.

Actual isolation boundaries (stated honestly — do not read this as end-to-end column-level tenancy):

  • Experience/distillation store: every query in internal/storage/postgres/repositories/experience_repository.go carries a tenant_id = $N predicate — column-level isolation. Distillation writes take the tenant through a context seam (distillation.WithTenant), so a runtime override reaches the write side.

  • Knowledge isolates by namespace, not by a tenant column: KnowledgeStore objects have a namespace column and no tenant_id column. StoreProvider maps tenant → namespace via namespaceFor (explicit Scope.Namespaces → tenantctx → provider default), so isolation depends on the caller always supplying one. The underlying Get/Delete/Search all carry AND namespace = ? predicates (store/postgres/store.go, store/sqlite/store.go), so cross-tenant access returns ErrObjectNotFound rather than leaking data.

  • AKG-distilled facts are not split per tenant: akgNamespace in internal/ares_bootstrap/knowledge_akg.go is the constant "default", passed straight into the distillation bridge (adapter/distill.go stores a fixed namespace), so every AKG fact lands in "default" regardless of the caller's tenant. Splitting them is a real design task, not a configuration flag.

  • Multi-tenant deployments: the tenant is currently caller-declared at the HTTP boundary. A genuine multi-tenant deployment must bind the tenant at the auth layer (e.g. derive it from the JWT principal server-side) rather than trust the request body — and the two knowledge-side gaps above must be closed first before the isolation is end to end. See SECURITY.md → Tenancy.

Honest limits

Every line below is the current state with the file that proves it. If a claim elsewhere in this README is not in this list, it is either verified in code or it is a bug in the README.

  • Tenancy is not end-to-end. The experience/distillation store isolates per tenant column, but the knowledge side isolates by namespace and depends on the caller supplying one; AKG-distilled facts default to the "default" namespace when no tenant context is present, and land in the caller's namespace when one is supplied. A real multi-tenant deployment must bind the tenant at the auth layer rather than trust the request body — see Tenancy Model above and SECURITY.md → Tenancy.
  • WithMaxTokens is a peer-lifetime budget, not a per-run cap. Since 0.3.1 it is enforced (no longer a silent no-op): it bridges into the runtime governance budget (sdk/sdk.go:441) and the scheduler's budgetOK gate stops an agent whose tokenUsed has reached TokenBudget at the next quantum boundary. Two real caveats: the budget is the L2 peer's lifetime total — the first positive value wins and later agents cannot tighten it — and enforcement is cooperative (yield at a quantum boundary, never mid-LLM-call) (sdk/options.go:703-717). <= 0 means unbounded.
  • ask_agent returns before the answer exists, but the answer is not lost. The call returns {status: "pending"}; when the target replies, it is delivered to the asker as a task whose payload carries an ask_reply entry, and the asking agent reads it in a later turn. "fire-and-forget" described the old path, where the reply was logged and dropped.
  • Tiered AKG recall is opt-in and still bounded by the same quality bar. With knowledge.tiered_retrieval, recall goes L1 (exact keywords over the store) then L2 (semantic + graph) instead of the single-shot path. It is off by default because it REPLACES how recall happens. Two properties are worth knowing before enabling it: L1 keeps the same minimum-confidence bar (0.4) the single-shot path enforces, and the merged result is capped at top_k — the tiered merge itself is not bounded, so the adapter caps by score. L1 is scoped to the resolved namespace (explicit > tenant > user > default tenant); an empty namespace would skip L1 entirely rather than recall across tenants.
  • Tool advertising is narrowed per task, and the narrowing fails open. The planner used to advertise the whole registry; each quantum now filters by ① L1 enabled (a ToolClass the evolution disabled is never shown), ② a static kernel.tool_tag_filter (all tags must match), ③ the task's capability tags (union). Tags come from the task payload when a submitter set them, otherwise from a keyword table in internal/tools/capability, otherwise from the model when kernel.llm_tool_tagging is on (one call per quantum). A filter matching nothing falls back to the previous set with a warning: an empty toolbelt is indistinguishable from "that tool does not exist". need_tools is the escape hatch for the partial-miss case, and it reaches the next quantum only because the kernel carries task-scoped payload keys across the checkpoint re-wrap. MCP tools take part in this path: at registration an MCP tool derives cap_* tags from its advertised description (MCP carries prose, not metadata), so capability routing can select it. A tool that declares no capability at all is never hidden by capability matching — a filter must not drop a tool it cannot judge.
  • The resilience score's measured inputs need samples before they mean anything. Recovery timing and data consistency are now both produced: the recovery path notifies an observer on each successful revival, and every task-lifecycle checkpoint decode notifies one too (both wired in cmd/ares). Two limits remain. A rate is published only after enough samples, so a fresh process reports the input as unmeasured until then; and a deployment that never resumes a task never decodes a checkpoint, so its consistency input stays unmeasured indefinitely. MetricsSnapshot.Unmeasured names whichever input lacks samples rather than letting a zero look like a measurement.
  • The GA proposes; the kernel disposes. Nothing the evolution loop produces reaches a running strategy without passing the kernel: a candidate is a proposal plus its evidence, the apply path is gated on manual approval when the lifecycle is holding one, and knowledge is never allowed to grade a candidate. Concretely, GA may tune parameters, choose and combine strategies, and bias candidate generation — it may not bypass permissions, exceed a budget or blast-radius, change running state behind the kernel's back, or apply its own patch. The intended rollout order is one production objective at a time (agent policy parameters first), proving the full six-step loop before widening: running several evolving subsystems at once makes every regression ambiguous.
  • Experiment records are durable, and a verdict is a second record. ExperimentRecord captures what makes a run replayable (genome, the evidence that narrowed it, the fitness configuration in force — copied, not referenced — the gate verdicts, and the outcome once observed). FileExperimentLog appends JSONL and fsyncs every record; it is armed by evolution.experiment_log_path (empty = off, which seals nothing). A generation seals outcome: pending; the lifecycle seals a second record with the verdict and a ProposalKey pointing at the proposal, because the two are decided at different times by different components — rewriting the first would erase the fact that the proposal preceded the verdict. Knowledge narrows candidates only: recording an outcome deliberately writes nothing back to the graph, which is what keeps the GA from reinforcing its own opinion.
  • Multi-objective GA is wired on both evolution paths, from one implementation. The dimension pass lives on genome.Population (ScoreAgentsWithDimensions), so the public service and the in-process EvolveAfterScoring loop fill DimensionScores from per-candidate execution evidence (strategy → success_rate, dimension_eval → quality) and "nsga2" ranks by Pareto dominance. Without a dimension scorer, or for a candidate with no evidence, selection uses the scalar score. cost and latency are filled from a separate metrics channel (the observer records the inverse of its own penalties, so 0 = fastest or cheapest) and are ranked as Minimize objectives. They are kept out of the fitness mean and out of the staging sample count on purpose: folding a spending target into "fitness" would make a slow-but-correct candidate score worse than a fast-and-wrong one.
  • The GA apply gate is installed but narrow. It refuses a patch whose strategy the lifecycle is holding for manual approval; unattributed component patches pass (the deployment adapter already refuses those as unmeasurable), and with nothing held — the default — every patch passes. It does not grade quality: that stays the coordinator's own fitness threshold, which is why the type is still named UngatedPatcher.
  • Scheduling is cooperative, not preemptive at the token level. An agent yields only at a ReAct-round boundary; a runaway LLM call is bounded by a timeout, not sliced.
  • The default fabric is in-memory and single-process. Task durability across a restart requires the Postgres-backed event store; this is not a distributed scheduler.
  • AKG API is frozen (0.3.4): the core types (KnowledgeObject, GraphProvider, KnowledgeStore) and the 4 MCP tools are stable. Schema versioning (SchemaVersion) and temporal fields (valid_from/valid_until/observed_at/source_version) are additive — zero values preserve pre-0.3.4 behaviour.
  • Most 0.3.4 AKG features are not wired into production yet — the API surface is frozen, the features behind it are not live. Verified by repo-wide grep for non-test callers: the M2.5 relation validation gate (ValidateRelation / FilterRelations), M4 build observability (BuildReport / ContentFingerprint), and M6 tiered retrieval + eval (TieredRetriever / EvalHarness) all have zero production callers, and each carries a TODO(tech-debt) at its definition. Two exceptions, both operator surfaces (never MCP tools — a knowledge dump is not a capability to hand a model): M4 archival (ApplyDecay) runs on the maintenance sweep when knowledge.decay_archive_after is set (off by default), visiting each namespace the store lists; and M3's snapshot + migration surface (ExportStore / ImportStore / MigrateNamespace) is driven by ares knowledge export|import|migrate, which requires the persistent Postgres store. A snapshot carries embedding vectors, not only objects — without them a restore silently degraded recall to lexical. Do not read "API frozen" as "the features shipped".
  • M5 "one user one graph" is wired, but only takes effect when a submission declares a user. The user is caller-declared (submit user_id), carried in the task payload — which the checkpoint envelope already persists, so no envelope schema change was needed — stamped onto the execution context as userctx (mirroring tenantctx) and resolved to tu:<hash(tenant)>:<hash(user)> on both the write (DistillBridge) and read (StoreProvider) sides. With no user_id the behaviour is unchanged (the tenant namespace). Three caveats: facts written before a user is declared live under the tenant/default namespace, so enabling user_id makes them invisible to user-scoped recall until migrated — ares knowledge migrate --from <ns> --tenant T --user U re-homes them, and it is a move, not a copy: the store keys objects by ID alone and refuses to re-home an ID under a different namespace, so a copy would need new IDs while leaving the facts visible to exactly the tenant-scoped recall the move exists to scope down. Vectors travel with their objects, a failed save is rolled back rather than dropping the fact, and a re-run resumes with whatever is left in the source. The user, like the tenant, is caller-declared rather than derived from the authenticated principal (see Tenancy Model / SECURITY.md); and the AKG store defaults to in-memory — buildBootstrapKnowledgeStore returns the in-memory store unless storage.enabled: true plus a Postgres host is configured — so a distilled user graph does not survive a restart out of the box.
  • The whole loop needs three switches, and all three default off. Declare user_id on the submission, run a persistent store (storage.enabled: true + Postgres), and opt into recall injection (memory.enable_rag: true — retrieval fires only when that gate is on and retrievers are wired). With any switch missing the AKG pipeline still runs, but in-process only and only through the explicit MCP tools; "the longer you use it, the better it knows you" is not the default behaviour.
  • Benchmarks are single-run and single-machine (Apple M3 Max, -benchtime=500ms): a smoke baseline for before/after comparison, not an SLA.
  • Coverage is uneven. cmd/ares (the HTTP/serve surface) and the discovery/introspection paths are the thinnest, and that is where the review batches keep finding defects.

Stability & Performance

The 0.3.1 hardening cycle closed every crash and leak class the deep reviews found — each with a lock-in test — and committed a performance baseline that future changes must compare against. No claim here is "all known defects fixed": the 0.3.1 batch alone was ~230 review findings, and each cycle finds more.

Where the records live:

  • The stability program (planned outside this repo, executed inside it): lock-in tests for every fixed defect, goleak gates on the kernel and workflow-engine packages, HTTP panic guard + request-ID observability, flake attribution, and a soak harness (SOAK_SECONDS=N go test ./tests/soak/)
  • benchmarks/ — the committed benchmark baseline (benchmark_report.md, benchmark_results.json) and the benchstat comparison workflow; any optimization PR must show a before/after comparison. (Do not link plan/ from the repo: that tree is local-only and gitignored.)

Two examples of what "lock-in test" means: the AKG short-query panic (a nil knowledge repo dereferenced by the precision pipeline) now fails loudly with a config error — locked by retrieval_nil_kbrepo_test.go — and every HTTP handler runs under a panic guard that returns a structured 500 with a request ID instead of dropping the connection. Full narrative: docs/articles/.

Baseline headline numbers (Apple M3 Max, 14 cores; -benchtime=500ms -count=1; re-measured 2026-10-09 for 0.3.2): scheduler drain 1.03ms per 100 tasks (~10µs/task, 4,525 allocs), empty tick 8.6ns (zero allocs), 64-node L2 growth chain 132ms (1.41MB, 13,733 allocs), and AKG retrieval 13.0ms / 100 objs, 139ms / 500 objs. benchmarks/benchmark_report.md holds the per-package tables (2026-09-12 baseline + 2026-10-09 re-run); benchmark_results.json is the 2026-09-12 structured set.

Quality gate: make check (vet + staticcheck + golangci-lint + tests) must stay green on every change.

AKG — Knowledge Graph Without LLMs (Experimental)

AKG API is frozen as of 0.3.4 (see the Status table at the top). Schema versioning and temporal fields are additive.

Exploration goal

AKG is an experiment with one question: can we build a precise, queryable knowledge graph from source material WITHOUT a generative LLM in the extraction loop? The current pipeline uses only embeddings + rules + deterministic scoring — no LLM calls during the write/build/retrieve path. The goal is to measure how far rule-based extraction and hybrid retrieval can go before an LLM becomes a necessity, and to keep the knowledge layer cheap, reproducible, and fully offline-capable.

How the LLM-free loop works

Write:  source → KnowledgeObject (Raw/Normalized/Summary) → RelationExtractor (rules)
                → EmbeddingService → QualityGate → KnowledgeStore
Retrieve: query → EmbeddingService → HybridSearch (0.7·vector + 0.3·lexical)
                → ranked KnowledgeObjects → ContextSnippet
Inject:   ContextSnippets → the Agent's reasoning LLM (the ONLY place an LLM is involved)

The LLM never participates in extraction or build — it only consumes the retrieved facts at inference time.

Current capabilities (no LLM in the loop)

  • Three-layer KnowledgeObject (Raw → Normalized → Summary) with evidence/provenance tracing.
  • Rule-based relation extraction over a closed predicate vocabulary: calls, fixes, depends_on, belongs_to, similar_to, supersedes, causes, related_to.
  • Multi-dimensional QualityGate (extraction / consistency / freshness / usage) driving a candidate → active → superseded/rejected lifecycle with promotion.
  • HybridSearch: vector cosine + lexical Jaccard, filtered by namespace and status.
  • Multi-backend persistence: Memory, SQLite, PostgreSQL.

Honest limitations

  • No entity disambiguation — two facts about "Redis" are not merged into one entity.
  • No semantic relation inference — only rule-pattern matches are extracted.
  • No abstractive summarization — Summary is extracted/normalized text, not LLM-generated.
  • Rule regexes can be greedy on unusual formatting.
  • Vector recall is in-process brute-force cosine — fine for tens of thousands of vectors, not millions.

Extensibility — the architecture is open

Extension point What to do Interface touched
New database backend Add internal/knowledge/store/<name>/store.go implementing KnowledgeStore. Shipped: Memory, SQLite, PostgreSQL. A MySQL / CockroachDB / TiDB / Spanner backend is one file each — none has been written yet. KnowledgeStore (unchanged for new backends)
Professional vector DB Add vector recall inside your KnowledgeStore implementation (the PostgreSQL store already uses pgvector ORDER BY embedding <=> $1 for HybridSearch). KnowledgeStore (unchanged for new backends)
Multi-tenancy Per-request opt-in (see Tenancy Model): the submission's tenant_id rides the checkpoint envelope into the execution context. Isolation is layered: the experience/distillation store isolates per tenant column (queries carry a tenant_id predicate); the knowledge side isolates per namespace, not a tenant column, and AKG facts currently all write to the default namespace. Default deployment is single-tenant (default). No new interface

Design invariant: KnowledgeStore is the single persistence contract. Adding a database or a vector index never changes it — only new implementations appear. This is what keeps the upper runtime logic untouched as the storage layer evolves.

Module Map

Start from "I want to use capability X" and find the code in one step.

CLI

# Minimal setup — only the LLM endpoint is required; all subsystems
# (agents, memory, tools, storage) are assembled by the runtime from defaults.
ares serve --llm-url https://api.openai.com/v1 --llm-api-key sk-...
ares serve --llm-url http://localhost:11434               # local ollama (no key)
ares serve              # Full agent monitoring from config file (LLM + MCP + dashboard)
ares arena run/validate/list/serve/survival/inspect  # Chaos engineering scenarios
ares evolution run/status         # Runtime evolution
ares flight inspect/replay        # Inspect and replay task recordings
ares knowledge build <goal>       # Build a knowledge graph (via HTTP API)
ares recall query/round           # Query and step through recorded task memory
ares mcp-null serve     # Start minimal MCP null server (stdio)
ares db migrate/setup-test/create-table/check-rls  # Database management
ares auth token         # Issue / inspect JWT tokens
ares init               # Scaffold a new project (main.go + ares.yaml)
ares run                # Run agent from config file
ares bench              # Quick performance benchmark
ares doctor             # Diagnose environment (LLM key, Ollama, Git)
ares status             # Show runtime status at a glance (config / agents / kernel policy)
ares version            # Show version

SDK

import "github.com/Timwood0x10/ares/api"

rt, err := api.New(
    api.WithOpenAI("gpt-4o-mini"),          // or WithOllama, WithAnthropic
    api.WithDefaultMemory(),                 // session history
    api.WithEvolution(),                     // strategy evolution
    api.WithMCP(api.MCPConn{               // MCP server tools
        Name: "my-server", Command: "/path/to/server", Args: []string{"serve"},
    }),
)
if err != nil {
    log.Fatal(err)
}
defer rt.Close()

// Agent with tools.
agent := rt.NewAgent("assistant",
    api.WithInstruction("You are helpful."),
    api.WithTools(calculatorTool, weatherTool),
)
result, _ := agent.Run(ctx, "Calculate 15*23")

// NOTE: api.WithHumanInput is deprecated and NOT enforced — the L2 execution
// path has no per-tool-call approval hook, so Agent.Run refuses with
// api.ErrHumanInputUnsupported rather than silently ignoring the gate.
// Use api.WithAgentGovernance(tokens, tools, deadline) to bound a run.

// Streaming response.
ch, _ := agent.Stream(ctx, "Tell me a story")
for chunk := range ch { fmt.Print(chunk.Content) }

// Multi-agent: register capabilities and submit tasks.
rt.RegisterAgent("researcher", api.WithInstruction("You research."))
rt.RegisterAgent("writer", api.WithInstruction("You write."))
result, _ := rt.Submit(ctx, api.Task{Capability: "researcher", Input: "Find sources on Go."})

See examples/README.md for hands-on examples.

Agent-OS Primitives (2026-08)

Platform-level primitives added since 0.3.0, all additive and tested. They are the "agent OS" building blocks distilled from the prime-agent comparison.

Primitive Package / API Purpose
Active tools subset internal/tools/resources/core: Registry.SetActiveTools / ActiveTools / ClearActiveTools Advertise only the active tool subset to the LLM (progressive disclosure)
Native command discovery internal/tools/discovery Probe command -v + --help for allowlisted host commands and expose them as tools (tools.native_allowlist)
Peer messaging internal/agents/peer Direct agent-to-agent message registry + delivery
Small-step evolution internal/runtime/ares_evolution/refine Baseline-checked, rollback-capable supplement-state updates (plan → apply → rollback)
Capability Fabric (SkillCatalog) internal/runtime/protocol/skills: Catalog / SourceManager / Indexer / Discovery / Loader / Resolver / Experience Skill = capability package: declared-source metadata index (no disk scanning), progressive disclosure metadata → SKILL.md → resources, trust-gated tool resolution (MCP / Executable / Builtin), learned-source relevance priors
Output guard internal/agents/outputguard Reject structurally inconsistent agent results at the boundary
Run budgets api.WithMaxTokens (governance token budget) / api.WithTimeout (Task.Timeout) Both enforced on the L2 path since 0.3.1, at quantum boundaries. WithMaxTokens is the peer's lifetime budget (first positive value wins, not a per-run allowance)
Fingerprint cache internal/runtime/arena: WithFingerprint Skip re-running regression when the environment is unchanged
Skills (progressive disclosure) internal/knowledge/skills Description resident in context; detail loaded on demand
Session lease internal/agents/lease Exclusive expiring holds for concurrent session access
Task Fabric internal/fabric/task Durable Task state machine (cross-restart rebuild from the event log via RestoreFromStore; non-terminal tasks resume from checkpoint unowned) + Lease/fencing (epoch) + capability-aware Scheduler (Score/Pick/Schedule) + Work Stealing + DAG ReadyTasks + cooperative preempt (0.3.0 Kernel Scheduler pillar)
Agent Fabric internal/fabric/agent spawn/suspend/resume/retire/kill/recover + Process Tree (provenance, not hierarchy) + Cognitive State + 3-layer Context + P5 resource quota (WithResourceBudget) (0.3.0 Kernel Lifecycle pillar)
Agent IPC internal/agentipc Peer Send/Request/Reply/Delegate/Handoff/Subscribe (task dispatch lives in the HTTP submit path + kernelScheduler, not here) (0.3.0 Kernel IPC pillar)
Runtime Recovery internal/aresrecovery lease-expiry requeue / checkpoint resume / agent restart / Chaos fault-injection validation (Agent death ≠ Task death)
Kernel assembly cmd/ares/kernel.go + agent_kernel.go kernelScheduler — HTTP-submitted tasks (submitPeerTask / POST /api/graphs) + subagents[].dependencies DAG wiring (kernel.policy is display-only in ares status)

Wiring: output guard validates sub-agent results; native tools and the peer registry are wired in cmd/ares/serve.go; state snapshots ride workflow checkpoints; strategy feedback flows through the refine trail; run budgets are exposed via the SDK options above.

Articles

Deep dives into ARES internals:

English 中文
Architecture 架构
Agent Harmony Agent 通信协议
Memory & Distillation 记忆与蒸馏
Workflow Engine 工作流引擎
Tool System 工具系统
Security & Observability 安全与可观测性
Runtime Lifecycle 运行时生命周期
Event System 事件系统
Chaos Arena 混沌测试
Retrieval System 检索系统
Autonomous Evolution 自主进化
Security Hardening 安全加固
Bootstrap & API Bootstrap 与 API
Plugin System 插件系统
MCP Integration MCP 集成
Flight Recorder Flight Recorder
SDK Layer SDK 层
Knowledge Graph Build 知识图谱构建
Storage Layer 存储层
LLM Client Layer LLM 客户端层
Evaluation Framework 评估框架
Config System 配置系统
Quant Trading Module 量化交易模块
GA Deep Dive GA 深度解析
GA Tiered Scorer GA 分层评分
GA Selection Benchmark GA 选择算子对比
GA Promoter GA 晋升系统
GA Genealogy GA 谱系记录
GA in the Trenches GA 实战经验
config.yaml Guide config.yaml 配置指南

Architecture

Closed-Loop Runtime Architecture (ultimate view)

Two views: the component map (forward wiring, top to bottom in bootstrap order) and the six feedback loops that close back onto the runtime. Every loop is regression-locked (table below).

The full component map (bootstrap order, all 38 packages, data flow and the step-by-step POST /api/tasks walkthrough) lives in ARCHITECTURE.md; this README keeps only the feedback loops and the mental model.

The six closed loops (dashed edges = feedback closing back on the runtime)

flowchart LR
    subgraph LOOPS["Six closed loops (feedback edges only)"]
        direction TB
        API["Console<br/>:8080"]
        FABRIC["Task Fabric<br/>+ lease Renew"]
        SCHED["KernelScheduler"]
        AG["Peer agents"]
        STRAT["StrategyStore"]
        DIS["Distillation<br/>ExpRepo"]
        KR["KnowledgeRuntime<br/>AKG store"]
        REC["Recovery"]
        OBS["Observability<br/>introspect routes"]
    end

    API -- "L1 submit / result reflux" --> FABRIC
    FABRIC --> SCHED -- "run quantum" --> AG

    SCHED -. "L2 fitness" .-> STRAT
    STRAT -. "L2 strategy → executors" .-> AG

    SCHED -. "L3 finalize events" .-> DIS
    DIS -. "L3 spawn prior + RAG context" .-> AG

    DIS -. "L4 facts" .-> KR
    KR -. "L4 AKF tools" .-> AG

    AFABK["agent kill"] -. "L5 expiry → requeue → W1 rebind" .-> SCHED
    SCHED -. "L5 renew heartbeat" .-> FABRIC

    SCHED -. "L6 traces · feedback · spans" .-> OBS

    style STRAT fill:#2d1b69,stroke:#8b5cf6,color:#fff
    style DIS fill:#1a2332,stroke:#64748b,color:#fff
    style KR fill:#1a2332,stroke:#64748b,color:#fff
    style REC fill:#3b2f2f,stroke:#f59e0b,color:#fff
    style OBS fill:#1a3a2a,stroke:#22c55e,color:#fff

The six loops, and what locks them shut:

Loop Closed path Regression lock
L1 task POST /api/tasks → Fabric → scheduler quantum (lease renewed while running) → result reflux through checkpoint TestGraphsEndpoint*, TestSchedulerRenewsLeaseDuringLongQuantum
L2 strategy flight fitness → evidence → GA genome → diff → coordinator → deployment pipeline (staging never mutates live state) → StrategyStore → StrategySource injected into every executor TestDeploymentStaging_DoesNotMutateLiveRegistry, TestUpdateLiveDAG_WiredFromServeShape
L3 distillation task-finalize events → distillation → experience repo → spawn prior (G1) + RAG retrieval bootstrap closure suite
L4 knowledge DistillBridge → AKG store → shared KnowledgeRuntime ↔ AKF tools; knowledge patches hit the same instance (recovery.strategy target registered) TestUpdateLiveDAG_*, patch-registry tests
L5 recovery kill → lease expiry (heartbeat-aware) → requeue → W1 replacement bound → checkpoint resume; zombie registrations swept per drain TestReconcileFabricDeaths_*, TestSchedulerAttributesFailureAsFailure
L6 observability runtime hooks write tracers/feedback/spans → introspect ControlServer (/api/observability/*, /api/flight/*, /api/evolution/*) reads them live bootstrap dashboard tests

Runtime Kernel (0.3.0)

ARES is an agent-oriented dynamic compute runtime: agents are not orchestrated, they are scheduled — the leader/sub hierarchy is gone and one kernelScheduler drives every path (the legacy dual-track execution policy was retired in v0.3.3).

Pillar Package Responsibility
Scheduler internal/fabric/task durable task state machine + lease/epoch fencing, cap×load×conf scoring, work stealing, DAG ReadyTasks, cooperative preempt
IPC internal/agentipc peer Send/Request/Reply/Delegate/Handoff/Subscribe (dispatch retired to the HTTP submit path + kernelScheduler)
Lifecycle internal/fabric/agent spawn/suspend/resume/retire/kill/recover, process-tree provenance, cognitive state, resource quota

Recovery (internal/aresrecovery) is what makes agent death ≠ task death: lease expiry → requeue → checkpoint resume on another executor. Full design: zh / en.

The mental model: agent-as-process, task-as-thread-of-work

ARES borrows the operating-system scheduling model as a design lens — it is an analogy that shapes the API, not a claim to be a real OS. The mapping is literal in the code:

OS concept ARES Where
Process / PCB Task — durable, outlives its executor, has an explicit state machine (READY→RUNNING→SUSPENDED→…) internal/fabric/task
Ownership / fencing token Lease + epoch — a resumed task rejects a stale owner's late write fabric/task.Fabric.Acquire/Preempt
Scheduled execution unit Agent — acquires a task, runs it, yields it back internal/fabric/agent + internal/kernel
Time slice Quantum — one ReAct round (reason → tool → observe → checkpoint), then yield fabric/agent/planner_cognition.go, fabric/task.Fabric.Yield
Context save/restore Checkpoint + event-sourced replay — a crashed agent's task is requeued and resumed elsewhere internal/aresrecovery
Scheduler policy capability match × load × confidence, priority, work-stealing kernel.Scheduler

Be precise about what this is and isn't:

  • Scheduling is cooperative, not preemptive at the token level. An agent yields only at a semantic boundary — the end of a ReAct round — never mid-LLM-call. PreemptLowerPriority marks a lower-priority task READY at the next quantum boundary; it does not interrupt an in-flight step. A single runaway LLM call is bounded by a timeout, not sliced.
  • A "quantum" is one tool round, not a CPU instruction. Granularity is coarse by design — the unit of scheduling is a cognitive step.
  • The default fabric is in-memory and single-process. Durability of tasks across a restart requires the Postgres-backed event store; the analogy does not imply a distributed scheduler.
  • This is experimental. The model is implemented and tested (durable task state machine, lease/epoch fencing, quantum yield/resume, recovery), but it is a runtime design under active change, not a hardened kernel.

The one invariant that pays for the whole model: an agent crashing is an execution failure, not a task failure — the task's lease expires, it returns to READY, and its checkpoint resumes on another executor.

Data Flow

sequenceDiagram
    participant U as User
    participant S as SDK
    participant A as Agent
    participant GA as GA Engine
    participant C as Coordinator
    participant E as Executors
    participant M as Memory

    U->>S: rt.Evolve(agent, task)
    S->>GA: Create Population(10)
    loop 3 generations
        GA->>GA: ScoreAgents(execution results)
        GA->>GA: Evolve(selection → crossover → mutation)
    end
    GA->>S: BestStrategy params
    S->>A: applyEvolvedParams(tool_selector, search_depth, scheduler...)

    Note over S,A: Strategy params applied to live agent

    U->>A: agent.Run(task)
    A->>M: Read strategy, load tools
    A->>A: Execute with evolved params
    A->>C: Submit evidence
    C->>E: Apply patches if needed

    Note over GA,C: Background: ticker + scheduler trigger evolution
    loop Every 5min
        GA->>GA: Run evolution cycle
        GA->>C: submitToCoordinator(patches)
        C->>E: Evaluate & Apply
    end

Cookbook

Recipe Code
Chat Agent 20-line conversational agent
Tool Calling Custom tools for LLM function calling
Multi-Agent Capability-based registration and task dispatch
Memory Persistent conversation context
Coding Agent Code generation with specialized instructions
Code Review Automated PR review
GitHub Agent Issue and PR automation

Runtime Evolution

ARES's runtime evolution system is evidence-driven: every execution, fault, and insight produces Evidence, which feeds into the evolution cycle. The system evolves DAG topology, scheduler selection, knowledge planner parameters, and recovery strategies — all in production, without restarts.

Architecture

Execution → Evidence → Genome → Candidate → Diff Engine → RuntimePatch → Coordinator → Apply
Component Role Sources
5 Genomes Generate candidate configurations via mutation + crossover workflow, scheduler, knowledge, recovery, prompt
4 Differs Compare old vs new snapshots → produce RuntimePatches workflow, knowledge, scheduler, recovery
Coordinator Decides Apply/Reject/Delay for each PatchProposal GA, Chaos, AKF, LLM, Human, K8s, Rule
3 Executors Apply patches to live runtime Graph, Knowledge, Recovery
LLM Adapter Converts natural-language suggestions into PatchProposals parsed format → Coordinator

Key design: LLM is a participant, not a controller. The Coordinator treats all 7 PatchSource values equally. No source has privileged access.

Re-measured 2026-10-09 for 0.3.2 (-benchtime=500ms -count=1 -benchmem, Apple M3 Max 14 cores, go1.27.1). Full per-package tables and the 2026-09-12 baseline: benchmarks/benchmark_report.md.

Benchmark time B/op allocs/op
Bus_Send (IPC) 303ns 400 8
Fabric_Schedule 552ns 444 10
Fabric_RunQuantum 1.31µs 1.2KB 16
SchedulerDrainEmpty 8.6ns – 0
SchedulerDrain100Tasks 1.03ms 578KB 4,525
L2GraphGrowthChain64 132ms 1.41MB 13,733
KnowledgePlanner_Plan 740ns 1.0KB 14
Retriever_Retrieve / 100 objs 13.0ms 11.2MB 100,202
Retriever_Retrieve / 500 objs 139ms 106MB 1,029,675
SimilarityLinker / 500 objs 18.6ms 79.8MB 2,032
ExactMatchEvaluator_Evaluate 2.3ns – 0
UngatedPatcher_Evaluate 6.3ns – 0

CLI

ares evolution status   # Show genomes, differs, coordinator state
ares evolution run      # Run one evolution cycle

Examples

go run examples/_internal/11-knowledge-import/ --dir ./notes          # Ingest markdown into pgvector
go run examples/_internal/11-knowledge-import/ --ask "question"       # RAG query against KB
go run examples/_internal/11-knowledge-import/ --evolve "task"        # GA evolution on import
go run examples/_internal/11-knowledge-import/ --chat                 # Interactive chat with tools
go run examples/_internal/11-knowledge-import/ --team --dir ./notes   # Multi-agent import
go run examples/_internal/11-knowledge-import/ --chaos-fail 0.3       # With fault injection
go run examples/_internal/11-knowledge-import/akg/                    # Build AKG from KB
go run examples/_internal/runtime_evolution/basic/      # Full end-to-end evolution demo
go run examples/_internal/runtime_evolution/knowledge/  # Knowledge parameter evolution
go run examples/_internal/runtime_evolution/full/       # All 4 genomes + real executors

Strategy Evolution (GA)

Beyond runtime-level evolution, ARES includes a strategy-level Genetic Algorithm that optimizes agent inference parameters (temperature, top_k, prompt templates, tool configs) through population-based search. The system evolves a population of strategies across generations using selection, crossover, and mutation, with zero-cost background evolution cycles.

Key Features

Feature Description
NSGA-II Multi-Objective 4 default dimensions (success_rate 0.40, quality 0.25, cost 0.20, latency 0.15) with direction-aware Pareto dominance
Steady-State GA Configurable replace rate (0.1–0.5, default 0.3) — replaces only the worst individuals each generation
Score / SelectionScore Canonical score preserved; selection score adjusted by fitness sharing for diversity
Fitness Sharing 3 strategies — full O(n²), reservoir sampling, spatial grid index (for >500 individuals)
3 Crossover Types Uniform (per-gene), Two-Point (swap segment), Segment (contiguous block)
6 Mutation Types Parameter, Prompt, Tool, Swap, Inversion, Scramble
Evolution Callbacks OnGeneration / OnFitness / OnMutation / OnCrossover
Termination MaxGenerations + TargetFitness (stops when BestEverScore ≥ target)
Generation History Per-generation snapshots with metadata
Experience System 3-tier pipeline: ToolCallRecord → RawExperience → NormalizedExperience → EvolutionHint → GuidanceProvider

Benchmarks (Apple M3 Max, darwin/arm64, 2026-09-12)

=== GA Genome (internal/runtime/ares_evolution/genome) ===
CrossoverUniform (10 params)          262k    2.29µs   2.97KB     31 allocs
CrossoverUniform (100 params)        34.1k    17.2µs   20.6KB     38 allocs
TruncationSelection (pop=100)        103k     5.82µs   952B        3 allocs
TournamentSelection (pop=50,k=2)     158k     3.84µs   13.3KB    101 allocs
RouletteWheelSelection (pop=100)     208k     3.02µs   3.34KB      7 allocs
Evolve_OneGeneration (pop=100)       2.22M    271ns    344B        6 allocs
Evolve_MultipleGenerations (100)     23.2k    26.3µs   33.6KB    600 allocs
ApplyFitnessSharing (pop=100)        429      1.36ms   527KB     106 allocs
RealWorldEvolution (100 gen)         58       10.5ms   4.31MB  61922 allocs

Examples

go run examples/_internal/10-ga-full-evolution/main.go   # Full GA evolution demo
go run examples/_fixtures/05-evolution-demo/main.go       # Pre-NSGA-II evolution demo

License

Apache 2.0

Acknowledgments

ARES's genetic algorithm implementation was inspired by the design and features of PyGAD — the Python genetic algorithm library by Ahmed F. Gad. PyGAD's architecture, operator design, and multi-objective optimization capabilities served as a valuable reference for building the GA engine in this project.

We recommend PyGAD for anyone looking for a mature, well-documented GA library in Python:

Additional GA concepts and terminology follow the standard definitions from the Genetic Algorithm article on Wikipedia.

Directories

Path Synopsis
Package ares is the public API for the ARES agent runtime.
Package ares is the public API for the ARES agent runtime.
cmd
ares command
agent — the control-plane actionHandler skeleton: the endpoint registry (M-S2) and its dispatch/authz core, plus the panel/cost read adapters.
agent — the control-plane actionHandler skeleton: the endpoint registry (M-S2) and its dispatch/authz core, plus the panel/cost read adapters.
mock-db command
Command mock-db provides a local sqlite mock database for tests that need a storage table without a PostgreSQL instance.
Command mock-db provides a local sqlite mock database for tests that need a storage table without a PostgreSQL instance.
examples
_fixtures/01-quickstart command
Quickstart — the golden path: one interface, the whole AgentOS kernel.
Quickstart — the golden path: one interface, the whole AgentOS kernel.
_fixtures/02-tool-calling command
Tool calling — demonstrates how to create and use multiple tools with ARES.
Tool calling — demonstrates how to create and use multiple tools with ARES.
_fixtures/03-dag-workflow command
DAG workflow — dynamic orchestration with the peer Runtime (ares.Graph).
DAG workflow — dynamic orchestration with the peer Runtime (ares.Graph).
_fixtures/04-multi-agent command
Multi-agent — demonstrates multiple specialised agents with the peer Runtime (H1: RegisterAgent + Submit, no leader/sub).
Multi-agent — demonstrates multiple specialised agents with the peer Runtime (H1: RegisterAgent + Submit, no leader/sub).
_fixtures/05-evolution-demo command
Evolution demo — demonstrates strategy evolution to improve agent performance.
Evolution demo — demonstrates strategy evolution to improve agent performance.
_fixtures/06-chaos-resilience command
Chaos resilience — demonstrates real failure handling and self-healing patterns.
Chaos resilience — demonstrates real failure handling and self-healing patterns.
_fixtures/07-human-in-loop command
Human-in-loop — why the approval callback is refused, and what to use instead.
Human-in-loop — why the approval callback is refused, and what to use instead.
_fixtures/08-mcp-integration command
MCP integration — demonstrates connecting to an MCP server and using its tools.
MCP integration — demonstrates connecting to an MCP server and using its tools.
_fixtures/09-full-app command
Example 09 — Full App: a complete ARES application with a web UI.
Example 09 — Full App: a complete ARES application with a web UI.
_fixtures/12-yaml-driven-flags command
Example 12 — YAML-driven flags: the "one yaml + one go file starts an agent" philosophy.
Example 12 — YAML-driven flags: the "one yaml + one go file starts an agent" philosophy.
_fixtures/27-peer-spawn-demo command
Peer-spawn demo — prove a REAL LLM autonomously decomposes a task.
Peer-spawn demo — prove a REAL LLM autonomously decomposes a task.
_fixtures/28-collab-graphs command
Collaboration graphs — submit an explicit DAG over HTTP and let the kernel execute it (fusion plan Phase C4: ares.Graph shapes reachable from ops).
Collaboration graphs — submit an explicit DAG over HTTP and let the kernel execute it (fusion plan Phase C4: ares.Graph shapes reachable from ops).
_fixtures/30-agentos-capabilities command
AgentOS capabilities — showcase the full agent operating system features.
AgentOS capabilities — showcase the full agent operating system features.
_fixtures/31-memory-distillation command
Memory distillation — demonstrate automatic knowledge extraction from conversations.
Memory distillation — demonstrate automatic knowledge extraction from conversations.
_fixtures/32-llm-service-direct command
LLM service direct — access the LLM without the agent loop.
LLM service direct — access the LLM without the agent loop.
_fixtures/eval command
Eval — runs concrete evaluation scenarios to measure ARES capabilities.
Eval — runs concrete evaluation scenarios to measure ARES capabilities.
_fixtures/evaluation
Package evaluation provides a framework for benchmarking ARES agent capabilities.
Package evaluation provides a framework for benchmarking ARES agent capabilities.
_internal/11-knowledge-import command
This file provides Arena-style chaos injection and Resurrection-style agent recovery for the knowledge base example.
This file provides Arena-style chaos injection and Resurrection-style agent recovery for the knowledge base example.
_internal/11-knowledge-import/akg command
Command akg-build — builds an AKG knowledge graph from knowledge_chunks_1024 using the existing PGProvider + KnowledgeRuntime pipeline.
Command akg-build — builds an AKG knowledge graph from knowledge_chunks_1024 using the existing PGProvider + KnowledgeRuntime pipeline.
_internal/13-archive-akg-chain command
Example 13 — Raw Conversation → AKG Knowledge Pipeline.
Example 13 — Raw Conversation → AKG Knowledge Pipeline.
_internal/14-tool-discovery command
Example 14 — Tool Discovery: MCP-style proactive discovery + the discover_tools meta-tool.
Example 14 — Tool Discovery: MCP-style proactive discovery + the discover_tools meta-tool.
_internal/15-llm-evolution-suite command
Scenario: gate3 — candidate gate-3 end-to-end (real LLM).
Scenario: gate3 — candidate gate-3 end-to-end (real LLM).
_internal/19-ga-candidate-e2e command
Command 19-ga-candidate-e2e runs a REAL multi-generation GA evolution loop end to end and turns the evolved champion into a candidate:
Command 19-ga-candidate-e2e runs a REAL multi-generation GA evolution loop end to end and turns the evolved champion into a candidate:
_internal/21-ai-assistant-integration command
Command 21-ai-assistant-integration demonstrates a complete AI assistant knowledge integration using the public api/knowledge packages and the KnowledgeService exposed by the service adapter.
Command 21-ai-assistant-integration demonstrates a complete AI assistant knowledge integration using the public api/knowledge packages and the KnowledgeService exposed by the service adapter.
_internal/26-runtime-scheduling-demo command
Runtime scheduling demo — submit a real task, let the runtime schedule it, and watch a capability agent analyse the module (H1: RegisterAgent + Submit).
Runtime scheduling demo — submit a real task, let the runtime schedule it, and watch a capability agent analyse the module (H1: RegisterAgent + Submit).
_internal/29-akf-graph-node command
AKF as a sdk.Graph node (BETA) — run ARES Knowledge Fabric steps inside a DAG without an LLM call.
AKF as a sdk.Graph node (BETA) — run ARES Knowledge Fabric steps inside a DAG without an LLM call.
_internal/aresos-demo command
ARES "Agent-OS" Grand-Loop demo — one continuous story proving the thesis:
ARES "Agent-OS" Grand-Loop demo — one continuous story proving the thesis:
_internal/custom-store command
custom-store demonstrates implementing a custom ServiceStore for persistent service discovery (SQLite, Postgres, JSON file, etc.).
custom-store demonstrates implementing a custom ServiceStore for persistent service discovery (SQLite, Postgres, JSON file, etc.).
_internal/discovery command
discovery demonstrates the Service Discovery Engine (internal/discovery).
discovery demonstrates the Service Discovery Engine (internal/discovery).
_internal/external-tools command
external-tools demonstrates how external projects use the ares public API.
external-tools demonstrates how external projects use the ares public API.
_internal/knowledge-fabric command
AKF demo — demonstrates the complete ARES Knowledge Fabric pipeline.
AKF demo — demonstrates the complete ARES Knowledge Fabric pipeline.
_internal/mcp-registry command
mcp-registry demonstrates MCP service discovery and lifecycle management.
mcp-registry demonstrates MCP service discovery and lifecycle management.
_internal/runtime_evolution/basic command
Runtime Evolution Demo (basic) — the shallowest of the three runtime evolution example: a WorkflowGenome evolves through mutate → fitness → diff → coordinator, showing the minimal closed loop.
Runtime Evolution Demo (basic) — the shallowest of the three runtime evolution example: a WorkflowGenome evolves through mutate → fitness → diff → coordinator, showing the minimal closed loop.
_internal/runtime_evolution/full command
Runtime Evolution Demo (full) — the runtime evolution chain over three genomes (workflow, knowledge, recovery; the scheduler dimension is retired), real executors, and a full evolution cycle per subsystem.
Runtime Evolution Demo (full) — the runtime evolution chain over three genomes (workflow, knowledge, recovery; the scheduler dimension is retired), real executors, and a full evolution cycle per subsystem.
_internal/runtime_evolution/knowledge command
Runtime Evolution Demo (knowledge) — the deepest of the three runtime evolution examples: it evolves the KNOWLEDGE subsystem's parameters (MaxResults, ReducerStrategy, PlannerStrategy) through the KnowledgeGenome, diffs the config drift into patches, and applies them via the real KnowledgePatchExecutor through the coordinator.
Runtime Evolution Demo (knowledge) — the deepest of the three runtime evolution examples: it evolves the KNOWLEDGE subsystem's parameters (MaxResults, ReducerStrategy, PlannerStrategy) through the KnowledgeGenome, diffs the config drift into patches, and applies them via the real KnowledgePatchExecutor through the coordinator.
internal
agentipc
collaboration_observer.go makes the bus measure collaboration receipts.
collaboration_observer.go makes the bus measure collaboration receipts.
agentruntime
Package agentruntime provides the shared L2 execution-kernel assembly used by both cmd/ares (serve) and sdk: the session registry, the incremental compile coordinator, the planner/router cognition, and the per-session task lifecycle (admission, release, harvest, reaping).
Package agentruntime provides the shared L2 execution-kernel assembly used by both cmd/ares (serve) and sdk: the session registry, the incremental compile coordinator, the planner/router cognition, and the per-session task lifecycle (admission, release, harvest, reaping).
agents
Package agent provides error definitions for agent service.
Package agent provides error definitions for agent service.
agents/lease
Package lease implements session leasing for concurrent access control (ares-vs-prime-agent 5.3, medium-high priority).
Package lease implements session leasing for concurrent access control (ares-vs-prime-agent 5.3, medium-high priority).
agents/outputguard
Package outputguard validates agent outputs before they are consumed downstream (primitive 6: framework-level output validation).
Package outputguard validates agent outputs before they are consumed downstream (primitive 6: framework-level output validation).
agents/peer
Package peer provides peer-to-peer agent messaging primitives: a registry that maps agent IDs to send functions and a direct-delivery Send path, so agents can exchange messages without routing through the leader (primitive 2: peer-to-peer agent communication).
Package peer provides peer-to-peer agent messaging primitives: a registry that maps agent IDs to send functions and a direct-delivery Send path, so agents can exchange messages without routing through the leader (primitive 2: peer-to-peer agent communication).
agents/sub
tool_observer.go closes the tool-channel half: tool calls now produce an evolution feature, not only a distillation side note.
tool_observer.go closes the tool-channel half: tool calls now produce an evolution feature, not only a distillation side note.
agentsyscall
Package agentsyscall provides the Kernel-validated spawn_agent and create_task syscalls that are exposed to real LLM agents as tools.
Package agentsyscall provides the Kernel-validated spawn_agent and create_task syscalls that are exposed to real LLM agents as tools.
apitools
Package apitools ...
Package apitools ...
ares_bootstrap
Package ares_bootstrap orchestrates component assembly.
Package ares_bootstrap orchestrates component assembly.
ares_callbacks
Package callbacks provides lifecycle event hooks for LLM calls and agent execution.
Package callbacks provides lifecycle event hooks for LLM calls and agent execution.
ares_config
package config - provides configuration loading and validation for ares.
package config - provides configuration loading and validation for ares.
ares_events
Package events defines event sourcing types and the event store interface.
Package events defines event sourcing types and the event store interface.
ares_ratelimit
Package ares_ratelimit ...
Package ares_ratelimit ...
ares_shutdown
Package ares_shutdown ...
Package ares_shutdown ...
aresrecovery
Package aresrecovery implements the ARES Kernel Recovery subsystem (see docs/zh/architecture/ares-runtime.md): the independent responsibility of keeping durable tasks alive across agent deaths.
Package aresrecovery implements the ARES Kernel Recovery subsystem (see docs/zh/architecture/ares-runtime.md): the independent responsibility of keeping durable tasks alive across agent deaths.
causalchain
Package causalchain keeps the causal chain of an agent step — WHY it acted, WHAT it did, WHAT it saw, and the edge that binds the step to the decision it was made from — in a form that survives compression.
Package causalchain keeps the causal chain of an agent step — WHY it acted, WHAT it did, WHAT it saw, and the edge that binds the step to the decision it was made from — in a form that survives compression.
discovery
Package discovery provides a pluggable service discovery engine.
Package discovery provides a pluggable service discovery engine.
discovery/providers
Package providers implements DiscoveryProvider for various sources.
Package providers implements DiscoveryProvider for various sources.
embedding
Package embedding provides the canonical contract for vector embedding services.
Package embedding provides the canonical contract for vector embedding services.
evidence
Package evidence provides the universal data primitive for ARES.
Package evidence provides the universal data primitive for ARES.
fabric
Package fabric is the unified orchestration layer for ARES AgentOS.
Package fabric is the unified orchestration layer for ARES AgentOS.
fabric/agent
Package agentfabric implements the ARES Kernel Lifecycle pillar (docs/zh/architecture/ares-runtime.md): Agent as a disposable, peer-equivalent cognitive process managed by the Runtime.
Package agentfabric implements the ARES Kernel Lifecycle pillar (docs/zh/architecture/ares-runtime.md): Agent as a disposable, peer-equivalent cognitive process managed by the Runtime.
fabric/planprojection
Package planprojection provides the single projection function from workflow engine steps to taskfabric PlanSteps, plus a compile coordinator that records compile provenance for introspection.
Package planprojection provides the single projection function from workflow engine steps to taskfabric PlanSteps, plus a compile coordinator that records compile provenance for introspection.
fabric/task
Package taskfabric is the ARES task projection layer (relocated from internal/taskfabric, package identity kept).
Package taskfabric is the ARES task projection layer (relocated from internal/taskfabric, package identity kept).
fabric/task/workflow/engine
package engine - Human-in-the-loop (HITL) support for pausing and resuming workflow execution.
package engine - Human-in-the-loop (HITL) support for pausing and resuming workflow execution.
fabric/task/workflow/graph
Package graph provides dynamic agent orchestration with pluggable scheduling.
Package graph provides dynamic agent orchestration with pluggable scheduling.
feedback
Package feedback carries the primitives of the three channels through which an agent can actually observe the outside world (closure plan Step Y): its own task outcomes, the tools it called, and the collaboration receipts other agents sent back.
Package feedback carries the primitives of the three channels through which an agent can actually observe the outside world (closure plan Step Y): its own task outcomes, the tools it called, and the collaboration receipts other agents sent back.
introspect
Package introspect — chaos read-model.
Package introspect — chaos read-model.
kernel
Package kernel provides the system-level control plane that unifies component assembly, dependency resolution, lifecycle orchestration, and shutdown coordination across all entry points (serve, start, SDK).
Package kernel provides the system-level control plane that unifies component assembly, dependency resolution, lifecycle orchestration, and shutdown coordination across all entry points (serve, start, SDK).
kernel/ctx
Package ctx carries Kernel-validated caller identity through tool execution contexts.
Package ctx carries Kernel-validated caller identity through tool execution contexts.
knowledge
Package knowledge provides core types for the ARES Knowledge Fabric (AKF), the Agent Knowledge Graph (AKG).
Package knowledge provides core types for the ARES Knowledge Fabric (AKF), the Agent Knowledge Graph (AKG).
knowledge/adapter
Package adapter provides bridges between existing ARES subsystems and AKF (the Agent Knowledge Graph).
Package adapter provides bridges between existing ARES subsystems and AKF (the Agent Knowledge Graph).
knowledge/compiler
Package compiler compiles a WorkingGraph into multiple output formats (Prompt, Markdown, JSON, XML, ToolSchema) for LLM consumption.
Package compiler compiles a WorkingGraph into multiple output formats (Prompt, Markdown, JSON, XML, ToolSchema) for LLM consumption.
knowledge/linker
Package linker provides pluggable Relation generators for AKF.
Package linker provides pluggable Relation generators for AKF.
knowledge/mcp
Package mcp provides MCP tool definitions for ARES Knowledge Fabric (AKF).
Package mcp provides MCP tool definitions for ARES Knowledge Fabric (AKF).
knowledge/pipeline
Package pipeline provides concrete implementations of the AKF processing pipeline: Normalizer, Summarizer, EntityMatcher, and Validator.
Package pipeline provides concrete implementations of the AKF processing pipeline: Normalizer, Summarizer, EntityMatcher, and Validator.
knowledge/planner
Package planner provides knowledge planning, source discovery, and query planning.
Package planner provides knowledge planning, source discovery, and query planning.
knowledge/provider
Package provider defines the GraphProvider interface for pluggable external data sources.
Package provider defines the GraphProvider interface for pluggable external data sources.
knowledge/provider/code
Package code implements a GraphProvider that analyses Go source directories and emits functions, types, and interfaces as KnowledgeObjects.
Package code implements a GraphProvider that analyses Go source directories and emits functions, types, and interfaces as KnowledgeObjects.
knowledge/provider/evolution
Package evolution provides a GraphProvider that reads from the evolution system's StrategyStore and streams strategies as KnowledgeObjects.
Package evolution provides a GraphProvider that reads from the evolution system's StrategyStore and streams strategies as KnowledgeObjects.
knowledge/provider/memory
Package memory provides a GraphProvider that wraps a memory service, converting historical task data into KnowledgeObject streams.
Package memory provides a GraphProvider that wraps a memory service, converting historical task data into KnowledgeObject streams.
knowledge/provider/postgres
Package postgres implements a GraphProvider for external PostgreSQL databases.
Package postgres implements a GraphProvider for external PostgreSQL databases.
knowledge/provider/store
Package store wraps a knowledge.KnowledgeStore as a GraphProvider so the AKF KnowledgeRuntime can read back facts distilled and persisted by the AKG pipeline.
Package store wraps a knowledge.KnowledgeStore as a GraphProvider so the AKF KnowledgeRuntime can read back facts distilled and persisted by the AKG pipeline.
knowledge/provider/vector
Package vector implements a GraphProvider for any VectorStore backend.
Package vector implements a GraphProvider for any VectorStore backend.
knowledge/retriever
Package retriever implements intent-driven knowledge retrieval.
Package retriever implements intent-driven knowledge retrieval.
knowledge/runtime
Package runtime provides the KnowledgeRuntime — the core execution engine of AKF.
Package runtime provides the KnowledgeRuntime — the core execution engine of AKF.
knowledge/service
Package service adapts the internal KnowledgeRuntime to the canonical knowledgeapi.KnowledgeService interface.
Package service adapts the internal KnowledgeRuntime to the canonical knowledgeapi.KnowledgeService interface.
knowledge/skills
Package skills implements progressive disclosure for agent capabilities (ares-vs-prime-agent 5.7, high priority): only a skill's name and one-line description are resident in the LLM context; the full detail body is loaded on demand by ID.
Package skills implements progressive disclosure for agent capabilities (ares-vs-prime-agent 5.7, high priority): only a skill's name and one-line description are resident in the LLM context; the full detail body is loaded on demand by ID.
knowledge/store/memory
Package memorystore provides an in-memory KnowledgeStore implementation.
Package memorystore provides an in-memory KnowledgeStore implementation.
knowledge/store/postgres
Package postgresstore implements KnowledgeStore for PostgreSQL.
Package postgresstore implements KnowledgeStore for PostgreSQL.
knowledge/store/sqlite
Package sqlitestore implements KnowledgeStore for SQLite.
Package sqlitestore implements KnowledgeStore for SQLite.
knowledge/workflow
Package workflow integrates AKF (ARES Knowledge Fabric) with the DAG workflow engine.
Package workflow integrates AKF (ARES Knowledge Fabric) with the DAG workflow engine.
knowledgeapi
Package knowledgeapi provides the canonical type and interface domain for the ARES Knowledge Fabric (AKF) — the Agent Knowledge Graph (AKG).
Package knowledgeapi provides the canonical type and interface domain for the ARES Knowledge Fabric (AKF) — the Agent Knowledge Graph (AKG).
llm
Package llm provides LLM client functionality for various providers.
Package llm provides LLM client functionality for various providers.
llmcore
Package llmcore provides core abstractions for LLM operations.
Package llmcore provides core abstractions for LLM operations.
llmexp
Package llmexp provides the canonical experience-storage and memory-distillation DTOs.
Package llmexp provides the canonical experience-storage and memory-distillation DTOs.
llmservice
Package llm provides error definitions for LLM service.
Package llm provides error definitions for LLM service.
llmsvcapi
Package llmsvcapi provides the LLM service API used by the sdk layer (M5 internalization of the former api/service/llm).
Package llmsvcapi provides the LLM service API used by the sdk layer (M5 internalization of the former api/service/llm).
logger
Package logger provides module-scoped structured logging helpers.
Package logger provides module-scoped structured logging helpers.
mcpclient
Package mcpclient ...
Package mcpclient ...
runtime
detached-context utilities for tracing and lifecycle management, formerly the standalone internal/ares_ctxutil package (consolidation D3).
detached-context utilities for tracing and lifecycle management, formerly the standalone internal/ares_ctxutil package (consolidation D3).
runtime/archive
Package ares_archive provides archive-style round summarization for the closed-loop agent.
Package ares_archive provides archive-style round summarization for the closed-loop agent.
runtime/arena
Package arena runs ARES chaos-engineering scenarios.
Package arena runs ARES chaos-engineering scenarios.
runtime/ares_evolution
channel_feedback.go closes N-11 (closure plan Step Y.2/Y.3): the OBSERVE stage for the two perception channels evolution was blind to — cross-agent collaboration receipts and tool-call outcomes.
channel_feedback.go closes N-11 (closure plan Step Y.2/Y.3): the OBSERVE stage for the two perception channels evolution was blind to — cross-agent collaboration receipts and tool-call outcomes.
runtime/ares_evolution/experience
Package experience provides evidence aggregation for the GA/Memory/Tool fusion system.
Package experience provides evidence aggregation for the GA/Memory/Tool fusion system.
runtime/ares_evolution/genome
Package genome provides genetic algorithm crossover (recombination) operators for combining two parent strategies into a child strategy.
Package genome provides genetic algorithm crossover (recombination) operators for combining two parent strategies into a child strategy.
runtime/ares_evolution/mutation
Package mutation ...
Package mutation ...
runtime/ares_evolution/promotion
Package promotion provides strategy promotion and demotion logic.
Package promotion provides strategy promotion and demotion logic.
runtime/ares_evolution/refine
Package refine implements Harness-style small-step evolution of supplement state (memory / skill / context entries): plan → apply → rollback with baseline conflict detection (primitive 1).
Package refine implements Harness-style small-step evolution of supplement state (memory / skill / context entries): plan → apply → rollback with baseline conflict detection (primitive 1).
runtime/ares_evolution/scoring
Package scoring ...
Package scoring ...
runtime/ares_evolution/service
Package evolution provides error definitions for the evolution service.
Package evolution provides error definitions for the evolution service.
runtime/eval
Package eval is the ARES evaluation service.
Package eval is the ARES evaluation service.
runtime/evolution
Package evolution provides the Candidate → Verify → Promote pipeline for safe, auditable agent evolution in ARES 0.3.0.
Package evolution provides the Candidate → Verify → Promote pipeline for safe, auditable agent evolution in ARES 0.3.0.
runtime/evolution/coordinator
Package coordinator provides the central decision-maker for runtime patches.
Package coordinator provides the central decision-maker for runtime patches.
runtime/evolution/deployment
Package deployment manages the safe promotion of evolution patches from staging to the live runtime.
Package deployment manages the safe promotion of evolution patches from staging to the live runtime.
runtime/evolution/diff
Package diff provides the Runtime Diff Engine.
Package diff provides the Runtime Diff Engine.
runtime/evolution/genome
Package genome provides score evaluation helpers for evolution.
Package genome provides score evaluation helpers for evolution.
runtime/evolution/patch
Package patch provides the universal mutation language for ARES Runtime.
Package patch provides the universal mutation language for ARES Runtime.
runtime/memory
Package memory is the ARES memory service.
Package memory is the ARES memory service.
runtime/memory/context
Package context ...
Package context ...
runtime/memory/distillation
Package distillation provides memory distillation functionality for agent experience extraction.
Package distillation provides memory distillation functionality for agent experience extraction.
runtime/memory/embedding
Package embedding provides canonical embedding types and a unified pipeline for generating vector embeddings across memory distillation, storage, and retrieval.
Package embedding provides canonical embedding types and a unified pipeline for generating vector embeddings across memory distillation, storage, and retrieval.
runtime/memory/experience
Package experience provides experience conflict resolution service.
Package experience provides experience conflict resolution service.
runtime/memory/experienceadapters
Package experienceadapters provides the shared adapter types that bridge production storage/knowledge types to the memory-retriever and distillation contracts.
Package experienceadapters provides the shared adapter types that bridge production storage/knowledge types to the memory-retriever and distillation contracts.
runtime/memory/push
Package push provides active knowledge recommendation to strategies.
Package push provides active knowledge recommendation to strategies.
runtime/memory/report
Package report provides human-readable evolution report generation.
Package report provides human-readable evolution report generation.
runtime/memory/tokencount
Package tokencount estimates token cost without a tokenizer.
Package tokencount estimates token cost without a tokenizer.
runtime/observability
Package observability is the ARES telemetry service.
Package observability is the ARES telemetry service.
runtime/observability/flight
Package flight provides runtime intelligence for ares agents.
Package flight provides runtime intelligence for ares agents.
runtime/protocol
Package protocol groups the ARES external-protocol adapters.
Package protocol groups the ARES external-protocol adapters.
runtime/protocol/mcp
Package ares_mcp ...
Package ares_mcp ...
runtime/protocol/skills
Package ares_skills implements the ARES Capability Fabric (0.3.0): a small abstraction that treats a Skill as a Capability Package (SKILL.md + references + tool declarations) rather than a Tool.
Package ares_skills implements the ARES Capability Fabric (0.3.0): a small abstraction that treats a Skill as a Capability Package (SKILL.md + references + tool declarations) rather than a Tool.
scoreutil
Package scoreutil provides helpers for normalizing relevance and confidence scores into a canonical range so downstream sorting, filtering, and display operate on a well-defined domain regardless of which backend produced them.
Package scoreutil provides helpers for normalizing relevance and confidence scores into a canonical range so downstream sorting, filtering, and display operate on a well-defined domain regardless of which backend produced them.
storage
package storage defines the vector storage interface.
package storage defines the vector storage interface.
storage/postgres
Package postgres provides PostgreSQL database operations for the storage system.
Package postgres provides PostgreSQL database operations for the storage system.
storage/postgres/adapters
Package adapters provides format conversion layer for storage operations.
Package adapters provides format conversion layer for storage operations.
storage/postgres/embedding
Package embedding ...
Package embedding ...
storage/postgres/models
Package models defines data structures for the storage system.
Package models defines data structures for the storage system.
storage/postgres/repositories
Package repositories provides data access layer for storage system.
Package repositories provides data access layer for storage system.
tenantctx
Package tenantctx carries the request-scoped tenant through the execution path.
Package tenantctx carries the request-scoped tenant through the execution path.
tools/capability
Package capability maps free text to the capability names tools declare, so the routing table lives in one place instead of in whichever caller happens to need it.
Package capability maps free text to the capability names tools declare, so the routing table lives in one place instead of in whichever caller happens to need it.
tools/discovery
Package discovery provides runtime discovery of native host commands and adapts them into core.Tool instances for the tool registry.
Package discovery provides runtime discovery of native host commands and adapts them into core.Tool instances for the tool registry.
tools/envcap
Package envcap provides agent-bundled environment capability retrieval (primitive 7 completion): a running agent can search the machine's environment through one unified entry point.
Package envcap provides agent-bundled environment capability retrieval (primitive 7 completion): a running agent can search the machine's environment through one unified entry point.
tools/planner
Package planner - capability definition model.
Package planner - capability definition model.
tools/resources/builtin/embedding
Package builtin ...
Package builtin ...
tools/resources/builtin/execution
Package builtin ...
Package builtin ...
tools/resources/builtin/file
Package builtin ...
Package builtin ...
tools/resources/builtin/hash
Package builtin - cryptographic hash and base64 encoding tools.
Package builtin - cryptographic hash and base64 encoding tools.
tools/resources/builtin/network
Package builtin ...
Package builtin ...
tools/resources/builtin/pdf
Package builtin ...
Package builtin ...
tools/resources/builtin/planning
Package builtin ...
Package builtin ...
tools/toolsource
Package toolsource provides MCP-style proactive tool discovery (ToolSource) and per-task tool selection (ToolSelector), wired into the L2 execution path (fabric/agent router cognition).
Package toolsource provides MCP-style proactive tool discovery (ToolSource) and per-task tool selection (ToolSelector), wired into the L2 execution path (fabric/agent router cognition).
truncate
Package truncate provides rune-safe string truncation utilities.
Package truncate provides rune-safe string truncation utilities.
userctx
Package userctx carries the request-scoped user through the execution path.
Package userctx carries the request-scoped user through the execution path.
Package sdk — Bootstrap-backed runtime core (Stage 8).
Package sdk — Bootstrap-backed runtime core (Stage 8).
services
embedding command
Simple embedding bridge that forwards requests to Ollama's embedding API.
Simple embedding bridge that forwards requests to Ollama's embedding API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL