# Herma -- the context & capability shim for any agent: full text

> Herma: context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

The main documents of this repo in full, in reading order (read_order in architecture.json), so a review tool or a model can read the whole design from one file. Generated by `scripts/build_index.py`; the files themselves win if they ever differ.

Contents: README.md, docs/summary.md, docs/architecture.md, docs/harnesses.md, docs/setup.md, examples/provisions/README.md, docs/handoff.md, AGENTS.md

========================================================================
FILE: README.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/README.md
========================================================================

# Herma -- the context & capability shim for any agent

**Herma:** context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

## Tasks (`verbs`) & Task Objects (`nouns`) in Plain Language

Everything in the `ta-amps` ecosystem reduces to two plain-language primitives plus two public surfaces:

- **Tasks (`verbs` on the wire)**: independently schedulable units of work (`enqueue -> claim -> heartbeat -> submit/park`) leased by an authorized worker and guarded by a monotonic `fence` token so two workers never double-execute the same job.
- **Task Objects (`nouns` on the wire)**: every reusable tool, `Feed`, dataset, statute card, LoRA adapter spec, provision shim, or SHA-256 receipt a task uses or creates, stored as compare-and-set records guarded by `expected_version`.
- **Two public surfaces + two infrastructure layers**: **Eranos** (the two-sided public-good token marketplace) and **Agora** (the single public overview of architecture, setup, harness feeds, and contribution) are the two public surfaces; **Tessera** (atomic work & CAS storage engine) and **Herma** (inline context & capability shim) are supporting infrastructure. Seed packs bundle reusable Task Objects and Tasks.

## Why Everyday AI Use Feels Frustratingly Dumb Without a Shim

Raw LLM API calls force an ugly tradeoff on every turn:

1. **Prompt bloat (`HarnessTax`)**: Stuffing every project rule, post-cutoff schema, URI, and refusal boundary into a static system prompt burns thousands of tokens on every turn even when 95% of those rules are irrelevant to the current edit.
2. **Post-cutoff amnesia**: Omitting those local contracts makes even strong models hallucinate retired fields, skip optimistic concurrency (`expected_version`) or queue lease `fence` tokens, and miss newly created Task Objects.

In Classical Greece, a *herma* was an inscribed roadside stone pillar placed along the road with concise directional pointers for travellers *en route*. **Herma** sits inline between configurable coding harnesses (`muse-code`, `opencode`, `claude-code`, `codex`, `swarm-worker`, `personal-assistant`) and upstream model endpoints (`/v1/chat/completions`, `/v1/responses`, `/v1/messages`). On each request, Herma evaluates **three trigger tiers** (`keyword`, `semantic`, `micromodel`) with strict **`caller_scope` isolation** to either:

- **Respond directly (`action: "respond_directly"`)** in 0 upstream LLM tokens when a deterministic contract or natural-language schema lookup (`"What are tasks and task objects?"`) has an authoritative answer, or
- **Shim bounded Task Object & Task context (`action: "shim_context"`)** right before inference -- lifting frozen 150-row `Llama 3.2 3B` exact tool-call accuracy from **`52.0% -> 64.7%` (+12.7 pp)** with **zero weight updates** (see [`eval/shim_lift_summary.json`](eval/shim_lift_summary.json) and [`eval/herma-shim-lift.svg`](eval/herma-shim-lift.svg)).

![Herma Context Shim Lift & Meta Model Routing](eval/herma-shim-lift.svg)

## Which Meta Models Do What

Herma coordinates frontier Muse models, open-weights `Muse Glimmer` QLoRA specialists, local `Llama 3.2` Shim Routers / Parametric Memory LoRAs, and the `Muse Code` coding harness under one strict privacy invariant (`ContributorTierRefusedError` blocks every `*-contributor` tier so private or NGO inputs never enter training):

| Meta Model / Harness | Role in Herma & `ta-amps` | Memory / Routing Regime | Measured / Verified Signal |
| :--- | :--- | :--- | :--- |
| **`Muse Spark 1.3`** (`muse-spark-1.3`) | Frontier workhorse for open-ended multi-step coding, complex tool orchestration, and independent review Tasks (`verbs`). | Herma Context Shim + Standard-mode passthrough (`*-contributor` refused with HTTP 403). | Enforces `caller_scope` isolation, durable microdollar budget reservations, and SHA-256 `InjectionReceipt` auditing. |
| **`Muse Wonder 1.0`** (`muse-wonder-1.0`) | Fast structured synthesis and typed work-conversation proposals (`POST /v1/conversations/turn`). | Schema-checked single-proposal dialogue (`executed: false`; never runs domain side effects server-side). | Deterministic duplicate-key JSON rejection and exact picodollar/microdollar spend ceilings across Python and Worker. |
| **`Muse Glimmer 30B QLoRA`** | Open-weights specialist fine-tuned with 4-bit QLoRA adapters for recurring post-cutoff Task Object schemas and refusal rules. | **LoRA as Parametric Memory** -- internalizes stabilized schemas so turns avoid repeated `HarnessTax` prompt bloat. | **`93.3% -> 99.3%`** (+6.0 pp) exact tool-call match on pre-registered 150-row synthetic holdout (`100.0%` valid JSON). |
| **`Llama 3.2 1B / 3B`** | Sub-10ms local Tier-3 **Shim Router** (`1B` PEFT LoRA) & edge **LoRAs as Parametric Memory** (`1B`/`3B` PEFT LoRA). | Zero-weight Herma Shim first (`52.0% -> 64.7%` on `3B`), then PEFT LoRA (`r=16..32`) once schemas stabilize. | `Llama 3.2 3B`: `52.0%` base -> **`64.7%` Herma Shim** -> **`72.7%` promoted LoRA**; `1B`: `12.0% -> 50.7%` on 150-row frozen test. |
| **`Muse Code`** (`X-Herma-Harness: muse-code`) | Configurable agentic coding harness connecting inline to Herma over `/v1/responses` and `/v1/chat/completions`. | Benchmarked alongside **Harness Square / Harness2**, **OpenCode**, and **Pi** inside encapsulating `Feed` Task Objects. | Shimmed via `PROV-HARNESS-FEEDS-GUIDE` with explicit `HarnessTax` token overhead and receipt-backed benchmark profiles. |

