@defrex/autobuild 1.5.0 → 1.6.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 (74) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -14
  3. package/docs/answering-blocked-builds.md +7 -4
  4. package/docs/architecture.md +38 -10
  5. package/docs/configuration.md +55 -5
  6. package/docs/dispatcher.md +2 -2
  7. package/docs/glossary.md +1 -1
  8. package/docs/operating.md +1 -1
  9. package/docs/operator-api.md +14 -2
  10. package/docs/plugin-authoring.md +4 -0
  11. package/docs/remote-store-protocol.md +14 -4
  12. package/docs/restacking.md +4 -0
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +2 -0
  17. package/packages/core/src/cli/dashboard/model.ts +14 -4
  18. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  19. package/packages/core/src/cli/dashboard/render.ts +3 -0
  20. package/packages/core/src/cli/dispatch-preflight.ts +4 -1
  21. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  22. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  23. package/packages/core/src/cli/dispatch.ts +368 -98
  24. package/packages/core/src/cli/help.ts +4 -2
  25. package/packages/core/src/cli/repo-lease.ts +225 -0
  26. package/packages/core/src/cli/repository-status.ts +3 -1
  27. package/packages/core/src/cli/status.ts +13 -13
  28. package/packages/core/src/cli/wait.ts +4 -1
  29. package/packages/core/src/cli/watch.ts +15 -4
  30. package/packages/core/src/config/schema.ts +38 -2
  31. package/packages/core/src/events/catalog.ts +2 -0
  32. package/packages/core/src/events/payloads.ts +15 -0
  33. package/packages/core/src/events/policy.ts +2 -0
  34. package/packages/core/src/events/repository.ts +2 -0
  35. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +196 -230
  36. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  37. package/packages/core/src/kernel/engine.ts +13 -6
  38. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  39. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  40. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  41. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  42. package/packages/core/src/kernel/log-index.ts +1 -1
  43. package/packages/core/src/kernel/node-landing.ts +2 -1
  44. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  45. package/packages/core/src/kernel/reducer.ts +58 -4
  46. package/packages/core/src/kernel/ticket-preparation.ts +11 -7
  47. package/packages/core/src/operator/query.ts +15 -12
  48. package/packages/core/src/ports/tickets/create.ts +19 -5
  49. package/packages/core/src/ports/types.ts +4 -0
  50. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  51. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  52. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  53. package/packages/core/src/ports/workspace/vercel-sandbox.ts +3 -0
  54. package/packages/core/src/processes/build-runner.ts +2 -1
  55. package/packages/core/src/processes/dispatcher.ts +231 -41
  56. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  57. package/packages/core/src/processes/harvest-child.ts +4 -2
  58. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  59. package/packages/core/src/processes/harvest-runner.ts +246 -17
  60. package/packages/core/src/scenarios/harness.ts +145 -35
  61. package/packages/core/src/store/reduced-reads.ts +10 -0
  62. package/packages/core/src/store/reducer-value-shapes.json +1463 -1215
  63. package/packages/core/src/store/remote/released-clients.json +11 -0
  64. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  65. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  66. package/packages/core/src/testing/reduced-read-budget.ts +339 -2
  67. package/skills/guide/SKILL.md +53 -17
  68. package/skills/guide/references/operator-api.md +14 -2
  69. package/skills/guide/references/plugin-authoring.md +4 -0
  70. package/skills/guide/references/remote-store-protocol.md +14 -4
  71. package/skills/guide/references/restacking.md +4 -0
  72. package/skills/operate/SKILL.md +50 -11
  73. package/skills/tickets/SKILL.md +4 -2
  74. 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',
