@tellagen/mcp-server 0.5.1 → 0.7.0

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.
Files changed (123) hide show
  1. package/README.md +53 -3
  2. package/SKILL.md +143 -19
  3. package/contracts/mcp-protocol.json +64 -3
  4. package/contracts/runbooks/manifest.json +24 -14
  5. package/contracts/runbooks/v2/client-protocol.json +65 -2
  6. package/contracts/runbooks/v2/client-writes.guidance.json +16 -1
  7. package/contracts/runbooks/v2/fixtures/filesystem-pressure.json +22 -31
  8. package/contracts/runbooks/v2/fixtures/timeline-event-blocks-rejected.json +15 -1
  9. package/contracts/runbooks/v2/investigation-window.guidance.json +45 -0
  10. package/contracts/runbooks/v2/question-checks.guidance.json +49 -0
  11. package/contracts/runbooks/v2/result-summary.guidance.json +53 -5
  12. package/contracts/runbooks/v2/timeline-event-blocks.schema.json +66 -3
  13. package/contracts/tellagen-runbook-contracts.json +3 -3
  14. package/dist/active-run.d.ts +6 -0
  15. package/dist/active-run.js +14 -0
  16. package/dist/active-run.js.map +1 -1
  17. package/dist/cli/doctor.d.ts +19 -0
  18. package/dist/cli/doctor.js +179 -0
  19. package/dist/cli/doctor.js.map +1 -0
  20. package/dist/cli/kubernetes.d.ts +47 -0
  21. package/dist/cli/kubernetes.js +369 -0
  22. package/dist/cli/kubernetes.js.map +1 -0
  23. package/dist/cli/main.js +10 -0
  24. package/dist/cli/main.js.map +1 -1
  25. package/dist/diagnosis-structure.d.ts +380 -102
  26. package/dist/diagnosis-structure.js +334 -14
  27. package/dist/diagnosis-structure.js.map +1 -1
  28. package/dist/doctor/checks.d.ts +42 -0
  29. package/dist/doctor/checks.js +181 -0
  30. package/dist/doctor/checks.js.map +1 -0
  31. package/dist/doctor/config-files.d.ts +49 -0
  32. package/dist/doctor/config-files.js +121 -0
  33. package/dist/doctor/config-files.js.map +1 -0
  34. package/dist/doctor/k8s-read-only.d.ts +16 -0
  35. package/dist/doctor/k8s-read-only.js +89 -0
  36. package/dist/doctor/k8s-read-only.js.map +1 -0
  37. package/dist/doctor/real-fs.d.ts +3 -0
  38. package/dist/doctor/real-fs.js +36 -0
  39. package/dist/doctor/real-fs.js.map +1 -0
  40. package/dist/doctor/toml.d.ts +13 -0
  41. package/dist/doctor/toml.js +205 -0
  42. package/dist/doctor/toml.js.map +1 -0
  43. package/dist/figures.d.ts +520 -101
  44. package/dist/figures.js +341 -7
  45. package/dist/figures.js.map +1 -1
  46. package/dist/heartbeat.d.ts +3 -0
  47. package/dist/heartbeat.js +32 -1
  48. package/dist/heartbeat.js.map +1 -1
  49. package/dist/index.js +1 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/k8s-safety.d.ts +42 -0
  52. package/dist/k8s-safety.js +33 -0
  53. package/dist/k8s-safety.js.map +1 -0
  54. package/dist/listen-config.d.ts +5 -5
  55. package/dist/listen-probe.d.ts +14 -1
  56. package/dist/listen-probe.js +83 -5
  57. package/dist/listen-probe.js.map +1 -1
  58. package/dist/listen-settings.d.ts +8 -0
  59. package/dist/listen-settings.js +29 -0
  60. package/dist/listen-settings.js.map +1 -1
  61. package/dist/listener.d.ts +11 -0
  62. package/dist/listener.js +60 -16
  63. package/dist/listener.js.map +1 -1
  64. package/dist/log-lines.d.ts +118 -0
  65. package/dist/log-lines.js +534 -0
  66. package/dist/log-lines.js.map +1 -0
  67. package/dist/redact.d.ts +21 -0
  68. package/dist/redact.js +212 -5
  69. package/dist/redact.js.map +1 -1
  70. package/dist/run-events.js +13 -1
  71. package/dist/run-events.js.map +1 -1
  72. package/dist/run-requests.d.ts +16 -0
  73. package/dist/run-requests.js +56 -0
  74. package/dist/run-requests.js.map +1 -0
  75. package/dist/run-window.d.ts +59 -0
  76. package/dist/run-window.js +141 -0
  77. package/dist/run-window.js.map +1 -0
  78. package/dist/server.d.ts +1 -1
  79. package/dist/server.js +11 -9
  80. package/dist/server.js.map +1 -1
  81. package/dist/session.d.ts +37 -0
  82. package/dist/session.js +59 -0
  83. package/dist/session.js.map +1 -1
  84. package/dist/tool-report.d.ts +2 -0
  85. package/dist/tool-report.js +3 -0
  86. package/dist/tool-report.js.map +1 -0
  87. package/dist/tools/amendments.d.ts +13 -0
  88. package/dist/tools/amendments.js +206 -0
  89. package/dist/tools/amendments.js.map +1 -0
  90. package/dist/tools/catalog.js +4 -0
  91. package/dist/tools/catalog.js.map +1 -1
  92. package/dist/tools/diagnostics.js +131 -3
  93. package/dist/tools/diagnostics.js.map +1 -1
  94. package/dist/tools/figures.d.ts +2 -2
  95. package/dist/tools/figures.js +37 -9
  96. package/dist/tools/figures.js.map +1 -1
  97. package/dist/tools/findings.d.ts +136 -0
  98. package/dist/tools/findings.js +68 -7
  99. package/dist/tools/findings.js.map +1 -1
  100. package/dist/tools/index.js +4 -0
  101. package/dist/tools/index.js.map +1 -1
  102. package/dist/tools/investigations.d.ts +3223 -5
  103. package/dist/tools/investigations.js +202 -50
  104. package/dist/tools/investigations.js.map +1 -1
  105. package/dist/tools/next.d.ts +16 -0
  106. package/dist/tools/next.js +49 -1
  107. package/dist/tools/next.js.map +1 -1
  108. package/dist/tools/postmortem-runbooks.d.ts +20 -20
  109. package/dist/tools/requests.d.ts +3 -0
  110. package/dist/tools/requests.js +62 -0
  111. package/dist/tools/requests.js.map +1 -0
  112. package/dist/tools/resume.js +14 -1
  113. package/dist/tools/resume.js.map +1 -1
  114. package/dist/tools/source-links.d.ts +7 -0
  115. package/dist/tools/source-links.js +32 -5
  116. package/dist/tools/source-links.js.map +1 -1
  117. package/dist/tools/timeline.js +24 -2
  118. package/dist/tools/timeline.js.map +1 -1
  119. package/dist/version.d.ts +4 -2
  120. package/dist/version.js +6 -1
  121. package/dist/version.js.map +1 -1
  122. package/package.json +1 -1
  123. package/server.json +1 -1
