# Host Agent Integration

**Status:** Active  
**Last updated:** 2026-05-20

Single source for integrating Sruja with any AI agent host (Cursor, Claude Code, CI, OpenHands, etc.). Sruja is a **CLI-first autonomous coding agent** that also works as a passive harness from any editor host.

## One blessed loop

This repo is cohesive when every integration (local dev, AI editor, CI, AI-DLC workflows) funnels into the same loop:

```text
START → workflow status --check (if AI-DLC) → focus/ai → host ACT → verify-task → drift-pr/drift → RECORD/LEARN
```

Adoption tiers and rollout guidance: [ENTERPRISE_ADOPTION.md](ENTERPRISE_ADOPTION.md).

---

## Trust model: “earned confidence” (multi-agent, go/no-go)

Sruja’s deterministic layer can make checks deterministic, but it cannot prevent an LLM (in `agent loop` or an editor host) from producing a confident, wrong narrative. For high-stakes usage, implement a **role-separated multi-pass review** (even if it’s the same model invoked multiple times).

### Normative requirement (when enabled)

When `high_stakes=true` (host configuration), the host MUST treat output as shippable only after:

- **Generator pass** (draft) produces changes + explicit claims.
- **Verifier pass** produces a “GO/NO-GO” with evidence links (commands run, files read, test output).
- **Adversary pass** produces a “GO/NO-GO” focused on failure modes, boundary violations, and abuse cases.
- **Go/no-go rule**: any single NO-GO blocks ship and triggers either more evidence collection or human escalation.

This mirrors “second opinion / four eyes” patterns in medicine, finance, and safety-critical operations.

### Recommended host payloads (for CI + tooling)

Hosts should standardize three artifacts per task/PR:

- **`claims.json`**: structured list of critical claims + how they were verified.
- **`verification.json`**: `sruja verify-task -f json` output for the selected profile.
- **`go_no_go.json`**: verdicts from verifier + adversary, including disagreements and required next actions.

At minimum, hosts MUST capture `verification.json` (or a lossless equivalent) and store it in CI logs.

### Human escalation contract

When a NO-GO occurs or agents disagree, the host SHOULD escalate with:

- the minimal failing evidence (command output / failing step IDs)
- the exact claim(s) in dispute
- the smallest next action that would resolve uncertainty (run test X, read file Y, add invariant test Z)

Hosts should avoid “debate transcripts”. The escalation payload must be short and actionable.

---

## Boundary Table

| Layer | Owner | Responsibility |
|-------|-------|----------------|
| **Autonomous loop** | Sruja CLI (`agent loop`) | comprehend → plan → execute → critique → replan, bounded by iterations/spend/file guards |
| **Deterministic grader** | Sruja CLI + MCP | `sync`, `lint`, `drift`, `intent check`, `verify-task`, focus briefings, agent memory, MCP tools |
| **Agent host** (optional) | Your editor / CI / script | Interactive loop using Sruja's passive gates and MCP tools |
| **Reviewed truth** | Humans + promotion flow | `repo.sruja`, Decision Records, approved proposals |

**Sruja ships:**
- `sruja agent loop` — closed-loop autonomous coding agent
- `sruja agent run/plan/apply` — headless/CI convenience helpers
- MCP server for editor-host integration
- Agent memory with retrieval/outcome tracking

See [GROUNDED_HARNESS_AND_CONTINUAL_LEARNING.md](GROUNDED_HARNESS_AND_CONTINUAL_LEARNING.md) and [docs/plans/LOOP_AGENT_PLAN.md](plans/LOOP_AGENT_PLAN.md) for details.

**Copy-paste examples:** [examples/host-gates/](examples/host-gates/) (CI workflow, shell hook, dogfood checklist).

---

## Run Envelope (Normative)

Every task follows the same end-of-task contract, regardless of host or skill:

```
START → drift/focus → ACT (host/skill) → VERIFY (bundle) → RECORD (event) → LEARN (memory)
```

### Step-by-step

#### 1. START — Ground the task

```bash
# Check for architectural drift before starting
sruja drift -r . -f json

# Get a focus briefing for the target file/element
sruja focus --file src/auth.rs -r . -f for-ai
```

**MCP equivalent:** `sruja_get_focus_briefing`, `sruja_check_drift`

