# ADR-0006 — Fabric Core Intelligence: a governed specialist layer over existing seams

- **Status:** Accepted and promoted to default-on governed advisory integration
  (architecture review 2026-07-29; promotion 2026-07-30). Principles accepted;
  **Phase 0 completed, including the 38-case hand-labeled historical corpus; Phase 1 single-slice
  implementation and repeated qualification are complete. The Failure Investigator is qualified for
  governed runtime assistance. Phase 2 is implemented with three proposal-only specialists and three
  deterministic Micro-Agent guards. Context Researcher, Recovery Strategist, and Outcome Verifier
  are qualified.
  Recovery Strategist cleared its latency gate using a Qwen 9B route plus a deterministic safety
  envelope for approval/evidence/provenance. Phase 3 Agent Architect is qualified and connected to
  Studio creation, refresh, and architecture-upgrade flows by default. Agent Builder's deterministic
  typed-proposal lane and binding guard are qualified on a frozen 12-case corpus and require the
  resolved Architect result. The Certification Agent
  deterministic review lane and evidence guard are qualified on a separate frozen 12-case corpus
  and connected to governed certification review. Core assistance is also default-on for node
  assistance, eligible Forge-agent runtime advice, and retained Weave events.**
  Revisions **R1–R8** below are
  binding on the implementation and are incorporated into this document. The promoted layer remains
  **advisory, read-only, bounded, fail-closed, and reversible**: deterministic workflows, parent
  agents, approvals, publication controls, and completion checks retain authority. The persistent
  Settings kill switch and the `FABRIC_CORE` process override disable Core/Micro routing and cancel
  active Core requests. Weave's retained-event specialist coordinator now executes exclusively
  behind the Fabric Gateway, including the compatibility route used when promoted Core routing is
  disabled. A complete Fabric-operated
  Photoshop → visual approval → Unity validation → handoff → publication run with retained evidence
  remains a production-readiness gate.
- **Date:** 2026-07-29
- **Deciders:** Forge/Fabric architecture (TD + Principal Systems Architect + Lead AI Eng + Lead PD)
- **Implementer:** codex (this ADR is written to be implemented against directly)
- **Related:** ADR-0001 (RAG deployment/retrieval boundary), ADR-0003 (Code Intelligence evidence),
  ADR-0004 (evidence-based review protocol), ADR-0005 (memory architecture), the agent-provenance
  change in `agents_store.py` (`_forge_header.origin`).
- **Scope:** A shared internal specialist-intelligence layer for Fabric — Gateway, Core
  Orchestrator, Core/Micro agent contracts, certified assistance policy, authority model, model
  routing, runtime + Weave + Studio integration, evaluation, flags, rollback.
- **Compatibility posture:** Additive, default-on, kill-switch controlled, and fail-closed. Every
  existing deterministic path — `run_typed_agent`, `fabric_harness.certify`, approvals, receipts,
  recovery, workspace/run isolation — remains authoritative. Core/Micro results never grant
  mutation, approval, publication, or completion authority; disabling Core returns callers to their
  deterministic paths.
- **Phase 0 evidence:** `docs/benchmarks/fabric-core-phase0-baseline-2026-07-29.md` and frozen dataset
  `docs/benchmarks/fabric-core-phase0-failure-investigation-v1.json`; historical comparison evidence
  is `docs/benchmarks/fabric-core-phase0-historical-baseline-2026-07-29.md` with frozen corpus
  `docs/benchmarks/fabric-core-phase0-historical-failures-v1.json`. Phase 1 candidate results are
  `docs/benchmarks/fabric-core-phase1-qwen9b-benchmark-2026-07-29.md` and
  `docs/benchmarks/fabric-core-phase1-qwen27b-benchmark-2026-07-29.md`. Final repeated evidence is
  summarized in `docs/benchmarks/fabric-core-phase1-qualification-2026-07-29.md`.
  Phase 2 pilot contracts are documented in
  `docs/architecture/fabric-core-phase2-pilot.md`; qualification evidence is summarized in
  `docs/benchmarks/fabric-core-phase2-qualification-2026-07-29.md`.

---

## Context

The originating spec ("Fabric Core Agents") proposes a governed internal intelligence platform:
Forge Agents own user goals; **Fabric Core Agents** provide shared specialist cognition (research,
planning, review, diagnosis, recovery, verification); **Micro-Agents** perform narrow bounded tasks;
a **Core Orchestrator** coordinates them; a **Fabric Intelligence Gateway** is the only access
boundary; the **Control Plane** keeps authority, execution and receipts. Core/Micro agents return
**typed proposals only** — never production writes. The governance model is correct and is adopted
here without weakening.

