@granular-software/fractory 0.0.0-stage → 0.1.25

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 (285) 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 +122 -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 +1240 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +87 -0
  40. package/dist/core.js +207 -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 +67 -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 +7 -0
  54. package/dist/factory-graph.js +389 -0
  55. package/dist/factory-model.d.ts +111 -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/interface-map.d.ts +15 -0
  76. package/dist/interface-map.js +125 -0
  77. package/dist/issue-cache.d.ts +9 -0
  78. package/dist/issue-cache.js +68 -0
  79. package/dist/issue-cli.d.ts +1 -0
  80. package/dist/issue-cli.js +89 -0
  81. package/dist/issue-links.d.ts +15 -0
  82. package/dist/issue-links.js +125 -0
  83. package/dist/linear-issues.d.ts +19 -0
  84. package/dist/linear-issues.js +124 -0
  85. package/dist/local-runtime.d.ts +8 -0
  86. package/dist/local-runtime.js +59 -0
  87. package/dist/map-activity.d.ts +73 -0
  88. package/dist/map-activity.js +234 -0
  89. package/dist/map-model.d.ts +5 -0
  90. package/dist/map-model.js +166 -0
  91. package/dist/map-quality.d.ts +20 -0
  92. package/dist/map-quality.js +61 -0
  93. package/dist/mapping-coverage.d.ts +87 -0
  94. package/dist/mapping-coverage.js +404 -0
  95. package/dist/model.d.ts +186 -0
  96. package/dist/model.js +66 -0
  97. package/dist/operation-benchmark-worker.d.ts +2 -0
  98. package/dist/operation-benchmark-worker.js +60 -0
  99. package/dist/operation-benchmark.d.ts +29 -0
  100. package/dist/operation-benchmark.js +1 -0
  101. package/dist/otel-metrics.d.ts +21 -0
  102. package/dist/otel-metrics.js +146 -0
  103. package/dist/performance-model.d.ts +185 -0
  104. package/dist/performance-model.js +396 -0
  105. package/dist/product-map.d.ts +71 -0
  106. package/dist/product-map.js +197 -0
  107. package/dist/provider-access.cjs +207 -0
  108. package/dist/provider-access.d.cts +14 -0
  109. package/dist/public-boundaries.d.ts +13 -0
  110. package/dist/public-boundaries.js +115 -0
  111. package/dist/reports-cli.d.ts +1 -0
  112. package/dist/reports-cli.js +111 -0
  113. package/dist/reports-model.d.ts +27 -0
  114. package/dist/reports-model.js +39 -0
  115. package/dist/reports.d.ts +23 -0
  116. package/dist/reports.js +223 -0
  117. package/dist/repository-map.d.ts +22 -0
  118. package/dist/repository-map.js +153 -0
  119. package/dist/resource-cache.d.ts +17 -0
  120. package/dist/resource-cache.js +65 -0
  121. package/dist/review-cli.d.ts +19 -0
  122. package/dist/review-cli.js +224 -0
  123. package/dist/review.d.ts +48 -0
  124. package/dist/review.js +289 -0
  125. package/dist/runtime-metrics.d.ts +26 -0
  126. package/dist/runtime-metrics.js +290 -0
  127. package/dist/scope.d.ts +14 -0
  128. package/dist/scope.js +168 -0
  129. package/dist/sentry-activity.d.ts +39 -0
  130. package/dist/sentry-activity.js +174 -0
  131. package/dist/sentry.d.ts +130 -0
  132. package/dist/sentry.js +369 -0
  133. package/dist/service-release.d.ts +16 -0
  134. package/dist/service-release.js +14 -0
  135. package/dist/setup-cli.d.ts +2 -0
  136. package/dist/setup-cli.js +52 -0
  137. package/dist/setup-kit.cjs +163 -0
  138. package/dist/setup-kit.d.cts +32 -0
  139. package/dist/source-index.d.ts +37 -0
  140. package/dist/source-index.js +170 -0
  141. package/dist/source-review-git.d.ts +7 -0
  142. package/dist/source-review-git.js +105 -0
  143. package/dist/source-review.d.ts +18 -0
  144. package/dist/source-review.js +573 -0
  145. package/dist/telemetry.d.ts +17 -0
  146. package/dist/telemetry.js +51 -0
  147. package/dist/time-window.d.ts +9 -0
  148. package/dist/time-window.js +35 -0
  149. package/dist/trace-evidence.d.ts +23 -0
  150. package/dist/trace-evidence.js +55 -0
  151. package/dist/trace-model.d.ts +26 -0
  152. package/dist/trace-model.js +1 -0
  153. package/dist/tracing.d.ts +44 -0
  154. package/dist/tracing.js +123 -0
  155. package/dist/work-check.d.ts +18 -0
  156. package/dist/work-check.js +115 -0
  157. package/dist/work-cli.d.ts +1 -0
  158. package/dist/work-cli.js +176 -0
  159. package/dist/work-context.d.ts +59 -0
  160. package/dist/work-context.js +594 -0
  161. package/dist/work-intents.d.ts +6 -0
  162. package/dist/work-intents.js +140 -0
  163. package/dist/work-items.d.ts +58 -0
  164. package/dist/work-items.js +86 -0
  165. package/dist/work-lock-check.d.ts +12 -0
  166. package/dist/work-lock-check.js +339 -0
  167. package/dist/work-locks.d.ts +10 -0
  168. package/dist/work-locks.js +98 -0
  169. package/dist/work-model.d.ts +119 -0
  170. package/dist/work-model.js +310 -0
  171. package/dist/work-review-git.d.ts +8 -0
  172. package/dist/work-review-git.js +111 -0
  173. package/dist/work-review.d.ts +26 -0
  174. package/dist/work-review.js +426 -0
  175. package/dist/work-switcher-model.d.ts +43 -0
  176. package/dist/work-switcher-model.js +79 -0
  177. package/dist/work-switcher.d.ts +6 -0
  178. package/dist/work-switcher.js +171 -0
  179. package/dist/working-cli.d.ts +1 -0
  180. package/dist/working-cli.js +33 -0
  181. package/dist/working-code.d.ts +74 -0
  182. package/dist/working-code.js +421 -0
  183. package/dist/workspace-notes.d.ts +71 -0
  184. package/dist/workspace-notes.js +177 -0
  185. package/dist/workspace-tests.d.ts +21 -0
  186. package/dist/workspace-tests.js +573 -0
  187. package/package.json +547 -4
  188. package/src/activity-volume.ts +149 -0
  189. package/src/annotations.ts +485 -0
  190. package/src/benchmark-cli.ts +118 -0
  191. package/src/benchmark-worker.ts +22 -0
  192. package/src/benchmarks.ts +493 -0
  193. package/src/bin.ts +54 -0
  194. package/src/block-cli.ts +106 -0
  195. package/src/block-documents.ts +117 -0
  196. package/src/change-impact.ts +280 -0
  197. package/src/check-source.ts +82 -0
  198. package/src/checks-model.ts +108 -0
  199. package/src/cli.ts +440 -0
  200. package/src/code-model.ts +159 -0
  201. package/src/code-store.ts +98 -0
  202. package/src/compare-artifact.ts +314 -0
  203. package/src/compare.ts +440 -0
  204. package/src/compiler.ts +1512 -0
  205. package/src/compose.ts +94 -0
  206. package/src/core.ts +361 -0
  207. package/src/coverage-cli.ts +52 -0
  208. package/src/declaration-sources.ts +69 -0
  209. package/src/declared-graph.ts +75 -0
  210. package/src/display-name.ts +8 -0
  211. package/src/error-heat.ts +161 -0
  212. package/src/evidence.ts +94 -0
  213. package/src/factory-graph.ts +462 -0
  214. package/src/factory-model.ts +82 -0
  215. package/src/git-code.ts +461 -0
  216. package/src/git-refs.ts +43 -0
  217. package/src/history-activity.ts +146 -0
  218. package/src/history-churn.ts +416 -0
  219. package/src/history-git.ts +163 -0
  220. package/src/history-ledger.ts +636 -0
  221. package/src/history-ownership.ts +116 -0
  222. package/src/history-source.ts +117 -0
  223. package/src/integrations-cli.ts +187 -0
  224. package/src/interface-map.ts +166 -0
  225. package/src/issue-cache.ts +96 -0
  226. package/src/issue-cli.ts +137 -0
  227. package/src/issue-links.ts +153 -0
  228. package/src/linear-issues.ts +154 -0
  229. package/src/local-runtime.ts +70 -0
  230. package/src/map-activity.ts +309 -0
  231. package/src/map-model.ts +213 -0
  232. package/src/map-quality.ts +66 -0
  233. package/src/mapping-coverage.ts +570 -0
  234. package/src/model.ts +228 -0
  235. package/src/operation-benchmark-worker.ts +60 -0
  236. package/src/operation-benchmark.ts +28 -0
  237. package/src/otel-metrics.ts +176 -0
  238. package/src/performance-model.ts +575 -0
  239. package/src/product-map.ts +271 -0
  240. package/src/provider-access.cjs +207 -0
  241. package/src/provider-access.d.cts +14 -0
  242. package/src/public-boundaries.ts +143 -0
  243. package/src/reports-cli.ts +125 -0
  244. package/src/reports-model.ts +73 -0
  245. package/src/reports.ts +276 -0
  246. package/src/repository-map.ts +191 -0
  247. package/src/resource-cache.ts +76 -0
  248. package/src/review-cli.ts +256 -0
  249. package/src/review.ts +376 -0
  250. package/src/runtime-metrics.ts +386 -0
  251. package/src/scope.ts +192 -0
  252. package/src/sentry-activity.ts +234 -0
  253. package/src/sentry.ts +545 -0
  254. package/src/service-release.ts +18 -0
  255. package/src/setup-cli.ts +58 -0
  256. package/src/setup-kit.cjs +163 -0
  257. package/src/setup-kit.d.cts +32 -0
  258. package/src/source-index.ts +208 -0
  259. package/src/source-review-git.ts +131 -0
  260. package/src/source-review.ts +736 -0
  261. package/src/telemetry.ts +68 -0
  262. package/src/time-window.ts +51 -0
  263. package/src/trace-evidence.ts +80 -0
  264. package/src/trace-model.ts +26 -0
  265. package/src/tracing.ts +165 -0
  266. package/src/work-check.ts +149 -0
  267. package/src/work-cli.ts +229 -0
  268. package/src/work-context.ts +753 -0
  269. package/src/work-intents.ts +196 -0
  270. package/src/work-items.ts +151 -0
  271. package/src/work-lock-check.ts +549 -0
  272. package/src/work-locks.ts +108 -0
  273. package/src/work-model.ts +466 -0
  274. package/src/work-review-git.ts +130 -0
  275. package/src/work-review.ts +573 -0
  276. package/src/work-switcher-model.ts +121 -0
  277. package/src/work-switcher.ts +191 -0
  278. package/src/working-cli.ts +38 -0
  279. package/src/working-code.ts +582 -0
  280. package/src/workspace-notes.ts +203 -0
  281. package/src/workspace-tests.ts +654 -0
  282. package/toolkit/GUIDE.md +354 -0
  283. package/toolkit/SKILL.md +142 -0
  284. package/toolkit/bin/fractory +2 -0
  285. package/toolkit/build.json +1 -0
