Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 30 additions & 21 deletions examples/alert-triage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,54 @@ workload from synthesis up through the lifecycle dial, L5 graduates to a real
app: a webhook receives alerts, a Temporal worker runs a phased triage workflow
over each, and a human approves anything risky before it is applied.

> **Status:** this first slice ships the app's **Kubernetes manifests** and the
> **triage Op skeleton**. The worker, the triage activities (the agent — stubbed
> by default, real Claude when `ANTHROPIC_API_KEY` is set), and a `WatchOp` drift
> source as a second event source land in follow-ups. See
The triage workflow is **raw Temporal**, not a chant Op — its activities are
custom app logic (they run the agent), so it's a hand-written Temporal
workflow + worker, with chant synthesizing the Kubernetes manifests around it.
This is chant's documented "Raw Temporal + chant" path, the same split as
`temporal-crdb-deploy`. (chant Ops are for infra-deploy workflows over pre-built
steps, not arbitrary app logic.)

> **Status:** so far this ships the app's **Kubernetes manifests** and the
> **triage activities** (the agent — stubbed by default, real Claude when
> `ANTHROPIC_API_KEY` is set). The Temporal **workflow + worker** wiring, a
> webhook source, and a `WatchOp` drift source land in follow-ups. See
> [#74](https://github.com/INTENTIUS/chant/issues/74).

## What's here now

| File | What it declares |
| File | What it is |
|---|---|
| `src/config.ts` | pinned image refs (replace with your own builds) |
| `src/workloads.ts` | the webhook (`WebApp` → Deployment + Service + Ingress + PDB) and the worker (`WorkerPool` → Deployment) |
| `alert-triage.op.ts` | the triage Op: **Classify → Context → Propose → Approve (gate) → Notify** |
| `src/workloads.ts` | chant manifests — the webhook (`WebApp` → Deployment + Service + Ingress + PDB) and the worker (`WorkerPool` → Deployment) |
| `activities/triage.ts` | the triage activities (raw Temporal): `classifyAlert`, `gatherContext`, `proposeRemediation`, `notifyOutcome` |
| `chant.config.ts` | k8s + temporal lexicons, and a local Temporal profile |

```bash
npm install
npm run build # → k8s.yaml (plain Kubernetes)
npm run lint # clean
npm run list # what you declared
npm test # unit-tests the triage activities
```

## The triage workflow
## The triage activities

One alert in, a phased triage out. Each non-gate phase is an activity run by the
worker; the `Approve` gate pauses for a human, which makes the Op Temporal-bound:
One alert in, a phased triage out: classify severity, gather context, propose a
remediation, and (in the workflow) gate on human approval for risky changes,
then notify. The activities are deterministic by default, so they run in CI and
offline with no key:

```bash
chant run alert-triage --temporal # pauses at "Approve"
chant run signal alert-triage approve-remediation
```

The activities run the agent — **stubbed by default** (no key, runs anywhere),
and a real Claude call when `ANTHROPIC_API_KEY` is set. The first run shows
chant, not an LLM.
- `classifyAlert` — severity from the alert text.
- `gatherContext` — stands in for a tool registry (kubectl, logs, dig).
- `proposeRemediation` — **stub by default; real Claude when `ANTHROPIC_API_KEY`
is set** (and `@anthropic-ai/sdk` is installed). The first run shows chant, not
an LLM. Override the model with `ANTHROPIC_MODEL` (default `claude-sonnet-4-6`).
- `notifyOutcome` — logs the outcome; a real build would post to Slack.

## Coming in follow-ups

- The worker and the triage activities (classify / gather context / propose / notify).
- The agent: deterministic stub by default, real Anthropic opt-in.
- A `WatchOp` that turns drift on the deployed namespace into a second event source.
- The raw Temporal **workflow** (classify → context → propose → approval gate →
notify) and the **worker** that registers these activities.
- A webhook source, and a `WatchOp` that turns drift on the deployed namespace
into a second event source.
- A local k3d + Temporal `npm run dev` and a tutorial.
59 changes: 59 additions & 0 deletions examples/alert-triage/activities/triage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { describe, test, expect, beforeEach, afterEach } from "vitest";
import {
classifyAlert,
gatherContext,
proposeRemediation,
notifyOutcome,
type Alert,
} from "./triage";

const alert: Alert = { id: "a1", title: "API outage in prod", source: "datadog" };

describe("triage activities (stub path)", () => {
// Ensure the deterministic stub path — never hit the real API in CI.
const saved = process.env.ANTHROPIC_API_KEY;
beforeEach(() => {
delete process.env.ANTHROPIC_API_KEY;
});
afterEach(() => {
if (saved !== undefined) process.env.ANTHROPIC_API_KEY = saved;
});

test("classifyAlert maps keywords to severity", async () => {
expect((await classifyAlert({ id: "1", title: "API outage" })).severity).toBe("critical");
expect((await classifyAlert({ id: "2", title: "request failed" })).severity).toBe("high");
expect((await classifyAlert({ id: "3", title: "latency degraded" })).severity).toBe("medium");
expect((await classifyAlert({ id: "4", title: "nightly report ready" })).severity).toBe("low");
});

test("gatherContext returns signals for the source", async () => {
const ctx = await gatherContext(alert);
expect(ctx.signals.length).toBeGreaterThan(0);
expect(ctx.signals[0]).toContain("datadog");
});

test("proposeRemediation (stub) flags high/critical as risky", async () => {
const classification = await classifyAlert(alert);
const context = await gatherContext(alert);
const r = await proposeRemediation({ alert, classification, context });
expect(r.summary).toContain(alert.title);
expect(r.risky).toBe(true); // critical → risky
});

test("proposeRemediation (stub) marks low severity as not risky", async () => {
const classification = await classifyAlert({ id: "5", title: "info: cache warmed" });
const context = await gatherContext({ id: "5", title: "info: cache warmed" });
const r = await proposeRemediation({
alert: { id: "5", title: "info: cache warmed" },
classification,
context,
});
expect(r.risky).toBe(false);
});

test("notifyOutcome runs without throwing", async () => {
await expect(
notifyOutcome({ alert, remediation: { summary: "x", risky: false }, approved: true }),
).resolves.toBeUndefined();
});
});
128 changes: 128 additions & 0 deletions examples/alert-triage/activities/triage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Triage activities — plain async functions the Temporal worker registers.
//
// These are raw Temporal activities (not chant Op steps): the triage workflow is
// custom app logic, so it's hand-written Temporal with chant synthesizing the
// manifests around it. See chant's "Raw Temporal + chant" deployment path.
//
// The agent is stubbed by default — deterministic, no key, runs in CI and
// offline. When ANTHROPIC_API_KEY is set, `proposeRemediation` calls Claude.

export interface Alert {
id: string;
title: string;
body?: string;
source?: string;
}

export type Severity = "low" | "medium" | "high" | "critical";

export interface Classification {
severity: Severity;
rationale: string;
}

export interface TriageContext {
signals: string[];
}

export interface Remediation {
summary: string;
/** Risky remediations route through the human-approval gate. */
risky: boolean;
}

/** Classify severity. Deterministic stub: keyword heuristic. */
export async function classifyAlert(alert: Alert): Promise<Classification> {
const text = `${alert.title} ${alert.body ?? ""}`.toLowerCase();
const severity: Severity = /\b(outage|down|unavailable)\b/.test(text)
? "critical"
: /\b(error|fail|failed|crash)\b/.test(text)
? "high"
: /\b(warn|warning|degraded)\b/.test(text)
? "medium"
: "low";
return { severity, rationale: `keyword heuristic over "${alert.title}"` };
}

/** Gather context. Stub stands in for a tool registry (kubectl, logs, dig). */
export async function gatherContext(alert: Alert): Promise<TriageContext> {
return {
signals: [
`recent events for ${alert.source ?? "unknown source"}`,
"no correlated incidents (stub)",
],
};
}

/**
* Propose a remediation. Stub by default; real Claude when ANTHROPIC_API_KEY is
* set (and `@anthropic-ai/sdk` is installed).
*/
export async function proposeRemediation(input: {
alert: Alert;
classification: Classification;
context: TriageContext;
}): Promise<Remediation> {
if (process.env.ANTHROPIC_API_KEY) {
return proposeWithClaude(input);
}
const risky =
input.classification.severity === "high" ||
input.classification.severity === "critical";
return {
summary: `Proposed (stub): mitigate "${input.alert.title}" [${input.classification.severity}]`,
risky,
};
}

/** Post the outcome. Stub logs; a real build would post to Slack. */
export async function notifyOutcome(input: {
alert: Alert;
remediation: Remediation;
approved: boolean;
}): Promise<void> {
const status = input.remediation.risky
? input.approved
? "applied after approval"
: "held — not approved"
: "applied";
console.log(`[alert-triage] ${input.alert.id}: ${input.remediation.summary} — ${status}`);
}

// ── Real-agent path (opt-in) ──────────────────────────────────────────────────

interface MinimalAnthropic {
messages: {
create(body: unknown): Promise<{ content: Array<{ type: string; text?: string }> }>;
};
}

async function proposeWithClaude(input: {
alert: Alert;
classification: Classification;
context: TriageContext;
}): Promise<Remediation> {
// Variable specifier keeps bundlers from resolving the optional dep when absent.
const pkg = "@anthropic-ai/sdk";
let Anthropic: new () => MinimalAnthropic;
try {
Anthropic = ((await import(pkg)) as { default: new () => MinimalAnthropic }).default;
} catch {
throw new Error(
"ANTHROPIC_API_KEY is set but @anthropic-ai/sdk is not installed — run `npm i @anthropic-ai/sdk`.",
);
}
const client = new Anthropic();
const model = process.env.ANTHROPIC_MODEL ?? "claude-sonnet-4-6";
const prompt =
`Alert: ${input.alert.title}\nSeverity: ${input.classification.severity}\n` +
`Context: ${input.context.signals.join("; ")}\n\n` +
`Propose a one-line remediation. End with RISKY or SAFE.`;
const res = await client.messages.create({
model,
max_tokens: 512,
messages: [{ role: "user", content: prompt }],
});
const text = res.content.map((b) => b.text ?? "").join("").trim();
return { summary: text.replace(/\b(RISKY|SAFE)\s*$/i, "").trim(), risky: /RISKY\s*$/i.test(text) };
}
32 changes: 0 additions & 32 deletions examples/alert-triage/alert-triage.op.ts

This file was deleted.

25 changes: 5 additions & 20 deletions examples/examples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import deployGatedOp from "./getting-started/deploy-gated.op";
import observeOp from "./getting-started/observe.op";
import reconcileOp from "./getting-started/reconcile.op";
import applyOp from "./getting-started/apply.op";
import alertTriageOp from "./alert-triage/alert-triage.op";
import { resolve } from "path";

/** Read an Op default export's name. */
Expand Down Expand Up @@ -133,8 +132,9 @@ describe("golden example L4 — lifecycle dial", () => {
});

// ── Golden teaching example — L5 capstone: alert-triage (#74) ────────
// First slice: the app's k8s manifests + the triage Op skeleton. Worker,
// activities, and WatchOp source land in follow-ups.
// The app's chant-synthesized k8s manifests. The triage workflow itself is raw
// Temporal (custom agent activities); its activities are unit-tested separately
// under examples/alert-triage/activities/. Workflow + worker land in follow-ups.

describeExample(
"alert-triage",
Expand All @@ -155,23 +155,8 @@ describeExample(
},
);

describe("alert-triage L5 — triage Op", () => {
test("compiles with the triage phases and an approval gate", () => {
const props = (alertTriageOp as unknown as {
props: { name: string; phases: Array<{ name: string; steps: Array<{ kind: string }> }> };
}).props;
expect(props.name).toBe("alert-triage");
expect(props.phases.map((p) => p.name)).toEqual([
"Classify",
"Context",
"Propose",
"Approve",
"Notify",
]);
const approve = props.phases.find((p) => p.name === "Approve");
expect(approve?.steps.some((s) => s.kind === "gate")).toBe(true);
});
});
// The triage workflow is raw Temporal (custom agent activities), not a chant Op.
// Its activities are unit-tested in examples/alert-triage/activities/.

// ── K8s + AWS EKS microservice (comprehensive) ──────────────────────

Expand Down
2 changes: 1 addition & 1 deletion examples/getting-started/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Start here if you are new to chant. Stop at whatever level answers your question
| **L2 — Ops, local** | wrap the declarations in an Op that `kubectl apply`s to a local k3d cluster | k3d (Docker) |
| **L3 — gate + Temporal** | a human-approval gate before apply | a local Temporal (Docker) |
| **L4 — the lifecycle dial** | observe drift, reconcile, apply against the cluster | the k3d cluster |
| **L5 — capstone** | the [alert-triage app](../alert-triage/) ([#74](https://github.com/INTENTIUS/chant/issues/74)) — manifests + triage Op so far | the full local stack |
| **L5 — capstone** | the [alert-triage app](../alert-triage/) ([#74](https://github.com/INTENTIUS/chant/issues/74)) — manifests + triage activities so far | the full local stack |

## L1 — what is here

Expand Down
4 changes: 4 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export default defineConfig({
"packages/**/*.test.ts",
"lexicons/**/*.test.ts",
"examples/examples.test.ts",
// The alert-triage app ships colocated unit tests for its triage
// activities. (examples/ is not globbed wholesale — fargate's docker
// e2e/volume suites need Docker and aren't CI unit tests.)
"examples/alert-triage/**/*.test.ts",
],
environment: "node",
// The Temporal runtime/compile-smoke suites bundle workflows with webpack
Expand Down