@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
@@ -15,6 +15,7 @@ export const executionProgress = {
15
15
  'build.compatibility-deferred': 'bookkeeping',
16
16
  'build.janitor-attempt-failed': 'bookkeeping',
17
17
  'build.janitor-failing': 'bookkeeping',
18
+ 'build.janitor-escalated': 'bookkeeping',
18
19
  'build.janitor-recovered': 'bookkeeping',
19
20
  'landing.application-failed': 'failure',
20
21
  'landing.decided': 'progress',
@@ -25,6 +26,7 @@ export const executionProgress = {
25
26
  'landing.forge-merged': 'progress',
26
27
  'landing.native-applied': 'bookkeeping',
27
28
  'target.distance': 'bookkeeping',
29
+ 'pipeline.settled': 'bookkeeping',
28
30
  'target.rewritten': 'bookkeeping',
29
31
  'target.rewrite-cleared': 'bookkeeping',
30
32
  'target.moved': 'bookkeeping',
@@ -20,6 +20,7 @@ import { openProductionStore, type StoreOpener } from '../cli/store-opening'
20
20
  import { resolveRepoStatePaths } from '../cli/repo-state'
21
21
  import { DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS } from '../kernel/harvest'
22
22
  import { HarvestRunner } from './harvest-runner'
23
+ import { GITHUB_REQUIRE_CREDENTIAL_ENV } from '../ports/forge/github-transport'
23
24
 
24
25
  export type { HarvestExecutionEnvironment }
25
26
 
@@ -113,8 +114,10 @@ export async function runHarvestChild(
113
114
  clock: systemClock,
114
115
  instance: input.instance,
115
116
  ...(input.preparedRun ? { preparedRun: input.preparedRun } : {}),
116
- // Adopted holder: the guest skips its own claim, heartbeats the owning
117
- // dispatch loop's repository lease, and never releases it.
117
+ // The launching invocation's holder, matched against this execution's
118
+ // authorization. A prepared guest's authority is that durable fact: it
119
+ // never claims, renews or releases the repository lease, so `--once`
120
+ // teardown and a successor's claim do not fence it.
118
121
  ...(input.leaseHolder !== undefined ? { leaseHolder: input.leaseHolder } : {}),
119
122
  ...(input.environment !== undefined ? { environment: input.environment } : {}),
120
123
  sessionEnv: {
@@ -122,6 +125,9 @@ export async function runHarvestChild(
122
125
  ...(env.AB_TICKET_TOKEN ? { AB_TICKET_TOKEN: env.AB_TICKET_TOKEN } : {}),
123
126
  AB_STORE: input.storeRef,
124
127
  ...(env.AB_TOKEN !== undefined && env.AB_TOKEN !== '' ? { AB_TOKEN: env.AB_TOKEN } : {}),
128
+ ...(env[GITHUB_REQUIRE_CREDENTIAL_ENV] === '1'
129
+ ? { [GITHUB_REQUIRE_CREDENTIAL_ENV]: '1' }
130
+ : {}),
125
131
  },
126
132
  opts: {
127
133
  maxRecoveryAttempts: DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS,
@@ -67,6 +67,110 @@ export function openHarvestExecutions(events: readonly RepositoryEvent[]): OpenH
67
67
  return openHarvestExecutionsReducer.reduce(events)
68
68
  }
69
69
 
70
+ /** The current hosted harvest execution authority: the latest
71
+ * `harvest.execution.authorized` and whether that execution was since ended or
72
+ * released. Only a repository-lease holder can append an authorization, so
73
+ * the journal totally orders them. */
74
+ export interface CurrentHarvestAuthority {
75
+ execution: string
76
+ run: string
77
+ leaseHolder: string
78
+ released: boolean
79
+ }
80
+
81
+ export const HOSTED_HARVEST_AUTHORITY_REDUCER_VERSION = 1
82
+
83
+ /** Constant-size current-authority projection a prepared hosted guest re-reads
84
+ * at its durable boundaries. Unlike `repositoryReadFacts`, it keeps no history:
85
+ * a later authorization for a different execution replaces `current`, a
86
+ * repeated authorization of the same execution keeps the first (matching the
87
+ * first-wins authorization map), and only an ending or release of the current
88
+ * execution sets `released` — older executions are already fenced as
89
+ * replaced. It carries no journal position, so even its serialized size is
90
+ * independent of log length. */
91
+ export const hostedHarvestAuthorityReducer = defineReducer<
92
+ { current?: CurrentHarvestAuthority },
93
+ RepositoryEvent,
94
+ { current?: CurrentHarvestAuthority }
95
+ >({
96
+ version: HOSTED_HARVEST_AUTHORITY_REDUCER_VERSION,
97
+ initial: () => ({}),
98
+ fold(acc, events) {
99
+ for (const event of events) {
100
+ if (event.type === 'harvest.execution.authorized') {
101
+ if (acc.current?.execution === event.payload.execution) continue
102
+ acc.current = {
103
+ execution: event.payload.execution,
104
+ run: event.payload.run,
105
+ leaseHolder: event.payload.leaseHolder,
106
+ released: false,
107
+ }
108
+ } else if (
109
+ (event.type === 'harvest.execution.released' || event.type === 'harvest.execution.ended') &&
110
+ acc.current?.execution === event.payload.execution
111
+ ) {
112
+ acc.current.released = true
113
+ }
114
+ }
115
+ },
116
+ finish: (acc) => (acc.current ? { current: { ...acc.current } } : {}),
117
+ })
118
+
119
+ export type HostedHarvestAuthorityValue = ReturnType<typeof hostedHarvestAuthorityReducer.finish>
120
+
121
+ /** Why a prepared hosted guest stopped: its authorization is missing or names
122
+ * another run or holder (`unauthorized`), a later execution was authorized
123
+ * (`replaced`), settlement ended or released it (`released`), or its
124
+ * authority could not be read — a permanent contract error (`unsupported`),
125
+ * an auth refusal (`revoked`), or transient failures outlasting the lease TTL
126
+ * (`unverified`). */
127
+ export type HarvestAuthorityFence =
128
+ | 'unauthorized'
129
+ | 'replaced'
130
+ | 'released'
131
+ | 'unsupported'
132
+ | 'revoked'
133
+ | 'unverified'
134
+
135
+ export type HostedHarvestAuthority =
136
+ | { kind: 'authorized' }
137
+ | { kind: 'fenced'; reason: 'unauthorized' | 'replaced' | 'released' }
138
+
139
+ /** Decide, in O(1), whether the guest running `input.execution` still holds
140
+ * harvest authority. The decision reads durable facts only — a live sandbox is
141
+ * never the proof. */
142
+ export function decideHostedHarvestAuthority(
143
+ value: HostedHarvestAuthorityValue,
144
+ input: { execution: string; run: string; leaseHolder: string },
145
+ ): HostedHarvestAuthority {
146
+ const current = value.current
147
+ if (current === undefined) return { kind: 'fenced', reason: 'unauthorized' }
148
+ if (current.execution !== input.execution) return { kind: 'fenced', reason: 'replaced' }
149
+ if (current.run !== input.run || current.leaseHolder !== input.leaseHolder)
150
+ return { kind: 'fenced', reason: 'unauthorized' }
151
+ if (current.released) return { kind: 'fenced', reason: 'released' }
152
+ return { kind: 'authorized' }
153
+ }
154
+
155
+ /** Classify a failed authority read. Contract errors — an unknown, excluded or
156
+ * wrong-scope reducer, or a value this client cannot represent — are
157
+ * `permanent`; an auth refusal is `revoked`; anything else (network, 5xx,
158
+ * timeout) is `transient`. Classified by `name` so this module imports no
159
+ * store adapter. */
160
+ export function classifyAuthorityReadError(error: unknown): 'permanent' | 'revoked' | 'transient' {
161
+ const name = error instanceof Error ? error.name : undefined
162
+ if (name === 'AuthError') return 'revoked'
163
+ if (
164
+ name === 'ReducerValueIncompatibilityError' ||
165
+ name === 'ReducerValueValidationError' ||
166
+ name === 'EventValidationError'
167
+ )
168
+ return 'permanent'
169
+ const message = error instanceof Error ? error.message : String(error)
170
+ if (/unknown reducer|excluded reducer|wrong scope for reducer/.test(message)) return 'permanent'
171
+ return 'transient'
172
+ }
173
+
70
174
  export interface HarvestExecutionClassificationInput {
71
175
  /** Repo-journal seq of this execution's `harvest.execution.started` fact. */
72
176
  executionStartedSeq: number
@@ -1,11 +1,12 @@
1
1
  import { accountRedactor, redactAccountStore } from '../store/account-redaction'
2
+ import { creationAssignees } from '../ports/tickets/assignees'
2
3
  import {
3
4
  guardNativeHandle,
4
5
  nativeSessionHandleSchema,
5
6
  resumeAgent,
6
7
  } from '../ports/runner/native-session'
7
8
  import type { NativeSessionHandle, AgentStartOpts } from '../ports/types'
8
- import { readRepositoryFacts } from '../store/reduced-reads'
9
+ import { readHostedHarvestAuthority, readRepositoryFacts } from '../store/reduced-reads'
9
10
  import { issueTicketGrant } from '../ports/tickets/grants'
10
11
  import { delegateCredential } from '../store/remote/credentials'
11
12
  /**
@@ -69,6 +70,12 @@ import {
69
70
  scanUnclaimedObservations,
70
71
  } from './harvest'
71
72
  import type { BuildStore, Clock } from '../store/types'
73
+ import {
74
+ classifyAuthorityReadError,
75
+ decideHostedHarvestAuthority,
76
+ type HarvestAuthorityFence,
77
+ type HostedHarvestAuthority,
78
+ } from './harvest-execution-state'
72
79
 
73
80
  /** Reserved provenance marker for deterministic harvest-created proposals. */
74
81
  export const HARVEST_PROPOSAL_LABEL = 'autobuild:proposal'
@@ -101,14 +108,26 @@ export interface HarvestRunnerDeps {
101
108
  clock: Clock
102
109
  instance: string
103
110
  /** Repository-lease holder adopted from the owning DispatchLoop: when
104
- * present, the runner skips its own claim, heartbeats with that holder, and
105
- * never releases at the end — the owning loop holds the lease for its
106
- * lifetime. Absent keeps the standalone self-claiming behavior. */
111
+ * present, the runner skips its own claim and never releases at the end —
112
+ * the owning loop holds the lease for its lifetime. Without
113
+ * `holdsAuthority` it heartbeats with that holder; a prepared hosted guest
114
+ * instead uses it only to match its durable authorization. Absent keeps the
115
+ * standalone self-claiming behavior. */
107
116
  leaseHolder?: string
117
+ /** The owning DispatchLoop's repository authority: synchronous, no I/O.
118
+ * When present, the loop's lease resolver owns reclaiming the adopted
119
+ * lease, so the runner never claims it itself; a false answer stops the
120
+ * run before its next turn starts, as a lost lease. */
121
+ holdsAuthority?: () => boolean
108
122
  /** Provider-native identity of the disposable environment this run
109
123
  * executes in (hosted harvest). Stamped into the run's harvest.started
110
124
  * payload so the journal records where it ran; absent on local runs. */
111
125
  environment?: { provider: string; environmentId: string; sessionId?: string }
126
+ /** The run a dispatcher prepared and authorized for this execution. Without
127
+ * `holdsAuthority` this is a hosted guest: its authority is the durable
128
+ * `harvest.execution.authorized` for `instance`, never the launching
129
+ * invocation's repository lease, which it neither claims, renews nor
130
+ * releases. */
112
131
  preparedRun?: { run: string }
113
132
  sessionEnv?: Record<string, string>
114
133
  shutdownSignal?: AbortSignal
@@ -167,16 +186,47 @@ class HarvestParkedSignal extends Error {
167
186
  }
168
187
  }
169
188
 
170
- /** A heartbeat proved this process no longer owns the repository lease and a
171
- * replacement claimed it before we could re-acquire. This is not workflow
172
- * failure: the replacement resumes the same journal at the next boundary. */
189
+ /** This process lost its authority: a heartbeat proved it no longer owns the
190
+ * repository lease and a replacement claimed it before we could re-acquire,
191
+ * or — for a prepared hosted guest — its durable execution authority fenced
192
+ * it (`reason`). This is not workflow failure: the replacement resumes the
193
+ * same journal at the next boundary. */
173
194
  class HarvestLeaseLostError extends Error {
174
- constructor(repo: string, instance: string) {
175
- super(`harvest lease for ${repo} is held by another runner ` + `(former holder ${instance})`)
195
+ constructor(
196
+ repo: string,
197
+ instance: string,
198
+ readonly reason?: HarvestAuthorityFence,
199
+ ) {
200
+ super(
201
+ reason === undefined
202
+ ? `harvest lease for ${repo} is held by another runner (former holder ${instance})`
203
+ : `harvest execution ${instance} for ${repo} lost its execution authority: ${reason}`,
204
+ )
176
205
  this.name = 'HarvestLeaseLostError'
177
206
  }
178
207
  }
179
208
 
209
+ /** The session bracket this runner opened and has not yet ended or
210
+ * suspended, with what a fenced exit needs to close it with evidence. */
211
+ interface OpenSessionBracket {
212
+ spec: {
213
+ run: string
214
+ role: 'harvest' | 'harvest-review'
215
+ step: 'synthesize' | 'review'
216
+ round: number
217
+ }
218
+ session: string
219
+ model?: string
220
+ stream?: SessionBracketStream
221
+ owner?: AgentRunner
222
+ handle?: AgentSessionHandle
223
+ transcript?: {
224
+ content: string
225
+ usage: { inputTokens: number; outputTokens: number; turns: number }
226
+ model?: string
227
+ }
228
+ }
229
+
180
230
  function errorMessage(error: unknown): string {
181
231
  return error instanceof Error ? error.message : String(error)
182
232
  }
@@ -206,6 +256,14 @@ export class HarvestRunner {
206
256
  * rejected heartbeat is an outage; later beats retry until one can decide. */
207
257
  private leaseLost = false
208
258
  private producer: ProducerSession | undefined
259
+ /** Prepared hosted guest only: when the durable authority was last read
260
+ * successfully, and what it decided. No verdict never passes. */
261
+ private authorityCheckedAt: number | undefined
262
+ private lastAuthoritySuccessAt: number | undefined
263
+ private authorityVerdict: HostedHarvestAuthority | undefined
264
+ /** Set once a fence fires; final for this runner. */
265
+ private authorityFence: HarvestAuthorityFence | undefined
266
+ private openBracket: OpenSessionBracket | undefined
209
267
 
210
268
  constructor(private readonly deps: HarvestRunnerDeps) {
211
269
  const redactor = accountRedactor(
@@ -236,6 +294,12 @@ export class HarvestRunner {
236
294
  )
237
295
  }
238
296
 
297
+ /** A prepared hosted guest: authority is its durable execution
298
+ * authorization, not a repository lease (see `ensureLease`). */
299
+ private get executionAuthority(): boolean {
300
+ return this.deps.preparedRun !== undefined && this.deps.holdsAuthority === undefined
301
+ }
302
+
239
303
  private currentConfig(): Config {
240
304
  return this.deps.getConfig?.() ?? this.deps.config
241
305
  }
@@ -255,6 +319,7 @@ export class HarvestRunner {
255
319
  if (!this.deps.preparedRun) await store.ensureRepo(repo)
256
320
  if (
257
321
  this.deps.leaseHolder === undefined &&
322
+ !this.executionAuthority &&
258
323
  !(await store.claimRepoLease(repo, instance, this.leaseTtlMs))
259
324
  ) {
260
325
  return { outcome: 'held' }
@@ -423,7 +488,10 @@ export class HarvestRunner {
423
488
  ? { outcome: 'parked' }
424
489
  : { outcome: 'parked', run: parkedRun }
425
490
  }
426
- if (error instanceof HarvestLeaseLostError) return { outcome: 'held' }
491
+ if (error instanceof HarvestLeaseLostError) {
492
+ if (this.executionAuthority) await this.closeFencedBracket(error.reason ?? 'unverified')
493
+ return { outcome: 'held' }
494
+ }
427
495
  throw error
428
496
  } finally {
429
497
  this.stopHeartbeat()
@@ -435,8 +503,10 @@ export class HarvestRunner {
435
503
  }
436
504
  this.producer = undefined
437
505
  }
438
- // An adopted holder is released by the owning DispatchLoop, never here.
439
- if (this.deps.leaseHolder === undefined) await store.releaseRepoLease(repo, instance)
506
+ // An adopted holder is released by the owning DispatchLoop, never here;
507
+ // a prepared hosted guest never held the lease.
508
+ if (this.deps.leaseHolder === undefined && !this.executionAuthority)
509
+ await store.releaseRepoLease(repo, instance)
440
510
  }
441
511
  }
442
512
 
@@ -773,6 +843,12 @@ export class HarvestRunner {
773
843
  : {}),
774
844
  },
775
845
  })
846
+ this.openBracket = {
847
+ spec,
848
+ session,
849
+ ...(target.model !== undefined ? { model: target.model } : {}),
850
+ ...(streamBracket !== undefined ? { stream: streamBracket } : {}),
851
+ }
776
852
 
777
853
  let handle: AgentSessionHandle | undefined
778
854
  let result: AgentTurnResult | undefined
@@ -886,6 +962,7 @@ export class HarvestRunner {
886
962
  opts,
887
963
  )
888
964
  } else {
965
+ this.requireAuthority()
889
966
  const turn = await target.runner.start(opts)
890
967
  handle = turn.session
891
968
  result = turn.result
@@ -895,6 +972,10 @@ export class HarvestRunner {
895
972
  } catch (error) {
896
973
  turnError = error
897
974
  }
975
+ if (handle !== undefined && this.openBracket?.session === session) {
976
+ this.openBracket.handle = handle
977
+ this.openBracket.owner = live?.runner ?? target.runner
978
+ }
898
979
  if (observationFailure instanceof HarvestLeaseLostError) throw observationFailure
899
980
  if (observationFailure !== undefined)
900
981
  throw new HarvestPersistenceError('Native identity persistence failed', {
@@ -906,7 +987,16 @@ export class HarvestRunner {
906
987
  } catch (error) {
907
988
  if (handle !== undefined && live === undefined) {
908
989
  try {
909
- await target.runner.end(handle)
990
+ const transcript = await target.runner.end(handle)
991
+ // A fenced guest closes its own bracket with this evidence.
992
+ if (this.openBracket?.session === session)
993
+ this.openBracket.transcript = {
994
+ content: transcript.content,
995
+ usage: transcript.metadata.usage,
996
+ ...(transcript.metadata.model !== undefined
997
+ ? { model: transcript.metadata.model }
998
+ : {}),
999
+ }
910
1000
  } catch {
911
1001
  // A dead session may have nothing left to close.
912
1002
  }
@@ -981,6 +1071,7 @@ export class HarvestRunner {
981
1071
  },
982
1072
  }),
983
1073
  )
1074
+ if (this.openBracket?.session === session) this.openBracket = undefined
984
1075
  } catch (error) {
985
1076
  throw new HarvestPersistenceError('Harvest suspension persistence failed', {
986
1077
  cause: error,
@@ -1158,6 +1249,8 @@ export class HarvestRunner {
1158
1249
  // the ordering structural rather than call-site discipline.
1159
1250
  await close.stream.sink.close(close.outcome)
1160
1251
  }
1252
+ if (this.openBracket?.session === session)
1253
+ this.openBracket.transcript = { content, usage, ...(model !== undefined ? { model } : {}) }
1161
1254
  await this.ensureLease()
1162
1255
  await this.deps.store.appendRepoWithArtifacts(
1163
1256
  this.deps.repo,
@@ -1187,6 +1280,73 @@ export class HarvestRunner {
1187
1280
  },
1188
1281
  }),
1189
1282
  )
1283
+ if (this.openBracket?.session === session) this.openBracket = undefined
1284
+ }
1285
+
1286
+ /**
1287
+ * A prepared hosted guest fenced by its execution authority closes the
1288
+ * session bracket it still has open, so a successor finds an ended session
1289
+ * rather than judging runner loss. Best effort and deliberately unfenced: it
1290
+ * is evidence about this guest's own session, not new work, and the store's
1291
+ * delegated-grant check still refuses it once the grant is retired. A
1292
+ * failed close leaves the release-then-judge path to settle the session.
1293
+ */
1294
+ private async closeFencedBracket(reason: HarvestAuthorityFence): Promise<void> {
1295
+ const bracket = this.openBracket
1296
+ this.openBracket = undefined
1297
+ if (bracket === undefined) return
1298
+ const { spec, session } = bracket
1299
+ try {
1300
+ let transcript = bracket.transcript
1301
+ if (transcript === undefined && bracket.handle !== undefined && bracket.owner !== undefined) {
1302
+ try {
1303
+ const ended = await bracket.owner.end(bracket.handle)
1304
+ transcript = {
1305
+ content: ended.content,
1306
+ usage: ended.metadata.usage,
1307
+ ...(ended.metadata.model !== undefined ? { model: ended.metadata.model } : {}),
1308
+ }
1309
+ } catch {
1310
+ // A dead session may have nothing left to close.
1311
+ }
1312
+ if (this.producer?.handle === bracket.handle) this.producer = undefined
1313
+ }
1314
+ await bracket.stream?.sink.close('aborted')
1315
+ const content =
1316
+ transcript !== undefined && transcript.content.trim() !== ''
1317
+ ? transcript.content
1318
+ : JSON.stringify({ session, fenced: reason })
1319
+ const usage = transcript?.usage ?? { inputTokens: 0, outputTokens: 0, turns: 0 }
1320
+ const model = transcript?.model ?? bracket.model
1321
+ await this.deps.store.appendRepoWithArtifacts(
1322
+ this.deps.repo,
1323
+ [
1324
+ {
1325
+ kind: HARVEST_TRANSCRIPT_ARTIFACT,
1326
+ content,
1327
+ metadata: {
1328
+ run: spec.run,
1329
+ step: spec.step,
1330
+ round: spec.round,
1331
+ role: spec.role,
1332
+ session,
1333
+ ...(model !== undefined ? { model } : {}),
1334
+ usage,
1335
+ fenced: reason,
1336
+ },
1337
+ },
1338
+ ],
1339
+ (deposited) => ({
1340
+ actor: KERNEL,
1341
+ type: 'harvest.session.ended',
1342
+ payload: { run: spec.run, session, transcript: artifactRef(deposited[0]!), usage },
1343
+ }),
1344
+ )
1345
+ } catch (error) {
1346
+ this.onDiagnostic(
1347
+ `harvest session "${session}" fenced (${reason}) could not be closed: ${errorMessage(error)}`,
1348
+ )
1349
+ }
1190
1350
  }
1191
1351
 
1192
1352
  private async file(run: HarvestRunState, approved: ArtifactRef): Promise<void> {
@@ -1275,6 +1435,9 @@ export class HarvestRunner {
1275
1435
  reservations.set(proposalKey, reservation)
1276
1436
  }
1277
1437
  const body = renderHarvestProposal(proposal, observations)
1438
+ // A configured createAssignee (`me` is this dispatcher's credential
1439
+ // owner) assigns the proposal; none sends no assignee.
1440
+ const assignees = creationAssignees(config.tickets)
1278
1441
  // Harvest proposals are always normal priority; grooming may mark one urgent.
1279
1442
  const ticket = (
1280
1443
  await tickets.create(
@@ -1283,6 +1446,7 @@ export class HarvestRunner {
1283
1446
  body,
1284
1447
  labels: [HARVEST_PROPOSAL_LABEL],
1285
1448
  ...(blockers.blockedBy.length > 0 ? { blockedBy: blockers.blockedBy } : {}),
1449
+ ...(assignees !== undefined ? { assignees } : {}),
1286
1450
  },
1287
1451
  {
1288
1452
  state: defaultProposalState(config),
@@ -1795,11 +1959,21 @@ export class HarvestRunner {
1795
1959
  void stream.sink.close(outcome)
1796
1960
  }
1797
1961
 
1798
- /** Re-acquire a lapsed lease only when no replacement won it. Checked at
1799
- * every durable boundary; work already in an agent turn cannot be revoked,
1800
- * but this process performs no subsequent kernel/file action without
1801
- * ownership. */
1962
+ /** Checked at every durable boundary; work already in an agent turn cannot
1963
+ * be revoked, but this process performs no subsequent kernel/file action
1964
+ * without authority. Three modes:
1965
+ * - in-process (`holdsAuthority`): the owning loop's synchronous fence;
1966
+ * - prepared hosted guest (`preparedRun` without `holdsAuthority`): its
1967
+ * durable execution authority (`ensureExecutionAuthority`);
1968
+ * - standalone or adopted lease: re-acquire a lapsed lease only when no
1969
+ * replacement won it. */
1802
1970
  private async ensureLease(): Promise<void> {
1971
+ if (this.deps.holdsAuthority !== undefined) {
1972
+ this.requireAuthority()
1973
+ this.leaseLost = false
1974
+ return
1975
+ }
1976
+ if (this.executionAuthority) return this.ensureExecutionAuthority()
1803
1977
  if (!this.leaseLost) return
1804
1978
  const { store, repo } = this.deps
1805
1979
  const holder = this.deps.leaseHolder ?? this.deps.instance
@@ -1808,7 +1982,67 @@ export class HarvestRunner {
1808
1982
  this.leaseLost = false
1809
1983
  }
1810
1984
 
1985
+ /** Synchronous authority fence, called immediately before a turn starts. */
1986
+ private requireAuthority(): void {
1987
+ if (this.deps.holdsAuthority?.() === false)
1988
+ throw new HarvestLeaseLostError(this.deps.repo, this.deps.leaseHolder ?? this.deps.instance)
1989
+ }
1990
+
1991
+ /**
1992
+ * A prepared hosted guest's authority is the latest
1993
+ * `harvest.execution.authorized`, which only a repository-lease holder can
1994
+ * append — not the launching invocation's lease, so `--once` teardown and a
1995
+ * successor's claim never fence it. Re-read at most once per `heartbeatMs`
1996
+ * as one constant-size served value, and fail closed: no verdict passes
1997
+ * until a read succeeds; a fenced verdict is final; a permanent contract
1998
+ * error fences `unsupported`, an auth refusal `revoked`; transient errors
1999
+ * keep the last successful verdict only until it is `leaseTtlMs` old.
2000
+ */
2001
+ private async ensureExecutionAuthority(): Promise<void> {
2002
+ const { store, repo, instance } = this.deps
2003
+ const fence = (reason: HarvestAuthorityFence): never => {
2004
+ this.authorityFence = reason
2005
+ throw new HarvestLeaseLostError(repo, instance, reason)
2006
+ }
2007
+ if (this.authorityFence !== undefined) fence(this.authorityFence)
2008
+ const verdict = this.authorityVerdict
2009
+ const now = this.deps.clock().getTime()
2010
+ if (
2011
+ verdict !== undefined &&
2012
+ this.authorityCheckedAt !== undefined &&
2013
+ now - this.authorityCheckedAt < this.heartbeatMs
2014
+ )
2015
+ return
2016
+ try {
2017
+ const { value } = await readHostedHarvestAuthority(store, repo)
2018
+ this.authorityCheckedAt = now
2019
+ this.lastAuthoritySuccessAt = now
2020
+ this.authorityVerdict = decideHostedHarvestAuthority(value, {
2021
+ execution: instance,
2022
+ run: this.deps.preparedRun!.run,
2023
+ leaseHolder: this.deps.leaseHolder ?? instance,
2024
+ })
2025
+ } catch (error) {
2026
+ const kind = classifyAuthorityReadError(error)
2027
+ this.onDiagnostic(
2028
+ `harvest execution ${instance} authority read failed (${kind}): ${errorMessage(error)}`,
2029
+ )
2030
+ if (kind === 'permanent') fence('unsupported')
2031
+ if (kind === 'revoked') fence('revoked')
2032
+ if (
2033
+ this.lastAuthoritySuccessAt === undefined ||
2034
+ now - this.lastAuthoritySuccessAt >= this.leaseTtlMs
2035
+ )
2036
+ fence('unverified')
2037
+ }
2038
+ const decided = this.authorityVerdict
2039
+ if (decided === undefined) fence('unverified')
2040
+ else if (decided.kind === 'fenced') fence(decided.reason)
2041
+ }
2042
+
1811
2043
  private async startHeartbeat(): Promise<void> {
2044
+ // A prepared hosted guest never renews the dispatcher's lease.
2045
+ if (this.executionAuthority) return
1812
2046
  const { store, repo } = this.deps
1813
2047
  const holder = this.deps.leaseHolder ?? this.deps.instance
1814
2048
  if (!(await store.heartbeatRepo(repo, holder))) this.leaseLost = true
@@ -127,6 +127,7 @@ export class RepoViewStore implements BuildStore {
127
127
  opts: RepoViewOptions,
128
128
  ) {
129
129
  this.getBuildEventPage = backing.getBuildEventPage?.bind(backing)
130
+ this.buildCreationIdentity = backing.buildCreationIdentity?.bind(backing)
130
131
  this.getRepositoryTail = backing.getRepositoryTail?.bind(backing)
131
132
  this.getStreamSeed = backing.getStreamSeed?.bind(backing)
132
133
  this.getHarvestHistoryPage = backing.getHarvestHistoryPage?.bind(backing)
@@ -295,6 +296,7 @@ export class RepoViewStore implements BuildStore {
295
296
  return this.backing.getRepoStateEvents(repo)
296
297
  }
297
298
  getBuildEventPage: BuildStore['getBuildEventPage']
299
+ buildCreationIdentity: BuildStore['buildCreationIdentity']
298
300
  getRepositoryTail: BuildStore['getRepositoryTail']
299
301
  getStreamSeed: BuildStore['getStreamSeed']
300
302
  getHarvestHistoryPage: BuildStore['getHarvestHistoryPage']