dsh-pilot-board 0.1.0 → 0.2.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.
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pilot-board",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "One board for a project's ROADMAP.md milestones and tasks: agents in any git worktree claim, note, and submit tasks; a human approves or sends feedback.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -131,7 +131,8 @@ export async function runMergePipeline({
131
131
  if (taskTip === null) {
132
132
  const prior = !verificationPending && await mergedEarlier(root, base)
133
133
  if (prior && await baseMatches(baseTip)) {
134
- return { outcome: 'already-merged', base, commit: prior.commit, notes: ['Already merged earlier; nothing else to clean up.'] }
134
+ return { outcome: 'already-merged', base, commit: prior.commit, notes: ['Already merged earlier; nothing else to clean up.'],
135
+ cleanup: { worktree: { state: 'absent', path: worktree || null }, branch: { state: 'removed', name: branch } } }
135
136
  }
136
137
  return record('blocked', missingBranchMessage ?? `Branch ${branch} does not exist. Nothing was changed.`)
137
138
  }
@@ -197,8 +198,17 @@ export async function runMergePipeline({
197
198
 
198
199
  const summary = already ? `${branch} was already in ${base}.` : `Merged ${branch} into ${base} as ${String(commit).slice(0, 7)}.`
199
200
  if (!(await onVerifiedMerge({ commit, summary, notes: [...notes], already }))) return { outcome: 'halted' }
200
- const result = { outcome: already ? 'already-merged' : 'merged', base, commit, notes, text: summary, verificationPending: false }
201
- if (checkoutRepairRequired) return result
201
+ // Per-item cleanup state for callers that must show what was left behind.
202
+ const NOT_RUN = 'Cleanup did not run.'
203
+ const cleanup = {
204
+ worktree: tree === null ? { state: 'absent', path: worktree || null } : { state: 'kept', path: worktree, message: NOT_RUN },
205
+ branch: { state: 'kept', name: branch, message: NOT_RUN },
206
+ }
207
+ const result = { outcome: already ? 'already-merged' : 'merged', base, commit, notes, text: summary, verificationPending: false, cleanup }
208
+ if (checkoutRepairRequired) {
209
+ for (const item of Object.values(cleanup)) if (item.message === NOT_RUN) item.message = 'Skipped: the base checkout needs repair.'
210
+ return result
211
+ }
202
212
  try {
203
213
  step('cleanup')
204
214
  if (!(await baseMatches(commit)) || !(await taskMatches()) || !(await git.commitInBranch(root, taskTip, base, gitOptions))) {
@@ -207,11 +217,15 @@ export async function runMergePipeline({
207
217
  if (tree !== null) {
208
218
  const removed = await git.removeWorktree(root, tree, gitOptions)
209
219
  notes.push(removed.ok ? `Removed worktree ${worktree}.` : `Kept worktree ${worktree}: ${removed.message}`)
220
+ cleanup.worktree = removed.ok ? { state: 'removed', path: worktree } : { state: 'kept', path: worktree, message: removed.message }
210
221
  }
211
222
  const deleted = await git.deleteBranch(root, branch, { ...gitOptions, commonDir: project.commonDir, baseBranch: base, baseTip: commit, taskTip })
212
223
  notes.push(deleted.ok ? `Deleted branch ${branch}.` : `Kept branch ${branch}: ${deleted.message}`)
224
+ cleanup.branch = deleted.ok ? { state: 'removed', name: branch } : { state: 'kept', name: branch, message: deleted.message }
213
225
  } catch (error) {
214
- notes.push(`Cleanup stopped: ${String(error?.message ?? error)}`)
226
+ const message = `Cleanup stopped: ${String(error?.message ?? error)}`
227
+ notes.push(message)
228
+ for (const item of Object.values(cleanup)) if (item.message === NOT_RUN) item.message = message
215
229
  }
216
230
  return { ...result, detail: notes.join('\n') }
217
231
  }
@@ -112,6 +112,20 @@ export function createSessionsPort(ctx, { tracker, deliver, cwdOf }) {
112
112
  async cancel(sessionId) {
113
113
  await controller().cancel({ sessionId })
114
114
  },
115
+ /**
116
+ * Archive a session the board created (pilot teardown). Never stops running
117
+ * work: a busy session is refused by the registry and reported, not thrown.
118
+ */
119
+ async archive(sessionId) {
120
+ const registry = ctx.get?.('workspaceRegistry')
121
+ if (typeof registry?.archiveSession !== 'function') return { ok: false, message: 'The workspace registry cannot archive sessions on this Host.' }
122
+ try {
123
+ await registry.archiveSession(sessionId)
124
+ return { ok: true, message: '' }
125
+ } catch (error) {
126
+ return { ok: false, message: String(error?.message ?? error) }
127
+ }
128
+ },
115
129
  }
116
130
  }
117
131
 
@@ -45,7 +45,8 @@ export const AGENTS_DOMAIN_SPEC = Object.freeze({ name: 'dsh_roadmap_board_agent
45
45
 
46
46
  /** Stored roadmap documents (M12.2): opened on the first db-mode read, roadmap-store call, or cutover. */
47
47
  export const ROADMAPS_DOMAIN_SPEC = Object.freeze({ name: 'dsh_roadmap_board_roadmaps_v1', version: 1 })
48
- export const PILOTS_DOMAIN_SPEC = Object.freeze({ name: 'roadmap-board-pilots', version: 1 })
48
+ /** Milestone pilot rows (M14.2). Storage-domain names allow `[a-z0-9_]` only, like the other domains. */
49
+ export const PILOTS_DOMAIN_SPEC = Object.freeze({ name: 'dsh_roadmap_board_pilots_v1', version: 1 })
49
50
 
50
51
  /** QA evidence content domain identity (M5.1): large, so opened only when evidence is written or read. */
51
52
  export const QA_BLOB_DOMAIN_SPEC = Object.freeze({ name: 'dsh_roadmap_board_qa_blobs_v1', version: 1 })
@@ -25,13 +25,21 @@ export function createSpawner(ctx) {
25
25
  async start({ parent, cwd, label, route, prompt, signal }) {
26
26
  const runtime = subagents()
27
27
  const maxDepth = runtime.resolveMaxDepth?.()
28
+ // DSH spreads these options after the inherited parent route, so a key
29
+ // present with an undefined value would erase the parent's provider or
30
+ // model and fail the child with MODEL_UNAVAILABLE.
31
+ const routeOptions = {
32
+ ...(nonBlank(route?.provider) ? { provider: route.provider } : {}),
33
+ ...(nonBlank(route?.model) ? { model: route.model } : {}),
34
+ ...(nonBlank(route?.reasoningEffort) ? { reasoningEffort: route.reasoningEffort } : {}),
35
+ }
28
36
  const started = await runtime.startActivation({
29
37
  provider: 'spawn',
30
38
  label,
31
39
  parent,
32
40
  cwd,
33
41
  prompt: [{ type: 'text', text: prompt }],
34
- agentOptions: { provider: route.provider, model: route.model, ...(nonBlank(route.reasoningEffort) ? { reasoningEffort: route.reasoningEffort } : {}) },
42
+ agentOptions: routeOptions,
35
43
  ...(maxDepth === undefined ? {} : { maxDepth }),
36
44
  signal,
37
45
  delivery: 'parent',
@@ -0,0 +1,97 @@
1
+ import * as gitModule from '../../core/git.mjs'
2
+ import { applyCleanup, applyCleanupDismiss, cleanupKept, expectCleanupNeeded, expectPhase } from './model.mjs'
3
+
4
+ const messageOf = error => String(error?.message ?? error)
5
+
6
+ /**
7
+ * Teardown of a merged pilot (docs/superpowers/specs/2026-12-04-pilot-running-card-design.md §4):
8
+ * record what the merge pipeline and the session archive left, then retry or
9
+ * dismiss only those items. Nothing here forces: Git refuses dirty trees and
10
+ * unmerged branches, and the registry refuses a busy session.
11
+ */
12
+ export function createPilotCleanup({ kernel, requirePilot, saveRow, pilotPorts, pilotProject, git = gitModule, gitTimeoutMs = 5000 }) {
13
+ const gitOptions = { timeoutMs: gitTimeoutMs }
14
+
15
+ /** Archive outside `kernel.serialize`: the archive event re-enters the service (releaseSession). */
16
+ async function archiveSession(id) {
17
+ const archive = pilotPorts.sessions?.archive
18
+ if (typeof archive !== 'function') return { state: 'kept', id, message: 'Session archiving is unavailable on this Host.' }
19
+ try {
20
+ const result = await archive(id)
21
+ return result?.ok === true ? { state: 'removed', id } : { state: 'kept', id, message: String(result?.message || 'The session could not be archived.') }
22
+ } catch (error) {
23
+ return { state: 'kept', id, message: messageOf(error) }
24
+ }
25
+ }
26
+
27
+ async function retryWorktree(root, project, row, item) {
28
+ try {
29
+ const tree = await git.integrationWorktree(root, item.path, project.commonDir, row.branch, gitOptions)
30
+ if (tree === null) return { state: 'removed', path: item.path }
31
+ if (tree === false) return { ...item, message: `${item.path} is not the registered worktree of ${row.branch}; it was left alone.` }
32
+ const status = await git.worktreeStatus(tree, gitOptions)
33
+ if (status.operation !== null) return { ...item, message: `A ${status.operation} is in progress.` }
34
+ if (status.dirty.length > 0) return { ...item, message: `It has uncommitted changes: ${status.dirty.slice(0, 10).join(', ')}` }
35
+ const removed = await git.removeWorktree(root, tree, gitOptions)
36
+ return removed.ok ? { state: 'removed', path: item.path } : { ...item, message: removed.message }
37
+ } catch (error) {
38
+ return { ...item, message: messageOf(error) }
39
+ }
40
+ }
41
+
42
+ async function retryBranch(root, project, item) {
43
+ try {
44
+ const head = await git.branchHead(root, item.name, gitOptions)
45
+ if (head === null) return { state: 'removed', name: item.name }
46
+ if (!(await git.commitInBranch(root, head, project.baseBranch, gitOptions))) {
47
+ return { ...item, message: `${item.name} has commits that are not in ${project.baseBranch}; it was kept.` }
48
+ }
49
+ const deleted = await git.deleteBranch(root, item.name, gitOptions)
50
+ return deleted.ok ? { state: 'removed', name: item.name } : { ...item, message: deleted.message }
51
+ } catch (error) {
52
+ return { ...item, message: messageOf(error) }
53
+ }
54
+ }
55
+
56
+ /** After a verified merge: archive the session, then record the per-item result. */
57
+ async function pilotRecordCleanup({ pilotId, cleanup }) {
58
+ const row = await requirePilot(pilotId)
59
+ expectPhase(row, ['done'], 'recording cleanup')
60
+ const missing = 'The merge reported no cleanup result.'
61
+ const worktree = cleanup?.worktree ?? { state: 'kept', path: row.worktree, message: missing }
62
+ const branch = cleanup?.branch ?? { state: 'kept', name: row.branch, message: missing }
63
+ const session = await archiveSession(row.sessionId)
64
+ return kernel.serialize(row.projectId, async () =>
65
+ saveRow(applyCleanup(await requirePilot(pilotId), { worktree, branch, session }, kernel.now())))
66
+ }
67
+
68
+ /** Retry only the kept items; approving the merge already authorised exactly these names. */
69
+ async function pilotRetryCleanup({ pilotId }) {
70
+ const row = await requirePilot(pilotId)
71
+ expectCleanupNeeded(row)
72
+ kernel.assertNotIntegrating(row.projectId)
73
+ const kept = new Set(cleanupKept(row.cleanup))
74
+ const session = kept.has('session') ? await archiveSession(row.sessionId) : row.cleanup.session
75
+ return kernel.serialize(row.projectId, async () => {
76
+ const current = await requirePilot(pilotId)
77
+ expectCleanupNeeded(current)
78
+ // Again under the lock: a merge reserves inside serialize, so one may have started since the early check.
79
+ kernel.assertNotIntegrating(current.projectId)
80
+ const project = pilotProject(current.projectId)
81
+ const root = git.mainWorktreeRoot(project.commonDir)
82
+ const next = { ...current.cleanup, session }
83
+ const noRoot = 'The repository has no main working tree.'
84
+ if (kept.has('worktree')) next.worktree = root === null ? { ...next.worktree, message: noRoot } : await retryWorktree(root, project, current, next.worktree)
85
+ if (kept.has('branch')) next.branch = root === null ? { ...next.branch, message: noRoot } : await retryBranch(root, project, next.branch)
86
+ return saveRow(applyCleanup(current, next, kernel.now(), 'human'))
87
+ })
88
+ }
89
+
90
+ async function pilotDismissCleanup({ pilotId }) {
91
+ const row = await requirePilot(pilotId)
92
+ return kernel.serialize(row.projectId, async () =>
93
+ saveRow(applyCleanupDismiss(await requirePilot(pilotId), {}, kernel.now())))
94
+ }
95
+
96
+ return { pilotRecordCleanup, pilotRetryCleanup, pilotDismissCleanup }
97
+ }
@@ -10,6 +10,7 @@ export const errors = Object.freeze({
10
10
  'pilot-goal-unavailable': 503,
11
11
  'pilot-start-failed': 500,
12
12
  'pilot-skills-install-failed': 502,
13
+ 'pilot-cleanup-not-needed': 409,
13
14
  })
14
15
 
15
16
  export const fail = defineErrors(errors)
@@ -130,7 +130,21 @@ export function createPilotMerger({ service, config, git = gitModule, check, log
130
130
  return current.phase === 'merging' && latest.baseBranch === project.baseBranch && (latest.verifyCommand ?? '') === verifyCommand
131
131
  },
132
132
  })
133
- if (finalized) return
133
+ const settle = result => settleOutcome(result, { finalized: () => finalized, finish, completeTasks, project })
134
+ await settle(result)
135
+ // Teardown is reported after the outcome; a failure here never undoes the merge.
136
+ if (result.outcome !== 'merged' && result.outcome !== 'already-merged') return
137
+ try {
138
+ if ((await service.pilotGetById(pilotId)).phase !== 'done') return
139
+ await service.pilotRecordCleanup({ pilotId, cleanup: result.cleanup })
140
+ } catch (error) {
141
+ warn(`pilot ${pilotId} cleanup could not be recorded: ${messageOf(error)}`)
142
+ }
143
+ }
144
+
145
+ /** Record the outcome of one pipeline run exactly once (the verified callback may already have). */
146
+ async function settleOutcome(result, { finalized, finish, completeTasks, project }) {
147
+ if (finalized()) return
134
148
  if (result.outcome === 'merged' || result.outcome === 'already-merged') {
135
149
  // The missing-branch recovery returns before the verified callback: the
136
150
  // work is merged, so account for its tasks here.
@@ -188,3 +188,39 @@ export function applyAbort(row, _input, at) {
188
188
  expectPhase(row, [...ACTIVE_PILOT_PHASES], 'aborting')
189
189
  return change(row, 'aborted', 'human', 'Pilot aborted', at, { resumePhase: null, blockerReason: null })
190
190
  }
191
+
192
+ /** What a pilot's teardown touches, in the order it reports them. */
193
+ export const CLEANUP_ITEMS = ['worktree', 'branch', 'session']
194
+ const CLEANUP_WORDS = {
195
+ worktree: { removed: 'worktree removed', kept: 'worktree kept', absent: 'no worktree' },
196
+ branch: { removed: 'branch deleted', kept: 'branch kept', absent: 'no branch' },
197
+ session: { removed: 'session archived', kept: 'session kept', absent: 'no session' },
198
+ }
199
+
200
+ export const cleanupKept = cleanup => CLEANUP_ITEMS.filter(name => cleanup?.[name]?.state === 'kept')
201
+
202
+ export function cleanupSummary(cleanup) {
203
+ return `Cleanup: ${CLEANUP_ITEMS.map(name => CLEANUP_WORDS[name][cleanup?.[name]?.state] ?? `${name} unknown`).join(', ')}`
204
+ }
205
+
206
+ /** Record the teardown of a merged pilot. The phase stays `done`. */
207
+ export function applyCleanup(row, { worktree, branch, session }, at, actor = 'system') {
208
+ expectPhase(row, ['done'], 'recording cleanup')
209
+ const cleanup = { worktree, branch, session, at, dismissedAt: null }
210
+ return change(row, 'done', actor, cleanupSummary(cleanup), at, { cleanup })
211
+ }
212
+
213
+ /** Retry and dismiss apply only to a done pilot that kept something not yet dismissed. */
214
+ export function expectCleanupNeeded(row) {
215
+ expectPhase(row, ['done'], 'cleaning up')
216
+ if (!row.cleanup || (row.cleanup.dismissedAt ?? null) !== null || cleanupKept(row.cleanup).length === 0) {
217
+ throw fail('pilot-cleanup-not-needed', 'This pilot has nothing left to clean up.')
218
+ }
219
+ }
220
+
221
+ export function applyCleanupDismiss(row, _input, at) {
222
+ expectCleanupNeeded(row)
223
+ return change(row, 'done', 'human', `Dismissed cleanup of: ${cleanupKept(row.cleanup).join(', ')}`, at, {
224
+ cleanup: { ...row.cleanup, dismissedAt: at },
225
+ })
226
+ }
@@ -58,4 +58,10 @@ export function routes(router, deps) {
58
58
  router.post('/pilot/runs/:pilotId/abort', async ({ params, send }) => {
59
59
  send(200, { pilot: await deps.service.pilotAbort({ pilotId: params.pilotId }) })
60
60
  })
61
+ router.post('/pilot/runs/:pilotId/cleanup', async ({ params, send }) => {
62
+ send(200, { pilot: await deps.service.pilotRetryCleanup({ pilotId: params.pilotId }) })
63
+ })
64
+ router.post('/pilot/runs/:pilotId/cleanup/dismiss', async ({ params, send }) => {
65
+ send(200, { pilot: await deps.service.pilotDismissCleanup({ pilotId: params.pilotId }) })
66
+ })
61
67
  }
@@ -75,6 +75,14 @@ export function pilotRowSchema(z) {
75
75
  text: z.string(),
76
76
  at: z.number().int(),
77
77
  })
78
+ const cleanupState = z.enum(['removed', 'kept', 'absent'])
79
+ const cleanupRecord = z.object({
80
+ worktree: z.object({ state: cleanupState, path: z.string().nullable(), message: z.string().optional() }),
81
+ branch: z.object({ state: cleanupState, name: z.string(), message: z.string().optional() }),
82
+ session: z.object({ state: cleanupState, id: z.string(), message: z.string().optional() }),
83
+ at: z.number().int(),
84
+ dismissedAt: z.number().int().nullable(),
85
+ })
78
86
  return z.object({
79
87
  id: z.string(),
80
88
  projectId: z.string(),
@@ -96,6 +104,7 @@ export function pilotRowSchema(z) {
96
104
  decisions: z.array(decision),
97
105
  taskProgress: z.record(z.string(), taskEntry),
98
106
  lastMerge: mergeOutcome.nullable(),
107
+ cleanup: cleanupRecord.nullable().optional(),
99
108
  superpowers: z.boolean(),
100
109
  history: z.array(historyEntry),
101
110
  createdAt: z.number().int(),
@@ -30,6 +30,7 @@ import {
30
30
  import { blindQaPrompt, gateResumeMessage, pilotPhaseInstructions } from './prompts.mjs'
31
31
  import { pilotRowParser } from './schema.mjs'
32
32
  import { createPilotSkills } from './skills-service.mjs'
33
+ import { createPilotCleanup } from './cleanup.mjs'
33
34
 
34
35
  const messageOf = error => String(error?.message ?? error)
35
36
 
@@ -289,7 +290,11 @@ export function extendService(kernel, deps = {}) {
289
290
  copy.goalDisarmed = false
290
291
  try {
291
292
  const goal = await pilotPorts.goals?.get?.(row.sessionId)
292
- copy.goalDisarmed = Boolean(goal && goal.id === row.goalId && goal.phase === 'active' && goal.activation === 'disarmed')
293
+ const own = Boolean(goal && goal.id === row.goalId)
294
+ copy.goalDisarmed = own && goal.phase === 'active' && goal.activation === 'disarmed'
295
+ // The drawer shows "17 of 200 rounds"; only the DSH goal knows them.
296
+ if (own && Number.isInteger(goal.roundsStarted)) copy.roundsStarted = goal.roundsStarted
297
+ if (own && Number.isInteger(goal.maxGoalRounds)) copy.maxGoalRounds = goal.maxGoalRounds
293
298
  } catch { /* Goal availability must not prevent reading the pilot. */ }
294
299
  }
295
300
  return copy
@@ -302,8 +307,13 @@ export function extendService(kernel, deps = {}) {
302
307
  async function pilotList({ projectId, includeGoal = true }) {
303
308
  kernel.requireRecord(projectId)
304
309
  const rows = (await readProjectRows(projectId)).sort((a, b) => b.updatedAt - a.updatedAt)
305
- const listed = await Promise.all(rows.map(row => publicPilot(row, includeGoal)))
306
- return { active: listed.filter(isPilotActive), pilots: listed }
310
+ // How many project agents are ready to delegate to (mapped model), for the drawer's roster line;
311
+ // null when unknown. Read beside the goals, not after them: the board polls this list.
312
+ const readRoster = includeGoal && typeof pilotPorts.agents?.roster === 'function'
313
+ ? Promise.resolve().then(() => pilotPorts.agents.roster(projectId)).then(ready => ({ ready: ready.length }), () => null)
314
+ : Promise.resolve(null)
315
+ const [listed, roster] = await Promise.all([Promise.all(rows.map(row => publicPilot(row, includeGoal))), readRoster])
316
+ return { active: listed.filter(isPilotActive), pilots: listed, roster }
307
317
  }
308
318
 
309
319
  async function pilotStatus({ sessionId, cwd }) {
@@ -322,11 +332,12 @@ export function extendService(kernel, deps = {}) {
322
332
  }
323
333
  }
324
334
 
325
- async function agentStep({ sessionId, cwd }, applyFn) {
335
+ async function agentStep({ sessionId, cwd }, applyFn, beforeApply) {
326
336
  const projectId = await kernel.projectForCwd(cwd)
327
337
  await resolveOwnedPilot(projectId, sessionId)
328
338
  const saved = await kernel.serialize(projectId, async () => {
329
339
  const current = await resolveOwnedPilot(projectId, sessionId)
340
+ beforeApply?.(current)
330
341
  const next = await applyFn(current, projectId)
331
342
  return saveRow(next)
332
343
  })
@@ -442,7 +453,11 @@ export function extendService(kernel, deps = {}) {
442
453
  }
443
454
 
444
455
  const pilotBlock = ({ sessionId, cwd, reason }) =>
445
- agentStep({ sessionId, cwd }, row => applyBlock(row, { reason }, kernel.now()))
456
+ agentStep({ sessionId, cwd }, row => applyBlock(row, { reason }, kernel.now()), row => {
457
+ // Pause and abort refuse during a merge; a block must not leave the
458
+ // merger running against a pilot row that is no longer in `merging`.
459
+ if (row.phase === 'merging') kernel.assertNotIntegrating(row.projectId)
460
+ })
446
461
 
447
462
  async function pilotAnswer({ pilotId, text }) {
448
463
  const initial = await requirePilot(pilotId)
@@ -478,7 +493,7 @@ export function extendService(kernel, deps = {}) {
478
493
  return saved
479
494
  }
480
495
 
481
- async function pilotRecordMergeOutcome({ pilotId, outcome, text, commit = null, detail = null, verificationPending }) {
496
+ async function pilotRecordMergeOutcome({ pilotId, outcome, text, commit = null, detail = null, verificationPending, resume = true }) {
482
497
  const initial = await requirePilot(pilotId)
483
498
  const saved = await kernel.serialize(initial.projectId, async () => {
484
499
  const current = await requirePilot(pilotId)
@@ -486,7 +501,7 @@ export function extendService(kernel, deps = {}) {
486
501
  })
487
502
  if (saved.phase === 'done') {
488
503
  await pilotPorts.goals?.complete?.(saved.sessionId, saved.goalId)
489
- } else {
504
+ } else if (resume) {
490
505
  await resumeAndDeliver(saved, gateResumeMessage('merge', { decision: outcome, text: [text, detail].filter(Boolean).join('\n\n') }))
491
506
  }
492
507
  return saved
@@ -539,6 +554,7 @@ export function extendService(kernel, deps = {}) {
539
554
 
540
555
  return {
541
556
  ...pilotSkills,
557
+ ...createPilotCleanup({ kernel, requirePilot, saveRow, pilotPorts, pilotProject, git: deps.git, gitTimeoutMs }),
542
558
  pilotHydrate,
543
559
  pilotProject,
544
560
  pilotCreateRow,
@@ -87,15 +87,22 @@ async function defaultCloneRepo(dir) {
87
87
  * staged beside the target and renamed into place in one step per skill, and
88
88
  * the temporary clone is always removed. A skill folder that already exists is
89
89
  * reported under `skipped` and never touched.
90
- * @param {{ targetSkillsDir: string, missingOnly?: string[], cloneRepo?: (dir: string) => Promise<void>, exists?: (file: string) => Promise<boolean> }} options
90
+ * @param {{ targetSkillsDir: string, missingOnly?: string[], cloneRepo?: (dir: string) => Promise<void>, exists?: (file: string) => Promise<boolean>, makeTemp?: () => Promise<string>, move?: (from: string, to: string) => Promise<void> }} options
91
91
  * @returns {Promise<{ installed: string[], skipped: string[] }>}
92
92
  */
93
- export async function installSuperpowersToDir({ targetSkillsDir, missingOnly = PILOT_SKILLS, cloneRepo = defaultCloneRepo, exists = defaultExists } = {}) {
93
+ export async function installSuperpowersToDir({
94
+ targetSkillsDir,
95
+ missingOnly = PILOT_SKILLS,
96
+ cloneRepo = defaultCloneRepo,
97
+ exists = defaultExists,
98
+ makeTemp = () => mkdtemp(join(tmpdir(), 'pilot-skills-')),
99
+ move = rename,
100
+ } = {}) {
94
101
  const wanted = [...new Set(missingOnly)].filter(name => PILOT_SKILLS.includes(name))
95
102
  if (wanted.length === 0) return { installed: [], skipped: [] }
96
103
  let source = null
97
104
  try {
98
- source = await mkdtemp(join(tmpdir(), 'pilot-skills-'))
105
+ source = await makeTemp()
99
106
  await cloneRepo(source)
100
107
  // Validate every requested skill before copying any of them.
101
108
  for (const name of wanted) {
@@ -120,7 +127,7 @@ export async function installSuperpowersToDir({ targetSkillsDir, missingOnly = P
120
127
  skipped.push(name)
121
128
  continue
122
129
  }
123
- await rename(join(staging, name), destination)
130
+ await move(join(staging, name), destination)
124
131
  placed.push(name)
125
132
  }
126
133
  } catch (error) {
@@ -79,6 +79,9 @@ export function createPilotStarter({ service, git, sessions, goals, gitOptions =
79
79
  pilotId,
80
80
  outcome: 'blocked',
81
81
  text: 'The board restarted during the merge. The branch and worktree were kept; review it again and the merge can be retried.',
82
+ // After a restart the goal is disarmed. Recovering the row must not
83
+ // resume it: the human re-arms it explicitly, as for any other gate.
84
+ resume: false,
82
85
  })
83
86
  results.push({ pilotId, action: 'recovered-merge' })
84
87
  continue