@defrex/autobuild 1.16.0 → 1.18.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 (97) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +132 -9
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +42 -3
  5. package/docs/configuration.md +44 -7
  6. package/docs/dispatcher-hosting.md +5 -3
  7. package/docs/operator-api.md +29 -6
  8. package/docs/plugin-authoring.md +30 -1
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +37 -2
  11. package/docs/restacking.md +46 -1
  12. package/docs/setup.md +24 -9
  13. package/docs/ticket-sources.md +28 -1
  14. package/docs/troubleshooting.md +54 -2
  15. package/docs/workspaces.md +3 -1
  16. package/package.json +4 -4
  17. package/packages/core/src/cli/accounts.ts +3 -0
  18. package/packages/core/src/cli/binary-direct.ts +14 -1
  19. package/packages/core/src/cli/binary.ts +10 -7
  20. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  21. package/packages/core/src/cli/dispatch.ts +503 -334
  22. package/packages/core/src/cli/secrets.ts +2 -0
  23. package/packages/core/src/config/schema.ts +17 -3
  24. package/packages/core/src/events/payloads.ts +8 -5
  25. package/packages/core/src/events/repository.ts +37 -1
  26. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  27. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  28. package/packages/core/src/kernel/engine.ts +118 -0
  29. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  30. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  31. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  32. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  33. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  34. package/packages/core/src/ontology.ts +1 -0
  35. package/packages/core/src/operator/index.ts +10 -0
  36. package/packages/core/src/operator/merged-builds.ts +51 -0
  37. package/packages/core/src/operator/registry.ts +254 -110
  38. package/packages/core/src/operator/repo-argument.ts +43 -0
  39. package/packages/core/src/operator/tickets.ts +139 -25
  40. package/packages/core/src/plugin-sdk/index.ts +4 -0
  41. package/packages/core/src/plugins/manifest.ts +1 -1
  42. package/packages/core/src/ports/tickets/completion.ts +71 -0
  43. package/packages/core/src/ports/tickets/contract.ts +73 -0
  44. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  45. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  46. package/packages/core/src/ports/tickets/github.ts +18 -6
  47. package/packages/core/src/ports/tickets/grants.ts +2 -0
  48. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  49. package/packages/core/src/ports/tickets/linear.ts +18 -2
  50. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  51. package/packages/core/src/ports/tickets/remote.ts +43 -3
  52. package/packages/core/src/ports/tickets/tree.ts +11 -1
  53. package/packages/core/src/ports/types.ts +47 -4
  54. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  55. package/packages/core/src/ports/workspace/vercel-sandbox.ts +649 -160
  56. package/packages/core/src/processes/build-child.ts +15 -1
  57. package/packages/core/src/processes/build-runner.ts +349 -20
  58. package/packages/core/src/processes/dispatcher.ts +880 -283
  59. package/packages/core/src/processes/harvest-child.ts +21 -1
  60. package/packages/core/src/processes/harvest-runner.ts +82 -35
  61. package/packages/core/src/processes/pass-stages.ts +32 -6
  62. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  63. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  64. package/packages/core/src/processes/repo-view.ts +25 -4
  65. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  66. package/packages/core/src/store/adapter.ts +34 -5
  67. package/packages/core/src/store/build-feed.ts +148 -22
  68. package/packages/core/src/store/build-scope.ts +12 -3
  69. package/packages/core/src/store/caller-attribution.ts +170 -0
  70. package/packages/core/src/store/contract.ts +1038 -165
  71. package/packages/core/src/store/local/schema.ts +12 -1
  72. package/packages/core/src/store/local/store.ts +260 -25
  73. package/packages/core/src/store/memory.ts +156 -9
  74. package/packages/core/src/store/phase-session.ts +23 -3
  75. package/packages/core/src/store/reducer-value-shapes.json +8196 -8118
  76. package/packages/core/src/store/remote/client.ts +90 -11
  77. package/packages/core/src/store/remote/credentials.ts +2 -0
  78. package/packages/core/src/store/remote/index.ts +31 -5
  79. package/packages/core/src/store/remote/protocol.ts +45 -8
  80. package/packages/core/src/store/remote/released-clients.json +22 -0
  81. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  82. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  83. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  84. package/packages/core/src/store/session-handle.ts +12 -3
  85. package/packages/core/src/store/types.ts +48 -3
  86. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  87. package/packages/core/src/testing/index.ts +2 -0
  88. package/packages/core/src/testing/reduced-read-budget.ts +420 -6
  89. package/skills/guide/SKILL.md +67 -13
  90. package/skills/guide/references/operator-api.md +29 -6
  91. package/skills/guide/references/plugin-authoring.md +30 -1
  92. package/skills/guide/references/remote-store-protocol.md +13 -3
  93. package/skills/guide/references/remote-ticket-protocol.md +37 -2
  94. package/skills/guide/references/restacking.md +46 -1
  95. package/skills/guide/references/setup.md +24 -9
  96. package/skills/operate/SKILL.md +42 -4
  97. package/templates/hosted-service/package.json +2 -2
