@aviaratech/ai-delivery 0.3.34 → 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 (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  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 +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  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 +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  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 -477
  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.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,408 +1,495 @@
1
- import { lstatSync, readFileSync, realpathSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { isAbsolute, join, relative } from 'node:path';
4
- import { z } from 'zod';
5
- import { git } from '../git.js';
6
- import { DeliveryError } from '../errors.js';
7
- import { digestValue } from '../delivery/common.js';
8
- import { createDeliveryGitHubClients, retainMachineAuthorForConfiguration } from '../github/client.js';
9
- import { resolveRepoFromRemote } from '../github/repo.js';
10
- import { discoverDeliveryRouting } from '../github/discovery.js';
11
- export const DELIVERY_CONFIG_FILE = 'ai-delivery.config.json';
12
- export const DELIVERY_POLICY_CONTRACT = 'RepositoryDeliveryPolicy@1';
1
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, relative } from "node:path";
4
+ import { z } from "zod";
5
+ import { git } from "../git.js";
6
+ import { DeliveryError } from "../errors.js";
7
+ import { digestValue } from "../delivery/common.js";
8
+ import { createDeliveryGitHubClients, retainMachineAuthorForConfiguration } from "../github/client.js";
9
+ import { resolveRepoFromRemote } from "../github/repo.js";
10
+ import { discoverDeliveryRouting } from "../github/discovery.js";
11
+ import { MACHINE_AUTH_ENV_NAMES } from "../github/machineAuth.js";
12
+ const DELIVERY_CONFIG_FILE = "ai-delivery.config.json";
13
+ const DELIVERY_POLICY_CONTRACT = "RepositoryDeliveryPolicy@1";
14
+ function configurationIssueMessages(issues, root, prefix = []) {
15
+ return issues.flatMap((issue) => {
16
+ const path = [...prefix, ...issue.path];
17
+ return issue.code === "invalid_union" ? issue.errors.flatMap((branch) => configurationIssueMessages(branch, root, path)) : [`${path.join(".") || root}: ${issue.message}`];
18
+ });
19
+ }
13
20
  const Name = z.string().trim().min(1);
14
- export const WipLimits = z
15
- .array(z.strictObject({
21
+ const WipLimits = z.array(
22
+ z.strictObject({
16
23
  repository: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u),
17
24
  name: Name,
18
25
  match: z.union([
19
- z.strictObject({ label: Name }),
20
- z.strictObject({ field: Name, value: z.union([z.string().min(1), z.number().finite()]) }),
26
+ z.strictObject({ label: Name }),
27
+ z.strictObject({ field: Name, value: z.union([z.string().min(1), z.number().finite()]) })
21
28
  ]),
22
- limit: z.number().int().nonnegative().safe(),
23
- }))
24
- .superRefine((lanes, context) => {
25
- const identities = lanes.map((lane) => JSON.stringify([lane.repository.toLowerCase(), lane.name]));
26
- if (new Set(identities).size !== identities.length)
27
- context.addIssue({ code: 'custom', message: 'WIP lane names must be unique within each repository.' });
29
+ limit: z.number().int().nonnegative().safe()
30
+ })
31
+ ).superRefine((lanes, context) => {
32
+ const identities = lanes.map((lane) => JSON.stringify([lane.repository.toLowerCase(), lane.name]));
33
+ if (new Set(identities).size !== identities.length)
34
+ context.addIssue({ code: "custom", message: "WIP lane names must be unique within each repository." });
28
35
  });
29
36
  const EnvName = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);
30
37
  const PositiveInteger = z.number().int().positive();
31
- const NativeFieldId = z
32
- .string()
33
- .regex(/^[1-9]\d*$/u)
34
- .refine((value) => Number.isSafeInteger(Number(value)));
35
- const UniqueNames = z
36
- .array(Name)
37
- .min(1)
38
- .superRefine((values, context) => {
39
- if (new Set(values).size !== values.length) {
40
- context.addIssue({ code: 'custom', message: 'Values must be unique.' });
41
- }
38
+ const NativeFieldId = z.string().regex(/^[1-9]\d*$/u).refine((value) => Number.isSafeInteger(Number(value)));
39
+ const UniqueNames = z.array(Name).min(1).superRefine((values, context) => {
40
+ if (new Set(values).size !== values.length) {
41
+ context.addIssue({ code: "custom", message: "Values must be unique." });
42
+ }
42
43
  });
43
- const NativeField = z
44
- .object({
45
- databaseId: NativeFieldId,
46
- name: Name,
47
- values: UniqueNames,
48
- })
49
- .strict();
50
- const AppRole = z
51
- .object({
52
- authSource: z.literal('app').optional(),
53
- credentialEnv: z
54
- .object({
55
- appId: EnvName,
56
- installationId: EnvName,
57
- privateKeyPath: EnvName,
58
- })
59
- .strict(),
60
- identity: Name,
61
- })
62
- .strict();
44
+ const NativeField = z.object({
45
+ databaseId: NativeFieldId,
46
+ name: Name,
47
+ values: UniqueNames
48
+ }).strict();
49
+ const LegacyAppRole = z.object({
50
+ authSource: z.literal("app").optional(),
51
+ credentialEnv: z.object({
52
+ appId: EnvName,
53
+ installationId: EnvName,
54
+ privateKeyPath: EnvName
55
+ }).strict(),
56
+ identity: Name
57
+ }).strict();
58
+ const ReviewProvider = z.enum(["openai", "anthropic", "google", "qwen"]);
59
+ const Encoding = z.enum(["pem", "base64"]).optional();
60
+ const CredentialSource = z.union([
61
+ z.strictObject({ type: z.literal("env"), variable: EnvName.optional(), encoding: Encoding }),
62
+ z.strictObject({ type: z.literal("file"), path: Name.refine(isAbsolute, "Key path must be absolute.") }),
63
+ z.strictObject({
64
+ type: z.literal("command"),
65
+ argv: z.array(z.string().max(4096)).min(1).max(64).refine(
66
+ (argv) => isAbsolute(argv[0]) && argv.every((part) => !part.includes("\0")),
67
+ "Command requires an absolute executable and literal argv without NUL."
68
+ ),
69
+ encoding: Encoding,
70
+ env: z.array(EnvName).max(32).optional()
71
+ })
72
+ ]);
73
+ const ConfiguredAppRole = z.strictObject({
74
+ authSource: z.literal("app"),
75
+ identity: z.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u),
76
+ appId: PositiveInteger.safe(),
77
+ installationId: PositiveInteger.safe(),
78
+ actorLogin: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9-]{0,99}\[bot\]$/u),
79
+ provider: ReviewProvider,
80
+ credentialSource: CredentialSource.optional()
81
+ });
82
+ const AppRole = z.union([LegacyAppRole, ConfiguredAppRole]);
83
+ function appCredentialSource(role) {
84
+ return role.credentialSource ?? { type: "env" };
85
+ }
86
+ function privateKeyVariable(role) {
87
+ const source = appCredentialSource(role);
88
+ return source.type === "env" && source.variable !== void 0 ? source.variable : `GH_PRIVATE_KEY_${role.identity.toUpperCase().replace(/[^A-Z0-9]/gu, "_")}`;
89
+ }
90
+ function credentialReferenceNames(role) {
91
+ if ("credentialEnv" in role) return Object.values(role.credentialEnv);
92
+ const source = appCredentialSource(role);
93
+ return source.type === "env" ? [privateKeyVariable(role)] : source.type === "command" ? source.env ?? [] : [];
94
+ }
63
95
  const AuthorRole = z.union([
64
- AppRole,
65
- z
66
- .object({
67
- authSource: z.literal('personal'),
68
- credentialEnv: z.object({ token: EnvName }).strict(),
69
- identity: Name,
70
- })
71
- .strict(),
96
+ AppRole,
97
+ z.object({
98
+ authSource: z.literal("personal"),
99
+ credentialEnv: z.object({ token: EnvName }).strict(),
100
+ identity: Name
101
+ }).strict()
72
102
  ]);