## Prompt Shimming vs LoRAs as Parametric Memory (`training/` & `eval/`)

Herma pairs zero-weight prompt shimming with reproducible PEFT LoRA specifications (see [`training/README.md`](training/README.md), [`training/shim-router-lora-spec.json`](training/shim-router-lora-spec.json), and builtin starter `PROV-LORA-MEMORY-ROUTING`):

1. **Volatile or caller-scoped facts -> Herma Context Shim (`0` weight updates)**: Live queue lease rules, newly minted URIs, statute cards, and per-caller provisions (`POST /v1/context`, `PUT /v1/provisions/{id}`).
2. **Stable post-cutoff schemas -> PEFT LoRA as Parametric Memory**: Once a Task Object schema or natural-language routing boundary stabilizes across hundreds of turns, compile synthetic verified traces into a `Llama 3.2 1B/3B` or `Muse Glimmer 30B` PEFT LoRA adapter gated by held-out promotion checks.
3. **Novel multi-step reasoning -> Frontier Passthrough**: Route through Herma to `Muse Spark 1.3` or `Muse Wonder 1.0` in Standard mode.

## Core Architecture & Operational Boundaries

The default agentic executor is the worker's own harness holding a Tessera Task (`verb`). Inputs, contracts, artifacts, and evidence remain scoped Task Objects (`nouns`). Herma supplies configured context when useful; server model turns are explicit bounded exceptions.

