@granular-software/fractory 0.0.0-stage → 0.1.24

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 (273) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +28 -2
  3. package/dist/activity-volume.d.ts +18 -0
  4. package/dist/activity-volume.js +94 -0
  5. package/dist/annotations.d.ts +118 -0
  6. package/dist/annotations.js +304 -0
  7. package/dist/benchmark-cli.d.ts +1 -0
  8. package/dist/benchmark-cli.js +95 -0
  9. package/dist/benchmark-worker.d.ts +2 -0
  10. package/dist/benchmark-worker.js +22 -0
  11. package/dist/benchmarks.d.ts +19 -0
  12. package/dist/benchmarks.js +414 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +63 -0
  15. package/dist/block-cli.d.ts +1 -0
  16. package/dist/block-cli.js +88 -0
  17. package/dist/block-documents.d.ts +35 -0
  18. package/dist/block-documents.js +84 -0
  19. package/dist/change-impact.d.ts +55 -0
  20. package/dist/change-impact.js +223 -0
  21. package/dist/check-source.d.ts +2 -0
  22. package/dist/check-source.js +66 -0
  23. package/dist/checks-model.d.ts +64 -0
  24. package/dist/checks-model.js +36 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +359 -0
  27. package/dist/code-model.d.ts +38 -0
  28. package/dist/code-model.js +94 -0
  29. package/dist/code-store.d.ts +9 -0
  30. package/dist/code-store.js +79 -0
  31. package/dist/compare-artifact.d.ts +6 -0
  32. package/dist/compare-artifact.js +277 -0
  33. package/dist/compare.d.ts +81 -0
  34. package/dist/compare.js +291 -0
  35. package/dist/compiler.d.ts +10 -0
  36. package/dist/compiler.js +1083 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +86 -0
  40. package/dist/core.js +206 -0
  41. package/dist/coverage-cli.d.ts +1 -0
  42. package/dist/coverage-cli.js +42 -0
  43. package/dist/declaration-sources.d.ts +3 -0
  44. package/dist/declaration-sources.js +51 -0
  45. package/dist/declared-graph.d.ts +3 -0
  46. package/dist/declared-graph.js +66 -0
  47. package/dist/display-name.d.ts +2 -0
  48. package/dist/display-name.js +8 -0
  49. package/dist/error-heat.d.ts +58 -0
  50. package/dist/error-heat.js +96 -0
  51. package/dist/evidence.d.ts +3 -0
  52. package/dist/evidence.js +68 -0
  53. package/dist/factory-graph.d.ts +4 -0
  54. package/dist/factory-graph.js +318 -0
  55. package/dist/factory-model.d.ts +97 -0
  56. package/dist/factory-model.js +1 -0
  57. package/dist/git-code.d.ts +47 -0
  58. package/dist/git-code.js +352 -0
  59. package/dist/git-refs.d.ts +4 -0
  60. package/dist/git-refs.js +37 -0
  61. package/dist/history-activity.d.ts +4 -0
  62. package/dist/history-activity.js +129 -0
  63. package/dist/history-churn.d.ts +36 -0
  64. package/dist/history-churn.js +302 -0
  65. package/dist/history-git.d.ts +21 -0
  66. package/dist/history-git.js +125 -0
  67. package/dist/history-ledger.d.ts +43 -0
  68. package/dist/history-ledger.js +450 -0
  69. package/dist/history-ownership.d.ts +10 -0
  70. package/dist/history-ownership.js +75 -0
  71. package/dist/history-source.d.ts +13 -0
  72. package/dist/history-source.js +100 -0
  73. package/dist/integrations-cli.d.ts +2 -0
  74. package/dist/integrations-cli.js +159 -0
  75. package/dist/issue-cache.d.ts +9 -0
  76. package/dist/issue-cache.js +68 -0
  77. package/dist/issue-cli.d.ts +1 -0
  78. package/dist/issue-cli.js +89 -0
  79. package/dist/issue-links.d.ts +15 -0
  80. package/dist/issue-links.js +125 -0
  81. package/dist/linear-issues.d.ts +19 -0
  82. package/dist/linear-issues.js +124 -0
  83. package/dist/local-runtime.d.ts +8 -0
  84. package/dist/local-runtime.js +59 -0
  85. package/dist/map-activity.d.ts +73 -0
  86. package/dist/map-activity.js +234 -0
  87. package/dist/map-model.d.ts +5 -0
  88. package/dist/map-model.js +166 -0
  89. package/dist/map-quality.d.ts +14 -0
  90. package/dist/map-quality.js +56 -0
  91. package/dist/mapping-coverage.d.ts +87 -0
  92. package/dist/mapping-coverage.js +404 -0
  93. package/dist/model.d.ts +182 -0
  94. package/dist/model.js +66 -0
  95. package/dist/operation-benchmark-worker.d.ts +2 -0
  96. package/dist/operation-benchmark-worker.js +60 -0
  97. package/dist/operation-benchmark.d.ts +29 -0
  98. package/dist/operation-benchmark.js +1 -0
  99. package/dist/otel-metrics.d.ts +21 -0
  100. package/dist/otel-metrics.js +146 -0
  101. package/dist/performance-model.d.ts +185 -0
  102. package/dist/performance-model.js +396 -0
  103. package/dist/product-map.d.ts +69 -0
  104. package/dist/product-map.js +168 -0
  105. package/dist/provider-access.cjs +207 -0
  106. package/dist/provider-access.d.cts +14 -0
  107. package/dist/reports-cli.d.ts +1 -0
  108. package/dist/reports-cli.js +111 -0
  109. package/dist/reports-model.d.ts +27 -0
  110. package/dist/reports-model.js +39 -0
  111. package/dist/reports.d.ts +23 -0
  112. package/dist/reports.js +223 -0
  113. package/dist/repository-map.d.ts +22 -0
  114. package/dist/repository-map.js +151 -0
  115. package/dist/resource-cache.d.ts +17 -0
  116. package/dist/resource-cache.js +65 -0
  117. package/dist/review-cli.d.ts +19 -0
  118. package/dist/review-cli.js +224 -0
  119. package/dist/review.d.ts +48 -0
  120. package/dist/review.js +289 -0
  121. package/dist/runtime-metrics.d.ts +26 -0
  122. package/dist/runtime-metrics.js +290 -0
  123. package/dist/scope.d.ts +12 -0
  124. package/dist/scope.js +94 -0
  125. package/dist/sentry-activity.d.ts +39 -0
  126. package/dist/sentry-activity.js +174 -0
  127. package/dist/sentry.d.ts +130 -0
  128. package/dist/sentry.js +369 -0
  129. package/dist/service-release.d.ts +16 -0
  130. package/dist/service-release.js +14 -0
  131. package/dist/setup-cli.d.ts +2 -0
  132. package/dist/setup-cli.js +52 -0
  133. package/dist/setup-kit.cjs +163 -0
  134. package/dist/setup-kit.d.cts +32 -0
  135. package/dist/source-index.d.ts +37 -0
  136. package/dist/source-index.js +166 -0
  137. package/dist/source-review-git.d.ts +7 -0
  138. package/dist/source-review-git.js +103 -0
  139. package/dist/source-review.d.ts +16 -0
  140. package/dist/source-review.js +493 -0
  141. package/dist/telemetry.d.ts +17 -0
  142. package/dist/telemetry.js +51 -0
  143. package/dist/time-window.d.ts +9 -0
  144. package/dist/time-window.js +35 -0
  145. package/dist/trace-evidence.d.ts +23 -0
  146. package/dist/trace-evidence.js +55 -0
  147. package/dist/trace-model.d.ts +26 -0
  148. package/dist/trace-model.js +1 -0
  149. package/dist/tracing.d.ts +44 -0
  150. package/dist/tracing.js +123 -0
  151. package/dist/work-check.d.ts +17 -0
  152. package/dist/work-check.js +110 -0
  153. package/dist/work-cli.d.ts +1 -0
  154. package/dist/work-cli.js +148 -0
  155. package/dist/work-context.d.ts +57 -0
  156. package/dist/work-context.js +568 -0
  157. package/dist/work-intents.d.ts +6 -0
  158. package/dist/work-intents.js +140 -0
  159. package/dist/work-items.d.ts +58 -0
  160. package/dist/work-items.js +86 -0
  161. package/dist/work-model.d.ts +110 -0
  162. package/dist/work-model.js +261 -0
  163. package/dist/work-review-git.d.ts +8 -0
  164. package/dist/work-review-git.js +111 -0
  165. package/dist/work-review.d.ts +26 -0
  166. package/dist/work-review.js +426 -0
  167. package/dist/work-switcher-model.d.ts +43 -0
  168. package/dist/work-switcher-model.js +79 -0
  169. package/dist/work-switcher.d.ts +6 -0
  170. package/dist/work-switcher.js +171 -0
  171. package/dist/working-cli.d.ts +1 -0
  172. package/dist/working-cli.js +33 -0
  173. package/dist/working-code.d.ts +74 -0
  174. package/dist/working-code.js +421 -0
  175. package/dist/workspace-notes.d.ts +71 -0
  176. package/dist/workspace-notes.js +177 -0
  177. package/dist/workspace-tests.d.ts +21 -0
  178. package/dist/workspace-tests.js +573 -0
  179. package/package.json +547 -4
  180. package/src/activity-volume.ts +149 -0
  181. package/src/annotations.ts +481 -0
  182. package/src/benchmark-cli.ts +118 -0
  183. package/src/benchmark-worker.ts +22 -0
  184. package/src/benchmarks.ts +493 -0
  185. package/src/bin.ts +54 -0
  186. package/src/block-cli.ts +106 -0
  187. package/src/block-documents.ts +117 -0
  188. package/src/change-impact.ts +280 -0
  189. package/src/check-source.ts +82 -0
  190. package/src/checks-model.ts +108 -0
  191. package/src/cli.ts +440 -0
  192. package/src/code-model.ts +159 -0
  193. package/src/code-store.ts +98 -0
  194. package/src/compare-artifact.ts +314 -0
  195. package/src/compare.ts +440 -0
  196. package/src/compiler.ts +1326 -0
  197. package/src/compose.ts +94 -0
  198. package/src/core.ts +357 -0
  199. package/src/coverage-cli.ts +52 -0
  200. package/src/declaration-sources.ts +69 -0
  201. package/src/declared-graph.ts +74 -0
  202. package/src/display-name.ts +8 -0
  203. package/src/error-heat.ts +161 -0
  204. package/src/evidence.ts +94 -0
  205. package/src/factory-graph.ts +378 -0
  206. package/src/factory-model.ts +73 -0
  207. package/src/git-code.ts +461 -0
  208. package/src/git-refs.ts +43 -0
  209. package/src/history-activity.ts +146 -0
  210. package/src/history-churn.ts +416 -0
  211. package/src/history-git.ts +163 -0
  212. package/src/history-ledger.ts +636 -0
  213. package/src/history-ownership.ts +116 -0
  214. package/src/history-source.ts +117 -0
  215. package/src/integrations-cli.ts +187 -0
  216. package/src/issue-cache.ts +96 -0
  217. package/src/issue-cli.ts +137 -0
  218. package/src/issue-links.ts +153 -0
  219. package/src/linear-issues.ts +154 -0
  220. package/src/local-runtime.ts +70 -0
  221. package/src/map-activity.ts +309 -0
  222. package/src/map-model.ts +213 -0
  223. package/src/map-quality.ts +61 -0
  224. package/src/mapping-coverage.ts +570 -0
  225. package/src/model.ts +221 -0
  226. package/src/operation-benchmark-worker.ts +60 -0
  227. package/src/operation-benchmark.ts +28 -0
  228. package/src/otel-metrics.ts +176 -0
  229. package/src/performance-model.ts +575 -0
  230. package/src/product-map.ts +236 -0
  231. package/src/provider-access.cjs +207 -0
  232. package/src/provider-access.d.cts +14 -0
  233. package/src/reports-cli.ts +125 -0
  234. package/src/reports-model.ts +73 -0
  235. package/src/reports.ts +276 -0
  236. package/src/repository-map.ts +189 -0
  237. package/src/resource-cache.ts +76 -0
  238. package/src/review-cli.ts +256 -0
  239. package/src/review.ts +376 -0
  240. package/src/runtime-metrics.ts +386 -0
  241. package/src/scope.ts +103 -0
  242. package/src/sentry-activity.ts +234 -0
  243. package/src/sentry.ts +545 -0
  244. package/src/service-release.ts +18 -0
  245. package/src/setup-cli.ts +58 -0
  246. package/src/setup-kit.cjs +163 -0
  247. package/src/setup-kit.d.cts +32 -0
  248. package/src/source-index.ts +205 -0
  249. package/src/source-review-git.ts +129 -0
  250. package/src/source-review.ts +637 -0
  251. package/src/telemetry.ts +68 -0
  252. package/src/time-window.ts +51 -0
  253. package/src/trace-evidence.ts +80 -0
  254. package/src/trace-model.ts +26 -0
  255. package/src/tracing.ts +165 -0
  256. package/src/work-check.ts +143 -0
  257. package/src/work-cli.ts +195 -0
  258. package/src/work-context.ts +713 -0
  259. package/src/work-intents.ts +196 -0
  260. package/src/work-items.ts +151 -0
  261. package/src/work-model.ts +400 -0
  262. package/src/work-review-git.ts +130 -0
  263. package/src/work-review.ts +573 -0
  264. package/src/work-switcher-model.ts +121 -0
  265. package/src/work-switcher.ts +191 -0
  266. package/src/working-cli.ts +38 -0
  267. package/src/working-code.ts +582 -0
  268. package/src/workspace-notes.ts +203 -0
  269. package/src/workspace-tests.ts +654 -0
  270. package/toolkit/GUIDE.md +305 -0
  271. package/toolkit/SKILL.md +131 -0
  272. package/toolkit/bin/fractory +2 -0
  273. package/toolkit/build.json +1 -0