73
- const DeliveryConfigSchema = z
74
- .object({
75
- wipLimits: WipLimits.optional(),
76
- commandPolicy: z
77
- .object({
78
- checks: z
79
- .object({
80
- format: z.enum(['REQUIRED', 'OPTIONAL', 'SKIP']),
81
- gitClean: z.enum(['REQUIRED', 'OPTIONAL', 'SKIP']),
82
- lint: z.enum(['REQUIRED', 'OPTIONAL', 'SKIP']),
83
- test: z.enum(['REQUIRED', 'OPTIONAL', 'SKIP']),
84
- typecheck: z.enum(['REQUIRED', 'OPTIONAL', 'SKIP']),
85
- })
86
- .strict(),
87
- timeoutsMs: z
88
- .object({
89
- lint: PositiveInteger,
90
- test: PositiveInteger,
91
- typecheck: PositiveInteger,
92
- })
93
- .strict(),
94
- })
95
- .strict(),
96
- native: z
97
- .object({
98
- issueTypes: UniqueNames,
99
- milestones: z.literal('repository'),
100
- organization: Name,
101
- points: NativeField,
102
- priority: NativeField,
103
- project: z
104
- .object({
105
- number: PositiveInteger,
106
- statuses: z
107
- .object({
108
- blocked: Name,
109
- done: Name,
110
- inProgress: Name,
111
- todo: Name,
112
- })
113
- .strict(),
114
- statusField: Name,
115
- title: Name,
116
- })
117
- .strict(),
118
- relationships: z
119
- .object({
120
- blockedBy: z.literal('native'),
121
- parent: z.literal('native'),
122
- })
123
- .strict(),
124
- })
125
- .strict(),
126
- policy: z
127
- .object({
128
- contract: z.enum([DELIVERY_POLICY_CONTRACT, 'RepositoryDeliveryPolicy@2']),
129
- module: z.string().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u),
130
- })
131
- .strict(),
132
- repository: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u),
133
- roles: z.object({ author: AuthorRole, reviewer: AppRole }).strict(),
134
- schemaVersion: z.literal('ai-delivery.config@2'),
135
- })
136
- .strict()
137
- .superRefine((value, context) => {
138
- if (value.repository.split('/')[0]?.toLowerCase() !== value.native.organization.toLowerCase()) {
139
- context.addIssue({
140
- code: 'custom',
141
- message: 'Organization must match repository owner.',
142
- path: ['native', 'organization'],
143
- });
144
- }
145
- if (value.roles.author.identity.toLowerCase() === value.roles.reviewer.identity.toLowerCase()) {
146
- context.addIssue({
147
- code: 'custom',
148
- message: 'Author and reviewer identities must be distinct.',
149
- path: ['roles'],
150
- });
151
- }
152
- if ([value.roles.author, value.roles.reviewer].some((role) => role.authSource !== 'personal' && /^personal(?:$|[-_])/iu.test(role.identity))) {
153
- context.addIssue({
154
- code: 'custom',
155
- message: 'App role identities cannot be personal identities.',
156
- path: ['roles'],
157
- });
158
- }
159
- const authorEnv = Object.values(value.roles.author.credentialEnv);
160
- const reviewerEnv = Object.values(value.roles.reviewer.credentialEnv);
161
- if (new Set([...authorEnv, ...reviewerEnv]).size !== authorEnv.length + reviewerEnv.length) {
162
- context.addIssue({
163
- code: 'custom',
164
- message: 'Author and reviewer credential environment names must be distinct.',
165
- path: ['roles'],
166
- });
167
- }
168
- if (new Set(Object.values(value.native.project.statuses)).size !== 4) {
169
- context.addIssue({
170
- code: 'custom',
171
- message: 'Project statuses must be distinct.',
172
- path: ['native', 'project', 'statuses'],
173
- });
174
- }
175
- if (value.native.points.values.some((point) => !/^[1-9]\d*$/u.test(point) || !Number.isSafeInteger(Number(point)))) {
176
- context.addIssue({
177
- code: 'custom',
178
- message: 'Point values must be positive safe integers.',
179
- path: ['native', 'points', 'values'],
180
- });
181
- }
182
- if (value.native.points.name === value.native.priority.name) {
183
- context.addIssue({ code: 'custom', message: 'Points and priority fields must be distinct.', path: ['native'] });
184
- }
185
- if (value.native.points.databaseId === value.native.priority.databaseId) {
186
- context.addIssue({
187
- code: 'custom',
188
- message: 'Points and priority field IDs must be distinct.',
189
- path: ['native'],
190
- });
191
- }
103
+ const DeliveryConfigSchema = z.object({
104
+ wipLimits: WipLimits.optional(),
105
+ commandPolicy: z.object({
106
+ checks: z.object({
107
+ format: z.enum(["REQUIRED", "OPTIONAL", "SKIP"]),
108
+ gitClean: z.enum(["REQUIRED", "OPTIONAL", "SKIP"]),
109
+ lint: z.enum(["REQUIRED", "OPTIONAL", "SKIP"]),
110
+ test: z.enum(["REQUIRED", "OPTIONAL", "SKIP"]),
111
+ typecheck: z.enum(["REQUIRED", "OPTIONAL", "SKIP"])
112
+ }).strict(),
113
+ timeoutsMs: z.object({
114
+ lint: PositiveInteger,
115
+ test: PositiveInteger,
116
+ typecheck: PositiveInteger
117
+ }).strict()
118
+ }).strict(),
119
+ native: z.object({
120
+ issueTypes: UniqueNames,
121
+ milestones: z.literal("repository"),
122
+ organization: Name,
123
+ points: NativeField,
124
+ priority: NativeField,
125
+ project: z.object({
126
+ number: PositiveInteger,
127
+ statuses: z.object({
128
+ blocked: Name,
129
+ done: Name,
130
+ inProgress: Name,
131
+ todo: Name
132
+ }).strict(),
133
+ statusField: Name,
134
+ title: Name
135
+ }).strict(),
136
+ relationships: z.object({
137
+ blockedBy: z.literal("native"),
138
+ parent: z.literal("native")
139
+ }).strict()
140
+ }).strict(),
141
+ policy: z.object({
142
+ contract: z.enum([DELIVERY_POLICY_CONTRACT, "RepositoryDeliveryPolicy@2"]),
143
+ module: z.string().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u)
144
+ }).strict(),
145
+ repository: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u),
146
+ roles: z.object({ author: AuthorRole, reviewer: AppRole }).strict(),
147
+ schemaVersion: z.literal("ai-delivery.config@2")
148
+ }).strict().superRefine((value, context) => {
149
+ if (value.repository.split("/")[0]?.toLowerCase() !== value.native.organization.toLowerCase()) {
150
+ context.addIssue({
151
+ code: "custom",
152
+ message: "Organization must match repository owner.",
153
+ path: ["native", "organization"]
154
+ });
155
+ }
156
+ if (value.roles.author.identity.toLowerCase() === value.roles.reviewer.identity.toLowerCase()) {
157
+ context.addIssue({
158
+ code: "custom",
159
+ message: "Author and reviewer identities must be distinct.",
160
+ path: ["roles"]
161
+ });
162
+ }
163
+ if ([value.roles.author, value.roles.reviewer].some(
164
+ (role) => role.authSource !== "personal" && /^personal(?:$|[-_])/iu.test(role.identity)
165
+ )) {
166
+ context.addIssue({
167
+ code: "custom",
168
+ message: "App role identities cannot be personal identities.",
169
+ path: ["roles"]
170
+ });
171
+ }
172
+ const authorEnv = credentialReferenceNames(value.roles.author);
173
+ const reviewerEnv = credentialReferenceNames(value.roles.reviewer);
174
+ if ((/* @__PURE__ */ new Set([...authorEnv, ...reviewerEnv])).size !== authorEnv.length + reviewerEnv.length) {
175
+ context.addIssue({
176
+ code: "custom",
177
+ message: "Author and reviewer credential environment names must be distinct.",
178
+ path: ["roles"]
179
+ });
180
+ }
181
+ if (new Set(Object.values(value.native.project.statuses)).size !== 4) {
182
+ context.addIssue({
183
+ code: "custom",
184
+ message: "Project statuses must be distinct.",
185
+ path: ["native", "project", "statuses"]
186
+ });
187
+ }
188
+ if (value.native.points.values.some((point) => !/^[1-9]\d*$/u.test(point) || !Number.isSafeInteger(Number(point)))) {
189
+ context.addIssue({
190
+ code: "custom",
191
+ message: "Point values must be positive safe integers.",
192
+ path: ["native", "points", "values"]
193
+ });
194
+ }
195
+ if (value.native.points.name === value.native.priority.name) {
196
+ context.addIssue({ code: "custom", message: "Points and priority fields must be distinct.", path: ["native"] });
197
+ }
198
+ if (value.native.points.databaseId === value.native.priority.databaseId) {
199
+ context.addIssue({
200
+ code: "custom",
201
+ message: "Points and priority field IDs must be distinct.",
202
+ path: ["native"]
203
+ });
204
+ }
192
205
  });
