@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,413 +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
  });
193
- export const NativeDeliveryConfigSchema = DeliveryConfigSchema.shape.native;
206
+ const NativeDeliveryConfigSchema = DeliveryConfigSchema.shape.native;
194
207
  const ModulePath = z.string().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u);
195
- const OverridesSchema = z
196
- .object({
197
- schemaVersion: z.literal('ai-delivery.config@2').optional(),
198
- repository: z
199
- .string()
200
- .regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)
201
- .optional(),
202
- remote: Name.optional(),
203
- policy: z.object({ module: ModulePath }).strict().optional(),
204
- project: PositiveInteger.optional(),
205
- pointsField: Name.optional(),
206
- priorityField: Name.optional(),
207
- statusField: Name.optional(),
208
- statuses: z.object({ blocked: Name, done: Name, inProgress: Name, todo: Name }).strict().optional(),
209
- issueTypes: UniqueNames.optional(),
210
- })
211
- .strict();
212
- const UserSettingsSchema = z
213
- .strictObject({
214
- wipLimits: WipLimits.optional(),
215
- schemaVersion: z.literal('ai-delivery.user@1'),
216
- roles: z.strictObject({
217
- author: z.discriminatedUnion('authSource', [AppRole, AuthorRole.options[1]]),
218
- reviewer: AppRole,
219
- }),
220
- project: PositiveInteger,
221
- checkoutRoots: z.array(z.string().min(1).refine(isAbsolute, 'Checkout roots must be absolute.')),
222
- pointsField: Name.optional(),
223
- priorityField: Name.optional(),
224
- statusField: Name.optional(),
225
- statuses: OverridesSchema.shape.statuses,
226
- issueTypes: UniqueNames.optional(),
227
- })
228
- .superRefine((value, context) => {
229
- const roles = value.roles;
230
- if (roles.author.identity.toLowerCase() === roles.reviewer.identity.toLowerCase())
231
- context.addIssue({
232
- code: 'custom',
233
- path: ['roles'],
234
- message: 'Author and reviewer identities must be distinct.',
235
- });
236
- if ([roles.author, roles.reviewer].some((role) => role.authSource !== 'personal' && /^personal(?:$|[-_])/iu.test(role.identity)))
237
- context.addIssue({
238
- code: 'custom',
239
- path: ['roles'],
240
- message: 'App role identities cannot be personal identities.',
241
- });
242
- if (value.statuses && new Set(Object.values(value.statuses)).size !== 4)
243
- context.addIssue({ code: 'custom', path: ['statuses'], message: 'Project statuses must be distinct.' });
244
- 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)];
245
270
  if (new Set(names).size !== names.length)
246
- 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
+ }
247
277
  });