**The decisive finding from repository inspection: most of the proposed "Control Plane" already
exists.** Building the spec's Phase 1 ("Foundations") verbatim would re-implement shipped systems
and violate the spec's own anti-duplication rule. Verified present:

| Spec component | Already implemented |
|---|---|
| Model Router | `dashboard/fabric_ai.py` (`resolve_capability`, `CAPABILITY_MODELS`, `enabled()`) |
| Capability Registry | `dashboard/capability_registry.py` |
| Durable Workflow Engine + idempotency | `dashboard/weave_workflows.py` (`execute_once`, `claim_operation`, `idempotency_key`, `transition`) |
| Orchestration / plan tree | `dashboard/weave_execution_plans.py` (parent/child, `complete_child`) |
| Evidence & Receipt Ledger | `dashboard/weave_receipts.py` + `dashboard/control_store.py` |
| Deterministic Validators / typed contracts | `dashboard/run_contracts.py` (`resolve`, `validate`) |
| Certification | `dashboard/fabric_harness.py` (`certify`) |
| Policy & Approval / authority | `dashboard/decision_engine.py` (`action_class`: read/run/deploy/admin/deny, default-deny) |
| Evaluation harness | `dashboard/agent_evaluations.py` |
| Typed agent-to-agent / subagents | `dashboard/callable_agents.py`, agent `dynamic_subagents` / `subagent_policy` |
| Persistent def / ephemeral run + provenance | `dashboard/agents_store.py` (+ `_forge_header.origin` enum) |
| Specialist catalog (the "Core/Micro agents") | 18 `weave-*` skills + `engineering-*` skills (`.claude/skills/`) |

Two structural facts follow:

1. **The specialist catalog largely exists as skills.** `weave-reasoning`, `weave-planning-impact`,
   `weave-answer-critic`, `weave-ticket-investigator`, `weave-connector-diagnostician`,
   `weave-knowledge-research`, `weave-scope-guard`, plus `engineering-debugging`,
   `engineering-root-cause-regression`, `engineering-runtime-validation`,
   `engineering-test-generation` map almost 1:1 onto the proposed Core/Micro agents.
2. **Weave is already a specialist orchestrator** — but only for the *chat* surface
   (`weave_intelligence.py`, `weave_helper.py`, `weave_execution_plans.py`). Forge Agents, Studio and
   Certification cannot call that intelligence today.

The gap is therefore **not** "build 13 Core Agents + ~40 Micro-Agents + a control plane." The gap is:

> A **typed, governed access boundary** (the Gateway) and a **thin Core Orchestrator** that expose
> the specialist system Weave already has to Forge Agents, Studio and Certification — reusing the
> router, workflow engine, ledger, contracts, certification and authority modules above rather than
> cloning them.

---

## Decision

**D1 — Reframe: Gateway over existing specialists, not a parallel stack.** Fabric Core Intelligence
is a new *boundary and orchestration* layer that wraps existing capability. New code is limited to:
`fabric_gateway.py` (typed request/identity/budget boundary), `fabric_core_orchestrator.py` (thin
scheduler + reconciler), a `fabric_core_registry.py` (persistent Core Agent definitions), and typed
contracts. Everything else is reuse. Any proposal to re-implement a module from the table above must
carry an explicit justification in its PR description or is rejected in review.

**D2 — Advisory-only authority is absolute.** Core Agents and Micro-Agents return **typed proposals
with evidence/provenance/assumptions/conflicts/unresolved**. They never write production state, never
change workflow state, never authorize capabilities, never approve. Only Control-Plane services
(`decision_engine`, `weave_workflows`, `run_typed_agent`, `fabric_harness`, `weave_receipts`) commit
side effects. This is enforced structurally: Core/Micro agents run with `write_access=false` and have
no handle to the executor or approval APIs.

**D3 — The Gateway is the only door, and it is thin (R3).** No subsystem calls a Core Agent or a
skill-as-specialist directly. All callers issue a **typed `GatewayRequest`** and receive a **typed
`GatewayResponse`**. The Gateway does exactly five things — validate caller identity/role, validate
the caller's *certified* assistance policy, validate scope and evidence bounds, enforce budgets, then
**delegate** orchestration, **validate** the returned schema, and **audit**. It performs no reasoning
and owns no retrieval, scheduling, caching, rate-limiting, authority, or receipt logic; each of those
is **reused** from an existing module (authority `decision_engine`; idempotency/dedup
`weave_workflows`; scheduling `weave_execution_plans`; retrieval `workspace_context`/`fabric_rag`;
receipts `weave_receipts`; rate-limit the existing middleware). Direct integrations are prohibited.

