@aviaratech/ai-delivery 0.3.31 → 0.3.33

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 (74) hide show
  1. package/README.md +116 -3
  2. package/dist/cli.js +28 -3
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cliResult.js +10 -0
  5. package/dist/cliResult.js.map +1 -1
  6. package/dist/cliResult.test.js +61 -0
  7. package/dist/cliResult.test.js.map +1 -1
  8. package/dist/config/deliveryConfig.d.ts +36 -0
  9. package/dist/config/deliveryConfig.js +27 -2
  10. package/dist/config/deliveryConfig.js.map +1 -1
  11. package/dist/config/deliveryConfig.test.js +39 -2
  12. package/dist/config/deliveryConfig.test.js.map +1 -1
  13. package/dist/currentTrackingScenario.test.js +5 -1
  14. package/dist/currentTrackingScenario.test.js.map +1 -1
  15. package/dist/dispatch.d.ts +2 -0
  16. package/dist/dispatch.js +15 -4
  17. package/dist/dispatch.js.map +1 -1
  18. package/dist/errors.d.ts +11 -0
  19. package/dist/errors.js +35 -0
  20. package/dist/errors.js.map +1 -1
  21. package/dist/fixtures/discovery.d.ts +11 -0
  22. package/dist/fixtures/inertTarget.d.ts +5 -0
  23. package/dist/fixtures/issue63.d.ts +11 -0
  24. package/dist/fixtures/issue63.js +16 -9
  25. package/dist/fixtures/issue63.js.map +1 -1
  26. package/dist/github/client.d.ts +3 -0
  27. package/dist/github/client.js +21 -10
  28. package/dist/github/client.js.map +1 -1
  29. package/dist/github/commandIdentityPolicy.js +1 -0
  30. package/dist/github/commandIdentityPolicy.js.map +1 -1
  31. package/dist/github/machineAuth.test.js +20 -0
  32. package/dist/github/machineAuth.test.js.map +1 -1
  33. package/dist/github/projectDelivery.d.ts +3 -0
  34. package/dist/github/projectDelivery.js +44 -12
  35. package/dist/github/projectDelivery.js.map +1 -1
  36. package/dist/issue.d.ts +53 -6
  37. package/dist/issue.js +696 -58
  38. package/dist/issue.js.map +1 -1
  39. package/dist/issueBatchUpdate.test.d.ts +1 -0
  40. package/dist/issueBatchUpdate.test.js +730 -0
  41. package/dist/issueBatchUpdate.test.js.map +1 -0
  42. package/dist/issueBlockerGuard.test.js +78 -0
  43. package/dist/issueBlockerGuard.test.js.map +1 -1
  44. package/dist/issueContract.d.ts +68 -2
  45. package/dist/issueContract.js +101 -9
  46. package/dist/issueContract.js.map +1 -1
  47. package/dist/issueContract.test.d.ts +5 -0
  48. package/dist/issueContract.test.js +28 -1
  49. package/dist/issueContract.test.js.map +1 -1
  50. package/dist/issueIntake.test.js +972 -19
  51. package/dist/issueIntake.test.js.map +1 -1
  52. package/dist/issueJournal.js +12 -8
  53. package/dist/issueJournal.js.map +1 -1
  54. package/dist/issueJournal.test.js +138 -0
  55. package/dist/issueJournal.test.js.map +1 -1
  56. package/dist/mcp/index.js +20 -2
  57. package/dist/mcp/index.js.map +1 -1
  58. package/dist/mcp/tools.d.ts +104 -12
  59. package/dist/mcp/tools.js +50 -34
  60. package/dist/mcp/tools.js.map +1 -1
  61. package/dist/services/agentReadinessService.js +2 -0
  62. package/dist/services/agentReadinessService.js.map +1 -1
  63. package/dist/setup.js +65 -2
  64. package/dist/setup.js.map +1 -1
  65. package/dist/setup.test.js +857 -23
  66. package/dist/setup.test.js.map +1 -1
  67. package/dist/verification.js +42 -3
  68. package/dist/verification.js.map +1 -1
  69. package/package.json +1 -1
  70. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  71. package/plugins/ai-delivery/plugin.json +1 -1
  72. package/plugins/ai-delivery/runtime/dist/cli.js +67 -55
  73. package/plugins/ai-delivery/runtime/package.json +1 -1
  74. package/plugins/ai-delivery/skills/intake-create/SKILL.md +22 -2
package/dist/issue.js CHANGED
@@ -1,29 +1,33 @@
1
+ import { types } from 'node:util';
1
2
  import { z } from 'zod';
2
- import { loadDeliveryConfig } from './config/deliveryConfig.js';
3
+ import { loadDeliveryConfig, WipLimits } from './config/deliveryConfig.js';
3
4
  import { digestValue } from './delivery/legacy.js';
4
- import { DeliveryError } from './errors.js';
5
+ import { DeliveryError, getRateLimitDiagnostics, getMachineRequestDiagnostics, } from './errors.js';
5
6
  import { createDeliveryGitHubClients } from './github/client.js';
6
7
  import { NATIVE_ISSUE_API_VERSION, clearConfiguredNativeIssuePoints, getConfiguredNativeIssueMetadata, nativeIssueSettingsFromDeliveryConfig, setConfiguredNativeIssueMetadata, } from './github/nativeIssueMetadata.js';
7
- import { getIssueProjectStatus, projectSettingsFromDeliveryConfig, syncIssueProjectStatus, } from './github/projectDelivery.js';
8
+ import { getIssueProjectStatus, getProjectDeliveryConfiguration, projectSettingsFromDeliveryConfig, syncIssueProjectStatus, } from './github/projectDelivery.js';
8
9
  import { getNativeBlockerRelationships, hasNativeSubIssues, linkBlockedBy, replaceBlockedBy, replaceParentIssue, resolveNativeRelationshipTargets, } from './github/relationships.js';
9
- import { prepareBlockerGuard } from './services/blockerGuardService.js';
10
+ import { prepareBlockerGuard, OverrideReason } from './services/blockerGuardService.js';
10
11
  import {} from './github/repo.js';
11
12
  import { evaluateAgentReadiness } from './services/agentReadinessService.js';
12
13
  import { JournalInputSchema, renderJournal } from './issueJournal.js';
13
- import { IssueFields, IssueWriteFields, parseIssueBody, requireIssue, renderIssueBody, issueWarnings, issueBodyDiff, issueStartFooter, validateIssue, IssueValidationError, } from './issueContract.js';
14
+ import { IssueFields, IssueWriteFields, CreateIssueStatus, IssueStatusPatch, requireIssueStatus, parseIssueBody, requireIssue, renderIssueBody, issueWarnings, issueBodyDiff, issueStartFooter, validateIssue, IssueValidationError, requireDeferralPatch, } from './issueContract.js';
14
15
  // Matches GitHub's first-party JavaScript comment-length validation:
15
16
  // https://github.com/github/gh-aw/blob/3ead8042c7b1edc2128ba1b28b1b80d00b7f4c22/actions/setup/js/comment_limit_helpers.cjs
16
17
  export const ISSUE_COMMENT_BODY_LIMIT = 65_536;
17
18
  const RawIssueCommentSchema = z.strictObject({ issueNumber: z.number().int().positive(), body: z.string() });
18
19
  /** One canonical exact-body operation shared by direct calls, MCP, and lifecycle journals. */
