Metadata-Version: 2.4
Name: incident-agent
Version: 0.1.1
Summary: Watches payflow-engine and agentic-rag, and investigates their incidents with a read-only Strands agent.
License-Expression: MIT
Project-URL: Homepage, https://github.com/larryaus/incident-agent
Project-URL: Source, https://github.com/larryaus/incident-agent
Project-URL: Releases, https://github.com/larryaus/incident-agent/releases
Keywords: incident response,root cause analysis,observability,agents,strands,claude
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Monitoring
Classifier: Environment :: Console
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: strands-agents[anthropic,otel]==1.68.0
Requires-Dist: httpx<1,>=0.28
Requires-Dist: pydantic<3,>=2.9
Requires-Dist: PyYAML<7,>=6
Provides-Extra: aws
Requires-Dist: boto3<2,>=1.40; extra == "aws"
Provides-Extra: openai
Requires-Dist: strands-agents[openai]==1.68.0; extra == "openai"
Provides-Extra: dev
Requires-Dist: pytest<9,>=8; extra == "dev"
Requires-Dist: ruff>=0.11; extra == "dev"
Requires-Dist: mypy>=1.15; extra == "dev"
Requires-Dist: types-PyYAML; extra == "dev"
Requires-Dist: boto3<2,>=1.40; extra == "dev"
Requires-Dist: moto[cloudwatch,logs]<6,>=5; extra == "dev"
Dynamic: license-file

# incident-agent