**D4 — Reuse authority, but keep Core definitions in their own registry (R1).** The user-facing
prohibition on invoking Core Agents is enforced through the existing `decision_engine.action_class`
(default-deny) plus the Gateway policy check (a user role can never select a Core Specialist). **For
Phase 1, `fabric_core_registry.py` is the authoritative store of Core Specialist definitions — not
`agents_store`.** Core definitions are deliberately kept out of `agents_store` until we prove their
lifecycle, editing, execution, visibility and certification semantics genuinely align with Forge
Agents. That convergence — and any use of an `origin=fabric_core` marker *inside* `agents_store` — is
explicitly deferred and gated on that proof (see Open Questions). `fabric_core` remains a reserved
governance label and a Gateway-level visibility filter, not a Phase-1 storage location.

**D5 — No recursion, bounded fan-out.** Micro-Agents cannot spawn Micro-Agents. Core Agents cannot
call the Gateway. Every invocation carries explicit time/token/latency/model/fan-out/round budgets,
enforced by the Gateway *before* dispatch. Exceeding budget fails closed with a typed partial result.

**D6 — Deterministic-sufficiency first, with a typed verdict (R2).** Before any model call the
Orchestrator runs a deterministic check that returns a typed `DeterministicSufficiency.v1` —
`resolved | specialist_required | blocked`, carrying a reason code, evidence, and (when a specialist
is required) the required task class. `resolved` short-circuits with no specialist; `blocked` fails
closed with its reason; only `specialist_required` dispatches. Specialists are used only for
genuinely uncertain cognition.

**D7 — Confidence is computed, not self-reported.** Per principle #11, model self-reported confidence
is never a gate. Reconciliation and escalation use measurable signals only (schema adherence,
evidence quality/freshness/provenance, retrieval agreement, deterministic-validation outcome,
historical route accuracy from `fabric_learn`/`agent_evaluations`). See Reconciliation cold-start.

**D8 — Ollama-enable stays separate from Agentic-enable.** `fabric_ai.enabled()` (models available)
is distinct from a new `fabric_core.enabled()` (specialist layer active). Enabling local models must
not enable agentic assistance, and vice-versa.

**D9 — Invert the spec's phasing.** Do **not** build the full framework first. Ship **one governed
vertical slice on one pilot agent**, measured against baseline, and grow the Gateway/Orchestrator
from what that slice actually requires. Framework-from-a-working-slice.

**D10 — Baseline before targets.** The spec's acceptance numbers (30% fewer corrections, etc.) are
**hypotheses, not gates**, until the current baseline is measured with `agent_evaluations`. The first
deliverable of the pilot is the measured baseline. "Goal-completion classification" accuracy requires
a hand-labeled benchmark set — model-as-judge self-report is not evidence.

**D11 — Name Phase 1 honestly: a bounded Core Specialist, not an autonomous agent (R4).** The Phase 1
deliverable is a *registered bounded Core Specialist* that performs single-shot advisory analysis
under a fixed policy. It does **not** independently observe its environment, choose among strategies,
or replan, and this ADR does not describe it as full agent autonomy. "Core Agent" denotes the governed
role and its typed contract; autonomy (observe → decide → replan under policy) is claimed only when a
specialist demonstrably does so **and is measured doing it** — not before.

---

## Terminology → module map (authoritative)

| Spec term | Concrete realization |
|---|---|
| Forge Agent | Existing user agent JSON in `agents_store` (`origin` ∈ {human, fabric, seed, …}) |
| Fabric Core Agent (Phase 1: **bounded Core Specialist**) | Persistent definition in `fabric_core_registry.py` — **authoritative, not `agents_store`** (R1); dispatches an existing specialist skill via `fabric_ai`. Phase 1 is single-shot advisory, not autonomous (D11) |
| Fabric Micro-Agent | A bounded typed sub-task inside a Core Agent; realized as a scoped skill/prompt call; no delegation, no writes |
| Core Orchestrator | New `fabric_core_orchestrator.py`; reuses `weave_execution_plans` for scheduling, `fabric_ai` for routing |
| Intelligence Gateway | New `fabric_gateway.py`; typed boundary + budget + identity + `decision_engine` authority check |
| Control Plane | Existing: `decision_engine`, `weave_workflows`, `run_typed_agent`, `fabric_harness`, `weave_receipts`, `control_store`, `run_contracts` |

---

## Target architecture (reconciled to real modules)