@@ -0,0 +1,386 @@
1
+ import { readFileSync, existsSync, statSync } from "node:fs";
2
+ import { checkedPath } from "./workspace-notes";
3
+ import type { DefinitionGraph } from "./model";
4
+ import type { TimeWindow } from "./time-window";
5
+ import type {
6
+ RuntimeMetrics,
7
+ MetricBoundary,
8
+ MetricGauge,
9
+ } from "./performance-model";
10
+ export interface MetricsConnection {
11
+ url?: string;
12
+ token?: string;
13
+ username?: string;
14
+ environment?: string;
15
+ }
16
+ export function metricsConnection(env = process.env): MetricsConnection {
17
+ return {
18
+ url: env.FRACTAL_METRICS_URL,
19
+ token: env.FRACTAL_METRICS_TOKEN,
20
+ username: env.FRACTAL_METRICS_USERNAME,
21
+ environment: env.FRACTAL_METRICS_ENVIRONMENT || "production",
22
+ };
23
+ }
24
+ type PromSeries = {
25
+ metric: Record<string, string>;
26
+ value?: [number, string];
27
+ values?: [number, string][];
28
+ };
29
+ export class PrometheusReader {
30
+ constructor(
31
+ private configuration: MetricsConnection,
32
+ private transport: typeof fetch = fetch,
33
+ ) {}
34
+ async query(
35
+ query: string,
36
+ at: string,
37
+ range?: { from: string; step: number },
38
+ ): Promise<PromSeries[]> {
39
+ if (!this.configuration.url)
40
+ throw Error("Connect a Prometheus metrics source in Integrations.");
41
+ const base = new URL(this.configuration.url);
42
+ if (
43
+ base.username ||
44
+ base.password ||
45
+ (base.protocol !== "https:" &&
46
+ !(
47
+ base.protocol === "http:" &&
48
+ ["127.0.0.1", "localhost", "[::1]"].includes(base.hostname)
49
+ ))
50
+ )
51
+ throw Error("Use HTTPS, or a local Prometheus endpoint.");
52
+ const url = new URL(
53
+ base.pathname.replace(/\/$/, "") +
54
+ "/api/v1/" +
55
+ (range ? "query_range" : "query"),
56
+ base.origin,
57
+ );
58
+ url.searchParams.set("query", query);
59
+ if (range) {
60
+ url.searchParams.set("start", range.from);
61
+ url.searchParams.set("end", at);
62
+ url.searchParams.set("step", String(range.step));
63
+ } else url.searchParams.set("time", at);
64
+ const headers: Record<string, string> = { Accept: "application/json" };
65
+ if (this.configuration.token)
66
+ headers.Authorization = this.configuration.username
67
+ ? "Basic " +
68
+ Buffer.from(
69
+ this.configuration.username + ":" + this.configuration.token,
70
+ ).toString("base64")
71
+ : "Bearer " + this.configuration.token;
72
+ const response = await this.transport(url, {
73
+ headers,
74
+ redirect: "error",
75
+ signal: AbortSignal.timeout(15000),
76
+ });
77
+ if (!response.ok)
78
+ throw Object.assign(
79
+ Error(
80
+ `Metrics source returned ${response.status}. Check its read credential and URL.`,
81
+ ),
82
+ { status: response.status },
83
+ );
84
+ const reader = response.body?.getReader();
85
+ if (!reader) throw Error("Empty metrics response");
86
+ const chunks: Uint8Array[] = [];
87
+ let size = 0;
88
+ while (true) {
89
+ const { done, value } = await reader.read();
90
+ if (done) break;
91
+ size += value.length;
92
+ if (size > 6 * 1024 * 1024) {
93
+ await reader.cancel();
94
+ throw Error(
95
+ "Metrics query exceeds the 6 MB read limit. Narrow the selected period.",
96
+ );
97
+ }
98
+ chunks.push(value);
99
+ }
100
+ let payload: any;
101
+ try {
102
+ payload = JSON.parse(Buffer.concat(chunks).toString());
103
+ } catch {
104
+ throw Error("Metrics source returned an invalid response.");
105
+ }
106
+ if (payload.status !== "success" || !Array.isArray(payload.data?.result))
107
+ throw Error("The metrics source rejected this query.");
108
+ if (payload.data.result.length > 24000)
109
+ throw Error("Metrics query returned more than 24,000 series.");
110
+ return payload.data.result;
111
+ }
112
+ }
113
+ function gaugeDefinitions(root: string, graph: DefinitionGraph) {
114
+ const path = checkedPath(root, "fractory.metrics.json", true);
115
+ if (!existsSync(path)) return [];
116
+ if (statSync(path).size > 64000)
117
+ throw Error("Keep fractory.metrics.json below 64 KB");
118
+ const data = JSON.parse(readFileSync(path, "utf8"));
119
+ if (
120
+ data.schema !== "fractory.metrics.v1" ||
121
+ !Array.isArray(data.gauges) ||
122
+ data.gauges.length > 12
123
+ )
124
+ throw Error("Invalid fractory.metrics.json");
125
+ const ids = new Set(graph.elements.map((node) => node.id));
126
+ for (const gauge of data.gauges)
127
+ if (
128
+ !/^[a-z][a-z0-9_-]{0,40}$/.test(gauge.id) ||
129
+ typeof gauge.label !== "string" ||
130
+ gauge.label.length > 80 ||
131
+ typeof gauge.unit !== "string" ||
132
+ gauge.unit.length > 24 ||
133
+ !["sum", "max"].includes(gauge.aggregation) ||
134
+ (gauge.description !== undefined &&
135
+ (typeof gauge.description !== "string" ||
136
+ gauge.description.length > 300)) ||
137
+ (gauge.chart !== undefined && !["line", "bar"].includes(gauge.chart)) ||
138
+ !Array.isArray(gauge.sources) ||
139
+ gauge.sources.length > 20 ||
140
+ gauge.sources.some(
141
+ (source: any) =>
142
+ !ids.has(source.block) ||
143
+ typeof source.query !== "string" ||
144
+ source.query.length > 1000,
145
+ )
146
+ )
147
+ throw Error(
148
+ "Choose valid gauge labels, units, aggregation and mapped blocks.",
149
+ );
150
+ if (
151
+ data.gauges.reduce(
152
+ (sum: number, gauge: any) => sum + gauge.sources.length,
153
+ 0,
154
+ ) > 20
155
+ )
156
+ throw Error("Keep gauge attachments to at most 20 source queries.");
157
+ return data.gauges as {
158
+ id: string;
159
+ label: string;
160
+ unit: string;
161
+ aggregation: "sum" | "max";
162
+ description?: string;
163
+ chart?: "line" | "bar";
164
+ sources: { block: string; query: string }[];
165
+ }[];
166
+ }
167
+ export async function readRuntimeMetrics(
168
+ root: string,
169
+ graph: DefinitionGraph,
170
+ window: TimeWindow,
171
+ connection = metricsConnection(),
172
+ transport?: typeof fetch,
173
+ ): Promise<RuntimeMetrics> {
174
+ const output: RuntimeMetrics = {
175
+ source: "prometheus",
176
+ configured: !!connection.url,
177
+ window,
178
+ environment: connection.environment || "production",
179
+ checkedAt: new Date().toISOString(),
180
+ boundaries: [],
181
+ gauges: [],
182
+ warnings: [],
183
+ };
184
+ const definitions = existsSync(root) ? gaugeDefinitions(root, graph) : [];
185
+ output.gauges = definitions.map((d) => ({
186
+ ...d,
187
+ status: "empty",
188
+ values: [],
189
+ }));
190
+ if (!connection.url) return output;
191
+ const seconds = Math.ceil(
192
+ (Date.parse(window.to) - Date.parse(window.from)) / 1000,
193
+ ),
194
+ step = Math.max(60, Math.ceil(seconds / 32));
195
+ const selector = `{fractory_environment=${JSON.stringify(output.environment)}}`;
196
+ const labels = "fractory_target,fractory_caller";
197
+ const reader = new PrometheusReader(connection, transport);
198
+ const queried = await Promise.allSettled([
199
+ reader.query(
200
+ `sum by (${labels},fractory_outcome) (increase(fractory_calls_total${selector}[${seconds}s]))`,
201
+ window.to,
202
+ ),
203
+ reader.query(
204
+ `sum by (${labels},le) (increase(fractory_duration_seconds_bucket${selector}[${seconds}s]))`,
205
+ window.to,
206
+ ),
207
+ reader.query(
208
+ `sum by (${labels},fractory_outcome) (rate(fractory_calls_total${selector}[${Math.max(60, step * 2)}s]))`,
209
+ window.to,
210
+ { from: window.from, step },
211
+ ),
212
+ reader.query(
213
+ `max(timestamp(fractory_calls_total${selector})) by ()`,
214
+ window.to,
215
+ ),
216
+ reader.query(
217
+ `sum by (${labels},le) (rate(fractory_duration_seconds_bucket${selector}[${Math.max(300, step * 2)}s]))`,
218
+ window.to,
219
+ { from: window.from, step },
220
+ ),
221
+ ]);
222
+ if (
223
+ queried[0].status === "rejected" &&
224
+ [401, 403].includes(queried[0].reason?.status)
225
+ )
226
+ throw queried[0].reason;
227
+ const [counts, buckets, trend, latest, latency] = queried.map(
228
+ (result, index) => {
229
+ if (result.status === "fulfilled") return result.value;
230
+ output.warnings.push(
231
+ `${["Calls", "Latency", "Trend", "Last sample", "Latency trend"][index]} unavailable: ${result.reason instanceof Error ? result.reason.message : "query failed"}`,
232
+ );
233
+ return [] as PromSeries[];
234
+ },
235
+ );
236
+ const rows = new Map<string, MetricBoundary>();
237
+ const row = (metric: Record<string, string>) => {
238
+ if (!metric.fractory_target) return undefined;
239
+ const caller =
240
+ metric.fractory_caller === "external"
241
+ ? undefined
242
+ : metric.fractory_caller;
243
+ const key = JSON.stringify([metric.fractory_target, caller]);
244
+ let value = rows.get(key);
245
+ if (!value) {
246
+ value = {
247
+ target: metric.fractory_target,
248
+ caller,
249
+ calls: 0,
250
+ callsKnown: false,
251
+ errors: 0,
252
+ buckets: [],
253
+ trend: [],
254
+ };
255
+ rows.set(key, value);
256
+ }
257
+ return value;
258
+ };
259
+ for (const series of counts) {
260
+ const target = row(series.metric),
261
+ value = Number(series.value?.[1]);
262
+ if (!target || !Number.isFinite(value) || value < 0) continue;
263
+ target.callsKnown = true;
264
+ target.calls += value;
265
+ if (series.metric.fractory_outcome === "error") target.errors += value;
266
+ }
267
+ const unlabelled = counts.filter(
268
+ (series) => !series.metric.fractory_target,
269
+ ).length;
270
+ if (unlabelled)
271
+ output.warnings.push(
272
+ `${unlabelled} aggregate series have no factory target label; check instrumentation cardinality and attribute export.`,
273
+ );
274
+ for (const series of buckets) {
275
+ const target = row(series.metric),
276
+ count = Number(series.value?.[1]),
277
+ le =
278
+ series.metric.le === "+Inf"
279
+ ? Number.MAX_VALUE
280
+ : Number(series.metric.le);
281
+ if (!target || !Number.isFinite(count) || count < 0 || !Number.isFinite(le))
282
+ continue;
283
+ target.buckets.push({ le, count });
284
+ }
285
+ for (const series of trend) {
286
+ const target = row(series.metric);
287
+ if (!target) continue;
288
+ for (const [at, text] of series.values || []) {
289
+ const value = Number(text) * 60;
290
+ if (!Number.isFinite(value) || value < 0) continue;
291
+ const time = at * 1000;
292
+ const existing = target.trend.find((p) => p.at === time);
293
+ if (existing) existing.value += value;
294
+ else target.trend.push({ at: time, value });
295
+ if (series.metric.fractory_outcome === "error") {
296
+ target.failedTrend ||= [];
297
+ const point = target.failedTrend.find((p) => p.at === time);
298
+ if (point) point.value += value;
299
+ else target.failedTrend.push({ at: time, value });
300
+ }
301
+ }
302
+ }
303
+ for (const series of latency) {
304
+ const target = row(series.metric),
305
+ le =
306
+ series.metric.le === "+Inf"
307
+ ? Number.MAX_VALUE
308
+ : Number(series.metric.le);
309
+ if (!target || !Number.isFinite(le)) continue;
310
+ target.latencyTrend ||= [];
311
+ for (const [at, text] of series.values || []) {
312
+ const count = Number(text);
313
+ if (!Number.isFinite(count) || count < 0) continue;
314
+ const time = at * 1000;
315
+ let point = target.latencyTrend.find((p) => p.at === time);
316
+ if (!point) {
317
+ point = { at: time, buckets: [] };
318
+ target.latencyTrend.push(point);
319
+ }
320
+ point.buckets.push({ le, count });
321
+ }
322
+ }
323
+ for (const value of rows.values()) value.buckets.sort((a, b) => a.le - b.le);
324
+ output.boundaries = [...rows.values()];
325
+ const last = Number(latest[0]?.value?.[1]);
326
+ if (Number.isFinite(last))
327
+ output.lastSampleAt = new Date(last * 1000).toISOString();
328
+ output.gauges = [];
329
+ for (const definition of definitions) {
330
+ const gauge: MetricGauge = { ...definition, status: "empty", values: [] };
331
+ const results = await Promise.all(
332
+ definition.sources.map(async (source) => {
333
+ let result: PromSeries[];
334
+ try {
335
+ result = await reader.query(
336
+ source.query.replace(
337
+ /\$environment\b/g,
338
+ JSON.stringify(output.environment),
339
+ ),
340
+ window.to,
341
+ { from: window.from, step },
342
+ );
343
+ } catch {
344
+ gauge.status = "error";
345
+ gauge.error = "Source query unavailable";
346
+ output.warnings.push(`${definition.label}: source query unavailable`);
347
+ return;
348
+ }
349
+ // Gauges must explicitly reduce to one series; arbitrary series are never silently summed.
350
+ if (result.length > 1) {
351
+ output.warnings.push(
352
+ `${definition.label}: query must return one series per attached source`,
353
+ );
354
+ return;
355
+ }
356
+ const points = (result[0]?.values || []).flatMap(([at, text]) =>
357
+ Number.isFinite(Number(text))
358
+ ? [{ at: at * 1000, value: Number(text) }]
359
+ : [],
360
+ );
361
+ if (points.length)
362
+ return {
363
+ block: source.block,
364
+ value: points.at(-1)!.value,
365
+ trend: points,
366
+ };
367
+ }),
368
+ );
369
+ gauge.values = results.filter(
370
+ (value): value is NonNullable<typeof value> => !!value,
371
+ );
372
+ if (gauge.values.length && gauge.status !== "error") gauge.status = "ready";
373
+ for (const value of gauge.values) {
374
+ const at = value.trend.at(-1)?.at;
375
+ if (at && (!output.lastSampleAt || at > Date.parse(output.lastSampleAt)))
376
+ output.lastSampleAt = new Date(at).toISOString();
377
+ }
378
+ output.gauges.push(gauge);
379
+ }
380
+ if (
381
+ queried.every((r) => r.status === "rejected") &&
382
+ !output.gauges.some((g) => g.values.length)
383
+ )
384
+ throw (queried[0] as PromiseRejectedResult).reason;
385
+ return output;
386
+ }
package/src/scope.ts ADDED
@@ -0,0 +1,103 @@
1
+ import type { DefinitionGraph, Element, Connection } from "./model";
2
+
3
+ /** A focused scope shows its contents and genuine external endpoints, never unrelated siblings. */
4
+ export function scopeGraph(
5
+ graph: DefinitionGraph,
6
+ focus: string,
7
+ expanded: ReadonlySet<string>,
8
+ ) {
9
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
10
+ const scope = byId.get(focus) || byId.get(graph.id)!;
11
+ const inside = (id: string) => {
12
+ let current = byId.get(id);
13
+ while (current) {
14
+ if (current.id === scope.id) return true;
15
+ current = current.parent ? byId.get(current.parent) : undefined;
16
+ }
17
+ return false;
18
+ };
19
+ const visibleInside = (node: Element): boolean =>
20
+ node.parent === scope.id ||
21
+ (!!node.parent &&
22
+ inside(node.parent) &&
23
+ expanded.has(node.parent) &&
24
+ !!byId.get(node.parent) &&
25
+ visibleInside(byId.get(node.parent)!));
26
+ const nodes = graph.elements.filter(
27
+ (node) => node.id !== scope.id && inside(node.id) && visibleInside(node),
28
+ );
29
+ const shown = new Set(nodes.map((node) => node.id));
30
+ const external = new Set<string>();
31
+ const contextLabel = (node: Element) => {
32
+ const names: string[] = [];
33
+ let current = node.parent ? byId.get(node.parent) : undefined;
34
+ while (current && current.id !== graph.id) {
35
+ names.unshift(current.label);
36
+ current = current.parent ? byId.get(current.parent) : undefined;
37
+ }
38
+ return names.join(" / ");
39
+ };
40
+ const endpoint = (id: string): string | undefined => {
41
+ if (id === scope.id) {
42
+ if (scope.id === graph.id) return;
43
+ if (!shown.has(id)) {
44
+ nodes.push(scope);
45
+ shown.add(id);
46
+ }
47
+ return id;
48
+ }
49
+ let current = byId.get(id);
50
+ if (!current) return;
51
+ if (inside(id)) {
52
+ while (current && !shown.has(current.id))
53
+ current = current.parent ? byId.get(current.parent) : undefined;
54
+ return current?.id;
55
+ }
56
+ // Outside methods meet this scope through their public interface. Preserve
57
+ // original endpoints on the edge for contracts and source inspection.
58
+ if (
59
+ current.kind === "method" &&
60
+ current.parent &&
61
+ byId.get(current.parent)?.kind === "interface"
62
+ ) {
63
+ current = byId.get(current.parent)!;
64
+ id = current.id;
65
+ }
66
+ // At a product-area zoom level, outside peers are product areas too. Keep
67
+ // fine-grained endpoints on the wire instead of filling the canvas with
68
+ // external methods. Deeper views still meet public interfaces directly.
69
+ if (scope.parent === graph.id) {
70
+ while (current.parent && current.parent !== graph.id) {
71
+ const parent = byId.get(current.parent);
72
+ if (!parent) break;
73
+ current = parent;
74
+ }
75
+ id = current.id;
76
+ }
77
+ if (!shown.has(id)) {
78
+ nodes.push(current);
79
+ shown.add(id);
80
+ external.add(id);
81
+ }
82
+ return id;
83
+ };
84
+ const edges: (Connection & {
85
+ originalSource: string;
86
+ originalTarget: string;
87
+ })[] = [];
88
+ for (const edge of graph.connections) {
89
+ if (!inside(edge.source) && !inside(edge.target)) continue;
90
+ const source = endpoint(edge.source),
91
+ target = endpoint(edge.target);
92
+ if (source && target && source !== target)
93
+ edges.push({
94
+ ...edge,
95
+ source,
96
+ target,
97
+ originalSource: edge.source,
98
+ originalTarget: edge.target,
99
+ });
100
+ }
101
+ if (!nodes.length && scope.id !== graph.id) nodes.push(scope);
102
+ return { scope, nodes, edges, external, contextLabel };
103
+ }