plugin-git-manager 1.2.27 → 1.3.1

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 (138) hide show
  1. package/README.md +151 -108
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +3 -3
  5. package/client.js +1 -1
  6. package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
  7. package/dist/client/941.1793e67472872992.js +10 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
  10. package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
  11. package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
  12. package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
  13. package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/externalVersion.js +9 -8
  16. package/dist/locale/en-US.json +396 -297
  17. package/dist/locale/vi-VN.json +384 -292
  18. package/dist/locale/zh-CN.json +150 -51
  19. package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
  20. package/dist/node_modules/simple-git/package.json +1 -1
  21. package/dist/node_modules/zod/index.cjs +1 -1
  22. package/dist/node_modules/zod/package.json +1 -1
  23. package/dist/server/actions/git-actions.js +90 -36
  24. package/dist/server/actions/gitlab-api.js +4 -2
  25. package/dist/server/actions/poller.js +5 -2
  26. package/dist/server/actions/review-cutover.js +137 -0
  27. package/dist/server/actions/review.js +150 -51
  28. package/dist/server/actions/role-permissions.js +1 -0
  29. package/dist/server/ai-tools.js +8 -9
  30. package/dist/server/collections/gitCodeReviews.js +10 -0
  31. package/dist/server/collections/gitReviewCutover.js +44 -0
  32. package/dist/server/collections/gitReviewFlows.js +3 -0
  33. package/dist/server/collections/gitReviewInbox.js +51 -0
  34. package/dist/server/collections/gitReviewProjects.js +43 -0
  35. package/dist/server/collections/gitReviewRequests.js +56 -0
  36. package/dist/server/index.js +8 -2
  37. package/dist/server/plugin.js +57 -20
  38. package/dist/server/poller.js +95 -74
  39. package/dist/server/repository-access.js +23 -5
  40. package/dist/server/request-method-policy.js +76 -0
  41. package/dist/server/review-control-access.js +79 -0
  42. package/dist/server/services/legacy-post-service.js +412 -0
  43. package/dist/server/services/registry-content-service.js +4 -3
  44. package/dist/server/services/review-service.js +1451 -0
  45. package/dist/server/services/review-source.js +325 -0
  46. package/dist/server/utils/get-repo-account.js +3 -2
  47. package/dist/server/utils/url-security.js +24 -0
  48. package/package.json +61 -43
  49. package/server.d.ts +2 -2
  50. package/server.js +1 -1
  51. package/src/client/__tests__/CommitHistory.test.tsx +79 -0
  52. package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
  53. package/src/client/__tests__/RunReviewButton.test.tsx +84 -0
  54. package/src/client/__tests__/workflowRoutes.test.ts +65 -0
  55. package/src/client/ai-context.tsx +114 -114
  56. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  57. package/src/client/components/CommitHistory.tsx +429 -374
  58. package/src/client/components/FileExplorer.tsx +386 -386
  59. package/src/client/components/GitAccounts.tsx +179 -179
  60. package/src/client/components/GitManagerSettings.tsx +160 -160
  61. package/src/client/components/GitOperations.tsx +220 -220
  62. package/src/client/components/LLMModelSelect.tsx +63 -63
  63. package/src/client/components/LLMServiceSelect.tsx +58 -58
  64. package/src/client/components/MarkdownView.tsx +80 -80
  65. package/src/client/components/MergeRequests.tsx +790 -790
  66. package/src/client/components/PollingStatus.tsx +225 -225
  67. package/src/client/components/RepositoryConfig.tsx +335 -335
  68. package/src/client/components/RepositoryPermissions.tsx +123 -123
  69. package/src/client/components/ReviewFlows.tsx +352 -303
  70. package/src/client/components/ReviewHistory.tsx +796 -566
  71. package/src/client/components/RunReviewButton.tsx +57 -173
  72. package/src/client/context/GitManagerContext.tsx +92 -92
  73. package/src/client/index.tsx +91 -82
  74. package/src/client/locale.ts +9 -9
  75. package/src/client/promptTemplates.ts +31 -31
  76. package/src/client/workflowRoutes.ts +42 -0
  77. package/src/client-v2/ai-context.tsx +99 -0
  78. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  79. package/src/client-v2/index.tsx +1 -1
  80. package/src/client-v2/locale.ts +8 -8
  81. package/src/client-v2/plugin.tsx +67 -39
  82. package/src/index.ts +2 -2
  83. package/src/locale/en-US.json +396 -297
  84. package/src/locale/vi-VN.json +384 -292
  85. package/src/locale/zh-CN.json +150 -51
  86. package/src/server/__tests__/git-actions.test.ts +24 -24
  87. package/src/server/__tests__/git-security.test.ts +170 -0
  88. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  89. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  90. package/src/server/__tests__/poller.test.ts +37 -37
  91. package/src/server/__tests__/repository-access.test.ts +760 -752
  92. package/src/server/__tests__/review-service.integration.test.ts +1263 -0
  93. package/src/server/__tests__/review.test.ts +76 -137
  94. package/src/server/__tests__/role-permissions.test.ts +147 -147
  95. package/src/server/__tests__/smoke.test.ts +139 -17
  96. package/src/server/__tests__/subtree.test.ts +85 -85
  97. package/src/server/actions/git-actions.ts +540 -480
  98. package/src/server/actions/gitlab-api.ts +422 -411
  99. package/src/server/actions/poller.ts +39 -27
  100. package/src/server/actions/review-cutover.ts +121 -0
  101. package/src/server/actions/review.ts +1498 -1369
  102. package/src/server/actions/role-permissions.ts +331 -321
  103. package/src/server/actions/subtree.ts +508 -508
  104. package/src/server/ai-tools.ts +334 -319
  105. package/src/server/collections/gitAccounts.ts +56 -56
  106. package/src/server/collections/gitCodeReviews.ts +218 -199
  107. package/src/server/collections/gitRepositories.ts +87 -87
  108. package/src/server/collections/gitReviewCutover.ts +23 -0
  109. package/src/server/collections/gitReviewFlows.ts +120 -108
  110. package/src/server/collections/gitReviewInbox.ts +30 -0
  111. package/src/server/collections/gitReviewProjects.ts +22 -0
  112. package/src/server/collections/gitReviewRequests.ts +35 -0
  113. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  114. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  115. package/src/server/index.ts +14 -2
  116. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  117. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  118. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  119. package/src/server/plugin.ts +409 -361
  120. package/src/server/poller.ts +365 -352
  121. package/src/server/repository-access.ts +803 -773
  122. package/src/server/request-method-policy.ts +56 -0
  123. package/src/server/review-control-access.ts +71 -0
  124. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  125. package/src/server/services/__tests__/review-source.test.ts +226 -0
  126. package/src/server/services/legacy-post-service.ts +550 -0
  127. package/src/server/services/registry-content-service.ts +495 -484
  128. package/src/server/services/review-service.ts +1899 -0
  129. package/src/server/services/review-source.ts +359 -0
  130. package/src/server/utils/__tests__/redact.test.ts +56 -56
  131. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  132. package/src/server/utils/get-repo-account.ts +51 -41
  133. package/src/server/utils/gitlab-url.ts +38 -38
  134. package/src/server/utils/redact.ts +87 -87
  135. package/src/server/utils/url-security.ts +128 -95
  136. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  137. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  138. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -0,0 +1,1451 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var review_service_exports = {};
