# Fix One Security Finding a Day with Agents

> A Type.com automation example with two agents. Each morning, one finishes the open fix pull request, or another audits the code and fixes the top finding.

Canonical page: https://docs.type.com/automations/examples/security-audit-fix/

Every morning, this automation makes the code base a little safer. It never has more than one fix in flight:

- If yesterday's fix pull request is still open, an agent gets its CI green.
- Otherwise, an agent audits the code with the team's security-audit skill, fixes the single most severe confirmed finding, and opens a pull request.

Either way, code posts one short report in Slack. This is a simplified version of the daily audit that Type runs on its own repository.

| | |
| --- | --- |
| **Trigger** | A cron schedule: 5:00 every day |
| **Stages** | `checkOpenFix` (code) → `finishFix` or `auditAndFix` (agent) → `postReport` (code) |
| **Needs** | A GitHub connection with full automation access, a `security-audit` skill in the Space, and Slack |

## How it runs

```mermaid
flowchart LR
  everyMorning(["everyMorning · schedule"])
  checkOpenFix["checkOpenFix · code + sandbox"]
  finishFix{{"finishFix · agent"}}
  auditAndFix{{"auditAndFix · agent + skill"}}
  postReport["postReport · code"]
  everyMorning -->|entry| checkOpenFix
  checkOpenFix -->|next| finishFix
  checkOpenFix -->|next| auditAndFix
  finishFix -->|onResult| postReport
  auditAndFix -->|onResult| postReport
```

Each node in the graph is one key in the code:

| Node | Type | What it does |
| --- | --- | --- |
| `everyMorning` | Trigger | Starts a run at 5:00 every day. |
| `checkOpenFix` | Code stage | Lists open `sec-audit/` pull requests with the GitHub CLI, and routes the run. |
| `finishFix` | Agent stage | Gets the open fix pull request to green CI. |
| `auditAndFix` | Agent stage | Audits the code and fixes the most severe confirmed finding. |
| `postReport` | Code stage | Posts one report in Slack. |

## The code

