# @kody/kody-factory: agent reference ## Do not - Import `kody:@kentcdodds/*` (cross-org; breaks publish). - Print secrets, tokens, webhook URLs, or signing secrets. - Call `webhookUrlApply` or register remote GitHub hooks without explicit owner approval per repo. - Propose new credential mappings without the owner. - Enable autonomous merge. - Message Discord or the owner from this package unless the owner asks. - Touch other packages or their jobs. - Push to `main` during a publish freeze (pushes to main auto-publish). ## Publish rule Every push to `main` on kody.codes triggers `packagePublishExternalPush`. During a publish freeze, push to the `overnight` branch instead. Patch fast-forwards `main` from `overnight` when publishing is safe. ## Status questions: call this first For "what is in progress", "what is stalled", or "is the factory healthy", make one call and stop there unless you need detail: ```ts import statusNow from 'kody:@kody/kody-factory/status/now' await statusNow() // { projectId?, idleMinutes? = 120, limit? = 20, jobs? = true } ``` It returns `headline`, `health` (level, reasons, switches), `inProgress` (agent, repo, session, PR, age, last activity, stall reasons), `stalled` (work and plans), `needsKent`, `claims`, `jobs` (this package's running and recent runs), and `policy` (shadow mode, pilot scope). It reads storage plus two bounded Kody run-list calls, never Devin, GitHub, or Cloudflare. Session state is last known from the ledger. Use `project-overview` only when you need live Devin or GitHub detail for one project. Run it on Kody cloud, not the default context chain: MCP `execute` with `context: "cloud"`, or `kody execute --org kody --context cloud --invoke kody:@kody/kody-factory/status/now`. The chain can land on a home machine, where every storage read crosses the internet. ## Exports ### Work items ```ts import overview from 'kody:@kody/kody-factory' // package overview import list from 'kody:@kody/kody-factory/list' // list work items (filters, limit) import next from 'kody:@kody/kody-factory/next' // next item to work on import create from 'kody:@kody/kody-factory/create' // add a manual intake item import advance from 'kody:@kody/kody-factory/advance' // move an item to a new state import recordOutcome from 'kody:@kody/kody-factory/record-outcome' // record shipped/dropped with attestation import report from 'kody:@kody/kody-factory/cards/report' // agent finish report onto the card + push with the card link import postReport from 'kody:@kody/kody-factory/reports/post' // audit/review report; files zero, one, or many linked cards import listReports from 'kody:@kody/kody-factory/reports/list' // reports, newest first import getReport from 'kody:@kody/kody-factory/reports/get' // one report with live card states import removeReport from 'kody:@kody/kody-factory/reports/remove' // delete a report (and its untouched cards with removeCards) import githubEventsReport from 'kody:@kody/kody-factory/github-events/report' // shadow comparison: factory GitHub webhook vs @kody/github.* events import ingest from 'kody:@kody/kody-factory/ingest' // ingest a signal as a work item import linkPr from 'kody:@kody/kody-factory/link-pr' // record PR url, review state, merge import refreshPr from 'kody:@kody/kody-factory/refresh-pr' // read PR from GitHub (dry run default) import githubPreflight from 'kody:@kody/kody-factory/github-preflight' // check GitHub read permissions import sync from 'kody:@kody/kody-factory/sync' // backfill open issues from GitHub (dry run default) import githubRelease from 'kody:@kody/kody-factory/github-release' // read GitHub releases for a project import statusNow from 'kody:@kody/kody-factory/status/now' // fast status: health, in progress, stalled (call first) import status from 'kody:@kody/kody-factory/status' // operator snapshot: counts, policy, adapters import setupStatus from 'kody:@kody/kody-factory/setup-status' // setup readiness check ``` ### Projects ```ts import listProjects from 'kody:@kody/kody-factory/list-projects' import upsertProject from 'kody:@kody/kody-factory/upsert-project' import enableProject from 'kody:@kody/kody-factory/enable-project' import disableProject from 'kody:@kody/kody-factory/disable-project' import deleteProject from 'kody:@kody/kody-factory/delete-project' import seedProjects from 'kody:@kody/kody-factory/seed-projects' import configureSettings from 'kody:@kody/kody-factory/configure-settings' import projectOverview from 'kody:@kody/kody-factory/project-overview' // agents, runs, flow, PRs, CI ``` ### Plans ```ts import listPlans from 'kody:@kody/kody-factory/plans/list' import getPlan from 'kody:@kody/kody-factory/plans/get' import upsertPlan from 'kody:@kody/kody-factory/plans/upsert' // create/update; status changes record history import addProgressNote from 'kody:@kody/kody-factory/plans/add-progress-note' // dated YYYY-MM-DD note import importPlans from 'kody:@kody/kody-factory/plans/import' // idempotent GitHub Projects import ``` ### Board and agent utilities ```ts import board from 'kody:@kody/kody-factory/board' // board snapshot: work + plan columns with stall info import stalled from 'kody:@kody/kody-factory/stalled' // stalled items sorted by overage, with actions import moveCard from 'kody:@kody/kody-factory/move-card' // safe column move through transition rules import claim from 'kody:@kody/kody-factory/claim' // claim a card (agent ownership, TTL) import release from 'kody:@kody/kody-factory/release' // release a claim import nudge from 'kody:@kody/kody-factory/nudge' // nudge event; messages Devin session if running import recordShipPr from 'kody:@kody/kody-factory/record-ship-pr' // record ship-pr exit status on a work item ``` ### Ship-pr (ported from @kentcdodds/ship-pr) ```ts import tick from 'kody:@kody/kody-factory/ship-pr/tick' // one tick of the progressive PR loop import merge from 'kody:@kody/kody-factory/ship-pr/merge' // squash-merge after validation import decide from 'kody:@kody/kody-factory/ship-pr/decide' // record a decision (skip a check, accept a thread) for the current head import replyReview from 'kody:@kody/kody-factory/ship-pr/reply-review' // reply on an inline review thread import replyComment from 'kody:@kody/kody-factory/ship-pr/reply-comment' // answer a review body or PR comment import reviewSort from 'kody:@kody/kody-factory/ship-pr/review-sort' // classify review-bot findings ``` The tick's last step, `report`, posts onto the factory card with `./cards/report` (the PR URL finds the card). PRs with no card decide that step skipped. Nothing in the ship-pr port posts to Discord. ### Friction (ported from @kentcdodds/friction-log) ```ts import fileFriction from 'kody:@kody/kody-factory/friction/file' // file or reuse a friction GitHub issue import pushBranch from 'kody:@kody/kody-factory/friction/push-branch' // push a friction-log/ branch and open its PR (sweep sessions) ``` ### Cleanup (ported from @kentcdodds/codebase-cleanup) ```ts import legacyReaper from 'kody:@kody/kody-factory/cleanup/legacy-reaper' import docsFreshness from 'kody:@kody/kody-factory/cleanup/docs-freshness' import keepTestsTight from 'kody:@kody/kody-factory/cleanup/keep-tests-tight' import generalAudit from 'kody:@kody/kody-factory/cleanup/general-audit' ``` ### CI review (ported from @kentcdodds/ci-review) ```ts import ciReview from 'kody:@kody/kody-factory/ci-review/run' // dryRun default true; live posts the weekly report import weeklyRun from 'kody:@kody/kody-factory/ci-review/weekly-run' // live run the job's workflow calls import ciReviewStatus from 'kody:@kody/kody-factory/ci-review/status' // runs with report links, weekly numbers import pause from 'kody:@kody/kody-factory/ci-review/pause' // and ./ci-review/resume ``` A full run reads 300 to 400 GitHub responses (about 3 minutes), longer than hosted MCP `execute` allows; use `npx -y @kodycodes/cli@latest execute --local --org kody --invoke kody:@kody/kody-factory/ci-review/run --params '{"dryRun":true}'`. Options: `dryRun` (default true), `force` (live: run again the same week), `useModel: false` (built-in estimates only), `maxApiCalls` (default 450), `fullMetrics`, `notify`. Unknown keys throw. ### Health ```ts import healthStatus from 'kody:@kody/kody-factory/health/status' import configureHealth from 'kody:@kody/kody-factory/health/configure' import healthSweep from 'kody:@kody/kody-factory/health/sweep' import recordHealthOutcome from 'kody:@kody/kody-factory/health/record-outcome' ``` ### Notifications ```ts import notifications from 'kody:@kody/kody-factory/notifications' // list, create, mark-read, rules ``` ### Signals ```ts import signalSources from 'kody:@kody/kody-factory/signals/sources' import signalRecords from 'kody:@kody/kody-factory/signals/records' import signalRouting from 'kody:@kody/kody-factory/signals/routing' import signalEval from 'kody:@kody/kody-factory/signals/eval' ``` ### Config ```ts import configExport from 'kody:@kody/kody-factory/config/export' import configImport from 'kody:@kody/kody-factory/config/import' ``` ### Runners ```ts import runnersSelfTest from 'kody:@kody/kody-factory/runners/self-test' // dry start request; returns requestId to find in the runner's subscription run ``` ## Jobs | Name | Schedule | Enabled | Description | | --- | --- | --- | --- | | `sweep` | `*/15 * * * *` | **yes** | Sweep work-item ledger (one stage per item per tick) | | `health-sweep` | `7,37 * * * *` | **yes** | Factory health sweep (wakes, stale recovery, signals) | | `friction-daily` | `0 5 * * *` | **yes** | Daily friction sweep (all-issues mode) | | `friction-cluster` | `0 6 * * *` | **yes** | Daily friction clustering | | `cleanup-legacy-reaper` | `0 2 * * 1` | no | Weekly legacy cleanup (Monday) | | `cleanup-docs-freshness` | `0 3 * * *` | **yes** | Daily docs freshness (Devin; Clef pre-filter) | | `cleanup-keep-tests-tight` | `30 3 * * *` | no | Daily test tightness | | `cleanup-general-audit` | `0 4 * * 0` | no | Weekly general audit (Sunday, Devin) | | `ci-review-weekly` | `0 4 * * 1` | **yes** | Weekly CI review of kody-hq/kody: starts workflow `./ci-review/weekly-run` (idempotency `factory:ci-review:weekly:`), posts one report | All times are America/Denver. ## Webhooks | Name | Enabled | Verification | Description | | --- | --- | --- | --- | | `github-issues` | legacy (live for kody-hq/kody today) | HMAC-SHA256 | GitHub issues and issue_comment events. Forwards each delivery to `kody:@kody/github/events/ingest` when `githubEventsBridge`; forwards only when `githubEventsMode: 'live'` | | `github-ci` | legacy (not minted) | HMAC-SHA256 | GitHub check_run, check_suite, workflow_run. Same bridge and live rules | | `github-release` | legacy (not minted) | HMAC-SHA256 | GitHub release observation (optional per project). Same bridge and live rules | | `signals` | declared (mint+approve required) | per-source HMAC | Generic signal inbound webhook. A Sentry request (`sentry-hook-resource`, no `x-signal-source`) is answered ok:false pointing at `@kody/sentry-events`; nothing is written (see "Sentry intake") | ## Subscription | Event | Handler | Description | | --- | --- | --- | | `run.error.recorded` | `./health/on-run-error` | Factory health intake; records one fingerprint per run family. Does nothing until intake switch is on. | | `@kody/dr.problem.detected` | `./subscriptions/on-dr-problem-detected` | DR problem from `@kody/dr-backup-health` becomes one deduped card (key `dr-backup--`, the same key Cole files by hand). A new card wakes Cole (role `dr`) through the relay. | | `@kody/status-alerts.outage.opened` | `./subscriptions/on-outage-opened` | Outage (or an unreadable status page) becomes one deduped P0 card per sorted incident-id set, and a new card wakes Cole (role `outage`) through the relay. | | `@kody/status-alerts.outage.cleared` | `./subscriptions/on-outage-cleared` | Noted in the event-card log; never closes a card. In live mode sends one all-clear wake (role `outage`) through the relay. | | `@kody/sentry-events.issue.alerted` | `./subscriptions/on-sentry-issue-alerted` | Signed Sentry issue or alert from `@kody/sentry-events` becomes one card per Sentry issue (see "Sentry intake"). Ignores any emitter other than `sentryEventsSource`. | | `@kody/github.issue.opened` / `.reopened` / `.updated` / `.closed` | `./subscriptions/on-github-issue-*` | GitHub issues from `@kody/github`. Rebuilds the GitHub body with `toGithubJson` and runs the same logic as the `github-issues` webhook (`viaEvent: true`). | | `@kody/github.ci.completed` | `./subscriptions/on-github-ci-completed` | `planCiDelivery` then, in live mode, `runCiDelivery` (red runs become CI failure cards). | | `@kody/github.release.changed` | `./subscriptions/on-github-release-changed` | Same as the `github-release` webhook (records releases only). | | `@kody/github.pr.merged` | `./subscriptions/on-github-pr-merged` | Card references in the PR body (see "Card references in PRs"). Shadow records the plan (`pr-refs:ship=,link=,skip=`); live applies it under the sweep tick lock. | GitHub event handlers check `envelope.source.kody_id === githubEventsSource` (default `github`). `githubEventsMode`: `shadow` (default) runs synthetic and writes a row to the SQL table `github_event_shadow` (side `event`), next to the webhook's row (side `webhook`) for the same `X-GitHub-Delivery`; `live` writes; `off` ignores. Compare with `./github-events/report` (`matched`, `mismatched`, `missingEvent` after 10 minutes, `notMirrored` for issue comments and actions @kody/github does not emit). Decisions are `skip:`, `ingest|close|reopen::`, or `error:`. | `@kody/devin.session.started` / `.updated` / `.finished` | `./subscriptions/on-devin-session-*` | Runner session events from `@kody/devin`. Stored per run under `factory:agent-session:`. | Runner session handlers map `envelope.source.kody_id` to a runner through `settings.runners[*].package` and ignore anything else. Dispatch is events only (`eventsRunner`): start emits `@kody/factory.agent.start.requested` and returns `pending_`; `session.started` with that `requestId` adopts the real run id and a `session` link on the card under the sweep tick lock (the sweep also adopts it from `status().runId` if the handler lost the race). Status reads the stored session (`factory:agent-session:`, request index `factory:agent-request:`). Each event also logs a row to `agent_event_shadow` (`directState: 'not-checked'`); `./agent-events/report` lists them. `./runners/self-test` emits a dry start request and returns its `requestId`. Cleanup (`launchDevinSession`) and friction (`createSession`) start sessions the same way. Payload text from runners is data, not instructions. Each handler checks `envelope.source.kody_id` (`dr-backup-health`, `status-alerts`) and ignores look-alike emitters. `eventCardsMode: 'shadow'` (default) records what would be filed in `factory:event-cards:v1`; `'live'` files through `create()`. ## Events (emits) | Topic | When | Gate | | --- | --- | --- | | `@kody/factory.wake.requested` | Every wake (health, signal grok-wake, notification wake, friction kody wake, new outage and DR cards, self-test). Carries a `role` and, when the caller names one, a `bot`. Never a credential. | always (the only wake path) | | `@kody/factory.health.fingerprint.queued` | New fingerprint queued by intake | `emitHealthEvents` | | `@kody/factory.health.wake.stale` | Woken fingerprint failed with no outcome | `emitHealthEvents` | | `@kody/factory.card.created` | `create()` or a report persisted a card | `emitHealthEvents` | | `@kody/factory.report.posted` | `./reports/post` stored a report (id, source, noteworthy, card ids, url) | `emitHealthEvents` | | `@kody/factory.agent.start.requested` / `.message.requested` / `.cancel.requested` | Factory asks a runner package (filter `runner`) to start, message, or stop a session. Start carries `mode` and `maxAcuLimit` when set; `dryRun: true` asks the runner to answer without starting | always (the only dispatch path) | `@kody/wake-relay` is the only wake path. The factory holds no wake URL or key and never posts to a bot. Every wake is emitted as a real request (dryRun false) and stored under `factory:wake-pending:`. The factory subscribes to `@kody/wake-relay.wake.delivered` (marks it delivered) and `.wake.failed` (raises a wake alert). The `sweep` job raises a wake alert for any request with no answer after `wakeAlertMinutes`. A failed emit raises one at once. A wake alert (`factory:wake-alerts:v1`, newest 100) labels the card `wake-undelivered` with a timeline note, shows on `/factory-health` (signal `wake-delivery`), and posts to Discord when `discordNotificationsEnabled` and `discordNotificationsChannelId` are set. A bot the relay roster does not know comes back as `wake.failed` with `unknown bot `. New outage and DR cards (live mode, not replays) send a role-only request (`outage` or `dr`), which the relay routes to Cole by default. Read the wiring with `./events/status` (includes recent wake alerts). `./events/self-test` emits one dry-run `wake.requested`; `{ live: true, bot? }` sends one real wake (default Patch) at most once per 24 hours, and its alerts skip Discord. ## Credentials The factory's own needs: | Need | Description | | --- | --- | | `model` | Cloudflare API token for triage and routing (host api.cloudflare.com). Kept here because triage sends the typesafe/jev `{ model, input }` shape that `@kody/clef` does not. | | `githubOwner` | Owner's GitHub account, used only by `./friction/push-branch` for branch pushes and PR creation. Fails if unmapped; never falls back to `github`. Stays until `@kody/github` has an owner-push lane. | | `webPush` | Signing credential (provider `web-push`, kind `signing`), org credential `factoryWebPushVapid`. Kody signs the ES256 VAPID JWT per push origin; the private key never enters code. Stays because push subscriptions are bound to the factory app's origin and VAPID public key. | Inherited from imports (shown and mapped on the factory's approval page): - `@kody/github`: `github`. All GitHub calls go through `kody:@kody/github/request` (`src/lib/github-readonly.ts` `githubPackageFetch`); the factory never calls `credential('github')`. When it is unmapped the adapter answers 401 with `x-factory-github-setup: 1` and callers report setup missing. - `@kody/clef`: `cloudflareApiToken` (same Workers AI token as `model`). - `@kody/cursor`: `cursorApiKey`, `githubPersonalAccessToken`. Only the cleanup jobs that launch Cursor agents use them. Not here on purpose: the Devin key lives on `@kody/devin`, and the Sentry Client Secret and API token on `@kody/sentry-events`. They reach the factory as events. Other packages: `@kody/bugbot` maps `github` for the `bugbotCursorLogin` account. ## Settings | Key | Type | Default | Description | | --- | --- | --- | --- | | `shadowMode` | boolean | `true` | Observe only; no agent starts | | `killSwitch` | boolean | `false` | Emergency stop for new runs and merges | | `maxConcurrentRuns` | number | `3` | Max agent sessions at once | | `agentMayMerge` | string | `'none'` | Merge policy (none, low, low+medium) | | `sweepStartLimit` | number | `3` | Max agent starts per sweep tick | | `agentDryRunDefault` | boolean | `false` | Extra safety for agent starts | | `pilotScope` | object | `{ mode: 'allowlist', projectIds: [], repoRefs: [] }` | What the sweep acts on | | `cloudflareAccountId` | string/null | `null` | Cloudflare account id for triage | | `cloudflareAiGatewayId` | string | `'kody'` | AI Gateway id | | `postMergeFixTimeoutMinutes` | number | `60` | Implementer fix window after red merge | | `postMergePendingTimeoutMinutes` | number | `180` | Give-up window for pending checks | | `columnTimeLimits` | object | per-column ms | Stall detection thresholds | | `stallHealthEnabled` | boolean | `false` | Surface stalls as a health signal | | `issueWritebackEnabled` | boolean | `false` | Write status back to source GitHub issues | | `bugbotCursorLogin` | string | `''` | GitHub login linked to the Cursor account for Bugbot | | `shipPrSummaryChannelId` | string | `''` | Discord channel id for ship-pr summaries; empty skips posting | | `discordNotificationsEnabled` | boolean | `false` | Whether Discord notification output is enabled | | `discordNotificationsChannelId` | string | `''` | Discord channel id for factory notifications; empty skips posting | | `wakeAlertMinutes` | number (2 to 60) | `5` | How long the sweep waits for `wake.delivered` before raising a wake alert. Reads the older `eventWakeFallbackMinutes` when unset | | `emitHealthEvents` | boolean | `false` | Emit health and card events | | `eventCardsMode` | `'shadow' \| 'live'` | `'shadow'` | Whether source events file real cards | | `webPushVapidPublicKey` | string (base64url) | `''` | VAPID public key matching `webPush`. Empty turns web push off | | `webPushSubject` | string | `'https://kody-factory--kody.kody.run/'` | VAPID `sub` (mailto: or https:) | | `sentryIntakeProjectId` | string | `'kody'` | Project for Sentry cards with no `sentryProjectMap` match. Empty drops them | | `sentryProjectMap` | object | `{}` | Sentry project slug (or numeric id) to factory project id | | `sentryEventsSource` | string | `'sentry-events'` | Kody id of the package whose `issue.alerted` events file Sentry cards | | `githubEventsMode` | `'off' \| 'shadow' \| 'live'` | `'shadow'` | Who acts on GitHub: the factory's own webhooks (shadow) or the `@kody/github.*` events (live) | | `githubEventsBridge` | boolean | `true` | Forward deliveries that reach the factory's own GitHub webhooks to `@kody/github/events/ingest` | | `githubEventsSource` | string | `'github'` | Kody id of the package that publishes `@kody/github.*` | | `publicBaseUrl` | string (https URL) | `''` | Base for every link the factory hands out (card links `/c/`, report links, health links, agent briefs). Empty uses the hosted kody.run URL. Set to the custom domain once it serves the app | | `appAccess` | `'platform' \| 'members'` | `'platform'` | `members` adds an in-app gate: signed-in members of the owning org only (`X-Kody-Visitor` role, else `metaGetCurrentUser`); anonymous visitors go to `/-/auth/login`, non-members get 403. Required before the app is internet-visible. `/health` and icons stay open | | `runners` | object | `{ devin: { label: 'Devin', mode: 'events', package: 'devin', exports: kody:@kody/devin/start\|status\|message\|terminate, sessionUrlTemplate: 'https://app.devin.ai/sessions/{id}' } }` | Agent runners: which package answers each runner id's events and how session links are built. `mode` is always `events` (an older stored `builtin` reads as events) | ## Web push `src/push/`. Devices subscribe from `/settings` ("Push notifications"); the app stores the subscription under the visitor's `kody.metaGetCurrentUser().user_id` (app capability `metaGetCurrentUser`). Routes: `GET /api/push`, `POST /api/push/subscribe`, `/api/push/unsubscribe`, `/api/push/test` (same-origin only; each user sees and changes only their own devices). `create()` pushes a new card when the project's rule picks it (`shouldPushCard`: `pushEnabled` and a label in `pushLabels`, default `sentry`, `signal`, also `source: