@aviaratech/ai-delivery 0.3.37 → 0.3.39

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 (172) hide show
  1. package/README.md +14 -18
  2. package/dist/agent.d.ts +0 -4
  3. package/dist/agent.js +1 -8
  4. package/dist/agent.js.map +2 -2
  5. package/dist/cli.js +2 -72
  6. package/dist/cli.js.map +2 -2
  7. package/dist/cliResult.js +2 -14
  8. package/dist/cliResult.js.map +2 -2
  9. package/dist/cliResult.test.js +0 -74
  10. package/dist/cliResult.test.js.map +2 -2
  11. package/dist/config/deliveryConfig.d.ts +0 -6
  12. package/dist/config/deliveryConfig.js +2 -35
  13. package/dist/config/deliveryConfig.js.map +2 -2
  14. package/dist/config/deliveryConfig.test.js +1 -25
  15. package/dist/config/deliveryConfig.test.js.map +2 -2
  16. package/dist/contributorChecks.test.js +5 -3
  17. package/dist/contributorChecks.test.js.map +2 -2
  18. package/dist/delivery/common.d.ts +0 -14
  19. package/dist/delivery/common.js +1 -44
  20. package/dist/delivery/common.js.map +2 -2
  21. package/dist/directoryIndependent.test.js +2 -24
  22. package/dist/directoryIndependent.test.js.map +2 -2
  23. package/dist/dispatch.js +0 -46
  24. package/dist/dispatch.js.map +3 -3
  25. package/dist/fixtures/inertTarget.js +3 -5
  26. package/dist/fixtures/inertTarget.js.map +2 -2
  27. package/dist/fixtures/recordedGitHubFlows.d.ts +0 -72
  28. package/dist/fixtures/recordedGitHubFlows.js +1 -57
  29. package/dist/fixtures/recordedGitHubFlows.js.map +2 -2
  30. package/dist/git.d.ts +0 -6
  31. package/dist/git.js +0 -15
  32. package/dist/git.js.map +2 -2
  33. package/dist/github/client.js +0 -3
  34. package/dist/github/client.js.map +2 -2
  35. package/dist/github/commandIdentityPolicy.js +0 -1
  36. package/dist/github/commandIdentityPolicy.js.map +2 -2
  37. package/dist/github/issueHistory.d.ts +0 -6
  38. package/dist/github/issueHistory.js +0 -39
  39. package/dist/github/issueHistory.js.map +2 -2
  40. package/dist/github/nativeIssueMetadata.d.ts +0 -10
  41. package/dist/github/nativeIssueMetadata.js +1 -33
  42. package/dist/github/nativeIssueMetadata.js.map +3 -3
  43. package/dist/github/projectDelivery.d.ts +0 -34
  44. package/dist/github/projectDelivery.js +0 -211
  45. package/dist/github/projectDelivery.js.map +2 -2
  46. package/dist/github/repo.d.ts +0 -8
  47. package/dist/github/repo.js +0 -72
  48. package/dist/github/repo.js.map +2 -2
  49. package/dist/issue.js +22 -17
  50. package/dist/issue.js.map +2 -2
  51. package/dist/issue63Routes.test.js +1 -72
  52. package/dist/issue63Routes.test.js.map +2 -2
  53. package/dist/issueInfoReadback.test.js +59 -1
  54. package/dist/issueInfoReadback.test.js.map +2 -2
  55. package/dist/issueIntake.test.js +12 -0
  56. package/dist/issueIntake.test.js.map +2 -2
  57. package/dist/issueJournal.d.ts +0 -9
  58. package/dist/issueJournal.js +10 -76
  59. package/dist/issueJournal.js.map +2 -2
  60. package/dist/issueJournal.test.js +1 -108
  61. package/dist/issueJournal.test.js.map +2 -2
  62. package/dist/issueTracking.test.js +0 -48
  63. package/dist/issueTracking.test.js.map +2 -2
  64. package/dist/lifecycle.test.js +12 -48
  65. package/dist/lifecycle.test.js.map +2 -2
  66. package/dist/logger.d.ts +0 -4
  67. package/dist/logger.js +0 -31
  68. package/dist/logger.js.map +2 -2
  69. package/dist/mcp/tools.d.ts +2 -618
  70. package/dist/mcp/tools.js +8 -34
  71. package/dist/mcp/tools.js.map +2 -2
  72. package/dist/pluginAuthProbe.js +0 -3
  73. package/dist/pluginAuthProbe.js.map +2 -2
  74. package/dist/pluginDoctor.test.js +1 -1
  75. package/dist/pluginDoctor.test.js.map +2 -2
  76. package/dist/pluginInstaller.js +0 -3
  77. package/dist/pluginInstaller.js.map +2 -2
  78. package/dist/pluginInstaller.test.js +3 -19
  79. package/dist/pluginInstaller.test.js.map +2 -2
  80. package/dist/pluginPackaging.test.js +1 -118
  81. package/dist/pluginPackaging.test.js.map +2 -2
  82. package/dist/pr.d.ts +2 -73
  83. package/dist/pr.js +27 -220
  84. package/dist/pr.js.map +3 -3
  85. package/dist/pr.test.js +11 -304
  86. package/dist/pr.test.js.map +2 -2
  87. package/dist/prAssociation.test.js +112 -22
  88. package/dist/prAssociation.test.js.map +2 -2
  89. package/dist/prDispatch.test.js +4 -11
  90. package/dist/prDispatch.test.js.map +2 -2
  91. package/dist/releaseWorkflow.test.js +0 -1
  92. package/dist/releaseWorkflow.test.js.map +2 -2
  93. package/dist/review.d.ts +0 -82
  94. package/dist/review.js +3 -94
  95. package/dist/review.js.map +2 -2
  96. package/dist/review.test.js +2 -4
  97. package/dist/review.test.js.map +2 -2
  98. package/dist/services/agentReadinessService.d.ts +0 -1
  99. package/dist/services/agentReadinessService.js.map +2 -2
  100. package/dist/stdoutRegression.test.js +3 -22
  101. package/dist/stdoutRegression.test.js.map +2 -2
  102. package/dist/targetPolicyDiscovery.test.js +0 -86
  103. package/dist/targetPolicyDiscovery.test.js.map +2 -2
  104. package/dist/targetPolicyEntrypoints.test.js +1 -54
  105. package/dist/targetPolicyEntrypoints.test.js.map +2 -2
  106. package/dist/targetRepositoryExecution.test.js +1 -49
  107. package/dist/targetRepositoryExecution.test.js.map +2 -2
  108. package/dist/terminalMessages.d.ts +0 -10
  109. package/dist/terminalMessages.js +1 -31
  110. package/dist/terminalMessages.js.map +2 -2
  111. package/dist/toolOutput.js +0 -2
  112. package/dist/toolOutput.js.map +2 -2
  113. package/dist/toolOutput.test.js +15 -1
  114. package/dist/toolOutput.test.js.map +2 -2
  115. package/dist/verification.d.ts +1 -186
  116. package/dist/verification.js +29 -587
  117. package/dist/verification.js.map +3 -3
  118. package/dist/verificationGate.test.js +4 -90
  119. package/dist/verificationGate.test.js.map +2 -2
  120. package/dist/version.d.ts +0 -6
  121. package/dist/version.js +2 -39
  122. package/dist/version.js.map +2 -2
  123. package/package.json +1 -1
  124. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  125. package/plugins/ai-delivery/plugin.json +1 -1
  126. package/plugins/ai-delivery/runtime/dist/cli.js +118 -162
  127. package/plugins/ai-delivery/runtime/package.json +1 -1
  128. package/dist/boardReconcile.test.d.ts +0 -1
  129. package/dist/boardReconcile.test.js +0 -1746
  130. package/dist/boardReconcile.test.js.map +0 -7
  131. package/dist/delivery/delivery.test.d.ts +0 -1
  132. package/dist/delivery/delivery.test.js +0 -560
  133. package/dist/delivery/delivery.test.js.map +0 -7
  134. package/dist/delivery/evidence.d.ts +0 -92
  135. package/dist/delivery/evidence.js +0 -139
  136. package/dist/delivery/evidence.js.map +0 -7
  137. package/dist/delivery/legacy.d.ts +0 -8
  138. package/dist/delivery/legacy.js +0 -65
  139. package/dist/delivery/legacy.js.map +0 -7
  140. package/dist/delivery/policy.d.ts +0 -252
  141. package/dist/delivery/policy.js +0 -221
  142. package/dist/delivery/policy.js.map +0 -7
  143. package/dist/delivery/stage.d.ts +0 -179
  144. package/dist/delivery/stage.js +0 -242
  145. package/dist/delivery/stage.js.map +0 -7
  146. package/dist/deliveryBoard.d.ts +0 -74
  147. package/dist/deliveryBoard.js +0 -644
  148. package/dist/deliveryBoard.js.map +0 -7
  149. package/dist/deliveryBoard.test.d.ts +0 -1
  150. package/dist/deliveryBoard.test.js +0 -649
  151. package/dist/deliveryBoard.test.js.map +0 -7
  152. package/dist/deliveryHealth.test.d.ts +0 -1
  153. package/dist/deliveryHealth.test.js +0 -191
  154. package/dist/deliveryHealth.test.js.map +0 -7
  155. package/dist/fixtures/deliveryBoardReplay.d.ts +0 -56
  156. package/dist/fixtures/deliveryBoardReplay.js +0 -617
  157. package/dist/fixtures/deliveryBoardReplay.js.map +0 -7
  158. package/dist/genericCompatibility.test.d.ts +0 -1
  159. package/dist/genericCompatibility.test.js +0 -66
  160. package/dist/genericCompatibility.test.js.map +0 -7
  161. package/dist/services/boardReconcileService.d.ts +0 -1204
  162. package/dist/services/boardReconcileService.js +0 -1445
  163. package/dist/services/boardReconcileService.js.map +0 -7
  164. package/dist/services/deliveryHealthService.d.ts +0 -84
  165. package/dist/services/deliveryHealthService.js +0 -204
  166. package/dist/services/deliveryHealthService.js.map +0 -7
  167. package/dist/services/legacyIssueMigration.d.ts +0 -46
  168. package/dist/services/legacyIssueMigration.js +0 -299
  169. package/dist/services/legacyIssueMigration.js.map +0 -7
  170. package/dist/utils/filesystem.d.ts +0 -1
  171. package/dist/utils/filesystem.js +0 -5
  172. package/dist/utils/filesystem.js.map +0 -7