@@ -10,6 +10,11 @@ import { mixedVersionDeferred } from './mixed-version'
10
10
  import { integrationCurrent, integrationConfig, integrationFailed } from './integration-state'
11
11
  import { proposeRunDue, proposeStarted } from './optimization'
12
12
  import { reopenSpecPending, reviseSpecPending } from './reopen-state'
13
+ import {
14
+ dirtyWorktreeArtifact,
15
+ dirtyWorktreeGuidance,
16
+ dirtyWorktreeSetAsideObservation,
17
+ } from './tracked-dirt'
13
18
  /**
14
19
  * The kernel pipeline engine (SPEC §8): "read the event log, decide the next
15
20
  * phase per the transition table, invoke the AgentRunner with `/{skill}
@@ -136,6 +141,20 @@ export type Decision =
136
141
  reconcile?: { attempt: number }
137
142
  /** Present iff phase === 'propose': the open request it answers. */
138
143
  propose?: { request: string; head: string }
144
+ /** The answered `policy/dirty-worktree` escalation this implement round
145
+ * recovers from. Engine-derived, never persisted: the runner skips the
146
+ * setup dirt check for it, since this round's agent handles the dirt. */
147
+ dirtyRecovery?: string
148
+ }
149
+ /** An answered dirty-worktree escalation abandons a frozen preparation that
150
+ * has no publish intent. The worktree keeps the dirt; HEAD returns to the
151
+ * build branch if a replay detached it. */
152
+ | {
153
+ kind: 'supersede-dirty-preparation'
154
+ escalation: string
155
+ attempt: number
156
+ cycle: number
157
+ restackId?: string
139
158
  }
140
159
  | VerifyAction