19
20
  export async function commentIssue(context, input, lifecycleKey) {
21
+ return writeAuthenticatedIssueComment(context, input, lifecycleKey);
22
+ }
23
+ async function writeAuthenticatedIssueComment(context, input, lifecycleKey, rawMarker) {
20
24
  const accepted = 'body' in input ? RawIssueCommentSchema.parse(input) : JournalInputSchema.parse(input);
21
25
  const rawBody = 'body' in accepted ? accepted.body : undefined;
22
26
  if (rawBody !== undefined && lifecycleKey !== undefined)
23
27
  throw new DeliveryError('Raw issue comments do not accept a lifecycle journal key.');
24
28
  const marker = rawBody === undefined
25
29
  ? `<!-- ai-delivery:journal@1:${digestValue({ issueNumber: accepted.issueNumber, key: lifecycleKey ?? accepted })} -->`
26
- : undefined;
30
+ : rawMarker;
27
31
  const body = rawBody ?? renderJournal(accepted, marker);
28
32
  if (body.length > ISSUE_COMMENT_BODY_LIMIT || !body.trim())
29
33
  throw new DeliveryError(`Issue comment body must contain text and fit ${String(ISSUE_COMMENT_BODY_LIMIT)} UTF-16 code units.`);
@@ -44,8 +48,11 @@ export async function commentIssue(context, input, lifecycleKey) {
44
48
  page,
45
49
  per_page: 100,
46
50
  })).data;
47
- matches.push(...batch.filter((comment) => (marker === undefined ? comment.body === body : comment.body?.endsWith(marker)) &&
48
- comment.user?.login.toLowerCase() === actor.toLowerCase()));
51
+ matches.push(...batch.filter((comment) => (marker === undefined
52
+ ? comment.body === body
53
+ : rawMarker === undefined
54
+ ? comment.body?.endsWith(marker)
55
+ : comment.body?.includes(marker)) && comment.user?.login.toLowerCase() === actor.toLowerCase()));
49
56
  if (batch.length < 100)
50
57
  break;
51
58
  if (page === 20)
@@ -54,25 +61,32 @@ export async function commentIssue(context, input, lifecycleKey) {
54
61
  if (matches.length > 1)
55
62
  throw new DeliveryError('Issue comment has duplicate authored retry matches.');
56
63
  const existing = matches[0];
64
+ if (rawMarker !== undefined && existing && existing.body !== body)
65
+ throw new DeliveryError('Issue comment conflicts with its authored operation marker.');
57
66
  const created = existing ??
58
67
  (await context.clients.rest.issues.createComment({ ...context.repo, issue_number: input.issueNumber, body }))
59
68
  .data;
60
- const readback = (await context.clients.rest.issues.getComment({ ...context.repo, comment_id: created.id })).data;
61
- const expectedIssuePath = `/repos/${context.repo.owner}/${context.repo.repo}/issues/${String(input.issueNumber)}`;
62
- if (!Number.isSafeInteger(readback.id) ||
63
- readback.id <= 0 ||
64
- readback.id !== created.id ||
65
- readback.html_url !== created.html_url ||
66
- readback.body !== (existing?.body ?? body) ||
67
- (lifecycleKey === undefined && readback.body !== body) ||
68
- readback.user?.login.toLowerCase() !== actor.toLowerCase() ||
69
- new URL(readback.issue_url).pathname.toLowerCase() !== expectedIssuePath.toLowerCase() ||
70
- !readback.html_url.startsWith('https://'))
69
+ if (lifecycleKey === undefined && (existing?.body ?? body) !== body)
71
70
  throw new DeliveryError('Issue comment readback disagrees with the authored issue comment.');
72
- return { commentId: readback.id, url: readback.html_url, body: readback.body, reused: existing !== undefined };
71
+ const readback = await readAuthoredIssueComment(context, input.issueNumber, created, existing?.body ?? body, actor);
72
+ return { ...readback, reused: existing !== undefined };
73
73
  };
74
74
  return operation();
75
75
  }
