@skyhook-io/radar-app 1.18.2 → 1.19.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 (78) hide show
  1. package/package.json +4 -4
  2. package/src/App.tsx +0 -1
  3. package/src/api/diagnose.test.ts +33 -2
  4. package/src/api/diagnose.ts +93 -3
  5. package/src/api/radarFeatures.ts +1 -0
  6. package/src/components/diagnose/AIMarkdown.tsx +1 -1
  7. package/src/components/diagnose/ActivityTurn.tsx +34 -14
  8. package/src/components/diagnose/AgentControls.tsx +53 -6
  9. package/src/components/diagnose/AgentSetupNotice.tsx +1 -1
  10. package/src/components/diagnose/AgentSigninNotice.test.tsx +98 -0
  11. package/src/components/diagnose/AgentSigninNotice.tsx +61 -0
  12. package/src/components/diagnose/AnalysisStory.test.tsx +22 -0
  13. package/src/components/diagnose/AnalysisStory.tsx +17 -4
  14. package/src/components/diagnose/AssessmentCard.tsx +39 -8
  15. package/src/components/diagnose/DiagnoseContext.capacity.test.tsx +113 -0
  16. package/src/components/diagnose/DiagnoseContext.question.test.tsx +245 -0
  17. package/src/components/diagnose/DiagnoseContext.tsx +205 -9
  18. package/src/components/diagnose/DiagnoseSurface.test.tsx +54 -0
  19. package/src/components/diagnose/DiagnoseSurface.tsx +93 -21
  20. package/src/components/diagnose/EvidenceCard.tsx +67 -14
  21. package/src/components/diagnose/Home.test.tsx +182 -5
  22. package/src/components/diagnose/Home.tsx +168 -36
  23. package/src/components/diagnose/InvestigationCapacityNotice.test.tsx +246 -0
  24. package/src/components/diagnose/InvestigationCapacityNotice.tsx +241 -0
  25. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +97 -6
  26. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +57 -0
  27. package/src/components/diagnose/InvestigationEvidencePane.tsx +59 -11
  28. package/src/components/diagnose/InvestigationEvidenceSections.tsx +5 -1
  29. package/src/components/diagnose/InvestigationView.tsx +156 -29
  30. package/src/components/diagnose/LocalDiagnoseAction.tsx +23 -16
  31. package/src/components/diagnose/QuestionComposer.test.tsx +553 -0
  32. package/src/components/diagnose/QuestionComposer.tsx +487 -0
  33. package/src/components/diagnose/QuestionFocus.test.tsx +38 -0
  34. package/src/components/diagnose/QuestionFocus.tsx +123 -0
  35. package/src/components/diagnose/ResourcePicker.tsx +206 -0
  36. package/src/components/diagnose/StoryExcerpt.tsx +12 -3
  37. package/src/components/diagnose/assessmentCopy.ts +5 -0
  38. package/src/components/diagnose/investigationCase.runs.test.tsx +328 -0
  39. package/src/components/diagnose/investigationCase.ts +33 -1
  40. package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +46 -0
  41. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +8 -0
  42. package/src/components/diagnose/investigationEvidence/adapters/posture.ts +29 -1
  43. package/src/components/diagnose/investigationEvidence/adapters/prometheus.test.ts +40 -0
  44. package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +27 -1
  45. package/src/components/diagnose/investigationEvidence/bodies/metrics.test.tsx +111 -0
  46. package/src/components/diagnose/investigationEvidence/bodies/metrics.tsx +67 -16
  47. package/src/components/diagnose/investigationEvidence/excerpt.test.ts +18 -5
  48. package/src/components/diagnose/investigationEvidence/excerpt.ts +22 -11
  49. package/src/components/diagnose/investigationEvidence/index.ts +1 -1
  50. package/src/components/diagnose/investigationEvidence/navigation.tsx +2 -0
  51. package/src/components/diagnose/investigationEvidence/types.ts +2 -0
  52. package/src/components/diagnose/investigationEvidencePartition.ts +6 -1
  53. package/src/components/diagnose/investigationFocus.test.ts +271 -0
  54. package/src/components/diagnose/investigationFocus.ts +132 -0
  55. package/src/components/diagnose/parts.test.tsx +20 -0
  56. package/src/components/diagnose/questionSuggestions.test.ts +111 -0
  57. package/src/components/diagnose/questionSuggestions.ts +150 -0
  58. package/src/components/diagnose/storyParts.test.tsx +13 -0
  59. package/src/components/diagnose/target.test.ts +143 -2
  60. package/src/components/diagnose/target.ts +109 -7
  61. package/src/components/diagnose/testdata/story-runs.json +474 -0
  62. package/src/components/diagnose/verdictText.test.tsx +87 -0
  63. package/src/components/diagnose/verdictText.ts +68 -0
  64. package/src/components/home/ClusterHealthCard.tsx +13 -39
  65. package/src/components/home/HomeAgentBlock.test.tsx +113 -0
  66. package/src/components/home/HomeAgentBlock.tsx +94 -0
  67. package/src/components/home/HomeView.tsx +5 -6
  68. package/src/components/home/RadarVersionLine.test.tsx +0 -14
  69. package/src/components/home/RadarVersionLine.tsx +3 -28
  70. package/src/components/ui/Omnibar.investigate.test.tsx +105 -0
  71. package/src/components/ui/Omnibar.tsx +47 -3
  72. package/src/components/ui/RadarOmnibar.test.tsx +1 -0
  73. package/src/components/ui/RadarOmnibar.tsx +11 -0
  74. package/src/components/whats-new/WhatsNewDialog.test.tsx +3 -3
  75. package/src/components/whats-new/releaseNotes.ts +60 -1
  76. package/src/hooks/useAgentSignin.test.tsx +190 -0
  77. package/src/hooks/useAgentSignin.ts +160 -0
  78. package/src/hooks/useApproveAfterSignin.test.tsx +108 -0
