@defrex/autobuild 1.0.0-beta.3 → 1.0.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 (168) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +362 -56
  3. package/bin/ab-dispatch-generation.ts +93 -0
  4. package/docs/agent-runtimes.md +157 -0
  5. package/docs/answering-blocked-builds.md +21 -3
  6. package/docs/architecture.md +166 -7
  7. package/docs/build-store.md +123 -0
  8. package/docs/builds.md +82 -0
  9. package/docs/cli.md +48 -0
  10. package/docs/configuration-overview.md +93 -0
  11. package/docs/configuration.md +1778 -188
  12. package/docs/dispatcher-hosting.md +115 -0
  13. package/docs/dispatcher.md +59 -0
  14. package/docs/forges.md +121 -0
  15. package/docs/getting-started.md +60 -0
  16. package/docs/glossary.md +60 -0
  17. package/docs/hosted-service.md +2 -2
  18. package/docs/intake.md +48 -0
  19. package/docs/integration-overview.md +81 -0
  20. package/docs/integration-tree.md +87 -2
  21. package/docs/integration.md +54 -0
  22. package/docs/operating.md +114 -0
  23. package/docs/operator-api.md +64 -11
  24. package/docs/operator-surfaces.md +90 -0
  25. package/docs/overview.md +49 -0
  26. package/docs/plugin-authoring.md +426 -0
  27. package/docs/remote-store-protocol.md +12 -9
  28. package/docs/restacking.md +4 -1
  29. package/docs/seams.md +66 -0
  30. package/docs/setup.md +28 -6
  31. package/docs/skills.md +119 -0
  32. package/docs/spec-standard.md +23 -5
  33. package/docs/ticket-sources.md +132 -0
  34. package/docs/tickets.md +69 -0
  35. package/docs/troubleshooting.md +111 -0
  36. package/docs/upgrading.md +50 -0
  37. package/docs/verification.md +146 -0
  38. package/docs/website.md +47 -5
  39. package/docs/workspaces.md +152 -0
  40. package/package.json +5 -4
  41. package/packages/core/src/cli/artifact.ts +5 -4
  42. package/packages/core/src/cli/attention.ts +2 -0
  43. package/packages/core/src/cli/binary-direct.ts +190 -0
  44. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  45. package/packages/core/src/cli/binary.ts +24 -210
  46. package/packages/core/src/cli/build-control.ts +105 -2
  47. package/packages/core/src/cli/context.ts +41 -1
  48. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  49. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  50. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  51. package/packages/core/src/cli/dashboard/model.ts +34 -10
  52. package/packages/core/src/cli/dashboard/render.ts +24 -2
  53. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  54. package/packages/core/src/cli/dispatch-args.ts +53 -0
  55. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  56. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  57. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  58. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  59. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  60. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  61. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  62. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  63. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  64. package/packages/core/src/cli/dispatch-process.ts +22 -90
  65. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  66. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  67. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  68. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  69. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  70. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  71. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  72. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  73. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  74. package/packages/core/src/cli/dispatch.ts +604 -60
  75. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  76. package/packages/core/src/cli/env.ts +1 -1
  77. package/packages/core/src/cli/harvest.ts +28 -11
  78. package/packages/core/src/cli/help.ts +10 -5
  79. package/packages/core/src/cli/installation.ts +5 -3
  80. package/packages/core/src/cli/main-checkout.ts +59 -0
  81. package/packages/core/src/cli/main.ts +15 -45
  82. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  83. package/packages/core/src/cli/repo-state.ts +3 -58
  84. package/packages/core/src/cli/repository-status.ts +67 -3
  85. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  86. package/packages/core/src/cli/status.ts +57 -3
  87. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  88. package/packages/core/src/cli/wait.ts +3 -0
  89. package/packages/core/src/cli/watch.ts +7 -0
  90. package/packages/core/src/config/landing.ts +8 -0
  91. package/packages/core/src/config/live.ts +1 -0
  92. package/packages/core/src/config/reference-metadata.ts +31 -0
  93. package/packages/core/src/config/reference.ts +342 -0
  94. package/packages/core/src/config/roles.ts +1 -1
  95. package/packages/core/src/config/schema.ts +352 -10
  96. package/packages/core/src/distribution-packaging.ts +116 -0
  97. package/packages/core/src/events/catalog.ts +6 -0
  98. package/packages/core/src/events/payloads.ts +53 -9
  99. package/packages/core/src/events/policy.ts +25 -0
  100. package/packages/core/src/events/repository.ts +184 -4
  101. package/packages/core/src/events/runtime.ts +16 -0
  102. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  103. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  104. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  105. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  106. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  107. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  108. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  109. package/packages/core/src/kernel/harvest.ts +98 -4
  110. package/packages/core/src/kernel/integration-attention.ts +20 -0
  111. package/packages/core/src/kernel/integration-state.ts +80 -11
  112. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  113. package/packages/core/src/kernel/mixed-version.ts +34 -0
  114. package/packages/core/src/kernel/node-polling.ts +160 -0
  115. package/packages/core/src/kernel/read-facts.ts +40 -5
  116. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  117. package/packages/core/src/kernel/reducer.ts +75 -14
  118. package/packages/core/src/kernel/service-facts.ts +11 -4
  119. package/packages/core/src/ontology.ts +2 -2
  120. package/packages/core/src/open-map.ts +3 -1
  121. package/packages/core/src/operator/presentation.ts +7 -0
  122. package/packages/core/src/operator/query.ts +6 -2
  123. package/packages/core/src/operator/registry.ts +1 -1
  124. package/packages/core/src/plugins/load.ts +4 -1
  125. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  126. package/packages/core/src/ports/forge/contract.ts +29 -0
  127. package/packages/core/src/ports/forge/github.ts +189 -61
  128. package/packages/core/src/ports/forge-failure.ts +1 -0
  129. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  130. package/packages/core/src/ports/runner/session-env.ts +1 -0
  131. package/packages/core/src/ports/types.ts +10 -0
  132. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  133. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  134. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  135. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  136. package/packages/core/src/processes/build-child-exit.ts +5 -26
  137. package/packages/core/src/processes/build-runner.ts +81 -11
  138. package/packages/core/src/processes/dispatcher.ts +254 -23
  139. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  140. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  141. package/packages/core/src/processes/execution-settlement.ts +16 -7
  142. package/packages/core/src/processes/harvest-runner.ts +328 -292
  143. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  144. package/packages/core/src/runtime-identity.ts +22 -3
  145. package/packages/core/src/store/contract.ts +153 -0
  146. package/packages/core/src/store/local/store.ts +197 -72
  147. package/packages/core/src/store/reduced-reads.ts +8 -0
  148. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  149. package/packages/core/src/store/remote/client.ts +43 -0
  150. package/packages/core/src/store/repo-state-events.ts +20 -3
  151. package/packages/core/src/store/types.ts +7 -0
  152. package/skills/finalize/SKILL.md +3 -1
  153. package/skills/guide/SKILL.md +273 -48
  154. package/skills/guide/references/integration-tree.md +87 -2
  155. package/skills/guide/references/operator-api.md +71 -14
  156. package/skills/guide/references/plugin-authoring.md +231 -266
  157. package/skills/guide/references/remote-store-protocol.md +12 -9
  158. package/skills/guide/references/restacking.md +4 -1
  159. package/skills/guide/references/setup.md +28 -6
  160. package/skills/guide/references/spec-standard.md +23 -5
  161. package/skills/harvest/SKILL.md +4 -0
  162. package/skills/harvest-review/SKILL.md +4 -0
  163. package/skills/implement/SKILL.md +4 -2
  164. package/skills/operate/SKILL.md +104 -35
  165. package/skills/plan/SKILL.md +12 -4
  166. package/skills/spec/SKILL.md +20 -2
  167. package/skills/tickets/SKILL.md +20 -1
  168. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,9 @@