```ts title="src/main.ts"

import {
  agent,
  agentResult,
  automation,
  code,
  complete,
  next,
  recurringEventSchema,
} from "@type-dot-com/sdk/automations";

// Replace with your repository, reviewer, and Slack details.
const repository = "acme/project";
const reviewerGithubLogin = "octocat";
const slackConnectionId = "orgint_slack";
const securityChannelId = "C0123456789"; // #security

// Lists open pull requests whose branch starts with "sec-audit/", and prints
// them on one line that starts with "JSON:". The values are fixed constants.
const listOpenFixes = `
token_env=$(printf %s "$TYPE_GITHUB_CONNECTIONS" | jq -er 'first(.[] | select(.fullName == "${repository}") | .tokenEnv)') || { echo "No GitHub connection covers ${repository}" >&2; exit 1; }
fixes=$(GH_TOKEN=$(printenv "$token_env") gh api 'repos/${repository}/pulls?state=open&per_page=100' --jq '[.[] | select(.head.ref | startswith("sec-audit/")) | {number, url: .html_url}]') || exit 1
printf 'JSON:%s\\n' "$fixes"
`;

// JSON.parse throws on bad input. This version returns a Result.
const parseJson = Result.fromThrowable(
  (text: string): unknown => JSON.parse(text),
  () => new TypeApiError("The command printed invalid JSON", "invalid_response"),
);

// The shape of the JSON that the command prints.
const openFixes = z.array(z.object({ number: z.number(), url: z.string() }));

// Both agent stages get the same input and must submit the same result,
// so one code stage can report either one.
const auditInput = z.object({
  day: z.string(),
  openFix: z.object({ number: z.number(), url: z.string() }).nullable(),
});
const auditReport = z.object({
  status: z.enum(["green", "red", "nothing_found"]),
  pullRequestUrl: z.string().nullable(),
  severity: z.enum(["critical", "high"]).nullable(),
  summary: z.string().min(1).max(2000),
});

const sharedRules = [
  "Defensive source review only. Never send attack traffic to production or any live system; reproduce only in local tests.",
  "Follow the repository's CLAUDE.md. Add a test that fails before the fix and passes after it.",
  "Never skip, disable, or weaken a test or a check. Never merge.",
  "Keep descriptions defensive. Never post exploit details.",
  "Do not post in Slack: the automation posts your report.",
].join("\n");

export default automation({
  output: z.object({ status: z.string(), pullRequestUrl: z.string().nullable() }),

  deployment: {
    subscriptions: {
      everyMorning: {
        title: "Daily security audit",
        description: "Fix one confirmed Critical or High finding each day",
        source: {
          kind: "recurring",
          schedule: { kind: "cron", expression: "0 5 * * *", timezone: "America/Los_Angeles" },
        },
        entry: "checkOpenFix",
      },
    },
  },

  stages: {
    // 1. Code + sandbox: an open fix pull request is finished before new work starts.
    checkOpenFix: code({
      input: recurringEventSchema,
      transitions: ["finishFix", "auditAndFix"],
      async run({ ctx, input }) {
        const commandResult = await ctx.tools.call(
          {
            service: "managed-sandbox",
            name: "exec_command",
            arguments: { command: listOpenFixes },
          },
          { automationEffectKey: `security-audit:list:${input.scheduledAt}` },
        );
        if (commandResult.isErr()) {
          return err(commandResult.error);
        }

        const output = commandResult.value.content.map((block) => block.text ?? "").join("\n");
        if (commandResult.value.isError) {
          return err(new TypeApiError(`The GitHub CLI failed: ${output.slice(0, 300)}`, "invalid_response"));
        }
        const jsonLine = output.split("\n").find((line) => line.startsWith("JSON:"));
        if (!jsonLine) {
          return err(new TypeApiError("The command printed no JSON line", "invalid_response"));
        }
        const json = parseJson(jsonLine.slice("JSON:".length));
        if (json.isErr()) {
          return err(json.error);
        }
        const fixes = openFixes.safeParse(json.value);
        if (!fixes.success) {
          return err(new TypeApiError("Unexpected pull request data", "invalid_response"));
        }

        const day = input.scheduledAt.slice(0, 10);
        const openFix = fixes.data[0] ?? null;

        // Route the run: finish yesterday's work, or start today's audit.
        if (openFix) {
          return next("finishFix", { day, openFix });
        }
        return next("auditAndFix", { day, openFix: null });
      },
    }),

    // 2a. Agent: get the open fix pull request to green CI.
    finishFix: agent({
      input: auditInput,
      output: auditReport,
      instructions: [
        `Get the pull request in taskInput.openFix to green CI in ${repository}.`,
        "Read the failing check logs, fix the root cause, push, and wait for CI again.",
        "Return status green when every required check passes, or red with what you tried.",
        sharedRules,
      ].join("\n"),
      onResult: "postReport",
    }),

    // 2b. Agent: audit the code, fix the single most severe finding, and get it green.
    auditAndFix: agent({
      input: auditInput,
      output: auditReport,
      instructions: [
        `Security-audit ${repository} with the security-audit skill of this Space.`,
        "Cover areas that recent audits did not: authorization and tenant isolation, webhooks, sandboxed execution, credential storage, file uploads, SSRF, and injection.",
        "Keep only findings that you verified independently as Critical or High.",
        "Fix the single most severe one with the smallest root-cause change.",
        `Open a pull request on a sec-audit/ branch, assigned to ${reviewerGithubLogin}, and get CI green.`,
        "Return nothing_found if no finding qualifies.",
        sharedRules,
      ].join("\n"),
      onResult: "postReport",
    }),

    // 3. Code: post one short report in Slack.
    postReport: code({
      input: agentResult({ input: auditInput, output: auditReport }),
      transitions: [],
      async run({ ctx, input }) {
        const { status, pullRequestUrl, severity, summary } = input.result;
        const badge = status === "green" ? ":white_check_mark: green" : status === "red" ? ":x: red" : "nothing new";
        const headline = pullRequestUrl
          ? `*Security audit ${input.taskInput.day}* · ${severity ?? ""} fix ${pullRequestUrl} · ${badge}`
          : `*Security audit ${input.taskInput.day}* · ${badge}`;

        const posted = await ctx.write.call(
          {
            service: "slack",
            name: "slack_post_message",
            organizationIntegrationId: slackConnectionId,
            arguments: { channel_id: securityChannelId, text: `${headline}\n${summary}` },
          },
          z.looseObject({ status: z.literal("sent") }),
          { effectKey: `security-audit:report:${input.taskInput.day}` },
        );
        if (posted.isErr()) {
          return err(posted.error);
        }

        return complete({ status, pullRequestUrl });
      },
    }),
  },
});
```

