diff --git a/CHANGELOG.md b/CHANGELOG.md index 63117172..991bbd46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] ### Added +- **`kit health` now covers all three git hosts: GitLab CI and Bitbucket Pipelines sensors (GitHub was already there).** Both probe the platform REST API via a new `httpGet` on `HealthDeps` (the HTTP-probe path the sentinel design anticipated): GitLab `GET /api/v4/projects/:path/pipelines` with `GITLAB_TOKEN`, Bitbucket `GET /2.0/repositories/:ws/:repo/pipelines/` with `BITBUCKET_TOKEN` (or `BITBUCKET_USERNAME` + `BITBUCKET_APP_PASSWORD`). Each flags the most recent terminal pipeline as red when it failed, records the `host/path` it checked, and reports `unknown` (never a false `green`) on a missing token, a non-OK response, or no git remote. Sensors are selected by CI-file presence (`.gitlab-ci.yml` / `bitbucket-pipelines.yml`). Also: `analyze`'s CI-file detection now recognizes `bitbucket-pipelines.yml` (it knew `.github/workflows` + `.gitlab-ci.yml` but missed Bitbucket). Live API smoke is pending a real GitLab/Bitbucket project + tokens; the parsers + auth + remote-parsing are fixture-tested against the documented schemas. - **Two services in the registry: Keycloak and Atlassian (acli).** Keycloak is detected from its clients (`keycloak-js`, `keycloak-connect`, `keycloak-admin-client`, `keycloak-angular`, `python-keycloak`, Go `gocloak`) and declares its realm/admin secrets (`KEYCLOAK_URL`, `KEYCLOAK_REALM`, `KEYCLOAK_CLIENT_ID/SECRET`, `KEYCLOAK_ADMIN/_PASSWORD`); it carries no mise tool because it is a self-hosted server (run via Docker), with admin through the server's own `kcadm.sh`. Atlassian is detected from `bitbucket-pipelines.yml` / `.bitbucket`, provisions the Atlassian CLI via mise (`tool: acli` → `aqua:atlassian.com/acli`), and tracks `ATLASSIAN_API_TOKEN` / `ATLASSIAN_SITE_URL`; its auth is left as an informational note rather than a guessed login command. Adding each was a single registry data row (no detector/generator edits), per the unified-registry design. ### Fixed diff --git a/src/analyze.ts b/src/analyze.ts index 9152188c..77c08d8d 100644 --- a/src/analyze.ts +++ b/src/analyze.ts @@ -104,6 +104,7 @@ async function detectCiFiles(cwd: string): Promise { } } if (await fileExists(join(cwd, ".gitlab-ci.yml"))) ci.push(".gitlab-ci.yml"); + if (await fileExists(join(cwd, "bitbucket-pipelines.yml"))) ci.push("bitbucket-pipelines.yml"); if (await fileExists(join(cwd, "circleci", "config.yml"))) ci.push("circleci/config.yml"); return ci; diff --git a/src/cli.ts b/src/cli.ts index b07d67b3..ca018c5f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4061,12 +4061,15 @@ async function cmdHealth(): Promise { const { syncHealthFindings } = await import("./health-track.js"); const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); - // git remote presence drives sensor selection + // git remote + CI-file presence drive sensor selection const remote = await execFileNoThrow("git", ["remote"], { timeout: 5_000 }); + const cwd = process.cwd(); const ctx = { - cwd: process.cwd(), + cwd, config, gitRemote: remote.ok && remote.stdout.trim().length > 0, + gitlabCi: existsSync(resolve(cwd, ".gitlab-ci.yml")), + bitbucketPipelines: existsSync(resolve(cwd, "bitbucket-pipelines.yml")), }; const sensors = selectSensors(ctx); diff --git a/src/health-sensors/bitbucket-pipelines.test.ts b/src/health-sensors/bitbucket-pipelines.test.ts new file mode 100644 index 00000000..d3c6473c --- /dev/null +++ b/src/health-sensors/bitbucket-pipelines.test.ts @@ -0,0 +1,88 @@ +import { describe, it, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { + parseBitbucketPipelines, + latestFailedBitbucket, + bitbucketAuthHeader, + bitbucketSensor, +} from "./bitbucket-pipelines.js"; +import type { HealthCtx, HealthDeps, HttpResponse } from "../health.js"; + +const body = JSON.stringify({ + values: [ + { build_number: 42, state: { name: "COMPLETED", result: { name: "FAILED" } }, target: { ref_name: "main" }, created_on: "2026-06-22T08:00:00Z" }, + { build_number: 41, state: { name: "COMPLETED", result: { name: "SUCCESSFUL" } }, target: { ref_name: "main" }, created_on: "2026-06-21T08:00:00Z" }, + { build_number: 43, state: { name: "IN_PROGRESS" }, target: { ref_name: "feat" }, created_on: "2026-06-22T09:00:00Z" }, + ], +}); + +function deps(over: { remoteOk?: boolean; remote?: string; http?: HttpResponse } = {}): HealthDeps { + return { + runCli: async (cmd, args) => { + if (cmd === "git" && args[0] === "remote") { + const ok = over.remoteOk ?? true; + return { stdout: over.remote ?? "git@bitbucket.org:acme/web.git", stderr: "", exitCode: ok ? 0 : 1, ok }; + } + return { stdout: "", stderr: "", exitCode: 0, ok: true }; + }, + httpGet: async () => over.http ?? { ok: true, status: 200, body }, + }; +} +const ctx: HealthCtx = { cwd: "/tmp/repo", config: {} }; + +describe("parseBitbucketPipelines / latestFailedBitbucket", () => { + it("flags the most recent COMPLETED pipeline when FAILED (ignores IN_PROGRESS)", () => { + const f = latestFailedBitbucket(parseBitbucketPipelines(body)); + assert.equal(f?.build_number, 42); + }); + it("returns null when the latest completed pipeline succeeded", () => { + const ok = JSON.stringify({ values: [{ build_number: 41, state: { name: "COMPLETED", result: { name: "SUCCESSFUL" } }, created_on: "2026-06-21T08:00:00Z" }] }); + assert.equal(latestFailedBitbucket(parseBitbucketPipelines(ok)), null); + }); + it("treats STOPPED (cancelled) as not-red", () => { + const stopped = JSON.stringify({ values: [{ build_number: 40, state: { name: "COMPLETED", result: { name: "STOPPED" } }, created_on: "2026-06-22T08:00:00Z" }] }); + assert.equal(latestFailedBitbucket(parseBitbucketPipelines(stopped)), null); + }); +}); + +describe("bitbucketAuthHeader", () => { + it("prefers a bearer token", () => { + assert.equal(bitbucketAuthHeader({ BITBUCKET_TOKEN: "t" } as NodeJS.ProcessEnv), "Bearer t"); + }); + it("falls back to basic from username + app password", () => { + const h = bitbucketAuthHeader({ BITBUCKET_USERNAME: "u", BITBUCKET_APP_PASSWORD: "p" } as NodeJS.ProcessEnv); + assert.equal(h, `Basic ${Buffer.from("u:p").toString("base64")}`); + }); + it("returns null with no creds", () => { + assert.equal(bitbucketAuthHeader({} as NodeJS.ProcessEnv), null); + }); +}); + +describe("bitbucketSensor.probe", () => { + afterEach(() => { + delete process.env.BITBUCKET_TOKEN; + delete process.env.BITBUCKET_USERNAME; + delete process.env.BITBUCKET_APP_PASSWORD; + }); + + it("emits red when the latest pipeline failed", async () => { + process.env.BITBUCKET_TOKEN = "bbt"; + const out = await bitbucketSensor.probe(ctx, deps()); + assert.equal(out[0].status, "red"); + assert.equal(out[0].source, "bitbucket.org/acme/web"); + assert.match(out[0].title, /main/); + }); + + it("is unknown (not green) when no credentials — no silent gap", async () => { + const out = await bitbucketSensor.probe(ctx, deps()); + assert.equal(out[0].status, "unknown"); + assert.match(out[0].title, /credentials/); + }); + + it("is unknown on a non-OK API response", async () => { + process.env.BITBUCKET_TOKEN = "bbt"; + const out = await bitbucketSensor.probe(ctx, deps({ http: { ok: false, status: 403, body: "" } })); + assert.equal(out[0].status, "unknown"); + assert.match(out[0].title, /403/); + }); +}); diff --git a/src/health-sensors/bitbucket-pipelines.ts b/src/health-sensors/bitbucket-pipelines.ts new file mode 100644 index 00000000..be0b8cfa --- /dev/null +++ b/src/health-sensors/bitbucket-pipelines.ts @@ -0,0 +1,95 @@ +import type { HealthFinding, HealthSensor } from "../health.js"; +import { parseGitRemote } from "./remote.js"; + +export interface BbPipeline { + uuid?: string; + build_number?: number; + state?: { name?: string; result?: { name?: string } }; + target?: { ref_name?: string }; + created_on: string; +} + +// Bitbucket pipeline result names that mean "red" (STOPPED = user-cancelled, not a failure). +const BB_RED = new Set(["FAILED", "ERROR"]); + +export function parseBitbucketPipelines(body: string): BbPipeline[] { + try { + const obj = JSON.parse(body) as { values?: BbPipeline[] }; + return Array.isArray(obj.values) ? obj.values : []; + } catch { + return []; + } +} + +/** Most recent COMPLETED pipeline; returned only when its result is FAILED/ERROR. */ +export function latestFailedBitbucket(pipelines: BbPipeline[]): BbPipeline | null { + const completed = pipelines.filter((p) => p.state?.name === "COMPLETED"); + if (completed.length === 0) return null; + const latest = completed.reduce((a, b) => (a.created_on >= b.created_on ? a : b)); + const result = latest.state?.result?.name; + return result && BB_RED.has(result) ? latest : null; +} + +/** Build the Authorization header from env, or null when no credentials are set. */ +export function bitbucketAuthHeader(env: NodeJS.ProcessEnv): string | null { + if (env.BITBUCKET_TOKEN) return `Bearer ${env.BITBUCKET_TOKEN}`; + if (env.BITBUCKET_USERNAME && env.BITBUCKET_APP_PASSWORD) { + const basic = Buffer.from(`${env.BITBUCKET_USERNAME}:${env.BITBUCKET_APP_PASSWORD}`).toString("base64"); + return `Basic ${basic}`; + } + return null; +} + +export const bitbucketSensor: HealthSensor = { + id: "bitbucket-pipelines", + async probe(_ctx, deps): Promise { + const remoteRes = await deps.runCli("git", ["remote", "get-url", "origin"]); + const slug = remoteRes.ok ? parseGitRemote(remoteRes.stdout) : null; + if (!slug) { + return [{ + sensor: "bitbucket-pipelines", + source: "(no git remote)", + status: "unknown", + title: "Bitbucket Pipelines probe could not resolve the remote", + detail: "git remote get-url origin failed", + }]; + } + const source = `${slug.host}/${slug.path}`; + const auth = bitbucketAuthHeader(process.env); + if (!auth) { + return [{ + sensor: "bitbucket-pipelines", + source, + status: "unknown", + title: "Bitbucket Pipelines probe skipped: no credentials", + detail: "set BITBUCKET_TOKEN, or BITBUCKET_USERNAME + BITBUCKET_APP_PASSWORD", + }]; + } + const url = + `https://api.bitbucket.org/2.0/repositories/${slug.path}/pipelines/?sort=-created_on&pagelen=20`; + const res = await deps.httpGet(url, { Authorization: auth }); + if (!res.ok) { + return [{ + sensor: "bitbucket-pipelines", + source, + status: "unknown", + title: `Bitbucket Pipelines API returned HTTP ${res.status}`, + detail: "check the token scope (pipeline:read) / repo access", + }]; + } + const failed = latestFailedBitbucket(parseBitbucketPipelines(res.body)); + if (!failed) { + return [{ sensor: "bitbucket-pipelines", source, status: "green", title: "Bitbucket Pipelines: latest run green" }]; + } + const ref = failed.target?.ref_name ?? "?"; + return [{ + sensor: "bitbucket-pipelines", + source, + status: "red", + severity: "high", + title: `Bitbucket Pipelines failing on ${ref}`, + detail: `pipeline #${failed.build_number ?? "?"} ${failed.state?.result?.name} (${failed.created_on})`, + suggestedClass: "code", + }]; + }, +}; diff --git a/src/health-sensors/github-actions.test.ts b/src/health-sensors/github-actions.test.ts index f8bae9db..4a092b43 100644 --- a/src/health-sensors/github-actions.test.ts +++ b/src/health-sensors/github-actions.test.ts @@ -22,6 +22,7 @@ function deps(over: Record = {}): Healt if (r) return { stdout: r.stdout, stderr: "", exitCode: r.ok ? 0 : 1, ok: r.ok }; return { stdout: "", stderr: "", exitCode: 0, ok: true }; }, + httpGet: async () => ({ ok: true, status: 200, body: "" }), }; } const ctx: HealthCtx = { cwd: "/tmp/repo", config: {} }; diff --git a/src/health-sensors/gitlab-ci.test.ts b/src/health-sensors/gitlab-ci.test.ts new file mode 100644 index 00000000..66d856c8 --- /dev/null +++ b/src/health-sensors/gitlab-ci.test.ts @@ -0,0 +1,79 @@ +import { describe, it, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { parseGitlabPipelines, latestFailedPipeline, gitlabSensor } from "./gitlab-ci.js"; +import type { HealthCtx, HealthDeps, HttpResponse } from "../health.js"; + +const pipelines = JSON.stringify([ + { id: 9, status: "failed", ref: "main", created_at: "2026-06-22T08:00:00Z" }, + { id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }, + { id: 7, status: "running", ref: "feat", created_at: "2026-06-22T09:00:00Z" }, +]); + +function deps(over: { remoteOk?: boolean; remote?: string; http?: HttpResponse } = {}): HealthDeps { + return { + runCli: async (cmd, args) => { + if (cmd === "git" && args[0] === "remote") { + const ok = over.remoteOk ?? true; + return { stdout: over.remote ?? "git@gitlab.com:acme/web.git", stderr: "", exitCode: ok ? 0 : 1, ok }; + } + return { stdout: "", stderr: "", exitCode: 0, ok: true }; + }, + httpGet: async () => over.http ?? { ok: true, status: 200, body: pipelines }, + }; +} +const ctx: HealthCtx = { cwd: "/tmp/repo", config: {} }; + +describe("parseGitlabPipelines / latestFailedPipeline", () => { + it("flags the most recent TERMINAL pipeline when it failed (ignores running)", () => { + const f = latestFailedPipeline(parseGitlabPipelines(pipelines)); + assert.equal(f?.id, 9); + }); + it("returns null when the latest terminal pipeline succeeded", () => { + const json = JSON.stringify([{ id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }]); + assert.equal(latestFailedPipeline(parseGitlabPipelines(json)), null); + }); + it("returns [] on garbage", () => { + assert.deepEqual(parseGitlabPipelines("nope"), []); + }); +}); + +describe("gitlabSensor.probe", () => { + afterEach(() => { + delete process.env.GITLAB_TOKEN; + }); + + it("emits red when the latest pipeline failed", async () => { + process.env.GITLAB_TOKEN = "glpat-xxx"; + const out = await gitlabSensor.probe(ctx, deps()); + assert.equal(out.length, 1); + assert.equal(out[0].status, "red"); + assert.equal(out[0].source, "gitlab.com/acme/web"); + assert.equal(out[0].suggestedClass, "code"); + }); + + it("emits green when the latest terminal pipeline passed", async () => { + process.env.GITLAB_TOKEN = "glpat-xxx"; + const ok = JSON.stringify([{ id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }]); + const out = await gitlabSensor.probe(ctx, deps({ http: { ok: true, status: 200, body: ok } })); + assert.equal(out[0].status, "green"); + }); + + it("is unknown (not green) when GITLAB_TOKEN is missing — no silent gap", async () => { + const out = await gitlabSensor.probe(ctx, deps()); + assert.equal(out[0].status, "unknown"); + assert.match(out[0].title, /GITLAB_TOKEN/); + }); + + it("is unknown on a non-OK API response", async () => { + process.env.GITLAB_TOKEN = "glpat-xxx"; + const out = await gitlabSensor.probe(ctx, deps({ http: { ok: false, status: 401, body: "" } })); + assert.equal(out[0].status, "unknown"); + assert.match(out[0].title, /401/); + }); + + it("is unknown when there is no git remote", async () => { + process.env.GITLAB_TOKEN = "glpat-xxx"; + const out = await gitlabSensor.probe(ctx, deps({ remoteOk: false })); + assert.equal(out[0].status, "unknown"); + }); +}); diff --git a/src/health-sensors/gitlab-ci.ts b/src/health-sensors/gitlab-ci.ts new file mode 100644 index 00000000..85f288d4 --- /dev/null +++ b/src/health-sensors/gitlab-ci.ts @@ -0,0 +1,83 @@ +import type { HealthFinding, HealthSensor } from "../health.js"; +import { parseGitRemote } from "./remote.js"; + +export interface GlPipeline { + id: number; + status: string; + ref: string; + sha?: string; + web_url?: string; + created_at: string; +} + +// GitLab pipeline terminal states (non-terminal: created/waiting/preparing/pending/running/manual/scheduled). +const TERMINAL = new Set(["success", "failed", "canceled", "skipped"]); + +export function parseGitlabPipelines(json: string): GlPipeline[] { + try { + const arr = JSON.parse(json) as GlPipeline[]; + return Array.isArray(arr) ? arr : []; + } catch { + return []; + } +} + +/** Most recent terminal pipeline; returned only when it failed. */ +export function latestFailedPipeline(pipelines: GlPipeline[]): GlPipeline | null { + const terminal = pipelines.filter((p) => TERMINAL.has(p.status)); + if (terminal.length === 0) return null; + const latest = terminal.reduce((a, b) => (a.created_at >= b.created_at ? a : b)); + return latest.status === "failed" ? latest : null; +} + +export const gitlabSensor: HealthSensor = { + id: "gitlab-ci", + async probe(_ctx, deps): Promise { + const remoteRes = await deps.runCli("git", ["remote", "get-url", "origin"]); + const slug = remoteRes.ok ? parseGitRemote(remoteRes.stdout) : null; + if (!slug) { + return [{ + sensor: "gitlab-ci", + source: "(no git remote)", + status: "unknown", + title: "GitLab CI probe could not resolve the remote", + detail: "git remote get-url origin failed", + }]; + } + const source = `${slug.host}/${slug.path}`; + const token = process.env.GITLAB_TOKEN; + if (!token) { + return [{ + sensor: "gitlab-ci", + source, + status: "unknown", + title: "GitLab CI probe skipped: GITLAB_TOKEN not set", + detail: "set GITLAB_TOKEN (read_api) to enable the GitLab CI sensor", + }]; + } + const url = `https://${slug.host}/api/v4/projects/${encodeURIComponent(slug.path)}/pipelines?per_page=20`; + const res = await deps.httpGet(url, { "PRIVATE-TOKEN": token }); + if (!res.ok) { + return [{ + sensor: "gitlab-ci", + source, + status: "unknown", + title: `GitLab CI API returned HTTP ${res.status}`, + detail: "check GITLAB_TOKEN scope / project access", + }]; + } + const failed = latestFailedPipeline(parseGitlabPipelines(res.body)); + if (!failed) { + return [{ sensor: "gitlab-ci", source, status: "green", title: "GitLab CI: latest pipeline green" }]; + } + return [{ + sensor: "gitlab-ci", + source, + status: "red", + severity: "high", + title: `GitLab CI pipeline failing on ${failed.ref}`, + detail: `pipeline #${failed.id} failed (${failed.created_at})`, + suggestedClass: "code", + }]; + }, +}; diff --git a/src/health-sensors/remote.test.ts b/src/health-sensors/remote.test.ts new file mode 100644 index 00000000..117247e1 --- /dev/null +++ b/src/health-sensors/remote.test.ts @@ -0,0 +1,26 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { parseGitRemote } from "./remote.js"; + +describe("parseGitRemote", () => { + it("parses an SSH remote", () => { + assert.deepEqual(parseGitRemote("git@gitlab.com:acme/web.git"), { host: "gitlab.com", path: "acme/web" }); + }); + + it("parses an HTTPS remote and strips .git", () => { + assert.deepEqual(parseGitRemote("https://bitbucket.org/acme/web.git"), { host: "bitbucket.org", path: "acme/web" }); + }); + + it("keeps GitLab nested subgroups", () => { + assert.deepEqual(parseGitRemote("git@gitlab.com:acme/team/web.git"), { host: "gitlab.com", path: "acme/team/web" }); + }); + + it("strips an embedded HTTPS user", () => { + assert.deepEqual(parseGitRemote("https://x-token-auth@bitbucket.org/acme/web"), { host: "bitbucket.org", path: "acme/web" }); + }); + + it("returns null for junk", () => { + assert.equal(parseGitRemote(""), null); + assert.equal(parseGitRemote("not a url"), null); + }); +}); diff --git a/src/health-sensors/remote.ts b/src/health-sensors/remote.ts new file mode 100644 index 00000000..79928048 --- /dev/null +++ b/src/health-sensors/remote.ts @@ -0,0 +1,30 @@ +/** Parsed git remote: the host and the owner/repo path (no `.git`, no leading slash). */ +export interface RemoteSlug { + host: string; + path: string; +} + +/** + * Parse a git remote URL into { host, path }. Handles both SSH + * (`git@gitlab.com:group/sub/repo.git`) and HTTPS + * (`https://bitbucket.org/ws/repo.git`) forms. Returns null if unparseable. + * `path` keeps nested groups (GitLab subgroups) and drops a trailing `.git`. + */ +export function parseGitRemote(url: string): RemoteSlug | null { + const trimmed = url.trim(); + if (!trimmed) return null; + + // SSH: git@host:owner/repo(.git) or ssh://git@host/owner/repo(.git) + const ssh = trimmed.match(/^(?:ssh:\/\/)?[^@]+@([^:/]+)[:/](.+?)(?:\.git)?$/); + if (ssh) return { host: ssh[1], path: stripGit(ssh[2]) }; + + // HTTPS/HTTP: https://host/owner/repo(.git) + const https = trimmed.match(/^https?:\/\/(?:[^@/]+@)?([^/]+)\/(.+?)(?:\.git)?$/); + if (https) return { host: https[1], path: stripGit(https[2]) }; + + return null; +} + +function stripGit(p: string): string { + return p.replace(/\.git$/, "").replace(/^\/+/, "").replace(/\/+$/, ""); +} diff --git a/src/health.test.ts b/src/health.test.ts index 311f9673..7b45c722 100644 --- a/src/health.test.ts +++ b/src/health.test.ts @@ -4,7 +4,10 @@ import { runHealth, type HealthSensor, type HealthCtx, type HealthDeps } from ". import { selectSensors, defaultHealthDeps, HEALTH_SENSORS } from "./health.js"; const ctx: HealthCtx = { cwd: "/tmp/repo", config: {} }; -const deps: HealthDeps = { runCli: async () => ({ stdout: "", stderr: "", exitCode: 0, ok: true }) }; +const deps: HealthDeps = { + runCli: async () => ({ stdout: "", stderr: "", exitCode: 0, ok: true }), + httpGet: async () => ({ ok: true, status: 200, body: "" }), +}; describe("runHealth", () => { it("aggregates findings from all sensors", async () => { @@ -36,8 +39,19 @@ describe("selectSensors", () => { assert.equal(sel.some((s) => s.id === "github-actions"), false); }); - it("registry is non-empty and defaultHealthDeps exposes runCli", () => { - assert.ok(HEALTH_SENSORS.length >= 1); + it("includes gitlab-ci only when a .gitlab-ci.yml is present", () => { + assert.ok(selectSensors({ cwd: "/r", config: {}, gitlabCi: true }).some((s) => s.id === "gitlab-ci")); + assert.equal(selectSensors({ cwd: "/r", config: {} }).some((s) => s.id === "gitlab-ci"), false); + }); + + it("includes bitbucket-pipelines only when a bitbucket-pipelines.yml is present", () => { + assert.ok(selectSensors({ cwd: "/r", config: {}, bitbucketPipelines: true }).some((s) => s.id === "bitbucket-pipelines")); + assert.equal(selectSensors({ cwd: "/r", config: {} }).some((s) => s.id === "bitbucket-pipelines"), false); + }); + + it("registry has all three CI sensors and defaultHealthDeps exposes runCli + httpGet", () => { + assert.ok(HEALTH_SENSORS.length >= 3); assert.equal(typeof defaultHealthDeps.runCli, "function"); + assert.equal(typeof defaultHealthDeps.httpGet, "function"); }); }); diff --git a/src/health.ts b/src/health.ts index 6f101d3b..51c9c3f8 100644 --- a/src/health.ts +++ b/src/health.ts @@ -1,6 +1,8 @@ import type { kitConfig } from "./config.js"; import { execFileNoThrow, type ExecResult } from "./utils/execFileNoThrow.js"; import { githubActionsSensor } from "./health-sensors/github-actions.js"; +import { gitlabSensor } from "./health-sensors/gitlab-ci.js"; +import { bitbucketSensor } from "./health-sensors/bitbucket-pipelines.js"; export type HealthStatus = "green" | "red" | "unknown"; export type HealthClass = "code" | "human" | "noise"; @@ -21,10 +23,22 @@ export interface HealthCtx { config: kitConfig; /** True when the repo has a git remote (computed by the CLI layer). */ gitRemote?: boolean; + /** True when a .gitlab-ci.yml is present (GitLab CI in use). */ + gitlabCi?: boolean; + /** True when a bitbucket-pipelines.yml is present (Bitbucket Pipelines in use). */ + bitbucketPipelines?: boolean; +} + +export interface HttpResponse { + ok: boolean; + status: number; + body: string; } export interface HealthDeps { runCli(command: string, args: string[]): Promise; + /** Read-only HTTP GET for API-based probes (Bitbucket, future Vercel/Sentry/Resend). */ + httpGet(url: string, headers?: Record): Promise; } export interface HealthSensor { @@ -58,20 +72,35 @@ export async function runHealth( return all.flat(); } -export const HEALTH_SENSORS: HealthSensor[] = [githubActionsSensor]; +export const HEALTH_SENSORS: HealthSensor[] = [githubActionsSensor, gitlabSensor, bitbucketSensor]; -/** Returns the sensors whose underlying service the project is connected to. */ +/** Returns the sensors whose underlying CI platform the project actually uses. */ export function selectSensors(ctx: HealthCtx): HealthSensor[] { return HEALTH_SENSORS.filter((s) => { - if (s.id === "github-actions") { - return ctx.gitRemote === true || ctx.config.context?.github !== undefined; + switch (s.id) { + case "github-actions": + return ctx.gitRemote === true || ctx.config.context?.github !== undefined; + case "gitlab-ci": + return ctx.gitlabCi === true; + case "bitbucket-pipelines": + return ctx.bitbucketPipelines === true; + default: + return false; } - return false; }); } export const defaultHealthDeps: HealthDeps = { runCli: (command, args) => execFileNoThrow(command, args, { timeout: 15_000 }), + httpGet: async (url, headers) => { + try { + const res = await fetch(url, { headers, signal: AbortSignal.timeout(15_000) }); + return { ok: res.ok, status: res.status, body: await res.text() }; + } catch (e) { + // Network error / timeout → not ok, status 0; the sensor maps this to `unknown`. + return { ok: false, status: 0, body: e instanceof Error ? e.message : String(e) }; + } + }, }; const MARK: Record = { green: "✓", red: "✗", unknown: "?" };