package/dist/figures.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { diffHunksFromPatch, diffShapeAdvice, hasDiffLineDetail, MAX_DIFF_CHANGED_LINES, MAX_DIFF_CONTEXT_EDGE, MAX_DIFF_CONTEXT_GAP, MAX_SELECTED_HUNKS, withoutDiffLineDetail, } from "./diff-figure.js";
3
+ import { MAX_LOG_COUNT, MAX_LOG_FIELD_KEY, MAX_LOG_FIELD_VALUE, MAX_LOG_FIELDS, MAX_LOG_LINES, MAX_LOG_NOTE, MAX_LOG_TEXT, readLogEntries, relationCounts, selectLogLines, } from "./log-lines.js";
4
+ import { redactLogText } from "./redact.js";
5
+ import { windowEnd } from "./run-window.js";
3
6
  /**
4
7
  * Figures are the typed widgets Tellagen draws in the Diagnosis tab, on the
5
8
  * timeline and in the postmortem. The agent sends data and Tellagen draws it.
@@ -23,6 +26,7 @@ export const STEP_FIGURE_TYPES = [
23
26
  "histogram",
24
27
  "run_history",
25
28
  "diff",
29
+ "log_lines",
26
30
  ];
27
31
  /** Types the API accepts in a timeline event's `blocks`. */