@@ -0,0 +1,290 @@
1
+ import { readFileSync, existsSync, statSync } from "node:fs";
2
+ import { checkedPath } from "./workspace-notes.js";
3
+ export function metricsConnection(env = process.env) {
4
+ return {
5
+ url: env.FRACTAL_METRICS_URL,
6
+ token: env.FRACTAL_METRICS_TOKEN,
7
+ username: env.FRACTAL_METRICS_USERNAME,
8
+ environment: env.FRACTAL_METRICS_ENVIRONMENT || "production",
9
+ };
10
+ }
11
+ export class PrometheusReader {
12
+ configuration;
13
+ transport;
14
+ constructor(configuration, transport = fetch) {
15
+ this.configuration = configuration;
16
+ this.transport = transport;
17
+ }
18
+ async query(query, at, range) {
19
+ if (!this.configuration.url)
20
+ throw Error("Connect a Prometheus metrics source in Integrations.");
21
+ const base = new URL(this.configuration.url);
22
+ if (base.username ||
23
+ base.password ||
24
+ (base.protocol !== "https:" &&
25
+ !(base.protocol === "http:" &&
26
+ ["127.0.0.1", "localhost", "[::1]"].includes(base.hostname))))
27
+ throw Error("Use HTTPS, or a local Prometheus endpoint.");
28
+ const url = new URL(base.pathname.replace(/\/$/, "") +
29
+ "/api/v1/" +
30
+ (range ? "query_range" : "query"), base.origin);
31
+ url.searchParams.set("query", query);
32
+ if (range) {
33
+ url.searchParams.set("start", range.from);
34
+ url.searchParams.set("end", at);
35
+ url.searchParams.set("step", String(range.step));
36
+ }
37
+ else
38
+ url.searchParams.set("time", at);
39
+ const headers = { Accept: "application/json" };
40
+ if (this.configuration.token)
41
+ headers.Authorization = this.configuration.username
42
+ ? "Basic " +
43
+ Buffer.from(this.configuration.username + ":" + this.configuration.token).toString("base64")
44
+ : "Bearer " + this.configuration.token;
45
+ const response = await this.transport(url, {
46
+ headers,
47
+ redirect: "error",
48
+ signal: AbortSignal.timeout(15000),
49
+ });
50
+ if (!response.ok)
51
+ throw Object.assign(Error(`Metrics source returned ${response.status}. Check its read credential and URL.`), { status: response.status });
52
+ const reader = response.body?.getReader();
53
+ if (!reader)
54
+ throw Error("Empty metrics response");
55
+ const chunks = [];
56
+ let size = 0;
57
+ while (true) {
58
+ const { done, value } = await reader.read();
59
+ if (done)
60
+ break;
61
+ size += value.length;
62
+ if (size > 6 * 1024 * 1024) {
63
+ await reader.cancel();
64
+ throw Error("Metrics query exceeds the 6 MB read limit. Narrow the selected period.");
65
+ }
66
+ chunks.push(value);
67
+ }
68
+ let payload;
69
+ try {
70
+ payload = JSON.parse(Buffer.concat(chunks).toString());
71
+ }
72
+ catch {
73
+ throw Error("Metrics source returned an invalid response.");
74
+ }
75
+ if (payload.status !== "success" || !Array.isArray(payload.data?.result))
76
+ throw Error("The metrics source rejected this query.");
77
+ if (payload.data.result.length > 24000)
78
+ throw Error("Metrics query returned more than 24,000 series.");
79
+ return payload.data.result;
80
+ }
81
+ }
82
+ function gaugeDefinitions(root, graph) {
83
+ const path = checkedPath(root, "fractory.metrics.json", true);
84
+ if (!existsSync(path))
85
+ return [];
86
+ if (statSync(path).size > 64000)
87
+ throw Error("Keep fractory.metrics.json below 64 KB");
88
+ const data = JSON.parse(readFileSync(path, "utf8"));
89
+ if (data.schema !== "fractory.metrics.v1" ||
90
+ !Array.isArray(data.gauges) ||
91
+ data.gauges.length > 12)
92
+ throw Error("Invalid fractory.metrics.json");
93
+ const ids = new Set(graph.elements.map((node) => node.id));
94
+ for (const gauge of data.gauges)
95
+ if (!/^[a-z][a-z0-9_-]{0,40}$/.test(gauge.id) ||
96
+ typeof gauge.label !== "string" ||
97
+ gauge.label.length > 80 ||
98
+ typeof gauge.unit !== "string" ||
99
+ gauge.unit.length > 24 ||
100
+ !["sum", "max"].includes(gauge.aggregation) ||
101
+ (gauge.description !== undefined &&
102
+ (typeof gauge.description !== "string" ||
103
+ gauge.description.length > 300)) ||
104
+ (gauge.chart !== undefined && !["line", "bar"].includes(gauge.chart)) ||
105
+ !Array.isArray(gauge.sources) ||
106
+ gauge.sources.length > 20 ||
107
+ gauge.sources.some((source) => !ids.has(source.block) ||
108
+ typeof source.query !== "string" ||
109
+ source.query.length > 1000))
110
+ throw Error("Choose valid gauge labels, units, aggregation and mapped blocks.");
111
+ if (data.gauges.reduce((sum, gauge) => sum + gauge.sources.length, 0) > 20)
112
+ throw Error("Keep gauge attachments to at most 20 source queries.");
113
+ return data.gauges;
114
+ }
115
+ export async function readRuntimeMetrics(root, graph, window, connection = metricsConnection(), transport) {
116
+ const output = {
117
+ source: "prometheus",
118
+ configured: !!connection.url,
119
+ window,
120
+ environment: connection.environment || "production",
121
+ checkedAt: new Date().toISOString(),
122
+ boundaries: [],
123
+ gauges: [],
124
+ warnings: [],
125
+ };
126
+ const definitions = existsSync(root) ? gaugeDefinitions(root, graph) : [];
127
+ output.gauges = definitions.map((d) => ({
128
+ ...d,
129
+ status: "empty",
130
+ values: [],
131
+ }));
132
+ if (!connection.url)
133
+ return output;
134
+ const seconds = Math.ceil((Date.parse(window.to) - Date.parse(window.from)) / 1000), step = Math.max(60, Math.ceil(seconds / 32));
135
+ const selector = `{fractory_environment=${JSON.stringify(output.environment)}}`;
136
+ const labels = "fractory_target,fractory_caller";
137
+ const reader = new PrometheusReader(connection, transport);
138
+ const queried = await Promise.allSettled([
139
+ reader.query(`sum by (${labels},fractory_outcome) (increase(fractory_calls_total${selector}[${seconds}s]))`, window.to),
140
+ reader.query(`sum by (${labels},le) (increase(fractory_duration_seconds_bucket${selector}[${seconds}s]))`, window.to),
141
+ reader.query(`sum by (${labels},fractory_outcome) (rate(fractory_calls_total${selector}[${Math.max(60, step * 2)}s]))`, window.to, { from: window.from, step }),
142
+ reader.query(`max(timestamp(fractory_calls_total${selector})) by ()`, window.to),
143
+ reader.query(`sum by (${labels},le) (rate(fractory_duration_seconds_bucket${selector}[${Math.max(300, step * 2)}s]))`, window.to, { from: window.from, step }),
144
+ ]);
145
+ if (queried[0].status === "rejected" &&
146
+ [401, 403].includes(queried[0].reason?.status))
147
+ throw queried[0].reason;
148
+ const [counts, buckets, trend, latest, latency] = queried.map((result, index) => {
149
+ if (result.status === "fulfilled")
150
+ return result.value;
151
+ output.warnings.push(`${["Calls", "Latency", "Trend", "Last sample", "Latency trend"][index]} unavailable: ${result.reason instanceof Error ? result.reason.message : "query failed"}`);
152
+ return [];
153
+ });
154
+ const rows = new Map();
155
+ const row = (metric) => {
156
+ if (!metric.fractory_target)
157
+ return undefined;
158
+ const caller = metric.fractory_caller === "external"
159
+ ? undefined
160
+ : metric.fractory_caller;
161
+ const key = JSON.stringify([metric.fractory_target, caller]);
162
+ let value = rows.get(key);
163
+ if (!value) {
164
+ value = {
165
+ target: metric.fractory_target,
166
+ caller,
167
+ calls: 0,
168
+ callsKnown: false,
169
+ errors: 0,
170
+ buckets: [],
171
+ trend: [],
172
+ };
173
+ rows.set(key, value);
174
+ }
175
+ return value;
176
+ };
177
+ for (const series of counts) {
178
+ const target = row(series.metric), value = Number(series.value?.[1]);
179
+ if (!target || !Number.isFinite(value) || value < 0)
180
+ continue;
181
+ target.callsKnown = true;
182
+ target.calls += value;
183
+ if (series.metric.fractory_outcome === "error")
184
+ target.errors += value;
185
+ }
186
+ const unlabelled = counts.filter((series) => !series.metric.fractory_target).length;
187
+ if (unlabelled)
188
+ output.warnings.push(`${unlabelled} aggregate series have no factory target label; check instrumentation cardinality and attribute export.`);
189
+ for (const series of buckets) {
190
+ const target = row(series.metric), count = Number(series.value?.[1]), le = series.metric.le === "+Inf"
191
+ ? Number.MAX_VALUE
192
+ : Number(series.metric.le);
193
+ if (!target || !Number.isFinite(count) || count < 0 || !Number.isFinite(le))
194
+ continue;
195
+ target.buckets.push({ le, count });
196
+ }
197
+ for (const series of trend) {
198
+ const target = row(series.metric);
199
+ if (!target)
200
+ continue;
201
+ for (const [at, text] of series.values || []) {
202
+ const value = Number(text) * 60;
203
+ if (!Number.isFinite(value) || value < 0)
204
+ continue;
205
+ const time = at * 1000;
206
+ const existing = target.trend.find((p) => p.at === time);
207
+ if (existing)
208
+ existing.value += value;
209
+ else
210
+ target.trend.push({ at: time, value });
211
+ if (series.metric.fractory_outcome === "error") {
212
+ target.failedTrend ||= [];
213
+ const point = target.failedTrend.find((p) => p.at === time);
214
+ if (point)
215
+ point.value += value;
216
+ else
217
+ target.failedTrend.push({ at: time, value });
218
+ }
219
+ }
220
+ }
221
+ for (const series of latency) {
222
+ const target = row(series.metric), le = series.metric.le === "+Inf"
223
+ ? Number.MAX_VALUE
224
+ : Number(series.metric.le);
225
+ if (!target || !Number.isFinite(le))
226
+ continue;
227
+ target.latencyTrend ||= [];
228
+ for (const [at, text] of series.values || []) {
229
+ const count = Number(text);
230
+ if (!Number.isFinite(count) || count < 0)
231
+ continue;
232
+ const time = at * 1000;
233
+ let point = target.latencyTrend.find((p) => p.at === time);
234
+ if (!point) {
235
+ point = { at: time, buckets: [] };
236
+ target.latencyTrend.push(point);
237
+ }
238
+ point.buckets.push({ le, count });
239
+ }
240
+ }
241
+ for (const value of rows.values())
242
+ value.buckets.sort((a, b) => a.le - b.le);
243
+ output.boundaries = [...rows.values()];
244
+ const last = Number(latest[0]?.value?.[1]);
245
+ if (Number.isFinite(last))
246
+ output.lastSampleAt = new Date(last * 1000).toISOString();
247
+ output.gauges = [];
248
+ for (const definition of definitions) {
249
+ const gauge = { ...definition, status: "empty", values: [] };
250
+ const results = await Promise.all(definition.sources.map(async (source) => {
251
+ let result;
252
+ try {
253
+ result = await reader.query(source.query.replace(/\$environment\b/g, JSON.stringify(output.environment)), window.to, { from: window.from, step });
254
+ }
255
+ catch {
256
+ gauge.status = "error";
257
+ gauge.error = "Source query unavailable";
258
+ output.warnings.push(`${definition.label}: source query unavailable`);
259
+ return;
260
+ }
261
+ // Gauges must explicitly reduce to one series; arbitrary series are never silently summed.
262
+ if (result.length > 1) {
263
+ output.warnings.push(`${definition.label}: query must return one series per attached source`);
264
+ return;
265
+ }
266
+ const points = (result[0]?.values || []).flatMap(([at, text]) => Number.isFinite(Number(text))
267
+ ? [{ at: at * 1000, value: Number(text) }]
268
+ : []);
269
+ if (points.length)
270
+ return {
271
+ block: source.block,
272
+ value: points.at(-1).value,
273
+ trend: points,
274
+ };
275
+ }));
276
+ gauge.values = results.filter((value) => !!value);
277
+ if (gauge.values.length && gauge.status !== "error")
278
+ gauge.status = "ready";
279
+ for (const value of gauge.values) {
280
+ const at = value.trend.at(-1)?.at;
281
+ if (at && (!output.lastSampleAt || at > Date.parse(output.lastSampleAt)))
282
+ output.lastSampleAt = new Date(at).toISOString();
283
+ }
284
+ output.gauges.push(gauge);
285
+ }
286
+ if (queried.every((r) => r.status === "rejected") &&
287
+ !output.gauges.some((g) => g.values.length))
288
+ throw queried[0].reason;
289
+ return output;
290
+ }
@@ -0,0 +1,14 @@
1
+ import type { DefinitionGraph, Element, Connection } from "./model.js";
2
+ /** A focused scope shows its contents and genuine external endpoints, never unrelated siblings. */
3
+ export declare function scopeGraph(graph: DefinitionGraph, focus: string, expanded: ReadonlySet<string>): {
4
+ scope: Element;
5
+ nodes: Element[];
6
+ edges: (Connection & {
7
+ originalSource: string;
8
+ originalTarget: string;
9
+ })[];
10
+ external: Set<string>;
11
+ frontier: Set<string>;
12
+ implementation: Set<string>;
13
+ contextLabel: (node: Element) => string;
14
+ };
package/dist/scope.js ADDED
@@ -0,0 +1,168 @@
1
+ /** A focused scope shows its contents and genuine external endpoints, never unrelated siblings. */
2
+ export function scopeGraph(graph, focus, expanded) {
3
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
4
+ const scope = byId.get(focus) || byId.get(graph.id);
5
+ const inside = (id) => {
6
+ let current = byId.get(id);
7
+ while (current) {
8
+ if (current.id === scope.id)
9
+ return true;
10
+ current = current.parent ? byId.get(current.parent) : undefined;
11
+ }
12
+ return false;
13
+ };
14
+ const visibleInside = (node) => node.parent === scope.id ||
15
+ (!!node.parent &&
16
+ inside(node.parent) &&
17
+ expanded.has(node.parent) &&
18
+ !!byId.get(node.parent) &&
19
+ visibleInside(byId.get(node.parent)));
20
+ const nodes = graph.elements.filter((node) => node.id !== scope.id && inside(node.id) && visibleInside(node));
21
+ const shown = new Set(nodes.map((node) => node.id));
22
+ const external = new Set();
23
+ const frontier = new Set(nodes.filter((node) => node.kind === "interface").map((node) => node.id));
24
+ const incoming = new Set(graph.connections
25
+ .filter((edge) => edge.relation !== "exposes" &&
26
+ !inside(edge.source) &&
27
+ inside(edge.target))
28
+ .map((edge) => edge.target));
29
+ // Explicitly exposed nested contracts appear on this boundary themselves;
30
+ // a presentation projection must not replace them with a bare owner box.
31
+ for (const edge of graph.connections) {
32
+ const api = byId.get(edge.target);
33
+ if (edge.relation === "exposes" &&
34
+ edge.source === scope.id &&
35
+ api?.kind === "interface" &&
36
+ inside(api.id) &&
37
+ incoming.has(api.id)) {
38
+ frontier.add(api.id);
39
+ if (!shown.has(api.id)) {
40
+ nodes.push(api);
41
+ shown.add(api.id);
42
+ }
43
+ }
44
+ }
45
+ const implementation = new Set();
46
+ let owner = byId.get(scope.parent || "");
47
+ while (owner && ["interface", "method", "operation"].includes(owner.kind))
48
+ owner = byId.get(owner.parent || "");
49
+ const implementationPeer = (id) => {
50
+ const seen = new Set();
51
+ while (owner && byId.has(id) && !seen.has(id)) {
52
+ if (id === owner.id)
53
+ return true;
54
+ seen.add(id);
55
+ id = byId.get(id).parent || "";
56
+ }
57
+ return false;
58
+ };
59
+ const contextLabel = (node) => {
60
+ const names = [];
61
+ let current = node.parent ? byId.get(node.parent) : undefined;
62
+ while (current && current.id !== graph.id) {
63
+ names.unshift(current.label);
64
+ current = current.parent ? byId.get(current.parent) : undefined;
65
+ }
66
+ return names.join(" / ");
67
+ };
68
+ const endpoint = (id) => {
69
+ if (id === scope.id) {
70
+ if (scope.id === graph.id)
71
+ return;
72
+ if (!shown.has(id)) {
73
+ nodes.push(scope);
74
+ shown.add(id);
75
+ }
76
+ return id;
77
+ }
78
+ let current = byId.get(id);
79
+ if (!current)
80
+ return;
81
+ if (inside(id)) {
82
+ while (current && !shown.has(current.id))
83
+ current = current.parent ? byId.get(current.parent) : undefined;
84
+ return current?.id;
85
+ }
86
+ // Outside methods meet this scope through their public interface. Preserve
87
+ // original endpoints on the edge for contracts and source inspection.
88
+ if (current.kind === "method" &&
89
+ current.parent &&
90
+ byId.get(current.parent)?.kind === "interface") {
91
+ current = byId.get(current.parent);
92
+ id = current.id;
93
+ }
94
+ // At a product-area zoom level, outside peers are product areas too. Keep
95
+ // fine-grained endpoints on the wire instead of filling the canvas with
96
+ // external methods. Deeper views still meet public interfaces directly.
97
+ if (scope.kind !== "interface" && scope.parent === graph.id) {
98
+ while (current.parent && current.parent !== graph.id) {
99
+ const parent = byId.get(current.parent);
100
+ if (!parent)
101
+ break;
102
+ current = parent;
103
+ }
104
+ id = current.id;
105
+ }
106
+ if (!shown.has(id)) {
107
+ nodes.push(current);
108
+ shown.add(id);
109
+ external.add(id);
110
+ if (scope.kind === "interface" && implementationPeer(id))
111
+ implementation.add(id);
112
+ }
113
+ return id;
114
+ };
115
+ const edges = [];
116
+ // The canonical receiver stays the public API. When that API is open, show
117
+ // the known implementation endpoint through its boundary, rather than two
118
+ // unrelated wires ending and starting at different points on the enclosure.
119
+ const entrypoints = new Map(graph.connections.flatMap((edge) => scope.kind === "interface" &&
120
+ edge.target === scope.id &&
121
+ !inside(edge.source) &&
122
+ edge.provenance !== "proposed" &&
123
+ edge.entrypoint &&
124
+ edge.entrypoint !== scope.id &&
125
+ inside(edge.entrypoint)
126
+ ? [[edge.id, edge.entrypoint]]
127
+ : []));
128
+ const reached = new Set(entrypoints.values());
129
+ for (const edge of graph.connections) {
130
+ // Exposure is a contract declaration, shown by the real frontier card.
131
+ // It is not an invocation and should not become another canvas wire.
132
+ if (edge.relation === "exposes")
133
+ continue;
134
+ // This generated fallback only supplies the interior half when the exact
135
+ // caller-to-member wire is not already visible. Keep authored delegations.
136
+ if (edge.source === scope.id &&
137
+ reached.has(edge.target) &&
138
+ edge.id === `interface-implementation:${scope.id}:${edge.target}`)
139
+ continue;
140
+ if (edge.relation === "delegates" &&
141
+ edge.target === scope.id &&
142
+ byId.get(edge.source)?.kind === "interface" &&
143
+ byId.get(edge.source)?.parent === scope.id)
144
+ continue;
145
+ if (!inside(edge.source) && !inside(edge.target))
146
+ continue;
147
+ const source = endpoint(edge.source), target = endpoint(entrypoints.get(edge.id) || edge.target);
148
+ if (source && target && source !== target)
149
+ edges.push({
150
+ ...edge,
151
+ source,
152
+ target,
153
+ originalSource: edge.source,
154
+ originalTarget: edge.target,
155
+ });
156
+ }
157
+ if (!nodes.length && scope.id !== graph.id)
158
+ nodes.push(scope);
159
+ return {
160
+ scope,
161
+ nodes,
162
+ edges,
163
+ external,
164
+ frontier,
165
+ implementation,
166
+ contextLabel,
167
+ };
168
+ }
@@ -0,0 +1,39 @@
1
+ import type { DefinitionGraph } from "./model.js";
2
+ import type { CodeSnapshot } from "./code-model.js";
3
+ import { type ErrorCount, type ErrorObservation } from "./error-heat.js";
4
+ import { SentryReader, type SentryAreaRule, type SentryProjectWarning } from "./sentry.js";
5
+ import { type TimeWindow } from "./time-window.js";
6
+ /** Provider occurrence counts drive the map. Small filtered samples drive inspection.
7
+ * Only stored, exact-revision artifacts permit a sample to claim source ownership. */
8
+ export declare function sentryActivity(graph: DefinitionGraph, reader: SentryReader, options: {
9
+ org: string;
10
+ projects: string[];
11
+ window: TimeWindow;
12
+ areas: SentryAreaRule[];
13
+ snapshot: (commit: string) => CodeSnapshot | undefined;
14
+ }): Promise<{
15
+ period: string;
16
+ window: TimeWindow;
17
+ warnings: SentryProjectWarning[];
18
+ accounting: {
19
+ projects: {
20
+ project: string;
21
+ total: number | null;
22
+ }[];
23
+ samplePartial: boolean;
24
+ classificationPartial: boolean;
25
+ total: number;
26
+ source: number;
27
+ related: number;
28
+ };
29
+ counts?: ErrorCount[];
30
+ fetchedAt: string;
31
+ partial: boolean;
32
+ events: ErrorObservation[];
33
+ cells: Record<string, {
34
+ source: number;
35
+ related: number;
36
+ intensity: number;
37
+ }>;
38
+ unassigned: number;
39
+ }>;
@@ -0,0 +1,174 @@
1
+ import { errorHeat, } from "./error-heat.js";
2
+ import { readSentryProjects, relatedSentryAreas, matchSentryEvent, eventCommit, } from "./sentry.js";
3
+ import { inTimeWindow } from "./time-window.js";
4
+ /** Provider occurrence counts drive the map. Small filtered samples drive inspection.
5
+ * Only stored, exact-revision artifacts permit a sample to claim source ownership. */
6
+ export async function sentryActivity(graph, reader, options) {
7
+ const tags = [...new Set(options.areas.map((rule) => rule.tag))];
8
+ const sampleWarnings = [];
9
+ const { pages, warnings } = await readSentryProjects(options.projects, async (project) => {
10
+ const counts = await reader.errorCounts(project, options.window, tags);
11
+ let samples = {
12
+ events: [],
13
+ partial: false,
14
+ };
15
+ try {
16
+ samples = await reader.errorSamples(project, options.window, tags);
17
+ }
18
+ catch (error) {
19
+ sampleWarnings.push({
20
+ project,
21
+ scope: "samples",
22
+ message: error instanceof Error && error.message.startsWith("Sentry")
23
+ ? error.message
24
+ : "Sentry event samples are unavailable.",
25
+ });
26
+ }
27
+ return { counts, samples };
28
+ });
29
+ const rows = [], observations = [];
30
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
31
+ for (const page of pages) {
32
+ const groups = page.counts.groups.map((group) => {
33
+ const areas = [
34
+ ...new Set(relatedSentryAreas(graph, page.project, {
35
+ tags: Object.entries(group.tags).map(([key, value]) => ({
36
+ key,
37
+ value,
38
+ })),
39
+ }, options.areas).map((area) => area.id)),
40
+ ];
41
+ const elementId = areas.length === 1 ? areas[0] : undefined;
42
+ const row = {
43
+ project: page.project,
44
+ count: group.count,
45
+ elementId,
46
+ basis: elementId ? "component" : "unassigned",
47
+ reason: elementId
48
+ ? "Provider component tag; not a verified leaf source match"
49
+ : areas.length > 1
50
+ ? "Component tags point to several blocks"
51
+ : "No mapped block attribution tag",
52
+ };
53
+ rows.push(row);
54
+ return { group, row };
55
+ });
56
+ const remainder = {
57
+ project: page.project,
58
+ count: page.counts.total -
59
+ groups.reduce((sum, value) => sum + value.row.count, 0),
60
+ basis: "unassigned",
61
+ reason: page.counts.partial
62
+ ? "Classification budget reached; occurrences remain in the total"
63
+ : "No mapped block attribution tag",
64
+ };
65
+ rows.push(remainder);
66
+ let inspected = 0;
67
+ const seen = new Set();
68
+ for (const sample of page.counts.total ? page.samples.events : []) {
69
+ const eventId = sample.eventID || sample.id;
70
+ if (!eventId ||
71
+ seen.has(eventId) ||
72
+ !inTimeWindow(sample.dateCreated, options.window))
73
+ continue;
74
+ seen.add(eventId);
75
+ const commit = eventCommit(sample), snapshot = commit ? options.snapshot(commit) : undefined;
76
+ let matchReason = !commit
77
+ ? "Event has no unambiguous full Git commit"
78
+ : !snapshot
79
+ ? "No factory snapshot captured for this commit"
80
+ : "Full frame inspection is available on demand";
81
+ let owner, basis = "unassigned";
82
+ // Do not download stacks for every occurrence or reconstruct historical factories.
83
+ if (snapshot && inspected < 2) {
84
+ inspected++;
85
+ try {
86
+ const full = await reader.event(page.project, eventId), match = matchSentryEvent(full, snapshot);
87
+ const first = match.matches.find((frame) => frame.status !== "unmapped");
88
+ if (first?.status === "matched") {
89
+ const original = first.elementIds[0];
90
+ let node = snapshot.graph.elements.find((node) => node.id === original);
91
+ const visited = new Set();
92
+ while (node && !visited.has(node.id)) {
93
+ visited.add(node.id);
94
+ const id = graph.aliases?.[node.id] || node.id;
95
+ if (byId.has(id)) {
96
+ owner = id;
97
+ basis = node.id === original ? "source" : "component";
98
+ break;
99
+ }
100
+ node = snapshot.graph.elements.find((parent) => parent.id === node?.parent);
101
+ }
102
+ }
103
+ matchReason =
104
+ match.reason ||
105
+ "Historical owner is no longer on the displayed map";
106
+ }
107
+ catch {
108
+ matchReason =
109
+ "Full source inspection is unavailable; aggregate counts are retained";
110
+ }
111
+ }
112
+ const grouped = groups.find(({ group }) => Object.entries(group.tags).every(([key, value]) => (sample.tags?.find((tag) => tag.key === key)?.value || "") ===
113
+ value));
114
+ if (owner) {
115
+ const from = grouped?.row.count
116
+ ? grouped.row
117
+ : remainder.count
118
+ ? remainder
119
+ : undefined;
120
+ if (from) {
121
+ from.count--;
122
+ rows.push({
123
+ project: page.project,
124
+ count: 1,
125
+ elementId: owner,
126
+ basis,
127
+ reason: basis === "source"
128
+ ? "Exact-version source match for this inspected event"
129
+ : "Historical source owner rolled up to its surviving parent",
130
+ });
131
+ }
132
+ else
133
+ owner = undefined;
134
+ }
135
+ if (!owner) {
136
+ owner = grouped?.row.elementId;
137
+ basis = owner ? "component" : "unassigned";
138
+ }
139
+ observations.push({
140
+ eventId,
141
+ project: page.project,
142
+ issueId: sample.groupID,
143
+ title: sample.title || "Sentry error",
144
+ at: sample.dateCreated,
145
+ commit,
146
+ elementId: owner,
147
+ basis,
148
+ matchReason: basis === "source" ? undefined : matchReason,
149
+ issueUrl: sample.groupID && /^\d+$/.test(sample.groupID)
150
+ ? `https://${encodeURIComponent(options.org)}.sentry.io/issues/${sample.groupID}/`
151
+ : undefined,
152
+ });
153
+ }
154
+ }
155
+ const result = errorHeat(graph, observations, warnings.length > 0, rows.filter((row) => row.count));
156
+ const total = pages.reduce((sum, page) => sum + page.counts.total, 0);
157
+ if (result.accounting?.total !== total)
158
+ throw Error("Sentry accounting did not reconcile; no partial totals were published.");
159
+ return {
160
+ ...result,
161
+ period: "custom",
162
+ window: options.window,
163
+ warnings: [...warnings, ...sampleWarnings],
164
+ accounting: {
165
+ ...result.accounting,
166
+ projects: options.projects.map((project) => ({
167
+ project,
168
+ total: pages.find((page) => page.project === project)?.counts.total ?? null,
169
+ })),
170
+ samplePartial: pages.some((page) => page.samples.partial),
171
+ classificationPartial: pages.some((page) => page.counts.partial),
172
+ },
173
+ };
174
+ }