@@ -113,8 +113,10 @@ export async function runHarvestChild(
113
113
  clock: systemClock,
114
114
  instance: input.instance,
115
115
  ...(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.
116
+ // The launching invocation's holder, matched against this execution's
117
+ // authorization. A prepared guest's authority is that durable fact: it
118
+ // never claims, renews or releases the repository lease, so `--once`
119
+ // teardown and a successor's claim do not fence it.
118
120
  ...(input.leaseHolder !== undefined ? { leaseHolder: input.leaseHolder } : {}),
119
121
  ...(input.environment !== undefined ? { environment: input.environment } : {}),
120
122
  sessionEnv: {
@@ -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
@@ -5,7 +5,7 @@ import {
5
5
  resumeAgent,
6
6
  } from '../ports/runner/native-session'
7
7
  import type { NativeSessionHandle, AgentStartOpts } from '../ports/types'
8
- import { readRepositoryFacts } from '../store/reduced-reads'
8
+ import { readHostedHarvestAuthority, readRepositoryFacts } from '../store/reduced-reads'
9
9
  import { issueTicketGrant } from '../ports/tickets/grants'
10
10
  import { delegateCredential } from '../store/remote/credentials'
11
11
  /**
@@ -69,6 +69,12 @@ import {
69
69
  scanUnclaimedObservations,
70
70
  } from './harvest'
71
71
  import type { BuildStore, Clock } from '../store/types'
72
+ import {
73
+ classifyAuthorityReadError,
74
+ decideHostedHarvestAuthority,
75
+ type HarvestAuthorityFence,
76
+ type HostedHarvestAuthority,
77
+ } from './harvest-execution-state'
72
78
 
73
79
  /** Reserved provenance marker for deterministic harvest-created proposals. */
74
80
  export const HARVEST_PROPOSAL_LABEL = 'autobuild:proposal'
@@ -101,14 +107,26 @@ export interface HarvestRunnerDeps {
101
107
  clock: Clock
102
108
  instance: string
103
109
  /** 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. */
110
+ * present, the runner skips its own claim and never releases at the end —
111
+ * the owning loop holds the lease for its lifetime. Without
112
+ * `holdsAuthority` it heartbeats with that holder; a prepared hosted guest
113
+ * instead uses it only to match its durable authorization. Absent keeps the
114
+ * standalone self-claiming behavior. */
107
115
  leaseHolder?: string
116
+ /** The owning DispatchLoop's repository authority: synchronous, no I/O.
117
+ * When present, the loop's lease resolver owns reclaiming the adopted
118
+ * lease, so the runner never claims it itself; a false answer stops the
119
+ * run before its next turn starts, as a lost lease. */
120
+ holdsAuthority?: () => boolean
108
121
  /** Provider-native identity of the disposable environment this run
109
122
  * executes in (hosted harvest). Stamped into the run's harvest.started
110
123
  * payload so the journal records where it ran; absent on local runs. */
111
124
  environment?: { provider: string; environmentId: string; sessionId?: string }
125
+ /** The run a dispatcher prepared and authorized for this execution. Without
126
+ * `holdsAuthority` this is a hosted guest: its authority is the durable
127
+ * `harvest.execution.authorized` for `instance`, never the launching
128
+ * invocation's repository lease, which it neither claims, renews nor
129
+ * releases. */
112
130
  preparedRun?: { run: string }
113
131
  sessionEnv?: Record<string, string>
114
132
  shutdownSignal?: AbortSignal
@@ -167,16 +185,47 @@ class HarvestParkedSignal extends Error {
167
185
  }
168
186
  }
169
187
 
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. */
188
+ /** This process lost its authority: a heartbeat proved it no longer owns the
189
+ * repository lease and a replacement claimed it before we could re-acquire,
190
+ * or — for a prepared hosted guest — its durable execution authority fenced
191
+ * it (`reason`). This is not workflow failure: the replacement resumes the
192
+ * same journal at the next boundary. */
173
193
  class HarvestLeaseLostError extends Error {
174
- constructor(repo: string, instance: string) {
175
- super(`harvest lease for ${repo} is held by another runner ` + `(former holder ${instance})`)
194
+ constructor(
195
+ repo: string,
196
+ instance: string,
197
+ readonly reason?: HarvestAuthorityFence,
198
+ ) {
199
+ super(
200
+ reason === undefined
201
+ ? `harvest lease for ${repo} is held by another runner (former holder ${instance})`
202
+ : `harvest execution ${instance} for ${repo} lost its execution authority: ${reason}`,
203
+ )
176
204
  this.name = 'HarvestLeaseLostError'
177
205
  }
178
206
  }
179
207
 
208
+ /** The session bracket this runner opened and has not yet ended or
209
+ * suspended, with what a fenced exit needs to close it with evidence. */
210
+ interface OpenSessionBracket {
211
+ spec: {
212
+ run: string
213
+ role: 'harvest' | 'harvest-review'
214
+ step: 'synthesize' | 'review'
215
+ round: number
216
+ }
217
+ session: string
218
+ model?: string
219
+ stream?: SessionBracketStream
220
+ owner?: AgentRunner
221
+ handle?: AgentSessionHandle
222
+ transcript?: {
223
+ content: string
224
+ usage: { inputTokens: number; outputTokens: number; turns: number }
225
+ model?: string
226
+ }
227
+ }
228
+
180
229
  function errorMessage(error: unknown): string {
181
230
  return error instanceof Error ? error.message : String(error)
182
231
  }
@@ -206,6 +255,14 @@ export class HarvestRunner {
206
255
  * rejected heartbeat is an outage; later beats retry until one can decide. */
207
256
  private leaseLost = false
208
257
  private producer: ProducerSession | undefined
258
+ /** Prepared hosted guest only: when the durable authority was last read
259
+ * successfully, and what it decided. No verdict never passes. */
260
+ private authorityCheckedAt: number | undefined
261
+ private lastAuthoritySuccessAt: number | undefined
262
+ private authorityVerdict: HostedHarvestAuthority | undefined
263
+ /** Set once a fence fires; final for this runner. */
264
+ private authorityFence: HarvestAuthorityFence | undefined
265
+ private openBracket: OpenSessionBracket | undefined
209
266
 
210
267
  constructor(private readonly deps: HarvestRunnerDeps) {
211
268
  const redactor = accountRedactor(
@@ -236,6 +293,12 @@ export class HarvestRunner {
236
293
  )
237
294
  }
238
295
 
296
+ /** A prepared hosted guest: authority is its durable execution
297
+ * authorization, not a repository lease (see `ensureLease`). */
298
+ private get executionAuthority(): boolean {
299
+ return this.deps.preparedRun !== undefined && this.deps.holdsAuthority === undefined
300
+ }
301
+
239
302
  private currentConfig(): Config {
240
303
  return this.deps.getConfig?.() ?? this.deps.config
241
304
  }
@@ -255,6 +318,7 @@ export class HarvestRunner {
255
318
  if (!this.deps.preparedRun) await store.ensureRepo(repo)
256
319
  if (
257
320
  this.deps.leaseHolder === undefined &&
321
+ !this.executionAuthority &&
258
322
  !(await store.claimRepoLease(repo, instance, this.leaseTtlMs))
259
323
  ) {
260
324
  return { outcome: 'held' }
@@ -423,7 +487,10 @@ export class HarvestRunner {
423
487
  ? { outcome: 'parked' }
424
488
  : { outcome: 'parked', run: parkedRun }
425
489
  }
426
- if (error instanceof HarvestLeaseLostError) return { outcome: 'held' }
490
+ if (error instanceof HarvestLeaseLostError) {
491
+ if (this.executionAuthority) await this.closeFencedBracket(error.reason ?? 'unverified')
492
+ return { outcome: 'held' }
493
+ }
427
494
  throw error
428
495
  } finally {
429
496
  this.stopHeartbeat()
@@ -435,8 +502,10 @@ export class HarvestRunner {
435
502
  }
436
503
  this.producer = undefined
437
504
  }
438
- // An adopted holder is released by the owning DispatchLoop, never here.
439
- if (this.deps.leaseHolder === undefined) await store.releaseRepoLease(repo, instance)
505
+ // An adopted holder is released by the owning DispatchLoop, never here;
506
+ // a prepared hosted guest never held the lease.
507
+ if (this.deps.leaseHolder === undefined && !this.executionAuthority)
508
+ await store.releaseRepoLease(repo, instance)
440
509
  }
441
510
  }
442
511
 
@@ -773,6 +842,12 @@ export class HarvestRunner {
773
842
  : {}),
774
843
  },
775
844
  })
845
+ this.openBracket = {
846
+ spec,
847
+ session,
848
+ ...(target.model !== undefined ? { model: target.model } : {}),
849
+ ...(streamBracket !== undefined ? { stream: streamBracket } : {}),
850
+ }
776
851
 
777
852
  let handle: AgentSessionHandle | undefined
778
853
  let result: AgentTurnResult | undefined
@@ -886,6 +961,7 @@ export class HarvestRunner {
886
961
  opts,
887
962
  )
888
963
  } else {
964
+ this.requireAuthority()
889
965
  const turn = await target.runner.start(opts)
890
966
  handle = turn.session
891
967
  result = turn.result
@@ -895,6 +971,10 @@ export class HarvestRunner {
895
971
  } catch (error) {
896
972
  turnError = error
897
973
  }
974
+ if (handle !== undefined && this.openBracket?.session === session) {
975
+ this.openBracket.handle = handle
976
+ this.openBracket.owner = live?.runner ?? target.runner
977
+ }
898
978
  if (observationFailure instanceof HarvestLeaseLostError) throw observationFailure
899
979
  if (observationFailure !== undefined)
900
980
  throw new HarvestPersistenceError('Native identity persistence failed', {
@@ -906,7 +986,16 @@ export class HarvestRunner {
906
986
  } catch (error) {
907
987
  if (handle !== undefined && live === undefined) {
908
988
  try {
909
- await target.runner.end(handle)
989
+ const transcript = await target.runner.end(handle)
990
+ // A fenced guest closes its own bracket with this evidence.
991
+ if (this.openBracket?.session === session)
992
+ this.openBracket.transcript = {
993
+ content: transcript.content,
994
+ usage: transcript.metadata.usage,
995
+ ...(transcript.metadata.model !== undefined
996
+ ? { model: transcript.metadata.model }
997
+ : {}),
998
+ }
910
999
  } catch {
911
1000
  // A dead session may have nothing left to close.
912
1001
  }
@@ -981,6 +1070,7 @@ export class HarvestRunner {
981
1070
  },
982
1071
  }),
983
1072
  )
1073
+ if (this.openBracket?.session === session) this.openBracket = undefined
984
1074
  } catch (error) {
985
1075
  throw new HarvestPersistenceError('Harvest suspension persistence failed', {
986
1076
  cause: error,
@@ -1158,6 +1248,8 @@ export class HarvestRunner {
1158
1248
  // the ordering structural rather than call-site discipline.
1159
1249
  await close.stream.sink.close(close.outcome)
1160
1250
  }
1251
+ if (this.openBracket?.session === session)
1252
+ this.openBracket.transcript = { content, usage, ...(model !== undefined ? { model } : {}) }
1161
1253
  await this.ensureLease()
1162
1254
  await this.deps.store.appendRepoWithArtifacts(
1163
1255
  this.deps.repo,
@@ -1187,6 +1279,73 @@ export class HarvestRunner {
1187
1279
  },
1188
1280
  }),
1189
1281
  )
1282
+ if (this.openBracket?.session === session) this.openBracket = undefined
1283
+ }
1284
+
1285
+ /**
1286
+ * A prepared hosted guest fenced by its execution authority closes the
1287
+ * session bracket it still has open, so a successor finds an ended session
1288
+ * rather than judging runner loss. Best effort and deliberately unfenced: it
1289
+ * is evidence about this guest's own session, not new work, and the store's
1290
+ * delegated-grant check still refuses it once the grant is retired. A
1291
+ * failed close leaves the release-then-judge path to settle the session.
1292
+ */
1293
+ private async closeFencedBracket(reason: HarvestAuthorityFence): Promise<void> {
1294
+ const bracket = this.openBracket
1295
+ this.openBracket = undefined
1296
+ if (bracket === undefined) return
1297
+ const { spec, session } = bracket
1298
+ try {
1299
+ let transcript = bracket.transcript
1300
+ if (transcript === undefined && bracket.handle !== undefined && bracket.owner !== undefined) {
1301
+ try {
1302
+ const ended = await bracket.owner.end(bracket.handle)
1303
+ transcript = {
1304
+ content: ended.content,
1305
+ usage: ended.metadata.usage,
1306
+ ...(ended.metadata.model !== undefined ? { model: ended.metadata.model } : {}),
1307
+ }
1308
+ } catch {
1309
+ // A dead session may have nothing left to close.
1310
+ }
1311
+ if (this.producer?.handle === bracket.handle) this.producer = undefined
1312
+ }
1313
+ await bracket.stream?.sink.close('aborted')
1314
+ const content =
1315
+ transcript !== undefined && transcript.content.trim() !== ''
1316
+ ? transcript.content
1317
+ : JSON.stringify({ session, fenced: reason })
1318
+ const usage = transcript?.usage ?? { inputTokens: 0, outputTokens: 0, turns: 0 }
1319
+ const model = transcript?.model ?? bracket.model
1320
+ await this.deps.store.appendRepoWithArtifacts(
1321
+ this.deps.repo,
1322
+ [
1323
+ {
1324
+ kind: HARVEST_TRANSCRIPT_ARTIFACT,
1325
+ content,
1326
+ metadata: {
1327
+ run: spec.run,
1328
+ step: spec.step,
1329
+ round: spec.round,
1330
+ role: spec.role,
1331
+ session,
1332
+ ...(model !== undefined ? { model } : {}),
1333
+ usage,
1334
+ fenced: reason,
1335
+ },
1336
+ },
1337
+ ],
1338
+ (deposited) => ({
1339
+ actor: KERNEL,
1340
+ type: 'harvest.session.ended',
1341
+ payload: { run: spec.run, session, transcript: artifactRef(deposited[0]!), usage },
1342
+ }),
1343
+ )
1344
+ } catch (error) {
1345
+ this.onDiagnostic(
1346
+ `harvest session "${session}" fenced (${reason}) could not be closed: ${errorMessage(error)}`,
1347
+ )
1348
+ }
1190
1349
  }
1191
1350
 
1192
1351
  private async file(run: HarvestRunState, approved: ArtifactRef): Promise<void> {
@@ -1795,11 +1954,21 @@ export class HarvestRunner {
1795
1954
  void stream.sink.close(outcome)
1796
1955
  }
1797
1956
 
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. */
1957
+ /** Checked at every durable boundary; work already in an agent turn cannot
1958
+ * be revoked, but this process performs no subsequent kernel/file action
1959
+ * without authority. Three modes:
1960
+ * - in-process (`holdsAuthority`): the owning loop's synchronous fence;
1961
+ * - prepared hosted guest (`preparedRun` without `holdsAuthority`): its
1962
+ * durable execution authority (`ensureExecutionAuthority`);
1963
+ * - standalone or adopted lease: re-acquire a lapsed lease only when no
1964
+ * replacement won it. */
1802
1965
  private async ensureLease(): Promise<void> {
1966
+ if (this.deps.holdsAuthority !== undefined) {
1967
+ this.requireAuthority()
1968
+ this.leaseLost = false
1969
+ return
1970
+ }
1971
+ if (this.executionAuthority) return this.ensureExecutionAuthority()
1803
1972
  if (!this.leaseLost) return
1804
1973
  const { store, repo } = this.deps
1805
1974
  const holder = this.deps.leaseHolder ?? this.deps.instance
@@ -1808,7 +1977,67 @@ export class HarvestRunner {
1808
1977
  this.leaseLost = false
1809
1978
  }
1810
1979
 
1980
+ /** Synchronous authority fence, called immediately before a turn starts. */
1981
+ private requireAuthority(): void {
1982
+ if (this.deps.holdsAuthority?.() === false)
1983
+ throw new HarvestLeaseLostError(this.deps.repo, this.deps.leaseHolder ?? this.deps.instance)
1984
+ }
1985
+
1986
+ /**
1987
+ * A prepared hosted guest's authority is the latest
1988
+ * `harvest.execution.authorized`, which only a repository-lease holder can
1989
+ * append — not the launching invocation's lease, so `--once` teardown and a
1990
+ * successor's claim never fence it. Re-read at most once per `heartbeatMs`
1991
+ * as one constant-size served value, and fail closed: no verdict passes
1992
+ * until a read succeeds; a fenced verdict is final; a permanent contract
1993
+ * error fences `unsupported`, an auth refusal `revoked`; transient errors
1994
+ * keep the last successful verdict only until it is `leaseTtlMs` old.
1995
+ */
1996
+ private async ensureExecutionAuthority(): Promise<void> {
1997
+ const { store, repo, instance } = this.deps
1998
+ const fence = (reason: HarvestAuthorityFence): never => {
1999
+ this.authorityFence = reason
2000
+ throw new HarvestLeaseLostError(repo, instance, reason)
2001
+ }
2002
+ if (this.authorityFence !== undefined) fence(this.authorityFence)
2003
+ const verdict = this.authorityVerdict
2004
+ const now = this.deps.clock().getTime()
2005
+ if (
2006
+ verdict !== undefined &&
2007
+ this.authorityCheckedAt !== undefined &&
2008
+ now - this.authorityCheckedAt < this.heartbeatMs
2009
+ )
2010
+ return
2011
+ try {
2012
+ const { value } = await readHostedHarvestAuthority(store, repo)
2013
+ this.authorityCheckedAt = now
2014
+ this.lastAuthoritySuccessAt = now
2015
+ this.authorityVerdict = decideHostedHarvestAuthority(value, {
2016
+ execution: instance,
2017
+ run: this.deps.preparedRun!.run,
2018
+ leaseHolder: this.deps.leaseHolder ?? instance,
2019
+ })
2020
+ } catch (error) {
2021
+ const kind = classifyAuthorityReadError(error)
2022
+ this.onDiagnostic(
2023
+ `harvest execution ${instance} authority read failed (${kind}): ${errorMessage(error)}`,
2024
+ )
2025
+ if (kind === 'permanent') fence('unsupported')
2026
+ if (kind === 'revoked') fence('revoked')
2027
+ if (
2028
+ this.lastAuthoritySuccessAt === undefined ||
2029
+ now - this.lastAuthoritySuccessAt >= this.leaseTtlMs
2030
+ )
2031
+ fence('unverified')
2032
+ }
2033
+ const decided = this.authorityVerdict
2034
+ if (decided === undefined) fence('unverified')
2035
+ else if (decided.kind === 'fenced') fence(decided.reason)
2036
+ }
2037
+
1811
2038
  private async startHeartbeat(): Promise<void> {
2039
+ // A prepared hosted guest never renews the dispatcher's lease.
2040
+ if (this.executionAuthority) return
1812
2041
  const { store, repo } = this.deps
1813
2042
  const holder = this.deps.leaseHolder ?? this.deps.instance
1814
2043
  if (!(await store.heartbeatRepo(repo, holder))) this.leaseLost = true