28
32
  export const TIMELINE_BLOCK_TYPES = [
@@ -36,9 +40,20 @@ export const TIMELINE_BLOCK_TYPES = [
36
40
  "histogram",
37
41
  "run_history",
38
42
  "diff",
43
+ "log_lines",
39
44
  ];
40
45
  /** The most JSON one step figure may take, as the backend measures it. */
41
46
  export const MAX_STEP_FIGURE_BYTES = 16 * 1024;
47
+ /**
48
+ * A log_lines figure may take more: 8 lines of 500 characters with fields are
49
+ * about 20 KB. A Tellagen that lists log_lines_v1 accepts a step figure of
50
+ * this size.
51
+ */
52
+ export const MAX_LOG_LINES_STEP_FIGURE_BYTES = 48 * 1024;
53
+ /** The most JSON a step figure of this type may take. */
54
+ export function maxStepFigureBytes(type) {
55
+ return type === "log_lines" ? MAX_LOG_LINES_STEP_FIGURE_BYTES : MAX_STEP_FIGURE_BYTES;
56
+ }
42
57
  const MAX_ABS = 1_000_000_000_000;
43
58
  const MAX_TREND_POINTS = 500;
44
59
  /** Stats a server with figure_extras_v1 takes; the first MAX_STATS_TILES are tiles. */
@@ -47,6 +62,10 @@ export const MAX_STATS_TILES = 4;
47
62
  const MAX_RUNS_NOT_SHOWN = 1_000_000;
48
63
  /** The server takes a stats title, more than 4 stats and runs_not_shown. */
49
64
  export const FIGURE_EXTRAS_CAPABILITY = "figure_extras_v1";
65
+ /** The server takes a `limit` on a compare row (the row is then "after against limit"). */
66
+ export const FIGURE_LIMITS_CAPABILITY = "figure_limits_v1";
67
+ /** The server takes a log_lines figure. */
68
+ export const LOG_LINES_CAPABILITY = "log_lines_v1";
50
69
  const number = z.number().finite().min(-MAX_ABS).max(MAX_ABS);
51
70
  const positive = z.number().finite().gt(0).max(MAX_ABS);
52
71
  const text = (min, max) => z.string().min(min).max(max);
@@ -92,8 +111,11 @@ const compareBase = z
92
111
  .object({
93
112
  label: text(1, 80).describe("One host, route, query or job"),
94
113
  mono: z.boolean().optional().describe("Draw the label in a monospace face"),
95
- before: number,
114
+ before: number.optional().describe("The value before the change. Left out only on a row with a limit. Never put a limit or a budget here."),
96
115
  after: number,
116
+ limit: number
117
+ .optional()
118
+ .describe("A limit or budget the after value is measured against, in the figure's unit. Only when the server lists figure_limits_v1; the row then needs no before."),
97
119
  details: z
98
120
  .array(z
99
121
  .object({ label: text(1, 32), before: text(1, 32), after: text(1, 32) })
@@ -101,7 +123,8 @@ const compareBase = z
101
123
  .max(3)
102
124
  .optional(),
103
125
  })
104
- .strict())
126
+ .strict()
127
+ .refine((row) => row.before !== undefined || row.limit !== undefined, { message: "send before, or a limit to measure after against" }))
105
128
  .min(1)
106
129
  .max(8)
107
130
  .describe("One row per host, route, query or job, biggest movers first"),
@@ -352,12 +375,70 @@ const diffBase = z
352
375
  .describe("1 to 6 hunks, at most 12 changed lines (+ and -) in all. Send every line of a short change, each removed line next to the line that replaced it."),
353
376
  })
354
377
  .strict();
378
+ const logSourceSchema = z
379
+ .object({
380
+ kind: blockText(80).optional().describe("logql for Loki"),
381
+ datasource: blockText(80).optional().describe("The Grafana data source uid or name, so the page can open Explore"),
382
+ // Only source.query may hold line breaks and tabs.
383
+ query: z
384
+ .string()
385
+ .max(2000)
386
+ .refine((value) => !CODE_UNSAFE.test(value.replace(/\n/g, "")), { message: "must not contain control characters other than line breaks and tabs" })
387
+ .optional(),
388
+ from: rfc3339.optional(),
389
+ to: rfc3339.optional(),
390
+ })
391
+ .strict();
392
+ // A log line keeps its indentation and may hold tabs; other control characters are refused.
393
+ const logTextLine = codeLine(MAX_LOG_TEXT).refine((value) => value.trim() !== "", { message: "is required" });
394
+ const logLineSchema = z
395
+ .object({
396
+ time: rfc3339,
397
+ level: z.enum(["error", "warn", "info", "debug", "other"]),
398
+ text: logTextLine,
399
+ fields: z
400
+ .record(blockText(MAX_LOG_FIELD_VALUE, true))
401
+ .superRefine((fields, ctx) => {
402
+ const keys = Object.keys(fields);
403
+ if (keys.length > MAX_LOG_FIELDS) {
404
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `at most ${MAX_LOG_FIELDS} fields (got ${keys.length})` });
405
+ }
406
+ for (const key of keys) {
407
+ const trimmed = key.trim();
408
+ if (trimmed === "" || charCount(trimmed) > MAX_LOG_FIELD_KEY || BLOCK_UNSAFE.test(trimmed)) {
409
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `the field name "${key.slice(0, 20).replace(/[\u0000-\u001f]/g, " ")}" must be 1 to ${MAX_LOG_FIELD_KEY} characters, on one line` });
410
+ }
411
+ }
412
+ const trimmedKeys = keys.map((key) => key.trim());
413
+ if (new Set(trimmedKeys).size !== trimmedKeys.length) {
414
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "has two field names that are the same once trimmed" });
415
+ }
416
+ })
417
+ .optional(),
418
+ relation: z.enum(["matches_event", "context", "unrelated"]).optional(),
419
+ note: blockText(MAX_LOG_NOTE).optional(),
420
+ })
421
+ .strict();
422
+ const logCount = z.number().int().min(0).max(MAX_LOG_COUNT);
423
+ const logLinesBase = z
424
+ .object({
425
+ type: z.literal("log_lines"),
426
+ title: blockText(80).optional(),
427
+ source: logSourceSchema.optional(),
428
+ matched: logCount.describe("How many lines matched the query in the range"),
429
+ scanned: logCount.optional().describe("How many lines the query looked at. Not below matched."),
430
+ event_at: rfc3339.optional().describe("The moment of the event the lines are about"),
431
+ lines: z.array(logLineSchema).max(MAX_LOG_LINES).optional(),
432
+ lines_not_shown: logCount.optional().describe("How many matches are not in lines"),
433
+ })
434
+ .strict();
355
435
  /** Exported for the step figure schema of tellagen_complete_investigation. */
