@defrex/autobuild 1.5.0 → 1.7.0

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 (126) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +192 -24
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/answering-blocked-builds.md +7 -4
  5. package/docs/architecture.md +100 -32
  6. package/docs/configuration-overview.md +10 -0
  7. package/docs/configuration.md +340 -10
  8. package/docs/dispatcher.md +2 -2
  9. package/docs/forges.md +1 -0
  10. package/docs/glossary.md +1 -1
  11. package/docs/operating.md +1 -1
  12. package/docs/operator-api.md +33 -10
  13. package/docs/operator-surfaces.md +6 -3
  14. package/docs/plugin-authoring.md +48 -6
  15. package/docs/remote-store-protocol.md +33 -10
  16. package/docs/restacking.md +16 -7
  17. package/docs/ticket-sources.md +34 -6
  18. package/docs/tickets.md +7 -1
  19. package/docs/troubleshooting.md +1 -1
  20. package/docs/workspaces.md +1 -1
  21. package/package.json +3 -3
  22. package/packages/core/src/cli/attention.ts +3 -0
  23. package/packages/core/src/cli/binary-direct.ts +1 -0
  24. package/packages/core/src/cli/dashboard/model.ts +14 -4
  25. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  26. package/packages/core/src/cli/dashboard/render.ts +3 -0
  27. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  28. package/packages/core/src/cli/dispatch-preflight.ts +5 -1
  29. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  30. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  31. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  32. package/packages/core/src/cli/dispatch.ts +377 -101
  33. package/packages/core/src/cli/help.ts +15 -6
  34. package/packages/core/src/cli/init-validation.ts +14 -1
  35. package/packages/core/src/cli/repo-lease.ts +225 -0
  36. package/packages/core/src/cli/repository-status.ts +40 -3
  37. package/packages/core/src/cli/status.ts +21 -13
  38. package/packages/core/src/cli/ticket.ts +22 -4
  39. package/packages/core/src/cli/wait.ts +4 -1
  40. package/packages/core/src/cli/watch.ts +17 -4
  41. package/packages/core/src/config/live.ts +4 -0
  42. package/packages/core/src/config/profiles.ts +96 -0
  43. package/packages/core/src/config/ready-assignee.ts +43 -11
  44. package/packages/core/src/config/roles.ts +33 -10
  45. package/packages/core/src/config/schema.ts +204 -26
  46. package/packages/core/src/events/catalog.ts +2 -0
  47. package/packages/core/src/events/compatibility.ts +3 -1
  48. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  49. package/packages/core/src/events/payloads.ts +23 -0
  50. package/packages/core/src/events/policy.ts +3 -0
  51. package/packages/core/src/events/repository.ts +19 -0
  52. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +267 -352
  53. package/packages/core/src/kernel/build-creation.ts +29 -0
  54. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  55. package/packages/core/src/kernel/engine.ts +13 -6
  56. package/packages/core/src/kernel/forge-health.ts +47 -0
  57. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  58. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  59. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  60. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  61. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  62. package/packages/core/src/kernel/log-index.ts +1 -1
  63. package/packages/core/src/kernel/node-landing.ts +2 -1
  64. package/packages/core/src/kernel/node-parent.ts +2 -0
  65. package/packages/core/src/kernel/read-facts.ts +9 -1
  66. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  67. package/packages/core/src/kernel/reducer.ts +75 -4
  68. package/packages/core/src/kernel/ticket-preparation.ts +15 -8
  69. package/packages/core/src/operator/protocol.ts +10 -0
  70. package/packages/core/src/operator/query.ts +16 -13
  71. package/packages/core/src/operator/registry.ts +25 -5
  72. package/packages/core/src/operator/sandbox-host.ts +3 -0
  73. package/packages/core/src/operator/tickets.ts +15 -3
  74. package/packages/core/src/plugin-sdk/index.ts +4 -0
  75. package/packages/core/src/ports/forge/create.ts +6 -0
  76. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  77. package/packages/core/src/ports/forge/github.ts +12 -1
  78. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  79. package/packages/core/src/ports/forge-failure.ts +31 -2
  80. package/packages/core/src/ports/runner/routing.ts +66 -5
  81. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  82. package/packages/core/src/ports/tickets/contract.ts +164 -4
  83. package/packages/core/src/ports/tickets/create.ts +35 -7
  84. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  85. package/packages/core/src/ports/tickets/github.ts +247 -29
  86. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  87. package/packages/core/src/ports/tickets/operations.ts +6 -1
  88. package/packages/core/src/ports/tickets/tree.ts +12 -2
  89. package/packages/core/src/ports/tickets/update.ts +6 -2
  90. package/packages/core/src/ports/types.ts +37 -3
  91. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  92. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  93. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  94. package/packages/core/src/ports/workspace/vercel-sandbox.ts +12 -0
  95. package/packages/core/src/processes/build-child.ts +28 -7
  96. package/packages/core/src/processes/build-execution-state.ts +4 -1
  97. package/packages/core/src/processes/build-runner.ts +17 -2
  98. package/packages/core/src/processes/dispatcher.ts +329 -59
  99. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  100. package/packages/core/src/processes/harvest-child.ts +8 -2
  101. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  102. package/packages/core/src/processes/harvest-runner.ts +251 -17
  103. package/packages/core/src/processes/repo-view.ts +2 -0
  104. package/packages/core/src/scenarios/harness.ts +160 -36
  105. package/packages/core/src/store/reduced-reads.ts +10 -0
  106. package/packages/core/src/store/reducer-value-shapes.json +3339 -2898
  107. package/packages/core/src/store/remote/client.ts +21 -8
  108. package/packages/core/src/store/remote/index.ts +4 -0
  109. package/packages/core/src/store/remote/protocol.ts +7 -0
  110. package/packages/core/src/store/remote/released-clients.json +22 -0
  111. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  112. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  113. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  114. package/packages/core/src/store/repo-state-events.ts +1 -0
  115. package/packages/core/src/store/types.ts +11 -0
  116. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  117. package/packages/core/src/testing/index.ts +2 -0
  118. package/packages/core/src/testing/reduced-read-budget.ts +411 -11
  119. package/skills/guide/SKILL.md +166 -35
  120. package/skills/guide/references/operator-api.md +33 -10
  121. package/skills/guide/references/plugin-authoring.md +48 -6
  122. package/skills/guide/references/remote-store-protocol.md +33 -10
  123. package/skills/guide/references/restacking.md +16 -7
  124. package/skills/operate/SKILL.md +79 -14
  125. package/skills/tickets/SKILL.md +22 -4
  126. package/templates/hosted-service/package.json +2 -2