248
- /** The optional file contains choices, never a required copy of GitHub metadata. */
249
- export function readDeliveryOverrides(repositoryRoot) {
250
- const root = realpathSync(repositoryRoot);
251
- const path = join(root, DELIVERY_CONFIG_FILE);
252
- try {
253
- lstatSync(path);
254
- }
255
- catch (error) {
256
- if (error.code === 'ENOENT')
257
- return { overrides: {}, bytes: Buffer.alloc(0), path: null };
258
- throw new DeliveryError(`Unable to read ${DELIVERY_CONFIG_FILE}.`);
259
- }
260
- if (!isWithin(root, realpathSync(path)))
261
- throw new DeliveryError(`${DELIVERY_CONFIG_FILE} must stay within the repository root.`);
262
- try {
263
- git(root, 'ls-files', '--error-unmatch', '--', DELIVERY_CONFIG_FILE);
264
- }
265
- catch {
266
- throw new DeliveryError(`${DELIVERY_CONFIG_FILE} must be source-controlled for historical parsing.`);
267
- }
268
- const bytes = readFileSync(path);
269
- try {
270
- const raw = JSON.parse(bytes.toString('utf8'));
271
- return { overrides: OverridesSchema.parse(raw), bytes, path };
272
- }
273
- catch {
274
- 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.`);
275
- }
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
+ }
276
304
  }
277
- /** Only operator-owned JSON supplies settings. Target repository files are never loaded. */
278
- export async function loadDeliverySettings(_repositoryRoot) {
279
- const path = process.env.AI_DELIVERY_CONFIG ?? join(homedir(), '.config', 'aviaratech-ai', 'ai-delivery.json');
280
- if (!isAbsolute(path))
281
- throw new DeliveryError('AI_DELIVERY_CONFIG must be an absolute user configuration path.');
282
- let bytes;
283
- try {
284
- bytes = readFileSync(path);
285
- }
286
- catch {
287
- throw new DeliveryError(`Missing user configuration ${path}; configure roles.author, roles.reviewer, project and checkoutRoots.`);
288
- }
289
- let raw;
290
- try {
291
- raw = JSON.parse(bytes.toString('utf8'));
292
- }
293
- catch {
294
- throw new DeliveryError(`Invalid user configuration JSON at ${path}.`);
295
- }
296
- const result = UserSettingsSchema.safeParse(raw);
297
- if (!result.success) {
298
- const details = result.error.issues
299
- .map((issue) => `${issue.path.join('.') || 'configuration'}: ${issue.message}`)
300
- .join('; ');
301
- 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];
302
367
  }
303
- const { roles, checkoutRoots, wipLimits, schemaVersion: _schema, ...overrides } = result.data;
304
- return {
305
- roles,
306
- checkoutRoots,
307
- ...(wipLimits === undefined ? {} : { wipLimits }),
308
- configPath: path,
309
- overrides,
310
- sourceDigest: digestValue(result.data),
311
- };
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
+ };
312
380
  }
313
- export async function loadDeliveryConfig(repositoryRoot, options = {}) {
314
- options.signal?.throwIfAborted();
315
- const settings = await loadDeliverySettings();
316
- const repository = options.repository ??
317
- (() => {
318
- const coordinates = resolveRepoFromRemote(repositoryRoot, 'origin');
319
- return `${coordinates.owner}/${coordinates.repo}`;
320
- })();
321
- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(repository))
322
- throw new DeliveryError('Repository must be owner/name.');
323
- const clients = options.clients ??
324
- (await createDeliveryGitHubClients({
325
- config: settings,
326
- identity: options.personalAuth === true && settings.roles.author.authSource !== 'personal'
327
- ? 'personal'
328
- : settings.roles.author.identity,
329
- role: 'author',
330
- ...(options.personalAuth === true ? { personalAuth: { enabled: true } } : {}),
331
- ...(options.signal === undefined ? {} : { signal: options.signal }),
332
- }));
333
- let routing;
334
- try {
335
- routing = await discoverDeliveryRouting({
336
- clients,
337
- repository,
338
- overrides: settings.overrides,
339
- repositorySelected: options.repository !== undefined,
340
- ...(options.readPageLimit === undefined ? {} : { maxPages: options.readPageLimit }),
341
- ...(options.requireWritableProject === undefined
342
- ? {}
343
- : { requireWritableProject: options.requireWritableProject }),
344
- });
345
- }
346
- catch (error) {
347
- if (error instanceof DeliveryError)
348
- throw error;
349
- if (options.clients === undefined &&
350
- settings.roles.author.authSource === 'personal' &&
351
- error.status === 401)
352
- throw new DeliveryError('Configured personal author token is invalid or expired; refresh the selected token.');
353
- throw error;
354
- }
355
- const config = {
356
- ...(settings.wipLimits === undefined ? {} : { wipLimits: settings.wipLimits }),
357
- schemaVersion: 'ai-delivery.github@1',
358
- repository: routing.repository,
359
- roles: settings.roles,
360
- native: routing.native,
361
- };
362
- if (options.clients === undefined)
363
- retainMachineAuthorForConfiguration(config, clients, options.signal);
364
- return {
365
- config,
366
- configDigest: digestValue({ sourceDigest: settings.sourceDigest, routing, roles: config.roles }),
367
- configPath: settings.configPath,
368
- routing,
369
- };
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
+ };
370
434
  }
371
- export function parseDeliveryConfig(input) {
372
- const result = DeliveryConfigSchema.safeParse(input);
373
- if (!result.success) {
374
- const details = result.error.issues
375
- .map((issue) => `${issue.path.join('.') || 'config'}: ${issue.message}`)
376
- .join('; ');
377
- throw new DeliveryError(`Invalid ${DELIVERY_CONFIG_FILE}: ${details}`);
378
- }
379
- 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;
380
442
  }
381
- export function resolveDeliveryRoleCredentials(input) {
382
- const { config, role } = input;
383
- if (config.roles[role].authSource === 'personal') {
384
- throw new DeliveryError('Personal author credentials use the configured token environment variable.');
385
- }
386
- const env = input.env ?? process.env;
387
- const names = config.roles[role].credentialEnv;
388
- const values = {
389
- appId: env[names.appId]?.trim(),
390
- installationId: env[names.installationId]?.trim(),
391
- privateKeyPath: env[names.privateKeyPath]?.trim(),
392
- };
393
- if (!values.appId || !values.installationId || !values.privateKeyPath) {
394
- throw new DeliveryError(`Missing GitHub App credentials for ${role} role. Set ${names.appId}, ${names.installationId} and ${names.privateKeyPath}.`);
395
- }
396
- if (!isAbsolute(values.privateKeyPath)) {
397
- throw new DeliveryError(`GitHub App private-key path for ${role} role (${names.privateKeyPath}) must be absolute.`);
398
- }
399
- const installationId = Number(values.installationId);
400
- if (!Number.isSafeInteger(installationId) || installationId <= 0) {
401
- throw new DeliveryError(`Invalid GitHub App installation ID for ${role} role (${names.installationId}).`);
402
- }
403
- const appId = Number(values.appId);
404
- if (!Number.isSafeInteger(appId) || appId <= 0) {
405
- throw new DeliveryError(`Invalid GitHub App ID for ${role} role (${names.appId}).`);
406
- }
407
- 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 };
408
475
  }
409
476
  function isWithin(root, path) {
410
- const relation = relative(root, path);
411
- 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);
412
479
  }
413
- //# 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