206
+ const NativeDeliveryConfigSchema = DeliveryConfigSchema.shape.native;
193
207
  const ModulePath = z.string().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u);
194
- const OverridesSchema = z
195
- .object({
196
- schemaVersion: z.literal('ai-delivery.config@2').optional(),
197
- repository: z
198
- .string()
199
- .regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)
200
- .optional(),
201
- remote: Name.optional(),
202
- policy: z.object({ module: ModulePath }).strict().optional(),
203
- project: PositiveInteger.optional(),
204
- pointsField: Name.optional(),
205
- priorityField: Name.optional(),
206
- statusField: Name.optional(),
207
- statuses: z.object({ blocked: Name, done: Name, inProgress: Name, todo: Name }).strict().optional(),
208
- issueTypes: UniqueNames.optional(),
209
- })
210
- .strict();
211
- const UserSettingsSchema = z
212
- .strictObject({
213
- wipLimits: WipLimits.optional(),
214
- schemaVersion: z.literal('ai-delivery.user@1'),
215
- roles: z.strictObject({
216
- author: z.discriminatedUnion('authSource', [AppRole, AuthorRole.options[1]]),
217
- reviewer: AppRole,
218
- }),
219
- project: PositiveInteger,
220
- checkoutRoots: z.array(z.string().min(1).refine(isAbsolute, 'Checkout roots must be absolute.')),
221
- pointsField: Name.optional(),
222
- priorityField: Name.optional(),
223
- statusField: Name.optional(),
224
- statuses: OverridesSchema.shape.statuses,
225
- issueTypes: UniqueNames.optional(),
226
- })
227
- .superRefine((value, context) => {
228
- const roles = value.roles;
229
- if (roles.author.identity.toLowerCase() === roles.reviewer.identity.toLowerCase())
230
- context.addIssue({
231
- code: 'custom',
232
- path: ['roles'],
233
- message: 'Author and reviewer identities must be distinct.',
234
- });
235
- if ([roles.author, roles.reviewer].some((role) => role.authSource !== 'personal' && /^personal(?:$|[-_])/iu.test(role.identity)))
236
- context.addIssue({
237
- code: 'custom',
238
- path: ['roles'],
239
- message: 'App role identities cannot be personal identities.',
240
- });
241
- if (value.statuses && new Set(Object.values(value.statuses)).size !== 4)
242
- context.addIssue({ code: 'custom', path: ['statuses'], message: 'Project statuses must be distinct.' });
243
- const names = [...Object.values(roles.author.credentialEnv), ...Object.values(roles.reviewer.credentialEnv)];
208
+ const OverridesSchema = z.object({
209
+ schemaVersion: z.literal("ai-delivery.config@2").optional(),
210
+ repository: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),
211
+ remote: Name.optional(),
212
+ policy: z.object({ module: ModulePath }).strict().optional(),
213
+ project: PositiveInteger.optional(),
214
+ pointsField: Name.optional(),
215
+ priorityField: Name.optional(),
216
+ statusField: Name.optional(),
217
+ statuses: z.object({ blocked: Name, done: Name, inProgress: Name, todo: Name }).strict().optional(),
218
+ issueTypes: UniqueNames.optional()
219
+ }).strict();
220
+ const UserSettingsSchema = z.strictObject({
221
+ wipLimits: WipLimits.optional(),
222
+ schemaVersion: z.literal("ai-delivery.user@1"),
223
+ roles: z.strictObject({
224
+ author: AuthorRole,
225
+ reviewer: AppRole
226
+ }),
227
+ reviewerProfiles: z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u), ConfiguredAppRole).optional(),
228
+ project: PositiveInteger,
229
+ checkoutRoots: z.array(z.string().min(1).refine(isAbsolute, "Checkout roots must be absolute.")),
230
+ pointsField: Name.optional(),
231
+ priorityField: Name.optional(),
232
+ statusField: Name.optional(),
233
+ statuses: OverridesSchema.shape.statuses,
234
+ issueTypes: UniqueNames.optional()
235
+ }).superRefine((value, context) => {
236
+ const roles = value.roles;
237
+ if (roles.author.identity.toLowerCase() === roles.reviewer.identity.toLowerCase())
238
+ context.addIssue({
239
+ code: "custom",
240
+ path: ["roles"],
241
+ message: "Author and reviewer identities must be distinct."
242
+ });
243
+ if ([roles.author, roles.reviewer].some(
244
+ (role) => role.authSource !== "personal" && /^personal(?:$|[-_])/iu.test(role.identity)
245
+ ))
246
+ context.addIssue({
247
+ code: "custom",
248
+ path: ["roles"],
249
+ message: "App role identities cannot be personal identities."
250
+ });
251
+ if (value.statuses && new Set(Object.values(value.statuses)).size !== 4)
252
+ context.addIssue({ code: "custom", path: ["statuses"], message: "Project statuses must be distinct." });
253
+ const profiles = [roles.reviewer, ...Object.values(value.reviewerProfiles ?? {})];
254
+ if (new Set(profiles.map((profile) => profile.identity.toLowerCase())).size !== profiles.length)
255
+ context.addIssue({
256
+ code: "custom",
257
+ path: ["reviewerProfiles"],
258
+ message: "Reviewer profile identities must be distinct; ambiguous selection is refused."
259
+ });
260
+ for (const [name, profile] of Object.entries(value.reviewerProfiles ?? {})) {
261
+ if (name !== profile.identity || profile.identity.toLowerCase() === roles.author.identity.toLowerCase() || /^personal(?:$|[-_])/iu.test(profile.identity))
262
+ context.addIssue({
263
+ code: "custom",
264
+ path: ["reviewerProfiles", name],
265
+ message: "Profile key must equal its distinct reviewer identity."
266
+ });
267
+ }
268
+ for (const profile of profiles) {
269
+ const names = [...credentialReferenceNames(roles.author), ...credentialReferenceNames(profile)];
244
270
  if (new Set(names).size !== names.length)
245
- context.addIssue({ code: 'custom', path: ['roles'], message: 'Credential environment names must be distinct.' });
271
+ context.addIssue({
272
+ code: "custom",
273
+ path: ["roles"],
274
+ message: "Credential environment names must be distinct."
275
+ });
276
+ }
246
277
  });
