From a79fe5d9839cb86a3b1500e0b101bcd0b8beed1a Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 16:11:52 +0000 Subject: [PATCH 1/5] stewards: an ops steward kind that watches production and files tickets (BB-9) A fourth binding kind, ops, bound to a watch target in the project file (ops.targets: [{ kind: "k8s-namespace", name }]) rather than a Linear or GitHub entity. It has no entity-state phases and nothing terminal: it lives while its target is listed, reports to the project steward, and looks every requeue-default (1h in the template) and at every sweep. Steward threads have no cluster access, so the plugin looks itself, from the bb-server pod, with the ServiceAccount bb-gate mounts there (kube.ts: GETs only, plus SelfSubjectAccessReviews for check). Each problem is named by a fingerprint, workload + container + error signature from the container's status (ops.ts), and a fingerprint map in the store points it at the Linear ticket the steward reports with steward_report { opsTickets }. A new problem, or one back after its ticket was resolved, wakes the steward at once; one still failing under its open ticket wakes it at the requeue, to comment there and file nothing new. A look that finds nothing wrong wakes nobody. The ops-watch playbook (may: read, file-ticket, comment, escalate) files one ticket per problem and raises one decision escalation to the project steward, whose wake says how to adopt (label and Todo, the ordinary path). ops.autoAdopt names priorities labelled on filing. bb stewards init writes the playbook; check validates ops and reports a target this server cannot read, or any write it holds there. Until the access exists, ops bindings wait and list says why. source-contract.ts is unchanged. Co-Authored-By: Claude Opus 5.5 --- plugins/stewards/DESIGN.md | 107 ++++++- plugins/stewards/README.md | 47 ++- plugins/stewards/config.test.ts | 66 ++++- plugins/stewards/config.ts | 80 ++++- plugins/stewards/fixtures.ts | 40 +++ plugins/stewards/kube.ts | 196 +++++++++++++ plugins/stewards/ops.test.ts | 111 +++++++ plugins/stewards/ops.ts | 338 ++++++++++++++++++++++ plugins/stewards/server.test.ts | 211 +++++++++++++- plugins/stewards/server.ts | 260 +++++++++++++++-- plugins/stewards/skills/stewards/SKILL.md | 45 ++- plugins/stewards/store.test.ts | 44 +++ plugins/stewards/store.ts | 90 +++++- plugins/stewards/templates.ts | 64 +++- plugins/stewards/wake.ts | 103 +++++++ 15 files changed, 1736 insertions(+), 66 deletions(-) create mode 100644 plugins/stewards/kube.ts create mode 100644 plugins/stewards/ops.test.ts create mode 100644 plugins/stewards/ops.ts diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 511341fd..a5a6496f 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -5,7 +5,7 @@ thread that manages it until it is done**. The thread, a **steward**, acts on the entity as you, according to a playbook the project keeps in `.bb`, and you steer it only from bb. -Status: built (steps 1–4 of the build order; the board is not, but the settings page lists every steward and its status). See +Status: built (steps 1–6 of the build order, ops stewards included). See [README.md](README.md) for how it runs and where it goes beyond this design. ## Scope @@ -35,8 +35,8 @@ existing bb-gate-hooks pipeline; workers for bounded tasks. | Term | Meaning | |---|---| -| **Entity** | A Linear issue or a GitHub pull request. | -| **Binding** | The durable record that a steward manages an entity. Kinds: `ticket`, `pr`, `review`. No TTL. | +| **Entity** | A Linear issue or a GitHub pull request; for an `ops` binding, a watch target (§18). | +| **Binding** | The durable record that a steward manages an entity. Kinds: `ticket`, `pr`, `review`, `ops`. No TTL. | | **Ticket steward** | The long-lived thread bound to a labelled ticket or pull request. Decides and delegates; does not write code. | | **Review steward** | The long-lived thread bound to a teammate's pull request. Reviews it, as you, for as long as it is open. | | **Project steward** | One per bb project. Reads every binding's status record, sets priorities and holds, routes escalations, writes the morning digest. | @@ -126,6 +126,7 @@ These were settled while designing; each changes what gets built. linear-tickets.md github-prs.md github-reviews.md + ops-watch.md only read when ops.targets lists something (§18) ``` ### `project.json` @@ -195,6 +196,7 @@ HEAD; a checkout with local commits is left as it is and read as it is. | `ticket` | `bb-managed` added to an issue in a listed Linear team | `linear-tickets` | | `pr` | `bb-managed` added to a pull request in a repo from `repos.json` not in `github.exclude` | `github-prs` | | `review` | a non-draft pull request, authored by someone other than you, opened or marked ready in a repo from `repos.json` not in `github.exclude` | `github-reviews` | +| `ops` | a target listed in the project file's `ops.targets` (§18) | `ops-watch` | - The plugin hears triggers through bb-gate-hooks `team` and `repo` leases, which already exist. The nightly pass re-lists labelled tickets and open @@ -694,6 +696,92 @@ plugins' contract before stewards uses them, bb-plugins before bb-gate. 4. **Reviews.** Review bindings, review workers. 5. **Board.** Built: the Stewards page, the question record (§12), and the digest assembled from records. +6. **Ops.** Built in this plugin (§18). It reads only what bb-gate grants the + server, so the read-only cluster access in `bb-gate` lands first; until + it does, ops bindings wait and `bb stewards check` says why. + +## 18. Ops stewards + +Every other kind manages work that already exists as a ticket or a pull +request. Nothing watched production, so operational problems were noticed by +a person or not at all. An `ops` binding watches a **target** and turns what +goes wrong there into Linear tickets for the project steward to adopt. + +```jsonc +"ops": { + "targets": [{ "kind": "k8s-namespace", "name": "bb-gate-production" }], + "team": "BB", // where tickets are filed; the first linear.teams entry when left out + "autoAdopt": ["urgent"] // priorities labelled when filed, without asking; empty by default +} +``` + +- **The entity is the target.** One binding per target, keyed + `k8s-namespace/`, with the source `ops`: there is no source plugin + behind it, and `source-contract.ts` does not change. It has no phases + keyed on entity state and no terminal state. It lives while the project + file lists its target: taken out, the binding ends (`unconfigured`) and + its thread is archived; put back, the same binding and thread resume. + `bb stewards detach` ends it until the target is taken out and put back, + as a ticket stays detached until its label is. It reports to the project + steward and has no workers. On the Stewards page it is grouped as + `watch`; in `bb stewards list` it shows when it last looked and how many + problems are failing. +- **The plugin looks; the steward judges.** Steward threads run on a + developer's machine with no cluster access, so the plugin reads the + target itself, from the bb-server pod, with the ServiceAccount bb-gate + mounts there (`kube.ts`): pods, Warning events, Deployments, and the last + log lines of a failing container where `pods/log` is granted, with + obvious credentials redacted. A look happens at every sweep and requeue. + It is the ops binding's snapshot (`bindings.ops_look`), and the wake + carries it. +- **Fingerprints.** A problem is named by its target, its workload (a + Deployment's pods share it whatever their generated names, so a rollout + or a second replica is the same problem), its container, and an error + signature from the container's status: `CrashLoopBackOff::`, `ImagePullBackOff`, `Restarted:OOMKilled:137`, `Failed:Evicted`, + `Unschedulable`, `NotReady` (a running pod unready for ten minutes). Log + text is evidence, never part of the name: it changes on every line. +- **The fingerprint map** (`ops_fingerprints`) holds, per project, each + fingerprint ever seen and the Linear ticket it is tracked under. The + steward reports what it did in `steward_report { opsTickets: [{ + fingerprint, ticket, did: filed | commented | reopened }] }`, and the + plugin records it. Each look classifies its findings against the map, and + reads each ticket's state through linear's `sourceSnapshot`: + - **new** — no ticket. Worth a turn at once. + - **recurring** — its ticket is open, or cannot be read (a comment on a + closed ticket does less harm than a duplicate). Worth a turn only at the + requeue, so a crash loop is one comment per `requeue-default`, and + never a second ticket. + - **returned** — its ticket was Done or Canceled and the problem is back. + Worth a turn at once. The playbook's `## Returned` section decides + between reopening and filing anew; the default comments on a ticket + closed within two weeks and escalates a reopen, and otherwise files a new + ticket linking the old one. + A look that finds nothing failing wakes nobody: the binding's next look + is a `requeue-default` away, and its last report stands. A nightly pass + turn still comes. +- **Triage is the project steward's.** The steward files one ticket per new + problem — pod, since when, the evidence, a diagnosis, a priority, and the + fingerprint on a line of its own — and raises one `decision` escalation + for the tickets of the turn ("Filed BB-N (high): …. Recommend adopting."). + The project steward adopts by adding the label and moving the ticket to + Todo, the ordinary path, and the team lease brings a ticket steward; or + declines with a reason. `ops.autoAdopt` names priorities the ops steward + labels itself when filing, without escalating. +- **`may` is `[read, file-ticket, comment, escalate]`**, and like every + `may` list it is advisory (§11). The wall is RBAC: the ServiceAccount + holds get, list and watch on pods, events and deployments, and + `pods/log` only where no developer's backend runs; nothing mutating. The + plugin itself only issues GETs, plus SelfSubjectAccessReviews for + `check`, which change nothing. +- **`bb stewards check`** validates `ops` (namespace names, duplicates, + that the team is one of `linear.teams`), then asks the API server, for + each target, whether this server can list its pods, events and + deployments and read its logs. A target it cannot read is a problem, as is + any write the account holds there. +- **Before the access exists** (no token mounted, or a 403), the binding is + made but its steward is not spawned or woken; `bb stewards list` shows + `cannot read the target`, and the first look that succeeds wakes it. ## Known limits @@ -709,6 +797,19 @@ plugins' contract before stewards uses them, bb-plugins before bb-gate. through bb-gate-hooks, and the deploy in the snapshot) would be new work in three repos. Until then, a playbook that wants a deploy watched has the steward follow through (§5) while a worker watches and verifies it. +- **One server watches production.** An ops binding runs on the server of + the developer who runs the project's stewards, the only one bb-gate gives + the ServiceAccount, like everything else here (one developer per + project). Nothing looks while that server is down, and in particular + during bb-gate's 03:00–05:00 US Eastern quiet window, when staged updates + restart servers: a crash in that window is seen at the first look after. + Nothing pages anyone either: this is periodic looks, not alerting. +- **Logs are partial.** In `bb-gate-production`, where developers' own + backends run, RBAC cannot grant `pods/log` for some pods only, so there + are no logs: diagnosis is from status and events. Healthy pods' logs are + never scanned, so an error that does not crash, restart or unready a pod + goes unseen. Push sources (Sentry, alerts through bb-gate-hooks) would + cover that, and are separate work. - **Comments and the team lease.** bb-gate-hooks does not always know a Linear comment's team, so a team lease alone misses some comments. That is why every binding also holds an issue lease for its own entity (§16). diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index d563e072..09a5dc0a 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -1,7 +1,8 @@ # Stewards Give a Linear ticket or a GitHub pull request **a long-lived thread that -manages it until it is done**. The thread, a **steward**, acts on the entity +manages it until it is done**, and production a thread that watches it and +files what goes wrong. The thread, a **steward**, acts on the entity as you, by a playbook the project keeps in `.bb`, and you steer it only from bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. @@ -17,6 +18,24 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. on bithub that was 88 of the project steward's 96 turns. A project's stewards share one sidebar section, named after the project, with each steward's workers nested under it; see DESIGN.md §15. +- **Ops stewards.** Each target in the project file's `ops.targets` (a + Kubernetes namespace) gets an `ops` steward, reporting to the project + steward, for as long as it is listed. The plugin looks at the target from + the bb-server pod with the ServiceAccount bb-gate mounts there + ([kube.ts](kube.ts)): pods, Warning events, Deployments, and a failing + container's last log lines where `pods/log` is granted. It names each + problem by a fingerprint (workload, container, error signature; + [ops.ts](ops.ts)) and keeps a fingerprint → Linear ticket map. A new + problem, or one back after its ticket was resolved, wakes the steward at + once; one still failing under its open ticket wakes it at the requeue + (`requeue-default`, 1h in the template), to comment there and file + nothing new. A look that finds nothing wrong wakes nobody. The steward + files one ticket per problem and escalates a `decision` to the project + steward ("Filed BB-N (high), recommend adopting"); the project steward + adopts with the label and Todo, the ordinary path. It never changes the + cluster: its playbook allows reading, filing, commenting and escalating, + and RBAC allows only reads. Until the server can read a target, its + binding waits and `bb stewards check` says why. DESIGN.md §18. - **The reconcile loop.** linear and github-watcher hold bb-gate-hooks leases for the project's teams and repos and for every bound entity, and ring this plugin on a doorbell. A ring is debounced, the entity is snapshotted, compared with @@ -127,6 +146,7 @@ stewards/ linear-tickets.md front matter + one ## section per phase github-prs.md github-reviews.md + ops-watch.md no phases; ## New, ## Recurring and ## Returned sections ``` `bb stewards init` writes starting points ([templates.ts](templates.ts)); @@ -134,11 +154,17 @@ stewards/ fails to parse is reported and bindings keep running under the last good version. Project file fields beyond the design: `nightly.until`, `nightly.max`, `playbooks` (which playbook governs each kind), -`reviews.enabled`, `adoption.perPass`, and `bigDecisions` (what reaches you; -defaults in [config.ts](config.ts)). - -Playbook front matter: `name`, `kind` (`ticket`, `pr`, `review`), `source`, -`phases` (state → `{ stage, stuck }`), `terminal`, `ready` (`checklist`, +`reviews.enabled`, `adoption.perPass`, `bigDecisions` (what reaches you; +defaults in [config.ts](config.ts)), and `ops`: `targets` (`{ kind: +"k8s-namespace", name }`, at most ten), `team` (where tickets are filed; the +first of `linear.teams` by default, and it must be one of them) and +`autoAdopt` (Linear priorities, `urgent`, `high`, `medium`, `low`, whose +tickets the ops steward labels for a steward itself when it files them). +`ops-watch.md` is read only when `ops.targets` lists something. + +Playbook front matter: `name`, `kind` (`ticket`, `pr`, `review`, `ops`), +`source` (`linear`, `github`, or `k8s` for `ops`), `phases` (state → `{ stage, +stuck }`; none for `ops`), `terminal` (at least one; none for `ops`), `ready` (`checklist`, `substantial`, `approval: project` (default), `me` or `{ linear-state: … }`), `promote`, `may` (policy stated in every wake), `models` (`steward`, `worker` as `provider/model/level`; `claude` means `claude-code`; the model may hold @@ -159,7 +185,9 @@ None beyond the playbook's word. A steward acts with the user's credentials and a shell; its `may` list and the ready gate are stated in every wake, and everything it writes is signed with its thread, so what it did is visible afterwards. The runaway guard is the one hard stop. GitHub writes go through -`gh`; there are no write tools to check. +`gh`; there are no write tools to check. Ops stewards are the exception +where a wall exists: the cluster access bb-gate grants is read-only, and +`bb stewards check` reports any write it finds. ## The contract with linear and github-watcher @@ -180,4 +208,7 @@ bb plugin build Deployment needs this directory added to bb-gate's `docker/bb-server/Dockerfile` (the sparse checkout, the `mv`, and `BB_PLUGIN_DIRS`), and multi-repo, linear and github-watcher at versions that serve -the contract. +the contract. Ops stewards need bb-gate to mount a read-only ServiceAccount +into the backend of the developer who runs them, at the standard path +(`/var/run/secrets/kubernetes.io/serviceaccount`: `token` and `ca.crt`); +the plugin calls `https://kubernetes.default.svc`. diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 644599dd..a826b7a9 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { isTerminal, modelSpecSchema, parsePlaybook, parseProjectFile, phaseInstructions, phaseOf, playbookStates } from "./config.js"; -import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, projectFileTemplate } from "./templates.js"; +import { isTerminal, opsTeam, usesKind, modelSpecSchema, parsePlaybook, parseProjectFile, phaseInstructions, phaseOf, playbookStates } from "./config.js"; +import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, projectFileTemplate } from "./templates.js"; describe("the project file", () => { it("parses the template with defaults filled in", () => { @@ -13,6 +13,8 @@ describe("the project file", () => { expect(parsed.value.projectSteward.model).toMatchObject({ providerId: "claude-code", model: "claude-opus-5-5", reasoningLevel: "high" }); expect(parsed.value.reviews.enabled).toBe(true); expect(parsed.value.github.exclude).toEqual([]); + expect(parsed.value.ops).toEqual({ targets: [], autoAdopt: [] }); + expect(usesKind(parsed.value, "ops")).toBe(false); }); it("names the file and the field in errors", () => { @@ -27,9 +29,44 @@ describe("the project file", () => { }); }); +describe("ops in the project file", () => { + const file = (ops: unknown, teams = ["ENG", "OPS"]) => parseProjectFile(JSON.stringify({ version: 1, linear: { teams }, ops })); + const error = (ops: unknown, teams?: string[]) => { + const r = file(ops, teams); + if (r.ok) expect.fail(`accepted ${JSON.stringify(ops)}`); + return r.error; + }; + + it("takes namespace targets, a team and the priorities to adopt at once", () => { + const r = file({ targets: [{ kind: "k8s-namespace", name: "bb-gate-production" }, { kind: "k8s-namespace", name: "devbox-production" }], team: "ops", autoAdopt: ["urgent"] }); + if (!r.ok) throw new Error(r.error); + expect(r.value.ops).toEqual({ targets: [{ kind: "k8s-namespace", name: "bb-gate-production" }, { kind: "k8s-namespace", name: "devbox-production" }], team: "OPS", autoAdopt: ["urgent"] }); + expect(usesKind(r.value, "ops")).toBe(true); + expect(opsTeam(r.value)).toBe("OPS"); + }); + + it("files in the first Linear team when no team is named", () => { + const r = file({ targets: [{ kind: "k8s-namespace", name: "prod" }] }); + expect(r.ok && opsTeam(r.value)).toBe("ENG"); + expect(r.ok && r.value.ops.autoAdopt).toEqual([]); + }); + + it("refuses what would watch nothing or file where nobody stewards", () => { + expect(error({ targets: [{ kind: "k8s-namespace", name: "Prod_1" }] })).toMatch(/ops\.targets\.0\.name: a namespace name/u); + expect(error({ targets: [{ kind: "pod", name: "prod" }] })).toMatch(/ops\.targets\.0\.kind/u); + expect(error({ targets: [{ kind: "k8s-namespace", name: "prod" }, { kind: "k8s-namespace", name: "prod" }] })).toMatch(/ops\.targets\.1: k8s-namespace\/prod is listed twice/u); + expect(error({ targets: [{ kind: "k8s-namespace", name: "prod" }], team: "SALES" })).toMatch(/ops\.team: SALES is not one of linear\.teams/u); + expect(error({ targets: [{ kind: "k8s-namespace", name: "prod" }] }, [])).toMatch(/ops needs a Linear team/u); + expect(error({ targets: [], autoAdopt: ["critical"] })).toMatch(/ops\.autoAdopt\.0/u); + expect(error({ targets: [], watch: true })).toMatch(/ops/u); + // No targets, no team needed. + expect(file({ targets: [] }, []).ok).toBe(true); + }); +}); + describe("playbooks", () => { - it("parses the three defaults", () => { - for (const [name, text] of [["linear-tickets", LINEAR_TICKETS], ["github-prs", GITHUB_PRS], ["github-reviews", GITHUB_REVIEWS]] as const) { + it("parses the four defaults", () => { + for (const [name, text] of [["linear-tickets", LINEAR_TICKETS], ["github-prs", GITHUB_PRS], ["github-reviews", GITHUB_REVIEWS], ["ops-watch", OPS_WATCH]] as const) { const parsed = parsePlaybook(text, name); expect(parsed.ok, parsed.ok ? "" : parsed.error).toBe(true); } @@ -67,6 +104,27 @@ describe("playbooks", () => { }); }); +describe("the ops playbook", () => { + it("has no phases or terminal states, sections for what a look found, and a may list that only reads, files, comments and escalates", () => { + const parsed = parsePlaybook(OPS_WATCH, "ops-watch"); + if (!parsed.ok) throw new Error(parsed.error); + const p = parsed.value; + expect(p).toMatchObject({ kind: "ops", source: "k8s", phases: {}, terminal: [], ready: null, may: ["read", "file-ticket", "comment", "escalate"], requeueDefaultMs: 3_600_000 }); + expect(phaseInstructions(p, "new")).toMatch(/File one ticket per problem/u); + expect(phaseInstructions(p, "recurring")).toMatch(/File nothing new/u); + expect(phaseInstructions(p, "returned")).toMatch(/reopened/u); + expect(p.general).toMatch(/Fingerprint: ``/u); + }); + + it("refuses entity state on an ops playbook, the wrong source, and a non-ops playbook with nothing terminal", () => { + const phased = OPS_WATCH.replace("may:", "phases:\n open: {}\nmay:"); + expect(parsePlaybook(phased, "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook has no phases/u) }); + expect(parsePlaybook(OPS_WATCH.replace("may:", "terminal: [Done]\nmay:"), "ops-watch")).toMatchObject({ ok: false }); + expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: linear"), "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook reads k8s/u) }); + expect(parsePlaybook(GITHUB_PRS.replace("terminal: [merged, closed]\n", ""), "github-prs")).toMatchObject({ ok: false, error: expect.stringMatching(/terminal: name at least one state/u) }); + }); +}); + describe("model specs", () => { it("takes a model id with slashes, and the level only when the last part names one", () => { const parse = (text: string) => modelSpecSchema.parse(text); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index ffbb198f..b6855c2c 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -7,6 +7,7 @@ import { createHash } from "node:crypto"; import { parse as parseYaml } from "yaml"; import { z } from "zod"; +import type { OpsTarget } from "./ops.js"; export const STEWARDS_DIR = "stewards"; export const PROJECT_FILE = `${STEWARDS_DIR}/project.json`; @@ -83,10 +84,10 @@ export const DEFAULT_BIG_DECISIONS = [ const clock = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/u, 'a time such as "01:00"'); -export const KINDS = ["ticket", "pr", "review"] as const; +export const KINDS = ["ticket", "pr", "review", "ops"] as const; export type BindingKind = (typeof KINDS)[number]; -export const DEFAULT_PLAYBOOKS: Record = { ticket: "linear-tickets", pr: "github-prs", review: "github-reviews" }; +export const DEFAULT_PLAYBOOKS: Record = { ticket: "linear-tickets", pr: "github-prs", review: "github-reviews", ops: "ops-watch" }; const playbookName = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/u, "a playbook name: lowercase letters, digits and dashes"); @@ -99,10 +100,22 @@ function validTimezone(tz: string): boolean { } } +const teamKey = z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*$/u, "a team key such as ENG").transform((s) => s.toUpperCase()); + +/** Linear's priorities, as `ops.autoAdopt` names them. */ +export const LINEAR_PRIORITIES = ["urgent", "high", "medium", "low"] as const; + +const opsTargetSchema = z + .object({ + kind: z.literal("k8s-namespace"), + name: z.string().trim().regex(/^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/u, "a namespace name such as bb-gate-production"), + }) + .strict(); + export const projectFileSchema = z .object({ version: z.literal(1), - linear: z.object({ teams: z.array(z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*$/u, "a team key such as ENG").transform((s) => s.toUpperCase())).max(50).default([]) }).strict().default({ teams: [] }), + linear: z.object({ teams: z.array(teamKey).max(50).default([]) }).strict().default({ teams: [] }), /** * GitHub repos are the project's repos.json; these are left out of it, * for repos in the workspace that stewards should not manage. @@ -122,7 +135,7 @@ export const projectFileSchema = z .default({ at: "01:00", timezone: "America/New_York", until: "02:45", max: 100 }), projectSteward: z.object({ model: modelSpecSchema.optional() }).strict().default({}), /** Which playbook governs each kind of binding. */ - playbooks: z.object({ ticket: playbookName.optional(), pr: playbookName.optional(), review: playbookName.optional() }).strict().default({}), + playbooks: z.object({ ticket: playbookName.optional(), pr: playbookName.optional(), review: playbookName.optional(), ops: playbookName.optional() }).strict().default({}), /** Reviews: on unless turned off. */ reviews: z.object({ enabled: z.boolean().default(true) }).strict().default({ enabled: true }), adoption: z.object({ perPass: z.number().int().min(1).max(100).default(10) }).strict().default({ perPass: 10 }), @@ -131,8 +144,35 @@ export const projectFileSchema = z * stewards and the project steward, from the project's own guidance. */ bigDecisions: z.array(z.string().trim().min(1).max(300)).max(30).default(DEFAULT_BIG_DECISIONS), + /** + * Production to watch: one ops binding per target, which files a Linear + * ticket for each problem it finds and escalates it to the project + * steward. `team` is where tickets are filed (the first of linear.teams + * when left out); `autoAdopt` names the priorities whose tickets are + * labelled for a steward when filed, without asking. + */ + ops: z + .object({ + targets: z.array(opsTargetSchema).max(10).default([]), + team: teamKey.optional(), + autoAdopt: z.array(z.enum(LINEAR_PRIORITIES)).max(4).default([]), + }) + .strict() + .default({ targets: [], autoAdopt: [] }), }) - .strict(); + .strict() + .superRefine((file, ctx) => { + const seen = new Set(); + file.ops.targets.forEach((t, i) => { + const key = `${t.kind}/${t.name}`; + if (seen.has(key)) ctx.addIssue({ code: "custom", path: ["ops", "targets", i], message: `${key} is listed twice` }); + seen.add(key); + }); + if (file.ops.targets.length === 0) return; + // A ticket filed outside the project's teams is never adopted, so the project steward could not act on it. + if (file.ops.team === undefined && file.linear.teams.length === 0) ctx.addIssue({ code: "custom", path: ["ops", "team"], message: "ops needs a Linear team to file tickets in: set ops.team or linear.teams" }); + if (file.ops.team !== undefined && !file.linear.teams.includes(file.ops.team)) ctx.addIssue({ code: "custom", path: ["ops", "team"], message: `${file.ops.team} is not one of linear.teams, so a ticket filed there would never be stewarded` }); + }); export type ProjectFile = z.infer; export type Parsed = { ok: true; value: T } | { ok: false; error: string }; @@ -154,6 +194,14 @@ export function parseProjectFile(text: string): Parsed { export const playbookNameFor = (project: ProjectFile, kind: BindingKind): string => project.playbooks[kind] ?? DEFAULT_PLAYBOOKS[kind]; +/** Whether a project uses a kind of binding at all: reviews can be turned off, and ops needs a target. */ +export const usesKind = (project: ProjectFile, kind: BindingKind): boolean => (kind === "review" ? project.reviews.enabled : kind === "ops" ? project.ops.targets.length > 0 : true); + +export const opsTargets = (project: ProjectFile): OpsTarget[] => project.ops.targets; + +/** The Linear team an ops steward files in. */ +export const opsTeam = (project: ProjectFile): string | null => project.ops.team ?? project.linear.teams[0] ?? null; + // ---- playbooks --------------------------------------------------------------------- export const STAGES = ["spec", "build", "review"] as const; @@ -185,13 +233,17 @@ export type ReadyConfig = z.infer; /** The default cap on follow-through: a deploy and its verification, with room to spare. */ export const DEFAULT_FOLLOW_THROUGH_MS = 6 * 3_600_000; +export const PLAYBOOK_SOURCES = ["linear", "github", "k8s"] as const; +const SOURCE_OF: Record = { ticket: "linear", pr: "github", review: "github", ops: "k8s" }; + export const frontMatterSchema = z .object({ name: playbookName, kind: z.enum(KINDS), - source: z.enum(["linear", "github"]), - phases: z.record(z.string().trim().min(1).max(100), phaseSchema.nullable().transform((p) => p ?? {})), - terminal: z.array(z.string().trim().min(1).max(100)).min(1), + /** Where the entity lives; an ops playbook watches k8s, and has no entity state. */ + source: z.enum(PLAYBOOK_SOURCES), + phases: z.record(z.string().trim().min(1).max(100), phaseSchema.nullable().transform((p) => p ?? {})).default({}), + terminal: z.array(z.string().trim().min(1).max(100)).default([]), ready: readySchema.optional(), promote: z.string().trim().max(1000).optional(), /** What the steward may do on the entity. Policy the wake states, not a wall. */ @@ -208,7 +260,7 @@ export const frontMatterSchema = z export type Playbook = { name: string; kind: BindingKind; - source: "linear" | "github"; + source: (typeof PLAYBOOK_SOURCES)[number]; phases: Record; terminal: string[]; ready: ReadyConfig | null; @@ -242,8 +294,14 @@ export function parsePlaybook(text: string, expectedName: string): Parsed 0 || fm.terminal.length > 0 || fm.ready !== undefined || fm.promote !== undefined) { + return { ok: false, error: `${file}: an ops playbook has no phases, terminal states, ready gate or promote rule: it watches a target, not an entity` }; + } + } else if (fm.terminal.length === 0) return { ok: false, error: `${file}: terminal: name at least one state that ends the binding` }; const lowerPhases = new Set(Object.keys(fm.phases).map((p) => p.toLowerCase())); const overlap = fm.terminal.filter((t) => lowerPhases.has(t.toLowerCase())); if (overlap.length > 0) return { ok: false, error: `${file}: ${overlap.join(", ")} cannot be both a phase and terminal` }; diff --git a/plugins/stewards/fixtures.ts b/plugins/stewards/fixtures.ts index 03026deb..dc0dc18d 100644 --- a/plugins/stewards/fixtures.ts +++ b/plugins/stewards/fixtures.ts @@ -57,3 +57,43 @@ export const comment = (over: Partial = {}): SnapshotComment => signedBy: null, ...over, }); + +/** A Deployment's pod as the Kubernetes API lists it, its one container in a crash loop. */ +export const crashingPod = (name = "bb-gate-router-6d4f9c7b8-x2k4q", over: { restarts?: number; exitCode?: number; finishedAt?: string } = {}) => ({ + metadata: { + name, + labels: { app: "bb-gate-router", "pod-template-hash": "6d4f9c7b8" }, + ownerReferences: [{ kind: "ReplicaSet", name: "bb-gate-router-6d4f9c7b8", controller: true }], + }, + status: { + phase: "Running", + conditions: [{ type: "Ready", status: "False", lastTransitionTime: "2026-10-14T14:00:00Z" }], + containerStatuses: [ + { + name: "router", + ready: false, + restartCount: over.restarts ?? 7, + state: { waiting: { reason: "CrashLoopBackOff", message: "back-off 5m0s restarting failed container" } }, + lastState: { terminated: { reason: "Error", exitCode: over.exitCode ?? 1, finishedAt: over.finishedAt ?? "2026-10-14T14:55:00Z" } }, + }, + ], + }, +}); + +export const healthyPod = (name = "bb-gate-hooks-7f8d9-abcde") => ({ + metadata: { name, labels: { "pod-template-hash": "7f8d9" }, ownerReferences: [{ kind: "ReplicaSet", name: "bb-gate-hooks-7f8d9", controller: true }] }, + status: { + phase: "Running", + conditions: [{ type: "Ready", status: "True", lastTransitionTime: "2026-10-14T10:00:00Z" }], + containerStatuses: [{ name: "hooks", ready: true, restartCount: 0, state: { running: { startedAt: "2026-10-14T10:00:00Z" } }, lastState: {} }], + }, +}); + +export const warningEvent = (pod: string, reason = "BackOff", message = "Back-off restarting failed container router") => ({ + involvedObject: { kind: "Pod", name: pod }, + type: "Warning", + reason, + message, + count: 12, + lastTimestamp: "2026-10-14T14:58:00Z", +}); diff --git a/plugins/stewards/kube.ts b/plugins/stewards/kube.ts new file mode 100644 index 00000000..3a946746 --- /dev/null +++ b/plugins/stewards/kube.ts @@ -0,0 +1,196 @@ +// The ops kind's eyes: read-only calls to the Kubernetes API from the +// bb-server pod, with the ServiceAccount bb-gate mounts into the backend of +// the developer who runs the project's ops steward. Steward threads run on a +// machine with no cluster access, so the plugin looks and the wake carries +// what it saw. +// +// Only GETs, plus SelfSubjectAccessReviews for `bb stewards check`, which +// ask the API server what the account may do and change nothing. RBAC is +// the wall (DESIGN.md §11); this file never builds a write. +import { readFileSync } from "node:fs"; +import https from "node:https"; +import { join } from "node:path"; +import { deploymentsOf, eventsOf, findingsOf, logTail, otherWarnings, podsOf, type OpsTarget, type RawLook } from "./ops.js"; + +export const SERVICE_ACCOUNT_DIR = "/var/run/secrets/kubernetes.io/serviceaccount"; +export const IN_CLUSTER_API = "https://kubernetes.default.svc"; +const TIMEOUT_MS = 15_000; +/** Logs are read for at most this many findings per look. */ +const LOGS_PER_LOOK = 5; + +/** What `bb stewards check` reports for one target. */ +export type OpsAccess = { + /** Set when nothing could be asked: no credentials, or the API server unreachable. */ + error: string | null; + /** Each read a look makes, and whether it works. */ + reads: Array<{ what: string; ok: boolean; detail: string | null }>; + /** Whether container logs may be read; null when the server could not say. */ + logs: boolean | null; + /** Writes the account holds there, which it should not. */ + mutating: string[]; +}; + +export interface OpsReader { + /** One look at a target. Throws when its pods cannot be listed: then there is nothing to look at. */ + look(target: OpsTarget, at: { now: number; since: number }): Promise; + access(target: OpsTarget): Promise; +} + +export class KubeError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + this.name = "KubeError"; + } +} + +/** The pod's mounted ServiceAccount, read on every call: projected tokens rotate. */ +function credentials(dir: string): { token: string; ca: string } { + try { + return { token: readFileSync(join(dir, "token"), "utf8").trim(), ca: readFileSync(join(dir, "ca.crt"), "utf8") }; + } catch { + throw new KubeError(0, `this server has no cluster access: no ServiceAccount token at ${dir} (bb-gate mounts one only into the backend of the developer who runs the project's ops steward)`); + } +} + +export function createKubeReader(opts: { dir?: string; apiUrl?: string } = {}): OpsReader { + const dir = opts.dir ?? SERVICE_ACCOUNT_DIR; + const api = new URL(opts.apiUrl ?? IN_CLUSTER_API); + + function call(method: "GET" | "POST", path: string, body?: unknown): Promise { + const { token, ca } = credentials(dir); + return new Promise((resolve, reject) => { + const payload = body === undefined ? undefined : JSON.stringify(body); + const req = https.request( + { + protocol: api.protocol, + hostname: api.hostname, + port: api.port === "" ? 443 : Number(api.port), + path, + method, + ca, + timeout: TIMEOUT_MS, + headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(payload === undefined ? {} : { "content-type": "application/json" }) }, + }, + (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + const status = res.statusCode ?? 0; + if (status >= 200 && status < 300) return resolve(text); + let message = text.slice(0, 300); + try { + message = String((JSON.parse(text) as { message?: unknown }).message ?? message); + } catch { + // not JSON: keep the text + } + reject(new KubeError(status, `${status}: ${message}`)); + }); + }, + ); + req.on("timeout", () => req.destroy(new KubeError(0, `the API server did not answer in ${TIMEOUT_MS / 1000}s`))); + req.on("error", (error) => reject(error instanceof KubeError ? error : new KubeError(0, error.message))); + if (payload !== undefined) req.write(payload); + req.end(); + }); + } + + const get = async (path: string): Promise => JSON.parse(await call("GET", path)) as unknown; + const ns = (t: OpsTarget) => encodeURIComponent(t.name); + const forbidden = (e: unknown) => e instanceof KubeError && (e.status === 401 || e.status === 403); + + async function can(namespace: string, verb: string, resource: string, extra: { group?: string; subresource?: string } = {}): Promise { + const out = JSON.parse( + await call("POST", "/apis/authorization.k8s.io/v1/selfsubjectaccessreviews", { + apiVersion: "authorization.k8s.io/v1", + kind: "SelfSubjectAccessReview", + spec: { resourceAttributes: { namespace, verb, resource, ...extra } }, + }), + ) as { status?: { allowed?: boolean } }; + return out.status?.allowed === true; + } + + return { + async look(target, at) { + const base = `/api/v1/namespaces/${ns(target)}`; + const pods = podsOf(await get(`${base}/pods`)); + const notes: string[] = []; + const optional = async (what: string, read: () => Promise, empty: T): Promise => { + try { + return await read(); + } catch (error) { + notes.push(`${what} could not be read (${error instanceof Error ? error.message : String(error)})`); + return empty; + } + }; + const events = await optional("Events", async () => eventsOf(await get(`${base}/events?limit=500`)), []); + const deployments = await optional("Deployments", async () => deploymentsOf(await get(`/apis/apps/v1/namespaces/${ns(target)}/deployments`)), []); + const sightings = findingsOf(target, pods, events, at); + let logs: RawLook["logs"] = "unneeded"; + for (const s of sightings.filter((x) => x.container !== null).slice(0, LOGS_PER_LOOK)) { + const container = s.container!.replace(/^init:/u, ""); + const path = (previous: boolean) => `${base}/pods/${encodeURIComponent(s.pods[0]!)}/log?container=${encodeURIComponent(container)}&tailLines=60${previous ? "&previous=true" : ""}`; + try { + let text: string; + try { + text = await call("GET", path(s.previous)); + } catch (error) { + // No previous run to read (it was never restarted, or was replaced): read the current one. + if (!s.previous || forbidden(error)) throw error; + s.previous = false; + text = await call("GET", path(false)); + } + s.logs = logTail(text); + logs = "read"; + } catch (error) { + if (forbidden(error)) { + logs = "not granted"; + break; + } + notes.push(`The logs of ${s.pods[0]}/${container} could not be read (${error instanceof Error ? error.message : String(error)})`); + } + } + const healthy = pods.filter((p) => p.phase === "Succeeded" || (p.phase === "Running" && p.ready)).length; + return { pods: pods.length, healthy, deployments, warnings: otherWarnings(events, sightings, at.since), logs, notes, sightings }; + }, + + async access(target) { + const reads: OpsAccess["reads"] = []; + const base = `/api/v1/namespaces/${ns(target)}`; + for (const [what, path] of [ + ["list pods", `${base}/pods?limit=1`], + ["list events", `${base}/events?limit=1`], + ["list deployments", `/apis/apps/v1/namespaces/${ns(target)}/deployments?limit=1`], + ] as const) { + try { + await call("GET", path); + reads.push({ what, ok: true, detail: null }); + } catch (error) { + if (error instanceof KubeError && error.status === 0) return { error: error.message, reads: [], logs: null, mutating: [] }; + reads.push({ what, ok: false, detail: error instanceof Error ? error.message : String(error) }); + } + } + let logs: boolean | null = null; + const mutating: string[] = []; + try { + logs = await can(target.name, "get", "pods", { subresource: "log" }); + const writes = [ + ["delete", "pods", ""], + ["create", "pods", ""], + ["patch", "deployments", "apps"], + ["update", "deployments", "apps"], + ["delete", "deployments", "apps"], + ] as const; + for (const [verb, resource, group] of writes) { + if (await can(target.name, verb, resource, group === "" ? {} : { group })) mutating.push(`${verb} ${resource}`); + } + } catch { + // The server would not answer access reviews; the reads above still say what works. + } + return { error: null, reads, logs, mutating }; + }, + }; +} diff --git a/plugins/stewards/ops.test.ts b/plugins/stewards/ops.test.ts new file mode 100644 index 00000000..1c0ef1cd --- /dev/null +++ b/plugins/stewards/ops.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vitest"; +import { crashingPod, healthyPod, warningEvent } from "./fixtures.js"; +import { classify, eventsOf, findingsOf, logTail, lookChanges, opsTargetKey, parseOpsTargetKey, podsOf, workloadOf, type OpsLook, type Sighting } from "./ops.js"; + +const target = { kind: "k8s-namespace", name: "bb-gate-production" } as const; +const now = Date.parse("2026-10-14T15:00:00Z"); +const at = { now, since: now - 3_600_000 }; +const look = (list: unknown[], events: unknown[] = []) => findingsOf(target, podsOf({ items: list }), eventsOf({ items: events }), at); + +describe("targets", () => { + it("round-trip through their binding key", () => { + expect(opsTargetKey(target)).toBe("k8s-namespace/bb-gate-production"); + expect(parseOpsTargetKey("k8s-namespace/bb-gate-production")).toEqual(target); + expect(parseOpsTargetKey("acme/web#3")).toBeNull(); + }); +}); + +describe("a look's findings", () => { + it("names a crash loop by workload, container and exit, the same whatever the pod is called", () => { + const [first] = look([crashingPod()], [warningEvent("bb-gate-router-6d4f9c7b8-x2k4q")]); + expect(first).toMatchObject({ + fingerprint: "k8s-namespace/bb-gate-production/bb-gate-router/router#CrashLoopBackOff:Error:1", + workload: "bb-gate-router", + pods: ["bb-gate-router-6d4f9c7b8-x2k4q"], + container: "router", + restarts: 7, + previous: true, + summary: expect.stringMatching(/router is in CrashLoopBackOff \(last run: Error, exit 1\), 7 restarts/u), + }); + expect(first!.events).toEqual(["2026-10-14T14:58:00Z Pod/bb-gate-router-6d4f9c7b8-x2k4q BackOff ×12: Back-off restarting failed container router"]); + // A rollout's new pod, or a second replica, is the same problem. + const replicas = look([crashingPod("bb-gate-router-6d4f9c7b8-aaaaa"), crashingPod("bb-gate-router-6d4f9c7b8-bbbbb", { restarts: 9 })]); + expect(replicas).toHaveLength(1); + expect(replicas[0]).toMatchObject({ fingerprint: first!.fingerprint, pods: ["bb-gate-router-6d4f9c7b8-aaaaa", "bb-gate-router-6d4f9c7b8-bbbbb"], restarts: 9 }); + // A different exit is a different problem. + expect(look([crashingPod(undefined, { exitCode: 137 })])[0]!.fingerprint).toMatch(/CrashLoopBackOff:Error:137$/u); + }); + + it("finds nothing in healthy pods, and a restart only once, at the look after it", () => { + expect(look([healthyPod()])).toEqual([]); + const restarted = healthyPod(); + restarted.status.containerStatuses[0]!.lastState = { terminated: { reason: "OOMKilled", exitCode: 137, finishedAt: "2026-10-14T14:30:00Z" } } as never; + expect(look([restarted])).toMatchObject([{ signature: "Restarted:OOMKilled:137", workload: "bb-gate-hooks" }]); + // Before the last look: already seen. + expect(findingsOf(target, podsOf({ items: [restarted] }), [], { now, since: Date.parse("2026-10-14T14:45:00Z") })).toEqual([]); + }); + + it("finds failed, unschedulable and long-unready pods, and lets a fresh rollout settle", () => { + const failed = { metadata: { name: "job-x" }, status: { phase: "Failed", reason: "Evicted", message: "low on memory" } }; + const pending = (since: string) => ({ metadata: { name: "web-0", ownerReferences: [{ kind: "StatefulSet", name: "web", controller: true }] }, status: { phase: "Pending", conditions: [{ type: "PodScheduled", status: "False", reason: "Unschedulable", message: "0/3 nodes are available", lastTransitionTime: since }] } }); + const unready = (since: string) => ({ ...healthyPod("api-5c-zzzzz"), status: { ...healthyPod().status, conditions: [{ type: "Ready", status: "False", lastTransitionTime: since }] } }); + expect(look([failed]).map((f) => f.signature)).toEqual(["Failed:Evicted"]); + expect(look([pending("2026-10-14T14:00:00Z")])).toMatchObject([{ signature: "Unschedulable", workload: "web", container: null }]); + expect(look([unready("2026-10-14T14:00:00Z")]).map((f) => f.signature)).toEqual(["NotReady"]); + expect(look([pending("2026-10-14T14:58:00Z"), unready("2026-10-14T14:58:00Z")])).toEqual([]); + }); + + it("works out a pod's workload from its owner", () => { + expect(workloadOf(crashingPod())).toBe("bb-gate-router"); + expect(workloadOf({ metadata: { name: "lonely" } })).toBe("lonely"); + expect(workloadOf({ metadata: { name: "x-1", ownerReferences: [{ kind: "DaemonSet", name: "x", controller: true }] } })).toBe("x"); + }); +}); + +describe("log tails", () => { + it("keep the last lines, clipped, with credentials redacted", () => { + const text = ["boot", "Authorization: Bearer eyJhbGciOi.secret", "token=abc123 next", "", `${"x".repeat(500)}`, "panic: boom"].join("\n"); + const tail = logTail(text, 4); + expect(tail).toHaveLength(4); + expect(tail[0]).toBe("Authorization: Bearer [redacted]"); + expect(tail[1]).toBe("token=[redacted] next"); + expect(tail[2]!.length).toBe(401); + expect(tail.at(-1)).toBe("panic: boom"); + }); +}); + +describe("the fingerprint map", () => { + const sighting = look([crashingPod()])[0]!; + const row = (ticketKey: string | null) => new Map([[sighting.fingerprint, { fingerprint: sighting.fingerprint, ticketKey, firstSeenAt: 1_000, lastCommentedAt: ticketKey === null ? null : 2_000 }]]); + + it("classifies a problem as new, recurring under its open ticket, or returned after its ticket was resolved", () => { + expect(classify([sighting], new Map(), new Map(), now)[0]).toMatchObject({ class: "new", ticket: null, firstSeenAt: now }); + expect(classify([sighting], row(null), new Map(), now)[0]).toMatchObject({ class: "new", firstSeenAt: 1_000 }); + expect(classify([sighting], row("OPS-5"), new Map([["OPS-5", { state: "In Progress", stateType: "started" }]]), now)[0]).toMatchObject({ class: "recurring", ticket: "OPS-5", ticketState: "In Progress", lastCommentedAt: 2_000 }); + expect(classify([sighting], row("OPS-5"), new Map([["OPS-5", { state: "Done", stateType: "completed" }]]), now)[0]).toMatchObject({ class: "returned", ticketState: "Done" }); + expect(classify([sighting], row("OPS-5"), new Map([["OPS-5", { state: "Canceled", stateType: "canceled" }]]), now)[0]!.class).toBe("returned"); + // A ticket that cannot be read is taken as open: a comment does less harm than a duplicate. + expect(classify([sighting], row("OPS-5"), new Map([["OPS-5", null]]), now)[0]).toMatchObject({ class: "recurring", ticketState: null }); + }); + + it("makes a new or returned problem worth a turn at once, and a recurring one only at the requeue", () => { + const base: Omit = { at: now, target: "k8s-namespace/bb-gate-production", error: null, pods: 2, healthy: 1, deployments: [], warnings: [], logs: "read", notes: [] }; + const lookWith = (findings: ReturnType): OpsLook => ({ ...base, findings }); + const as = (s: Sighting, rows: ReturnType, state: "started" | "completed" | null = null) => classify([s], rows, new Map([["OPS-5", state === null ? null : { state, stateType: state }]]), now); + const fresh = lookWith(as(sighting, new Map())); + expect(lookChanges(null, fresh)).toEqual([{ text: expect.stringMatching(/^New problem: k8s-namespace\/bb-gate-production\/bb-gate-router\/router#/u), actionable: true }]); + // Still unfiled at the next look: not news again. + expect(lookChanges(fresh, fresh)).toEqual([]); + const filed = lookWith(as(sighting, row("OPS-5"), "started")); + expect(lookChanges(fresh, filed)).toEqual([]); + expect(lookChanges(filed, filed)).toEqual([]); + const back = lookWith(as(sighting, row("OPS-5"), "completed")); + expect(lookChanges(filed, back)).toEqual([{ text: expect.stringMatching(/^Back after OPS-5 was resolved \(completed\)/u), actionable: true }]); + expect(lookChanges(filed, lookWith([]))).toEqual([{ text: expect.stringMatching(/^No longer seen: .* \(OPS-5\)$/u), actionable: false }]); + // An unreadable target is said once, and its recovery is quiet. + const broken: OpsLook = { ...lookWith([]), error: "403: forbidden" }; + expect(lookChanges(filed, broken)).toEqual([{ text: "Cannot read k8s-namespace/bb-gate-production: 403: forbidden", actionable: false }]); + expect(lookChanges(broken, broken)).toEqual([]); + expect(lookChanges(broken, lookWith([]))).toEqual([{ text: "k8s-namespace/bb-gate-production is readable again", actionable: false }]); + }); +}); diff --git a/plugins/stewards/ops.ts b/plugins/stewards/ops.ts new file mode 100644 index 00000000..8c3d42e1 --- /dev/null +++ b/plugins/stewards/ops.ts @@ -0,0 +1,338 @@ +// The ops kind's mechanical tier, as pure functions: what a look at a watch +// target found, each problem's fingerprint, and how each compares with the +// fingerprint map (new, still failing under its ticket, or back after its +// ticket was resolved). kube.ts reads the cluster; server.ts stores and +// wakes; nothing here talks to anything. +// +// A fingerprint names one problem across looks and restarts: the target, the +// workload (a Deployment's pods share it whatever their generated names), the +// container, and an error signature built from the container's status, never +// from log text, which changes on every line. +import { z } from "zod"; +import type { Change } from "./reconcile.js"; + +export type OpsTarget = { kind: "k8s-namespace"; name: string }; + +/** The binding's entity id and key for a target: "k8s-namespace/bb-gate-production". */ +export const opsTargetKey = (t: OpsTarget): string => `${t.kind}/${t.name}`; + +export function parseOpsTargetKey(key: string): OpsTarget | null { + const m = /^(k8s-namespace)\/([a-z0-9][-a-z0-9]*)$/u.exec(key); + return m === null ? null : { kind: m[1] as OpsTarget["kind"], name: m[2]! }; +} + +// ---- reading the Kubernetes API's JSON -------------------------------------------- + +export type OpsContainer = { + name: string; + ready: boolean; + restarts: number; + waiting: { reason: string; message: string | null } | null; + lastTerminated: { reason: string | null; exitCode: number | null; finishedAt: string | null } | null; +}; + +export type OpsPod = { + name: string; + workload: string; + phase: string; + reason: string | null; + message: string | null; + ready: boolean; + /** When the Ready condition last changed. */ + readySince: string | null; + /** The scheduler's message while the pod cannot be placed, and since when. */ + unschedulable: { message: string; since: string | null } | null; + containers: OpsContainer[]; +}; + +type Json = Record; +const obj = (v: unknown): Json => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Json) : {}); +const arr = (v: unknown): Json[] => (Array.isArray(v) ? v.map(obj) : []); +const str = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null); +const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); + +/** + * The workload a pod belongs to: a Deployment's ReplicaSet without its + * template hash, or the StatefulSet, DaemonSet or Job that owns it. A pod + * nothing owns is its own workload. + */ +export function workloadOf(pod: Json): string { + const meta = obj(pod.metadata); + const name = str(meta.name) ?? "?"; + const owner = arr(meta.ownerReferences).find((o) => o.controller === true) ?? arr(meta.ownerReferences)[0]; + if (owner === undefined) return name; + const ownerName = str(owner.name) ?? name; + if (owner.kind !== "ReplicaSet") return ownerName; + const hash = str(obj(meta.labels)["pod-template-hash"]); + if (hash !== null && ownerName.endsWith(`-${hash}`)) return ownerName.slice(0, -hash.length - 1); + return ownerName.replace(/-[a-z0-9]{6,10}$/u, ""); +} + +function containerOf(status: Json, prefix = ""): OpsContainer { + const state = obj(status.state); + const waiting = obj(state.waiting); + const last = obj(obj(status.lastState).terminated); + return { + name: `${prefix}${str(status.name) ?? "?"}`, + ready: status.ready === true, + restarts: num(status.restartCount) ?? 0, + waiting: str(waiting.reason) === null ? null : { reason: str(waiting.reason)!, message: str(waiting.message) }, + lastTerminated: Object.keys(last).length === 0 ? null : { reason: str(last.reason), exitCode: num(last.exitCode), finishedAt: str(last.finishedAt) }, + }; +} + +/** A pod list from the API, as the parts a look reads. */ +export function podsOf(list: unknown): OpsPod[] { + return arr(obj(list).items).map((pod) => { + const meta = obj(pod.metadata); + const status = obj(pod.status); + const conditions = arr(status.conditions); + const ready = conditions.find((c) => c.type === "Ready"); + const scheduled = conditions.find((c) => c.type === "PodScheduled"); + return { + name: str(meta.name) ?? "?", + workload: workloadOf(pod), + phase: str(status.phase) ?? "Unknown", + reason: str(status.reason), + message: str(status.message), + ready: ready?.status === "True", + readySince: str(ready?.lastTransitionTime), + unschedulable: scheduled?.status === "False" && scheduled.reason === "Unschedulable" ? { message: str(scheduled.message) ?? "unschedulable", since: str(scheduled.lastTransitionTime) } : null, + containers: [...arr(status.initContainerStatuses).map((c) => containerOf(c, "init:")), ...arr(status.containerStatuses).map((c) => containerOf(c))], + }; + }); +} + +export type OpsEvent = { kind: string; name: string; type: string; reason: string; message: string; count: number; at: string | null }; + +export function eventsOf(list: unknown): OpsEvent[] { + return arr(obj(list).items).map((e) => { + const involved = obj(e.involvedObject); + const series = obj(e.series); + return { + kind: str(involved.kind) ?? "?", + name: str(involved.name) ?? "?", + type: str(e.type) ?? "Normal", + reason: str(e.reason) ?? "?", + message: str(e.message) ?? str(e.note) ?? "", + count: num(e.count) ?? num(series.count) ?? 1, + at: str(e.lastTimestamp) ?? str(series.lastObservedTime) ?? str(e.eventTime) ?? str(obj(e.metadata).creationTimestamp), + }; + }); +} + +export type OpsDeployment = { name: string; ready: number; desired: number }; + +export function deploymentsOf(list: unknown): OpsDeployment[] { + return arr(obj(list).items).map((d) => ({ name: str(obj(d.metadata).name) ?? "?", ready: num(obj(d.status).readyReplicas) ?? 0, desired: num(obj(d.spec).replicas) ?? 1 })); +} + +// ---- findings ------------------------------------------------------------------------ + +/** Waiting reasons that mean a container cannot run, not that it is starting. */ +const BAD_WAITING = new Set(["CrashLoopBackOff", "ImagePullBackOff", "ErrImagePull", "CreateContainerConfigError", "CreateContainerError", "InvalidImageName", "RunContainerError"]); +/** A pod not ready, or not placed, for this long is a problem rather than a rollout. */ +export const SETTLE_MS = 10 * 60_000; +const EVENTS_PER_FINDING = 5; +const WARNINGS_MAX = 10; + +/** One problem seen in one look, before it is compared with the fingerprint map. */ +export type Sighting = { + fingerprint: string; + workload: string; + /** Every pod showing it; the first is the one its logs were read from. */ + pods: string[]; + container: string | null; + signature: string; + summary: string; + restarts: number; + /** Warning events about its pods, newest first, as lines. */ + events: string[]; + /** The container's last log lines, redacted; null when they were not read. */ + logs: string[] | null; + /** Whether its logs are of the container's previous run (the one that crashed). */ + previous: boolean; +}; + +export const fingerprintOf = (target: OpsTarget, workload: string, container: string | null, signature: string): string => + `${opsTargetKey(target)}/${workload}/${container ?? "pod"}#${signature}`; + +const olderThan = (at: string | null, ms: number, now: number) => at !== null && now - Date.parse(at) >= ms; +const exit = (t: OpsContainer["lastTerminated"]) => (t === null ? "" : `${t.reason ?? "terminated"}, exit ${t.exitCode ?? "?"}`); + +export const eventLine = (e: OpsEvent): string => `${e.at ?? "?"} ${e.kind}/${e.name} ${e.reason}${e.count > 1 ? ` ×${e.count}` : ""}: ${e.message.replace(/\s+/gu, " ").trim()}`; + +/** + * What is wrong in a target, one sighting per fingerprint. `since` is the + * last look: a container that restarted after it, and is running again, is + * still a sighting, once. + */ +export function findingsOf(target: OpsTarget, pods: OpsPod[], events: OpsEvent[], at: { now: number; since: number }): Sighting[] { + const found = new Map(); + const add = (pod: OpsPod, container: OpsContainer | null, signature: string, summary: string) => { + const fingerprint = fingerprintOf(target, pod.workload, container?.name ?? null, signature); + const seen = found.get(fingerprint); + if (seen !== undefined) { + seen.pods.push(pod.name); + seen.restarts = Math.max(seen.restarts, container?.restarts ?? 0); + return; + } + found.set(fingerprint, { fingerprint, workload: pod.workload, pods: [pod.name], container: container?.name ?? null, signature, summary, restarts: container?.restarts ?? 0, events: [], logs: null, previous: container?.lastTerminated != null }); + }; + for (const pod of pods) { + if (pod.phase === "Succeeded") continue; + if (pod.phase === "Failed") { + add(pod, null, `Failed:${pod.reason ?? "Unknown"}`, `Pod ${pod.name} failed${pod.reason === null ? "" : ` (${pod.reason})`}${pod.message === null ? "" : `: ${pod.message}`}`); + continue; + } + let containerProblem = false; + for (const c of pod.containers) { + const last = c.lastTerminated; + if (c.waiting !== null && BAD_WAITING.has(c.waiting.reason)) { + containerProblem = true; + const signature = c.waiting.reason === "CrashLoopBackOff" ? `CrashLoopBackOff:${last?.reason ?? "?"}:${last?.exitCode ?? "?"}` : c.waiting.reason; + add(pod, c, signature, `Container ${c.name} is in ${c.waiting.reason}${last === null ? "" : ` (last run: ${exit(last)})`}, ${c.restarts} restart${c.restarts === 1 ? "" : "s"}${c.waiting.message === null ? "" : `: ${c.waiting.message}`}`); + } else if (last !== null && last.finishedAt !== null && Date.parse(last.finishedAt) >= at.since && (last.exitCode !== 0 || last.reason === "OOMKilled")) { + containerProblem = true; + add(pod, c, `Restarted:${last.reason ?? "?"}:${last.exitCode ?? "?"}`, `Container ${c.name} restarted at ${last.finishedAt} (${exit(last)}), ${c.restarts} restart${c.restarts === 1 ? "" : "s"} in all`); + } + } + if (pod.phase === "Pending" && pod.unschedulable !== null && olderThan(pod.unschedulable.since, SETTLE_MS, at.now)) { + add(pod, null, "Unschedulable", `Pod ${pod.name} cannot be scheduled: ${pod.unschedulable.message}`); + } else if (pod.phase === "Running" && !pod.ready && !containerProblem && olderThan(pod.readySince, SETTLE_MS, at.now)) { + add(pod, null, "NotReady", `Pod ${pod.name} has been running but not ready since ${pod.readySince}`); + } + } + const warnings = events.filter((e) => e.type === "Warning").sort((a, b) => (b.at ?? "").localeCompare(a.at ?? "")); + for (const s of found.values()) { + s.events = warnings.filter((e) => e.kind === "Pod" && s.pods.includes(e.name)).slice(0, EVENTS_PER_FINDING).map(eventLine); + } + return [...found.values()]; +} + +/** Recent warning events about anything the findings do not already cover, for context. */ +export function otherWarnings(events: OpsEvent[], sightings: Sighting[], since: number): string[] { + const covered = new Set(sightings.flatMap((s) => s.pods)); + return events + .filter((e) => e.type === "Warning" && !(e.kind === "Pod" && covered.has(e.name)) && e.at !== null && Date.parse(e.at) >= since) + .sort((a, b) => (b.at ?? "").localeCompare(a.at ?? "")) + .slice(0, WARNINGS_MAX) + .map(eventLine); +} + +// ---- logs ------------------------------------------------------------------------------ + +export const LOG_LINES = 30; +const LOG_LINE_CHARS = 400; +const SECRET = /((?:authorization|token|secret|password|passwd|api[_-]?key|cookie|set-cookie)["']?\s*[:=]\s*["']?(?:bearer\s+)?|bearer\s+)([^\s"',;]+)/giu; + +/** + * The last lines of a log, clipped and with obvious credentials replaced. + * They go into a Linear ticket, so a token printed by a crashing process + * should not. + */ +export function logTail(text: string, lines = LOG_LINES): string[] { + return text + .split(/\r?\n/u) + .filter((l) => l.trim() !== "") + .slice(-lines) + .map((l) => l.replace(SECRET, "$1[redacted]")) + .map((l) => (l.length <= LOG_LINE_CHARS ? l : `${l.slice(0, LOG_LINE_CHARS)}…`)); +} + +// ---- the look, compared with the fingerprint map ---------------------------------------- + +export const FINDING_CLASSES = ["new", "recurring", "returned"] as const; +export type FindingClass = (typeof FINDING_CLASSES)[number]; + +export const opsFindingSchema = z.object({ + fingerprint: z.string(), + workload: z.string(), + pods: z.array(z.string()), + container: z.string().nullable(), + signature: z.string(), + summary: z.string(), + restarts: z.number(), + events: z.array(z.string()), + logs: z.array(z.string()).nullable(), + previous: z.boolean().default(false), + /** new: no ticket yet. recurring: its ticket is open. returned: its ticket was resolved and it is back. */ + class: z.enum(FINDING_CLASSES), + ticket: z.string().nullable(), + /** The ticket's state, when it could be read. */ + ticketState: z.string().nullable(), + firstSeenAt: z.number(), + lastCommentedAt: z.number().nullable(), +}); +export type OpsFinding = z.infer; + +/** Whether logs were read: some were, the server may not read them (no pods/log grant), or none were needed. */ +export const LOG_ACCESS = ["read", "not granted", "unneeded"] as const; + +export const opsLookSchema = z.object({ + at: z.number(), + target: z.string(), + /** Set when the target could not be read; the rest is then empty. */ + error: z.string().nullable(), + pods: z.number(), + healthy: z.number(), + deployments: z.array(z.object({ name: z.string(), ready: z.number(), desired: z.number() })), + /** Warning events no finding covers. */ + warnings: z.array(z.string()), + logs: z.enum(LOG_ACCESS), + /** What the reader could not see, in sentences: events or deployments not readable. */ + notes: z.array(z.string()), + findings: z.array(opsFindingSchema), +}); +export type OpsLook = z.infer; + +/** What a reader returns for one target, before the fingerprint map. */ +export type RawLook = Omit & { sightings: Sighting[] }; + +/** A fingerprint map row, as classification needs it. */ +export type FingerprintRow = { fingerprint: string; ticketKey: string | null; firstSeenAt: number; lastCommentedAt: number | null }; + +/** A ticket's state as the linear plugin reports it; null when it could not be read. */ +export type TicketState = { state: string; stateType: string | null } | null; + +const resolvedTicket = (t: TicketState) => t !== null && (t.stateType === "completed" || t.stateType === "canceled"); + +/** + * Each sighting against the fingerprint map: new when it has no ticket, + * recurring while its ticket is open (or cannot be read: a comment on a + * ticket that turns out closed does less harm than a duplicate), returned + * once its ticket was resolved. + */ +export function classify(sightings: Sighting[], rows: ReadonlyMap, tickets: ReadonlyMap, now: number): OpsFinding[] { + return sightings.map((s) => { + const row = rows.get(s.fingerprint); + const ticket = row?.ticketKey ?? null; + const state = ticket === null ? null : (tickets.get(ticket) ?? null); + const cls: FindingClass = ticket === null ? "new" : resolvedTicket(state) ? "returned" : "recurring"; + return { ...s, class: cls, ticket, ticketState: state?.state ?? null, firstSeenAt: row?.firstSeenAt ?? now, lastCommentedAt: row?.lastCommentedAt ?? null }; + }); +} + +/** + * What changed between two looks, as the mechanical tier weighs it. A + * problem new to this look, or back after its ticket was resolved, is worth + * a turn at once. One still failing under its open ticket waits for the + * requeue, so a crash loop is a comment per interval rather than per look. + */ +export function lookChanges(before: OpsLook | null, after: OpsLook): Change[] { + if (after.error !== null) return before === null || before.error === null ? [{ text: `Cannot read ${after.target}: ${after.error}`, actionable: false }] : []; + const changes: Change[] = []; + if (before !== null && before.error !== null) changes.push({ text: `${after.target} is readable again`, actionable: false }); + const was = new Map((before?.findings ?? []).map((f) => [f.fingerprint, f])); + for (const f of after.findings) { + const prev = was.get(f.fingerprint); + if (f.class === "new" && (prev === undefined || prev.class !== "new")) changes.push({ text: `New problem: ${f.fingerprint} — ${f.summary}`, actionable: true }); + else if (f.class === "returned" && prev?.class !== "returned") changes.push({ text: `Back after ${f.ticket} was resolved (${f.ticketState ?? "closed"}): ${f.fingerprint}`, actionable: true }); + else if (f.class === "recurring" && prev === undefined) changes.push({ text: `Seen again under ${f.ticket}: ${f.fingerprint}`, actionable: false }); + } + const now = new Set(after.findings.map((f) => f.fingerprint)); + for (const f of was.values()) { + if (!now.has(f.fingerprint)) changes.push({ text: `No longer seen: ${f.fingerprint}${f.ticket === null ? "" : ` (${f.ticket})`}`, actionable: false }); + } + return changes; +} diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 445f3e7c..ffdfc828 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -2,11 +2,13 @@ import Database from "better-sqlite3"; import { createFakePluginHost, makePluginAgentConfigurationContext, makeThreadResponse } from "@get-bb/plugin-sdk/testing"; import { describe, expect, it } from "vitest"; import { PROJECT_FILE, playbookPath } from "./config.js"; -import { comment, issue, pull } from "./fixtures.js"; -import { createStewardsPlugin, testHooks } from "./server.js"; +import { comment, crashingPod, issue, pull, warningEvent } from "./fixtures.js"; +import type { OpsAccess, OpsReader } from "./kube.js"; +import { eventsOf, findingsOf, podsOf } from "./ops.js"; +import { createStewardsPlugin, testHooks, type StewardsDeps } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; import { MIGRATIONS } from "./store.js"; -import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, projectFileTemplate } from "./templates.js"; +import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, projectFileTemplate } from "./templates.js"; type Call = { pluginId: string; method: string; input: Record }; @@ -150,10 +152,10 @@ function world() { return { files, writes, repos, entities, rpcCalls, threads, sections, usage, metadata, spawns, sends, userTurns, sdk, now: () => now, advance: (ms: number) => (now += ms) }; } -async function setup() { +async function setup(extra: Partial = {}) { const w = world(); const { bb, harness } = createFakePluginHost({ pluginId: "stewards", sdk: w.sdk as never, agentSkillIds: ["stewards"] }); - await createStewardsPlugin({ now: w.now, timing: { debounceMs: 1, nightlyStaggerMs: 0 } })(bb); + await createStewardsPlugin({ now: w.now, timing: { debounceMs: 1, nightlyStaggerMs: 0 }, ...extra })(bb); const hooks = testHooks.get("stewards")!; /** Let debounced work run to completion. */ const flush = async () => { @@ -1291,6 +1293,7 @@ describe("bb stewards init", () => { const out = await t.harness.behavior.runCli(["init", "--teams", "eng"], { threadId: "thr_me", projectId: "p1", cwd: "/w" }); expect(out.exitCode).toBe(0); expect(t.writes).toContainEqual({ path: `/w/.bb/${PROJECT_FILE}`, hostId: "host_me" }); + expect(t.writes).toContainEqual({ path: `/w/.bb/${playbookPath("ops-watch")}`, hostId: "host_me" }); expect(t.writes.every((w) => w.hostId === "host_me")).toBe(true); }); @@ -1298,7 +1301,7 @@ describe("bb stewards init", () => { const t = await setup(); t.threads.set("thr_me", { status: "active", archivedAt: null }); await t.harness.behavior.runCli(["init", "--teams", "ENG"], { threadId: "thr_me", projectId: "p1", cwd: "/w" }); - expect(t.writes.length).toBe(4); + expect(t.writes.length).toBe(5); expect(t.writes.every((w) => w.hostId === "host_on")).toBe(true); }); }); @@ -1492,3 +1495,199 @@ describe("the settings page", () => { expect(check.ok).toBe(false); }); }); + +describe("ops stewards", () => { + const TARGET = "k8s-namespace/bb-gate-production"; + const FP = `${TARGET}/bb-gate-router/router#CrashLoopBackOff:Error:1`; + + /** A namespace the fake cluster serves, as kube.ts would read it, through the real parsing. */ + function cluster() { + const state = { pods: [] as unknown[], events: [] as unknown[], error: null as string | null, logs: false, access: null as OpsAccess | null }; + const reader: OpsReader = { + async look(target, at) { + if (state.error !== null) throw new Error(state.error); + const pods = podsOf({ items: state.pods }); + const sightings = findingsOf(target, pods, eventsOf({ items: state.events }), at); + const failing = sightings.filter((x) => x.container !== null); + if (state.logs) for (const x of failing) x.logs = ["panic: listen tcp :8080: address already in use"]; + return { pods: pods.length, healthy: pods.filter((p) => p.ready).length, deployments: [{ name: "bb-gate-router", ready: 0, desired: 1 }], warnings: [], logs: failing.length === 0 ? "unneeded" : state.logs ? "read" : "not granted", notes: [], sightings }; + }, + async access() { + return state.access ?? { error: "this server has no cluster access: no ServiceAccount token at /var/run/secrets/kubernetes.io/serviceaccount", reads: [], logs: null, mutating: [] }; + }, + }; + return { state, reader }; + } + + const opsProject = (targets: string[] = ["bb-gate-production"], extra: Record = {}) => + JSON.stringify({ version: 1, linear: { teams: ["ENG"] }, ops: { targets: targets.map((name) => ({ kind: "k8s-namespace", name })), ...extra } }); + + async function watched(over: { error?: string } = {}) { + const c = cluster(); + const t = await setup({ ops: c.reader }); + t.files[PROJECT_FILE] = opsProject(); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + c.state.pods = [crashingPod()]; + c.state.events = [warningEvent("bb-gate-router-6d4f9c7b8-x2k4q")]; + if (over.error !== undefined) c.state.error = over.error; + await t.hooks.sweep(); + await t.flush(); + const steward = () => t.spawns.find((x) => String(x.title).startsWith("Ops watch")); + const wakes = () => { + const id = steward()?.id; + return id === undefined ? [] : [String(steward()!.prompt), ...t.sends.filter((x) => x.threadId === id).map((x) => x.text)]; + }; + return { t, c, steward, wakes }; + } + + it("watches a configured target, files one ticket for a crash loop, and comments on it while it keeps crashing", async () => { + const { t, steward, wakes } = await watched(); + const [project] = t.spawns; + const ops = steward()!; + // A binding of its own, reporting to the project steward, in the list and on the page. + expect(await t.list()).toMatchObject([{ key: TARGET, kind: "ops", threadId: ops.id, ended: false }]); + expect(ops).toMatchObject({ title: "Ops watch: bb-gate-production", sectionId: "sec_1", environment: { type: "reuse", environmentId: "env1" }, model: "claude-sonnet-5-5" }); + const board = (await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: { stewards: Array<{ key: string; kind: string; stage: string | null }> } }; + expect(board.board.stewards).toEqual([expect.objectContaining({ key: TARGET, kind: "ops", stage: "watch" })]); + + const first = wakes()[0]!; + expect(first).toMatch(/^# Ops watch: k8s-namespace\/bb-gate-production/u); + expect(first).toMatch(/You have just been made the ops steward/u); + expect(first).toContain(`#### ${FP}`); + expect(first).toMatch(/### New: no ticket yet/u); + expect(first).toMatch(/File one ticket per problem/u); + expect(first).not.toMatch(/### Recurring/u); + expect(first).toMatch(/BackOff ×12: Back-off restarting failed container router/u); + // bb-gate-production grants no logs: the wake says to diagnose from status and events. + expect(first).toMatch(/Logs: not readable from this server \(no pods\/log grant here\)/u); + expect(first).toMatch(/File tickets in the Linear team ENG/u); + expect(first).toMatch(/Allowed actions: read, file-ticket, comment, escalate\./u); + + // A fingerprint it has not seen is refused, and nothing is recorded. + const base = { phase: "watching", summary: "router crash-looping; filed ENG-50", nextAction: "Watch", actor: "steward" }; + const wrong = await t.tool("steward_report", { ...base, opsTickets: [{ fingerprint: "made-up", ticket: "ENG-50", did: "filed" }] }, ops.id); + expect(wrong).toMatchObject({ error: true, text: expect.stringMatching(/"made-up" is not a fingerprint/u) }); + expect(wrong.text).toContain(FP); + expect(t.hooks.store.fingerprint("p1", FP)).toMatchObject({ ticketKey: null }); + + // It files, and escalates once to the project steward, which hears how to adopt. + const report = await t.tool( + "steward_report", + { ...base, opsTickets: [{ fingerprint: FP, ticket: "ENG-50", did: "filed" }], escalate: { kind: "decision", question: "Filed ENG-50 (high): bb-gate-router crash-loops on start. Recommend adopting.", meanwhile: "Keep watching." } }, + ops.id, + ); + expect(report).toMatchObject({ error: false, text: expect.stringMatching(/Recorded ENG-50 \(filed\) against its fingerprint/u) }); + expect(t.hooks.store.fingerprint("p1", FP)).toMatchObject({ ticketKey: "ENG-50" }); + const told = t.sends.filter((x) => x.threadId === project!.id).at(-1)!.text; + expect(told).toMatch(/New escalations routed to you/u); + expect(told).toMatch(/from k8s-namespace\/bb-gate-production \(decision\): Filed ENG-50/u); + expect(told).toMatch(/An escalation from an ops steward .* add the label `bb-managed` and move it to Todo/u); + + // Another look before the requeue, still crashing: nothing new, nobody woken. + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", title: "bb-gate-router crash-loops", labels: [], state: "Triage", stateType: "triage" })); + const before = wakes().length; + await t.hooks.sweep(); + await t.flush(); + expect(wakes()).toHaveLength(before); + + // At the requeue, the same problem is a comment on ENG-50: recurring, and no new ticket. + t.advance(61 * 60_000); + await t.hooks.sweep(); + await t.flush(); + const again = wakes().at(-1)!; + expect(wakes()).toHaveLength(before + 1); + expect(again).toMatch(/### Recurring: its ticket is open/u); + expect(again).toMatch(/ticket ENG-50 \(Triage\)/u); + expect(again).toMatch(/Comment on that ticket/u); + expect(again).toMatch(/File nothing new/u); + expect(again).not.toMatch(/### New/u); + expect(again).toMatch(/Requeue time came, with problems still failing/u); + expect((await t.tool("steward_report", { ...base, opsTickets: [{ fingerprint: FP, ticket: "ENG-50", did: "commented" }] }, ops.id)).error).toBe(false); + expect(t.hooks.store.fingerprints(t.hooks.store.find(TARGET)!.id)).toMatchObject([{ fingerprint: FP, ticketKey: "ENG-50", lastCommentedAt: t.now() }]); + + // The project steward adopts it the usual way (label and Todo); the team lease brings a ticket steward. + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", title: "bb-gate-router crash-loops", labels: ["bb-managed"], state: "Todo" })); + await t.ring("linear", "ENG-50"); + expect(await t.list()).toEqual(expect.arrayContaining([expect.objectContaining({ key: "ENG-50", kind: "ticket" })])); + + // Done, and the router crashes again: back at once, for the playbook to reopen or file anew. + t.entities.set("ENG-50", issue({ id: "ENG-50", key: "ENG-50", labels: ["bb-managed"], state: "Done", stateType: "completed" })); + await t.hooks.sweep(); + await t.flush(); + const back = wakes().at(-1)!; + expect(back).toMatch(/### Returned: its ticket was resolved/u); + expect(back).toMatch(/Back after ENG-50 was resolved \(Done\)/u); + expect(back).toMatch(/escalate\s+a decision recommending it be reopened/u); + }); + + it("makes a binding that waits while the server cannot read its target, and wakes once it can", async () => { + const { t, c, steward } = await watched({ error: "403: pods is forbidden" }); + expect(await t.list()).toMatchObject([{ key: TARGET, kind: "ops", threadId: null }]); + expect(steward()).toBeUndefined(); + const listed = await t.harness.behavior.runCli(["list"], { projectId: "p1" }); + expect(listed.stdout).toMatch(/cannot read the target: 403: pods is forbidden/u); + + c.state.error = null; + await t.hooks.sweep(); + await t.flush(); + expect(steward()).toBeDefined(); + expect(String(steward()!.prompt)).toMatch(/You have just been made the ops steward/u); + }); + + it("ends with its target's removal from the project file, and resumes the same thread when it is back", async () => { + const { t, steward, wakes } = await watched(); + const id = steward()!.id; + t.files[PROJECT_FILE] = opsProject([]); + await t.hooks.sweep(); + await t.flush(); + expect(await t.list()).toMatchObject([{ key: TARGET, ended: true }]); + expect(t.threads.get(id)!.archivedAt).not.toBeNull(); + + t.files[PROJECT_FILE] = opsProject(); + await t.hooks.sweep(); + await t.flush(); + expect(await t.list()).toMatchObject([{ key: TARGET, ended: false, threadId: id }]); + expect(t.threads.get(id)!.archivedAt).toBeNull(); + expect(wakes().at(-1)).toMatch(/configured again and its binding has resumed/u); + expect(t.spawns.filter((x) => String(x.title).startsWith("Ops watch"))).toHaveLength(1); + }); + + it("is checked: a target this server cannot read is a problem, as is any write it holds there", async () => { + const { t, c } = await watched(); + const check = () => t.harness.behavior.runCli(["check"], { projectId: "p1" }); + const none = await check(); + expect(none.exitCode).toBe(1); + expect(none.stdout).toMatch(/ops: tickets filed in ENG/u); + expect(none.stdout).toMatch(/problem: ops: this server cannot read k8s-namespace\/bb-gate-production: this server has no cluster access/u); + expect(none.stdout).toMatch(/^ops: ops-watch@/mu); + + const reads = [{ what: "list pods", ok: true, detail: null }, { what: "list events", ok: true, detail: null }, { what: "list deployments", ok: false, detail: "403: forbidden" }]; + c.state.access = { error: null, reads, logs: false, mutating: [] }; + const readable = await check(); + expect(readable.exitCode).toBe(0); + expect(readable.stdout).toMatch(/ops: k8s-namespace\/bb-gate-production is readable \(list pods, list events\); logs not granted, so diagnosis is from status and events/u); + expect(readable.stdout).toMatch(/cannot list deployments \(403: forbidden\); looks go without it/u); + + c.state.access = { error: null, reads, logs: true, mutating: ["delete pods"] }; + const writable = await check(); + expect(writable.exitCode).toBe(1); + expect(writable.stdout).toMatch(/problem: ops: this server may delete pods in k8s-namespace\/bb-gate-production; an ops steward's access should be read-only/u); + + // A project file whose ops section is wrong is a problem too. + t.files[PROJECT_FILE] = opsProject(["bb-gate-production"], { team: "SALES" }); + expect((await check()).stdout).toMatch(/problem: stewards\/project\.json: ops\.team: SALES is not one of linear\.teams/u); + }); + + it("gives an ops steward its own instructions, and refuses opsTickets from any other steward", async () => { + const { t, steward } = await watched(); + const config = await t.harness.behavior.resolveAgentConfiguration(makePluginAgentConfigurationContext({ thread: { id: steward()!.id, title: null, parentThreadId: null, sourceThreadId: null } })); + expect(config.instructions).toMatch(/You are the ops steward watching "k8s-namespace\/bb-gate-production"/u); + expect(config.instructions).toMatch(/never change production and start no workers/u); + + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + const ticketSteward = t.spawns.find((x) => x.title === "ENG-12: Fix login")!.id; + const r = await t.tool("steward_report", { phase: "Todo", summary: "x", nextAction: "y", actor: "steward", opsTickets: [{ fingerprint: FP, ticket: "ENG-50", did: "filed" }] }, ticketSteward); + expect(r).toMatchObject({ error: true, text: expect.stringMatching(/opsTickets is for an ops steward's report/u) }); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 9c474021..4a0f0078 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -24,19 +24,24 @@ import { formatDuration, isTerminal, modelSpecSchema, + opsTargets, + opsTeam, parsePlaybook, parseProjectFile, playbookNameFor, playbookPath, playbookStates, STAGES, + usesKind, type BindingKind, type EscalationKind, type ModelSpec, type Playbook, type ProjectFile, } from "./config.js"; +import { createKubeReader, type OpsAccess, type OpsReader } from "./kube.js"; import { nightlyDue, stillNight } from "./nightly.js"; +import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type OpsLook, type OpsTarget, type TicketState } from "./ops.js"; import { advanced, approvalWanted, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, lifecycle, newestCommentAt, phaseAndStage, resolveChecklistItem, specHash, stuckDue, unheardWait, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, @@ -50,7 +55,7 @@ import { } from "./source-contract.js"; import { ACTORS, MIGRATIONS, createStore, type Binding, type Escalation, type EscalationRoute, type Observed, type Question, type ReadyState, type Store } from "./store.js"; import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; -import { PROJECT_STEWARD_INTRO, formatProjectWake, formatWake, type DigestRecords, type WakeReason } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, formatOpsWake, formatProjectWake, formatWake, type DigestRecords, type WakeReason } from "./wake.js"; export const MULTI_REPO_PLUGIN_ID = "multi-repo"; /** multi-repo's environment provider: where every thread of a stewards project works. */ @@ -106,6 +111,8 @@ export const DEFAULT_TIMING: Timing = { export interface StewardsDeps { now: () => number; timing?: Partial; + /** How ops bindings read their targets: the pod's ServiceAccount by default. */ + ops?: OpsReader; } const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); @@ -393,7 +400,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P file = lastParsed.value; } - const kinds = KINDS.filter((k) => k !== "review" || file.reviews.enabled); + const kinds = KINDS.filter((k) => usesKind(file, k)); const names = new Map(kinds.map((k) => [k, playbookNameFor(file, k)] as const)); const texts = await readFiles(projectId, [...new Set(names.values())].map(playbookPath)); const playbooks: Partial> = {}; @@ -817,7 +824,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P projectId: b.projectId, ...(sectionId === null ? {} : { sectionId }), prompt, - title: b.kind === "review" ? `Review ${b.entityKey}: ${b.title ?? ""}`.trim() : `${b.entityKey}: ${b.title ?? ""}`.trim(), + title: b.kind === "review" ? `Review ${b.entityKey}: ${b.title ?? ""}`.trim() : b.kind === "ops" ? (b.title ?? `Ops watch: ${b.entityKey}`) : `${b.entityKey}: ${b.title ?? ""}`.trim(), ...modelArgs(stewardModel(b, playbook)), pluginMetadata: { role: "steward", bindingId: b.id, threadBriefs: STEWARD_BRIEFS }, }; @@ -845,6 +852,22 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return store.children(b.id).flatMap((child) => store.openEscalations(child.id).filter((x) => x.route === "parent").map((escalation) => ({ escalation, from: child }))); } + /** Send a wake, spawning the steward's thread on the first; false when nothing was delivered. */ + async function deliverWake(b: Binding, config: ProjectConfig, playbook: Playbook, text: string): Promise { + if (b.threadId === null) { + await spawnSteward(b, config, playbook, text); + return true; + } + const sent = await sendTo(b.threadId, text); + if (sent === "gone") { + // The user deleted the thread: that is a detach they meant. + store.patch(b.id, { endedAt: now(), endReason: "deleted", manualDetach: true }); + pushInterest(); + return false; + } + return sent === "sent"; + } + /** Wake the steward, spawning its thread on the first wake. */ async function wake(b: Binding, config: ProjectConfig, playbook: Playbook, observed: Observed, changes: string[], reason: WakeReason): Promise { const gate = gateState(playbook, b.ready, specHash(observed.entity, b.threadId)); @@ -864,18 +887,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P label: config.file.label, now: now(), }); - if (b.threadId === null) { - await spawnSteward(b, config, playbook, text); - } else { - const sent = await sendTo(b.threadId, text); - if (sent === "gone") { - // The user deleted the thread: that is a detach they meant. - store.patch(b.id, { endedAt: now(), endReason: "deleted", manualDetach: true }); - pushInterest(); - return; - } - if (sent === "failed") return; - } + if (!(await deliverWake(b, config, playbook, text))) return; const cursor = newestCommentAt(observed); store.patch(b.id, { awaitingReport: true, @@ -914,6 +926,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (config === null) return; const playbook = playbookFor(config, b.kind); if (playbook === null) return; + if (b.source === "ops") { + await reconcileOps(b, config, playbook, force); + return; + } let entity: EntitySnapshot | null; try { @@ -1030,6 +1046,143 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await wake(b, config, playbook, observed, lines, reason ?? (followingThrough(b) ? "follow-through" : b.requeueAt !== null && b.requeueAt <= now() && loudQueued === 0 ? "requeue" : "changed")); } + // ---- ops bindings ---------------------------------------------------------------------------- + // + // An ops binding watches a target the project file lists rather than an + // entity in a source plugin. Its steward's thread has no cluster access, + // so the plugin looks (kube.ts), compares what it saw with the + // fingerprint map, and wakes the steward with the look: at once for a + // problem that is new or back after its ticket was resolved, and at the + // requeue for one still failing under its open ticket. A look that finds + // nothing wrong is recorded and wakes nobody. + + const opsReader = deps.ops ?? createKubeReader(); + + /** The states of the tickets a look's problems are filed under, read through linear; null for one that cannot be read. */ + async function ticketStates(keys: string[]): Promise> { + const out = new Map(); + for (const key of [...new Set(keys)].slice(0, 20)) { + const e = await snapshot("linear", key).catch(() => null); + out.set(key, e === null ? null : { state: e.state, stateType: e.stateType }); + } + return out; + } + + /** One look at an ops binding's target, its problems entered in the fingerprint map and classified against it. */ + async function lookAt(b: Binding, target: OpsTarget, playbook: Playbook): Promise { + const at = now(); + const since = b.opsLook !== null && b.opsLook.error === null ? b.opsLook.at : at - playbook.requeueDefaultMs; + try { + const { sightings, ...rest } = await opsReader.look(target, { now: at, since }); + const rows = store.sight(b.projectId, b.id, sightings.map((s) => ({ fingerprint: s.fingerprint, summary: s.summary }))); + const tickets = await ticketStates([...rows.values()].map((r) => r.ticketKey).filter((k): k is string => k !== null)); + return { ...rest, at, target: opsTargetKey(target), error: null, findings: classify(sightings, rows, tickets, at) }; + } catch (error) { + return { at, target: opsTargetKey(target), error: errorMessage(error), pods: 0, healthy: 0, deployments: [], warnings: [], logs: "unneeded", notes: [], findings: [] }; + } + } + + async function reconcileOps(b: Binding, config: ProjectConfig, playbook: Playbook, force: WakeReason | null): Promise { + if (b.endedAt !== null || b.ending !== null) return; + const target = parseOpsTargetKey(b.entityId); + // A target no longer listed is ended by the sweep. + if (target === null || !opsTargets(config.file).some((t) => opsTargetKey(t) === b.entityId)) return; + const before = b.opsLook; + const look = await lookAt(b, target, playbook); + const requeueCame = b.requeueAt !== null && b.requeueAt <= now(); + // The next look is due a requeue from now, whether or not this one wakes anyone. + const requeueAt = requeueCame || b.requeueAt === null ? now() + playbook.requeueDefaultMs : b.requeueAt; + b = store.patch(b.id, { opsLook: look, requeueAt }); + if (look.error !== null) { + // Nothing to wake the steward with until the server can read the target; `bb stewards check` says why. + if (before?.error !== look.error) bb.log.warn(`stewards: cannot read ${b.entityKey}: ${look.error}`); + return; + } + + const changes = lookChanges(before, look); + if (requeueCame && look.findings.length > 0) changes.push({ text: "Requeue time came, with problems still failing", actionable: true }); + if (b.playbookVersion !== playbook.version) changes.push({ text: `Playbook ${playbook.name} updated (${b.playbookVersion} → ${playbook.version})`, actionable: false }); + const queued = b.pending; + const loudQueued = queued.filter((n) => n.quiet !== true).length; + for (const n of queued) { + const same = changes.find((c) => c.text === n.text); + if (same !== undefined) same.actionable ||= n.quiet !== true; + else changes.push({ text: n.text, actionable: n.quiet !== true }); + } + b = store.patch(b.id, { playbookVersion: playbook.version }); + const keep = () => { + for (const c of changes) if (!queued.some((n) => n.text === c.text && (n.quiet === true) === !c.actionable)) store.note(b.id, c.text, !c.actionable); + }; + // A steward that has never been woken is due its first turn as soon as the target can be read. + const reason = force ?? (b.threadId === null ? "adopted" : null); + if (reason === null && !changes.some((c) => c.actionable)) { + keep(); + return; + } + const deferred = (await settings.get()).paused || (b.hold !== null && reason === null && loudQueued === 0); + const info = b.threadId === null ? null : await threadInfo(b.threadId); + if (deferred || (info !== null && busy(info.status))) { + keep(); + if (reason !== null && reason !== "changed" && reason !== "adopted") store.note(b.id, `Due: ${reason}`); + return; + } + const text = formatOpsWake({ + reason: reason ?? (requeueCame && loudQueued === 0 ? "requeue" : "changed"), + binding: b, + playbook, + look, + team: opsTeam(config.file), + label: config.file.label, + autoAdopt: config.file.ops.autoAdopt, + escalations: store.openEscalations(b.id), + changes: [...new Set(changes.map((c) => c.text))], + }); + if (!(await deliverWake(b, config, playbook, text))) return; + store.patch(b.id, { awaitingReport: true, wokeAt: now(), lastJudgmentAt: now(), pending: [], archiveWhenIdle: false, requeueAt: now() + playbook.requeueDefaultMs }); + } + + /** + * One ops binding per configured target. A target taken out of the + * project file ends its binding; put back, the same binding and thread + * resume. One detached by hand stays ended while its target is listed, + * as a ticket stays detached while it keeps its label. + */ + async function syncOpsBindings(config: ProjectConfig): Promise { + const wanted = new Map(opsTargets(config.file).map((t) => [opsTargetKey(t), t] as const)); + const existing = store.all(config.projectId).filter((b) => b.kind === "ops"); + for (const b of existing) { + if (wanted.has(b.entityId)) continue; + if (b.endedAt === null) { + await serial(`b:${b.id}`, async () => { + const fresh = store.binding(b.id); + if (fresh !== null && fresh.endedAt === null) await finishEnding(fresh, "unconfigured"); + }); + } else if (b.manualDetach) store.patch(b.id, { manualDetach: false }); + } + const playbook = playbookFor(config, "ops"); + if (playbook === null || (await settings.get()).paused) return; + for (const [key, target] of wanted) { + const b = existing.find((x) => x.entityId === key); + if (b === undefined) { + let created: Binding; + try { + created = store.create({ projectId: config.projectId, source: "ops", entityId: key, entityKey: key, url: null, title: `Ops watch: ${target.name}`, kind: "ops", playbook: playbook.name, playbookVersion: playbook.version, parentBindingId: null, phase: "watching", stage: null }); + } catch { + continue; // made concurrently + } + bb.log.info(`stewards: watching ${key} with an ops binding (${playbook.name})`); + await serial(`b:${created.id}`, () => reconcileBinding(created.id, "adopted")); + } else if (b.endedAt !== null && !b.manualDetach) { + await serial(`b:${b.id}`, async () => { + const fresh = store.binding(b.id); + if (fresh === null || fresh.endedAt === null) return; + await reopen(fresh, `${key} is listed in ops.targets again`); + await reconcileBinding(b.id, "reopen"); + }); + } + } + } + // ---- lifecycle ------------------------------------------------------------------------------- async function stopWorkers(b: Binding): Promise { @@ -1269,7 +1422,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const withUser = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "me" && x.kind !== "approval").map((escalation) => ({ escalation, from: b }))); const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); - const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, timeZone: config.file.nightly.timezone, ...(records === undefined ? {} : { records }) }); + const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, timeZone: config.file.nightly.timezone, label: config.file.label, ...(records === undefined ? {} : { records }) }); delivered.ids = routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id); delivered.at = store.markDelivered(delivered.ids); return text; @@ -1577,7 +1730,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P playbooks: config === null ? [] - : KINDS.filter((k) => k !== "review" || config.file.reviews.enabled).map((kind) => ({ kind, name: playbookNameFor(config.file, kind), version: config.playbooks[kind]?.version ?? null })), + : KINDS.filter((k) => usesKind(config.file, k)).map((kind) => ({ kind, name: playbookNameFor(config.file, kind), version: config.playbooks[kind]?.version ?? null })), problems: config?.problems ?? [], nightly: config === null ? null : { at: config.file.nightly.at, timezone: config.file.nightly.timezone }, lastNight: row.nightlyDate, @@ -1650,7 +1803,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P title: b.title, kind: b.kind, phase: b.phase, - stage: b.stage, + // Ops bindings have no stage of their own; the page groups them as watching. + stage: b.kind === "ops" ? "watch" : b.stage, threadId: b.threadId, summary: b.status?.summary ?? null, nextAction: b.status?.nextAction ?? null, @@ -1721,6 +1875,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }; } const b = role.binding; + if (b.kind === "ops") { + return { + tools: ["steward_report", "steward_update"], + skills: ["stewards"], + instructions: + `You are the ops steward watching ${JSON.stringify(b.entityKey)} (binding ${b.id}, playbook ${JSON.stringify(b.playbook)}), and your thread id is ${context.thread.id}. ` + + "The plugin looks at the target for you and every wake carries what it found; you never change production and start no workers. " + + "File and comment on Linear tickets with the linear_ tools, which sign for you; escalate each ticket you file to the project steward with steward_report, as the playbook says. " + + "End every turn you were woken for with steward_report, listing in opsTickets every ticket you filed, commented on or reopened. Read the stewards skill for the protocol.", + }; + } return { tools: ["steward_report", "steward_update"], skills: ["stewards"], @@ -1819,10 +1984,30 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .max(600) .optional() .describe("Only after a terminal state (a wrap-up or follow-through turn): what remains to finish, such as a worker watching the deploy and verifying it. The binding stays open, its workers keep running, and you are woken as usual. Leave it out once the work is done, and the binding ends after this turn."), + opsTickets: z + .array( + z.object({ + fingerprint: z.string().trim().min(1).max(400).describe("The problem's fingerprint, as the wake gives it."), + ticket: z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*-\d+$/u, "a Linear key such as OPS-12").describe("The Linear ticket."), + did: z.enum(["filed", "commented", "reopened"]), + }), + ) + .max(20) + .optional() + .describe("Ops stewards only: every ticket you filed, commented on or reopened this turn, by fingerprint. The next look then treats the problem as filed under that ticket, so a recurrence is a comment there and nothing new."), }), async execute(input, { threadId }) { try { let b = ownBinding(threadId); + const opsTickets = input.opsTickets ?? []; + if (opsTickets.length > 0) { + if (b.kind !== "ops") return toolError(new Error("opsTickets is for an ops steward's report. Report without it.")); + const unknown = opsTickets.filter((t) => store.fingerprint(b.projectId, t.fingerprint) === null).map((t) => JSON.stringify(t.fingerprint)); + if (unknown.length > 0) { + const known = (b.opsLook?.findings ?? []).map((f) => `- ${f.fingerprint}`).join("\n"); + return toolError(new Error(`Nothing was recorded: ${unknown.join(", ")} ${unknown.length === 1 ? "is not a fingerprint" : "are not fingerprints"} this project has seen. Use them as the wake gives them${known === "" ? "." : `:\n${known}`}`)); + } + } if (input.followThrough !== undefined && b.ending !== "terminal") { return toolError(new Error(`followThrough is only for after a terminal state, and ${b.entityKey} is not in one now. Report without it.`)); } @@ -1855,6 +2040,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }; } if (input.voidApproval === true && ready.approval !== null) ready = { ...ready, approval: null, voidedAt: now() }; + for (const t of opsTickets) store.recordTicket(b.projectId, t.fingerprint, t.ticket, t.did); // Delivered after the status is written, together with any approval // request this report makes due, so the project steward reads the // new status and is woken once. @@ -1918,7 +2104,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return `Reported.${escalated} The binding stays open to follow through until ${iso(followThroughUntil!)}; running workers keep going. You will be woken when a worker finishes or something actionable changes, or in ${formatDuration(requeueMs)}. End the turn now.`; } const archived = archiveWhenIdle && store.openEscalations(b.id).length === 0 ? " Your thread is archived when the turn ends, and comes back on that wake." : ""; - return `Reported.${gateNote}${escalated} You will be woken when something actionable changes, or in ${formatDuration(requeueMs)}.${archived} End the turn now.`; + const recorded = opsTickets.length === 0 ? "" : ` Recorded ${opsTickets.map((t) => `${t.ticket} (${t.did})`).join(", ")} against ${opsTickets.length === 1 ? "its fingerprint" : "their fingerprints"}.`; + return `Reported.${recorded}${gateNote}${escalated} You will be woken when something actionable changes, or in ${formatDuration(requeueMs)}.${archived} End the turn now.`; } catch (error) { return toolError(error); } @@ -2057,7 +2244,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } // Pinned to the spec as it is now, not as last observed: a spec // comment posted since the last ring is part of what was read. - approval = { entity: (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser }; + const source = target.source; + approval = { entity: (source === "ops" ? null : await snapshot(source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser }; } if (resolve !== undefined) { if (guidance === undefined) return toolError(new Error("Give the answer as guidance when resolving.")); @@ -2149,7 +2337,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .map((b) => { const s = b.status; const open = store.openEscalations(b.id); - const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), unheardWait(s, open)].filter((f) => f !== null); + const look = b.opsLook; + const watch = look === null ? null : look.error !== null ? `cannot read the target: ${look.error}` : `looked ${iso(look.at)}: ${look.findings.length === 0 ? "nothing failing" : `${look.findings.length} problem(s) failing`}`; + const flags = [b.endedAt === null ? null : `ended: ${b.endReason}`, watch, b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}`, ...open.map((x) => `${x.kind} escalation ${x.id} with ${x.route}`), unheardWait(s, open)].filter((f) => f !== null); return `${b.entityKey} — ${b.kind}, ${b.phase ?? "?"}${b.threadId === null ? "" : `, thread ${b.threadId}`}\n ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.blockedOn === null ? "" : `; blocked on ${s.blockedOn}`}`}${flags.length > 0 ? `\n [${flags.join("; ")}]` : ""}`; }) .join("\n"); @@ -2171,6 +2361,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P for (const config of projects) { if (!(await settings.get()).paused) await adoptionPass(config); await keepProjectSteward(config.projectId); + await syncOpsBindings(config); const playbooks = config.playbooks; for (const b of store.open(config.projectId)) { if (b.threadId !== null) await keepSteward(config.projectId, b.threadId); @@ -2284,7 +2475,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const lines: string[] = [...config.problems.map((p) => `problem: ${p}`)]; const ticket = config.playbooks.ticket; lines.push(`Linear teams: ${config.file.linear.teams.join(", ") || "(none)"}; repos: ${config.repos.join(", ") || "(none)"}${config.file.github.exclude.length > 0 ? ` (excluded: ${config.file.github.exclude.join(", ")})` : ""}; label ${config.file.label}`); - for (const kind of KINDS) { + for (const kind of KINDS.filter((k) => usesKind(config.file, k))) { const p = config.playbooks[kind]; lines.push(`${kind}: ${p === undefined ? `no usable playbook (${playbookNameFor(config.file, kind)})` : `${p.name}@${p.version}`}`); } @@ -2304,13 +2495,29 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }; await validate("linear", config.file.linear.teams, ticket === undefined ? [] : playbookStates(ticket)); await validate("github", config.repos, []); + if (usesKind(config.file, "ops")) { + const auto = config.file.ops.autoAdopt; + lines.push(`ops: tickets filed in ${opsTeam(config.file) ?? "(no team)"}${auto.length > 0 ? `, adopted when filed at ${auto.join(", ")}` : ""}`); + for (const target of opsTargets(config.file)) lines.push(...opsAccessLines(opsTargetKey(target), await opsReader.access(target).catch((error: unknown): OpsAccess => ({ error: errorMessage(error), reads: [], logs: null, mutating: [] })))); + } return { ok: !lines.some((l) => l.startsWith("problem:")), lines }; } + /** What `bb stewards check` says about one ops target: readable or not, logs or not, and any write it should not hold. */ + function opsAccessLines(key: string, a: OpsAccess): string[] { + if (a.error !== null) return [`problem: ops: this server cannot read ${key}: ${a.error}`]; + const pods = a.reads.find((r) => r.what === "list pods"); + if (pods !== undefined && !pods.ok) return [`problem: ops: this server cannot read ${key}: list pods: ${pods.detail ?? "refused"}`]; + const lines = [`ops: ${key} is readable (${a.reads.filter((r) => r.ok).map((r) => r.what).join(", ")}); logs ${a.logs === true ? "readable" : a.logs === false ? "not granted, so diagnosis is from status and events" : "unknown"}`]; + for (const r of a.reads.filter((x) => !x.ok)) lines.push(`ops: ${key}: cannot ${r.what} (${r.detail ?? "refused"}); looks go without it`); + if (a.mutating.length > 0) lines.push(`problem: ops: this server may ${a.mutating.join(", ")} in ${key}; an ops steward's access should be read-only`); + return lines; + } + bb.cli.register( defineCli({ name: "stewards", - summary: "Long-lived threads that manage labelled Linear tickets and GitHub pull requests", + summary: "Long-lived threads that manage labelled Linear tickets and GitHub pull requests, and watch production", description: "Configuration lives in the project's .bb (stewards/project.json and stewards/playbooks/), read from committed HEAD through multi-repo.", commands: { init: cliCommand({ @@ -2354,7 +2561,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }), check: cliCommand({ - summary: "Validate the project file and every playbook against Linear and GitHub", + summary: "Validate the project file and every playbook against Linear and GitHub, and that this server can read every ops target", options: { project: PROJECT_OPTION }, async run(input, ctx) { const result = await check(projectOf(input.options.project, ctx)); @@ -2378,13 +2585,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P options: { project: PROJECT_OPTION, json: JSON_OPTION }, async run(input, ctx) { const b = bindingOrThrow(input.positionals.key, input.options.project ?? ctx.projectId); - const detail = { binding: b, escalations: store.escalations(b.id), workers: store.workers(b.id), children: store.children(b.id).map((c) => c.entityKey) }; + const detail = { binding: b, escalations: store.escalations(b.id), workers: store.workers(b.id), children: store.children(b.id).map((c) => c.entityKey), fingerprints: store.fingerprints(b.id) }; if (input.options.json) return { exitCode: 0, stdout: JSON.stringify(detail) }; const lines = [formatBindings([b]), "", `Playbook ${b.playbook}@${b.playbookVersion}; stage ${b.stage ?? "?"}; created ${iso(b.createdAt)}${b.requeueAt === null ? "" : `; requeue ${iso(b.requeueAt)}`}`]; - lines.push(`Ready: ${b.ready.checklist.map((c) => `[${c.met ? "x" : " "}] ${c.item}`).join("; ") || "not reported"}; substantial ${b.ready.substantial ?? "?"}; approval ${b.ready.approval === null ? "none" : iso(b.ready.approval.at)}`); + if (b.kind !== "ops") lines.push(`Ready: ${b.ready.checklist.map((c) => `[${c.met ? "x" : " "}] ${c.item}`).join("; ") || "not reported"}; substantial ${b.ready.substantial ?? "?"}; approval ${b.ready.approval === null ? "none" : iso(b.ready.approval.at)}`); for (const g of b.guidance) lines.push(`Guidance ${iso(g.at)}: ${g.text}`); for (const x of detail.escalations) lines.push(`Escalation ${x.id} ${x.kind} (${x.status}, ${x.route}): ${x.question}${x.resolution === null ? "" : ` → ${x.resolution}`}`); for (const w of detail.workers) lines.push(`Worker ${w.threadId} ${w.title}: ${w.status}`); + for (const f of store.fingerprints(b.id)) lines.push(`Fingerprint ${f.fingerprint} → ${f.ticketKey ?? "no ticket"}; seen ${f.seenCount} time(s), last ${iso(f.lastSeenAt)}${f.lastCommentedAt === null ? "" : `; last word ${iso(f.lastCommentedAt)}`}`); return { exitCode: 0, stdout: lines.join("\n") }; }, }), diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 95604908..0b0c374d 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -1,6 +1,6 @@ --- name: stewards -description: Work as a steward (a long-lived thread bound to a Linear ticket or GitHub pull request) or as the project steward, or set up and diagnose stewards for a project with `bb stewards`. +description: Work as a steward (a long-lived thread bound to a Linear ticket or GitHub pull request, or an ops steward watching production) or as the project steward, or set up and diagnose stewards for a project with `bb stewards`. --- # Stewards @@ -15,6 +15,7 @@ steward** per project sits above all of them. | `ticket` | the project's label (default `bb-managed`) is on a Linear issue in a listed team | `linear-tickets` | | `pr` | the label is on a pull request in one of the project's repos | `github-prs` | | `review` | a teammate opens, or marks ready, a pull request in one of the project's repos | `github-reviews` | +| `ops` | `project.json` lists a target in `ops.targets` (a Kubernetes namespace) | `ops-watch` | ## If you are a steward @@ -82,6 +83,30 @@ Two tools are yours; everything else you do with the tools every thread has. The plugin then archives your thread after a wake turn, unless a worker runs or an escalation is open, and the next wake brings it back. +## If you are an ops steward + +You watch one production target; the wake is the plugin's look at it (pods, +Warning events, and log lines where the server may read them), with each +problem's fingerprint marked new, recurring or returned. You never change +production and start no workers. + +- **New:** search the team for an open ticket about it, then file one ticket + per problem with `linear_create_issue`: pod and container, since when, the + evidence quoted, your diagnosis, a priority, and a line + ``Fingerprint: `` ``. Raise one `decision` escalation for the + tickets of the turn: "Filed BB-N (high): …. Recommend adopting." A priority + the wake says `ops.autoAdopt` covers you label and move to Todo yourself, + with no escalation. +- **Recurring:** comment on its ticket when the evidence moved; file nothing. +- **Returned:** as the playbook says: comment and escalate a reopen, or file + anew linking the old ticket. +- **Report every ticket** in `steward_report { opsTickets: [{ fingerprint, + ticket, did: "filed" | "commented" | "reopened" }] }`, by the fingerprint the + wake gives. That is what makes the next look a comment instead of a + duplicate. +- **No logs** (the wake says so on `bb-gate-production`): diagnose from status + and events, and say in the ticket that logs were not available. + ## If you are the project steward You decide what the stewards below you escalate, from the project's own @@ -96,6 +121,10 @@ with `guidance` + `resolve` saying what must change. When the user acts on an entity whose escalation you forwarded to them — edits the ticket, comments, moves it — you are woken with the change: if it answers the escalation, record it with `guidance` + `resolve`; if not, leave it open. +An ops steward's `decision` escalation is a ticket it filed about +production: adopt it when the project's guidance says it is worth working +(add the label, move it to Todo with `linear_update_issue`; a ticket steward +picks it up), or decline with a reason, then resolve the escalation. Everything you ask the user is a record. Forwarding an escalation to them makes a question for it; anything else you ask in a reply, record first @@ -118,12 +147,15 @@ The project must be a multi-repo project: configuration is read from its 1. From a thread in the project: `bb stewards init` writes `.bb/stewards/project.json` (Linear teams you belong to, or `--teams - ENG,OPS`) and the three default playbooks into the workspace's `.bb`. + ENG,OPS`) and the four default playbooks into the workspace's `.bb`. + To watch production, list targets in `ops.targets`, such as + `{ "kind": "k8s-namespace", "name": "bb-gate-production" }`. 2. Review them, commit inside `.bb`, publish with `workspace_publish_guidance`, and merge the `guidance-` branch. Edits take effect only once merged. 3. `bb stewards check` validates the project file and playbooks against - Linear (teams, states, label) and GitHub (repos, label). + Linear (teams, states, label) and GitHub (repos, label), and that this + server can read every ops target (and holds no write there). 4. Label a ticket `bb-managed`. Its steward thread appears beside the project steward's, not under it: a parent thread is woken whenever a child finishes a turn, and stewards report through their bindings. @@ -134,7 +166,7 @@ project. | Command | Does | |---|---| | `bb stewards list [--all] [--json]` | Bindings and their status records | -| `bb stewards show ` | One binding in full: gate, guidance, escalations, workers | +| `bb stewards show ` | One binding in full: gate, guidance, escalations, workers, fingerprints | | `bb stewards detach ` | One stop turn; stays detached until the label is removed and re-added | | `bb stewards pass [--nightly]` | The mechanical sweep now, or the full nightly pass | | `bb stewards digest` | The latest morning digest | @@ -149,6 +181,11 @@ above which a steward is compacted after its turn. ticket, its team in `linear.teams`, and the linear plugin connected. Rings need bb-gate-hooks (`BB_HOOKS_URL`); without it, adoption waits for the half-hourly sweep. +- **An ops steward never wakes.** `bb stewards list` shows `cannot read the + target` and `bb stewards check` says why: this server has no + ServiceAccount (bb-gate mounts one only into the backend of the developer + who runs the project's ops steward), or it may not list pods there. A look + that finds nothing failing wakes nobody, by design. - **A repo should not be stewarded.** Every GitHub repo in `repos.json` is, unless `project.json` lists it in `github.exclude` (`owner/repo`). Bindings already running there end with `bb stewards detach`. diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index 710183d8..1f028836 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -49,3 +49,47 @@ describe("questions to the user", () => { expect(s.openQuestions("p1")).toEqual([]); }); }); + +describe("the fingerprint map", () => { + const ops = (s: ReturnType["s"], projectId = "p1") => + s.create({ projectId, source: "ops", entityId: "k8s-namespace/prod", entityKey: "k8s-namespace/prod", url: null, title: "Ops watch: prod", kind: "ops", playbook: "ops-watch", playbookVersion: "v1", parentBindingId: null, phase: "watching", stage: null }); + const fp = "k8s-namespace/prod/web/app#CrashLoopBackOff:Error:1"; + + it("enters a problem on first sight with no ticket, and counts each sighting after", () => { + const { s, advance } = store(); + const b = ops(s); + const first = s.sight("p1", b.id, [{ fingerprint: fp, summary: "web crashes" }]); + expect(first.get(fp)).toMatchObject({ fingerprint: fp, bindingId: b.id, ticketKey: null, firstSeenAt: 1_000, lastSeenAt: 1_000, seenCount: 1, filedAt: null, lastCommentedAt: null }); + advance(60_000); + const again = s.sight("p1", b.id, [{ fingerprint: fp, summary: "web crashes, 9 restarts" }]); + expect(again.get(fp)).toMatchObject({ ticketKey: null, firstSeenAt: 1_000, lastSeenAt: 61_000, seenCount: 2, summary: "web crashes, 9 restarts" }); + expect(s.fingerprints(b.id).map((f) => f.fingerprint)).toEqual([fp]); + }); + + it("points a problem at the ticket filed for it, and a comment moves only the last word", () => { + const { s, advance } = store(); + const b = ops(s); + s.sight("p1", b.id, [{ fingerprint: fp, summary: "web crashes" }]); + expect(s.recordTicket("p1", "k8s-namespace/prod/other#x", "OPS-1", "filed")).toBe(false); + advance(1_000); + expect(s.recordTicket("p1", fp, "ops-7", "filed")).toBe(true); + expect(s.fingerprint("p1", fp)).toMatchObject({ ticketKey: "OPS-7", filedAt: 2_000, lastCommentedAt: 2_000 }); + advance(1_000); + s.recordTicket("p1", fp, "OPS-7", "commented"); + expect(s.fingerprint("p1", fp)).toMatchObject({ ticketKey: "OPS-7", filedAt: 2_000, lastCommentedAt: 3_000 }); + // Back after OPS-7 was closed, filed anew: the next sighting is OPS-9's. + advance(1_000); + s.recordTicket("p1", fp, "OPS-9", "filed"); + expect(s.fingerprint("p1", fp)).toMatchObject({ ticketKey: "OPS-9", filedAt: 4_000 }); + // Another project's map is its own. + expect(s.fingerprint("p2", fp)).toBeNull(); + }); + + it("keeps an ops binding's last look", () => { + const { s } = store(); + const b = ops(s); + expect(b).toMatchObject({ source: "ops", kind: "ops", opsLook: null, lastSnapshot: null }); + const look = { at: 5, target: "k8s-namespace/prod", error: "403: forbidden", pods: 0, healthy: 0, deployments: [], warnings: [], logs: "unneeded" as const, notes: [], findings: [] }; + expect(s.patch(b.id, { opsLook: look }).opsLook).toEqual(look); + }); +}); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 9cd686fa..e38ba986 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -10,6 +10,7 @@ import type Database from "better-sqlite3"; import { z } from "zod"; import { entitySnapshotSchema, type Source } from "./source-contract.js"; import type { BindingKind, EscalationKind, Stage } from "./config.js"; +import { opsLookSchema, type FingerprintRow, type OpsLook } from "./ops.js"; // Append-only: bb.storage.migrate records each statement's hash and refuses a // changed one, so a schema change is a new statement at the end. @@ -120,6 +121,22 @@ export const MIGRATIONS = [ `ALTER TABLE escalations ADD COLUMN delivered_at INTEGER`, // Escalations open before delivery was recorded were all delivered already. `UPDATE escalations SET delivered_at = created_at WHERE status = 'open' AND delivered_at IS NULL`, + // An ops binding's last look at its target: what it found, classified against the fingerprint map. + `ALTER TABLE bindings ADD COLUMN ops_look TEXT`, + // The fingerprint map: one problem an ops steward has seen, and the Linear ticket it was filed or commented on under. + `CREATE TABLE IF NOT EXISTS ops_fingerprints ( + project_id TEXT NOT NULL, + fingerprint TEXT NOT NULL, + binding_id TEXT NOT NULL, + summary TEXT NOT NULL, + ticket_key TEXT, + first_seen_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + seen_count INTEGER NOT NULL DEFAULT 1, + filed_at INTEGER, + last_commented_at INTEGER, + PRIMARY KEY (project_id, fingerprint) + )`, ]; // ---- values kept as JSON ------------------------------------------------------------ @@ -180,10 +197,13 @@ function json(schema: z.ZodType, raw: string | null, fallback: T): T { // ---- bindings -------------------------------------------------------------------------- +/** Where a binding's entity lives: a source plugin's, or "ops" for a watch target, which the plugin reads itself. */ +export type BindingSource = Source | "ops"; + export type Binding = { id: string; projectId: string; - source: Source; + source: BindingSource; entityId: string; entityKey: string; url: string | null; @@ -224,6 +244,8 @@ export type Binding = { /** When follow-through runs out, whatever the steward says: set when it is first declared. */ followThroughUntil: number | null; manualDetach: boolean; + /** An ops binding's last look; null for every other kind. */ + opsLook: OpsLook | null; createdAt: number; endedAt: number | null; endReason: string | null; @@ -239,7 +261,7 @@ function rowToBinding(r: BindingRow): Binding { return { id: r.id, projectId: String(r.project_id), - source: String(r.source) as Source, + source: String(r.source) as BindingSource, entityId: String(r.entity_id), entityKey: String(r.entity_key), url: str("url"), @@ -274,6 +296,7 @@ function rowToBinding(r: BindingRow): Binding { followThrough: str("follow_through"), followThroughUntil: num("follow_through_until"), manualDetach: Number(r.manual_detach) === 1, + opsLook: json(opsLookSchema.nullable(), str("ops_look"), null), createdAt: Number(r.created_at), endedAt: num("ended_at"), endReason: str("end_reason"), @@ -314,6 +337,7 @@ const COLUMNS = { followThrough: "follow_through", followThroughUntil: "follow_through_until", manualDetach: "manual_detach", + opsLook: "ops_look", endedAt: "ended_at", endReason: "end_reason", } as const satisfies Partial>; @@ -373,6 +397,12 @@ export type Question = { export type WorkerStatus = "running" | "finished" | "failed" | "stopped"; export type Worker = { threadId: string; bindingId: string; title: string; status: WorkerStatus; result: string | null; startedAt: number; endedAt: number | null }; +/** One problem an ops steward has seen, and the ticket it is tracked under. */ +export type Fingerprint = FingerprintRow & { projectId: string; bindingId: string; summary: string; lastSeenAt: number; seenCount: number; filedAt: number | null }; + +/** What a steward reports doing about a fingerprint: filing a ticket, commenting on one, or reopening one. */ +export type TicketAction = "filed" | "commented" | "reopened"; + export type ProjectStewardRow = { projectId: string; threadId: string | null; digest: string | null; digestAt: number | null; nightlyDate: string | null; digestPending: boolean; title: string | null; sectionId: string | null }; /** Guidance repeated within this window is a retry, not new guidance. */ @@ -427,6 +457,15 @@ export function createStore(db: Database.Database, now: () => number) { const spawnsSince = db.prepare<[string, number], { n: number }>("SELECT COUNT(*) AS n FROM workers WHERE binding_id = ? AND started_at >= ?"); const setWorker = db.prepare("UPDATE workers SET status = ?, result = ?, ended_at = ? WHERE thread_id = ?"); + const getFingerprint = db.prepare<[string, string], Record>("SELECT * FROM ops_fingerprints WHERE project_id = ? AND fingerprint = ?"); + const fingerprintsFor = db.prepare<[string], Record>("SELECT * FROM ops_fingerprints WHERE binding_id = ? ORDER BY first_seen_at"); + const sight = db.prepare( + `INSERT INTO ops_fingerprints (project_id, fingerprint, binding_id, summary, first_seen_at, last_seen_at) VALUES (@project_id, @fingerprint, @binding_id, @summary, @at, @at) + ON CONFLICT (project_id, fingerprint) DO UPDATE SET binding_id = @binding_id, summary = @summary, last_seen_at = @at, seen_count = seen_count + 1`, + ); + const setTicket = db.prepare("UPDATE ops_fingerprints SET ticket_key = ?, filed_at = ?, last_commented_at = ? WHERE project_id = ? AND fingerprint = ?"); + const setCommented = db.prepare("UPDATE ops_fingerprints SET ticket_key = ?, last_commented_at = ? WHERE project_id = ? AND fingerprint = ?"); + const getProject = db.prepare<[string], Record>("SELECT * FROM project_stewards WHERE project_id = ?"); const byProjectThread = db.prepare<[string], Record>("SELECT * FROM project_stewards WHERE thread_id = ?"); const upsertProject = db.prepare("INSERT INTO project_stewards (project_id) VALUES (?) ON CONFLICT (project_id) DO NOTHING"); @@ -467,6 +506,18 @@ export function createStore(db: Database.Database, now: () => number) { startedAt: Number(r.started_at), endedAt: r.ended_at === null ? null : Number(r.ended_at), }); + const toFingerprint = (r: Record): Fingerprint => ({ + projectId: String(r.project_id), + fingerprint: String(r.fingerprint), + bindingId: String(r.binding_id), + summary: String(r.summary), + ticketKey: r.ticket_key === null ? null : String(r.ticket_key), + firstSeenAt: Number(r.first_seen_at), + lastSeenAt: Number(r.last_seen_at), + seenCount: Number(r.seen_count), + filedAt: r.filed_at === null ? null : Number(r.filed_at), + lastCommentedAt: r.last_commented_at === null ? null : Number(r.last_commented_at), + }); const toProject = (r: Record): ProjectStewardRow => ({ projectId: String(r.project_id), threadId: r.thread_id === null ? null : String(r.thread_id), @@ -502,7 +553,7 @@ export function createStore(db: Database.Database, now: () => number) { const r = getBinding.get(id); return r === undefined ? null : rowToBinding(r); }, - byEntity(source: Source, entityId: string): Binding | null { + byEntity(source: BindingSource, entityId: string): Binding | null { const r = byEntity.get(source, entityId); return r === undefined ? null : rowToBinding(r); }, @@ -668,6 +719,39 @@ export function createStore(db: Database.Database, now: () => number) { setWorker.run(status, result, status === "running" ? null : now(), threadId); }, + // the fingerprint map + fingerprint(projectId: string, fingerprint: string): Fingerprint | null { + const r = getFingerprint.get(projectId, fingerprint); + return r === undefined ? null : toFingerprint(r); + }, + fingerprints(bindingId: string): Fingerprint[] { + return fingerprintsFor.all(bindingId).map(toFingerprint); + }, + /** Record that a look saw these problems: new ones enter the map with no ticket, known ones count another sighting. */ + sight(projectId: string, bindingId: string, seen: Array<{ fingerprint: string; summary: string }>): Map { + return db.transaction(() => { + const at = now(); + const out = new Map(); + for (const s of seen) { + sight.run({ project_id: projectId, fingerprint: s.fingerprint, binding_id: bindingId, summary: s.summary, at }); + out.set(s.fingerprint, toFingerprint(getFingerprint.get(projectId, s.fingerprint)!)); + } + return out; + })(); + }, + /** + * Record what a steward did about a problem. Filing or reopening points + * the fingerprint at that ticket, so its next sighting is a comment there + * and nothing new; a comment counts as the latest word on it. False when + * the map has no such fingerprint. + */ + recordTicket(projectId: string, fingerprint: string, ticketKey: string, did: TicketAction): boolean { + const at = now(); + const key = ticketKey.toUpperCase(); + const changed = did === "commented" ? setCommented.run(key, at, projectId, fingerprint) : setTicket.run(key, at, at, projectId, fingerprint); + return changed.changes > 0; + }, + // project stewards project(projectId: string): ProjectStewardRow { upsertProject.run(projectId); diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index e97404ee..016d1411 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -1,5 +1,5 @@ // What `bb stewards init` writes into a project's `.bb`: the project file and -// the three default playbooks. They are starting points, meant to be edited +// the four default playbooks. They are starting points, meant to be edited // and reviewed like any other change to `.bb`. import { DEFAULT_BIG_DECISIONS, DEFAULT_LABEL } from "./config.js"; @@ -12,6 +12,8 @@ export function projectFileTemplate(teams: string[]): string { nightly: { at: "01:00", timezone: "America/New_York", until: "02:45", max: 100 }, projectSteward: { model: "claude/claude-opus-5-5/high" }, bigDecisions: DEFAULT_BIG_DECISIONS, + // Add a target, such as { "kind": "k8s-namespace", "name": "bb-gate-production" }, to watch it. + ops: { targets: [], autoAdopt: [] }, }, null, 2, @@ -170,8 +172,68 @@ Run a round when one is due; otherwise there is nothing to do. The author took it back to draft. Do nothing until it is ready again. `; +// No phases and nothing terminal: an ops binding watches its target for as +// long as the project file lists it. Its sections are keyed by what a look +// found instead: new, recurring, returned. +export const OPS_WATCH = `--- +name: ops-watch +kind: ops +source: k8s +may: [read, file-ticket, comment, escalate] +models: + steward: claude/claude-sonnet-5-5/medium +requeue-default: 1h +--- + +You watch one production target and turn what goes wrong there into Linear +tickets. You never change production: no restarts, no scaling, no edits, no +workers. You read what each wake shows, file tickets, comment on them, and +escalate to the project steward, which decides whether a ticket is worked. + +The plugin looks at the target for you: pod health, Warning events, and the +last log lines of a failing container where the server may read logs. Where +it may not (bb-gate-production grants no logs), diagnose from status and +events, and say in the ticket that logs were not available. + +Each problem has a fingerprint: the workload, the container and an error +signature. Put it in the ticket description on a line of its own, +"Fingerprint: \`\`", so a person can match ticket and problem. +After acting, report every ticket you filed, commented on or reopened in +steward_report's opsTickets: that is how the next look knows a problem is +already filed. + +A ticket you file says: which pod and container, since when and how often; +the evidence (status, events, log lines) quoted; your diagnosis, the likely +cause and what would confirm it; and a priority: urgent when users cannot +work, high when a service is degraded, medium otherwise. Search the team for +an open ticket about the same problem first (linear_search), and comment +there instead of filing a second one. + +## New + +File one ticket per problem, in the team the wake names. Then raise one +decision escalation to the project steward for every ticket filed this turn: +"Filed BB-N (high): . Recommend adopting." Meanwhile: keep +watching. A priority ops.autoAdopt names is labelled when filed, as the +wake says; such a ticket needs no escalation. + +## Recurring + +The problem is still there and its ticket is open. Comment on that ticket +when the evidence moved since your last comment (more restarts, a new error, +a new pod), and at most once every few hours otherwise. File nothing new. + +## Returned + +The problem is back after its ticket was resolved. If the ticket was closed +within the last two weeks, comment on it with the new evidence and escalate +a decision recommending it be reopened. Otherwise file a new ticket that +links the old one, and escalate it as a new one. +`; + export const PLAYBOOK_TEMPLATES: Record = { "linear-tickets": LINEAR_TICKETS, "github-prs": GITHUB_PRS, "github-reviews": GITHUB_REVIEWS, + "ops-watch": OPS_WATCH, }; diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 40b2f2ef..38dff496 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -6,6 +6,7 @@ // transcript stop being the source of truth. import { formatDuration, phaseInstructions, type Playbook } from "./config.js"; import { localParts } from "./nightly.js"; +import { FINDING_CLASSES, type FindingClass, type OpsFinding, type OpsLook } from "./ops.js"; import { newHumanComments, reportedItem, unheardWait, type GateState } from "./reconcile.js"; import type { EntitySnapshot, SnapshotComment } from "./source-contract.js"; import type { Binding, Escalation, Observed, Question, Worker } from "./store.js"; @@ -238,6 +239,100 @@ export function formatWake(input: WakeInput): string { return fit(head, snapshot, out); } +export type OpsWakeInput = { + reason: WakeReason; + binding: Binding; + playbook: Playbook; + look: OpsLook; + /** The Linear team tickets are filed in. */ + team: string | null; + label: string; + /** Priorities whose tickets are labelled when filed (ops.autoAdopt). */ + autoAdopt: string[]; + escalations: Escalation[]; + changes: string[]; +}; + +const OPS_LIFECYCLE: Partial> = { + adopted: "You have just been made the ops steward for this target. Read everything below, then act on what the look found.", + reopen: "This target is configured again and its binding has resumed. Re-read everything below as if new.", + nightly: "This is the nightly reconcile pass: check that every problem below is filed, and report.", +}; + +const CLASS_TITLES: Record = { new: "New: no ticket yet", recurring: "Recurring: its ticket is open", returned: "Returned: its ticket was resolved" }; + +function findingLines(f: OpsFinding, look: OpsLook): string[] { + const lines = [`#### ${f.fingerprint}`, ""]; + const ticket = f.ticket === null ? "" : ` · ticket ${f.ticket}${f.ticketState === null ? "" : ` (${f.ticketState})`}${f.lastCommentedAt === null ? "" : `, your last word on it ${iso(f.lastCommentedAt)}`}`; + lines.push(`- ${f.summary}`); + lines.push(`- Workload ${f.workload}; pod${f.pods.length === 1 ? "" : "s"} ${f.pods.join(", ")}${f.container === null ? "" : `; container ${f.container}`}; first seen ${iso(f.firstSeenAt)}${ticket}`); + if (f.events.length > 0) lines.push("- Warning events, newest first:", ...f.events.map((e) => ` - ${e}`)); + if (f.logs !== null) lines.push(`- Last log lines${f.previous ? " of the run that ended" : ""}:`, "", "```", ...(f.logs.length === 0 ? ["(empty)"] : f.logs), "```"); + else if (f.container !== null) lines.push(look.logs === "not granted" ? "- Logs: not readable from this server (no pods/log grant here). Diagnose from status and events, and say so in the ticket." : "- Logs: not read."); + return [...lines, ""]; +} + +/** An ops binding's wake: instructions, steering, the look, what changed. */ +export function formatOpsWake(input: OpsWakeInput): string { + const { binding, playbook, look } = input; + const out: string[] = []; + out.push(`# Ops watch: ${look.target}`); + out.push(`Binding ${binding.id} · ops · playbook ${playbook.name}@${playbook.version} · looked ${iso(look.at)}`); + out.push("", `${binding.threadId === null ? "Your thread id is in `$BB_THREAD_ID`." : `Your thread id is ${binding.threadId}.`} Use it wherever you name yourself, and never take one from your workspace's path: you share the project steward's workspace, and its path names that thread.`); + const special = OPS_LIFECYCLE[input.reason]; + if (special !== undefined) out.push("", `**${special}**`); + + out.push("", "## 1. Instructions"); + if (playbook.general !== "") out.push("", playbook.general); + const present = FINDING_CLASSES.filter((c) => look.findings.some((f) => f.class === c)); + for (const c of present) { + const section = phaseInstructions(playbook, c); + if (section !== null) out.push("", `### ${c.charAt(0).toUpperCase()}${c.slice(1)}`, "", section); + } + out.push("", `Allowed actions: ${playbook.may.join(", ") || "(none)"}.`); + out.push(input.team === null ? "No Linear team is configured to file in: escalate a blocked question instead of filing." : `File tickets in the Linear team ${input.team} with linear_create_issue.`); + if (input.autoAdopt.length > 0) { + out.push( + `ops.autoAdopt: a ticket you file at ${input.autoAdopt.join(" or ")} priority is adopted at once: add the label \`${input.label}\` and move it to Todo when you file it, and raise no escalation for it. Say in your report that you did.`, + ); + } + + out.push("", "## 2. Guidance, priority and holds", ""); + if (binding.guidance.length === 0) out.push("No standing guidance."); + for (const g of binding.guidance) out.push(`- ${iso(g.at)} (${g.by}): ${g.text}`); + out.push(`- Priority: ${binding.priority ?? "normal"}`); + out.push(binding.hold === null ? "- Hold: none" : `- **HOLD: ${binding.hold}** — file and comment nothing until it is lifted.`); + + const head = out.splice(0); + out.push("", "## 3. The look", ""); + out.push(`- ${look.pods} pod${look.pods === 1 ? "" : "s"}, ${look.healthy} healthy; logs: ${look.logs === "read" ? "read where a finding needed them" : look.logs === "not granted" ? "not granted on this target" : "none needed"}`); + if (look.deployments.length > 0) out.push(`- Deployments: ${look.deployments.map((d) => `${d.name} ${d.ready}/${d.desired}`).join(", ")}`); + for (const n of look.notes) out.push(`- ${n}`); + if (look.findings.length === 0) out.push("", "Nothing is failing."); + for (const c of present) { + out.push("", `### ${CLASS_TITLES[c]}`, ""); + for (const f of look.findings.filter((x) => x.class === c)) out.push(...findingLines(f, look)); + } + if (look.warnings.length > 0) out.push("", "### Other warning events", "", ...look.warnings.map((w) => `- ${w}`)); + const open = input.escalations.filter((x) => x.status === "open"); + if (open.length > 0) { + out.push("", "### Open escalations", ""); + for (const x of open) out.push(`- ${x.id} (${x.kind}, with ${x.route === "me" ? "the user" : "the project steward"}): ${x.question}`); + } + + const snapshot = out.splice(0); + out.push("", "## 4. What changed since your last turn", ""); + if (input.changes.length === 0) out.push("Nothing new; this is a scheduled look."); + for (const c of input.changes) out.push(`- ${c}`); + out.push( + "", + "---", + "Before filing, look for evidence that you already did (a signed ticket or comment with the fingerprint). " + + `End your turn with steward_report, listing in opsTickets every ticket you filed, commented on or reopened, by fingerprint: { fingerprint, ticket: "${input.team ?? "ENG"}-123", did: "filed" | "commented" | "reopened" }. requeueAfter defaults to ${formatDuration(playbook.requeueDefaultMs)}.`, + ); + return fit(head, snapshot, out); +} + /** What the project steward is woken with, at the end of a nightly pass or when an escalation reaches it. */ export function formatProjectWake(input: { reason: string; @@ -255,6 +350,8 @@ export function formatProjectWake(input: { records?: DigestRecords; /** The project's nightly time zone, which dates are given in; UTC when absent. */ timeZone?: string; + /** The adoption label, for adopting what an ops steward filed. */ + label?: string; }): string { const day = dayIn(input.timeZone ?? "UTC"); const out: string[] = [`# Project steward: ${input.reason}`, ""]; @@ -274,6 +371,12 @@ export function formatProjectWake(input: { ...input.bigDecisions.map((d) => `- ${d}`), "", ); + if (input.routed.some((r) => r.from.kind === "ops")) { + out.push( + `An escalation from an ops steward is a ticket it filed about production, with a priority and a recommendation. Adopt it when the project's guidance says the problem is worth working: add the label \`${input.label ?? "bb-managed"}\` and move it to Todo (linear_update_issue), and a ticket steward picks it up; then resolve the escalation with guidance saying so. Otherwise decline: resolve it with guidance giving the reason.`, + "", + ); + } if (input.routed.some((r) => r.escalation.kind === "approval")) { out.push( "An approval escalation is the plugin's: the ticket's ready gate waits on you. Judge the spec (`bb stewards show `, and the ticket itself) against the project's guidance. Approve it with steward_update { binding, approve: true }, which closes the request; or decline with steward_update { binding, guidance: what must change, resolve }. If the steward also escalated asking for this approval, resolve that one too.", From d909253bdaa8a2b343a480e6968e5a6fd68107e9 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 16:13:47 +0000 Subject: [PATCH 2/5] stewards: an ops steward takes a turn at every requeue, healthy or not (BB-9) The acceptance criterion is a turn every requeue-default. A requeue now wakes the ops steward whatever the look found; a healthy one is a short wake saying all is healthy, reported with actor other, which archives the thread until the next look. A sweep's look between requeues still wakes it only for a new or returned problem. Co-Authored-By: Claude Opus 5.5 --- plugins/stewards/DESIGN.md | 10 ++++---- plugins/stewards/README.md | 7 +++--- plugins/stewards/server.test.ts | 28 +++++++++++++++++++++++ plugins/stewards/server.ts | 10 ++++---- plugins/stewards/skills/stewards/SKILL.md | 6 +++-- plugins/stewards/templates.ts | 3 ++- plugins/stewards/wake.ts | 2 +- 7 files changed, 51 insertions(+), 15 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index a5a6496f..3360e71e 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -749,7 +749,7 @@ goes wrong there into Linear tickets for the project steward to adopt. reads each ticket's state through linear's `sourceSnapshot`: - **new** — no ticket. Worth a turn at once. - **recurring** — its ticket is open, or cannot be read (a comment on a - closed ticket does less harm than a duplicate). Worth a turn only at the + closed ticket does less harm than a duplicate). Worth a turn at the requeue, so a crash loop is one comment per `requeue-default`, and never a second ticket. - **returned** — its ticket was Done or Canceled and the problem is back. @@ -757,9 +757,11 @@ goes wrong there into Linear tickets for the project steward to adopt. between reopening and filing anew; the default comments on a ticket closed within two weeks and escalates a reopen, and otherwise files a new ticket linking the old one. - A look that finds nothing failing wakes nobody: the binding's next look - is a `requeue-default` away, and its last report stands. A nightly pass - turn still comes. + Every `requeue-default` the steward takes a turn whatever the look + found; a healthy one is cheap, a wake that says "all healthy" and a + report with actor `other`, which archives the thread until the next + look. A sweep's look between requeues wakes it only for a new or + returned problem. - **Triage is the project steward's.** The steward files one ticket per new problem — pod, since when, the evidence, a diagnosis, a priority, and the fingerprint on a line of its own — and raises one `decision` escalation diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 09a5dc0a..84860737 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -27,9 +27,10 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. problem by a fingerprint (workload, container, error signature; [ops.ts](ops.ts)) and keeps a fingerprint → Linear ticket map. A new problem, or one back after its ticket was resolved, wakes the steward at - once; one still failing under its open ticket wakes it at the requeue - (`requeue-default`, 1h in the template), to comment there and file - nothing new. A look that finds nothing wrong wakes nobody. The steward + once. Every requeue (`requeue-default`, 1h in the template) is a turn + whatever the look found: a problem still failing under its open ticket is + a comment there and nothing new filed, and a healthy look is a short + "all healthy" report. The steward files one ticket per problem and escalates a `decision` to the project steward ("Filed BB-N (high), recommend adopting"); the project steward adopts with the label and Todo, the ordinary path. It never changes the diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index ffdfc828..353c8fc1 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -1620,6 +1620,34 @@ describe("ops stewards", () => { expect(back).toMatch(/escalate\s+a decision recommending it be reopened/u); }); + it("takes a short turn at every requeue when all is healthy, and none between", async () => { + const { t, c, steward, wakes } = await watched(); + c.state.pods = []; + c.state.events = []; + const ops = steward()!; + expect((await t.tool("steward_report", { phase: "watching", summary: "Filed ENG-50.", nextAction: "Watch", actor: "other" }, ops.id)).error).toBe(false); + await t.idle(ops.id); + const before = wakes().length; + + // A sweep's look before the requeue: healthy, nothing new, nobody woken. + t.advance(30 * 60_000); + await t.hooks.sweep(); + await t.flush(); + expect(wakes()).toHaveLength(before); + + // The requeue is a turn all the same, saying so, and its report archives the thread until the next. + t.advance(31 * 60_000); + await t.hooks.sweep(); + await t.flush(); + expect(wakes()).toHaveLength(before + 1); + const healthy = wakes().at(-1)!; + expect(healthy).toMatch(/All healthy: nothing is failing\./u); + expect(healthy).toMatch(/Requeue time came: a scheduled look/u); + expect(healthy).not.toMatch(/#### /u); + const report = await t.tool("steward_report", { phase: "watching", summary: "All healthy.", nextAction: "Look again", actor: "other" }, ops.id); + expect(report.text).toMatch(/Your thread is archived when the turn ends/u); + }); + it("makes a binding that waits while the server cannot read its target, and wakes once it can", async () => { const { t, c, steward } = await watched({ error: "403: pods is forbidden" }); expect(await t.list()).toMatchObject([{ key: TARGET, kind: "ops", threadId: null }]); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 4a0f0078..8189abe8 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -1052,9 +1052,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // entity in a source plugin. Its steward's thread has no cluster access, // so the plugin looks (kube.ts), compares what it saw with the // fingerprint map, and wakes the steward with the look: at once for a - // problem that is new or back after its ticket was resolved, and at the - // requeue for one still failing under its open ticket. A look that finds - // nothing wrong is recorded and wakes nobody. + // problem that is new or back after its ticket was resolved, and at every + // requeue whatever it finds, so a problem still failing under its open + // ticket is one comment per interval and a healthy look is one short + // "all healthy" report. A sweep's look between requeues that finds + // nothing new is recorded and wakes nobody. const opsReader = deps.ops ?? createKubeReader(); @@ -1100,7 +1102,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } const changes = lookChanges(before, look); - if (requeueCame && look.findings.length > 0) changes.push({ text: "Requeue time came, with problems still failing", actionable: true }); + if (requeueCame) changes.push({ text: look.findings.length > 0 ? "Requeue time came, with problems still failing" : "Requeue time came: a scheduled look", actionable: true }); if (b.playbookVersion !== playbook.version) changes.push({ text: `Playbook ${playbook.name} updated (${b.playbookVersion} → ${playbook.version})`, actionable: false }); const queued = b.pending; const loudQueued = queued.filter((n) => n.quiet !== true).length; diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 0b0c374d..c47156a9 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -104,6 +104,8 @@ production and start no workers. ticket, did: "filed" | "commented" | "reopened" }] }`, by the fingerprint the wake gives. That is what makes the next look a comment instead of a duplicate. +- **All healthy:** the wake says so every requeue; report it with + `actor: other` and end the turn. - **No logs** (the wake says so on `bb-gate-production`): diagnose from status and events, and say in the ticket that logs were not available. @@ -184,8 +186,8 @@ above which a steward is compacted after its turn. - **An ops steward never wakes.** `bb stewards list` shows `cannot read the target` and `bb stewards check` says why: this server has no ServiceAccount (bb-gate mounts one only into the backend of the developer - who runs the project's ops steward), or it may not list pods there. A look - that finds nothing failing wakes nobody, by design. + who runs the project's ops steward), or it may not list pods there. + Otherwise it takes a turn every `requeue-default`, healthy or not. - **A repo should not be stewarded.** Every GitHub repo in `repos.json` is, unless `project.json` lists it in `github.exclude` (`owner/repo`). Bindings already running there end with `bb stewards detach`. diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 016d1411..64c02993 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -200,7 +200,8 @@ signature. Put it in the ticket description on a line of its own, "Fingerprint: \`\`", so a person can match ticket and problem. After acting, report every ticket you filed, commented on or reopened in steward_report's opsTickets: that is how the next look knows a problem is -already filed. +already filed. When the wake says all is healthy, just report it, with actor +other, and end the turn. A ticket you file says: which pod and container, since when and how often; the evidence (status, events, log lines) quoted; your diagnosis, the likely diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 38dff496..32bf64de 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -308,7 +308,7 @@ export function formatOpsWake(input: OpsWakeInput): string { out.push(`- ${look.pods} pod${look.pods === 1 ? "" : "s"}, ${look.healthy} healthy; logs: ${look.logs === "read" ? "read where a finding needed them" : look.logs === "not granted" ? "not granted on this target" : "none needed"}`); if (look.deployments.length > 0) out.push(`- Deployments: ${look.deployments.map((d) => `${d.name} ${d.ready}/${d.desired}`).join(", ")}`); for (const n of look.notes) out.push(`- ${n}`); - if (look.findings.length === 0) out.push("", "Nothing is failing."); + if (look.findings.length === 0) out.push("", "**All healthy: nothing is failing.** There is nothing to file or comment on: report that with steward_report (actor other) and end the turn."); for (const c of present) { out.push("", `### ${CLASS_TITLES[c]}`, ""); for (const f of look.findings.filter((x) => x.class === c)) out.push(...findingLines(f, look)); From 0a7d31fb4a68ae0d17532e9157377582c76f5385 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 17:27:27 +0000 Subject: [PATCH 3/5] stewards: ops looks with kubectl on the developer's machine, behind a verb gate (BB-9) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The spec changed: there is no ServiceAccount, and nothing changes in bb-gate or devbox. The project's machine, the developer's own, reaches the cluster with kubectl as them (bc-prod through the Tailscale API proxy). kube.ts and its in-pod API client are gone. A host entry (host.ts, one method, opsKubectl) runs kubectl on the project's machine, and kubectl.ts reads pods, events, deployments and logs with it. Every call passes one function, kubectlRefusal, on the server and again on the host: only get, describe, logs and auth can-i, and no flag that swaps the kubeconfig, credentials or identity. A stricter wall can slot in behind it later. ops-watch.md's may list is kubectl get, describe, logs and auth can-i, then filing, commenting and escalating. bb stewards check runs kubectl per target and reports "cannot read the target" when it cannot reach it; writes the developer holds are said, not counted as problems. ops.context picks a kubeconfig context. DESIGN.md §18, README and the skill say so; the tests use a fake kubectl, and host.ts is tested against a fake kubectl script. Co-Authored-By: Claude Opus 5.5 --- plugins/stewards/DESIGN.md | 85 ++++++---- plugins/stewards/README.md | 36 ++-- plugins/stewards/config.test.ts | 4 +- plugins/stewards/config.ts | 7 +- plugins/stewards/host-contract.ts | 12 ++ plugins/stewards/host.ts | 35 ++++ plugins/stewards/kube.ts | 196 ---------------------- plugins/stewards/kubectl.test.ts | 80 +++++++++ plugins/stewards/kubectl.ts | 133 +++++++++++++++ plugins/stewards/ops.ts | 4 +- plugins/stewards/package.json | 1 + plugins/stewards/server.test.ts | 104 ++++++++---- plugins/stewards/server.ts | 64 ++++--- plugins/stewards/skills/stewards/SKILL.md | 15 +- plugins/stewards/templates.ts | 13 +- plugins/stewards/wake.ts | 2 +- 16 files changed, 468 insertions(+), 323 deletions(-) create mode 100644 plugins/stewards/host-contract.ts create mode 100644 plugins/stewards/host.ts delete mode 100644 plugins/stewards/kube.ts create mode 100644 plugins/stewards/kubectl.test.ts create mode 100644 plugins/stewards/kubectl.ts diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 3360e71e..ee6e91ec 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -696,9 +696,8 @@ plugins' contract before stewards uses them, bb-plugins before bb-gate. 4. **Reviews.** Review bindings, review workers. 5. **Board.** Built: the Stewards page, the question record (§12), and the digest assembled from records. -6. **Ops.** Built in this plugin (§18). It reads only what bb-gate grants the - server, so the read-only cluster access in `bb-gate` lands first; until - it does, ops bindings wait and `bb stewards check` says why. +6. **Ops.** Built in this plugin (§18), with kubectl on the developer's + machine; nothing changes in bb-gate or devbox. ## 18. Ops stewards @@ -726,14 +725,18 @@ goes wrong there into Linear tickets for the project steward to adopt. steward and has no workers. On the Stewards page it is grouped as `watch`; in `bb stewards list` it shows when it last looked and how many problems are failing. -- **The plugin looks; the steward judges.** Steward threads run on a - developer's machine with no cluster access, so the plugin reads the - target itself, from the bb-server pod, with the ServiceAccount bb-gate - mounts there (`kube.ts`): pods, Warning events, Deployments, and the last - log lines of a failing container where `pods/log` is granted, with - obvious credentials redacted. A look happens at every sweep and requeue. - It is the ops binding's snapshot (`bindings.ops_look`), and the wake - carries it. +- **The plugin looks with kubectl, as the developer; the steward judges.** + There is no cluster identity of the plugin's own. The project's machine + — the developer's, a tailnet node, where the steward's turns run too — + has `kubectl`, which reaches the cluster through the developer's + kubeconfig (for bc-prod, the Tailscale API proxy) as them. The plugin's + server is elsewhere, so it asks the machine to run kubectl through its + host entry (`host.ts`, one method, `opsKubectl`), and reads with it + (`kubectl.ts`): pods, Warning events, Deployments, and the last log lines + of a failing container, with obvious credentials redacted. `ops.context` + names the kubeconfig context; the machine's current one otherwise. A look + happens at every sweep and requeue. It is the ops binding's snapshot + (`bindings.ops_look`), and the wake carries it. - **Fingerprints.** A problem is named by its target, its workload (a Deployment's pods share it whatever their generated names, so a rollout or a second replica is the same problem), its container, and an error @@ -770,20 +773,27 @@ goes wrong there into Linear tickets for the project steward to adopt. Todo, the ordinary path, and the team lease brings a ticket steward; or declines with a reason. `ops.autoAdopt` names priorities the ops steward labels itself when filing, without escalating. -- **`may` is `[read, file-ticket, comment, escalate]`**, and like every - `may` list it is advisory (§11). The wall is RBAC: the ServiceAccount - holds get, list and watch on pods, events and deployments, and - `pods/log` only where no developer's backend runs; nothing mutating. The - plugin itself only issues GETs, plus SelfSubjectAccessReviews for - `check`, which change nothing. +- **Read-only is a convention, not a wall.** kubectl acts as the + developer, whose rights are broad. Every kubectl call the plugin makes + passes one function, `kubectlRefusal`, checked by the server before it + asks and by the host entry before it runs: only `get`, `describe`, + `logs` and `auth can-i`, and no flag that swaps the kubeconfig, + credentials or identity. The playbook's `may` list says the same for the + steward's own kubectl (`kubectl get`, `describe`, `logs`, `auth can-i`, + then filing, commenting and escalating), and like every `may` list it is + advisory (§11): nothing stops the steward's shell. A real wall, such as a + read-only identity for kubectl, would slot in behind that one function. - **`bb stewards check`** validates `ops` (namespace names, duplicates, - that the team is one of `linear.teams`), then asks the API server, for - each target, whether this server can list its pods, events and - deployments and read its logs. A target it cannot read is a problem, as is - any write the account holds there. -- **Before the access exists** (no token mounted, or a 403), the binding is - made but its steward is not spawned or woken; `bb stewards list` shows - `cannot read the target`, and the first look that succeeds wakes it. + that the team is one of `linear.teams`), then runs kubectl on the + project's machine for each target: `get` its pods, events and + deployments, and `auth can-i` for its logs. A target kubectl cannot + reach — no kubectl, the machine not on the tailnet as the developer, no + kubeconfig or context for the cluster, pods forbidden — is a problem, + "cannot read the target". Writes the identity holds there are said, not + counted as a problem: they are expected of a developer. +- **When kubectl cannot read the target**, the binding is made but its + steward is not spawned or woken; `bb stewards list` shows `cannot read + the target`, and the first look that succeeds wakes it. ## Known limits @@ -799,19 +809,20 @@ goes wrong there into Linear tickets for the project steward to adopt. through bb-gate-hooks, and the deploy in the snapshot) would be new work in three repos. Until then, a playbook that wants a deploy watched has the steward follow through (§5) while a worker watches and verifies it. -- **One server watches production.** An ops binding runs on the server of - the developer who runs the project's stewards, the only one bb-gate gives - the ServiceAccount, like everything else here (one developer per - project). Nothing looks while that server is down, and in particular - during bb-gate's 03:00–05:00 US Eastern quiet window, when staged updates - restart servers: a crash in that window is seen at the first look after. - Nothing pages anyone either: this is periodic looks, not alerting. -- **Logs are partial.** In `bb-gate-production`, where developers' own - backends run, RBAC cannot grant `pods/log` for some pods only, so there - are no logs: diagnosis is from status and events. Healthy pods' logs are - never scanned, so an error that does not crash, restart or unready a pod - goes unseen. Push sources (Sentry, alerts through bb-gate-hooks) would - cover that, and are separate work. +- **One developer's server and machine watch production.** An ops binding + runs on the server of the developer who runs the project's stewards, and + looks with kubectl on their machine, as them, like everything else here + (one developer per project). Nothing looks while either is down: in + particular during bb-gate's 03:00–05:00 US Eastern quiet window, when + staged updates restart servers, and while the machine is off or off the + tailnet. A crash then is seen at the first look after. Nothing pages + anyone either: this is periodic looks, not alerting. +- **Read-only rests on the gate and the playbook.** kubectl runs with the + developer's own rights (§18); a steward that ignored its `may` list could + use them. +- **Healthy pods' logs are never scanned**, so an error that does not + crash, restart or unready a pod goes unseen. Push sources (Sentry, alerts + through bb-gate-hooks) would cover that, and are separate work. - **Comments and the team lease.** bb-gate-hooks does not always know a Linear comment's team, so a team lease alone misses some comments. That is why every binding also holds an issue lease for its own entity (§16). diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 84860737..69b81c72 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -20,10 +20,11 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. steward's workers nested under it; see DESIGN.md §15. - **Ops stewards.** Each target in the project file's `ops.targets` (a Kubernetes namespace) gets an `ops` steward, reporting to the project - steward, for as long as it is listed. The plugin looks at the target from - the bb-server pod with the ServiceAccount bb-gate mounts there - ([kube.ts](kube.ts)): pods, Warning events, Deployments, and a failing - container's last log lines where `pods/log` is granted. It names each + steward, for as long as it is listed. The plugin looks at the target with + `kubectl` on the project's machine, the developer's own, as them (through + its host entry, [host.ts](host.ts), and [kubectl.ts](kubectl.ts)): pods, + Warning events, Deployments, and a failing container's last log lines. + It names each problem by a fingerprint (workload, container, error signature; [ops.ts](ops.ts)) and keeps a fingerprint → Linear ticket map. A new problem, or one back after its ticket was resolved, wakes the steward at @@ -33,10 +34,12 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. "all healthy" report. The steward files one ticket per problem and escalates a `decision` to the project steward ("Filed BB-N (high), recommend adopting"); the project steward - adopts with the label and Todo, the ordinary path. It never changes the - cluster: its playbook allows reading, filing, commenting and escalating, - and RBAC allows only reads. Until the server can read a target, its - binding waits and `bb stewards check` says why. DESIGN.md §18. + adopts with the label and Todo, the ordinary path. Every kubectl call the + plugin makes passes one gate that allows only `get`, `describe`, `logs` + and `auth can-i`, and the playbook's `may` list holds the steward to the + same; the developer's own rights are broad, so that is a convention, not a + wall. Until kubectl can read a target, its binding waits and `bb stewards + check` says "cannot read the target". DESIGN.md §18. - **The reconcile loop.** linear and github-watcher hold bb-gate-hooks leases for the project's teams and repos and for every bound entity, and ring this plugin on a doorbell. A ring is debounced, the entity is snapshotted, compared with @@ -159,7 +162,8 @@ version. Project file fields beyond the design: `nightly.until`, defaults in [config.ts](config.ts)), and `ops`: `targets` (`{ kind: "k8s-namespace", name }`, at most ten), `team` (where tickets are filed; the first of `linear.teams` by default, and it must be one of them) and -`autoAdopt` (Linear priorities, `urgent`, `high`, `medium`, `low`, whose +`context` (the kubeconfig context kubectl uses; the machine's current one +when left out) and `autoAdopt` (Linear priorities, `urgent`, `high`, `medium`, `low`, whose tickets the ops steward labels for a steward itself when it files them). `ops-watch.md` is read only when `ops.targets` lists something. @@ -186,9 +190,9 @@ None beyond the playbook's word. A steward acts with the user's credentials and a shell; its `may` list and the ready gate are stated in every wake, and everything it writes is signed with its thread, so what it did is visible afterwards. The runaway guard is the one hard stop. GitHub writes go through -`gh`; there are no write tools to check. Ops stewards are the exception -where a wall exists: the cluster access bb-gate grants is read-only, and -`bb stewards check` reports any write it finds. +`gh`; there are no write tools to check. Ops stewards are no exception: +kubectl acts as the developer, and only the plugin's verb gate and the +playbook keep the steward to reading. ## The contract with linear and github-watcher @@ -209,7 +213,7 @@ bb plugin build Deployment needs this directory added to bb-gate's `docker/bb-server/Dockerfile` (the sparse checkout, the `mv`, and `BB_PLUGIN_DIRS`), and multi-repo, linear and github-watcher at versions that serve -the contract. Ops stewards need bb-gate to mount a read-only ServiceAccount -into the backend of the developer who runs them, at the standard path -(`/var/run/secrets/kubernetes.io/serviceaccount`: `token` and `ca.crt`); -the plugin calls `https://kubernetes.default.svc`. +the contract. Ops stewards need `kubectl` on the project's machine, with a +kubeconfig that reaches the cluster as the developer (for bc-prod, the +Tailscale API proxy: the machine on the tailnet as its developer, not a +tagged node). The plugin's host entry runs it there. diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index a826b7a9..e26c009c 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -105,11 +105,11 @@ describe("playbooks", () => { }); describe("the ops playbook", () => { - it("has no phases or terminal states, sections for what a look found, and a may list that only reads, files, comments and escalates", () => { + it("has no phases or terminal states, sections for what a look found, and a may list of read-only kubectl, filing, commenting and escalating", () => { const parsed = parsePlaybook(OPS_WATCH, "ops-watch"); if (!parsed.ok) throw new Error(parsed.error); const p = parsed.value; - expect(p).toMatchObject({ kind: "ops", source: "k8s", phases: {}, terminal: [], ready: null, may: ["read", "file-ticket", "comment", "escalate"], requeueDefaultMs: 3_600_000 }); + expect(p).toMatchObject({ kind: "ops", source: "k8s", phases: {}, terminal: [], ready: null, may: ["kubectl get", "kubectl describe", "kubectl logs", "kubectl auth can-i", "file-ticket", "comment", "escalate"], requeueDefaultMs: 3_600_000 }); expect(phaseInstructions(p, "new")).toMatch(/File one ticket per problem/u); expect(phaseInstructions(p, "recurring")).toMatch(/File nothing new/u); expect(phaseInstructions(p, "returned")).toMatch(/reopened/u); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index b6855c2c..5e7ad111 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -148,13 +148,16 @@ export const projectFileSchema = z * Production to watch: one ops binding per target, which files a Linear * ticket for each problem it finds and escalates it to the project * steward. `team` is where tickets are filed (the first of linear.teams - * when left out); `autoAdopt` names the priorities whose tickets are - * labelled for a steward when filed, without asking. + * when left out); `context` is the kubeconfig context kubectl reads it + * with; `autoAdopt` names the priorities whose tickets are labelled for + * a steward when filed, without asking. */ ops: z .object({ targets: z.array(opsTargetSchema).max(10).default([]), team: teamKey.optional(), + /** The kubeconfig context kubectl uses on the developer's machine; its current context when left out. */ + context: z.string().trim().min(1).max(200).regex(/^[^\s-][^\s]*$/u, "a kubeconfig context name").optional(), autoAdopt: z.array(z.enum(LINEAR_PRIORITIES)).max(4).default([]), }) .strict() diff --git a/plugins/stewards/host-contract.ts b/plugins/stewards/host-contract.ts new file mode 100644 index 00000000..af1c1237 --- /dev/null +++ b/plugins/stewards/host-contract.ts @@ -0,0 +1,12 @@ +// What stewards' server asks of its host entry (host.ts), on the developer's +// machine. One method: run kubectl, for the ops kind, with arguments that +// pass kubectlRefusal on both sides. +import { defineRpcContract } from "@get-bb/plugin-sdk"; +import { z } from "zod"; + +export const hostContract = defineRpcContract({ + opsKubectl: { + input: z.object({ args: z.array(z.string().min(1).max(300)).min(1).max(30), timeoutMs: z.number().int().min(1000).max(120_000) }).strict(), + output: z.object({ exitCode: z.number().int(), stdout: z.string(), stderr: z.string(), missing: z.boolean() }).strict(), + }, +}); diff --git a/plugins/stewards/host.ts b/plugins/stewards/host.ts new file mode 100644 index 00000000..bad1ae2f --- /dev/null +++ b/plugins/stewards/host.ts @@ -0,0 +1,35 @@ +// The host entry: the part of stewards that runs on the developer's machine, +// where kubectl and its kubeconfig are. It runs only what kubectlRefusal +// allows (get, describe, logs, auth can-i), whatever the server sends. +import { execFile } from "node:child_process"; +import { experimental_defineHostEntry, experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host"; +import { hostContract } from "./host-contract.js"; +import { kubectlRefusal } from "./kubectl.js"; + +/** A namespace's pods as JSON can be large; past this, kubectl's output is cut and fails to parse rather than flooding the call. */ +const MAX_OUTPUT_BYTES = 16 * 1024 * 1024; + +export function runKubectlHere(args: string[], timeoutMs: number, command = "kubectl"): Promise<{ exitCode: number; stdout: string; stderr: string; missing: boolean }> { + const refused = kubectlRefusal(args); + if (refused !== null) return Promise.resolve({ exitCode: 126, stdout: "", stderr: refused, missing: false }); + return new Promise((resolve) => { + execFile( + command, + args, + { timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, env: { ...experimental_sanitizeInheritedChildProcessEnv({ env: process.env }), NO_COLOR: "1" }, windowsHide: true }, + (error, stdout, stderr) => { + const e = error as (Omit & { code?: string | number; killed?: boolean }) | null; + if (e?.code === "ENOENT") return resolve({ exitCode: 127, stdout: "", stderr: `${command}: not found`, missing: true }); + const exitCode = e === null ? 0 : typeof e.code === "number" ? e.code : 1; + resolve({ exitCode, stdout: String(stdout), stderr: e !== null && e.killed ? `kubectl did not finish in ${timeoutMs / 1000}s` : String(stderr), missing: false }); + }, + ); + }); +} + +export default experimental_defineHostEntry({ + contract: hostContract, + handlers: { + opsKubectl: ({ args, timeoutMs }) => runKubectlHere(args, timeoutMs), + }, +}); diff --git a/plugins/stewards/kube.ts b/plugins/stewards/kube.ts deleted file mode 100644 index 3a946746..00000000 --- a/plugins/stewards/kube.ts +++ /dev/null @@ -1,196 +0,0 @@ -// The ops kind's eyes: read-only calls to the Kubernetes API from the -// bb-server pod, with the ServiceAccount bb-gate mounts into the backend of -// the developer who runs the project's ops steward. Steward threads run on a -// machine with no cluster access, so the plugin looks and the wake carries -// what it saw. -// -// Only GETs, plus SelfSubjectAccessReviews for `bb stewards check`, which -// ask the API server what the account may do and change nothing. RBAC is -// the wall (DESIGN.md §11); this file never builds a write. -import { readFileSync } from "node:fs"; -import https from "node:https"; -import { join } from "node:path"; -import { deploymentsOf, eventsOf, findingsOf, logTail, otherWarnings, podsOf, type OpsTarget, type RawLook } from "./ops.js"; - -export const SERVICE_ACCOUNT_DIR = "/var/run/secrets/kubernetes.io/serviceaccount"; -export const IN_CLUSTER_API = "https://kubernetes.default.svc"; -const TIMEOUT_MS = 15_000; -/** Logs are read for at most this many findings per look. */ -const LOGS_PER_LOOK = 5; - -/** What `bb stewards check` reports for one target. */ -export type OpsAccess = { - /** Set when nothing could be asked: no credentials, or the API server unreachable. */ - error: string | null; - /** Each read a look makes, and whether it works. */ - reads: Array<{ what: string; ok: boolean; detail: string | null }>; - /** Whether container logs may be read; null when the server could not say. */ - logs: boolean | null; - /** Writes the account holds there, which it should not. */ - mutating: string[]; -}; - -export interface OpsReader { - /** One look at a target. Throws when its pods cannot be listed: then there is nothing to look at. */ - look(target: OpsTarget, at: { now: number; since: number }): Promise; - access(target: OpsTarget): Promise; -} - -export class KubeError extends Error { - constructor( - readonly status: number, - message: string, - ) { - super(message); - this.name = "KubeError"; - } -} - -/** The pod's mounted ServiceAccount, read on every call: projected tokens rotate. */ -function credentials(dir: string): { token: string; ca: string } { - try { - return { token: readFileSync(join(dir, "token"), "utf8").trim(), ca: readFileSync(join(dir, "ca.crt"), "utf8") }; - } catch { - throw new KubeError(0, `this server has no cluster access: no ServiceAccount token at ${dir} (bb-gate mounts one only into the backend of the developer who runs the project's ops steward)`); - } -} - -export function createKubeReader(opts: { dir?: string; apiUrl?: string } = {}): OpsReader { - const dir = opts.dir ?? SERVICE_ACCOUNT_DIR; - const api = new URL(opts.apiUrl ?? IN_CLUSTER_API); - - function call(method: "GET" | "POST", path: string, body?: unknown): Promise { - const { token, ca } = credentials(dir); - return new Promise((resolve, reject) => { - const payload = body === undefined ? undefined : JSON.stringify(body); - const req = https.request( - { - protocol: api.protocol, - hostname: api.hostname, - port: api.port === "" ? 443 : Number(api.port), - path, - method, - ca, - timeout: TIMEOUT_MS, - headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(payload === undefined ? {} : { "content-type": "application/json" }) }, - }, - (res) => { - const chunks: Buffer[] = []; - res.on("data", (c: Buffer) => chunks.push(c)); - res.on("end", () => { - const text = Buffer.concat(chunks).toString("utf8"); - const status = res.statusCode ?? 0; - if (status >= 200 && status < 300) return resolve(text); - let message = text.slice(0, 300); - try { - message = String((JSON.parse(text) as { message?: unknown }).message ?? message); - } catch { - // not JSON: keep the text - } - reject(new KubeError(status, `${status}: ${message}`)); - }); - }, - ); - req.on("timeout", () => req.destroy(new KubeError(0, `the API server did not answer in ${TIMEOUT_MS / 1000}s`))); - req.on("error", (error) => reject(error instanceof KubeError ? error : new KubeError(0, error.message))); - if (payload !== undefined) req.write(payload); - req.end(); - }); - } - - const get = async (path: string): Promise => JSON.parse(await call("GET", path)) as unknown; - const ns = (t: OpsTarget) => encodeURIComponent(t.name); - const forbidden = (e: unknown) => e instanceof KubeError && (e.status === 401 || e.status === 403); - - async function can(namespace: string, verb: string, resource: string, extra: { group?: string; subresource?: string } = {}): Promise { - const out = JSON.parse( - await call("POST", "/apis/authorization.k8s.io/v1/selfsubjectaccessreviews", { - apiVersion: "authorization.k8s.io/v1", - kind: "SelfSubjectAccessReview", - spec: { resourceAttributes: { namespace, verb, resource, ...extra } }, - }), - ) as { status?: { allowed?: boolean } }; - return out.status?.allowed === true; - } - - return { - async look(target, at) { - const base = `/api/v1/namespaces/${ns(target)}`; - const pods = podsOf(await get(`${base}/pods`)); - const notes: string[] = []; - const optional = async (what: string, read: () => Promise, empty: T): Promise => { - try { - return await read(); - } catch (error) { - notes.push(`${what} could not be read (${error instanceof Error ? error.message : String(error)})`); - return empty; - } - }; - const events = await optional("Events", async () => eventsOf(await get(`${base}/events?limit=500`)), []); - const deployments = await optional("Deployments", async () => deploymentsOf(await get(`/apis/apps/v1/namespaces/${ns(target)}/deployments`)), []); - const sightings = findingsOf(target, pods, events, at); - let logs: RawLook["logs"] = "unneeded"; - for (const s of sightings.filter((x) => x.container !== null).slice(0, LOGS_PER_LOOK)) { - const container = s.container!.replace(/^init:/u, ""); - const path = (previous: boolean) => `${base}/pods/${encodeURIComponent(s.pods[0]!)}/log?container=${encodeURIComponent(container)}&tailLines=60${previous ? "&previous=true" : ""}`; - try { - let text: string; - try { - text = await call("GET", path(s.previous)); - } catch (error) { - // No previous run to read (it was never restarted, or was replaced): read the current one. - if (!s.previous || forbidden(error)) throw error; - s.previous = false; - text = await call("GET", path(false)); - } - s.logs = logTail(text); - logs = "read"; - } catch (error) { - if (forbidden(error)) { - logs = "not granted"; - break; - } - notes.push(`The logs of ${s.pods[0]}/${container} could not be read (${error instanceof Error ? error.message : String(error)})`); - } - } - const healthy = pods.filter((p) => p.phase === "Succeeded" || (p.phase === "Running" && p.ready)).length; - return { pods: pods.length, healthy, deployments, warnings: otherWarnings(events, sightings, at.since), logs, notes, sightings }; - }, - - async access(target) { - const reads: OpsAccess["reads"] = []; - const base = `/api/v1/namespaces/${ns(target)}`; - for (const [what, path] of [ - ["list pods", `${base}/pods?limit=1`], - ["list events", `${base}/events?limit=1`], - ["list deployments", `/apis/apps/v1/namespaces/${ns(target)}/deployments?limit=1`], - ] as const) { - try { - await call("GET", path); - reads.push({ what, ok: true, detail: null }); - } catch (error) { - if (error instanceof KubeError && error.status === 0) return { error: error.message, reads: [], logs: null, mutating: [] }; - reads.push({ what, ok: false, detail: error instanceof Error ? error.message : String(error) }); - } - } - let logs: boolean | null = null; - const mutating: string[] = []; - try { - logs = await can(target.name, "get", "pods", { subresource: "log" }); - const writes = [ - ["delete", "pods", ""], - ["create", "pods", ""], - ["patch", "deployments", "apps"], - ["update", "deployments", "apps"], - ["delete", "deployments", "apps"], - ] as const; - for (const [verb, resource, group] of writes) { - if (await can(target.name, verb, resource, group === "" ? {} : { group })) mutating.push(`${verb} ${resource}`); - } - } catch { - // The server would not answer access reviews; the reads above still say what works. - } - return { error: null, reads, logs, mutating }; - }, - }; -} diff --git a/plugins/stewards/kubectl.test.ts b/plugins/stewards/kubectl.test.ts new file mode 100644 index 00000000..e24c9ca5 --- /dev/null +++ b/plugins/stewards/kubectl.test.ts @@ -0,0 +1,80 @@ +import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { crashingPod } from "./fixtures.js"; +import { runKubectlHere } from "./host.js"; +import { createKubectlReader, kubectlError, kubectlRefusal, type KubectlResult } from "./kubectl.js"; + +const target = { kind: "k8s-namespace", name: "devbox-production" } as const; +const now = Date.parse("2026-10-14T15:00:00Z"); + +describe("the kubectl gate", () => { + it("lets through only get, describe, logs and auth can-i", () => { + for (const ok of [["get", "pods", "-n", "x", "-o", "json"], ["describe", "pod", "p"], ["logs", "p", "-c", "c", "--previous"], ["auth", "can-i", "get", "pods/log", "-n", "x"]]) expect(kubectlRefusal(ok), ok.join(" ")).toBeNull(); + for (const bad of [["delete", "pod", "p"], ["exec", "p", "--", "sh"], ["apply", "-f", "x.yaml"], ["rollout", "restart", "deploy/x"], ["scale", "deploy/x", "--replicas=0"], ["auth", "reconcile"], ["edit", "deploy/x"], [], ["patch", "deploy/x"]]) { + expect(kubectlRefusal(bad), bad.join(" ")).toMatch(/is not allowed: the ops kind runs only get, describe, logs, auth can-i/u); + } + }); + + it("refuses other credentials or another identity", () => { + for (const flag of ["--kubeconfig=/tmp/admin", "--token=abc", "--as=system:admin", "--server", "--as-group=system:masters"]) { + expect(kubectlRefusal(["get", "pods", flag]), flag).toMatch(/is not allowed: the ops kind uses the machine's own kubeconfig/u); + } + expect(kubectlRefusal(["get", "pods", "--context=bc-prod", "--request-timeout=20s"])).toBeNull(); + }); +}); + +describe("the kubectl reader", () => { + const fake = (answer: (args: string[]) => KubectlResult) => { + const calls: string[][] = []; + return { calls, run: async (args: string[]) => (calls.push(args), answer(args)) }; + }; + const ok = (stdout: string): KubectlResult => ({ exitCode: 0, stdout, stderr: "" }); + + it("reads a crashed run's logs, falling back to the current run when there is no previous one", async () => { + const k = fake((a) => (a[0] === "get" ? ok(JSON.stringify({ items: a[1] === "pods" ? [crashingPod()] : [] })) : a.includes("--previous") ? { exitCode: 1, stdout: "", stderr: 'previous terminated container "router" in pod "x" not found' } : ok("boom\n"))); + const look = await createKubectlReader(k.run, { context: "bc-prod" }).look(target, { now, since: now - 3_600_000 }); + expect(look).toMatchObject({ pods: 1, healthy: 0, logs: "read", sightings: [{ logs: ["boom"], previous: false }] }); + expect(k.calls[0]).toEqual(["get", "pods", "-n", "devbox-production", "-o", "json", "--request-timeout=20s", "--context=bc-prod"]); + expect(k.calls.every((a) => kubectlRefusal(a) === null)).toBe(true); + }); + + it("says logs are not granted when kubectl is forbidden them, and fails a look it cannot list pods for", async () => { + const k = fake((a) => (a[0] === "get" ? ok(JSON.stringify({ items: a[1] === "pods" ? [crashingPod()] : [] })) : { exitCode: 1, stdout: "", stderr: 'Error from server (Forbidden): pods "x" is forbidden' })); + expect(await createKubectlReader(k.run).look(target, { now, since: 0 })).toMatchObject({ logs: "not granted", sightings: [{ logs: null }] }); + const down = fake(() => ({ exitCode: 1, stdout: "", stderr: "error: Unable to connect to the server: dial tcp: i/o timeout\n" })); + await expect(createKubectlReader(down.run).look(target, { now, since: 0 })).rejects.toThrow(/^Unable to connect to the server/u); + }); + + it("reports an unreachable target, or one with no kubectl, as an error for check", async () => { + const missing = fake(() => ({ exitCode: 127, stdout: "", stderr: "kubectl: not found", missing: true })); + expect(await createKubectlReader(missing.run).access(target)).toMatchObject({ error: "kubectl is not installed on this machine, or not on its PATH" }); + const noContext = fake(() => ({ exitCode: 1, stdout: "", stderr: 'error: context "bc-prod" does not exist' })); + expect((await createKubectlReader(noContext.run).access(target)).error).toBe('context "bc-prod" does not exist'); + const fine = fake((a) => (a[0] === "auth" ? (a[3] === "pods/log" ? ok("yes\n") : { exitCode: 1, stdout: "no\n", stderr: "" }) : ok("pod/a\n"))); + expect(await createKubectlReader(fine.run).access(target)).toEqual({ error: null, reads: ["pods", "events", "deployments"].map((r) => ({ what: `get ${r}`, ok: true, detail: null })), logs: true, writes: [] }); + expect(kubectlError({ exitCode: 2, stdout: "", stderr: "" })).toBe("kubectl exited 2"); + }); +}); + +describe("the host's kubectl", () => { + const dir = mkdtempSync(join(tmpdir(), "stewards-kubectl-")); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + const marker = join(dir, "ran"); + const script = join(dir, "kubectl"); + writeFileSync(script, `#!/bin/sh\ntouch ${JSON.stringify(marker)}\nif [ "$1" = "auth" ]; then echo no; exit 1; fi\necho "args: $*"\necho "warn" >&2\n`); + chmodSync(script, 0o755); + + it("runs allowed arguments and reports the exit code and output", async () => { + expect(await runKubectlHere(["get", "pods", "-n", "x"], 5000, script)).toEqual({ exitCode: 0, stdout: "args: get pods -n x\n", stderr: "warn\n", missing: false }); + expect(await runKubectlHere(["auth", "can-i", "delete", "pods"], 5000, script)).toMatchObject({ exitCode: 1, stdout: "no\n" }); + }); + + it("never starts kubectl for refused arguments, and says when there is no kubectl", async () => { + rmSync(marker, { force: true }); + expect(await runKubectlHere(["delete", "pod", "p"], 5000, script)).toMatchObject({ exitCode: 126, stderr: expect.stringMatching(/kubectl delete is not allowed/u) }); + expect(existsSync(marker)).toBe(false); + expect(await runKubectlHere(["get", "pods"], 5000, join(dir, "nope"))).toMatchObject({ exitCode: 127, missing: true }); + }); +}); diff --git a/plugins/stewards/kubectl.ts b/plugins/stewards/kubectl.ts new file mode 100644 index 00000000..37b7da7e --- /dev/null +++ b/plugins/stewards/kubectl.ts @@ -0,0 +1,133 @@ +// The ops kind's eyes: kubectl, run on the developer's own machine, where it +// reaches the cluster through their kubeconfig (on bc-prod, the Tailscale API +// proxy) as them. Steward threads run there too; the plugin's server does +// not, so it asks the machine to run kubectl (host.ts) and the wake carries +// what came back. +// +// Every kubectl call, the plugin's and the host's, passes kubectlRefusal: +// only get, describe, logs and auth can-i. The developer's own rights are +// broad, so this and the playbook's `may` list are what keep the ops steward +// read-only (DESIGN.md §11, §18). A real wall, such as a read-only identity, +// would slot in behind the same function. +import { deploymentsOf, eventsOf, findingsOf, logTail, otherWarnings, podsOf, type OpsTarget, type RawLook } from "./ops.js"; + +/** What the ops kind may ask kubectl to do. Nothing else is run. */ +export const KUBECTL_VERBS = ["get", "describe", "logs", "auth can-i"] as const; + +/** Flags that would point kubectl at other credentials or another identity. */ +const REFUSED_FLAGS = /^--(?:kubeconfig|token|server|as|as-group|as-uid|username|password|client-certificate|client-key|insecure-skip-tls-verify)(?:=|$)/u; + +/** Why kubectl may not run these arguments, or null when it may. */ +export function kubectlRefusal(args: readonly string[]): string | null { + const verb = args[0] === "auth" ? `auth ${args[1] ?? ""}`.trim() : (args[0] ?? ""); + if (!(KUBECTL_VERBS as readonly string[]).includes(verb)) return `kubectl ${verb || "(nothing)"} is not allowed: the ops kind runs only ${KUBECTL_VERBS.join(", ")}`; + const flag = args.find((a) => REFUSED_FLAGS.test(a)); + if (flag !== undefined) return `kubectl ${flag.split("=")[0]} is not allowed: the ops kind uses the machine's own kubeconfig as it is`; + return null; +} + +/** One kubectl run. `missing` when there is no kubectl to run. */ +export type KubectlResult = { exitCode: number; stdout: string; stderr: string; missing?: boolean }; +export type Kubectl = (args: string[]) => Promise; + +/** What `bb stewards check` reports for one target. */ +export type OpsAccess = { + /** Set when nothing could be asked: no kubectl, no machine, or the cluster unreachable. */ + error: string | null; + /** Each read a look makes, and whether it works. */ + reads: Array<{ what: string; ok: boolean; detail: string | null }>; + /** Whether container logs may be read; null when kubectl could not say. */ + logs: boolean | null; + /** Writes the identity holds there. Expected of a developer: the gate and the playbook, not the cluster, keep the steward from them. */ + writes: string[]; +}; + +export interface OpsReader { + /** One look at a target. Throws when its pods cannot be listed: then there is nothing to look at. */ + look(target: OpsTarget, at: { now: number; since: number }): Promise; + access(target: OpsTarget): Promise; +} + +const REQUEST_TIMEOUT = "--request-timeout=20s"; +/** Logs are read for at most this many findings per look. */ +const LOGS_PER_LOOK = 5; + +/** The first useful line of kubectl's complaint. */ +export function kubectlError(r: KubectlResult): string { + if (r.missing === true) return "kubectl is not installed on this machine, or not on its PATH"; + const line = r.stderr.split(/\r?\n/u).map((l) => l.trim()).find((l) => l !== "") ?? `kubectl exited ${r.exitCode}`; + return line.replace(/^error:\s*/iu, "").slice(0, 300); +} + +const forbidden = (r: KubectlResult) => /\bforbidden\b/iu.test(r.stderr); +/** Nothing answered: kubectl is missing, or the cluster is unreachable from this machine. */ +const unreachable = (r: KubectlResult) => r.missing === true || /unable to connect|connection refused|no such host|i\/o timeout|deadline exceeded|context deadline|couldn't get current server|no configuration has been provided|current-context is not set|context .* does not exist|tls|x509|unauthorized/iu.test(r.stderr); + +/** A reader of one project's targets, through one kubectl that already passed the gate. `context` picks a kubeconfig context. */ +export function createKubectlReader(kubectl: Kubectl, opts: { context?: string } = {}): OpsReader { + const run = (args: string[]) => kubectl([...args, REQUEST_TIMEOUT, ...(opts.context === undefined ? [] : [`--context=${opts.context}`])]); + const getJson = async (resource: string, ns: string): Promise => { + const r = await run(["get", resource, "-n", ns, "-o", "json"]); + if (r.exitCode !== 0) throw new Error(kubectlError(r)); + return JSON.parse(r.stdout) as unknown; + }; + + return { + async look(target, at) { + const ns = target.name; + const pods = podsOf(await getJson("pods", ns)); + const notes: string[] = []; + const optional = async (what: string, read: () => Promise, empty: T): Promise => { + try { + return await read(); + } catch (error) { + notes.push(`${what} could not be read (${error instanceof Error ? error.message : String(error)})`); + return empty; + } + }; + const events = await optional("Events", async () => eventsOf(await getJson("events", ns)), []); + const deployments = await optional("Deployments", async () => deploymentsOf(await getJson("deployments", ns)), []); + const sightings = findingsOf(target, pods, events, at); + let logs: RawLook["logs"] = "unneeded"; + for (const s of sightings.filter((x) => x.container !== null).slice(0, LOGS_PER_LOOK)) { + const container = s.container!.replace(/^init:/u, ""); + const args = (previous: boolean) => ["logs", s.pods[0]!, "-n", ns, "-c", container, "--tail=60", ...(previous ? ["--previous"] : [])]; + let r = await run(args(s.previous)); + // No previous run to read (never restarted, or replaced): read the current one. + if (r.exitCode !== 0 && s.previous && !forbidden(r)) { + s.previous = false; + r = await run(args(false)); + } + if (r.exitCode === 0) { + s.logs = logTail(r.stdout); + logs = "read"; + } else if (forbidden(r)) { + logs = "not granted"; + break; + } else notes.push(`The logs of ${s.pods[0]}/${container} could not be read (${kubectlError(r)})`); + } + const healthy = pods.filter((p) => p.phase === "Succeeded" || (p.phase === "Running" && p.ready)).length; + return { pods: pods.length, healthy, deployments, warnings: otherWarnings(events, sightings, at.since), logs, notes, sightings }; + }, + + async access(target) { + const ns = target.name; + const reads: OpsAccess["reads"] = []; + for (const resource of ["pods", "events", "deployments"]) { + const r = await run(["get", resource, "-n", ns, "-o", "name"]); + if (r.exitCode !== 0 && unreachable(r)) return { error: kubectlError(r), reads: [], logs: null, writes: [] }; + reads.push({ what: `get ${resource}`, ok: r.exitCode === 0, detail: r.exitCode === 0 ? null : kubectlError(r) }); + } + // `auth can-i` answers yes (exit 0) or no (exit 1); anything else is kubectl failing to ask. + const can = async (what: string): Promise => { + const r = await run(["auth", "can-i", ...what.split(" "), "-n", ns]); + const answer = r.stdout.trim().toLowerCase(); + return answer.startsWith("yes") ? true : answer.startsWith("no") ? false : null; + }; + const logs = await can("get pods/log"); + const writes: string[] = []; + for (const what of ["delete pods", "create pods/exec", "patch deployments"]) if ((await can(what)) === true) writes.push(what); + return { error: null, reads, logs, writes }; + }, + }; +} diff --git a/plugins/stewards/ops.ts b/plugins/stewards/ops.ts index 8c3d42e1..2173bd8d 100644 --- a/plugins/stewards/ops.ts +++ b/plugins/stewards/ops.ts @@ -1,7 +1,7 @@ // The ops kind's mechanical tier, as pure functions: what a look at a watch // target found, each problem's fingerprint, and how each compares with the // fingerprint map (new, still failing under its ticket, or back after its -// ticket was resolved). kube.ts reads the cluster; server.ts stores and +// ticket was resolved). kubectl.ts reads the cluster; server.ts stores and // wakes; nothing here talks to anything. // // A fingerprint names one problem across looks and restarts: the target, the @@ -266,7 +266,7 @@ export const opsFindingSchema = z.object({ }); export type OpsFinding = z.infer; -/** Whether logs were read: some were, the server may not read them (no pods/log grant), or none were needed. */ +/** Whether logs were read: some were, kubectl may not read them (forbidden), or none were needed. */ export const LOG_ACCESS = ["read", "not granted", "unneeded"] as const; export const opsLookSchema = z.object({ diff --git a/plugins/stewards/package.json b/plugins/stewards/package.json index 52ac890e..1bd60dea 100644 --- a/plugins/stewards/package.json +++ b/plugins/stewards/package.json @@ -14,6 +14,7 @@ "icon": "ShieldCheck" }, "server": "./server.ts", + "host": "./host.ts", "app": "./app.tsx", "skills": [ "skills" diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 353c8fc1..48c8ce33 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -3,8 +3,7 @@ import { createFakePluginHost, makePluginAgentConfigurationContext, makeThreadRe import { describe, expect, it } from "vitest"; import { PROJECT_FILE, playbookPath } from "./config.js"; import { comment, crashingPod, issue, pull, warningEvent } from "./fixtures.js"; -import type { OpsAccess, OpsReader } from "./kube.js"; -import { eventsOf, findingsOf, podsOf } from "./ops.js"; +import { kubectlRefusal, type KubectlResult } from "./kubectl.js"; import { createStewardsPlugin, testHooks, type StewardsDeps } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; import { MIGRATIONS } from "./store.js"; @@ -1500,36 +1499,40 @@ describe("ops stewards", () => { const TARGET = "k8s-namespace/bb-gate-production"; const FP = `${TARGET}/bb-gate-router/router#CrashLoopBackOff:Error:1`; - /** A namespace the fake cluster serves, as kube.ts would read it, through the real parsing. */ + /** A fake kubectl on the project's machine, serving one namespace, recording every call. */ function cluster() { - const state = { pods: [] as unknown[], events: [] as unknown[], error: null as string | null, logs: false, access: null as OpsAccess | null }; - const reader: OpsReader = { - async look(target, at) { - if (state.error !== null) throw new Error(state.error); - const pods = podsOf({ items: state.pods }); - const sightings = findingsOf(target, pods, eventsOf({ items: state.events }), at); - const failing = sightings.filter((x) => x.container !== null); - if (state.logs) for (const x of failing) x.logs = ["panic: listen tcp :8080: address already in use"]; - return { pods: pods.length, healthy: pods.filter((p) => p.ready).length, deployments: [{ name: "bb-gate-router", ready: 0, desired: 1 }], warnings: [], logs: failing.length === 0 ? "unneeded" : state.logs ? "read" : "not granted", notes: [], sightings }; - }, - async access() { - return state.access ?? { error: "this server has no cluster access: no ServiceAccount token at /var/run/secrets/kubernetes.io/serviceaccount", reads: [], logs: null, mutating: [] }; - }, + const state = { pods: [] as unknown[], events: [] as unknown[], unreachable: false, logs: true, deployments: true, writes: false }; + const calls: Array<{ args: string[]; hostId: string | null }> = []; + const kubectl = async (args: string[], where: { hostId: string | null }): Promise => { + calls.push({ args, hostId: where.hostId }); + const ok = (stdout: string): KubectlResult => ({ exitCode: 0, stdout, stderr: "" }); + const fail = (stderr: string, exitCode = 1): KubectlResult => ({ exitCode, stdout: "", stderr }); + if (state.unreachable) return fail("Unable to connect to the server: dial tcp: lookup bc-prod.example.ts.net: no such host"); + const a = args.filter((x) => !x.startsWith("--request-timeout") && !x.startsWith("--context")); + const names = (items: unknown[]) => items.map((i, n) => `${a[1]}/${(i as { metadata?: { name: string } }).metadata?.name ?? n}`).join("\n"); + if (a[0] === "get") { + const items = a[1] === "pods" ? state.pods : a[1] === "events" ? state.events : [{ metadata: { name: "bb-gate-router" }, spec: { replicas: 1 }, status: { readyReplicas: 0 } }]; + if (a[1] === "deployments" && !state.deployments) return fail('Error from server (Forbidden): deployments.apps is forbidden: User "jane@acme.com" cannot list resource "deployments"'); + return ok(a.includes("json") ? JSON.stringify({ items }) : names(items)); + } + if (a[0] === "logs") return state.logs ? ok("starting router\npanic: listen tcp :8080: address already in use\n") : fail('Error from server (Forbidden): pods "x" is forbidden: User cannot get resource "pods/log"'); + if (a[0] === "auth") return a[3] === "pods/log" ? (state.logs ? ok("yes\n") : { exitCode: 1, stdout: "no\n", stderr: "" }) : state.writes ? ok("yes\n") : { exitCode: 1, stdout: "no\n", stderr: "" }; + return fail(`unexpected kubectl ${args.join(" ")}`); }; - return { state, reader }; + return { state, calls, kubectl }; } const opsProject = (targets: string[] = ["bb-gate-production"], extra: Record = {}) => JSON.stringify({ version: 1, linear: { teams: ["ENG"] }, ops: { targets: targets.map((name) => ({ kind: "k8s-namespace", name })), ...extra } }); - async function watched(over: { error?: string } = {}) { + async function watched(over: { unreachable?: boolean } = {}) { const c = cluster(); - const t = await setup({ ops: c.reader }); + const t = await setup({ kubectl: c.kubectl }); t.files[PROJECT_FILE] = opsProject(); t.files[playbookPath("ops-watch")] = OPS_WATCH; c.state.pods = [crashingPod()]; c.state.events = [warningEvent("bb-gate-router-6d4f9c7b8-x2k4q")]; - if (over.error !== undefined) c.state.error = over.error; + if (over.unreachable === true) c.state.unreachable = true; await t.hooks.sweep(); await t.flush(); const steward = () => t.spawns.find((x) => String(x.title).startsWith("Ops watch")); @@ -1541,7 +1544,7 @@ describe("ops stewards", () => { } it("watches a configured target, files one ticket for a crash loop, and comments on it while it keeps crashing", async () => { - const { t, steward, wakes } = await watched(); + const { t, c, steward, wakes } = await watched(); const [project] = t.spawns; const ops = steward()!; // A binding of its own, reporting to the project steward, in the list and on the page. @@ -1558,10 +1561,15 @@ describe("ops stewards", () => { expect(first).toMatch(/File one ticket per problem/u); expect(first).not.toMatch(/### Recurring/u); expect(first).toMatch(/BackOff ×12: Back-off restarting failed container router/u); - // bb-gate-production grants no logs: the wake says to diagnose from status and events. - expect(first).toMatch(/Logs: not readable from this server \(no pods\/log grant here\)/u); + // The crashed run's last log lines, read with kubectl as the developer. + expect(first).toMatch(/Last log lines of the run that ended:\n\n```\nstarting router\npanic: listen tcp :8080: address already in use\n```/u); + // Every kubectl call ran on the project's machine, and only get, logs and auth can-i. + expect(c.calls.length).toBeGreaterThan(0); + expect(c.calls.every((x) => x.hostId === "host_on" && kubectlRefusal(x.args) === null)).toBe(true); + expect(c.calls.map((x) => x.args.slice(0, 2).join(" "))).toEqual(expect.arrayContaining(["get pods", "get events", "get deployments", "logs bb-gate-router-6d4f9c7b8-x2k4q"])); + expect(c.calls.find((x) => x.args[0] === "logs")!.args).toEqual(["logs", "bb-gate-router-6d4f9c7b8-x2k4q", "-n", "bb-gate-production", "-c", "router", "--tail=60", "--previous", "--request-timeout=20s"]); expect(first).toMatch(/File tickets in the Linear team ENG/u); - expect(first).toMatch(/Allowed actions: read, file-ticket, comment, escalate\./u); + expect(first).toMatch(/Allowed actions: kubectl get, kubectl describe, kubectl logs, kubectl auth can-i, file-ticket, comment, escalate\./u); // A fingerprint it has not seen is refused, and nothing is recorded. const base = { phase: "watching", summary: "router crash-looping; filed ENG-50", nextAction: "Watch", actor: "steward" }; @@ -1648,14 +1656,14 @@ describe("ops stewards", () => { expect(report.text).toMatch(/Your thread is archived when the turn ends/u); }); - it("makes a binding that waits while the server cannot read its target, and wakes once it can", async () => { - const { t, c, steward } = await watched({ error: "403: pods is forbidden" }); + it("makes a binding that waits while kubectl cannot read its target, and wakes once it can", async () => { + const { t, c, steward } = await watched({ unreachable: true }); expect(await t.list()).toMatchObject([{ key: TARGET, kind: "ops", threadId: null }]); expect(steward()).toBeUndefined(); const listed = await t.harness.behavior.runCli(["list"], { projectId: "p1" }); - expect(listed.stdout).toMatch(/cannot read the target: 403: pods is forbidden/u); + expect(listed.stdout).toMatch(/cannot read the target: Unable to connect to the server: dial tcp: lookup bc-prod\.example\.ts\.net: no such host/u); - c.state.error = null; + c.state.unreachable = false; await t.hooks.sweep(); await t.flush(); expect(steward()).toBeDefined(); @@ -1680,30 +1688,52 @@ describe("ops stewards", () => { expect(t.spawns.filter((x) => String(x.title).startsWith("Ops watch"))).toHaveLength(1); }); - it("is checked: a target this server cannot read is a problem, as is any write it holds there", async () => { + it("is checked: a target kubectl cannot reach is a problem; writes the developer holds are only said", async () => { const { t, c } = await watched(); const check = () => t.harness.behavior.runCli(["check"], { projectId: "p1" }); + c.state.unreachable = true; const none = await check(); expect(none.exitCode).toBe(1); expect(none.stdout).toMatch(/ops: tickets filed in ENG/u); - expect(none.stdout).toMatch(/problem: ops: this server cannot read k8s-namespace\/bb-gate-production: this server has no cluster access/u); + expect(none.stdout).toMatch(/ops: kubectl runs on host_on, in its current context/u); + expect(none.stdout).toMatch(/problem: ops: cannot read the target k8s-namespace\/bb-gate-production: Unable to connect to the server/u); expect(none.stdout).toMatch(/^ops: ops-watch@/mu); - const reads = [{ what: "list pods", ok: true, detail: null }, { what: "list events", ok: true, detail: null }, { what: "list deployments", ok: false, detail: "403: forbidden" }]; - c.state.access = { error: null, reads, logs: false, mutating: [] }; + c.state.unreachable = false; + c.state.logs = false; + c.state.deployments = false; const readable = await check(); + expect(readable.stdout).not.toMatch(/problem:/u); expect(readable.exitCode).toBe(0); - expect(readable.stdout).toMatch(/ops: k8s-namespace\/bb-gate-production is readable \(list pods, list events\); logs not granted, so diagnosis is from status and events/u); - expect(readable.stdout).toMatch(/cannot list deployments \(403: forbidden\); looks go without it/u); + expect(readable.stdout).toMatch(/ops: k8s-namespace\/bb-gate-production is readable \(get pods, get events\); logs not readable, so diagnosis is from status and events/u); + expect(readable.stdout).toMatch(/cannot get deployments \(Error from server \(Forbidden\): deployments\.apps is forbidden.*\); looks go without it/u); - c.state.access = { error: null, reads, logs: true, mutating: ["delete pods"] }; + // kubectl acts as the developer, whose rights are broad: said, not a problem. + c.state.writes = true; const writable = await check(); - expect(writable.exitCode).toBe(1); - expect(writable.stdout).toMatch(/problem: ops: this server may delete pods in k8s-namespace\/bb-gate-production; an ops steward's access should be read-only/u); + expect(writable.exitCode).toBe(0); + expect(writable.stdout).toMatch(/this identity may also delete pods, create pods\/exec, patch deployments; the plugin and the playbook keep to get, describe, logs, auth can-i/u); + expect(c.calls.every((x) => kubectlRefusal(x.args) === null)).toBe(true); // A project file whose ops section is wrong is a problem too. t.files[PROJECT_FILE] = opsProject(["bb-gate-production"], { team: "SALES" }); expect((await check()).stdout).toMatch(/problem: stewards\/project\.json: ops\.team: SALES is not one of linear\.teams/u); + // A context, when named, is passed on every call. + t.files[PROJECT_FILE] = opsProject(["bb-gate-production"], { context: "bc-prod" }); + expect((await check()).stdout).toMatch(/kubectl runs on host_on, in context bc-prod/u); + expect(c.calls.at(-1)!.args.at(-1)).toBe("--context=bc-prod"); + }); + + it("runs kubectl through its host entry on the project's machine by default", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = opsProject(); + t.files[playbookPath("ops-watch")] = OPS_WATCH; + await t.hooks.sweep(); + await t.flush(); + const calls = t.harness.experimental_hostRpcCalls; + expect(calls.length).toBeGreaterThan(0); + expect(calls[0]).toMatchObject({ method: "opsKubectl", hostId: "host_on", input: { args: ["get", "pods", "-n", "bb-gate-production", "-o", "json", "--request-timeout=20s"] } }); + expect(calls.every((x) => kubectlRefusal((x.input as { args: string[] }).args) === null)).toBe(true); }); it("gives an ops steward its own instructions, and refuses opsTickets from any other steward", async () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 8189abe8..cf751dcc 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -39,7 +39,8 @@ import { type Playbook, type ProjectFile, } from "./config.js"; -import { createKubeReader, type OpsAccess, type OpsReader } from "./kube.js"; +import { hostContract } from "./host-contract.js"; +import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, type OpsAccess, type OpsReader } from "./kubectl.js"; import { nightlyDue, stillNight } from "./nightly.js"; import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type OpsLook, type OpsTarget, type TicketState } from "./ops.js"; import { advanced, approvalWanted, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, lifecycle, newestCommentAt, phaseAndStage, resolveChecklistItem, specHash, stuckDue, unheardWait, type Change } from "./reconcile.js"; @@ -111,8 +112,8 @@ export const DEFAULT_TIMING: Timing = { export interface StewardsDeps { now: () => number; timing?: Partial; - /** How ops bindings read their targets: the pod's ServiceAccount by default. */ - ops?: OpsReader; + /** Runs kubectl for ops bindings: on the project's machine, through the host entry, by default. */ + kubectl?: (args: string[], where: { projectId: string; hostId: string | null }) => Promise; } const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); @@ -1049,8 +1050,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // ---- ops bindings ---------------------------------------------------------------------------- // // An ops binding watches a target the project file lists rather than an - // entity in a source plugin. Its steward's thread has no cluster access, - // so the plugin looks (kube.ts), compares what it saw with the + // entity in a source plugin. The plugin looks with kubectl on the + // project's machine (kubectl.ts, host.ts), compares what it saw with the // fingerprint map, and wakes the steward with the look: at once for a // problem that is new or back after its ticket was resolved, and at every // requeue whatever it finds, so a problem still failing under its open @@ -1058,7 +1059,28 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // "all healthy" report. A sweep's look between requeues that finds // nothing new is recorded and wakes nobody. - const opsReader = deps.ops ?? createKubeReader(); + // Made on first use: only a project with ops targets needs its host entry. + let hostClient: ReturnType> | null = null; + const KUBECTL_TIMEOUT_MS = 30_000; + + /** + * Every kubectl call goes through here, and only get, describe, logs and + * auth can-i pass (kubectlRefusal; host.ts checks again). It runs on the + * project's machine, the developer's own, where kubectl reaches the + * cluster as them. Where a stricter wall comes later, it goes here. + */ + async function runKubectl(projectId: string, args: string[]): Promise { + const refused = kubectlRefusal(args); + if (refused !== null) throw new Error(refused); + const hostId = await projectHost(projectId); + if (deps.kubectl !== undefined) return deps.kubectl(args, { projectId, hostId }); + if (hostId === null) throw new Error("the project has no machine bb can reach to run kubectl on"); + hostClient ??= bb.hosts.experimental_client({ contract: hostContract }); + return hostClient.call("opsKubectl", { args, timeoutMs: KUBECTL_TIMEOUT_MS }, { hostId, timeoutMs: KUBECTL_TIMEOUT_MS + 10_000 }); + } + + const opsReaderFor = (config: ProjectConfig): OpsReader => + createKubectlReader((args) => runKubectl(config.projectId, args), config.file.ops.context === undefined ? {} : { context: config.file.ops.context }); /** The states of the tickets a look's problems are filed under, read through linear; null for one that cannot be read. */ async function ticketStates(keys: string[]): Promise> { @@ -1071,11 +1093,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** One look at an ops binding's target, its problems entered in the fingerprint map and classified against it. */ - async function lookAt(b: Binding, target: OpsTarget, playbook: Playbook): Promise { + async function lookAt(b: Binding, config: ProjectConfig, target: OpsTarget, playbook: Playbook): Promise { const at = now(); const since = b.opsLook !== null && b.opsLook.error === null ? b.opsLook.at : at - playbook.requeueDefaultMs; try { - const { sightings, ...rest } = await opsReader.look(target, { now: at, since }); + const { sightings, ...rest } = await opsReaderFor(config).look(target, { now: at, since }); const rows = store.sight(b.projectId, b.id, sightings.map((s) => ({ fingerprint: s.fingerprint, summary: s.summary }))); const tickets = await ticketStates([...rows.values()].map((r) => r.ticketKey).filter((k): k is string => k !== null)); return { ...rest, at, target: opsTargetKey(target), error: null, findings: classify(sightings, rows, tickets, at) }; @@ -1090,13 +1112,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // A target no longer listed is ended by the sweep. if (target === null || !opsTargets(config.file).some((t) => opsTargetKey(t) === b.entityId)) return; const before = b.opsLook; - const look = await lookAt(b, target, playbook); + const look = await lookAt(b, config, target, playbook); const requeueCame = b.requeueAt !== null && b.requeueAt <= now(); // The next look is due a requeue from now, whether or not this one wakes anyone. const requeueAt = requeueCame || b.requeueAt === null ? now() + playbook.requeueDefaultMs : b.requeueAt; b = store.patch(b.id, { opsLook: look, requeueAt }); if (look.error !== null) { - // Nothing to wake the steward with until the server can read the target; `bb stewards check` says why. + // Nothing to wake the steward with until kubectl can read the target; `bb stewards check` says why. if (before?.error !== look.error) bb.log.warn(`stewards: cannot read ${b.entityKey}: ${look.error}`); return; } @@ -1883,7 +1905,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P skills: ["stewards"], instructions: `You are the ops steward watching ${JSON.stringify(b.entityKey)} (binding ${b.id}, playbook ${JSON.stringify(b.playbook)}), and your thread id is ${context.thread.id}. ` + - "The plugin looks at the target for you and every wake carries what it found; you never change production and start no workers. " + + "The plugin looks at the target for you and every wake carries what it found; you never change production and start no workers. To dig further, run kubectl on the target yourself, but only get, describe, logs and auth can-i: it acts as the user, whose rights are broad. " + "File and comment on Linear tickets with the linear_ tools, which sign for you; escalate each ticket you file to the project steward with steward_report, as the playbook says. " + "End every turn you were woken for with steward_report, listing in opsTickets every ticket you filed, commented on or reopened. Read the stewards skill for the protocol.", }; @@ -2500,19 +2522,23 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (usesKind(config.file, "ops")) { const auto = config.file.ops.autoAdopt; lines.push(`ops: tickets filed in ${opsTeam(config.file) ?? "(no team)"}${auto.length > 0 ? `, adopted when filed at ${auto.join(", ")}` : ""}`); - for (const target of opsTargets(config.file)) lines.push(...opsAccessLines(opsTargetKey(target), await opsReader.access(target).catch((error: unknown): OpsAccess => ({ error: errorMessage(error), reads: [], logs: null, mutating: [] })))); + const host = await projectHost(projectId); + lines.push(`ops: kubectl runs on ${host ?? "no machine"}${config.file.ops.context === undefined ? ", in its current context" : `, in context ${config.file.ops.context}`}`); + const reader = opsReaderFor(config); + for (const target of opsTargets(config.file)) lines.push(...opsAccessLines(opsTargetKey(target), await reader.access(target).catch((error: unknown): OpsAccess => ({ error: errorMessage(error), reads: [], logs: null, writes: [] })))); } return { ok: !lines.some((l) => l.startsWith("problem:")), lines }; } - /** What `bb stewards check` says about one ops target: readable or not, logs or not, and any write it should not hold. */ + /** What `bb stewards check` says about one ops target: readable or not, and whether its logs are. */ function opsAccessLines(key: string, a: OpsAccess): string[] { - if (a.error !== null) return [`problem: ops: this server cannot read ${key}: ${a.error}`]; - const pods = a.reads.find((r) => r.what === "list pods"); - if (pods !== undefined && !pods.ok) return [`problem: ops: this server cannot read ${key}: list pods: ${pods.detail ?? "refused"}`]; - const lines = [`ops: ${key} is readable (${a.reads.filter((r) => r.ok).map((r) => r.what).join(", ")}); logs ${a.logs === true ? "readable" : a.logs === false ? "not granted, so diagnosis is from status and events" : "unknown"}`]; + if (a.error !== null) return [`problem: ops: cannot read the target ${key}: ${a.error}`]; + const pods = a.reads.find((r) => r.what === "get pods"); + if (pods !== undefined && !pods.ok) return [`problem: ops: cannot read the target ${key}: get pods: ${pods.detail ?? "refused"}`]; + const lines = [`ops: ${key} is readable (${a.reads.filter((r) => r.ok).map((r) => r.what).join(", ")}); logs ${a.logs === true ? "readable" : a.logs === false ? "not readable, so diagnosis is from status and events" : "unknown"}`]; for (const r of a.reads.filter((x) => !x.ok)) lines.push(`ops: ${key}: cannot ${r.what} (${r.detail ?? "refused"}); looks go without it`); - if (a.mutating.length > 0) lines.push(`problem: ops: this server may ${a.mutating.join(", ")} in ${key}; an ops steward's access should be read-only`); + // Expected: kubectl acts as the developer. Said so nobody mistakes the playbook for a wall. + if (a.writes.length > 0) lines.push(`ops: ${key}: this identity may also ${a.writes.join(", ")}; the plugin and the playbook keep to ${KUBECTL_VERBS.join(", ")}`); return lines; } @@ -2563,7 +2589,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }), check: cliCommand({ - summary: "Validate the project file and every playbook against Linear and GitHub, and that this server can read every ops target", + summary: "Validate the project file and every playbook against Linear and GitHub, and that kubectl can read every ops target", options: { project: PROJECT_OPTION }, async run(input, ctx) { const result = await check(projectOf(input.options.project, ctx)); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index c47156a9..7aa58ce5 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -88,7 +88,9 @@ Two tools are yours; everything else you do with the tools every thread has. You watch one production target; the wake is the plugin's look at it (pods, Warning events, and log lines where the server may read them), with each problem's fingerprint marked new, recurring or returned. You never change -production and start no workers. +production and start no workers. To dig further you may run kubectl on the +target yourself, but only `get`, `describe`, `logs` and `auth can-i`: it +acts as the user, whose rights are broad, and nothing else stops a write. - **New:** search the team for an open ticket about it, then file one ticket per problem with `linear_create_issue`: pod and container, since when, the @@ -106,8 +108,8 @@ production and start no workers. duplicate. - **All healthy:** the wake says so every requeue; report it with `actor: other` and end the turn. -- **No logs** (the wake says so on `bb-gate-production`): diagnose from status - and events, and say in the ticket that logs were not available. +- **No logs** (the wake says so): diagnose from status and events, and say + in the ticket that logs were not available. ## If you are the project steward @@ -184,9 +186,10 @@ above which a steward is compacted after its turn. need bb-gate-hooks (`BB_HOOKS_URL`); without it, adoption waits for the half-hourly sweep. - **An ops steward never wakes.** `bb stewards list` shows `cannot read the - target` and `bb stewards check` says why: this server has no - ServiceAccount (bb-gate mounts one only into the backend of the developer - who runs the project's ops steward), or it may not list pods there. + target` and `bb stewards check` says why: kubectl on the project's + machine cannot reach the cluster (not installed, the machine not on the + tailnet as the developer or a tagged node, no kubeconfig or context for + it; `ops.context` picks one), or it may not list pods there. Otherwise it takes a turn every `requeue-default`, healthy or not. - **A repo should not be stewarded.** Every GitHub repo in `repos.json` is, unless `project.json` lists it in `github.exclude` (`owner/repo`). Bindings diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 64c02993..aba2faab 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -179,7 +179,7 @@ export const OPS_WATCH = `--- name: ops-watch kind: ops source: k8s -may: [read, file-ticket, comment, escalate] +may: [kubectl get, kubectl describe, kubectl logs, kubectl auth can-i, file-ticket, comment, escalate] models: steward: claude/claude-sonnet-5-5/medium requeue-default: 1h @@ -190,10 +190,13 @@ tickets. You never change production: no restarts, no scaling, no edits, no workers. You read what each wake shows, file tickets, comment on them, and escalate to the project steward, which decides whether a ticket is worked. -The plugin looks at the target for you: pod health, Warning events, and the -last log lines of a failing container where the server may read logs. Where -it may not (bb-gate-production grants no logs), diagnose from status and -events, and say in the ticket that logs were not available. +The plugin looks at the target for you, with kubectl on this machine as the +user: pod health, Warning events, and the last log lines of a failing +container. To dig further you may run kubectl yourself, but only get, +describe, logs and auth can-i, against the target. The user's own rights +are broad; nothing but this list stops a delete, an exec, a restart or an +edit, so never run one. Where logs could not be read, diagnose from status +and events, and say so in the ticket. Each problem has a fingerprint: the workload, the container and an error signature. Put it in the ticket description on a line of its own, diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 32bf64de..9842e506 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -268,7 +268,7 @@ function findingLines(f: OpsFinding, look: OpsLook): string[] { lines.push(`- Workload ${f.workload}; pod${f.pods.length === 1 ? "" : "s"} ${f.pods.join(", ")}${f.container === null ? "" : `; container ${f.container}`}; first seen ${iso(f.firstSeenAt)}${ticket}`); if (f.events.length > 0) lines.push("- Warning events, newest first:", ...f.events.map((e) => ` - ${e}`)); if (f.logs !== null) lines.push(`- Last log lines${f.previous ? " of the run that ended" : ""}:`, "", "```", ...(f.logs.length === 0 ? ["(empty)"] : f.logs), "```"); - else if (f.container !== null) lines.push(look.logs === "not granted" ? "- Logs: not readable from this server (no pods/log grant here). Diagnose from status and events, and say so in the ticket." : "- Logs: not read."); + else if (f.container !== null) lines.push(look.logs === "not granted" ? "- Logs: kubectl may not read them here. Diagnose from status and events, and say so in the ticket." : "- Logs: not read."); return [...lines, ""]; } From 170fd18df5c15e7c2eac80f8208d3b4092bfcb40 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 18:44:04 +0000 Subject: [PATCH 4/5] stewards: say plainly that the verb allowlist is the ops kind's only guard (BB-9) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DESIGN.md §18 now says the ambient kubectl credential may be broader than read and that kubectlRefusal is the plugin's only guard; the gate test covers every other mutating or interactive kubectl verb. Co-Authored-By: Claude Opus 5.5 --- plugins/stewards/DESIGN.md | 15 +++++++++------ plugins/stewards/kubectl.test.ts | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index ee6e91ec..9edd69b6 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -773,12 +773,15 @@ goes wrong there into Linear tickets for the project steward to adopt. Todo, the ordinary path, and the team lease brings a ticket steward; or declines with a reason. `ops.autoAdopt` names priorities the ops steward labels itself when filing, without escalating. -- **Read-only is a convention, not a wall.** kubectl acts as the - developer, whose rights are broad. Every kubectl call the plugin makes - passes one function, `kubectlRefusal`, checked by the server before it - asks and by the host entry before it runs: only `get`, `describe`, - `logs` and `auth can-i`, and no flag that swaps the kubeconfig, - credentials or identity. The playbook's `may` list says the same for the +- **Read-only is a convention, not a wall.** There is no separate + identity: the plugin assumes kubectl read access is available on the + machine, and uses whatever credential is there. **That ambient + credential may be broader than read** — a developer's usually can + delete, exec and patch — **and the verb allowlist is the plugin's only + guard.** Every kubectl call the plugin makes passes one function, + `kubectlRefusal`, checked by the server before it asks and by the host + entry before it runs: only `get`, `describe`, `logs` and `auth can-i`, + and no flag that swaps the kubeconfig, credentials or identity. The playbook's `may` list says the same for the steward's own kubectl (`kubectl get`, `describe`, `logs`, `auth can-i`, then filing, commenting and escalating), and like every `may` list it is advisory (§11): nothing stops the steward's shell. A real wall, such as a diff --git a/plugins/stewards/kubectl.test.ts b/plugins/stewards/kubectl.test.ts index e24c9ca5..12685030 100644 --- a/plugins/stewards/kubectl.test.ts +++ b/plugins/stewards/kubectl.test.ts @@ -12,7 +12,7 @@ const now = Date.parse("2026-10-14T15:00:00Z"); describe("the kubectl gate", () => { it("lets through only get, describe, logs and auth can-i", () => { for (const ok of [["get", "pods", "-n", "x", "-o", "json"], ["describe", "pod", "p"], ["logs", "p", "-c", "c", "--previous"], ["auth", "can-i", "get", "pods/log", "-n", "x"]]) expect(kubectlRefusal(ok), ok.join(" ")).toBeNull(); - for (const bad of [["delete", "pod", "p"], ["exec", "p", "--", "sh"], ["apply", "-f", "x.yaml"], ["rollout", "restart", "deploy/x"], ["scale", "deploy/x", "--replicas=0"], ["auth", "reconcile"], ["edit", "deploy/x"], [], ["patch", "deploy/x"]]) { + for (const bad of [["delete", "pod", "p"], ["exec", "p", "--", "sh"], ["apply", "-f", "x.yaml"], ["rollout", "restart", "deploy/x"], ["scale", "deploy/x", "--replicas=0"], ["auth", "reconcile"], ["edit", "deploy/x"], [], ["patch", "deploy/x"], ["create", "job", "x"], ["replace", "-f", "x"], ["label", "pod/p", "a=b"], ["annotate", "pod/p", "a=b"], ["cordon", "node"], ["drain", "node"], ["cp", "p:/etc/x", "x"], ["port-forward", "p", "8080"], ["attach", "p"], ["debug", "p"], ["proxy"], ["set", "image", "deploy/x", "a=b"], ["GET", "pods"], ["--namespace=x", "get", "pods"]]) { expect(kubectlRefusal(bad), bad.join(" ")).toMatch(/is not allowed: the ops kind runs only get, describe, logs, auth can-i/u); } }); From 901aac433a45647cc195e260236eb51e48b069bd Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Mon, 19 Oct 2026 18:51:56 +0000 Subject: [PATCH 5/5] stewards: refuse kubectl --raw and require phases again (BB-9) Review round 1 on #26: - kubectlRefusal now refuses --raw, which turned an allowed get into any API path (a secrets dump); a test covers it. - A ticket, pr or review playbook needs its phases again at parse time, as before the ops kind made them optional. Co-Authored-By: Claude Opus 5.5 --- plugins/stewards/config.test.ts | 4 ++++ plugins/stewards/config.ts | 17 +++++++++++------ plugins/stewards/kubectl.test.ts | 6 ++++++ plugins/stewards/kubectl.ts | 12 +++++++++--- 4 files changed, 30 insertions(+), 9 deletions(-) diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index e26c009c..6c70b0ea 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -122,6 +122,10 @@ describe("the ops playbook", () => { expect(parsePlaybook(OPS_WATCH.replace("may:", "terminal: [Done]\nmay:"), "ops-watch")).toMatchObject({ ok: false }); expect(parsePlaybook(OPS_WATCH.replace("source: k8s", "source: linear"), "ops-watch")).toMatchObject({ ok: false, error: expect.stringMatching(/an ops playbook reads k8s/u) }); expect(parsePlaybook(GITHUB_PRS.replace("terminal: [merged, closed]\n", ""), "github-prs")).toMatchObject({ ok: false, error: expect.stringMatching(/terminal: name at least one state/u) }); + // A ticket, pr or review playbook still needs its phases, as before ops. + const noPhases = GITHUB_PRS.replace(/phases:\n(?: {2}.*\n)+/u, ""); + expect(noPhases).not.toMatch(/phases:/u); + expect(parsePlaybook(noPhases, "github-prs")).toMatchObject({ ok: false, error: expect.stringMatching(/phases: map the entity's states to stages/u) }); }); }); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 5e7ad111..9a307048 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -245,7 +245,8 @@ export const frontMatterSchema = z kind: z.enum(KINDS), /** Where the entity lives; an ops playbook watches k8s, and has no entity state. */ source: z.enum(PLAYBOOK_SOURCES), - phases: z.record(z.string().trim().min(1).max(100), phaseSchema.nullable().transform((p) => p ?? {})).default({}), + /** Required for every kind but ops, which has none. */ + phases: z.record(z.string().trim().min(1).max(100), phaseSchema.nullable().transform((p) => p ?? {})).optional(), terminal: z.array(z.string().trim().min(1).max(100)).default([]), ready: readySchema.optional(), promote: z.string().trim().max(1000).optional(), @@ -301,14 +302,18 @@ export function parsePlaybook(text: string, expectedName: string): Parsed 0 || fm.terminal.length > 0 || fm.ready !== undefined || fm.promote !== undefined) { + if (Object.keys(fm.phases ?? {}).length > 0 || fm.terminal.length > 0 || fm.ready !== undefined || fm.promote !== undefined) { return { ok: false, error: `${file}: an ops playbook has no phases, terminal states, ready gate or promote rule: it watches a target, not an entity` }; } - } else if (fm.terminal.length === 0) return { ok: false, error: `${file}: terminal: name at least one state that ends the binding` }; - const lowerPhases = new Set(Object.keys(fm.phases).map((p) => p.toLowerCase())); + } else { + if (fm.phases === undefined) return { ok: false, error: `${file}: phases: map the entity's states to stages` }; + if (fm.terminal.length === 0) return { ok: false, error: `${file}: terminal: name at least one state that ends the binding` }; + } + const phases = fm.phases ?? {}; + const lowerPhases = new Set(Object.keys(phases).map((p) => p.toLowerCase())); const overlap = fm.terminal.filter((t) => lowerPhases.has(t.toLowerCase())); if (overlap.length > 0) return { ok: false, error: `${file}: ${overlap.join(", ")} cannot be both a phase and terminal` }; - if (fm.ready === undefined && fm.kind === "ticket" && Object.values(fm.phases).some((p) => p.stage === "build")) { + if (fm.ready === undefined && fm.kind === "ticket" && Object.values(phases).some((p) => p.stage === "build")) { return { ok: false, error: `${file}: a ticket playbook with a build stage needs a ready gate` }; } @@ -319,7 +324,7 @@ export function parsePlaybook(text: string, expectedName: string): Parsed { } expect(kubectlRefusal(["get", "pods", "--context=bc-prod", "--request-timeout=20s"])).toBeNull(); }); + + it("refuses --raw, which would make a get read any API path", () => { + for (const raw of [["get", "--raw", "/api/v1/namespaces/x/secrets"], ["get", "--raw=/api/v1/namespaces/x/secrets"], ["get", "pods", "--raw", "/healthz"]]) { + expect(kubectlRefusal(raw), raw.join(" ")).toMatch(/kubectl --raw is not allowed/u); + } + }); }); describe("the kubectl reader", () => { diff --git a/plugins/stewards/kubectl.ts b/plugins/stewards/kubectl.ts index 37b7da7e..07715a44 100644 --- a/plugins/stewards/kubectl.ts +++ b/plugins/stewards/kubectl.ts @@ -14,15 +14,21 @@ import { deploymentsOf, eventsOf, findingsOf, logTail, otherWarnings, podsOf, ty /** What the ops kind may ask kubectl to do. Nothing else is run. */ export const KUBECTL_VERBS = ["get", "describe", "logs", "auth can-i"] as const; -/** Flags that would point kubectl at other credentials or another identity. */ -const REFUSED_FLAGS = /^--(?:kubeconfig|token|server|as|as-group|as-uid|username|password|client-certificate|client-key|insecure-skip-tls-verify)(?:=|$)/u; +/** + * Flags that would point kubectl at other credentials or another identity, + * or (`--raw`) turn a get into an arbitrary API path, such as a secrets dump. + */ +const REFUSED_FLAGS = /^--(?:kubeconfig|token|server|as|as-group|as-uid|username|password|client-certificate|client-key|insecure-skip-tls-verify|raw)(?:=|$)/u; /** Why kubectl may not run these arguments, or null when it may. */ export function kubectlRefusal(args: readonly string[]): string | null { const verb = args[0] === "auth" ? `auth ${args[1] ?? ""}`.trim() : (args[0] ?? ""); if (!(KUBECTL_VERBS as readonly string[]).includes(verb)) return `kubectl ${verb || "(nothing)"} is not allowed: the ops kind runs only ${KUBECTL_VERBS.join(", ")}`; const flag = args.find((a) => REFUSED_FLAGS.test(a)); - if (flag !== undefined) return `kubectl ${flag.split("=")[0]} is not allowed: the ops kind uses the machine's own kubeconfig as it is`; + if (flag !== undefined) { + const name = flag.split("=")[0]!; + return name === "--raw" ? "kubectl --raw is not allowed: the ops kind reads resources by name, not arbitrary API paths" : `kubectl ${name} is not allowed: the ops kind uses the machine's own kubeconfig as it is`; + } return null; }