356
436
  export const checksBlockSchema = checksBase;
357
437
  export const rangeOverlapBlockSchema = rangeOverlapBase;
358
438
  export const histogramBlockSchema = histogramBase;
359
439
  export const runHistoryBlockSchema = runHistoryBase;
360
440
  export const diffBlockSchema = diffBase;
441
+ export const logLinesBlockSchema = logLinesBase;
361
442
  const formatEdge = (n) => String(n);
362
443
  /**
363
444
  * The rules of a diff's hunks that span lines, with the API's messages: the
@@ -531,6 +612,31 @@ export function figureRuleIssues(block) {
531
612
  const b = block;
532
613
  issues.push(...diffRuleIssues(b.hunks));
533
614
  }
615
+ if (block.type === "log_lines") {
616
+ const b = block;
617
+ const shown = b.lines?.length ?? 0;
618
+ if (b.scanned !== undefined && b.scanned < b.matched)
619
+ add(["scanned"], "must not be below matched");
620
+ if (shown > b.matched)
621
+ add(["lines"], `has ${shown} lines but matched is ${b.matched}`);
622
+ else if (b.matched > 0 && shown === 0) {
623
+ add(["lines"], "needs at least 1 line when matched is above 0; send matched 0 for a query with no result");
624
+ }
625
+ else if ((b.lines_not_shown ?? 0) > b.matched - shown) {
626
+ add(["lines_not_shown"], "must not be more than the matches that are not in lines");
627
+ }
628
+ if (b.matched === 0) {
629
+ if (b.scanned === undefined)
630
+ add(["scanned"], "is required when matched is 0, so the empty result says how much was searched");
631
+ if (b.source?.from === undefined || b.source?.to === undefined) {
632
+ add(["source"], "needs from and to when matched is 0, so the empty result says where and when it searched");
633
+ }
634
+ }
635
+ const from = b.source?.from === undefined ? undefined : Date.parse(b.source.from);
636
+ const to = b.source?.to === undefined ? undefined : Date.parse(b.source.to);
637
+ if (from !== undefined && to !== undefined && from > to)
638
+ add(["source", "to"], "must not be before from");
639
+ }
534
640
  return issues;
535
641
  }
536
642
  /** Where a block sits on a timeline event. Not together. */
@@ -555,6 +661,7 @@ export const timelineBlockSchema = z.discriminatedUnion("type", [
555
661
  histogramBase.extend(placementFields),
556
662
  runHistoryBase.extend(placementFields),
557
663
  diffBase.extend(placementFields),
664
+ logLinesBase.extend(placementFields),
558
665
  ]);
