@bli-cockpit/telemetry-core 0.1.59 → 0.1.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@
4
4
  * both thin callers of `digestSource`, so they print the same thing.
5
5
  */
6
6
  import { ClassTable } from "./classify.js";
7
- import { type RoutineEvents } from "./digest.js";
7
+ import { type DigestResult, type RoutineEvents } from "./digest.js";
8
8
  import { type LogFn, type RunCli, type SourceContext } from "./sources/types.js";
9
9
  export declare const SOURCE_NAMES: readonly ["collector", "dashboard", "railway", "railway:<service>", "-"];
10
10
  /** A Railway service name: validated before anything is spawned, because a Windows run goes through cmd.exe. */
@@ -95,5 +95,7 @@ export interface Refusal {
95
95
  export type DigestOutcome = DigestAnswer | RawAnswer | Refusal;
96
96
  /** `railway:ladder` becomes `railway`: the source family a table pattern's `source` regex is matched against. */
97
97
  export declare function sourceFamily(source: string): string;
98
+ /** Every group of a digest result, classified and ordered: what needs a person first, then by count. */
99
+ export declare function classifyTemplates(result: DigestResult, table: ClassTable, family: string): DigestTemplate[];
98
100
  /** Reads, digests, classifies and renders one source. Never throws for a refusal: it is returned, named. */
99
101
  export declare function digestSource(request: DigestRequest, env?: DigestEnvironment): Promise<DigestOutcome>;
@@ -44,7 +44,8 @@ const iso = (epoch) => new Date(epoch * 1000).toISOString();
44
44
  function windowFacts(window) {
45
45
  return { from: iso(window.fromEpoch), to: iso(window.toEpoch), label: window.label };
46
46
  }
47
- function templates(result, table, family) {
47
+ /** Every group of a digest result, classified and ordered: what needs a person first, then by count. */
48
+ export function classifyTemplates(result, table, family) {
48
49
  const rows = result.groups.map((record) => {
49
50
  const verdict = table.classify(record.unit, record.template, family);
50
51
  return {
@@ -122,7 +123,7 @@ export async function digestSource(request, env = {}) {
122
123
  return { ok: true, kind: "raw", source: request.source, tid: wanted, window: facts, matched, lines, notes: source.notes, text: [head, ...lines].join("\n") };
123
124
  }
124
125
  const text = renderCapped(result, { source: request.source, window: window.label, classify: (unit, template) => table.classify(unit, template, family), maxBytes: request.maxBytes ?? DEFAULT_MAX_BYTES, notes: source.notes });
125
- const all = templates(result, table, family);
126
+ const all = classifyTemplates(result, table, family);
126
127
  const rawChars = source.rawChars ?? source.lines.reduce((sum, line) => sum + line.message.length + 1, 0);
127
128
  const errors = all.filter((entry) => entry.severity === "ERROR").length;
128
129
  log("[logs digest] digested", { source: family, window: window.label, lines: result.lines, noise: result.noise, templates: all.length, error_templates: errors, printed_bytes: Buffer.byteLength(text, "utf8"), raw_chars: rawChars });
@@ -30,6 +30,9 @@ export const DEFAULT_NOISE = [
30
30
  // systemd's own routine words about a unit; the rest of such a line is the unit's description, which can say anything
31
31
  const SYSTEMD_ROUTINE = /^(Starting|Started|Finished|Stopping|Stopped|Reloading|Reloaded|Created slice|Removed slice|Listening|Reached target|Closed|Queued|Activating|Deactivated|Consumed|\S+: (Deactivated|Consumed|Succeeded|Main process exited, code=exited, status=0\/SUCCESS))/;
32
32
  const EXCEPTION_LINE = /^([A-Za-z_][\w.]*(?:Error|Exception|Interrupt|Exit|Warning|Failure))(?::\s?(.*))?$/;
33
+ // A thrown JavaScript error (`TypeError: ...`, `PostgresError: ...`): the word `error` is glued to its name, so the
34
+ // Python-ported word list (`\berror\b`) never sees it. Only consulted for Tower-shaped sources (`taggedLines`).
35
+ const JS_EXCEPTION = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/;
33
36
  const FRAME_LINE = /^\s+File "([^"]+)", line \d+, in (\S+)/;
34
37
  function compileAll(patterns) {
35
38
  return patterns.map((pattern) => new RegExp(pattern));
@@ -152,7 +155,7 @@ export class Digest {
152
155
  // The source's own level is NOT a verdict on a plain line: Tower writes ordinary output to stderr, which Vercel
153
156
  // and Railway both mark "error" (measured 2026-10-07). Words and fields decide; see tagged.ts.
154
157
  const judgedText = this.taggedLines ? withoutZeroCounters(message) : message;
155
- if (looksImportant(judgedText) && !(manager && SYSTEMD_ROUTINE.test(message))) {
158
+ if ((looksImportant(judgedText) || (this.taggedLines && JS_EXCEPTION.test(judgedText))) && !(manager && SYSTEMD_ROUTINE.test(message))) {
156
159
  this.addGroup(group, instance, event, mask(message), ts, message);
157
160
  return;
158
161
  }
@@ -6,10 +6,14 @@ export { CLASS_ORDER, ClassTable, type Classify, type ClassInfo, type ClassTable
6
6
  export { clock, fleetView, numberText, renderCapped, renderFleet, renderLocal, routineText, subjectsText, timeRange, type CappedOptions, type FleetView, } from "./render.js";
7
7
  export { TOWER_CLASSES, TOWER_PATTERNS, TOWER_TABLE, towerClassTable } from "./tower-classes.js";
8
8
  export { WindowError, isoOf, parseWindow, relativeSeconds, type LogWindow } from "./window.js";
9
- export { DEFAULT_MAX_BYTES, SOURCE_NAMES, digestSource, sourceFamily, type DigestAnswer, type DigestEnvironment, type DigestOutcome, type DigestRequest, type DigestTemplate, type RawAnswer, type Refusal, } from "./digest-source.js";
9
+ export { DEFAULT_MAX_BYTES, SOURCE_NAMES, classifyTemplates, digestSource, sourceFamily, type DigestAnswer, type DigestEnvironment, type DigestOutcome, type DigestRequest, type DigestTemplate, type RawAnswer, type Refusal, } from "./digest-source.js";
10
10
  export { SourceRefusal, type CliRun, type LogFn, type RunCli, type SourceContext, type SourceLine, type SourceRead } from "./sources/types.js";
11
11
  export { nodeRunCli } from "./sources/process.js";
12
12
  export { readCollector, receiptLine, streamLines, windowShare } from "./sources/collector.js";
13
13
  export { RAILWAY_ENVIRONMENT, RAILWAY_PROJECT_ID, railwayRefusal, readRailway } from "./sources/railway.js";
14
- export { VERCEL_PROJECT, VERCEL_SCOPE, readDashboard, routeTemplate, vercelRefusal } from "./sources/vercel.js";
14
+ export { VERCEL_PROJECT, VERCEL_SCOPE, readDashboard, routeTemplate, vercelRecordLines, vercelRefusal, type VercelClasses, type VercelRecord } from "./sources/vercel.js";
15
15
  export { readStdin } from "./sources/stdin.js";
16
+ export { LOCAL_ACCESS_REFUSALS, STORED_MAX_TEMPLATES_PER_WINDOW, digestLines, mergeStored, scrubRow, storedRowBytes, toStoredRows, type DigestedLines, type StoredMerge, type StoredRow, type StoredWindow, } from "./stored.js";
17
+ export { PROJECT_TABLES, projectClassTable } from "./project-classes.js";
18
+ export { LOG_EXCLUDED, LOG_EXCLUDED_SUPABASE_REFS, LOG_PROJECTS, LOG_PROJECT_IDS, LOG_PROJECT_PATTERN, TOWER_RAILWAY, VERCEL_TEAM_ID, findLogProject, type LogProject, type LogSource, type NotWiredSource, type RailwaySource, type SupabaseSource, type SupabaseStream, type VercelSource, } from "./log-projects.js";
19
+ export { STORED_EXAMPLE_CHARS, STORED_TEMPLATE_CHARS, scrubForStorage, scrubLine, scrubUnit } from "./scrub.js";
@@ -6,10 +6,14 @@ export { CLASS_ORDER, ClassTable, } from "./classify.js";
6
6
  export { clock, fleetView, numberText, renderCapped, renderFleet, renderLocal, routineText, subjectsText, timeRange, } from "./render.js";
7
7
  export { TOWER_CLASSES, TOWER_PATTERNS, TOWER_TABLE, towerClassTable } from "./tower-classes.js";
8
8
  export { WindowError, isoOf, parseWindow, relativeSeconds } from "./window.js";
9
- export { DEFAULT_MAX_BYTES, SOURCE_NAMES, digestSource, sourceFamily, } from "./digest-source.js";
9
+ export { DEFAULT_MAX_BYTES, SOURCE_NAMES, classifyTemplates, digestSource, sourceFamily, } from "./digest-source.js";
10
10
  export { SourceRefusal } from "./sources/types.js";
11
11
  export { nodeRunCli } from "./sources/process.js";
12
12
  export { readCollector, receiptLine, streamLines, windowShare } from "./sources/collector.js";
13
13
  export { RAILWAY_ENVIRONMENT, RAILWAY_PROJECT_ID, railwayRefusal, readRailway } from "./sources/railway.js";
14
- export { VERCEL_PROJECT, VERCEL_SCOPE, readDashboard, routeTemplate, vercelRefusal } from "./sources/vercel.js";
14
+ export { VERCEL_PROJECT, VERCEL_SCOPE, readDashboard, routeTemplate, vercelRecordLines, vercelRefusal } from "./sources/vercel.js";
15
15
  export { readStdin } from "./sources/stdin.js";
16
+ export { LOCAL_ACCESS_REFUSALS, STORED_MAX_TEMPLATES_PER_WINDOW, digestLines, mergeStored, scrubRow, storedRowBytes, toStoredRows, } from "./stored.js";
17
+ export { PROJECT_TABLES, projectClassTable } from "./project-classes.js";
18
+ export { LOG_EXCLUDED, LOG_EXCLUDED_SUPABASE_REFS, LOG_PROJECTS, LOG_PROJECT_IDS, LOG_PROJECT_PATTERN, TOWER_RAILWAY, VERCEL_TEAM_ID, findLogProject, } from "./log-projects.js";
19
+ export { STORED_EXAMPLE_CHARS, STORED_TEMPLATE_CHARS, scrubForStorage, scrubLine, scrubUnit } from "./scrub.js";
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The project registry (BLI-12855): which Vercel project, Railway project and
3
+ * Supabase project each BLI product runs on, so the server-side cron knows what
4
+ * to read and `cockpit logs <project>` knows what to answer for.
5
+ *
6
+ * Ids and names only: no URL with a secret, no token, no env value. Every id
7
+ * below was discovered from the platforms' own CLIs on 2026-10-07
8
+ * (`vercel project ls --scope bli-inc`, `vercel api /v9/projects`,
9
+ * `railway list` and the Railway GraphQL API, `supabase projects list`), and the
10
+ * Vercel-to-Supabase pairing was read from each repo's own code
11
+ * (`gh search code supabase.co --repo BLI-INC/<repo>`), never guessed. A source
12
+ * that cannot be read is `not_wired` with the reason, so a gap is a line in this
13
+ * file and in `docs/runbooks/tower-logs.md`, not a silence.
14
+ *
15
+ * Adding a project: `docs/runbooks/tower-logs.md`, "Add a project".
16
+ */
17
+ /** The Vercel team every BLI project lives in (slug `bli-inc`). */
18
+ export declare const VERCEL_TEAM_ID = "team_JPu5D09vtC8U3J7FyVxintpK";
19
+ /** Railway project `bli-cockpit-inference` (workspace "canakobli's Projects"), environment `production`. */
20
+ export declare const TOWER_RAILWAY: {
21
+ readonly project_id: "868238ce-d8fe-4629-8e05-fb7492baff1f";
22
+ readonly environment_id: "ec008563-7123-4f26-b425-fb6bb498a404";
23
+ readonly environment: "production";
24
+ };
25
+ export type SupabaseStream = "postgres" | "api" | "auth";
26
+ interface SourceBase {
27
+ /** A stable label stored with every row: `vercel:<name>`, `railway:<project>`, `supabase:<name>`. */
28
+ source: string;
29
+ /** What the class table's `source` regex sees: `dashboard`, `railway`, `vercel`, `supabase`. */
30
+ family: string;
31
+ }
32
+ export interface VercelSource extends SourceBase {
33
+ kind: "vercel";
34
+ /** `prj_...` */
35
+ project_id: string;
36
+ name: string;
37
+ /** The unit prefix of every line: `dashboard` keeps Tower's own class table matching. */
38
+ unit_prefix: string;
39
+ }
40
+ export interface RailwaySource extends SourceBase {
41
+ kind: "railway";
42
+ project_id: string;
43
+ environment_id: string;
44
+ environment: string;
45
+ }
46
+ export interface SupabaseSource extends SourceBase {
47
+ kind: "supabase";
48
+ ref: string;
49
+ name: string;
50
+ streams: readonly SupabaseStream[];
51
+ }
52
+ export interface NotWiredSource extends SourceBase {
53
+ kind: "not_wired";
54
+ /** The platform it would be read from. */
55
+ platform: string;
56
+ /** Plain words: why nothing reads it, and what would. */
57
+ reason: string;
58
+ }
59
+ export type LogSource = VercelSource | RailwaySource | SupabaseSource | NotWiredSource;
60
+ export interface LogProject {
61
+ /** What `cockpit logs <project>` takes. */
62
+ id: string;
63
+ name: string;
64
+ sources: readonly LogSource[];
65
+ }
66
+ export declare const LOG_PROJECTS: readonly LogProject[];
67
+ /** Not Tower, so not here: Veetesh's own Vercel project. */
68
+ export declare const LOG_EXCLUDED: readonly ["bli-cockpit-oversight"];
69
+ /**
70
+ * Supabase refs that must NEVER be read, from the project sessions' handoffs on ticket 12860: Kolm's frozen v14 and its
71
+ * empty project, and Pearl Portal's unused staging. `stored.test.ts` pins that none is in the registry.
72
+ */
73
+ export declare const LOG_EXCLUDED_SUPABASE_REFS: Readonly<Record<string, string>>;
74
+ export declare function findLogProject(id: string): LogProject | null;
75
+ export declare const LOG_PROJECT_IDS: readonly string[];
76
+ /** A project id as `cockpit logs <project>` spells it: lowercase letters, digits and dashes. */
77
+ export declare const LOG_PROJECT_PATTERN: RegExp;
78
+ export {};
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The project registry (BLI-12855): which Vercel project, Railway project and
3
+ * Supabase project each BLI product runs on, so the server-side cron knows what
4
+ * to read and `cockpit logs <project>` knows what to answer for.
5
+ *
6
+ * Ids and names only: no URL with a secret, no token, no env value. Every id
7
+ * below was discovered from the platforms' own CLIs on 2026-10-07
8
+ * (`vercel project ls --scope bli-inc`, `vercel api /v9/projects`,
9
+ * `railway list` and the Railway GraphQL API, `supabase projects list`), and the
10
+ * Vercel-to-Supabase pairing was read from each repo's own code
11
+ * (`gh search code supabase.co --repo BLI-INC/<repo>`), never guessed. A source
12
+ * that cannot be read is `not_wired` with the reason, so a gap is a line in this
13
+ * file and in `docs/runbooks/tower-logs.md`, not a silence.
14
+ *
15
+ * Adding a project: `docs/runbooks/tower-logs.md`, "Add a project".
16
+ */
17
+ /** The Vercel team every BLI project lives in (slug `bli-inc`). */
18
+ export const VERCEL_TEAM_ID = "team_JPu5D09vtC8U3J7FyVxintpK";
19
+ /** Railway project `bli-cockpit-inference` (workspace "canakobli's Projects"), environment `production`. */
20
+ export const TOWER_RAILWAY = {
21
+ project_id: "868238ce-d8fe-4629-8e05-fb7492baff1f",
22
+ environment_id: "ec008563-7123-4f26-b425-fb6bb498a404",
23
+ environment: "production",
24
+ };
25
+ const vercel = (name, project_id, options = {}) => ({
26
+ kind: "vercel",
27
+ source: `vercel:${name}`,
28
+ family: options.family ?? "vercel",
29
+ project_id,
30
+ name,
31
+ unit_prefix: options.unit_prefix ?? name,
32
+ });
33
+ const supabase = (name, ref, streams = ["postgres", "api", "auth"]) => ({
34
+ kind: "supabase",
35
+ source: `supabase:${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`,
36
+ family: "supabase",
37
+ ref,
38
+ name,
39
+ streams,
40
+ });
41
+ const notWired = (source, platform, reason) => ({ kind: "not_wired", source, family: platform, platform, reason });
42
+ export const LOG_PROJECTS = [
43
+ {
44
+ id: "tower",
45
+ name: "Tower",
46
+ sources: [
47
+ vercel("bli-cockpit-dashboard", "prj_tKAQTQFCCBIXfnEJWvAbMGAqJjuN", { unit_prefix: "dashboard", family: "dashboard" }),
48
+ { kind: "railway", source: "railway:bli-cockpit-inference", family: "railway", ...TOWER_RAILWAY },
49
+ supabase("BLI-Cockpit", "bnwolptxyrjalnppqyaf"),
50
+ ],
51
+ },
52
+ {
53
+ id: "portpal",
54
+ name: "PortPal",
55
+ sources: [
56
+ vercel("portpal-2", "prj_QfzQ7rmAAlIdYphezkFXY4JebM3W"),
57
+ supabase("PortPal", "qcnozghkxbnlofahaqig"),
58
+ ],
59
+ },
60
+ {
61
+ id: "blue-pearl-website",
62
+ name: "Blue Pearl website",
63
+ sources: [
64
+ vercel("blue-pearl-landing-page", "prj_qNlZmob3hynJcGfSY6EQRgriDENe"),
65
+ vercel("azure-pearl-insurance", "prj_AYGiGlrYR6Oc6QPA4YxTCL9MTvYp"),
66
+ // The website's own Supabase project, not Pearl Portal's (named in the Pearl Portal session's handoff on ticket 12860).
67
+ supabase("blue-pearl-website", "wcdvrwqwnhbsqtyoqrot"),
68
+ ],
69
+ },
70
+ {
71
+ id: "pearl-portal",
72
+ name: "Pearl Portal",
73
+ sources: [
74
+ vercel("bluepearl-frontend", "prj_cnvD5OppdZqyc8NjlfELlJlChkWf"),
75
+ supabase("BluePearl", "cfznyqwbdjlyvmfhvfuo"),
76
+ // From the Pearl Portal session (ticket 12860's comment), not re-verified live from here.
77
+ notWired("gcp:blue-pearl-mortgage", "gcp", "gcloud_not_authenticated: Pearl's mortgage backend runs on Google Cloud Run (service blue-pearl-mortgage, GCP project buildlaunchiterate, region northamerica-northeast2), read through Cloud Logging; this machine's gcloud login (edward@buildlaunchiterate.ca) needs a fresh `gcloud auth login` before a read-only service account (roles/logging.viewer) can be minted, and the cron holds no Google credential yet"),
78
+ notWired("sentry:build-launch-iterate/javascript-nextjs", "sentry", "sentry_token_not_mintable: the Pearl frontend also reports to Sentry (org build-launch-iterate, project javascript-nextjs); a read-only internal-integration token (event:read, project:read, org:read) needs org-level write that the existing Sentry login lacks (creating the integration answered 403), so no token was minted and Edward's broader personal token was not copied; create the integration in Sentry settings, then register the source"),
79
+ ],
80
+ },
81
+ {
82
+ id: "triage-ocr",
83
+ name: "Triage OCR",
84
+ sources: [
85
+ vercel("triage-ocr", "prj_649ktBEpFEkkd46MFAbIFRml55N3"),
86
+ notWired("supabase:triage-ocr", "supabase", "the repo's Supabase ref (xdcheixvpvanblntpisx) is in no Supabase organization the Tower login can read, so its logs cannot be queried; add the ref once a token with access exists"),
87
+ ],
88
+ },
89
+ {
90
+ id: "triage-crm",
91
+ name: "Triage CRM",
92
+ sources: [
93
+ vercel("triage-engine", "prj_PYzJea8t6bgMeUlHGZnwNFklH7GU"),
94
+ supabase("Triage-CRM", "qpzgytjwjgyvevtmrjai"),
95
+ ],
96
+ },
97
+ {
98
+ id: "kolm",
99
+ name: "Kolm",
100
+ sources: [
101
+ vercel("kolm-dashboard-v15", "prj_suQSpiNRR0qi6DEeaYUtYIdL6pia"),
102
+ // Kolm PRODUCTION (the Kolm session's handoff on ticket 12860). The CLI lists this ref under the name "kolm-v15-staging".
103
+ supabase("Kolm", "hvhoyqalnkvbnpteggpi"),
104
+ ],
105
+ },
106
+ {
107
+ id: "kaiben",
108
+ name: "Kaiben",
109
+ sources: [
110
+ supabase("kaiben-core", "ozwovnqtzdwptaeslrep"),
111
+ notWired("droplet:kaiben-ridestyler", "droplet", "Kaiben's operator already writes a 15-minute fleet digest, but only as files on the droplet (/var/log/kaiben-operator/digest-latest.txt and digests/); there is no HTTP or API read, only ssh, which a Railway cron does not hold; the fix is for the operator to POST its digest to a Tower door"),
112
+ ],
113
+ },
114
+ {
115
+ id: "black-knight-tire",
116
+ name: "Black Knight Tire",
117
+ sources: [
118
+ vercel("black-knight-marketplace", "prj_u02otChICpzmg01INncuB2agKDL0"),
119
+ vercel("bkt-reply-copilot", "prj_zvDt2gD4N69hMpU7zfzgNBFlDhgR"),
120
+ supabase("Black Knight Tire", "lvfxhppyzfnvooerblrz"),
121
+ ],
122
+ },
123
+ {
124
+ id: "sublimation-squad",
125
+ name: "Sublimation Squad",
126
+ sources: [
127
+ vercel("sublimation", "prj_CK3YtimGeLZoEbk66Tzr9SVbayWH"),
128
+ supabase("Sublimation-Website", "jlfrjgqvevdnyilkpoue"),
129
+ ],
130
+ },
131
+ {
132
+ id: "bli-website",
133
+ name: "BLI website",
134
+ sources: [
135
+ vercel("bli-website", "prj_7CvxylNLGAFeUeWzEXY7lYjHllIs"),
136
+ vercel("buildlaunchiterate", "prj_Tk79luzslERUZyA8xuGvciVBdPhX"),
137
+ ],
138
+ },
139
+ {
140
+ id: "keep-downloader",
141
+ name: "keep-downloader",
142
+ sources: [
143
+ notWired("railway:keep-downloader", "railway", "a second Railway project (id 84fb1eba-5a8e-4071-a392-22bea076ceee, service keep) with no owner named in any ticket; not wired until someone says it is a BLI product, then it needs its own Railway project token"),
144
+ ],
145
+ },
146
+ ];
147
+ /** Not Tower, so not here: Veetesh's own Vercel project. */
148
+ export const LOG_EXCLUDED = ["bli-cockpit-oversight"];
149
+ /**
150
+ * Supabase refs that must NEVER be read, from the project sessions' handoffs on ticket 12860: Kolm's frozen v14 and its
151
+ * empty project, and Pearl Portal's unused staging. `stored.test.ts` pins that none is in the registry.
152
+ */
153
+ export const LOG_EXCLUDED_SUPABASE_REFS = {
154
+ bgrbctwnlnccilpejgth: "Kolm v14, frozen",
155
+ imzkkjrhincdbiejfmlp: "Kolm, an empty project",
156
+ wsqxucgzdqomoyrfnazw: "Pearl Portal staging, unused",
157
+ };
158
+ export function findLogProject(id) {
159
+ return LOG_PROJECTS.find((project) => project.id === id) ?? null;
160
+ }
161
+ export const LOG_PROJECT_IDS = LOG_PROJECTS.map((project) => project.id);
162
+ /** A project id as `cockpit logs <project>` spells it: lowercase letters, digits and dashes. */
163
+ export const LOG_PROJECT_PATTERN = /^[a-z][a-z0-9-]{1,40}$/;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * One class table per project (BLI-12855): which masked log templates are bugs,
3
+ * hiccups or harmless, for each BLI product the cron digests.
4
+ *
5
+ * Every table starts from Tower's classes and the `any-*` patterns of Tower's own
6
+ * table (a warning every AI SDK app prints, an npm notice every Railway service
7
+ * prints), then adds that project's own patterns. A project's patterns are seeded
8
+ * from its FIRST REAL DAY of logs, each naming the window and count it came from;
9
+ * a template no pattern matches stays `unknown` and alerts, so a table only ever
10
+ * grows by explaining something, never by silencing it (the rule of
11
+ * `tower-classes.ts`, "Teach it a new pattern" in `docs/runbooks/tower-logs.md`).
12
+ */
13
+ import { ClassTable, type ClassTableData } from "./classify.js";
14
+ export declare const PROJECT_TABLES: Record<string, ClassTableData>;
15
+ /** The compiled table of one project (built once per process); an unknown project gets the shared one. */
16
+ export declare function projectClassTable(project: string): ClassTable;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * One class table per project (BLI-12855): which masked log templates are bugs,
3
+ * hiccups or harmless, for each BLI product the cron digests.
4
+ *
5
+ * Every table starts from Tower's classes and the `any-*` patterns of Tower's own
6
+ * table (a warning every AI SDK app prints, an npm notice every Railway service
7
+ * prints), then adds that project's own patterns. A project's patterns are seeded
8
+ * from its FIRST REAL DAY of logs, each naming the window and count it came from;
9
+ * a template no pattern matches stays `unknown` and alerts, so a table only ever
10
+ * grows by explaining something, never by silencing it (the rule of
11
+ * `tower-classes.ts`, "Teach it a new pattern" in `docs/runbooks/tower-logs.md`).
12
+ */
13
+ import { ClassTable } from "./classify.js";
14
+ import { LOG_PROJECT_IDS } from "./log-projects.js";
15
+ import { TOWER_CLASSES, TOWER_PATTERNS } from "./tower-classes.js";
16
+ const SHARED = TOWER_PATTERNS.filter((pattern) => pattern.id.startsWith("any-"));
17
+ /** Patterns seeded from each project's first real day. Specific patterns first; first match wins. */
18
+ const SEEDED = {
19
+ tower: TOWER_PATTERNS,
20
+ };
21
+ export const PROJECT_TABLES = Object.fromEntries(LOG_PROJECT_IDS.map((id) => [id, { version: 1, classes: TOWER_CLASSES, patterns: SEEDED[id] ?? SHARED, noiseUnits: [] }]));
22
+ const compiled = new Map();
23
+ /** The compiled table of one project (built once per process); an unknown project gets the shared one. */
24
+ export function projectClassTable(project) {
25
+ let table = compiled.get(project);
26
+ if (!table) {
27
+ table = new ClassTable(PROJECT_TABLES[project] ?? { version: 1, classes: TOWER_CLASSES, patterns: SHARED, noiseUnits: [] });
28
+ compiled.set(project, table);
29
+ }
30
+ return table;
31
+ }
@@ -0,0 +1,11 @@
1
+ export declare const STORED_TEMPLATE_CHARS = 160;
2
+ export declare const STORED_EXAMPLE_CHARS = 160;
3
+ /** Email and phone only: the light pass applied to every line before it is digested. */
4
+ export declare function scrubLine(message: string): string;
5
+ /** A unit (a route family or service name) is never a path to mask; only a person's email or phone in it goes. */
6
+ export declare function scrubUnit(unit: string): string;
7
+ /**
8
+ * The full scrub of a template or an example. Idempotent: scrubbing a scrubbed
9
+ * text returns it unchanged, so the read path can apply it again for free.
10
+ */
11
+ export declare function scrubForStorage(text: string, limit?: number): string;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The storage scrubber (BLI-12855): what may be written to `project_log_digests`.
3
+ *
4
+ * Plain words: a stored digest row is readable by every `member` and later feeds
5
+ * the brain, and a log line can carry a borrower's email, name, phone or amount
6
+ * (Pearl Portal is a mortgage CRM). The digest's own `redact()` removes secrets
7
+ * only. This removes the people: emails become `<email>`, phone-shaped runs
8
+ * `<phone>`, every number, id, url and path a placeholder (the digest's `mask()`),
9
+ * and every quoted VALUE `"<q>"` (a JSON key stays so the line still reads).
10
+ * What is stored is therefore a masked line, never a raw one.
11
+ *
12
+ * It runs on the STORAGE path only, so the Python-parity digest and the local
13
+ * `cockpit logs` are untouched. Two entry points:
14
+ * - `scrubLine`: email and phone only, applied to each line BEFORE it is
15
+ * digested, so the template id is stable across borrowers and a 200-character
16
+ * cut can never land in the middle of an email.
17
+ * - `scrubForStorage`: the full scrub of a template or example, applied before
18
+ * insert and again on the way out of the table (idempotent, so a row written
19
+ * by anything else is still scrubbed when it is read).
20
+ *
21
+ * What it cannot see, stated plainly: a name that is not quoted and not a
22
+ * `name=...` field ("Borrower Jane Doe applied") is plain prose. That is why the
23
+ * example is cut to 160 characters and why the runbook lists it.
24
+ */
25
+ import { cut, mask, squash } from "./mask.js";
26
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
27
+ // +1 604 555 0199, (604) 555-0199, 604-555-0199, 604.555.0199. A bare digit run is left to mask()'s number rule.
28
+ const PHONE = /(?<![\w.:-])(?:\+\d{1,3}[\s.-]?)?(?:\(\d{3}\)|\d{3})[\s.-]\d{3}[\s.-]\d{4}(?![\w:])|(?<![\w.:-])\+\d[\d\s().-]{7,}\d(?![\w:])/g;
29
+ // `name=Jane`, `applicant=Jane`: a person's field written as key=value outside JSON.
30
+ const PERSON_FIELD = /\b((?:first_?name|last_?name|full_?name|given_?name|surname|name|borrower|applicant|customer|client|contact|owner|address|dob|birth_?date|sin|ssn)\s*=\s*)[^\s,;&}"'<]+/gi;
31
+ const DOUBLE_QUOTED = /"([^"\n]{0,300})"(\s*:)?/g;
32
+ const SINGLE_QUOTED = /(?<![\w])'([^'\n]{0,300}?)'(?![\w])/g;
33
+ const UNTERMINATED_DOUBLE = /"[^"\n\u0001\u0002\u0003]*$/;
34
+ const UNTERMINATED_SINGLE = /(?<![\w\u0001\u0003])'[^'\n\u0001\u0003]*$/;
35
+ // Control characters stand in for finished quotes while the text is worked on, so a leftover quote mark is an open one.
36
+ const VALUE = "\u0001";
37
+ const KEY = "\u0002";
38
+ const SINGLE_VALUE = "\u0003";
39
+ export const STORED_TEMPLATE_CHARS = 160;
40
+ export const STORED_EXAMPLE_CHARS = 160;
41
+ const CUT_MARK = "…";
42
+ /** Email and phone only: the light pass applied to every line before it is digested. */
43
+ export function scrubLine(message) {
44
+ return message.replace(EMAIL, "<email>").replace(PHONE, "<phone>");
45
+ }
46
+ /** A unit (a route family or service name) is never a path to mask; only a person's email or phone in it goes. */
47
+ export function scrubUnit(unit) {
48
+ return cut(scrubLine(unit), 200);
49
+ }
50
+ function maskQuotedValues(text) {
51
+ let out = text.replace(DOUBLE_QUOTED, (_match, inner, colon) => (colon ? `${KEY}${inner}${KEY}${colon}` : VALUE));
52
+ out = out.replace(SINGLE_QUOTED, SINGLE_VALUE);
53
+ // A cut can land inside a quote: what is left open at the end is a value too.
54
+ out = out.replace(UNTERMINATED_DOUBLE, '"<q>').replace(UNTERMINATED_SINGLE, "'<q>");
55
+ return out.replaceAll(VALUE, '"<q>"').replaceAll(SINGLE_VALUE, "'<q>'").replaceAll(KEY, '"');
56
+ }
57
+ /**
58
+ * The full scrub of a template or an example. Idempotent: scrubbing a scrubbed
59
+ * text returns it unchanged, so the read path can apply it again for free.
60
+ */
61
+ export function scrubForStorage(text, limit = STORED_EXAMPLE_CHARS) {
62
+ if (text === "")
63
+ return text;
64
+ const alreadyCut = text.endsWith(CUT_MARK);
65
+ const body = alreadyCut ? text.slice(0, -CUT_MARK.length) : text;
66
+ let out = scrubLine(body).replace(PERSON_FIELD, "$1<redacted>");
67
+ out = mask(out); // numbers, ids, urls, paths, secrets; cuts to 160
68
+ out = maskQuotedValues(out);
69
+ out = squash(out);
70
+ if (Array.from(out).length > limit)
71
+ return `${cut(out, limit - 1)}${CUT_MARK}`;
72
+ return alreadyCut ? `${out}${CUT_MARK}` : out;
73
+ }
@@ -1,10 +1,40 @@
1
- import { SourceRefusal, type CliRun, type SourceContext, type SourceRead } from "./types.js";
1
+ import { SourceRefusal, type CliRun, type SourceContext, type SourceLine, type SourceRead } from "./types.js";
2
2
  export declare const VERCEL_PROJECT = "bli-cockpit-dashboard";
3
3
  export declare const VERCEL_SCOPE = "bli-inc";
4
+ export interface VercelRecord {
5
+ id?: string;
6
+ timestamp?: number;
7
+ level?: string;
8
+ message?: string;
9
+ source?: string;
10
+ requestMethod?: string;
11
+ requestPath?: string;
12
+ responseStatusCode?: number;
13
+ logs?: Array<{
14
+ level?: string;
15
+ message?: string;
16
+ }>;
17
+ }
4
18
  /** `/api/docs/3f2a…` becomes `/api/docs/:id`; digits, uuids, long hex and long slugs are one placeholder. */
5
19
  export declare function routeTemplate(path: string | undefined): string;
6
20
  /** Which named refusal a failed `vercel` run is, or null when the run is not a refusal. */
7
21
  export declare function vercelRefusal(run: CliRun): SourceRefusal | null;
8
22
  /** The refusal-pattern the runner stops on, so an interactive login is never left waiting. */
9
23
  export declare const VERCEL_ABORT_PATTERN: RegExp;
24
+ /** Request classes counted while a Vercel read is turned into lines. */
25
+ export interface VercelClasses {
26
+ ok: number;
27
+ redirect: number;
28
+ client: number;
29
+ server: number;
30
+ }
31
+ /**
32
+ * Turns Vercel request records into digest lines: each nested console line is one line, and a request that ended
33
+ * 5xx / 429 / 403 adds a synthetic line even when the code logged nothing. Shared by the CLI reader above and the
34
+ * server-side HTTP reader (`apps/dashboard/src/lib/project-logs`), so both digest the same text.
35
+ */
36
+ export declare function vercelRecordLines(records: readonly VercelRecord[], fromEpoch: number, unitPrefix: string): {
37
+ lines: SourceLine[];
38
+ classes: VercelClasses;
39
+ };
10
40
  export declare function readDashboard(context: SourceContext): Promise<SourceRead>;
@@ -77,6 +77,40 @@ function parseRecords(stdout) {
77
77
  }
78
78
  return records;
79
79
  }
80
+ /**
81
+ * Turns Vercel request records into digest lines: each nested console line is one line, and a request that ended
82
+ * 5xx / 429 / 403 adds a synthetic line even when the code logged nothing. Shared by the CLI reader above and the
83
+ * server-side HTTP reader (`apps/dashboard/src/lib/project-logs`), so both digest the same text.
84
+ */
85
+ export function vercelRecordLines(records, fromEpoch, unitPrefix) {
86
+ const lines = [];
87
+ const classes = { ok: 0, redirect: 0, client: 0, server: 0 };
88
+ for (const record of records) {
89
+ const ts = (record.timestamp ?? 0) / 1000;
90
+ if (ts && ts < fromEpoch)
91
+ continue;
92
+ const route = routeTemplate(record.requestPath);
93
+ const unit = route ? `${unitPrefix}:${route}` : unitPrefix;
94
+ const nested = record.logs && record.logs.length > 0 ? record.logs : record.message ? [{ level: record.level, message: record.message }] : [];
95
+ for (const entry of nested) {
96
+ if (typeof entry.message === "string" && entry.message)
97
+ lines.push({ unit, message: entry.message, ts, level: entry.level });
98
+ }
99
+ const status = record.responseStatusCode ?? 0;
100
+ if (status >= 200 && status < 300)
101
+ classes.ok += 1;
102
+ else if (status >= 300 && status < 400)
103
+ classes.redirect += 1;
104
+ else if (status >= 400 && status < 500)
105
+ classes.client += 1;
106
+ else if (status >= 500)
107
+ classes.server += 1;
108
+ if (status >= 500 || status === 429 || status === 403) {
109
+ lines.push({ unit, message: `HTTP ${status} ${record.requestMethod ?? "?"} ${route || "?"}`, ts, level: "error" });
110
+ }
111
+ }
112
+ return { lines, classes };
113
+ }
80
114
  export async function readDashboard(context) {
81
115
  const { window, run, log } = context;
82
116
  const allLevels = context.allLevels ?? false;
@@ -147,32 +181,7 @@ export async function readDashboard(context) {
147
181
  await Promise.all(Array.from({ length: CONCURRENCY }, () => worker()));
148
182
  if (failure)
149
183
  throw failure;
150
- const lines = [];
151
- const classes = { ok: 0, redirect: 0, client: 0, server: 0 };
152
- for (const record of seen.values()) {
153
- const ts = (record.timestamp ?? 0) / 1000;
154
- if (ts && ts < window.fromEpoch)
155
- continue;
156
- const route = routeTemplate(record.requestPath);
157
- const unit = route ? `dashboard:${route}` : "dashboard";
158
- const nested = record.logs && record.logs.length > 0 ? record.logs : record.message ? [{ level: record.level, message: record.message }] : [];
159
- for (const entry of nested) {
160
- if (typeof entry.message === "string" && entry.message)
161
- lines.push({ unit, message: entry.message, ts, level: entry.level });
162
- }
163
- const status = record.responseStatusCode ?? 0;
164
- if (status >= 200 && status < 300)
165
- classes.ok += 1;
166
- else if (status >= 300 && status < 400)
167
- classes.redirect += 1;
168
- else if (status >= 400 && status < 500)
169
- classes.client += 1;
170
- else if (status >= 500)
171
- classes.server += 1;
172
- if (status >= 500 || status === 429 || status === 403) {
173
- lines.push({ unit, message: `HTTP ${status} ${record.requestMethod ?? "?"} ${route || "?"}`, ts, level: "error" });
174
- }
175
- }
184
+ const { lines, classes } = vercelRecordLines([...seen.values()], window.fromEpoch, "dashboard");
176
185
  const notes = [];
177
186
  const requests = classes.ok + classes.redirect + classes.client + classes.server;
178
187
  notes.push(allLevels
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Stored digests (BLI-12855): the server-side half of `cockpit logs`.
3
+ *
4
+ * Plain words: Tower's cron reads each project's platform logs every 15 minutes,
5
+ * digests them (the same masking, counting and classifying as a local
6
+ * `cockpit logs`) and keeps ONLY the digest: one row per template per window,
7
+ * never a raw line. `digestLines` is the write half (lines to rows);
8
+ * `mergeStored` is the read half (many windows of rows back into one capped
9
+ * digest, real bugs first), which is what `cockpit logs <project>` and the MCP
10
+ * `logs_digest` print when no local log is in reach.
11
+ *
12
+ * Pure functions: no I/O, no clock. The cron and the dashboard door own both.
13
+ */
14
+ import { type ClassTable } from "./classify.js";
15
+ import { type DigestTemplate } from "./digest-source.js";
16
+ import type { SourceLine } from "./sources/types.js";
17
+ /**
18
+ * The refusals of a LOCAL read that mean "this machine cannot reach the platform": the stored digest is the answer
19
+ * for them, in `cockpit logs` and in the MCP `logs_digest` alike.
20
+ */
21
+ export declare const LOCAL_ACCESS_REFUSALS: ReadonlySet<string>;
22
+ /** A window keeps at most this many templates; the rest are counted, never silently lost. */
23
+ export declare const STORED_MAX_TEMPLATES_PER_WINDOW = 200;
24
+ /** One template in one window of one source of one project. Metadata only: the example is redacted and cut. */
25
+ export interface StoredRow {
26
+ project: string;
27
+ source: string;
28
+ window_start: string;
29
+ window_end: string;
30
+ tid: string;
31
+ unit: string;
32
+ class: string;
33
+ severity: string;
34
+ template: string;
35
+ example: string;
36
+ count: number;
37
+ first_at: string | null;
38
+ last_at: string | null;
39
+ }
40
+ /** One finished (or refused) window of one source: the commit marker the cursor reads. */
41
+ export interface StoredWindow {
42
+ project: string;
43
+ source: string;
44
+ window_start: string;
45
+ window_end: string;
46
+ /** `ok`, or the named reason this window could not be read (`vercel_token_missing`...). */
47
+ status: string;
48
+ lines_read: number;
49
+ noise: number;
50
+ raw_chars: number;
51
+ }
52
+ export interface DigestedLines {
53
+ lines: number;
54
+ noise: number;
55
+ /** Characters of the log lines read: what the digest saved. */
56
+ rawChars: number;
57
+ /** The kept templates, what needs a person first. */
58
+ templates: DigestTemplate[];
59
+ /** Templates beyond the per-window cap, counted so the loss is said. */
60
+ dropped: number;
61
+ }
62
+ /** Digests one window's lines and classifies every template with the project's table. */
63
+ export declare function digestLines(lines: readonly SourceLine[], options: {
64
+ family: string;
65
+ table: ClassTable;
66
+ maxTemplates?: number;
67
+ }): DigestedLines;
68
+ /** Template rows ready to store: the redacted example and the masked template, never a raw line. */
69
+ export declare function toStoredRows(templates: readonly DigestTemplate[], window: {
70
+ project: string;
71
+ source: string;
72
+ window_start: string;
73
+ window_end: string;
74
+ }): StoredRow[];
75
+ /** A stored row as it may leave the table. */
76
+ export declare function scrubRow(row: StoredRow): StoredRow;
77
+ /** The size of one stored row as JSON: what "bytes stored" counts. */
78
+ export declare function storedRowBytes(row: StoredRow): number;
79
+ export interface StoredMerge {
80
+ text: string;
81
+ /** Merged templates, what needs a person first. */
82
+ templates: Array<DigestTemplate & {
83
+ sources: string[];
84
+ }>;
85
+ windows: number;
86
+ windows_ok: number;
87
+ lines: number;
88
+ noise: number;
89
+ /** `source: reason` for every distinct refusal inside the span, so a blind spot is named. */
90
+ refusals: string[];
91
+ }
92
+ /** Many windows of stored rows merged by template id into one capped digest (about 2 KB, real bugs first). */
93
+ export declare function mergeStored(storedRows: readonly StoredRow[], windows: readonly StoredWindow[], options: {
94
+ project: string;
95
+ label: string;
96
+ maxBytes?: number;
97
+ extraNotes?: readonly string[];
98
+ }): StoredMerge;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Stored digests (BLI-12855): the server-side half of `cockpit logs`.
3
+ *
4
+ * Plain words: Tower's cron reads each project's platform logs every 15 minutes,
5
+ * digests them (the same masking, counting and classifying as a local
6
+ * `cockpit logs`) and keeps ONLY the digest: one row per template per window,
7
+ * never a raw line. `digestLines` is the write half (lines to rows);
8
+ * `mergeStored` is the read half (many windows of rows back into one capped
9
+ * digest, real bugs first), which is what `cockpit logs <project>` and the MCP
10
+ * `logs_digest` print when no local log is in reach.
11
+ *
12
+ * Pure functions: no I/O, no clock. The cron and the dashboard door own both.
13
+ */
14
+ import { CLASS_ORDER } from "./classify.js";
15
+ import { Digest } from "./digest.js";
16
+ import { classifyTemplates } from "./digest-source.js";
17
+ import { mergeResults } from "./merge.js";
18
+ import { renderCapped } from "./render.js";
19
+ import { STORED_EXAMPLE_CHARS, STORED_TEMPLATE_CHARS, scrubForStorage, scrubLine, scrubUnit } from "./scrub.js";
20
+ /**
21
+ * The refusals of a LOCAL read that mean "this machine cannot reach the platform": the stored digest is the answer
22
+ * for them, in `cockpit logs` and in the MCP `logs_digest` alike.
23
+ */
24
+ export const LOCAL_ACCESS_REFUSALS = new Set([
25
+ "vercel_cli_missing", "vercel_not_logged_in", "vercel_scope_denied", "railway_cli_missing", "railway_not_logged_in", "railway_project_unreachable",
26
+ ]);
27
+ /** A window keeps at most this many templates; the rest are counted, never silently lost. */
28
+ export const STORED_MAX_TEMPLATES_PER_WINDOW = 200;
29
+ const iso = (epoch) => (epoch ? new Date(epoch * 1000).toISOString() : null);
30
+ /** Digests one window's lines and classifies every template with the project's table. */
31
+ export function digestLines(lines, options) {
32
+ const digest = new Digest({ noise: options.table.noiseUnits, taggedLines: true });
33
+ let rawChars = 0;
34
+ for (const line of lines) {
35
+ rawChars += line.message.length + 1;
36
+ // Storage path only: people are removed from each line BEFORE it is digested, so the template id is stable across
37
+ // borrowers and a cut can never land inside an email. The local `cockpit logs` digest does not do this.
38
+ digest.addLine(scrubUnit(line.unit), scrubLine(line.message), line.ts, { level: line.level });
39
+ }
40
+ const result = digest.result();
41
+ const all = classifyTemplates(result, options.table, options.family);
42
+ const cap = options.maxTemplates ?? STORED_MAX_TEMPLATES_PER_WINDOW;
43
+ return { lines: result.lines, noise: result.noise, rawChars, templates: all.slice(0, cap), dropped: Math.max(0, all.length - cap) };
44
+ }
45
+ /** Template rows ready to store: the redacted example and the masked template, never a raw line. */
46
+ export function toStoredRows(templates, window) {
47
+ return templates.map((template) => ({
48
+ ...window,
49
+ tid: template.tid,
50
+ unit: scrubUnit(template.unit),
51
+ class: template.class,
52
+ severity: template.severity,
53
+ // What is stored is a masked line, never a raw one (see scrub.ts).
54
+ template: scrubForStorage(template.template, STORED_TEMPLATE_CHARS),
55
+ example: scrubForStorage(template.example, STORED_EXAMPLE_CHARS),
56
+ count: template.count,
57
+ first_at: iso(template.first),
58
+ last_at: iso(template.last),
59
+ }));
60
+ }
61
+ /** A stored row as it may leave the table. */
62
+ export function scrubRow(row) {
63
+ return {
64
+ ...row,
65
+ unit: scrubUnit(row.unit),
66
+ template: scrubForStorage(row.template, STORED_TEMPLATE_CHARS),
67
+ example: scrubForStorage(row.example, STORED_EXAMPLE_CHARS),
68
+ };
69
+ }
70
+ /** The size of one stored row as JSON: what "bytes stored" counts. */
71
+ export function storedRowBytes(row) {
72
+ return Buffer.byteLength(JSON.stringify(row), "utf8");
73
+ }
74
+ const MAX_REFUSALS_NOTED = 4;
75
+ /** Many windows of stored rows merged by template id into one capped digest (about 2 KB, real bugs first). */
76
+ export function mergeStored(storedRows, windows, options) {
77
+ // Defence in depth: whatever wrote the rows, what leaves the table is scrubbed again (the scrub is idempotent).
78
+ const rows = storedRows.map(scrubRow);
79
+ const newestFirst = [...rows].sort((a, b) => (a.window_end < b.window_end ? 1 : a.window_end > b.window_end ? -1 : 0));
80
+ // The exact verdict of a template id (newest window wins), and a verdict by printed text for the renderer, which only
81
+ // sees unit and template: two ids whose scrubbed text is identical share it, and the WORSE class wins, so a
82
+ // collision can only make a line louder, never hide a bug.
83
+ const verdictOfTid = new Map();
84
+ const verdicts = new Map();
85
+ const sources = new Map();
86
+ for (const row of newestFirst) {
87
+ const key = `${row.unit}\x1f${row.template}`;
88
+ if (!verdictOfTid.has(row.tid))
89
+ verdictOfTid.set(row.tid, { class: row.class, severity: row.severity });
90
+ const known = verdicts.get(key);
91
+ if (!known || (CLASS_ORDER[row.class] ?? 0) < (CLASS_ORDER[known.class] ?? 0))
92
+ verdicts.set(key, { class: row.class, severity: row.severity });
93
+ const names = sources.get(row.tid) ?? new Set();
94
+ names.add(row.source);
95
+ sources.set(row.tid, names);
96
+ }
97
+ const groups = rows.map((row) => ({
98
+ tid: row.tid,
99
+ unit: row.unit,
100
+ event: "stored",
101
+ template: row.template,
102
+ count: row.count,
103
+ first: row.first_at ? Date.parse(row.first_at) / 1000 : null,
104
+ last: row.last_at ? Date.parse(row.last_at) / 1000 : null,
105
+ example: row.example,
106
+ instances: [],
107
+ }));
108
+ const okWindows = windows.filter((window) => window.status === "ok");
109
+ const lines = okWindows.reduce((sum, window) => sum + window.lines_read, 0);
110
+ const noise = okWindows.reduce((sum, window) => sum + window.noise, 0);
111
+ const merged = mergeResults([{ lines, noise, groups, span: [null, null] }]);
112
+ const refusals = [...new Set(windows.filter((window) => window.status !== "ok").map((window) => `${window.source}: ${window.status}`))];
113
+ const notes = [];
114
+ const spans = okWindows.map((window) => [Date.parse(window.window_start), Date.parse(window.window_end)]);
115
+ if (spans.length > 0) {
116
+ const from = new Date(Math.min(...spans.map((span) => span[0]))).toISOString().slice(0, 16);
117
+ const to = new Date(Math.max(...spans.map((span) => span[1]))).toISOString().slice(0, 16);
118
+ const names = new Set(okWindows.map((window) => window.source));
119
+ notes.push(`stored digests: ${okWindows.length} window${okWindows.length === 1 ? "" : "s"} of ${names.size} source${names.size === 1 ? "" : "s"}, ${from}Z to ${to}Z`);
120
+ }
121
+ else {
122
+ notes.push("stored digests: no window was read in this span (the cron has not run for this project yet, or every read was refused)");
123
+ }
124
+ if (refusals.length > 0) {
125
+ notes.push(`unread: ${refusals.slice(0, MAX_REFUSALS_NOTED).join("; ")}${refusals.length > MAX_REFUSALS_NOTED ? ` +${refusals.length - MAX_REFUSALS_NOTED}` : ""}`);
126
+ }
127
+ notes.push(...(options.extraNotes ?? []));
128
+ const text = renderCapped(merged, {
129
+ source: options.project,
130
+ window: options.label,
131
+ maxBytes: options.maxBytes,
132
+ notes,
133
+ classify: (unit, template) => {
134
+ const verdict = verdicts.get(`${unit}\x1f${template}`);
135
+ return { class: verdict?.class ?? "unknown", severity: (verdict?.severity ?? "ERROR"), pattern: null, note: "" };
136
+ },
137
+ });
138
+ const templates = merged.groups
139
+ .map((group) => {
140
+ const verdict = verdictOfTid.get(group.tid);
141
+ return {
142
+ tid: group.tid, unit: group.unit, class: verdict?.class ?? "unknown", severity: verdict?.severity ?? "ERROR", pattern: null,
143
+ count: group.count, first: group.first, last: group.last, template: group.template, example: group.example, instances: [],
144
+ sources: [...(sources.get(group.tid) ?? [])].sort(),
145
+ };
146
+ })
147
+ .sort((a, b) => (CLASS_ORDER[a.class] ?? 0) - (CLASS_ORDER[b.class] ?? 0) || b.count - a.count || (a.tid < b.tid ? -1 : 1));
148
+ return { text, templates, windows: windows.length, windows_ok: okWindows.length, lines, noise, refusals };
149
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.59",
3
+ "version": "0.1.60",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",