diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c218d67..2c4e667f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.19.0] - 2026-06-23 + +### Added +- **Sentinel layer 2 — the agent-agnostic responder (`kit sentinel run`).** kit **proposes**, any agent **disposes**, any scheduler **triggers**. `kit sentinel run --json` turns red layer-1 findings into a stable, typed remediation-proposal document — kit never calls an LLM and never opens a PR/issue; whichever agent (Claude Code, Codex, Cursor, …) reads the JSON and performs the writes with its own model + creds (the JSON contract is the agnostic seam). Triage→artifact: **code**→draft-PR, **human/infra**→issue, **noise**→suppression-PR (never a silent mute). Each artifact carries a `` marker; kit dedups read-only against open issues/PRs via `gh` (agent stays write-only), and `.kit/sentinel-suppress.toml` (`suppress = [...]`) filters findings. Pure proposal engine fixture-tested; the `buildHealthCtx` sensor-selection builder is now shared by `kit health` + sentinel. Design: `docs/specs/2026-06-23-sentinel-layer2-responder.md`. (#52) + ## [1.18.0] - 2026-06-23 ### Added diff --git a/docs/specs/2026-06-23-sentinel-layer2-responder.md b/docs/specs/2026-06-23-sentinel-layer2-responder.md new file mode 100644 index 00000000..08424b6b --- /dev/null +++ b/docs/specs/2026-06-23-sentinel-layer2-responder.md @@ -0,0 +1,96 @@ +# Sentinel Layer 2 — the responder (agent-agnostic) — design + +**Issue:** #52. **Builds on:** `docs/specs/2026-06-21-kit-sentinel-design.md` (layer 1 = `kit health`/`kit check` → PAL red findings, shipped). + +## The hard constraint (CEO, 2026-06-23) + +The responder must be **agent-agnostic**: it works with **any** coding agent — Claude +Code, Codex, Cursor, Gemini, … — and must not bind to one runtime. kit also stays +**zero-LLM** (its invariant). Those two together force the architecture below. + +## The contract: kit proposes, any agent disposes, any scheduler triggers + +kit does NOT call an LLM, does NOT open PRs/issues, and does NOT embed an agent. +Layer 2 is a **pure, deterministic translation**: red findings → a stable, typed +**remediation-proposal** document. Three independent roles, decoupled by that contract: + +``` + [scheduler] [kit — zero-LLM] [any agent] + cron / GH Action ──► kit sentinel run --json ──► reads proposals, + launchd / CI (PAL red findings → opens the artifacts + (BYO, agnostic) typed proposals + dedup) with ITS creds (BYO, agnostic) +``` + +- **kit** is the deterministic engine: classify each red finding, emit the exact + artifact it should become (title, body, branch, labels, suggested commands). +- **the agent** (whichever) consumes `--json` and executes — makes the code change, + opens the draft PR / issue / suppression PR — using its own model + the user's creds. +- **the scheduler** (whichever) invokes `kit sentinel run` on a cadence. kit is + stateless + idempotent, so the scheduler is interchangeable. + +This is the same propose-pattern kit already uses (`kit memory suggest`, `kit heal +--agent`): kit emits structured work; the agent acts. Layer 2 generalizes it to the +finding→artifact arc and makes the JSON the **agnostic seam**. + +## The proposal contract (the agnostic seam) + +`kit sentinel run --json` → + +```jsonc +{ + "generatedAtMarker": "", + "proposals": [ + { + "findingId": "health:vercel:prod-deploy-failed", // stable; the dedup key + "class": "code" | "human" | "noise", + "artifact": "draft-pr" | "issue" | "suppression-pr", + "title": "…", + "body": "… includes the marker …", + "branch": "kit/sentinel/", // draft-pr / suppression-pr only + "labels": ["kit-sentinel", "…"], + "suggestedCommands": ["…"], // deterministic hints, optional + "alreadyOpen": false // set by dedup (below) + } + ] +} +``` + +`kit sentinel run --agent ` emits the same proposals +formatted as that agent's idiom (a prompt block), mirroring `kit agent-config`'s +multi-target table — but the JSON is canonical; the `--agent` views are sugar. + +## Triage → artifact (from the layer-1 design, unchanged) + +| finding class | artifact | who acts | +|---|---|---| +| **code** (a fix in this repo) | **draft PR** — kit proposes branch + change description + commands; the agent makes the change & opens the draft | agent | +| **human / customer / infra** (DNS, billing, a vendor dashboard) | **issue + checklist** — kit proposes the body; the agent opens it | agent | +| **noise** (benign, to be filtered) | **suppression PR** — kit proposes the edit to `.kit/sentinel-suppress.toml`; agent opens a draft PR. **Never a silent mute.** | agent | + +## Dedup / idempotency (kept in kit, deterministic) + +Re-runs must not pile up duplicates. kit embeds a `` +marker in every artifact body, and before emitting a proposal it **reads open +issues/PRs read-only** (via `gh`/`glab`/`bitbucket` — the host CLIs kit already shells) +and sets `alreadyOpen: true` when the marker exists. The agent skips `alreadyOpen` +proposals. kit doing the host *read* keeps dedup deterministic; the agent still owns +all *writes*. Host CLI absent → kit emits with `alreadyOpen: null` (agent dedups, fail-open). + +## What kit must NOT do (the boundary) + +- No LLM call anywhere in kit (invariant). +- No PR/issue creation by kit (that is the agent's write, with the agent's creds). +- No agent-specific assumption in the JSON contract (the agnostic seam). +- No silent suppression (noise → a reviewable PR, never an auto-mute). + +## Open decisions for sign-off (before any build) + +1. **Dedup reads:** OK for `kit sentinel run` to do read-only `gh/glab` calls to set + `alreadyOpen`? (Alternative: leave all dedup to the agent — simpler kit, weaker guarantee.) +2. **Suppression store:** `.kit/sentinel-suppress.toml` (committed, by-findingId) — confirm path/shape. +3. **`--agent` sugar in v1**, or JSON-only first and add agent-idiom formatting later? + +## Then layer 3 (#53) + +`kit sentinel install` wires a chosen scheduler to `kit sentinel run` + adds the +SessionStart `[sentinel · N]` surface that reads the cached proposals. Out of scope here. diff --git a/package-lock.json b/package-lock.json index fbe45a13..9a5df019 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.18.0", + "version": "1.19.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.18.0", + "version": "1.19.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 8c2da716..50e58b32 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.18.0", + "version": "1.19.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/src/cli.ts b/src/cli.ts index c4a0a956..1714a9e5 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -11,6 +11,7 @@ import { checkTools } from "./check-tools.js"; import { checkServices } from "./check-services.js"; import { checkSecrets } from "./check-secrets.js"; import { checkSecurity } from "./check-security.js"; +import type { HealthCtx } from "./health.js"; import { syncSecurityFindings } from "./findings-track.js"; import { checkWebSearch } from "./check-web-search.js"; import { installTools } from "./install.js"; @@ -4049,6 +4050,44 @@ async function cmdStatus(): Promise { return true; } +/** Build the health context (sensor selection inputs) — shared by health + sentinel. */ +async function buildHealthCtx(config: kitConfig): Promise { + const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); + const remote = await execFileNoThrow("git", ["remote"], { timeout: 5_000 }); + const cwd = process.cwd(); + let vercel: { orgId?: string; projectId?: string } | undefined; + try { + const vj = JSON.parse(readFileSync(resolve(cwd, ".vercel", "project.json"), "utf8")) as { + orgId?: string; + projectId?: string; + }; + if (vj.projectId) vercel = { orgId: vj.orgId, projectId: vj.projectId }; + } catch { + vercel = undefined; + } + let services: string[] = []; + try { + const pkg = JSON.parse(readFileSync(resolve(cwd, "package.json"), "utf8")) as { + dependencies?: Record; + devDependencies?: Record; + }; + const deps = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]; + const { detectServices } = await import("./service-registry.js"); + services = await detectServices({ deps, fileExists: async (p) => existsSync(resolve(cwd, p)) }); + } catch { + services = []; + } + return { + cwd, + config, + gitRemote: remote.ok && remote.stdout.trim().length > 0, + gitlabCi: existsSync(resolve(cwd, ".gitlab-ci.yml")), + bitbucketPipelines: existsSync(resolve(cwd, "bitbucket-pipelines.yml")), + vercel, + services, + }; +} + async function cmdHealth(): Promise { const jsonMode = hasFlag(process.argv, "--json"); const config = await loadConfig(resolveConfigPath()); @@ -4059,43 +4098,8 @@ async function cmdHealth(): Promise { async () => { const { runHealth, selectSensors, defaultHealthDeps, formatHealth } = await import("./health.js"); const { syncHealthFindings } = await import("./health-track.js"); - const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); - // git remote + CI-file presence + Vercel link drive sensor selection - const remote = await execFileNoThrow("git", ["remote"], { timeout: 5_000 }); - const cwd = process.cwd(); - let vercel: { orgId?: string; projectId?: string } | undefined; - try { - const vj = JSON.parse(readFileSync(resolve(cwd, ".vercel", "project.json"), "utf8")) as { - orgId?: string; - projectId?: string; - }; - if (vj.projectId) vercel = { orgId: vj.orgId, projectId: vj.projectId }; - } catch { - vercel = undefined; - } - // Connected services (registry detection) drive the dep-detected sensors (sentry/resend). - let services: string[] = []; - try { - const pkg = JSON.parse(readFileSync(resolve(cwd, "package.json"), "utf8")) as { - dependencies?: Record; - devDependencies?: Record; - }; - const deps = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]; - const { detectServices } = await import("./service-registry.js"); - services = await detectServices({ deps, fileExists: async (p) => existsSync(resolve(cwd, p)) }); - } catch { - services = []; - } - const ctx = { - cwd, - config, - gitRemote: remote.ok && remote.stdout.trim().length > 0, - gitlabCi: existsSync(resolve(cwd, ".gitlab-ci.yml")), - bitbucketPipelines: existsSync(resolve(cwd, "bitbucket-pipelines.yml")), - vercel, - services, - }; + const ctx = await buildHealthCtx(config); const sensors = selectSensors(ctx); const findings = await runHealth(ctx, sensors, defaultHealthDeps); @@ -4216,6 +4220,66 @@ async function cmdAgentAudit(): Promise { return fails === 0; } +async function cmdSentinel(): Promise { + if (process.argv[3] !== "run") { + console.error(`${c.red}usage: kit sentinel run [--json]${c.reset}`); + process.exitCode = 1; + return false; + } + const jsonMode = hasFlag(process.argv, "--json"); + const config = await loadConfig(resolveConfigPath()); + const { runSentinel, healthToRedFindings } = await import("./sentinel.js"); + const { runHealth, selectSensors, defaultHealthDeps } = await import("./health.js"); + const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); + + const proposals = await runSentinel(process.cwd(), { + gatherRed: async () => { + const ctx = await buildHealthCtx(config); + return healthToRedFindings(await runHealth(ctx, selectSensors(ctx), defaultHealthDeps)); + }, + openMarkers: async () => { + // Read-only dedup: open issues + PRs labeled kit-sentinel, scrape findingId markers. + const out = new Set(); + for (const base of [ + ["issue", "list"], + ["pr", "list"], + ]) { + const res = await execFileNoThrow( + "gh", + [...base, "--label", "kit-sentinel", "--state", "open", "--json", "body", "--limit", "200"], + { timeout: 15_000 }, + ); + if (!res.ok) return null; // gh absent/unauth → agent dedups (fail-open) + try { + for (const it of JSON.parse(res.stdout) as { body?: string }[]) { + for (const g of (it.body ?? "").matchAll(/kit-sentinel:([^\s]+?)\s*-->/g)) out.add(g[1]); + } + } catch { + return null; + } + } + return out; + }, + }); + + if (jsonMode) { + console.log(JSON.stringify({ proposals }, null, 2)); + return true; + } + + const fresh = proposals.filter((p) => p.alreadyOpen !== true); + console.log(`${c.bold}kit sentinel${c.reset} ${c.dim}${proposals.length} proposal(s), ${fresh.length} fresh${c.reset}`); + if (proposals.length === 0) console.log(` ${c.dim}no red findings — nothing to propose${c.reset}`); + for (const p of proposals) { + const tag = p.alreadyOpen === true ? ` ${c.dim}(already open)${c.reset}` : ""; + const color = p.class === "human" ? c.red : p.class === "code" ? c.yellow : c.dim; + console.log(` ${color}${p.artifact}${c.reset} ${p.title}${tag}`); + console.log(` ${c.dim}${p.findingId} — your agent opens this with its own creds${c.reset}`); + } + if (proposals.length > 0) console.log(`${c.dim}run with --json and have any agent act on the fresh proposals${c.reset}`); + return true; +} + async function cmdWhoami(): Promise { const jsonMode = hasFlag(process.argv, "--json"); @@ -4957,6 +5021,7 @@ async function main(): Promise { ingest: cmdIngest, "supply-chain": cmdSupplyChain, "agent-audit": cmdAgentAudit, + sentinel: cmdSentinel, init: cmdInit, upgrade: cmdUpgrade, install: cmdInstall, diff --git a/src/sentinel.test.ts b/src/sentinel.test.ts new file mode 100644 index 00000000..925c36ab --- /dev/null +++ b/src/sentinel.test.ts @@ -0,0 +1,101 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + artifactForClass, + findingMarker, + healthToRedFindings, + buildProposal, + buildProposals, + applyDedup, + parseSuppressions, + runSentinel, + type RedFinding, +} from "./sentinel.js"; +import type { HealthFinding } from "./health.js"; + +describe("artifactForClass", () => { + it("maps class → artifact", () => { + assert.equal(artifactForClass("code"), "draft-pr"); + assert.equal(artifactForClass("human"), "issue"); + assert.equal(artifactForClass("noise"), "suppression-pr"); + }); +}); + +describe("healthToRedFindings", () => { + const findings: HealthFinding[] = [ + { sensor: "vercel", source: "team/p", status: "red", title: "prod deploy failed", suggestedClass: "code" }, + { sensor: "resend", source: "resend", status: "red", title: "domain unverified", suggestedClass: "human" }, + { sensor: "sentry", source: "o/p", status: "green", title: "ok" }, + { sensor: "gitlab", source: "g/r", status: "red", title: "pipeline failed" }, // no class → human + ]; + it("keeps only red, maps class (default human), stable id per sensor", () => { + const red = healthToRedFindings(findings); + assert.equal(red.length, 3); + assert.deepEqual(red.map((r) => r.id), ["health:vercel", "health:resend", "health:gitlab"]); + assert.equal(red.find((r) => r.id === "health:vercel")!.class, "code"); + assert.equal(red.find((r) => r.id === "health:gitlab")!.class, "human"); + }); +}); + +describe("buildProposal", () => { + it("code → draft-pr with a branch and the dedup marker in the body", () => { + const p = buildProposal({ id: "health:vercel", class: "code", title: "deploy failed", detail: "ERROR state" }); + assert.equal(p.artifact, "draft-pr"); + assert.equal(p.branch, "kit/sentinel/health-vercel"); + assert.ok(p.body.includes(findingMarker("health:vercel"))); + assert.deepEqual(p.labels, ["kit-sentinel", "code"]); + }); + it("human → issue, no branch", () => { + const p = buildProposal({ id: "health:resend", class: "human", title: "domain unverified" }); + assert.equal(p.artifact, "issue"); + assert.equal(p.branch, undefined); + }); + it("noise → suppression-pr with a suppress title + command", () => { + const p = buildProposal({ id: "x:y", class: "noise", title: "benign" }); + assert.equal(p.artifact, "suppression-pr"); + assert.match(p.title, /suppress x:y/); + assert.ok(p.suggestedCommands?.some((c) => c.includes("sentinel-suppress.toml"))); + }); +}); + +describe("buildProposals + suppression", () => { + const red: RedFinding[] = [ + { id: "health:vercel", class: "code", title: "a" }, + { id: "health:resend", class: "human", title: "b" }, + ]; + it("drops suppressed findings", () => { + const out = buildProposals(red, new Set(["health:resend"])); + assert.equal(out.length, 1); + assert.equal(out[0].findingId, "health:vercel"); + }); +}); + +describe("applyDedup", () => { + const proposals = buildProposals([{ id: "health:vercel", class: "code", title: "a" }]); + it("sets alreadyOpen from markers; null when not checked", () => { + assert.equal(applyDedup(proposals, new Set(["health:vercel"]))[0].alreadyOpen, true); + assert.equal(applyDedup(proposals, new Set(["other"]))[0].alreadyOpen, false); + assert.equal(applyDedup(proposals, null)[0].alreadyOpen, null); + }); +}); + +describe("parseSuppressions", () => { + it("reads the suppress = [...] array", () => { + const ids = parseSuppressions('# note\nsuppress = ["health:resend", "x:y"]\n'); + assert.deepEqual([...ids].sort(), ["health:resend", "x:y"]); + }); + it("empty when absent", () => { + assert.equal(parseSuppressions("nothing here").size, 0); + }); +}); + +describe("runSentinel (gather → build → dedup)", () => { + it("wires deps and produces deduped proposals (no suppress file in /tmp)", async () => { + const out = await runSentinel("/tmp/nonexistent-kit-repo", { + gatherRed: async () => [{ id: "health:vercel", class: "code", title: "deploy failed" }], + openMarkers: async () => new Set(["health:vercel"]), + }); + assert.equal(out.length, 1); + assert.equal(out[0].alreadyOpen, true); + }); +}); diff --git a/src/sentinel.ts b/src/sentinel.ts new file mode 100644 index 00000000..d81621a8 --- /dev/null +++ b/src/sentinel.ts @@ -0,0 +1,130 @@ +/** + * Sentinel layer 2 — the agent-agnostic responder. + * + * kit PROPOSES, any agent DISPOSES, any scheduler TRIGGERS. This module is the + * "propose" half: it deterministically turns red findings (layer 1) into a typed + * remediation-proposal document. kit never calls an LLM and never opens a PR/issue + * — `kit sentinel run --json` emits the proposals; whichever agent (Claude Code, + * Codex, Cursor, …) reads the stable JSON and performs the writes with its own + * model + creds. The JSON contract is the agnostic seam. + * + * See docs/specs/2026-06-23-sentinel-layer2-responder.md. + */ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { HealthFinding } from "./health.js"; + +export type FindingClass = "code" | "human" | "noise"; +export type Artifact = "draft-pr" | "issue" | "suppression-pr"; + +/** Normalized red finding (the responder's input — source-agnostic). */ +export interface RedFinding { + id: string; // stable; the dedup + suppression key + class: FindingClass; + title: string; + detail?: string; +} + +export interface Proposal { + findingId: string; + class: FindingClass; + artifact: Artifact; + title: string; + body: string; + branch?: string; + labels: string[]; + suggestedCommands?: string[]; + /** true = an artifact with this finding's marker is already open; null = not checked. */ + alreadyOpen: boolean | null; +} + +/** The body marker that makes an artifact dedup-able + traceable to its finding. */ +export function findingMarker(id: string): string { + return ``; +} + +export function artifactForClass(c: FindingClass): Artifact { + return c === "code" ? "draft-pr" : c === "human" ? "issue" : "suppression-pr"; +} + +function slug(id: string): string { + return id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50); +} + +/** Map a layer-1 health finding to the normalized responder shape (red only). */ +export function healthToRedFindings(findings: HealthFinding[]): RedFinding[] { + return findings + .filter((f) => f.status === "red") + .map((f) => ({ + id: `health:${f.sensor}`, + // unclassified red defaults to `human` (needs a person to look), never `noise`. + class: (f.suggestedClass ?? "human") as FindingClass, + title: f.title, + detail: f.detail, + })); +} + +/** One finding → one typed proposal (pure). */ +export function buildProposal(f: RedFinding): Proposal { + const artifact = artifactForClass(f.class); + const marker = findingMarker(f.id); + const body = [ + f.detail ?? f.title, + "", + marker, + "", + "_Proposed by `kit sentinel` (layer 2). kit detects deterministically; you (the agent) make the change and open this artifact._", + ].join("\n"); + const proposal: Proposal = { + findingId: f.id, + class: f.class, + artifact, + title: artifact === "suppression-pr" ? `chore(sentinel): suppress ${f.id}` : f.title, + body, + labels: ["kit-sentinel", f.class], + alreadyOpen: null, + }; + if (artifact !== "issue") proposal.branch = `kit/sentinel/${slug(f.id)}`; + if (artifact === "suppression-pr") { + proposal.suggestedCommands = [`add "${f.id}" to .kit/sentinel-suppress.toml`]; + } + return proposal; +} + +/** Findings (minus suppressed) → proposals. Pure. */ +export function buildProposals(findings: RedFinding[], suppressed: ReadonlySet = new Set()): Proposal[] { + return findings.filter((f) => !suppressed.has(f.id)).map(buildProposal); +} + +/** Mark proposals whose finding already has an open artifact (null openMarkers = not checked). */ +export function applyDedup(proposals: Proposal[], openMarkers: ReadonlySet | null): Proposal[] { + return proposals.map((p) => ({ ...p, alreadyOpen: openMarkers ? openMarkers.has(p.findingId) : null })); +} + +/** Parse `.kit/sentinel-suppress.toml` — `suppress = ["id-a", "id-b"]`. */ +export function parseSuppressions(toml: string): Set { + const ids = new Set(); + const m = /suppress\s*=\s*\[([^\]]*)\]/s.exec(toml); + if (m) for (const q of m[1].matchAll(/"([^"]+)"|'([^']+)'/g)) ids.add(q[1] ?? q[2]); + return ids; +} + +export interface SentinelDeps { + /** Gather the current red findings (layer 1). */ + gatherRed(): Promise; + /** Markers of findings that already have an open artifact (null = couldn't check). */ + openMarkers(): Promise | null>; +} + +/** Build the agent-agnostic proposal set: gather → drop suppressed → build → dedup. */ +export async function runSentinel(cwd: string, deps: SentinelDeps): Promise { + let suppressed = new Set(); + try { + suppressed = parseSuppressions(readFileSync(resolve(cwd, ".kit", "sentinel-suppress.toml"), "utf8")); + } catch { + // no suppress file → nothing suppressed + } + const findings = await deps.gatherRed(); + const proposals = buildProposals(findings, suppressed); + return applyDedup(proposals, await deps.openMarkers()); +}