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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/analyze.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ async function detectCiFiles(cwd: string): Promise<string[]> {
}
}
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;
Expand Down
7 changes: 5 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4061,12 +4061,15 @@ async function cmdHealth(): Promise<boolean> {
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);
Expand Down
88 changes: 88 additions & 0 deletions src/health-sensors/bitbucket-pipelines.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
95 changes: 95 additions & 0 deletions src/health-sensors/bitbucket-pipelines.ts
Original file line number Diff line number Diff line change
@@ -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<HealthFinding[]> {
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",
}];
},
};
1 change: 1 addition & 0 deletions src/health-sensors/github-actions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function deps(over: Record<string, { stdout: string; ok: boolean }> = {}): 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: {} };
Expand Down
79 changes: 79 additions & 0 deletions src/health-sensors/gitlab-ci.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
83 changes: 83 additions & 0 deletions src/health-sensors/gitlab-ci.ts
Original file line number Diff line number Diff line change
@@ -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<HealthFinding[]> {
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",
}];
},
};
Loading
Loading