[![CI](https://github.com/larryaus/incident-agent/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/larryaus/incident-agent/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/release/larryaus/incident-agent?include_prereleases&sort=semver)](https://github.com/larryaus/incident-agent/releases)
[![PyPI](https://img.shields.io/pypi/v/incident-agent)](https://pypi.org/project/incident-agent/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/larryaus/incident-agent/blob/main/LICENSE)
[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue)](https://github.com/larryaus/incident-agent/blob/main/pyproject.toml)

Watches [payflow-engine](https://github.com/larryaus/payflow-engine) and
[agentic-rag](https://github.com/larryaus/agentic-rag), opens an incident when something breaks, and has a
read-only [Strands](https://strandsagents.com) agent on Claude investigate it: it collects evidence from logs,
health and business checks, git history, code and runbooks, then writes a root cause analysis with proposed fixes
for a person to approve. After the fix, it verifies recovery and closes the incident.

```text
  payflow-engine                 agentic-rag (local)              agentic-rag (AWS)
  actuator health, audit log,    /healthz, JSON app logs          CloudWatch alarms,
  stuck payments, service logs   ("chat turn completed")          CloudWatch Logs
           │                               │                              │
           └───────────────┬───────────────┴──────────────────────────────┘
                           ▼
        1. Detect     checks: deterministic, no model ─────────► incident opened (one per system)
                           │
        2. Investigate  Strands agent on Claude, read-only tools:
                        run_checks · error_summary · search_logs · get_trace · http_get (allow-listed GET)
                        recent_changes · show_commit · search_code · read_file · list/read_runbook
                           │
                           ▼  RCA report (Markdown + JSON): timeline, hypotheses with evidence,
                              root cause, proposed actions with rollback, verification plan
        3. Approve    a person approves an action and applies it; the agent never changes anything
                           │
        4. Verify     the same checks, until they pass N times in a row ──► incident resolved
```

OpenTelemetry traces the agent itself: each check, the investigation, every model call and tool call.

## Try it without running anything

Two captured incidents replay from log files, in the formats the two systems actually write:

| Example | What happened |
|---|---|
| `examples/payflow-ledger-outage` | ledger-service runs out of heap; payment-service's circuit breaker opens; payments fail and are compensated; one compensation cannot unfreeze 50000 cents because of an optimistic-lock conflict, so it needs a person |
| `examples/agentic-rag-model-errors` | after the app is recreated with a new model name, every chat turn ends with `stopReason=error` (`NotFoundError`) while HTTP stays 200 |

```bash
python3.12 -m venv .venv && .venv/bin/pip install -e '.[dev]'

# What the checks see, and the evidence the agent starts from (no model call):
.venv/bin/incident-agent check    -t examples/payflow-ledger-outage/target.yaml --at 2026-11-28T02:15:00Z
.venv/bin/incident-agent evidence -t examples/payflow-ledger-outage/target.yaml --at 2026-11-28T02:15:00Z

# The full investigation (needs a model, see below):
export ANTHROPIC_API_KEY=...
.venv/bin/incident-agent investigate -t examples/payflow-ledger-outage/target.yaml --at 2026-11-28T02:15:00Z
```

`--at` anchors every time window to the moment of the incident. Code and git history come from your
`payflow-engine` and `agentic-rag` checkouts next to this repository (or `PAYFLOW_REPO` / `AGENTIC_RAG_REPO`).

## Watch the real systems

Start them as their READMEs describe (`docker compose up -d` in each checkout), then:

```bash
cp .env.example .env            # set ANTHROPIC_API_KEY (or another provider)
set -a; . ./.env; set +a

.venv/bin/incident-agent check                     # one pass over payflow and agentic-rag
.venv/bin/incident-agent watch --interval 60       # open, investigate and resolve incidents on a loop
.venv/bin/incident-agent watch --no-investigate    # detect only, no model calls
```

The PayFlow gateway and agentic-rag's Keycloak both listen on 8080; move one (and its URL variable) to watch both
at once. Logs are read with `docker compose logs` from each checkout, so run the watcher on the Docker host.

For agentic-rag on AWS, install the `aws` extra, give the watcher read-only credentials
(`cloudwatch:DescribeAlarms`, `logs:FilterLogEvents`), export the log group names listed in
`targets/agentic-rag-aws.yaml`, and add `-t agentic-rag-aws`.

### When an incident opens

```bash
incident-agent list                                        # incidents and their status
incident-agent show payflow-20261128-021500                # the report (also in reports/<id>.md)
incident-agent approve payflow-20261128-021500 --action 1 --by alice --note "restarting ledger"
# ...apply the action yourself...
incident-agent verify payflow-20261128-021500              # 3 healthy rounds 30 s apart resolve it
incident-agent investigate --incident payflow-20261128-021500   # investigate again with fresh evidence
incident-agent investigate -t payflow --question "Refunds got slow after lunch, why?"
```

`approve` records who approved which action; it does not run anything. `watch` also resolves an incident by
itself after `--resolve-after` healthy cycles (default 3). Set `NOTIFY_WEBHOOK_URL` to post openings,
investigation summaries and resolutions to Slack or any webhook that takes `{"text": ...}`.

### Cost controls

Checks cost nothing; each investigation is a model run, roughly $1–3 on Claude Opus 5.5 with prompt caching
(an estimate: it depends on how many turns the agent takes). Two limits keep `watch` from running up a bill when a
service keeps failing and recovering:

| Setting | Default | What it does |
|---|---|---|
| `INVESTIGATION_COOLDOWN_MINUTES` / `--cooldown-minutes` | 60 | A target that fails again this soon after its incident was resolved **reopens** that incident instead of opening and investigating a new one. A flapping service costs one investigation, not one every few minutes. `0` turns it off. |
| `MAX_INVESTIGATIONS_PER_DAY` / `--max-investigations-per-day` | 5 | Automatic investigations allowed in any 24 hours, across all targets. Over the limit, incidents still open and notify, but are not investigated. `0` turns automatic investigation off. |

A reopened or uninvestigated incident says so in its report's Activity section, with the command to investigate it
anyway. Investigations run by hand (`incident-agent investigate`) are never blocked, but count towards the limit.

## Models

| `MODEL_PROVIDER` | Default `MODEL_ID` | Credentials |
|---|---|---|
| `anthropic` (default) | `claude-opus-5-5` | `ANTHROPIC_API_KEY` or an `ant auth login` profile |
| `bedrock` | `anthropic.claude-opus-5-5` | AWS credentials, `AWS_REGION` (Anthropic SDK's Bedrock client) |
| `openai` | none, set `MODEL_ID` | `LLM_BASE_URL`, `LLM_API_KEY`; any OpenAI-compatible server such as Ollama (`.[openai]` extra) |

Claude runs with effort `high` (`MODEL_EFFORT`), prompt caching on the system prompt, tools and transcript, and
native structured output for the report. If the model declines an investigation (stop reason `refusal`), it is
re-run once on `MODEL_FALLBACK_ID` (`claude-opus-5` by default) and the report notes it. An investigation gets 40
turns; if it uses them all, the agent is asked for its report from the evidence it has.

## What the agent can and cannot do

Every tool reads. `http_get` only issues GET requests to the URL prefixes a target allows (health, metrics,
payments, audit), rejects `..` paths and credentials in URLs, and PayFlow's money-moving endpoints are not on the
list. `read_file` and `search_code` stay inside the repository and never read `.env`, keys or credentials. Log text
is scrubbed of bearer tokens, JWTs, passwords and AWS keys before it is sent to the model, and tool output is
capped (`MAX_TOOL_OUTPUT_CHARS`).

Each target's `context` gives the agent the system's rules, which its proposed actions must respect. For PayFlow:
never compensate a payment whose transfer succeeded, never edit ledger rows, and never bypass the payment state
machine. For agentic-rag: never `docker compose down -v`, never turn off the guardrail.

## Checks

Targets live in `targets/*.yaml`; `${VAR:-default}` is expanded in every value.

| `type` | Signals when |
|---|---|
| `http` | status, JSON body (`expect_json` subset or exact value) or latency differs; names actuator components that are down |
| `log_errors` | a service logs `threshold` or more lines at the given levels within `window_minutes` |
| `log_match` | a regex matches a log message, optionally with JSON field values (`fields: {stopReason: error}`) |
| `payflow_stuck_payments` | payments stay PENDING/PROCESSING longer than `older_than_minutes` |
| `payflow_audit` | the audit log has actions that always need a person, such as `RECONCILE_REQUIRED` |
| `cloudwatch_alarms` | CloudWatch alarms matching a prefix or names are in ALARM |

Log sources: `docker_compose` (local stacks), `cloudwatch` (Lambda) and `file` (replays). The parser understands
logback with `[traceId=...]`, Spring Boot's default pattern, Python logging and uvicorn, Go's `log.Printf`, JSON
lines, and Docker's `--timestamps` prefix. Java stack traces stay attached to the line that printed them.

> **PayFlow's ledger balance check is disabled.** `GET /api/v1/ledger/verify` always returns `false`:
> `LedgerEntryRepository` sums entries `WHERE entryType = 'DEBIT'` / `'CREDIT'`, but entries are written with
> `entryType` `PAYMENT` or `REVERSAL`. Re-enable the check in `targets/payflow.yaml` once that is fixed.

## Runbooks

`runbooks/<system>/*.md` hold what responders already know about each failure mode: signals, how to confirm it,
safe actions and what never to do. The agent lists and reads them during an investigation. When an incident teaches
something new, add or extend a runbook; that is how a resolved incident makes the next one faster.

## OpenTelemetry

Set `OTEL_EXPORTER_OTLP_ENDPOINT` (for example a local Jaeger at `http://localhost:4318`) to export the agent's
traces, or pass `--trace-console`. Strands records prompts and tool output on its spans, which include log lines;
send them only to a collector you run.

## Development

```bash
.venv/bin/ruff check src tests && .venv/bin/ruff format --check src tests
.venv/bin/mypy
.venv/bin/pytest -q
```

No test calls a model, Docker or AWS. The investigator tests run the real Strands agent loop against a scripted
model, so tool calls execute against the replay logs and the report comes back through Strands' structured output;
CloudWatch is mocked with moto.

## Releasing

1. Bump `__version__` in `src/incident_agent/__init__.py` (the package reads its version from there) and merge
   it to `main`.
2. Tag the merged commit and push the tag:

   ```bash
   git checkout main && git pull
   git tag v0.2.0 && git push origin v0.2.0      # v0.2.0-rc.1 publishes a pre-release
   ```

The `Release` workflow runs the full CI on the tag, refuses a tag that is not on `main` or does not match
`__version__` (compared as PEP 440 versions, so `v0.2.0-rc.1` matches `0.2.0rc1`), builds the sdist and wheel, checks
that the wheel installs and reports that version, and publishes a GitHub release with both files and notes generated
from the merged pull requests. It then uploads the same two files to PyPI, so `pip install incident-agent` gets
exactly what the release holds. If a release for the tag
already exists (made by hand on GitHub), the workflow attaches the files to it instead, so a failed run can be
re-run safely.

PyPI publishing uses [trusted publishing](https://docs.pypi.org/trusted-publishers/): no token is stored. It needs
a one-time setup on PyPI: under *Your projects → Publishing → Add a new pending publisher*, enter project
`incident-agent`, owner `larryaus`, repository `incident-agent`, workflow `release.yml` and environment `pypi`. To
publish a release that is already out, run the `Release` workflow by hand (*Actions → Release → Run workflow*) with
its tag; it uploads that release's files without building again.

The package installs the `incident-agent` command only. The targets, runbooks and examples come from the repository
(or the release's source archive): run the command from that directory, or point `INCIDENT_AGENT_TARGETS` at its
`targets/`.

## Code layout

```text
src/incident_agent/
  config.py        target YAML and environment settings
  logs.py          log sources and parsers
  checks.py        the checks
  incidents.py     incident lifecycle and state file
  tools.py         the agent's read-only tools
  investigator.py  the Strands agent, model providers, refusal fallback
  report.py        the RCA schema and Markdown
  service.py       watch cycle, investigate, approve, verify
  cli.py           the incident-agent command
targets/           payflow, agentic-rag (local), agentic-rag-aws
runbooks/          per-system runbooks
examples/          replayable incidents
```

## License

[MIT](https://github.com/larryaus/incident-agent/blob/main/LICENSE)
