@checkstack/dashboards-backend 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,120 @@
1
+ import { z } from "zod";
2
+ import { qualifyAccessRuleId } from "@checkstack/common";
3
+ import { toJsonSchema } from "@checkstack/backend-api";
4
+ import {
5
+ BUILTIN_VISUALIZATION_SPECS,
6
+ DASHBOARD_GRID_COLUMNS,
7
+ DASHBOARD_MAX_PANELS,
8
+ DASHBOARD_WIDGET_PANEL_TYPE,
9
+ dashboardsAccess,
10
+ pluginMetadata,
11
+ } from "@checkstack/dashboards-common";
12
+ import type { RegisteredAiTool } from "@checkstack/ai-backend";
13
+ import type { BuildingBlocksRegistry } from "../building-blocks";
14
+ import { renderToolNames } from "./tool-names";
15
+
16
+ export const GetBuildingBlocksInputSchema = z.object({
17
+ dataSourceId: z
18
+ .string()
19
+ .optional()
20
+ .describe(
21
+ "Only describe this data source (e.g. metricstream.metric). Omit for everything.",
22
+ ),
23
+ });
24
+ export type GetBuildingBlocksInput = z.infer<typeof GetBuildingBlocksInputSchema>;
25
+
26
+ /**
27
+ * What a dashboard can be built from on THIS instance: the grid, every panel
28
+ * type with its options schema, every registered data source with its query
29
+ * schema and how to fill it, and every widget. Pure, so it is tested directly.
30
+ */
31
+ export function describeBuildingBlocks({
32
+ registry,
33
+ dataSourceId,
34
+ }: {
35
+ registry: BuildingBlocksRegistry;
36
+ dataSourceId?: string;
37
+ }) {
38
+ const dataSources = registry
39
+ .dataSources()
40
+ .filter((spec) => !dataSourceId || spec.dataSourceId === dataSourceId)
41
+ .map((spec) => ({
42
+ dataSourceId: spec.dataSourceId,
43
+ label: spec.label,
44
+ description: spec.description,
45
+ produces: spec.produces,
46
+ useFor: spec.ai.useFor,
47
+ howToFill: renderToolNames(spec.ai.howToFill),
48
+ requiredFields: spec.requiredFields,
49
+ querySchema: toJsonSchema(spec.querySchema, { io: "input" }),
50
+ exampleQuery: spec.ai.exampleQuery,
51
+ recommendedVisualizations: spec.ai.visualizations,
52
+ }));
53
+ if (dataSourceId) return { dataSources };
54
+
55
+ return {
56
+ grid: {
57
+ columns: DASHBOARD_GRID_COLUMNS,
58
+ rowHeightPx: 30,
59
+ maxPanels: DASHBOARD_MAX_PANELS,
60
+ rules:
61
+ "gridPos {x,y,w,h}: x+w <= 24, panels must not overlap, y grows downward. Common widths: 24 (full), 12 (half), 8 (third), 6 (quarter).",
62
+ },
63
+ visualizations: Object.values(BUILTIN_VISUALIZATION_SPECS).map((spec) => ({
64
+ type: spec.visualizationId,
65
+ label: spec.label,
66
+ description: spec.description,
67
+ useFor: spec.useFor,
68
+ acceptsQueries: spec.acceptsQueries,
69
+ renders: spec.accepts,
70
+ defaultSize: spec.defaultSize,
71
+ ...(spec.minSize ? { minSize: spec.minSize } : {}),
72
+ optionsSchema: toJsonSchema(spec.optionsSchema, { io: "input" }),
73
+ })),
74
+ dataSources,
75
+ widgets: {
76
+ panelType: DASHBOARD_WIDGET_PANEL_TYPE,
77
+ usage:
78
+ 'A widget panel has type "dashboards.widget", no queries and options { widgetId, height: "auto" }. Widgets show platform-wide sections and suit global/home dashboards.',
79
+ available: registry.widgets(),
80
+ },
81
+ examplePanel: {
82
+ id: "latency",
83
+ type: BUILTIN_VISUALIZATION_SPECS.timeseries.visualizationId,
84
+ title: "Latency",
85
+ gridPos: { x: 0, y: 2, w: 12, h: 8 },
86
+ queries: [
87
+ {
88
+ refId: "A",
89
+ dataSourceId: "healthcheck.metrics",
90
+ query: { configurationId: "", metric: "latencyAvg" },
91
+ },
92
+ ],
93
+ options: { style: "line", unit: "ms" },
94
+ },
95
+ };
96
+ }
97
+
98
+ /** `dashboards.getBuildingBlocks` - discovery for dashboard drafting. */
99
+ export function createGetBuildingBlocksTool({
100
+ registry,
101
+ }: {
102
+ registry: BuildingBlocksRegistry;
103
+ }): RegisteredAiTool<GetBuildingBlocksInput, unknown> {
104
+ return {
105
+ name: "dashboards.getBuildingBlocks",
106
+ description:
107
+ "Describe what dashboards can be built from: the 24-column grid, every panel type (visualization) with its options, every data source (health checks, metrics, logs, traces, SLOs, ...) with its query schema, an example query and which tools find the ids it needs, and the widgets for home dashboards. Call this before drafting a dashboard with {{tool:dashboards.propose}}.",
108
+ effect: "read",
109
+ input: GetBuildingBlocksInputSchema,
110
+ requiredAccessRules: [
111
+ qualifyAccessRuleId(pluginMetadata, dashboardsAccess.dashboard.read),
112
+ ],
113
+ async execute({ input }) {
114
+ return describeBuildingBlocks({
115
+ registry,
116
+ dataSourceId: input.dataSourceId,
117
+ });
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,121 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { Panel } from "@checkstack/dashboards-common";
3
+ import { renderLayoutPreview, validateDashboardDraft } from "./draft-validation";
4
+ import { metricPanel, testRegistry } from "./test-fixtures";
5
+
6
+ const validate = ({
7
+ panels,
8
+ dashboardSystemId = "sys-1",
9
+ }: {
10
+ panels: Panel[];
11
+ dashboardSystemId?: string | null;
12
+ }) => validateDashboardDraft({ panels, dashboardSystemId, registry: testRegistry() });
13
+
14
+ const paths = (issues: Array<{ path: string }>) => issues.map((i) => i.path);
15
+
16
+ describe("validateDashboardDraft", () => {
17
+ it("accepts a valid layout", () => {
18
+ const result = validate({
19
+ panels: [
20
+ { id: "s", type: "dashboards.section", title: "Load", gridPos: { x: 0, y: 0, w: 24, h: 2 }, queries: [], options: {} },
21
+ metricPanel({ id: "a", gridPos: { x: 0, y: 2, w: 12, h: 8 } }),
22
+ metricPanel({ id: "b", gridPos: { x: 12, y: 2, w: 12, h: 8 } }),
23
+ ],
24
+ });
25
+ expect(result).toEqual({ errors: [], warnings: [] });
26
+ });
27
+
28
+ it("rejects overlapping and out-of-grid panels", () => {
29
+ const { errors } = validate({
30
+ panels: [
31
+ metricPanel({ id: "a", gridPos: { x: 0, y: 0, w: 12, h: 8 } }),
32
+ metricPanel({ id: "b", gridPos: { x: 6, y: 4, w: 12, h: 8 } }),
33
+ metricPanel({ id: "c", gridPos: { x: 20, y: 20, w: 8, h: 8 } }),
34
+ ],
35
+ });
36
+ expect(paths(errors)).toEqual(["panels[2].gridPos", "panels[1].gridPos"]);
37
+ expect(errors[1].message).toContain('overlaps panel "a"');
38
+ });
39
+
40
+ it("rejects unknown panel types and data sources with the valid choices", () => {
41
+ const panel = metricPanel({ id: "a" });
42
+ const { errors } = validate({
43
+ panels: [
44
+ { ...panel, type: "dashboards.piechart" },
45
+ { ...metricPanel({ id: "b", gridPos: { x: 12, y: 0, w: 12, h: 8 } }), queries: [{ ...panel.queries[0], dataSourceId: "prometheus.query" }] },
46
+ ],
47
+ });
48
+ expect(paths(errors)).toEqual(["panels[0].type", "panels[1].queries[0].dataSourceId"]);
49
+ expect(errors[0].message).toContain("dashboards.timeseries");
50
+ expect(errors[1].message).toContain("metricstream.metric");
51
+ });
52
+
53
+ it("rejects empty required query fields and bad option values", () => {
54
+ const { errors } = validate({
55
+ panels: [{ ...metricPanel({ id: "a", query: { streamId: "s1" } }), options: { style: "pie" } }],
56
+ });
57
+ expect(paths(errors)).toEqual(["panels[0].options.style", "panels[0].queries[0].query"]);
58
+ // One message per query, with the fill guide's tool names rendered.
59
+ expect(errors[1].message).toContain('needs "metricName"');
60
+ expect(errors[1].message).toContain("metricstream_listStreamsForSystem");
61
+ expect(errors[1].message).not.toContain("{{tool:");
62
+ });
63
+
64
+ it("requires a system per query on a global dashboard", () => {
65
+ const { errors } = validate({ panels: [metricPanel({ id: "a" })], dashboardSystemId: null });
66
+ expect(paths(errors)).toEqual(["panels[0].queries[0].systemId"]);
67
+ });
68
+
69
+ it("validates widget panels", () => {
70
+ const widget = (widgetId: string, y: number): Panel => ({
71
+ id: `w${y}`,
72
+ type: "dashboards.widget",
73
+ title: "",
74
+ gridPos: { x: 0, y, w: 24, h: 6 },
75
+ queries: [],
76
+ options: { widgetId },
77
+ });
78
+ const result = validate({
79
+ panels: [widget("dashboard.system-health", 0), widget("", 6), widget("acme.unknown", 12)],
80
+ dashboardSystemId: null,
81
+ });
82
+ expect(paths(result.errors)).toEqual(["panels[1].options.widgetId"]);
83
+ expect(paths(result.warnings)).toEqual(["panels[2].options.widgetId"]);
84
+ });
85
+
86
+ it("warns about unreadable or empty panels and ignored fields", () => {
87
+ const { errors, warnings } = validate({
88
+ panels: [
89
+ metricPanel({ id: "tiny", gridPos: { x: 0, y: 0, w: 2, h: 2 }, query: { streamId: "s1", metricName: "cpu", metric: "x" } }),
90
+ { ...metricPanel({ id: "empty", gridPos: { x: 2, y: 0, w: 12, h: 8 } }), queries: [] },
91
+ ],
92
+ });
93
+ expect(errors).toEqual([]);
94
+ expect(paths(warnings)).toEqual([
95
+ "panels[0].gridPos",
96
+ "panels[0].queries[0].query.metric",
97
+ "panels[1].queries",
98
+ ]);
99
+ });
100
+ });
101
+
102
+ describe("renderLayoutPreview", () => {
103
+ it("draws each panel with its letter and lists them", () => {
104
+ const preview = renderLayoutPreview({
105
+ panels: [
106
+ metricPanel({ id: "a", gridPos: { x: 0, y: 0, w: 12, h: 1 } }),
107
+ metricPanel({ id: "b", gridPos: { x: 12, y: 0, w: 12, h: 2 } }),
108
+ ],
109
+ });
110
+ const [grid, legend] = preview.split("\n\n");
111
+ expect(grid.split("\n")).toEqual([
112
+ "AAAAAAAAAAAABBBBBBBBBBBB",
113
+ "............BBBBBBBBBBBB",
114
+ ]);
115
+ expect(legend).toContain("A = CPU [timeseries] 12x1 at (0,0)");
116
+ });
117
+
118
+ it("handles an empty dashboard", () => {
119
+ expect(renderLayoutPreview({ panels: [] })).toBe("(no panels)");
120
+ });
121
+ });
@@ -0,0 +1,301 @@
1
+ import { z } from "zod";
2
+ import {
3
+ BUILTIN_VISUALIZATION_SPECS,
4
+ DASHBOARD_GRID_COLUMNS,
5
+ DASHBOARD_WIDGET_PANEL_TYPE,
6
+ WidgetPanelOptionsSchema,
7
+ type DashboardVisualizationSpec,
8
+ type Panel,
9
+ } from "@checkstack/dashboards-common";
10
+ import type { BuildingBlocksRegistry } from "../building-blocks";
11
+ import { renderToolNames } from "./tool-names";
12
+
13
+ /**
14
+ * Pure validation of an AI-drafted dashboard against the building blocks
15
+ * registered on this instance. Errors block the proposal; warnings are shown
16
+ * with it (they flag drafts that would work but read badly).
17
+ */
18
+
19
+ export interface DraftIssue {
20
+ /** Where, e.g. `panels[2].queries[0].query.metricName`. */
21
+ path: string;
22
+ message: string;
23
+ }
24
+
25
+ export interface DraftValidation {
26
+ errors: DraftIssue[];
27
+ warnings: DraftIssue[];
28
+ }
29
+
30
+ const VISUALIZATIONS: Record<string, DashboardVisualizationSpec> =
31
+ Object.fromEntries(
32
+ Object.values(BUILTIN_VISUALIZATION_SPECS).map((spec) => [
33
+ spec.visualizationId,
34
+ spec,
35
+ ]),
36
+ );
37
+
38
+ /** Panel types an agent may use: the built-in visualizations and widgets. */
39
+ export function knownPanelTypes(): string[] {
40
+ return [...Object.keys(VISUALIZATIONS), DASHBOARD_WIDGET_PANEL_TYPE];
41
+ }
42
+
43
+ /** Smallest readable size of a card panel with data. */
44
+ const MIN_DATA_PANEL = { w: 3, h: 3 };
45
+
46
+ function zodIssues({
47
+ error,
48
+ prefix,
49
+ }: {
50
+ error: z.ZodError;
51
+ prefix: string;
52
+ }): DraftIssue[] {
53
+ return error.issues.map((issue) => ({
54
+ path: [prefix, ...issue.path.map(String)].join("."),
55
+ message: issue.message,
56
+ }));
57
+ }
58
+
59
+ /** Keys the agent sent that the schema does not know (they would be dropped). */
60
+ function unknownKeys({
61
+ schema,
62
+ value,
63
+ }: {
64
+ schema: z.ZodType;
65
+ value: Record<string, unknown>;
66
+ }): string[] {
67
+ if (!(schema instanceof z.ZodObject)) return [];
68
+ const known = new Set(Object.keys(schema.shape));
69
+ return Object.keys(value).filter((key) => !known.has(key));
70
+ }
71
+
72
+ function overlaps(a: Panel["gridPos"], b: Panel["gridPos"]): boolean {
73
+ return (
74
+ a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
75
+ );
76
+ }
77
+
78
+ function validateQueries({
79
+ panel,
80
+ path,
81
+ viz,
82
+ dashboardSystemId,
83
+ registry,
84
+ errors,
85
+ warnings,
86
+ }: {
87
+ panel: Panel;
88
+ path: string;
89
+ viz: DashboardVisualizationSpec;
90
+ dashboardSystemId: string | null;
91
+ registry: BuildingBlocksRegistry;
92
+ errors: DraftIssue[];
93
+ warnings: DraftIssue[];
94
+ }): void {
95
+ if (panel.queries.length === 0) {
96
+ warnings.push({
97
+ path: `${path}.queries`,
98
+ message: `"${viz.label}" panel has no queries, so it shows no data. Add a query (see dashboards_getBuildingBlocks for data sources).`,
99
+ });
100
+ return;
101
+ }
102
+ const refIds = new Set<string>();
103
+ for (const [qi, query] of panel.queries.entries()) {
104
+ const qPath = `${path}.queries[${qi}]`;
105
+ if (refIds.has(query.refId)) {
106
+ errors.push({ path: `${qPath}.refId`, message: `Duplicate refId "${query.refId}" in this panel; use A, B, C, ...` });
107
+ }
108
+ refIds.add(query.refId);
109
+
110
+ const source = registry.getDataSource(query.dataSourceId);
111
+ if (!source) {
112
+ const ids = registry.dataSources().map((s) => s.dataSourceId);
113
+ errors.push({
114
+ path: `${qPath}.dataSourceId`,
115
+ message: `Unknown data source "${query.dataSourceId}". Available: ${ids.join(", ") || "none"}.`,
116
+ });
117
+ continue;
118
+ }
119
+ if (dashboardSystemId === null && !query.systemId) {
120
+ errors.push({
121
+ path: `${qPath}.systemId`,
122
+ message: "This dashboard has no system, so every query needs its own systemId (find it with catalog_listSystems).",
123
+ });
124
+ }
125
+ const parsed = source.querySchema.safeParse(query.query);
126
+ if (!parsed.success) {
127
+ errors.push(...zodIssues({ error: parsed.error, prefix: `${qPath}.query` }));
128
+ continue;
129
+ }
130
+ for (const key of unknownKeys({ schema: source.querySchema, value: query.query })) {
131
+ warnings.push({
132
+ path: `${qPath}.query.${key}`,
133
+ message: `"${key}" is not a field of ${source.dataSourceId} and is ignored.`,
134
+ });
135
+ }
136
+ const missing = source.requiredFields.filter((field) => {
137
+ const value = parsed.data[field];
138
+ return value === undefined || value === null || value === "";
139
+ });
140
+ if (missing.length > 0) {
141
+ errors.push({
142
+ path: `${qPath}.query`,
143
+ message: `${source.dataSourceId} needs ${missing.map((f) => `"${f}"`).join(" and ")}. ${renderToolNames(source.ai.howToFill)}`,
144
+ });
145
+ }
146
+ if (!source.produces.some((kind) => viz.accepts.includes(kind))) {
147
+ warnings.push({
148
+ path: qPath,
149
+ message: `${source.dataSourceId} produces ${source.produces.join("/")} data, which "${viz.label}" does not render well. Better: ${source.ai.visualizations.join(", ")}.`,
150
+ });
151
+ }
152
+ }
153
+ }
154
+
155
+ function validatePanelBody({
156
+ panel,
157
+ path,
158
+ dashboardSystemId,
159
+ registry,
160
+ errors,
161
+ warnings,
162
+ }: {
163
+ panel: Panel;
164
+ path: string;
165
+ dashboardSystemId: string | null;
166
+ registry: BuildingBlocksRegistry;
167
+ errors: DraftIssue[];
168
+ warnings: DraftIssue[];
169
+ }): void {
170
+ if (panel.type === DASHBOARD_WIDGET_PANEL_TYPE) {
171
+ const options = WidgetPanelOptionsSchema.safeParse(panel.options);
172
+ if (!options.success) {
173
+ errors.push(...zodIssues({ error: options.error, prefix: `${path}.options` }));
174
+ return;
175
+ }
176
+ if (panel.queries.length > 0) {
177
+ errors.push({ path: `${path}.queries`, message: "Widget panels fetch their own data; remove the queries." });
178
+ }
179
+ const widgetIds = registry.widgets().map((w) => w.widgetId);
180
+ if (options.data.widgetId === "") {
181
+ errors.push({ path: `${path}.options.widgetId`, message: `Set options.widgetId to one of: ${widgetIds.join(", ")}.` });
182
+ } else if (!registry.getWidget(options.data.widgetId)) {
183
+ warnings.push({
184
+ path: `${path}.options.widgetId`,
185
+ message: `"${options.data.widgetId}" is not a known widget (known: ${widgetIds.join(", ")}); it renders nothing unless a frontend plugin provides it.`,
186
+ });
187
+ }
188
+ return;
189
+ }
190
+
191
+ const viz = VISUALIZATIONS[panel.type];
192
+ if (!viz) {
193
+ errors.push({ path: `${path}.type`, message: `Unknown panel type "${panel.type}". Use one of: ${knownPanelTypes().join(", ")}.` });
194
+ return;
195
+ }
196
+ const options = viz.optionsSchema.safeParse(panel.options);
197
+ if (!options.success) {
198
+ errors.push(...zodIssues({ error: options.error, prefix: `${path}.options` }));
199
+ }
200
+ for (const key of unknownKeys({ schema: viz.optionsSchema, value: panel.options })) {
201
+ warnings.push({ path: `${path}.options.${key}`, message: `"${key}" is not an option of ${viz.visualizationId} and is ignored.` });
202
+ }
203
+ if (!viz.acceptsQueries) {
204
+ if (panel.queries.length > 0) {
205
+ errors.push({ path: `${path}.queries`, message: `"${viz.label}" panels take no queries; remove them.` });
206
+ }
207
+ if (viz.id === "section" && panel.title.trim() === "") {
208
+ warnings.push({ path: `${path}.title`, message: "A section header shows its title; set one." });
209
+ }
210
+ return;
211
+ }
212
+ if (panel.gridPos.w < MIN_DATA_PANEL.w || panel.gridPos.h < MIN_DATA_PANEL.h) {
213
+ warnings.push({
214
+ path: `${path}.gridPos`,
215
+ message: `${panel.gridPos.w}x${panel.gridPos.h} is too small to read; use at least ${viz.defaultSize.w}x${viz.defaultSize.h} (the default) or ${MIN_DATA_PANEL.w}x${MIN_DATA_PANEL.h}.`,
216
+ });
217
+ }
218
+ validateQueries({ panel, path, viz, dashboardSystemId, registry, errors, warnings });
219
+ }
220
+
221
+ /**
222
+ * Validate a drafted panel list. `dashboardSystemId` is the dashboard's own
223
+ * system (null for a global dashboard, whose queries must each name one).
224
+ */
225
+ export function validateDashboardDraft({
226
+ panels,
227
+ dashboardSystemId,
228
+ registry,
229
+ }: {
230
+ panels: Panel[];
231
+ dashboardSystemId: string | null;
232
+ registry: BuildingBlocksRegistry;
233
+ }): DraftValidation {
234
+ const errors: DraftIssue[] = [];
235
+ const warnings: DraftIssue[] = [];
236
+
237
+ const ids = new Set<string>();
238
+ for (const [index, panel] of panels.entries()) {
239
+ const path = `panels[${index}]`;
240
+ if (ids.has(panel.id)) {
241
+ errors.push({ path: `${path}.id`, message: `Duplicate panel id "${panel.id}".` });
242
+ }
243
+ ids.add(panel.id);
244
+ if (panel.gridPos.x + panel.gridPos.w > DASHBOARD_GRID_COLUMNS) {
245
+ errors.push({
246
+ path: `${path}.gridPos`,
247
+ message: `x + w = ${panel.gridPos.x + panel.gridPos.w} exceeds the ${DASHBOARD_GRID_COLUMNS}-column grid.`,
248
+ });
249
+ }
250
+ validatePanelBody({ panel, path, dashboardSystemId, registry, errors, warnings });
251
+ }
252
+
253
+ for (let i = 0; i < panels.length; i++) {
254
+ for (let j = i + 1; j < panels.length; j++) {
255
+ if (overlaps(panels[i].gridPos, panels[j].gridPos)) {
256
+ errors.push({
257
+ path: `panels[${j}].gridPos`,
258
+ message: `Panel "${panels[j].id}" overlaps panel "${panels[i].id}". Place it beside it (x) or below it (y >= ${panels[i].gridPos.y + panels[i].gridPos.h}).`,
259
+ });
260
+ }
261
+ }
262
+ }
263
+
264
+ return { errors, warnings };
265
+ }
266
+
267
+ const PREVIEW_MAX_ROWS = 80;
268
+ const PANEL_MARKS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
269
+
270
+ /**
271
+ * A text picture of the grid: one character per column, one line per row,
272
+ * each panel drawn with its letter - so a reviewer (and the model) can see the
273
+ * layout without rendering it.
274
+ */
275
+ export function renderLayoutPreview({ panels }: { panels: Panel[] }): string {
276
+ if (panels.length === 0) return "(no panels)";
277
+ const bottom = Math.min(
278
+ PREVIEW_MAX_ROWS,
279
+ Math.max(...panels.map((p) => p.gridPos.y + p.gridPos.h)),
280
+ );
281
+ const rows = Array.from({ length: bottom }, () =>
282
+ Array.from({ length: DASHBOARD_GRID_COLUMNS }, () => "."),
283
+ );
284
+ const legend: string[] = [];
285
+ for (const [index, panel] of panels.entries()) {
286
+ const mark = PANEL_MARKS[index % PANEL_MARKS.length];
287
+ const { x, y, w, h } = panel.gridPos;
288
+ for (let row = y; row < Math.min(y + h, bottom); row++) {
289
+ for (let col = x; col < Math.min(x + w, DASHBOARD_GRID_COLUMNS); col++) {
290
+ rows[row][col] = mark;
291
+ }
292
+ }
293
+ const kind =
294
+ panel.type === DASHBOARD_WIDGET_PANEL_TYPE
295
+ ? `widget ${String(panel.options.widgetId ?? "")}`
296
+ : panel.type.replace(/^dashboards\./, "");
297
+ legend.push(`${mark} = ${panel.title || "(untitled)"} [${kind}] ${w}x${h} at (${x},${y})`);
298
+ }
299
+ const grid = rows.map((cols) => cols.join("")).join("\n");
300
+ return `${grid}\n\n${legend.join("\n")}`;
301
+ }
@@ -0,0 +1,65 @@
1
+ import type { AiGuidanceSection } from "@checkstack/ai-backend";
2
+
3
+ /**
4
+ * How to build a good dashboard: the discover -> draft -> propose tool chain
5
+ * and the layout conventions the UI follows. Contributed through
6
+ * `aiGuidanceExtensionPoint`, so it is in the chat / headless prompt and the
7
+ * MCP instructions only for principals who can use the dashboard tools.
8
+ */
9
+ export const DASHBOARD_BUILDING_INSTRUCTION =
10
+ "To build or change a dashboard, discover first, then draft, then propose. " +
11
+ "1) Discover: call {{tool:dashboards.getBuildingBlocks}} for the panel types, " +
12
+ "data sources (with their query fields and example queries) and widgets. " +
13
+ "Resolve the system with {{tool:catalog.listSystems}}, then find what it " +
14
+ "actually has: checks via {{tool:healthcheck.listSystemChecks}}, metric " +
15
+ "streams via {{tool:metricstream.listStreamsForSystem}} and metric names via " +
16
+ "{{tool:metricstream.listMetricNames}}, log streams via " +
17
+ "{{tool:logstream.listStreamsForSystem}}, trace streams via " +
18
+ "{{tool:tracestream.listStreamsForSystem}}, and SLOs via " +
19
+ "{{tool:slo.getObjectivesForSystem}}. Only chart what exists; never invent " +
20
+ "ids or metric names. " +
21
+ "2) Draft a layout a person can scan top to bottom: a row of 3-4 Stat panels " +
22
+ "(w 6, h 5) with the headline numbers first (status, availability, latency, " +
23
+ "error count), then the trends as Time series panels in pairs (w 12, h 8), " +
24
+ "then details such as logs (w 24) or tables. Group related panels under a " +
25
+ 'Section header panel ("dashboards.section", w 24, h 2, the title is the ' +
26
+ "heading). Give every panel a short title that says what it shows, set " +
27
+ 'units (ms, percent) and use style "bars" for counts and "line" for ' +
28
+ "measurements. Prefer fewer, meaningful panels over one per metric. Panels " +
29
+ "sit on a 24-column grid, must not overlap and must fit (x + w <= 24). " +
30
+ "3) Propose with {{tool:dashboards.propose}}. It validates the draft and " +
31
+ "returns every problem at once; fix them all and propose again. The " +
32
+ "operator reviews a layout picture and approves. " +
33
+ "4) Check your work. The applied result (and {{tool:dashboards.inspect}} for any " +
34
+ "dashboard) has a text picture of the layout and the URL to open it. If you have " +
35
+ "browser tools and can see images, open the URL, take a screenshot once the " +
36
+ "panels have loaded and fix what looks wrong: empty or erroring panels, unreadable " +
37
+ "or cramped panels, ragged rows. When the browser is not signed in, open the " +
38
+ "returned signInUrl and ask the user to sign in there themselves; never ask for or " +
39
+ "type their password. " +
40
+ "To edit a dashboard, find it with {{tool:dashboards.listDashboards}}, read " +
41
+ "it with {{tool:dashboards.getDashboard}}, change the panel list and pass " +
42
+ "dashboardId with the complete new panel list, keeping the ids of panels you " +
43
+ "did not change. A system dashboard sets systemId once; a global or home " +
44
+ "dashboard omits it and sets systemId on each query, and may use widgets " +
45
+ "(type dashboards.widget). To make a dashboard the start page use " +
46
+ "{{tool:dashboards.setMyHomeDashboard}} (just for the operator) or " +
47
+ "{{tool:dashboards.setGlobalHomeDashboard}} (for everyone).";
48
+
49
+ /** The tools whose availability makes the dashboard playbook relevant. */
50
+ export const DASHBOARD_BUILDING_TOOLS = [
51
+ "dashboards.propose",
52
+ "dashboards.getBuildingBlocks",
53
+ ];
54
+
55
+ /** Guidance sections the dashboards plugin contributes. */
56
+ export function buildDashboardsGuidance(): AiGuidanceSection[] {
57
+ return [
58
+ {
59
+ id: "building-dashboards",
60
+ title: "Building dashboards",
61
+ body: DASHBOARD_BUILDING_INSTRUCTION,
62
+ tools: DASHBOARD_BUILDING_TOOLS,
63
+ },
64
+ ];
65
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from "zod";
2
+ import { qualifyAccessRuleId } from "@checkstack/common";
3
+ import {
4
+ DashboardsApi,
5
+ dashboardsAccess,
6
+ pluginMetadata,
7
+ } from "@checkstack/dashboards-common";
8
+ import type { RegisteredAiTool } from "@checkstack/ai-backend";
9
+ import { renderLayoutPreview } from "./draft-validation";
10
+ import {
11
+ VISUAL_INSPECTION_STEPS,
12
+ dashboardViewLinks,
13
+ type DashboardViewLinks,
14
+ } from "./view-links";
15
+
16
+ export const InspectDashboardInputSchema = z.object({
17
+ dashboardId: z.string().min(1).describe("The dashboard to inspect"),
18
+ });
19
+ export type InspectDashboardInput = z.infer<typeof InspectDashboardInputSchema>;
20
+
21
+ export interface InspectDashboardResult {
22
+ title: string;
23
+ panelCount: number;
24
+ links: DashboardViewLinks;
25
+ /** Text picture of the grid, one letter per panel. */
26
+ layoutPreview: string;
27
+ /** How to check it in a browser tool. */
28
+ visualInspection: string;
29
+ }
30
+
31
+ /**
32
+ * `dashboards.inspect` - the links to open a dashboard in a browser tool, the
33
+ * steps to check it visually, and a text picture of its layout (for agents
34
+ * without vision). Reads the dashboard as the user, so it only answers for
35
+ * dashboards the user can view.
36
+ */
37
+ export function createInspectDashboardTool({
38
+ baseUrl,
39
+ }: {
40
+ baseUrl: () => string;
41
+ }): RegisteredAiTool<InspectDashboardInput, InspectDashboardResult> {
42
+ return {
43
+ name: "dashboards.inspect",
44
+ description:
45
+ "Look at a dashboard you built or changed: returns a text picture of its layout, the URL to open it in a browser tool (plus a sign-in link that returns to it, and a public link for public dashboards) and the steps to check it visually with a screenshot. Find the dashboard id with {{tool:dashboards.listDashboards}}.",
46
+ effect: "read",
47
+ input: InspectDashboardInputSchema,
48
+ requiredAccessRules: [
49
+ qualifyAccessRuleId(pluginMetadata, dashboardsAccess.dashboard.read),
50
+ ],
51
+ async execute({ input, rpcClient }) {
52
+ const dashboard = await rpcClient
53
+ .forPlugin(DashboardsApi)
54
+ .getDashboard({ id: input.dashboardId });
55
+ if (!dashboard) {
56
+ throw new Error(
57
+ `Dashboard ${input.dashboardId} was not found or you cannot view it. Find ids with dashboards_listDashboards.`,
58
+ );
59
+ }
60
+ return {
61
+ title: dashboard.title,
62
+ panelCount: dashboard.panels.length,
63
+ links: dashboardViewLinks({ baseUrl: baseUrl(), dashboard }),
64
+ layoutPreview: renderLayoutPreview({ panels: dashboard.panels }),
65
+ visualInspection: VISUAL_INSPECTION_STEPS,
66
+ };
67
+ },
68
+ };
69
+ }