@@ -1,1445 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { isAbsolute, relative } from "node:path";
4
- import { z } from "zod";
5
- import { loadDeliveryConfig, NativeDeliveryConfigSchema } from "../config/deliveryConfig.js";
6
- import { digestValue } from "../delivery/common.js";
7
- import {
8
- CollectionLimitError,
9
- DeliveryError,
10
- getRateLimitDiagnostics,
11
- getMachineRequestDiagnostics
12
- } from "../errors.js";
13
- import { GIT_EXECUTABLE, gitEnvironment, inertGitArguments } from "../gitProcess.js";
14
- import { resolveRepoFromRemote } from "../github/repo.js";
15
- import { getNativeBlockerRelationships, hasNativeSubIssues } from "../github/relationships.js";
16
- import {
17
- getProjectDeliveryConfiguration,
18
- projectSettingsFromDeliveryConfig,
19
- readProjectDeliveryItems,
20
- ensureIssueProjectMembership,
21
- syncIssueProjectStatus
22
- } from "../github/projectDelivery.js";
23
- import {
24
- assertIssueStartCapacity,
25
- capacityNextPage,
26
- readIssueNativeFields,
27
- linkedIssueBranches,
28
- readyCheck
29
- } from "../issue.js";
30
- import {
31
- nativeIssueSettingsFromDeliveryConfig,
32
- parseConfiguredNativeIssueMetadata
33
- } from "../github/nativeIssueMetadata.js";
34
- import { parseIssueBody } from "../issueContract.js";
35
- import { readPackageArtifactIdentity } from "../version.js";
36
- const MAX_BYTES = 16 * 1024 * 1024;
37
- class RetainedOutputLimitError extends DeliveryError {
38
- }
39
- const ALGORITHM = "board-reconcile@1";
40
- const Id = z.string().min(1).max(512);
41
- const Sha256 = z.string().regex(/^sha256:[a-f0-9]{64}$/u);
42
- const Repo = z.string().trim().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u);
43
- const Status = z.enum(["Todo", "In Progress", "Blocked", "Done"]);
44
- const Count = z.number().int().nonnegative().safe();
45
- const CheckoutSchema = z.strictObject({
46
- repository: Repo,
47
- issueNumber: z.number().int().positive().safe(),
48
- path: z.string().max(4096).refine(isAbsolute)
49
- });
50
- const ActorSchema = z.strictObject({ actorLogin: Id, credentialIdentity: Id });
51
- const ArtifactSchema = z.strictObject({ packageVersion: Id, packageManifestDigest: Sha256, packageDistDigest: Sha256 });
52
- const StatusIds = z.strictObject({ Todo: Id, "In Progress": Id, Blocked: Id, Done: Id });
53
- const RoutingSchema = z.strictObject({
54
- repository: Repo,
55
- repositoryId: Id,
56
- projectId: Id,
57
- projectSource: z.enum(["explicit", "linked"]),
58
- statusFieldId: Id,
59
- statusOptionIds: StatusIds,
60
- pointsFieldId: Id,
61
- priorityFieldId: Id,
62
- native: NativeDeliveryConfigSchema
63
- });
64
- const BindingSchema = z.strictObject({
65
- repository: Repo,
66
- configDigest: Sha256,
67
- checkoutRootsDigest: Sha256,
68
- actor: ActorSchema.nullable(),
69
- routing: RoutingSchema
70
- });
71
- const GapSchema = z.strictObject({
72
- repository: Repo,
73
- projectId: Id.optional(),
74
- stage: z.string().min(1).max(80),
75
- reason: z.string().min(1).max(200),
76
- collection: z.string().max(100).optional(),
77
- pagesRequested: Count.optional(),
78
- rowsObserved: Count.optional(),
79
- limit: Count.optional()
80
- });
81
- const DiagnosticSchema = z.strictObject({
82
- code: z.enum(["missing-points", "parent-points", "duplicate-field-label", "unknown-metadata"]),
83
- field: Id,
84
- message: z.string().max(200),
85
- fixHint: z.string().max(200),
86
- fieldId: Id.nullable(),
87
- authoritativeValue: z.union([z.string().max(512), z.number().finite(), z.null()]),
88
- label: z.string().max(128).nullable(),
89
- labelValue: z.string().max(128).nullable(),
90
- mapping: z.enum(["exact", "conflicting", "unknown"]).nullable()
91
- });
92
- const BlockerSchema = z.strictObject({
93
- id: Id,
94
- repository: Repo,
95
- number: z.number().int().positive().safe(),
96
- state: z.enum(["OPEN", "CLOSED"])
97
- });
98
- const ObservationSchema = z.strictObject({
99
- path: z.string().max(4096),
100
- clone: z.string().max(4096),
101
- commonDirectory: z.string().max(4096),
102
- branch: Id,
103
- head: z.string().regex(/^[a-f0-9]{40}$/u),
104
- repository: Repo,
105
- issueNodeId: Id,
106
- linkedRefName: Id,
107
- linkedRefOid: z.string().regex(/^[a-f0-9]{40}$/u)
108
- });
109
- const ActivitySchema = z.strictObject({
110
- state: z.enum(["observed-checkout", "unknown"]),
111
- observation: ObservationSchema.nullable()
112
- });
113
- const MembershipSchema = z.strictObject({
114
- kind: z.enum(["absent", "present", "not-required", "archived-preserved", "duplicate", "unknown"]),
115
- itemId: Id.nullable(),
116
- itemIds: z.array(Id)
117
- });
118
- const NativeSchema = z.strictObject({
119
- state: z.enum(["open", "closed"]),
120
- bodyDigest: Sha256,
121
- canonical: z.boolean(),
122
- draft: z.boolean().nullable(),
123
- deferred: z.boolean().nullable(),
124
- blockers: z.array(BlockerSchema).nullable(),
125
- hasChildren: z.boolean().nullable(),
126
- points: z.number().finite().nullable(),
127
- priority: z.string().max(512).nullable()
128
- });
129
- const StatusObservationSchema = z.strictObject({
130
- current: Status.nullable(),
131
- kind: z.enum(["verified", "unset", "unreadable"]),
132
- name: Id.nullable(),
133
- optionId: Id.nullable()
134
- });
135
- const IssueSchema = z.strictObject({
136
- repository: Repo,
137
- issueNodeId: Id,
138
- issueNumber: z.number().int().positive().safe(),
139
- projectId: Id,
140
- native: NativeSchema,
141
- membership: MembershipSchema,
142
- status: StatusObservationSchema.extend({
143
- target: Status.nullable(),
144
- rule: z.enum(["closed", "blocker", "parked", "active", "unknown", "preserved"])
145
- }),
146
- activity: ActivitySchema,
147
- metadata: z.array(DiagnosticSchema),
148
- gaps: z.array(GapSchema)
149
- });
150
- const OperationSchema = z.strictObject({
151
- operationId: Sha256,
152
- repository: Repo,
153
- issueNodeId: Id,
154
- issueNumber: z.number().int().positive().safe(),
155
- projectId: Id,
156
- kind: z.enum(["add-membership", "set-status"]),
157
- prerequisiteDigest: Sha256,
158
- expected: z.strictObject({
159
- membership: z.enum(["absent", "present"]),
160
- itemId: Id.nullable(),
161
- status: Status.nullable()
162
- }),
163
- target: Status.nullable(),
164
- fieldId: Id.nullable(),
165
- optionId: Id.nullable()
166
- });
167
- const BoundsSchema = z.strictObject({
168
- repositories: z.literal(10),
169
- issuesPerRepository: z.literal(500),
170
- pagesPerCollection: z.literal(20),
171
- retainedBytes: z.literal(MAX_BYTES)
172
- });
173
- const BoardReconcilePlanSchema = z.strictObject({
174
- schemaVersion: z.literal("ai-delivery.board-reconcile-plan@1"),
175
- planId: Sha256,
176
- algorithm: z.literal(ALGORITHM),
177
- packageIdentity: ArtifactSchema.nullable(),
178
- collectionStartedAt: z.iso.datetime(),
179
- collectionCompletedAt: z.iso.datetime(),
180
- scope: z.array(Repo).min(1).max(10),
181
- checkouts: z.array(CheckoutSchema),
182
- bindings: z.array(BindingSchema),
183
- bounds: BoundsSchema,
184
- scopeComplete: z.boolean(),
185
- issues: z.array(IssueSchema).max(5e3),
186
- operations: z.array(OperationSchema).max(1e4),
187
- gaps: z.array(GapSchema),
188
- summary: z.strictObject({ proposed: Count, noops: Count, refused: Count, unresolved: Count })
189
- });
190
- const Outcome = z.enum(["applied", "satisfied", "failed", "drifted", "refused", "unknown"]);
191
- const ItemEvidenceSchema = z.strictObject({ itemId: Id, status: StatusObservationSchema, archived: z.boolean() });
192
- const AttemptEvidenceSchema = z.strictObject({
193
- outcome: Outcome,
194
- attempted: z.boolean(),
195
- before: ItemEvidenceSchema.nullable(),
196
- readback: ItemEvidenceSchema.nullable()
197
- });
198
- const ResultOperationSchema = OperationSchema.extend({
199
- outcome: Outcome,
200
- attempted: z.boolean(),
201
- before: ItemEvidenceSchema.nullable(),
202
- readback: ItemEvidenceSchema.nullable(),
203
- priorEvidence: z.array(AttemptEvidenceSchema),
204
- knownItemIds: z.array(Id)
205
- });
206
- const BoardReconcileResultSchema = z.strictObject({
207
- schemaVersion: z.literal("ai-delivery.board-reconcile-result@1"),
208
- planId: Sha256,
209
- scope: z.array(Repo).min(1).max(10),
210
- scopeComplete: z.boolean(),
211
- observedBindings: z.array(BindingSchema),
212
- operations: z.array(ResultOperationSchema).max(1e4),
213
- issues: z.array(IssueSchema).max(5e3),
214
- gaps: z.array(GapSchema),
215
- summary: z.strictObject({
216
- applied: Count,
217
- satisfied: Count,
218
- failed: Count,
219
- drifted: Count,
220
- refused: Count,
221
- unknown: Count,
222
- unresolved: Count
223
- })
224
- });
225
- function bounded(value) {
226
- let serialized;
227
- try {
228
- serialized = JSON.stringify(value);
229
- } catch {
230
- throw new DeliveryError("Reconciliation evidence must be serializable JSON.");
231
- }
232
- if (serialized === void 0 || Buffer.byteLength(serialized, "utf8") > MAX_BYTES)
233
- throw new RetainedOutputLimitError("Reconciliation retained input/output exceeds 16 MiB UTF-8 or is not JSON.");
234
- }
235
- function normalizedScope(scope) {
236
- return scope.map((r) => r.trim().toLowerCase()).sort();
237
- }
238
- function sameScope(a, b) {
239
- return digestValue(normalizedScope(a)) === digestValue(normalizedScope(b));
240
- }
241
- function operationId(operation) {
242
- return digestValue(operation);
243
- }
244
- function planId(plan) {
245
- const { planId: _id, collectionStartedAt: _start, collectionCompletedAt: _end, ...semantic } = plan;
246
- return digestValue(semantic);
247
- }
248
- function validatePlan(plan) {
249
- bounded(plan);
250
- if (plan.planId !== planId(plan) || !plan.scopeComplete || !plan.packageIdentity)
251
- throw new DeliveryError("Apply requires a complete original plan with valid integrity and package identity.");
252
- const ids = /* @__PURE__ */ new Set();
253
- for (const operation of plan.operations) {
254
- const { operationId: id, ...intent } = operation;
255
- if (id !== operationId(intent) || ids.has(id)) throw new DeliveryError("Plan operation integrity is invalid.");
256
- ids.add(id);
257
- }
258
- }
259
- function validatePrior(plan, prior) {
260
- bounded(prior);
261
- if (prior.planId !== plan.planId || !sameScope(prior.scope, plan.scope) || prior.operations.length !== plan.operations.length)
262
- throw new DeliveryError("Prior result does not bind to this exact plan and operation set.");
263
- const byId = new Map(prior.operations.map((o) => [o.operationId, o]));
264
- if (byId.size !== prior.operations.length) throw new DeliveryError("Prior result repeats operation identities.");
265
- for (const operation of plan.operations) {
266
- const found = byId.get(operation.operationId);
267
- if (!found) throw new DeliveryError("Prior result omitted a plan operation.");
268
- const {
269
- outcome: _outcome,
270
- attempted: _attempted,
271
- before: _before,
272
- readback: _readback,
273
- priorEvidence: _prior,
274
- knownItemIds: _known,
275
- ...intent
276
- } = found;
277
- if (digestValue(intent) !== digestValue(operation))
278
- throw new DeliveryError("Prior result changes original operation intent.");
279
- }
280
- }
281
- const BoardReconcileInput = z.strictObject({
282
- repositories: z.array(Repo).min(1).max(10),
283
- repo: Repo.optional(),
284
- mode: z.enum(["dry-run", "apply"]).default("dry-run"),
285
- checkouts: z.array(CheckoutSchema).optional(),
286
- plan: BoardReconcilePlanSchema.optional(),
287
- priorResult: BoardReconcileResultSchema.optional()
288
- }).superRefine((value, context) => {
289
- const refuse = (message) => context.addIssue({ code: "custom", message });
290
- try {
291
- bounded(value);
292
- } catch {
293
- refuse("Reconciliation input exceeds its retained JSON bound.");
294
- }
295
- const scope = normalizedScope(value.repositories);
296
- if (new Set(scope).size !== scope.length) refuse("Repositories must be unique after case folding.");
297
- if (value.repo !== void 0 && (scope.length !== 1 || scope[0] !== value.repo.toLowerCase()))
298
- refuse("Singular and plural repository selectors must agree.");
299
- if (value.mode === "dry-run") {
300
- if (value.plan !== void 0 || value.priorResult !== void 0) refuse("Dry-run forbids plan/priorResult.");
301
- } else {
302
- if (value.plan === void 0 || value.checkouts !== void 0)
303
- refuse("Apply requires a plan and forbids extra checkout selectors.");
304
- else
305
- try {
306
- validatePlan(value.plan);
307
- if (!sameScope(value.repositories, value.plan.scope))
308
- throw new DeliveryError("Apply repository scope changed.");
309
- if (value.priorResult !== void 0) validatePrior(value.plan, value.priorResult);
310
- } catch {
311
- refuse("Apply plan/prior-result integrity or scope is invalid.");
312
- }
313
- }
314
- const subjects = /* @__PURE__ */ new Set(), paths = /* @__PURE__ */ new Set();
315
- for (const selected of value.checkouts ?? []) {
316
- const key = `${selected.repository.toLowerCase()}:${String(selected.issueNumber)}`;
317
- if (!scope.includes(selected.repository.toLowerCase()) || subjects.has(key) || paths.has(selected.path))
318
- refuse("Checkout selectors must be in scope and unambiguous.");
319
- subjects.add(key);
320
- paths.add(selected.path);
321
- }
322
- });
323
- function parseBoardReconcileRequest(raw) {
324
- bounded(raw);
325
- const parsed = BoardReconcileInput.parse(raw);
326
- const { mode, plan, priorResult, checkouts, ...common } = parsed;
327
- if (mode === "apply") {
328
- if (!plan) throw new DeliveryError("Apply requires its validated original plan.");
329
- return { ...common, mode, plan, ...priorResult === void 0 ? {} : { priorResult } };
330
- }
331
- return { ...common, mode, ...checkouts === void 0 ? {} : { checkouts } };
332
- }
333
- function globalFailureReason(error) {
334
- if (getRateLimitDiagnostics(error, true) !== void 0) return "rate-limit";
335
- if (getMachineRequestDiagnostics(error)?.status === 401 || error instanceof Error && Object.getOwnPropertyDescriptor(error, "status")?.value === 401)
336
- return "authentication";
337
- return null;
338
- }
339
- function boardReconcileGap(repository, stage, error, projectId) {
340
- return {
341
- repository,
342
- stage,
343
- reason: error instanceof CollectionLimitError ? "collection-limit" : globalFailureReason(error) ?? "evidence-unavailable",
344
- ...projectId === void 0 ? {} : { projectId },
345
- ...error instanceof CollectionLimitError ? {
346
- collection: error.collection,
347
- pagesRequested: error.pagesRequested,
348
- rowsObserved: error.rowsObserved,
349
- limit: error.limit
350
- } : {}
351
- };
352
- }
353
- function emptyPlan(request) {
354
- const now = (/* @__PURE__ */ new Date()).toISOString();
355
- return {
356
- schemaVersion: "ai-delivery.board-reconcile-plan@1",
357
- planId: `sha256:${"0".repeat(64)}`,
358
- algorithm: ALGORITHM,
359
- packageIdentity: null,
360
- collectionStartedAt: now,
361
- collectionCompletedAt: now,
362
- scope: [...request.repositories].sort(),
363
- checkouts: [...request.checkouts ?? []].sort(
364
- (a, b) => `${a.repository}:${a.issueNumber}`.localeCompare(`${b.repository}:${b.issueNumber}`)
365
- ),
366
- bindings: [],
367
- bounds: { repositories: 10, issuesPerRepository: 500, pagesPerCollection: 20, retainedBytes: MAX_BYTES },
368
- scopeComplete: true,
369
- issues: [],
370
- operations: [],
371
- gaps: [],
372
- summary: { proposed: 0, noops: 0, refused: 0, unresolved: 0 }
373
- };
374
- }
375
- function finishPlan(plan) {
376
- plan.issues.sort((a, b) => a.repository.localeCompare(b.repository) || a.issueNodeId.localeCompare(b.issueNodeId));
377
- plan.operations.sort(
378
- (a, b) => a.repository.localeCompare(b.repository) || a.issueNodeId.localeCompare(b.issueNodeId) || (a.kind === b.kind ? 0 : a.kind === "add-membership" ? -1 : 1)
379
- );
380
- plan.bindings.sort((a, b) => a.repository.localeCompare(b.repository));
381
- plan.collectionCompletedAt = (/* @__PURE__ */ new Date()).toISOString();
382
- const refusedStatus = new Set(
383
- plan.issues.filter((issue) => issue.status.target !== null && issue.status.kind === "unreadable").map((issue) => issue.issueNodeId)
384
- );
385
- plan.summary = {
386
- proposed: plan.operations.length,
387
- noops: plan.issues.filter(
388
- (i) => !refusedStatus.has(i.issueNodeId) && !plan.operations.some((o) => o.issueNodeId === i.issueNodeId)
389
- ).length,
390
- refused: (plan.scopeComplete ? 0 : plan.operations.length) + refusedStatus.size,
391
- unresolved: plan.gaps.length + plan.issues.reduce((n, i) => n + i.gaps.length, 0)
392
- };
393
- plan.planId = planId(plan);
394
- bounded(plan);
395
- return BoardReconcilePlanSchema.parse(plan);
396
- }
397
- function incompleteBoardReconcile(request, failure) {
398
- if (request.mode === "dry-run") {
399
- const plan = emptyPlan(request);
400
- plan.scopeComplete = false;
401
- plan.gaps.push(failure);
402
- return finishPlan(plan);
403
- }
404
- const prior = new Map(request.priorResult?.operations.map((o) => [o.operationId, o]));
405
- const operations = request.plan.operations.map((operation) => {
406
- const old = prior.get(operation.operationId);
407
- const outcome = old?.outcome === "unknown" ? "unknown" : "refused";
408
- return {
409
- ...operation,
410
- outcome,
411
- attempted: false,
412
- before: null,
413
- readback: null,
414
- knownItemIds: [
415
- .../* @__PURE__ */ new Set([
416
- ...old?.knownItemIds ?? [],
417
- ...operation.expected.itemId === null ? [] : [operation.expected.itemId],
418
- ...old?.before ? [old.before.itemId] : [],
419
- ...old?.readback ? [old.readback.itemId] : []
420
- ])
421
- ].sort(),
422
- priorEvidence: old ? [
423
- ...old.priorEvidence,
424
- { outcome: old.outcome, attempted: old.attempted, before: old.before, readback: old.readback }
425
- ] : []
426
- };
427
- });
428
- const result = {
429
- schemaVersion: "ai-delivery.board-reconcile-result@1",
430
- planId: request.plan.planId,
431
- scope: request.plan.scope,
432
- scopeComplete: false,
433
- observedBindings: [],
434
- operations,
435
- issues: [],
436
- gaps: [failure],
437
- summary: {
438
- applied: 0,
439
- satisfied: 0,
440
- failed: 0,
441
- drifted: 0,
442
- refused: operations.filter((o) => o.outcome === "refused").length,
443
- unknown: operations.filter((o) => o.outcome === "unknown").length,
444
- unresolved: 1
445
- }
446
- };
447
- bounded(result);
448
- return BoardReconcileResultSchema.parse(result);
449
- }
450
- const NativeIssueSchema = z.object({
451
- number: z.number().int().positive().safe(),
452
- node_id: Id,
453
- state: z.enum(["open", "closed"]),
454
- title: z.string().max(512),
455
- body: z.string().nullable().optional(),
456
- html_url: z.string().url(),
457
- labels: z.array(z.union([z.string().max(128), z.object({ name: z.string().max(128) })])).default([])
458
- });
459
- const InventoryIdentitySchema = NativeIssueSchema.pick({ number: true, node_id: true });
460
- const PullRequestInventorySchema = InventoryIdentitySchema.extend({
461
- html_url: z.string().url(),
462
- pull_request: z.object({ url: z.string().url() })
463
- });
464
- function nativeIssue(value, repository) {
465
- const issue = NativeIssueSchema.parse(value);
466
- const url = new URL(issue.html_url);
467
- if (url.protocol !== "https:" || url.hostname !== "github.com" || url.search || url.hash || url.pathname.toLowerCase() !== `/${repository}/issues/${String(issue.number)}`.toLowerCase())
468
- throw new DeliveryError("Native issue identity does not match the selected repository.");
469
- return issue;
470
- }
471
- async function inventory(context, rows, signal) {
472
- const numbers = /* @__PURE__ */ new Set();
473
- const nodeIds = /* @__PURE__ */ new Set();
474
- for (let page = 1; ; page++) {
475
- signal?.throwIfAborted();
476
- if (page > 20)
477
- throw new CollectionLimitError({
478
- collection: "repository-issues",
479
- pagesRequested: page - 1,
480
- rowsObserved: rows.size,
481
- limit: 20
482
- });
483
- const response = await context.clients.rest.issues.listForRepo({
484
- ...context.repo,
485
- state: "all",
486
- page,
487
- per_page: 100,
488
- sort: "created",
489
- direction: "asc"
490
- });
491
- if (!Array.isArray(response.data) || response.data.length > 100)
492
- throw new DeliveryError("Native issue inventory is incomplete.");
493
- for (const value of response.data) {
494
- const identity = InventoryIdentitySchema.parse(value);
495
- if (numbers.has(identity.number) || nodeIds.has(identity.node_id))
496
- throw new DeliveryError("Issue inventory repeats a native issue or pull-request identity.");
497
- numbers.add(identity.number);
498
- nodeIds.add(identity.node_id);
499
- if ("pull_request" in value) {
500
- const pr = PullRequestInventorySchema.parse(value), api = new URL(pr.pull_request.url), html = new URL(pr.html_url);
501
- if (api.protocol !== "https:" || api.hostname !== "api.github.com" || api.search || api.hash || api.pathname.toLowerCase() !== `/repos/${context.config.repository}/pulls/${String(pr.number)}`.toLowerCase() || html.protocol !== "https:" || html.hostname !== "github.com" || html.search || html.hash || html.pathname.toLowerCase() !== `/${context.config.repository}/pull/${String(pr.number)}`.toLowerCase())
502
- throw new DeliveryError("Issue inventory has an unreadable or foreign pull-request identity.");
503
- continue;
504
- }
505
- const issue = nativeIssue(value, context.config.repository);
506
- if (rows.size >= 500)
507
- throw new CollectionLimitError({
508
- collection: "repository-issues",
509
- pagesRequested: page,
510
- rowsObserved: rows.size,
511
- limit: 500
512
- });
513
- rows.set(issue.node_id, issue);
514
- }
515
- if (capacityNextPage(response, page, 100) === null) return;
516
- }
517
- }
518
- function projectIdentity(configuration) {
519
- const { writable: _writable, ...identity } = configuration;
520
- return digestValue(identity);
521
- }
522
- function localGit(path, args, signal) {
523
- signal?.throwIfAborted();
524
- const result = spawnSync(GIT_EXECUTABLE, [...inertGitArguments(path), ...args], {
525
- cwd: path,
526
- env: gitEnvironment(),
527
- encoding: "utf8",
528
- maxBuffer: 1024 * 1024,
529
- timeout: 1e4,
530
- stdio: ["ignore", "pipe", "pipe"]
531
- });
532
- signal?.throwIfAborted();
533
- if (result.error || result.status !== 0) throw new DeliveryError("Physical Git observation is unavailable.");
534
- return result.stdout.replace(/\n$/u, "");
535
- }
536
- function inside(root, path) {
537
- const part = relative(root, path);
538
- return part === "" || !isAbsolute(part) && part !== ".." && !part.startsWith("../");
539
- }
540
- async function activity(context, issue, selected, options) {
541
- if (!selected) return { state: "unknown", observation: null };
542
- const path = realpathSync(selected.path);
543
- const roots = options.checkoutRoots.map((root) => realpathSync(root));
544
- if (!roots.some((root) => inside(root, path)) || realpathSync(localGit(path, ["rev-parse", "--show-toplevel"], options.signal)) !== path || localGit(path, ["rev-parse", "--is-bare-repository"], options.signal) !== "false")
545
- throw new DeliveryError("Selected checkout does not match a configured physical root.");
546
- const commonDirectory = realpathSync(
547
- localGit(path, ["rev-parse", "--path-format=absolute", "--git-common-dir"], options.signal)
548
- );
549
- const branch = localGit(path, ["symbolic-ref", "--quiet", "--short", "HEAD"], options.signal);
550
- const head = localGit(path, ["rev-parse", "HEAD"], options.signal);
551
- const entries = [];
552
- for (const field of localGit(path, ["worktree", "list", "--porcelain", "-z"], options.signal).split("\0")) {
553
- if (field.startsWith("worktree ")) entries.push({ worktree: field.slice(9) });
554
- else if (field) {
555
- const split = field.indexOf(" ");
556
- const entry2 = entries.at(-1);
557
- if (entry2) entry2[split < 0 ? field : field.slice(0, split)] = split < 0 ? "" : field.slice(split + 1);
558
- }
559
- }
560
- const matches = entries.filter((entry2) => {
561
- try {
562
- return entry2.worktree !== void 0 && realpathSync(entry2.worktree) === path;
563
- } catch {
564
- return false;
565
- }
566
- });
567
- const entry = matches[0], primary = entries[0]?.worktree;
568
- if (matches.length !== 1 || !entry || "locked" in entry || "prunable" in entry || entry.branch !== `refs/heads/${branch}` || entry.HEAD !== head || !primary)
569
- throw new DeliveryError("Selected checkout is detached, locked, prunable or ambiguous.");
570
- const clone = realpathSync(primary);
571
- if (!roots.some((root) => inside(root, clone)) || localGit(clone, ["rev-parse", "--is-bare-repository"], options.signal) !== "false" || realpathSync(localGit(clone, ["rev-parse", "--path-format=absolute", "--git-common-dir"], options.signal)) !== commonDirectory)
572
- throw new DeliveryError("Selected checkout has no matching configured clone/common directory.");
573
- for (const root of [clone, path]) {
574
- const remote = resolveRepoFromRemote(root);
575
- if (`${remote.owner}/${remote.repo}`.toLowerCase() !== context.config.repository.toLowerCase())
576
- throw new DeliveryError("Selected checkout repository changed.");
577
- }
578
- const refs = (await linkedIssueBranches(context, issue.number)).filter(
579
- (ref) => ref.name === branch && ref.repository.toLowerCase() === context.config.repository.toLowerCase()
580
- );
581
- if (refs.length !== 1) throw new DeliveryError("No unambiguous live native branch link proves this checkout.");
582
- const observation = ObservationSchema.parse({
583
- path,
584
- clone,
585
- commonDirectory,
586
- branch,
587
- head,
588
- repository: context.config.repository,
589
- issueNodeId: issue.node_id,
590
- linkedRefName: refs[0].name,
591
- linkedRefOid: refs[0].sha
592
- });
593
- return { state: "observed-checkout", observation };
594
- }
595
- function diagnostic(code, field, fieldId, value, fixHint) {
596
- return {
597
- code,
598
- field,
599
- fieldId,
600
- authoritativeValue: value,
601
- fixHint,
602
- message: fixHint,
603
- label: null,
604
- labelValue: null,
605
- mapping: null
606
- };
607
- }
608
- function metadata(context, issue, configuration, native, knownNativeFields, currentStatus, knownStatus) {
609
- const reports = [];
610
- const points = context.config.native.points;
611
- if (native.hasChildren === null || !knownNativeFields)
612
- reports.push(
613
- diagnostic(
614
- "unknown-metadata",
615
- points.name,
616
- points.databaseId,
617
- null,
618
- "Resolve incomplete native child/field evidence before migration."
619
- )
620
- );
621
- else if (native.hasChildren && native.points !== null)
622
- reports.push(
623
- diagnostic(
624
- "parent-points",
625
- points.name,
626
- points.databaseId,
627
- native.points,
628
- "Use a separately authorized explicit native Points clear for this planning parent."
629
- )
630
- );
631
- else if (!native.hasChildren && native.state === "open" && native.points === null)
632
- reports.push(
633
- diagnostic(
634
- "missing-points",
635
- points.name,
636
- points.databaseId,
637
- null,
638
- "Explicitly select supported native Points before execution."
639
- )
640
- );
641
- const normalize = (name) => name.trim().toLowerCase().replace(/\s+/gu, " ");
642
- for (const raw of issue.labels) {
643
- const label = typeof raw === "string" ? raw : raw.name;
644
- const separator = label.indexOf(":");
645
- if (separator < 0) continue;
646
- const prefix = normalize(label.slice(0, separator)), labelValue = label.slice(separator + 1).trim();
647
- const field = prefix === "points" || prefix === normalize(points.name) ? {
648
- name: points.name,
649
- id: points.databaseId,
650
- value: native.points,
651
- known: knownNativeFields,
652
- status: false,
653
- values: points.values
654
- } : prefix === "priority" || prefix === normalize(context.config.native.priority.name) ? {
655
- name: context.config.native.priority.name,
656
- id: context.config.native.priority.databaseId,
657
- value: native.priority,
658
- known: knownNativeFields,
659
- status: false,
660
- values: context.config.native.priority.values
661
- } : prefix === "status" || prefix === normalize(configuration.settings.statusField) ? {
662
- name: configuration.settings.statusField,
663
- id: configuration.statusFieldId,
664
- value: currentStatus === null ? null : configuration.settings.statuses[currentStatus],
665
- known: knownStatus,
666
- status: true,
667
- values: Object.values(configuration.settings.statuses)
668
- } : null;
669
- if (!field) continue;
670
- const target = field.status ? Object.entries(configuration.settings.statuses).find(
671
- ([canonical, configured]) => [normalize(canonical), normalize(canonical.replace(/ /gu, "-")), normalize(configured)].includes(
672
- normalize(labelValue)
673
- )
674
- )?.[1] ?? null : field.values.find((value) => normalize(value) === normalize(labelValue)) ?? null;
675
- reports.push({
676
- ...diagnostic(
677
- "duplicate-field-label",
678
- field.name,
679
- field.id,
680
- field.value,
681
- "Resolve the native/Project value explicitly before removing this duplicate label through its existing owner."
682
- ),
683
- label,
684
- labelValue,
685
- mapping: field.known && target !== null ? normalize(String(field.value)) === normalize(target) ? "exact" : "conflicting" : "unknown"
686
- });
687
- }
688
- return reports;
689
- }
690
- function prerequisites(issue, kind) {
691
- if (kind === "add-membership") return { state: issue.native.state };
692
- switch (issue.status.rule) {
693
- case "closed":
694
- return { state: issue.native.state };
695
- case "blocker":
696
- return { state: issue.native.state, openBlockers: issue.native.blockers?.filter((b) => b.state === "OPEN") };
697
- case "parked":
698
- return {
699
- state: issue.native.state,
700
- bodyDigest: issue.native.bodyDigest,
701
- blockers: issue.native.blockers,
702
- draft: issue.native.draft,
703
- deferred: issue.native.deferred
704
- };
705
- case "active": {
706
- const { priority: _priority, ...native } = issue.native;
707
- return { native, activity: issue.activity };
708
- }
709
- default:
710
- throw new DeliveryError("No proven Status rule authorizes an operation.");
711
- }
712
- }
713
- function propose(issue, configuration) {
714
- const operations = [];
715
- const add = (kind, target) => {
716
- const intent = {
717
- repository: issue.repository,
718
- issueNodeId: issue.issueNodeId,
719
- issueNumber: issue.issueNumber,
720
- projectId: issue.projectId,
721
- kind,
722
- prerequisiteDigest: digestValue(prerequisites(issue, kind)),
723
- expected: {
724
- membership: issue.membership.kind === "absent" ? "absent" : "present",
725
- itemId: issue.membership.itemId,
726
- status: kind === "set-status" ? issue.status.current : null
727
- },
728
- target,
729
- fieldId: target === null ? null : configuration.statusFieldId,
730
- optionId: target === null ? null : configuration.statusOptionIds[target]
731
- };
732
- operations.push({ ...intent, operationId: operationId(intent) });
733
- };
734
- if (issue.membership.kind === "absent" && issue.native.state === "open") add("add-membership", null);
735
- if (["present", "absent"].includes(issue.membership.kind) && issue.status.kind !== "unreadable" && issue.status.target !== null && issue.status.target !== issue.status.current)
736
- add("set-status", issue.status.target);
737
- return operations;
738
- }
739
- function readState() {
740
- return {
741
- scopeComplete: true,
742
- globalReadFailure: void 0,
743
- failedFieldCatalogs: /* @__PURE__ */ new Map(),
744
- stoppedProjects: /* @__PURE__ */ new Set()
745
- };
746
- }
747
- async function observeIssue(context, listed, configuration, items, checkouts, options, state, intent) {
748
- const repository = context.config.repository;
749
- const { failedFieldCatalogs, stoppedProjects } = state;
750
- options.signal?.throwIfAborted();
751
- const gaps = [];
752
- const missing = (stage, error) => {
753
- gaps.push(boardReconcileGap(repository, stage, error, configuration?.projectId));
754
- if (globalFailureReason(error) !== null) {
755
- state.scopeComplete = false;
756
- state.globalReadFailure = error;
757
- }
758
- if (error instanceof CollectionLimitError) {
759
- state.scopeComplete = false;
760
- if (configuration) stoppedProjects.add(configuration.projectId);
761
- if (error.collection === "native-field-catalog")
762
- failedFieldCatalogs.set(context.config.native.organization.toLowerCase(), error);
763
- }
764
- };
765
- let native = listed;
766
- try {
767
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
768
- native = nativeIssue(
769
- (await context.clients.rest.issues.get({ ...context.repo, issue_number: listed.number })).data,
770
- repository
771
- );
772
- if (native.number !== listed.number || native.node_id !== listed.node_id)
773
- throw new DeliveryError("Native issue identity changed.");
774
- } catch (error) {
775
- missing("native-identity", error);
776
- state.scopeComplete = false;
777
- }
778
- options.signal?.throwIfAborted();
779
- let canonical = false, draft = null, deferred = null;
780
- if (intent === void 0 || intent.kind === "set-status" && intent.target !== "Done" && intent.target !== "Blocked") {
781
- try {
782
- const body = parseIssueBody(native.body ?? "", { title: native.title });
783
- if (!body.legacy) {
784
- canonical = true;
785
- draft = body.issue.draft ?? false;
786
- deferred = body.issue.deferral != null;
787
- } else missing("canonical-body");
788
- } catch (error) {
789
- missing("canonical-body", error);
790
- }
791
- }
792
- let blockers = null;
793
- if (intent === void 0 || intent.kind === "set-status" && intent.target !== "Done" && native.state === "open") {
794
- try {
795
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
796
- const relationships = await getNativeBlockerRelationships({
797
- graphql: context.clients.graphql,
798
- repo: context.repo,
799
- issueNumber: native.number,
800
- issueNodeId: native.node_id,
801
- requireRepositoryIdentity: true,
802
- maxPages: 20
803
- });
804
- blockers = relationships.blockers.map((b) => BlockerSchema.parse({ id: b.id, repository: b.repository, number: b.number, state: b.state })).sort((a, b) => a.id.localeCompare(b.id));
805
- } catch (error) {
806
- missing("native-blockers", error);
807
- }
808
- options.signal?.throwIfAborted();
809
- }
810
- let tracking = null;
811
- if (intent === void 0 || intent.kind === "set-status" && intent.target === "In Progress" && native.state === "open") {
812
- try {
813
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
814
- const failed = failedFieldCatalogs.get(context.config.native.organization.toLowerCase());
815
- if (failed) throw failed;
816
- const fields = await readIssueNativeFields(context, native.number);
817
- tracking = parseConfiguredNativeIssueMetadata(
818
- fields.values,
819
- nativeIssueSettingsFromDeliveryConfig(context.config)
820
- );
821
- } catch (error) {
822
- missing("native-metadata", error);
823
- }
824
- options.signal?.throwIfAborted();
825
- }
826
- let hasChildren = null;
827
- if (intent === void 0 || intent.kind === "set-status" && intent.target === "In Progress" && native.state === "open") {
828
- try {
829
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
830
- hasChildren = await hasNativeSubIssues({
831
- issueNumber: native.number,
832
- repo: context.repo,
833
- rest: context.clients.rest,
834
- requireComplete: true
835
- });
836
- } catch (error) {
837
- missing("native-children", error);
838
- }
839
- }
840
- let observed = { state: "unknown", observation: null };
841
- if (intent === void 0 || intent.kind === "set-status" && intent.target === "In Progress" && native.state === "open") {
842
- try {
843
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
844
- observed = await activity(
845
- context,
846
- native,
847
- checkouts.find((checkout) => checkout.repository === repository && checkout.issueNumber === native.number),
848
- options
849
- );
850
- } catch (error) {
851
- missing("checkout", error);
852
- }
853
- }
854
- const matches = items?.filter((item) => item.contentKind === "issue" && item.contentId === native.node_id) ?? [];
855
- if (matches.some(
856
- (item) => item.repository?.toLowerCase() !== repository.toLowerCase() || item.issueNumber !== native.number
857
- )) {
858
- missing("membership-identity");
859
- state.scopeComplete = false;
860
- }
861
- const member = matches.length === 1 ? matches[0] : null;
862
- const membership = {
863
- kind: items === null ? "unknown" : matches.length > 1 ? "duplicate" : member?.archived ? "archived-preserved" : member ? "present" : native.state === "closed" ? "not-required" : "absent",
864
- itemId: member?.id ?? null,
865
- itemIds: matches.map((item) => item.id).sort()
866
- };
867
- if (membership.kind === "unknown" || membership.kind === "duplicate") {
868
- missing("membership");
869
- state.scopeComplete = false;
870
- }
871
- const record = {
872
- repository,
873
- issueNodeId: native.node_id,
874
- issueNumber: native.number,
875
- projectId: configuration?.projectId ?? context.configuration?.routing.projectId ?? "unresolved-project",
876
- native: {
877
- state: native.state,
878
- bodyDigest: digestValue(native.body ?? ""),
879
- canonical,
880
- draft,
881
- deferred,
882
- blockers,
883
- hasChildren,
884
- points: tracking?.points ?? null,
885
- priority: tracking?.priority ?? null
886
- },
887
- membership,
888
- status: {
889
- current: member?.status ?? null,
890
- kind: member?.statusRead ?? (membership.kind === "absent" || membership.kind === "not-required" ? "unset" : "unreadable"),
891
- name: member?.statusName ?? null,
892
- optionId: member?.statusOptionId ?? null,
893
- target: null,
894
- rule: "unknown"
895
- },
896
- activity: observed,
897
- metadata: [],
898
- gaps
899
- };
900
- if (member && !member.archived && record.status.kind === "unreadable") missing("project-status");
901
- if (!["present", "absent"].includes(membership.kind)) record.status.rule = "preserved";
902
- else if (native.state === "closed") record.status = { ...record.status, target: "Done", rule: "closed" };
903
- else if (blockers?.some((blocker) => blocker.state === "OPEN"))
904
- record.status = { ...record.status, target: "Blocked", rule: "blocker" };
905
- else if (blockers !== null && canonical && (draft === true || deferred === true))
906
- record.status = { ...record.status, target: "Todo", rule: "parked" };
907
- else if (blockers !== null && canonical && draft === false && deferred === false && observed.state === "observed-checkout" && tracking !== null && tracking.points !== void 0 && hasChildren === false && configuration !== null && !stoppedProjects.has(configuration.projectId)) {
908
- try {
909
- const ready = await readyCheck(context, native.number, ({ info, issueNodeId, issueNumber, trackingParent }) => {
910
- if (issueNodeId !== native.node_id || issueNumber !== native.number || info.url !== native.html_url || info.state !== "open" || digestValue(info.body) !== record.native.bodyDigest || info.points !== record.native.points || trackingParent || info.blockedBy.length !== 0 || info.projectStatus !== record.status.current && info.projectStatus !== "In Progress")
911
- throw new DeliveryError("Native or Project facts changed during readiness.");
912
- native = nativeIssue({ ...native, labels: info.labels }, repository);
913
- record.native.priority = info.priority ?? null;
914
- });
915
- if (!ready.ready) throw new DeliveryError("Readiness is not satisfied.");
916
- if (record.status.current !== "In Progress") await assertIssueStartCapacity(context, native.number);
917
- const latestConfiguration = await getProjectDeliveryConfiguration({
918
- graphql: context.clients.graphql,
919
- org: context.config.native.organization,
920
- settings: projectSettingsFromDeliveryConfig(context.config),
921
- requireWritable: intent !== void 0,
922
- maxPages: 20
923
- });
924
- if (projectIdentity(latestConfiguration) !== projectIdentity(configuration))
925
- throw new DeliveryError("Project mapping changed during readiness.");
926
- const latestItems = await readProjectDeliveryItems({
927
- graphql: context.clients.graphql,
928
- org: context.config.native.organization,
929
- configuration: latestConfiguration,
930
- maxPages: 20
931
- });
932
- const latestMatches = latestItems.filter(
933
- (item) => item.contentKind === "issue" && item.contentId === native.node_id
934
- );
935
- const latestMember = latestMatches[0];
936
- if (latestMatches.length !== matches.length || member && (!latestMember || latestMember.id !== member.id || latestMember.archived !== member.archived || latestMember.projectId !== member.projectId || latestMember.projectNumber !== member.projectNumber || latestMember.repository?.toLowerCase() !== member.repository?.toLowerCase() || latestMember.issueNumber !== member.issueNumber))
937
- throw new DeliveryError("Project membership changed during readiness.");
938
- if (member && latestMember) {
939
- const sameStatus = latestMember.status === member.status && latestMember.statusRead === member.statusRead && latestMember.statusName === member.statusName && latestMember.statusOptionId === member.statusOptionId;
940
- const completedStatus = latestMember.statusRead === "verified" && latestMember.status === "In Progress" && latestMember.statusOptionId === latestConfiguration.statusOptionIds["In Progress"];
941
- if (!sameStatus && !completedStatus) throw new DeliveryError("Project Status changed during readiness.");
942
- record.status = {
943
- ...record.status,
944
- current: latestMember.status,
945
- kind: latestMember.statusRead,
946
- name: latestMember.statusName,
947
- optionId: latestMember.statusOptionId
948
- };
949
- }
950
- options.signal?.throwIfAborted();
951
- record.status = { ...record.status, target: "In Progress", rule: "active" };
952
- } catch (error) {
953
- missing("readiness-capacity", error);
954
- }
955
- }
956
- if (record.status.rule === "unknown" && (intent === void 0 || intent.kind === "set-status"))
957
- missing("status-evidence");
958
- if (configuration) {
959
- const reports = metadata(
960
- context,
961
- native,
962
- configuration,
963
- record.native,
964
- tracking !== null,
965
- record.status.current,
966
- member !== null && record.status.kind !== "unreadable"
967
- );
968
- record.metadata = intent === void 0 || intent.target === "In Progress" ? reports : reports.filter(
969
- (value) => value.code === "duplicate-field-label" && value.fieldId === configuration.statusFieldId
970
- );
971
- }
972
- bounded(record);
973
- return record;
974
- }
975
- async function collectBoardReconcilePlan(contexts, raw, options) {
976
- const parsed = parseBoardReconcileRequest(raw);
977
- if (parsed.mode !== "dry-run") throw new DeliveryError("The read-only collector requires dry-run mode.");
978
- const plan = emptyPlan(parsed);
979
- try {
980
- plan.packageIdentity = readPackageArtifactIdentity();
981
- } catch (error) {
982
- plan.scopeComplete = false;
983
- plan.gaps.push(boardReconcileGap(plan.scope[0], "package-identity", error));
984
- }
985
- const selected = new Map(contexts.map((context) => [context.config.repository.toLowerCase(), context]));
986
- if (selected.size !== contexts.length || contexts.length !== plan.scope.length || contexts.some((context) => !normalizedScope(plan.scope).includes(context.config.repository.toLowerCase())))
987
- throw new DeliveryError("Reconciliation contexts must match the exact explicit repository scope.");
988
- plan.scope = plan.scope.map((repository) => selected.get(repository.toLowerCase())?.config.repository ?? repository).sort();
989
- plan.checkouts = plan.checkouts.map((checkout) => ({
990
- ...checkout,
991
- repository: selected.get(checkout.repository.toLowerCase())?.config.repository ?? checkout.repository
992
- }));
993
- const projects = /* @__PURE__ */ new Map();
994
- const state = readState();
995
- const { stoppedProjects } = state;
996
- let retainedRecordsBytes = 0;
997
- let currentRepository = plan.scope[0];
998
- try {
999
- for (const repository of plan.scope) {
1000
- currentRepository = repository;
1001
- const context = selected.get(repository.toLowerCase());
1002
- if (!context) {
1003
- plan.scopeComplete = false;
1004
- plan.gaps.push(boardReconcileGap(repository, "context"));
1005
- continue;
1006
- }
1007
- if (context.readPageLimit !== 20 || context.clients.role !== "author" || `${context.repo.owner}/${context.repo.repo}`.toLowerCase() !== repository.toLowerCase())
1008
- throw new DeliveryError("Reconciliation requires a bounded configured author context.");
1009
- const rows = /* @__PURE__ */ new Map();
1010
- try {
1011
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
1012
- await inventory(context, rows, options.signal);
1013
- } catch (error) {
1014
- plan.scopeComplete = false;
1015
- if (globalFailureReason(error) !== null) state.globalReadFailure = error;
1016
- plan.gaps.push(boardReconcileGap(repository, "issue-inventory", error));
1017
- }
1018
- let configuration = null;
1019
- let items = null;
1020
- try {
1021
- options.signal?.throwIfAborted();
1022
- if (state.globalReadFailure !== void 0) throw state.globalReadFailure;
1023
- if (context.configuration && stoppedProjects.has(context.configuration.routing.projectId))
1024
- throw new DeliveryError("Shared Project collection previously stopped.");
1025
- configuration = await getProjectDeliveryConfiguration({
1026
- graphql: context.clients.graphql,
1027
- org: context.config.native.organization,
1028
- settings: projectSettingsFromDeliveryConfig(context.config),
1029
- requireWritable: false,
1030
- maxPages: 20
1031
- });
1032
- const identity = projectIdentity(configuration), previous = projects.get(configuration.projectId);
1033
- if (previous && previous.identity !== identity)
1034
- throw new DeliveryError("Selected repositories disagree on their shared Project mapping.");
1035
- if (previous) items = previous.items;
1036
- else {
1037
- projects.set(configuration.projectId, { identity, items: null });
1038
- items = await readProjectDeliveryItems({
1039
- graphql: context.clients.graphql,
1040
- org: context.config.native.organization,
1041
- configuration,
1042
- maxPages: 20
1043
- });
1044
- projects.set(configuration.projectId, { identity, items });
1045
- }
1046
- if (!items) throw new DeliveryError("Shared Project inventory is incomplete.");
1047
- if (!context.configuration) throw new DeliveryError("Configured repository routing is unavailable.");
1048
- const routing = context.configuration.routing;
1049
- if (routing.projectId !== configuration.projectId || routing.statusFieldId !== configuration.statusFieldId || digestValue(routing.statusOptionIds) !== digestValue(configuration.statusOptionIds) || routing.pointsFieldId !== configuration.pointsFieldId || routing.priorityFieldId !== configuration.priorityFieldId)
1050
- throw new DeliveryError("Project routing changed during collection.");
1051
- let actor = null;
1052
- try {
1053
- if (!context.clients.authenticatedAuthor)
1054
- throw new DeliveryError("Configured author readback is unavailable.");
1055
- actor = ActorSchema.parse(await context.clients.authenticatedAuthor(options.signal));
1056
- } catch (error) {
1057
- plan.scopeComplete = false;
1058
- if (globalFailureReason(error) !== null) state.globalReadFailure = error;
1059
- plan.gaps.push(boardReconcileGap(repository, "actor", error, configuration.projectId));
1060
- }
1061
- plan.bindings.push({
1062
- repository,
1063
- routing,
1064
- actor,
1065
- configDigest: context.configuration.configDigest,
1066
- checkoutRootsDigest: digestValue([...options.checkoutRoots].sort())
1067
- });
1068
- } catch (error) {
1069
- plan.scopeComplete = false;
1070
- if (globalFailureReason(error) !== null) state.globalReadFailure = error;
1071
- const projectId = configuration?.projectId ?? context.configuration?.routing.projectId;
1072
- if (projectId !== void 0) stoppedProjects.add(projectId);
1073
- plan.gaps.push(boardReconcileGap(repository, "project-inventory", error, configuration?.projectId));
1074
- }
1075
- for (const listed of rows.values()) {
1076
- const record = await observeIssue(context, listed, configuration, items, plan.checkouts, options, state);
1077
- plan.scopeComplete = plan.scopeComplete && state.scopeComplete;
1078
- const operations = configuration ? propose(record, configuration) : [];
1079
- const recordBytes = Buffer.byteLength(JSON.stringify(record), "utf8") + operations.reduce((n, operation) => n + Buffer.byteLength(JSON.stringify(operation), "utf8") + 1, 0) + 1;
1080
- const overhead = Buffer.byteLength(JSON.stringify({ ...plan, issues: [], operations: [] }), "utf8");
1081
- if (retainedRecordsBytes + recordBytes + overhead + 4096 > MAX_BYTES) {
1082
- plan.scopeComplete = false;
1083
- plan.gaps.push(boardReconcileGap(repository, "retained-output"));
1084
- return finishPlan(plan);
1085
- }
1086
- retainedRecordsBytes += recordBytes;
1087
- plan.operations.push(...operations);
1088
- plan.issues.push(record);
1089
- }
1090
- }
1091
- } catch (error) {
1092
- plan.scopeComplete = false;
1093
- plan.gaps.push(boardReconcileGap(currentRepository, "collection", error));
1094
- }
1095
- return finishPlan(plan);
1096
- }
1097
- class OperationRefusal extends DeliveryError {
1098
- constructor(stage, outcome = "drifted", global = false) {
1099
- super("Reconciliation prerequisites changed or cannot be proved.");
1100
- this.stage = stage;
1101
- this.outcome = outcome;
1102
- this.global = global;
1103
- }
1104
- stage;
1105
- outcome;
1106
- global;
1107
- }
1108
- class SatisfiedAtBoundary extends Error {
1109
- }
1110
- function itemEvidence(issue) {
1111
- if (issue.membership.itemId === null) return null;
1112
- const { target: _target, rule: _rule, ...status } = issue.status;
1113
- return { itemId: issue.membership.itemId, status, archived: issue.membership.kind === "archived-preserved" };
1114
- }
1115
- function rememberItems(result, operation, ids) {
1116
- const peers = result.operations.filter(
1117
- (value) => value.repository === operation.repository && value.issueNodeId === operation.issueNodeId && value.projectId === operation.projectId
1118
- );
1119
- const known = [.../* @__PURE__ */ new Set([...peers.flatMap((value) => value.knownItemIds), ...ids])].sort();
1120
- for (const peer of peers) peer.knownItemIds = known;
1121
- }
1122
- function captureEvidence(result, operation, issue, phase) {
1123
- if (issue.repository !== operation.repository || issue.issueNodeId !== operation.issueNodeId || issue.issueNumber !== operation.issueNumber || issue.projectId !== operation.projectId)
1124
- return;
1125
- operation[phase] = itemEvidence(issue);
1126
- if (issue.membership.itemId !== null) rememberItems(result, operation, [issue.membership.itemId]);
1127
- }
1128
- function finishResult(result) {
1129
- const count = (outcome) => result.operations.filter((operation) => operation.outcome === outcome).length;
1130
- const unresolved = result.issues.filter(
1131
- (issue) => ["present", "absent"].includes(issue.membership.kind) && (issue.status.rule === "unknown" || issue.status.kind === "unreadable" || issue.status.target !== null && issue.status.current !== issue.status.target)
1132
- ).length;
1133
- result.summary = {
1134
- applied: count("applied"),
1135
- satisfied: count("satisfied"),
1136
- failed: count("failed"),
1137
- drifted: count("drifted"),
1138
- refused: count("refused"),
1139
- unknown: count("unknown"),
1140
- unresolved: unresolved + result.gaps.length
1141
- };
1142
- bounded(result);
1143
- return BoardReconcileResultSchema.parse(result);
1144
- }
1145
- function updateObservedIssue(result, current, operation) {
1146
- const index = result.issues.findIndex(
1147
- (issue) => issue.repository === current.repository && issue.issueNodeId === current.issueNodeId
1148
- );
1149
- if (index < 0) return;
1150
- const old = result.issues[index];
1151
- const { target, rule, ...status } = current.status;
1152
- const active = operation.kind === "set-status" && operation.target === "In Progress";
1153
- const statusFieldId = result.observedBindings.find((binding) => binding.repository === current.repository)?.routing.statusFieldId;
1154
- const issues = [...result.issues];
1155
- issues[index] = {
1156
- ...old,
1157
- membership: current.membership,
1158
- status: {
1159
- ...old.status,
1160
- ...status,
1161
- ...rule !== "unknown" || operation.kind === "set-status" ? { target, rule } : {}
1162
- },
1163
- native: active ? current.native : { ...old.native, state: current.native.state },
1164
- activity: active ? current.activity : old.activity,
1165
- metadata: active ? current.metadata : [...old.metadata.filter((value) => value.fieldId !== statusFieldId), ...current.metadata],
1166
- gaps: [...new Map([...old.gaps, ...current.gaps].map((value) => [digestValue(value), value])).values()]
1167
- };
1168
- bounded({ ...result, issues, pendingEvidenceReserve: " ".repeat(12288) });
1169
- result.issues = issues;
1170
- }
1171
- function assertMapping(configuration, binding) {
1172
- const routing = binding.routing;
1173
- if (configuration.projectId !== routing.projectId || configuration.projectNumber !== routing.native.project.number || configuration.statusFieldId !== routing.statusFieldId || configuration.pointsFieldId !== routing.pointsFieldId || configuration.priorityFieldId !== routing.priorityFieldId || digestValue(configuration.statusOptionIds) !== digestValue(routing.statusOptionIds))
1174
- throw new OperationRefusal("project-routing");
1175
- }
1176
- async function refreshContext(context, options) {
1177
- options.signal?.throwIfAborted();
1178
- const loaded = await loadDeliveryConfig("", {
1179
- clients: context.clients,
1180
- repository: context.config.repository,
1181
- readPageLimit: 20,
1182
- ...options.signal === void 0 ? {} : { signal: options.signal }
1183
- });
1184
- const { projectConfiguration: _old, ...rest } = context;
1185
- return { ...rest, config: loaded.config, configuration: loaded, readPageLimit: 20 };
1186
- }
1187
- async function guardObservation(context, original, operation, options) {
1188
- const live = await refreshContext(context, options);
1189
- const binding = original.bindings.find((value) => value.repository === operation.repository);
1190
- if (!binding || !live.configuration || !live.clients.authenticatedAuthor)
1191
- throw new OperationRefusal("configured-author", "refused", true);
1192
- let actor;
1193
- try {
1194
- actor = ActorSchema.parse(await live.clients.authenticatedAuthor(options.signal));
1195
- } catch (error) {
1196
- if (globalFailureReason(error) !== null) throw error;
1197
- throw new OperationRefusal("actor-readback", "refused", true);
1198
- }
1199
- if (digestValue(actor) !== digestValue(binding.actor)) throw new OperationRefusal("actor", "refused", true);
1200
- if (live.configuration.configDigest !== binding.configDigest || digestValue(live.configuration.routing) !== digestValue(binding.routing) || digestValue([...options.checkoutRoots].sort()) !== binding.checkoutRootsDigest)
1201
- throw new OperationRefusal("configuration-routing");
1202
- if (digestValue(readPackageArtifactIdentity()) !== digestValue(original.packageIdentity))
1203
- throw new OperationRefusal("executing-artifact", "refused", true);
1204
- const configuration = await getProjectDeliveryConfiguration({
1205
- graphql: live.clients.graphql,
1206
- org: live.config.native.organization,
1207
- settings: projectSettingsFromDeliveryConfig(live.config),
1208
- requireWritable: true,
1209
- maxPages: 20
1210
- });
1211
- assertMapping(configuration, binding);
1212
- if (configuration.projectId !== operation.projectId) throw new OperationRefusal("operation-destination");
1213
- const items = await readProjectDeliveryItems({
1214
- graphql: live.clients.graphql,
1215
- org: live.config.native.organization,
1216
- configuration,
1217
- maxPages: 20
1218
- });
1219
- const selected = original.issues.find(
1220
- (issue2) => issue2.repository === operation.repository && issue2.issueNodeId === operation.issueNodeId && issue2.issueNumber === operation.issueNumber
1221
- );
1222
- if (!selected) throw new OperationRefusal("operation-subject");
1223
- const listed = {
1224
- number: selected.issueNumber,
1225
- node_id: selected.issueNodeId,
1226
- state: selected.native.state,
1227
- title: "",
1228
- body: null,
1229
- html_url: `https://github.com/${selected.repository}/issues/${String(selected.issueNumber)}`,
1230
- labels: []
1231
- };
1232
- const state = readState();
1233
- const issue = await observeIssue(live, listed, configuration, items, original.checkouts, options, state, operation);
1234
- return { context: live, configuration, issue, state };
1235
- }
1236
- function assertGuardComplete(observation) {
1237
- if (observation.state.globalReadFailure !== void 0) throw observation.state.globalReadFailure;
1238
- if (!observation.state.scopeComplete) {
1239
- const failure = observation.issue.gaps.find((value) => value.reason === "collection-limit");
1240
- if (failure?.collection !== void 0 && failure.limit !== void 0 && failure.pagesRequested !== void 0 && failure.rowsObserved !== void 0)
1241
- throw new CollectionLimitError({
1242
- collection: failure.collection,
1243
- limit: failure.limit,
1244
- pagesRequested: failure.pagesRequested,
1245
- rowsObserved: failure.rowsObserved
1246
- });
1247
- throw new OperationRefusal("incomplete-native-membership", "refused");
1248
- }
1249
- }
1250
- function operationState(operation, current, knownItemIds) {
1251
- if (current.repository !== operation.repository || current.issueNodeId !== operation.issueNodeId || current.issueNumber !== operation.issueNumber || current.projectId !== operation.projectId)
1252
- throw new OperationRefusal("subject-destination");
1253
- if (["archived-preserved", "duplicate", "unknown", "not-required"].includes(current.membership.kind))
1254
- throw new OperationRefusal("membership-state");
1255
- if (knownItemIds.some((id) => id !== current.membership.itemId)) throw new OperationRefusal("known-item-disappeared");
1256
- if (operation.kind === "add-membership") {
1257
- if (current.native.state !== "open" || digestValue(prerequisites(current, operation.kind)) !== operation.prerequisiteDigest)
1258
- throw new OperationRefusal("native-membership-truth");
1259
- if (current.membership.kind === "present") return "satisfied";
1260
- return "pending";
1261
- }
1262
- if (current.membership.kind !== "present" || current.status.kind === "unreadable")
1263
- throw new OperationRefusal("status-membership-preimage", "refused");
1264
- if (current.status.target !== operation.target || current.status.rule === "unknown" || digestValue(prerequisites(current, operation.kind)) !== operation.prerequisiteDigest)
1265
- throw new OperationRefusal("native-status-truth");
1266
- if (current.status.current === operation.target) return "satisfied";
1267
- if (operation.expected.membership === "absent" ? current.status.current !== null : current.status.current !== operation.expected.status)
1268
- throw new OperationRefusal("status-preimage", "refused");
1269
- return "pending";
1270
- }
1271
- function inventoryIdentity(plan) {
1272
- return digestValue(
1273
- plan.issues.map((issue) => [issue.repository, issue.issueNodeId, issue.issueNumber]).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))
1274
- );
1275
- }
1276
- async function boardReconcile(contexts, raw, options) {
1277
- const request = parseBoardReconcileRequest(raw);
1278
- if (request.mode === "dry-run") return collectBoardReconcilePlan(contexts, request, options);
1279
- const original = request.plan;
1280
- let current;
1281
- const refuse = (stage, error) => {
1282
- const result2 = incompleteBoardReconcile(request, boardReconcileGap(original.scope[0], stage, error));
1283
- if (current) {
1284
- result2.observedBindings = current.bindings;
1285
- result2.issues = current.issues;
1286
- }
1287
- try {
1288
- return finishResult(result2);
1289
- } catch {
1290
- result2.issues = [];
1291
- result2.scopeComplete = false;
1292
- result2.gaps = [boardReconcileGap(original.scope[0], "retained-output")];
1293
- return finishResult(result2);
1294
- }
1295
- };
1296
- const liveContexts = [];
1297
- const configurations = /* @__PURE__ */ new Map();
1298
- try {
1299
- for (const context of contexts) liveContexts.push(await refreshContext(context, options));
1300
- current = await collectBoardReconcilePlan(
1301
- liveContexts,
1302
- { repositories: original.scope, mode: "dry-run", checkouts: original.checkouts },
1303
- options
1304
- );
1305
- if (!current.scopeComplete) return refuse("incomplete-preflight");
1306
- if (digestValue(current.packageIdentity) !== digestValue(original.packageIdentity))
1307
- return refuse("executing-artifact");
1308
- if (digestValue(current.bindings) !== digestValue(original.bindings)) return refuse("actor-configuration-routing");
1309
- if (inventoryIdentity(current) !== inventoryIdentity(original)) return refuse("issue-inventory-drift");
1310
- for (const context of liveContexts) {
1311
- const configuration = await getProjectDeliveryConfiguration({
1312
- graphql: context.clients.graphql,
1313
- org: context.config.native.organization,
1314
- settings: projectSettingsFromDeliveryConfig(context.config),
1315
- requireWritable: true,
1316
- maxPages: 20
1317
- });
1318
- const binding = original.bindings.find((value) => value.repository === context.config.repository);
1319
- if (!binding) return refuse("binding-subject");
1320
- assertMapping(configuration, binding);
1321
- configurations.set(context.config.repository, configuration);
1322
- }
1323
- for (const operation of original.operations) {
1324
- const issue = original.issues.find(
1325
- (value) => value.repository === operation.repository && value.issueNodeId === operation.issueNodeId && value.issueNumber === operation.issueNumber
1326
- );
1327
- const configuration = configurations.get(operation.repository);
1328
- if (!issue || !configuration || operation.projectId !== configuration.projectId || !propose(issue, configuration).some((value) => digestValue(value) === digestValue(operation)))
1329
- return refuse("original-operation-intent");
1330
- }
1331
- } catch (error) {
1332
- return refuse("preflight", error);
1333
- }
1334
- const result = incompleteBoardReconcile(request, boardReconcileGap(original.scope[0], "not-started"));
1335
- result.scopeComplete = true;
1336
- result.gaps = [];
1337
- result.observedBindings = current.bindings;
1338
- result.issues = current.issues;
1339
- for (const operation of result.operations) rememberItems(result, operation, []);
1340
- try {
1341
- bounded({ ...result, pendingEvidenceReserve: " ".repeat(12288) });
1342
- } catch (error) {
1343
- return refuse("retained-output", error);
1344
- }
1345
- const stopped = /* @__PURE__ */ new Set();
1346
- let globalStop = false;
1347
- const ordered = [...result.operations].sort(
1348
- (a, b) => a.repository.localeCompare(b.repository) || a.issueNodeId.localeCompare(b.issueNodeId) || (a.kind === b.kind ? 0 : a.kind === "add-membership" ? -1 : 1)
1349
- );
1350
- for (const operation of ordered) {
1351
- const context = liveContexts.find((value) => value.config.repository === operation.repository);
1352
- if (!context || globalStop || stopped.has(operation.projectId)) continue;
1353
- let observation;
1354
- try {
1355
- options.signal?.throwIfAborted();
1356
- bounded({ ...result, pendingEvidenceReserve: " ".repeat(12288) });
1357
- observation = await guardObservation(context, original, operation, options);
1358
- captureEvidence(result, operation, observation.issue, "before");
1359
- updateObservedIssue(result, observation.issue, operation);
1360
- assertGuardComplete(observation);
1361
- const state = operationState(operation, observation.issue, operation.knownItemIds);
1362
- if (state === "satisfied") {
1363
- operation.outcome = "satisfied";
1364
- operation.readback = itemEvidence(observation.issue);
1365
- continue;
1366
- }
1367
- bounded({ ...result, pendingEvidenceReserve: " ".repeat(12288) });
1368
- const guard = async () => {
1369
- const checked = await guardObservation(context, original, operation, options);
1370
- captureEvidence(result, operation, checked.issue, "before");
1371
- updateObservedIssue(result, checked.issue, operation);
1372
- assertGuardComplete(checked);
1373
- if (operationState(operation, checked.issue, operation.knownItemIds) === "satisfied")
1374
- throw new SatisfiedAtBoundary();
1375
- options.signal?.throwIfAborted();
1376
- operation.attempted = true;
1377
- };
1378
- try {
1379
- if (operation.kind === "add-membership") {
1380
- await ensureIssueProjectMembership({
1381
- graphql: context.clients.graphql,
1382
- org: context.config.native.organization,
1383
- configuration: observation.configuration,
1384
- issueNodeId: operation.issueNodeId,
1385
- maxPages: 20,
1386
- beforeAdd: guard,
1387
- onItemKnown: (id) => rememberItems(result, operation, [id])
1388
- });
1389
- } else {
1390
- if (operation.target === null) throw new OperationRefusal("missing-status-target", "refused");
1391
- await syncIssueProjectStatus({
1392
- graphql: context.clients.graphql,
1393
- org: context.config.native.organization,
1394
- configuration: observation.configuration,
1395
- issueNodeId: operation.issueNodeId,
1396
- status: operation.target,
1397
- maxPages: 20,
1398
- beforeAdd: async () => {
1399
- throw new OperationRefusal("status-cannot-create-membership");
1400
- },
1401
- beforeAdvance: guard
1402
- });
1403
- }
1404
- } catch (error) {
1405
- if (!(error instanceof SatisfiedAtBoundary)) throw error;
1406
- }
1407
- observation = await guardObservation(context, original, operation, options);
1408
- captureEvidence(result, operation, observation.issue, "readback");
1409
- updateObservedIssue(result, observation.issue, operation);
1410
- assertGuardComplete(observation);
1411
- if (operationState(operation, observation.issue, operation.knownItemIds) !== "satisfied")
1412
- throw new OperationRefusal("write-postimage");
1413
- operation.outcome = operation.attempted ? "applied" : "satisfied";
1414
- } catch (error) {
1415
- operation.outcome = error instanceof OperationRefusal ? error.outcome : operation.attempted ? "unknown" : "refused";
1416
- result.gaps.push(
1417
- boardReconcileGap(
1418
- operation.repository,
1419
- error instanceof OperationRefusal ? error.stage : "operation-read-write",
1420
- error,
1421
- operation.projectId
1422
- )
1423
- );
1424
- stopped.add(operation.projectId);
1425
- if (error instanceof CollectionLimitError || error instanceof RetainedOutputLimitError)
1426
- result.scopeComplete = false;
1427
- if (globalFailureReason(error) !== null || options.signal?.aborted || error instanceof OperationRefusal && error.global) {
1428
- globalStop = true;
1429
- result.scopeComplete = false;
1430
- }
1431
- }
1432
- }
1433
- return finishResult(result);
1434
- }
1435
- export {
1436
- BoardReconcileInput,
1437
- BoardReconcilePlanSchema,
1438
- BoardReconcileResultSchema,
1439
- boardReconcile,
1440
- boardReconcileGap,
1441
- collectBoardReconcilePlan,
1442
- incompleteBoardReconcile,
1443
- parseBoardReconcileRequest
1444
- };
1445
- //# sourceMappingURL=boardReconcileService.js.map