@aviaratech/ai-delivery 0.3.35 → 0.3.36

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