[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-110813":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":14,"stars7d":15,"stars30d":16,"stars90d":14,"forks30d":14,"starsTrendScore":14,"compositeScore":17,"rankGlobal":9,"rankLanguage":9,"license":9,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":9,"pushedAt":22,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":14,"starSnapshotCount":14,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},110813,"SreAgentHarness","rainyZhou2\u002FSreAgentHarness","rainyZhou2","Self-hosted, multi-tenant agent harness for SRE incident diagnosis — risk-gated tool approvals, durable resumable runs, audit trail, model gateway, MCP tools, and a native desktop chat client. Written in Go.",null,"Go",142,11,5,0,3,102,51.74,false,"main",true,[],"2026-11-17 01:17:05","2026-11-21 11:18:44","\u003Cdiv align=\"center\">\n\n# go-sre-harness\n\n**English** | [简体中文](README.zh-CN.md)\n\nA cognitive agent runtime for SRE: every reasoning step and tool call runs as a recoverable, auditable distributed transaction.\n\n\u003Cimg src=\"docs\u002Fimages\u002Fdesktop-diagnosis.png\" alt=\"Desktop client: a diagnosis with its work log, tool calls and verified hypotheses\" width=\"900\">\n\n[Desktop client](#desktop-client) · [Quick start](#quick-start) · [Architecture](#architecture) · [Agent runtime](#agent-runtime) · [Memory](#memory) · [Reasoning quality](#reasoning-quality) · [Triggers & policy](#triggers-policy-rules-and-the-action-loop) · [Deployment](#deployment) · [Configuration](#configuration) · [API](#api)\n\n\u003C\u002Fdiv>\n\n## Highlights\n\n- **The database is the only truth; push is an accelerator.** Disconnects, dropped messages and replica failures cannot make state inconsistent.\n- **Side effects cannot be duplicated.** Approvals bind an action hash and are re-checked before execution; an unknown outcome goes to a human instead of being retried.\n- **Plugins can only tighten, never relax.** The policy floor, risk-class source, trust rules and audit are enforced by the framework.\n- **The full path runs without an API key.** The built-in scripted model exercises the ledger, prompt manifest, streaming and tool validation.\n- **The evolution loop is complete.** Freeze a dataset → replay offline → gate → human approval → canary → automatic rollback.\n\n## Core capabilities\n\n| Area | Capability |\n|---|---|\n| **Durable execution** | Run\u002FStep\u002FAttempt state machine, step-level leases + fence tokens, resume after a crash; side-effect results are recorded before the step commit, so a lost commit never turns a known outcome into a human escalation |\n| **Safe execution** | R0–R3 risk classes, approvals bound to `action_hash`, single-use grants, side-effect ledger; unknown outcomes go to `NEEDS_HUMAN` and are never replayed |\n| **Conversations** | Session \u002F Turn \u002F Branch, single-writer queue, branch fork, replayable messages and events |\n| **Model gateway** | Alias → hard filters → soft-score routing, circuit breakers, budget and concurrency admission, fallback only while \"not yet sent\"; Claude, OpenAI-compatible and Gemini |\n| **Context & intent** | Prompt manifest (per-section hashes), deterministic compaction; each message is classified as a question, a task or a clarification |\n| **Long-term memory** | Full-text + vector + dependency-graph recall, RRF fusion, poisoning checks and conflict resolution |\n| **Orchestration DSL** | A profile-embedded flow graph: conditions\u002Floops, parallel child runs, variable interpolation, approvals\u002Fhuman input, subflows and multi-agent |\n| **Web** | `web.fetch` works out of the box; `web.search` supports Brave \u002F Tavily \u002F Bing \u002F a generic backend, with output treated as untrusted |\n| **Evaluation & evolution** | Datasets recorded from real runs, offline replay, non-inferiority gate, canary with automatic rollback |\n| **Event delivery** | Committed event → event log → relay → JetStream → SSE; reconnects resume from the cursor, with no steady-state database reads |\n| **Plugins** | Everything is replaceable except the state machine, leases, transactional commit, outbox and core routes |\n\n## Desktop client\n\n[`desktop\u002F`](desktop\u002FREADME.md) is a native Wails client. It starts in **Local runtime** mode: the app launches a bundled SQLite-backed harness core, writes execution events to an append-only JSONL log, and keeps SQLite only as the query index. No Docker, PostgreSQL, NATS or terminal is needed. Switch to **Team server** to use a shared harness. Sessions, streamed reasoning, tool-call cards, inline approvals, an approval inbox, a Works view for continuous v2 Works, and model \u002F MCP \u002F HTTP tool \u002F skill management are the same in both modes; local mode implements the same `\u002Fv1\u002Fextensions`, command, checkpoint\u002Ffork, memory, graph and evaluation APIs. Commands are version-guarded and idempotent across restarts, cancelling a flow cascades to child runs, and compaction summaries, memory hits, checkpoints and step output revisions are persisted in the local store.\n\n```bash\ndesktop\u002Fbuild.sh run\n```\n\n### Screenshots\n\nAll screenshots are the local runtime with no model configured (the rule-based strategy).\n\n\u003Ctable>\n\u003Ctr>\n\u003Ctd width=\"50%\" valign=\"top\">\u003Cimg src=\"docs\u002Fimages\u002Fdesktop-approval.png\" alt=\"Inline approval\">\u003Cbr>\u003Cb>Inline approval\u003C\u002Fb> — a generated plan with side effects waits for review: risk class, plan hash, expiry and action hash\u003C\u002Ftd>\n\u003Ctd width=\"50%\" valign=\"top\">\u003Cimg src=\"docs\u002Fimages\u002Fdesktop-inbox.png\" alt=\"Approvals inbox\">\u003Cbr>\u003Cb>Approvals inbox\u003C\u002Fb> — pending approvals from every chat, with a badge and system notifications\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd width=\"50%\" valign=\"top\">\u003Cimg src=\"docs\u002Fimages\u002Fdesktop-gallery.png\" alt=\"Gallery\">\u003Cbr>\u003Cb>Gallery\u003C\u002Fb> — ready-made SRE skills (latency, error spikes, dependencies, rollouts…) added with one click\u003C\u002Ftd>\n\u003Ctd width=\"50%\" valign=\"top\">\u003Cimg src=\"docs\u002Fimages\u002Fdesktop-graph.png\" alt=\"Graph\">\u003Cbr>\u003Cb>Graph\u003C\u002Fb> — search the links between runs, steps, tools, memories and services\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftable>\n\n### Answer cards\n\nThe final answer is shown as a card, not plain text, in both modes:\n\n- **Markdown**: headings, lists, code blocks, GFM tables, math (KaTeX) and mermaid diagrams. Raw HTML is never rendered (it shows as text). Links open in the system browser through `OpenURL`, which accepts only `http`, `https` and `mailto`. `javascript:`, `file:` and other schemes are not linked or opened, and links to files (`.pdf`, `.csv`, `.json`, …) get a type badge.\n- **Structured attachments**: `submit_conclusion` takes an optional `attachments` list of `{type: table|image|link|file, title, caption, url | ref, mime_type, columns, rows}`. The kernel validates the list before it reaches the run result (`result.attachments`). URLs must be absolute `http(s)` with no credentials. A `ref` must name an offloaded tool output of the same tenant (`obs:step\u003CN>` resolves to its handle). Text and tables are capped (12 attachments, 20 columns × 200 rows), and anything else is dropped. Conclusions without attachments are unchanged.\n- **Client rendering**: a table becomes a scrollable card with *Copy CSV*. An image from a URL loads lazily with no referrer, and a stored image (PNG, JPEG, GIF or WebP only, never SVG) is fetched by the Go side and shown inline. A link becomes a tile with its host, and a file becomes a tile with name, type and size plus *Open* (URL) or *Download* (stored output, saved through a save dialog). The WebView never holds the API token. Exported chats include the attachments.\n- **API consumers**: attachments arrive in `GET \u002Fv1\u002Fruns\u002F{id}` (`result.attachments`) and in session messages (the assistant message's content is the result artifact). `GET \u002Fv1\u002Fruns\u002F{id}\u002Fattachments\u002F{index}` (viewer) serves a stored attachment of that run's result. It serves only refs the kernel accepted, at most 32 MiB, with `nosniff` and a sandbox CSP, and always as a download except for an inline raster image.\n\n## Quick start\n\nRequires Go 1.26+ and PostgreSQL 14+; NATS is optional.\n\n```bash\ncreatedb harness\nHARNESS_DATABASE_URL=postgres:\u002F\u002Flocalhost\u002Fharness go run .\u002Fcmd\u002Fharness all\n```\n\nWith a model:\n\n```bash\nANTHROPIC_API_KEY=sk-ant-... HARNESS_DATABASE_URL=postgres:\u002F\u002Flocalhost\u002Fharness go run .\u002Fcmd\u002Fharness all\n```\n\nDemo (create a run → R2 approval → SSE → conclusion):\n\n```bash\nscripts\u002Fdemo.sh \"remediate high latency service=checkout\"\n```\n\nThe default `dev` authentication mode only listens on loopback addresses.\n\n## Architecture\n\n```\nclients (web \u002F desktop)\n   │ REST + SSE\ninternal\u002Fapi ── extensions: memory \u002F eval \u002F extensions\n   │\ninternal\u002Fkernel ── Durable Step Engine\n   ├─ cognitive  intent analysis, context assembly, prompt manifest, strategies\n   ├─ gateway    routing, circuit breakers, budget, request\u002Fusage ledger\n   ├─ tools      MCP \u002F gRPC \u002F Kubernetes \u002F Prometheus \u002F HTTP\n   └─ policy     risk gate and approvals\n   │\nPostgreSQL (source of truth)  +  NATS JetStream (wake-ups and event delivery)\n```\n\n- **Claim in a short transaction → execute outside it → commit with the fence**: a worker that lost its lease discards its result, so stale workers cannot overwrite new state.\n- **Gap-free event log + transactional outbox**: state, events and wake-ups commit together; the reconciler recovers anything stuck.\n- **Event plane**: a leased relay tails the event log, JetStream fans events out per run, and the SSE gateway reads the log once before streaming live updates.\n- **The kernel depends only on interfaces**: it never imports PostgreSQL, NATS or a model SDK, so adapters are replaceable and testable.\n\n### Orchestration DSL\n\nA profile can set `strategy: \"flow\"` and embed a `flow` graph. The DSL compiles to the existing step engine: the parent run only coordinates, while agent \u002F tool \u002F subflow nodes become child runs, so leases, fences, approvals, the effect ledger and checkpoint recovery are reused. Parallelism is carried by child runs and joined by a `join` node; a child inherits the parent profile and can only narrow its tools and permissions.\n\n```yaml\nstrategy: flow\ntools: [demo.metrics, demo.restart]\nmax_steps: 40\nflow:\n  version: 1\n  entry: triage\n  limits: {max_steps: 20, max_children: 4, max_total_runs: 8, max_depth: 2}\n  nodes:\n    - id: triage\n      type: agent\n      role: triage\n      tools: [demo.metrics]\n      next: [{to: finish}]\n    - id: finish\n      type: end\n      output: \"${nodes.triage.output}\"\n```\n\nNode types: `agent` \u002F `tool` \u002F `subflow` \u002F `parallel` \u002F `join` \u002F `approval` \u002F `input` \u002F `loop` \u002F `end`. `GET \u002Fv1\u002Fruns\u002F{id}\u002Fflow` returns node and child-run state; the `provide_input` command answers an `input` node. Built-in examples: `sre-diagnosis@8` (parallel diagnosis + approval) and `@9` (human input + subflow).\n\n### Generated plans\n\nThe desktop client does not ask you to choose a profile. An auto session starts with a durable **plan step**: the planner LLM submits a flow DSL through `submit_flow`; the server compiles it, runs a static safety\u002Fbudget analysis, repairs malformed plans, and pins the plan as an artifact. A generated plan with side effects (or an R2\u002FR3 tool) gets a **plan review** step whose approval binds the plan hash; changing the graph, inputs or tool set invalidates the approval. Only then is the flow step appended. If the model cannot produce a valid plan, the runtime falls back to the configured runbook (default `sre-diagnosis@8`) or ReAct. Generated plans, flow nodes, child runs, approvals and input gates are rendered in the conversation.\n\nThe planner treats its own inputs as untrusted: the goal, session history, capability lines and a failed attempt's node outputs are enclosed in `\u003C\u003C\u003CDATA>>>` boundaries with chat-template tokens neutralized, and tool descriptions (which come from plugins and tenant MCP servers) that look like injected instructions are withheld from both the prompt and the tool schemas. Any such finding is recorded on the plan and forces a plan review of a generated flow, even with `HARNESS_PLAN_APPROVAL=never`. When a generated flow fails, the run is not failed straight away: up to `HARNESS_PLAN_MAX_REPLANS` times the planner is called again with the failure, the nodes that ran and the side effects that completed, and the new plan runs as a new flow generation (fresh state and child runs; the failed generation stays for audit, and its approvals do not carry over because the plan hash binds the generation).\n\nPlans improve from earlier runs. A run that completes on a model-generated flow (not a fallback, no injection flag, not rejected, not disputed, not marked wrong) is distilled into a *plan exemplar* memory (scoped to the service, deduplicated by content) that follows the normal memory lifecycle; the planner is shown the closest ACTIVE exemplars and reasoning patterns for the goal and services, as untrusted data. Each run records plan metrics (repairs, fallback, replans, review requested\u002Frejected, injection, cache hit), and the canary and candidate gates compare fallback, repair, replan, rejection, success and injection rates against the baseline. Routing tries a hint, the requested mode and named actions, then the regex lists, then a classifier (an n-gram kNN over labelled example goals by default, or an embedding classifier; set `ClassifierFirst` to consult it before the regexes). Every generated or fallback flow is dry-run with simulated successful children before approval: a flow that cannot complete its default path within its own limits is repaired, and side-effect nodes reached without a prior approval are flagged. The plan review carries a readable summary, ordered steps, risks, the dry-run path, and a diff against the previous generation (replan) or the fallback runbook. Agent nodes without pinned tools are pinned to the read-only tools so their risk is not assumed to be the highest. Token estimates use a typical output size, with the worst case reported alongside. Plans without replan or injection flags are cached per tenant and inputs, and a cache hit is re-validated against the current tool catalog. A profile's `planner` section can tighten (never loosen) these settings per tenant: model alias or ladder, approval mode, node\u002Fcall\u002Ftoken\u002Frepair\u002Freplan limits, and fallback rules by service or goal pattern.\n\n## Agent runtime\n\nHow a single agent run stays bounded, fast and contained.\n\n### Agent loop safeguards\n\n- **Run budget**: the kernel reads the run's model usage before each reasoning step. At 80% of `HARNESS_RUN_MAX_COST_USD` \u002F `HARNESS_RUN_MAX_TOKENS` (or the profile's tighter `run_limits.max_cost_usd` \u002F `max_tokens`) the model gets a `[kernel notice]` and a conclude-now instruction; at 100% the kernel writes the final answer itself (`stopped` in the result: the hypotheses and last tool results so far, marked UNVERIFIED) and skips the review, so a looping run cannot spend past its limit.\n- **Parallel read-only calls**: when one response asks for several tools, the extra calls run together with the first in a kernel-owned `harness.parallel` step (hidden from the model, refused if it calls it) when each is registered, visible, allowed without approval, read-only and not a repeat; at most `max_parallel_tools`. Each call becomes its own observation (`obs:step\u003CN>.\u003CK>`), and a call that fails or changed since planning fails alone. Calls left out (side effects, approval needed, duplicates) are listed in the step summary as `deferred_not_run`; side-effecting calls always go one at a time through the approval gate.\n- **Tool errors as observations**: a read-only call that fails permanently (bad arguments, missing resource, permission) becomes an `outcome=error` observation the agent can adapt to instead of failing the run; transient (retryable) errors still retry the step, and side-effecting calls keep the unknown-effect handling.\n- **Repair feedback**: an unusable response (no parseable tool call, schema-invalid arguments, an invalid decision, an unknown tool) is sent back to the model as a `[correction]` naming the problem (and the available tools) up to twice per attempt before the step retries; repairs are recorded in the step summary.\n- **Loop and stall guard**: an identical call (tool and canonical arguments) that already ran `max_repeats` times, or that was denied, rejected or expired, is not run again: it is recorded as a skipped step whose reason points to the earlier result. After `stall_steps` tool results without new content (repeats, errors, identical output) the agent is told to change approach; after twice that, a further tool call is replaced by a kernel conclusion.\n- Profiles set these per agent under `run_limits` (`max_cost_usd`, `max_tokens`, `max_repeats`, `stall_steps`, `max_parallel_tools`); they can only tighten the process settings.\n\n### Agent loop performance\n\n- **Context rebuild**: each reasoning step rebuilds its context from the run history, which keeps retries deterministic. Artifacts are immutable, so the worker caches the ones it writes and reads (LRU, `HARNESS_ARTIFACT_CACHE_BYTES`); a step reads only what is new. Steps of a run already chain inside one worker (up to 20 before handing back to the queue).\n- **Prompt cache**: the history section only grows between steps, so the request marks a cache breakpoint at its end (in addition to the system\u002Ftool prefix); the ledger, notices and instruction follow it. Providers with automatic prefix caching ignore the marker.\n- **Tool selection**: with more than `HARNESS_TOOL_TOP_K` visible tools the model sees a stable subset per run — tools used or loaded in the run, builtins, tools named in the request, then the best word matches with the request — and a `[more tools]` list of the rest, which it loads with `harness.load_tools`. The choice does not change from step to step, so the cached prefix stays valid; any visible tool is still accepted.\n- **Model routing**: with `HARNESS_MODEL_ROUTINE_ALIAS` \u002F `HARNESS_MODEL_ESCALATED_ALIAS` the first analysis, likely or forced conclusions, stalls, the step after a rejected conclusion and repairs use the escalated alias, the other steps the routine one (`model_tier` in the step summary). A flow node's own alias takes precedence.\n- **Adaptive stop**: when the ledger settles (a VERIFIED hypothesis at ≥ 0.8 and no competing hypothesis open) the agent is advised to conclude, before the step budget or the stall guard would intervene.\n- **Token-budget compaction**: besides every N tool steps, history is compacted when the uncompacted results exceed `HARNESS_COMPACT_TOKENS` (then all but the newest result are folded). The default compactor (`deterministic-v2`) writes one line per result led by its citable ref and renders large JSON objects as their top-level fields; compacted refs, including batch parts, stay citable.\n- **Speculative read-only calls** (`HARNESS_SPECULATIVE_TOOLS`): as each tool call completes in the model's stream, a call that is visible, read-only, allowed without approval and not a repeat starts at once; the tool step that runs the same call (same version, risk and arguments) takes the result. Unused results expire after two minutes; side-effecting calls are never started early.\n- **Observability**: every step summary carries `timings_ms` (queue, context, model, review, tool), exported as `harness_step_phase_seconds{kind,phase}` together with commit time; `harness_agent_loop_events_total{event}` counts repairs, loop guards, notices, batches, convergence, routing, compaction, speculation and artifact-cache hits. The run result carries `loop` (steps, model requests, tokens, cost).\n\n### Sandbox\n\n`harness.sandbox.exec` runs a command (`command` for `sh -c`, or `argv`) in the run's sandbox: input `files` are written into `\u002Fworkspace`, which persists across the run's calls and is never shared with another run or tenant, and the listed `outputs` are returned with exit code, stdout and stderr. It is for computing over data the agent already has; production changes still go through typed tools and approval.\n\n- **Safety floor**: no harness environment or credentials (only variables the request sets), network `none`, read-only root file system, non-root user, all capabilities dropped, `no-new-privileges`, CPU \u002F memory \u002F process \u002F time \u002F output limits. Workspace files are read and written through `os.Root`, so a symlink planted by the command cannot reach host files. Results are untrusted (T4) and the tool is R0, so it needs no approval; it is never started speculatively.\n- **Backends** (`sandbox` plugin kind): `container` runs a fresh docker or podman container per call (`extra_args: [--runtime=runsc]` for gVisor). The server enables it with `sandbox: {name: container, config: {...}}` (see `deploy\u002Fharness.example.yaml`); the desktop runtime with `HARNESS_SANDBOX_RUNTIME=docker|podman` and optional `HARNESS_SANDBOX_IMAGE` (default `python:3.12-alpine`). Workspaces untouched for `workspace_ttl` (24h) are removed. When the harness itself runs in a container, `root` must be a path the container daemon can mount.\n- **MCP stdio servers** no longer inherit the harness environment: they get basic variables (`PATH`, `HOME`, locale, temp directory) plus their configured `env`; a bare `KEY` in an operator's config passes that variable through, which tenant-installed servers cannot do.\n\n## Memory\n\nWhat the agent remembers, for how long, and how memories are kept current.\n\n### Memory tiers\n\n| Tier | Lifetime | What it holds | Written by |\n|---|---|---|---|\n| Working | one run | the agent's notes: established facts, constraints, what is left to check; plus the hypothesis ledger | `notes` with scope `run` |\n| Short-term | one conversation (branch) | the last `HARNESS_SHORT_TERM_MESSAGES` messages verbatim, a digest of older turns, and session notes | `notes` with scope `session` |\n| Long-term | the tenant | incidents, remediations, reasoning patterns, plan exemplars, proposed facts (organization \u002F service \u002F incident scopes) | the consolidator, operators, `notes` with scope `long_term` (as CANDIDATE) |\n| Personal | one user | stable preferences of the user who started the run (language, format, defaults) | `notes` with scope `user`, or the user via `\u002Fv1\u002Fme\u002Fmemories` |\n\n- **Notes**: the agent writes memory in its `THOUGHT` line or its conclusion as `\"notes\":[{\"key\",\"value\",\"scope\"}]`; writing a key again updates it, an empty value deletes it. The kernel rebuilds notes from the stored decisions, so they survive retries and compaction, and renders them in a `[working memory]` section inside a data boundary. A tier holds at most 24 notes of 500 characters.\n- **Short-term**: the session notes after a run are stored in its result (`memory.session`); the next turn on the same branch starts from the latest completed turn's notes, so a forked branch sees only its own history.\n- **Personal**: when a user-started run completes, its `user` notes create, reinforce, revise (new version) or archive that user's memory for each key (`pref:\u003Ckey>`, ACTIVE, `restricted`). Personal memory is pinned with the run's retrieved memories and rendered in an `[about the user]` section for that user's runs only; shared retrieval, `harness.memory_search` and other users never see it (admins can list it). Instruction-like text is rejected, and a preference never authorizes an action. Users manage theirs with `GET \u002Fv1\u002Fme\u002Fmemories`, `PUT|DELETE \u002Fv1\u002Fme\u002Fmemories\u002F{key}`.\n- **Long-term from the agent**: `long_term` notes of a completed, undisputed run become CANDIDATE memories (VALIDATING when feedback verified the run) with subject `note:\u003Ckey>`, reviewed like any other.\n\n### Updating memory\n\n- **Reinforcement instead of duplicates**: writing the same content again in the same scope, or a near-identical memory with the same subject (embedding cosine ≥ 0.95, or token overlap ≥ 0.85 without a comparable embedding) that is at least as validated, counts a reinforcement on the existing memory (`reinforcements`, `last_reinforced_at`, merged `source_refs`) when it comes from a new source. Reinforced memories rank slightly higher (up to ×1.3).\n- **Revisions**: `PATCH \u002Fv1\u002Fmemories\u002F{id}` (approver; `expected_version`, `title` and\u002For `content`, `reason`) writes a new version: redacted and poison-checked like a new memory, re-embedded and re-indexed, audited, the status unchanged. Earlier versions stay in `agent_memory_versions`, so citations pinned to them still resolve; a revision that would duplicate another memory's content is rejected.\n- **Supersession** (activating a memory retires ACTIVE ones with the same subject and scope), **lifecycle transitions**, feedback and retention work as before. Consolidation is idempotent: a re-run after feedback does not reinforce or revise twice.\n\n### Memory search\n\n- **Search during the run**: the first reasoning step sees the memories retrieved for the goal. `harness.memory_search` (R0, `query`, optional `service` and `top_k` ≤ 10) runs the same pipeline (hard filters, full-text, vector and dependency branches, RRF, trust and profile exclusions, conflict resolution) with what the agent has learned since: a hypothesis, an error message, a component. Hits are returned as past experience to verify, with their `memory:\u003Cid>@\u003Cv>` refs; those refs are citable and reach the independent verifier as memory evidence. The stall notice suggests a search when the tool is visible.\n- **Model embeddings**: the `http` embedder calls any OpenAI-compatible `\u002Fembeddings` endpoint (`base_url`, `model`, `api_key_env`, `dimensions`, `timeout`) with a small query cache; when it fails, retrieval runs without its vector branch. Vectors are only compared within one embedding model, so after a switch the consolidator's indexer (`index`, default on; `index_batch`, default 50) re-embeds live memories, active ones first, a batch per tick.\n- **Chinese, Japanese and Korean text**: tokenization turns CJK runs into overlapping character bigrams, so full-text search (Postgres stores them in `search_terms`, part of `search_tsv`), the local store's matching and the hashing embedder (`hash-uni-bigram-v2`) find CJK fragments without a word segmenter. The indexer fills in terms for memories written before migration 0018.\n\n## Reasoning quality\n\nThe agent's explicit decision trace (plan, hypotheses with confidence, verification) is scored, reused and improved. Provider-hidden reasoning is never read. Design: `docs\u002Fsuperpowers\u002Fspecs\u002F2026-11-07-reasoning-quality-and-self-improvement-design.md`.\n\n- **Measure**: every finished run is scored by the consolidator (and rescored when feedback arrives). The score covers calibration (Brier score of hypotheses that ended VERIFIED\u002FREFUTED), evidence grounding, redundant tool calls, steps to the first verdict, the conclusion verdict and a composite quality. Offline replays are scored the same way, and the release gate fails a candidate whose calibration, grounding, redundancy or quality regresses on the holdout split.\n- **Citation check**: every observation header carries its ref (`obs:step\u003CN>`), as do evidence (`kv:\u003Ckey>@\u003Cv>`) and memories (`memory:\u003Cid>@\u003Cv>`). The kernel resolves each citation in `supports`, `refutes` and `evidence_refs` against what that request showed the model (aliases such as `obs:4`, `obs:\u003Ctool>` or an offload handle map to the canonical form). A citation that names nothing shown is stored as `unresolved:\u003Ctext>` and does not count as grounding. A hypothesis settled without a resolved citation is an unsupported verdict, and a VERIFIED conclusion where neither the verification nor any verified hypothesis cites a resolved item is self-declared: it is scored and counted as unverified, does not count as success and is not distilled. Citation validity and the unsupported-verdict and unsupported-conclusion rates are summarized, gated in releases and canaries, and drive a `citation` playbook hint in the improvement loop.\n- **Independent verification and backtracking**: a final task conclusion is checked by a verifier that did not write it. A rule layer (always on) requires every VERIFIED\u002FREFUTED claim to cite evidence that exists, does not accept a failed tool call or a memory alone as evidence, and requires a VERIFIED conclusion to have at least one supported verified claim; an optional model judge (`HARNESS_VERIFIER_MODEL_ALIAS`, its own prompt, no agent history) decides per claim whether the cited evidence supports, contradicts or does not settle it. A conclusion that is not SUPPORTED is handed back to the agent through a kernel-owned `harness.conclusion_review` step (hidden from the model, refused when the model calls it) up to `HARNESS_REASONING_MAX_BACKTRACKS` times; its hypotheses show as CHALLENGED in the ledger. Otherwise the run completes with the report in `independent_verification`, and an unaccepted answer is marked as such. Scoring takes the independent verdict over the agent's own: a contradicted or insufficient conclusion is not a success and is not distilled.\n- **Multiple hypotheses and self-consistency**: while investigating, the agent lists its competing hypotheses (id, status, probability) in the THOUGHT line; the kernel rebuilds a hypothesis ledger from the run's decisions and shows it every step, so the agent discriminates between open hypotheses and returns to the next one when the first is refuted. With `HARNESS_REASONING_SAMPLES` > 1 a final task conclusion is sampled that many times and the largest cluster of agreeing conclusions wins; agreement below `HARNESS_REASONING_MIN_AGREEMENT` counts as insufficient and triggers the review.\n- **Post-hoc calibration**: each run records its hypotheses' first stated confidence and how they settled (the independent verdict decides when there is one). An isotonic calibrator per tenant profile is fitted from recent runs (independently judged forecasts preferred); the kernel stores the calibrated confidence next to the stated one, shows the model how often its stated confidences held, and the summary reports ECE and the calibrated Brier score; a rising ECE or contradiction rate fails the gate.\n- **Induced playbook**: with `inducer_model_alias` on the `reasoning_improver` job, the improver shows a model the digests of the weakest runs (hypotheses and how they settled, tools, verifier objections; no raw tool output) and asks for general guidance lines. Lines that name resources or runs, look like instructions, weaken approvals, review, verification or trust rules, or repeat existing lines are rejected; template guidance is the fallback. The candidate still goes through the holdout gate, approval by someone other than the proposer, and the canary.\n- **Reuse**: completed, undisputed runs with a VERIFIED conclusion are distilled into *reasoning patterns*: procedural memories listing the hypotheses checked in order, their verdicts and the tools used until the first verdict. They follow the normal memory lifecycle (CANDIDATE → approval → ACTIVE), so an operator activates every pattern. Each memory's success rate and Wilson lower bound are measured from the runs that retrieved it.\n- **Pattern effectiveness**: a pattern is judged against the baseline success rate of the same service (runs that did not see it), not an absolute rate. Explicit citations (`memory:\u003Cid>` in evidence or hypothesis refs) decide once there are enough of them. Patterns significantly and materially worse than the baseline are excluded. Excluded patterns are still shown to a small, deterministic share of runs (`reasoning.pattern_probe_rate`, at most 0.2) and are reinstated when those runs reach the baseline. Stale entries are pruned, and the list keeps the strongest cases when it hits its 500-entry limit. Operators can propose an exclusion or reinstatement by hand.\n- **Trace structure**: hypotheses carry a stable `id` used for deduplication across rewording. Confidence coverage and the structured share are measured, gated and diagnosed; a settled hypothesis without a confidence counts as a 0.5 forecast.\n- **Improve**: the `reasoning_improver` job (or `POST \u002Fv1\u002Freasoning\u002Fimprove`) diagnoses weak dimensions and underperforming ACTIVE patterns. It proposes a profile candidate that changes only `reasoning.playbook` (fixed, domain-free guidance; at most 2,000 characters, poison-checked, rendered before the trust rules) and `reasoning.patterns_excluded`. Runs behind holdout cases are excluded from the diagnosis. The candidate goes through the existing pipeline: holdout gate, approval by a human other than the proposer, canary with automatic rollback. The canary monitor also rolls back when the canary's reasoning regresses against the control group (default on, at least 20 scored runs per side). The loop never approves, canaries or promotes, and proposes one change at a time.\n- **Retention**: reasoning scores are kept for `reasoning_retention` (default 90 days) by the `retention` job.\n- **APIs**: `GET \u002Fv1\u002Freasoning\u002Fsummary`, `GET \u002Fv1\u002Freasoning\u002Fruns\u002F{run_id}`, `GET \u002Fv1\u002Freasoning\u002Fpatterns`, `POST \u002Fv1\u002Freasoning\u002Fpatterns\u002F{memory_id}\u002Fexclude|reinstate` (operator), `POST \u002Fv1\u002Freasoning\u002Fimprove` (admin). The desktop runtime scores and distills the same way and improves only on demand.\n\n## Triggers, policy rules and the action loop\n\n- **Triggers** (`triggers:`): `POST \u002Fv1\u002Ftriggers\u002F{name}` turns webhooks (Alertmanager, Grafana, PagerDuty, CI, …) into runs. Items fan out, `filter` drops noise, `resolve` events only attach evidence. Duplicates within the dedup window are injected into the open run as evidence instead of starting a new one; deduplication is shared through the database, so replicas agree. Optional HMAC signatures (`X-Harness-Signature: sha256=…`) and per-trigger rate limits. `schedule:` triggers create one run per interval across scheduler replicas.\n- **Rule-based policy** (`policy: {name: rules}`): matchers over tool, source, labels, risk, environment, target, arguments, time windows, rate and blast radius. The strictest matching rule decides; the framework floor always applies. The environment is resolved per call and bound into the action intent.\n- **Time and environment context**: runs carry a pinned `now`, incident window, services and labels (`context` on `POST \u002Fv1\u002Fruns`, or rendered by a trigger). `context_provider` plugins add topology, ownership and recent changes once per run; facts are pinned for replay and rendered as untrusted data. Tools with `time_args` get the window filled in when the model leaves it out.\n- **Verify and compensate** (`tool_overlays.\u003Ctool>.lifecycle`): after a side effect the kernel polls the verify tool until `expect` holds. A refuted action proposes the compensation, which always waits for approval.\n- **Large outputs**: oversized tool results become a `tool-output` artifact plus a structured summary (log levels, time range, frequent templates; JSON shape and numeric stats). The model queries the rest with `harness.artifact_query` (head, tail, lines, grep, JSON path, time range).\n- **Untrusted output**: every tool result, operator evidence block and compacted summary is enclosed in a content-derived `\u003C\u003C\u003CDATA id=…>>>` boundary that the content cannot close; chat-template control tokens are neutralized and instruction-like text (the memory poisoning patterns) is flagged `injection_suspected` in the prompt, the observation and the prompt manifest. Content is never dropped, only marked. Compaction keeps offload handles, verification verdicts and these flags outside the excerpt limit.\n- **Routing**: when planning fails, the goal-context hint, the model's requested mode, configured patterns and side-effecting tools named in the goal decide between the fallback flow and ReAct.\n\nThe desktop runtime reads the same sections (`policy`, `triggers`, `context_providers`, `tool_overlays`) from `harness.local.json` in its data directory, or from `HARNESS_LOCAL_CONFIG`.\n\n## Continuous Works (v2 control plane)\n\nBehind `HARNESS_WORK_ENGINE_ENABLED`, a **Work** is a durable goal that spans many runs: events are deduplicated and correlated into Works, durable watches wait for events and timers, actions are planned against a bitemporal world state, held for approval bound to an intent hash, dispatched ledger-first and never replayed blindly, and a Work only succeeds with a verified outcome (metrics, world state, events or a human). `HARNESS_EVENT_SHADOW_MODE` (default on) routes events without creating Works; `HARNESS_ACTION_V2_ENABLED` turns on actions. Templates and correlation rules live under `work:` in the config file (`harness.local.json` on the desktop); `work_extension` plugins add action executors and metric sources. Run `scripts\u002Fv2\u002Fdemo.sh` for an offline end-to-end incident on the built-in simulator, or `scripts\u002Fv2\u002Fdemo-pg.sh` for the same on `harness all` + PostgreSQL with change\u002Falert correlation, idempotent replay, `kill -9` crash recovery and pod topology checks.\n\n- **Queues and resource pools**: five scheduling queues (`critical-mitigation`, `incident-investigate`, `routine-work`, `batch-evaluation`, `background-improvement`), each with its own claim loop and concurrency, plus pools for model runs (per tenant, across replicas), production actions and world snapshots. A full pool defers a step instead of failing it; queues never relax approval or risk rules.\n- **Bounds** (RFC §20.3): besides runs, replans, duration, agents and actions, a template caps the total model spend of a Work (`max_cost_usd`), its active watches (`max_watches`, default 8), its evidence (`max_evidence` 500 \u002F `max_evidence_bytes` 4 MiB) and the correlated events per minute that reach it (`max_event_rate`, default 120: past it, events stay linked in the inbox but neither grow the timeline nor wake the Work). A step refused by a bound blocks the Work with the reason; hits are counted in `harness_work_limit_total{limit}`. Per-run tokens, cost and parallel read-only tools are bounded by the run profile; snapshot depth and size by the world service.\n- **Evidence planning** (RFC §12.4): before a run or agents stage starts and the Work already has competing hypotheses, the framework ranks read-only checks by how well they separate them (discrimination × output trust × freshness, minus latency, cost and load) and puts the top checks in each run's goal; parallel agents get different checks. Only tools the run's profile shows, that are R0 after risk overrides, that the policy allows without approval and that fit the remaining budget can be planned; a run's `next_checks` suggestions only re-rank those. Plans are on the timeline (`work.evidence_planned`) and counted in `harness_evidence_plan_total`. Operators describe checks with tool labels `evidence.topics`, `evidence.latency`, `evidence.cost`, `evidence.load` and `evidence.exclude`; stages tune it with `evidence_plan: {max_checks, disabled}`; `HARNESS_EVIDENCE_PLANNING=false` turns it off.\n- **Security**: roles `viewer`, `operator`, `approver`, `admin`, `service` (events only) and `break_glass` (never implied); per-principal scopes limit event sources\u002Ftypes, resources and the approvable risk. R3 is never allowed, R2 always needs an approval bound to the intent hash; denials, approvals and break-glass are audited.\n- **Domain plugins**: `sre` (Prometheus\u002FAlertmanager, Kubernetes, OTel, GitOps\u002FArgo CD, Istio traffic, CMDB, Jira, AI infra) and `sre-sim`; source-native webhooks at `POST \u002Fv1\u002Fsources\u002F{source}\u002Fevents`; external plugins use `pkg\u002Fsdk`.\n- **Evaluation and learning**: per-Work scorecard and safety gates (`\u002Fevaluation`), ledger-based postmortems (`\u002Fpostmortem`, Markdown or a review Work), `postmortem` and `follow-up` templates, playbook proposals (`\u002Fplaybook`) and memories with applicability and verified-outcome promotion.\n- **Work bench**: `harness work-bench run bench\u002Fcases` replays incidents deterministically with expectations and a baseline gate; `record`\u002F`replay` turn a real Work into a case.\n- **Observability**: Work, action, event, watch and world metrics, with a Grafana dashboard and alert rules in `deploy\u002Fobservability\u002F`.\n- **Desktop**: a Works view with outcomes, scorecard, action approvals, hypotheses, timeline and postmortems.\n\nDetails: [docs\u002Fv2-control-plane.md](docs\u002Fv2-control-plane.md).\n\n## Deployment\n\n```bash\ndocker compose -f deploy\u002Fdocker-compose.yml up --build\n```\n\n- Roles: `api` \u002F `worker` \u002F `scheduler`; `all` runs them in one process, multiple processes need NATS.\n- Kubernetes manifests: `deploy\u002Fk8s\u002Fharness.yaml`.\n- Full plugin and configuration example: `deploy\u002Fharness.example.yaml`.\n- In production use a non-superuser database role, otherwise RLS has no effect.\n\n## Configuration\n\n| Variable | Purpose |\n|---|---|\n| `HARNESS_DATABASE_URL` | required |\n| `HARNESS_NATS_URL` | cross-process wake-ups and event delivery |\n| `HARNESS_CONFIG` | plugin config file (YAML\u002FJSON) |\n| `HARNESS_AUTH_MODE` | `dev` \u002F `token` \u002F `oidc` |\n| `HARNESS_SSE_MODE` | `push` (default) \u002F `poll` |\n| `HARNESS_MODEL_DAILY_BUDGET_USD` | per-tenant daily budget |\n| `HARNESS_REQUIRE_DISTINCT_APPROVER` | the approver cannot be the initiator |\n| `HARNESS_AUTO_PROFILE` \u002F `_VERSION` | run profile for auto sessions; defaults to `sre-diagnosis` \u002F `10` |\n| `HARNESS_PLANNER_MODEL_ALIAS` \u002F `_EFFORT` | model and effort used by the planner |\n| `HARNESS_PLANNER_FALLBACK_PROFILE` \u002F `_VERSION` | runbook used when planning fails; defaults to `sre-diagnosis` \u002F `8` |\n| `HARNESS_PLANNER_MAX_REPAIRS` \u002F `_MAX_NODES` | plan repair attempts and generated node limit |\n| `HARNESS_PLAN_APPROVAL` | `auto` (default), `always` or `never`; `auto` reviews generated plans with writes |\n| `HARNESS_PLAN_APPROVERS` | required plan approvals; R3 plans always require at least two |\n| `HARNESS_PLAN_MAX_REPLANS` | times a failed generated flow is replaced by a new plan in the same run (default 1, negative disables); the new plan sees which nodes ran and which side effects completed, and runs as a new flow generation |\n| `HARNESS_PLANNER_MAX_CHILDREN` \u002F `_TOTAL_RUNS` \u002F `_DEPTH` \u002F `_ITERATIONS` | generated-graph fan-out limits |\n| `HARNESS_PLANNER_MAX_MODEL_CALLS` \u002F `_MAX_ESTIMATED_TOKENS` | static model-call and output-token ceilings |\n| `HARNESS_OUTPUT_OFFLOAD_BYTES` | tool results above this size are stored and summarized; the model reads them with `harness.artifact_query` (default 24576, negative disables) |\n| `HARNESS_CONTEXT_PROVIDER_TIMEOUT` \u002F `HARNESS_CONTEXT_MAX_FACTS` | per-provider deadline and fact limit for environment facts |\n| `HARNESS_PLANNER_REACT_PATTERNS` \u002F `_FLOW_PATTERNS` | fallback routing patterns, `\\|\\|`-separated regexes; `none` disables a list |\n| `HARNESS_PLANNER_ROUTER_EXAMPLES` | JSON file of `{\"text\",\"mode\"}` examples replacing the built-in routing classifier examples |\n| `HARNESS_PLANNER_FALLBACKS` | JSON list of `{\"name\",\"services\",\"goal_pattern\",\"profile_id\",\"version\"}` fallback rules tried before the default runbook |\n| `HARNESS_PLANNER_MODEL_LADDER` | comma-separated model aliases: the first plans, each repair escalates to the next |\n| `HARNESS_PLANNER_CACHE_TTL` \u002F `_CACHE_SIZE` | plan cache lifetime (default `10m`, `0` disables) and entries (default 512) |\n| `HARNESS_PLANNER_TYPICAL_OUTPUT_TOKENS` | per-call output used for the token estimate (default a quarter of the max; negative uses the worst case) |\n| `HARNESS_PLANNER_AUTO_PIN` \u002F `_DRY_RUN` | pin tool-less agent nodes to read-only tools; dry-run plans before approval (both default `true`) |\n| `HARNESS_REASONING_VERIFY` | independent verification of final task conclusions (default `true`; the rule layer needs no model) |\n| `HARNESS_VERIFIER_MODEL_ALIAS` \u002F `_EFFORT` \u002F `_TIMEOUT` | model judge for the verifier (empty: rules only), its effort and deadline (default `1m`) |\n| `HARNESS_VERIFIER_MEMORY_IS_EVIDENCE` | let a memory alone support a VERIFIED claim (default `false`) |\n| `HARNESS_REASONING_MAX_BACKTRACKS` | times an unaccepted conclusion is handed back to the agent (default 1, negative: never) |\n| `HARNESS_REASONING_SAMPLES` \u002F `_MIN_AGREEMENT` | self-consistency samples of a final conclusion (default 1: off) and the agreement it needs (default 0.6) |\n| `HARNESS_REASONING_CALIBRATION` \u002F `HARNESS_CALIBRATION_MIN_FORECASTS` | confidence calibration per profile (default `true`) and the forecasts needed to fit it (default 30) |\n| `HARNESS_RUN_MAX_COST_USD` \u002F `HARNESS_RUN_MAX_TOKENS` | per-run model spend limit (default 0: off); from 80% the agent is told to conclude, at 100% the kernel concludes for it without another model call. A profile's `run_limits` can only tighten them |\n| `HARNESS_LOOP_MAX_REPEATS` \u002F `HARNESS_LOOP_STALL_STEPS` | how often an identical call may run again (default 1, negative: unlimited) and how many tool results without new content trigger the stall notice (default 4; twice that forces a conclusion; negative: off) |\n| `HARNESS_MAX_PARALLEL_TOOLS` | read-only calls of one model response that run together (default 4; 1: one call per step) |\n| `HARNESS_ARTIFACT_CACHE_BYTES` | worker cache of immutable artifacts used to rebuild the agent context (default 64 MiB; negative: off) |\n| `HARNESS_TOOL_TOP_K` | tool schemas the model sees per run when more tools are visible (default 30; negative: all); the rest are listed by name and loaded with `harness.load_tools` |\n| `HARNESS_COMPACT_TOKENS` | compact history when uncompacted tool results exceed about this many tokens (default 16000; negative: step count only) |\n| `HARNESS_MODEL_ROUTINE_ALIAS` \u002F `HARNESS_MODEL_ESCALATED_ALIAS` | model alias for routine investigation steps and for the steps that decide the outcome (default: the strategy's alias) |\n| `HARNESS_SPECULATIVE_TOOLS` | start allowed read-only calls while the model is still streaming and reuse the result in the tool step (default `false`) |\n| `HARNESS_LEASE_SAFETY_MARGIN` | drift margin the worker subtracts (on top of one heartbeat interval) from its lease; it stops executing, and never dispatches a side effect, once that conservative lease runs out (default `2s`) |\n| `HARNESS_COMMIT_RETRY_BUDGET` | how long a failed step commit is retried while the lease is kept alive (default `30s`; negative: one try). A commit that failed ambiguously is settled from the fenced attempt row |\n| `HARNESS_DB_LOCK_TIMEOUT` \u002F `HARNESS_DB_STATEMENT_TIMEOUT` \u002F `HARNESS_DB_TX_RETRIES` | per-transaction limits for kernel transactions (claim, commit, effect ledger, lease recovery; defaults `2s` \u002F `10s`) and re-runs after failures PostgreSQL guarantees rolled back (serialization, deadlock, lock timeout; default 3) |\n| `HARNESS_DB_IDLE_TX_TIMEOUT` | `idle_in_transaction_session_timeout` for every pool connection (default `1m`; `0` disables) |\n| `HARNESS_SHORT_TERM_MESSAGES` | earlier conversation messages rendered verbatim (default 12; older ones are condensed into a digest; negative: all) |\n| `HARNESS_EMBEDDING_BASE_URL` \u002F `_MODEL` \u002F `_DIMENSIONS` \u002F `_API_KEY_ENV` | desktop runtime: use an OpenAI-compatible embeddings endpoint instead of the hashing embedder; the key is read from the variable named by `_API_KEY_ENV` (default `HARNESS_EMBEDDING_API_KEY`). The server configures `embedder: {name: http, …}` in `HARNESS_CONFIG` |\n\nGenerated plans emit `plan.generated`, `plan.validation_failed`, `plan.repaired`, `plan.fallback`, `plan.approval_requested`, `plan.approved`, `plan.rejected`, `plan.executed`, `plan.injection_suspected`, `plan.replan_requested` and `plan.replanned` events. Planner metrics are exposed on `\u002Fmetrics`: `harness_plan_total`, `harness_plan_duration_seconds`, `harness_plan_repairs_total`, `harness_plan_validation_failures_total` and `harness_plan_fallback_total`.\n\nPlan datasets record the plan artifact, analysis, flow state, approvals, outcome, duration and cost. `POST \u002Fv1\u002Feval\u002Fdatasets\u002F{id}\u002Fplan-cases` adds a terminal run, `POST \u002Fv1\u002Feval\u002Fplan-runs` replays the frozen split offline, and the report groups success, safety, replay completion, steps, duration and cost by variant (`react`, `fallback_flow`, `generated_flow`, `profile_flow`).\n\nSee `deploy\u002Fharness.example.yaml` for the rest.\n\n## API\n\n`POST \u002Fv1\u002Fruns`, `GET \u002Fv1\u002Fruns\u002F{id}\u002Fevents\u002Fstream` (SSE), `POST \u002Fv1\u002Fruns\u002F{id}\u002Fcommands` (approve \u002F pause \u002F cancel), `\u002Fv1\u002Fsessions…`, `\u002Fv1\u002Fmemories…`, `\u002Fv1\u002Feval…`, `\u002Fv1\u002Fevolution…`, `\u002Fv1\u002Fextensions…`, `\u002Fv1\u002Ftriggers…`, `\u002Fv1\u002Freasoning…`, `GET \u002Fv1\u002Fruns\u002F{id}\u002Fattachments\u002F{index}`, `\u002Fhealthz`, `\u002Fmetrics`. With the work engine: `\u002Fv1\u002Fworks…`, `\u002Fv1\u002Fwork-templates`, `\u002Fv1\u002Fevents…`, `\u002Fv1\u002Fworld…`, `\u002Fv1\u002Factions…` (see [docs\u002Fv2-control-plane.md](docs\u002Fv2-control-plane.md)).\n\n## Tests\n\n```bash\nHARNESS_PG_TEST_URL=postgres:\u002F\u002Flocalhost\u002Fharness_test go test -race .\u002F...\nharness work-bench run bench\u002Fcases\n```\n\nThe CI gates (RFC §24.3) are below; the workflow file and the benchmark cases are kept local, not in the repository:\n\n- **gofmt, go vet** (also with `-tags=integration`).\n- **Unit tests** on SQLite and PostgreSQL, plain and with `-race`.\n- **Migrations are append-only**: `migrations\u002Fchecksums.sha256` pins every applied file. After adding a migration, record it with `go test .\u002Fmigrations -run AppendOnly -update-checksums`; editing a recorded migration fails the build.\n- **Upgrade compatibility**: `TestUpgradeKeepsOldRecordsReadable` seeds records at old schema versions (v1.0, the last v1 schema, early v2), upgrades to the latest and reads them back with today's code.\n- **Fault injection** (`go test -tags=integration .\u002Finternal\u002Forchestration -run Fault`): three replicas process the same Works while replicas crash mid-pass, commits are lost after they succeeded and the executor times out before or after applying. The gate: every effect is dispatched and applied at most once, nothing needing approval is dispatched without it, every SUCCEEDED Work has a SATISFIED outcome, and the only other end state is BLOCKED on an unknown effect for a human. The run logs its seed; set `HARNESS_CHAOS_SEED` to replay one.\n- **Bench and load**: the benchmark cases, then `harness work-bench load`, which reports p50\u002Fp95\u002Fp99 and throughput for Work creation, event correlation, wake lag (a Work becoming due until an orchestrator starts it) and world snapshots, and fails when a series breaks the `-budget` file:\n\n```bash\nharness work-bench load -budget bench\u002Fload-budget.json            # temporary SQLite store\nHARNESS_DATABASE_URL=postgres:\u002F\u002Flocalhost\u002Fscratch harness work-bench load -store postgres -works 2000 -events 20000\n```\n\nPoint `-store postgres` at a migrated scratch database: the run writes Works, events and facts under tenant `load`.\n\nPostgreSQL tests (including the v2 control-plane contract tests, which always run on SQLite too) read `HARNESS_PG_TEST_URL` and are skipped when it is unset; use a UTF-8 database, since full-text search on `SQL_ASCII` drops CJK text. The live planner probe exercises the real provider tool-call path (and exits non-zero if the model does not call `submit_flow` with a valid plan):\n\n```bash\nANTHROPIC_API_KEY=sk-ant-... go run .\u002Fcmd\u002Fplancheck -goal \"restart checkout after approval\"\n```\n\n## Known limitations\n\n- Model routing and KV-cache offload control for vLLM\u002FSGLang are not implemented; serving health, diagnosis and prefill\u002Fdecode pool scaling are.\n- Artifacts: the filesystem store is single-node; use the `s3` store (S3\u002FMinIO) in production.\n- Offline evaluation uses its own in-memory ledger; its cost is not charged to the tenant budget.\n- Plan replay drives the flow state machine with recorded node results; graphs with bounded loops are compiled and safety-checked but not step-replayed.\n- Plugin config is read at startup; changes need a restart. Observability sources are the exception: they are versioned in the catalog and change online through the API (with rollback).\n\n\n## Production control plane\n\nThe Work engine (`HARNESS_WORK_ENGINE_ENABLED`) runs long-lived goals on top\nof the durable run kernel. With it off, nothing below runs and the run API is\nunchanged. This section lists what the control plane provides for production\nuse.\n\n- **Deployment gate.** `HARNESS_DEPLOYMENT_TIER=local|staging|production`.\n  `harness validate-config --tier production` evaluates the flags against the\n  tier without connecting to anything and derives the rollout stage\n  (G0 legacy, G1 shadow, G2 read-only, G3 dry-run, G4 bounded production,\n  G5 scoped automation). A production deployment missing a safeguard (custom\n  policy, audit sink, known-target and distinct-approver checks, an action\n  allow-list and scope, healthy required sources) is refused or runs in\n  *investigation mode* with actions withheld. `harness doctor` checks a\n  running deployment; `harness release-gate` compares two attestations;\n  `GET \u002Fv1\u002Fgovernance\u002Fattestation` serves the current one.\n- **Cluster-wide admission.** Model-run budgets are transactional\n  reservations, so replicas cannot oversubscribe; reservations are fenced,\n  idempotent per stage and reaped (renewed when the run is really in flight).\n  Weighted tenant fairness, priority aging, reserved critical capacity,\n  admission deadlines and load shedding for batch queues. Run terminal events\n  wake the owning Work at once; polling and the reconciler remain the safety\n  net.\n- **Observability Query Broker.** A tenant-scoped Source Catalog (endpoints\n  and credentials are operator-owned references), Prometheus\u002FVictoriaMetrics\u002F\n  Mimir, Loki, Tempo, Jaeger and change-ledger providers, scope and budget\n  checks, circuit breakers, caching, redaction, prompt-injection flagging,\n  artifact storage and an audit trail. Results are `ok|partial|empty|stale|\n  unavailable|unauthorized|denied`; only a complete bundle can support a\n  \"healthy\" statement. Semantic tools: `sre.service_health`,\n  `sre.latency_diagnose`, `sre.error_diagnose`, `sre.dependency_health`,\n  `sre.gpu_health`, `sre.inference_health`, `sre.change_correlation`.\n- **Action safety.** Resource identity (aliases share one lock; a recreated\n  resource invalidates old approvals), descriptor contract hashing, unknown\n  effects block further writes to the target, dry-run \u002F allow-list \u002F scope \u002F\n  strict pre-authorization, break-glass with incident reference, expiry and a\n  second-person review, and `actiontest.Certify` for executor contracts.\n- **World quality.** Collector health, source authority and conflict\n  detection fail closed for production actions; stale facts are kept, never\n  deleted.\n- **Work graph.** Child Works inside the parent's ceiling, dependency edges\n  with atomic cycle rejection, a `children` stage, cancellation cascade,\n  structured agent findings validated against the evidence ledger (independent\n  evidence, no majority vote), a runbook registry, Improvement Works from\n  postmortems and an intent router.\n- **Events and protocol.** A versioned event envelope, signed sources,\n  late-event handling, recorded correlation decisions and topology-assisted\n  leads. A stable event contract (`?protocol=1`), a unified\n  `\u002Fv1\u002Fworks\u002F{id}\u002Fview`, and a Go SDK with a resumable `Subscribe`.\n- **AI infrastructure.** UUID-based GPU identity (replacement and MIG\n  changes), ECC\u002FNVLink\u002FPCIe signals, TPOT\u002FE2E\u002Fcache\u002Fprefill\u002Fdecode signals,\n  prefill\u002Fdecode diagnosis, guarded `serving.scale_prefill|decode`, a cost\n  model, and an S3\u002FMinIO artifact store.\n- **Rule-as-code.** `monitoring.rule_validate`, `monitoring.rule_propose` (R0)\n  and `monitoring.apply_via_gitops` (R2, pull request only).\n\nSchema changes are append-only migrations for PostgreSQL and SQLite. CI, the\ndeterministic bench cases and the load budget live in `.github\u002Fworkflows` and\n`bench\u002F`.\n","SreAgentHarness 是一个面向站点可靠性工程（SRE）的自托管、多租户智能体运行时框架，专用于自动化事故诊断与响应。其核心功能包括：基于风险等级（R0–R3）的工具调用审批机制、支持崩溃恢复的持久化可续跑执行、完整审计追踪、模型网关（支持Claude\u002FOpenAI\u002FGemini）、MCP兼容工具集成，以及原生桌面聊天客户端。技术上采用Go编写，以数据库为单一事实源，通过动作哈希防重放、租约+围栏令牌保障状态一致性，并内置提示词清单、向量+图谱混合记忆与可验证推理流。适用于中大型运维团队在生产环境中安全、可控地落地AIOps诊断场景。",2,"2026-11-24 04:39:39","CREATED_QUERY"]