76
+ async function readAuthoredIssueComment(context, issueNumber, created, body, actor) {
77
+ const readback = (await context.clients.rest.issues.getComment({ ...context.repo, comment_id: created.id })).data;
78
+ const expectedIssuePath = `/repos/${context.repo.owner}/${context.repo.repo}/issues/${String(issueNumber)}`;
79
+ if (!Number.isSafeInteger(readback.id) ||
80
+ readback.id <= 0 ||
81
+ readback.id !== created.id ||
82
+ readback.html_url !== created.html_url ||
83
+ readback.body !== body ||
84
+ readback.user?.login.toLowerCase() !== actor.toLowerCase() ||
85
+ new URL(readback.issue_url).pathname.toLowerCase() !== expectedIssuePath.toLowerCase() ||
86
+ !readback.html_url.startsWith('https://'))
87
+ throw new DeliveryError('Issue comment readback disagrees with the authored issue comment.');
88
+ return { commentId: readback.id, url: readback.html_url, body: readback.body };
89
+ }
76
90
  export async function journalIssueStart(context, issueNumber) {
77
91
  const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
78
92
  return commentIssue(context, {
@@ -140,7 +154,14 @@ async function labels(context, input) {
140
154
  }
141
155
  throw new DeliveryError('Repository label listing exceeds the bounded readback window.');
142
156
  }
143
- function prepareIssueWrite(input, current) {
157
+ function prepareIssueWrite(input, current, forIntent = false) {
158
+ const patch = input.status === undefined
159
+ ? undefined
160
+ : requireIssueStatus(IssueStatusPatch, current === undefined ? requireIssueStatus(CreateIssueStatus, input.status) : input.status);
161
+ if (input.blockedBy !== undefined && patch && 'blockers' in patch)
162
+ throw new DeliveryError('Choose native blockedBy or display-only status.blockers in one update, not both.');
163
+ const statusOnly = patch !== undefined &&
164
+ Object.entries(input).every(([key, value]) => value === undefined || ['repo', 'issueNumber', 'status'].includes(key));
144
165
  const title = input.title ?? current?.title ?? '';
145
166
  const source = input.body ?? current?.body;
146
167
  const prior = current?.body ?? source;
@@ -152,8 +173,10 @@ function prepareIssueWrite(input, current) {
152
173
  ...(current.issueType === null ? {} : { issueType: current.issueType }),
153
174
  });
154
175
  const currentLegacy = currentParsed?.legacy === true;
155
- const points = input.points ?? current?.points;
156
- const issueType = input.issueType ?? current?.issueType ?? undefined;
176
+ if (statusOnly && currentLegacy)
177
+ throw new DeliveryError('Convert the legacy contract explicitly before a status-only update.');
178
+ const points = statusOnly ? currentParsed?.issue.points : (input.points ?? current?.points);
179
+ const issueType = statusOnly ? currentParsed?.issue.issueType : (input.issueType ?? current?.issueType ?? undefined);
157
180
  const metadata = {
158
181
  title: input.body === undefined && current ? current.title : title,
159
182
  ...(points === undefined ? {} : { points }),
@@ -165,31 +188,93 @@ function prepareIssueWrite(input, current) {
165
188
  legacyBody !== undefined &&
166
189
  !legacyBody.includes(parsed.issue.legacyBody))
167
190
  legacyBody += '\n\n' + parsed.issue.legacyBody;
191
+ const incomingLegacy = current !== undefined &&
192
+ parsed.issue.legacyBody !== undefined &&
193
+ parsed.issue.legacyBody !== currentParsed?.issue.legacyBody &&
194
+ parsed.issue.legacyBody !== current.body;
168
195
  const fields = Object.fromEntries(Object.keys(IssueWriteFields).flatMap((key) => {
169
196
  const value = input[key];
170
197
  return value === undefined ? [] : [[key, value]];
171
198
  }));
172
199
  const issue = requireIssue({
173
200
  ...parsed.issue,
201
+ // Body replacements and unrelated typed patches cannot implicitly resume deferred work.
202
+ deferral: input.undefer === true
203
+ ? undefined
204
+ : (input.defer ?? (current === undefined ? parsed.issue.deferral : currentParsed?.issue.deferral)),
174
205
  ...metadata,
175
206
  ...fields,
176
207
  title,
177
208
  ...(legacyBody === undefined ? {} : { legacyBody }),
209
+ ...(input.retainLegacyBody !== undefined
210
+ ? { retainLegacyBody: input.retainLegacyBody }
211
+ : incomingLegacy
212
+ ? { retainLegacyBody: true }
213
+ : current !== undefined && legacyBody !== undefined && input.preserveHistory !== false && !statusOnly
214
+ ? { retainLegacyBody: false }
215
+ : {}),
178
216
  ...(input.park ? { draft: true } : {}),
179
217
  });
180
- const body = renderIssueBody(issue) + (source === undefined || parsed.legacy ? '' : issueStartFooter(source));
218
+ const unchangedContract = currentParsed !== undefined && JSON.stringify(issue) === JSON.stringify(currentParsed.issue);
219
+ const legacyFormatting = unchangedContract && parsed.legacyFormatting === true;
220
+ const base = parsed.status ?? currentParsed?.status;
221
+ const proposed = {
222
+ state: issue.draft ? 'Draft' : 'Ready',
223
+ lastUpdated: base?.lastUpdated ?? new Date(Date.now()).toISOString(),
224
+ nextMilestone: patch?.nextMilestone ?? base?.nextMilestone ?? 'Not started',
225
+ blockers: patch?.blockers ?? base?.blockers ?? 'None',
226
+ latestJournal: patch?.latestJournal ?? base?.latestJournal ?? 'None yet',
227
+ ...(input.blockedBy === undefined
228
+ ? {}
229
+ : {
230
+ blockers: input.blockedBy.length ? input.blockedBy.map((number) => '#' + String(number)).join(', ') : 'None',
231
+ }),
232
+ };
233
+ const unchangedDisplay = currentParsed?.status !== undefined &&
234
+ ['state', 'nextMilestone', 'blockers', 'latestJournal'].every((key) => proposed[key] === currentParsed.status[key]);
235
+ const displayChanged = JSON.stringify(proposed) !== JSON.stringify(base);
236
+ const status = forIntent
237
+ ? undefined
238
+ : current === undefined
239
+ ? {
240
+ ...proposed,
241
+ state: issue.draft ? 'Draft' : 'Ready',
242
+ lastUpdated: new Date(Date.now()).toISOString(),
243
+ blockers: input.blockedBy?.length ? input.blockedBy.map((number) => '#' + String(number)).join(', ') : 'None',
244
+ latestJournal: 'None yet',
245
+ }
246
+ : unchangedContract && unchangedDisplay
247
+ ? currentParsed?.status
248
+ : !unchangedContract ||
249
+ (patch !== undefined && displayChanged) ||
250
+ (input.blockedBy !== undefined && displayChanged)
251
+ ? {
252
+ ...proposed,
253
+ lastUpdated: new Date(Date.now()).toISOString(),
254
+ }
255
+ : base;
256
+ const body = renderIssueBody(issue, status, forIntent ? false : legacyFormatting) +
257
+ (source === undefined || parsed.legacy ? '' : issueStartFooter(source));
181
258
  return {
182
259
  issue,
183
260
  body,
184
- warnings: issueWarnings(issue),
261
+ statusOnly,
262
+ preserveHistory: input.preserveHistory ??
263
+ ((currentLegacy ||
264
+ parsed.legacy ||
265
+ (legacyBody !== undefined &&
266
+ issue.retainLegacyBody === false &&
267
+ currentParsed?.issue.retainLegacyBody !== false)) &&
268
+ !statusOnly),
269
+ warnings: issueWarnings(issue, status, legacyFormatting),
185
270
  ...((currentLegacy || parsed.legacy) && prior !== undefined
186
271
  ? { conversion: { priorBody: prior, canonicalBody: body, diff: issueBodyDiff(prior, body) } }
187
272
  : {}),
188
273
  };
189
274
  }
190
- /** The normal start route computes its retry intent from the same accepted canonical write. */
275
+ /** Display timestamps are excluded from the contract-bound normal-start retry intent. */
191
276
  export function canonicalIssueBody(input) {
192
- return prepareIssueWrite(input).body;
277
+ return prepareIssueWrite(input, undefined, true).body;
193
278
  }
194
279
  export class CreatedTrackingIssueError extends DeliveryError {
195
280
  created;
@@ -341,16 +426,43 @@ const ListedIssue = z.object({
341
426
  number: z.number().int().positive().safe(),
342
427
  node_id: z.string().min(1),
343
428
  title: z.string(),
429
+ body: z.string().nullable().optional(),
344
430
  state: z.enum(['open', 'closed']),
345
431
  labels: z.array(z.union([z.string(), z.object({ name: z.string() })])),
346
432
  type: z.object({ name: z.string() }).nullable().optional(),
347
433
  html_url: z.url(),
348
434
  updated_at: z.iso.datetime({ offset: true }),
349
435
  });
350
- async function issueFieldPages(context, route, parameters) {
436
+ function capacityNextPage(response, page, perPage) {
437
+ if (!Array.isArray(response.data) || response.data.length > perPage)
438
+ throw new DeliveryError('WIP capacity pagination returned invalid native data.');
439
+ const link = response.headers?.link;
440
+ if (link === undefined || link === '')
441
+ return response.data.length === perPage ? page + 1 : null;
442
+ const parts = [...link.matchAll(/<([^>]+)>;\s*rel="([^"]+)"/gu)];
443
+ const next = parts.filter((part) => part[2] === 'next');
444
+ const residue = link.replace(/<([^>]+)>;\s*rel="([^"]+)"/gu, '').replace(/[,\s]/gu, '');
445
+ if (!parts.length ||
446
+ residue ||
447
+ next.length > 1 ||
448
+ parts.some((part) => !['first', 'prev', 'next', 'last'].includes(part[2])))
449
+ throw new DeliveryError('WIP capacity native pagination is malformed.');
450
+ if (!next.length)
451
+ return null;
452
+ const url = new URL(next[0][1]);
453
+ if (url.protocol !== 'https:' ||
454
+ url.hostname !== 'api.github.com' ||
455
+ url.searchParams.get('page') !== String(page + 1) ||
456
+ url.searchParams.get('per_page') !== String(perPage))
457
+ throw new DeliveryError('WIP capacity native pagination did not advance consistently.');
458
+ return page + 1;
459
+ }
460
+ async function issueFieldPages(context, route, parameters, maxPages) {
351
461
  const values = [];
352
462
  const seenPages = new Set();
353
463
  for (let page = 1;; page += 1) {
464
+ if (maxPages !== undefined && page > maxPages)
465
+ throw new DeliveryError('WIP capacity native field pagination is incomplete.');
354
466
  const response = await context.clients.rest.request(route, {
355
467
  ...parameters,
356
468
  headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
@@ -364,12 +476,12 @@ async function issueFieldPages(context, route, parameters) {
364
476
  throw new DeliveryError('Native issue fields repeated a pagination page.');
365
477
  seenPages.add(fingerprint);
366
478
  values.push(...response.data);
367
- if (response.data.length < 100)
479
+ if (maxPages === undefined ? response.data.length < 100 : capacityNextPage(response, page, 100) === null)
368
480
  return values;
369
481
  }
370
482
  }
371
483
  /** A bounded GitHub page; local filters can produce an empty page with a nextPage. */
372
- export async function listIssues(context, input) {
484
+ export async function listIssues(context, input, options = {}) {
373
485
  const page = input.page ?? 1;
374
486
  const perPage = input.perPage ?? 30;
375
487
  if (!Number.isSafeInteger(page) || page <= 0 || !Number.isSafeInteger(perPage) || perPage <= 0 || perPage > 100)
@@ -407,7 +519,7 @@ export async function listIssues(context, input) {
407
519
  nextPage = page * perPage < response.total_count ? page + 1 : null;
408
520
  }
409
521
  else {
410
- raw = (await context.clients.rest.issues.listForRepo({
522
+ const response = await context.clients.rest.issues.listForRepo({
411
523
  ...context.repo,
412
524
  state: input.state ?? 'open',
413
525
  ...(input.labels === undefined ? {} : { labels: input.labels.join(',') }),
@@ -417,12 +529,17 @@ export async function listIssues(context, input) {
417
529
  sort: 'updated',
418
530
  direction: 'desc',
419
531
  headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
420
- })).data;
421
- nextPage = raw.length === perPage ? page + 1 : null;
532
+ });
533
+ raw = response.data;
534
+ nextPage = options.capacityRead
535
+ ? capacityNextPage(response, page, perPage)
536
+ : raw.length === perPage
537
+ ? page + 1
538
+ : null;
422
539
  }
423
540
  const catalog = z
424
541
  .array(FieldCatalogEntry)
425
- .parse(await issueFieldPages(context, 'GET /orgs/{org}/issue-fields', { org: context.config.native.organization }));
542
+ .parse(await issueFieldPages(context, 'GET /orgs/{org}/issue-fields', { org: context.config.native.organization }, options.capacityRead ? 20 : undefined));
426
543
  if (new Set(catalog.map((field) => field.name)).size !== catalog.length ||
427
544
  new Set(catalog.map((field) => field.id)).size !== catalog.length)
428
545
  throw new DeliveryError('Native issue field catalog has duplicate identities or names.');
@@ -439,6 +556,18 @@ export async function listIssues(context, input) {
439
556
  `/${context.repo.owner}/${context.repo.repo}/issues/${String(current.number)}`.toLowerCase())
440
557
  throw new DeliveryError('GitHub issue list returned a foreign repository issue.');
441
558
  const selectedLabels = current.labels.map((label) => (typeof label === 'string' ? label : label.name));
559
+ if (options.capacityRead) {
560
+ const url = new URL(current.html_url);
561
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com')
562
+ throw new DeliveryError('WIP capacity issue URL is not the selected GitHub repository.');
563
+ const native = (await context.clients.rest.issues.get({ ...context.repo, issue_number: current.number })).data;
564
+ if ('pull_request' in native ||
565
+ native.number !== current.number ||
566
+ native.node_id !== current.node_id ||
567
+ native.html_url !== current.html_url ||
568
+ native.state !== current.state)
569
+ throw new DeliveryError('WIP capacity issue identity or state changed during native readback.');
570
+ }
442
571
  if (input.state !== undefined && input.state !== 'all' && current.state !== input.state)
443
572
  continue;
444
573
  if ((input.labels ?? []).some((label) => !selectedLabels.some((selected) => selected.toLowerCase() === label.toLowerCase())))
@@ -462,6 +591,7 @@ export async function listIssues(context, input) {
462
591
  const project = await getIssueProjectStatus({
463
592
  graphql: context.clients.graphql,
464
593
  issueNodeId: current.node_id,
594
+ ...(options.capacityRead ? { capacityRead: true, maxPages: 20 } : {}),
465
595
  org: context.config.native.organization,
466
596
  ...(context.projectConfiguration ? { configuration: context.projectConfiguration } : {}),
467
597
  settings: projectSettingsFromDeliveryConfig(context.config),
@@ -472,7 +602,7 @@ export async function listIssues(context, input) {
472
602
  const values = z.array(FieldValueEntry).parse(await issueFieldPages(context, 'GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {
473
603
  ...context.repo,
474
604
  issue_number: current.number,
475
- }));
605
+ }, options.capacityRead ? 20 : undefined));
476
606
  const observed = new Set();
477
607
  for (const field of values) {
478
608
  const definition = catalog.find((candidate) => candidate.id === field.issue_field_id);
@@ -482,6 +612,13 @@ export async function listIssues(context, input) {
482
612
  observed.has(field.issue_field_id))
483
613
  throw new DeliveryError('Native issue field readback conflicts with its catalog.');
484
614
  observed.add(field.issue_field_id);
615
+ if (options.capacityRead &&
616
+ (field.data_type === 'single_select'
617
+ ? field.single_select_option === undefined && field.value !== null
618
+ : field.data_type === 'multi_select'
619
+ ? field.multi_select_options === undefined && field.value !== null
620
+ : field.value === undefined))
621
+ throw new DeliveryError('WIP capacity native field value payload is missing.');
485
622
  if (((field.data_type === 'single_select' && !field.single_select_option) ||
486
623
  (field.data_type === 'multi_select' && field.multi_select_options === undefined)) &&
487
624
  field.value !== null &&
@@ -506,6 +643,10 @@ export async function listIssues(context, input) {
506
643
  throw new DeliveryError('Native issue field has an invalid value type.');
507
644
  }
508
645
  issues.push({
646
+ ...(options.capacityRead
647
+ ? { nodeId: current.node_id, fieldIds: Object.fromEntries(catalog.map((field) => [field.name, field.id])) }
648
+ : {}),
649
+ ...deferralReadback(current.body, current.title),
509
650
  number: current.number,
510
651
  title: current.title,
511
652
  state: current.state,
@@ -577,7 +718,24 @@ export async function readIssueClosure(context, issueNumber) {
577
718
  : { number: parsed.duplicateOf.number, repository: parsed.duplicateOf.repository.nameWithOwner },
578
719
  };
579
720
  }
580
- export async function updateIssue(context, input) {
721
+ function updateProjectStatus(info, input) {
722
+ return info.state === 'closed' || info.projectStatus === 'Done'
723
+ ? 'Done'
724
+ : info.blockedBy.length > 0
725
+ ? 'Blocked'
726
+ : input.park === true || input.blockedBy !== undefined || info.projectStatus === null
727
+ ? 'Todo'
728
+ : info.projectStatus === 'In Progress' || (info.projectStatus === 'Blocked' && input.state === undefined)
729
+ ? info.projectStatus
730
+ : 'Todo';
731
+ }
732
+ async function prepareIssueUpdate(context, input) {
733
+ requireDeferralPatch({
734
+ ...(input.defer === undefined ? {} : { defer: input.defer }),
735
+ ...(input.undefer === undefined ? {} : { undefer: input.undefer }),
736
+ });
737
+ if ('deferral' in input)
738
+ throw new DeliveryError('Use defer or undefer to change deferral state.');
581
739
  if (context.clients.role !== 'author')
582
740
  throw new DeliveryError('Issue writes require the configured author role.');
583
741
  if ((input.closeReason !== undefined && !['completed', 'not_planned', 'duplicate'].includes(input.closeReason)) ||
@@ -591,12 +749,16 @@ export async function updateIssue(context, input) {
591
749
  const prepared = prepareIssueWrite(input, currentContent);
592
750
  input = {
593
751
  ...input,
594
- title: prepared.issue.title,
595
752
  body: prepared.body,
596
- ...(prepared.issue.issueType === undefined ? {} : { issueType: prepared.issue.issueType }),
597
- ...(prepared.issue.points === undefined ? {} : { points: prepared.issue.points }),
598
- ...(prepared.conversion === undefined ? {} : { preserveHistory: true }),
599
- ...(prepared.issue.draft ? { park: true } : {}),
753
+ ...(prepared.statusOnly
754
+ ? {}
755
+ : {
756
+ title: prepared.issue.title,
757
+ ...(prepared.issue.issueType === undefined ? {} : { issueType: prepared.issue.issueType }),
758
+ ...(prepared.issue.points === undefined ? {} : { points: prepared.issue.points }),
759
+ ...(prepared.issue.draft ? { park: true } : {}),
760
+ }),
761
+ preserveHistory: prepared.preserveHistory,
600
762
  };
601
763
  const acceptedLabels = input.labels === undefined ? undefined : await labels(context, input.labels);
602
764
  if (input.issueType !== undefined && !config.native.issueTypes.includes(input.issueType)) {
@@ -669,13 +831,15 @@ export async function updateIssue(context, input) {
669
831
  }
670
832
  }
671
833
  }
672
- let historyComment;
673
- let priorContent;
834
+ let historyBody;
835
+ let priorContent = input.status === undefined ? undefined : { title: currentContent.title, body: currentContent.body };
674
836
  if (input.preserveHistory === true && (input.title !== undefined || input.body !== undefined)) {
675
837
  const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
676
838
  if (current.number !== input.issueNumber || 'pull_request' in current)
677
839
  throw new DeliveryError('History target is not the requested issue.');
678
840
  const prior = { title: current.title, body: current.body ?? '' };
841
+ if (prior.title !== currentContent.title || prior.body !== currentContent.body)
842
+ throw new DeliveryError('Issue content changed after preparation; retry against the current title and body.');
679
843
  if ((input.title !== undefined && input.title !== prior.title) ||
680
844
  (input.body !== undefined && input.body !== prior.body)) {
681
845
  const body = renderIssueHistory(prior.title, prior.body);
@@ -685,14 +849,40 @@ export async function updateIssue(context, input) {
685
849
  if (body.length > ISSUE_COMMENT_BODY_LIMIT)
686
850
  throw new DeliveryError('Complete issue history exceeds the supported comment body limit; issue was not rewritten.');
687
851
  priorContent = prior;
688
- historyComment = await commentIssue(context, { issueNumber: input.issueNumber, body });
852
+ historyBody = body;
689
853
  }
690
854
  }
855
+ const closureBody = closeReason === undefined
856
+ ? undefined
857
+ : `Requested closure reason: ${closeReason}.${input.supersededBy === undefined ? '' : `\nSuperseded by ${repo.owner}/${repo.repo}#${String(input.supersededBy)}.`}`;
858
+ return {
859
+ input,
860
+ prepared,
861
+ acceptedLabels,
862
+ beforeAdd,
863
+ closeReason,
864
+ supersedingIssueId,
865
+ assertClosure,
866
+ currentContent,
867
+ priorContent,
868
+ historyBody,
869
+ closureBody,
870
+ };
871
+ }
872
+ export async function updateIssue(context, input) {
873
+ return applyIssueUpdate(context, await prepareIssueUpdate(context, input));
874
+ }
875
+ async function applyIssueUpdate(context, plan) {
876
+ const { clients, config, repo } = context;
877
+ const { input, prepared, acceptedLabels, beforeAdd, closeReason, supersedingIssueId, assertClosure, priorContent, historyBody, closureBody, } = plan;
878
+ const historyComment = historyBody === undefined
879
+ ? undefined
880
+ : await commentIssue(context, { issueNumber: input.issueNumber, body: historyBody });
691
881
  let closureComment;
692
- if (closeReason !== undefined)
882
+ if (closureBody !== undefined)
693
883
  closureComment = await commentIssue(context, {
694
884
  issueNumber: input.issueNumber,
695
- body: `Requested closure reason: ${closeReason}.${input.supersededBy === undefined ? '' : `\nSuperseded by ${repo.owner}/${repo.repo}#${String(input.supersededBy)}.`}`,
885
+ body: closureBody,
696
886
  });
697
887
  if (priorContent !== undefined) {
698
888
  const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
@@ -700,7 +890,7 @@ export async function updateIssue(context, input) {
700
890
  'pull_request' in current ||
701
891
  current.title !== priorContent.title ||
702
892
  (current.body ?? '') !== priorContent.body)
703
- throw new DeliveryError('Issue content changed after history readback; retry against the current title and body.');
893
+ throw new DeliveryError('Issue content changed after preparation; retry against the current title and body.');
704
894
  }
705
895
  await clients.rest.issues.update({
706
896
  issue_number: input.issueNumber,
@@ -776,15 +966,7 @@ export async function updateIssue(context, input) {
776
966
  throw new DeliveryError(`Issue #${input.issueNumber} content or metadata may have changed, but dependency tracking did not complete: ${error instanceof Error ? error.message : String(error)}. Inspect native state and resume this existing issue.`);
777
967
  }
778
968
  const info = await issueInfo(context, input.issueNumber);
779
- const status = info.state === 'closed' || info.projectStatus === 'Done'
780
- ? 'Done'
781
- : info.blockedBy.length > 0
782
- ? 'Blocked'
783
- : input.park === true || input.blockedBy !== undefined || info.projectStatus === null
784
- ? 'Todo'
785
- : info.projectStatus === 'In Progress' || (info.projectStatus === 'Blocked' && input.state === undefined)
786
- ? info.projectStatus
787
- : 'Todo';
969
+ const status = updateProjectStatus(info, input);
788
970
  const issue = (await clients.rest.issues.get({ issue_number: input.issueNumber, ...repo })).data;
789
971
  await syncIssueProjectStatus({
790
972
  graphql: clients.graphql,
@@ -811,9 +993,336 @@ export async function updateIssue(context, input) {
811
993
  : { closure: { ...closure, supersededBy: input.supersededBy ?? null, comment: closureComment } }),
812
994
  };
813
995
  }
996
+ /** Read-only inspection of the same authenticated closure journal used by updateIssue. */
997
+ async function hasUpdateComment(context, issueNumber, body) {
998
+ if (!context.clients.authenticatedAuthor)
999
+ throw new DeliveryError('Authenticated update journal author is missing.');
1000
+ const actor = (await context.clients.authenticatedAuthor()).actorLogin;
1001
+ if (!actor)
1002
+ throw new DeliveryError('Update journal author identity is missing.');
1003
+ const matches = [];
1004
+ let complete = false;
1005
+ for (let page = 1; page <= 20; page++) {
1006
+ const comments = (await context.clients.rest.issues.listComments({
1007
+ ...context.repo,
1008
+ issue_number: issueNumber,
1009
+ per_page: 100,
1010
+ page,
1011
+ })).data;
1012
+ matches.push(...comments.filter((comment) => comment.user?.login?.toLowerCase() === actor.toLowerCase() && comment.body === body));
1013
+ if (comments.length < 100) {
1014
+ complete = true;
1015
+ break;
1016
+ }
1017
+ }
1018
+ if (!complete)
1019
+ throw new DeliveryError('Update journal readback exceeds the bounded history window.');
1020
+ if (matches.length > 1)
1021
+ throw new DeliveryError('Issue comment has duplicate authored retry matches.');
1022
+ if (!matches[0])
1023
+ return false;
1024
+ await readAuthoredIssueComment(context, issueNumber, matches[0], body, actor);
1025
+ return true;
1026
+ }
1027
+ async function updateProjection(context, plan) {
1028
+ const { input } = plan;
1029
+ const readback = await issueInfo(context, input.issueNumber);
1030
+ const values = { ...readback };
1031
+ const relationships = async (issueNumber) => {
1032
+ const native = await getNativeBlockerRelationships({
1033
+ graphql: context.clients.graphql,
1034
+ repo: context.repo,
1035
+ issueNumber,
1036
+ requireRepositoryIdentity: true,
1037
+ });
1038
+ const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1039
+ const edges = [
1040
+ ...native.blockers,
1041
+ ...(native.parentNumber === null
1042
+ ? []
1043
+ : [{ number: native.parentNumber, id: native.parentId, repository: native.parentRepository }]),
1044
+ ];
1045
+ if (edges.some((edge) => edge.repository?.toLowerCase() !== repository))
1046
+ throw new DeliveryError('Native batch relationship belongs to a different repository.');
1047
+ const targets = await resolveNativeRelationshipTargets({
1048
+ blockers: edges.map((edge) => edge.number),
1049
+ repo: context.repo,
1050
+ rest: context.clients.rest,
1051
+ });
1052
+ if (edges.some((edge) => edge.id !== targets.blockerNodeIds.get(edge.number)))
1053
+ throw new DeliveryError('Native batch relationship node identity disagrees with its repository issue.');
1054
+ return native;
1055
+ };
1056
+ if (input.blockedBy !== undefined || input.parentIssueNumber !== undefined) {
1057
+ const native = await relationships(input.issueNumber);
1058
+ if (native.parentNumber !== readback.parentIssueNumber)
1059
+ throw new DeliveryError('Native parent changed during batch readback; reconcile the current state.');
1060
+ if (input.blockedBy !== undefined)
1061
+ values.blockedBy = native.blockers.map((value) => value.number).sort((a, b) => a - b);
1062
+ }
1063
+ if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null) {
1064
+ const metadata = await getConfiguredNativeIssueMetadata({
1065
+ issueNumber: input.parentIssueNumber,
1066
+ ...context.repo,
1067
+ rest: context.clients.rest,
1068
+ settings: nativeIssueSettingsFromDeliveryConfig(context.config),
1069
+ });
1070
+ values.parentPoints = { issueNumber: input.parentIssueNumber, points: metadata.points ?? null };
1071
+ }
1072
+ if (input.blocks !== undefined) {
1073
+ values.blocks = await Promise.all([...new Set(input.blocks)].map(async (dependent) => ({
1074
+ issueNumber: dependent,
1075
+ linked: (await relationships(dependent)).blockers.some((value) => value.number === input.issueNumber),
1076
+ })));
1077
+ }
1078
+ if (plan.closeReason !== undefined) {
1079
+ const closure = await readIssueClosure(context, input.issueNumber);
1080
+ values.closeReason = closure.closeReason;
1081
+ if (plan.closeReason === 'duplicate' && input.supersededBy !== undefined)
1082
+ values.supersededBy = closure.duplicateOf?.number ?? null;
1083
+ values.closureComment = await hasUpdateComment(context, input.issueNumber, plan.closureBody);
1084
+ }
1085
+ return { readback, values };
1086
+ }
1087
+ async function desiredUpdateValues(context, plan) {
1088
+ const { input } = plan;
1089
+ const values = {};
1090
+ for (const key of [
1091
+ 'title',
1092
+ 'body',
1093
+ 'issueType',
1094
+ 'points',
1095
+ 'priority',
1096
+ 'milestone',
1097
+ 'state',
1098
+ 'parentIssueNumber',
1099
+ ]) {
1100
+ if (input[key] !== undefined)
1101
+ values[key] = input[key];
1102
+ }
1103
+ if (plan.acceptedLabels !== undefined)
1104
+ values.labels = [...plan.acceptedLabels].sort();
1105
+ let openBlockers = plan.currentContent.blockedBy;
1106
+ if (input.blockedBy !== undefined) {
1107
+ values.blockedBy = [...new Set(input.blockedBy)].sort((a, b) => a - b);
1108
+ const targets = await Promise.all(input.blockedBy.map(async (number) => (await context.clients.rest.issues.get({ ...context.repo, issue_number: number })).data));
1109
+ openBlockers = targets.filter((target) => target.state === 'open').map((target) => target.number);
1110
+ }
1111
+ values.projectStatus = updateProjectStatus({
1112
+ ...plan.currentContent,
1113
+ state: input.state ?? plan.currentContent.state,
1114
+ blockedBy: openBlockers,
1115
+ }, input);
1116
+ if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null)
1117
+ values.parentPoints = { issueNumber: input.parentIssueNumber, points: null };
1118
+ if (input.blocks !== undefined)
1119
+ values.blocks = [...new Set(input.blocks)].map((issueNumber) => ({ issueNumber, linked: true }));
1120
+ if (plan.closeReason !== undefined) {
1121
+ values.closeReason = plan.closeReason;
1122
+ if (plan.closeReason === 'duplicate' && input.supersededBy !== undefined)
1123
+ values.supersededBy = input.supersededBy;
1124
+ values.closureComment = true;
1125
+ }
1126
+ return values;
1127
+ }
1128
+ function pendingUpdateValues(desired, actual) {
1129
+ const labels = (value) => Array.isArray(value) && value.every((label) => typeof label === 'string')
1130
+ ? value.map((label) => label.toLowerCase()).sort()
1131
+ : value;
1132
+ return Object.fromEntries(Object.entries(desired).filter(([key, value]) => JSON.stringify(key === 'labels' ? labels(value) : value) !==
1133
+ JSON.stringify(key === 'labels' ? labels(actual[key]) : actual[key])));
1134
+ }
1135
+ function localBatchFailureReason(error) {
1136
+ if (typeof error !== 'object' || error === null || types.isProxy(error))
1137
+ return undefined;
1138
+ const prototype = Object.getPrototypeOf(error);
1139
+ if (prototype === IssueValidationError.prototype)
1140
+ return 'Requested issue fields do not satisfy the issue contract.';
1141
+ if (prototype !== DeliveryError.prototype)
1142
+ return undefined;
1143
+ const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
1144
+ const message = descriptor && 'value' in descriptor ? descriptor.value : undefined;
1145
+ if (typeof message !== 'string')
1146
+ return undefined;
1147
+ if ([
1148
+ 'Choose a valid defer condition or explicit undefer, never both.',
1149
+ 'Use defer or undefer to change deferral state.',
1150
+ 'Choose native blockedBy or display-only status.blockers in one update, not both.',
1151
+ 'Convert the legacy contract explicitly before a status-only update.',
1152
+ 'Issue labels must be non-empty and unique.',
1153
+ 'Repository label listing exceeds the bounded readback window.',
1154
+ 'Unsupported configured Issue Type.',
1155
+ 'Unsupported configured Points value.',
1156
+ 'Unsupported configured Priority value.',
1157
+ 'Closure details require state closed and a supported close reason.',
1158
+ 'A superseding issue must be a different positive issue number.',
1159
+ 'Superseding issue readback is not the requested repository issue.',
1160
+ 'Issue is already closed with different closure evidence; reopen it explicitly first.',
1161
+ 'Native closure readback disagrees with the requested reason or superseding issue.',
1162
+ 'Native closure readback returned a foreign issue identity.',
1163
+ 'Native closure readback has contradictory state evidence.',
1164
+ 'History target is not the requested issue.',
1165
+ 'Issue content changed after preparation; retry against the current title and body.',
1166
+ 'Complete issue history exceeds the supported comment body limit; issue was not rewritten.',
1167
+ 'Issue update readback disagrees with the requested content or state.',
1168
+ 'Issue comments require the authenticated author role.',
1169
+ 'Issue comment author identity is missing.',
1170
+ 'Issue comment target is not the requested issue.',
1171
+ 'Issue comment history exceeds the bounded readback window.',
1172
+ 'Issue comment has duplicate authored retry matches.',
1173
+ 'Issue comment conflicts with its authored operation marker.',
1174
+ 'Issue comment readback disagrees with the authored issue comment.',
1175
+ 'Authenticated update journal author is missing.',
1176
+ 'Update journal author identity is missing.',
1177
+ 'Update journal readback exceeds the bounded history window.',
1178
+ 'An issue cannot be its own parent or blocker.',
1179
+ 'Native blockers must be unique.',
1180
+ 'Native Points and Priority catalogs must select distinct issue fields.',
1181
+ 'Dependency endpoint must be a positive issue number.',
1182
+ 'Dependency endpoint is not the requested repository issue.',
1183
+ 'Dependency writes require configured author authority.',
1184
+ 'Dependency author identity is unavailable.',
1185
+ 'An issue cannot block itself.',
1186
+ 'Dependency removal episode is ambiguous.',
1187
+ 'Complete dependency history is required for an active blocker override.',
1188
+ 'Override comment author, body or issue readback disagrees; native dependency was not added.',
1189
+ 'Override comment search is incomplete or has duplicate authoritative markers.',
1190
+ 'Override comment evidence is malformed.',
1191
+ 'Existing override comment conflicts with the requested reason or endpoint evidence.',
1192
+ 'Native batch relationship belongs to a different repository.',
1193
+ 'Native batch relationship node identity disagrees with its repository issue.',
1194
+ 'Native parent changed during batch readback; reconcile the current state.',
1195
+ 'Native issue changed during batch preparation; reconcile the current state.',
1196
+ 'Native batch readback disagrees with the requested outcomes.',
1197
+ ].includes(message))
1198
+ return message;
1199
+ if (message.startsWith('Unknown repository label(s): '))
1200
+ return 'One or more requested labels do not exist in the selected repository.';
1201
+ if (/^Adding a blocker to active issue #\d+ requires overrideReason\.$/u.test(message))
1202
+ return 'Adding a blocker to an active issue requires overrideReason.';
1203
+ if (/^Project status for dependent #\d+ is unresolved; dependency additions were refused\.$/u.test(message))
1204
+ return 'Project status for a dependent is unresolved; dependency additions were refused.';
1205
+ if (message.startsWith('Complete dependency history is required for an active blocker override: '))
1206
+ return 'Complete dependency history is required for an active blocker override.';
1207
+ if (/^Issue #\d+ content or metadata may have changed, but dependency tracking did not complete: /u.test(message))
1208
+ return 'Issue content or metadata may have changed, but dependency tracking did not complete. Inspect native state and resume this existing issue.';
1209
+ return undefined;
1210
+ }
1211
+ /** One serial operation; each application uses the existing single-update mutation owner. */
1212
+ export async function batchUpdateIssues(context, input, signal) {
1213
+ if (context.clients.role !== 'author')
1214
+ throw new DeliveryError('Batch updates require the configured author role.');
1215
+ if (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > 50)
1216
+ throw new DeliveryError('Provide 1–50 batch items.');
1217
+ const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1218
+ if (input.items.some((item) => item.repo !== undefined && item.repo.toLowerCase() !== repository))
1219
+ throw new DeliveryError('Every batch item must use the selected repository.');
1220
+ const results = [];
1221
+ const rateLimits = [];
1222
+ const priorRateObservation = context.clients.rateLimitObservation?.();
1223
+ let limited = false;
1224
+ for (const { repo: _repo, ...item } of input.items) {
1225
+ if (limited || signal?.aborted) {
1226
+ results.push({
1227
+ issueNumber: item.issueNumber,
1228
+ status: 'failed',
1229
+ reason: limited ? 'Not attempted: GitHub rate limit exhausted.' : 'Not attempted: operation cancelled.',
1230
+ readback: null,
1231
+ readbackError: 'No new readback requested after rate-limit exhaustion or cancellation.',
1232
+ });
1233
+ continue;
1234
+ }
1235
+ let phase = 'preparation';
1236
+ try {
1237
+ const plan = await prepareIssueUpdate(context, item);
1238
+ const desired = await desiredUpdateValues(context, plan);
1239
+ const before = await updateProjection(context, plan);
1240
+ if (JSON.stringify(before.readback) !== JSON.stringify(plan.currentContent))
1241
+ throw new DeliveryError('Native issue changed during batch preparation; reconcile the current state.');
1242
+ if (context.clients.rateLimitObservation?.() !== priorRateObservation)
1243
+ throw new DeliveryError('A native request exhausted its rate limit during batch preparation.');
1244
+ const changes = pendingUpdateValues(desired, before.values);
1245
+ if (Object.keys(changes).length === 0 || input.dryRun === true) {
1246
+ results.push({
1247
+ issueNumber: item.issueNumber,
1248
+ status: Object.keys(changes).length === 0 ? 'unchanged' : 'planned',
1249
+ changes,
1250
+ readback: before.readback,
1251
+ relatedReadback: before.values,
1252
+ });
1253
+ continue;
1254
+ }
1255
+ phase = 'application';
1256
+ await applyIssueUpdate(context, {
1257
+ ...plan,
1258
+ priorContent: { title: before.readback.title, body: before.readback.body },
1259
+ });
1260
+ phase = 'readback';
1261
+ const after = await updateProjection(context, plan);
1262
+ if (Object.keys(pendingUpdateValues(desired, after.values)).length)
1263
+ throw new DeliveryError('Native batch readback disagrees with the requested outcomes.');
1264
+ results.push({
1265
+ issueNumber: item.issueNumber,
1266
+ status: 'applied',
1267
+ changes,
1268
+ readback: after.readback,
1269
+ relatedReadback: after.values,
1270
+ });
1271
+ }
1272
+ catch (error) {
1273
+ const observed = context.clients.rateLimitObservation?.();
1274
+ const limit = getRateLimitDiagnostics(error) ?? (observed !== priorRateObservation ? observed : undefined);
1275
+ if (limit !== undefined) {
1276
+ limited = true;
1277
+ rateLimits.push(limit);
1278
+ }
1279
+ const diagnostics = getMachineRequestDiagnostics(error);
1280
+ const failed = {
1281
+ issueNumber: item.issueNumber,
1282
+ status: 'failed',
1283
+ readback: null,
1284
+ reason: limit !== undefined
1285
+ ? 'GitHub rate limit exhausted; reconcile native state before retrying.'
1286
+ : (localBatchFailureReason(error) ??
1287
+ `Issue update ${phase} failed; inspect native readback before retrying.`),
1288
+ ...(diagnostics === undefined ? {} : { diagnostics }),
1289
+ };
1290
+ if (!limited && !signal?.aborted) {
1291
+ try {
1292
+ failed.readback = await issueInfo(context, item.issueNumber);
1293
+ }
1294
+ catch (readbackError) {
1295
+ const latest = context.clients.rateLimitObservation?.();
1296
+ const readbackLimit = getRateLimitDiagnostics(readbackError) ?? (latest !== priorRateObservation ? latest : undefined);
1297
+ if (readbackLimit !== undefined) {
1298
+ limited = true;
1299
+ rateLimits.push(readbackLimit);
1300
+ }
1301
+ failed.readbackError = 'Native issue readback unavailable; reconcile this existing issue before retrying.';
1302
+ }
1303
+ }
1304
+ else
1305
+ failed.readbackError = 'Readback deferred after rate-limit exhaustion or cancellation.';
1306
+ results.push(failed);
1307
+ }
1308
+ }
1309
+ return {
1310
+ dryRun: input.dryRun === true,
1311
+ results,
1312
+ summary: {
1313
+ total: results.length,
1314
+ applied: results.filter((item) => item.status === 'applied').length,
1315
+ planned: results.filter((item) => item.status === 'planned').length,
1316
+ unchanged: results.filter((item) => item.status === 'unchanged').length,
1317
+ failed: results.filter((item) => item.status === 'failed').length,
1318
+ rateLimits,
1319
+ },
1320
+ };
1321
+ }
814
1322
  /** Complete the native tracking and Project state of an issue created before an interrupted response. */
815
1323
  export async function resumeCreatedIssue(context, input) {
816
- return updateIssue(context, input);
1324
+ // Tracking recovery must not trigger an unrelated first render omission and change the retry intent.
1325
+ return updateIssue(context, { ...input, preserveHistory: input.preserveHistory ?? false });
817
1326
  }
818
1327
  export async function issueInfo(context, issueNumber) {
819
1328
  const { clients, config, repo } = context;
@@ -838,6 +1347,7 @@ export async function issueInfo(context, issueNumber) {
838
1347
  }),
839
1348
  ]);
840
1349
  const info = {
1350
+ ...deferralReadback(issue.body, issue.title),
841
1351
  ...(context.configuration ? { routing: context.configuration.routing } : {}),
842
1352
  blockedBy: relationships.blockers.filter((blocker) => blocker.state === 'OPEN').map((blocker) => blocker.number),
843
1353
  body: issue.body ?? '',
@@ -856,6 +1366,19 @@ export async function issueInfo(context, issueNumber) {
856
1366
  };
857
1367
  return info;
858
1368
  }
1369
+ /** Invalid canonical content stays inspectable; omitted state is unknown, never an assertion of undeferred. */
1370
+ function deferralReadback(body, title) {
1371
+ if (body === undefined)
1372
+ return {};
1373
+ try {
1374
+ return { deferred: parseIssueBody(body ?? '', { title }).issue.deferral ?? null };
1375
+ }
1376
+ catch (error) {
1377
+ if (!(error instanceof IssueValidationError))
1378
+ throw error;
1379
+ return {};
1380
+ }
1381
+ }
859
1382
  export async function listIssueSubissues(context, issueNumber) {
860
1383
  const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
861
1384
  if ('pull_request' in issue)
@@ -950,7 +1473,7 @@ export async function startIssueBranch(context, issueNumber, selected) {
950
1473
  return { issueNumber, issueUrl: issue.html_url, branch: name, headSha: base, reused: false };
951
1474
  }
952
1475
  /** Recheck native eligibility before an explicit start changes its selected Project. */
953
- export async function startIssueProject(context, issueNumber) {
1476
+ export async function startIssueProject(context, issueNumber, overrideReason) {
954
1477
  const readiness = await readyCheck(context, issueNumber);
955
1478
  if (!readiness.ready)
956
1479
  throw new IssueValidationError(readiness.failures);
@@ -964,6 +1487,121 @@ export async function startIssueProject(context, issueNumber) {
964
1487
  ...(context.projectConfiguration === undefined ? {} : { configuration: context.projectConfiguration }),
965
1488
  settings: projectSettingsFromDeliveryConfig(context.config),
966
1489
  status: 'In Progress',
1490
+ beforeAdvance: async () => {
1491
+ const eligible = await readyCheck(context, issueNumber);
1492
+ if (!eligible.ready)
1493
+ throw new IssueValidationError(eligible.failures);
1494
+ await assertIssueStartCapacity(context, issueNumber, overrideReason, true);
1495
+ const current = await issueInfo(context, issueNumber);
1496
+ if (current.state !== 'open')
1497
+ throw new DeliveryError('Start requires the requested open issue.');
1498
+ const finalEligibility = await readyCheck(context, issueNumber);
1499
+ if (!finalEligibility.ready)
1500
+ throw new IssueValidationError(finalEligibility.failures);
1501
+ },
967
1502
  });
968
1503
  }
1504
+ /** A complete observed-capacity guard, not a cross-writer GitHub transaction. */
1505
+ export async function assertIssueStartCapacity(context, issueNumber, overrideReason, recordOverride = false) {
1506
+ const lanes = WipLimits.parse(context.config.wipLimits ?? []).filter((lane) => lane.repository.toLowerCase() === context.config.repository.toLowerCase());
1507
+ if (!lanes.length)
1508
+ return undefined;
1509
+ const configuration = context.projectConfiguration ??
1510
+ (await getProjectDeliveryConfiguration({
1511
+ graphql: context.clients.graphql,
1512
+ org: context.config.native.organization,
1513
+ settings: projectSettingsFromDeliveryConfig(context.config),
1514
+ }));
1515
+ const capacityContext = { ...context, projectConfiguration: configuration };
1516
+ const reason = overrideReason === undefined ? undefined : OverrideReason.parse(overrideReason);
1517
+ const publicReason = validateIssue({ title: 'WIP capacity override', legacyBody: reason ?? '', draft: true }, false);
1518
+ if (publicReason.failures.length)
1519
+ throw new IssueValidationError(publicReason.failures);
1520
+ if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
1521
+ throw new DeliveryError('WIP capacity repository identity disagrees with the selected repository.');
1522
+ const configuredLabels = lanes.flatMap((lane) => ('label' in lane.match ? [lane.match.label] : []));
1523
+ if (configuredLabels.length)
1524
+ await labels(context, [...new Map(configuredLabels.map((label) => [label.toLowerCase(), label])).values()]);
1525
+ const rows = [];
1526
+ const seen = new Set();
1527
+ for (let page = 1;; page++) {
1528
+ if (page > 20)
1529
+ throw new DeliveryError('WIP capacity issue pagination is incomplete.');
1530
+ const batch = await listIssues(capacityContext, { state: 'open', page, perPage: 100 }, { capacityRead: true });
1531
+ for (const row of batch.issues) {
1532
+ if (seen.has(row.number))
1533
+ throw new DeliveryError('WIP capacity repeats a native issue across pages.');
1534
+ seen.add(row.number);
1535
+ rows.push(row);
1536
+ }
1537
+ if (batch.nextPage === null)
1538
+ break;
1539
+ if (batch.nextPage !== page + 1)
1540
+ throw new DeliveryError('WIP capacity pagination did not advance.');
1541
+ }
1542
+ const target = rows.find((row) => row.number === issueNumber);
1543
+ if (!target?.nodeId)
1544
+ throw new DeliveryError('WIP capacity target is missing from the complete native issue readback.');
1545
+ const matches = (lane, row) => {
1546
+ if ('label' in lane.match) {
1547
+ const selected = lane.match.label;
1548
+ return row.labels.some((label) => label.toLowerCase() === selected.toLowerCase());
1549
+ }
1550
+ const { field, value } = lane.match;
1551
+ if (!row.fieldIds?.[field] || row.fieldIds[field] !== target.fieldIds?.[field] || !Object.hasOwn(row.fields, field))
1552
+ throw new DeliveryError(`WIP capacity native field ${field} is unknown or changed identity.`);
1553
+ const observed = row.fields[field];
1554
+ return Array.isArray(observed) ? typeof value === 'string' && observed.includes(value) : observed === value;
1555
+ };
1556
+ const observations = lanes.flatMap((lane) => {
1557
+ // Validate every configured field across the full snapshot, even when the target does not match it.
1558
+ const matching = rows.filter((row) => matches(lane, row));
1559
+ if (!matches(lane, target))
1560
+ return [];
1561
+ const count = matching.filter((row) => row.projectStatus === 'In Progress').length;
1562
+ return [
1563
+ {
1564
+ name: lane.name,
1565
+ match: lane.match,
1566
+ ...('field' in lane.match ? { fieldId: target.fieldIds[lane.match.field] } : {}),
1567
+ count,
1568
+ limit: lane.limit,
1569
+ },
1570
+ ];
1571
+ });
1572
+ const exceeded = target.projectStatus === 'In Progress' ? [] : observations.filter((lane) => lane.count + 1 > lane.limit);
1573
+ if (exceeded.length && reason === undefined)
1574
+ throw new DeliveryError(`WIP capacity limit exceeded: ${exceeded.map((lane) => `${lane.name} (${lane.count}/${lane.limit})`).join(', ')}. Supply overrideReason for a recorded capacity exception.`);
1575
+ const evidence = {
1576
+ schema: 'ai-delivery.wip-override@1',
1577
+ repository: context.config.repository,
1578
+ projectId: configuration.projectId,
1579
+ issue: { number: issueNumber, id: target.nodeId },
1580
+ observedStatus: target.projectStatus,
1581
+ lanes: observations,
1582
+ };
1583
+ if (!evidence.projectId)
1584
+ throw new DeliveryError('WIP capacity configured Project identity is unavailable.');
1585
+ const snapshot = JSON.stringify(evidence);
1586
+ if (exceeded.length && recordOverride) {
1587
+ if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor)
1588
+ throw new DeliveryError('WIP capacity override requires the authenticated configured author.');
1589
+ const author = await context.clients.authenticatedAuthor();
1590
+ if (!author.actorLogin || !author.credentialIdentity)
1591
+ throw new DeliveryError('WIP capacity author identity is incomplete.');
1592
+ const record = { ...evidence, author: author.actorLogin, reason };
1593
+ const marker = `<!-- ai-delivery:wip-override@1:${digestValue(record)} -->`;
1594
+ const body = `WIP capacity override.\n\n\`\`\`json\n${JSON.stringify(record, null, 2)}\n\`\`\`\n\n${marker}`;
1595
+ const publicRecord = validateIssue({ title: 'WIP capacity override', legacyBody: body, draft: true }, false);
1596
+ if (publicRecord.failures.length)
1597
+ throw new IssueValidationError(publicRecord.failures);
1598
+ await writeAuthenticatedIssueComment(context, { issueNumber, body }, undefined, marker);
1599
+ const finalAuthor = await context.clients.authenticatedAuthor();
1600
+ if (finalAuthor.actorLogin !== author.actorLogin || finalAuthor.credentialIdentity !== author.credentialIdentity)
1601
+ throw new DeliveryError('WIP capacity override author changed during comment verification.');
1602
+ if ((await assertIssueStartCapacity(context, issueNumber, reason)) !== snapshot)
1603
+ throw new DeliveryError('WIP capacity changed while recording the override; inspect native state and resume this issue.');
1604
+ }
1605
+ return snapshot;
1606
+ }
969
1607
  //# sourceMappingURL=issue.js.map