@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
@@ -201,12 +201,12 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
201
201
  detail: page([
202
202
  'Usage:',
203
203
  ' ab ticket tree [--json]',
204
- ' ab ticket create <title> --body <file> [--state <state>] [--labels a,b] [--blocked-by id,id] [--issues N[:refs],...] [--priority urgent|normal] [--kind work|node] [--target <id> | --no-target] [--json]',
204
+ ' ab ticket create <title> --body <file> [--state <state>] [--labels a,b] [--blocked-by id,id] [--issues N[:refs],...] [--priority urgent|normal] [--assignees a,b] [--kind work|node] [--target <id> | --no-target] [--json]',
205
205
  ' ab ticket edit <id>',
206
206
  ' ab ticket export <dir> [--store <ref>]',
207
207
  ' ab ticket import <dir> [--states <state,...>] [--store <ref>]',
208
208
  ' ab ticket migration record <dir> [--store <ref>]',
209
- ' ab ticket update <id> [--kind work|node] [--target <id> | --no-target] [--title <title>] [--body <file>] [--labels a,b] [--issues N[:refs],...] [--priority urgent|normal] [--expected-revision <opaque>] [--json]',
209
+ ' ab ticket update <id> [--kind work|node] [--target <id> | --no-target] [--title <title>] [--body <file>] [--labels a,b] [--issues N[:refs],...] [--priority urgent|normal] [--assignees a,b] [--expected-revision <opaque>] [--json]',
210
210
  ' ab ticket block <id> <blocker-id[,blocker-id...]> [--expected-revision <opaque>] [--json]',
211
211
  ' ab ticket unblock <id> <blocker-id[,blocker-id...]> [--expected-revision <opaque>] [--json]',
212
212
  ' ab ticket list [--state <state>] [--labels a,b] [--json]',
@@ -243,12 +243,18 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
243
243
  'in source order; it never preempts a running build. normal (the default)',
244
244
  'removes urgency. Sources that cannot store priority refuse urgent, name the',
245
245
  'source, and write nothing; normal is a no-op there.',
246
+ '--assignees entries are usernames or me (the owner of the source credential).',
247
+ 'On create they replace the [tickets].createAssignee default and --assignees ""',
248
+ 'creates an unassigned ticket; on update they replace the set and "" clears it.',
249
+ 'Sources that cannot store assignees refuse the write, name the source, and',
250
+ 'write nothing.',
246
251
  '',
247
252
  'With no list filters, list uses the same ready criteria as dispatch. show one ticket, including its body/spec.',
248
253
  'Human output is the default and marks urgent tickets. --json emits exactly',
249
254
  'one bare value, and every JSON ticket names its priority: Ticket[]',
250
255
  'for list, the hierarchy for tree, and the resulting Ticket for ticket mutations; show',
251
- 'adds an assets array (kind, name, revision, size, layout, fileCount).',
256
+ 'adds an assets array (kind, name, revision, size, layout, fileCount). Sources',
257
+ 'that store assignees add an assignees array of usernames.',
252
258
  '',
253
259
  'Ticket assets are files or folders (a design export, a reference screenshot, a',
254
260
  'sample payload) attached to a ticket and kept in the BuildStore, never in the',
@@ -400,13 +406,16 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
400
406
  ' --store <ref> Override the BuildStore path or URL.',
401
407
  '',
402
408
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
403
- 'integration.verification-failed (failed node verification), build.janitor-failing, build.compatibility-deferred,',
404
- 'node.item-conflicted, target.rewritten, conflicted restack.replayed, derived build.consent-ready and',
409
+ 'integration.verification-failed (failed node verification), build.janitor-failing, build.janitor-escalated,',
410
+ 'build.compatibility-deferred, node.item-conflicted, target.rewritten, conflicted restack.replayed,',
411
+ 'derived build.consent-ready and',
405
412
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
406
413
  'Consent and held ready merges use only build.consent-ready, once per readiness episode.',
407
414
  'Unready or stale consent candidates stay silent; one merge gate decision per build/PR.',
408
415
  'Repository: harvest.escalated, harvest.recovery-exhausted, dispatcher.config-rejected, dispatcher.forge-readiness-failed,',
409
- 'dispatcher.kernel-git-unavailable, dispatcher.config-reloaded with restartRequired, abnormal dispatcher.run-stopped,',
416
+ 'dispatcher.kernel-git-unavailable, forge.credential-limited, dispatcher.config-reloaded with restartRequired,',
417
+ 'abnormal dispatcher.run-stopped,',
418
+ 'abandoned ticket-preparation.resolved (claim confirmed or unconfirmed; ticket unchanged),',
410
419
  'and dispatcher.lost. dispatcher.ticket-source-persistent reports degradation past',
411
420
  'resetAt after a tick started at or after reset completes or fails while still degraded,',
412
421
  'or 15 minutes without a reset; dispatcher.tick-failure-persistent reports',
@@ -158,7 +158,13 @@ function effectiveTargets(
158
158
  ): Array<{ runtime: string; models: string[] }> {
159
159
  // Preserve eager registry/model/argument validation, but probe only routes
160
160
  // the pipeline can consume rather than every declared role table.
161
- createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds, config.accounts)
161
+ createRuntimeResolver(
162
+ runtimes,
163
+ config.roles,
164
+ config.policy.sessionBudgetSeconds,
165
+ config.accounts,
166
+ config.profiles,
167
+ )
162
168
  return effectiveRuntimeReferences(config).flatMap((group) => {
163
169
  const selected = Object.keys(config.accounts).length ? group.legacyAuthentication : group
164
170
  if (selected === undefined) return []
@@ -577,6 +583,7 @@ async function validateInitReadinessInner(opts: {
577
583
  ])
578
584
  let caps: WorkspaceProviderCapabilities | undefined
579
585
  let assigneeLine: string | undefined
586
+ let createAssigneeLine: string | undefined
580
587
  let roles: Awaited<ReturnType<typeof ticketRoleReadiness>> = { notes: [], checks: [] }
581
588
  let forgeChecks: ForgeReadinessCheck[] = readinessChecks(
582
589
  'unknown',
@@ -659,6 +666,11 @@ async function validateInitReadinessInner(opts: {
659
666
  const assignee = config.tickets.readyAssignee
660
667
  if (assignee !== undefined && ticketSource.describeReadyAssignee !== undefined)
661
668
  assigneeLine = `Ticket assignee gate: ${await ticketSource.describeReadyAssignee(assignee)}`
669
+ // Who every created ticket would be assigned to, so a create never
670
+ // finds out first.
671
+ const createAssignee = config.tickets.createAssignee
672
+ if (createAssignee !== undefined && ticketSource.describeCreateAssignee !== undefined)
673
+ createAssigneeLine = `Ticket create assignee: ${await ticketSource.describeCreateAssignee(createAssignee)}`
662
674
  await ticketSource.listReady({
663
675
  ...(config.tickets.readyLabels !== undefined ? { labels: config.tickets.readyLabels } : {}),
664
676
  state: config.tickets.readyState,
@@ -809,6 +821,7 @@ async function validateInitReadinessInner(opts: {
809
821
  stdout(`Store: ${state.storeRef}`)
810
822
  stdout(`Forge: ${config.forge}`)
811
823
  if (assigneeLine !== undefined) stdout(assigneeLine)
824
+ if (createAssigneeLine !== undefined) stdout(createAssigneeLine)
812
825
  for (const note of roles.notes) stdout(note)
813
826
  // Same raw `[workspace.config]` fallback guestEnvNames gets (f_55ba7591): a
814
827
  // provider that declares describeEnvironment without a configSchema still
@@ -0,0 +1,225 @@
1
+ import type { Forge } from '../ports/types'
2
+ import type { Exec } from '../ports/workspace/git-worktree'
3
+
4
+ /** Thrown in place of an effect that a dispatcher attempted without current
5
+ * repository authority: its repository lease lapsed and has not been
6
+ * reclaimed, or a peer replaced it. The effect was never started. Catch sites
7
+ * treat it as "stop this unit quietly", never as a recorded failure. */
8
+ export class RepositoryAuthorityLapsed extends Error {
9
+ constructor(message = 'repository dispatch lease lapsed; effect not started') {
10
+ super(message)
11
+ this.name = 'RepositoryAuthorityLapsed'
12
+ }
13
+ }
14
+
15
+ export function isRepositoryAuthorityLapse(error: unknown): error is RepositoryAuthorityLapsed {
16
+ return error instanceof RepositoryAuthorityLapsed
17
+ }
18
+
19
+ /** First statement of a catch that would otherwise record a failure fact: a
20
+ * lapse is not a failure of the unit, so it escapes unrecorded. */
21
+ export function rethrowAuthorityLapse(error: unknown): void {
22
+ if (isRepositoryAuthorityLapse(error)) throw error
23
+ }
24
+
25
+ /** The repository-lease subset of the BuildStore the resolver needs. */
26
+ export interface RepoLeaseStore {
27
+ getRepo(repo: string): Promise<{ lease?: { holder: string } | null } | null>
28
+ claimRepoLease(repo: string, holder: string, ttlMs: number): Promise<boolean>
29
+ }
30
+
31
+ /** `held`: the lease names this run again with a fresh expiry. `superseded`:
32
+ * another run holds or held it since. `unknown`: the store could not answer;
33
+ * do no work and ask again later. */
34
+ export type LapsedLeaseResolution = 'held' | 'superseded' | 'unknown'
35
+
36
+ /** Decide whether a holder whose own lease looks lapsed was replaced, and
37
+ * reclaim it when it was not. "My lease expired" alone never means "a peer
38
+ * replaced me": expiry leaves the record naming the old holder in every
39
+ * adapter, and only the holder's own release clears it. So:
40
+ *
41
+ * - a record naming this holder, expired or not, is claimed again. The claim
42
+ * is atomic in every adapter, so of two runs racing after expiry exactly one
43
+ * wins; a refused claim means the other one did.
44
+ * - a record naming another holder, expired or not, means a peer took over.
45
+ * - no record means a peer claimed and then released it (run ids are unique).
46
+ *
47
+ * A peer could claim and release between the read and the claim. That window
48
+ * is milliseconds wide and is accepted: the claim would then succeed against
49
+ * an absent record, which is the same outcome as a standby takeover. */
50
+ export async function resolveLapsedRepoLease(
51
+ store: RepoLeaseStore,
52
+ repo: string,
53
+ holder: string,
54
+ ttlMs: number,
55
+ ): Promise<LapsedLeaseResolution> {
56
+ try {
57
+ const record = await store.getRepo(repo)
58
+ if (record?.lease?.holder !== holder) return 'superseded'
59
+ return (await store.claimRepoLease(repo, holder, ttlMs)) ? 'held' : 'superseded'
60
+ } catch {
61
+ return 'unknown'
62
+ }
63
+ }
64
+
65
+ type Guard = () => void
66
+
67
+ /** Shallow method fences: each listed member is guarded when it is called,
68
+ * after every `await` that preceded the call. Nested objects are fenced by
69
+ * their own method lists. */
70
+ export interface EffectFence {
71
+ readonly methods: readonly string[]
72
+ readonly nested?: Readonly<Record<string, EffectFence>>
73
+ }
74
+
75
+ /** A view of `port` whose listed methods call `guard()` before delegating.
76
+ * The guard throws to refuse; a refused call returns a rejected promise and
77
+ * never reaches the port. Unlisted members, reads, and data properties pass
78
+ * through. Methods are applied to the real target, so class `this` and
79
+ * private fields keep working, and the view reports the target's prototype.
80
+ *
81
+ * The proxy wraps an empty facade rather than the port itself. A proxy over
82
+ * the port would have to return a frozen (non-configurable, non-writable)
83
+ * member unchanged, so `Object.freeze` on a plugin would let its effects and
84
+ * nested capabilities escape the fence. The facade has no such invariant.
85
+ *
86
+ * An effect that had already been called before a stall still completes:
87
+ * cancelling it could tear external state. Only effects called afterwards
88
+ * are fenced. */
89
+ export function fenceEffects<T extends object>(port: T, fence: EffectFence, guard: Guard): T {
90
+ const methods = new Set(fence.methods)
91
+ const nested = new Map<PropertyKey, { raw: object; wrapped: object }>()
92
+ const bound = new WeakMap<object, unknown>()
93
+ return new Proxy(Object.create(null) as T, {
94
+ getPrototypeOf: () => Reflect.getPrototypeOf(port),
95
+ has: (_facade, key) => Reflect.has(port, key),
96
+ ownKeys: () => Reflect.ownKeys(port),
97
+ getOwnPropertyDescriptor: (_facade, key) => {
98
+ const descriptor = Reflect.getOwnPropertyDescriptor(port, key)
99
+ return descriptor ? { ...descriptor, configurable: true } : undefined
100
+ },
101
+ set: (_facade, key, value) => Reflect.set(port, key, value, port),
102
+ defineProperty: (_facade, key, descriptor) => Reflect.defineProperty(port, key, descriptor),
103
+ deleteProperty: (_facade, key) => Reflect.deleteProperty(port, key),
104
+ get(_facade, key) {
105
+ const value: unknown = Reflect.get(port, key, port)
106
+ const inner = typeof key === 'string' ? fence.nested?.[key] : undefined
107
+ if (inner && value && typeof value === 'object') {
108
+ const cached = nested.get(key)
109
+ if (cached?.raw === value) return cached.wrapped
110
+ const wrapped = fenceEffects(value, inner, guard)
111
+ nested.set(key, { raw: value, wrapped })
112
+ return wrapped
113
+ }
114
+ if (typeof value !== 'function') return value
115
+ const fn = value as (...args: unknown[]) => unknown
116
+ if (typeof key === 'string' && methods.has(key))
117
+ return (...args: unknown[]) => {
118
+ try {
119
+ guard()
120
+ } catch (error) {
121
+ return Promise.reject(error)
122
+ }
123
+ return fn.apply(port, args)
124
+ }
125
+ let cached = bound.get(fn)
126
+ if (!cached) {
127
+ cached = fn.bind(port)
128
+ bound.set(fn, cached)
129
+ }
130
+ return cached
131
+ },
132
+ })
133
+ }
134
+
135
+ /** Forge members that only observe. Every other function member of a fenced
136
+ * forge, at any depth, is an effect and is refused without authority. Each
137
+ * entry is a read per its contract in `ports/types.ts`. */
138
+ export const FORGE_READ_ALLOWLIST: readonly string[] = [
139
+ 'withReadScope',
140
+ 'primeNodeReads',
141
+ 'observeRequests',
142
+ 'inspectReadiness',
143
+ 'inspectMergeFreshness',
144
+ 'inspectLandingGate',
145
+ 'inspectLandingPr',
146
+ 'compareBranches',
147
+ 'confirmPublication',
148
+ 'snapshotBase',
149
+ 'getPrState',
150
+ 'readCommitMessage',
151
+ 'containsBuild',
152
+ 'remoteBranchSha',
153
+ 'remoteBranchExists',
154
+ 'isCommitAncestor',
155
+ 'readFile',
156
+ ]
157
+
158
+ const FORGE_CAPABILITIES = ['rewrite', 'kernelRewrite', 'prAttachments']
159
+
160
+ /** A `git push` anywhere in a command line is a publication. */
161
+ function isGitPush(cmd: readonly string[]): boolean {
162
+ return cmd[0] === 'git' && cmd.includes('push')
163
+ }
164
+
165
+ /** Exec that refuses `git push` without authority; every other command runs. */
166
+ export function fenceExec(exec: Exec, guard: Guard): Exec {
167
+ return (cmd, opts) => {
168
+ if (isGitPush(cmd)) {
169
+ try {
170
+ guard()
171
+ } catch (error) {
172
+ return Promise.reject(error)
173
+ }
174
+ }
175
+ return exec(cmd, opts)
176
+ }
177
+ }
178
+
179
+ /** Deny-by-default forge fence. Every function member, including every method
180
+ * of the nested `rewrite`, `kernelRewrite` and `prAttachments` capabilities and
181
+ * any plugin-added method, is an effect unless it is on the read allowlist.
182
+ * `kernelExec` is fenced for `git push` only. Non-function properties pass
183
+ * through. Compose it underneath `guardForge`, so the guard's identity memo
184
+ * still recognises the outer object. */
185
+ export function fenceForge(forge: Forge, guard: Guard): Forge {
186
+ return fenceForgeObject(forge, guard, new Set(FORGE_READ_ALLOWLIST)) as Forge
187
+ }
188
+
189
+ function fenceForgeObject(target: object, guard: Guard, reads: ReadonlySet<string>): object {
190
+ const nested = new Map<PropertyKey, { raw: object; wrapped: object }>()
191
+ return new Proxy(
192
+ {},
193
+ {
194
+ has: (_facade, key) => key in target,
195
+ ownKeys: () => Reflect.ownKeys(target),
196
+ getOwnPropertyDescriptor: (_facade, key) => {
197
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key)
198
+ return descriptor ? { ...descriptor, configurable: true } : undefined
199
+ },
200
+ get(_facade, key) {
201
+ const value: unknown = Reflect.get(target, key, target)
202
+ const name = String(key)
203
+ if (value && typeof value === 'object' && FORGE_CAPABILITIES.includes(name)) {
204
+ const cached = nested.get(key)
205
+ if (cached?.raw === value) return cached.wrapped
206
+ const wrapped = fenceForgeObject(value, guard, new Set())
207
+ nested.set(key, { raw: value, wrapped })
208
+ return wrapped
209
+ }
210
+ if (typeof value !== 'function') return value
211
+ const fn = value as (...args: unknown[]) => unknown
212
+ if (name === 'kernelExec') return fenceExec(fn.bind(target) as Exec, guard)
213
+ if (reads.has(name)) return fn.bind(target)
214
+ return (...args: unknown[]) => {
215
+ try {
216
+ guard()
217
+ } catch (error) {
218
+ return Promise.reject(error)
219
+ }
220
+ return fn.apply(target, args)
221
+ }
222
+ },
223
+ },
224
+ )
225
+ }
@@ -9,13 +9,20 @@ import {
9
9
  type UpgradeRun,
10
10
  } from '../kernel/dispatch-upgrade'
11
11
  import { formatRuntimeIdentity } from '../events/runtime'
12
+ import { landingRestackDue } from '../kernel/engine'
12
13
  import {
13
14
  dispatchCapacity,
14
15
  waitingExplanation,
15
16
  type DispatchCapacity,
16
17
  type CapacityBuild,
17
18
  } from '../kernel/dispatch-capacity'
18
- import { forgeHealthReducer, type ForgeDegradation } from '../kernel/forge-health'
19
+ import {
20
+ activeForgeCredentialLimits,
21
+ forgeCredentialLimitsReducer,
22
+ forgeHealthReducer,
23
+ type ForgeCredentialLimit,
24
+ type ForgeDegradation,
25
+ } from '../kernel/forge-health'
19
26
  import { forgeHotspot, type ForgeRequestCounts } from '../ports/forge-telemetry'
20
27
  import { configSchema } from '../config/schema'
21
28
  import type { BuildStore } from '../store/types'
@@ -166,6 +173,10 @@ export interface RepositoryStatus extends DispatchSettings {
166
173
  capacity?: DispatchCapacity
167
174
  /** Dispatcher startup warnings, then forge readiness warnings. */
168
175
  warningLines?: string[]
176
+ /** Standing ticket diagnostics from the latest completed ticket scan — for
177
+ * example an invalid ticket, or a ready ticket whose labels select more than
178
+ * one role profile and is therefore not claimed. */
179
+ ticketDiagnostics?: string[]
169
180
  /** Standing dependency/target diagnostics from the latest completed ticket
170
181
  * scan — for example a ticket held because its target node is being built
171
182
  * by another store. */
@@ -175,6 +186,10 @@ export interface RepositoryStatus extends DispatchSettings {
175
186
  forgeRequests?: ForgeRequestCounts
176
187
  forgeRequestHotspot?: string
177
188
  forgeDegradation?: ForgeDegradation
189
+ /** Active rate limits outside the dispatcher's credential (unauthenticated
190
+ * requests, build runners, phase sessions). They never pause dispatcher
191
+ * forge work; each names the limited process. */
192
+ forgeCredentialLimits?: ForgeCredentialLimit[]
178
193
  ticketSourceDegradation?: TicketSourceDegradation
179
194
  /** Live operator sandboxes (AUT-340); released environments are omitted. */
180
195
  sandboxes: Array<{
@@ -215,7 +230,12 @@ export function projectRepositoryStatus(
215
230
  repo: string,
216
231
  events: RepositoryEvent[],
217
232
  dispatcher = projectDispatcherLiveness(null, [], new Date()),
233
+ now: Date = new Date(),
218
234
  ): RepositoryStatus {
235
+ const credentialLimits = activeForgeCredentialLimits(
236
+ forgeCredentialLimitsReducer.reduce(events),
237
+ now,
238
+ )
219
239
  const publications: RepositoryStatus['publications'] = []
220
240
  for (const event of events) {
221
241
  if (event.type !== 'orchestrator.sandbox.published') continue
@@ -251,10 +271,15 @@ export function projectRepositoryStatus(
251
271
  latestScan?.type === 'dispatcher.ticket-scan-completed'
252
272
  ? latestScan.payload.dependencyDiagnostics
253
273
  : []
274
+ const ticketDiagnostics =
275
+ latestScan?.type === 'dispatcher.ticket-scan-completed'
276
+ ? latestScan.payload.ticketDiagnostics
277
+ : []
254
278
  return {
255
279
  ...(forgeHealthReducer.reduce(events)
256
280
  ? { forgeDegradation: forgeHealthReducer.reduce(events) }
257
281
  : {}),
282
+ ...(credentialLimits.length ? { forgeCredentialLimits: credentialLimits } : {}),
258
283
  ...(active === undefined ? {} : { ticketSourceDegradation: active }),
259
284
  ...(Object.keys(repositoryReadFactsReducer.reduce(events).missingAccounts).length
260
285
  ? { missingAccounts: repositoryReadFactsReducer.reduce(events).missingAccounts }
@@ -265,6 +290,7 @@ export function projectRepositoryStatus(
265
290
  upgradeStatus: projectUpgradeStatus(dispatchUpgradeReducer.reduce(events), dispatcher),
266
291
  rollbackHold: effectiveRollbackHold(dispatchUpgradeReducer.reduce(events), dispatcher),
267
292
  ...(warningLines.length ? { warningLines } : {}),
293
+ ...(ticketDiagnostics.length ? { ticketDiagnostics: [...ticketDiagnostics] } : {}),
268
294
  ...(dependencyDiagnostics.length ? { dependencyDiagnostics: [...dependencyDiagnostics] } : {}),
269
295
  dispatcher,
270
296
  ...(() => {
@@ -293,11 +319,14 @@ export function repositoryStatusFromFacts(
293
319
  repo: string,
294
320
  facts: RepositoryReadFacts,
295
321
  dispatcher: DispatcherLiveness,
322
+ now: Date = new Date(),
296
323
  ): RepositoryStatus {
324
+ const credentialLimits = activeForgeCredentialLimits(facts.forgeCredentialLimits, now)
297
325
  const warningLines = facts.status
298
326
  ? [...facts.status.roleWarnings, ...forgeReadinessWarnings(facts.status)]
299
327
  : []
300
328
  const dependencyDiagnostics = facts.scan?.dependencyDiagnostics ?? []
329
+ const ticketDiagnostics = facts.scan?.ticketDiagnostics ?? []
301
330
  return {
302
331
  ...(Object.keys(facts.missingAccounts).length
303
332
  ? { missingAccounts: facts.missingAccounts }
@@ -308,6 +337,7 @@ export function repositoryStatusFromFacts(
308
337
  upgradeStatus: projectUpgradeStatus(facts.upgrades, dispatcher),
309
338
  rollbackHold: effectiveRollbackHold(facts.upgrades, dispatcher),
310
339
  ...(warningLines.length ? { warningLines } : {}),
340
+ ...(ticketDiagnostics.length ? { ticketDiagnostics: [...ticketDiagnostics] } : {}),
311
341
  ...(dependencyDiagnostics.length ? { dependencyDiagnostics: [...dependencyDiagnostics] } : {}),
312
342
  dispatcher,
313
343
  ...(() => {
@@ -320,6 +350,7 @@ export function repositoryStatusFromFacts(
320
350
  })(),
321
351
  ...facts.settings,
322
352
  ...(facts.forgeHealth ? { forgeDegradation: facts.forgeHealth } : {}),
353
+ ...(credentialLimits.length ? { forgeCredentialLimits: credentialLimits } : {}),
323
354
  ...(facts.health === undefined ? {} : { ticketSourceDegradation: facts.health }),
324
355
  sandboxes: facts.sandboxes
325
356
  .filter((state) => state.state !== 'released')
@@ -424,6 +455,10 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
424
455
  `forge ${status.forgeDegradation.forge}: degraded — ${status.forgeDegradation.message}; reset ${status.forgeDegradation.resetAt}`,
425
456
  ]
426
457
  : []),
458
+ ...(status.forgeCredentialLimits ?? []).map(
459
+ (limit) =>
460
+ `forge ${limit.forge}: ${limit.process} rate-limited (${limit.credential}${limit.missingCredential ? `: ${limit.missingCredential}` : ''}) until ${limit.resetAt}; dispatcher forge work is not paused`,
461
+ ),
427
462
  ...(active === undefined
428
463
  ? []
429
464
  : [
@@ -432,7 +467,7 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
432
467
  `repository: ${status.repo}`,
433
468
  ...(status.capacity
434
469
  ? [
435
- `capacity: ${status.capacity.occupied}/${status.capacity.effective} effective; ${status.capacity.configured} configured; ${status.capacity.borrowingNodes.length} node${status.capacity.borrowingNodes.length === 1 ? '' : 's'} using descendant-held slots${status.capacity.borrowingNodes.length ? `: ${status.capacity.borrowingNodes.join(', ')}` : ''}${status.capacity.waitingNodes?.length ? `; ${waitingExplanation(status.capacity, { requests: true })}` : ''}`,
470
+ `capacity: ${status.capacity.occupied}/${status.capacity.effective} effective; ${status.capacity.configured} configured; ${status.capacity.borrowingNodes.length} node${status.capacity.borrowingNodes.length === 1 ? '' : 's'} using descendant-held slots${status.capacity.borrowingNodes.length ? `: ${status.capacity.borrowingNodes.join(', ')}` : ''}${status.capacity.waitingNodes?.length || status.capacity.waitingBuilds?.length ? `; ${waitingExplanation(status.capacity, { requests: true })}` : ''}`,
436
471
  ]
437
472
  : []),
438
473
  ...(status.warningLines ?? []),
@@ -457,6 +492,7 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
457
492
  `intake: ${setting(status.intake)}`,
458
493
  `repository pause: ${setting(status.paused)}`,
459
494
  `default auto-merge: ${setting(status.defaultAutoMerge)}`,
495
+ ...(status.ticketDiagnostics ?? []).map((line) => `queue: ${line}`),
460
496
  ...(status.dependencyDiagnostics ?? []).map((line) => `queue: ${line}`),
461
497
  ...status.sandboxes.map(
462
498
  (sandbox) =>
@@ -499,6 +535,7 @@ export async function readRepositoryCapacity(
499
535
  state: build.state,
500
536
  workspace: build.workspace !== null,
501
537
  provisioning: build.provisionMarker !== undefined,
538
+ restackDue: landingRestackDue(build.state, build.log),
502
539
  })
503
540
  }
504
541
  return dispatchCapacity(
@@ -523,7 +560,7 @@ export async function abRepositoryStatus(opts: RepositoryStatusOpts): Promise<vo
523
560
  const observedAt = opts.now?.() ?? new Date()
524
561
  const { dispatcher } = await readDispatcherLiveness(store, repo, observedAt)
525
562
  const facts = (await readRepositoryFacts(store, repo)).value
526
- const status = repositoryStatusFromFacts(repo, facts, dispatcher)
563
+ const status = repositoryStatusFromFacts(repo, facts, dispatcher, observedAt)
527
564
  status.operator = {
528
565
  presence: 'loaded',
529
566
  registrations: (await store.listOperatorPresence(repo))
@@ -10,6 +10,7 @@ import { buildVocabulary } from './dashboard/model'
10
10
  import { readBuildDigests } from '../store/reduced-reads'
11
11
  import { readBuildFacts } from '../store/reduced-reads'
12
12
  import { slotRequest, slotWaitText, type SlotRequest } from '../kernel/dispatch-capacity'
13
+ import { landingRestackDue } from '../kernel/engine'
13
14
  import type { BuildFacts } from '../processes/repo-view'
14
15
  /**
15
16
  * `ab builds` and `ab build status <slug>` — the read-only query surface on
@@ -127,7 +128,7 @@ export interface BuildSummary {
127
128
  lease: LeaseInfo
128
129
  /** Durable-event progress, separate from mutable lease renewal. */
129
130
  progress: BuildProgress
130
- /** A node's runner request, admitted ahead of new ticket claims. */
131
+ /** A node's or parked build's runner request, admitted ahead of new ticket claims. */
131
132
  slotWait?: SlotRequest
132
133
  }
133
134
 
@@ -184,6 +185,9 @@ export interface BuildDetail extends BuildSummary {
184
185
  issueLinks?: BuildState['issueLinks']
185
186
  /** Present with `issueLinks`: whether finalize sealed them for the PR. */
186
187
  issueLinksSealed?: boolean
188
+ /** The role profile frozen at claim; `configured: false` when the latest
189
+ * session found it removed and used the repository roles. Omitted when none. */
190
+ profile?: { name: string; configured: boolean }
187
191
  suspendedSessions: OpenSession[]
188
192
  sessionTotals: BuildState['sessions']['totals']
189
193
  openSessions: StatusOpenSession[]
@@ -411,6 +415,7 @@ export function detailFromFacts(
411
415
  issueLinksSealed: state.issueLinksSealedSeq !== undefined,
412
416
  }
413
417
  : {}),
418
+ ...(state.profile !== undefined ? { profile: { ...state.profile } } : {}),
414
419
  ...(state.reviewRoundCeilings.plan !== undefined || state.reviewRoundCeilings.code !== undefined
415
420
  ? { reviewRoundCeilings: { ...state.reviewRoundCeilings } }
416
421
  : {}),
@@ -598,7 +603,7 @@ export function renderSummaries(summaries: BuildSummary[], now: Date, emptyNote:
598
603
  summary.status,
599
604
  summary.kind === 'integration'
600
605
  ? `integration ${summary.integration ?? ''}${summary.slotWait ? `, ${slotWaitText(summary.slotWait)}` : ''}`
601
- : phaseCell(summary),
606
+ : `${phaseCell(summary)}${summary.slotWait ? `, ${slotWaitText(summary.slotWait)}` : ''}`,
602
607
  healthWord(summary.lease.health),
603
608
  summary.progress.heartbeatAt === undefined
604
609
  ? '—'
@@ -636,6 +641,10 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
636
641
  const sealed = d.issueLinksSealed === true ? ' (sealed)' : ''
637
642
  lines.push(` issues: ${safeStatusText(describeIssueLinks(d.issueLinks))}${sealed}`)
638
643
  }
644
+ if (d.profile !== undefined)
645
+ lines.push(
646
+ ` profile: ${safeStatusText(d.profile.name)}${d.profile.configured ? '' : " (no longer configured — sessions use the repository's roles)"}`,
647
+ )
639
648
  if (d.target)
640
649
  lines.push(
641
650
  ` ${d.kind ?? 'work'} · target ${d.target}${d.integration ? ` · ${d.integration}` : ''}`,
@@ -967,17 +976,16 @@ export async function abBuilds(opts: AbBuildsOpts): Promise<void> {
967
976
  record,
968
977
  facts.state,
969
978
  now,
970
- facts.state.kind === 'node'
971
- ? slotRequest(
972
- {
973
- record,
974
- state: facts.state,
975
- workspace: facts.workspace !== null,
976
- provisioning: facts.provisionMarker !== undefined,
977
- },
978
- now,
979
- )
980
- : undefined,
979
+ slotRequest(
980
+ {
981
+ record,
982
+ state: facts.state,
983
+ workspace: facts.workspace !== null,
984
+ provisioning: facts.provisionMarker !== undefined,
985
+ restackDue: landingRestackDue(facts.state, facts.log),
986
+ },
987
+ now,
988
+ ),
981
989
  )
982
990
  if (wanted.has(summary.status)) summaries.push(summary)
983
991
  }