@aviaratech/ai-delivery 0.3.32 → 0.3.34

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 (99) hide show
  1. package/README.md +138 -6
  2. package/dist/cli.js +30 -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/inertEntrypoints.js +7 -0
  23. package/dist/fixtures/inertEntrypoints.js.map +1 -1
  24. package/dist/fixtures/inertTarget.d.ts +5 -0
  25. package/dist/fixtures/issue63.d.ts +11 -0
  26. package/dist/fixtures/issue63.js +16 -9
  27. package/dist/fixtures/issue63.js.map +1 -1
  28. package/dist/github/client.d.ts +3 -0
  29. package/dist/github/client.js +21 -10
  30. package/dist/github/client.js.map +1 -1
  31. package/dist/github/commandIdentityPolicy.js +1 -0
  32. package/dist/github/commandIdentityPolicy.js.map +1 -1
  33. package/dist/github/machineAuth.test.js +20 -0
  34. package/dist/github/machineAuth.test.js.map +1 -1
  35. package/dist/github/nativeIssueMetadata.d.ts +27 -0
  36. package/dist/github/nativeIssueMetadata.js +58 -0
  37. package/dist/github/nativeIssueMetadata.js.map +1 -1
  38. package/dist/github/projectDelivery.d.ts +3 -0
  39. package/dist/github/projectDelivery.js +44 -12
  40. package/dist/github/projectDelivery.js.map +1 -1
  41. package/dist/issue.d.ts +58 -7
  42. package/dist/issue.js +786 -108
  43. package/dist/issue.js.map +1 -1
  44. package/dist/issueBatchUpdate.test.d.ts +1 -0
  45. package/dist/issueBatchUpdate.test.js +730 -0
  46. package/dist/issueBatchUpdate.test.js.map +1 -0
  47. package/dist/issueBlockerGuard.test.js +78 -0
  48. package/dist/issueBlockerGuard.test.js.map +1 -1
  49. package/dist/issueContract.d.ts +68 -2
  50. package/dist/issueContract.js +101 -9
  51. package/dist/issueContract.js.map +1 -1
  52. package/dist/issueContract.test.d.ts +5 -0
  53. package/dist/issueContract.test.js +28 -1
  54. package/dist/issueContract.test.js.map +1 -1
  55. package/dist/issueDates.test.d.ts +1 -0
  56. package/dist/issueDates.test.js +253 -0
  57. package/dist/issueDates.test.js.map +1 -0
  58. package/dist/issueIntake.test.js +972 -19
  59. package/dist/issueIntake.test.js.map +1 -1
  60. package/dist/issueJournal.js +12 -8
  61. package/dist/issueJournal.js.map +1 -1
  62. package/dist/issueJournal.test.js +138 -0
  63. package/dist/issueJournal.test.js.map +1 -1
  64. package/dist/mcp/index.js +20 -2
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/tools.d.ts +110 -12
  67. package/dist/mcp/tools.js +53 -34
  68. package/dist/mcp/tools.js.map +1 -1
  69. package/dist/pr.d.ts +7 -0
  70. package/dist/pr.js +104 -99
  71. package/dist/pr.js.map +1 -1
  72. package/dist/pr.test.js +202 -223
  73. package/dist/pr.test.js.map +1 -1
  74. package/dist/prAssociation.test.js +11 -10
  75. package/dist/prAssociation.test.js.map +1 -1
  76. package/dist/review.d.ts +1 -0
  77. package/dist/review.js +7 -6
  78. package/dist/review.js.map +1 -1
  79. package/dist/review.test.js +8 -4
  80. package/dist/review.test.js.map +1 -1
  81. package/dist/services/agentReadinessService.js +2 -0
  82. package/dist/services/agentReadinessService.js.map +1 -1
  83. package/dist/setup.test.js +175 -4
  84. package/dist/setup.test.js.map +1 -1
  85. package/dist/stdoutRegression.test.js +22 -0
  86. package/dist/stdoutRegression.test.js.map +1 -1
  87. package/dist/targetPolicyRoutes.test.js +2 -2
  88. package/dist/targetPolicyRoutes.test.js.map +1 -1
  89. package/dist/verification.js +26 -0
  90. package/dist/verification.js.map +1 -1
  91. package/dist/verificationGate.test.js +25 -2
  92. package/dist/verificationGate.test.js.map +1 -1
  93. package/package.json +1 -1
  94. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  95. package/plugins/ai-delivery/plugin.json +1 -1
  96. package/plugins/ai-delivery/runtime/dist/cli.js +68 -56
  97. package/plugins/ai-delivery/runtime/package.json +1 -1
  98. package/plugins/ai-delivery/skills/intake-create/SKILL.md +22 -2
  99. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +4 -4
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
- import { NATIVE_ISSUE_API_VERSION, clearConfiguredNativeIssuePoints, getConfiguredNativeIssueMetadata, nativeIssueSettingsFromDeliveryConfig, setConfiguredNativeIssueMetadata, } from './github/nativeIssueMetadata.js';
7
- import { getIssueProjectStatus, projectSettingsFromDeliveryConfig, syncIssueProjectStatus, } from './github/projectDelivery.js';
7
+ import { NATIVE_ISSUE_API_VERSION, applyNativeIssueDates, prepareNativeIssueDates, parseConfiguredNativeIssueMetadata, clearConfiguredNativeIssuePoints, getConfiguredNativeIssueMetadata, nativeIssueSettingsFromDeliveryConfig, setConfiguredNativeIssueMetadata, } from './github/nativeIssueMetadata.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;
@@ -202,6 +287,7 @@ export async function createIssue(context, input) {
202
287
  if (context.clients.role !== 'author')
203
288
  throw new DeliveryError('Issue writes require the configured author role.');
204
289
  const prepared = prepareIssueWrite(input);
290
+ const dateChanges = await prepareIssueDates(context, input);
205
291
  input = {
206
292
  ...input,
207
293
  title: prepared.issue.title,
@@ -261,6 +347,7 @@ export async function createIssue(context, input) {
261
347
  rest: clients.rest,
262
348
  settings: nativeIssueSettingsFromDeliveryConfig(config),
263
349
  });
350
+ await applyNativeIssueDates({ changes: dateChanges, issueNumber, ...repo, rest: clients.rest });
264
351
  if (input.parentIssueNumber !== undefined)
265
352
  await replaceParentIssue({
266
353
  graphql: clients.graphql,
@@ -341,16 +428,43 @@ const ListedIssue = z.object({
341
428
  number: z.number().int().positive().safe(),
342
429
  node_id: z.string().min(1),
343
430
  title: z.string(),
431
+ body: z.string().nullable().optional(),
344
432
  state: z.enum(['open', 'closed']),
345
433
  labels: z.array(z.union([z.string(), z.object({ name: z.string() })])),
346
434
  type: z.object({ name: z.string() }).nullable().optional(),
347
435
  html_url: z.url(),
348
436
  updated_at: z.iso.datetime({ offset: true }),
349
437
  });
350
- async function issueFieldPages(context, route, parameters) {
438
+ function capacityNextPage(response, page, perPage) {
439
+ if (!Array.isArray(response.data) || response.data.length > perPage)
440
+ throw new DeliveryError('WIP capacity pagination returned invalid native data.');
441
+ const link = response.headers?.link;
442
+ if (link === undefined || link === '')
443
+ return response.data.length === perPage ? page + 1 : null;
444
+ const parts = [...link.matchAll(/<([^>]+)>;\s*rel="([^"]+)"/gu)];
445
+ const next = parts.filter((part) => part[2] === 'next');
446
+ const residue = link.replace(/<([^>]+)>;\s*rel="([^"]+)"/gu, '').replace(/[,\s]/gu, '');
447
+ if (!parts.length ||
448
+ residue ||
449
+ next.length > 1 ||
450
+ parts.some((part) => !['first', 'prev', 'next', 'last'].includes(part[2])))
451
+ throw new DeliveryError('WIP capacity native pagination is malformed.');
452
+ if (!next.length)
453
+ return null;
454
+ const url = new URL(next[0][1]);
455
+ if (url.protocol !== 'https:' ||
456
+ url.hostname !== 'api.github.com' ||
457
+ url.searchParams.get('page') !== String(page + 1) ||
458
+ url.searchParams.get('per_page') !== String(perPage))
459
+ throw new DeliveryError('WIP capacity native pagination did not advance consistently.');
460
+ return page + 1;
461
+ }
462
+ async function issueFieldPages(context, route, parameters, maxPages) {
351
463
  const values = [];
352
464
  const seenPages = new Set();
353
465
  for (let page = 1;; page += 1) {
466
+ if (maxPages !== undefined && page > maxPages)
467
+ throw new DeliveryError('WIP capacity native field pagination is incomplete.');
354
468
  const response = await context.clients.rest.request(route, {
355
469
  ...parameters,
356
470
  headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
@@ -364,12 +478,86 @@ async function issueFieldPages(context, route, parameters) {
364
478
  throw new DeliveryError('Native issue fields repeated a pagination page.');
365
479
  seenPages.add(fingerprint);
366
480
  values.push(...response.data);
367
- if (response.data.length < 100)
481
+ if (maxPages === undefined ? response.data.length < 100 : capacityNextPage(response, page, 100) === null)
368
482
  return values;
369
483
  }
370
484
  }
485
+ async function readIssueFieldCatalog(context, capacityRead = false) {
486
+ const catalog = z
487
+ .array(FieldCatalogEntry)
488
+ .parse(await issueFieldPages(context, 'GET /orgs/{org}/issue-fields', { org: context.config.native.organization }, capacityRead ? 20 : undefined));
489
+ if (new Set(catalog.map((field) => field.name)).size !== catalog.length ||
490
+ new Set(catalog.map((field) => field.id)).size !== catalog.length)
491
+ throw new DeliveryError('Native issue field catalog has duplicate identities or names.');
492
+ return catalog;
493
+ }
494
+ async function readIssueFields(context, issueNumber, catalog, capacityRead = false) {
495
+ const fields = Object.fromEntries(catalog.map((field) => [field.name, null]));
496
+ const values = z.array(FieldValueEntry).parse(await issueFieldPages(context, 'GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {
497
+ ...context.repo,
498
+ issue_number: issueNumber,
499
+ }, capacityRead ? 20 : undefined));
500
+ const observed = new Set();
501
+ for (const field of values) {
502
+ const definition = catalog.find((candidate) => candidate.id === field.issue_field_id);
503
+ if (!definition ||
504
+ definition.name !== field.issue_field_name ||
505
+ definition.data_type !== field.data_type ||
506
+ observed.has(field.issue_field_id))
507
+ throw new DeliveryError('Native issue field readback conflicts with its catalog.');
508
+ observed.add(field.issue_field_id);
509
+ if (capacityRead &&
510
+ (field.data_type === 'single_select'
511
+ ? field.single_select_option === undefined && field.value !== null
512
+ : field.data_type === 'multi_select'
513
+ ? field.multi_select_options === undefined && field.value !== null
514
+ : field.value === undefined))
515
+ throw new DeliveryError('WIP capacity native field value payload is missing.');
516
+ // Existing issue-info metadata accepts configured option names as raw values.
517
+ // Preserve that exact compatibility without treating numeric option IDs as names.
518
+ const configuredOptionName = !capacityRead &&
519
+ field.data_type === 'single_select' &&
520
+ typeof field.value === 'string' &&
521
+ ((field.issue_field_name === context.config.native.points.name &&
522
+ String(field.issue_field_id) === context.config.native.points.databaseId &&
523
+ context.config.native.points.values.includes(field.value)) ||
524
+ (field.issue_field_name === context.config.native.priority.name &&
525
+ String(field.issue_field_id) === context.config.native.priority.databaseId &&
526
+ context.config.native.priority.values.includes(field.value)))
527
+ ? field.value
528
+ : undefined;
529
+ if (((field.data_type === 'single_select' && !field.single_select_option && configuredOptionName === undefined) ||
530
+ (field.data_type === 'multi_select' && field.multi_select_options === undefined)) &&
531
+ field.value !== null &&
532
+ field.value !== undefined)
533
+ throw new DeliveryError('Native select field omitted its named option readback.');
534
+ const value = field.data_type === 'single_select'
535
+ ? (field.single_select_option?.name ?? configuredOptionName ?? null)
536
+ : field.data_type === 'multi_select'
537
+ ? field.multi_select_options?.map((option) => option.name)
538
+ : field.value;
539
+ if (field.data_type === 'date' && value !== null && value !== undefined && !z.iso.date().safeParse(value).success)
540
+ throw new DeliveryError('Native date field has an invalid date value.');
541
+ if (value === null || value === undefined)
542
+ fields[definition.name] = null;
543
+ else if (field.data_type === 'number'
544
+ ? typeof value === 'number' && Number.isFinite(value)
545
+ : field.data_type === 'multi_select'
546
+ ? Array.isArray(value)
547
+ : typeof value === 'string')
548
+ fields[definition.name] = value;
549
+ else
550
+ throw new DeliveryError('Native issue field has an invalid value type.');
551
+ }
552
+ return { fields, values, catalog };
553
+ }
554
+ async function prepareIssueDates(context, patch) {
555
+ if (patch.startDate === undefined && patch.targetDate === undefined)
556
+ return [];
557
+ return prepareNativeIssueDates(patch, await readIssueFieldCatalog(context));
558
+ }
371
559
  /** A bounded GitHub page; local filters can produce an empty page with a nextPage. */
372
- export async function listIssues(context, input) {
560
+ export async function listIssues(context, input, options = {}) {
373
561
  const page = input.page ?? 1;
374
562
  const perPage = input.perPage ?? 30;
375
563
  if (!Number.isSafeInteger(page) || page <= 0 || !Number.isSafeInteger(perPage) || perPage <= 0 || perPage > 100)
@@ -407,7 +595,7 @@ export async function listIssues(context, input) {
407
595
  nextPage = page * perPage < response.total_count ? page + 1 : null;
408
596
  }
409
597
  else {
410
- raw = (await context.clients.rest.issues.listForRepo({
598
+ const response = await context.clients.rest.issues.listForRepo({
411
599
  ...context.repo,
412
600
  state: input.state ?? 'open',
413
601
  ...(input.labels === undefined ? {} : { labels: input.labels.join(',') }),
@@ -417,15 +605,15 @@ export async function listIssues(context, input) {
417
605
  sort: 'updated',
418
606
  direction: 'desc',
419
607
  headers: { 'X-GitHub-Api-Version': NATIVE_ISSUE_API_VERSION },
420
- })).data;
421
- nextPage = raw.length === perPage ? page + 1 : null;
608
+ });
609
+ raw = response.data;
610
+ nextPage = options.capacityRead
611
+ ? capacityNextPage(response, page, perPage)
612
+ : raw.length === perPage
613
+ ? page + 1
614
+ : null;
422
615
  }
423
- const catalog = z
424
- .array(FieldCatalogEntry)
425
- .parse(await issueFieldPages(context, 'GET /orgs/{org}/issue-fields', { org: context.config.native.organization }));
426
- if (new Set(catalog.map((field) => field.name)).size !== catalog.length ||
427
- new Set(catalog.map((field) => field.id)).size !== catalog.length)
428
- throw new DeliveryError('Native issue field catalog has duplicate identities or names.');
616
+ const catalog = await readIssueFieldCatalog(context, options.capacityRead);
429
617
  const issues = [];
430
618
  const seen = new Set();
431
619
  for (const entry of raw) {
@@ -439,6 +627,18 @@ export async function listIssues(context, input) {
439
627
  `/${context.repo.owner}/${context.repo.repo}/issues/${String(current.number)}`.toLowerCase())
440
628
  throw new DeliveryError('GitHub issue list returned a foreign repository issue.');
441
629
  const selectedLabels = current.labels.map((label) => (typeof label === 'string' ? label : label.name));
630
+ if (options.capacityRead) {
631
+ const url = new URL(current.html_url);
632
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com')
633
+ throw new DeliveryError('WIP capacity issue URL is not the selected GitHub repository.');
634
+ const native = (await context.clients.rest.issues.get({ ...context.repo, issue_number: current.number })).data;
635
+ if ('pull_request' in native ||
636
+ native.number !== current.number ||
637
+ native.node_id !== current.node_id ||
638
+ native.html_url !== current.html_url ||
639
+ native.state !== current.state)
640
+ throw new DeliveryError('WIP capacity issue identity or state changed during native readback.');
641
+ }
442
642
  if (input.state !== undefined && input.state !== 'all' && current.state !== input.state)
443
643
  continue;
444
644
  if ((input.labels ?? []).some((label) => !selectedLabels.some((selected) => selected.toLowerCase() === label.toLowerCase())))
@@ -462,50 +662,19 @@ export async function listIssues(context, input) {
462
662
  const project = await getIssueProjectStatus({
463
663
  graphql: context.clients.graphql,
464
664
  issueNodeId: current.node_id,
665
+ ...(options.capacityRead ? { capacityRead: true, maxPages: 20 } : {}),
465
666
  org: context.config.native.organization,
466
667
  ...(context.projectConfiguration ? { configuration: context.projectConfiguration } : {}),
467
668
  settings: projectSettingsFromDeliveryConfig(context.config),
468
669
  });
469
670
  if (input.projectStatus !== undefined && (project?.status ?? null) !== input.projectStatus)
470
671
  continue;
471
- const fields = Object.fromEntries(catalog.map((field) => [field.name, null]));
472
- const values = z.array(FieldValueEntry).parse(await issueFieldPages(context, 'GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values', {
473
- ...context.repo,
474
- issue_number: current.number,
475
- }));
476
- const observed = new Set();
477
- for (const field of values) {
478
- const definition = catalog.find((candidate) => candidate.id === field.issue_field_id);
479
- if (!definition ||
480
- definition.name !== field.issue_field_name ||
481
- definition.data_type !== field.data_type ||
482
- observed.has(field.issue_field_id))
483
- throw new DeliveryError('Native issue field readback conflicts with its catalog.');
484
- observed.add(field.issue_field_id);
485
- if (((field.data_type === 'single_select' && !field.single_select_option) ||
486
- (field.data_type === 'multi_select' && field.multi_select_options === undefined)) &&
487
- field.value !== null &&
488
- field.value !== undefined)
489
- throw new DeliveryError('Native select field omitted its named option readback.');
490
- const value = field.data_type === 'single_select'
491
- ? (field.single_select_option?.name ?? null)
492
- : field.data_type === 'multi_select'
493
- ? field.multi_select_options?.map((option) => option.name)
494
- : field.value;
495
- if (field.data_type === 'date' && value !== null && value !== undefined && !z.iso.date().safeParse(value).success)
496
- throw new DeliveryError('Native date field has an invalid date value.');
497
- if (value === null || value === undefined)
498
- fields[definition.name] = null;
499
- else if (field.data_type === 'number'
500
- ? typeof value === 'number' && Number.isFinite(value)
501
- : field.data_type === 'multi_select'
502
- ? Array.isArray(value)
503
- : typeof value === 'string')
504
- fields[definition.name] = value;
505
- else
506
- throw new DeliveryError('Native issue field has an invalid value type.');
507
- }
672
+ const { fields } = await readIssueFields(context, current.number, catalog, options.capacityRead);
508
673
  issues.push({
674
+ ...(options.capacityRead
675
+ ? { nodeId: current.node_id, fieldIds: Object.fromEntries(catalog.map((field) => [field.name, field.id])) }
676
+ : {}),
677
+ ...deferralReadback(current.body, current.title),
509
678
  number: current.number,
510
679
  title: current.title,
511
680
  state: current.state,
@@ -577,7 +746,24 @@ export async function readIssueClosure(context, issueNumber) {
577
746
  : { number: parsed.duplicateOf.number, repository: parsed.duplicateOf.repository.nameWithOwner },
578
747
  };
579
748
  }
580
- export async function updateIssue(context, input) {
749
+ function updateProjectStatus(info, input) {
750
+ return info.state === 'closed' || info.projectStatus === 'Done'
751
+ ? 'Done'
752
+ : info.blockedBy.length > 0
753
+ ? 'Blocked'
754
+ : input.park === true || input.blockedBy !== undefined || info.projectStatus === null
755
+ ? 'Todo'
756
+ : info.projectStatus === 'In Progress' || (info.projectStatus === 'Blocked' && input.state === undefined)
757
+ ? info.projectStatus
758
+ : 'Todo';
759
+ }
760
+ async function prepareIssueUpdate(context, input) {
761
+ requireDeferralPatch({
762
+ ...(input.defer === undefined ? {} : { defer: input.defer }),
763
+ ...(input.undefer === undefined ? {} : { undefer: input.undefer }),
764
+ });
765
+ if ('deferral' in input)
766
+ throw new DeliveryError('Use defer or undefer to change deferral state.');
581
767
  if (context.clients.role !== 'author')
582
768
  throw new DeliveryError('Issue writes require the configured author role.');
583
769
  if ((input.closeReason !== undefined && !['completed', 'not_planned', 'duplicate'].includes(input.closeReason)) ||
@@ -587,16 +773,21 @@ export async function updateIssue(context, input) {
587
773
  (!Number.isSafeInteger(input.supersededBy) || input.supersededBy <= 0 || input.supersededBy === input.issueNumber))
588
774
  throw new DeliveryError('A superseding issue must be a different positive issue number.');
589
775
  const { clients, config, repo } = context;
776
+ const dateChanges = await prepareIssueDates(context, input);
590
777
  const currentContent = await issueInfo(context, input.issueNumber);
591
778
  const prepared = prepareIssueWrite(input, currentContent);
592
779
  input = {
593
780
  ...input,
594
- title: prepared.issue.title,
595
781
  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 } : {}),
782
+ ...(prepared.statusOnly
783
+ ? {}
784
+ : {
785
+ title: prepared.issue.title,
786
+ ...(prepared.issue.issueType === undefined ? {} : { issueType: prepared.issue.issueType }),
787
+ ...(prepared.issue.points === undefined ? {} : { points: prepared.issue.points }),
788
+ ...(prepared.issue.draft ? { park: true } : {}),
789
+ }),
790
+ preserveHistory: prepared.preserveHistory,
600
791
  };
601
792
  const acceptedLabels = input.labels === undefined ? undefined : await labels(context, input.labels);
602
793
  if (input.issueType !== undefined && !config.native.issueTypes.includes(input.issueType)) {
@@ -669,13 +860,15 @@ export async function updateIssue(context, input) {
669
860
  }
670
861
  }
671
862
  }
672
- let historyComment;
673
- let priorContent;
863
+ let historyBody;
864
+ let priorContent = input.status === undefined ? undefined : { title: currentContent.title, body: currentContent.body };
674
865
  if (input.preserveHistory === true && (input.title !== undefined || input.body !== undefined)) {
675
866
  const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
676
867
  if (current.number !== input.issueNumber || 'pull_request' in current)
677
868
  throw new DeliveryError('History target is not the requested issue.');
678
869
  const prior = { title: current.title, body: current.body ?? '' };
870
+ if (prior.title !== currentContent.title || prior.body !== currentContent.body)
871
+ throw new DeliveryError('Issue content changed after preparation; retry against the current title and body.');
679
872
  if ((input.title !== undefined && input.title !== prior.title) ||
680
873
  (input.body !== undefined && input.body !== prior.body)) {
681
874
  const body = renderIssueHistory(prior.title, prior.body);
@@ -685,14 +878,41 @@ export async function updateIssue(context, input) {
685
878
  if (body.length > ISSUE_COMMENT_BODY_LIMIT)
686
879
  throw new DeliveryError('Complete issue history exceeds the supported comment body limit; issue was not rewritten.');
687
880
  priorContent = prior;
688
- historyComment = await commentIssue(context, { issueNumber: input.issueNumber, body });
881
+ historyBody = body;
689
882
  }
690
883
  }
884
+ const closureBody = closeReason === undefined
885
+ ? undefined
886
+ : `Requested closure reason: ${closeReason}.${input.supersededBy === undefined ? '' : `\nSuperseded by ${repo.owner}/${repo.repo}#${String(input.supersededBy)}.`}`;
887
+ return {
888
+ input,
889
+ prepared,
890
+ acceptedLabels,
891
+ beforeAdd,
892
+ closeReason,
893
+ supersedingIssueId,
894
+ assertClosure,
895
+ currentContent,
896
+ dateChanges,
897
+ priorContent,
898
+ historyBody,
899
+ closureBody,
900
+ };
901
+ }
902
+ export async function updateIssue(context, input) {
903
+ return applyIssueUpdate(context, await prepareIssueUpdate(context, input));
904
+ }
905
+ async function applyIssueUpdate(context, plan) {
906
+ const { clients, config, repo } = context;
907
+ const { input, prepared, acceptedLabels, beforeAdd, closeReason, supersedingIssueId, assertClosure, priorContent, historyBody, closureBody, } = plan;
908
+ const historyComment = historyBody === undefined
909
+ ? undefined
910
+ : await commentIssue(context, { issueNumber: input.issueNumber, body: historyBody });
691
911
  let closureComment;
692
- if (closeReason !== undefined)
912
+ if (closureBody !== undefined)
693
913
  closureComment = await commentIssue(context, {
694
914
  issueNumber: input.issueNumber,
695
- body: `Requested closure reason: ${closeReason}.${input.supersededBy === undefined ? '' : `\nSuperseded by ${repo.owner}/${repo.repo}#${String(input.supersededBy)}.`}`,
915
+ body: closureBody,
696
916
  });
697
917
  if (priorContent !== undefined) {
698
918
  const current = (await clients.rest.issues.get({ ...repo, issue_number: input.issueNumber })).data;
@@ -700,7 +920,7 @@ export async function updateIssue(context, input) {
700
920
  'pull_request' in current ||
701
921
  current.title !== priorContent.title ||
702
922
  (current.body ?? '') !== priorContent.body)
703
- throw new DeliveryError('Issue content changed after history readback; retry against the current title and body.');
923
+ throw new DeliveryError('Issue content changed after preparation; retry against the current title and body.');
704
924
  }
705
925
  await clients.rest.issues.update({
706
926
  issue_number: input.issueNumber,
@@ -735,6 +955,12 @@ export async function updateIssue(context, input) {
735
955
  rest: clients.rest,
736
956
  settings: nativeIssueSettingsFromDeliveryConfig(config),
737
957
  });
958
+ await applyNativeIssueDates({
959
+ changes: plan.dateChanges,
960
+ issueNumber: input.issueNumber,
961
+ ...repo,
962
+ rest: clients.rest,
963
+ });
738
964
  if (input.parentIssueNumber !== undefined)
739
965
  await replaceParentIssue({
740
966
  graphql: clients.graphql,
@@ -776,15 +1002,7 @@ export async function updateIssue(context, input) {
776
1002
  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
1003
  }
778
1004
  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';
1005
+ const status = updateProjectStatus(info, input);
788
1006
  const issue = (await clients.rest.issues.get({ issue_number: input.issueNumber, ...repo })).data;
789
1007
  await syncIssueProjectStatus({
790
1008
  graphql: clients.graphql,
@@ -811,23 +1029,346 @@ export async function updateIssue(context, input) {
811
1029
  : { closure: { ...closure, supersededBy: input.supersededBy ?? null, comment: closureComment } }),
812
1030
  };
813
1031
  }
1032
+ /** Read-only inspection of the same authenticated closure journal used by updateIssue. */
1033
+ async function hasUpdateComment(context, issueNumber, body) {
1034
+ if (!context.clients.authenticatedAuthor)
1035
+ throw new DeliveryError('Authenticated update journal author is missing.');
1036
+ const actor = (await context.clients.authenticatedAuthor()).actorLogin;
1037
+ if (!actor)
1038
+ throw new DeliveryError('Update journal author identity is missing.');
1039
+ const matches = [];
1040
+ let complete = false;
1041
+ for (let page = 1; page <= 20; page++) {
1042
+ const comments = (await context.clients.rest.issues.listComments({
1043
+ ...context.repo,
1044
+ issue_number: issueNumber,
1045
+ per_page: 100,
1046
+ page,
1047
+ })).data;
1048
+ matches.push(...comments.filter((comment) => comment.user?.login?.toLowerCase() === actor.toLowerCase() && comment.body === body));
1049
+ if (comments.length < 100) {
1050
+ complete = true;
1051
+ break;
1052
+ }
1053
+ }
1054
+ if (!complete)
1055
+ throw new DeliveryError('Update journal readback exceeds the bounded history window.');
1056
+ if (matches.length > 1)
1057
+ throw new DeliveryError('Issue comment has duplicate authored retry matches.');
1058
+ if (!matches[0])
1059
+ return false;
1060
+ await readAuthoredIssueComment(context, issueNumber, matches[0], body, actor);
1061
+ return true;
1062
+ }
1063
+ async function updateProjection(context, plan) {
1064
+ const { input } = plan;
1065
+ const readback = await issueInfo(context, input.issueNumber);
1066
+ const values = { ...readback };
1067
+ const relationships = async (issueNumber) => {
1068
+ const native = await getNativeBlockerRelationships({
1069
+ graphql: context.clients.graphql,
1070
+ repo: context.repo,
1071
+ issueNumber,
1072
+ requireRepositoryIdentity: true,
1073
+ });
1074
+ const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1075
+ const edges = [
1076
+ ...native.blockers,
1077
+ ...(native.parentNumber === null
1078
+ ? []
1079
+ : [{ number: native.parentNumber, id: native.parentId, repository: native.parentRepository }]),
1080
+ ];
1081
+ if (edges.some((edge) => edge.repository?.toLowerCase() !== repository))
1082
+ throw new DeliveryError('Native batch relationship belongs to a different repository.');
1083
+ const targets = await resolveNativeRelationshipTargets({
1084
+ blockers: edges.map((edge) => edge.number),
1085
+ repo: context.repo,
1086
+ rest: context.clients.rest,
1087
+ });
1088
+ if (edges.some((edge) => edge.id !== targets.blockerNodeIds.get(edge.number)))
1089
+ throw new DeliveryError('Native batch relationship node identity disagrees with its repository issue.');
1090
+ return native;
1091
+ };
1092
+ if (input.blockedBy !== undefined || input.parentIssueNumber !== undefined) {
1093
+ const native = await relationships(input.issueNumber);
1094
+ if (native.parentNumber !== readback.parentIssueNumber)
1095
+ throw new DeliveryError('Native parent changed during batch readback; reconcile the current state.');
1096
+ if (input.blockedBy !== undefined)
1097
+ values.blockedBy = native.blockers.map((value) => value.number).sort((a, b) => a - b);
1098
+ }
1099
+ if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null) {
1100
+ const metadata = await getConfiguredNativeIssueMetadata({
1101
+ issueNumber: input.parentIssueNumber,
1102
+ ...context.repo,
1103
+ rest: context.clients.rest,
1104
+ settings: nativeIssueSettingsFromDeliveryConfig(context.config),
1105
+ });
1106
+ values.parentPoints = { issueNumber: input.parentIssueNumber, points: metadata.points ?? null };
1107
+ }
1108
+ if (input.blocks !== undefined) {
1109
+ values.blocks = await Promise.all([...new Set(input.blocks)].map(async (dependent) => ({
1110
+ issueNumber: dependent,
1111
+ linked: (await relationships(dependent)).blockers.some((value) => value.number === input.issueNumber),
1112
+ })));
1113
+ }
1114
+ if (plan.closeReason !== undefined) {
1115
+ const closure = await readIssueClosure(context, input.issueNumber);
1116
+ values.closeReason = closure.closeReason;
1117
+ if (plan.closeReason === 'duplicate' && input.supersededBy !== undefined)
1118
+ values.supersededBy = closure.duplicateOf?.number ?? null;
1119
+ values.closureComment = await hasUpdateComment(context, input.issueNumber, plan.closureBody);
1120
+ }
1121
+ return { readback, values };
1122
+ }
1123
+ async function desiredUpdateValues(context, plan) {
1124
+ const { input } = plan;
1125
+ const values = {};
1126
+ for (const key of [
1127
+ 'title',
1128
+ 'body',
1129
+ 'issueType',
1130
+ 'points',
1131
+ 'priority',
1132
+ 'startDate',
1133
+ 'targetDate',
1134
+ 'milestone',
1135
+ 'state',
1136
+ 'parentIssueNumber',
1137
+ ]) {
1138
+ if (input[key] !== undefined)
1139
+ values[key] = input[key];
1140
+ }
1141
+ if (plan.acceptedLabels !== undefined)
1142
+ values.labels = [...plan.acceptedLabels].sort();
1143
+ let openBlockers = plan.currentContent.blockedBy;
1144
+ if (input.blockedBy !== undefined) {
1145
+ values.blockedBy = [...new Set(input.blockedBy)].sort((a, b) => a - b);
1146
+ const targets = await Promise.all(input.blockedBy.map(async (number) => (await context.clients.rest.issues.get({ ...context.repo, issue_number: number })).data));
1147
+ openBlockers = targets.filter((target) => target.state === 'open').map((target) => target.number);
1148
+ }
1149
+ values.projectStatus = updateProjectStatus({
1150
+ ...plan.currentContent,
1151
+ state: input.state ?? plan.currentContent.state,
1152
+ blockedBy: openBlockers,
1153
+ }, input);
1154
+ if (input.parentIssueNumber !== undefined && input.parentIssueNumber !== null)
1155
+ values.parentPoints = { issueNumber: input.parentIssueNumber, points: null };
1156
+ if (input.blocks !== undefined)
1157
+ values.blocks = [...new Set(input.blocks)].map((issueNumber) => ({ issueNumber, linked: true }));
1158
+ if (plan.closeReason !== undefined) {
1159
+ values.closeReason = plan.closeReason;
1160
+ if (plan.closeReason === 'duplicate' && input.supersededBy !== undefined)
1161
+ values.supersededBy = input.supersededBy;
1162
+ values.closureComment = true;
1163
+ }
1164
+ return values;
1165
+ }
1166
+ function pendingUpdateValues(desired, actual) {
1167
+ const labels = (value) => Array.isArray(value) && value.every((label) => typeof label === 'string')
1168
+ ? value.map((label) => label.toLowerCase()).sort()
1169
+ : value;
1170
+ return Object.fromEntries(Object.entries(desired).filter(([key, value]) => JSON.stringify(key === 'labels' ? labels(value) : value) !==
1171
+ JSON.stringify(key === 'labels' ? labels(actual[key]) : actual[key])));
1172
+ }
1173
+ function localBatchFailureReason(error) {
1174
+ if (typeof error !== 'object' || error === null || types.isProxy(error))
1175
+ return undefined;
1176
+ const prototype = Object.getPrototypeOf(error);
1177
+ if (prototype === IssueValidationError.prototype)
1178
+ return 'Requested issue fields do not satisfy the issue contract.';
1179
+ if (prototype !== DeliveryError.prototype)
1180
+ return undefined;
1181
+ const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
1182
+ const message = descriptor && 'value' in descriptor ? descriptor.value : undefined;
1183
+ if (typeof message !== 'string')
1184
+ return undefined;
1185
+ if ([
1186
+ 'Choose a valid defer condition or explicit undefer, never both.',
1187
+ 'Use defer or undefer to change deferral state.',
1188
+ 'Choose native blockedBy or display-only status.blockers in one update, not both.',
1189
+ 'Convert the legacy contract explicitly before a status-only update.',
1190
+ 'Issue labels must be non-empty and unique.',
1191
+ 'Repository label listing exceeds the bounded readback window.',
1192
+ 'Unsupported configured Issue Type.',
1193
+ 'Unsupported configured Points value.',
1194
+ 'Unsupported configured Priority value.',
1195
+ 'Closure details require state closed and a supported close reason.',
1196
+ 'A superseding issue must be a different positive issue number.',
1197
+ 'Superseding issue readback is not the requested repository issue.',
1198
+ 'Issue is already closed with different closure evidence; reopen it explicitly first.',
1199
+ 'Native closure readback disagrees with the requested reason or superseding issue.',
1200
+ 'Native closure readback returned a foreign issue identity.',
1201
+ 'Native closure readback has contradictory state evidence.',
1202
+ 'History target is not the requested issue.',
1203
+ 'Issue content changed after preparation; retry against the current title and body.',
1204
+ 'Complete issue history exceeds the supported comment body limit; issue was not rewritten.',
1205
+ 'Issue update readback disagrees with the requested content or state.',
1206
+ 'Issue comments require the authenticated author role.',
1207
+ 'Issue comment author identity is missing.',
1208
+ 'Issue comment target is not the requested issue.',
1209
+ 'Issue comment history exceeds the bounded readback window.',
1210
+ 'Issue comment has duplicate authored retry matches.',
1211
+ 'Issue comment conflicts with its authored operation marker.',
1212
+ 'Issue comment readback disagrees with the authored issue comment.',
1213
+ 'Authenticated update journal author is missing.',
1214
+ 'Update journal author identity is missing.',
1215
+ 'Update journal readback exceeds the bounded history window.',
1216
+ 'An issue cannot be its own parent or blocker.',
1217
+ 'Native blockers must be unique.',
1218
+ 'Native Points and Priority catalogs must select distinct issue fields.',
1219
+ 'Dependency endpoint must be a positive issue number.',
1220
+ 'Dependency endpoint is not the requested repository issue.',
1221
+ 'Dependency writes require configured author authority.',
1222
+ 'Dependency author identity is unavailable.',
1223
+ 'An issue cannot block itself.',
1224
+ 'Dependency removal episode is ambiguous.',
1225
+ 'Complete dependency history is required for an active blocker override.',
1226
+ 'Override comment author, body or issue readback disagrees; native dependency was not added.',
1227
+ 'Override comment search is incomplete or has duplicate authoritative markers.',
1228
+ 'Override comment evidence is malformed.',
1229
+ 'Existing override comment conflicts with the requested reason or endpoint evidence.',
1230
+ 'Native batch relationship belongs to a different repository.',
1231
+ 'Native batch relationship node identity disagrees with its repository issue.',
1232
+ 'Native parent changed during batch readback; reconcile the current state.',
1233
+ 'Native issue changed during batch preparation; reconcile the current state.',
1234
+ 'Native batch readback disagrees with the requested outcomes.',
1235
+ ].includes(message))
1236
+ return message;
1237
+ if (message.startsWith('Unknown repository label(s): '))
1238
+ return 'One or more requested labels do not exist in the selected repository.';
1239
+ if (/^Adding a blocker to active issue #\d+ requires overrideReason\.$/u.test(message))
1240
+ return 'Adding a blocker to an active issue requires overrideReason.';
1241
+ if (/^Project status for dependent #\d+ is unresolved; dependency additions were refused\.$/u.test(message))
1242
+ return 'Project status for a dependent is unresolved; dependency additions were refused.';
1243
+ if (message.startsWith('Complete dependency history is required for an active blocker override: '))
1244
+ return 'Complete dependency history is required for an active blocker override.';
1245
+ if (/^Issue #\d+ content or metadata may have changed, but dependency tracking did not complete: /u.test(message))
1246
+ return 'Issue content or metadata may have changed, but dependency tracking did not complete. Inspect native state and resume this existing issue.';
1247
+ return undefined;
1248
+ }
1249
+ /** One serial operation; each application uses the existing single-update mutation owner. */
1250
+ export async function batchUpdateIssues(context, input, signal) {
1251
+ if (context.clients.role !== 'author')
1252
+ throw new DeliveryError('Batch updates require the configured author role.');
1253
+ if (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > 50)
1254
+ throw new DeliveryError('Provide 1–50 batch items.');
1255
+ const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
1256
+ if (input.items.some((item) => item.repo !== undefined && item.repo.toLowerCase() !== repository))
1257
+ throw new DeliveryError('Every batch item must use the selected repository.');
1258
+ const results = [];
1259
+ const rateLimits = [];
1260
+ const priorRateObservation = context.clients.rateLimitObservation?.();
1261
+ let limited = false;
1262
+ for (const { repo: _repo, ...item } of input.items) {
1263
+ if (limited || signal?.aborted) {
1264
+ results.push({
1265
+ issueNumber: item.issueNumber,
1266
+ status: 'failed',
1267
+ reason: limited ? 'Not attempted: GitHub rate limit exhausted.' : 'Not attempted: operation cancelled.',
1268
+ readback: null,
1269
+ readbackError: 'No new readback requested after rate-limit exhaustion or cancellation.',
1270
+ });
1271
+ continue;
1272
+ }
1273
+ let phase = 'preparation';
1274
+ try {
1275
+ const plan = await prepareIssueUpdate(context, item);
1276
+ const desired = await desiredUpdateValues(context, plan);
1277
+ const before = await updateProjection(context, plan);
1278
+ if (JSON.stringify(before.readback) !== JSON.stringify(plan.currentContent))
1279
+ throw new DeliveryError('Native issue changed during batch preparation; reconcile the current state.');
1280
+ if (context.clients.rateLimitObservation?.() !== priorRateObservation)
1281
+ throw new DeliveryError('A native request exhausted its rate limit during batch preparation.');
1282
+ const changes = pendingUpdateValues(desired, before.values);
1283
+ if (Object.keys(changes).length === 0 || input.dryRun === true) {
1284
+ results.push({
1285
+ issueNumber: item.issueNumber,
1286
+ status: Object.keys(changes).length === 0 ? 'unchanged' : 'planned',
1287
+ changes,
1288
+ readback: before.readback,
1289
+ relatedReadback: before.values,
1290
+ });
1291
+ continue;
1292
+ }
1293
+ phase = 'application';
1294
+ await applyIssueUpdate(context, {
1295
+ ...plan,
1296
+ priorContent: { title: before.readback.title, body: before.readback.body },
1297
+ });
1298
+ phase = 'readback';
1299
+ const after = await updateProjection(context, plan);
1300
+ if (Object.keys(pendingUpdateValues(desired, after.values)).length)
1301
+ throw new DeliveryError('Native batch readback disagrees with the requested outcomes.');
1302
+ results.push({
1303
+ issueNumber: item.issueNumber,
1304
+ status: 'applied',
1305
+ changes,
1306
+ readback: after.readback,
1307
+ relatedReadback: after.values,
1308
+ });
1309
+ }
1310
+ catch (error) {
1311
+ const observed = context.clients.rateLimitObservation?.();
1312
+ const limit = getRateLimitDiagnostics(error) ?? (observed !== priorRateObservation ? observed : undefined);
1313
+ if (limit !== undefined) {
1314
+ limited = true;
1315
+ rateLimits.push(limit);
1316
+ }
1317
+ const diagnostics = getMachineRequestDiagnostics(error);
1318
+ const failed = {
1319
+ issueNumber: item.issueNumber,
1320
+ status: 'failed',
1321
+ readback: null,
1322
+ reason: limit !== undefined
1323
+ ? 'GitHub rate limit exhausted; reconcile native state before retrying.'
1324
+ : (localBatchFailureReason(error) ??
1325
+ `Issue update ${phase} failed; inspect native readback before retrying.`),
1326
+ ...(diagnostics === undefined ? {} : { diagnostics }),
1327
+ };
1328
+ if (!limited && !signal?.aborted) {
1329
+ try {
1330
+ failed.readback = await issueInfo(context, item.issueNumber);
1331
+ }
1332
+ catch (readbackError) {
1333
+ const latest = context.clients.rateLimitObservation?.();
1334
+ const readbackLimit = getRateLimitDiagnostics(readbackError) ?? (latest !== priorRateObservation ? latest : undefined);
1335
+ if (readbackLimit !== undefined) {
1336
+ limited = true;
1337
+ rateLimits.push(readbackLimit);
1338
+ }
1339
+ failed.readbackError = 'Native issue readback unavailable; reconcile this existing issue before retrying.';
1340
+ }
1341
+ }
1342
+ else
1343
+ failed.readbackError = 'Readback deferred after rate-limit exhaustion or cancellation.';
1344
+ results.push(failed);
1345
+ }
1346
+ }
1347
+ return {
1348
+ dryRun: input.dryRun === true,
1349
+ results,
1350
+ summary: {
1351
+ total: results.length,
1352
+ applied: results.filter((item) => item.status === 'applied').length,
1353
+ planned: results.filter((item) => item.status === 'planned').length,
1354
+ unchanged: results.filter((item) => item.status === 'unchanged').length,
1355
+ failed: results.filter((item) => item.status === 'failed').length,
1356
+ rateLimits,
1357
+ },
1358
+ };
1359
+ }
814
1360
  /** Complete the native tracking and Project state of an issue created before an interrupted response. */
815
1361
  export async function resumeCreatedIssue(context, input) {
816
- return updateIssue(context, input);
1362
+ // Tracking recovery must not trigger an unrelated first render omission and change the retry intent.
1363
+ return updateIssue(context, { ...input, preserveHistory: input.preserveHistory ?? false });
817
1364
  }
818
1365
  export async function issueInfo(context, issueNumber) {
819
1366
  const { clients, config, repo } = context;
820
1367
  const issue = (await clients.rest.issues.get({ issue_number: issueNumber, owner: repo.owner, repo: repo.repo })).data;
821
1368
  if ('pull_request' in issue)
822
1369
  throw new DeliveryError('Requested issue number is a pull request.');
823
- const [metadata, relationships, project] = await Promise.all([
824
- getConfiguredNativeIssueMetadata({
825
- issueNumber,
826
- owner: repo.owner,
827
- repo: repo.repo,
828
- rest: clients.rest,
829
- settings: nativeIssueSettingsFromDeliveryConfig(config),
830
- }),
1370
+ const [nativeFields, relationships, project] = await Promise.all([
1371
+ readIssueFieldCatalog(context).then((catalog) => readIssueFields(context, issueNumber, catalog)),
831
1372
  getNativeBlockerRelationships({ graphql: clients.graphql, issueNumber, repo }),
832
1373
  getIssueProjectStatus({
833
1374
  graphql: clients.graphql,
@@ -837,7 +1378,9 @@ export async function issueInfo(context, issueNumber) {
837
1378
  settings: projectSettingsFromDeliveryConfig(config),
838
1379
  }),
839
1380
  ]);
1381
+ const metadata = parseConfiguredNativeIssueMetadata(nativeFields.values, nativeIssueSettingsFromDeliveryConfig(config));
840
1382
  const info = {
1383
+ ...deferralReadback(issue.body, issue.title),
841
1384
  ...(context.configuration ? { routing: context.configuration.routing } : {}),
842
1385
  blockedBy: relationships.blockers.filter((blocker) => blocker.state === 'OPEN').map((blocker) => blocker.number),
843
1386
  body: issue.body ?? '',
@@ -845,6 +1388,13 @@ export async function issueInfo(context, issueNumber) {
845
1388
  issueType: issue.type?.name ?? null,
846
1389
  labels: (issue.labels ?? []).flatMap((label) => typeof label === 'string' ? [label] : label.name === undefined ? [] : [label.name]),
847
1390
  milestone: issue.milestone?.number ?? null,
1391
+ fields: nativeFields.fields,
1392
+ ...(nativeFields.catalog.some((field) => field.name === 'Start date' && field.data_type === 'date')
1393
+ ? { startDate: nativeFields.fields['Start date'] }
1394
+ : {}),
1395
+ ...(nativeFields.catalog.some((field) => field.name === 'Target date' && field.data_type === 'date')
1396
+ ? { targetDate: nativeFields.fields['Target date'] }
1397
+ : {}),
848
1398
  parentIssueNumber: relationships.parentNumber,
849
1399
  ...(metadata.points === undefined ? {} : { points: metadata.points }),
850
1400
  ...(metadata.priority === undefined ? {} : { priority: metadata.priority }),
@@ -856,6 +1406,19 @@ export async function issueInfo(context, issueNumber) {
856
1406
  };
857
1407
  return info;
858
1408
  }
1409
+ /** Invalid canonical content stays inspectable; omitted state is unknown, never an assertion of undeferred. */
1410
+ function deferralReadback(body, title) {
1411
+ if (body === undefined)
1412
+ return {};
1413
+ try {
1414
+ return { deferred: parseIssueBody(body ?? '', { title }).issue.deferral ?? null };
1415
+ }
1416
+ catch (error) {
1417
+ if (!(error instanceof IssueValidationError))
1418
+ throw error;
1419
+ return {};
1420
+ }
1421
+ }
859
1422
  export async function listIssueSubissues(context, issueNumber) {
860
1423
  const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;
861
1424
  if ('pull_request' in issue)
@@ -950,7 +1513,7 @@ export async function startIssueBranch(context, issueNumber, selected) {
950
1513
  return { issueNumber, issueUrl: issue.html_url, branch: name, headSha: base, reused: false };
951
1514
  }
952
1515
  /** Recheck native eligibility before an explicit start changes its selected Project. */
953
- export async function startIssueProject(context, issueNumber) {
1516
+ export async function startIssueProject(context, issueNumber, overrideReason) {
954
1517
  const readiness = await readyCheck(context, issueNumber);
955
1518
  if (!readiness.ready)
956
1519
  throw new IssueValidationError(readiness.failures);
@@ -964,6 +1527,121 @@ export async function startIssueProject(context, issueNumber) {
964
1527
  ...(context.projectConfiguration === undefined ? {} : { configuration: context.projectConfiguration }),
965
1528
  settings: projectSettingsFromDeliveryConfig(context.config),
966
1529
  status: 'In Progress',
1530
+ beforeAdvance: async () => {
1531
+ const eligible = await readyCheck(context, issueNumber);
1532
+ if (!eligible.ready)
1533
+ throw new IssueValidationError(eligible.failures);
1534
+ await assertIssueStartCapacity(context, issueNumber, overrideReason, true);
1535
+ const current = await issueInfo(context, issueNumber);
1536
+ if (current.state !== 'open')
1537
+ throw new DeliveryError('Start requires the requested open issue.');
1538
+ const finalEligibility = await readyCheck(context, issueNumber);
1539
+ if (!finalEligibility.ready)
1540
+ throw new IssueValidationError(finalEligibility.failures);
1541
+ },
1542
+ });
1543
+ }
1544
+ /** A complete observed-capacity guard, not a cross-writer GitHub transaction. */
1545
+ export async function assertIssueStartCapacity(context, issueNumber, overrideReason, recordOverride = false) {
1546
+ const lanes = WipLimits.parse(context.config.wipLimits ?? []).filter((lane) => lane.repository.toLowerCase() === context.config.repository.toLowerCase());
1547
+ if (!lanes.length)
1548
+ return undefined;
1549
+ const configuration = context.projectConfiguration ??
1550
+ (await getProjectDeliveryConfiguration({
1551
+ graphql: context.clients.graphql,
1552
+ org: context.config.native.organization,
1553
+ settings: projectSettingsFromDeliveryConfig(context.config),
1554
+ }));
1555
+ const capacityContext = { ...context, projectConfiguration: configuration };
1556
+ const reason = overrideReason === undefined ? undefined : OverrideReason.parse(overrideReason);
1557
+ const publicReason = validateIssue({ title: 'WIP capacity override', legacyBody: reason ?? '', draft: true }, false);
1558
+ if (publicReason.failures.length)
1559
+ throw new IssueValidationError(publicReason.failures);
1560
+ if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())
1561
+ throw new DeliveryError('WIP capacity repository identity disagrees with the selected repository.');
1562
+ const configuredLabels = lanes.flatMap((lane) => ('label' in lane.match ? [lane.match.label] : []));
1563
+ if (configuredLabels.length)
1564
+ await labels(context, [...new Map(configuredLabels.map((label) => [label.toLowerCase(), label])).values()]);
1565
+ const rows = [];
1566
+ const seen = new Set();
1567
+ for (let page = 1;; page++) {
1568
+ if (page > 20)
1569
+ throw new DeliveryError('WIP capacity issue pagination is incomplete.');
1570
+ const batch = await listIssues(capacityContext, { state: 'open', page, perPage: 100 }, { capacityRead: true });
1571
+ for (const row of batch.issues) {
1572
+ if (seen.has(row.number))
1573
+ throw new DeliveryError('WIP capacity repeats a native issue across pages.');
1574
+ seen.add(row.number);
1575
+ rows.push(row);
1576
+ }
1577
+ if (batch.nextPage === null)
1578
+ break;
1579
+ if (batch.nextPage !== page + 1)
1580
+ throw new DeliveryError('WIP capacity pagination did not advance.');
1581
+ }
1582
+ const target = rows.find((row) => row.number === issueNumber);
1583
+ if (!target?.nodeId)
1584
+ throw new DeliveryError('WIP capacity target is missing from the complete native issue readback.');
1585
+ const matches = (lane, row) => {
1586
+ if ('label' in lane.match) {
1587
+ const selected = lane.match.label;
1588
+ return row.labels.some((label) => label.toLowerCase() === selected.toLowerCase());
1589
+ }
1590
+ const { field, value } = lane.match;
1591
+ if (!row.fieldIds?.[field] || row.fieldIds[field] !== target.fieldIds?.[field] || !Object.hasOwn(row.fields, field))
1592
+ throw new DeliveryError(`WIP capacity native field ${field} is unknown or changed identity.`);
1593
+ const observed = row.fields[field];
1594
+ return Array.isArray(observed) ? typeof value === 'string' && observed.includes(value) : observed === value;
1595
+ };
1596
+ const observations = lanes.flatMap((lane) => {
1597
+ // Validate every configured field across the full snapshot, even when the target does not match it.
1598
+ const matching = rows.filter((row) => matches(lane, row));
1599
+ if (!matches(lane, target))
1600
+ return [];
1601
+ const count = matching.filter((row) => row.projectStatus === 'In Progress').length;
1602
+ return [
1603
+ {
1604
+ name: lane.name,
1605
+ match: lane.match,
1606
+ ...('field' in lane.match ? { fieldId: target.fieldIds[lane.match.field] } : {}),
1607
+ count,
1608
+ limit: lane.limit,
1609
+ },
1610
+ ];
967
1611
  });
1612
+ const exceeded = target.projectStatus === 'In Progress' ? [] : observations.filter((lane) => lane.count + 1 > lane.limit);
1613
+ if (exceeded.length && reason === undefined)
1614
+ throw new DeliveryError(`WIP capacity limit exceeded: ${exceeded.map((lane) => `${lane.name} (${lane.count}/${lane.limit})`).join(', ')}. Supply overrideReason for a recorded capacity exception.`);
1615
+ const evidence = {
1616
+ schema: 'ai-delivery.wip-override@1',
1617
+ repository: context.config.repository,
1618
+ projectId: configuration.projectId,
1619
+ issue: { number: issueNumber, id: target.nodeId },
1620
+ observedStatus: target.projectStatus,
1621
+ lanes: observations,
1622
+ };
1623
+ if (!evidence.projectId)
1624
+ throw new DeliveryError('WIP capacity configured Project identity is unavailable.');
1625
+ const snapshot = JSON.stringify(evidence);
1626
+ if (exceeded.length && recordOverride) {
1627
+ if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor)
1628
+ throw new DeliveryError('WIP capacity override requires the authenticated configured author.');
1629
+ const author = await context.clients.authenticatedAuthor();
1630
+ if (!author.actorLogin || !author.credentialIdentity)
1631
+ throw new DeliveryError('WIP capacity author identity is incomplete.');
1632
+ const record = { ...evidence, author: author.actorLogin, reason };
1633
+ const marker = `<!-- ai-delivery:wip-override@1:${digestValue(record)} -->`;
1634
+ const body = `WIP capacity override.\n\n\`\`\`json\n${JSON.stringify(record, null, 2)}\n\`\`\`\n\n${marker}`;
1635
+ const publicRecord = validateIssue({ title: 'WIP capacity override', legacyBody: body, draft: true }, false);
1636
+ if (publicRecord.failures.length)
1637
+ throw new IssueValidationError(publicRecord.failures);
1638
+ await writeAuthenticatedIssueComment(context, { issueNumber, body }, undefined, marker);
1639
+ const finalAuthor = await context.clients.authenticatedAuthor();
1640
+ if (finalAuthor.actorLogin !== author.actorLogin || finalAuthor.credentialIdentity !== author.credentialIdentity)
1641
+ throw new DeliveryError('WIP capacity override author changed during comment verification.');
1642
+ if ((await assertIssueStartCapacity(context, issueNumber, reason)) !== snapshot)
1643
+ throw new DeliveryError('WIP capacity changed while recording the override; inspect native state and resume this issue.');
1644
+ }
1645
+ return snapshot;
968
1646
  }
969
1647
  //# sourceMappingURL=issue.js.map