```
Caller (Forge Agent runtime / Weave / Studio / Certification / Recovery / RAG / …)
  │  typed GatewayRequest
  ▼
fabric_gateway.py   ── identity · workspace/run/branch scope · allowed roles/task-classes ·
  │                     data classification · budgets · rate-limit · dedup · timeout · audit
  │                     authority: decision_engine.action_class (default-deny; users blocked)
  ▼
fabric_core_orchestrator.py
  ├─ deterministic-sufficiency check (run_contracts / validators)  ── may return with NO model call
  ├─ smallest Core-Agent team selection (from fabric_core_registry)
  ├─ context isolation (workspace_context, bounded evidence_refs)
  ├─ scheduling (reuse weave_execution_plans; sequential-default, opt-in parallel)
  ├─ Micro-Agent fan-out control (bounded, non-recursive)
  ├─ reconciliation (evidence + schema + policy; history when available)
  └─ ONE typed consolidated GatewayResponse
  ▼
Fabric Core Agents (origin=fabric_core)  → dispatch existing weave-*/engineering-* specialists
  ▼  via fabric_ai.resolve_capability(profile)   (model router — reused)
Bounded Micro-Agents  → typed advisory result (evidence + provenance), write_access=false
  ▲
  └── result returned to caller as a PROPOSAL
      Side effects (if any) go through the caller's OWN existing governed path:
        decision_engine → run_contracts → plan compile → approval revalidation →
        run_typed_agent / weave_workflows.execute_once → weave_receipts ledger
```

The user always sees **one coherent Forge Agent / Weave answer**. Core/Micro activity is hidden by
default; an advanced trace (authorized roles) exposes specialists used, routes, evidence,
disagreements, reconciliation, latency, tokens, trace_id, and a `no_direct_writes: true` attestation.

---

## Contracts

All contracts are additive typed schemas validated at every boundary. Free-form model output must
never cross an orchestration boundary without schema validation (fail closed on invalid).

### `GatewayRequest.v1`
```json
{
  "caller": {"system": "forge_agent|weave|forge_studio|certification|runtime_recovery|rag|connector_mgmt",
             "component": "", "agent_id": "", "agent_version": "", "role": "operator",
             "workspace_id": "", "run_id": "", "branch_id": ""},
  "task": {"type": "context_resolution|capability_matching|plan_generation|failure_analysis|recovery_planning|outcome_verification|agent_architecture|agent_build|certification_review",
           "goal": "", "constraints": [], "required_output_schema": "FailureAssessment.v1"},
  "context_manifest": {"evidence_refs": [], "allowed_sources": []},
  "policy": {"allowed_core_agents": [], "allowed_task_classes": [],
             "write_access": false, "hosted_models_allowed": false},
  "budget": {"max_core_agents": 3, "max_micro_agents": 6, "max_reasoning_rounds": 2,
             "token_budget": 0, "latency_ms_budget": 0, "timeout_ms": 0}
}
```
Rejected at the Gateway: wildcard `allowed_core_agents:["*"]`; `write_access:true`; caller role that
`decision_engine` classifies as unauthorized; budget above the caller's certified ceiling; evidence
outside `allowed_sources`; cross-workspace `evidence_refs`.

### `GatewayResponse.v1`
```json
{"status": "completed|partial|refused|failed", "recommendation": {}, "evidence": [],
 "assumptions": [], "conflicts": [], "unresolved_items": [], "confidence_inputs": {},
 "specialists_used": [], "no_direct_writes": true, "trace_id": "", "metrics": {}}
```

### `DeterministicSufficiency.v1`  (R2)
```json
{"verdict": "resolved|specialist_required|blocked",
 "reason_code": "", "evidence": [],
 "required_task_class": "failure_analysis|context_resolution|…|null",
 "resolved_result": {}}
```
Emitted by the Orchestrator before any model call. `resolved` returns `resolved_result` directly with
no specialist; `blocked` fails closed with `reason_code`; only `specialist_required` dispatches.

### `ContextPolicyDigest.v1`  (R7)
```json
{"digest": "<sha256>", "signed_by": "fabric_core",
 "components": {"workspace_id": "", "branch_id": "", "capability_versions": {},
   "source_freshness": {}, "model_provider_policy": "", "assistance_policy_version": "",
   "task_type": "", "evidence_refs": []}}
```
This signed digest **is** the cache identity for any specialist result — never a loose tuple. Two
requests share a cached result only if their digest is identical; any drift (a new capability version,
a fresher source hash, a changed model or assistance policy, a different branch) yields a new digest
and forces recomputation. Model self-reported confidence is never a component.

### `FailureAssessment.v1`  (Phase 1 specialist output — advisory only)
```json
{"failure_class": "", "root_cause_hypotheses": [{"cause": "", "evidence_refs": [], "confidence_inputs": {}}],
 "impacted_symbols": [], "evidence": [], "assumptions": [], "unresolved_questions": [],
 "recommended_task_class_next": "recovery_planning|null", "provenance": []}
```
`recommended_task_class_next` is a suggestion the caller may ignore; **Phase 1 never acts on it.**

