@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 476 lines 15.5 KB
Raw
1 import * as ssm from "@distilled.cloud/gcp/securesourcemanager_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { hasAlchemyLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 catchMissing,
12 collectPages,
13 expandName,
14 fingerprint,
15 forEachRepository,
16 hasOwnershipMarker,
17 nameFromOperation,
18 normalizeLocation,
19 ownedByAlchemy,
20 PAGE_SIZE,
21 parseName,
22 parseOwnership,
23 replaceOnIdentity,
24 ResourceNotResolved,
25 retryConflict,
26 sameText,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 export type PullRequestCommentReview = {
33 /**
34 * Review action (`COMMENT`, `CHANGE_REQUESTED`, `APPROVED`).
35 */
36 actionType?: ssm.ReviewActionTypeEnum | (string & {});
37 /** Optional review summary body. */
38 body?: string;
39 };
40
41 export type PullRequestCommentCode = {
42 /** Comment body. */
43 body?: string;
44 /** Parent code-comment name this comment replies to. */
45 reply?: string;
46 /** File path of the comment. */
47 position?: {
48 /** Path of the file. */
49 path?: string;
50 /** Line number (positive = new side, negative = old side). */
51 line?: string;
52 };
53 };
54
55 export type RepositoriesPullRequestsPullRequestCommentProps = {
56 /**
57 * Parent pull request. Full name
58 * `projects/{project}/locations/{location}/repositories/{repository}/pullRequests/{pullRequest}`
59 * or the pull-request id (combined with `repository`). Immutable —
60 * changing it replaces the comment.
61 */
62 pullRequest: string;
63 /**
64 * Parent repository used when `pullRequest` is a bare id.
65 */
66 repository?: string;
67 /**
68 * Region used when `pullRequest` or `repository` is a bare id.
69 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
70 */
71 location?: string;
72 /**
73 * Server-assigned comment id. Set after create. Immutable — changing
74 * it replaces the comment.
75 */
76 commentId?: string;
77 /**
78 * General pull-request comment. Mutually exclusive with `review` and
79 * `code`. Posted as given; comments have no labels, so Alchemy tracks
80 * the comment by its server-assigned id.
81 */
82 comment?: { body: string };
83 /**
84 * Review summary comment. Mutually exclusive with `comment` and `code`.
85 */
86 review?: PullRequestCommentReview;
87 /**
88 * Line-level code comment. Mutually exclusive with `comment` and
89 * `review`. Creating a root code comment requires
90 * `BatchCreatePullRequestComments`; this resource creates a general
91 * comment or a code reply.
92 */
93 code?: PullRequestCommentCode;
94 };
95
96 export type RepositoriesPullRequestsPullRequestComment = Resource<
97 "GCP.SecureSourceManager.RepositoriesPullRequestsPullRequestComment",
98 RepositoriesPullRequestsPullRequestCommentProps,
99 {
100 /** Full resource name. */
101 name: string;
102 /** Server-assigned comment id. */
103 commentId: string;
104 /** Parent pull-request resource name. */
105 pullRequest: string;
106 /** Project id. */
107 project: string;
108 /** Location id. */
109 location: string;
110 /** General comment body with ownership prefix stripped. */
111 comment: { body: string } | undefined;
112 /** Review summary with ownership prefix stripped from `body`. */
113 review: PullRequestCommentReview | undefined;
114 /** Code comment with ownership prefix stripped from `body`. */
115 code:
116 | {
117 body: string | undefined;
118 reply: string | undefined;
119 resolved: boolean | undefined;
120 position:
121 | {
122 path: string | undefined;
123 line: string | undefined;
124 }
125 | undefined;
126 }
127 | undefined;
128 /** RFC3339 creation timestamp. */
129 createTime: string | undefined;
130 /** RFC3339 last-update timestamp. */
131 updateTime: string | undefined;
132 },
133 never,
134 Providers
135 >;
136
137 /**
138 * A comment on a Secure Source Manager pull request.
139 *
140 * Comment ids are server-assigned. Changing `commentId` or `pullRequest`
141 * replaces the comment. Body updates in place. Ownership for `list` /
142 * nuke is stamped into the comment body (comments have no labels field).
143 * Create a general `comment`, a `review`, or a `code` reply — batch
144 * review-plus-code threads use the distilled batch-create API.
145 *
146 * ### Creating a Pull Request Comment
147 * **Example:** General comment
148 * ```typescript
149 * const comment =
150 * yield* GCP.SecureSourceManager.RepositoriesPullRequestsPullRequestComment(
151 * "Note",
152 * {
153 * pullRequest: pullRequest.name,
154 * comment: { body: "looks good" },
155 * },
156 * );
157 * ```
158 *
159 * ### Updating a Pull Request Comment
160 * Re-declare the same logical id with changed props; the engine keeps the
161 * physical resource and updates it in place.
162 *
163 * **Example:** Edit the body
164 * ```typescript
165 * const comment =
166 * yield* GCP.SecureSourceManager.RepositoriesPullRequestsPullRequestComment(
167 * "Note",
168 * {
169 * pullRequest: pullRequest.name,
170 * comment: { body: "looks good after the rebase" },
171 * },
172 * );
173 * ```
174 *
175 * @resource
176 * @category SecureSourceManager
177 */
178 export const RepositoriesPullRequestsPullRequestComment =
179 Resource<RepositoriesPullRequestsPullRequestComment>(
180 "GCP.SecureSourceManager.RepositoriesPullRequestsPullRequestComment",
181 );
182
183 const resourceName = (pullRequest: string, commentId: string) =>
184 `${pullRequest}/pullRequestComments/${commentId}`;
185
186 const expandPullRequest = (
187 pullRequest: string,
188 repository: string | undefined,
189 project: string,
190 location: string,
191 ) => {
192 const next = pullRequest.replace(/\/+$/, "");
193 if (next.includes("/")) return next;
194 const repo = expandName(repository ?? "", project, location, "repositories");
195 return repo.length > 0 ? `${repo}/pullRequests/${next}` : next;
196 };
197
198 const ownershipBodyOf = (item: ssm.PullRequestComment) =>
199 item.comment?.body ?? item.review?.body ?? item.code?.body;
200
201 const toAttrs = (item: ssm.PullRequestComment, project: string, region: string) => {
202 const name = item.name ?? "";
203 const parsed = parseName(name, "pullRequestComments", region);
204 const commentBody = parseOwnership(item.comment?.body);
205 const reviewBody = parseOwnership(item.review?.body);
206 const codeBody = parseOwnership(item.code?.body);
207 return {
208 name,
209 commentId: parsed.id,
210 pullRequest: parsed.parent,
211 project: parsed.project || project,
212 location: parsed.location,
213 comment: item.comment === undefined ? undefined : { body: commentBody.text ?? "" },
214 review:
215 item.review === undefined
216 ? undefined
217 : {
218 actionType: item.review.actionType,
219 body: reviewBody.text,
220 },
221 code:
222 item.code === undefined
223 ? undefined
224 : {
225 body: codeBody.text,
226 reply: item.code.reply,
227 resolved: item.code.resolved,
228 position:
229 item.code.position === undefined
230 ? undefined
231 : {
232 path: item.code.position.path,
233 line: item.code.position.line,
234 },
235 },
236 createTime: item.createTime,
237 updateTime: item.updateTime,
238 };
239 };
240
241 const encodeBodies = (
242 news: RepositoriesPullRequestsPullRequestCommentProps,
243 ): ssm.PullRequestComment => {
244 if (news.review !== undefined) {
245 return {
246 review: {
247 actionType: news.review.actionType,
248 body: news.review.body,
249 },
250 };
251 }
252 if (news.code !== undefined) {
253 return {
254 code: {
255 body: news.code.body,
256 reply: news.code.reply,
257 position: news.code.position,
258 },
259 };
260 }
261 return {
262 comment: {
263 body: news.comment?.body,
264 },
265 };
266 };
267
268 const desiredBody = (news: RepositoriesPullRequestsPullRequestCommentProps): string | undefined =>
269 news.review?.body ?? news.code?.body ?? news.comment?.body;
270
271 const getByName = (name: string) =>
272 name.length === 0
273 ? Effect.undefined
274 : catchMissing(
275 ssm.getProjectsLocationsRepositoriesPullRequestsPullRequestComments({
276 name,
277 }),
278 );
279
280 const listOnPullRequest = (pullRequest: string) =>
281 collectPages(
282 ssm.listProjectsLocationsRepositoriesPullRequestsPullRequestComments.pages({
283 parent: pullRequest,
284 pageSize: PAGE_SIZE,
285 }),
286 (page) => page.pullRequestComments,
287 );
288
289 const listOnRepository = (repository: string) =>
290 Effect.gen(function* () {
291 const pullRequests = yield* collectPages(
292 ssm.listProjectsLocationsRepositoriesPullRequests.pages({
293 parent: repository,
294 pageSize: PAGE_SIZE,
295 }),
296 (page) => page.pullRequests,
297 );
298 const pages = yield* Effect.forEach(
299 pullRequests.filter((item) => (item.name ?? "").length > 0),
300 (item) => listOnPullRequest(item.name!),
301 { concurrency: 4 },
302 );
303 return pages.flat();
304 });
305
306 /**
307 * A comment on the pull request with this body (or one carrying a legacy
308 * ownership marker for `id`). Recovers a comment whose create succeeded but
309 * was never recorded.
310 */
311 const findMatching = (pullRequest: string, id: string, body: string | undefined) =>
312 Effect.gen(function* () {
313 if (pullRequest.length === 0) return undefined;
314 const items = yield* listOnPullRequest(pullRequest);
315 for (const item of items) {
316 if (yield* ownedByAlchemy(id, ownershipBodyOf(item))) return item;
317 if (sameText(ownershipBodyOf(item), body)) return item;
318 }
319 return undefined;
320 });
321
322 const listOwned = (project: string, region: string) =>
323 forEachRepository(project, region, (repository) =>
324 listOnRepository(repository).pipe(
325 Effect.map((items) => items.filter((item) => hasOwnershipMarker(ownershipBodyOf(item)))),
326 ),
327 );
328
329 export const RepositoriesPullRequestsPullRequestCommentProvider = () =>
330 Provider.succeed(RepositoriesPullRequestsPullRequestComment, {
331 stables: ["name", "commentId", "pullRequest", "project", "location", "createTime"],
332
333 diff: Effect.fn(function* ({ news, olds, output }) {
334 if (!isResolved(news)) return undefined;
335 const env = yield* GcpEnvironment.current;
336 const location = normalizeLocation(
337 news.location ?? olds?.location ?? output?.location,
338 env.region,
339 );
340 const nextKind =
341 news.review !== undefined ? "review" : news.code !== undefined ? "code" : "comment";
342 const previousKind =
343 olds?.review !== undefined || output?.review !== undefined
344 ? "review"
345 : olds?.code !== undefined || output?.code !== undefined
346 ? "code"
347 : olds?.comment !== undefined || output?.comment !== undefined
348 ? "comment"
349 : nextKind;
350 return replaceOnIdentity({
351 previousId: olds?.commentId ?? output?.commentId,
352 nextId: news.commentId ?? olds?.commentId ?? output?.commentId,
353 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
354 nextLocation: location,
355 previousParent: olds?.pullRequest ?? output?.pullRequest,
356 nextParent: expandPullRequest(news.pullRequest, news.repository, env.project, location),
357 extra:
358 previousKind !== nextKind ||
359 fingerprint(news.code?.position) !==
360 fingerprint(olds?.code?.position ?? output?.code?.position) ||
361 !sameText(news.code?.reply, olds?.code?.reply ?? output?.code?.reply) ||
362 !sameText(
363 news.review?.actionType,
364 olds?.review?.actionType ?? output?.review?.actionType,
365 ),
366 });
367 }),
368
369 read: Effect.fn(function* ({ id, olds, output }) {
370 const env = yield* GcpEnvironment.current;
371 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
372 const pullRequest = expandPullRequest(
373 olds?.pullRequest ?? output?.pullRequest ?? "",
374 olds?.repository,
375 env.project,
376 location,
377 );
378 const commentId = olds?.commentId ?? output?.commentId;
379 const name =
380 output?.name ??
381 (commentId !== undefined && pullRequest.length > 0
382 ? resourceName(pullRequest, commentId)
383 : "");
384 let existing = yield* getByName(name);
385 const recorded = existing !== undefined && output !== undefined;
386 if (existing === undefined && olds !== undefined) {
387 existing = yield* findMatching(pullRequest, id, desiredBody(olds));
388 }
389 if (existing === undefined) return undefined;
390 const attrs = toAttrs(existing, env.project, env.region);
391 const { labels } = parseOwnership(ownershipBodyOf(existing));
392 // A matching comment found without a recorded id could be anyone's.
393 return recorded || (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
394 }),
395
396 list: () =>
397 Effect.gen(function* () {
398 const env = yield* GcpEnvironment.current;
399 const items = yield* listOwned(env.project, env.region);
400 return items.map((item: ssm.PullRequestComment) => toAttrs(item, env.project, env.region));
401 }),
402
403 reconcile: Effect.fn(function* ({ id, news, output }) {
404 const env = yield* GcpEnvironment.current;
405 const location = normalizeLocation(news.location ?? output?.location, env.region);
406 const pullRequest = expandPullRequest(
407 news.pullRequest,
408 news.repository,
409 env.project,
410 location,
411 );
412 const encoded = encodeBodies(news);
413 const name =
414 output?.name ??
415 (news.commentId !== undefined ? resourceName(pullRequest, news.commentId) : "");
416
417 let current = yield* getByName(name);
418 if (current === undefined) {
419 current = yield* findMatching(pullRequest, id, desiredBody(news));
420 }
421
422 if (current === undefined) {
423 const created = yield* ssm
424 .createProjectsLocationsRepositoriesPullRequestsPullRequestComments({
425 parent: pullRequest,
426 body: encoded,
427 })
428 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
429 if (created !== undefined) {
430 const operation = yield* waitForOperation(created);
431 const createdName = nameFromOperation(operation);
432 if (createdName !== undefined) {
433 current = yield* waitUntilExists(getByName(createdName), createdName);
434 }
435 }
436 if (current === undefined) {
437 current = yield* findMatching(pullRequest, id, desiredBody(news));
438 }
439 }
440
441 if (current === undefined) {
442 return yield* new ResourceNotResolved({
443 resourceName: name || pullRequest,
444 });
445 }
446
447 const currentName = current.name ?? name;
448 // Raw body: also rewrites a legacy ownership marker away.
449 if (!sameText(ownershipBodyOf(current), desiredBody(news))) {
450 const operation =
451 yield* ssm.patchProjectsLocationsRepositoriesPullRequestsPullRequestComments({
452 name: currentName,
453 updateMask: "body",
454 body: encoded,
455 });
456 yield* waitForOperation(operation);
457 current = yield* waitUntilExists(getByName(currentName), currentName);
458 }
459
460 return toAttrs(current, env.project, env.region);
461 }),
462
463 delete: Effect.fn(function* ({ output }) {
464 const operation = yield* retryConflict(
465 ssm
466 .deleteProjectsLocationsRepositoriesPullRequestsPullRequestComments({
467 name: output.name,
468 })
469 .pipe(Effect.catchTag("NotFound", () => Effect.undefined)),
470 );
471 if (operation !== undefined) {
472 yield* waitForOperation(operation, { notFoundOk: true });
473 }
474 yield* waitUntilGone(getByName(output.name), output.name);
475 }),
476 });