@@ -0,0 +1,206 @@
1
+ // Search for the one resource a question is about, the way the Omnibar
2
+ // searches: workloads before the objects they own.
3
+ import { useEffect, useId, useMemo, useState } from "react";
4
+ import { useDebouncedValue } from "@skyhook-io/k8s-ui";
5
+
6
+ import { type SearchResult, useSearch } from "../../api/client";
7
+ import {
8
+ PENDING_RETRY_BUDGET_MS,
9
+ PENDING_RETRY_MS,
10
+ searchCoverageNote,
11
+ } from "../ui/searchCoverageNote";
12
+ import type { QuestionPin } from "./questionSuggestions";
13
+ import { formatInvestigationKind } from "./target";
14
+
15
+ function stillSyncing(data: SearchResult | undefined): boolean {
16
+ return !!data?.coverage?.gaps.some((gap) => gap.code === "kind_sync_pending");
17
+ }
18
+
19
+ // Kinds that are usually children of what an engineer means: a question is
20
+ // about the Deployment or Service, not one of its ReplicaSets or Pods. They
21
+ // stay pickable, after everything else.
22
+ const OWNED_KINDS = new Set([
23
+ "Pod",
24
+ "ReplicaSet",
25
+ "ControllerRevision",
26
+ "EndpointSlice",
27
+ "Event",
28
+ ]);
29
+
30
+ function rankForPinning<T extends { kind: string }>(hits: T[]): T[] {
31
+ return [...hits].sort(
32
+ (a, b) => Number(OWNED_KINDS.has(a.kind)) - Number(OWNED_KINDS.has(b.kind)),
33
+ );
34
+ }
35
+
36
+ export function ResourcePicker({
37
+ inputRef,
38
+ onPick,
39
+ onCancel,
40
+ }: {
41
+ inputRef: React.RefObject<HTMLInputElement | null>;
42
+ onPick: (pin: QuestionPin) => void;
43
+ onCancel: () => void;
44
+ }) {
45
+ const [query, setQuery] = useState("");
46
+ const [active, setActive] = useState(0);
47
+ const listId = useId();
48
+ // Search the way the Omnibar does: once typing pauses, not per keystroke.
49
+ const searched = useDebouncedValue(query, 150, (value) => !value.trim());
50
+ // Kinds still syncing answer "not yet", not "no": keep asking, as the
51
+ // Omnibar does, for a bounded while.
52
+ const [exhausted, setExhausted] = useState<string | null>(null);
53
+ const { data, isFetching, isPlaceholderData, isError, refetch } = useSearch(
54
+ searched,
55
+ {
56
+ context: "none",
57
+ limit: 8,
58
+ globalNs: true,
59
+ refetchInterval: (latest) =>
60
+ stillSyncing(latest) && exhausted !== searched
61
+ ? PENDING_RETRY_MS
62
+ : false,
63
+ },
64
+ );
65
+ const syncing = !isPlaceholderData && stillSyncing(data);
66
+ useEffect(() => {
67
+ if (!syncing) return;
68
+ const timer = setTimeout(
69
+ () => setExhausted(searched),
70
+ PENDING_RETRY_BUDGET_MS,
71
+ );
72
+ return () => clearTimeout(timer);
73
+ }, [syncing, searched]);
74
+ // Results belong to what is in the box only once it has been searched.
75
+ const current =
76
+ searched === query && query.trim().length >= 2 && !isPlaceholderData;
77
+ // Results kept from the previous query while the next one loads must not
78
+ // be pinnable: Enter would pin what the engineer just typed away from.
79
+ const hits = useMemo(
80
+ () => (current && !isError ? rankForPinning(data?.hits ?? []) : []),
81
+ [current, isError, data],
82
+ );
83
+ const note = current
84
+ ? searchCoverageNote(data?.coverage, {
85
+ hits: data?.hits,
86
+ query,
87
+ pendingExhausted: exhausted === searched,
88
+ })
89
+ : undefined;
90
+ const noteText = note?.parts
91
+ ? note.parts.map((part) => part.text).join(" ")
92
+ : note?.text;
93
+ const activeIndex = Math.min(active, Math.max(hits.length - 1, 0));
94
+ const pick = (hit: (typeof hits)[number]) =>
95
+ onPick({
96
+ kind: hit.kind,
97
+ group: hit.group ?? "",
98
+ namespace: hit.namespace ?? "",
99
+ name: hit.name,
100
+ });
101
+ return (
102
+ <div className="border-t border-theme-border-subtle px-3 py-2">
103
+ <input
104
+ ref={inputRef}
105
+ value={query}
106
+ onChange={(event) => {
107
+ setQuery(event.target.value);
108
+ setActive(0);
109
+ }}
110
+ onKeyDown={(event) => {
111
+ if (event.key === "Escape") {
112
+ event.preventDefault();
113
+ event.stopPropagation();
114
+ onCancel();
115
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
116
+ event.preventDefault();
117
+ if (hits.length === 0) return;
118
+ const step = event.key === "ArrowDown" ? 1 : -1;
119
+ setActive((activeIndex + step + hits.length) % hits.length);
120
+ } else if (event.key === "Enter") {
121
+ event.preventDefault();
122
+ const hit = hits[activeIndex];
123
+ if (hit) pick(hit);
124
+ }
125
+ }}
126
+ role="combobox"
127
+ aria-expanded={hits.length > 0}
128
+ aria-label="Search for a resource to pin"
129
+ aria-controls={listId}
130
+ aria-activedescendant={
131
+ hits.length > 0 ? `${listId}-${activeIndex}` : undefined
132
+ }
133
+ placeholder="Search resources by name, kind:Deployment, ns:shop…"
134
+ className="w-full rounded-md border border-theme-border bg-theme-elevated px-2 py-1 text-sm text-theme-text-primary placeholder:text-theme-text-tertiary focus:border-accent focus:outline-none"
135
+ />
136
+ <ul id={listId} role="listbox" className="mt-1 max-h-48 overflow-y-auto">
137
+ {hits.map((hit, index) => (
138
+ <li
139
+ key={`${hit.group ?? ""}/${hit.kind}/${hit.namespace ?? ""}/${hit.name}`}
140
+ id={`${listId}-${index}`}
141
+ role="option"
142
+ aria-selected={index === activeIndex}
143
+ >
144
+ <button
145
+ type="button"
146
+ tabIndex={-1}
147
+ onClick={() => pick(hit)}
148
+ onMouseEnter={() => setActive(index)}
149
+ className={`flex w-full items-baseline gap-2 rounded px-2 py-1 text-left text-sm ${
150
+ index === activeIndex ? "bg-theme-hover" : ""
151
+ }`}
152
+ >
153
+ <span className="truncate text-theme-text-primary">
154
+ {hit.name}
155
+ </span>
156
+ <span className="shrink-0 text-xs text-theme-text-tertiary">
157
+ {formatInvestigationKind(hit.kind, hit.group ?? "")}
158
+ {hit.namespace ? ` · ${hit.namespace}` : ""}
159
+ </span>
160
+ </button>
161
+ </li>
162
+ ))}
163
+ {current && isError && !isFetching && (
164
+ <li className="flex items-center gap-2 px-2 py-1 text-xs text-theme-text-secondary">
165
+ Couldn’t search resources.
166
+ <button
167
+ type="button"
168
+ onClick={() => void refetch()}
169
+ className="font-medium text-theme-text-primary hover:underline"
170
+ >
171
+ Try again
172
+ </button>
173
+ </li>
174
+ )}
175
+ {current && !isError && !isFetching && hits.length === 0 && (
176
+ <li className="px-2 py-1 text-xs text-theme-text-tertiary">
177
+ {noteText
178
+ ? "No matches in what Radar searched."
179
+ : "No matching resources."}
180
+ </li>
181
+ )}
182
+ {current && !isError && noteText && (
183
+ <li className="px-2 py-1 text-[11px] text-theme-text-tertiary">
184
+ {noteText}
185
+ {syncing && exhausted === searched && (
186
+ <button
187
+ type="button"
188
+ onClick={() => {
189
+ setExhausted(null);
190
+ void refetch();
191
+ }}
192
+ className="ml-1 font-medium text-theme-text-primary hover:underline"
193
+ >
194
+ Try again
195
+ </button>
196
+ )}
197
+ </li>
198
+ )}
199
+ </ul>
200
+ <p className="mt-1 text-[11px] text-theme-text-tertiary">
201
+ Pinning starts the investigation at that resource, and lets you apply a
202
+ fix from it.
203
+ </p>
204
+ </div>
205
+ );
206
+ }
@@ -30,6 +30,7 @@ export function StoryExcerpt({
30
30
  open,
31
31
  canExpand,
32
32
  changeCoverage,
33
+ chartId,
33
34
  }: {
34
35
  excerpt: Excerpt;
35
36
  data: InvestigationEvidenceData;
@@ -37,6 +38,8 @@ export function StoryExcerpt({
37
38
  open: boolean;
38
39
  canExpand: boolean;
39
40
  changeCoverage?: MetricsChangeCoverage;
41
+ /** Panel id for the card header's aria-controls when the chart folds. */
42
+ chartId?: string;
40
43
  }) {
41
44
  const padding = prominence === "primary" ? "px-3 pb-2.5" : "px-2.5 pb-2";
42
45
  switch (excerpt.kind) {
@@ -129,9 +132,15 @@ export function StoryExcerpt({
129
132
  );
130
133
  case "chart":
131
134
  return data.type === "metrics" ? (
132
- <div data-story-metrics className={padding}>
133
- <MetricsBody data={data} changeCoverage={changeCoverage} />
134
- </div>
135
+ <Collapse open={open} mountLazily id={chartId}>
136
+ <div data-story-metrics className={padding}>
137
+ <MetricsBody
138
+ data={data}
139
+ changeCoverage={changeCoverage}
140
+ size={excerpt.size}
141
+ />
142
+ </div>
143
+ </Collapse>
135
144
  ) : null;
136
145
  }
137
146
  }
@@ -19,6 +19,9 @@ export interface AssessmentCopyRadar {
19
19
  /** Where and when: the header line a reader in a channel needs first. */
20
20
  context?: {
21
21
  target: string;
22
+ /** The engineer's question on a run that names a resource; a run opened
23
+ * by the question alone already has it as its target. */
24
+ asked?: string;
22
25
  cluster?: string;
23
26
  startedAt?: string;
24
27
  agent?: string;
@@ -60,6 +63,8 @@ export function assessmentCopyText(
60
63
  .filter(Boolean)
61
64
  .join(" · "),
62
65
  );
66
+ const asked = radar.context.asked?.replace(/\s+/g, " ").trim();
67
+ if (asked) parts.push(`Asked: “${asked}”`);
63
68
  }
64
69
  if (diagnosis.summary) {
65
70
  const certainty = diagnosis.healthy
@@ -0,0 +1,328 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { renderToStaticMarkup } from "react-dom/server";
3
+
4
+ import type {
5
+ DiagnosisEvidenceItem,
6
+ DiagnosisRuledOut,
7
+ } from "../../api/diagnose";
8
+ import { InvestigationEvidencePane } from "./InvestigationEvidencePane";
9
+ import { resolveInvestigationCase } from "./investigationCase";
10
+ import {
11
+ projectInvestigationEvidence,
12
+ type InvestigationEvidenceTarget,
13
+ type InvestigationEvidenceTimelineItem,
14
+ } from "./investigationEvidence";
15
+ import runs from "./testdata/story-runs.json";
16
+
17
+ // Recorded investigations against the test cluster's fixtures: every Radar
18
+ // tool call of the run as the UI received it, and the final verdict.
19
+ interface RecordedRun {
20
+ target: InvestigationEvidenceTarget;
21
+ timeline: InvestigationEvidenceTimelineItem[];
22
+ diagnosis: {
23
+ evidence: DiagnosisEvidenceItem[];
24
+ report: string;
25
+ ruledOut?: DiagnosisRuledOut[];
26
+ };
27
+ }
28
+ const recorded = runs as unknown as Record<string, RecordedRun>;
29
+
30
+ function resolve(run: RecordedRun) {
31
+ const projection = projectInvestigationEvidence(
32
+ [{ timeline: run.timeline }],
33
+ run.target,
34
+ );
35
+ return {
36
+ projection,
37
+ investigationCase: resolveInvestigationCase(projection, run.diagnosis, 0),
38
+ };
39
+ }
40
+
41
+ function renderPane(run: RecordedRun) {
42
+ const { projection, investigationCase } = resolve(run);
43
+ return renderToStaticMarkup(
44
+ <InvestigationEvidencePane
45
+ projection={projection}
46
+ investigationCase={investigationCase}
47
+ story={{ report: run.diagnosis.report, evidence: run.diagnosis.evidence }}
48
+ collecting={false}
49
+ animateGroupIds={new Set()}
50
+ onViewSource={() => {}}
51
+ onViewActivity={() => {}}
52
+ />,
53
+ );
54
+ }
55
+
56
+ describe("a Pod cited for the agent's own Prometheus query", () => {
57
+ // Both runs cite their restart-count query as evidence 2, naming the one
58
+ // Pod the query selects (`pod=~"^(<pod>)$"`) rather than the Deployment.
59
+ const cases = [
60
+ ["run-7885e0cdb0", "api-7c6f9c7bb9-p9czp"],
61
+ ["run-01f749634a", "batch-worker-74b5656749-phx2t"],
62
+ ] as const;
63
+
64
+ it.each(cases)("%s pins the citation to the query's chart", (id, pod) => {
65
+ const run = recorded[id];
66
+ expect(run.diagnosis.evidence[2].subject).toMatchObject({
67
+ kind: "Pod",
68
+ name: pod,
69
+ observation: "metrics",
70
+ });
71
+ const item = resolve(run).investigationCase.items.find(
72
+ (candidate) => candidate.index === 2,
73
+ );
74
+ expect(item?.placement).toBe("card");
75
+ expect(item?.source.tool).toBe("query_prometheus");
76
+ expect(item?.observation?.data).toMatchObject({
77
+ type: "metrics",
78
+ origin: "query",
79
+ });
80
+ });
81
+
82
+ it.each(cases)("%s loses no cited result in the story", (id) => {
83
+ const html = renderPane(recorded[id]);
84
+ expect(html).not.toContain("could not be shown here");
85
+ expect(html).not.toContain("data-story-lost-support");
86
+ });
87
+
88
+ it("does not pin a Pod the query does not select", () => {
89
+ const run = recorded["run-7885e0cdb0"];
90
+ const other = {
91
+ ...run,
92
+ diagnosis: {
93
+ ...run.diagnosis,
94
+ evidence: run.diagnosis.evidence.map((entry, index) =>
95
+ index === 2 && entry.subject
96
+ ? { ...entry, subject: { ...entry.subject, name: "api-other" } }
97
+ : entry,
98
+ ),
99
+ },
100
+ };
101
+ const item = resolve(other).investigationCase.items.find(
102
+ (candidate) => candidate.index === 2,
103
+ );
104
+ expect(item?.placement).toBe("source");
105
+ });
106
+ });
107
+
108
+ describe("a Pod cited for a target query that selects a sibling", () => {
109
+ it("does not pin the sibling to the target's chart", () => {
110
+ const run = recorded["run-7885e0cdb0"];
111
+ // `deployment="api"` makes the query target-scoped while the pod
112
+ // matcher names a Pod nothing established as the target's own.
113
+ const timeline = run.timeline.map((item) => {
114
+ if (item.kind !== "tool" || item.tool !== "query_prometheus") return item;
115
+ const result = JSON.parse(item.result ?? "{}");
116
+ result.selectors = [
117
+ {
118
+ metric: "kube_pod_container_status_restarts_total",
119
+ matchers: [
120
+ { label: "namespace", op: "=", value: "gl-crash-config" },
121
+ { label: "deployment", op: "=", value: "api" },
122
+ { label: "pod", op: "=", value: "sibling-0" },
123
+ ],
124
+ },
125
+ ];
126
+ return { ...item, result: JSON.stringify(result) };
127
+ });
128
+ const evidence = run.diagnosis.evidence.map((entry, index) =>
129
+ index === 2 && entry.subject
130
+ ? { ...entry, subject: { ...entry.subject, name: "sibling-0" } }
131
+ : entry,
132
+ );
133
+ const { projection, investigationCase } = resolve({
134
+ ...run,
135
+ timeline,
136
+ diagnosis: { ...run.diagnosis, evidence },
137
+ });
138
+ const chart = projection.groups
139
+ .flatMap((group) => group.observations)
140
+ .find((observation) => observation.source.tool === "query_prometheus");
141
+ expect(chart?.relevance).toBe("target");
142
+ const item = investigationCase.items.find(
143
+ (candidate) => candidate.index === 2,
144
+ );
145
+ expect(item?.placement).toBe("source");
146
+ });
147
+ });
148
+
149
+ describe("a Pod cited for a diagnose bundle's chart", () => {
150
+ // The herring run rules out memory pressure on the bundle's memory chart,
151
+ // naming the Deployment's one Pod: `{kind: Pod, observation:
152
+ // "metrics:memory"}` against charts that state the Deployment.
153
+ const run = recorded["run-01f749634a"];
154
+ const itemThree = (candidate: RecordedRun) =>
155
+ resolve(candidate).investigationCase.items.find((item) => item.index === 3);
156
+ // Rewrites the diagnose payload, the source of both the charts and the
157
+ // pods Radar establishes as the target's own.
158
+ const withDiagnose = (
159
+ edit: (payload: Record<string, unknown>) => void,
160
+ ): RecordedRun => ({
161
+ ...run,
162
+ timeline: run.timeline.map((item) => {
163
+ if (item.kind !== "tool" || item.tool !== "diagnose") return item;
164
+ const payload = JSON.parse(item.result ?? "{}");
165
+ edit(payload);
166
+ return { ...item, result: JSON.stringify(payload) };
167
+ }),
168
+ });
169
+
170
+ it("pins the citation to the chart its category names when the target has one Pod", () => {
171
+ expect(run.diagnosis.evidence[3].subject).toMatchObject({
172
+ kind: "Pod",
173
+ name: "batch-worker-74b5656749-phx2t",
174
+ observation: "metrics:memory",
175
+ });
176
+ const item = itemThree(run);
177
+ expect(item?.placement).toBe("card");
178
+ expect(item?.source.tool).toBe("diagnose");
179
+ expect(item?.groupId).toBe(
180
+ resolve(run).projection.groups.find(
181
+ (group) =>
182
+ group.kind === "metrics" &&
183
+ group.identity.endsWith(":memory") &&
184
+ group.latest.source.tool === "diagnose",
185
+ )?.id,
186
+ );
187
+ });
188
+
189
+ it("does not pin one Pod of a target with two", () => {
190
+ const twoPods = withDiagnose((payload) => {
191
+ payload.pods = 2;
192
+ payload.podNames = [
193
+ "batch-worker-74b5656749-phx2t",
194
+ "batch-worker-74b5656749-zzzzz",
195
+ ];
196
+ (payload.metrics as { pods: number }).pods = 2;
197
+ });
198
+ expect(resolve(twoPods).projection.targetPods).toHaveLength(2);
199
+ expect(itemThree(twoPods)?.placement).toBe("source");
200
+ });
201
+
202
+ it("does not pin a Pod when the bundle's pod list was cut short", () => {
203
+ const truncated = withDiagnose((payload) => {
204
+ payload.podNamesTruncated = true;
205
+ });
206
+ expect(itemThree(truncated)?.placement).toBe("source");
207
+ });
208
+
209
+ it("keeps the citation pinned when a later turn diagnoses a replacement Pod", () => {
210
+ // A follow-up reads the workload again after its Pod was replaced. The
211
+ // first chart still covered only the first Pod, so the first assessment's
212
+ // citation stays on that read, now a revision under the newer chart.
213
+ const diagnose = run.timeline.find(
214
+ (item) => item.kind === "tool" && item.tool === "diagnose",
215
+ )!;
216
+ const payload = JSON.parse(
217
+ (diagnose as { result?: string }).result ?? "{}",
218
+ );
219
+ payload.podNames = ["batch-worker-74b5656749-new01"];
220
+ const later = {
221
+ ...diagnose,
222
+ id: "toolu_followup_diagnose",
223
+ result: JSON.stringify(payload),
224
+ evidenceRef: undefined,
225
+ } as InvestigationEvidenceTimelineItem;
226
+ const projection = projectInvestigationEvidence(
227
+ [{ timeline: run.timeline }, { timeline: [later] }],
228
+ run.target,
229
+ );
230
+ expect(projection.targetPods).toHaveLength(2);
231
+ const item = resolveInvestigationCase(
232
+ projection,
233
+ run.diagnosis,
234
+ 0,
235
+ ).items.find((candidate) => candidate.index === 3);
236
+ expect(item?.placement).toBe("revision");
237
+ expect(item?.observation?.source.id).toBe(item?.source.id);
238
+ });
239
+
240
+ it("does not pin a Pod to a chart that summed more than one", () => {
241
+ const summedTwo = withDiagnose((payload) => {
242
+ (payload.metrics as { pods: number }).pods = 2;
243
+ });
244
+ expect(itemThree(summedTwo)?.placement).toBe("source");
245
+ });
246
+
247
+ it("does not pin a Pod the target does not have", () => {
248
+ const other: RecordedRun = {
249
+ ...run,
250
+ diagnosis: {
251
+ ...run.diagnosis,
252
+ evidence: run.diagnosis.evidence.map((entry, index) =>
253
+ index === 3 && entry.subject
254
+ ? {
255
+ ...entry,
256
+ subject: { ...entry.subject, name: "batch-worker-other" },
257
+ }
258
+ : entry,
259
+ ),
260
+ },
261
+ };
262
+ expect(itemThree(other)?.placement).toBe("source");
263
+ });
264
+
265
+ it("does not pick one of the bundle's charts for a Pod citation without a category", () => {
266
+ const bare: RecordedRun = {
267
+ ...run,
268
+ diagnosis: {
269
+ ...run.diagnosis,
270
+ evidence: run.diagnosis.evidence.map((entry, index) =>
271
+ index === 3 && entry.subject
272
+ ? {
273
+ ...entry,
274
+ subject: { ...entry.subject, observation: "metrics" },
275
+ }
276
+ : entry,
277
+ ),
278
+ },
279
+ };
280
+ expect(itemThree(bare)?.placement).toBe("source");
281
+ });
282
+ });
283
+
284
+ describe("a healthy verdict's Pod citations (run-40c65bb5ed)", () => {
285
+ // boutique/adservice: one ready Pod. The agent rules out restarts on its own
286
+ // 7-day query and resource pressure on the bundle's memory chart, naming
287
+ // the Pod both times.
288
+ const run = recorded["run-40c65bb5ed"];
289
+
290
+ it("places both citations and keeps both ruled-out hypotheses", () => {
291
+ const { investigationCase } = resolve(run);
292
+ const byIndex = (index: number) =>
293
+ investigationCase.items.find((item) => item.index === index);
294
+ expect(byIndex(2)).toMatchObject({
295
+ placement: "card",
296
+ source: { tool: "query_prometheus" },
297
+ });
298
+ expect(byIndex(3)).toMatchObject({
299
+ placement: "card",
300
+ source: { tool: "diagnose" },
301
+ });
302
+ expect(byIndex(3)?.observation?.data).toMatchObject({
303
+ type: "metrics",
304
+ origin: "diagnose",
305
+ label: "Memory working set",
306
+ });
307
+ expect(investigationCase.ruledOut.map((entry) => entry.hypothesis)).toEqual(
308
+ [
309
+ "Crash loop or OOM-kill restarts",
310
+ "Container pressing against its memory/CPU limits",
311
+ ],
312
+ );
313
+ });
314
+
315
+ it("loses no cited result in the story", () => {
316
+ const html = renderPane(run);
317
+ expect(html).not.toContain("could not be shown here");
318
+ expect(html).not.toContain("data-story-lost-support");
319
+ });
320
+ });
321
+
322
+ describe("run-8b924c437a", () => {
323
+ it("places every story citation", () => {
324
+ const html = renderPane(recorded["run-8b924c437a"]);
325
+ expect(html).not.toContain("could not be shown here");
326
+ expect(html).not.toContain("data-story-lost-support");
327
+ });
328
+ });
@@ -8,6 +8,7 @@ import {
8
8
  investigationEvidenceSubjectRef,
9
9
  investigationSourceArgs,
10
10
  isInvestigationEvidenceRef,
11
+ metricsSelectedPod,
11
12
  sameKind,
12
13
  type InvestigationEvidenceData,
13
14
  type InvestigationEvidenceGroup,
@@ -408,7 +409,7 @@ function observationMatchesSubject(
408
409
  // name is the handle that tells them apart.
409
410
  if (observation.data.type === "alerts" && subject.name !== undefined)
410
411
  return observation.data.rule.name === subject.name;
411
- const identities = observationIdentities(observation);
412
+ const identities = observationIdentities(observation, targetPods);
412
413
  // An observation that states no resource of its own (an agent-run query
413
414
  // whose selectors do not name the target exactly, a topology summary) can
414
415
  // only be named by its evidence kind; the ref and the uniqueness rule do
@@ -427,6 +428,7 @@ function observationMatchesSubject(
427
428
  */
428
429
  function observationIdentities(
429
430
  observation: InvestigationEvidenceObservation,
431
+ targetPods: ReadonlySet<string>,
430
432
  ): ObservationSubjectIdentity[] {
431
433
  const stated = observationSubjectIdentity(observation);
432
434
  const identities = stated ? [stated] : [];
@@ -460,6 +462,36 @@ function observationIdentities(
460
462
  });
461
463
  }
462
464
  }
465
+ // A chart about the target that covers exactly one Pod is also that Pod's
466
+ // chart, and only for a Pod established as the target's own. An agent-run
467
+ // query says which Pod in its selectors, and a workload label can make it
468
+ // target-scoped while its pod matcher names a sibling. A diagnose bundle's
469
+ // chart parses no selectors; its own call lists the pods it summed, so it
470
+ // is a Pod's chart only when that list is the one Pod. A multi-pod
471
+ // aggregate never stands in for one of its pods, and a later read of a
472
+ // replacement Pod does not change what an earlier chart covered.
473
+ if (
474
+ observation.data.type === "metrics" &&
475
+ observation.relevance === "target" &&
476
+ stated
477
+ ) {
478
+ const { data } = observation;
479
+ const pod =
480
+ data.origin === "query"
481
+ ? metricsSelectedPod(data.selectors ?? [])
482
+ : data.pods === 1 &&
483
+ data.partial !== true &&
484
+ data.podNames?.length === 1
485
+ ? data.podNames[0]
486
+ : undefined;
487
+ if (pod && targetPods.has(pod))
488
+ identities.push({
489
+ kind: "Pod",
490
+ group: "",
491
+ namespace: stated.namespace,
492
+ name: pod,
493
+ });
494
+ }
463
495
  if (observation.data.type === "logs" && stated) {
464
496
  const args = investigationSourceArgs(observation.source);
465
497
  if (args && nonEmptyString(args.kind) && nonEmptyString(args.name)) {