#### 2. ACT — Execute the work

**Autonomous mode:** `sruja agent loop` performs the code or DSL changes via
its own tool registry (file_read, file_write, file_edit, glob, grep, shell).

**Host mode:** the editor agent (Cursor, Claude Code) or CI script performs the changes.

#### 3. VERIFY — Run verification bundle

```bash
# Coding task (default)
sruja verify-task --profile coding -r .

# Bugfix targeting a specific file
sruja verify-task --profile bugfix --file src/auth.rs -r .

# Pre-merge review
sruja verify-task --profile review -r .

# Architecture change
sruja verify-task --profile arch -r .

# JSON output for CI/MCP
sruja verify-task --profile coding -r . -f json
```

**Verification bundle format (`verify_task/v1`):**
```json
{
  "schema_version": "verify_task/v1",
  "profile": "coding",
  "repo": ".",
  "all_passed": true,
  "steps": [
    {
      "step_id": "lint_repo_sruja",
      "status": "ok",
      "exit_code": 0,
      "stdout": "...",
      "stderr": "",
      "elapsed_ms": 42
    }
  ],
  "elapsed_ms": 1250
}
```

**Profiles:**

| Profile | Steps |
|---------|-------|
| `coding` | `lint repo.sruja` + `just check` (or `make check` / `sruja drift --ci`) + `drift` |
| `bugfix` | `focus --file` + `just check` (or `make check` / `sruja drift --ci`) + `intent check` |
| `review` | `review -f json` + `intent check` + `drift` |
| `arch` | `lint repo.sruja` + `drift` + `intent check` + `review -f json` |

**MCP equivalent:** `sruja_verify_task`

### Evidence Packs

Evidence packs make Sruja outputs easy to archive as CI artifacts and attach to change records.

When enabled, `verify-task` writes a folder containing:

- `verify-task.json` — `verify_task/v2` output (includes provenance)
- `drift.json` — from the `drift_check` step (when present)
- `intent.json` — from the `intent_check` step (when present)
- `review.json` — from the `review` step (when present)

**How to generate:**

Default location (recommended for local runs):

```bash
sruja verify-task --profile review -r . --evidence-pack -f json
```

Override output directory (recommended for CI):

```bash
sruja verify-task --profile review -r . --evidence-pack-dir "$RUNNER_TEMP/sruja-evidence" -f json
```

Evidence packs also work with the `confidence` command:

```bash
sruja confidence -r . --evidence-pack -f json
```

### Optional: Verifier/Adversary gates

For high-stakes changes, add role-separated multi-pass review on top of Sruja's deterministic grader. `sruja agent loop` already runs an internal critique phase; this is for an additional independent adversarial check.

```text
ACT (generator) → VERIFY (sruja) → VERIFIER PASS (GO/NO-GO) → ADVERSARY PASS (GO/NO-GO) → SHIP/ESCALATE
```

The **verifier/adversary passes MUST be conditioned on the same evidence** the generator used (files read, command outputs). Do not allow a verifier to “vote GO” without checking `verify-task` and the relevant sources of truth.

#### 4. RECORD — Log the event

```bash
# Events are auto-recorded for drift/intent/propose operations
# Manual event recording:
sruja event append -r . --json '{"kind": "task_complete", "details": {...}}'
```

**MCP equivalent:** `sruja_append_event`

#### 5. LEARN — Record learnings (on verify pass or failure)

```bash
# Record a learning from the task
sruja agent record -r . \
  -c "Refactored auth module" \
  -H "Migrate to JWT tokens" \
  -o success \
  -g "Always run verify-task after auth changes"

# Or on failure (correction learning)
sruja agent record -r . \
  -c "Auth refactor" \
  -H "Merge auth into API container" \
  -o failed \
  -g "Auth must remain a separate container per architecture"
```

**MCP equivalent:** `sruja_record_learning`

---

## MCP vs CLI Usage Patterns

### CLI (scripts, CI, shell hooks)

```bash
# Pre-commit hook
sruja verify-task --profile coding -r . || exit 1

# CI gate
sruja drift -r . -f json | jq '.violations | length' | grep -q '^0$'

# Post-merge sync
sruja sync -r .
```