247
- /** The optional file contains choices, never a required copy of GitHub metadata. */
248
- export function readDeliveryOverrides(repositoryRoot) {
249
- const root = realpathSync(repositoryRoot);
250
- const path = join(root, DELIVERY_CONFIG_FILE);
251
- try {
252
- lstatSync(path);
253
- }
254
- catch (error) {
255
- if (error.code === 'ENOENT')
256
- return { overrides: {}, bytes: Buffer.alloc(0), path: null };
257
- throw new DeliveryError(`Unable to read ${DELIVERY_CONFIG_FILE}.`);
258
- }
259
- if (!isWithin(root, realpathSync(path)))
260
- throw new DeliveryError(`${DELIVERY_CONFIG_FILE} must stay within the repository root.`);
261
- try {
262
- git(root, 'ls-files', '--error-unmatch', '--', DELIVERY_CONFIG_FILE);
263
- }
264
- catch {
265
- throw new DeliveryError(`${DELIVERY_CONFIG_FILE} must be source-controlled for historical parsing.`);
266
- }
267
- const bytes = readFileSync(path);
268
- try {
269
- const raw = JSON.parse(bytes.toString('utf8'));
270
- return { overrides: OverridesSchema.parse(raw), bytes, path };
271
- }
272
- catch {
273
- throw new DeliveryError(`Invalid ${DELIVERY_CONFIG_FILE}; expected optional ai-delivery.config@2 routing overrides. Migrate authentication and command settings to the policy module's deliverySettings export.`);
274
- }
278
+ function readDeliveryOverrides(repositoryRoot) {
279
+ const root = realpathSync(repositoryRoot);
280
+ const path = join(root, DELIVERY_CONFIG_FILE);
281
+ try {
282
+ lstatSync(path);
283
+ } catch (error) {
284
+ if (error.code === "ENOENT")
285
+ return { overrides: {}, bytes: Buffer.alloc(0), path: null };
286
+ throw new DeliveryError(`Unable to read ${DELIVERY_CONFIG_FILE}.`);
287
+ }
288
+ if (!isWithin(root, realpathSync(path)))
289
+ throw new DeliveryError(`${DELIVERY_CONFIG_FILE} must stay within the repository root.`);
290
+ try {
291
+ git(root, "ls-files", "--error-unmatch", "--", DELIVERY_CONFIG_FILE);
292
+ } catch {
293
+ throw new DeliveryError(`${DELIVERY_CONFIG_FILE} must be source-controlled for historical parsing.`);
294
+ }
295
+ const bytes = readFileSync(path);
296
+ try {
297
+ const raw = JSON.parse(bytes.toString("utf8"));
298
+ return { overrides: OverridesSchema.parse(raw), bytes, path };
299
+ } catch {
300
+ throw new DeliveryError(
301
+ `Invalid ${DELIVERY_CONFIG_FILE}; expected optional ai-delivery.config@2 routing overrides. Migrate authentication and command settings to the policy module's deliverySettings export.`
302
+ );
303
+ }
275
304
  }
276
- /** Only operator-owned JSON supplies settings. Target repository files are never loaded. */
277
- export async function loadDeliverySettings(_repositoryRoot) {
278
- const path = process.env.AI_DELIVERY_CONFIG ?? join(homedir(), '.config', 'aviaratech-ai', 'ai-delivery.json');
279
- if (!isAbsolute(path))
280
- throw new DeliveryError('AI_DELIVERY_CONFIG must be an absolute user configuration path.');
281
- let bytes;
282
- try {
283
- bytes = readFileSync(path);
284
- }
285
- catch {
286
- throw new DeliveryError(`Missing user configuration ${path}; configure roles.author, roles.reviewer, project and checkoutRoots.`);
287
- }
288
- let raw;
289
- try {
290
- raw = JSON.parse(bytes.toString('utf8'));
291
- }
292
- catch {
293
- throw new DeliveryError(`Invalid user configuration JSON at ${path}.`);
294
- }
295
- const result = UserSettingsSchema.safeParse(raw);
296
- if (!result.success) {
297
- const details = result.error.issues
298
- .map((issue) => `${issue.path.join('.') || 'configuration'}: ${issue.message}`)
299
- .join('; ');
300
- throw new DeliveryError(`Invalid user configuration ${path}: ${details}`);
305
+ async function loadDeliverySettings(_repositoryRoot, options = {}) {
306
+ const inherited = options.env ?? process.env;
307
+ const path = inherited.AI_DELIVERY_CONFIG ?? join(homedir(), ".config", "aviaratech-ai", "ai-delivery.json");
308
+ if (!isAbsolute(path)) throw new DeliveryError("AI_DELIVERY_CONFIG must be an absolute user configuration path.");
309
+ let bytes;
310
+ try {
311
+ bytes = readFileSync(path);
312
+ } catch {
313
+ throw new DeliveryError(
314
+ `Missing user configuration ${path}; configure roles.author, roles.reviewer, project and checkoutRoots.`
315
+ );
316
+ }
317
+ let raw;
318
+ try {
319
+ raw = JSON.parse(bytes.toString("utf8"));
320
+ } catch {
321
+ throw new DeliveryError(`Invalid user configuration JSON at ${path}.`);
322
+ }
323
+ const result = UserSettingsSchema.safeParse(raw);
324
+ if (!result.success) {
325
+ const details = configurationIssueMessages(result.error.issues, "configuration").join("; ");
326
+ throw new DeliveryError(`Invalid user configuration ${path}: ${details}`);
327
+ }
328
+ const sourceDigest = digestValue(result.data);
329
+ const { roles, reviewerProfiles, checkoutRoots, wipLimits, schemaVersion: _schema, ...overrides } = result.data;
330
+ const credentialKeyReferences = [
331
+ ...new Set(
332
+ [roles.author, roles.reviewer, ...Object.values(reviewerProfiles ?? {})].flatMap(
333
+ (role) => "credentialEnv" in role ? role.authSource === "personal" ? [role.credentialEnv.token] : [role.credentialEnv.privateKeyPath] : appCredentialSource(role).type === "env" ? [privateKeyVariable(role)] : []
334
+ )
335
+ )
336
+ ];
337
+ if (options.reviewerIdentity !== void 0) {
338
+ const identity = options.reviewerIdentity;
339
+ const selected = identity === roles.reviewer.identity ? roles.reviewer : reviewerProfiles?.[identity];
340
+ if (!selected || !("appId" in selected) || identity === roles.author.identity)
341
+ throw new DeliveryError(
342
+ "identity: Select an explicit configured reviewer profile with provider, App ID and actorLogin."
343
+ );
344
+ roles.reviewer = selected;
345
+ }
346
+ const environment = {};
347
+ if (options.prepareEnvironment) {
348
+ const selectors = [...MACHINE_AUTH_ENV_NAMES, "TMPDIR", "TEMP", "TMP"];
349
+ if (credentialKeyReferences.some((name) => selectors.includes(name)))
350
+ throw new DeliveryError("Credential reference conflicts with an implicit execution selector.");
351
+ const reviewerSource = "appId" in roles.reviewer ? appCredentialSource(roles.reviewer) : void 0;
352
+ if (reviewerSource?.type === "command" && reviewerSource.env?.some((name) => credentialKeyReferences.includes(name)))
353
+ throw new DeliveryError(
354
+ "Selected helper environment cannot include an author or configured private-key reference."
355
+ );
356
+ const names = /* @__PURE__ */ new Set([
357
+ ...MACHINE_AUTH_ENV_NAMES,
358
+ "TMPDIR",
359
+ "TEMP",
360
+ "TMP",
361
+ ...Object.values(roles).flatMap(credentialReferenceNames)
362
+ ]);
363
+ for (const name of names) {
364
+ if (/^(?:NODE_|NPM_|DYLD_|LD_|BASH_|GIT_)/u.test(name) || ["ENV", "BASH_ENV", "SHELLOPTS", "CDPATH"].includes(name))
365
+ throw new DeliveryError("Credential environment reference conflicts with an execution selector.");
366
+ if (inherited[name] !== void 0) environment[name] = inherited[name];
301
367
  }
302
- const { roles, checkoutRoots, wipLimits, schemaVersion: _schema, ...overrides } = result.data;
303
- return {
304
- roles,
305
- checkoutRoots,
306
- ...(wipLimits === undefined ? {} : { wipLimits }),
307
- configPath: path,
308
- overrides,
309
- sourceDigest: digestValue(result.data),
310
- };
368
+ environment.AI_DELIVERY_CONFIG = path;
369
+ }
370
+ return {
371
+ credentialKeyReferences,
372
+ ...options.prepareEnvironment ? { environment } : {},
373
+ roles,
374
+ checkoutRoots,
375
+ ...wipLimits === void 0 ? {} : { wipLimits },
376
+ configPath: path,
377
+ overrides,
378
+ sourceDigest
379
+ };
311
380
  }
312
- export async function loadDeliveryConfig(repositoryRoot, options = {}) {
313
- options.signal?.throwIfAborted();
314
- const settings = await loadDeliverySettings();
315
- const repository = options.repository ??
316
- (() => {
317
- const coordinates = resolveRepoFromRemote(repositoryRoot, 'origin');
318
- return `${coordinates.owner}/${coordinates.repo}`;
319
- })();
320
- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(repository))
321
- throw new DeliveryError('Repository must be owner/name.');
322
- const clients = options.clients ??
323
- (await createDeliveryGitHubClients({
324
- config: settings,
325
- identity: options.personalAuth === true && settings.roles.author.authSource !== 'personal'
326
- ? 'personal'
327
- : settings.roles.author.identity,
328
- role: 'author',
329
- ...(options.personalAuth === true ? { personalAuth: { enabled: true } } : {}),
330
- ...(options.signal === undefined ? {} : { signal: options.signal }),
331
- }));
332
- let routing;
333
- try {
334
- routing = await discoverDeliveryRouting({
335
- clients,
336
- repository,
337
- overrides: settings.overrides,
338
- repositorySelected: options.repository !== undefined,
339
- });
340
- }
341
- catch (error) {
342
- if (error instanceof DeliveryError)
343
- throw error;
344
- if (options.clients === undefined &&
345
- settings.roles.author.authSource === 'personal' &&
346
- error.status === 401)
347
- throw new DeliveryError('Configured personal author token is invalid or expired; refresh the selected token.');
348
- throw error;
349
- }
350
- const config = {
351
- ...(settings.wipLimits === undefined ? {} : { wipLimits: settings.wipLimits }),
352
- schemaVersion: 'ai-delivery.github@1',
353
- repository: routing.repository,
354
- roles: settings.roles,
355
- native: routing.native,
356
- };
357
- if (options.clients === undefined)
358
- retainMachineAuthorForConfiguration(config, clients, options.signal);
359
- return {
360
- config,
361
- configDigest: digestValue({ sourceDigest: settings.sourceDigest, routing, roles: config.roles }),
362
- configPath: settings.configPath,
363
- routing,
364
- };
381
+ async function loadDeliveryConfig(repositoryRoot, options = {}) {
382
+ options.signal?.throwIfAborted();
383
+ const settings = options.settings ?? await loadDeliverySettings();
384
+ const repository = options.repository ?? (() => {
385
+ const coordinates = resolveRepoFromRemote(repositoryRoot, "origin");
386
+ return `${coordinates.owner}/${coordinates.repo}`;
387
+ })();
388
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(repository))
389
+ throw new DeliveryError("Repository must be owner/name.");
390
+ const clients = options.clients ?? await createDeliveryGitHubClients({
391
+ config: settings,
392
+ ...options.env === void 0 ? {} : { env: options.env },
393
+ identity: options.personalAuth === true && settings.roles.author.authSource !== "personal" ? "personal" : settings.roles.author.identity,
394
+ role: "author",
395
+ ...options.personalAuth === true ? { personalAuth: { enabled: true } } : {},
396
+ ...options.signal === void 0 ? {} : { signal: options.signal }
397
+ });
398
+ let routing;
399
+ try {
400
+ routing = await discoverDeliveryRouting({
401
+ clients,
402
+ repository,
403
+ overrides: settings.overrides,
404
+ repositorySelected: options.repository !== void 0,
405
+ ...options.readPageLimit === void 0 ? {} : { maxPages: options.readPageLimit },
406
+ ...options.requireWritableProject === void 0 ? {} : { requireWritableProject: options.requireWritableProject }
407
+ });
408
+ } catch (error) {
409
+ if (error instanceof DeliveryError) throw error;
410
+ if (options.clients === void 0 && settings.roles.author.authSource === "personal" && error.status === 401)
411
+ throw new DeliveryError("Configured personal author token is invalid or expired; refresh the selected token.");
412
+ throw error;
413
+ }
414
+ const config = {
415
+ ...settings.credentialKeyReferences === void 0 ? {} : { credentialKeyReferences: settings.credentialKeyReferences },
416
+ ...settings.wipLimits === void 0 ? {} : { wipLimits: settings.wipLimits },
417
+ schemaVersion: "ai-delivery.github@1",
418
+ repository: routing.repository,
419
+ roles: settings.roles,
420
+ native: routing.native
421
+ };
422
+ if (options.clients === void 0)
423
+ retainMachineAuthorForConfiguration(
424
+ config,
425
+ clients,
426
+ options.signal
427
+ );
428
+ return {
429
+ config,
430
+ configDigest: digestValue({ sourceDigest: settings.sourceDigest, routing, roles: config.roles }),
431
+ configPath: settings.configPath,
432
+ routing
433
+ };
365
434
  }
366
- export function parseDeliveryConfig(input) {
367
- const result = DeliveryConfigSchema.safeParse(input);
368
- if (!result.success) {
369
- const details = result.error.issues
370
- .map((issue) => `${issue.path.join('.') || 'config'}: ${issue.message}`)
371
- .join('; ');
372
- throw new DeliveryError(`Invalid ${DELIVERY_CONFIG_FILE}: ${details}`);
373
- }
374
- return result.data;
435
+ function parseDeliveryConfig(input) {
436
+ const result = DeliveryConfigSchema.safeParse(input);
437
+ if (!result.success) {
438
+ const details = configurationIssueMessages(result.error.issues, "config").join("; ");
439
+ throw new DeliveryError(`Invalid ${DELIVERY_CONFIG_FILE}: ${details}`);
440
+ }
441
+ return result.data;
375
442
  }
376
- export function resolveDeliveryRoleCredentials(input) {
377
- const { config, role } = input;
378
- if (config.roles[role].authSource === 'personal') {
379
- throw new DeliveryError('Personal author credentials use the configured token environment variable.');
380
- }
381
- const env = input.env ?? process.env;
382
- const names = config.roles[role].credentialEnv;
383
- const values = {
384
- appId: env[names.appId]?.trim(),
385
- installationId: env[names.installationId]?.trim(),
386
- privateKeyPath: env[names.privateKeyPath]?.trim(),
387
- };
388
- if (!values.appId || !values.installationId || !values.privateKeyPath) {
389
- throw new DeliveryError(`Missing GitHub App credentials for ${role} role. Set ${names.appId}, ${names.installationId} and ${names.privateKeyPath}.`);
390
- }
391
- if (!isAbsolute(values.privateKeyPath)) {
392
- throw new DeliveryError(`GitHub App private-key path for ${role} role (${names.privateKeyPath}) must be absolute.`);
393
- }
394
- const installationId = Number(values.installationId);
395
- if (!Number.isSafeInteger(installationId) || installationId <= 0) {
396
- throw new DeliveryError(`Invalid GitHub App installation ID for ${role} role (${names.installationId}).`);
397
- }
398
- const appId = Number(values.appId);
399
- if (!Number.isSafeInteger(appId) || appId <= 0) {
400
- throw new DeliveryError(`Invalid GitHub App ID for ${role} role (${names.appId}).`);
401
- }
402
- return { appId: values.appId, installationId, privateKeyPath: values.privateKeyPath };
443
+ function resolveDeliveryRoleCredentials(input) {
444
+ const { config, role } = input;
445
+ if (config.roles[role].authSource === "personal") {
446
+ throw new DeliveryError("Personal author credentials use the configured token environment variable.");
447
+ }
448
+ const env = input.env ?? process.env;
449
+ const selected = config.roles[role];
450
+ if ("appId" in selected)
451
+ return { appId: String(selected.appId), installationId: selected.installationId, profile: selected };
452
+ const names = selected.credentialEnv;
453
+ const values = {
454
+ appId: env[names.appId]?.trim(),
455
+ installationId: env[names.installationId]?.trim(),
456
+ privateKeyPath: env[names.privateKeyPath]?.trim()
457
+ };
458
+ if (!values.appId || !values.installationId || !values.privateKeyPath) {
459
+ throw new DeliveryError(
460
+ `Missing GitHub App credentials for ${role} role. Set ${names.appId}, ${names.installationId} and ${names.privateKeyPath}.`
461
+ );
462
+ }
463
+ if (!isAbsolute(values.privateKeyPath)) {
464
+ throw new DeliveryError(`GitHub App private-key path for ${role} role (${names.privateKeyPath}) must be absolute.`);
465
+ }
466
+ const installationId = Number(values.installationId);
467
+ if (!Number.isSafeInteger(installationId) || installationId <= 0) {
468
+ throw new DeliveryError(`Invalid GitHub App installation ID for ${role} role (${names.installationId}).`);
469
+ }
470
+ const appId = Number(values.appId);
471
+ if (!Number.isSafeInteger(appId) || appId <= 0) {
472
+ throw new DeliveryError(`Invalid GitHub App ID for ${role} role (${names.appId}).`);
473
+ }
474
+ return { appId: values.appId, installationId, privateKeyPath: values.privateKeyPath };
403
475
  }
404
476
  function isWithin(root, path) {
405
- const relation = relative(root, path);
406
- return (relation !== '..' && !relation.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) && !isAbsolute(relation));
477
+ const relation = relative(root, path);
478
+ return relation !== ".." && !relation.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) && !isAbsolute(relation);
407
479
  }
408
- //# sourceMappingURL=deliveryConfig.js.map
480
+ export {
481
+ DELIVERY_CONFIG_FILE,
482
+ DELIVERY_POLICY_CONTRACT,
483
+ NativeDeliveryConfigSchema,
484
+ ReviewProvider,
485
+ WipLimits,
486
+ appCredentialSource,
487
+ credentialReferenceNames,
488
+ loadDeliveryConfig,
489
+ loadDeliverySettings,
490
+ parseDeliveryConfig,
491
+ privateKeyVariable,
492
+ readDeliveryOverrides,
493
+ resolveDeliveryRoleCredentials
494
+ };
495
+ //# sourceMappingURL=deliveryConfig.js.map