@@ -28,8 +28,11 @@ import {
28
28
  } from '../ports/workspace/provider-capabilities'
29
29
  import { defineEntry, openMap, ownEntries, parseEntry } from '../open-map'
30
30
  import { forwardIssues } from '../zod-issues'
31
- import { effectiveRuntimeReferences } from './roles'
31
+ import { displayName, effectiveRuntimeReferences, RESERVED_ROLE } from './roles'
32
+ import { normalizeProfileLabel, profileRoles } from './profiles'
32
33
  import {
34
+ createAssigneeUnsupported,
35
+ GITHUB_CREATE_ASSIGNEE,
33
36
  GITHUB_READY_ASSIGNEE,
34
37
  LINEAR_READY_ASSIGNEE,
35
38
  readyAssigneeUnsupported,
@@ -727,10 +730,70 @@ documentSchema(roleSchema.shape.alternates, {
727
730
  })
728
731
  export type RoleConfig = z.infer<typeof roleSchema>
729
732
 
733
+ // ── [profiles] ───────────────────────────────────────────────────────────────
734
+ //
735
+ // Open map: profile → one ticket label plus role entries (SPEC §9). A build
736
+ // whose ticket carries the label at claim resolves its roles through this
737
+ // overlay. Label uniqueness, nonblank labels, the refused `default` entry and
738
+ // overlaid account selection are cross-validated in configSchema below;
739
+ // runtime and model compatibility is checked by the eager resolver.
740
+
741
+ const profileRoleSchema = roleSchema.extend({
742
+ // A distinct field schema so its reference names the profile inheritance
743
+ // order; the repository role's own budget sits between the entry and default.
744
+ sessionBudgetSeconds: z.number().int().positive().optional(),
745
+ })
746
+ documentSchema(profileRoleSchema.shape.sessionBudgetSeconds, {
747
+ description:
748
+ 'Active-time budget for each build phase session routed through this role in a profiled build. Suspended intervals are excluded; native continuation retains the original ceiling and accumulated active time. One budget covers the primary and every alternate target.',
749
+ constraints:
750
+ 'Omission inherits roles.<role>.sessionBudgetSeconds, then roles.default.sessionBudgetSeconds, otherwise policy.sessionBudgetSeconds.',
751
+ })
752
+ documentSchema(profileRoleSchema, {
753
+ description:
754
+ "Role override for builds whose ticket carries the profile's label. Omitted fields inherit `[roles.<role>]`, then `[roles.default]`; a declared alternates list, including [], replaces the inherited list.",
755
+ })
756
+
757
+ const profileSchema = z.strictObject({
758
+ label: z.string(),
759
+ roles: openMap('[profiles.<name>.roles]', profileRoleSchema),
760
+ })
761
+ documentFields(profileSchema, {
762
+ label:
763
+ "Ticket label that selects this profile, matched case-insensitively after trimming. A ticket carrying two profiles' labels is not claimed.",
764
+ roles:
765
+ 'Role entries this profile overrides. Any role name is accepted except the reserved default.',
766
+ })
767
+ documentSchema(profileSchema.shape.label, {
768
+ constraints: 'Nonblank; unique across profiles after trimming and case folding.',
769
+ })
770
+ documentSchema(profileSchema.shape.roles, {
771
+ constraints: 'An entry named default is refused',
772
+ })
773
+ documentSchema(profileSchema, {
774
+ description:
775
+ "Named role profile. The build's profile is fixed when its ticket is claimed; the profile's contents are read at each session boundary.",
776
+ })
777
+
730
778
  // ── [policy] ─────────────────────────────────────────────────────────────────
731
779
 
780
+ const DISPATCH_LEASE_PAIR_MESSAGE =
781
+ 'policy.dispatchLeaseTimeoutSeconds and policy.dispatchLeaseRenewalSeconds must be positive integers, with dispatchLeaseRenewalSeconds less than dispatchLeaseTimeoutSeconds'
782
+
732
783
  export const policySchema = z.strictObject({
733
784
  upgradeDrainSeconds: z.number().int().positive().default(900),
785
+ /** Repository dispatch lease lifetime without renewal (SPEC §12). */
786
+ dispatchLeaseTimeoutSeconds: z
787
+ .number()
788
+ .int(DISPATCH_LEASE_PAIR_MESSAGE)
789
+ .positive(DISPATCH_LEASE_PAIR_MESSAGE)
790
+ .default(60),
791
+ /** Interval between repository dispatch lease renewals; below the timeout. */
792
+ dispatchLeaseRenewalSeconds: z
793
+ .number()
794
+ .int(DISPATCH_LEASE_PAIR_MESSAGE)
795
+ .positive(DISPATCH_LEASE_PAIR_MESSAGE)
796
+ .default(20),
734
797
  /** Wall-clock bound for an agent phase session; roles may override it. */
735
798
  sessionBudgetSeconds: z.number().int().positive().default(3600),
736
799
  /** Same-finding survival threshold before auto-escalate (§10, §15.4). */
@@ -740,7 +803,7 @@ export const policySchema = z.strictObject({
740
803
  maxDispatchAttempts: z.number().int().positive().default(3),
741
804
  /** Consecutive workspace setup failures before human intervention is required. */
742
805
  maxSetupAttempts: z.number().int().positive().default(3),
743
- /** Consecutive provider lifecycle failures before recovery requires a human retry. */
806
+ /** Consecutive provider lifecycle failures before a setup-targeted escalation; a `retry` answer from any operator, agent or human, re-arms the budget. */
744
807
  maxInfrastructureAttempts: z.number().int().positive().default(3),
745
808
  maxReconcileAttempts: z.number().int().positive().default(3),
746
809
  /** converge's `maxRounds` for the review loops (SPEC §10). */
@@ -749,6 +812,7 @@ export const policySchema = z.strictObject({
749
812
  harvestThreshold: z.number().int().positive().default(5),
750
813
  /** Merged builds after the oldest observation that start harvest; zero disables drift. */
751
814
  janitorFailureAttentionSeconds: z.number().int().positive().default(600),
815
+ janitorFailureEscalationSeconds: z.number().int().positive().default(3600),
752
816
  nodeIdleAfterSeconds: z.number().int().positive().default(600),
753
817
  nodeIdlePollSeconds: z.number().int().positive().default(120),
754
818
  janitorBackoffMaxSeconds: z.number().int().positive().default(300),
@@ -758,6 +822,10 @@ export const policySchema = z.strictObject({
758
822
  documentFields(policySchema, {
759
823
  upgradeDrainSeconds:
760
824
  'Deadline for a retiring generation, relative to handoff start; hot-reloaded during drain.',
825
+ dispatchLeaseTimeoutSeconds:
826
+ "How long the repository dispatch lease survives without renewal. A dispatcher that stalls longer reclaims it on waking unless another run took it; a standby takes over a dead holder within this bound. A change takes effect at the dispatcher's next tick.",
827
+ dispatchLeaseRenewalSeconds:
828
+ 'Interval between repository dispatch lease renewals; adopted together with the timeout.',
761
829
  sessionBudgetSeconds:
762
830
  'Active-time bound for each build agent session unless its logical role overrides it. Native continuation retains the original ceiling; suspension does not consume it.',
763
831
  stallRounds: 'Escalate when the same review finding survives this many rounds.',
@@ -774,12 +842,20 @@ documentFields(policySchema, {
774
842
  'Default bound for each plan/review and implement/review convergence loop. Your agent may replace it for one parked build loop and current spec revision with `ab answer --review-round-ceiling`; other builds are unaffected.',
775
843
  harvestThreshold: 'New unclaimed observation occurrences needed to start one harvest run.',
776
844
  janitorFailureAttentionSeconds: 'Consecutive janitor failure duration before build attention.',
845
+ janitorFailureEscalationSeconds:
846
+ 'Consecutive janitor failure duration before the build raises one escalation; the janitor keeps retrying.',
777
847
  nodeIdleAfterSeconds: 'Quiet period before opened integration nodes enter idle polling.',
778
848
  nodeIdlePollSeconds: 'Interval between idle node checks; durable activity wakes the next tick.',
779
849
  janitorBackoffMaxSeconds: 'Cap on exponential janitor retry delay, starting at 30 seconds.',
780
850
  harvestMaxDrift:
781
851
  'Other builds merged after the oldest unclaimed observation needed to start a run; `0` disables drift.',
782
852
  })
853
+ documentSchema(policySchema.shape.dispatchLeaseTimeoutSeconds, {
854
+ constraints: 'Must be greater than `dispatchLeaseRenewalSeconds`.',
855
+ })
856
+ documentSchema(policySchema.shape.dispatchLeaseRenewalSeconds, {
857
+ constraints: 'Must be less than `dispatchLeaseTimeoutSeconds`.',
858
+ })
783
859
  export type PolicyConfig = z.infer<typeof policySchema>
784
860
 
785
861
  // ── [tickets] ────────────────────────────────────────────────────────────────
@@ -843,6 +919,21 @@ export const ticketsInputSchema = z.strictObject({
843
919
  '[tickets].readyAssignee must be a nonblank value with no surrounding whitespace',
844
920
  )
845
921
  .optional(),
922
+ /**
923
+ * Assigns every ticket Autobuild creates (`ab ticket create`, operator
924
+ * `tickets.create`, harvest proposals) to one user unless the create names
925
+ * its own assignees. A ticket-source capability: the source must declare
926
+ * `assignees`. github takes `"me"` (the owner of the creating credential —
927
+ * for harvest, the filing dispatcher's) or a username. Absent sends no
928
+ * assignee.
929
+ */
930
+ createAssignee: z
931
+ .string()
932
+ .refine(
933
+ (s) => s.trim().length > 0 && s === s.trim(),
934
+ '[tickets].createAssignee must be a nonblank value with no surrounding whitespace',
935
+ )
936
+ .optional(),
846
937
  /** Backend team key (e.g. "ENG") — required for linear and hosted;
847
938
  * forbidden for github. */
848
939
  teamKey: z.string().min(1).optional(),
@@ -918,6 +1009,8 @@ documentFields(ticketsInputSchema, {
918
1009
  readyState: 'The one workflow state eligible for dispatch.',
919
1010
  readyAssignee:
920
1011
  'Require the ticket to be assigned to one user, in addition to the state and label gates.',
1012
+ createAssignee:
1013
+ 'Assign every ticket Autobuild creates (`ab ticket create`, operator `tickets.create`, harvest proposals) to one user unless the create names its own assignees.',
921
1014
  teamKey: 'Backend team key such as `"ENG"`, or an existing plugin config field.',
922
1015
  claimedState: 'Workflow state entered when a ticket is claimed.',
923
1016
  doneState: 'Project completion state and merged-ticket transition.',
@@ -950,6 +1043,10 @@ documentSchema(ticketsInputSchema.shape.readyAssignee, {
950
1043
  constraints:
951
1044
  'Allowed for sources that can filter by assignee: linear ("me" or an email), github ("me" or a GitHub username, including managed-user logins such as mona_acme), and plugin sources that declare readyAssignee. Refused for file and hosted.',
952
1045
  })
1046
+ documentSchema(ticketsInputSchema.shape.createAssignee, {
1047
+ constraints:
1048
+ 'Allowed for github ("me" or a GitHub username) and plugin sources that declare assignees. Refused for file, hosted and linear.',
1049
+ })
953
1050
  documentSchema(ticketsInputSchema.shape.readyLabels, {
954
1051
  constraints:
955
1052
  'Omission uses source readiness defaults (Linear and GitHub: autobuild label; file: none). Explicit [] disables label gating.',
@@ -1174,6 +1271,7 @@ export const configRootSchema = z.strictObject({
1174
1271
  // therefore include the complete materialized runtime list in its diagnostic.
1175
1272
  accounts: openMap('[accounts]', accountSchema).default({}),
1176
1273
  roles: openMap('[roles]', roleSchema),
1274
+ profiles: openMap('[profiles]', profileSchema),
1177
1275
  policy: policySchema.prefault({}),
1178
1276
  orchestrator: orchestratorSchema.prefault({}),
1179
1277
  // An absent [tickets] table must NOT silently default past the mandatory
@@ -1191,7 +1289,7 @@ documentFields(configRootSchema, {
1191
1289
  upgrade: 'Automatic dispatcher runtime target checks and adoption.',
1192
1290
  baseBranch: 'Branch used to cut builds, target PRs, and merge during reconciliation.',
1193
1291
  capacity:
1194
- 'Concurrent occupied slots for this repository. Paused and blocked work retains slots. Node reconcile and verification exclude their own blocked/paused descendants at admission; new claims use total occupancy. See [integration capacity](integration-tree.md).',
1292
+ 'Builds running work at once for this repository. A build that finished its pipeline holds no slot while it waits for a merge decision; it is admitted ahead of new claims when it must run again. Unfinished paused and blocked work retains slots. Node reconcile and verification exclude their own blocked/paused descendants at admission; new claims use total occupancy. See [integration capacity](integration-tree.md).',
1195
1293
  ticketScanIntervalSeconds:
1196
1294
  'Ticket-source ready scan cadence; tick spacing is the effective minimum.',
1197
1295
  forge:
@@ -1210,6 +1308,8 @@ documentFields(configRootSchema, {
1210
1308
  accounts:
1211
1309
  'Named Claude subscription, Kimi Code, or ChatGPT subscription billing accounts. Descriptors contain credential variable names only.',
1212
1310
  roles: 'Named agent roles. The reserved default role provides inherited runtime axes.',
1311
+ profiles:
1312
+ 'Named role profiles selected by ticket label. A profile overrides only the role fields it declares, for the builds that selected it.',
1213
1313
  policy: 'Lifecycle budgets, retries, convergence and harvest limits.',
1214
1314
  orchestrator:
1215
1315
  'Operator-agent sandbox settings. This table does not start or host an operator agent.',
@@ -1255,6 +1355,14 @@ const normalizedConfigSchema = configRootSchema.transform((input, ctx) => {
1255
1355
  })
1256
1356
 
1257
1357
  export const configSchema = normalizedConfigSchema.superRefine((config, ctx) => {
1358
+ const { dispatchLeaseTimeoutSeconds: leaseTimeout, dispatchLeaseRenewalSeconds: leaseRenewal } =
1359
+ config.policy
1360
+ if (leaseRenewal >= leaseTimeout)
1361
+ ctx.addIssue({
1362
+ code: 'custom',
1363
+ path: ['policy', 'dispatchLeaseRenewalSeconds'],
1364
+ message: `${DISPATCH_LEASE_PAIR_MESSAGE} (dispatchLeaseRenewalSeconds = ${leaseRenewal}, dispatchLeaseTimeoutSeconds = ${leaseTimeout})`,
1365
+ })
1258
1366
  for (const [name, account] of Object.entries(config.accounts)) {
1259
1367
  if (account.kind !== 'chatgpt-subscription') continue
1260
1368
  if (
@@ -1279,31 +1387,79 @@ export const configSchema = normalizedConfigSchema.superRefine((config, ctx) =>
1279
1387
  path: ['orchestrator', 'sandbox', 'environmentVariables'],
1280
1388
  message: `Account credential variable ${JSON.stringify(name)} cannot enter an operator sandbox`,
1281
1389
  })
1282
- const defaults = config.roles.default ?? {}
1283
- for (const [role, spec] of Object.entries(config.roles)) {
1284
- const primary = {
1285
- runtime: spec.runtime ?? defaults.runtime,
1286
- account: spec.account ?? defaults.account,
1287
- }
1288
- const targets = [
1289
- primary,
1290
- ...(spec.alternates ?? defaults.alternates ?? []).map((alt) => ({
1291
- runtime: alt.runtime ?? primary.runtime,
1292
- account: alt.account ?? primary.account,
1293
- })),
1294
- ]
1295
- targets.forEach((target, index) => {
1296
- try {
1297
- selectAccount(
1298
- config.accounts,
1299
- target.runtime,
1300
- target.account,
1301
- `role ${JSON.stringify(role)}${index ? ` alternate[${index - 1}]` : ''}`,
1302
- )
1303
- } catch (error) {
1304
- ctx.addIssue({ code: 'custom', path: ['roles', role], message: (error as Error).message })
1390
+ const checkRoleAccounts = (
1391
+ roles: Record<string, RoleConfig>,
1392
+ keys: readonly string[],
1393
+ path: (role: string) => (string | number)[],
1394
+ label: (role: string) => string,
1395
+ ) => {
1396
+ const defaults = roles.default ?? {}
1397
+ for (const role of keys) {
1398
+ const spec = roles[role]!
1399
+ const primary = {
1400
+ runtime: spec.runtime ?? defaults.runtime,
1401
+ account: spec.account ?? defaults.account,
1305
1402
  }
1403
+ const targets = [
1404
+ primary,
1405
+ ...(spec.alternates ?? defaults.alternates ?? []).map((alt) => ({
1406
+ runtime: alt.runtime ?? primary.runtime,
1407
+ account: alt.account ?? primary.account,
1408
+ })),
1409
+ ]
1410
+ targets.forEach((target, index) => {
1411
+ try {
1412
+ selectAccount(
1413
+ config.accounts,
1414
+ target.runtime,
1415
+ target.account,
1416
+ `${label(role)}${index ? ` alternate[${index - 1}]` : ''}`,
1417
+ )
1418
+ } catch (error) {
1419
+ ctx.addIssue({ code: 'custom', path: path(role), message: (error as Error).message })
1420
+ }
1421
+ })
1422
+ }
1423
+ }
1424
+ checkRoleAccounts(
1425
+ config.roles,
1426
+ Object.keys(config.roles),
1427
+ (role) => ['roles', role],
1428
+ (role) => `role ${JSON.stringify(role)}`,
1429
+ )
1430
+
1431
+ const profileLabels = new Map<string, string>()
1432
+ for (const [name, profile] of Object.entries(config.profiles ?? {})) {
1433
+ const normalized = normalizeProfileLabel(profile.label)
1434
+ if (normalized.length === 0) {
1435
+ ctx.addIssue({
1436
+ code: 'custom',
1437
+ path: ['profiles', name, 'label'],
1438
+ message: `profile ${displayName(name)} needs a nonblank label`,
1439
+ })
1440
+ } else if (profileLabels.has(normalized)) {
1441
+ ctx.addIssue({
1442
+ code: 'custom',
1443
+ path: ['profiles', name, 'label'],
1444
+ message: `profiles ${displayName(profileLabels.get(normalized)!)} and ${displayName(name)} both declare label ${displayName(profile.label.trim())}; each profile needs its own label`,
1445
+ })
1446
+ } else profileLabels.set(normalized, name)
1447
+ const keys = Object.keys(profile.roles).filter((role) => {
1448
+ if (role !== RESERVED_ROLE) return true
1449
+ ctx.addIssue({
1450
+ code: 'custom',
1451
+ path: ['profiles', name, 'roles', role],
1452
+ message: `profile ${displayName(name)} cannot override the reserved default role; name each role it changes`,
1453
+ })
1454
+ return false
1306
1455
  })
1456
+ if (config.roles !== undefined)
1457
+ checkRoleAccounts(
1458
+ profileRoles(config.roles, profile.roles),
1459
+ keys,
1460
+ (role) => ['profiles', name, 'roles', role],
1461
+ (role) => `profile ${displayName(name)} role ${JSON.stringify(role)}`,
1462
+ )
1307
1463
  }
1308
1464
 
1309
1465
  for (const kind of ['verify', 'finalize'] as const) {
@@ -1521,6 +1677,28 @@ export const configSchema = normalizedConfigSchema.superRefine((config, ctx) =>
1521
1677
  ctx.addIssue({ code: 'custom', path: ['tickets', 'readyAssignee'], message: form.message })
1522
1678
  }
1523
1679
  }
1680
+ // createAssignee is the `assignees` capability, checked the same way.
1681
+ const createAssignee = tickets.createAssignee
1682
+ if (createAssignee !== undefined) {
1683
+ if (tickets.source === 'file' || tickets.source === 'hosted' || tickets.source === 'linear') {
1684
+ ctx.addIssue({
1685
+ code: 'custom',
1686
+ path: ['tickets', 'createAssignee'],
1687
+ message: createAssigneeUnsupported(tickets.source),
1688
+ })
1689
+ } else if (
1690
+ tickets.source === 'github' &&
1691
+ createAssignee.trim().length > 0 &&
1692
+ createAssignee === createAssignee.trim() &&
1693
+ !GITHUB_CREATE_ASSIGNEE.accepts(createAssignee)
1694
+ ) {
1695
+ ctx.addIssue({
1696
+ code: 'custom',
1697
+ path: ['tickets', 'createAssignee'],
1698
+ message: GITHUB_CREATE_ASSIGNEE.message,
1699
+ })
1700
+ }
1701
+ }
1524
1702
  // Plugin sources receive the existing ticket lifecycle/configuration fields
1525
1703
  // unchanged; adapter-specific validation belongs to their factory.
1526
1704
 
@@ -47,6 +47,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
47
47
  'build.janitor-attempt-failed': ['dispatcher'],
48
48
  'build.janitor-recovered': ['dispatcher'],
49
49
  'build.janitor-failing': ['dispatcher'],
50
+ 'build.janitor-escalated': ['dispatcher'],
50
51
  'landing.application-failed': ['dispatcher', 'kernel'],
51
52
  'landing.decided': ['dispatcher', 'kernel'],
52
53
  'build.hold-requested': ['human'],
@@ -56,6 +57,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
56
57
  'landing.forge-merged': ['kernel'],
57
58
  'landing.native-applied': ['dispatcher', 'kernel'],
58
59
  'target.distance': ['dispatcher'],
60
+ 'pipeline.settled': ['dispatcher'],
59
61
  'target.rewritten': ['dispatcher', 'kernel'],
60
62
  'target.rewrite-cleared': ['dispatcher', 'kernel'],
61
63
  'target.moved': ['dispatcher', 'kernel'],
@@ -25,7 +25,9 @@ export interface StoredEvent {
25
25
  /** Change this revision whenever projection semantics change without new types. */
26
26
  // Revision 3 retains optional billing-account descriptors in session/attempt projections.
27
27
  // Revision 4 retains the optional effective prompt in session projections.
28
- export const READ_DECODER_REVISION = 4
28
+ // Revision 5 retains the optional preparation creation key.
29
+ // Revision 6 retains the optional role profile on build creation and session starts.
30
+ export const READ_DECODER_REVISION = 6
29
31
  export function catalogIdentity(
30
32
  build: Record<string, string> = buildEventPolicy,
31
33
  repository: Record<string, string> = repositoryEventPolicy,
@@ -3,9 +3,23 @@ import { forgeHealthEventPayloadSchemas } from './repository'
3
3
  /** Hosted admission horizon; never applied to historical event decoding. */
4
4
  export const MAX_FORGE_DEGRADATION_MS = 24 * 60 * 60 * 1000
5
5
 
6
- export function validateForgeDegradation(payload: unknown, now: Date): void {
7
- const parsed = forgeHealthEventPayloadSchemas['dispatcher.forge-degraded'].parse(payload)
6
+ /** Forge-health facts whose `resetAt` hosted admission bounds. */
7
+ export const FORGE_RESET_EVENT_TYPES = [
8
+ 'dispatcher.forge-degraded',
9
+ 'forge.credential-limited',
10
+ ] as const
11
+
12
+ export function validateForgeResetHorizon(
13
+ type: (typeof FORGE_RESET_EVENT_TYPES)[number],
14
+ payload: unknown,
15
+ now: Date,
16
+ ): void {
17
+ const parsed = forgeHealthEventPayloadSchemas[type].parse(payload)
8
18
  const deadline = Date.parse(parsed.resetAt)
9
19
  if (!Number.isFinite(deadline) || deadline > now.getTime() + MAX_FORGE_DEGRADATION_MS)
10
20
  throw new Error('forge resetAt must be a finite ISO deadline within 24 hours of server time')
11
21
  }
22
+
23
+ export function validateForgeDegradation(payload: unknown, now: Date): void {
24
+ validateForgeResetHorizon('dispatcher.forge-degraded', payload, now)
25
+ }
@@ -347,6 +347,10 @@ export const eventPayloadSchemas = {
347
347
  )
348
348
  .superRefine(refineUniqueIssues)
349
349
  .optional(),
350
+ /** The `[profiles.<name>]` the ticket's labels selected, frozen at claim;
351
+ * later relabelling never changes it. Omitted for builds without a
352
+ * profile and in historical logs. */
353
+ profile: z.string().min(1).optional(),
350
354
  }),
351
355
  'node.opening': z.strictObject({
352
356
  branch: z.string().min(1),
@@ -890,6 +894,16 @@ export const eventPayloadSchemas = {
890
894
  nextAttemptAt: z.iso.datetime(),
891
895
  }),
892
896
  'build.janitor-failing': z.strictObject({ message: z.string().min(1) }),
897
+ /** One per janitor failure episode that outlasts the escalation limit. The
898
+ * reducer opens it as a policy escalation and closes it on recovery. */
899
+ 'build.janitor-escalated': z.strictObject({
900
+ id: z.string().min(1),
901
+ operation: z.string().min(1),
902
+ message: z.string().min(1),
903
+ attempt: z.number().int().positive(),
904
+ firstFailureAt: z.iso.datetime(),
905
+ question: z.string().min(1),
906
+ }),
893
907
  'build.janitor-recovered': empty,
894
908
  'landing.application-failed': z.strictObject({
895
909
  candidate: landingCandidateSchema,
@@ -985,6 +999,10 @@ export const eventPayloadSchemas = {
985
999
  * continue, the interruption notice for a native resume. Absent on
986
1000
  * historical events and when the runtime cannot report it. */
987
1001
  prompt: z.string().min(1).optional(),
1002
+ /** The build's frozen profile and whether this session's configuration
1003
+ * still defined it. Present only for builds created with a profile; a
1004
+ * `configured: false` session resolved through the repository roles. */
1005
+ profile: z.strictObject({ name: z.string().min(1), configured: z.boolean() }).optional(),
988
1006
  }),
989
1007
  'session.suspended': z.strictObject({
990
1008
  session: z.string().min(1),
@@ -1216,6 +1234,11 @@ export const eventPayloadSchemas = {
1216
1234
  count: z.number().int().nonnegative().nullable(),
1217
1235
  })
1218
1236
  .refine((sample) => sample.count === null || sample.head !== null),
1237
+ /** The dispatcher observed the engine's leaf `wait awaiting-pr` decision:
1238
+ * every verify step and finalize post-step is done for this settlement key
1239
+ * (max of the verify cycle start and finalize completion seqs). Capacity
1240
+ * evidence only; no pipeline decision reads it. */
1241
+ 'pipeline.settled': z.strictObject({ cycle: z.number().int().positive() }),
1219
1242
  'target.rewritten': z.strictObject({
1220
1243
  branch: z.string().min(1),
1221
1244
  previousSha: gitOid,
@@ -14,6 +14,7 @@ export const buildEventPolicy = {
14
14
  'build.janitor-attempt-failed': 'decisive',
15
15
  'build.janitor-recovered': 'decisive',
16
16
  'build.janitor-failing': 'advisory',
17
+ 'build.janitor-escalated': 'decisive',
17
18
  'landing.application-failed': 'decisive',
18
19
  'landing.decided': 'decisive',
19
20
  'build.hold-requested': 'decisive',
@@ -23,6 +24,7 @@ export const buildEventPolicy = {
23
24
  'landing.forge-merged': 'decisive',
24
25
  'landing.native-applied': 'decisive',
25
26
  'target.distance': 'advisory',
27
+ 'pipeline.settled': 'advisory',
26
28
  'target.rewritten': 'decisive',
27
29
  'target.rewrite-cleared': 'decisive',
28
30
  'target.moved': 'decisive',
@@ -241,6 +243,7 @@ export const repositoryEventPolicy = {
241
243
  'dispatcher.ticket-source-dependency-limited': 'decisive',
242
244
  'dispatcher.forge-degraded': 'decisive',
243
245
  'dispatcher.forge-recovered': 'decisive',
246
+ 'forge.credential-limited': 'advisory',
244
247
  'dispatcher.kernel-git-unavailable': 'advisory',
245
248
  'dispatcher.kernel-git-recovered': 'advisory',
246
249
  'dispatcher.ticket-source-degraded': 'decisive',
@@ -9,6 +9,7 @@ import { hardReadinessKeys } from '../ports/forge/readiness'
9
9
  * builds or new phases in the fixed build grammar.
10
10
  */
11
11
  import { z } from 'zod'
12
+ import { CREATION_KEY } from '../kernel/build-creation'
12
13
  import {
13
14
  artifactRefSchema,
14
15
  findingSchema,
@@ -774,6 +775,17 @@ export const forgeHealthEventPayloadSchemas = {
774
775
  forge: z.string().min(1),
775
776
  reason: z.string().trim().min(1).optional(),
776
777
  }),
778
+ /** A rate limit that does not belong to the dispatcher's credential: an
779
+ * unauthenticated request, or a limit seen by a build runner or phase
780
+ * session. Advisory attention; it never pauses repository forge work. */
781
+ 'forge.credential-limited': z.strictObject({
782
+ forge: z.string().min(1),
783
+ process: z.string().min(1).max(200),
784
+ credential: z.enum(['unauthenticated', 'process']),
785
+ missingCredential: z.string().min(1).max(1000).optional(),
786
+ message: z.string().min(1).max(2000),
787
+ resetAt: z.iso.datetime(),
788
+ }),
777
789
  } as const
778
790
 
779
791
  /** The dispatcher could not execute Git for kernel-side node work. One event
@@ -823,6 +835,9 @@ export const ticketPreparationEventPayloadSchemas = {
823
835
  'ticket-preparation.creation-selected': z.strictObject({
824
836
  ...preparationIdentity,
825
837
  slug: z.string().min(1),
838
+ // Additive: present only when the store attested keyed creation, so
839
+ // recovery can point-read the canonical slug this key derives.
840
+ creationKey: z.string().regex(CREATION_KEY).optional(),
826
841
  }),
827
842
  'ticket-preparation.failed': z.strictObject({
828
843
  ...preparationIdentity,
@@ -847,6 +862,8 @@ export const ticketPreparationEventPayloadSchemas = {
847
862
  ...preparationIdentity,
848
863
  outcome: z.enum(['lost-claim', 'handed-back', 'bounced', 'owned', 'abandoned']),
849
864
  reason: z.string().min(1).max(4000).optional(),
865
+ /** Written only for `abandoned`: the claim certainty known at resolution. */
866
+ claimed: z.boolean().optional(),
850
867
  }),
851
868
  }
852
869
 
@@ -902,6 +919,7 @@ export const REPOSITORY_ATTENTION_EVENTS = [
902
919
  'harvest.failed',
903
920
  'dispatcher.forge-degraded',
904
921
  'dispatcher.forge-recovered',
922
+ 'forge.credential-limited',
905
923
  'dispatcher.kernel-git-unavailable',
906
924
  'dispatcher.kernel-git-recovered',
907
925
  'dispatcher.ticket-source-degraded',
@@ -1028,6 +1046,7 @@ const allowedActorKinds: Record<RepositoryEventType, readonly ActorKind[]> = {
1028
1046
  'dispatcher.ticket-source-dependency-limited': ['dispatcher'],
1029
1047
  'dispatcher.forge-degraded': ['dispatcher', 'kernel'],
1030
1048
  'dispatcher.forge-recovered': ['dispatcher', 'kernel', 'human'],
1049
+ 'forge.credential-limited': ['dispatcher', 'kernel'],
1031
1050
  'dispatcher.kernel-git-unavailable': ['dispatcher'],
1032
1051
  'dispatcher.kernel-git-recovered': ['dispatcher'],
1033
1052
  'dispatcher.ticket-source-degraded': ['dispatcher'],