### MCP (AI editors, interactive sessions)

```
# Cursor/Claude/Copilot with Sruja MCP server
# Command: sruja mcp -r .

Tools available vary by profile:
- minimal (10 tools): Core ladder + focus briefing + essential utilities
- coding (15 tools, default): Minimal + hybrid query + critique + context pruning
- arch: Coding + read-only authoring helpers
- full: All tools (backward compatible)

Examples:
- sruja_get_focus_briefing — task-scoped briefing
- sruja_verify_task — run verification profile
- sruja_check_drift — detect architectural drift
- sruja_search_memory — search past learnings
- sruja_record_learning — record new learning
- sruja_get_topology — upstream/downstream dependencies
- ... (full list via MCP initialize)

Profile control:
- Set via environment: SRUJA_MCP_TOOL_PROFILE=coding
- Set via MCP initializationOptions
- Defaults to coding profile
```

### Read-only mode

Set `SRUJA_MCP_READONLY=1` to expose only read/query tools. Mutating calls (record_learning, propose, etc.) return an error.

```bash
SRUJA_MCP_READONLY=1 sruja mcp -r .
```

---

## Bot Approval Patterns

### GitHub Actions

```yaml
# .github/workflows/sruja-verify.yml
name: Sruja Verify
on: [pull_request]
jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: cargo install sruja-cli --locked
      - name: Verify task
        run: sruja verify-task --profile coding -r . -f json
      - name: Drift check
        run: sruja drift -r . -f json
```

### Service account + workflow approval

For AI-DLC workflows with phase gates:

```bash
# Initialize workflow
sruja workflow init --with-aidlc --title "Add auth endpoint"

# Bot advances phases when artifacts pass
sruja workflow approve --id wf-001 --phase construction

# CI required checks: verify-task + workflow status
sruja workflow status --check
```

See [AIDLC_INTEGRATION.md](AIDLC_INTEGRATION.md) for full AI-DLC workflow docs.

---

## Config Profiles

Customize verification profiles in `.sruja/config.toml`:

```toml
[verify]
default_profile = "coding"

[verify.coding]
steps = ["lint", "check", "drift-if-arch"]
timeout_ms = 60000

[verify.bugfix]
steps = ["focus", "check", "intent"]
timeout_ms = 30000
```

See `integrations/mod.rs` for the full config schema.

---

## Examples

### Shell pre-apply hook

```bash
#!/bin/bash
# .sruja/hooks/pre-apply.sh
# Run before any agent apply step

set -e
REPO="${1:-.}"

echo "Running pre-apply verification..."
sruja verify-task --profile coding -r "$REPO" -f json > /tmp/verify.json

if ! jq -e '.all_passed' /tmp/verify.json > /dev/null; then
  echo "Verification failed. Steps:"
  jq -r '.steps[] | select(.status == "error") | "  ✗ \(.step_id): \(.stderr)"' /tmp/verify.json
  exit 1
fi

echo "All verification steps passed."
```

### MCP readonly inception

```json
{
  "tool": "sruja_get_focus_briefing",
  "arguments": {
    "path": ".",
    "file": "src/main.rs"
  }
}
```

### GitHub Action with verify-task

See `.github/workflows/sruja-aidlc-gate.yml` for the label-triggered AIDLC gate.

---

## References

- [GETTING_STARTED_SKILL.md](GETTING_STARTED_SKILL.md) — Practical “harnessed AI coding” workflow (MCP + verify-task + skills + diagrams)
- [GROUNDED_HARNESS_AND_CONTINUAL_LEARNING.md](GROUNDED_HARNESS_AND_CONTINUAL_LEARNING.md) — Closed-loop agent, harness boundary, continual learning
- [docs/plans/LOOP_AGENT_PLAN.md](plans/LOOP_AGENT_PLAN.md) — Loop engineering thesis and phased plan
- [AIDLC_INTEGRATION.md](AIDLC_INTEGRATION.md) — AI-DLC workflow integration
- [CONTEXT_ENGINEERING.md](CONTEXT_ENGINEERING.md) — MCP ladder, focus, pruning
- [docs/plans/AGENT_DELIVERY_PLAN.md](plans/AGENT_DELIVERY_PLAN.md) — Delivery roadmap
