Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(shared): move serve lock, path normalizer and keyed cache into shared packages (#3021)
Raghav Chamadiyafe9497b7fe20
diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex 766fe2d48..451e7bd00 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -14,6 +14,7 @@"./types": "./src/types.ts","./blast-radius": "./src/blast-radius.ts","./c4": "./src/c4.ts",+ "./cache": "./src/cache.ts","./chat": "./src/chat.ts","./code-health": "./src/code-health.ts","./costs": "./src/costs.ts",diff --git a/packages/api-client/src/adapter-fetch.test.ts b/packages/api-client/src/adapter-fetch.test.tsnew file mode 100644index 000000000..84e6948d9--- /dev/null+++ b/packages/api-client/src/adapter-fetch.test.ts@@ -0,0 +1,172 @@+import { afterEach, describe, expect, it } from "vitest";++import {+ ApiClientError,+ apiGet,+ apiPost,+ configureApiClient,+ createAdapterFetch,+ type MinimalRequestInit,+ type MinimalResponse,+} from "./client";++interface Call {+ url: string;+ init: MinimalRequestInit;+}++function fakeMinimal(response: MinimalResponse) {+ const calls: Call[] = [];+ const minimal = async (url: string, init: MinimalRequestInit) => {+ calls.push({ url, init });+ return response;+ };+ return { calls, minimal };+}++function respond(status: number, text: string): MinimalResponse {+ return { status, ok: status >= 200 && status < 300, headers: {}, text };+}++describe("createAdapterFetch", () => {+ afterEach(() => {+ // The client config is module-global; leave it as the next test expects.+ configureApiClient({ baseUrl: "" });+ });++ it("parses an ok JSON body and passes method, headers and body through", async () => {+ const { calls, minimal } = fakeMinimal(respond(200, '{"id":"r1","n":2}'));+ configureApiClient({+ baseUrl: "http://127.0.0.1:7337",+ token: "secret",+ fetch: createAdapterFetch(minimal),+ });++ const result = await apiPost<{ id: string; n: number }>("/api/repos", { name: "x" });++ expect(result).toEqual({ id: "r1", n: 2 });+ expect(calls).toHaveLength(1);+ const [call] = calls;+ expect(call?.url).toBe("http://127.0.0.1:7337/api/repos");+ expect(call?.init.method).toBe("POST");+ expect(call?.init.body).toBe('{"name":"x"}');+ expect(call?.init.headers).toEqual({+ "Content-Type": "application/json",+ Authorization: "Bearer secret",+ });+ });++ it("flattens a Headers instance into a plain object", async () => {+ const { calls, minimal } = fakeMinimal(respond(200, "{}"));+ await createAdapterFetch(minimal)("http://h", { headers: new Headers({ "X-A": "1" }) });+ expect(calls[0]?.init.headers).toEqual({ "x-a": "1" });+ });++ describe("without a Headers global", () => {+ const realHeaders = globalThis.Headers;+ afterEach(() => {+ globalThis.Headers = realHeaders;+ });++ it("sends apiGet and apiPost with plain-object headers", async () => {+ // @ts-expect-error simulating a runtime that has no Headers global+ delete globalThis.Headers;+ expect(typeof globalThis.Headers).toBe("undefined");++ const { calls, minimal } = fakeMinimal(respond(200, '{"ok":true}'));+ configureApiClient({+ baseUrl: "http://h",+ token: () => "tok",+ fetch: createAdapterFetch(minimal),+ });++ await expect(apiGet("/api/a", { q: "x" })).resolves.toEqual({ ok: true });+ await expect(apiPost("/api/b", { n: 1 })).resolves.toEqual({ ok: true });++ const expectedHeaders = {+ "Content-Type": "application/json",+ Authorization: "Bearer tok",+ };+ expect(calls).toEqual([+ { url: "http://h/api/a?q=x", init: { method: "GET", headers: expectedHeaders } },+ {+ url: "http://h/api/b",+ init: { method: "POST", headers: expectedHeaders, body: '{"n":1}' },+ },+ ]);+ });++ it("omits Authorization when no token resolves", async () => {+ // @ts-expect-error simulating a runtime that has no Headers global+ delete globalThis.Headers;++ const { calls, minimal } = fakeMinimal(respond(200, "{}"));+ configureApiClient({ baseUrl: "http://h", fetch: createAdapterFetch(minimal) });++ await apiGet("/api/a");+ expect(calls[0]?.init.headers).toEqual({ "Content-Type": "application/json" });+ });+ });++ it("surfaces an error status through ApiClientError with the JSON detail", async () => {+ const { minimal } = fakeMinimal(respond(404, '{"detail":"Repo not found"}'));+ configureApiClient({ baseUrl: "http://h", fetch: createAdapterFetch(minimal) });++ const err = await apiGet("/api/repos/missing").catch((e: unknown) => e);++ expect(err).toBeInstanceOf(ApiClientError);+ expect((err as ApiClientError).status).toBe(404);+ expect((err as ApiClientError).detail).toBe("Repo not found");+ });++ it("falls back to the HTTP status as detail when an error body is not JSON", async () => {+ const { minimal } = fakeMinimal(respond(502, "<html>Bad Gateway</html>"));+ configureApiClient({ baseUrl: "http://h", fetch: createAdapterFetch(minimal) });++ const err = await apiGet("/api/x").catch((e: unknown) => e);++ expect(err).toBeInstanceOf(ApiClientError);+ expect((err as ApiClientError).status).toBe(502);+ expect((err as ApiClientError).detail).toBe("HTTP 502");+ expect((err as ApiClientError).message).toBe("API error 502: HTTP 502");+ });++ it("resolves an empty 204 body to undefined", async () => {+ const { minimal } = fakeMinimal(respond(204, ""));+ configureApiClient({ baseUrl: "http://h", fetch: createAdapterFetch(minimal) });++ await expect(apiPost("/api/x")).resolves.toBeUndefined();+ });++ it("rejects an ok response whose body is not JSON", async () => {+ const { minimal } = fakeMinimal(respond(200, "not json"));+ configureApiClient({ baseUrl: "http://h", fetch: createAdapterFetch(minimal) });++ await expect(apiGet("/api/x")).rejects.toBeInstanceOf(SyntaxError);+ });++ it("accepts URL input, record headers and exposes text()", async () => {+ const { calls, minimal } = fakeMinimal(respond(200, "graph TD"));+ const adapted = createAdapterFetch(minimal);+ const controller = new AbortController();++ const res = await adapted(new URL("http://h/api/c4"), {+ headers: { "X-Test": "1" },+ signal: controller.signal,+ });++ expect(await res.text()).toBe("graph TD");+ expect(res.statusText).toBe("HTTP 200");+ expect(calls[0]?.url).toBe("http://h/api/c4");+ expect(calls[0]?.init).toEqual({ headers: { "X-Test": "1" }, signal: controller.signal });+ });++ it("refuses a non-string body rather than sending it mangled", async () => {+ const { minimal } = fakeMinimal(respond(200, "{}"));+ const adapted = createAdapterFetch(minimal);++ await expect(adapted("http://h", { method: "POST", body: new Uint8Array([1]) })).rejects.toBeInstanceOf(+ TypeError,+ );+ });+});diff --git a/packages/api-client/src/cache.test.ts b/packages/api-client/src/cache.test.tsnew file mode 100644index 000000000..9b318d76f--- /dev/null+++ b/packages/api-client/src/cache.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";++import { createCache } from "./cache";++describe("createCache", () => {+ it("returns what was set under the same repo, key and tag", () => {+ const cache = createCache();+ cache.set("repo-1", "health", "abc123", { score: 7.2 });+ expect(cache.get("repo-1", "health", "abc123")).toEqual({ score: 7.2 });+ });++ it("misses when any part of the key differs", () => {+ const cache = createCache();+ cache.set("repo-1", "health", "abc123", 1);+ expect(cache.get("repo-2", "health", "abc123")).toBeUndefined();+ expect(cache.get("repo-1", "risk", "abc123")).toBeUndefined();+ // A new freshness tag (e.g. a new head commit) never reads the old entry.+ expect(cache.get("repo-1", "health", "def456")).toBeUndefined();+ });++ it("does not collide when parts would concatenate to the same string", () => {+ const cache = createCache();+ cache.set("a b", "c", "t", "first");+ cache.set("a", "b c", "t", "second");+ expect(cache.get("a b", "c", "t")).toBe("first");+ expect(cache.get("a", "b c", "t")).toBe("second");+ });++ it("overwrites an existing entry", () => {+ const cache = createCache();+ cache.set("r", "k", "t", "old");+ cache.set("r", "k", "t", "new");+ expect(cache.get("r", "k", "t")).toBe("new");+ });++ it("drops everything on invalidateAll", () => {+ const cache = createCache();+ cache.set("r", "k1", "t", 1);+ cache.set("r", "k2", "t", 2);+ cache.invalidateAll();+ expect(cache.get("r", "k1", "t")).toBeUndefined();+ expect(cache.get("r", "k2", "t")).toBeUndefined();+ });++ it("keeps separate instances independent", () => {+ const a = createCache();+ const b = createCache();+ a.set("r", "k", "t", 1);+ expect(b.get("r", "k", "t")).toBeUndefined();+ });+});diff --git a/packages/vscode/src/core/cache.ts b/packages/api-client/src/cache.tssimilarity index 96%rename from packages/vscode/src/core/cache.tsrename to packages/api-client/src/cache.tsindex 73e92ecc7..949aa2be2 100644Binary files a/packages/vscode/src/core/cache.ts and b/packages/api-client/src/cache.ts differdiff --git a/packages/api-client/src/client.ts b/packages/api-client/src/client.tsindex cb1b154a7..6ed8199e4 100644--- a/packages/api-client/src/client.ts+++ b/packages/api-client/src/client.ts@@ -40,18 +40,24 @@ function resolveToken(): string | null {return token ?? null;}-function buildHeaders(extra?: Record<string, string>): Headers {- const headers = new Headers({+// A plain object rather than `Headers`, so requests also work in runtimes+// that have no `Headers` global (see createAdapterFetch).+function requestHeaders(extra?: Record<string, string>): Record<string, string> {+ const headers: Record<string, string> = {"Content-Type": "application/json",...extra,- });+ };const token = resolveToken();if (token) {- headers.set("Authorization", `Bearer ${token}`);+ headers["Authorization"] = `Bearer ${token}`;}return headers;}+function buildHeaders(extra?: Record<string, string>): Headers {+ return new Headers(requestHeaders(extra));+}+export class ApiClientError extends Error {constructor(public readonly status: number,@@ -99,6 +105,71 @@ export function doFetch(url: string, init: RequestInit): Promise<Response> {return (config.fetch ?? fetch)(url, init);}+/** Request a bare HTTP primitive accepts: plain-object headers, string body. */+export interface MinimalRequestInit {+ method?: string;+ headers?: Record<string, string>;+ body?: string;+ signal?: AbortSignal;+}++/** Response a bare HTTP primitive returns: plain-object headers, text body. */+export interface MinimalResponse {+ status: number;+ ok: boolean;+ headers: Record<string, string>;+ text: string;+}++export type MinimalFetch = (url: string, init: MinimalRequestInit) => Promise<MinimalResponse>;++function headersToRecord(headers: HeadersInit | undefined): Record<string, string> {+ const out: Record<string, string> = {};+ if (!headers) return out;+ if (Array.isArray(headers)) {+ for (const [name, value] of headers) out[name] = value;+ } else if (typeof (headers as Headers).forEach === "function") {+ (headers as Headers).forEach((value, name) => {+ out[name] = value;+ });+ } else {+ Object.assign(out, headers);+ }+ return out;+}++/**+ * Wraps a minimal HTTP primitive as a `fetch` for `configureApiClient`. Pure:+ * it never constructs `Headers` or `Response`, so it runs where those globals+ * do not exist. The returned object carries what this client reads (`ok`,+ * `status`, `statusText`, `json()`, `text()`). The primitive reports no+ * status text, so `statusText` is `HTTP <status>`, which is what an error+ * with a non-JSON body shows as its detail.+ */+export function createAdapterFetch(minimal: MinimalFetch): typeof fetch {+ const adapted = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url =+ typeof input === "string" ? input : "href" in input ? input.href : input.url;+ const body = init?.body;+ if (body != null && typeof body !== "string") {+ throw new TypeError("createAdapterFetch only sends string bodies");+ }+ const request: MinimalRequestInit = { headers: headersToRecord(init?.headers) };+ if (init?.method) request.method = init.method;+ if (body != null) request.body = body;+ if (init?.signal) request.signal = init.signal;+ const res = await minimal(url, request);+ return {+ ok: res.ok,+ status: res.status,+ statusText: `HTTP ${res.status}`,+ json: async () => JSON.parse(res.text) as unknown,+ text: async () => res.text,+ } as unknown as Response;+ };+ return adapted as typeof fetch;+}+export async function apiGet<T>(path: string,params?: Record<string, string | number | boolean | undefined>,@@ -114,7 +185,7 @@ export async function apiGet<T>(}const res = await doFetch(url.toString(), {method: "GET",- headers: buildHeaders(),+ headers: requestHeaders(),...fetchOptions,});return handleResponse<T>(res);@@ -136,7 +207,7 @@ export async function apiPost<T>(}const res = await doFetch(url.toString(), {method: "POST",- headers: buildHeaders(),+ headers: requestHeaders(),...(body !== undefined ? { body: JSON.stringify(body) } : {}),...fetchOptions,});@@ -151,7 +222,7 @@ export async function apiPut<T>(const url = `${BASE_URL}${path}`;const res = await doFetch(url, {method: "PUT",- headers: buildHeaders(),+ headers: requestHeaders(),...(body !== undefined ? { body: JSON.stringify(body) } : {}),...fetchOptions,});@@ -166,7 +237,7 @@ export async function apiPatch<T>(const url = `${BASE_URL}${path}`;const res = await doFetch(url, {method: "PATCH",- headers: buildHeaders(),+ headers: requestHeaders(),...(body !== undefined ? { body: JSON.stringify(body) } : {}),...fetchOptions,});@@ -180,7 +251,7 @@ export async function apiDelete<T>(const url = `${BASE_URL}${path}`;const res = await doFetch(url, {method: "DELETE",- headers: buildHeaders(),+ headers: requestHeaders(),...fetchOptions,});return handleResponse<T>(res);diff --git a/packages/api-client/src/package-exports.test.ts b/packages/api-client/src/package-exports.test.tsindex 4ecc3bbbc..056056123 100644--- a/packages/api-client/src/package-exports.test.ts+++ b/packages/api-client/src/package-exports.test.ts@@ -19,6 +19,10 @@ describe("published export map", () => {expect(missing).toEqual([]);});+ it("publishes the shared cache module", () => {+ expect(exportMap["./cache"]).toBe("./src/cache.ts");+ });+it("is published under the scope the workflow authenticates against", () => {expect(manifest.name).toBe("@repowise-dev/api-client");expect(manifest.publishConfig?.registry).toBe("https://npm.pkg.github.com");diff --git a/packages/types/__tests__/repos.test.ts b/packages/types/__tests__/repos.test.tsnew file mode 100644index 000000000..3d52ddedd--- /dev/null+++ b/packages/types/__tests__/repos.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";++import { normalizeRepoPath } from "../src/repos.js";++describe("normalizeRepoPath on Windows", () => {+ it("turns drive paths into lowercase forward-slash form", () => {+ expect(normalizeRepoPath("C:\\Users\\Dev\\Repo", true)).toBe("c:/users/dev/repo");+ });++ it("treats both separators alike", () => {+ expect(normalizeRepoPath("C:\\Users/Dev\\Repo/src", true)).toBe("c:/users/dev/repo/src");+ expect(normalizeRepoPath("C:/Users/Dev/Repo", true)).toBe(+ normalizeRepoPath("c:\\users\\dev\\repo", true),+ );+ });++ it("drops trailing separators of either kind", () => {+ expect(normalizeRepoPath("C:\\Repo\\", true)).toBe("c:/repo");+ expect(normalizeRepoPath("C:\\Repo\\/\\", true)).toBe("c:/repo");+ expect(normalizeRepoPath("C:\\", true)).toBe("c:");+ });++ it("handles UNC paths", () => {+ expect(normalizeRepoPath("\\\\Server\\Share\\Repo", true)).toBe("//server/share/repo");+ });+});++describe("normalizeRepoPath on POSIX", () => {+ it("keeps case", () => {+ expect(normalizeRepoPath("/Users/Dev/Repo", false)).toBe("/Users/Dev/Repo");+ });++ it("drops trailing slashes only", () => {+ expect(normalizeRepoPath("/home/dev/repo//", false)).toBe("/home/dev/repo");+ expect(normalizeRepoPath("/", false)).toBe("");+ });++ it("keeps backslashes, which are filename characters there", () => {+ expect(normalizeRepoPath("/tmp/a\\b", false)).toBe("/tmp/a\\b");+ });+});diff --git a/packages/types/__tests__/serve-lock.test.ts b/packages/types/__tests__/serve-lock.test.tsnew file mode 100644index 000000000..f2a228541--- /dev/null+++ b/packages/types/__tests__/serve-lock.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";++import { isServeLock, type ServeLock } from "../src/serve-lock.js";++const VALID: ServeLock = {+ pid: 4242,+ host: "0.0.0.0",+ port: 7337,+ url: "http://127.0.0.1:7337",+ ui_port: 3000,+ server_version: "0.56.0",+ started_at: "2026-10-03T10:00:00Z",+};++describe("isServeLock", () => {+ it("accepts a complete lockfile", () => {+ expect(isServeLock(VALID)).toBe(true);+ });++ it("accepts a null ui_port (server started without the web UI)", () => {+ expect(isServeLock({ ...VALID, ui_port: null })).toBe(true);+ });++ it("rejects a lockfile missing any field", () => {+ for (const key of Object.keys(VALID)) {+ const partial: Record<string, unknown> = { ...VALID };+ delete partial[key];+ expect(isServeLock(partial), key).toBe(false);+ }+ });++ it("rejects fields of the wrong type", () => {+ expect(isServeLock({ ...VALID, pid: "4242" })).toBe(false);+ expect(isServeLock({ ...VALID, host: 1 })).toBe(false);+ expect(isServeLock({ ...VALID, port: "7337" })).toBe(false);+ expect(isServeLock({ ...VALID, url: null })).toBe(false);+ expect(isServeLock({ ...VALID, ui_port: "3000" })).toBe(false);+ expect(isServeLock({ ...VALID, ui_port: undefined })).toBe(false);+ expect(isServeLock({ ...VALID, server_version: 56 })).toBe(false);+ expect(isServeLock({ ...VALID, started_at: 0 })).toBe(false);+ });++ it("rejects non-object garbage", () => {+ for (const value of [null, undefined, 0, "lock", true, [], [VALID]]) {+ expect(isServeLock(value)).toBe(false);+ }+ });+});diff --git a/packages/types/package.json b/packages/types/package.jsonindex a856ea157..0acfe1623 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -37,6 +37,7 @@"./refactoring": "./src/refactoring.ts","./fix-first": "./src/fix-first.ts","./agent-prompts": "./src/agent-prompts.ts",+ "./serve-lock": "./src/serve-lock.ts","./generated/http": "./src/generated/http.ts"},"publishConfig": {diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex e084bbf73..2ac2a1401 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -36,3 +36,4 @@ export * from "./stats.js";export * from "./refactoring.js";export * from "./fix-first.js";export * from "./agent-prompts.js";+export * from "./serve-lock.js";diff --git a/packages/types/src/repos.ts b/packages/types/src/repos.tsindex e90b9c0ff..c2b5a8dd7 100644--- a/packages/types/src/repos.ts+++ b/packages/types/src/repos.ts@@ -53,3 +53,16 @@ export interface RepoSummaryRow {export interface ReposSummaryResponse {repos: RepoSummaryRow[];}++/**+ * Normalizes a repo path (e.g. a server-reported `local_path`) for equality+ * comparison: forward slashes, no trailing slash, and lowercase on Windows,+ * where paths are case-insensitive. On Windows both `\` and `/` count as+ * separators; elsewhere `\` is an ordinary filename character and is kept.+ * Pure: resolving relative paths and symlinks is the caller's job.+ */+export function normalizeRepoPath(p: string, isWindows: boolean): string {+ const slashed = isWindows ? p.replace(/\\/g, "/") : p;+ const trimmed = slashed.replace(/\/+$/, "");+ return isWindows ? trimmed.toLowerCase() : trimmed;+}diff --git a/packages/types/src/serve-lock.ts b/packages/types/src/serve-lock.tsnew file mode 100644index 000000000..95a218912--- /dev/null+++ b/packages/types/src/serve-lock.ts@@ -0,0 +1,29 @@+/**+ * Shape of `serve.lock.json`, written by the running server after it binds a+ * port. `url` is always a loopback address even when the server binds a+ * wildcard host, so it is safe to probe directly.+ */+export interface ServeLock {+ pid: number;+ host: string;+ port: number;+ url: string;+ ui_port: number | null;+ server_version: string;+ started_at: string;+}++/** Validates parsed lockfile JSON. Pure, so it runs without file or process access. */+export function isServeLock(value: unknown): value is ServeLock {+ if (typeof value !== "object" || value === null) return false;+ const v = value as Record<string, unknown>;+ return (+ typeof v.pid === "number" &&+ typeof v.host === "string" &&+ typeof v.port === "number" &&+ typeof v.url === "string" &&+ (typeof v.ui_port === "number" || v.ui_port === null) &&+ typeof v.server_version === "string" &&+ typeof v.started_at === "string"+ );+}diff --git a/packages/ui/__tests__/brand.test.ts b/packages/ui/__tests__/brand.test.tsindex f5ea1b7b5..0b7040e62 100644--- a/packages/ui/__tests__/brand.test.ts+++ b/packages/ui/__tests__/brand.test.ts@@ -1,7 +1,16 @@import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";import { join } from "node:path";-import { BRAND, LIGHT, DARK, GRADIENTS } from "../src/brand.js";+import { HEALTH_BAND_ORDER, bandForScore } from "@repowise-dev/types/health";+import {+ BRAND,+ LIGHT,+ DARK,+ DARK_CANVAS,+ DARK_CANVAS_BAND,+ GRADIENTS,+} from "../src/brand.js";+import { healthBandNodeFill } from "../src/health/tokens.js";// styles/globals.css is the single source of truth for the token system;// the brand constants exist for surfaces that can't resolve CSS vars. This@@ -57,6 +66,67 @@ describe("brand constants stay in sync with styles/globals.css", () => {});});+// The canvas ramp shares names with the light block, so its values are read+// from the first `.dark {` block rather than matched anywhere in the file.+function darkToken(name: string): string | undefined {+ const start = css.indexOf("\n.dark {");+ const block = css.slice(start, css.indexOf("\n}", start));+ const re = new RegExp(`--color-${escapeRegExp(name)}:\\s*(#[0-9a-f]{6})\\s*;`, "i");+ return re.exec(block)?.[1]?.toLowerCase();+}++describe("dark canvas constants match the .dark block", () => {+ it("node ramp and caution equal their dark tokens", () => {+ expect(DARK_CANVAS).toEqual({+ nodeAtRisk: darkToken("node-at-risk"),+ nodeNeedsWork: darkToken("node-needs-work"),+ nodeFair: darkToken("node-fair"),+ nodeGood: darkToken("node-good"),+ nodeExcellent: darkToken("node-excellent"),+ nodeNeutral: darkToken("node-neutral"),+ caution: darkToken("caution"),+ });+ });++ it("pins the literal values", () => {+ expect(DARK_CANVAS).toEqual({+ nodeAtRisk: "#b0544b",+ nodeNeedsWork: "#bd7c42",+ nodeFair: "#a89453",+ nodeGood: "#42906f",+ nodeExcellent: "#5cb389",+ nodeNeutral: "#333336",+ caution: "#d9b04a",+ });+ });++ it("band map covers exactly the health bands", () => {+ expect(Object.keys(DARK_CANVAS_BAND).sort()).toEqual([...HEALTH_BAND_ORDER].sort());+ });++ it("band map uses the node token the in-app health surface paints each band with", () => {+ for (const band of HEALTH_BAND_ORDER) {+ // healthBandNodeFill returns `var(--color-node-<x>)`; map <x> to its+ // DARK_CANVAS key (needs-work -> nodeNeedsWork).+ const match = /^var\(--color-node-([a-z-]+)\)$/.exec(healthBandNodeFill(band));+ expect(match, band).not.toBeNull();+ const key = `node-${match![1]}`.replace(/-([a-z])/g, (_, c: string) =>+ c.toUpperCase(),+ ) as keyof typeof DARK_CANVAS;+ expect(DARK_CANVAS[key], band).toBeDefined();+ expect(DARK_CANVAS_BAND[band], band).toBe(DARK_CANVAS[key]);+ }+ });++ it("band map resolves scores to the matching node token", () => {+ expect(DARK_CANVAS_BAND[bandForScore(9)]).toBe(darkToken("node-excellent"));+ expect(DARK_CANVAS_BAND[bandForScore(7.5)]).toBe(darkToken("node-good"));+ expect(DARK_CANVAS_BAND[bandForScore(6)]).toBe(darkToken("node-fair"));+ expect(DARK_CANVAS_BAND[bandForScore(4.5)]).toBe(darkToken("node-needs-work"));+ expect(DARK_CANVAS_BAND[bandForScore(2)]).toBe(darkToken("node-at-risk"));+ });+});+describe("brand module purity", () => {it("has no imports (dependency-free by contract)", () => {const src = readFileSync(join(__dirname, "../src/brand.ts"), "utf8");diff --git a/packages/ui/src/brand.ts b/packages/ui/src/brand.tsindex f1e3b8a56..2fcaf290e 100644--- a/packages/ui/src/brand.ts+++ b/packages/ui/src/brand.ts@@ -58,6 +58,35 @@ export const DARK = {error: "#e06a5a",} as const;+/**+ * Dark-theme canvas colors: the health node ramp (`--color-node-*`) and the+ * caution tone (`--color-caution`) from the `.dark` block. The ramp is deeper+ * and less saturated than the semantic colors so a field of nodes reads as+ * pigment rather than light. Dark only; there is no light counterpart here.+ */+export const DARK_CANVAS = {+ nodeAtRisk: "#b0544b",+ nodeNeedsWork: "#bd7c42",+ nodeFair: "#a89453",+ nodeGood: "#42906f",+ nodeExcellent: "#5cb389",+ nodeNeutral: "#333336",+ caution: "#d9b04a",+} as const;++/**+ * Dark canvas node color per health band. Keys are the `HealthBand` values+ * from `@repowise-dev/types` (`bandForScore`), spelled out because this+ * module stays import-free.+ */+export const DARK_CANVAS_BAND = {+ excellent: DARK_CANVAS.nodeExcellent,+ good: DARK_CANVAS.nodeGood,+ fair: DARK_CANVAS.nodeFair,+ needs_work: DARK_CANVAS.nodeNeedsWork,+ at_risk: DARK_CANVAS.nodeAtRisk,+} as const;+/** Signature gradients (CSS gradient strings) for hero/OG canvases. */export const GRADIENTS = {sunset: "linear-gradient(135deg, #58436c 0%, #f59520 55%, #f7a94d 100%)",diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex fe173dd14..1cb67b8c0 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -63,6 +63,7 @@ export default defineConfig({"../types/src/risk-semantics.ts",),"@repowise-dev/types/repos": path.resolve(__dirname, "../types/src/repos.ts"),+ "@repowise-dev/types/serve-lock": path.resolve(__dirname, "../types/src/serve-lock.ts"),"@repowise-dev/types/generated/http": path.resolve(__dirname,"../types/src/generated/http.ts",diff --git a/packages/vscode/src/core/api.ts b/packages/vscode/src/core/api.tsindex 3c54add3a..9a91f6d9f 100644--- a/packages/vscode/src/core/api.ts+++ b/packages/vscode/src/core/api.ts@@ -3,6 +3,7 @@ import { realpathSync } from "node:fs";import { configureApiClient } from "@repowise-dev/api-client";import { listRepos } from "@repowise-dev/api-client/repos";import type { RepoResponse } from "@repowise-dev/api-client/types";+import { normalizeRepoPath } from "@repowise-dev/types/repos";import type { Logger } from "./log";/** Result of a successful `/health` probe. */@@ -55,9 +56,7 @@ function canonicalPath(p: string): string {} catch {// Path may not exist on disk (server-reported path); fall back to resolve.}- // Windows paths are case-insensitive; normalize separators and case.- const normalized = resolved.split(path.sep).join("/").replace(/\/+$/, "");- return process.platform === "win32" ? normalized.toLowerCase() : normalized;+ return normalizeRepoPath(resolved, process.platform === "win32");}export function createApi(log: Logger): RepowiseApi {diff --git a/packages/vscode/src/core/context.ts b/packages/vscode/src/core/context.tsindex bb01aa62a..a3aca5ac9 100644--- a/packages/vscode/src/core/context.ts+++ b/packages/vscode/src/core/context.ts@@ -2,7 +2,7 @@ import * as vscode from "vscode";import { CONFIG_SECTION, REPO_DIR, STATE_CONTEXT_KEY, WORKSPACE_DIR } from "../constants";import type { Logger } from "./log";import type { RepowiseApi } from "./api";-import type { RepowiseCache } from "./cache";+import type { RepowiseCache } from "@repowise-dev/api-client/cache";import type { CliRunner } from "./cliRunner";import {createFreshnessWatcher,diff --git a/packages/vscode/src/core/lockfile.ts b/packages/vscode/src/core/lockfile.tsindex b1f528e68..488e68c9c 100644--- a/packages/vscode/src/core/lockfile.ts+++ b/packages/vscode/src/core/lockfile.ts@@ -1,33 +1,5 @@import { readFile } from "node:fs/promises";--/**- * Shape of `serve.lock.json`, written by the running server after it binds a- * port. `url` is always a loopback address even when the server binds a- * wildcard host, so it is safe to probe directly.- */-export interface ServeLock {- pid: number;- host: string;- port: number;- url: string;- ui_port: number | null;- server_version: string;- started_at: string;-}--function isServeLock(value: unknown): value is ServeLock {- if (typeof value !== "object" || value === null) return false;- const v = value as Record<string, unknown>;- return (- typeof v.pid === "number" &&- typeof v.host === "string" &&- typeof v.port === "number" &&- typeof v.url === "string" &&- (typeof v.ui_port === "number" || v.ui_port === null) &&- typeof v.server_version === "string" &&- typeof v.started_at === "string"- );-}+import { isServeLock, type ServeLock } from "@repowise-dev/types/serve-lock";/*** Reads and validates the lockfile. Returns null when the file is missing,diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.tsindex 33be5d774..008416e99 100644--- a/packages/vscode/src/extension.ts+++ b/packages/vscode/src/extension.ts@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";import { Commands, REPO_DIR, WORKSPACE_DIR } from "./constants";import { createLogger } from "./core/log";import { createApi } from "./core/api";-import { createCache } from "./core/cache";+import { createCache } from "@repowise-dev/api-client/cache";import { createCliRunner } from "./core/cliRunner";import { RepowiseContext } from "./core/context";import { registerStatusBar } from "./features/statusBar";