### `CoreAgentResult.v1`
```json
{"core_agent_id": "fabric.failure_investigator", "version": "1.0.0",
 "status": "completed|partial|failed", "recommendation": {}, "evidence": [], "assumptions": [],
 "constraints": [], "risk_flags": [], "unresolved_conflicts": [], "unresolved_questions": [],
 "confidence_inputs": {}, "provenance": [],
 "metrics": {"latency_ms": 0, "token_usage": 0, "model_route": ""}}
```

### `CoreAgentDefinition` (registry, persistent — `origin=fabric_core`)
Fields: `id, display_name, version, owner, purpose, supported_task_classes, input_schema,
output_schema, allowed_evidence_sources, allowed_capabilities, write_policy(=none),
model_routing_policy, timeout_ms, token_budget, latency_ms_budget, max_micro_fanout, retry_policy,
failure_policy, evaluation_suite, quality_history_ref, rollout_state, deprecation_state`.

### `MicroAgentContract`
One narrow task; fixed typed I/O; `write_access=false`, no approval/delegation authority; bounded
context; returns evidence+provenance; fail-closed on invalid output; independently testable;
replaceable without changing the parent Core Agent contract. **Parent Core Agent owns synthesis.**

### Certified Forge-Agent assistance policy (additive agent field)
```json
{"core_agent_assistance": {
  "enabled": false, "allowed_core_agents": [], "allowed_task_classes": [],
  "invocation_mode": "explicit|conditional|orchestrator_selected",
  "max_core_agents_per_request": 3, "max_micro_agents_per_request": 6, "max_reasoning_rounds": 2,
  "write_access": false, "hosted_models_allowed": false, "approval_required_for_escalation": true}}
```
`fabric_harness.certify` gains a check that **rejects** wildcard/unbounded policies, self-granted
scope, budget above ceiling, or `write_access:true`. A running Forge Agent cannot mutate its own
policy, widen context, or raise its own budget — the Gateway reads the *certified* policy from the
signed agent, not from runtime request fields.

---

## Governance & authority model

- **Only the Gateway** authorizes specialist access; it calls `decision_engine.action_class` and a
  new role check. Normal user roles are denied Core-Agent invocation (fail-closed).
- **Advisory → execution transition** (unchanged, reused): any proposal that would cause a side
  effect flows `proposal → schema validation → plan compile → capability validation → policy/effect
  validation → current-state validation → approval revalidation → plan-ledger update → governed
  execution`. **Materially changed plans/args invalidate prior approvals** (existing behavior in
  `update_agent_governed`; extend the check to plan revisions from Core Agents).
- **Isolation:** workspace/run/branch scope carried in every request; `evidence_refs` bounded to
  `allowed_sources`; no cross-workspace or cross-user reads (reuse `workspaces.current_id` +
  control-plane RLS). Zero cross-workspace leakage is a hard acceptance gate.
- **Provenance:** every recommendation carries evidence + provenance + `trace_id`; receipts written
  through `weave_receipts`. No Core/Micro agent appears as a user-created Forge Agent.

### Reconciliation (with cold-start honesty)
Reconciliation is **not** majority voting. Day-1 weighting = schema adherence + evidence
quality/freshness/provenance + policy compliance + deterministic-validation outcome. "Historical
accuracy" and "specialist relevance" weights start at neutral and **accrue over time** from
`agent_evaluations` / `fabric_learn`; the design must state that history-based weighting is disabled
until enough labeled outcomes exist, and never blocks on data it doesn't have.

---

## Model routing & escalation (reuse `fabric_ai`)

Expose named profiles routed by `fabric_ai.resolve_capability`: `no_model` (deterministic),
`fast_extract`, `retrieval_rank`, `balanced_reason`, `deep_plan`, `code_reason`, `vision`,
`security_critique`. Routing considers task type, risk, context size, latency, cost, availability,
historical accuracy, prior failure rate, schema-adherence rate. **Escalation triggers are measurable
only:** schema failure, missing required fields, conflicting evidence, low retrieval agreement,
repeated user correction, failed deterministic validation, unknown capability semantics, failed
postconditions, historical route underperformance. Never escalate on model self-confidence.

**Local-first latency reality (must be honored):** local Ollama reasoning is slow and, per this
session's telemetry, variable. Therefore the default is **sequential, single Core Agent, one round,
no fan-out**, with aggressive caching keyed on a signed **`ContextPolicyDigest.v1`** (workspace ·
branch · capability versions · source freshness · model policy · assistance-policy version · task ·
evidence — R7), never on a loose tuple. Parallel fan-out is opt-in and only where the ≤2× latency
budget can be met. The design must publish a latency
budget table per profile and treat ≤2× as a measured gate, not an assumption.