141
160
  | {
@@ -510,6 +529,41 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
510
529
  // ── 4. Spec (§6.3: dispatch owns the import; `spec` is not a phase §5) ─────
511
530
  if (state.specRev === undefined) return { kind: 'wait', reason: 'awaiting-spec' }
512
531
 
532
+ // An answered dirty-worktree escalation returns the build to implement
533
+ // (SPEC §11): a frozen preparation with no publish intent is superseded
534
+ // first; one with an intent falls through so its candidate settles (the
535
+ // runner sets the dirt aside); with nothing frozen, the recovery round runs.
536
+ const dirtyRecovery = dirtyWorktreeRecovery(state, log)
537
+ if (dirtyRecovery) {
538
+ const { escalation, round } = dirtyRecovery
539
+ const frozen = frozenPreparation(state, log)
540
+ if (frozen && !frozen.intended) {
541
+ const { intended: _intended, ...target } = frozen
542
+ return { kind: 'supersede-dirty-preparation', escalation: escalation.id, ...target }
543
+ }
544
+ if (!frozen)
545
+ return {
546
+ kind: 'run-phase',
547
+ phase: 'implement',
548
+ round,
549
+ dirtyRecovery: escalation.id,
550
+ feedback: {
551
+ guidance: {
552
+ escalation: escalation.id,
553
+ answer: dirtyWorktreeGuidance({
554
+ question: escalation.question,
555
+ ...(escalation.resolution === 'guidance' ? { answer: escalation.answer } : {}),
556
+ ...(state.observations.some(
557
+ (o) => o.id === dirtyWorktreeSetAsideObservation(escalation.id),
558
+ )
559
+ ? { setAside: dirtyWorktreeArtifact(escalation.id) }
560
+ : {}),
561
+ }),
562
+ },
563
+ },
564
+ }
565
+ }
566
+
513
567
  // A revised contract invalidates approvals, but an unfinished replay still
514
568
  // belongs to its reconcile occurrence. Publish it before opening the new
515
569
  // plan loop so no other phase inherits its detached/conflicted workspace.
@@ -1040,6 +1094,70 @@ interface LoopArgs {
1040
1094
  producerFeedback: () => Feedback | undefined
1041
1095
  }
1042
1096
 
1097
+ /**
1098
+ * The recovery an answered `policy/dirty-worktree` escalation selects: the
1099
+ * latest such guidance or retry answer after both restart boundaries, while
1100
+ * the plan loop is approved. The recovery round is the first implement round
1101
+ * started after the answer; until it completes, every rerun is that round.
1102
+ * Once it completes the ordinary loop owns the build.
1103
+ */
1104
+ export function dirtyWorktreeRecovery(
1105
+ state: BuildState,
1106
+ log: LogIndex,
1107
+ ): { escalation: AnsweredEscalation; round: number } | undefined {
1108
+ const escalation = state.answeredEscalations.findLast(
1109
+ (e) => e.source === 'policy' && e.policyCause === 'dirty-worktree',
1110
+ )
1111
+ if (
1112
+ escalation === undefined ||
1113
+ (escalation.resolution !== 'guidance' && escalation.resolution !== 'retry') ||
1114
+ escalation.answeredSeq <= Math.max(log.restartSeq, log.codeRestartSeq)
1115
+ )
1116
+ return undefined
1117
+ if (log.plan.rounds.get(log.plan.maxRound)?.verdict?.verdict !== 'approve') return undefined
1118
+ let designated: number | undefined
1119
+ for (const [round, record] of log.code.rounds)
1120
+ if (
1121
+ record.startedSeq !== undefined &&
1122
+ record.startedSeq > escalation.answeredSeq &&
1123
+ (designated === undefined || round < designated)
1124
+ )
1125
+ designated = round
1126
+ if (designated === undefined)
1127
+ return { escalation, round: (log.code.maxRound || log.code.maxRoundEver) + 1 }
1128
+ if (log.code.rounds.get(designated)?.completedSeq !== undefined) return undefined
1129
+ return { escalation, round: designated }
1130
+ }
1131
+
1132
+ /** A preparation already frozen in durable state: an active automatic
1133
+ * restack, or an open reconcile occurrence. `intended` when its candidate
1134
+ * recorded a publish intent and must settle rather than be superseded. */
1135
+ export function frozenPreparation(
1136
+ state: BuildState,
1137
+ log: LogIndex,
1138
+ ): { attempt: number; cycle: number; restackId?: string; intended: boolean } | undefined {
1139
+ const active = log.restack.active
1140
+ if (active !== undefined)
1141
+ return {
1142
+ // An unadopted automatic transaction never started a reconcile, so the
1143
+ // next attempt cannot match a completed occurrence's transaction.
1144
+ attempt: log.restack.reconcileAttempt ?? state.reconcileAttempts + 1,
1145
+ cycle: active.cycle,
1146
+ restackId: active.id,
1147
+ intended: log.restack.intent !== undefined || log.openReconcile?.intended === true,
1148
+ }
1149
+ if (state.currentPhase?.phase === 'reconcile' || log.openReconcile !== undefined)
1150
+ return {
1151
+ attempt:
1152
+ (state.currentPhase?.phase === 'reconcile' ? state.currentPhase.attempt : undefined) ??
1153
+ log.openReconcile?.attempt ??
1154
+ state.reconcileAttempts,
1155
+ cycle: log.lastConflict?.seq ?? 0,
1156
+ intended: log.openReconcile?.intended === true,
1157
+ }
1158
+ return undefined
1159
+ }
1160
+
1043
1161
  function decideLoop(args: LoopArgs): Decision | 'approved' {
1044
1162
  const {
1045
1163
  loop,
@@ -25,6 +25,13 @@ import {
25
25
  type RetentionOutcome,
26
26
  } from './history-retention'
27
27
  import { readRetainedPack, RetainedCopyInvalid } from './replay-retention'
28
+ import {
29
+ classifyTrackedDirt,
30
+ formatPathList,
31
+ listTrackedDirt,
32
+ restoreTrackedPaths,
33
+ TrackedDirtRefusal,
34
+ } from './tracked-dirt'
28
35
 
29
36
  export type ReconcileTransaction = EventPayload<'reconcile.prepared'>
30
37
  export interface RestackDeps {
@@ -36,6 +43,9 @@ export interface RestackDeps {
36
43
  instance?: string
37
44
  clock?: import('../store/types').Clock
38
45
  beforeRewrite?: () => Promise<void>
46
+ /** Declared `[[generated]]` entries: their tracked dirt is discarded before
47
+ * a replay instead of refusing preparation. */
48
+ generated?: readonly GeneratedEntry[]
39
49
  probeCandidate?: (input: {
40
50
  ref: string
41
51
  slug: string
@@ -578,11 +588,15 @@ async function continuePreparation(
578
588
  (e) => e.type === 'reconcile.publish-intended' && e.payload.id === transaction.id,
579
589
  )
580
590
  if (intent?.type === 'reconcile.publish-intended') {
591
+ // The frozen candidate publishes exactly as recorded, so dirt is
592
+ // classified even when the workspace already holds it (a same-workspace
593
+ // relaunch): generated dirt is discarded, undeclared dirt refuses.
594
+ await settleTrackedDirt(deps, {
595
+ operation: deps.automatic ? 'restack' : 'reconcile',
596
+ id: transaction.id,
597
+ prefix: 'cannot publish an intended replay over local changes',
598
+ })
581
599
  if (currentHead === intent.payload.headSha && parent === transaction.targetBase) return
582
- if ((await output(deps, ['status', '--porcelain', '--untracked-files=no'])) !== '')
583
- throw new Error(
584
- 'cannot restore an intended replay over local changes; preserve and inspect them',
585
- )
586
600
  const candidate = intent.payload.headSha
587
601
  await restoreOrRedo(ctx, candidate)
588
602
  await deps.beforeRewrite?.()
@@ -593,8 +607,17 @@ async function continuePreparation(
593
607
  parent === transaction.targetBase &&
594
608
  currentHead !== transaction.workspaceHead &&
595
609
  buildTrailers(await output(deps, ['show', '-s', '--format=%B', 'HEAD'])).join() === deps.slug
596
- )
610
+ ) {
611
+ // A completed automatic replay is about to record its intent: classify
612
+ // dirt now. A resolver's uncommitted work is left to its session.
613
+ if (deps.automatic !== undefined)
614
+ await settleTrackedDirt(deps, {
615
+ operation: 'restack',
616
+ id: transaction.id,
617
+ prefix: 'cannot publish a replay over local changes',
618
+ })
597
619
  return
620
+ }
598
621
  // A replacement workspace without a resolved intent replays the same durable
599
622
  // change; no resolver-authored result is discarded.
600
623
  }
@@ -626,10 +649,11 @@ async function continuePreparation(
626
649
  head !== transaction.workspaceHead
627
650
  )
628
651
  ) {
629
- if ((await output(deps, ['status', '--porcelain', '--untracked-files=no'])) !== '')
630
- throw new Error(
631
- 'reconcile preparation requires a clean tracked worktree; preserve and inspect local work',
632
- )
652
+ await settleTrackedDirt(deps, {
653
+ operation: deps.automatic ? 'restack' : 'reconcile',
654
+ id: transaction.id,
655
+ prefix: 'reconcile preparation requires a clean tracked worktree',
656
+ })
633
657
  await deps.beforeRewrite?.()
634
658
  await git(deps, ['checkout', '--detach', transaction.targetBase])
635
659
  const result = await commitGit(
@@ -676,6 +700,45 @@ async function continuePreparation(
676
700
  })
677
701
  }
678
702
 
703
+ /**
704
+ * The pre-replay clean-tree gate. A clean tree passes. Dirt confined to
705
+ * declared `[[generated]]` paths is restored to HEAD and recorded once as an
706
+ * observation. Any undeclared dirt refuses with `TrackedDirtRefusal` naming
707
+ * those paths, and nothing is touched, not even generated paths in the set.
708
+ */
709
+ export async function settleTrackedDirt(
710
+ deps: Pick<RestackDeps, 'store' | 'slug' | 'exec' | 'workspacePath' | 'generated'> &
711
+ Partial<Pick<RestackDeps, 'beforeRewrite'>>,
712
+ input: { operation: 'restack' | 'reconcile'; id: string; prefix?: string },
713
+ ): Promise<void> {
714
+ const dirt = await listTrackedDirt(deps.exec, deps.workspacePath)
715
+ if (dirt.length === 0) return
716
+ const { undeclared } = classifyTrackedDirt(dirt, deps.generated ?? [])
717
+ if (undeclared.length > 0)
718
+ throw new TrackedDirtRefusal(
719
+ input.prefix ?? `${input.operation} preparation requires a clean tracked worktree`,
720
+ undeclared,
721
+ )
722
+ await deps.beforeRewrite?.()
723
+ await restoreTrackedPaths(deps.exec, deps.workspacePath, dirt)
724
+ const id = `${input.operation}:${input.id}:generated-dirt:${createHash('sha256')
725
+ .update(JSON.stringify(dirt))
726
+ .digest('hex')}`
727
+ const { observations } = (await readBuildFacts(deps.store, deps.slug)).value
728
+ if (observations.some((entry) => entry.id === id)) return
729
+ await deps.store.append(deps.slug, {
730
+ actor: KERNEL,
731
+ type: 'observation.recorded',
732
+ payload: {
733
+ id,
734
+ kind: 'followup',
735
+ summary: `Discarded uncommitted [[generated]] changes before ${input.operation} preparation: ${formatPathList(dirt)}`,
736
+ files: dirt,
737
+ refs: [`${input.operation}:${input.id}`],
738
+ },
739
+ })
740
+ }
741
+
679
742
  /** `git clean` pathspecs for every declared generated selector. */
680
743
  export function generatedCleanPathspecs(declarations: readonly GeneratedEntry[]): string[] {
681
744
  return generatedSelectors(declarations).map((selector) => `:(glob)${selector}`)
@@ -99,4 +99,9 @@ export const REDUCER_REVISIONS: Readonly<Record<string, string>> = {
99
99
  'repositoryReadFacts/shape/ez3eddcdoo': '#1409 pass cursors and stage timings',
100
100
  'repositoryReadFacts/fold/0xl1c98cpy': '#1409 latest dispatcher.pass-cursors is carried forward',
101
101
  'repositoryReadFacts/shape/70jpyc3nd3': '#1415 launch step, cut instance in deferred hint',
102
+ 'repositoryReadFacts/shape/unl0u1aq73': '#1431 intended workDeadlineAt and claimDeferred',
103
+ 'ticketPreparation/shape/o2u9rxe2bv': '#1431 intended workDeadlineAt and claimDeferred',
104
+ 'repositoryReadFacts/fold/3vtj9fjj4k': '#1431 deferredWork carries tickets',
105
+ 'repositoryReadFacts/shape/l3uobdw03l': '#1431 intended records the admitted level',
106
+ 'ticketPreparation/shape/3hfd72gfgz': '#1431 intended records the admitted level',
102
107
  }
@@ -89,10 +89,13 @@ export interface RepositoryReadAcc {
89
89
  scanSeq?: number
90
90
  scan?: Extract<RepositoryEvent, { type: 'dispatcher.ticket-scan-completed' }>['payload']
91
91
  /** The latest `dispatcher.work-deferred` hint: builds the next tick sweeps
92
- * first. */
92
+ * first, and carried ticket-preparation attempts it resumes first. */
93
93
  deferredWork?: {
94
94
  seq: number
95
95
  builds: Extract<RepositoryEvent, { type: 'dispatcher.work-deferred' }>['payload']['builds']
96
+ tickets?: NonNullable<
97
+ Extract<RepositoryEvent, { type: 'dispatcher.work-deferred' }>['payload']['tickets']
98
+ >
96
99
  }
97
100
  /** The latest `dispatcher.pass-cursors` hint: where each rotated loop of
98
101
  * the next bounded pass continues. */
@@ -259,7 +262,11 @@ export const repositoryReadFactsReducer = defineReducer({
259
262
  acc.scanSeq = event.seq
260
263
  }
261
264
  if (event.type === 'dispatcher.work-deferred')
262
- acc.deferredWork = { seq: event.seq, builds: event.payload.builds }
265
+ acc.deferredWork = {
266
+ seq: event.seq,
267
+ builds: event.payload.builds,
268
+ ...(event.payload.tickets !== undefined ? { tickets: event.payload.tickets } : {}),
269
+ }
263
270
  if (event.type === 'dispatcher.pass-cursors')
264
271
  acc.passCursors = { seq: event.seq, cursors: event.payload.cursors }
265
272
  if (event.type === 'dispatcher.run-started') acc.latestRun = event.payload.run
@@ -20,6 +20,16 @@ export interface TicketPreparation {
20
20
  missing?: string[]
21
21
  /** Its hand-back has been reported (`ticket.handed-back`). */
22
22
  reported?: boolean
23
+ /** The bounded invocation's work deadline (ISO) the latest `intended` was
24
+ * written under. An attempt past it with no recorded failure or bounce was
25
+ * interrupted by that deadline: it resumes and is never handed back. */
26
+ workDeadlineAt?: string
27
+ /** Admitted without a claim call (the preparation would not fit before the
28
+ * work deadline); cleared when a later `intended` records the claim start. */
29
+ claimDeferred?: true
30
+ /** The build level admission decided, recorded by a bounded pass. A
31
+ * carried attempt resumes with it. */
32
+ level?: 'urgent' | 'high' | 'normal' | 'low'
23
33
  }
24
34
  /** Completed attempts leave no historical entries in the canonical value. */
25
35
  export const ticketPreparationReducer = defineReducer<
@@ -0,0 +1,173 @@
1
+ import { compilePathSelectors } from '../config/path-selectors'
2
+ import type { GeneratedEntry } from '../config/schema'
3
+ import type { Exec } from '../ports/workspace/git-worktree'
4
+
5
+ /**
6
+ * Tracked worktree dirt: uncommitted changes to files Git tracks. Declared
7
+ * `[[generated]]` outputs are disposable and discarded before a replay;
8
+ * anything else is work that must reach an agent, never a silent discard.
9
+ */
10
+
11
+ /** Paths with uncommitted tracked changes, sorted and unique. Both sides of a
12
+ * staged rename or copy are included, so restoring them restores the pair. */
13
+ export async function listTrackedDirt(exec: Exec, cwd: string): Promise<string[]> {
14
+ const result = await exec(['git', 'status', '--porcelain=v1', '-z', '--untracked-files=no'], {
15
+ cwd,
16
+ })
17
+ if (result.exitCode !== 0) throw new Error(`git status failed: ${result.stderr || result.stdout}`)
18
+ return parsePorcelainZ(result.stdout)
19
+ }
20
+
21
+ /** Parse `git status --porcelain=v1 -z` records. A rename or copy record is
22
+ * followed by its source path as a separate NUL-terminated field. */
23
+ export function parsePorcelainZ(output: string): string[] {
24
+ const fields = output.split('\0')
25
+ const paths = new Set<string>()
26
+ for (let index = 0; index < fields.length; index++) {
27
+ const record = fields[index]!
28
+ if (record.length < 4) continue
29
+ const status = record.slice(0, 2)
30
+ paths.add(record.slice(3))
31
+ if (status.includes('R') || status.includes('C')) {
32
+ const source = fields[++index]
33
+ if (source) paths.add(source)
34
+ }
35
+ }
36
+ return [...paths].sort()
37
+ }
38
+
39
+ export interface TrackedDirtClassification {
40
+ /** Paths some `[[generated]]` selector owns. */
41
+ generated: string[]
42
+ /** Paths no declaration owns. */
43
+ undeclared: string[]
44
+ }
45
+
46
+ export function classifyTrackedDirt(
47
+ paths: readonly string[],
48
+ declarations: readonly GeneratedEntry[],
49
+ ): TrackedDirtClassification {
50
+ const matches = compilePathSelectors(declarations.flatMap((entry) => entry.paths))
51
+ const generated: string[] = []
52
+ const undeclared: string[] = []
53
+ for (const path of paths) (matches(path) ? generated : undeclared).push(path)
54
+ return { generated, undeclared }
55
+ }
56
+
57
+ /** A bounded, human-readable path list: at most `limit`, then `(+N more)`. */
58
+ export function formatPathList(paths: readonly string[], limit = 20): string {
59
+ const shown = paths.slice(0, limit).join(', ')
60
+ return paths.length > limit ? `${shown} (+${paths.length - limit} more)` : shown
61
+ }
62
+
63
+ /** Reset `paths` to HEAD. A staged add absent from HEAD is only unstaged and
64
+ * left untracked, never deleted. Throws unless the paths end clean. */
65
+ export async function restoreTrackedPaths(
66
+ exec: Exec,
67
+ cwd: string,
68
+ paths: readonly string[],
69
+ ): Promise<void> {
70
+ if (paths.length === 0) return
71
+ const git = async (args: string[], allowFailure = false) => {
72
+ const result = await exec(['git', ...args], { cwd })
73
+ if (result.exitCode !== 0 && !allowFailure)
74
+ throw new Error(`git ${args.join(' ')} failed: ${result.stderr || result.stdout}`)
75
+ return result
76
+ }
77
+ await git(['reset', '-q', 'HEAD', '--', ...paths])
78
+ const present: string[] = []
79
+ for (const path of paths)
80
+ if ((await git(['cat-file', '-e', `HEAD:${path}`], true)).exitCode === 0) present.push(path)
81
+ if (present.length > 0) await git(['checkout', '-q', 'HEAD', '--', ...present])
82
+ const remaining = new Set(await listTrackedDirt(exec, cwd))
83
+ const left = paths.filter((path) => remaining.has(path))
84
+ if (left.length > 0) throw new Error(`could not restore tracked paths: ${formatPathList(left)}`)
85
+ }
86
+
87
+ /** Preparation found tracked changes outside `[[generated]]`; nothing was
88
+ * discarded. `paths` are the undeclared paths. */
89
+ export class TrackedDirtRefusal extends Error {
90
+ constructor(
91
+ readonly prefix: string,
92
+ readonly paths: readonly string[],
93
+ ) {
94
+ super(`${prefix}: uncommitted tracked changes outside [[generated]]: ${formatPathList(paths)}`)
95
+ this.name = 'TrackedDirtRefusal'
96
+ }
97
+ }
98
+
99
+ export type DirtyWorktreeOrigin =
100
+ | { origin: 'setup'; command: string }
101
+ | { origin: 'restack' }
102
+ | { origin: 'reconcile' }
103
+
104
+ /** The `policy/dirty-worktree` escalation question. */
105
+ export function dirtyWorktreeQuestion(
106
+ input: DirtyWorktreeOrigin & { paths: readonly string[] },
107
+ ): string {
108
+ const where =
109
+ input.origin === 'setup'
110
+ ? `[commands].setup ${JSON.stringify(input.command)} modified tracked files outside [[generated]]`
111
+ : `${input.origin} preparation found uncommitted tracked changes outside [[generated]]`
112
+ return (
113
+ `${where}: ${formatPathList(input.paths)}. ` +
114
+ 'Autobuild never commits or discards them on its own. Answer with guidance or a bare retry ' +
115
+ 'to return the build to implement, which commits, reverts or regenerates them (or fixes ' +
116
+ 'setup or [[generated]]); a frozen preparation is superseded, or settled first with the ' +
117
+ 'changes set aside as a build artifact.'
118
+ )
119
+ }
120
+
121
+ /** Artifact kind holding the binary patch of set-aside dirt. */
122
+ export const dirtyWorktreeArtifact = (escalation: string) => `dirty-worktree-${escalation}`
123
+ /** Deterministic observation id recording a set-aside. */
124
+ export const dirtyWorktreeSetAsideObservation = (escalation: string) =>
125
+ `dirty-worktree:${escalation}:set-aside`
126
+
127
+ /** Split a `git diff` patch into its per-file sections, keyed by header. */
128
+ function patchSections(patch: string): Map<string, string> {
129
+ const sections = new Map<string, string>()
130
+ for (const section of patch.split(/^(?=diff --git )/m)) {
131
+ if (!section.startsWith('diff --git ')) continue
132
+ sections.set(section.slice(0, section.indexOf('\n') + 1 || section.length), section)
133
+ }
134
+ return sections
135
+ }
136
+
137
+ /**
138
+ * The set-aside patch after a later capture: every file the current capture
139
+ * shows takes its current section, and every file only the earlier capture
140
+ * held keeps its earlier section, so no captured change is dropped.
141
+ * Base85 binary hunks never start a line with `diff --git `.
142
+ */
143
+ export function mergePatches(previous: string, current: string): string {
144
+ const merged = patchSections(previous)
145
+ for (const [header, section] of patchSections(current)) merged.set(header, section)
146
+ return [...merged.values()].join('')
147
+ }
148
+
149
+ /** The recovery implement round's feedback: question, answer and, when the
150
+ * dirt was set aside, how to get it back. */
151
+ export function dirtyWorktreeGuidance(input: {
152
+ question: string
153
+ /** The operator's guidance; absent for a bare retry. */
154
+ answer?: string
155
+ setAside?: string
156
+ }): string {
157
+ const parts = [`Dirty tracked worktree: ${input.question}`]
158
+ parts.push(
159
+ input.answer === undefined ? 'Operator answer: retry.' : `Operator answer: ${input.answer}`,
160
+ )
161
+ if (input.setAside !== undefined)
162
+ parts.push(
163
+ `The changes were set aside before the kernel moved the workspace. Restore them with ` +
164
+ `\`ab artifact download "$AB_BUILD" ${input.setAside} --output .ab/${input.setAside}.patch\` and ` +
165
+ `\`git apply --binary --3way .ab/${input.setAside}.patch\`, then decide what to keep.`,
166
+ )
167
+ else parts.push('The changes are still in the worktree.')
168
+ parts.push(
169
+ 'Commit, revert or regenerate each listed file, or fix [commands].setup or [[generated]] ' +
170
+ 'so setup stops modifying tracked files, then finish the round.',
171
+ )
172
+ return parts.join('\n\n')
173
+ }
@@ -119,6 +119,7 @@ export const policyEscalationCauseSchema = z.enum([
119
119
  'wait-unresolvable',
120
120
  'measurement-failed',
121
121
  'target-rewritten',
122
+ 'dirty-worktree',
122
123
  ])
123
124
  export type PolicyEscalationCause = z.infer<typeof policyEscalationCauseSchema>
124
125
 
@@ -47,6 +47,16 @@ export {
47
47
  toggleHarvestGate,
48
48
  toggleRepositorySetting,
49
49
  } from './control'
50
+ export {
51
+ listOperatorMergedBuilds,
52
+ type OperatorMergedBuild,
53
+ type OperatorMergedBuildPage,
54
+ } from './merged-builds'
55
+ export {
56
+ REPO_ARGUMENT_CONTRACT,
57
+ REPOSITORY_ARGUMENT_MESSAGE,
58
+ hasRepositoryArgument,
59
+ } from './repo-argument'
50
60
  export {
51
61
  getHarvestStatus,
52
62
  getOperatorBuild,
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `builds.list` with scope `merged`: a repository's merged builds, most
3
+ * recently merged first, paged.
4
+ *
5
+ * Read cost: exactly one `store.listMergedBuildsPage` call per request, at most
6
+ * `limit + 1` (≤ 101) listing-index entries joined to build records. Every
7
+ * field below comes from that page; nothing reads events, reduced values or
8
+ * another build record, so the cost is the same at 10 builds or 10,000 and at
9
+ * 100 events or 100,000.
10
+ */
11
+ import type { TicketRef } from '../ontology'
12
+ import type { MergedBuildPageOptions, MergedBuildTarget } from '../store/build-feed'
13
+ import type { BuildStore } from '../store/types'
14
+
15
+ /** One merged build as `builds.list` scope `merged` reports it. */
16
+ export interface OperatorMergedBuild {
17
+ slug: string
18
+ /** When the build merged: its merging `build.completed`, never a later
19
+ * cleanup write. */
20
+ mergedAt: string
21
+ kind: 'leaf' | 'node'
22
+ ticket?: TicketRef
23
+ pr?: { number: number; url: string }
24
+ /** The node build a child build targets; absent for root-targeting builds. */
25
+ target?: MergedBuildTarget
26
+ }
27
+
28
+ export interface OperatorMergedBuildPage {
29
+ builds: OperatorMergedBuild[]
30
+ /** Pass back as `cursor`, with the same window, for the next page; null on
31
+ * the last page. */
32
+ next: string | null
33
+ }
34
+
35
+ export async function listOperatorMergedBuilds(
36
+ opts: { store: BuildStore; repo: string } & MergedBuildPageOptions,
37
+ ): Promise<OperatorMergedBuildPage> {
38
+ const { store, repo, ...page } = opts
39
+ const answer = await store.listMergedBuildsPage(repo, page)
40
+ return {
41
+ builds: answer.builds.map((build) => ({
42
+ slug: build.record.slug,
43
+ mergedAt: build.mergedAt,
44
+ kind: build.kind,
45
+ ...(build.record.ticket ? { ticket: build.record.ticket } : {}),
46
+ ...(build.pr ? { pr: build.pr } : {}),
47
+ ...(build.target ? { target: build.target } : {}),
48
+ })),
49
+ next: answer.next,
50
+ }
51
+ }