Merge pull request #1892 from pikasTech/feat/issue-1887-monitor-workbench-r2-6-2
Pipelines as Code CI / hwlab-web-probe-sentinel-nc01- Success
Pipelines as Code CI / platform-infra-gitea-nc01- Success
Pipelines as Code CI / unidesk-host- Success

feat: 实现未暴露的 Monitor workbench 基础
This commit is contained in:
Lyon
2026-07-13 12:05:37 +08:00
committed by GitHub
8 changed files with 399 additions and 0 deletions
@@ -106,6 +106,71 @@ test("run detail returns normalized locator metadata without artifact bytes", as
assert.equal(response.valuesRedacted, true);
});
test("monitor workspace composes runs while runtime facts remain unavailable without metadata", async () => {
const target = service();
await target.ingest({ ...input("run-ok", "2026-07-12T11:00:00.000Z"), findings: [{ id: "finding-a" }] });
await target.ingest({ ...input("run-failed", "2026-07-12T10:00:00.000Z"), status: "failed", findings: [{ id: "finding-b" }, { id: "finding-c" }] });
const response = await target.fetch(new Request("http://local/api/monitor/workspace?sentinelId=sentinel-a&node=NC01&lane=v03&status=failed&from=2026-07-12T09:00:00.000Z&limit=20"));
const body = await response.json() as any;
assert.equal(body.selection.defaultRunId, "run-failed");
assert.equal(body.runs.items[0].findingCount, 2);
assert.equal(body.health.state, "degraded");
assert.equal(body.freshness.state, "unavailable");
assert.equal(body.cadence.state, "unavailable");
assert.equal(body.schemaVersion, undefined);
assert.equal(body.capability, undefined);
});
test("monitor workspace filters before paging and counts findings beyond page size", async () => {
const target = createMonitorCentralService({ store: createInMemoryMonitorCentralStore(), pageSize: 2 });
await target.ingest({ ...input("new-1", "2026-07-12T13:00:00.000Z"), status: "succeeded", findings: [] });
await target.ingest({ ...input("new-2", "2026-07-12T12:00:00.000Z"), status: "succeeded", findings: [] });
await target.ingest({ ...input("older-match", "2026-07-12T11:00:00.000Z"), status: "failed", findings: [{ id: "f1" }, { id: "f2" }, { id: "f3" }] });
const body = await (await target.fetch(new Request("http://local/api/monitor/workspace?sentinelId=sentinel-a&node=NC01&lane=v03&status=failed"))).json() as any;
assert.equal(body.runs.items[0].runId, "older-match");
assert.equal(body.runs.items[0].findingCount, 3);
assert.equal(body.summary.totalRuns, 1);
assert.equal(body.summary.findingCount, 3);
assert.deepEqual(body.summary.statusCounts, { failed: 1 });
assert.equal(body.runs.nextCursor, null);
});
test("monitor latest failure excludes running and unknown states", async () => {
const target = service();
await target.ingest({ ...input("failed-terminal", "2026-07-12T10:00:00.000Z"), status: "failed" });
await target.ingest({ ...input("running-newer", "2026-07-12T12:00:00.000Z"), status: "running" });
await target.ingest({ ...input("unknown-newest", "2026-07-12T13:00:00.000Z"), status: "unknown" });
const body = await (await target.fetch(new Request("http://local/api/monitor/workspace?sentinelId=sentinel-a&node=NC01&lane=v03"))).json() as any;
assert.equal(body.summary.latestFailureAt, "2026-07-12T10:00:00.000Z");
});
test("monitor workspace projects cadence freshness and health only from runtime metadata", async () => {
const store = createInMemoryMonitorCentralStore();
const normalized = normalizeMonitorCentralIngest(input("run-metadata"));
await store.importSource({ manifestId: "monitor-workbench-runtime", sourceFingerprint: "sha256:runtime", rowCount: 1 }, [normalized], [
{ sentinelId: "sentinel-a", node: "NC01", lane: "v03", key: "monitor.health", value: { state: "healthy" }, updatedAt: "2026-07-12T10:01:00.000Z" },
{ sentinelId: "sentinel-a", node: "NC01", lane: "v03", key: "monitor.freshness", value: { state: "current", ageSeconds: 30 }, updatedAt: "2026-07-12T10:01:00.000Z" },
{ sentinelId: "sentinel-a", node: "NC01", lane: "v03", key: "monitor.cadence", value: { state: "available", label: "owning-yaml-projected" }, updatedAt: "2026-07-12T10:01:00.000Z" },
]);
const target = createMonitorCentralService({ store, pageSize: 50 });
const body = await (await target.fetch(new Request("http://local/api/monitor/workspace?sentinelId=sentinel-a&node=NC01&lane=v03"))).json() as any;
assert.equal(body.health.state, "healthy");
assert.equal(body.freshness.ageSeconds, 30);
assert.equal(body.cadence.label, "owning-yaml-projected");
assert.equal(body.cadence.sourceKey, "monitor.cadence");
});
test("monitor run detail projects stable ids without a client join", async () => {
const target = service();
await target.ingest({ ...input("run-workbench"), payload: { diagnostics: { state: "ready" } }, timeline: [{ id: "event-done", phase: "done" }], findings: [{ id: "finding-visible" }] });
const response = await target.fetch(new Request("http://local/api/monitor/runs/run-workbench?sentinelId=sentinel-a&node=NC01&lane=v03"));
const body = await response.json() as any;
assert.equal(body.timeline[0].id, "event-done");
assert.equal(body.findings[0].id, "finding-visible");
assert.equal(body.artifacts[0].id, "artifact-0");
assert.deepEqual(body.diagnostics, { state: "ready" });
});
test("configuration is explicit and missing environment projection fails structurally", async () => {
const target = service();
assert.equal((await target.health()).ok, true);
+109
View File
@@ -56,6 +56,7 @@ export interface MonitorCentralStore {
runtimeMetadata(scope: Required<MonitorScope>): Promise<readonly MonitorRuntimeMetadata[]>;
updateArtifactAvailability(scope: Required<MonitorScope>, runId: string, locatorIndex: number, reachable: boolean): Promise<void>;
overview(scope: MonitorScope): Promise<Record<string, unknown>>;
monitorWorkspace(scope: MonitorScope, options: MonitorWorkspaceQueryOptions): Promise<MonitorWorkspaceQueryResult>;
runs(scope: MonitorScope, options: RunQueryOptions): Promise<readonly MonitorRun[]>;
run(scope: Required<MonitorScope>, runId: string): Promise<Record<string, unknown> | null>;
view(scope: Required<MonitorScope>, runId: string, view: string): Promise<Record<string, unknown> | null>;
@@ -97,6 +98,15 @@ export interface FindingQueryOptions {
readonly cursor: FindingCursor | null;
}
interface MonitorWorkspaceQueryOptions extends RunQueryOptions {
readonly status?: string;
readonly from?: string;
readonly to?: string;
}
interface MonitorWorkspaceRun extends MonitorRun { readonly findingCount: number; }
interface MonitorWorkspaceQueryResult { readonly items: readonly MonitorWorkspaceRun[]; readonly nextCursor: string | null; readonly totalRuns: number; readonly findingCount: number; readonly statusCounts: Readonly<Record<string, number>>; readonly latestSuccessAt: string | null; readonly latestFailureAt: string | null; }
export interface MonitorCentralService {
ingest(input: MonitorCentralIngest): Promise<Record<string, unknown>>;
health(): Promise<Record<string, unknown>>;
@@ -163,6 +173,9 @@ export function createMonitorCentralService(options: MonitorCentralServiceOption
return json(result, result.ok === true ? 200 : 503);
}
if (request.method === "GET" && url.pathname === "/api/overview") return json({ ok: true, overview: await store.overview(scopeFrom(url)), valuesRedacted: true });
if (request.method === "GET" && url.pathname === "/api/monitor/workspace") return json(await monitorWorkspace(store, url, pageSize));
const monitorRunMatch = request.method === "GET" ? url.pathname.match(/^\/api\/monitor\/runs\/([^/]+)$/u) : null;
if (monitorRunMatch) return monitorRunDetail(store, url, decodeURIComponent(monitorRunMatch[1]));
if (request.method === "GET" && url.pathname === "/api/runs") return json(runPage(await store.runs(scopeFrom(url), runQueryOptions(url, pageSize))));
if (request.method === "GET" && url.pathname === "/api/findings") return json(findingPage(await store.findings(scopeFrom(url), findingQueryOptions(url, pageSize))));
if (request.method === "GET" && url.pathname.startsWith("/api/runs/")) {
@@ -184,6 +197,60 @@ export function createMonitorCentralService(options: MonitorCentralServiceOption
return { ingest, health, fetch };
}
async function monitorWorkspace(store: MonitorCentralStore, url: URL, pageSize: number): Promise<Record<string, unknown>> {
const scope = scopeFrom(url);
const status = optional(url, "status");
const from = optionalDate(url, "from");
const to = optionalDate(url, "to");
const result = await store.monitorWorkspace(scope, { ...runQueryOptions(url, pageSize), status, from, to });
const runtime = await monitorRuntimeProjection(store, scope);
return {
ok: true,
query: { sentinelId: scope.sentinelId ?? null, node: scope.node ?? null, lane: scope.lane ?? null, status: status ?? null, from: from ?? null, to: to ?? null },
health: runtime.health,
freshness: runtime.freshness,
cadence: runtime.cadence,
summary: { totalRuns: result.totalRuns, statusCounts: result.statusCounts, findingCount: result.findingCount, latestSuccessAt: result.latestSuccessAt, latestFailureAt: result.latestFailureAt },
runs: { items: result.items, nextCursor: result.nextCursor },
selection: { defaultRunId: result.items[0]?.runId ?? null },
valuesRedacted: true,
};
}
async function monitorRuntimeProjection(store: MonitorCentralStore, scope: MonitorScope): Promise<Record<string, Record<string, unknown>>> {
if (!scope.sentinelId || !scope.node || !scope.lane) return unavailableRuntime("full_scope_required");
const metadata = await store.runtimeMetadata(scope as Required<MonitorScope>);
const values = new Map(metadata.map((item) => [item.key, item]));
const health = projectedRuntimeValue(values, ["monitor.health", "scheduler.health"]);
const freshness = projectedRuntimeValue(values, ["monitor.freshness", "scheduler.freshness"]);
const cadence = projectedRuntimeValue(values, ["monitor.cadence", "scheduler.cadence"]);
return {
health: health ?? { state: "degraded", reason: "runtime_metadata_unavailable" },
freshness: freshness ?? { state: "unavailable", reason: "runtime_metadata_unavailable" },
cadence: cadence ?? { state: "unavailable", reason: "runtime_metadata_unavailable" },
};
}
function projectedRuntimeValue(values: ReadonlyMap<string, MonitorRuntimeMetadata>, keys: readonly string[]): Record<string, unknown> | null {
for (const key of keys) {
const item = values.get(key);
if (item) return { ...recordOrEmpty(item.value), sourceKey: item.key, updatedAt: item.updatedAt };
}
return null;
}
function unavailableRuntime(reason: string): Record<string, Record<string, unknown>> {
return { health: { state: "degraded", reason }, freshness: { state: "unavailable", reason }, cadence: { state: "unavailable", reason } };
}
async function monitorRunDetail(store: MonitorCentralStore, url: URL, runId: string): Promise<Response> {
const scope = requireFullScope(scopeFrom(url));
const run = await store.run(scope, runId);
if (!run) return json({ ok: false, error: { code: "run_not_found" }, valuesRedacted: true }, 404);
const payload = recordOrEmpty(run.payload);
return json({ ok: true, run: { sentinelId: run.sentinelId, node: run.node, lane: run.lane, runId: run.runId, updatedAt: run.updatedAt, status: run.status, payloadHash: run.payloadHash }, timeline: arrayOrEmpty(run.timeline).map((event, index) => ({ id: objectId(event, `event-${index}`), event })), findings: arrayOrEmpty(run.findings).map((finding, index) => ({ id: objectId(finding, `finding-${index}`), finding })), diagnostics: recordOrEmpty(payload.diagnostics), artifacts: arrayOrEmpty(run.artifactLocators).map((artifact, index) => ({ id: `artifact-${index}`, ...recordOrEmpty(artifact) })), valuesRedacted: true });
}
export function createPostgresMonitorCentralStore(databaseUrl: string, options: PostgresMonitorCentralStoreOptions): MonitorCentralStore {
const sql = postgres(databaseUrl, { max: requirePositiveInteger(options.poolMax, "monitor_central_pg_pool_max_missing"), idle_timeout: requirePositiveInteger(options.idleTimeoutSeconds, "monitor_central_pg_idle_timeout_missing") });
return {
@@ -250,6 +317,7 @@ export function createPostgresMonitorCentralStore(databaseUrl: string, options:
const rows = await queryRuns(sql, scope, { limit: 1, cursor: null });
return { scope: publicScope(scope), runCount: await countRuns(sql, scope), latest: rows[0] ?? null };
},
async monitorWorkspace(scope, options) { return queryMonitorWorkspace(sql, scope, options); },
async runs(scope, options) { return queryRuns(sql, scope, options); },
async run(scope, runId) {
const where = identityWhere(scope, runId);
@@ -384,6 +452,16 @@ export function createInMemoryMonitorCentralStore(): MonitorCentralStore {
const runs = await this.runs(scope, { limit: 1, cursor: null });
return { scope: publicScope(scope), runCount: [...records.values()].filter((item) => matches(scope, item)).length, latest: runs[0] ?? null };
},
async monitorWorkspace(scope, options) {
const filteredRecords = [...records.values()].filter((item) => matches(scope, item) && monitorWorkspaceMatches(runFrom(item), options));
const all = sortRuns(filteredRecords.map(runFrom));
const findingCounts = new Map(filteredRecords.map((item) => [identityKey(item), item.findings.length]));
const candidates = all.filter((run) => afterRunCursor(run, options.cursor)).slice(0, options.limit + 1);
const hasMore = candidates.length > options.limit;
const items = candidates.slice(0, options.limit).map((run) => ({ ...run, findingCount: findingCounts.get(identityKey(run)) ?? 0 }));
const last = items.at(-1);
return { items, nextCursor: hasMore && last ? cursor(last) : null, totalRuns: all.length, findingCount: filteredRecords.reduce((total, item) => total + item.findings.length, 0), statusCounts: countBy(all, (run) => run.status), latestSuccessAt: all.find((run) => run.status === "succeeded")?.updatedAt ?? null, latestFailureAt: all.find((run) => monitorRunFailed(run.status))?.updatedAt ?? null };
},
async runs(scope, options) { return sortRuns([...records.values()].filter((item) => matches(scope, item)).map(runFrom)).filter((run) => afterRunCursor(run, options.cursor)).slice(0, options.limit); },
async run(scope, runId) {
const value = records.get(identityKey({ ...scope, runId }));
@@ -423,6 +501,7 @@ async function requestRecord(request: Request): Promise<Record<string, unknown>>
function scopeFrom(url: URL): MonitorScope { return { sentinelId: optional(url, "sentinelId"), node: optional(url, "node"), lane: optional(url, "lane") }; }
function requireFullScope(scope: MonitorScope): Required<MonitorScope> { if (!scope.sentinelId || !scope.node || !scope.lane) throw Object.assign(invalid("run detail requires sentinelId, node, and lane"), { code: "scope_required" }); return scope as Required<MonitorScope>; }
function optional(url: URL, name: string): string | undefined { return url.searchParams.get(name) || undefined; }
function optionalDate(url: URL, name: string): string | undefined { const value = optional(url, name); if (!value) return undefined; const timestamp = Date.parse(value); if (!Number.isFinite(timestamp)) throw invalid(`${name} must be an ISO timestamp`); return new Date(timestamp).toISOString(); }
function boundedLimit(value: string | null, pageSize: number): number { const parsed = Number(value ?? pageSize); return Number.isInteger(parsed) && parsed > 0 ? Math.min(parsed, pageSize) : pageSize; }
function runQueryOptions(url: URL, pageSize: number): RunQueryOptions { return { limit: boundedLimit(url.searchParams.get("limit"), pageSize), cursor: parseRunCursor(url.searchParams.get("cursor")) }; }
function findingQueryOptions(url: URL, pageSize: number): FindingQueryOptions { return { limit: boundedLimit(url.searchParams.get("limit"), pageSize), cursor: parseFindingCursor(url.searchParams.get("cursor")) }; }
@@ -432,6 +511,11 @@ function parseCursor(value: string | null, finding: boolean): RunCursor | Findin
function runPage(items: readonly MonitorRun[]): Record<string, unknown> { const last = items.at(-1); return { ok: true, items, nextCursor: last ? cursor(last) : null, valuesRedacted: true }; }
function findingPage(items: readonly Record<string, unknown>[]): Record<string, unknown> { const last = items.at(-1); return { ok: true, items, nextCursor: last ? cursor({ updatedAt: last.updatedAt, runId: last.runId, findingIndex: last.findingIndex }) : null, valuesRedacted: true }; }
function cursor(value: unknown): string { return Buffer.from(JSON.stringify(value)).toString("base64url"); }
function countBy<T>(items: readonly T[], key: (item: T) => string): Record<string, number> { const counts: Record<string, number> = {}; for (const item of items) counts[key(item)] = (counts[key(item)] ?? 0) + 1; return counts; }
function recordOrEmpty(value: unknown): Record<string, unknown> { return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; }
function arrayOrEmpty(value: unknown): readonly unknown[] { return Array.isArray(value) ? value : []; }
function objectId(value: unknown, fallback: string): string { const record = recordOrEmpty(value); return String(record.id ?? record.errorId ?? fallback); }
function dateOrNull(value: unknown): string | null { return value ? new Date(String(value)).toISOString() : null; }
function json(body: Record<string, unknown>, status = 200): Response { return Response.json(body, { status }); }
function httpStatus(error: unknown): number { return (error as { code?: string })?.code === "payload_hash_conflict" ? 409 : error instanceof MonitorCentralConfigurationError ? 503 : 400; }
export function structuredMonitorCentralError(error: unknown): Record<string, unknown> { return error instanceof MonitorCentralConfigurationError ? error.toJSON().error as Record<string, unknown> : { code: (error as { code?: string })?.code ?? "invalid_request", message: errorMessage(error) }; }
@@ -446,12 +530,37 @@ function matches(scope: MonitorScope, value: MonitorScope): boolean { return (!s
function runFrom(value: NormalizedMonitorCentralIngest): MonitorRun { return { sentinelId: value.sentinelId, node: value.node, lane: value.lane, runId: value.runId, updatedAt: value.updatedAt, status: value.status, payloadHash: value.payloadHash }; }
function sortRuns(runs: readonly MonitorRun[]): MonitorRun[] { return [...runs].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt) || right.runId.localeCompare(left.runId)); }
function afterRunCursor(run: MonitorRun, cursorValue: RunCursor | null): boolean { return !cursorValue || run.updatedAt < cursorValue.updatedAt || (run.updatedAt === cursorValue.updatedAt && run.runId < cursorValue.runId); }
function monitorWorkspaceMatches(run: MonitorRun, options: MonitorWorkspaceQueryOptions): boolean { return (!options.status || run.status === options.status) && (!options.from || run.updatedAt >= options.from) && (!options.to || run.updatedAt <= options.to); }
function monitorRunFailed(status: string): boolean { return status === "failed"; }
function compareFindings(left: Record<string, unknown>, right: Record<string, unknown>): number { return String(right.updatedAt).localeCompare(String(left.updatedAt)) || String(right.runId).localeCompare(String(left.runId)) || Number(right.findingIndex) - Number(left.findingIndex); }
function afterFindingCursor(finding: Record<string, unknown>, cursorValue: FindingCursor | null): boolean { if (!cursorValue) return true; return String(finding.updatedAt) < cursorValue.updatedAt || (finding.updatedAt === cursorValue.updatedAt && (String(finding.runId) < cursorValue.runId || (finding.runId === cursorValue.runId && Number(finding.findingIndex) < cursorValue.findingIndex))); }
export function monitorCentralStableJson(value: unknown): string { if (value === undefined) return "null"; if (Array.isArray(value)) return `[${value.map(monitorCentralStableJson).join(",")}]`; if (value && typeof value === "object") return `{${Object.entries(value as Record<string, unknown>).filter(([, item]) => item !== undefined).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${monitorCentralStableJson(item)}`).join(",")}}`; const json = JSON.stringify(value); return json === undefined ? "null" : json; }
function scopeWhere(scope: MonitorScope): { readonly text: string; readonly values: readonly string[] } { const entries = Object.entries({ sentinel_id: scope.sentinelId, node: scope.node, lane: scope.lane }).filter(([, value]) => value); return { text: entries.length ? entries.map(([key], index) => `r.${key} = $${index + 1}`).join(" and ") : "true", values: entries.map(([, value]) => String(value)) }; }
function identityWhere(scope: Required<MonitorScope>, runId: string): { readonly text: string; readonly values: readonly string[] } { return { text: "r.sentinel_id = $1 and r.node = $2 and r.lane = $3 and r.run_id = $4", values: [scope.sentinelId, scope.node, scope.lane, runId] }; }
async function queryRuns(sql: postgres.Sql, scope: MonitorScope, options: RunQueryOptions): Promise<MonitorRun[]> { const where = scopeWhere(scope); const values: unknown[] = [...where.values]; let cursorClause = ""; if (options.cursor) { values.push(options.cursor.updatedAt, options.cursor.runId); cursorClause = `and (r.updated_at, r.run_id) < ($${values.length - 1}, $${values.length})`; } values.push(options.limit); const rows = await sql.unsafe(`select r.sentinel_id, r.node, r.lane, r.run_id, r.updated_at, r.status, r.payload_hash from monitor.runs r where ${where.text} ${cursorClause} order by r.updated_at desc, r.run_id desc limit $${values.length}`, values); return rows.map(runRow); }
async function queryMonitorWorkspace(sql: postgres.Sql, scope: MonitorScope, options: MonitorWorkspaceQueryOptions): Promise<MonitorWorkspaceQueryResult> {
const where = scopeWhere(scope);
const values: unknown[] = [...where.values];
const filters: string[] = [where.text];
if (options.status) { values.push(options.status); filters.push(`r.status = $${values.length}`); }
if (options.from) { values.push(options.from); filters.push(`r.updated_at >= $${values.length}`); }
if (options.to) { values.push(options.to); filters.push(`r.updated_at <= $${values.length}`); }
const baseValues = [...values];
let cursorClause = "";
if (options.cursor) { values.push(options.cursor.updatedAt, options.cursor.runId); cursorClause = `and (r.updated_at, r.run_id) < ($${values.length - 1}, $${values.length})`; }
values.push(options.limit + 1);
const predicate = filters.join(" and ");
const [pageRows, summaryRows, statusRows] = await Promise.all([
sql.unsafe(`select r.sentinel_id, r.node, r.lane, r.run_id, r.updated_at, r.status, r.payload_hash, count(f.finding_index)::int as finding_count from monitor.runs r left join monitor.findings f using (sentinel_id, node, lane, run_id) where ${predicate} ${cursorClause} group by r.sentinel_id, r.node, r.lane, r.run_id, r.updated_at, r.status, r.payload_hash order by r.updated_at desc, r.run_id desc limit $${values.length}`, values),
sql.unsafe(`select count(*)::int as total_runs, coalesce(sum(finding_count),0)::int as finding_count, max(updated_at) filter (where status = 'succeeded') as latest_success_at, max(updated_at) filter (where status = 'failed') as latest_failure_at from (select r.status, r.updated_at, count(f.finding_index)::int as finding_count from monitor.runs r left join monitor.findings f using (sentinel_id, node, lane, run_id) where ${predicate} group by r.sentinel_id, r.node, r.lane, r.run_id, r.status, r.updated_at) filtered`, baseValues),
sql.unsafe(`select r.status, count(*)::int as status_count from monitor.runs r where ${predicate} group by r.status`, baseValues),
]);
const hasMore = pageRows.length > options.limit;
const items = pageRows.slice(0, options.limit).map((row) => ({ ...runRow(row), findingCount: Number(row.finding_count ?? 0) }));
const summary = summaryRows[0] ?? {};
const last = items.at(-1);
return { items, nextCursor: hasMore && last ? cursor(last) : null, totalRuns: Number(summary.total_runs ?? 0), findingCount: Number(summary.finding_count ?? 0), statusCounts: Object.fromEntries(statusRows.map((row) => [String(row.status), Number(row.status_count)])), latestSuccessAt: dateOrNull(summary.latest_success_at), latestFailureAt: dateOrNull(summary.latest_failure_at) };
}
async function countRuns(sql: postgres.Sql, scope: MonitorScope): Promise<number> { const where = scopeWhere(scope); const rows = await sql.unsafe(`select count(*)::int as count from monitor.runs r where ${where.text}`, where.values); return Number(rows[0]?.count ?? 0); }
async function updatePostgresArtifactAvailability(transaction: postgres.TransactionSql, input: NormalizedMonitorCentralIngest): Promise<void> {
for (const [index, locator] of input.artifactLocators.entries()) await transaction`
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { test } from "bun:test";
import { monitorRouteHref, readMonitorRoute, withMonitorRoute } from "../assets/web-probe-sentinel-monitor-workbench/state/monitor-route.js";
Object.assign(globalThis, { window: { location: { origin: "https://monitor.example.test" } } });
test("monitor route roundtrips run detail tab and filters", () => {
const route = readMonitorRoute("https://monitor.example.test/monitor/runs/run-1/findings/finding-2?sentinelId=s1&node=NC01&lane=v03&status=failed&tab=findings");
assert.equal(route.kind, "detail");
assert.equal(route.detailType, "finding");
assert.equal(monitorRouteHref(route), "/monitor/runs/run-1/findings/finding-2?sentinelId=s1&node=NC01&lane=v03&status=failed&tab=findings");
});
test("monitor route rejects unsupported paths and filter changes clear selection", () => {
assert.deepEqual(readMonitorRoute("https://monitor.example.test/dashboard"), { kind: "invalid", reason: "unsupported_path" });
const next = withMonitorRoute(readMonitorRoute("https://monitor.example.test/monitor/runs/run-1"), { kind: "workspace", runId: "", filters: { status: "failed" } });
assert.equal(monitorRouteHref(next), "/monitor?status=failed");
});
test("monitor route rejects invalid tab status time range and malformed encoding", () => {
assert.equal(readMonitorRoute("https://monitor.example.test/monitor?tab=raw").reason, "invalid_tab");
assert.equal(readMonitorRoute("https://monitor.example.test/monitor?status=surprise").reason, "invalid_status");
assert.equal(readMonitorRoute("https://monitor.example.test/monitor?from=invalid").reason, "invalid_time_range");
assert.equal(readMonitorRoute("https://monitor.example.test/monitor?from=2026-07-13T05:00:00Z&to=2026-07-13T04:00:00Z").reason, "invalid_time_range");
assert.equal(readMonitorRoute("https://monitor.example.test/monitor/runs/%E0%A4%A").reason, "malformed_url_encoding");
});
test("monitor route roundtrips diagnostic detail", () => {
const route = readMonitorRoute("https://monitor.example.test/monitor/runs/run-1/diagnostics/runtime?sentinelId=s1&node=NC01&lane=v03&tab=diagnostics");
assert.equal(route.detailType, "diagnostic");
assert.equal(route.detailId, "runtime");
assert.equal(monitorRouteHref(route), "/monitor/runs/run-1/diagnostics/runtime?sentinelId=s1&node=NC01&lane=v03&tab=diagnostics");
});