559
666
  /**
560
667
  * The light check the timeline tools apply to `blocks`. The full schema above
@@ -746,6 +853,59 @@ const diffInput = z
746
853
  .describe("With patch: the numbers (1 is the first @@ header) of the hunks the claim cites, in file order, when the change has more than 12 changed lines."),
747
854
  })
748
855
  .strict();
856
+ const logMarkSchema = z
857
+ .object({
858
+ contains: z.string().min(1).max(200).optional().describe("Marks every line that holds this text (case does not count)"),
859
+ field: z
860
+ .object({ key: z.string().min(1).max(MAX_LOG_FIELD_KEY), value: z.string().min(1).max(MAX_LOG_FIELD_VALUE) })
861
+ .strict()
862
+ .optional()
863
+ .describe("Marks every line whose JSON or logfmt field, or whose stream label, has this value, for example company_id 578"),
864
+ relation: z.enum(["matches_event", "context", "unrelated"]),
865
+ note: blockText(MAX_LOG_NOTE).optional().describe("Why the line is what its relation says, for example Company 578, 11 hours after the event"),
866
+ })
867
+ .strict()
868
+ .refine((mark) => mark.contains !== undefined || mark.field !== undefined, { message: "send contains or field" });
869
+ const logLinesInput = z
870
+ .object({
871
+ type: z.literal("log_lines"),
872
+ title: blockText(80).optional(),
873
+ query: z.string().max(2000).optional().describe("The LogQL that ran. It becomes source.query so the page can open it in Grafana Explore."),
874
+ datasource: blockText(80).optional().describe("The Grafana data source uid or name the query ran against"),
875
+ kind: blockText(80).optional().describe("Defaults to logql when query is sent"),
876
+ from: rfc3339.optional().describe("Start of the range the query searched. Defaults to the start of the run window."),
877
+ to: rfc3339.optional().describe("End of the range. Defaults to the end of the run window, or now for an open one."),
878
+ streams: z
879
+ .unknown()
880
+ .optional()
881
+ .describe("The streams of a Loki result, as returned: [{stream: {labels}, values: [[time, line], ...]}]. The whole Loki response body is accepted too."),
882
+ entries: z
883
+ .array(z.record(z.unknown()))
884
+ .max(5000)
885
+ .optional()
886
+ .describe("Or a flat list of entries: [{timestamp, line, labels}], as the Grafana log tools return them."),
887
+ matched: logCount
888
+ .optional()
889
+ .describe("How many lines the query matched in the range, when it is more than you send (the query had a limit). Defaults to the number of lines you send."),
890
+ scanned: logCount.optional().describe("How many lines the query looked at (query_loki_stats entries). Always send it with matched 0."),
891
+ event_at: rfc3339.optional().describe("The moment of the event, so the page can say how far a line is from it"),
892
+ match: z
893
+ .array(z.string().min(1).max(200))
894
+ .max(8)
895
+ .optional()
896
+ .describe("Terms that show the event. Lines that hold one are marked matches_event and come first."),
897
+ marks: z
898
+ .array(logMarkSchema)
899
+ .max(12)
900
+ .optional()
901
+ .describe("Mark lines by text or by a field: lines of another tenant, company or request are unrelated, with a note that says why. The first mark that fits a line wins."),
902
+ field_keys: z
903
+ .array(z.string().min(1).max(MAX_LOG_FIELD_KEY))
904
+ .max(MAX_LOG_FIELDS)
905
+ .optional()
906
+ .describe("The fields to show on each line, in order. Without it the builder takes up to six from the line and its labels."),
907
+ })
908
+ .strict();
749
909
  /** What tellagen_build_figure accepts. */
