<!-- BEGIN ZIBBY — managed by `zibby init`, do not edit between markers -->
# Zibby integration

This project uses **Zibby** (https://zibby.dev). Zibby is two surfaces
sharing one account, one CLI, one Studio:

1. **Agents** (a.k.a. workflows) — graphs of AI-agent-driven steps
   that run in a sandboxed container — on Zibby Cloud or on your
   self-hosted box. For event-driven automation that needs an LLM
   in the loop.
2. **Apps** — long-running hosted SaaS instances (n8n, Grafana,
   Outline, …) on Zibby's managed fleet, with an `agent-ops` sidecar.
   Pick from a catalog or describe a goal in natural language.

For deeper detail, see `.claude/CLAUDE.md` in this repo (canonical
reference) or https://docs.zibby.app.

---

## CLI quick reference

Use `zibby` on PATH (preferred) or `./.zibby/bin/zibby` as a fallback
shim in this repo. Never fall back to `npx @zibby/cli`.

### Auth + context

```bash
zibby login                         # browser OAuth → ~/.zibby/session.json
zibby status                        # current auth + workspace + project + agent creds
zibby logout                        # clear session
zibby list                          # list projects in this workspace
zibby project use <id>              # switch default project
```

For headless / CI: `export ZIBBY_API_KEY=zby_xxx` (PAT from https://zibby.dev/settings/api-keys). Env var beats session token.

### Workflows

```bash
zibby agent new <name>           # scaffold agents/<name>/
zibby agent run <name> -p k=v    # one-shot LOCAL run (preferred for dev loop)
zibby agent validate <name>      # static check (graph topology, schemas, skills)
zibby agent deploy <name>        # build + push to Zibby Cloud → UUID
zibby agent trigger <uuid> -p .. # remote run
zibby agent logs <uuid> -t       # tail live logs
zibby agent schedule <uuid> set "0 9 * * 1-5"   # 5-field Unix cron
zibby agent list                 # local + cloud
zibby agent delete <uuid>        # remove a deployed workflow
```

Workflow file layout:
```
<paths.agents or workflows>/<name>/
├── agent.json          name, entryClass, triggers, defaultAgent
├── graph.mjs              class extends WorkflowAgent — buildGraph() returns WorkflowGraph
├── nodes/*.mjs            one node per file: name, outputSchema (Zod), prompt|execute
├── state.js               OPTIONAL — Zod schema for caller-provided inputs
└── package.json           @zibby/core + zod
```

Node shape:
```js
import { z } from 'zod';
export const planNode = {
  name: 'plan',
  agent: 'claude',                    // optional override; defaults to workflow's defaultAgent
  outputSchema: z.object({ steps: z.array(z.string()) }),
  prompt: (state) => `Plan: ${state.userRequest}`,
  // OR for deterministic work:
  // execute: async (state) => ({ steps: [...] }),
};
```

Graph wiring:
```js
import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
export class MyWorkflow extends WorkflowAgent {
  buildGraph() {
    const graph = new WorkflowGraph();
    graph.addNode('plan', planNode);
    graph.addNode('act',  actNode);
    graph.addEdge('plan', 'act');
    graph.addEdge('act',  'END');
    graph.setEntryPoint('plan');
    return graph;
  }
}
```

**Each node's output goes to `state[nodeName]`.** Read it in downstream
nodes via `state.plan.steps`. Initial input from `-p key=value` is at
the TOP of state (`state.key`), not nested under `input`.

Loops: route back to an earlier node via `addConditionalEdges`. Counter
state lives in the looping node's own outputSchema (`state.check?.attempts`).

### Apps

```bash
zibby app templates                                 # browse the catalog
zibby app deploy <appType> --project <id> [--name "..."] [--auth-type basic|token|none ...]
zibby app deploy --goal "<text>" --project <id>     # goal-mode (LLM bootstrap)
zibby app list [--project <id>]
zibby app status <instanceId>
zibby app logs <instanceId> [-t] [--service <name>]
zibby app upgrade <instanceId> --version vX.Y.Z     # agent-ops base image bump
zibby app set-auth <instanceId> --auth-type basic --auth-user admin --auth-password ...
zibby app set-auth <instanceId> --off               # disable auth sidecar
zibby app destroy <instanceId> --yes                # PERMANENT — wipes app data
```

Two deploy paths:
- **Catalog** (`zibby app deploy <appType>`) — deterministic, baked task
  def, 2-3 min cold start.
- **Goal-mode** (`zibby app deploy --goal "..."`) — LLM bootstrap via
  `agent-ops`, 5-30 min cold start.

Goal-mode flags worth knowing: `--provider claude|codex`, `--model <id>`,
`--anthropic-token sk-ant-oat01-...` (per-deploy Claude credential override),
`--max-turns N` (default 25, heavy installs need 60-100), `--timeout-min N`
(default 20, heavy installs need 30-45).

Auth: every app gets a public `https://<id>.apps.zibby.app` URL. Lock it
down with `--auth-type basic|token`. Generate creds via `openssl rand -hex`.
Use `--auth-type none` (or omit) only if the app has its own login.

---

## Recipe: "create a workflow that does X"

0. **Study the patterns FIRST.** Read
   https://docs.zibby.app/concepts/designing-agents before sketching.
   The three patterns nearly every good agent uses: (a) **one agent,
   many entry points** — a code `route` node at the entry so a single
   deployed agent serves cron + human + webhook triggers, not two
   agents; (b) **zero-LLM code nodes that read/write Stores** — fetch /
   transform / query / persist is plain code (a node reads
   `ZIBBY_STORE__<name>` + `ZIBBY_ACCOUNT_API_URL` + `PROJECT_API_TOKEN`
   and hits the datasets API — sqlite/file/dataset — no model call);
   (c) **event-driven** — one agent subscribes to several events and
   branches per event. The shipped `sentry-triage` and
   `engineering-insights` agents are the canonical worked examples.
1. **Sketch the graph.** 2-5 nodes. LLM (judgement) vs custom-code
   (deterministic shell / HTTP / parse / Store I/O). Linear or
   conditional? Multiple triggers → a code `route` entry node, ONE
   agent (see pattern (a) above), not one agent per trigger.
2. `zibby agent new <name>` — scaffold.
3. Edit `agent.json`, `nodes/*.mjs`, `graph.mjs`. Every node has a
   Zod `outputSchema`. Default agent: `claude`.
4. `zibby agent validate <name>` — fix reported issues.
5. `zibby agent run <name> -p ...` — realistic input. Read the
   timeline. If a node fails, the `raw` field shows what the model
   returned vs what the schema expected.
6. Iterate prompts. The user shouldn't need to.
7. Ask before `zibby agent deploy` — cloud costs.

## Recipe: "combine several existing agents" (compose)

When the need spans MULTIPLE marketplace agents, don't rebuild —
**compose**: author a small wrapper workflow whose nodes dispatch the
deployed agents as sub-workflows via `graph.addNode('review', {
workflow: '<deployed-slug>', input: (state) => ({...}) })`. The child
runs in-process and its final state lands at `state[nodeName]` —
branch on it with `addConditionalEdges`. Never modify a marketplace
template's source (shared bricks); if a brick is already deployed,
ASK the user: reuse it (shared config) vs deploy a dedicated named
instance (isolated config). The wrapper declares its own triggers
(`agent.json` `triggers.events`); the platform suppresses wrapped
members' subscriptions so events don't double-fire. Works identically
against self-host (`ZIBBY_API_URL` + `ZIBBY_API_KEY`; self-signed
HTTPS → `NODE_EXTRA_CA_CERTS`, no --insecure flag exists). Full
recipe: `/zibby-compose` / §10 of `.claude/CLAUDE.md`.

## Recipe: "deploy a hosted X"

1. **Catalog or goal?** Check `zibby app templates`. Catalog if X
   is listed; else goal-mode.
2. **Which project?** `zibby status` for current; `zibby list` to
   pick.
3. **What auth?** Ask before running. `basic` for browser tools,
   `token` for APIs, `none` only for apps with their own login.
   Generate creds with `openssl rand -hex 16` (basic) / `-hex 32`
   (token).
4. **Run deploy.** Capture the `instanceId`.
5. **Tail logs while it boots** (`zibby app logs <id> -t` in background).
6. **Verify status reaches `running`.** Tell the user URL + creds.

## Recipe: "my workflow / app is broken"

For workflows:
1. `zibby agent list` — did the deploy succeed? Is `bundleStatus`
   ready?
2. `zibby agent trigger <uuid>` — did it accept?
3. `zibby agent logs <uuid> -t` — did the task start? Did a node
   fail? Read the `Prompt sent to LLM` + `Response` blocks for agent
   errors.

For apps:
1. `zibby app status <id>` — read the status. `failed` → reason field.
   Stuck `pending` → wait 5 min, then escalate to logs.
2. `zibby app logs <id> [--service agent-ops]` — supervisor trail +
   container stderr.
3. Decide: restart, env-fix, or destroy + redeploy. Never destroy
   without confirming permanent data loss.

## Recipe: "set an env var for production"

For a workflow:
```bash
# next trigger picks it up; existing executions unaffected
```

For an app:
```bash
```

Workflow env wins over project secrets. App env applies at task-start;
restart to apply changes.

## Recipe: "rotate the auth on a hosted app"

```bash
zibby app set-auth <instanceId> --auth-type basic \
  --auth-user admin \
  --auth-password $(openssl rand -hex 16)
```

The auth layer reloads in ~5s. Old creds stop working immediately. No
container restart. Tell the user to save the new password before they
log out.

## Recipe: "wire the Zibby MCP into my IDE"

```bash
zibby mcp install --project --yes        # ./.mcp.json (Claude Code project scope)
zibby mcp install --agent cursor --yes   # or claude-code / codex / gemini (global)
# reload the IDE; agent can now call zibby_workflow_* / zibby_app_* tools directly
```

No export step: every config carries the token inline (`0600`), and `./.mcp.json`
is added to `.gitignore` for you. Claude Code asks you to approve a project-scope
server once — run `claude` in that directory and accept. Use `--env-ref` if you'd
rather commit `.mcp.json` and have each teammate export `ZIBBY_PAT`.

Run it bare (`zibby mcp install`) for the interactive flow — it prompts
for the control-plane URL + token (cloud or self-host) and validates
both live before writing. For headless / shared configs, pass the token
via `ZIBBY_MCP_TOKEN` env (or `--token zby_xxx`) instead of using the
session token.

---

## Slash commands available in this repo

Every Zibby slash command starts with `/zibby-`:

**Workflows:** `/zibby-new-workflow`, `/zibby-add-node`, `/zibby-add-skill`,
`/zibby-validate-workflow`, `/zibby-compose`, `/zibby-deploy`, `/zibby-trigger`,
`/zibby-list`, `/zibby-tail`, `/zibby-debug`, `/zibby-delete`,
`/zibby-static-ip`, `/zibby-workflow-env`

**Apps:** `/zibby-deploy-app`, `/zibby-app-list`, `/zibby-app-status`,
`/zibby-app-logs`, `/zibby-app-restart`, `/zibby-app-upgrade`,
`/zibby-app-destroy`, `/zibby-set-auth`, `/zibby-app-env`

**Tests + memory:** `/zibby-test-write`, `/zibby-test-run`,
`/zibby-test-debug`, `/zibby-test-generate`, `/zibby-memory-stats`,
`/zibby-memory-cost`, `/zibby-memory-pull`,
`/zibby-memory-remote-use-hosted`

**Auth + setup:** `/zibby-login`, `/zibby-status`, `/zibby-mcp-install`

Each slash command is a self-contained recipe — invoke it and the
agent follows the steps inside. Live files: `.claude/commands/zibby-*.md`.

---

## Canonical docs

Single source of truth — when in doubt, fetch:

- Designing agents (READ FIRST when building one): https://docs.zibby.app/concepts/designing-agents
- Workflows: https://docs.zibby.app/workflows
- Apps: https://docs.zibby.app/apps
- agent-ops daemon: https://docs.zibby.app/apps/agent-ops
- CLI reference: https://docs.zibby.app/cli
- MCP server: https://docs.zibby.app/cli/mcp

These notes are a snapshot. Docs are kept current.
<!-- END ZIBBY -->