28
+ __export(review_service_exports, {
29
+ GitReviewService: () => GitReviewService
30
+ });
31
+ module.exports = __toCommonJS(review_service_exports);
32
+ var import_crypto = require("crypto");
33
+ var import_sequelize = require("sequelize");
34
+ var import_review = require("../actions/review");
35
+ var import_repository_access = require("../repository-access");
36
+ var import_review_source = require("./review-source");
37
+ function value(record, key) {
38
+ return record.get(key);
39
+ }
40
+ function fingerprint(markdown) {
41
+ return (0, import_crypto.createHash)("sha256").update(markdown).digest("hex");
42
+ }
43
+ function reviewConflict(message) {
44
+ const error = new Error(message);
45
+ error.status = 409;
46
+ throw error;
47
+ }
48
+ function legacyBlockReason(error) {
49
+ const message = error instanceof Error ? error.message : "";
50
+ if (/Legacy review has no pinned source commit/.test(message)) return "missing_pinned_head";
51
+ if (/Legacy branch review has no pinned base/.test(message)) return "missing_pinned_base";
52
+ if (/head changed before review admission/.test(message)) return "head_changed";
53
+ if (/actor has no unambiguous role|actor roles/.test(message)) return "actor_role_ambiguous";
54
+ if (/authenticated actor|actor does not have repository access|unable to resolve roles/i.test(message))
55
+ return "actor_unavailable";
56
+ if (/flow|workflow/i.test(message)) return "flow_or_workflow_unavailable";
57
+ if (/Repository not found|project|origin/i.test(message)) return "repository_unavailable";
58
+ return "migration_failed";
59
+ }
60
+ class GitReviewService {
61
+ constructor(app) {
62
+ this.app = app;
63
+ }
64
+ version = 1;
65
+ timer = null;
66
+ reconciling = false;
67
+ async enqueue(input) {
68
+ var _a;
69
+ const db = this.app.db;
70
+ await this.cutoverStatus();
71
+ const repo = await db.getRepository("gitRepositories").findOne({ filterByTk: input.repositoryId });
72
+ if (!repo) throw new Error("Repository not found");
73
+ const source = await (0, import_review_source.resolveReviewSource)(db, repo, input);
74
+ const flows = db.getRepository("gitReviewFlows");
75
+ const candidates = input.flowId ? [await flows.findOne({ filterByTk: input.flowId })].filter(Boolean) : await flows.find({
76
+ filter: { enabled: true, $or: [{ repositoryId: input.repositoryId }, { repositoryId: null }] },
77
+ sort: ["-repositoryId"]
78
+ });
79
+ const flow = input.flowId ? candidates[0] : (0, import_review.pickFlowMatchingBranch)(candidates, source.branch || void 0);
80
+ if (!flow || !value(flow, "enabled")) throw new Error("No enabled review flow found");
81
+ const flowRepoId = value(flow, "repositoryId");
82
+ if (flowRepoId != null && String(flowRepoId) !== String(input.repositoryId))
83
+ throw new Error("Review flow does not belong to this repository");
84
+ if (source.branch && !(0, import_review.branchMatches)(flow, source.branch))
85
+ throw new Error("Source branch does not match review flow");
86
+ const eventType = input.triggeredBy === "poll" ? input.eventType || "change_opened" : "manual";
87
+ const triggerMode = value(flow, "triggerMode");
88
+ if (eventType !== "manual" && !["onMergeRequestCreated", "both"].includes(triggerMode))
89
+ throw new Error("Flow does not permit automatic review");
90
+ if (eventType === "head_changed" && !value(flow, "reviewOnNewCommits"))
91
+ throw new Error("Review of new commits is not enabled");
92
+ if (eventType === "manual" && !["manual", "both"].includes(triggerMode))
93
+ throw new Error("Flow does not permit manual review");
94
+ const workflowKey = value(flow, "workflowKey");
95
+ if (!workflowKey) throw new Error("Review flow has not been bound to a workflow");
96
+ const boundWorkflowId = value(flow, "workflowId");
97
+ if (boundWorkflowId) {
98
+ const bound = await db.getRepository("workflows").findOne({ filterByTk: boundWorkflowId });
99
+ const options = bound ? value(bound, "options") : null;
100
+ if (((_a = options == null ? void 0 : options.gitReview) == null ? void 0 : _a.draft) === true) throw new Error("Review workflow setup is incomplete");
101
+ }
102
+ const workflow = await db.getRepository("workflows").findOne({ filter: { key: workflowKey, current: true, enabled: true } });
103
+ if (!workflow) throw new Error("Review workflow is not enabled");
104
+ const workflowId = value(workflow, "id");
105
+ const postMode = value(flow, "postMode");
106
+ const actorId = eventType === "manual" ? input.userId ?? null : value(flow, "createdById");
107
+ if (actorId == null) throw new Error("Review requires an authenticated actor");
108
+ const currentRoles = await (0, import_review.resolveBackgroundReviewRoles)(db, actorId);
109
+ const actorRoles = eventType === "manual" ? input.actorRoles || [] : currentRoles;
110
+ if (!actorRoles.length || actorRoles.some((role) => !currentRoles.includes(role)))
111
+ throw new Error("Review actor roles are unavailable or changed");
112
+ if (!await (0, import_repository_access.hasRepositoryAccess)({
113
+ acl: this.app.acl,
114
+ roles: actorRoles,
115
+ repositoryId: input.repositoryId,
116
+ action: "triggerReview"
117
+ }))
118
+ throw new Error("Review actor does not have repository access");
119
+ const payload = {
120
+ source,
121
+ flowId: value(flow, "id"),
122
+ workflowId,
123
+ workflowKey,
124
+ eventType,
125
+ userId: actorId,
126
+ actorRoles,
127
+ instructions: [value(flow, "instructions"), input.extraInstructions].filter(Boolean).join("\n\n"),
128
+ postMode: source.targetType !== "mr" ? "disabled" : postMode === "auto" || postMode === "disabled" ? postMode : "manual"
129
+ };
130
+ await this.assertSafeWorkflow(workflowId, payload.postMode, void 0, input.repositoryId);
131
+ const eventKey = eventType !== "manual" && !input.legacyReviewId ? fingerprint(
132
+ `${source.projectKey}:mr:${source.mrIid}${value(flow, "reviewOnNewCommits") ? `:${source.headSha}` : ""}`
133
+ ) : null;
134
+ const inboxRepo = db.getRepository("gitReviewInbox");
135
+ if (eventKey) {
136
+ const existing = await inboxRepo.findOne({ filter: { eventKey } });
137
+ if (existing) return value(existing, "reviewId");
138
+ }
139
+ if (input.legacyReviewId) {
140
+ const existing = await inboxRepo.findOne({ filter: { legacyReviewId: input.legacyReviewId } });
141
+ if (existing) return value(existing, "reviewId");
142
+ }
143
+ await this.ensureReviewProject(source.projectKey);
144
+ let reviewId;
145
+ try {
146
+ reviewId = await db.sequelize.transaction(async (transaction) => {
147
+ const reviews = db.getRepository("gitCodeReviews");
148
+ const values = {
149
+ flowId: payload.flowId,
150
+ repositoryId: input.repositoryId,
151
+ targetType: source.targetType,
152
+ mrIid: source.mrIid,
153
+ commitSha: source.targetType === "commit" ? source.headSha : null,
154
+ branch: source.branch,
155
+ folderPath: source.folderPath,
156
+ headSha: source.headSha,
157
+ latestSha: source.headSha,
158
+ triggeredBy: eventType === "manual" ? "manual" : "poll",
159
+ status: "queued",
160
+ postStatus: source.targetType === "mr" && payload.postMode !== "disabled" ? "pending_approval" : "skipped",
161
+ createdById: payload.userId,
162
+ metadata: { workflowManaged: true },
163
+ startedAt: null,
164
+ finishedAt: null,
165
+ error: null
166
+ };
167
+ let review;
168
+ if (input.legacyReviewId) {
169
+ const legacyReview = await db.getCollection("gitCodeReviews").model.findOne({
170
+ where: { id: input.legacyReviewId },
171
+ transaction,
172
+ lock: transaction.LOCK.UPDATE
173
+ });
174
+ if (!legacyReview || value(legacyReview, "status") !== "pending")
175
+ throw new Error("Legacy review is no longer pending");
176
+ review = legacyReview;
177
+ const [changed] = await db.getCollection("gitCodeReviews").model.update(values, {
178
+ where: { id: input.legacyReviewId, status: "pending" },
179
+ transaction
180
+ });
181
+ if (changed !== 1) throw new Error("Legacy review is no longer pending");
182
+ } else {
183
+ review = await reviews.create({ values, transaction });
184
+ }
185
+ const id = value(review, "id");
186
+ await inboxRepo.create({
187
+ values: {
188
+ projectKey: source.projectKey,
189
+ repositoryId: input.repositoryId,
190
+ reviewId: id,
191
+ legacyReviewId: input.legacyReviewId || null,
192
+ eventKey,
193
+ queuedAt: input.legacyReviewId ? value(review, "createdAt") || /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(),
194
+ state: "queued",
195
+ payload
196
+ },
197
+ transaction
198
+ });
199
+ return id;
200
+ });
201
+ } catch (error) {
202
+ if (eventKey) {
203
+ const existing = await inboxRepo.findOne({ filter: { eventKey } });
204
+ if (existing) return value(existing, "reviewId");
205
+ }
206
+ if (input.legacyReviewId) {
207
+ const existing = await inboxRepo.findOne({ filter: { legacyReviewId: input.legacyReviewId } });
208
+ if (existing) return value(existing, "reviewId");
209
+ }
210
+ throw error;
211
+ }
212
+ await this.reconcile().catch((error) => {
213
+ var _a2, _b;
214
+ return (_b = (_a2 = this.app.log) == null ? void 0 : _a2.error) == null ? void 0 : _b.call(_a2, "Git review dispatch will be retried", error);
215
+ });
216
+ return reviewId;
217
+ }
218
+ async ensureReviewProject(projectKey) {
219
+ var _a, _b;
220
+ const db = this.app.db;
221
+ const model = db.getCollection("gitReviewProjects").model;
222
+ for (let attempt = 0; ; attempt++) {
223
+ try {
224
+ await model.findOrCreate({ where: { projectKey }, defaults: { projectKey } });
225
+ return;
226
+ } catch (error) {
227
+ const sqliteError = error;
228
+ const busy = [sqliteError.code, (_a = sqliteError.original) == null ? void 0 : _a.code, (_b = sqliteError.parent) == null ? void 0 : _b.code].includes("SQLITE_BUSY");
229
+ if (db.sequelize.getDialect() !== "sqlite" || !busy || attempt >= 7) throw error;
230
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
231
+ }
232
+ }
233
+ }
234
+ async assertSafeWorkflow(workflowId, postMode, transaction, repositoryId) {
235
+ const integration = this.app.pm.get("plugin-workflow-git-review") || this.app.pm.get("workflow-git-review");
236
+ if ((integration == null ? void 0 : integration.enabled) !== true || !integration.assertSafeWorkflow)
237
+ throw new Error("Git review workflow integration is unavailable");
238
+ await integration.assertSafeWorkflow(workflowId, postMode, transaction, repositoryId);
239
+ }
240
+ async legacyRows() {
241
+ const db = this.app.db;
242
+ const candidates = await db.getRepository("gitCodeReviews").find({ filter: { status: { $in: ["pending", "running"] } }, sort: ["id"] });
243
+ const legacy = [];
244
+ for (const review of candidates) {
245
+ if (!await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId: value(review, "id") } }))
246
+ legacy.push(review);
247
+ }
248
+ return legacy;
249
+ }
250
+ async cutoverStatus() {
251
+ var _a, _b, _c;
252
+ const db = this.app.db;
253
+ const model = db.getCollection("gitReviewCutover").model;
254
+ const existingCount = await db.getRepository("gitCodeReviews").count();
255
+ let record = await model.findOne({ where: { key: "global" } });
256
+ for (let attempt = 0; !record; attempt++) {
257
+ try {
258
+ [record] = await model.findOrCreate({
259
+ where: { key: "global" },
260
+ defaults: { key: "global", state: existingCount ? "awaiting_confirmation" : "ready" }
261
+ });
262
+ } catch (error) {
263
+ const sqliteError = error;
264
+ const busy = ((_a = sqliteError.original) == null ? void 0 : _a.code) === "SQLITE_BUSY" || ((_b = sqliteError.parent) == null ? void 0 : _b.code) === "SQLITE_BUSY";
265
+ if (!busy || attempt >= 4) throw error;
266
+ await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1)));
267
+ record = await model.findOne({ where: { key: "global" } });
268
+ }
269
+ }
270
+ const legacy = await this.legacyRows();
271
+ const failed = await db.getRepository("gitCodeReviews").find({ filter: { status: "failed" }, sort: ["id"] });
272
+ const uncertain = [];
273
+ for (const review of failed) {
274
+ const metadata = value(review, "metadata");
275
+ if (!value(review, "startedAt") || (metadata == null ? void 0 : metadata.workflowManaged)) continue;
276
+ if (!await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId: value(review, "id") } }))
277
+ uncertain.push(review);
278
+ }
279
+ const activeRows = await db.getRepository("gitReviewInbox").find({ filter: { state: { $in: ["dispatched", "running", "quarantined"] } }, sort: ["id"] });
280
+ const quarantined = [];
281
+ const orphaned = [];
282
+ const postUnknownReviews = [];
283
+ const legacyPublicationHolds = [];
284
+ const legacyProjects = await db.getRepository("gitReviewProjects").find({
285
+ filter: { legacyPostReviewId: { $ne: null } },
286
+ sort: ["id"],
287
+ limit: 100
288
+ });
289
+ for (const project of legacyProjects) {
290
+ const reviewId = value(project, "legacyPostReviewId");
291
+ const heldReview = await db.getRepository("gitCodeReviews").findOne({ filterByTk: reviewId });
292
+ legacyPublicationHolds.push({
293
+ reviewId,
294
+ repositoryId: heldReview ? value(heldReview, "repositoryId") : null,
295
+ attemptId: heldReview ? value(heldReview, "legacyPostClaim") ?? null : null
296
+ });
297
+ }
298
+ const queuedBlocked = await db.getRepository("gitReviewInbox").find({ filter: { state: "queued", blockedReason: { $ne: null } }, sort: ["queuedAt", "id"], limit: 100 });
299
+ const unresolved = await db.getRepository("gitCodeReviews").find({ filter: { postStatus: { $in: ["posting", "post_unknown", "post_failed", "retrying"] } }, sort: ["id"] });
300
+ for (const review of unresolved) {
301
+ if (((_c = value(review, "metadata")) == null ? void 0 : _c.workflowManaged) && postUnknownReviews.length < 100) {
302
+ const inbox = await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId: value(review, "id") } });
303
+ const request = inbox && await db.getRepository("gitReviewRequests").findOne({ filter: { inboxId: value(inbox, "id") } });
304
+ const attemptId = request ? value(request, "postClaim") ?? null : null;
305
+ postUnknownReviews.push({
306
+ reviewId: value(review, "id"),
307
+ postStatus: value(review, "postStatus"),
308
+ hasClaim: attemptId != null,
309
+ attemptId
310
+ });
311
+ }
312
+ }
313
+ for (const inbox of activeRows) {
314
+ const request = await db.getRepository("gitReviewRequests").findOne({ filter: { inboxId: value(inbox, "id") } });
315
+ if (!request) {
316
+ if (orphaned.length < 100)
317
+ orphaned.push({ inboxId: value(inbox, "id"), reviewId: value(inbox, "reviewId") });
318
+ continue;
319
+ }
320
+ const executionId = value(request, "executionId");
321
+ const execution = executionId == null || !db.getCollection("executions") ? null : await db.getRepository("executions").findOne({ filterByTk: executionId });
322
+ const reason = value(inbox, "state") === "quarantined" ? "quarantined" : executionId == null ? "unclaimed" : !execution ? "execution_missing" : null;
323
+ if (reason && quarantined.length < 100)
324
+ quarantined.push({
325
+ requestId: value(request, "id"),
326
+ executionId,
327
+ reviewId: value(request, "reviewId"),
328
+ reason
329
+ });
330
+ }
331
+ return {
332
+ state: value(record, "state"),
333
+ legacyPending: legacy.filter((review) => value(review, "status") === "pending").length,
334
+ legacyRunning: legacy.filter((review) => value(review, "status") === "running").length,
335
+ legacyPendingReviews: legacy.filter((review) => value(review, "status") === "pending").slice(0, 100).map((review) => {
336
+ var _a2;
337
+ return {
338
+ legacyReviewId: value(review, "id"),
339
+ repositoryId: value(review, "repositoryId"),
340
+ reason: ((_a2 = value(review, "metadata")) == null ? void 0 : _a2.migrationBlockedReason) || "not_migrated"
341
+ };
342
+ }),
343
+ legacyRunningReviews: legacy.filter((review) => value(review, "status") === "running").slice(0, 100).map((review) => ({ legacyReviewId: value(review, "id") })),
344
+ legacyUncertain: uncertain.length,
345
+ legacyUncertainReviews: uncertain.slice(0, 100).map((review) => ({
346
+ legacyReviewId: value(review, "id"),
347
+ repositoryId: value(review, "repositoryId")
348
+ })),
349
+ quarantined,
350
+ orphaned,
351
+ postUnknownReviews,
352
+ legacyPublicationHolds,
353
+ queuedBlockedReviews: queuedBlocked.map((item) => ({
354
+ inboxId: value(item, "id"),
355
+ reviewId: value(item, "reviewId"),
356
+ repositoryId: value(item, "repositoryId"),
357
+ reason: value(item, "blockedReason")
358
+ }))
359
+ };
360
+ }
361
+ async confirmCutover(actor) {
362
+ await this.cutoverStatus();
363
+ await this.app.db.getCollection("gitReviewCutover").model.update(
364
+ { state: "ready", confirmedBy: String(actor), confirmedAt: /* @__PURE__ */ new Date() },
365
+ { where: { key: "global", state: "awaiting_confirmation" } }
366
+ );
367
+ await this.reconcile();
368
+ }
369
+ async legacyBlockedProjects() {
370
+ const db = this.app.db;
371
+ const keys = /* @__PURE__ */ new Set();
372
+ for (const review of await this.legacyRows()) {
373
+ try {
374
+ const repo = await db.getRepository("gitRepositories").findOne({ filterByTk: value(review, "repositoryId") });
375
+ if (!repo) return { keys, unknown: true };
376
+ keys.add(await (0, import_review_source.resolveReviewProjectKey)(db, repo));
377
+ } catch {
378
+ return { keys, unknown: true };
379
+ }
380
+ }
381
+ return { keys, unknown: false };
382
+ }
383
+ async recoverLegacy(reviewId, actor) {
384
+ const db = this.app.db;
385
+ if ((await this.cutoverStatus()).state !== "ready") throw new Error("Review cutover has not been confirmed");
386
+ if (await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId } }))
387
+ throw new Error("Review is managed by workflow");
388
+ const [changed] = await db.getCollection("gitCodeReviews").model.update(
389
+ { status: "failed", error: `Legacy worker stop confirmed by ${String(actor)}`, finishedAt: /* @__PURE__ */ new Date() },
390
+ { where: { id: reviewId, status: "running" } }
391
+ );
392
+ if (changed !== 1) throw new Error("Legacy review is not running");
393
+ await this.reconcile();
394
+ }
395
+ async cancelLegacy(reviewId, actor) {
396
+ const db = this.app.db;
397
+ if ((await this.cutoverStatus()).state !== "ready") throw new Error("Review cutover has not been confirmed");
398
+ await db.sequelize.transaction(async (transaction) => {
399
+ const review = await db.getCollection("gitCodeReviews").model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
400
+ if (!review || value(review, "status") !== "pending") throw new Error("Legacy review is not pending");
401
+ if (await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId }, transaction }))
402
+ throw new Error("Review is managed by workflow");
403
+ const metadata = value(review, "metadata") || {};
404
+ const [changed] = await db.getCollection("gitCodeReviews").model.update(
405
+ {
406
+ status: "failed",
407
+ error: "Legacy review canceled during workflow migration",
408
+ finishedAt: /* @__PURE__ */ new Date(),
409
+ metadata: {
410
+ ...metadata,
411
+ migrationCanceledBy: String(actor),
412
+ migrationCanceledAt: (/* @__PURE__ */ new Date()).toISOString()
413
+ }
414
+ },
415
+ { where: { id: reviewId, status: "pending" }, transaction }
416
+ );
417
+ if (changed !== 1) throw new Error("Legacy review is no longer pending");
418
+ });
419
+ await this.reconcile();
420
+ }
421
+ async cancelQueued(inboxId, actor) {
422
+ const db = this.app.db;
423
+ await db.sequelize.transaction(async (transaction) => {
424
+ const inbox = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
425
+ if (!inbox || value(inbox, "state") !== "queued") reviewConflict("Review is no longer queued");
426
+ if (await db.getRepository("gitReviewRequests").findOne({ filter: { inboxId }, transaction }))
427
+ reviewConflict("Review has already been dispatched");
428
+ const project = await db.getCollection("gitReviewProjects").model.findOne({
429
+ where: { projectKey: value(inbox, "projectKey") },
430
+ transaction,
431
+ lock: transaction.LOCK.UPDATE
432
+ });
433
+ if (project && String(value(project, "activeInboxId")) === String(inboxId))
434
+ reviewConflict("Review already owns a project reservation");
435
+ await inbox.update(
436
+ {
437
+ state: "canceled",
438
+ blockedReason: "canceled_by_operator",
439
+ recoveredBy: String(actor),
440
+ recoveredAt: /* @__PURE__ */ new Date()
441
+ },
442
+ { transaction }
443
+ );
444
+ await db.getRepository("gitCodeReviews").update({
445
+ filterByTk: value(inbox, "reviewId"),
446
+ values: { status: "failed", error: "Queued review canceled by operator", finishedAt: /* @__PURE__ */ new Date() },
447
+ transaction
448
+ });
449
+ });
450
+ await this.reconcile();
451
+ }
452
+ async recover(requestId, executionId, actor) {
453
+ const db = this.app.db;
454
+ await db.sequelize.transaction(async (transaction) => {
455
+ const request = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
456
+ if (!request || value(request, "fenced")) throw new Error("Review request is unavailable");
457
+ const owner = value(request, "executionId");
458
+ if (owner == null !== (executionId == null) || owner != null && String(owner) !== String(executionId))
459
+ throw new Error("Execution does not own request");
460
+ const execution = owner == null || !db.getCollection("executions") ? null : await db.getCollection("executions").model.findOne({ where: { id: owner }, transaction, lock: transaction.LOCK.UPDATE });
461
+ if (execution && (typeof value(execution, "status") !== "number" || value(execution, "status") === 0))
462
+ throw new Error("Execution is not terminal");
463
+ const inbox = await db.getCollection("gitReviewInbox").model.findOne({
464
+ where: { id: value(request, "inboxId") },
465
+ transaction,
466
+ lock: transaction.LOCK.UPDATE
467
+ });
468
+ if (!inbox || !["dispatched", "running", "quarantined"].includes(value(inbox, "state")))
469
+ throw new Error("Review is not recoverable");
470
+ if (execution && value(inbox, "state") !== "quarantined" && value(execution, "status") > 0)
471
+ throw new Error("Completed review is not quarantined");
472
+ await db.getCollection("gitReviewProjects").model.findOne({
473
+ where: { projectKey: value(inbox, "projectKey") },
474
+ transaction,
475
+ lock: transaction.LOCK.UPDATE
476
+ });
477
+ const review = await db.getCollection("gitCodeReviews").model.findOne({
478
+ where: { id: value(request, "reviewId") },
479
+ transaction,
480
+ lock: transaction.LOCK.UPDATE
481
+ });
482
+ if (!review || value(request, "postClaim") || ["posting", "post_unknown", "post_failed", "retrying"].includes(value(review, "postStatus"))) {
483
+ reviewConflict("Resolve publication or reset the stopped post attempt before recovery");
484
+ }
485
+ const [fenced] = await db.getCollection("gitReviewRequests").model.update({ fenced: true }, { where: { id: requestId, fenced: false }, transaction });
486
+ if (fenced !== 1) throw new Error("Review request could not be fenced");
487
+ await db.getCollection("gitReviewProjects").model.update(
488
+ { activeInboxId: null },
489
+ {
490
+ where: { projectKey: value(inbox, "projectKey"), activeInboxId: value(inbox, "id") },
491
+ transaction
492
+ }
493
+ );
494
+ await db.getRepository("gitReviewInbox").update({
495
+ filterByTk: value(inbox, "id"),
496
+ values: { state: "recovered", recoveredBy: String(actor), recoveredAt: /* @__PURE__ */ new Date() },
497
+ transaction
498
+ });
499
+ await db.getRepository("gitCodeReviews").update({
500
+ filterByTk: value(request, "reviewId"),
501
+ values: { status: "failed", error: "Review execution was stopped and recovered", finishedAt: /* @__PURE__ */ new Date() },
502
+ transaction
503
+ });
504
+ });
505
+ await this.reconcile();
506
+ }
507
+ async recoverOrphaned(inboxId, actor) {
508
+ const db = this.app.db;
509
+ await db.sequelize.transaction(async (transaction) => {
510
+ const inbox = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
511
+ if (!inbox || !["dispatched", "running", "quarantined"].includes(value(inbox, "state")))
512
+ throw new Error("Review is not recoverable");
513
+ if (await db.getRepository("gitReviewRequests").findOne({ filter: { inboxId }, transaction }))
514
+ throw new Error("Review request exists");
515
+ await db.getCollection("gitReviewProjects").model.update(
516
+ { activeInboxId: null },
517
+ { where: { projectKey: value(inbox, "projectKey"), activeInboxId: inboxId }, transaction }
518
+ );
519
+ await db.getRepository("gitReviewInbox").update({
520
+ filterByTk: inboxId,
521
+ values: { state: "recovered", recoveredBy: String(actor), recoveredAt: /* @__PURE__ */ new Date() },
522
+ transaction
523
+ });
524
+ await db.getRepository("gitCodeReviews").update({
525
+ filterByTk: value(inbox, "reviewId"),
526
+ values: { status: "failed", error: "Orphaned review was stopped and recovered", finishedAt: /* @__PURE__ */ new Date() },
527
+ transaction
528
+ });
529
+ });
530
+ await this.reconcile();
531
+ }
532
+ start() {
533
+ if (this.timer) return;
534
+ this.timer = setInterval(
535
+ () => this.reconcile().catch((error) => {
536
+ var _a, _b;
537
+ return (_b = (_a = this.app.log) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, "Git review reconciliation failed", error);
538
+ }),
539
+ 5e3
540
+ );
541
+ this.reconcile().catch((error) => {
542
+ var _a, _b;
543
+ return (_b = (_a = this.app.log) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, "Git review reconciliation failed", error);
544
+ });
545
+ }
546
+ stop() {
547
+ if (this.timer) clearInterval(this.timer);
548
+ this.timer = null;
549
+ }
550
+ async reconcile() {
551
+ var _a, _b;
552
+ if (this.reconciling) return;
553
+ this.reconciling = true;
554
+ try {
555
+ const status = await this.cutoverStatus();
556
+ if (status.state !== "ready") return;
557
+ await this.migrateLegacy();
558
+ const db = this.app.db;
559
+ const blocked = await this.legacyBlockedProjects();
560
+ if (blocked.unknown) return;
561
+ const pending = await db.getRepository("gitReviewInbox").find({ filter: { state: "queued" }, sort: ["queuedAt", "id"] });
562
+ const seen = /* @__PURE__ */ new Set();
563
+ for (const inbox of pending) {
564
+ const projectKey = value(inbox, "projectKey");
565
+ if (blocked.keys.has(projectKey)) continue;
566
+ if (seen.has(projectKey)) continue;
567
+ seen.add(projectKey);
568
+ const payload = value(inbox, "payload");
569
+ try {
570
+ const outcome = await db.sequelize.transaction(async (transaction) => {
571
+ var _a2, _b2;
572
+ const inboxId = value(inbox, "id");
573
+ const queued = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
574
+ if (!queued || value(queued, "state") !== "queued") return "stale";
575
+ const flow = await db.getRepository("gitReviewFlows").findOne({ filterByTk: payload.flowId, transaction });
576
+ if (!flow) {
577
+ await queued.update({ state: "canceled", blockedReason: "flow_deleted" }, { transaction });
578
+ await db.getRepository("gitCodeReviews").update({
579
+ filterByTk: value(queued, "reviewId"),
580
+ values: {
581
+ status: "failed",
582
+ error: "Review flow was deleted before dispatch",
583
+ finishedAt: /* @__PURE__ */ new Date()
584
+ },
585
+ transaction
586
+ });
587
+ return "canceled";
588
+ }
589
+ if (!value(flow, "enabled")) {
590
+ await queued.update({ blockedReason: "flow_disabled" }, { transaction });
591
+ return "blocked";
592
+ }
593
+ if (value(flow, "workflowKey") !== payload.workflowKey) {
594
+ await queued.update({ blockedReason: "workflow_binding_changed" }, { transaction });
595
+ return "blocked";
596
+ }
597
+ const boundId = value(flow, "workflowId");
598
+ if (boundId) {
599
+ const bound = await db.getRepository("workflows").findOne({ filterByTk: boundId, transaction });
600
+ if (!bound || ((_b2 = (_a2 = value(bound, "options")) == null ? void 0 : _a2.gitReview) == null ? void 0 : _b2.draft) === true) {
601
+ await queued.update({ blockedReason: "workflow_setup_incomplete" }, { transaction });
602
+ return "blocked";
603
+ }
604
+ }
605
+ const workflow = await db.getRepository("workflows").findOne({
606
+ filter: { key: payload.workflowKey, current: true, enabled: true },
607
+ transaction,
608
+ lock: transaction.LOCK.UPDATE
609
+ });
610
+ if (!workflow) {
611
+ await queued.update({ blockedReason: "workflow_disabled" }, { transaction });
612
+ return "blocked";
613
+ }
614
+ const workflowId = value(workflow, "id");
615
+ await this.assertSafeWorkflow(workflowId, payload.postMode, transaction, payload.source.repositoryId);
616
+ const [claimed] = await db.getCollection("gitReviewProjects").model.update(
617
+ { activeInboxId: inboxId },
618
+ { where: { projectKey, activeInboxId: null, legacyPostReviewId: null }, transaction }
619
+ );
620
+ if (claimed !== 1) {
621
+ if (value(queued, "blockedReason"))
622
+ await queued.update({ blockedReason: null }, { transaction });
623
+ return "busy";
624
+ }
625
+ await queued.update(
626
+ { state: "dispatched", blockedReason: null, payload: { ...payload, workflowId } },
627
+ { transaction }
628
+ );
629
+ await db.getRepository("gitReviewRequests").create({
630
+ values: {
631
+ inboxId,
632
+ reviewId: value(inbox, "reviewId"),
633
+ repositoryId: value(inbox, "repositoryId"),
634
+ flowId: payload.flowId,
635
+ workflowId,
636
+ workflowKey: payload.workflowKey,
637
+ eventType: payload.eventType
638
+ },
639
+ transaction
640
+ });
641
+ return "dispatched";
642
+ });
643
+ if (outcome === "canceled" || outcome === "stale") seen.delete(projectKey);
644
+ } catch (error) {
645
+ const reason = error instanceof Error && error.message === "No configured approver can access this repository" ? "approver_unavailable" : "workflow_unavailable";
646
+ await db.getCollection("gitReviewInbox").model.update({ blockedReason: reason }, { where: { id: value(inbox, "id"), state: "queued" } });
647
+ (_b = (_a = this.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(
648
+ _a,
649
+ `Git review ${String(value(inbox, "reviewId"))} is waiting for a safe workflow revision`
650
+ );
651
+ }
652
+ }
653
+ } finally {
654
+ this.reconciling = false;
655
+ }
656
+ }
657
+ async migrateLegacy() {
658
+ var _a, _b;
659
+ const db = this.app.db;
660
+ const reviews = db.getRepository("gitCodeReviews");
661
+ const legacy = await reviews.find({ filter: { status: { $in: ["pending", "running"] } }, sort: ["id"] });
662
+ for (const review of legacy) {
663
+ const reviewId = value(review, "id");
664
+ if (await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId } })) continue;
665
+ if (value(review, "status") === "running") continue;
666
+ const metadata = value(review, "metadata") || {};
667
+ try {
668
+ const targetType = value(review, "targetType");
669
+ const pinnedHead = value(review, "headSha");
670
+ const commitSha = value(review, "commitSha");
671
+ if (targetType === "branch") throw new Error("Legacy branch review has no pinned base");
672
+ const pinned = pinnedHead || (targetType === "commit" ? commitSha : null);
673
+ if (!pinned || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(pinned))
674
+ throw new Error("Legacy review has no pinned source commit");
675
+ const legacyActor = value(review, "createdById");
676
+ const legacyRoles = legacyActor ? await (0, import_review.resolveBackgroundReviewRoles)(db, legacyActor) : [];
677
+ if (value(review, "triggeredBy") !== "poll" && legacyRoles.length !== 1) {
678
+ throw new Error("Legacy review actor has no unambiguous role");
679
+ }
680
+ await this.enqueue({
681
+ legacyReviewId: reviewId,
682
+ repositoryId: value(review, "repositoryId"),
683
+ flowId: value(review, "flowId"),
684
+ targetType,
685
+ mrIid: value(review, "mrIid"),
686
+ commitSha,
687
+ branch: value(review, "branch"),
688
+ folderPath: value(review, "folderPath"),
689
+ headSha: pinned,
690
+ extraInstructions: typeof metadata.extraInstructions === "string" ? metadata.extraInstructions : void 0,
691
+ triggeredBy: value(review, "triggeredBy") === "poll" ? "poll" : "manual",
692
+ userId: legacyActor,
693
+ actorRoles: legacyRoles
694
+ });
695
+ } catch (error) {
696
+ const reason = legacyBlockReason(error);
697
+ await db.getCollection("gitCodeReviews").model.update(
698
+ { metadata: { ...metadata, migrationBlockedReason: reason } },
699
+ { where: { id: reviewId, status: "pending" } }
700
+ );
701
+ (_b = (_a = this.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `Legacy review ${reviewId} is waiting for migration: ${reason}`);
702
+ }
703
+ }
704
+ }
705
+ async owned(requestId, executionId) {
706
+ const db = this.app.db;
707
+ const request = await db.getRepository("gitReviewRequests").findOne({ filterByTk: requestId });
708
+ if (!request || value(request, "fenced") || String(value(request, "executionId")) !== String(executionId))
709
+ throw new Error("Review execution does not own this request");
710
+ const execution = await db.getRepository("executions").findOne({ filterByTk: executionId });
711
+ if (!execution || value(execution, "status") !== 0)
712
+ throw new Error("Review execution is no longer running");
713
+ const inbox = await db.getRepository("gitReviewInbox").findOne({ filterByTk: value(request, "inboxId") });
714
+ if (!inbox || !["running", "dispatched"].includes(value(inbox, "state")))
715
+ throw new Error("Review request is no longer active");
716
+ const project = await db.getRepository("gitReviewProjects").findOne({ filter: { projectKey: value(inbox, "projectKey") } });
717
+ if (!project || String(value(project, "activeInboxId")) !== String(value(inbox, "id")))
718
+ throw new Error("Review reservation no longer belongs to this request");
719
+ return { request, inbox, payload: value(inbox, "payload") };
720
+ }
721
+ async claim(requestId, executionId) {
722
+ const db = this.app.db;
723
+ if ((await this.cutoverStatus()).state !== "ready") return false;
724
+ return db.sequelize.transaction(async (transaction) => {
725
+ var _a;
726
+ const request = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
727
+ if (!request || value(request, "fenced")) return false;
728
+ const previous = value(request, "executionId");
729
+ if (previous != null && String(previous) !== String(executionId)) return false;
730
+ const execution = await db.getCollection("executions").model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
731
+ if (!execution || value(execution, "status") !== 0 || String(value(execution, "workflowId")) !== String(value(request, "workflowId")))
732
+ return false;
733
+ const context = value(execution, "context");
734
+ if (String((_a = context == null ? void 0 : context.data) == null ? void 0 : _a.id) !== String(requestId)) return false;
735
+ const inbox = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: value(request, "inboxId") }, transaction, lock: transaction.LOCK.UPDATE });
736
+ if (!inbox || value(inbox, "state") !== (previous == null ? "dispatched" : "running")) return false;
737
+ const project = await db.getCollection("gitReviewProjects").model.findOne({
738
+ where: { projectKey: value(inbox, "projectKey") },
739
+ transaction,
740
+ lock: transaction.LOCK.UPDATE
741
+ });
742
+ if (!project || String(value(project, "activeInboxId")) !== String(value(inbox, "id"))) return false;
743
+ if (previous != null) return true;
744
+ const [count] = await db.getCollection("gitReviewRequests").model.update({ executionId }, { where: { id: requestId, executionId: null, fenced: false }, transaction });
745
+ if (count !== 1) return false;
746
+ await db.getRepository("gitReviewInbox").update({ filterByTk: value(inbox, "id"), values: { state: "running" }, transaction });
747
+ await db.getRepository("gitCodeReviews").update({
748
+ filterByTk: value(request, "reviewId"),
749
+ values: {
750
+ status: "running",
751
+ startedAt: /* @__PURE__ */ new Date(),
752
+ metadata: { workflowManaged: true, workflowExecutionId: String(executionId) }
753
+ },
754
+ transaction
755
+ });
756
+ return true;
757
+ });
758
+ }
759
+ async prepareContext(requestId, executionId) {
760
+ const { request, payload } = await this.owned(requestId, executionId);
761
+ await this.assertActor(payload);
762
+ const repo = await this.app.db.getRepository("gitRepositories").findOne({ filterByTk: payload.source.repositoryId });
763
+ if (!repo) throw new Error("Repository not found");
764
+ const diff = await (0, import_review_source.readPinnedReviewSource)(this.app.db, repo, payload.source);
765
+ const limitations = [];
766
+ if (payload.source.targetType === "mr")
767
+ limitations.push("Provider comparison patches may omit binary content or truncate large files.");
768
+ if (/Binary files .* differ|GIT binary patch/.test(diff))
769
+ limitations.push("Binary file changes do not include readable source.");
770
+ return {
771
+ requestId,
772
+ reviewId: value(request, "reviewId"),
773
+ ...payload.source,
774
+ userId: payload.userId,
775
+ diff,
776
+ coverage: { complete: limitations.length === 0, limitations },
777
+ instructions: payload.instructions,
778
+ postMode: payload.postMode
779
+ };
780
+ }
781
+ async assertActor(payload) {
782
+ var _a;
783
+ if (!payload.userId || !((_a = payload.actorRoles) == null ? void 0 : _a.length)) throw new Error("Review actor is missing");
784
+ const current = await (0, import_review.resolveBackgroundReviewRoles)(this.app.db, payload.userId);
785
+ if (payload.actorRoles.some((role) => !current.includes(role))) throw new Error("Review actor roles changed");
786
+ const action = payload.source.targetType === "mr" ? "mergeRequestDetail" : "fileContent";
787
+ for (const required of ["triggerReview", action]) {
788
+ if (!await (0, import_repository_access.hasRepositoryAccess)({
789
+ acl: this.app.acl,
790
+ roles: payload.actorRoles,
791
+ repositoryId: payload.source.repositoryId,
792
+ action: required
793
+ }))
794
+ throw new Error("Review actor no longer has repository access");
795
+ }
796
+ }
797
+ async saveResult(requestId, executionId, markdown) {
798
+ if (typeof markdown !== "string" || !markdown.trim() || Buffer.byteLength(markdown) > 2e5)
799
+ throw new Error("Invalid review result");
800
+ const { request, payload } = await this.owned(requestId, executionId);
801
+ const hash = fingerprint(markdown);
802
+ const existing = value(request, "resultFingerprint");
803
+ if (existing && existing !== hash) throw new Error("Review result is immutable");
804
+ const persist = async (transaction) => {
805
+ const lockedRequest = await this.app.db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
806
+ if (!lockedRequest || value(lockedRequest, "fenced") || String(value(lockedRequest, "executionId")) !== String(executionId))
807
+ throw new Error("Review execution lost ownership");
808
+ const lockedFingerprint = value(lockedRequest, "resultFingerprint");
809
+ if (lockedFingerprint && lockedFingerprint !== hash) throw new Error("Review result is immutable");
810
+ const execution = await this.app.db.getCollection("executions").model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
811
+ const inbox = await this.app.db.getCollection("gitReviewInbox").model.findOne({ where: { id: value(request, "inboxId") }, transaction, lock: transaction.LOCK.UPDATE });
812
+ if (!execution || value(execution, "status") !== 0 || !inbox || value(inbox, "state") !== "running")
813
+ throw new Error("Review execution is no longer active");
814
+ if (lockedFingerprint === hash) return;
815
+ const [updated] = await this.app.db.getCollection("gitReviewRequests").model.update(
816
+ { resultFingerprint: hash },
817
+ { where: { id: requestId, executionId, fenced: false }, transaction }
818
+ );
819
+ if (updated !== 1) throw new Error("Review execution lost ownership");
820
+ await this.app.db.getRepository("gitCodeReviews").update({
821
+ filterByTk: value(request, "reviewId"),
822
+ values: {
823
+ reviewMarkdown: markdown,
824
+ status: "completed",
825
+ postStatus: payload.source.targetType === "mr" && payload.postMode !== "disabled" ? "pending_approval" : "skipped",
826
+ finishedAt: /* @__PURE__ */ new Date()
827
+ },
828
+ transaction
829
+ });
830
+ };
831
+ const sequelize = this.app.db.sequelize;
832
+ if (sequelize.getDialect() !== "sqlite") {
833
+ await sequelize.transaction(persist);
834
+ return hash;
835
+ }
836
+ const isBusy = (error) => {
837
+ var _a, _b;
838
+ const detail = error;
839
+ return [detail == null ? void 0 : detail.code, (_a = detail == null ? void 0 : detail.original) == null ? void 0 : _a.code, (_b = detail == null ? void 0 : detail.parent) == null ? void 0 : _b.code].includes("SQLITE_BUSY");
840
+ };
841
+ for (let attempt = 0; ; attempt++) {
842
+ let transaction;
843
+ try {
844
+ transaction = await sequelize.transaction({ type: import_sequelize.Transaction.TYPES.IMMEDIATE });
845
+ } catch (error) {
846
+ if (!isBusy(error) || attempt >= 7) throw error;
847
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
848
+ continue;
849
+ }
850
+ try {
851
+ await persist(transaction);
852
+ } catch (error) {
853
+ await transaction.rollback();
854
+ if (!isBusy(error) || attempt >= 7) throw error;
855
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
856
+ continue;
857
+ }
858
+ await transaction.commit();
859
+ return hash;
860
+ }
861
+ }
862
+ async startPublication(requestId, executionId, inboxId, reviewId, payload, hash, token, mode, start) {
863
+ const db = this.app.db;
864
+ const options = db.sequelize.getDialect() === "sqlite" ? { type: import_sequelize.Transaction.TYPES.IMMEDIATE } : {};
865
+ return db.sequelize.transaction(options, async (transaction) => {
866
+ var _a, _b, _c;
867
+ const request = await db.getCollection("gitReviewRequests").model.findOne({
868
+ where: { id: requestId },
869
+ transaction,
870
+ lock: transaction.LOCK.UPDATE
871
+ });
872
+ const execution = await db.getCollection("executions").model.findOne({
873
+ where: { id: executionId },
874
+ transaction,
875
+ lock: transaction.LOCK.UPDATE
876
+ });
877
+ const inbox = await db.getCollection("gitReviewInbox").model.findOne({
878
+ where: { id: inboxId },
879
+ transaction,
880
+ lock: transaction.LOCK.UPDATE
881
+ });
882
+ const project = await db.getCollection("gitReviewProjects").model.findOne({
883
+ where: { projectKey: payload.source.projectKey },
884
+ transaction,
885
+ lock: transaction.LOCK.UPDATE
886
+ });
887
+ const review = await db.getCollection("gitCodeReviews").model.findOne({
888
+ where: { id: reviewId },
889
+ transaction,
890
+ lock: transaction.LOCK.UPDATE
891
+ });
892
+ const currentPayload = inbox && value(inbox, "payload");
893
+ const context = execution && value(execution, "context");
894
+ if (!request || value(request, "fenced") || !value(request, "aiSettled") || value(request, "postClaim") !== token || String(value(request, "executionId")) !== String(executionId) || String(value(request, "inboxId")) !== String(inboxId) || String(value(request, "reviewId")) !== String(reviewId) || value(request, "resultFingerprint") !== hash || !execution || String(value(execution, "workflowId")) !== String(value(request, "workflowId")) || String((_a = context == null ? void 0 : context.data) == null ? void 0 : _a.id) !== String(requestId) || (mode === "initial" ? value(execution, "status") !== 0 : typeof value(execution, "status") !== "number" || value(execution, "status") === 0) || !inbox || mode === "initial" && value(inbox, "state") !== "running" || !currentPayload || currentPayload.postMode !== payload.postMode || JSON.stringify(currentPayload.source) !== JSON.stringify(payload.source) || !project || String(value(project, "activeInboxId")) !== String(inboxId) || value(project, "legacyPostReviewId") != null || !review || value(review, "status") !== "completed" || value(review, "postStatus") !== (mode === "initial" ? "posting" : "retrying") || String(value(review, "repositoryId")) !== String(payload.source.repositoryId) || value(review, "targetType") !== "mr" || String(value(review, "mrIid")) !== String(payload.source.mrIid) || value(review, "headSha") !== payload.source.headSha || fingerprint(value(review, "reviewMarkdown") || "") !== hash)
895
+ reviewConflict("Review publication claim changed");
896
+ const nodes = await db.getCollection("flow_nodes").model.findAll({
897
+ where: { workflowId: value(request, "workflowId") },
898
+ transaction,
899
+ lock: transaction.LOCK.UPDATE
900
+ });
901
+ const llms = nodes.filter((node) => value(node, "type") === "git-review-llm");
902
+ if (!llms.length) reviewConflict("Review publication claim changed");
903
+ for (const node of llms) {
904
+ const jobs = await db.getCollection("jobs").model.findAll({
905
+ where: { executionId, nodeId: value(node, "id") },
906
+ transaction,
907
+ lock: transaction.LOCK.UPDATE
908
+ });
909
+ if (jobs.length !== 1 || value(jobs[0], "status") !== 1)
910
+ reviewConflict("Review publication claim changed");
911
+ }
912
+ if (payload.postMode === "manual") {
913
+ const manual = nodes.filter((node) => value(node, "type") === "manual");
914
+ if (manual.length !== 1) reviewConflict("Review publication claim changed");
915
+ const jobs = await db.getCollection("jobs").model.findAll({
916
+ where: { executionId, nodeId: value(manual[0], "id") },
917
+ transaction,
918
+ lock: transaction.LOCK.UPDATE
919
+ });
920
+ const result = jobs[0] && value(jobs[0], "result");
921
+ if (jobs.length !== 1 || value(jobs[0], "status") !== 1 || (result == null ? void 0 : result._) !== "approve" || ((_b = result.review) == null ? void 0 : _b.fingerprint) !== hash)
922
+ reviewConflict("Review publication claim changed");
923
+ const workflow = await db.getCollection("workflows").model.findOne({
924
+ where: { id: value(request, "workflowId") },
925
+ transaction,
926
+ lock: transaction.LOCK.UPDATE
927
+ });
928
+ const options2 = workflow && value(workflow, "options");
929
+ const assignees = (_c = options2 == null ? void 0 : options2.gitReview) == null ? void 0 : _c.approverIds;
930
+ const tasks = await db.getCollection("workflowManualTasks").model.findAll({
931
+ where: {
932
+ executionId,
933
+ workflowId: value(request, "workflowId"),
934
+ nodeId: value(manual[0], "id"),
935
+ jobId: value(jobs[0], "id"),
936
+ status: 1
937
+ },
938
+ transaction,
939
+ lock: transaction.LOCK.UPDATE
940
+ });
941
+ if (!Array.isArray(assignees) || !tasks.some((task) => {
942
+ var _a2;
943
+ const decision = value(task, "result");
944
+ return (decision == null ? void 0 : decision._) === "approve" && ((_a2 = decision.review) == null ? void 0 : _a2.fingerprint) === hash && assignees.some((id) => String(id) === String(value(task, "userId")));
945
+ }))
946
+ reviewConflict("Review publication claim changed");
947
+ }
948
+ const response = start();
949
+ response.catch(() => void 0);
950
+ return { response };
951
+ });
952
+ }
953
+ async publish(requestId, executionId, approvedFingerprint) {
954
+ const { request, inbox, payload } = await this.owned(requestId, executionId);
955
+ await this.assertActor(payload);
956
+ const db = this.app.db;
957
+ const review = await db.getRepository("gitCodeReviews").findOne({ filterByTk: value(request, "reviewId") });
958
+ if (!review) throw new Error("Review not found");
959
+ const markdown = value(review, "reviewMarkdown");
960
+ if (!markdown || fingerprint(markdown) !== approvedFingerprint || value(request, "resultFingerprint") !== approvedFingerprint)
961
+ throw new Error("Approved review content changed");
962
+ if (payload.source.targetType !== "mr" || payload.postMode === "disabled") return { status: "skipped" };
963
+ if (payload.postMode === "manual") {
964
+ const integration = this.app.pm.get("plugin-workflow-git-review") || this.app.pm.get("workflow-git-review");
965
+ if ((integration == null ? void 0 : integration.enabled) !== true || !integration.assertManualApproval)
966
+ reviewConflict("Review approval verifier is unavailable");
967
+ await integration.assertManualApproval(value(request, "workflowId"), executionId, approvedFingerprint);
968
+ }
969
+ const reviewId = value(request, "reviewId");
970
+ const inboxId = value(inbox, "id");
971
+ const token = (0, import_crypto.randomUUID)();
972
+ const claim = async (transaction) => {
973
+ const lockedRequest = await db.getCollection("gitReviewRequests").model.findOne({
974
+ where: { id: requestId },
975
+ transaction,
976
+ lock: transaction.LOCK.UPDATE
977
+ });
978
+ const lockedExecution = await db.getCollection("executions").model.findOne({
979
+ where: { id: executionId },
980
+ transaction,
981
+ lock: transaction.LOCK.UPDATE
982
+ });
983
+ const lockedInbox = await db.getCollection("gitReviewInbox").model.findOne({
984
+ where: { id: inboxId },
985
+ transaction,
986
+ lock: transaction.LOCK.UPDATE
987
+ });
988
+ const project = await db.getCollection("gitReviewProjects").model.findOne({
989
+ where: { projectKey: payload.source.projectKey },
990
+ transaction,
991
+ lock: transaction.LOCK.UPDATE
992
+ });
993
+ const lockedReview = await db.getCollection("gitCodeReviews").model.findOne({
994
+ where: { id: reviewId },
995
+ transaction,
996
+ lock: transaction.LOCK.UPDATE
997
+ });
998
+ if (!lockedRequest || value(lockedRequest, "fenced") || !value(lockedRequest, "aiSettled") || String(value(lockedRequest, "executionId")) !== String(executionId) || value(lockedRequest, "resultFingerprint") !== approvedFingerprint || !lockedExecution || value(lockedExecution, "status") !== 0 || String(value(lockedExecution, "workflowId")) !== String(value(lockedRequest, "workflowId")) || !lockedInbox || value(lockedInbox, "state") !== "running" || !project || String(value(project, "activeInboxId")) !== String(inboxId) || value(project, "legacyPostReviewId") != null || !lockedReview || value(lockedReview, "status") !== "completed" || fingerprint(value(lockedReview, "reviewMarkdown") || "") !== approvedFingerprint)
999
+ reviewConflict("Review publication is already in progress or unavailable");
1000
+ const postStatus = value(lockedReview, "postStatus");
1001
+ if (value(lockedRequest, "postClaim")) return "in_progress";
1002
+ if (postStatus === "posted") {
1003
+ if (value(lockedReview, "postedNoteId") == null)
1004
+ reviewConflict("Review publication receipt is unavailable");
1005
+ return "posted";
1006
+ }
1007
+ if (["posting", "post_unknown", "post_failed", "retrying"].includes(postStatus)) return "in_progress";
1008
+ if (postStatus !== "pending_approval") reviewConflict("Review publication is already in progress or unavailable");
1009
+ await lockedRequest.update({ postClaim: token, postClaimedAt: /* @__PURE__ */ new Date() }, { transaction });
1010
+ await lockedReview.update({ postStatus: "posting" }, { transaction });
1011
+ return "claimed";
1012
+ };
1013
+ let admission;
1014
+ if (db.sequelize.getDialect() !== "sqlite") {
1015
+ admission = await db.sequelize.transaction(claim);
1016
+ } else {
1017
+ const isBusy = (error) => {
1018
+ var _a, _b;
1019
+ const detail = error;
1020
+ return [detail == null ? void 0 : detail.code, (_a = detail == null ? void 0 : detail.original) == null ? void 0 : _a.code, (_b = detail == null ? void 0 : detail.parent) == null ? void 0 : _b.code].includes("SQLITE_BUSY");
1021
+ };
1022
+ for (let attempt = 0; ; attempt++) {
1023
+ let transaction;
1024
+ try {
1025
+ transaction = await db.sequelize.transaction({ type: import_sequelize.Transaction.TYPES.IMMEDIATE });
1026
+ } catch (error) {
1027
+ if (!isBusy(error) || attempt >= 7) throw error;
1028
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
1029
+ continue;
1030
+ }
1031
+ try {
1032
+ admission = await claim(transaction);
1033
+ } catch (error) {
1034
+ await transaction.rollback();
1035
+ if (!isBusy(error) || attempt >= 7) throw error;
1036
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
1037
+ continue;
1038
+ }
1039
+ await transaction.commit();
1040
+ break;
1041
+ }
1042
+ }
1043
+ if (admission !== "claimed") return { status: admission };
1044
+ try {
1045
+ const repo = await db.getRepository("gitRepositories").findOne({ filterByTk: payload.source.repositoryId });
1046
+ if (!repo) throw new Error("Repository not found");
1047
+ await (0, import_review_source.assertCurrentMrHead)(db, repo, payload.source);
1048
+ const marker = `<!-- git-review:${String(requestId)}:${approvedFingerprint} -->`;
1049
+ const noteId = await (0, import_review_source.publishPinnedReview)(db, repo, payload.source, markdown, marker, async (start) => {
1050
+ await this.assertActor(payload);
1051
+ return this.startPublication(
1052
+ requestId,
1053
+ executionId,
1054
+ inboxId,
1055
+ reviewId,
1056
+ payload,
1057
+ approvedFingerprint,
1058
+ token,
1059
+ "initial",
1060
+ start
1061
+ );
1062
+ });
1063
+ await db.sequelize.transaction(async (transaction) => {
1064
+ const current = await db.getCollection("gitReviewRequests").model.findOne({
1065
+ where: { id: requestId },
1066
+ transaction,
1067
+ lock: transaction.LOCK.UPDATE
1068
+ });
1069
+ const currentReview = await db.getCollection("gitCodeReviews").model.findOne({
1070
+ where: { id: reviewId },
1071
+ transaction,
1072
+ lock: transaction.LOCK.UPDATE
1073
+ });
1074
+ if (!current || value(current, "fenced") || value(current, "postClaim") !== token || value(current, "resultFingerprint") !== approvedFingerprint || !currentReview || value(currentReview, "postStatus") !== "posting" || fingerprint(value(currentReview, "reviewMarkdown") || "") !== approvedFingerprint)
1075
+ reviewConflict("Review publication claim changed");
1076
+ await currentReview.update({ postStatus: "posted", postedNoteId: noteId, error: null }, { transaction });
1077
+ await current.update({ postClaim: null, postClaimedAt: null }, { transaction });
1078
+ });
1079
+ return { status: "posted" };
1080
+ } catch (error) {
1081
+ await db.sequelize.transaction(async (transaction) => {
1082
+ const current = await db.getCollection("gitReviewRequests").model.findOne({
1083
+ where: { id: requestId },
1084
+ transaction,
1085
+ lock: transaction.LOCK.UPDATE
1086
+ });
1087
+ if (!current || value(current, "postClaim") !== token) return;
1088
+ await db.getCollection("gitCodeReviews").model.update(
1089
+ { postStatus: "post_unknown", error: "Review publication outcome is unknown" },
1090
+ { where: { id: reviewId, postStatus: "posting" }, transaction }
1091
+ );
1092
+ });
1093
+ throw error;
1094
+ }
1095
+ }
1096
+ async retryPost(reviewId, actor, roles, allowResend) {
1097
+ const db = this.app.db;
1098
+ const review = await db.getRepository("gitCodeReviews").findOne({ filterByTk: reviewId });
1099
+ if (!review) reviewConflict("Review not found");
1100
+ const repositoryId = value(review, "repositoryId");
1101
+ const currentRoles = await (0, import_review.resolveBackgroundReviewRoles)(db, actor);
1102
+ if (!roles.length || roles.some((role) => !currentRoles.includes(role)) || !await (0, import_repository_access.hasRepositoryAccess)({ acl: this.app.acl, roles, repositoryId, action: "reviewWorkflowRetryPost" })) {
1103
+ const error = new Error("Permission denied");
1104
+ error.status = 403;
1105
+ throw error;
1106
+ }
1107
+ const inbox = await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId } });
1108
+ const request = inbox && await db.getRepository("gitReviewRequests").findOne({ filter: { inboxId: value(inbox, "id") } });
1109
+ if (!inbox || !request || value(request, "fenced") || !value(request, "aiSettled"))
1110
+ reviewConflict("Review is not settled or is no longer available");
1111
+ const executionId = value(request, "executionId");
1112
+ if (executionId == null) reviewConflict("Review execution is unavailable");
1113
+ const execution = await db.getRepository("executions").findOne({ filterByTk: executionId });
1114
+ if (!execution || typeof value(execution, "status") !== "number" || value(execution, "status") === 0)
1115
+ reviewConflict("Review execution is not terminal");
1116
+ const payload = value(inbox, "payload");
1117
+ if (!payload || payload.source.targetType !== "mr" || payload.postMode === "disabled")
1118
+ reviewConflict("Review cannot be published");
1119
+ const markdown = value(review, "reviewMarkdown");
1120
+ const hash = value(request, "resultFingerprint");
1121
+ if (!markdown || !hash || fingerprint(markdown) !== hash) reviewConflict("Approved review content changed");
1122
+ const integration = this.app.pm.get("plugin-workflow-git-review") || this.app.pm.get("workflow-git-review");
1123
+ if ((integration == null ? void 0 : integration.enabled) !== true) reviewConflict("Git review workflow integration is unavailable");
1124
+ await this.assertSafeWorkflow(value(request, "workflowId"), payload.postMode, void 0, repositoryId);
1125
+ if (payload.postMode === "manual") {
1126
+ if (!integration.assertManualApproval) reviewConflict("Review approval verifier is unavailable");
1127
+ await integration.assertManualApproval(value(request, "workflowId"), executionId, hash);
1128
+ }
1129
+ if (value(review, "postStatus") === "posted") {
1130
+ const noteId = value(review, "postedNoteId");
1131
+ if (noteId == null) reviewConflict("Review publication receipt is unavailable");
1132
+ return { status: "posted", postedNoteId: String(noteId), canResend: false };
1133
+ }
1134
+ const requestId = value(request, "id");
1135
+ const inboxId = value(inbox, "id");
1136
+ const token = (0, import_crypto.randomUUID)();
1137
+ let ownClaim = false;
1138
+ let acquiredProject = false;
1139
+ await db.sequelize.transaction(async (transaction) => {
1140
+ const lockedRequest = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
1141
+ const lockedExecution = await db.getCollection("executions").model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
1142
+ const lockedInbox = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
1143
+ const lockedProject = await db.getCollection("gitReviewProjects").model.findOne({
1144
+ where: { projectKey: payload.source.projectKey },
1145
+ transaction,
1146
+ lock: transaction.LOCK.UPDATE
1147
+ });
1148
+ const lockedReview = await db.getCollection("gitCodeReviews").model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
1149
+ if (!lockedRequest || value(lockedRequest, "fenced") || !value(lockedRequest, "aiSettled") || String(value(lockedRequest, "executionId")) !== String(executionId) || value(lockedRequest, "resultFingerprint") !== hash)
1150
+ reviewConflict("Review is no longer available");
1151
+ if (!lockedExecution || typeof value(lockedExecution, "status") !== "number" || value(lockedExecution, "status") === 0)
1152
+ reviewConflict("Review execution is not terminal");
1153
+ if (!lockedInbox || !lockedProject || !lockedReview || fingerprint(value(lockedReview, "reviewMarkdown") || "") !== hash || !["posting", "post_unknown", "post_failed", "retrying"].includes(value(lockedReview, "postStatus")))
1154
+ reviewConflict("Review publication cannot be retried");
1155
+ const active = value(lockedProject, "activeInboxId");
1156
+ if (value(lockedProject, "legacyPostReviewId") != null)
1157
+ reviewConflict("Another review is active for this project");
1158
+ if (active != null && String(active) !== String(inboxId))
1159
+ reviewConflict("Another review is active for this project");
1160
+ const existingClaim = value(lockedRequest, "postClaim");
1161
+ if (existingClaim) {
1162
+ if (allowResend) reviewConflict("A publication attempt may still be running");
1163
+ return;
1164
+ }
1165
+ if (active == null) {
1166
+ const [reserved] = await db.getCollection("gitReviewProjects").model.update(
1167
+ { activeInboxId: inboxId },
1168
+ {
1169
+ where: { projectKey: payload.source.projectKey, activeInboxId: null, legacyPostReviewId: null },
1170
+ transaction
1171
+ }
1172
+ );
1173
+ if (reserved !== 1) reviewConflict("Another review is active for this project");
1174
+ acquiredProject = true;
1175
+ }
1176
+ await lockedRequest.update({ postClaim: token, postClaimedAt: /* @__PURE__ */ new Date() }, { transaction });
1177
+ ownClaim = true;
1178
+ });
1179
+ let sent = false;
1180
+ try {
1181
+ const repo = await db.getRepository("gitRepositories").findOne({ filterByTk: repositoryId });
1182
+ if (!repo) reviewConflict("Repository not found");
1183
+ const marker = `<!-- git-review:${String(requestId)}:${hash} -->`;
1184
+ let noteId = await (0, import_review_source.findPublishedReview)(db, repo, payload.source, markdown, marker);
1185
+ if (!noteId && allowResend) {
1186
+ if (!ownClaim) reviewConflict("A publication attempt may still be running");
1187
+ await db.sequelize.transaction(async (transaction) => {
1188
+ const current = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
1189
+ const project = await db.getCollection("gitReviewProjects").model.findOne({
1190
+ where: { projectKey: payload.source.projectKey },
1191
+ transaction,
1192
+ lock: transaction.LOCK.UPDATE
1193
+ });
1194
+ if (!current || value(current, "fenced") || value(current, "postClaim") !== token || !project || String(value(project, "activeInboxId")) !== String(inboxId))
1195
+ reviewConflict("Review publication claim changed");
1196
+ const [changed] = await db.getCollection("gitCodeReviews").model.update(
1197
+ { postStatus: "retrying" },
1198
+ { where: { id: reviewId, postStatus: ["posting", "post_unknown", "post_failed"] }, transaction }
1199
+ );
1200
+ if (changed !== 1) reviewConflict("Review publication state changed");
1201
+ });
1202
+ sent = true;
1203
+ noteId = await (0, import_review_source.publishPinnedReview)(db, repo, payload.source, markdown, marker, async (start) => {
1204
+ const latestRoles = await (0, import_review.resolveBackgroundReviewRoles)(db, actor);
1205
+ if (roles.some((role) => !latestRoles.includes(role)) || !await (0, import_repository_access.hasRepositoryAccess)({ acl: this.app.acl, roles, repositoryId, action: "reviewWorkflowRetryPost" }))
1206
+ reviewConflict("Permission denied");
1207
+ return this.startPublication(requestId, executionId, inboxId, reviewId, payload, hash, token, "retry", start);
1208
+ });
1209
+ }
1210
+ if (!noteId) return { status: "unknown", canResend: ownClaim };
1211
+ if (!ownClaim) return { status: "observed", postedNoteId: noteId, canResend: false };
1212
+ await db.sequelize.transaction(async (transaction) => {
1213
+ const lockedRequest = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
1214
+ const lockedInbox = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
1215
+ const lockedProject = await db.getCollection("gitReviewProjects").model.findOne({
1216
+ where: { projectKey: payload.source.projectKey },
1217
+ transaction,
1218
+ lock: transaction.LOCK.UPDATE
1219
+ });
1220
+ const lockedReview = await db.getCollection("gitCodeReviews").model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
1221
+ if (!lockedRequest || value(lockedRequest, "fenced") || value(lockedRequest, "postClaim") !== token || value(lockedRequest, "resultFingerprint") !== hash || !lockedInbox || !lockedProject || String(value(lockedProject, "activeInboxId")) !== String(inboxId) || !lockedReview || fingerprint(value(lockedReview, "reviewMarkdown") || "") !== hash)
1222
+ reviewConflict("Review publication claim changed");
1223
+ if (value(lockedReview, "postStatus") === "posted" && String(value(lockedReview, "postedNoteId")) !== String(noteId))
1224
+ reviewConflict("Review publication state changed");
1225
+ const [cleared] = await db.getCollection("gitReviewRequests").model.update(
1226
+ { postClaim: null, postClaimedAt: null },
1227
+ { where: { id: requestId, postClaim: token, fenced: false }, transaction }
1228
+ );
1229
+ if (cleared !== 1) reviewConflict("Review publication claim changed");
1230
+ await db.getRepository("gitCodeReviews").update({
1231
+ filterByTk: reviewId,
1232
+ values: { postStatus: "posted", postedNoteId: noteId, error: null, status: "completed" },
1233
+ transaction
1234
+ });
1235
+ await db.getRepository("gitReviewInbox").update({ filterByTk: inboxId, values: { state: "completed" }, transaction });
1236
+ const [released] = await db.getCollection("gitReviewProjects").model.update(
1237
+ { activeInboxId: null },
1238
+ { where: { projectKey: payload.source.projectKey, activeInboxId: inboxId }, transaction }
1239
+ );
1240
+ if (released !== 1) reviewConflict("Review project reservation changed");
1241
+ });
1242
+ ownClaim = false;
1243
+ acquiredProject = false;
1244
+ await this.reconcile().catch((error) => {
1245
+ var _a, _b;
1246
+ return (_b = (_a = this.app.log) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, "Git review dispatch will be retried", error);
1247
+ });
1248
+ return { status: "posted", postedNoteId: noteId, canResend: false };
1249
+ } catch (error) {
1250
+ if (sent) {
1251
+ await db.sequelize.transaction(async (transaction) => {
1252
+ const current = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
1253
+ if (!current || value(current, "fenced") || value(current, "postClaim") !== token)
1254
+ return;
1255
+ const [changed] = await db.getCollection("gitCodeReviews").model.update(
1256
+ { postStatus: "post_unknown", error: "Review publication outcome is unknown" },
1257
+ { where: { id: reviewId, postStatus: "retrying" }, transaction }
1258
+ );
1259
+ if (changed)
1260
+ await db.getRepository("gitReviewInbox").update({ filterByTk: inboxId, values: { state: "quarantined" }, transaction });
1261
+ });
1262
+ acquiredProject = false;
1263
+ ownClaim = false;
1264
+ }
1265
+ throw error;
1266
+ } finally {
1267
+ if (!sent && (ownClaim || acquiredProject)) {
1268
+ await db.sequelize.transaction(async (transaction) => {
1269
+ const current = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
1270
+ if (!current || value(current, "postClaim") !== token) return;
1271
+ await current.update({ postClaim: null, postClaimedAt: null }, { transaction });
1272
+ if (acquiredProject)
1273
+ await db.getCollection("gitReviewProjects").model.update(
1274
+ { activeInboxId: null },
1275
+ { where: { projectKey: payload.source.projectKey, activeInboxId: inboxId }, transaction }
1276
+ );
1277
+ });
1278
+ }
1279
+ }
1280
+ }
1281
+ async resetPostClaim(reviewId, actor, expectedAttempt) {
1282
+ const db = this.app.db;
1283
+ const inbox = await db.getRepository("gitReviewInbox").findOne({ filter: { reviewId } });
1284
+ const request = inbox && await db.getRepository("gitReviewRequests").findOne({ filter: { inboxId: value(inbox, "id") } });
1285
+ if (!inbox || !request) reviewConflict("Review request not found");
1286
+ await db.sequelize.transaction(async (transaction) => {
1287
+ const requestId = value(request, "id");
1288
+ const locked = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
1289
+ if (!locked || value(locked, "fenced") || !value(locked, "aiSettled"))
1290
+ reviewConflict("No recoverable publication claim");
1291
+ const claim = value(locked, "postClaim") ?? null;
1292
+ if (claim !== expectedAttempt) reviewConflict("Review publication claim changed");
1293
+ const executionId = value(locked, "executionId");
1294
+ const execution = executionId == null ? null : await db.getCollection("executions").model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
1295
+ if (!execution || typeof value(execution, "status") !== "number" || value(execution, "status") === 0)
1296
+ reviewConflict("Review execution is not terminal");
1297
+ const lockedInbox = await db.getCollection("gitReviewInbox").model.findOne({ where: { id: value(inbox, "id") }, transaction, lock: transaction.LOCK.UPDATE });
1298
+ const project = lockedInbox && await db.getCollection("gitReviewProjects").model.findOne({
1299
+ where: { projectKey: value(lockedInbox, "projectKey") },
1300
+ transaction,
1301
+ lock: transaction.LOCK.UPDATE
1302
+ });
1303
+ const lockedReview = await db.getCollection("gitCodeReviews").model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
1304
+ if (!lockedInbox || !lockedReview || !["posting", "post_unknown", "post_failed", "retrying"].includes(value(lockedReview, "postStatus")))
1305
+ reviewConflict("Review publication cannot be recovered");
1306
+ const [reset] = await db.getCollection("gitReviewRequests").model.update(
1307
+ { postClaim: null, postClaimedAt: null, postResetBy: String(actor), postResetAt: /* @__PURE__ */ new Date() },
1308
+ { where: { id: requestId, postClaim: claim, fenced: false }, transaction }
1309
+ );
1310
+ if (reset !== 1) reviewConflict("Review publication claim changed");
1311
+ await lockedReview.update({ postStatus: "post_unknown" }, { transaction });
1312
+ if (project)
1313
+ await db.getCollection("gitReviewProjects").model.update(
1314
+ { activeInboxId: null },
1315
+ {
1316
+ where: {
1317
+ projectKey: value(lockedInbox, "projectKey"),
1318
+ activeInboxId: value(lockedInbox, "id")
1319
+ },
1320
+ transaction
1321
+ }
1322
+ );
1323
+ await lockedInbox.update({ state: "completed" }, { transaction });
1324
+ });
1325
+ await this.reconcile().catch((error) => {
1326
+ var _a, _b;
1327
+ return (_b = (_a = this.app.log) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, "Git review dispatch will be retried", error);
1328
+ });
1329
+ }
1330
+ async markAISettled(requestId, executionId) {
1331
+ await this.owned(requestId, executionId);
1332
+ const integration = this.app.pm.get("plugin-workflow-git-review") || this.app.pm.get("workflow-git-review");
1333
+ if (!(integration == null ? void 0 : integration.assertAISettled)) throw new Error("Review settlement verifier is unavailable");
1334
+ await integration.assertAISettled(requestId, executionId);
1335
+ const [updated] = await this.app.db.getCollection("gitReviewRequests").model.update({ aiSettled: true }, { where: { id: requestId, executionId, aiSettled: false, fenced: false } });
1336
+ if (!updated) {
1337
+ const request = await this.app.db.getRepository("gitReviewRequests").findOne({ filterByTk: requestId });
1338
+ if (!request || String(value(request, "executionId")) !== String(executionId) || value(request, "fenced") || !value(request, "aiSettled")) {
1339
+ throw new Error("Review settlement could not be recorded");
1340
+ }
1341
+ }
1342
+ }
1343
+ async onExecutionStatus(executionId, status) {
1344
+ const db = this.app.db;
1345
+ const request = await db.getRepository("gitReviewRequests").findOne({ filter: { executionId } });
1346
+ if (!request || value(request, "fenced")) return;
1347
+ const execution = await db.getRepository("executions").findOne({ filterByTk: executionId });
1348
+ if (!execution || String(value(execution, "status")) !== String(status)) return;
1349
+ const inbox = await db.getRepository("gitReviewInbox").findOne({ filterByTk: value(request, "inboxId") });
1350
+ if (!inbox || !["running", "dispatched", "quarantined"].includes(value(inbox, "state"))) return;
1351
+ if (value(request, "postClaim")) return;
1352
+ const review = await db.getRepository("gitCodeReviews").findOne({ filterByTk: value(request, "reviewId") });
1353
+ let rejected = false;
1354
+ let settledFailure = false;
1355
+ const fingerprint2 = value(request, "resultFingerprint");
1356
+ if (Number(status) === -5 && value(request, "aiSettled") && fingerprint2 && review) {
1357
+ const integration = this.app.pm.get("plugin-workflow-git-review") || this.app.pm.get("workflow-git-review");
1358
+ if (integration == null ? void 0 : integration.assertManualRejection) {
1359
+ try {
1360
+ await integration.assertManualRejection(value(request, "workflowId"), executionId, fingerprint2);
1361
+ rejected = true;
1362
+ } catch (_error) {
1363
+ rejected = false;
1364
+ }
1365
+ }
1366
+ }
1367
+ if ([-1, -2].includes(Number(status))) {
1368
+ const integration = this.app.pm.get("plugin-workflow-git-review") || this.app.pm.get("workflow-git-review");
1369
+ if (integration == null ? void 0 : integration.assertNoInFlightAI) {
1370
+ try {
1371
+ await integration.assertNoInFlightAI(value(request, "id"), executionId);
1372
+ settledFailure = true;
1373
+ } catch (_error) {
1374
+ settledFailure = false;
1375
+ }
1376
+ }
1377
+ }
1378
+ const completed = Number(status) === 1 && review && ["posted", "skipped"].includes(value(review, "postStatus"));
1379
+ const postUnresolved = review && ["posting", "post_unknown", "post_failed", "retrying"].includes(value(review, "postStatus"));
1380
+ if (postUnresolved || !completed && !rejected && !settledFailure || !settledFailure && (!value(request, "aiSettled") || !fingerprint2) || !review) {
1381
+ if (Number(status) !== 0) {
1382
+ await db.sequelize.transaction(async (transaction) => {
1383
+ const current = await db.getCollection("gitReviewRequests").model.findOne({ where: { id: value(request, "id") }, transaction, lock: transaction.LOCK.UPDATE });
1384
+ if (!current || value(current, "fenced") || value(current, "postClaim")) return;
1385
+ const [changed] = await db.getCollection("gitReviewInbox").model.update(
1386
+ { state: "quarantined" },
1387
+ { where: { id: value(inbox, "id"), state: ["dispatched", "running"] }, transaction }
1388
+ );
1389
+ if (changed === 1)
1390
+ await db.getRepository("gitCodeReviews").update({
1391
+ filterByTk: value(request, "reviewId"),
1392
+ values: {
1393
+ status: "failed",
1394
+ error: "Workflow ended without confirmed AI settlement; project remains reserved"
1395
+ },
1396
+ transaction
1397
+ });
1398
+ });
1399
+ }
1400
+ return;
1401
+ }
1402
+ await db.sequelize.transaction(async (transaction) => {
1403
+ const lockedRequest = await db.getCollection("gitReviewRequests").model.findOne({
1404
+ where: { id: value(request, "id") },
1405
+ transaction,
1406
+ lock: transaction.LOCK.UPDATE
1407
+ });
1408
+ if (!lockedRequest || value(lockedRequest, "fenced") || value(lockedRequest, "postClaim") || !settledFailure && !value(lockedRequest, "aiSettled"))
1409
+ return;
1410
+ const lockedInbox = await db.getCollection("gitReviewInbox").model.findOne({
1411
+ where: { id: value(inbox, "id") },
1412
+ transaction,
1413
+ lock: transaction.LOCK.UPDATE
1414
+ });
1415
+ if (!lockedInbox || !["running", "dispatched", "quarantined"].includes(value(lockedInbox, "state")))
1416
+ return;
1417
+ const lockedReview = await db.getCollection("gitCodeReviews").model.findOne({ where: { id: value(request, "reviewId") }, transaction, lock: transaction.LOCK.UPDATE });
1418
+ if (!lockedReview || ["posting", "post_unknown", "post_failed", "retrying"].includes(value(lockedReview, "postStatus")))
1419
+ return;
1420
+ const [released] = await db.getCollection("gitReviewProjects").model.update(
1421
+ { activeInboxId: null },
1422
+ {
1423
+ where: { projectKey: value(inbox, "projectKey"), activeInboxId: value(inbox, "id") },
1424
+ transaction
1425
+ }
1426
+ );
1427
+ if (released !== 1) return;
1428
+ if (settledFailure) {
1429
+ await lockedRequest.update({ aiSettled: true }, { transaction });
1430
+ await db.getRepository("gitCodeReviews").update({
1431
+ filterByTk: value(request, "reviewId"),
1432
+ values: { status: "failed", error: "Workflow failed after all started LLM calls settled" },
1433
+ transaction
1434
+ });
1435
+ }
1436
+ if (rejected) {
1437
+ await db.getRepository("gitCodeReviews").update({
1438
+ filterByTk: value(request, "reviewId"),
1439
+ values: { postStatus: "rejected", status: "completed" },
1440
+ transaction
1441
+ });
1442
+ }
1443
+ await db.getRepository("gitReviewInbox").update({ filterByTk: value(inbox, "id"), values: { state: "completed" }, transaction });
1444
+ });
1445
+ await this.reconcile();
1446
+ }
1447
+ }
1448
+ // Annotate the CommonJS export names for ESM import in node:
1449
+ 0 && (module.exports = {
1450
+ GitReviewService
1451
+ });