---

## The first slice (implement this only — single failure-investigation vertical)

**Scope: ONE task class — Failure Investigation.** The slice ships a single registered *bounded Core
Specialist*, `fabric.failure_investigator`, that produces a typed `FailureAssessment.v1` advisory from
existing failure evidence. It does **not** plan recovery, execute recovery, or verify outcomes — those
are later, evidence-gated phases. One specialist per event, one round, no fan-out, no replanning (D11).

New files (≈3 modules + tests):
1. `dashboard/fabric_gateway.py` — **thin** (R3): `request(gateway_request) -> GatewayResponse` does
   exactly — validate caller identity + role; validate the caller's *certified* assistance policy;
   validate scope (workspace/run/branch) + evidence bounds; enforce budgets; **delegate** to the
   orchestrator; **validate** the returned schema; write the audit receipt via `weave_receipts`. No
   reasoning; no retrieval/scheduling/caching/rate-limit/authority/receipt logic of its own — all
   reused. Fail-closed on every branch.
2. `dashboard/fabric_core_orchestrator.py` — `handle(task, policy, budget)`: emit a
   `DeterministicSufficiency.v1` verdict (R2); on `resolved`/`blocked` return with **no** model call;
   on `specialist_required` select `fabric.failure_investigator` from the registry → run via
   `fabric_ai` → schema-validate the `FailureAssessment.v1` → wrap as `GatewayResponse`. No writes.
3. `dashboard/fabric_core_registry.py` — **authoritative** (R1) definition for the one specialist;
   `fabric_core` hidden from the default agent list; user-role invocation blocked at the Gateway.

Integration point (single, reversible, advisory-only): in `run_typed_agent`, on a stage failure,
**behind `fabric_core.enabled()` AND the agent's certified `core_agent_assistance.enabled`**, call the
Gateway for a `FailureAssessment` and attach it to the failure record for the operator / advanced
trace. **Phase 1 does not auto-recover** — the assessment is advisory context only. Flag off →
byte-for-byte current behavior (hard-fail as today), with no Gateway call.

**Cancellation & flag terminal semantics (R5):** a cancelled or timed-out in-flight request returns
`status:"cancelled"`/`"failed"` with **no side effects** (specialists never write, so nothing needs
unwinding); the caller's pending state resolves down the existing deterministic path exactly as if the
Gateway were disabled. Flipping `fabric_core.enabled()` off mid-flight aborts in-flight requests and
discards their proposals — no caller is left blocked waiting on a specialist result.

Tests: gateway rejects wildcard/oversized/unauthorized/out-of-scope requests; orchestrator emits the
typed sufficiency verdict and short-circuits `resolved`/`blocked` with no model call; specialist
returns a schema-valid `FailureAssessment` with evidence/provenance and zero writes; flag-off path is
byte-for-byte unchanged; cancellation and mid-flight flag-off leave no side effects and no blocked
caller; cache identity is a signed `ContextPolicyDigest` (R7).

---

## Phasing (inverted from the spec)

- **Phase 0 — Baseline.** Measure current bug-fix/recovery metrics with `agent_evaluations` on a
  fixed task set. No new runtime code. Output: the numbers all targets are relative to.
- **Phase 1 — Pilot slice (failure investigation ONLY).** The single vertical above: one bounded Core
  Specialist, flagged, measured head-to-head vs Phase 0. **Gate:** meets the Phase 1 acceptance gates
  (see Evaluation) with no safety regression. Recovery Strategist, Outcome Verifier, Studio work and
  Weave migration **do not start** until this slice produces measured evidence.
- **Phase 2 — Complete the pilot triad.** Only after Phase 1 evidence: add Recovery Strategist +
  Outcome Verifier + Context Researcher; conditional invocation triggers; advanced trace UI.
  **Current:** all three specialists are qualified and connected to default-on, bounded runtime
  assistance. Explicit legacy policy can still disable assistance per agent; the global kill switch
  always wins.
- **Phase 3 — Creation intelligence.** Agent Architect + Agent Builder + Certification Agent behind
  the same Gateway, integrated into Studio create-flow and `fabric_harness.certify`.
  **Current:** Architect and Builder are qualified and invoked by default for Studio creation,
  refresh, architecture upgrade, and node assistance; Builder requires Architect's resolved typed
  result. Certification review is enabled by default and cannot change the deterministic Harness
  verdict.