## How it works

1. **`checkOpenFix`** runs the GitHub CLI in the run's sandbox. It lists open pull requests on `sec-audit/` branches and prints them as one `JSON:` line, which code parses and checks.
2. **Code routes the run.** `transitions: ["finishFix", "auditAndFix"]` declares both destinations. An open fix goes to `finishFix`. Otherwise, the run goes to `auditAndFix`. This keeps the rule "finish before you start" in code, where it always holds.
3. **Two agents, one contract.** Both agent stages take `auditInput` and must submit `auditReport`. Because the shapes match, both send their result to the same `postReport` stage.
4. **`sharedRules`** are appended to both agents' instructions: defensive review only, a failing test before the fix, and no merges.
5. **`postReport`** posts one message with the day, the severity, the pull request, and the CI status. The effect key is the day, so each day posts once.

## Test it

The fixtures answer the sandbox call and check the routing. Neither fixture has `expectedOutput`, because the entry stage returns `next()`:

```json title="fixtures.json"
[
  {
    "name": "starts a new audit when no fix is open",
    "subscriptionId": "everyMorning",
    "payload": {
      "scheduledAt": "2026-11-05T13:00:00.000Z"
    },
    "toolResponses": [
      {
        "request": {
          "service": "managed-sandbox",
          "name": "exec_command",
          "arguments": {
            "command": "\ntoken_env=$(printf %s \"$TYPE_GITHUB_CONNECTIONS\" | jq -er 'first(.[] | select(.fullName == \"acme/project\") | .tokenEnv)') || { echo \"No GitHub connection covers acme/project\" >&2; exit 1; }\nfixes=$(GH_TOKEN=$(printenv \"$token_env\") gh api 'repos/acme/project/pulls?state=open&per_page=100' --jq '[.[] | select(.head.ref | startswith(\"sec-audit/\")) | {number, url: .html_url}]') || exit 1\nprintf 'JSON:%s\\n' \"$fixes\"\n"
          }
        },
        "response": {
          "content": [
            {
              "type": "text",
              "text": "JSON:[]"
            }
          ]
        }
      }
    ]
  },
  {
    "name": "finishes an open fix first",
    "subscriptionId": "everyMorning",
    "payload": {
      "scheduledAt": "2026-11-05T13:00:00.000Z"
    },
    "toolResponses": [
      {
        "request": {
          "service": "managed-sandbox",
          "name": "exec_command",
          "arguments": {
            "command": "\ntoken_env=$(printf %s \"$TYPE_GITHUB_CONNECTIONS\" | jq -er 'first(.[] | select(.fullName == \"acme/project\") | .tokenEnv)') || { echo \"No GitHub connection covers acme/project\" >&2; exit 1; }\nfixes=$(GH_TOKEN=$(printenv \"$token_env\") gh api 'repos/acme/project/pulls?state=open&per_page=100' --jq '[.[] | select(.head.ref | startswith(\"sec-audit/\")) | {number, url: .html_url}]') || exit 1\nprintf 'JSON:%s\\n' \"$fixes\"\n"
          }
        },
        "response": {
          "content": [
            {
              "type": "text",
              "text": "JSON:[{\"number\":412,\"url\":\"https://github.com/acme/project/pull/412\"}]"
            }
          ]
        }
      }
    ]
  }
]
```

## Make it yours

| Value | Replace with |
| --- | --- |
| `acme/project` | Your repository. |
| `octocat` | The GitHub login of the person who reviews security fixes. |
| `orgint_slack`, `C0123456789` | Your Slack connection and security channel. |
| `security-audit` | The handle of the audit skill in your Space. |
| `0 5 * * *` | When the audit runs. Agent stages can work for a long time, so run it before the workday. |

## Related

- [Use the sandbox](https://docs.type.com/automations/sandbox/index.md): run the GitHub CLI and parse its output.
- [Use skills](https://docs.type.com/automations/skills/index.md): keep the audit method in a skill.
- [Agent stages](https://docs.type.com/automations/agent-handoff/index.md#branch-on-the-result): route a run between stages.