1
+ import {
2
+ guardNativeHandle,
3
+ nativeSessionHandleSchema,
4
+ resumeAgent,
5
+ } from '../ports/runner/native-session'
6
+ import type { NativeSessionHandle, AgentStartOpts } from '../ports/types'
1
7
  import { readRepositoryFacts } from '../store/reduced-reads'
2
8
  import { ticketIdentity } from '../ports/tickets/identity'
3
9
  import { issueTicketGrant } from '../ports/tickets/grants'
@@ -105,6 +111,8 @@ export interface HarvestRunnerDeps {
105
111
  environment?: { provider: string; environmentId: string; sessionId?: string }
106
112
  preparedRun?: { run: string }
107
113
  sessionEnv?: Record<string, string>
114
+ shutdownSignal?: AbortSignal
115
+ shutdownCause?: () => 'shutdown' | 'cutover'
108
116
  opts?: HarvestRunnerOpts
109
117
  }
110
118
 
@@ -113,6 +121,7 @@ export type HarvestRunnerResult =
113
121
  | { outcome: 'idle' }
114
122
  | { outcome: 'held' }
115
123
  | { outcome: 'parked'; run?: string }
124
+ | { outcome: 'suspended'; run?: string }
116
125
  | {
117
126
  outcome: 'completed' | 'escalated' | 'failed'
118
127
  launch: 'started' | 'resumed'
@@ -123,6 +132,7 @@ interface ProducerSession {
123
132
  handle: AgentSessionHandle
124
133
  runner: AgentRunner
125
134
  route: string
135
+ nativeHandle?: NativeSessionHandle
126
136
  }
127
137
 
128
138
  type HarvestProviderAttempt = NonNullable<
@@ -138,6 +148,9 @@ interface SessionBracketStream {
138
148
  streamId: string
139
149
  }
140
150
 
151
+ class HarvestSuspendedSignal extends Error {}
152
+ class HarvestPersistenceError extends Error {}
153
+
141
154
  class SessionFailure extends Error {
142
155
  constructor(message: string) {
143
156
  super(message)
@@ -234,6 +247,7 @@ export class HarvestRunner {
234
247
  let initial: 'started' | 'resumed' = 'resumed'
235
248
  let run: HarvestRunState | undefined
236
249
  try {
250
+ this.shutdownBoundary()
237
251
  await this.startHeartbeat()
238
252
  await this.ensureLease()
239
253
  // Bounded read (AUT-489): reduceHarvest and the verdict/failure filters
@@ -250,6 +264,26 @@ export class HarvestRunner {
250
264
  let state = events.harvest
251
265
  run = actionableHarvestRun(state)
252
266
 
267
+ // An open bracket after process loss is a real interrupted attempt.
268
+ // Orderly shutdown leaves a suspended bracket instead.
269
+ if (run?.sessions.at(-1)?.status === 'open') {
270
+ const session = run.sessions.at(-1)!
271
+ const terminal =
272
+ session.step === 'synthesize'
273
+ ? run.proposals.some((p) => p.round === session.round)
274
+ : run.reviews.some((r) => r.round === session.round)
275
+ const runId = run.run
276
+ const failureAlreadyRecorded = Object.values(events.harvestFailures).some(
277
+ ({ latest }) => latest.payload.run === runId && latest.seq > session.startedSeq,
278
+ )
279
+ if (!terminal && !failureAlreadyRecorded) {
280
+ await this.recordWorkflowFailure(
281
+ run.run,
282
+ new Error('harvest agent interrupted by runner loss'),
283
+ true,
284
+ )
285
+ }
286
+ }
253
287
  // Settle durable operator control before scanning or resuming work. The
254
288
  // selected run comes from the full journal, so a shadowed failure or
255
289
  // exhaustion barrier is recovered/reported before any later open run.
@@ -349,7 +383,12 @@ export class HarvestRunner {
349
383
  const outcome = await this.executeWorkflow(run)
350
384
  return { outcome, launch: initial, run: run.run }
351
385
  } catch (error) {
352
- if (error instanceof HarvestLeaseLostError || error instanceof HarvestParkedSignal) {
386
+ if (
387
+ error instanceof HarvestLeaseLostError ||
388
+ error instanceof HarvestParkedSignal ||
389
+ error instanceof HarvestSuspendedSignal ||
390
+ error instanceof HarvestPersistenceError
391
+ ) {
353
392
  throw error
354
393
  }
355
394
  if (error instanceof SessionFailure) {
@@ -361,6 +400,8 @@ export class HarvestRunner {
361
400
  return { outcome: 'failed', launch: initial, run: run.run }
362
401
  }
363
402
  } catch (error) {
403
+ if (error instanceof HarvestSuspendedSignal)
404
+ return { outcome: 'suspended', ...(run ? { run: run.run } : {}) }
364
405
  if (error instanceof HarvestParkedSignal) {
365
406
  const parkedRun = error.run ?? run?.run
366
407
  return parkedRun === undefined
@@ -585,7 +626,6 @@ export class HarvestRunner {
585
626
  terminal: (event: RepositoryEvent, session: string) => boolean
586
627
  }): Promise<void> {
587
628
  const resolved = this.currentResolver().resolve(spec.role)
588
- if (resolved.alternates.length === 0) return this.executeSingleSession(spec)
589
629
  return this.executeSessionChain(spec, resolved, resolved.alternates)
590
630
  }
591
631
 
@@ -603,6 +643,7 @@ export class HarvestRunner {
603
643
  alternates: readonly ResolvedRuntime[],
604
644
  ): Promise<void> {
605
645
  const { store, repo, ids, workspacePath } = this.deps
646
+ this.shutdownBoundary()
606
647
  await this.ensureLease()
607
648
  // Bounded read (AUT-489): reduceHarvest and the harvest.failed filter
608
649
  // consume durable types only.
@@ -620,7 +661,19 @@ export class HarvestRunner {
620
661
  throw new SessionFailure(`${spec.step}@${spec.round} exhausted retries`)
621
662
  }
622
663
 
623
- const targets = [primary, ...alternates]
664
+ const prior = current?.sessions.findLast(
665
+ (s) => s.step === spec.step && s.round === spec.round && s.status !== 'ended',
666
+ )
667
+ const candidates = [primary, ...alternates].map((target, index) => ({ target, index }))
668
+ const selected = prior
669
+ ? candidates.find(
670
+ ({ target: t }) =>
671
+ t.runtime === prior.runner &&
672
+ t.model === prior.model &&
673
+ JSON.stringify(t.args) === JSON.stringify(prior.args ?? []),
674
+ )
675
+ : undefined
676
+ const targets = selected ? [selected, ...candidates.filter((t) => t !== selected)] : candidates
624
677
  const attempts: HarvestProviderAttempt[] = []
625
678
  let substitution: HarvestProviderAttempt | undefined
626
679
  const primaryRoute = JSON.stringify({
@@ -641,12 +694,22 @@ export class HarvestRunner {
641
694
  this.producer = undefined
642
695
  primaryLive = undefined
643
696
  }
644
- for (let index = 0; index < targets.length; index += 1) {
645
- const target = targets[index]!
697
+ for (let position = 0; position < targets.length; position += 1) {
698
+ const { target, index } = targets[position]!
699
+ this.shutdownBoundary()
646
700
  const session = ids('hs')
701
+ const continuation =
702
+ position === 0 && prior
703
+ ? {
704
+ predecessor: prior.session,
705
+ root: prior.continuation?.root ?? prior.session,
706
+ ...(prior.nativeHandle ? { handle: prior.nativeHandle } : {}),
707
+ cause: prior.cause ?? ('runner-loss' as const),
708
+ }
709
+ : undefined
647
710
  // A pause requested while a provider failed is honored before another
648
711
  // provider starts; the incomplete step safely restarts at the primary.
649
- if (index > 0) await this.controlBoundary(spec.run)
712
+ if (position > 0) await this.controlBoundary(spec.run)
650
713
  else await this.ensureLease()
651
714
  const streamBracket = await this.openSessionStream(target, {
652
715
  session,
@@ -657,12 +720,14 @@ export class HarvestRunner {
657
720
  round: spec.round,
658
721
  })
659
722
  const stream = streamBracket?.sink
723
+ await this.ensureLease()
660
724
  const started = await store.appendRepo(repo, {
661
725
  actor: KERNEL,
662
726
  type: 'harvest.session.started',
663
727
  payload: {
664
728
  run: spec.run,
665
729
  session,
730
+ ...(continuation ? { continuation } : {}),
666
731
  role: spec.role,
667
732
  runner: target.runtime,
668
733
  ...(target.model !== undefined ? { model: target.model } : {}),
@@ -680,33 +745,127 @@ export class HarvestRunner {
680
745
  let result: AgentTurnResult | undefined
681
746
  let turnError: unknown
682
747
  const live = index === 0 ? primaryLive : undefined
748
+ let nativeHandle = live?.nativeHandle
749
+ let observationFailure: unknown
750
+ let accepted = false
751
+ let recorded = false
752
+ const onNativeSession = async (value: NativeSessionHandle) => {
753
+ try {
754
+ await this.ensureLease()
755
+ const validated = nativeSessionHandleSchema.parse(value)
756
+ const expected =
757
+ nativeHandle ?? (continuation && !fallback ? continuation.handle : undefined)
758
+ if (expected && JSON.stringify(expected) !== JSON.stringify(validated))
759
+ throw new Error('Conflicting harvest native identity')
760
+ if (!recorded) {
761
+ await store.appendRepo(repo, {
762
+ actor: KERNEL,
763
+ type: 'harvest.session.native-handle-recorded',
764
+ payload: { run: spec.run, session, handle: validated },
765
+ })
766
+ nativeHandle = validated
767
+ recorded = true
768
+ }
769
+ if (continuation && !fallback && !accepted) {
770
+ await store.appendRepo(repo, {
771
+ actor: KERNEL,
772
+ type: 'harvest.session.resumed',
773
+ payload: {
774
+ run: spec.run,
775
+ session,
776
+ predecessor: continuation.predecessor,
777
+ root: continuation.root,
778
+ handle: validated,
779
+ },
780
+ })
781
+ accepted = true
782
+ }
783
+ } catch (error) {
784
+ observationFailure = error
785
+ throw error
786
+ }
787
+ }
788
+ let fallback = false
789
+ const recordFallback = async (
790
+ reason: HarvestEventPayload<'harvest.session.resume-fallback'>['reason'],
791
+ message: string,
792
+ ) => {
793
+ await this.ensureLease()
794
+ await store.appendRepo(repo, {
795
+ actor: KERNEL,
796
+ type: 'harvest.session.resume-fallback',
797
+ payload: { run: spec.run, session, reason, message },
798
+ })
799
+ fallback = true
800
+ nativeHandle = undefined
801
+ recorded = false
802
+ }
683
803
  try {
684
- if (live !== undefined) {
685
- handle = live.handle
686
- result = await live.runner.continue(
687
- live.handle,
688
- `Revise harvest proposals for round ${spec.round}: run ab harvest context, address .ab/findings.json, then submit.`,
689
- {
690
- env: await this.sessionEnv(spec.run, spec.step, spec.round, session),
691
- ...(stream !== undefined ? { stream } : {}),
692
- },
693
- )
694
- } else {
695
- const turn = await target.runner.start({
696
- skill: spec.skill,
697
- invocation: spec.run,
698
- workspacePath,
699
- ...(target.model !== undefined ? { model: target.model } : {}),
700
- ...(target.args !== undefined ? { args: target.args } : {}),
701
- env: await this.sessionEnv(spec.run, spec.step, spec.round, session),
702
- ...(stream !== undefined ? { stream } : {}),
703
- })
704
- handle = turn.session
705
- result = turn.result
804
+ const opts: AgentStartOpts = {
805
+ skill: spec.skill,
806
+ invocation: spec.run,
807
+ workspacePath,
808
+ ...(target.model !== undefined ? { model: target.model } : {}),
809
+ args: target.args,
810
+ env: await this.sessionEnv(spec.run, spec.step, spec.round, session),
811
+ signal: this.deps.shutdownSignal,
812
+ onNativeSession,
813
+ ...(stream !== undefined ? { stream } : {}),
814
+ }
815
+ if (!this.deps.shutdownSignal?.aborted) {
816
+ if (continuation) {
817
+ if (!selected)
818
+ await recordFallback(
819
+ 'changed-route',
820
+ 'Original harvest runtime route is no longer configured',
821
+ )
822
+ else if (!continuation.handle)
823
+ await recordFallback(
824
+ 'missing-handle',
825
+ 'No native identity was recorded before suspension',
826
+ )
827
+ else {
828
+ const resumed =
829
+ guardNativeHandle(continuation.handle, target.runner.name, opts) ??
830
+ (await resumeAgent(
831
+ target.runner,
832
+ continuation.handle,
833
+ 'Continue this harvest turn. Run ab harvest context again and inspect authoritative artifacts and feedback before continuing.',
834
+ opts,
835
+ ))
836
+ if (resumed.kind === 'not-resumable')
837
+ await recordFallback(resumed.reason, resumed.message)
838
+ else {
839
+ handle = resumed.session
840
+ result = resumed.result
841
+ }
842
+ }
843
+ }
844
+ if ((!continuation || fallback) && !this.deps.shutdownSignal?.aborted) {
845
+ if (live !== undefined && !continuation) {
846
+ handle = live.handle
847
+ if (nativeHandle) await onNativeSession(nativeHandle)
848
+ if (!this.deps.shutdownSignal?.aborted)
849
+ result = await live.runner.continue(
850
+ live.handle,
851
+ `Revise harvest proposals for round ${spec.round}: run ab harvest context, address .ab/findings.json, then submit.`,
852
+ opts,
853
+ )
854
+ } else {
855
+ const turn = await target.runner.start(opts)
856
+ handle = turn.session
857
+ result = turn.result
858
+ }
859
+ }
706
860
  }
707
861
  } catch (error) {
708
862
  turnError = error
709
863
  }
864
+ if (observationFailure instanceof HarvestLeaseLostError) throw observationFailure
865
+ if (observationFailure !== undefined)
866
+ throw new HarvestPersistenceError('Native identity persistence failed', {
867
+ cause: observationFailure,
868
+ })
710
869
 
711
870
  try {
712
871
  await this.ensureLease()
@@ -723,16 +882,98 @@ export class HarvestRunner {
723
882
  }
724
883
 
725
884
  const since = await store.getRepoEvents(repo, started.seq)
726
- const terminal =
727
- turnError === undefined && since.some((event) => spec.terminal(event, session))
885
+ const terminal = since.some((event) => spec.terminal(event, session))
728
886
  const owner = live?.runner ?? target.runner
729
887
  const close =
730
888
  streamBracket !== undefined
731
889
  ? { stream: streamBracket, outcome: 'completed' as const }
732
890
  : undefined
891
+ if (this.deps.shutdownSignal?.aborted) {
892
+ let content = JSON.stringify({
893
+ session,
894
+ interrupted: true,
895
+ result,
896
+ error: turnError === undefined ? undefined : errorMessage(turnError),
897
+ })
898
+ let usage = result?.usage ?? { inputTokens: 0, outputTokens: 0, turns: 0 }
899
+ if (handle) {
900
+ try {
901
+ const transcript = await owner.end(handle)
902
+ if (transcript.content.trim() !== '') content = transcript.content
903
+ usage = transcript.metadata.usage
904
+ } catch {
905
+ /* Partial evidence remains explicit. */
906
+ }
907
+ }
908
+ if (spec.producer) this.producer = undefined
909
+ // Cleanup can finish a typed deposit already in flight. Its terminal
910
+ // wins even when cancellation initially observed no result.
911
+ const completed =
912
+ terminal ||
913
+ (await store.getRepoEvents(repo, started.seq)).some((event) =>
914
+ spec.terminal(event, session),
915
+ )
916
+ if (completed) {
917
+ await this.depositTranscript(spec, session, content, usage, target.model, close)
918
+ return
919
+ }
920
+ try {
921
+ await streamBracket?.sink.close('aborted')
922
+ await this.ensureLease()
923
+ await store.appendRepoWithArtifacts(
924
+ repo,
925
+ [
926
+ {
927
+ kind: HARVEST_TRANSCRIPT_ARTIFACT,
928
+ content,
929
+ metadata: {
930
+ run: spec.run,
931
+ session,
932
+ step: spec.step,
933
+ round: spec.round,
934
+ role: spec.role,
935
+ usage,
936
+ },
937
+ },
938
+ ],
939
+ (artifacts) => ({
940
+ actor: KERNEL,
941
+ type: 'harvest.session.suspended',
942
+ payload: {
943
+ run: spec.run,
944
+ session,
945
+ cause: this.deps.shutdownCause?.() ?? 'shutdown',
946
+ transcript: artifactRef(artifacts[0]!),
947
+ usage,
948
+ },
949
+ }),
950
+ )
951
+ } catch (error) {
952
+ throw new HarvestPersistenceError('Harvest suspension persistence failed', {
953
+ cause: error,
954
+ })
955
+ }
956
+ throw new HarvestSuspendedSignal()
957
+ }
958
+ if (terminal && (handle === undefined || result === undefined)) {
959
+ await this.depositTranscript(
960
+ spec,
961
+ session,
962
+ JSON.stringify({ session, terminal: true, interrupted: true }),
963
+ result?.usage ?? { inputTokens: 0, outputTokens: 0, turns: 0 },
964
+ target.model,
965
+ close,
966
+ )
967
+ return
968
+ }
733
969
  if (terminal && handle !== undefined && result !== undefined) {
734
970
  if (spec.producer && index === 0) {
735
- this.producer = { handle, runner: owner, route: primaryRoute }
971
+ this.producer = {
972
+ handle,
973
+ runner: owner,
974
+ route: primaryRoute,
975
+ ...(nativeHandle ? { nativeHandle } : {}),
976
+ }
736
977
  await this.depositTranscript(
737
978
  spec,
738
979
  session,
@@ -767,38 +1008,56 @@ export class HarvestRunner {
767
1008
  return
768
1009
  }
769
1010
 
1011
+ const failure: AgentTurnFailure =
1012
+ turnError !== undefined
1013
+ ? { message: errorMessage(turnError), permanent: false, cause: 'availability' }
1014
+ : result?.kind === 'failed'
1015
+ ? result.failure
1016
+ : { message: 'no-terminal', permanent: false }
1017
+ let content = JSON.stringify({ session, failed: true, error: failure.message, turn: result })
1018
+ let usage = result?.usage ?? { inputTokens: 0, outputTokens: 0, turns: 0 }
1019
+ let model = target.model
770
1020
  if (handle !== undefined) {
771
1021
  try {
772
1022
  const transcript = await owner.end(handle)
773
- await this.depositTranscript(
774
- spec,
775
- session,
776
- transcript.content,
777
- transcript.metadata.usage,
778
- transcript.metadata.model ?? target.model,
779
- streamBracket !== undefined
780
- ? { stream: streamBracket, outcome: 'aborted' as const }
781
- : undefined,
782
- )
1023
+ if (transcript.content.trim() !== '') content = transcript.content
1024
+ usage = transcript.metadata.usage
1025
+ model = transcript.metadata.model ?? model
783
1026
  } catch (error) {
784
- // The deposit was skipped, so the stream must not stay open behind
785
- // the rethrow (lease lost) or the failure appends below.
786
- this.closeBracketStream(streamBracket, 'aborted')
787
- if (error instanceof HarvestLeaseLostError) throw error
1027
+ if (error instanceof HarvestLeaseLostError) {
1028
+ this.closeBracketStream(streamBracket, 'aborted')
1029
+ throw error
1030
+ }
1031
+ content = JSON.stringify({
1032
+ session,
1033
+ failed: true,
1034
+ error: failure.message,
1035
+ turn: result,
1036
+ cleanupError: errorMessage(error),
1037
+ })
788
1038
  }
789
- } else {
790
- // No handle: the turn failed before the adapter owned a session, so
791
- // no deposit will run — close the bracket's stream here.
792
- this.closeBracketStream(streamBracket, 'aborted')
793
1039
  }
794
1040
  if (spec.producer) this.producer = undefined
795
-
796
- const failure: AgentTurnFailure =
797
- turnError !== undefined
798
- ? { message: errorMessage(turnError), permanent: false, cause: 'availability' }
799
- : result?.kind === 'failed'
800
- ? result.failure
801
- : { message: 'no-terminal', permanent: false }
1041
+ // A handled provider failure must close its bracket even when startup
1042
+ // yielded no handle or cleanup yielded no transcript. Otherwise the next
1043
+ // runner mistakes this ordinary retry for an interrupted native turn.
1044
+ try {
1045
+ await this.depositTranscript(
1046
+ spec,
1047
+ session,
1048
+ content,
1049
+ usage,
1050
+ model,
1051
+ streamBracket !== undefined
1052
+ ? { stream: streamBracket, outcome: 'aborted' as const }
1053
+ : undefined,
1054
+ )
1055
+ } catch (error) {
1056
+ if (error instanceof HarvestLeaseLostError) throw error
1057
+ throw new HarvestPersistenceError('Harvest failed-session transcript persistence failed', {
1058
+ cause: error,
1059
+ })
1060
+ }
802
1061
  const attempt: HarvestProviderAttempt = {
803
1062
  index,
804
1063
  session,
@@ -811,7 +1070,7 @@ export class HarvestRunner {
811
1070
  const eligibleForAlternate =
812
1071
  turnError !== undefined ||
813
1072
  (result?.kind === 'failed' && isAlternateEligible(result.failure))
814
- if (index + 1 < targets.length && eligibleForAlternate) {
1073
+ if (position + 1 < targets.length && eligibleForAlternate) {
815
1074
  substitution = attempt
816
1075
  continue
817
1076
  }
@@ -828,7 +1087,7 @@ export class HarvestRunner {
828
1087
  attempt: attemptNumber,
829
1088
  error: failure.message,
830
1089
  willRetry: mayRetryPhase(failure) && attemptNumber < this.maxSessionAttempts,
831
- providerAttempts: attempts,
1090
+ ...(alternates.length > 0 ? { providerAttempts: attempts } : {}),
832
1091
  },
833
1092
  })
834
1093
  await this.ensureLease()
@@ -847,238 +1106,6 @@ export class HarvestRunner {
847
1106
  }
848
1107
  }
849
1108
 
850
- private async executeSingleSession(spec: {
851
- run: string
852
- role: 'harvest' | 'harvest-review'
853
- skill: string
854
- step: 'synthesize' | 'review'
855
- round: number
856
- producer: boolean
857
- terminal: (event: RepositoryEvent, session: string) => boolean
858
- }): Promise<void> {
859
- const { store, repo, ids, workspacePath } = this.deps
860
- await this.ensureLease()
861
- // Bounded read (AUT-489): reduceHarvest and the harvest.failed filter
862
- // consume durable types only.
863
- const events = (await readRepositoryFacts(store, repo)).value
864
- const failureFacts = events.harvestFailures[JSON.stringify([spec.run, spec.step, spec.round])]
865
- const failures = failureFacts?.count ?? 0
866
- const latestFailure = failureFacts?.latest
867
- const current = events.harvest.runs.find((candidate) => candidate.run === spec.run)
868
- // A stopping failure may already have consumed the ordinary retry budget.
869
- // harvest.resumed deliberately clears that reduced stop and grants one real
870
- // re-entry without deleting history or resetting attempt numbers. The next
871
- // failure fact restores the guard (and parks the run again).
872
- const resumedAfterTerminalFailure =
873
- latestFailure?.payload.willRetry === false &&
874
- current?.status === 'running' &&
875
- current.failure === undefined &&
876
- events.latestHarvestResumedSeq > latestFailure.seq
877
- if (failures >= this.maxSessionAttempts && !resumedAfterTerminalFailure) {
878
- throw new SessionFailure(`${spec.step}@${spec.round} exhausted retries`)
879
- }
880
-
881
- const session = ids('hs')
882
- const resolved = this.currentResolver().resolve(spec.role)
883
- const route = JSON.stringify({
884
- runtime: resolved.runtime,
885
- model: resolved.model,
886
- args: resolved.args,
887
- })
888
- let live = spec.producer ? this.producer : undefined
889
- if (live !== undefined && (live.runner !== resolved.runner || live.route !== route)) {
890
- try {
891
- await live.runner.end(live.handle)
892
- } catch {
893
- // Best-effort cleanup after the old round reached a durable boundary.
894
- }
895
- this.producer = undefined
896
- live = undefined
897
- }
898
- await this.ensureLease()
899
- const streamBracket = await this.openSessionStream(resolved, {
900
- session,
901
- role: spec.role,
902
- runner: resolved.runtime,
903
- ...(resolved.model !== undefined ? { model: resolved.model } : {}),
904
- phase: `harvest:${spec.step}`,
905
- round: spec.round,
906
- })
907
- const stream = streamBracket?.sink
908
- const started = await store.appendRepo(repo, {
909
- actor: KERNEL,
910
- type: 'harvest.session.started',
911
- payload: {
912
- run: spec.run,
913
- session,
914
- role: spec.role,
915
- runner: resolved.runtime,
916
- ...(resolved.model !== undefined ? { model: resolved.model } : {}),
917
- args: [...resolved.args],
918
- step: spec.step,
919
- round: spec.round,
920
- ...(streamBracket !== undefined ? { stream: streamBracket.streamId } : {}),
921
- },
922
- })
923
-
924
- let handle: AgentSessionHandle | undefined
925
- let result: AgentTurnResult | undefined
926
- let turnError: unknown
927
- try {
928
- if (live !== undefined) {
929
- handle = live.handle
930
- result = await live.runner.continue(
931
- live.handle,
932
- `Revise harvest proposals for round ${spec.round}: run ab harvest context, address .ab/findings.json, then submit.`,
933
- {
934
- env: await this.sessionEnv(spec.run, spec.step, spec.round, session),
935
- ...(stream !== undefined ? { stream } : {}),
936
- },
937
- )
938
- } else {
939
- const turn = await resolved.runner.start({
940
- skill: spec.skill,
941
- invocation: spec.run,
942
- workspacePath,
943
- ...(resolved.model !== undefined ? { model: resolved.model } : {}),
944
- ...(resolved.args !== undefined ? { args: resolved.args } : {}),
945
- env: await this.sessionEnv(spec.run, spec.step, spec.round, session),
946
- ...(stream !== undefined ? { stream } : {}),
947
- })
948
- handle = turn.session
949
- result = turn.result
950
- }
951
- } catch (error) {
952
- turnError = error
953
- }
954
-
955
- try {
956
- await this.ensureLease()
957
- } catch (error) {
958
- // The turn may have crossed the lease-expiry boundary. Close adapter
959
- // resources, but deposit no transcript/result after a replacement has
960
- // taken ownership. Continued producers are closed by run()'s finally.
961
- this.closeBracketStream(streamBracket, 'aborted')
962
- if (handle !== undefined && live === undefined) {
963
- try {
964
- await resolved.runner.end(handle)
965
- } catch {
966
- // A dead session may have nothing left to close.
967
- }
968
- }
969
- throw error
970
- }
971
-
972
- const since = await store.getRepoEvents(repo, started.seq)
973
- const terminal = turnError === undefined && since.some((event) => spec.terminal(event, session))
974
-
975
- if (terminal && handle !== undefined && result !== undefined) {
976
- const close =
977
- streamBracket !== undefined
978
- ? { stream: streamBracket, outcome: 'completed' as const }
979
- : undefined
980
- if (spec.producer) {
981
- this.producer = {
982
- handle,
983
- runner: live?.runner ?? resolved.runner,
984
- route,
985
- }
986
- await this.depositTranscript(
987
- spec,
988
- session,
989
- JSON.stringify(
990
- {
991
- session,
992
- run: spec.run,
993
- step: spec.step,
994
- round: spec.round,
995
- turn: result,
996
- note: 'producer session kept live for convergence continuation',
997
- },
998
- null,
999
- 2,
1000
- ),
1001
- result.usage,
1002
- resolved.model,
1003
- close,
1004
- )
1005
- } else {
1006
- const transcript = await resolved.runner.end(handle)
1007
- await this.depositTranscript(
1008
- spec,
1009
- session,
1010
- transcript.content,
1011
- transcript.metadata.usage,
1012
- transcript.metadata.model ?? resolved.model,
1013
- close,
1014
- )
1015
- }
1016
- return
1017
- }
1018
-
1019
- if (handle !== undefined) {
1020
- try {
1021
- const owner = live?.runner ?? resolved.runner
1022
- const transcript = await owner.end(handle)
1023
- await this.depositTranscript(
1024
- spec,
1025
- session,
1026
- transcript.content,
1027
- transcript.metadata.usage,
1028
- transcript.metadata.model ?? resolved.model,
1029
- streamBracket !== undefined
1030
- ? { stream: streamBracket, outcome: 'aborted' as const }
1031
- : undefined,
1032
- )
1033
- } catch (error) {
1034
- // The deposit was skipped, so the stream must not stay open behind
1035
- // the rethrow (lease lost) or the failure appends below.
1036
- this.closeBracketStream(streamBracket, 'aborted')
1037
- if (error instanceof HarvestLeaseLostError) throw error
1038
- // A dead agent may have no recoverable transcript.
1039
- }
1040
- } else {
1041
- // No handle: the turn failed before the adapter owned a session, so
1042
- // no deposit will run — close the bracket's stream here.
1043
- this.closeBracketStream(streamBracket, 'aborted')
1044
- }
1045
- if (spec.producer) this.producer = undefined
1046
- const attempt = failures + 1
1047
- const structuredFailure =
1048
- turnError === undefined && result?.kind === 'failed' ? result.failure : undefined
1049
- const failureMessage =
1050
- turnError !== undefined
1051
- ? errorMessage(turnError)
1052
- : (structuredFailure?.message ?? 'no-terminal')
1053
- const willRetry = structuredFailure?.permanent !== true && attempt < this.maxSessionAttempts
1054
- await this.ensureLease()
1055
- await store.appendRepo(repo, {
1056
- actor: KERNEL,
1057
- type: 'harvest.failed',
1058
- payload: {
1059
- run: spec.run,
1060
- step: spec.step,
1061
- round: spec.round,
1062
- attempt,
1063
- error: failureMessage,
1064
- willRetry,
1065
- },
1066
- })
1067
- await this.ensureLease()
1068
- await store.appendRepo(repo, {
1069
- actor: KERNEL,
1070
- type: 'harvest.step.completed',
1071
- payload: {
1072
- run: spec.run,
1073
- step: spec.step,
1074
- round: spec.round,
1075
- outcome: 'failed',
1076
- detail: failureMessage,
1077
- },
1078
- })
1079
- throw new SessionFailure(`${spec.step}@${spec.round} failed: ${failureMessage}`)
1080
- }
1081
-
1082
1109
  private async depositTranscript(
1083
1110
  spec: {
1084
1111
  run: string
@@ -1332,7 +1359,11 @@ export class HarvestRunner {
1332
1359
  })
1333
1360
  }
1334
1361
 
1335
- private async recordWorkflowFailure(run: string, error: unknown): Promise<void> {
1362
+ private async recordWorkflowFailure(
1363
+ run: string,
1364
+ error: unknown,
1365
+ interrupted = false,
1366
+ ): Promise<void> {
1336
1367
  await this.ensureLease()
1337
1368
  // Bounded read (AUT-489): reduceHarvest and the harvest.failed filter
1338
1369
  // consume durable types only.
@@ -1347,7 +1378,7 @@ export class HarvestRunner {
1347
1378
  const round = open?.round
1348
1379
  const prior = events.harvestFailures[JSON.stringify([run, step, round])]?.count ?? 0
1349
1380
  const attempt = prior + 1
1350
- const willRetry = attempt < this.maxSessionAttempts
1381
+ const willRetry = !interrupted && attempt < this.maxSessionAttempts
1351
1382
  const message = errorMessage(error)
1352
1383
  await this.ensureLease()
1353
1384
  await this.deps.store.appendRepo(this.deps.repo, {
@@ -1440,11 +1471,16 @@ export class HarvestRunner {
1440
1471
  return true
1441
1472
  }
1442
1473
 
1474
+ private shutdownBoundary(): void {
1475
+ if (this.deps.shutdownSignal?.aborted) throw new HarvestSuspendedSignal()
1476
+ }
1477
+
1443
1478
  /** Settle repository-wide commands and automatic recovery only at a durable
1444
1479
  * workflow boundary. Requests and acknowledgements are separate facts, so a
1445
1480
  * replacement process can finish the same transition without spending a
1446
1481
  * second recovery attempt. */
1447
1482
  private async controlBoundary(run?: string): Promise<void> {
1483
+ this.shutdownBoundary()
1448
1484
  while (true) {
1449
1485
  await this.ensureLease()
1450
1486
  // Bounded read (AUT-489): reduceHarvest consumes durable types only.