- **Phase 4 — Weave via the Gateway.** Route Weave's specialist use through the Gateway (event-driven
  triggers, not a prompting loop), unifying the two paths.
  **Current:** every retained Weave helper event is sent through a qualified, task-specific Core
  Gateway route by default. The legacy direct `fabric_specialists` coordinator still produces the
  authoritative report, so the one-door architecture is not yet complete. The earlier two
  exact-caller compatibility routes and their historical qualification remain available behind
  independent flags. They route `knowledge_gap` through `evidence-researcher` +
  `knowledge-curator` and `certification_regression` through `policy-critic` +
  `independent-reviewer`; the latter passed three consecutive runs over a frozen 12-case corpus.
  Separately flagged, non-production-only per-route shadow canaries record parity, route,
  authority, signed-digest, and receipt evidence separately. The implemented producers admit only
  explicit evidence requests after an authorized RAG miss/error or a real retained Harness
  `regressed` verdict. Ten distinct flawless observations in one route only make that route's
  evidence reviewable; repeated or cross-route traffic cannot manufacture readiness. No automatic
  promotion is permitted.
  **Additive development pilot:** three separately registered ephemeral bounded workers exercise
  ticket/path reading, selected-node validation, and retained-evidence normalization through strict
  typed dry-run contracts. They perform no Jira fetch, Perforce sync, Unity/file change, model call,
  approval, publication, or parent completion. This does not promote Phase 5 or create new Core
  Agents; details are in `fabric-bounded-work-pilot.md`.
  The follow-on parent seam is also implemented: a deterministic Planner selects workers only from
  explicit typed input sections, the existing Pipeline Orchestrator runs their dry-run contracts in
  bounded parallel, and the registry exposes sanitized development observations. Ten distinct safe
  previews permit human review only; automatic promotion remains disabled.
  Two exact producers now feed genuine observations behind independent flags: ticket-aware
  `/api/extract` preflight and Studio `/api/harness/validate-selected`. Their existing deterministic
  results remain authoritative; shadow refusal, failure, timeout, or mismatch is observational and
  cannot change the caller response.
- **Phase 5 — Platform-wide.** Certification, Runtime recovery, RAG, Connector/skill mgmt, Insights.

No phase proceeds until the prior meets its acceptance gate with tests and measured evidence.
The authoritative implemented/planned role inventory is maintained in
`docs/architecture/fabric-core-agent-catalog.md`.

---

## Evaluation

Compare Core-Agent path vs current on identical tasks via `agent_evaluations`. Metrics: first-pass
Forge Agent validity; missing-requirement rate; wrong-capability rate; unsupported-assumption rate;
human corrections; certification pass rate; dry-run failure rate; runtime recovery success;
goal-verification accuracy; time-to-completion; token usage; model-call count; latency; security
findings; post-certification production failures.

**Targets are hypotheses tested against Phase 0**, not preconditions: ≥30% fewer corrections; ≥40%
fewer missing requirements; ≥25% better first-pass certification; ≥20% better bounded recovery;
≥95% goal-completion classification **on a hand-labeled benchmark**; no increase in unsafe capability
selection; <2× reasoning latency; full traceability; zero cross-workspace leakage; zero direct
Core/Micro writes; zero approval bypasses; zero recursive delegation. The last five are **hard safety
gates** (any failure blocks rollout); the percentages are directional.

**Recovery success is defined by outcome, not retry (R6).** A recovery counts as successful only when
the original failure's postcondition **independently holds** AND downstream integrity checks pass —
never merely because a retried step returned `ok`. Phase 1 ships no recovery, so this definition is
binding on Phase 2 (Recovery Strategist). Phase 1 instead measures **investigation accuracy**: does the
`FailureAssessment` identify the correct root-cause class against a hand-labeled failure benchmark?

**Phase 1 acceptance gates (R8)** — all required before the slice is judged, alongside the standing
safety gates (zero Core/Micro writes · zero approval bypasses · zero cross-workspace leakage · zero
recursive delegation):
- Every request yields a typed `DeterministicSufficiency.v1` verdict before any model call (R2).
- Cancellation and mid-flight flag-off have proven terminal semantics: no side effects, no blocked
  caller, deterministic fallback (R5).
- Cache identity is a signed `ContextPolicyDigest.v1`; any component change forces recomputation (R7).
- Investigation accuracy improves vs the Phase 0 baseline on the labeled failure benchmark, at <2×
  latency, with full per-recommendation traceability.
- The deliverable is documented and demoed as a **bounded Core Specialist, not autonomous** (R4/D11).

---

## Reliability & security requirements

