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