750
910
  export const figureInputSchema = z.discriminatedUnion("type", [
751
911
  statsBase,
@@ -758,9 +918,10 @@ export const figureInputSchema = z.discriminatedUnion("type", [
758
918
  histogramInput,
759
919
  runHistoryInput,
760
920
  diffInput,
921
+ logLinesInput,
761
922
  ]);
762
923
  /** The four figure types whose fields the tool listing leaves to the guide. */
763
- export const GUIDE_ONLY_FIGURE_TYPES = ["range_overlap", "histogram", "run_history", "diff"];
924
+ export const GUIDE_ONLY_FIGURE_TYPES = ["range_overlap", "histogram", "run_history", "diff", "log_lines"];
764
925
  /**
765
926
  * The figure as tellagen_build_figure lists it. The six original types carry
766
927
  * their full schema; the four newer ones only their type, so the listing stays
@@ -777,7 +938,7 @@ export const figureToolInputSchema = z.discriminatedUnion("type", [
777
938
  z
778
939
  .object({ type: z.enum(GUIDE_ONLY_FIGURE_TYPES) })
779
940
  .passthrough()
780
- .describe("range_overlap, histogram, run_history or diff, with the fields in resource://tellagen/figure-guide. Checked in full when the tool runs."),
941
+ .describe("range_overlap, histogram, run_history, diff or log_lines, with the fields in resource://tellagen/figure-guide. Checked in full when the tool runs."),
781
942
  ]);
782
943
  const issuesOf = (error) => error.issues.map((issue) => {
783
944
  const path = issue.path.join(".");
@@ -1242,6 +1403,114 @@ function buildDiff(input, options) {
1242
1403
  notes.push(...diffShapeAdvice(out, input.additions, input.deletions));
1243
1404
  return { block: { ...rest, hunks: out }, notes };
1244
1405
  }
1406
+ /**
1407
+ * A log_lines block from the result of a Loki query. The builder reads the
1408
+ * lines, parses the level, keeps at most 8 (the ones that show the event
1409
+ * first), and counts what is left out. Counts and times come from the result
1410
+ * or from what the agent sent; a range the agent did not send is the run
1411
+ * window, and the notes say so.
1412
+ */
1413
+ function buildLogLines(input, options) {
1414
+ const { streams, entries: rawEntries, query, datasource, kind, from, to, matched, scanned, event_at, match, marks, field_keys, ...rest } = input;
1415
+ const notes = [];
1416
+ const read = readLogEntries({ streams, entries: rawEntries });
1417
+ if (read.issues.length > 0)
1418
+ return { issues: read.issues.slice(0, 8) };
1419
+ if (streams === undefined && rawEntries === undefined) {
1420
+ return {
1421
+ issues: [
1422
+ "streams: send the streams of the Loki result, or entries, even for a query with no result (an empty list, with matched 0, scanned, from and to).",
1423
+ ],
1424
+ };
1425
+ }
1426
+ const eventMs = event_at === undefined ? undefined : Date.parse(event_at);
1427
+ const selection = selectLogLines(read.entries, {
1428
+ match,
1429
+ marks,
1430
+ fieldKeys: field_keys,
1431
+ eventAt: eventMs,
1432
+ });
1433
+ notes.push(...selection.notes);
1434
+ const total = selection.total;
1435
+ // Values beyond the input cap were counted, not kept: they are matches too.
1436
+ const overflow = read.overflow;
1437
+ if (overflow > 0) {
1438
+ notes.push(`The result held ${total + overflow} lines; only the first ${total} were read. The rest are counted in matched and lines_not_shown.`);
1439
+ }
1440
+ const matchedCount = matched ?? total + overflow;
1441
+ if (matched === undefined) {
1442
+ notes.push(`matched is the ${total + overflow} lines you sent. If the query had a limit and more lines matched, send matched with the real count.`);
1443
+ }
1444
+ else if (matched < total + overflow) {
1445
+ return { issues: [`matched: ${matched} is below the ${total + overflow} lines you sent. Send the number the query matched in the range.`] };
1446
+ }
1447
+ const source = {};
1448
+ if (query !== undefined && query.trim() !== "")
1449
+ source.query = redactLogText(query.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029]/g, " "));
1450
+ if (datasource !== undefined && datasource.trim() !== "")
1451
+ source.datasource = datasource;
1452
+ if (kind !== undefined && kind.trim() !== "")
1453
+ source.kind = kind;
1454
+ else if (source.query !== undefined)
1455
+ source.kind = "logql";
1456
+ let rangeFrom = from;
1457
+ let rangeTo = to;
1458
+ const window = options.window;
1459
+ if (window !== undefined && (rangeFrom === undefined || rangeTo === undefined)) {
1460
+ const used = [];
1461
+ if (rangeFrom === undefined) {
1462
+ rangeFrom = window.from;
1463
+ used.push("from");
1464
+ }
1465
+ if (rangeTo === undefined) {
1466
+ rangeTo = windowEnd(window, options.now);
1467
+ used.push("to");
1468
+ }
1469
+ notes.push(`${used.join(" and ")} ${used.length === 1 ? "was" : "were"} set to the run window because you sent none. If the query ran over another range, send from and to.`);
1470
+ }
1471
+ if (rangeFrom !== undefined)
1472
+ source.from = rangeFrom;
1473
+ if (rangeTo !== undefined)
1474
+ source.to = rangeTo;
1475
+ if (window !== undefined && rangeFrom !== undefined && rangeTo !== undefined && (from !== undefined || to !== undefined)) {
1476
+ const start = Date.parse(rangeFrom);
1477
+ const end = Date.parse(rangeTo);
1478
+ const lowest = Date.parse(window.baseline_from ?? window.from);
1479
+ const highest = window.to === undefined ? Number.POSITIVE_INFINITY : Date.parse(window.to);
1480
+ if (Number.isFinite(start) && Number.isFinite(end) && (start < lowest || end > highest)) {
1481
+ notes.push("The range reaches outside the run window and its baseline. Search for the cause inside the window; if the signal really starts outside it, send window_suggestion with the result.");
1482
+ }
1483
+ }
1484
+ const lines = selection.lines;
1485
+ if (matchedCount > 0 && lines.length === 0) {
1486
+ return { issues: ["streams: the result holds no usable line, but matched is above 0. Send the lines the query returned."] };
1487
+ }
1488
+ const block = { ...rest, matched: matchedCount };
1489
+ if (Object.keys(source).length > 0)
1490
+ block.source = source;
1491
+ if (scanned !== undefined)
1492
+ block.scanned = scanned;
1493
+ if (event_at !== undefined)
1494
+ block.event_at = event_at;
1495
+ block.lines = lines;
1496
+ const notShown = matchedCount - lines.length;
1497
+ if (notShown > 0)
1498
+ block.lines_not_shown = notShown;
1499
+ if (matchedCount === 0 && scanned === undefined) {
1500
+ return {
1501
+ issues: [
1502
+ "scanned: send how many lines the query looked at (for example from query_loki_stats) with matched 0. An empty result without the range and the count is not proof.",
1503
+ ],
1504
+ };
1505
+ }
1506
+ if (lines.some((line) => line.relation === "unrelated")) {
1507
+ notes.push("A line marked unrelated is not proof: never use its text as the quote of a finding.");
1508
+ }
1509
+ if (lines.length > 0 && lines.every((line) => line.relation === undefined) && match === undefined && marks === undefined) {
1510
+ notes.push("No line is marked. Send match terms for the lines that show the event, and marks for a line of another tenant, company or request, so a reader can tell proof from noise.");
1511
+ }
1512
+ return { block, notes };
1513
+ }
1245
1514
  /**
1246
1515
  * A diff block as a server without diff_lines_v1 takes it: no unchanged lines
1247
1516
  * and no line numbers. Any other block is returned as it is.
@@ -1283,6 +1552,33 @@ export function withoutFigureExtrasInBlock(block) {
1283
1552
  }
1284
1553
  return what.length > 0 ? { block: record, what } : { block, what };
1285
1554
  }
1555
+ /**
1556
+ * A compare block as a server without figure_limits_v1 takes it: no `limit`
1557
+ * on a row. A row that had only a limit has no before then, so `unusable` is
1558
+ * true and the figure cannot be sent. Any other block is returned as it is.
1559
+ */
1560
+ export function withoutFigureLimitsInBlock(block) {
1561
+ if (typeof block !== "object" || block === null || Array.isArray(block))
1562
+ return { block, what: [], unusable: false };
1563
+ const record = block;
1564
+ if (record.type !== "compare" || !Array.isArray(record.rows) || !record.rows.some((row) => typeof row === "object" && row !== null && "limit" in row)) {
1565
+ return { block, what: [], unusable: false };
1566
+ }
1567
+ let unusable = false;
1568
+ const rows = record.rows.map((row) => {
1569
+ if (typeof row !== "object" || row === null)
1570
+ return row;
1571
+ const { limit: _limit, ...rest } = row;
1572
+ if (rest.before === undefined)
1573
+ unusable = true;
1574
+ return rest;
1575
+ });
1576
+ return { block: { ...record, rows }, what: ["the row limits"], unusable };
1577
+ }
1578
+ /** Whether a block is a log_lines figure. */
1579
+ export function isLogLinesBlock(block) {
1580
+ return typeof block === "object" && block !== null && block.type === "log_lines";
1581
+ }
1286
1582
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1287
1583
  const describe = (block) => {
1288
1584
  switch (block.type) {
@@ -1324,6 +1620,17 @@ const describe = (block) => {
1324
1620
  const numbered = lines.some((l) => l.old_no !== undefined || l.new_no !== undefined);
1325
1621
  return `diff of ${block.path} at ${block.ref}: +${block.additions} -${block.deletions} in the whole change, ${plural(changed, "changed line")} shown${context > 0 ? ` with ${plural(context, "unchanged line")}` : ""}${numbered ? " and line numbers" : ""}`;
1326
1622
  }
1623
+ case "log_lines": {
1624
+ const lines = block.lines ?? [];
1625
+ const counts = relationCounts(lines);
1626
+ const marked = [
1627
+ counts.matches_event > 0 ? `${counts.matches_event} matching the event` : "",
1628
+ counts.context > 0 ? `${counts.context} context` : "",
1629
+ counts.unrelated > 0 ? `${counts.unrelated} unrelated` : "",
1630
+ ].filter((part) => part !== "");
1631
+ const scanned = typeof block.scanned === "number" ? ` of ${block.scanned} scanned` : "";
1632
+ return `log_lines: ${block.matched} lines matched${scanned}, ${plural(lines.length, "line")} shown${marked.length > 0 ? ` (${marked.join(", ")})` : ""}`;
1633
+ }
1327
1634
  default:
1328
1635
  return `changes with ${block.rows.length} rows`;
1329
1636
  }
@@ -1378,6 +1685,19 @@ export function buildFigure(input, options = {}) {
1378
1685
  if (failed)
1379
1686
  return failed;
1380
1687
  }
1688
+ else if (figure.type === "log_lines") {
1689
+ if (options.logLines !== true) {
1690
+ return {
1691
+ ok: false,
1692
+ issues: [
1693
+ `type: this Tellagen does not list ${LOG_LINES_CAPABILITY} in server_capabilities, so it would drop a log_lines figure. Show the log evidence as a checks or stats figure, and put the lines in the finding's evidence_summary.`,
1694
+ ],
1695
+ };
1696
+ }
1697
+ const failed = take(buildLogLines(figure, options));
1698
+ if (failed)
1699
+ return failed;
1700
+ }
1381
1701
  else if (figure.type === "table") {
1382
1702
  block = {
1383
1703
  ...figure,
@@ -1395,6 +1715,19 @@ export function buildFigure(input, options = {}) {
1395
1715
  notes.push(`Left out ${stripped.what.join(" and ")}: this Tellagen does not list ${FIGURE_EXTRAS_CAPABILITY} in server_capabilities.`);
1396
1716
  }
1397
1717
  }
1718
+ if (options.figureLimits !== true) {
1719
+ const stripped = withoutFigureLimitsInBlock(block);
1720
+ if (stripped.what.length > 0) {
1721
+ if (stripped.unusable) {
1722
+ return {
1723
+ ok: false,
1724
+ issues: [`rows: this Tellagen does not list ${FIGURE_LIMITS_CAPABILITY} in server_capabilities, so a row needs before. Send the value before the change, or leave the limit out of the figure and say it in the caption.`],
1725
+ };
1726
+ }
1727
+ block = stripped.block;
1728
+ notes.push(`Left out ${stripped.what.join(" and ")}: this Tellagen does not list ${FIGURE_LIMITS_CAPABILITY} in server_capabilities.`);
1729
+ }
1730
+ }
1398
1731
  if (input.placement === "timeline_block") {
1399
1732
  if (input.slot)
1400
1733
  block.slot = input.slot;
@@ -1408,10 +1741,11 @@ export function buildFigure(input, options = {}) {
1408
1741
  return { ok: false, issues };
1409
1742
  if (input.placement === "step_figure") {
1410
1743
  const bytes = new TextEncoder().encode(JSON.stringify(block)).length;
1411
- if (bytes > MAX_STEP_FIGURE_BYTES) {
1744
+ const limit = maxStepFigureBytes(block.type);
1745
+ if (bytes > limit) {
1412
1746
  return {
1413
1747
  ok: false,
1414
- issues: [`figure: ${bytes} bytes; a step figure holds at most ${MAX_STEP_FIGURE_BYTES}. Send fewer points, runs or rows, or put it on a timeline event.`],
1748
+ issues: [`figure: ${bytes} bytes; a step figure holds at most ${limit}. Send fewer points, runs or rows, or put it on a timeline event.`],
1415
1749
  };
1416
1750
  }
1417
1751
  }
@@ -1423,7 +1757,7 @@ export function buildFigure(input, options = {}) {
1423
1757
  summary: describe(block),
1424
1758
  notes,
1425
1759
  use: input.placement === "step_figure"
1426
- ? "Put this object in result_summary.causal_paths[].steps[].figure. One figure per step. It needs the diagnosis structure the pickup advertises as diagnosis_structure_v1. A Tellagen older than these figure types drops a checks, range_overlap, histogram, run_history or diff figure and says so in the completion warnings (figure_invalid)."
1760
+ ? "Put this object in result_summary.causal_paths[].steps[].figure. One figure per step. It needs the diagnosis structure the pickup advertises as diagnosis_structure_v1. A Tellagen older than these figure types drops a checks, range_overlap, histogram, run_history, diff or log_lines figure and says so in the completion warnings (figure_invalid)."
1427
1761
  : "Put this object in the blocks array of tellagen_post_timeline_event or tellagen_update_timeline_event. An update replaces the whole array, so send every block you want to keep.",
1428
1762
  };
1429
1763
  }