Schema validation at every boundary; strict workspace/run/branch isolation; no cross-tenant leakage;
no Core/Micro production writes; no recursion; no wildcard policy; timeouts; cancellation; rate
limits; invocation + fan-out budgets; idempotency (reuse `weave_workflows`); durable checkpoints
(reuse `dataflow_checkpoints`); failure classification; safe fallback to the deterministic path;
complete audit evidence (`weave_receipts`); feature flags; rollback; backward compatibility;
local-first; fail-closed wherever authority/evidence/correctness is uncertain.

## Feature flags & rollback

- `fabric_core.enabled()` — promoted default-on master switch for the specialist layer (distinct
  from `fabric_ai.enabled()` and Ollama availability). Its persisted Settings value defaults to
  enabled; `FABRIC_CORE` is an environment-level emergency override.
- Settings exposes an admin-only **Emergency stop Core & minions** control. Disabling cancels active
  Core requests and blocks new Core/Micro routing.
- New agents receive a governed `fabric_collaboration` build/runtime policy by default. Legacy
  agents without that envelope receive the same bounded read-only runtime assistance; an explicit
  v1 runtime-disabled policy remains authoritative.
- Legacy per-agent `core_agent_assistance.enabled` remains a compatibility path.
- Per-task-class enablement inside the pilot.
- **Terminal semantics for in-flight work (R5):** a cancel or timeout returns `cancelled`/`failed`
  with no side effects; flipping the master flag off mid-flight aborts in-flight Gateway requests and
  discards their proposals. In every case the caller's pending state is resolvable by the existing
  deterministic path — no caller blocks waiting on a specialist, and nothing needs unwinding because
  specialists never write.
- **Rollback:** flags off → the Gateway is never called; all callers use their existing deterministic
  paths unchanged. Because Core/Micro agents never write, disabling mid-flight cannot corrupt state;
  in-flight proposals are simply dropped. Registry definitions are additive and inert when the flag
  is off.

## Non-goals / explicit do-not

No unrestricted autonomous loops; no recursive delegation; no direct subsystem→Core-Agent calls; no
Core/Micro production writes; no weakening of approvals/receipts/recovery/certification; no replacing
deterministic services with LLMs; no duplicating router/workflow/ledger/registry/certification
without written justification; no exposing internal agents as user Forge Agents; no self-widening
assistance policy; Ollama ≠ Agentic; preserve local-first; keep the first implementation small,
measurable, reversible.

## Open questions

1. **Decided (R1):** Core Specialist definitions live in `fabric_core_registry.py`, authoritative for
   Phase 1. Convergence with `agents_store` (and any `origin=fabric_core` storage) is **deferred**
   until we prove their lifecycle/editing/execution/visibility/certification semantics genuinely align
   with Forge Agents — that proof is the entry criterion for reconsidering, not a Phase-1 task.
2. Advanced-trace surface: new panel vs extend the existing run/receipt view? Prefer extending.
3. Where does `hosted_models_allowed` policy compose with org model-provider policy — Gateway or
   `fabric_ai`? Enforce at Gateway, execute at `fabric_ai`.
4. **Open production gate:** retain evidence from at least one complete Fabric-operated art run
   spanning authoritative Jira input, Perforce acquisition, physical Photoshop execution, human
   visual approval, Unity import/validation, handoff, and governed publication.
5. **Closed convergence gate (2026-07-30):** Weave's six retained event types now execute through
   the Fabric Intelligence Gateway in both promoted and compatibility modes. The helper no longer
   invokes `fabric_specialists.coordinate` directly; exact specialist policy, scope, declared
   fan-out budget, evidence digest, report validation, and receipt creation share one boundary.
   Existing rollout and shadow flags retain their compatibility semantics.

## Consequences

**Positive:** materially better interpretation/planning/recovery/verification with one governed
boundary; ~90% reuse; safety preserved by construction (advisory-only + existing approval path);
reversible and measurable; unifies Weave's specialist intelligence with the rest of the platform.

**Negative / accepted:** a new mandatory hop (Gateway) adds latency — bounded and measured; new
persistent Core Agent definitions to own and version; conceptual overhead of the new vocabulary —
mitigated by the terminology→module map; local-model latency constrains parallelism early.

---

## Deliverables → phase index (spec's 23)

Current-state assessment · Target architecture · this ADR — **done here.** Core/Micro registries,
typed contracts, Gateway, Orchestrator, certified assistance policy, authority model, routing/
escalation — **Phase 1 (pilot-scoped), completed for real in Phases 1–3.** Forge runtime integration
— **Phase 1 (recovery only) → Phase 2/3.** Weave integration — **Phase 4.** Studio UX — **Phase 3.**
Evaluation harness/test strategy/benchmark plan — **Phase 0 + ongoing.** Migration/flags/rollback/
docs — **each phase.** Test results + measured before/after — **gate artifact of every phase.**