- **Three-Tier Trigger Engine (`action: "shim_context"` or `"respond_directly"`)**:
  - **Tier 1 -- Keyword, Regex, File-Path & Tool Triggers**: Exact natural-language phrases, bounded regexes, workspace file globs (`src/tessera/*.py`, `training/*`), and declared tool names.
  - **Tier 2 -- Semantic Similarity Triggers**: Hybrid concept-cluster + subword cosine matching (plus optional `/v1/embeddings`) matching paraphrased engineering intent without shared literal IDs.
  - **Tier 3 -- Micromodel Router Triggers**: Lightweight classifier prompt (`HERMA_MICROMODEL_URL`, with deterministic offline fallback) invoked only when Tier 1 and Tier 2 did not already match in `any` mode.
  - **Typed & Offline Boundaries**: Model decisions require a JSON boolean `apply` and finite numeric confidence; malformed replies never activate fallback. Offline previews and dry-runs skip remote model/embedding calls. See [routing boundaries and evidence](docs/design-and-evidence.md#configured-shim-reasoning-and-offline-boundaries).
- **Deterministic Anti-RAG Entity Memory & Self-Improving Shim Loop**:
  - Extracts `file_path`, `code_symbol`, `tessera_uri`, `statute_card_id`, and `error_signature` entities with **zero LLM calls and zero embeddings**, tracks working-entity frequency per `(caller_scope, project_tag)` (`GET /v1/memory`), attributes follow-up retry errors (`POST /v1/outcomes`), and synthesizes reviewable draft `candidate_provisions` (`GET /v1/insights`) without auto-mutating active rules.
- **Typed Work Conversations & Provider Accounting**:
  - Optional [typed work conversations](docs/conversations.md) let authenticated harnesses request one schema-checked noun/verb proposal at a time (`executed: false`). Operator-funded providers support independent pause/backpressure ([provider availability](docs/conversations.md#operator-availability-and-automatic-backpressure)), per-caller [operator grants](docs/conversations.md#operator-grants-per-caller), durable exact-microdollar reservations, and the offline [Jev worker adapter](docs/conversations.md#jev-typed-decisions). See also the [worker-first execution policy](docs/WORKER-FIRST-EXECUTION.md) and [agent troubleshooting guide](docs/agent-troubleshooting.md).
- **Caller Isolation & Layer-1 Governance Lens**:
  - Starter provisions (`PROV-DIRECT-NOUN-VERB-SCHEMA`, `PROV-TESSERA-FENCING`, `PROV-RISK-REVIEW-NON-ACCUSATORY`, `PROV-HARNESS-FEEDS-GUIDE`, `PROV-LORA-MEMORY-ROUTING`, `PROV-NGO-HUMAN-BOUNDARY`, `PROV-EDGE-ORIGIN-LOCKDOWN`) carry verified `metadata_tags.fabric_governance` and live in protected `system_builtin` (`403 builtin_protected` for non-admins). Custom rules and receipts are isolated per `caller_scope = key:<key_id>`.

## Quick Start & Reproducible Container

```bash
git clone https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents.git
cd herma-infrastructure-shim-for-intelligent-agents
make setup
make check
make demo
```

Herma installs independently (`pyproject.toml` pins Tessera to an immutable public Git commit and `uv.lock` locks dependencies). You can also build and run the standalone container from the repository root:

```bash
docker build -t herma-shim:local .
docker run --rm -p 7730:7730 herma-shim:local
```

## The `ta-amps` Ecosystem

- **Eranos** (`https://eranos.ta-amps.workers.dev`), public surface: the two-sided marketplace where people donate spare AI capacity and their agents build and review agent kits for nonprofits (`github.com/ta-amps/eranos-public-marketplace-for-public-good-token-burn`)
- **Agora** (`https://ta-amps.github.io/agora-public-overview-architecture-setup-and-contribution/`), public surface: the single overview of architecture and setup, harness research feeds, use cases, connecting any agent, and contributing (`github.com/ta-amps/agora-public-overview-architecture-setup-and-contribution`)
- **Tessera** (`https://tessera.ta-amps.workers.dev`), infrastructure: atomic Task (`verb`) work queue and compare-and-set Task Object (`noun`) storage (`github.com/ta-amps/tessera-infrastructure-work-and-storage-engine`)
- **Herma** (`https://herma.ta-amps.workers.dev`), infrastructure: context-shimming AI middleware for configurable coding harnesses (`github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents`)
- **Pack library** (`github.com/ta-amps/seed-packs-library-of-nouns-and-verbs`): seed packs of Task Objects (`nouns`) and Tasks (`verbs`), including synthetic-only exploitation-evidence checks
- `https://home.ta-amps.workers.dev` redirects visitors to Agora and serves the agent brief as text at `/connect`.

## Documentation & Artifacts

- [docs/summary.md](docs/summary.md) -- one-page overview
- [docs/architecture.md](docs/architecture.md) -- components, trust boundaries, and invariants
- [docs/harnesses.md](docs/harnesses.md) -- connecting `muse-code`, `opencode`, `claude-code`, and `codex`
- [docs/setup.md](docs/setup.md) -- local setup, context database (`GET/POST /v1/context`), Tessera & handshake sync, and Cloudflare deploy
- [docs/handoff.md](docs/handoff.md) -- current status and roadmap
- [examples/provisions/README.md](examples/provisions/README.md) -- builtin starter provisions & atomic Task Object / Task context entries
- [training/README.md](training/README.md) -- PEFT LoRA Shim Router & Parametric Memory specification (`requirements-train.txt`, `shim-router-lora-spec.json`)
- [eval/shim_lift_summary.json](eval/shim_lift_summary.json) & [eval/herma-shim-lift.svg](eval/herma-shim-lift.svg) -- measured context-shim lift and trigger routing benchmarks

External coding harnesses and personal assistants: [anonymous previews and tracked Tessera access](docs/access-modes.md), or `GET /connect.json`.

========================================================================
FILE: docs/summary.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/docs/summary.md
========================================================================

# Summary

**Herma:** context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

Before an outbound coding-harness request reaches `/v1/chat/completions`, `/v1/responses`, or `/v1/messages`, Herma:

1. Verifies the caller holds a scoped `hmk_` credential bound to a configurable coding harness (`muse-code`, `opencode`, `claude-code`, `codex`, `swarm-worker`, or `custom-harness`), isolates custom state under `caller_scope = key:<key_id>` while protecting `system_builtin` rules, and accepts personal assistants with the same scoped credentials. It refuses any model ID containing `contributor`, such as `*-contributor` (`HTTP 403`).
2. Evaluates `system_builtin` + caller-scoped **provisions** filtered by the Layer-1 Governance Lens across **keyword/regex/path/tool** (`~0 ms`), **semantic** (`~1-5 ms`), and **micromodel** triggers, short-circuiting Tier 3 whenever an earlier tier already matched in `any` mode.
3. **Shims context (`action: "shim_context"`)**: Injects matched rule details, SHA-256 verified URIs, and bounded `[NOUN/VERB CONTEXT]` entries resolved from Herma's caller-isolated context database (`context_entries` via `POST /v1/context`, governed Tessera noun/verb stores, or remote handshake servers), deduplicating prior turns (`once_per_conversation`).
4. **Responds directly (`action: "respond_directly"`) & learns deterministically**: Short-circuits upstream LLM execution with zero upstream token spend when a rule answers deterministically, tracks top-of-mind entities (`GET /v1/memory`) and retry-error outcomes (`POST /v1/outcomes`), and synthesizes reviewable `candidate_provisions` (`GET /v1/insights`) without mutating active rules.

========================================================================
FILE: docs/architecture.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/docs/architecture.md
========================================================================

# Architecture

**Herma:** context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

```mermaid
flowchart LR
  H["Configurable Coding Harness<br/>muse-code / opencode / claude-code / codex"] --> E["Cloudflare Worker Edge<br/>D1 + HSTS/CSP + x-edge-auth"]
  E --> G["Harness Gate & Caller Scope<br/>hmk_ key:<id> + builtin lock"]
  G --> T["3-Tier Trigger Engine<br/>1. Keyword  2. Semantic  3. Micromodel"]
  S[("Caller-Isolated Provisions + Context DB<br/>SQLite / D1 / Governed Tessera / Handshake")] --> T
  T -->|"action: respond_directly"| D["Direct Protocol Response<br/>0 upstream tokens + SHA-256 Receipt"]
  T -->|"action: shim_context"| I["Context Shim + Entity Memory<br/>[NOUN/VERB CONTEXT] + URIs + Outcomes"]
  I --> U["Upstream LLM Endpoint<br/>/v1/chat/completions · /v1/responses · /v1/messages"]
```

## Components

- `herma/errors.py` -- RFC 9457 `problem+json` error hierarchy (`403 harness_required`, `403 admin_required`, `403 builtin_protected`, `403 contributor_tier_refused`, `409 version_conflict`).
- `herma/schemas.py` -- strict Pydantic v2 models for `Provision` (`shim_context` / `respond_directly` + `context_refs`), `ContextEntry` (`noun` / `verb` / `detail` + `version`), `WorkingEntity`, `RuleOutcomeRecord`, `InsightsResponse`, `DryRunResponse`, and `InjectionReceipt`.
- `herma/harness_gate.py` -- constant-time `hmk_` verification, `caller_scope = key:<key_id>`, credentialed personal-assistant access, `configure` harness attestation, and refusal of any model ID containing `contributor`.
- `herma/triggers/` -- `keyword.py`, `semantic.py`, `micromodel.py`, and `engine.py`.
- `herma/memory.py` -- zero-LLM deterministic entity extraction (`file_path`, `code_symbol`, `tessera_uri`, `statute_card_id`, `error_signature`) and reviewable `candidate_provisions` synthesis.
- `herma/store.py` -- caller-partitioned SQLite WAL store (`provisions`, `context_entries`, `harness_keys`, `injection_receipts`, `working_entities`, `rule_outcomes`), single-statement atomic SQL CAS, Layer-1 Governance Lens + SHA-256 blob verification, Tessera store sync, and remote handshake sync.
- `herma/injector.py` -- multi-protocol envelope extraction, `[NOUN/VERB CONTEXT]` rendering, direct-response assembly, turn deduplication, entity extraction, and SHA-256 receipts.
- `herma/proxy.py` -- direct-response short-circuiting (`chat.completion`, `response`, `message`), turn telemetry persistence, and upstream forwarding (JSON and streaming SSE).
- `herma/api/` -- FastAPI app (`:7730`) serving caller-isolated `/v1/*` endpoints, `/v1/memory`, `/v1/outcomes`, `/v1/insights`, read-only `POST /api/preview`, stateless JSON-RPC 2.0 `POST /mcp`, discovery routes (`/llms.txt`, `/llms-full.txt`, `/.well-known/agent-card.json`, `/robots.txt`, `/healthz`, `/favicon.svg`), and responsive SVG-branded HTML pages.
- `deploy/cloudflare/` -- 24/7 native Cloudflare Worker + D1 (`ta-amps-herma`) + `TESSERA` Service Binding with full caller-isolation, CAS, governance lens, entity memory, preview, and MCP parity.

## Invariants

| Id | Always true | Checked by |
|---|---|---|
| H01 | Personal assistants with scoped keys are accepted; browser navigation and cookie authentication are refused | `test_personal_assistant_credentials_and_browser_navigation`, `test_http_edge_lockdown_and_dry_run_across_wire_formats` |
| H02 | Provision management and remote sync require both configure scope and explicit matching X-Herma-Harness attestation | `test_personal_assistant_credentials_and_browser_navigation`, `test_route_only_key_cannot_configure` |
| H03 | Contributor-tier models (any model ID containing contributor, including -contributor) are refused across outbound LLM payloads, micromodel trigger classifiers, provider plans and operator grants before offline fallback | `test_tier3_micromodel_classifier_and_contributor_refusal`, `test_http_edge_lockdown_and_dry_run_across_wire_formats`, `test_governance_lens_blob_sha256_integrity_and_contributor_offline_refusal`, `test_contributor_models_are_refused_in_plans_grants_and_configuration` |
| H04 | Tier-1 keyword, bounded regex, path-glob, and tool-name triggers match deterministically without network calls | `test_tier1_keyword_regex_path_and_tool_triggers` |
| H05 | Tier-2 semantic triggers match paraphrased intent without literal keyword overlap | `test_tier2_semantic_paraphrase_without_literal_id` |
| H06 | Tier-1 or Tier-2 hits short-circuit Tier-3 micromodel calls when trigger mode is any | `test_engine_short_circuits_micromodel_when_keyword_matches` |
| H07 | Single-statement atomic SQL compare-and-set versions prevent silent provision and context_entries overwrites, Tessera blob URIs verify SHA-256 digests, and remote handshakes clamp max_chars | `test_cas_conflict_and_tessera_blob_sync`, `test_remote_handshake_clamps_max_chars`, `test_multi_caller_non_poisoning_builtin_lock_admin_keys_and_cas_parity` |
| H08 | Multi-turn conversations deduplicate once_per_conversation provisions and HERMA_EDGE_SECRET blocks direct origin traffic lacking x-edge-auth | `test_http_edge_lockdown_and_dry_run_across_wire_formats` |
| H09 | Matched context_refs shim bounded atomic noun, verb, and detail entries from caller-scoped context_entries or governed Tessera stores and record shimmed_context_refs in the receipt | `test_store_context_entries_and_tessera_noun_verb_resolution`, `test_api_context_database_and_noun_verb_shimming` |
| H10 | Provisions with action=respond_directly return protocol-faithful completions across chat_completions, responses, and messages without invoking upstream LLM transport while recording a SHA-256 receipt | `test_direct_response_short_circuits_upstream_across_all_protocols`, `test_cloudflare_worker_context_shim_and_direct_response_parity` |
| H11 | Caller-scoped provisions, context_entries, and receipts never poison or leak across keys, system_builtin records return 403 builtin_protected on non-admin writes, and /v1/admin/keys requires bootstrap/admin credentials | `test_multi_caller_non_poisoning_builtin_lock_admin_keys_and_cas_parity` |
| H12 | Layer-1 Tessera governance refuses status:quarantined records, requires status:verified across surfaces, enforces visibility_scope/cohort/harness tags, and verifies 64-hex SHA-256 digests on tessera://blobs URIs | `test_governance_lens_blob_sha256_integrity_and_contributor_offline_refusal` |
| H13 | Deterministic regex extraction tracks 5 entity kinds per (caller_scope, project_tag), attributes Turn N error signatures to Turn N-1 fired rules as retry_error, and emits Provision-valid candidate_provisions without mutating active rules | `test_deterministic_entity_memory_retry_outcomes_and_candidate_insights_parity` |
| H14 | Public POST /api/preview evaluates system_builtin rules with persisted=false, SVG brand chrome renders cleanly, and discovery routes plus stateless JSON-RPC POST /mcp match across Python and Cloudflare Worker | `test_public_preview_svg_brand_chrome_discovery_and_stateless_mcp_parity` |
| H16 | Micromodel decisions require boolean apply and finite numeric confidence in [0,1], malformed replies do not activate fallback, and offline trigger evaluation skips classifier and remote embedding requests | `test_micromodel_requires_typed_decision`, `test_malformed_model_reply_does_not_activate_fallback`, `test_offline_engine_blocks_all_provider_calls`, `test_preview_and_dry_run_never_call_configured_trigger_providers`, `test/triggers.test.js` |
| H17 | Operator-funded conversation turns require the caller's own exact provider/model grant; uncertain-outcome failover requires that caller's grant plus the plan opt-in; one upstream model identity is reachable through one route per plan and is held against other routes during its rate or quota limit | `test_direct_turns_need_the_callers_own_exact_grant`, `test_uncertainty_grant_defaults_off_and_a_plan_cannot_supply_it`, `test_plans_refuse_a_second_credential_for_the_same_upstream_model`, `test_rate_limit_holds_the_upstream_model_against_other_credentials`, `test/provider_grants.test.js` |
| H18 | Served pages, discovery text, starter seed data and runtime sources never name a retired pack, and fabric imports trust only the current producer surfaces: Tessera, Herma, Eranos and Agora | `test_served_text_names_no_retired_pack`, `test_seed_data_and_runtime_sources_name_no_retired_pack`, `test_governance_lens_trusts_the_same_producer_surfaces` |
| H19 | Starters synced from Tessera into system_builtin fire for routed callers only when they carry fabric_governance that passes the Layer-1 lens, and Python and the Worker decide every stored row the same way | `test_synced_starters_fire_for_routed_callers_only_with_their_governance`, `test_stored_provisions_pass_the_lens_the_same_way` |

========================================================================
FILE: docs/harnesses.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/docs/harnesses.md
========================================================================

# Connecting Configurable Agentic Coding Harnesses

Herma accepts model routing and configuration from coding harnesses and personal assistants with scoped `hmk_` credentials. Public deterministic previews require no key. Matched requests either receive shimmed rule, URI, and `[NOUN/VERB CONTEXT]` entries from Herma's database or receive a zero-token direct response (`action: "respond_directly"`).

## 1. Issue a Key

```bash
uv run herma keys issue --label workstation --harness opencode --scopes route,configure
```

Save the printed `hmk_<id>.<secret>` token in a `0600` secret file.

This CLI issues a key in the selected local database. It does not provision the
hosted Worker. For hosted access an operator issues a scoped key through the
authenticated `/v1/admin/keys` route. A Tessera `tsk_` or `tan_` credential does
not substitute for a Herma harness key. Client labels do not create authority.

## 2. OpenCode / OpenAI-Compatible Harnesses (`/v1/chat/completions`)

Point your provider `baseURL` at `https://herma.ta-amps.workers.dev/v1` (or `http://127.0.0.1:7730/v1` locally) and attach:
- `X-Herma-Key: hmk_<id>.<secret>`
- `X-Herma-Harness: opencode`
- `X-Upstream-Api-Key: <your-upstream-llm-key>` (or set `HERMA_UPSTREAM_API_KEY` on the Herma origin; direct-response rules answer without an upstream key)

For an explicitly selected Meta provider, set `X-Upstream-Base-Url` to
`https://api.meta.ai/v1` with a caller-owned upstream key. The allowed hostname
does not let the request borrow an operator credential configured for another
origin. In Workers the generic proxy uses `UPSTREAM_LLM_URL` and
`UPSTREAM_LLM_API_KEY`; the paid conversation API uses separate `META_API_KEY`
and `OLLAMA_API_KEY` secrets. These are different configuration paths.

## 3. Muse Code / Responses-Compatible Harnesses (`/v1/responses`)

Point the Responses endpoint at `https://herma.ta-amps.workers.dev/v1/responses` with `X-Herma-Harness: muse-code` and `--contributor-mode off`. Herma shims matched provisions + noun/verb context into `instructions` or returns a direct `response` object.

This describes the Responses wire adapter, not a full native provider-host
replacement. Native Muse startup also requests `/muse-code/models`; a client that
sets only a global base URL may fail before inference. The recorded native Muse
fixture used Meta's provider path with a separate typed MCP connector. Full native
Muse startup through Herma's generic proxy is not certified. Preserve ordinary
client approvals and sandboxing; inspect actual native tool events.

## 4. Claude Code (`/v1/messages`)

Set `ANTHROPIC_BASE_URL=https://herma.ta-amps.workers.dev` and pass `X-Herma-Key` + `X-Herma-Harness: claude-code` via custom headers. Herma shims matched provisions + noun/verb context into the top-level `system` prompt or returns a direct Anthropic `message` object.

## Credential and client requirements

Personal assistants that support tool or MCP connections can use the open preview. Private routing and configuration require `X-Herma-Key` and a matching `X-Herma-Harness` declaration; client names and user-agent strings are not authorization.

See [the experiment matrix](design-and-evidence.md) for the distinction between
HTTP tests, native fixtures and pending full-loop tests, and the
[bilateral troubleshooting guide](agent-troubleshooting.md) for recovery steps.

========================================================================
FILE: docs/setup.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/docs/setup.md
========================================================================

# Setup, Context Database, Backing Stores & Cloudflare Deployment

> Herma: context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

## Local Development

Clone this repository alone. Tessera is installed from the immutable commit
`b1b470475c3ff03db0963bbcf6b271911d79f73e` through a standard PEP 508 Git dependency.
`uv.lock` records the resolution; no local sibling checkout is required.
The installer needs Python 3.12+, Git, uv and network access to the public repository.

```bash
make setup
make check
make demo
uv run herma serve --host 127.0.0.1 --port 7730
```

## Caller-Isolated Atomic Noun, Verb & Detail Database (`/v1/context`)

1. **Populate & Query Caller-Scoped Context Entries (`configure` scope)**:
   - `POST /v1/context` upserts single or batched `ContextEntry` records (`kind`: `"noun"`, `"verb"`, or `"detail"`; `entry_id`, `title`, `summary`, `schema_or_body`, `source_uri`) into `context_entries` partitioned by `caller_scope` (`?expected_version=<n>&check_cas=true` enforces single-statement atomic SQL CAS).
   - `GET /v1/context?kind=noun&prefix=noun:tessera.` returns `system_builtin` + the caller's own entries; non-admin attempts to overwrite `system_builtin` entries return `403 builtin_protected`.
2. **Tessera (`herma.provisions` + Governed Noun/Verb Stores + Verified Blobs)**:
   - Local Python store: `store.publish_to_tessera_store(t_store)` and `store.sync_from_tessera_store(t_store)`.
   - Over HTTP or Cloudflare Service Binding: `POST /v1/sync/tessera` with `{"base_url": "https://tessera.ta-amps.workers.dev", "bearer_token": "..."}`. Content-addressed `tessera://blobs/<sha256>` URIs are verified against `^[0-9a-f]{64}$` and `sha256(bytes)`, and items pass Herma's Layer-1 Governance Lens (`status:quarantined` refused, `visibility_scope` / `allowed_surfaces` / `X-Herma-Cohort` enforced).
3. **Entity Memory, Outcomes & Candidate Insights (`route` scope)**:
   - `GET /v1/memory?project_tag=<tag>` inspects top-of-mind extracted entities (`file_path`, `code_symbol`, `tessera_uri`, `statute_card_id`, `error_signature`).
   - `POST /v1/outcomes` records explicit `accepted` / `retry_error` / `ignored` / `overridden` signals, and `GET /v1/insights` returns telemetry plus reviewable draft `candidate_provisions`.
4. **Remote Handshake Provision & Context Server**:
   - `POST /v1/sync/remote` negotiates version and clamped `max_chars` via `POST /v1/handshake` (passing configurable `surface_header` + `surface_id`) before loading `/v1/provisions` (and optional `context_entries`).

## Deploying on Cloudflare `workers.dev` (24/7 Cloud-Persistent Mode)

`deploy/cloudflare/wrangler.jsonc` runs natively in Cloudflare's cloud (`STORAGE_MODE = "cloud"`) backed by the `ta-amps-herma` D1 database (`HERMA_DB`, auto-migrating composite `caller_scope` primary keys) and a direct `TESSERA` Service Binding (`deploy/cloudflare/d1-herma.sql`), or proxies to an external `ORIGIN` when `STORAGE_MODE = "origin"`:

```bash
npx --yes wrangler@4.149.0 d1 execute ta-amps-herma --remote --file deploy/cloudflare/d1-herma.sql --config deploy/cloudflare/wrangler.jsonc -y
npx --yes wrangler@4.149.0 deploy --config deploy/cloudflare/wrangler.jsonc
npx --yes wrangler@4.149.0 secret put BOOTSTRAP_SECRET --config deploy/cloudflare/wrangler.jsonc < /path/to/bootstrap.secret
```

========================================================================
FILE: examples/provisions/README.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/examples/provisions/README.md
========================================================================

# Example Provisions & Atomic Noun/Verb Context

Each `examples/provisions/*.json` file conforms to `herma.schemas.Provision` (`extra="forbid"`) and carries verified `metadata_tags.fabric_governance` for Layer-1 lens parity across local and cloud-synced callers, while `examples/provisions/context/*.json` holds atomic `herma.schemas.ContextEntry` records (`noun`, `verb`, `detail`) seeded into Herma's `system_builtin` context database:

- `PROV-DIRECT-NOUN-VERB-SCHEMA.json` -- `action: "respond_directly"` rule that answers natural-language **Tasks (`verbs` on the wire) and Task Objects (`nouns` on the wire)** and canonical noun/verb schema lookups directly in the caller's protocol (`/v1/chat/completions`, `/v1/responses`, `/v1/messages`, `/v1/dry-run`, `/api/preview`) with zero upstream LLM tokens, attaching `noun:tessera.lease_fence` and `verb:tessera.claim` from the context database.
- `PROV-TESSERA-FENCING.json` -- Tier-1 keyword/path/tool + Tier-2 semantic trigger (`action: "shim_context"`) that shims monotonic lease fencing rules, authoritative URIs, and `context_refs` (`noun:tessera.lease_fence`, `verb:tessera.claim`).
- `PROV-RISK-REVIEW-NON-ACCUSATORY.json` -- Tier-1 keyword/path + Tier-2 semantic trigger enforcing non-accusatory risk indicators and `SYNTHETIC` bundle checks.
- `PROV-HARNESS-FEEDS-GUIDE.json` -- Tier-1 keyword/path + Tier-2 semantic trigger shimming structured context on **Agent Harness Research Feeds** (encapsulating `Feed` Task Objects, `HarnessTax` token overhead, and receipt-backed benchmarks across **Harness Square / Harness2**, **OpenCode**, **Pi**, and **Muse Code**).
- `PROV-LORA-MEMORY-ROUTING.json` -- Tier-1 keyword/path + Tier-2 semantic trigger shimming the decision rule for **Prompt Shimming vs LoRAs as Parametric Memory vs Frontier Passthrough** (`Llama 3.2 1B/3B`, `Muse Glimmer 30B QLoRA`, `Muse Spark 1.3`, `Muse Wonder 1.0`).
- `PROV-NGO-HUMAN-BOUNDARY.json` -- Tier-3 micromodel classifier trigger enforcing `human_only` crisis boundaries and `drafter != reviewer`.
- `PROV-EDGE-ORIGIN-LOCKDOWN.json` -- Tier-1 keyword/path trigger enforcing `x-edge-auth` (`EDGE_SECRET`), cookie stripping, HSTS, and CSP on Cloudflare Workers.
- `context/CONTEXT-TESSERA-NOUNS-VERBS.json` -- Builtin atomic `noun`, `verb`, and `detail` entries (`noun:tessera.lease_fence`, `verb:tessera.claim`, `detail:herma.shim_budget`, `noun:harness.feed`, `detail:herma.lora_vs_shim`) queryable via `GET /v1/context` and protected under `caller_scope = "system_builtin"`.

========================================================================
FILE: docs/handoff.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/docs/handoff.md
========================================================================

# Handoff & Status

## Integration checkpoint, October 29, 2026

The reviewed release is merged into `main`. The tested implementation revision is
`e1b87f881a1e1a2427f06a5afb229603e7dee6eb`; [its GitHub checks](https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/actions/runs/40873481450) passed.
Fresh builds matched the deployed Worker executable exactly.

85 Python tests and 49 actual Worker checks passed, including strict decision types and offline no-egress controls.

The installed dependency now pins merged Tessera. Context injection is optional and does not grant authority. Explicit typed conversations and configured model-assisted routing retain caller scope, provider policy and budget controls; they do not become a mandatory model review stage.

Follow the [worker-first policy](WORKER-FIRST-EXECUTION.md): independently
schedulable reasoning is a claimed verb; inputs, contracts, artifacts and evidence
are scoped nouns. Workers reason and self-check. Authentication, leases, CAS,
types and receipts stay deterministic. Server inference is an explicitly
configured, scoped and bounded exception. Missing capacity or invalid input does
not enable it automatically.

The earlier inventory below is dated history. These checks cover the recorded
implementations and fixtures; they are not universal harness, load or rendered-UI
certification.

## Earlier handoff

> Herma: context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

- **Built & Verified (`v0.1.0`)**:
  - Strict Pydantic v2 schemas (`Provision` with `action: "shim_context" | "respond_directly"` and `context_refs`, versioned `ContextEntry` for `noun`/`verb`/`detail` records, `WorkingEntity`, `RuleOutcomeRecord`, `InsightsResponse`, `DryRunResponse`, `InjectionReceipt`).
  - Multi-caller isolation & privilege lockdown: `caller_scope = key:<key_id>` composite primary keys across `provisions`, `context_entries`, `injection_receipts`, `working_entities`, and `rule_outcomes`; `403 builtin_protected` on `system_builtin` IDs; `403 admin_required` on `/v1/admin/keys`; single-statement atomic SQL CAS (`409 version_conflict`); refusal of any model ID containing `contributor`.
  - Layer-1 Governance Lens & SHA-256 blob verification on Tessera and remote sync (`status:quarantined` blocked, cross-surface `status:verified` required, `visibility_scope` / `allowed_surfaces` / `X-Herma-Cohort` enforced).
  - Deterministic Anti-RAG entity memory (`GET /v1/memory`), automatic Turn `N` `error_signature` -> Turn `N-1` `retry_error` outcome telemetry (`POST /v1/outcomes`), and reviewable draft `candidate_provisions` synthesis (`GET /v1/insights`).
  - Responsive SVG-branded `/` and `/connect` pages with read-only interactive `POST /api/preview` (`persisted: false`), stateless JSON-RPC 2.0 `POST /mcp`, `/.well-known/agent-card.json`, `/llms.txt`, `/llms-full.txt`, `/robots.txt`, `/favicon.svg`, and `/healthz` across both Python FastAPI and Cloudflare Worker + D1.
- **Next Extensions**:
  - Per-repository rule-pack signature verification (Ed25519) on remote handshake bundles.
  - Streaming token-usage accounting attached to `InjectionReceipt`.

========================================================================
FILE: AGENTS.md
URL: https://github.com/ta-amps/herma-infrastructure-shim-for-intelligent-agents/blob/main/AGENTS.md
========================================================================

# AGENTS.md -- Herma Hard Rules

## Worker execution direction

Follow the [worker-first execution policy](docs/WORKER-FIRST-EXECUTION.md) when designing agentic work. Prefer claimed verbs and authorized workers, including private workers. Keep ordinary coordination deterministic; additional review is a verb when required. Distinguish required procedures from useful pointers and open-ended discovery. Tool preparation and separate-process execution follow the task workspace and execution contract. The policy does not widen effect, spending or publication authority.

Nouns and verbs are the domain primitives, supported by limited infrastructure and surfaces. Projects are human groupings or surface metadata, not a third primitive. Seed packs contain nouns and verbs. Server management work retains scoped noun/verb contracts; its location grants no general reasoning exception.

> Herma: context-shimming AI middleware for configurable coding harnesses -- intercepts requests via keyword, semantic, or micromodel rules to respond directly or shim atomic noun, verb, and URI context from a user-configured database before LLM execution.

1. **Configurable Harnesses & Caller Isolation Only**: Never weaken `herma/harness_gate.py` or `caller_scope` isolation. Provision and context-database management (`configure` scope), request interception (`route` scope), and working-entity memory require scoped `hmk_` credentials, isolate state per `caller_scope = key:<key_id>`, protect `system_builtin` entries (`403 builtin_protected`), require admin secrets on `/v1/admin/keys` (`403 admin_required`), and accept personal assistants with the same scoped credentials while rejecting browser navigation and cookie auth.
2. **Standard Mode Only**: Refuse every model ID containing `contributor` (including `contributor` and `*-contributor`) in outbound proxy payloads, micromodel classifier configs, provider plans, operator grants and managed conversation configuration, with one classifier in both runtimes (`ContributorTierRefusedError`).
3. **Domain-Neutral Core & HTTP Discipline**: Keep `herma/` domain-neutral. Specific project provisions and atomic `noun`/`verb`/`detail` context entries belong in `examples/provisions/`, SQLite/D1 `context_entries` (`POST /v1/context`), Tessera stores (`herma.provisions`), or remote handshake stores. Writes stay strictly `POST`/`PUT`/`DELETE` (`GET` on write-only endpoints returns `405`).
4. **Public Repo Hygiene**: Run `make check` (`ruff`, `mypy --strict`, `pytest`, `check_public.py`, `build_index.py --check`, `check_architecture.py`) before every commit. Never include secrets, tokens, em-dashes, or private names.
5. **Git Identity**: Commit as `ta-amps <348409696+ta-amps@users.noreply.github.com>` with zero `Co-Authored-By` trailers.
