@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
package/src/sentry.ts ADDED
@@ -0,0 +1,545 @@
1
+ import {
2
+ commitFromRelease,
3
+ locateCode,
4
+ type CodeMatch,
5
+ type CodeSnapshot,
6
+ } from "./code-model";
7
+ import { recentWindow } from "./time-window";
8
+ import type { DefinitionGraph } from "./model";
9
+
10
+ export interface SentryAreaRule {
11
+ project: string;
12
+ tag: string;
13
+ value: string;
14
+ elementId: string;
15
+ }
16
+ /** Coarse event metadata associations are separate from versioned source ownership. */
17
+ export function relatedSentryAreas(
18
+ graph: DefinitionGraph,
19
+ project: string,
20
+ event: SentryEvent,
21
+ rules: SentryAreaRule[],
22
+ ) {
23
+ return rules.flatMap((rule) => {
24
+ const node = graph.elements.find(
25
+ (element) =>
26
+ element.id === (graph.aliases?.[rule.elementId] || rule.elementId),
27
+ );
28
+ return node &&
29
+ rule.project === project &&
30
+ event.tags?.some(
31
+ (tag) => tag.key === rule.tag && tag.value === rule.value,
32
+ )
33
+ ? [{ id: node.id, label: node.label, basis: `${rule.tag}=${rule.value}` }]
34
+ : [];
35
+ });
36
+ }
37
+
38
+ type Frame = {
39
+ filename?: string;
40
+ absPath?: string;
41
+ abs_path?: string;
42
+ lineNo?: number;
43
+ lineno?: number;
44
+ inApp?: boolean;
45
+ in_app?: boolean;
46
+ };
47
+ export interface SentryEvent {
48
+ eventID?: string;
49
+ id?: string;
50
+ groupID?: string;
51
+ title?: string;
52
+ issueShortId?: string;
53
+ type?: string;
54
+ level?: string;
55
+ dateCreated?: string;
56
+ release?: string | { version?: string } | null;
57
+ tags?: { key: string; value: string }[];
58
+ entries?: {
59
+ type: string;
60
+ data?: {
61
+ values?: { stacktrace?: { frames?: Frame[] } }[];
62
+ frames?: Frame[];
63
+ };
64
+ }[];
65
+ exception?: { values?: { stacktrace?: { frames?: Frame[] } }[] };
66
+ }
67
+ export interface SentryCountGroup {
68
+ count: number;
69
+ tags: Record<string, string>;
70
+ }
71
+ export interface SentryCounts {
72
+ total: number;
73
+ groups: SentryCountGroup[];
74
+ partial: boolean;
75
+ }
76
+ export function eventCommit(event: SentryEvent): string | undefined {
77
+ const release =
78
+ typeof event.release === "string" ? event.release : event.release?.version;
79
+ const ids = new Set(
80
+ [
81
+ commitFromRelease(release),
82
+ ...(event.tags || [])
83
+ .filter(
84
+ (t) =>
85
+ t.key === "fractal.commit" ||
86
+ t.key === "git.commit" ||
87
+ t.key === "release",
88
+ )
89
+ .map((t) => commitFromRelease(t.value)),
90
+ ].filter((v): v is string => !!v),
91
+ );
92
+ return ids.size === 1 ? [...ids][0] : undefined;
93
+ }
94
+ export function matchSentryEvent(event: SentryEvent, snapshot?: CodeSnapshot) {
95
+ const commit = eventCommit(event);
96
+ if (!commit || !snapshot || snapshot.commit !== commit)
97
+ return {
98
+ commit,
99
+ status: "version_unavailable" as const,
100
+ matches: [] as CodeMatch[],
101
+ reason: !commit
102
+ ? "Event has no unambiguous full Git commit"
103
+ : "No factory snapshot captured for this commit",
104
+ };
105
+ const frames = [
106
+ ...(event.entries || []).flatMap((entry) =>
107
+ entry.type === "exception"
108
+ ? (entry.data?.values || []).flatMap((v) => v.stacktrace?.frames || [])
109
+ : entry.type === "stacktrace"
110
+ ? entry.data?.frames || []
111
+ : [],
112
+ ),
113
+ ...(event.exception?.values || []).flatMap(
114
+ (v) => v.stacktrace?.frames || [],
115
+ ),
116
+ ]
117
+ .filter((f) => f.inApp !== false && f.in_app !== false)
118
+ .slice(-128)
119
+ .reverse();
120
+ const seen = new Set<string>();
121
+ const matches = frames.flatMap((frame) => {
122
+ const paths = [
123
+ ...new Set(
124
+ [frame.filename, frame.absPath, frame.abs_path].filter(
125
+ (path): path is string => !!path,
126
+ ),
127
+ ),
128
+ ];
129
+ const file = paths[0];
130
+ const line = frame.lineNo ?? frame.lineno;
131
+ if (!file || !line || seen.has(`${file}:${line}`)) return [];
132
+ seen.add(`${file}:${line}`);
133
+ const candidates = paths.map((path) => locateCode(snapshot, path, line));
134
+ return [
135
+ candidates.find(
136
+ (match) => match.status === "matched" || match.status === "ambiguous",
137
+ ) ||
138
+ candidates.find((match) => match.file) ||
139
+ candidates[0],
140
+ ];
141
+ });
142
+ const matched = matches.some((m) => m.status === "matched");
143
+ return {
144
+ commit,
145
+ status: matched ? ("matched" as const) : ("unmapped" as const),
146
+ matches,
147
+ ...(!matched
148
+ ? {
149
+ reason:
150
+ "No unique mapped original-source frame. Check source maps and source ownership.",
151
+ }
152
+ : {}),
153
+ };
154
+ }
155
+
156
+ /** Server/CLI only. Credentials and raw event payloads never belong in the viewer. */
157
+ export class SentryReader {
158
+ constructor(
159
+ private config: {
160
+ token: string;
161
+ org: string;
162
+ projects: string[];
163
+ baseUrl?: string;
164
+ environment?: string;
165
+ },
166
+ private request: typeof fetch = fetch,
167
+ ) {}
168
+ private async get<T>(
169
+ path: string,
170
+ query?: Record<string, string | string[]>,
171
+ page?: { next?: string },
172
+ ): Promise<T> {
173
+ const base = new URL(this.config.baseUrl || "https://sentry.io");
174
+ if (
175
+ base.protocol !== "https:" ||
176
+ !/(^|\.)sentry\.io$/.test(base.hostname) ||
177
+ base.username ||
178
+ base.password
179
+ )
180
+ throw new Error("Use an HTTPS Sentry API hostname");
181
+ const url = new URL(`/api/0/${path}`, base);
182
+ for (const [key, value] of Object.entries(query || {}))
183
+ for (const entry of Array.isArray(value) ? value : [value])
184
+ url.searchParams.append(key, entry);
185
+ // One retry for a transient provider/network failure. Never retry an auth
186
+ // denial, missing project or rate limit. Two projects stay within the UI's
187
+ // request budget even if both first attempts time out.
188
+ for (let attempt = 0; attempt < 2; attempt++) {
189
+ let response: Response;
190
+ try {
191
+ response = await this.request(url, {
192
+ headers: {
193
+ Authorization: `Bearer ${this.config.token}`,
194
+ Accept: "application/json",
195
+ },
196
+ cache: "no-store",
197
+ redirect: "error",
198
+ signal: AbortSignal.timeout(10_000),
199
+ });
200
+ } catch {
201
+ if (attempt === 0) {
202
+ await new Promise((resolve) => setTimeout(resolve, 300));
203
+ continue;
204
+ }
205
+ throw Error(
206
+ "Sentry could not be reached. Check your connection and retry.",
207
+ );
208
+ }
209
+ if (response.ok) {
210
+ try {
211
+ if (page) {
212
+ const next = response.headers
213
+ .get("link")
214
+ ?.split(",")
215
+ .find(
216
+ (link) =>
217
+ link.includes('rel="next"') &&
218
+ link.includes('results="true"'),
219
+ );
220
+ page.next = next?.match(/cursor="([^"]{1,2048})"/)?.[1];
221
+ }
222
+ return (await response.json()) as T;
223
+ } catch {
224
+ throw Error("Sentry returned an unreadable response. Retry.");
225
+ }
226
+ }
227
+ // Provider bodies may contain private event data; never forward them.
228
+ await response.body?.cancel().catch(() => {});
229
+ if (response.status >= 500 && attempt === 0) {
230
+ await new Promise((resolve) => setTimeout(resolve, 300));
231
+ continue;
232
+ }
233
+ throw Error(
234
+ response.status === 401
235
+ ? "Sentry sign-in expired. Reconnect Sentry in Integrations."
236
+ : response.status === 403
237
+ ? "Sentry access denied. Check project read permissions in Integrations."
238
+ : response.status === 404
239
+ ? "Sentry project or event not found. Check the organization and projects in Integrations."
240
+ : response.status === 429
241
+ ? "Sentry rate limit: wait a minute before refreshing error activity."
242
+ : response.status >= 500
243
+ ? `Sentry is temporarily unavailable (HTTP ${response.status}). Retry.`
244
+ : `Sentry rejected the request (HTTP ${response.status}). Check the time range and project settings.`,
245
+ );
246
+ }
247
+ throw Error("Sentry could not be reached. Retry.");
248
+ }
249
+ private project(project: string) {
250
+ if (!this.config.projects.includes(project))
251
+ throw new Error("Sentry project is not configured");
252
+ return `projects/${encodeURIComponent(this.config.org)}/${encodeURIComponent(project)}`;
253
+ }
254
+ /** Explore applies environment and time filters; the legacy project event list ignores environment. */
255
+ private errorQuery(
256
+ project: string,
257
+ window: import("./time-window").TimeWindow,
258
+ ): Record<string, string | string[]> {
259
+ this.project(project);
260
+ return {
261
+ dataset: "errors",
262
+ project,
263
+ environment: this.config.environment || "production",
264
+ start: window.from,
265
+ end: window.to,
266
+ query: "!level:info !level:debug",
267
+ };
268
+ }
269
+ async errorCounts(
270
+ project: string,
271
+ window: import("./time-window").TimeWindow,
272
+ tags: string[],
273
+ ): Promise<SentryCounts> {
274
+ const keys = [...new Set(tags)];
275
+ if (
276
+ keys.length > 8 ||
277
+ keys.some((tag) => !/^[a-zA-Z0-9_.:-]{1,80}$/.test(tag))
278
+ )
279
+ throw Error("Sentry attribution tags exceed the read budget");
280
+ const path = `organizations/${encodeURIComponent(this.config.org)}/events/`,
281
+ query = this.errorQuery(project, window);
282
+ const groups = new Map<string, SentryCountGroup>();
283
+ let cursor: string | undefined,
284
+ partial = false;
285
+ if (keys.length)
286
+ for (let at = 0; at < 5; at++) {
287
+ const page: { next?: string } = {};
288
+ const response = await this.get<{ data: Record<string, unknown>[] }>(
289
+ path,
290
+ {
291
+ ...query,
292
+ field: [...keys, "count()"],
293
+ per_page: "100",
294
+ sort: "-count()",
295
+ ...(cursor ? { cursor } : {}),
296
+ },
297
+ page,
298
+ );
299
+ if (!Array.isArray(response.data))
300
+ throw Error("Sentry returned incomplete error counts");
301
+ for (const row of response.data) {
302
+ const count = Number(row["count()"]);
303
+ if (!Number.isSafeInteger(count) || count < 0)
304
+ throw Error("Sentry returned invalid error counts");
305
+ const tags = Object.fromEntries(
306
+ keys.map((key) => [
307
+ key,
308
+ typeof row[key] === "string" ? (row[key] as string) : "",
309
+ ]),
310
+ );
311
+ groups.set(JSON.stringify(tags), { count, tags });
312
+ }
313
+ if (!page.next) break;
314
+ partial = at === 4 || page.next === cursor;
315
+ if (partial) break;
316
+ cursor = page.next;
317
+ }
318
+ // Read the total independently: a classification budget must never truncate volume.
319
+ const totalRow = await this.get<{ data: Record<string, unknown>[] }>(path, {
320
+ ...query,
321
+ field: ["count()"],
322
+ per_page: "1",
323
+ });
324
+ if (!Array.isArray(totalRow.data) || totalRow.data.length > 1)
325
+ throw Error("Sentry returned incomplete error totals");
326
+ const total = totalRow.data.length
327
+ ? Number(totalRow.data[0]["count()"])
328
+ : 0;
329
+ if (
330
+ !Number.isSafeInteger(total) ||
331
+ total < 0 ||
332
+ [...groups.values()].reduce((sum, row) => sum + row.count, 0) > total
333
+ )
334
+ throw Error(
335
+ "Sentry error counts changed during the read. Refresh to retry.",
336
+ );
337
+ return { total, groups: [...groups.values()], partial };
338
+ }
339
+ async errorSamples(
340
+ project: string,
341
+ window: import("./time-window").TimeWindow,
342
+ tags: string[] = [],
343
+ ) {
344
+ const page: { next?: string } = {};
345
+ const fields = [
346
+ ...new Set(["id", "issue.id", "title", "timestamp", "release", ...tags]),
347
+ ];
348
+ const query = this.errorQuery(project, window);
349
+ const result = await this.get<{ data: Record<string, unknown>[] }>(
350
+ `organizations/${encodeURIComponent(this.config.org)}/events/`,
351
+ {
352
+ ...query,
353
+ field: fields,
354
+ sort: "-timestamp",
355
+ per_page: "10",
356
+ },
357
+ page,
358
+ );
359
+ if (!Array.isArray(result.data))
360
+ throw Error("Sentry returned incomplete event samples");
361
+ const events: SentryEvent[] = result.data.flatMap((row) =>
362
+ typeof row.id !== "string" ||
363
+ !/^[a-f0-9]{32}$/i.test(row.id) ||
364
+ typeof row.timestamp !== "string"
365
+ ? []
366
+ : [
367
+ {
368
+ eventID: row.id,
369
+ groupID: row["issue.id"] ? String(row["issue.id"]) : undefined,
370
+ title: typeof row.title === "string" ? row.title : "Sentry error",
371
+ dateCreated: row.timestamp,
372
+ release:
373
+ typeof row.release === "string" ? row.release : undefined,
374
+ tags: [
375
+ {
376
+ key: "environment",
377
+ value: this.config.environment || "production",
378
+ },
379
+ ...tags
380
+ .filter((key) => typeof row[key] === "string")
381
+ .map((key) => ({ key, value: row[key] as string })),
382
+ ],
383
+ },
384
+ ],
385
+ );
386
+ return { events, partial: !!page.next };
387
+ }
388
+ async errorVolume(
389
+ project: string,
390
+ window: import("./time-window").TimeWindow,
391
+ ): Promise<import("./activity-volume").ActivityVolume> {
392
+ const start = Date.parse(window.from),
393
+ end = Date.parse(window.to),
394
+ seconds = (end - start) / 1000;
395
+ const interval =
396
+ seconds <= 2 * 86400 ? 3600 : seconds <= 14 * 86400 ? 21600 : 86400;
397
+ const response = await this.get<{
398
+ timeSeries: {
399
+ values: { timestamp: number; value: number; incomplete?: boolean }[];
400
+ }[];
401
+ }>(
402
+ `organizations/${encodeURIComponent(this.config.org)}/events-timeseries/`,
403
+ {
404
+ ...this.errorQuery(project, window),
405
+ yAxis: "count()",
406
+ interval: String(interval),
407
+ },
408
+ );
409
+ if (
410
+ !Array.isArray(response.timeSeries) ||
411
+ response.timeSeries.length !== 1 ||
412
+ !Array.isArray(response.timeSeries[0].values)
413
+ )
414
+ throw Error("Sentry returned an incomplete error timeline");
415
+ const values = response.timeSeries[0].values;
416
+ if (
417
+ values.some(
418
+ (row) =>
419
+ !Number.isFinite(row.timestamp) ||
420
+ !Number.isSafeInteger(row.value) ||
421
+ row.value < 0,
422
+ )
423
+ )
424
+ throw Error("Sentry returned an invalid error timeline");
425
+ const step =
426
+ values.length > 1
427
+ ? values[1].timestamp - values[0].timestamp
428
+ : interval * 1000;
429
+ if (!(step > 0)) throw Error("Sentry returned invalid timeline intervals");
430
+ const buckets = values
431
+ .map((row) => ({
432
+ from: Math.max(start, row.timestamp),
433
+ to: Math.min(end, row.timestamp + step),
434
+ value: row.value,
435
+ }))
436
+ .filter((row) => row.to > row.from);
437
+ return {
438
+ window,
439
+ label: "Error events · configured projects",
440
+ unit: "errors",
441
+ buckets,
442
+ total: buckets.reduce((sum, row) => sum + row.value, 0),
443
+ partial: values.some((row) => row.incomplete),
444
+ };
445
+ }
446
+ async issues(project: string, window?: import("./time-window").TimeWindow) {
447
+ const data = await this.get<
448
+ {
449
+ id: string;
450
+ shortId: string;
451
+ title: string;
452
+ count: string;
453
+ lastSeen: string;
454
+ status: string;
455
+ }[]
456
+ >(`${this.project(project)}/issues/`, {
457
+ query: "is:unresolved !level:info !level:debug",
458
+ environment: this.config.environment || "production",
459
+ ...(window
460
+ ? { start: window.from, end: window.to }
461
+ : { statsPeriod: "14d" }),
462
+ per_page: "20",
463
+ });
464
+ return data.map((i) => ({
465
+ id: i.id,
466
+ shortId: i.shortId,
467
+ title: i.title,
468
+ count: i.count,
469
+ lastSeen: i.lastSeen,
470
+ status: i.status,
471
+ url: `https://sentry.io/organizations/${encodeURIComponent(this.config.org)}/issues/${encodeURIComponent(i.id)}/`,
472
+ }));
473
+ }
474
+ async errors(
475
+ project: string,
476
+ window?: import("./time-window").TimeWindow,
477
+ ): Promise<{ events: SentryEvent[]; partial: boolean }> {
478
+ return this.errorSamples(project, window || recentWindow());
479
+ }
480
+ async event(project: string, eventId: string): Promise<SentryEvent> {
481
+ if (!/^[a-f0-9]{32}$/i.test(eventId))
482
+ throw new Error("Use a 32 character Sentry event ID");
483
+ return this.get(`${this.project(project)}/events/${eventId}/`, {
484
+ collapse: "adjacentEvents",
485
+ });
486
+ }
487
+ async issueEvent(
488
+ project: string,
489
+ issue: string,
490
+ window = recentWindow(),
491
+ ): Promise<SentryEvent> {
492
+ this.project(project);
493
+ if (!/^\d{1,24}$/.test(issue)) throw new Error("Invalid Sentry issue ID");
494
+ // Confirm project ownership before retrieving an organization-scoped event.
495
+ const detail = await this.get<{
496
+ project?: { slug?: string };
497
+ shortId?: string;
498
+ }>(`organizations/${encodeURIComponent(this.config.org)}/issues/${issue}/`);
499
+ if (detail.project?.slug !== project)
500
+ throw new Error("Issue is outside the configured project");
501
+ const event = await this.get<SentryEvent>(
502
+ `organizations/${encodeURIComponent(this.config.org)}/issues/${issue}/events/latest/`,
503
+ {
504
+ environment: this.config.environment || "production",
505
+ start: window.from,
506
+ end: window.to,
507
+ collapse: "adjacentEvents",
508
+ },
509
+ );
510
+ return { ...event, issueShortId: detail.shortId };
511
+ }
512
+ }
513
+
514
+ export interface SentryProjectWarning {
515
+ project: string;
516
+ message: string;
517
+ scope?: "samples" | "counts";
518
+ }
519
+ /** A failed project is unavailable, never an empty project. Keep independent
520
+ * successful reads and tell the viewer exactly which projects are missing. */
521
+ export async function readSentryProjects<T extends object>(
522
+ projects: string[],
523
+ read: (project: string) => Promise<T>,
524
+ ) {
525
+ const pages: (T & { project: string })[] = [];
526
+ const warnings: SentryProjectWarning[] = [];
527
+ for (const project of projects) {
528
+ try {
529
+ pages.push({ project, ...(await read(project)) });
530
+ } catch (error) {
531
+ warnings.push({
532
+ project,
533
+ message:
534
+ error instanceof Error && error.message.startsWith("Sentry")
535
+ ? error.message
536
+ : "Sentry request failed. Retry.",
537
+ });
538
+ }
539
+ }
540
+ if (!pages.length && warnings.length)
541
+ throw Error(
542
+ `Sentry read failed for ${warnings.map((w) => w.project).join(", ")}. ${warnings[0].message}`,
543
+ );
544
+ return { pages, warnings };
545
+ }
@@ -0,0 +1,18 @@
1
+ import { commitFromRelease } from "./code-model";
2
+
3
+ /** Same build identity in HTTP, RPC, queues, alarms, Durable Objects and containers. */
4
+ export function serviceRelease(
5
+ env: { SENTRY_RELEASE?: string; ENVIRONMENT?: string },
6
+ service: string,
7
+ ) {
8
+ const commit = commitFromRelease(env.SENTRY_RELEASE);
9
+ return {
10
+ attachStacktrace: true,
11
+ release: env.SENTRY_RELEASE || undefined,
12
+ dist: service,
13
+ environment: env.ENVIRONMENT || "production",
14
+ initialScope: {
15
+ tags: { service, ...(commit ? { "fractal.commit": commit } : {}) },
16
+ },
17
+ };
18
+ }
@@ -0,0 +1,58 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { execFileSync } from "node:child_process";
5
+ import { setupInfo, installSkill } from "./setup-kit.cjs";
6
+
7
+ export function toolkitDirectory() {
8
+ return (
9
+ process.env.FRACTORY_TOOLKIT_DIR ||
10
+ resolve(dirname(fileURLToPath(import.meta.url)), "../toolkit")
11
+ );
12
+ }
13
+ export function runSetup(args: string[]) {
14
+ const index = args.indexOf("--root");
15
+ if (index >= 0 && (!args[index + 1] || args[index + 1].startsWith("--")))
16
+ throw Error("--root needs a path");
17
+ const root = resolve(index >= 0 ? args[index + 1] : process.cwd());
18
+ if (args.includes("--help"))
19
+ return "fractory setup [--root PATH] [--install-skill]\nfractory doctor [--root PATH]\nfractory guide\nfractory open [--block ID] [--root PATH]\nSetup prints a focused agent request; --install-skill installs the repository skill. Use fractory integrations --help for agent-driven account setup. Doctor checks local prerequisites without contacting providers. The SDK and guide ship with the Mac app.";
20
+ const directory = toolkitDirectory();
21
+ if (args[0] === "guide")
22
+ return readFileSync(join(directory, "GUIDE.md"), "utf8");
23
+ const metadata = join(directory, "build.json");
24
+ const version = existsSync(metadata)
25
+ ? JSON.parse(readFileSync(metadata, "utf8")).version
26
+ : "development";
27
+ const info = setupInfo(root, directory, version);
28
+ if (args[0] === "doctor") {
29
+ const { guide, prompt, ...status } = info;
30
+ if (info.mapError || !info.tools.git.available) process.exitCode = 1;
31
+ return JSON.stringify(
32
+ {
33
+ ...status,
34
+ integrations:
35
+ "Check each provider in Fractory → Integrations; local tool presence does not verify an account or data.",
36
+ source: "Current checkout; no repository code executed.",
37
+ },
38
+ null,
39
+ 2,
40
+ );
41
+ }
42
+ if (args[0] === "open") {
43
+ const url = new URL("fractory://open");
44
+ url.searchParams.set("repo", info.repository);
45
+ const at = args.indexOf("--block");
46
+ if (at >= 0) {
47
+ if (!args[at + 1] || args[at + 1].startsWith("--"))
48
+ throw Error("--block needs an ID");
49
+ url.searchParams.set("block", args[at + 1]);
50
+ }
51
+ execFileSync("open", [url.href], { stdio: "ignore", timeout: 5000 });
52
+ return url.href;
53
+ }
54
+ if (args.includes("--install-skill"))
55
+ return JSON.stringify(installSkill(root, directory), null, 2);
56
+ if (args.includes("--json")) return JSON.stringify(info, null, 2);
57
+ return info.prompt;
58
+ }