@polyweave/preston 0.0.0-stage → 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 (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -2
  3. package/assets/logo.png +0 -0
  4. package/assets/logo.webp +0 -0
  5. package/dist/agents/migration.js +29 -0
  6. package/dist/agents/migration.js.map +1 -0
  7. package/dist/agents/updater.js +385 -0
  8. package/dist/agents/updater.js.map +1 -0
  9. package/dist/channels/chat.js +236 -0
  10. package/dist/channels/chat.js.map +1 -0
  11. package/dist/channels/discord/index.js +491 -0
  12. package/dist/channels/discord/index.js.map +1 -0
  13. package/dist/channels/discord/transport.js +130 -0
  14. package/dist/channels/discord/transport.js.map +1 -0
  15. package/dist/channels/fake/index.js +104 -0
  16. package/dist/channels/fake/index.js.map +1 -0
  17. package/dist/channels/hub.js +153 -0
  18. package/dist/channels/hub.js.map +1 -0
  19. package/dist/channels/outbox.js +219 -0
  20. package/dist/channels/outbox.js.map +1 -0
  21. package/dist/channels/registry.js +67 -0
  22. package/dist/channels/registry.js.map +1 -0
  23. package/dist/channels/router.js +50 -0
  24. package/dist/channels/router.js.map +1 -0
  25. package/dist/channels/shared/delivery.js +74 -0
  26. package/dist/channels/shared/delivery.js.map +1 -0
  27. package/dist/channels/shared/files.js +87 -0
  28. package/dist/channels/shared/files.js.map +1 -0
  29. package/dist/channels/shared/pairing.js +99 -0
  30. package/dist/channels/shared/pairing.js.map +1 -0
  31. package/dist/channels/shared/secrets.js +75 -0
  32. package/dist/channels/shared/secrets.js.map +1 -0
  33. package/dist/channels/shared/text.js +68 -0
  34. package/dist/channels/shared/text.js.map +1 -0
  35. package/dist/channels/shared/typing.js +59 -0
  36. package/dist/channels/shared/typing.js.map +1 -0
  37. package/dist/channels/slack/index.js +560 -0
  38. package/dist/channels/slack/index.js.map +1 -0
  39. package/dist/channels/slack/transport.js +184 -0
  40. package/dist/channels/slack/transport.js.map +1 -0
  41. package/dist/channels/terminal.js +67 -0
  42. package/dist/channels/terminal.js.map +1 -0
  43. package/dist/channels/types.js +6 -0
  44. package/dist/channels/types.js.map +1 -0
  45. package/dist/cli-args.js +92 -0
  46. package/dist/cli-args.js.map +1 -0
  47. package/dist/cli.js +120 -0
  48. package/dist/cli.js.map +1 -0
  49. package/dist/clock.js +76 -0
  50. package/dist/clock.js.map +1 -0
  51. package/dist/config/config.js +184 -0
  52. package/dist/config/config.js.map +1 -0
  53. package/dist/config/schema.js +201 -0
  54. package/dist/config/schema.js.map +1 -0
  55. package/dist/coordinator/coordinator.js +491 -0
  56. package/dist/coordinator/coordinator.js.map +1 -0
  57. package/dist/coordinator/inbox.js +64 -0
  58. package/dist/coordinator/inbox.js.map +1 -0
  59. package/dist/coordinator/input.js +71 -0
  60. package/dist/coordinator/input.js.map +1 -0
  61. package/dist/daemon/daemon.js +228 -0
  62. package/dist/daemon/daemon.js.map +1 -0
  63. package/dist/daemon/ensure.js +87 -0
  64. package/dist/daemon/ensure.js.map +1 -0
  65. package/dist/daemon/lock.js +54 -0
  66. package/dist/daemon/lock.js.map +1 -0
  67. package/dist/daemon/start-at-login.js +20 -0
  68. package/dist/daemon/start-at-login.js.map +1 -0
  69. package/dist/daemon/stop.js +51 -0
  70. package/dist/daemon/stop.js.map +1 -0
  71. package/dist/goals/agents.js +36 -0
  72. package/dist/goals/agents.js.map +1 -0
  73. package/dist/goals/brief.js +51 -0
  74. package/dist/goals/brief.js.map +1 -0
  75. package/dist/goals/checks.js +75 -0
  76. package/dist/goals/checks.js.map +1 -0
  77. package/dist/goals/engine.js +1253 -0
  78. package/dist/goals/engine.js.map +1 -0
  79. package/dist/goals/messages.js +110 -0
  80. package/dist/goals/messages.js.map +1 -0
  81. package/dist/goals/status.js +118 -0
  82. package/dist/goals/status.js.map +1 -0
  83. package/dist/goals/store.js +285 -0
  84. package/dist/goals/store.js.map +1 -0
  85. package/dist/home.js +52 -0
  86. package/dist/home.js.map +1 -0
  87. package/dist/i18n/index.js +37 -0
  88. package/dist/i18n/index.js.map +1 -0
  89. package/dist/ipc/client.js +82 -0
  90. package/dist/ipc/client.js.map +1 -0
  91. package/dist/ipc/private-dir.js +23 -0
  92. package/dist/ipc/private-dir.js.map +1 -0
  93. package/dist/ipc/protocol.js +50 -0
  94. package/dist/ipc/protocol.js.map +1 -0
  95. package/dist/ipc/server.js +110 -0
  96. package/dist/ipc/server.js.map +1 -0
  97. package/dist/landing/exec.js +38 -0
  98. package/dist/landing/exec.js.map +1 -0
  99. package/dist/landing/git.js +93 -0
  100. package/dist/landing/git.js.map +1 -0
  101. package/dist/landing/github.js +154 -0
  102. package/dist/landing/github.js.map +1 -0
  103. package/dist/landing/hooks.js +2 -0
  104. package/dist/landing/hooks.js.map +1 -0
  105. package/dist/landing/landing.js +777 -0
  106. package/dist/landing/landing.js.map +1 -0
  107. package/dist/landing/messages.js +157 -0
  108. package/dist/landing/messages.js.map +1 -0
  109. package/dist/landing/migration.js +50 -0
  110. package/dist/landing/migration.js.map +1 -0
  111. package/dist/landing/paths.js +54 -0
  112. package/dist/landing/paths.js.map +1 -0
  113. package/dist/landing/project.js +95 -0
  114. package/dist/landing/project.js.map +1 -0
  115. package/dist/landing/publishing.js +208 -0
  116. package/dist/landing/publishing.js.map +1 -0
  117. package/dist/landing/stage.js +129 -0
  118. package/dist/landing/stage.js.map +1 -0
  119. package/dist/landing/store.js +160 -0
  120. package/dist/landing/store.js.map +1 -0
  121. package/dist/landing/tools.js +38 -0
  122. package/dist/landing/tools.js.map +1 -0
  123. package/dist/landing/workspace.js +349 -0
  124. package/dist/landing/workspace.js.map +1 -0
  125. package/dist/log.js +77 -0
  126. package/dist/log.js.map +1 -0
  127. package/dist/mcp/coordinator-tools.js +492 -0
  128. package/dist/mcp/coordinator-tools.js.map +1 -0
  129. package/dist/mcp/names.js +8 -0
  130. package/dist/mcp/names.js.map +1 -0
  131. package/dist/mcp/owner-turn.js +15 -0
  132. package/dist/mcp/owner-turn.js.map +1 -0
  133. package/dist/mcp/setup-tools.js +243 -0
  134. package/dist/mcp/setup-tools.js.map +1 -0
  135. package/dist/mcp/stdio.js +74 -0
  136. package/dist/mcp/stdio.js.map +1 -0
  137. package/dist/mcp/tools.js +76 -0
  138. package/dist/mcp/tools.js.map +1 -0
  139. package/dist/mcp/worker-tools.js +53 -0
  140. package/dist/mcp/worker-tools.js.map +1 -0
  141. package/dist/memory/files.js +183 -0
  142. package/dist/memory/files.js.map +1 -0
  143. package/dist/memory/index.js +174 -0
  144. package/dist/memory/index.js.map +1 -0
  145. package/dist/memory/service.js +319 -0
  146. package/dist/memory/service.js.map +1 -0
  147. package/dist/memory/tools.js +82 -0
  148. package/dist/memory/tools.js.map +1 -0
  149. package/dist/notify/index.js +122 -0
  150. package/dist/notify/index.js.map +1 -0
  151. package/dist/prompts/coordinator.js +72 -0
  152. package/dist/prompts/coordinator.js.map +1 -0
  153. package/dist/prompts/grilling.js +8 -0
  154. package/dist/prompts/grilling.js.map +1 -0
  155. package/dist/prompts/teaching.js +17 -0
  156. package/dist/prompts/teaching.js.map +1 -0
  157. package/dist/prompts/worker.js +50 -0
  158. package/dist/prompts/worker.js.map +1 -0
  159. package/dist/questions/questions.js +205 -0
  160. package/dist/questions/questions.js.map +1 -0
  161. package/dist/quota/monitor.js +399 -0
  162. package/dist/quota/monitor.js.map +1 -0
  163. package/dist/quota/schedule.js +38 -0
  164. package/dist/quota/schedule.js.map +1 -0
  165. package/dist/quota/store.js +94 -0
  166. package/dist/quota/store.js.map +1 -0
  167. package/dist/quota/time.js +41 -0
  168. package/dist/quota/time.js.map +1 -0
  169. package/dist/runtime.js +438 -0
  170. package/dist/runtime.js.map +1 -0
  171. package/dist/schedule/cron.js +354 -0
  172. package/dist/schedule/cron.js.map +1 -0
  173. package/dist/schedule/service.js +425 -0
  174. package/dist/schedule/service.js.map +1 -0
  175. package/dist/schedule/store.js +210 -0
  176. package/dist/schedule/store.js.map +1 -0
  177. package/dist/schedule/tools.js +246 -0
  178. package/dist/schedule/tools.js.map +1 -0
  179. package/dist/selfupdate/npm.js +114 -0
  180. package/dist/selfupdate/npm.js.map +1 -0
  181. package/dist/selfupdate/start.js +113 -0
  182. package/dist/selfupdate/start.js.map +1 -0
  183. package/dist/selfupdate/state.js +22 -0
  184. package/dist/selfupdate/state.js.map +1 -0
  185. package/dist/selfupdate/updater.js +120 -0
  186. package/dist/selfupdate/updater.js.map +1 -0
  187. package/dist/service/host.js +46 -0
  188. package/dist/service/host.js.map +1 -0
  189. package/dist/service/index.js +142 -0
  190. package/dist/service/index.js.map +1 -0
  191. package/dist/service/launchd.js +88 -0
  192. package/dist/service/launchd.js.map +1 -0
  193. package/dist/service/spec.js +9 -0
  194. package/dist/service/spec.js.map +1 -0
  195. package/dist/service/systemd.js +90 -0
  196. package/dist/service/systemd.js.map +1 -0
  197. package/dist/service/windows.js +122 -0
  198. package/dist/service/windows.js.map +1 -0
  199. package/dist/setup/pairing.js +143 -0
  200. package/dist/setup/pairing.js.map +1 -0
  201. package/dist/setup/setup.js +76 -0
  202. package/dist/setup/setup.js.map +1 -0
  203. package/dist/standing/defaults.js +80 -0
  204. package/dist/standing/defaults.js.map +1 -0
  205. package/dist/standing/model.js +72 -0
  206. package/dist/standing/model.js.map +1 -0
  207. package/dist/standing/service.js +228 -0
  208. package/dist/standing/service.js.map +1 -0
  209. package/dist/standing/tools.js +184 -0
  210. package/dist/standing/tools.js.map +1 -0
  211. package/dist/store/db.js +67 -0
  212. package/dist/store/db.js.map +1 -0
  213. package/dist/store/migrations.js +280 -0
  214. package/dist/store/migrations.js.map +1 -0
  215. package/dist/supervisor/processes.js +128 -0
  216. package/dist/supervisor/processes.js.map +1 -0
  217. package/dist/supervisor/stalls.js +103 -0
  218. package/dist/supervisor/stalls.js.map +1 -0
  219. package/dist/terminal/activity.js +97 -0
  220. package/dist/terminal/activity.js.map +1 -0
  221. package/dist/terminal/conversation.js +231 -0
  222. package/dist/terminal/conversation.js.map +1 -0
  223. package/dist/util/async-queue.js +41 -0
  224. package/dist/util/async-queue.js.map +1 -0
  225. package/dist/util/command.js +29 -0
  226. package/dist/util/command.js.map +1 -0
  227. package/dist/util/ids.js +9 -0
  228. package/dist/util/ids.js.map +1 -0
  229. package/dist/util/process-tree.js +62 -0
  230. package/dist/util/process-tree.js.map +1 -0
  231. package/dist/util/secrets.js +31 -0
  232. package/dist/util/secrets.js.map +1 -0
  233. package/dist/version.js +5 -0
  234. package/dist/version.js.map +1 -0
  235. package/dist/workers/claude/classify.js +172 -0
  236. package/dist/workers/claude/classify.js.map +1 -0
  237. package/dist/workers/claude/index.js +440 -0
  238. package/dist/workers/claude/index.js.map +1 -0
  239. package/dist/workers/claude/process.js +135 -0
  240. package/dist/workers/claude/process.js.map +1 -0
  241. package/dist/workers/claude/quota.js +37 -0
  242. package/dist/workers/claude/quota.js.map +1 -0
  243. package/dist/workers/claude/stream.js +286 -0
  244. package/dist/workers/claude/stream.js.map +1 -0
  245. package/dist/workers/codex/index.js +181 -0
  246. package/dist/workers/codex/index.js.map +1 -0
  247. package/dist/workers/codex/mapping.js +166 -0
  248. package/dist/workers/codex/mapping.js.map +1 -0
  249. package/dist/workers/codex/process.js +124 -0
  250. package/dist/workers/codex/process.js.map +1 -0
  251. package/dist/workers/codex/protocol.js +7 -0
  252. package/dist/workers/codex/protocol.js.map +1 -0
  253. package/dist/workers/codex/rpc.js +145 -0
  254. package/dist/workers/codex/rpc.js.map +1 -0
  255. package/dist/workers/codex/run.js +556 -0
  256. package/dist/workers/codex/run.js.map +1 -0
  257. package/dist/workers/env.js +49 -0
  258. package/dist/workers/env.js.map +1 -0
  259. package/dist/workers/fake/index.js +283 -0
  260. package/dist/workers/fake/index.js.map +1 -0
  261. package/dist/workers/models.js +171 -0
  262. package/dist/workers/models.js.map +1 -0
  263. package/dist/workers/registry.js +63 -0
  264. package/dist/workers/registry.js.map +1 -0
  265. package/dist/workers/types.js +6 -0
  266. package/dist/workers/types.js.map +1 -0
  267. package/package.json +66 -4
@@ -0,0 +1,777 @@
1
+ import { join } from "node:path";
2
+ import { isoNow, sleep } from "../clock.js";
3
+ import { runCheck } from "../goals/checks.js";
4
+ import { failedChecksEvidence } from "../goals/messages.js";
5
+ import { TERMINAL_GOAL_STATES } from "../goals/store.js";
6
+ import { errorMessage } from "../log.js";
7
+ import { recordEvent, transaction } from "../store/db.js";
8
+ import { defaultExec } from "./exec.js";
9
+ import { Git, gitProblem } from "./git.js";
10
+ import { chooseMergeMethod } from "./github.js";
11
+ import { ciFailedPrompt, commitFailedPrompt, commitMessage, conflictPrompt, failedAfterMergePrompt, heldMessage, inPlaceNote, landedLocally, landedOnGitHub, leftOutNote, mergeCommitMessage, nothingToLand, parseYesNo, publishQuestion, pullRequestBody, unlandedNote, } from "./messages.js";
12
+ import { samePath } from "./paths.js";
13
+ import { findRemote, inspectProject } from "./project.js";
14
+ import { detectPublishing, expectsPullRequestChecks, isInterestingPath, } from "./publishing.js";
15
+ import { stageWork } from "./stage.js";
16
+ import { LandingStore } from "./store.js";
17
+ import { Workspaces } from "./workspace.js";
18
+ /** Attempts at the whole sequence when git or GitHub fails; every step is safe to repeat. */
19
+ const MAX_ATTEMPTS = 3;
20
+ /** Times the work is combined with a main branch that kept moving. */
21
+ const MAX_PASSES = 3;
22
+ /** How often the working copies of ended Goals are looked at. */
23
+ const SWEEP_INTERVAL_MS = 60 * 60_000;
24
+ /**
25
+ * Lands a verified Goal's work: commits what the Worker left, combines it with the latest main
26
+ * branch and re-runs the Brief's checks on the result, then merges. With a GitHub remote that
27
+ * is a pull request merged after the required checks pass; otherwise a local merge that leaves
28
+ * the user's own checkout and uncommitted edits alone. Every step looks at what already exists
29
+ * before acting and is recorded, so a crash anywhere resumes without a second push, pull
30
+ * request or merge. It never force-pushes and never rewrites the user's history.
31
+ */
32
+ export class Landing {
33
+ deps;
34
+ store;
35
+ git;
36
+ workspaces;
37
+ aborts = new Map();
38
+ sweepTimer;
39
+ sweeping = Promise.resolve();
40
+ stopped = true;
41
+ constructor(deps) {
42
+ this.deps = deps;
43
+ this.store = new LandingStore(deps.db, deps.clock);
44
+ this.git = new Git(deps.exec ?? defaultExec);
45
+ this.workspaces = new Workspaces({
46
+ git: this.git,
47
+ store: this.store,
48
+ log: deps.log,
49
+ clock: deps.clock,
50
+ worktreesDir: deps.worktreesDir,
51
+ saveProject: (goal, info) => this.store.saveProjectInfo(goal.projectId, info),
52
+ });
53
+ }
54
+ /** Starts tidying the working copies of ended Goals: now, and then every hour. */
55
+ start() {
56
+ this.stopped = false;
57
+ this.scheduleSweep(0);
58
+ }
59
+ async stop() {
60
+ this.stopped = true;
61
+ this.sweepTimer?.cancel();
62
+ await this.sweeping;
63
+ }
64
+ scheduleSweep(delayMs) {
65
+ this.sweepTimer = this.deps.clock.setTimeout(() => {
66
+ if (this.stopped)
67
+ return;
68
+ this.sweeping = this.sweep()
69
+ .catch((err) => this.deps.log.error("tidying working copies failed", { error: err }))
70
+ .finally(() => {
71
+ if (!this.stopped)
72
+ this.scheduleSweep(SWEEP_INTERVAL_MS);
73
+ });
74
+ }, delayMs);
75
+ }
76
+ /**
77
+ * Removes the working copies of Goals that ended: at once when nothing would be lost, after
78
+ * `landing.worktreeRetentionMs` otherwise (keeping the branch). See `Workspaces.tidyEnded`.
79
+ */
80
+ async sweep() {
81
+ const retentionMs = this.deps.config.get().landing.worktreeRetentionMs;
82
+ for (const ws of this.store.activeWorktrees()) {
83
+ if (this.stopped)
84
+ return;
85
+ const goal = this.deps.goals.findGoal(ws.goalId);
86
+ if (!goal || !TERMINAL_GOAL_STATES.includes(goal.state) || this.aborts.has(goal.id))
87
+ continue;
88
+ try {
89
+ const result = await this.workspaces.tidyEnded(ws, { endedAt: goal.endedAt, retentionMs });
90
+ if (result !== "kept") {
91
+ this.deps.log.info("tidied a working copy", { goalId: goal.id, result });
92
+ }
93
+ }
94
+ catch (err) {
95
+ this.deps.log.warn("could not tidy a working copy", { goalId: goal.id, error: err });
96
+ }
97
+ }
98
+ }
99
+ // ---- Hooks for the Goal engine -----------------------------------------------------------
100
+ prepare(goal) {
101
+ return this.workspaces.prepare(goal);
102
+ }
103
+ usesWorktree(goalId) {
104
+ const ws = this.store.workspace(goalId);
105
+ return ws?.mode === "worktree" && ws.state === "active";
106
+ }
107
+ isLanding(goalId) {
108
+ const rec = this.store.landing(goalId);
109
+ return rec !== undefined && rec.state !== "awaiting_worker";
110
+ }
111
+ questionGoal(questionId) {
112
+ return this.store.landingByQuestion(questionId)?.goalId;
113
+ }
114
+ outcomeNote(goal) {
115
+ const ws = this.store.workspace(goal.id);
116
+ if (!ws)
117
+ return undefined;
118
+ if (ws.mode === "in_place")
119
+ return ws.reason ? inPlaceNote(ws.reason) : undefined;
120
+ if (ws.state === "active" && ws.branch)
121
+ return unlandedNote(ws.branch, ws.worktreePath);
122
+ return undefined;
123
+ }
124
+ async prepareReland(goal) {
125
+ const ws = this.store.workspace(goal.id);
126
+ const record = this.store.landing(goal.id);
127
+ if (ws?.mode !== "worktree" || !isTree(ws)) {
128
+ return "That work was done directly in the project folder, so there is nothing separate to merge.";
129
+ }
130
+ if (record?.result?.kind === "landed" || ws.state === "removed") {
131
+ return "That work is already merged.";
132
+ }
133
+ if (record?.result?.kind !== "held" && record?.result?.kind !== "blocked") {
134
+ return "Preston only merges work it has verified itself, and this was never verified. Start a follow-up Goal to finish it.";
135
+ }
136
+ if (!(await this.git.branchExists(ws.repoRoot, ws.branch))) {
137
+ return `The branch ${ws.branch} that held the finished work is gone, so there is nothing left to merge.`;
138
+ }
139
+ const prepared = await this.workspaces.prepare(goal);
140
+ return prepared.ok ? undefined : prepared.reason;
141
+ }
142
+ resetForReland(goalId, options) {
143
+ const record = this.store.ensureLanding(goalId);
144
+ this.store.updateLanding(goalId, {
145
+ state: "active",
146
+ result: null,
147
+ fixAttempts: 0,
148
+ ciStartedAt: null,
149
+ questionId: null,
150
+ publishing: null,
151
+ decision: options.allowPublishing ? "yes" : null,
152
+ ...(record.prNumber ? {} : { mode: null }),
153
+ });
154
+ }
155
+ abort(goalId) {
156
+ if (goalId)
157
+ this.aborts.get(goalId)?.abort();
158
+ else
159
+ for (const controller of this.aborts.values())
160
+ controller.abort();
161
+ }
162
+ async land(goal, run) {
163
+ const ws = this.store.workspace(goal.id);
164
+ if (ws?.mode !== "worktree" || !isTree(ws)) {
165
+ return { kind: "landed", message: "" };
166
+ }
167
+ // Everything up to the first await is synchronous: the engine calls this inside the
168
+ // transaction that records the verification, so a restart never sees one without the other.
169
+ const record = this.store.ensureLanding(goal.id);
170
+ if (record.result)
171
+ return record.result;
172
+ const controller = new AbortController();
173
+ this.aborts.set(goal.id, controller);
174
+ this.store.updateLanding(goal.id, { state: "active" });
175
+ recordEvent(this.deps.db, this.deps.clock, "landing_started", {
176
+ goalId: goal.id,
177
+ runId: run.id,
178
+ });
179
+ const ctx = {
180
+ goal,
181
+ run,
182
+ ws,
183
+ signal: controller.signal,
184
+ cfg: this.deps.config.get().landing,
185
+ };
186
+ try {
187
+ for (let attempt = 1;; attempt++) {
188
+ try {
189
+ return this.settle(goal.id, this.withLeftOut(ctx, await this.execute(ctx)));
190
+ }
191
+ catch (err) {
192
+ if (controller.signal.aborted)
193
+ return { kind: "aborted" };
194
+ this.deps.log.warn("landing step failed", { goalId: goal.id, attempt, error: err });
195
+ if (attempt >= MAX_ATTEMPTS) {
196
+ return this.settle(goal.id, {
197
+ kind: "blocked",
198
+ reason: this.stuck(ctx, errorMessage(err)),
199
+ });
200
+ }
201
+ await sleep(this.deps.clock, ctx.cfg.ciPollIntervalMs, controller.signal);
202
+ }
203
+ }
204
+ }
205
+ catch {
206
+ return { kind: "aborted" };
207
+ }
208
+ finally {
209
+ this.aborts.delete(goal.id);
210
+ }
211
+ }
212
+ /** Records where a landing stands, so a restart resumes rather than repeats. */
213
+ settle(goalId, result) {
214
+ switch (result.kind) {
215
+ case "landed":
216
+ case "held":
217
+ case "blocked":
218
+ this.store.updateLanding(goalId, { state: "done", result });
219
+ break;
220
+ case "needs_worker":
221
+ this.store.updateLanding(goalId, { state: "awaiting_worker" });
222
+ break;
223
+ case "waiting_for_user":
224
+ this.store.updateLanding(goalId, { state: "awaiting_user" });
225
+ break;
226
+ case "aborted":
227
+ break;
228
+ }
229
+ return result;
230
+ }
231
+ // ---- The landing sequence ----------------------------------------------------------------
232
+ async execute(ctx) {
233
+ const problem = await this.commitPending(ctx);
234
+ if (problem) {
235
+ return this.needsWorker(ctx, commitFailedPrompt(problem), `Git would not save the changes (${problem})`);
236
+ }
237
+ const mode = await this.decideMode(ctx);
238
+ return mode === "pr" ? this.landViaPullRequest(ctx) : this.landLocally(ctx);
239
+ }
240
+ /** Saves whatever the Worker left uncommitted on the Goal's branch. */
241
+ async commitPending(ctx) {
242
+ const { git } = this;
243
+ const path = ctx.ws.worktreePath;
244
+ if (!(await git.dirty(path)))
245
+ return undefined;
246
+ const staged = await stageWork(git, path);
247
+ if (staged.problem)
248
+ return staged.problem;
249
+ this.store.updateLanding(ctx.goal.id, { leftOut: staged.leftOut });
250
+ // Exit 0 means nothing is staged (only ignored files changed).
251
+ if (await git.ok(path, ["diff", "--cached", "--quiet"]))
252
+ return undefined;
253
+ const identity = await git.identityArgs(path);
254
+ const committed = await git.run(path, [
255
+ ...identity,
256
+ "commit",
257
+ "-m",
258
+ commitMessage(ctx.goal.brief),
259
+ ]);
260
+ return committed.code === 0 ? undefined : gitProblem(committed);
261
+ }
262
+ /** Tells the user what was not committed, in the outcome of work that was merged or held. */
263
+ withLeftOut(ctx, result) {
264
+ if (result.kind !== "landed" && result.kind !== "held")
265
+ return result;
266
+ const leftOut = this.require(ctx).leftOut;
267
+ if (!leftOut.length)
268
+ return result;
269
+ const note = leftOutNote(leftOut, this.keepsFolder(ctx) ? ctx.ws.worktreePath : null);
270
+ return { ...result, message: [result.message, note].filter(Boolean).join("\n") };
271
+ }
272
+ /** A large file was left out of the merge: its folder is kept, so the file is not lost. */
273
+ keepsFolder(ctx) {
274
+ return this.require(ctx).leftOut.some((l) => l.why === "large_binary");
275
+ }
276
+ /** Removes the Goal's worktree and branch once everything in them is merged. */
277
+ async tidy(ctx) {
278
+ if (!this.keepsFolder(ctx))
279
+ await this.workspaces.cleanup(ctx.ws, { deleteBranch: true });
280
+ }
281
+ /** Pull request when the repository has a usable GitHub remote, otherwise a local merge. */
282
+ async decideMode(ctx) {
283
+ const record = this.store.landing(ctx.goal.id);
284
+ if (record?.mode)
285
+ return record.mode;
286
+ const { git } = this;
287
+ const root = ctx.ws.repoRoot;
288
+ const decide = (mode, note) => {
289
+ this.store.updateLanding(ctx.goal.id, { mode, modeNote: note });
290
+ return mode;
291
+ };
292
+ const remote = await findRemote(git, root);
293
+ if (!remote)
294
+ return decide("local", null);
295
+ const host = await this.deps.github.repo(ctx.ws.worktreePath);
296
+ if (!host.ok)
297
+ return decide("local", `I didn't push it anywhere: ${host.reason}`);
298
+ const base = ctx.ws.baseBranch;
299
+ const fetched = await git.run(root, ["fetch", remote.name, base], { timeoutMs: 300_000 });
300
+ if (fetched.code !== 0) {
301
+ return decide("local", "I couldn't reach GitHub, so I didn't push anything.");
302
+ }
303
+ const remoteTip = await git.rev(root, `refs/remotes/${remote.name}/${base}`);
304
+ if (!remoteTip) {
305
+ return decide("local", `GitHub doesn't have a ${base} branch, so I didn't push anything.`);
306
+ }
307
+ if (!(await git.isAncestor(root, ctx.ws.baseSha, remoteTip))) {
308
+ return decide("local", `Your ${base} has changes that aren't on GitHub yet, so I didn't push anything.`);
309
+ }
310
+ return decide("pr", null);
311
+ }
312
+ // ---- Local merge -------------------------------------------------------------------------
313
+ async landLocally(ctx) {
314
+ const { git } = this;
315
+ const { repoRoot: root, baseBranch: base } = ctx.ws;
316
+ const baseRef = `refs/heads/${base}`;
317
+ const record = this.require(ctx);
318
+ if (record.candidateSha && (await git.isAncestor(root, record.candidateSha, baseRef))) {
319
+ return this.landedLocal(ctx, "untouched", record.modeNote);
320
+ }
321
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
322
+ const integrated = await this.integrate(ctx, baseRef, base);
323
+ if ("result" in integrated)
324
+ return integrated.result;
325
+ const gate = await this.gate(ctx, base, integrated, null);
326
+ if (gate)
327
+ return gate;
328
+ const advanced = await this.advanceLocal(ctx, integrated);
329
+ if (advanced)
330
+ return advanced;
331
+ }
332
+ return { kind: "blocked", reason: this.stuck(ctx, `${base} kept changing while I merged`) };
333
+ }
334
+ /**
335
+ * Moves the main branch to a merge commit of the verified work. It never resets or checks out
336
+ * anything in the user's folder: a checkout of the branch is fast-forwarded (git refuses if
337
+ * that would overwrite the user's edits), and a branch nobody has checked out is only moved.
338
+ * Returns undefined when the branch moved meanwhile and the work has to be combined again.
339
+ */
340
+ async advanceLocal(ctx, integrated) {
341
+ const { git } = this;
342
+ const { repoRoot: root, baseBranch: base, worktreePath: path } = ctx.ws;
343
+ const tree = await git.out(path, ["rev-parse", `${integrated.head}^{tree}`]);
344
+ if (!tree)
345
+ throw new Error("Could not read the finished work from Git.");
346
+ const squash = ctx.cfg.mergeMethod === "squash";
347
+ const identity = await git.identityArgs(path);
348
+ const message = squash
349
+ ? commitMessage(ctx.goal.brief)
350
+ : mergeCommitMessage(ctx.goal.brief, ctx.ws.branch);
351
+ const created = await git.run(path, [
352
+ ...identity,
353
+ "commit-tree",
354
+ tree,
355
+ "-p",
356
+ integrated.baseTip,
357
+ ...(squash ? [] : ["-p", integrated.head]),
358
+ "-m",
359
+ message,
360
+ ]);
361
+ const candidate = created.stdout.trim();
362
+ if (created.code !== 0 || !candidate)
363
+ throw new Error(gitProblem(created));
364
+ // Recorded before the branch moves: after a crash it shows whether it did.
365
+ this.store.updateLanding(ctx.goal.id, { candidateSha: candidate });
366
+ this.store.recordOp(ctx.goal.id, `advance:${integrated.baseTip}:${candidate}`);
367
+ const checkout = (await git.worktrees(root)).find((w) => w.branch === base && !samePath(w.path, path));
368
+ if (checkout) {
369
+ const dirty = await git.dirty(checkout.path);
370
+ const result = await git.run(checkout.path, ["merge", "--ff-only", candidate]);
371
+ if (result.code !== 0) {
372
+ if (/overwritten|local changes|untracked working tree/i.test(result.stderr)) {
373
+ return {
374
+ kind: "blocked",
375
+ reason: `Your own unsaved edits in ${checkout.path} are in the way of merging into ${base}, so I left everything as it was. The finished work is saved on branch ${ctx.ws.branch}. Once your edits are saved or set aside, ask me for a follow-up Goal to merge it.`,
376
+ };
377
+ }
378
+ if (/fast-forward/i.test(result.stderr))
379
+ return undefined;
380
+ throw new Error(gitProblem(result));
381
+ }
382
+ return this.landedLocal(ctx, dirty ? "updated_dirty" : "updated", this.require(ctx).modeNote);
383
+ }
384
+ const moved = await git.run(root, [
385
+ "update-ref",
386
+ "-m",
387
+ `preston: merge ${ctx.ws.branch}`,
388
+ `refs/heads/${base}`,
389
+ candidate,
390
+ integrated.baseTip,
391
+ ]);
392
+ if (moved.code !== 0)
393
+ return undefined;
394
+ return this.landedLocal(ctx, "untouched", this.require(ctx).modeNote);
395
+ }
396
+ async landedLocal(ctx, checkout, note) {
397
+ const currentBranch = await this.git.currentBranch(ctx.ws.repoRoot);
398
+ await this.tidy(ctx);
399
+ return {
400
+ kind: "landed",
401
+ message: landedLocally({ base: ctx.ws.baseBranch, checkout, currentBranch, note }),
402
+ };
403
+ }
404
+ // ---- Pull request ------------------------------------------------------------------------
405
+ async landViaPullRequest(ctx) {
406
+ const { git, deps } = { git: this.git, deps: this.deps };
407
+ const { repoRoot: root, worktreePath: path, branch, baseBranch: base } = ctx.ws;
408
+ const remote = await findRemote(git, root);
409
+ if (!remote)
410
+ throw new Error("The project's GitHub remote is not there any more.");
411
+ const host = await deps.github.repo(path);
412
+ if (!host.ok)
413
+ throw new Error(host.reason);
414
+ const remoteRef = `refs/remotes/${remote.name}/${base}`;
415
+ const record = this.require(ctx);
416
+ let pr = record.prNumber
417
+ ? await deps.github.getPr(path, record.prNumber)
418
+ : await deps.github.findPr(path, branch);
419
+ if (pr?.state === "merged")
420
+ return this.afterPullRequest(ctx, remote.name, pr);
421
+ if (pr?.state === "closed") {
422
+ return {
423
+ kind: "blocked",
424
+ reason: `The pull request was closed on GitHub without being merged (${pr.url}), so I stopped. The finished work is saved on branch ${branch}.`,
425
+ };
426
+ }
427
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
428
+ await this.fetch(ctx, remote.name, base);
429
+ const integrated = await this.integrate(ctx, remoteRef, base);
430
+ if ("result" in integrated)
431
+ return integrated.result;
432
+ await this.push(ctx, remote.name, integrated.head);
433
+ pr ??= await this.openPullRequest(ctx, base);
434
+ const gate = await this.gate(ctx, base, integrated, pr.url);
435
+ if (gate)
436
+ return gate;
437
+ const waited = await this.waitForChecks(ctx, pr, integrated.head);
438
+ if (waited)
439
+ return waited;
440
+ // The main branch moved while the checks ran: combine and check again.
441
+ await this.fetch(ctx, remote.name, base);
442
+ if ((await git.rev(root, remoteRef)) !== integrated.baseTip)
443
+ continue;
444
+ const method = chooseMergeMethod(ctx.cfg.mergeMethod, host.host.allowed);
445
+ try {
446
+ await deps.github.mergePr(path, pr.number, method);
447
+ }
448
+ catch (err) {
449
+ const now = await deps.github.getPr(path, pr.number).catch(() => undefined);
450
+ if (now?.state !== "merged") {
451
+ return {
452
+ kind: "blocked",
453
+ reason: `GitHub wouldn't let me merge the pull request (${errorMessage(err)}). It may need someone's approval or a setting changed. It is open at ${pr.url}, and the finished work is saved on branch ${branch}.`,
454
+ };
455
+ }
456
+ }
457
+ this.store.recordOp(ctx.goal.id, `merge:${pr.number}`);
458
+ return this.afterPullRequest(ctx, remote.name, { ...pr, state: "merged" });
459
+ }
460
+ return { kind: "blocked", reason: this.stuck(ctx, `${base} kept changing while I merged`) };
461
+ }
462
+ async fetch(ctx, remote, base) {
463
+ const result = await this.git.run(ctx.ws.repoRoot, ["fetch", remote, base], {
464
+ timeoutMs: 300_000,
465
+ });
466
+ if (result.code !== 0)
467
+ throw new Error(`Could not reach GitHub: ${gitProblem(result)}`);
468
+ }
469
+ /** Sends the branch. A fast-forward only, and only when the remote does not have it yet. */
470
+ async push(ctx, remote, head) {
471
+ const { git } = this;
472
+ const path = ctx.ws.worktreePath;
473
+ const listed = await git.out(path, ["ls-remote", remote, `refs/heads/${ctx.ws.branch}`]);
474
+ if (listed?.split(/\s+/)[0] === head)
475
+ return;
476
+ const pushed = await git.run(path, ["push", remote, `${ctx.ws.branch}:refs/heads/${ctx.ws.branch}`], { timeoutMs: 600_000 });
477
+ if (pushed.code !== 0)
478
+ throw new Error(`Could not send the branch to GitHub: ${gitProblem(pushed)}`);
479
+ this.store.recordOp(ctx.goal.id, `push:${head}`);
480
+ this.store.updateLanding(ctx.goal.id, { ciStartedAt: null });
481
+ }
482
+ /** The pull request for the branch: an existing one first, a new one only if there is none. */
483
+ async openPullRequest(ctx, base) {
484
+ const { github, goals } = this.deps;
485
+ const path = ctx.ws.worktreePath;
486
+ const existing = await github.findPr(path, ctx.ws.branch);
487
+ let pr = existing?.state === "open" ? existing : undefined;
488
+ if (!pr) {
489
+ const verification = goals
490
+ .verifications(ctx.goal.id)
491
+ .filter((v) => v.passed)
492
+ .at(-1);
493
+ const input = {
494
+ head: ctx.ws.branch,
495
+ base,
496
+ title: ctx.goal.brief.objective.trim().replace(/\s+/g, " ").slice(0, 120),
497
+ body: pullRequestBody(ctx.goal, ctx.run.report, verification?.results ?? []),
498
+ };
499
+ try {
500
+ pr = await github.createPr(path, input);
501
+ }
502
+ catch (err) {
503
+ // It may have been created although the call failed (a dropped connection).
504
+ pr = (await github.findPr(path, ctx.ws.branch)) ?? undefined;
505
+ if (!pr)
506
+ throw err;
507
+ }
508
+ this.store.recordOp(ctx.goal.id, "pr_create", pr.url);
509
+ }
510
+ this.store.updateLanding(ctx.goal.id, { prNumber: pr.number, prUrl: pr.url });
511
+ return pr;
512
+ }
513
+ /** Waits, by polling and without any model, for the repository's required checks. */
514
+ async waitForChecks(ctx, pr, head) {
515
+ const { clock, github } = this.deps;
516
+ const expected = expectsPullRequestChecks(await this.snapshot(ctx, head));
517
+ const record = this.require(ctx);
518
+ const started = record.ciStartedAt ?? isoNow(clock);
519
+ if (!record.ciStartedAt)
520
+ this.store.updateLanding(ctx.goal.id, { ciStartedAt: started });
521
+ for (;;) {
522
+ const checks = await github.checks(ctx.ws.worktreePath, pr.number);
523
+ if (checks.state === "failing") {
524
+ return this.needsWorker(ctx, ciFailedPrompt(checks.failing), `GitHub's required checks failed (${checks.failing.join(", ")}). The pull request is ${pr.url}`);
525
+ }
526
+ if (checks.state === "passing")
527
+ return undefined;
528
+ const waited = clock.now() - Date.parse(started);
529
+ if (checks.state === "none" && (!expected || waited >= ctx.cfg.ciStartGraceMs)) {
530
+ return undefined;
531
+ }
532
+ if (waited >= ctx.cfg.requireCiWaitMs) {
533
+ return {
534
+ kind: "blocked",
535
+ reason: `GitHub's checks were still running after ${Math.round(ctx.cfg.requireCiWaitMs / 60_000)} minutes, so I haven't merged. The pull request is open at ${pr.url}, and the finished work is saved on branch ${ctx.ws.branch}.`,
536
+ };
537
+ }
538
+ await sleep(clock, ctx.cfg.ciPollIntervalMs, ctx.signal);
539
+ }
540
+ }
541
+ async afterPullRequest(ctx, remote, pr) {
542
+ const { git } = this;
543
+ const { repoRoot: root, baseBranch: base, branch } = ctx.ws;
544
+ const fetched = await git.run(root, ["fetch", remote, base], { timeoutMs: 300_000 });
545
+ let local = "behind";
546
+ if (fetched.code === 0)
547
+ local = await this.catchUp(root, remote, base);
548
+ // Best effort: the remote copy of the branch is done with.
549
+ await git.run(root, ["push", remote, "--delete", branch], { timeoutMs: 120_000 });
550
+ await this.tidy(ctx);
551
+ return { kind: "landed", message: landedOnGitHub({ url: pr.url, base, local }) };
552
+ }
553
+ /** Brings the user's own copy of the main branch up to date, only when that is a fast-forward. */
554
+ async catchUp(root, remote, base) {
555
+ const { git } = this;
556
+ const remoteTip = await git.rev(root, `refs/remotes/${remote}/${base}`);
557
+ const localTip = await git.rev(root, `refs/heads/${base}`);
558
+ if (!remoteTip || !localTip)
559
+ return "behind";
560
+ if (remoteTip === localTip)
561
+ return "updated";
562
+ if (!(await git.isAncestor(root, localTip, remoteTip)))
563
+ return "behind";
564
+ const checkout = (await git.worktrees(root)).find((w) => w.branch === base);
565
+ if (checkout) {
566
+ return (await git.ok(checkout.path, ["merge", "--ff-only", remoteTip]))
567
+ ? "updated"
568
+ : "behind";
569
+ }
570
+ const moved = await git.ok(root, [
571
+ "update-ref",
572
+ "-m",
573
+ "preston: catch up",
574
+ `refs/heads/${base}`,
575
+ remoteTip,
576
+ localTip,
577
+ ]);
578
+ return moved ? "updated" : "behind";
579
+ }
580
+ // ---- Shared steps ------------------------------------------------------------------------
581
+ /**
582
+ * Brings the latest main branch into the Goal's branch (inside its own worktree) and, if that
583
+ * changed anything, re-runs the Brief's checks on the result. A conflict goes back to the
584
+ * Worker with the details.
585
+ */
586
+ async integrate(ctx, baseRef, base) {
587
+ const { git } = this;
588
+ const { repoRoot: root, worktreePath: path } = ctx.ws;
589
+ const baseTip = await git.rev(root, baseRef);
590
+ if (!baseTip) {
591
+ return {
592
+ result: {
593
+ kind: "blocked",
594
+ reason: `The ${base} branch is no longer in your project, so I can't merge into it. The finished work is saved on branch ${ctx.ws.branch}.`,
595
+ },
596
+ };
597
+ }
598
+ if (!(await git.isAncestor(path, baseTip, "HEAD"))) {
599
+ const identity = await git.identityArgs(path);
600
+ const merged = await git.run(path, [
601
+ ...identity,
602
+ "merge",
603
+ "--no-edit",
604
+ "-m",
605
+ `Bring in the latest ${base}`,
606
+ baseTip,
607
+ ]);
608
+ if (merged.code !== 0) {
609
+ const unmerged = await git.out(path, ["diff", "--name-only", "--diff-filter=U"]);
610
+ const files = unmerged?.split(/\r?\n/).filter(Boolean) ?? [];
611
+ await git.run(path, ["merge", "--abort"]);
612
+ if (files.length === 0)
613
+ throw new Error(gitProblem(merged));
614
+ return {
615
+ result: this.needsWorker(ctx, conflictPrompt(base, baseTip, files), `the work conflicts with newer changes to ${base} in ${files.join(", ")}`),
616
+ };
617
+ }
618
+ const joined = await git.rev(path, "HEAD");
619
+ if (joined)
620
+ this.store.recordOp(ctx.goal.id, `integrated:${joined}`);
621
+ }
622
+ const head = (await git.rev(path, "HEAD")) ?? "";
623
+ if ((await git.out(root, ["rev-list", "--count", `${baseTip}..${head}`])) === "0") {
624
+ await this.tidy(ctx);
625
+ return { result: { kind: "landed", message: nothingToLand(base) } };
626
+ }
627
+ if (this.store.hasOp(ctx.goal.id, `integrated:${head}`) &&
628
+ !this.store.hasOp(ctx.goal.id, `verified:${head}`)) {
629
+ const evidence = await this.verifyMerged(ctx);
630
+ if (evidence) {
631
+ return {
632
+ result: this.needsWorker(ctx, failedAfterMergePrompt(base, evidence), `my checks fail once the work is combined with the latest ${base}`),
633
+ };
634
+ }
635
+ this.store.recordOp(ctx.goal.id, `verified:${head}`);
636
+ }
637
+ return { baseTip, head };
638
+ }
639
+ /** The Brief's checks, run by Preston on the combined result. Undefined when they pass. */
640
+ async verifyMerged(ctx) {
641
+ const { clock, goals } = this.deps;
642
+ const startedAt = isoNow(clock);
643
+ const results = [];
644
+ for (const [index, check] of ctx.goal.brief.checks.entries()) {
645
+ results.push(await runCheck({ ...check, source: "brief" }, {
646
+ cwd: ctx.ws.workdir,
647
+ timeoutMs: this.deps.config.get().verification.checkTimeoutMs,
648
+ clock,
649
+ outputPath: join(ctx.run.transcriptDir, `landing-check-${Date.parse(startedAt)}-${index + 1}.log`),
650
+ signal: ctx.signal,
651
+ }));
652
+ }
653
+ if (ctx.signal.aborted)
654
+ throw new Error("stopped");
655
+ const passed = results.every((r) => r.passed);
656
+ goals.addVerification({
657
+ goalId: ctx.goal.id,
658
+ runId: ctx.run.id,
659
+ passed,
660
+ results,
661
+ startedAt,
662
+ endedAt: isoNow(clock),
663
+ });
664
+ return passed ? undefined : failedChecksEvidence(results);
665
+ }
666
+ /** Asks before a merge that would also publish something, unless the user has allowed it. */
667
+ async gate(ctx, base, integrated, prUrl) {
668
+ if (ctx.cfg.autoMergePublishing || this.deps.policy(ctx.goal).autoMergePublishing) {
669
+ return undefined;
670
+ }
671
+ const { questions } = this.deps;
672
+ const held = () => ({
673
+ kind: "held",
674
+ message: heldMessage({
675
+ branch: ctx.ws.branch,
676
+ prUrl: prUrl ?? this.require(ctx).prUrl,
677
+ worktreePath: ctx.ws.worktreePath,
678
+ }),
679
+ });
680
+ const record = this.require(ctx);
681
+ if (record.decision === "yes")
682
+ return undefined;
683
+ if (record.decision === "no")
684
+ return held();
685
+ if (record.questionId) {
686
+ const question = questions.find(record.questionId);
687
+ if (question?.state === "answered") {
688
+ const decision = parseYesNo(question.answer ?? "");
689
+ this.store.updateLanding(ctx.goal.id, { decision });
690
+ return decision === "yes" ? undefined : held();
691
+ }
692
+ if (question?.state === "pending_human" || question?.state === "pending_coordinator") {
693
+ return { kind: "waiting_for_user" };
694
+ }
695
+ throw new Error("The question about publishing is no longer open.");
696
+ }
697
+ const verdict = await this.publishing(ctx, integrated);
698
+ this.store.updateLanding(ctx.goal.id, { publishing: verdict });
699
+ if (verdict.verdict === "none")
700
+ return undefined;
701
+ const text = publishQuestion(ctx.goal, verdict, base, ctx.ws.branch, prUrl);
702
+ // Asked and recorded together: after a crash the question is never asked twice.
703
+ transaction(this.deps.db, () => {
704
+ const question = questions.askHuman(text, ctx.goal.id);
705
+ this.store.updateLanding(ctx.goal.id, { questionId: question.id });
706
+ });
707
+ return { kind: "waiting_for_user" };
708
+ }
709
+ async publishing(ctx, integrated) {
710
+ const reasons = new Set();
711
+ let verdict = "none";
712
+ for (const ref of [integrated.head, integrated.baseTip]) {
713
+ const found = detectPublishing(await this.snapshot(ctx, ref), ctx.ws.baseBranch);
714
+ for (const reason of found.reasons)
715
+ reasons.add(reason);
716
+ if (found.verdict === "publishes")
717
+ verdict = "publishes";
718
+ else if (found.verdict === "unsure" && verdict === "none")
719
+ verdict = "unsure";
720
+ }
721
+ return verdict === "none"
722
+ ? { verdict: "none", reasons: [] }
723
+ : { verdict, reasons: [...reasons] };
724
+ }
725
+ /** The repository's files at a commit, read from Git without checking anything out. */
726
+ async snapshot(ctx, ref) {
727
+ const { git } = this;
728
+ const path = ctx.ws.worktreePath;
729
+ const listed = (await git.out(path, ["ls-tree", "-r", "--name-only", "-z", ref])) ?? "";
730
+ const paths = listed.split("\0").filter(Boolean);
731
+ const files = new Map();
732
+ for (const file of paths.filter(isInterestingPath)) {
733
+ const text = await git.out(path, ["show", `${ref}:${file}`]);
734
+ if (text !== undefined)
735
+ files.set(file, text.slice(0, 200_000));
736
+ }
737
+ const refs = await git.out(path, [
738
+ "for-each-ref",
739
+ "--format=%(refname:short)",
740
+ "refs/heads",
741
+ "refs/remotes",
742
+ ]);
743
+ return { paths, files, branches: refs?.split(/\r?\n/).filter(Boolean) ?? [] };
744
+ }
745
+ /** Sends a fixable problem to the Worker once (configurable), otherwise reports Blocked. */
746
+ needsWorker(ctx, prompt, because) {
747
+ const record = this.require(ctx);
748
+ if (record.fixAttempts >= ctx.cfg.conflictFixAttempts) {
749
+ return { kind: "blocked", reason: this.stuck(ctx, because) };
750
+ }
751
+ this.store.updateLanding(ctx.goal.id, { fixAttempts: record.fixAttempts + 1 });
752
+ return { kind: "needs_worker", prompt };
753
+ }
754
+ stuck(ctx, because) {
755
+ const prUrl = this.store.landing(ctx.goal.id)?.prUrl;
756
+ const where = prUrl ? ` The pull request is at ${prUrl}.` : "";
757
+ return `I couldn't finish merging this on my own: ${because}. Nothing of yours was changed.${where} The finished work is saved on branch ${ctx.ws.branch}, with its files in ${ctx.ws.worktreePath}.`;
758
+ }
759
+ require(ctx) {
760
+ return this.store.ensureLanding(ctx.goal.id);
761
+ }
762
+ // ---- Projects ----------------------------------------------------------------------------
763
+ /** Every Project Preston knows, looked at again right now. */
764
+ async projects() {
765
+ const out = [];
766
+ for (const project of this.store.projects()) {
767
+ const info = await inspectProject(this.git, project.path, isoNow(this.deps.clock));
768
+ this.store.saveProjectInfo(project.id, info);
769
+ out.push({ ...project, info });
770
+ }
771
+ return out;
772
+ }
773
+ }
774
+ function isTree(ws) {
775
+ return Boolean(ws.repoRoot && ws.worktreePath && ws.branch && ws.baseBranch && ws.baseSha);
776
+ }
777
+ //# sourceMappingURL=landing.js.map