Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<!-- kit-sentinel:<id> -->` 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
Expand Down
96 changes: 96 additions & 0 deletions docs/specs/2026-06-23-sentinel-layer2-responder.md
Original file line number Diff line number Diff line change
@@ -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": "<caller stamps time>",
"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 <!-- kit-sentinel:findingId --> marker …",
"branch": "kit/sentinel/<findingId-slug>", // draft-pr / suppression-pr only
"labels": ["kit-sentinel", "…"],
"suggestedCommands": ["…"], // deterministic hints, optional
"alreadyOpen": false // set by dedup (below)
}
]
}
```

`kit sentinel run --agent <claude-code|codex|cursor|…>` 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 `<!-- kit-sentinel:<findingId> -->`
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.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
137 changes: 101 additions & 36 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -4049,6 +4050,44 @@ async function cmdStatus(): Promise<boolean> {
return true;
}

/** Build the health context (sensor selection inputs) — shared by health + sentinel. */
async function buildHealthCtx(config: kitConfig): Promise<HealthCtx> {
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<string, string>;
devDependencies?: Record<string, string>;
};
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<boolean> {
const jsonMode = hasFlag(process.argv, "--json");
const config = await loadConfig(resolveConfigPath());
Expand All @@ -4059,43 +4098,8 @@ async function cmdHealth(): Promise<boolean> {
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<string, string>;
devDependencies?: Record<string, string>;
};
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);
Expand Down Expand Up @@ -4216,6 +4220,66 @@ async function cmdAgentAudit(): Promise<boolean> {
return fails === 0;
}

async function cmdSentinel(): Promise<boolean> {
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<string>();
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<boolean> {
const jsonMode = hasFlag(process.argv, "--json");

Expand Down Expand Up @@ -4957,6 +5021,7 @@ async function main(): Promise<void> {
ingest: cmdIngest,
"supply-chain": cmdSupplyChain,
"agent-audit": cmdAgentAudit,
sentinel: cmdSentinel,
init: cmdInit,
upgrade: cmdUpgrade,
install: cmdInstall,
Expand Down
Loading
Loading