dsh-tower 0.0.0-stage → 1.1.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.
package/lib/tower.js ADDED
@@ -0,0 +1,1507 @@
1
+ // Tower domain: repo-scoped mission state machine, validation, and gates.
2
+ import path from 'node:path'
3
+ import {
4
+ git,
5
+ resolveRepo,
6
+ hasAnyCommit,
7
+ localBranchExists,
8
+ revParse,
9
+ branchExists,
10
+ currentBranch,
11
+ currentCommonDir,
12
+ addWorktree,
13
+ listWorktrees,
14
+ countCommits,
15
+ isClean,
16
+ isAncestor,
17
+ } from './git.js'
18
+ import {
19
+ pathsFor,
20
+ exists,
21
+ ensureDir,
22
+ readJson,
23
+ writeJsonAtomic,
24
+ appendJsonl,
25
+ readActivityTail,
26
+ withLock,
27
+ shortHash,
28
+ } from './store.js'
29
+
30
+ export const SCHEMA_VERSION = 1
31
+ export const MISSION_STATUSES = [
32
+ 'planned',
33
+ 'active',
34
+ 'completed',
35
+ 'blocked',
36
+ 'paused',
37
+ 'merged',
38
+ 'abandoned',
39
+ ]
40
+ const TERMINAL = new Set(['merged', 'abandoned'])
41
+ const TRANSITIONS = {
42
+ planned: ['active', 'abandoned'],
43
+ active: ['completed', 'blocked', 'paused', 'abandoned'],
44
+ blocked: ['active', 'paused', 'abandoned'],
45
+ paused: ['active', 'abandoned'],
46
+ completed: ['active', 'abandoned'],
47
+ merged: [],
48
+ abandoned: [],
49
+ }
50
+ const GLOB_META = /[*?[{]/
51
+
52
+ function slugify(title) {
53
+ const slug = String(title)
54
+ .toLowerCase()
55
+ .replace(/[^a-z0-9]+/g, '-')
56
+ .replace(/^-+|-+$/g, '')
57
+ .slice(0, 24)
58
+ return slug || 'mission'
59
+ }
60
+
61
+ export const FINDING_TYPES = ['bug', 'improve', 'vuln', 'idea']
62
+ export const FINDING_SEVERITIES = ['low', 'medium', 'high', 'critical']
63
+ export const MERGE_VERDICTS = ['merge', 'fix-then-merge', 'hold']
64
+ const MAX_REVIEW_ROUNDS = 5
65
+ const REVIEW_STATUS_RE = /^(clean|p1-\d+items|p2-\d+items)$/
66
+
67
+ function globToRegExp(pattern) {
68
+ let out = '^'
69
+ for (let index = 0; index < pattern.length; index += 1) {
70
+ const char = pattern[index]
71
+ if (char === '*') {
72
+ if (pattern[index + 1] === '*') {
73
+ out += '.*'
74
+ index += 1
75
+ } else {
76
+ out += '[^/]*'
77
+ }
78
+ } else if (char === '?') {
79
+ out += '[^/]'
80
+ } else {
81
+ out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
82
+ }
83
+ }
84
+ return new RegExp(`${out}$`)
85
+ }
86
+
87
+ export function fileInScope(scope, file) {
88
+ return (scope ?? []).some((pattern) => globToRegExp(pattern).test(file))
89
+ }
90
+
91
+ function fail(message) {
92
+ throw new Error(message)
93
+ }
94
+
95
+ function isPlainObject(value) {
96
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
97
+ }
98
+
99
+ export function validateTitle(title) {
100
+ if (typeof title !== 'string' || title.trim().length === 0) fail('mission title is required')
101
+ if (!/^[\x20-\x7E]+$/.test(title)) {
102
+ fail(`mission title must be printable ASCII: ${JSON.stringify(title)}`)
103
+ }
104
+ return title.trim()
105
+ }
106
+
107
+ export function normalizeScope(scope, { allowEmpty = false } = {}) {
108
+ if (!Array.isArray(scope)) fail('mission scope must be an array of relative globs')
109
+ if (scope.length === 0 && !allowEmpty) fail('mission scope must not be empty for a build mission')
110
+ const out = []
111
+ for (const raw of scope) {
112
+ if (typeof raw !== 'string' || raw.trim().length === 0) fail('scope entries must be non-empty strings')
113
+ const value = raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '').trim()
114
+ if (value.length === 0) fail('scope entries must be non-empty strings')
115
+ if (value.startsWith('/') || /^[A-Za-z]:/.test(value)) fail(`scope must be relative: ${raw}`)
116
+ if (value.split('/').some((part) => part === '..')) fail(`scope must not contain "..": ${raw}`)
117
+ if (!out.includes(value)) out.push(value)
118
+ }
119
+ return out
120
+ }
121
+
122
+ function scopePrefix(pattern) {
123
+ const index = pattern.search(GLOB_META)
124
+ const literal = index < 0 ? pattern : pattern.slice(0, index)
125
+ return literal.replace(/\/+$/, '')
126
+ }
127
+
128
+ export function scopesOverlap(a, b) {
129
+ for (const pa of a) {
130
+ for (const pb of b) {
131
+ if (pa === pb) return true
132
+ const x = scopePrefix(pa)
133
+ const y = scopePrefix(pb)
134
+ if (!x || !y) return true
135
+ if (x === y) return true
136
+ if (x.startsWith(`${y}/`) || y.startsWith(`${x}/`)) return true
137
+ }
138
+ }
139
+ return false
140
+ }
141
+
142
+ function nextMissionNumber(missions) {
143
+ let max = 0
144
+ for (const mission of missions) {
145
+ const match = /^M(\d+)$/.exec(mission.id)
146
+ if (match) max = Math.max(max, Number(match[1]))
147
+ }
148
+ return max + 1
149
+ }
150
+
151
+ function addDependency(mission, dep) {
152
+ if (mission.id === dep) return
153
+ if (!mission.deps.includes(dep)) mission.deps.push(dep)
154
+ }
155
+
156
+ function hasDependencyPath(missionsById, fromId, toId) {
157
+ const seen = new Set()
158
+ const stack = [fromId]
159
+ while (stack.length > 0) {
160
+ const current = stack.pop()
161
+ if (current === toId) return true
162
+ if (seen.has(current)) continue
163
+ seen.add(current)
164
+ const mission = missionsById.get(current)
165
+ if (!mission) continue
166
+ for (const dep of mission.deps) stack.push(dep)
167
+ }
168
+ return false
169
+ }
170
+
171
+ function assertAcyclic(missions) {
172
+ const byId = new Map(missions.map((mission) => [mission.id, mission]))
173
+ const state = new Map()
174
+ const visit = (id, trail) => {
175
+ const mark = state.get(id)
176
+ if (mark === 'done') return
177
+ if (mark === 'visiting') fail(`mission dependencies have a cycle: ${[...trail, id].join(' -> ')}`)
178
+ state.set(id, 'visiting')
179
+ const mission = byId.get(id)
180
+ if (mission) for (const dep of mission.deps) visit(dep, [...trail, id])
181
+ state.set(id, 'done')
182
+ }
183
+ for (const mission of missions) visit(mission.id, [])
184
+ }
185
+
186
+ /**
187
+ * Kimi-style heuristic: overlapping build scopes are serialized by an
188
+ * auto-added dependency. It is conservative, not a proof of disjointness.
189
+ */
190
+ function addAutoDeps(newMissions, existingMissions) {
191
+ const openExisting = existingMissions.filter((mission) => !TERMINAL.has(mission.status))
192
+ const all = [...existingMissions, ...newMissions]
193
+ const byId = new Map(all.map((mission) => [mission.id, mission]))
194
+
195
+ for (let i = 0; i < newMissions.length; i += 1) {
196
+ for (let j = i + 1; j < newMissions.length; j += 1) {
197
+ const earlier = newMissions[i]
198
+ const later = newMissions[j]
199
+ if (earlier.kind === 'survey' || later.kind === 'survey') continue
200
+ if (!scopesOverlap(earlier.scope, later.scope)) continue
201
+ if (hasDependencyPath(byId, later.id, earlier.id)) continue
202
+ addDependency(later, earlier.id)
203
+ }
204
+ const mission = newMissions[i]
205
+ if (mission.kind === 'survey') continue
206
+ for (const other of openExisting) {
207
+ if (other.kind === 'survey') continue
208
+ if (!scopesOverlap(mission.scope, other.scope)) continue
209
+ if (hasDependencyPath(byId, mission.id, other.id)) continue
210
+ addDependency(mission, other.id)
211
+ }
212
+ }
213
+ }
214
+
215
+ function normalizeMissionInput(input, index) {
216
+ if (!isPlainObject(input)) fail(`missions[${index}] must be an object`)
217
+ const title = validateTitle(input.title)
218
+ const kind = input.kind === 'survey' ? 'survey' : 'build'
219
+ const scope = normalizeScope(input.scope ?? [], { allowEmpty: kind === 'survey' })
220
+ const tasks = []
221
+ if (input.tasks !== undefined) {
222
+ if (!Array.isArray(input.tasks)) fail(`missions[${index}].tasks must be an array of strings`)
223
+ for (const task of input.tasks) {
224
+ if (typeof task !== 'string' || task.trim().length === 0) {
225
+ fail(`missions[${index}].tasks entries must be non-empty strings`)
226
+ }
227
+ tasks.push({ text: task.trim(), status: 'open' })
228
+ }
229
+ }
230
+ const deps = []
231
+ if (input.deps !== undefined) {
232
+ if (!Array.isArray(input.deps)) fail(`missions[${index}].deps must be an array of mission ids`)
233
+ for (const dep of input.deps) {
234
+ if (typeof dep !== 'string' || dep.trim().length === 0) {
235
+ fail(`missions[${index}].deps entries must be non-empty mission ids`)
236
+ }
237
+ if (!deps.includes(dep.trim())) deps.push(dep.trim())
238
+ }
239
+ }
240
+ const context = typeof input.context === 'string' ? input.context.slice(0, 4096) : ''
241
+ return { title, kind, scope, tasks, deps, context }
242
+ }
243
+
244
+ function newMission(id, input, now) {
245
+ return {
246
+ id,
247
+ title: input.title,
248
+ kind: input.kind,
249
+ scope: input.scope,
250
+ tasks: input.tasks,
251
+ deps: input.deps,
252
+ context: input.context,
253
+ status: 'planned',
254
+ owner: null,
255
+ blockers: [],
256
+ notes: [],
257
+ reviews: [],
258
+ scopeGeneration: 1,
259
+ createdAt: now,
260
+ updatedAt: now,
261
+ }
262
+ }
263
+
264
+ export function validateState(state, statePath) {
265
+ const where = statePath ? ` at ${statePath}` : ''
266
+ if (!isPlainObject(state)) fail(`tower state is not an object${where}`)
267
+ if (state.schemaVersion !== SCHEMA_VERSION) {
268
+ fail(`unsupported tower state schemaVersion ${state.schemaVersion}${where}`)
269
+ }
270
+ if (!Array.isArray(state.missions)) fail(`tower state has no missions array${where}`)
271
+ const ids = new Set()
272
+ for (const mission of state.missions) {
273
+ if (!isPlainObject(mission) || typeof mission.id !== 'string') fail(`mission entry without id${where}`)
274
+ if (ids.has(mission.id)) fail(`duplicate mission id ${mission.id}${where}`)
275
+ ids.add(mission.id)
276
+ if (!MISSION_STATUSES.includes(mission.status)) {
277
+ fail(`mission ${mission.id} has unknown status ${mission.status}${where}`)
278
+ }
279
+ if (!Array.isArray(mission.tasks)) fail(`mission ${mission.id} has no tasks array${where}`)
280
+ if (!Array.isArray(mission.deps)) fail(`mission ${mission.id} has no deps array${where}`)
281
+ }
282
+ if (state.roster !== undefined) {
283
+ if (!Array.isArray(state.roster)) fail(`tower state roster is not an array${where}`)
284
+ const names = new Set()
285
+ const agents = new Set()
286
+ for (const entry of state.roster) {
287
+ if (!entry || typeof entry.name !== 'string' || typeof entry.agentId !== 'string') {
288
+ fail(`invalid roster entry${where}`)
289
+ }
290
+ if (names.has(entry.name)) fail(`duplicate roster name ${entry.name}${where}`)
291
+ if (agents.has(entry.agentId)) fail(`duplicate roster agent ${entry.agentId}${where}`)
292
+ names.add(entry.name)
293
+ agents.add(entry.agentId)
294
+ }
295
+ }
296
+ if (state.messages !== undefined) {
297
+ if (!Array.isArray(state.messages)) fail(`tower state messages is not an array${where}`)
298
+ const ids = new Set()
299
+ for (const message of state.messages) {
300
+ if (!message || typeof message.id !== 'string' || typeof message.to !== 'string') {
301
+ fail(`invalid message entry${where}`)
302
+ }
303
+ if (ids.has(message.id)) fail(`duplicate message id ${message.id}${where}`)
304
+ ids.add(message.id)
305
+ if (!Array.isArray(message.readBy)) fail(`message ${message.id} has no readBy array${where}`)
306
+ }
307
+ }
308
+ if (state.findings !== undefined) {
309
+ if (!Array.isArray(state.findings)) fail(`tower state findings is not an array${where}`)
310
+ const ids = new Set()
311
+ for (const finding of state.findings) {
312
+ if (!finding || typeof finding.id !== 'string') fail(`invalid finding entry${where}`)
313
+ if (ids.has(finding.id)) fail(`duplicate finding id ${finding.id}${where}`)
314
+ ids.add(finding.id)
315
+ }
316
+ }
317
+ if (state.reviews !== undefined) {
318
+ if (!Array.isArray(state.reviews)) fail(`tower state reviews is not an array${where}`)
319
+ const ids = new Set()
320
+ for (const review of state.reviews) {
321
+ if (!review || typeof review.id !== 'string') fail(`invalid review entry${where}`)
322
+ if (ids.has(review.id)) fail(`duplicate review id ${review.id}${where}`)
323
+ ids.add(review.id)
324
+ if (!REVIEW_STATUS_RE.test(String(review.status))) {
325
+ fail(`review ${review.id} has unknown status ${review.status}${where}`)
326
+ }
327
+ if (!MERGE_VERDICTS.includes(review.mergeVerdict)) {
328
+ fail(`review ${review.id} has unknown merge verdict ${review.mergeVerdict}${where}`)
329
+ }
330
+ }
331
+ }
332
+ return state
333
+ }
334
+
335
+ function taskCounts(tasks) {
336
+ const counts = { total: tasks.length, done: 0, open: 0, dropped: 0 }
337
+ for (const task of tasks) {
338
+ if (task.status === 'done') counts.done += 1
339
+ else if (task.status === 'dropped') counts.dropped += 1
340
+ else counts.open += 1
341
+ }
342
+ return counts
343
+ }
344
+
345
+ export function missionSummary(mission) {
346
+ return {
347
+ id: mission.id,
348
+ title: mission.title,
349
+ kind: mission.kind,
350
+ status: mission.status,
351
+ scope: mission.scope,
352
+ deps: mission.deps,
353
+ owner: mission.owner ?? null,
354
+ worktree: mission.worktree
355
+ ? {
356
+ path: mission.worktree.path,
357
+ branch: mission.worktree.branch,
358
+ baseCommit: mission.worktree.baseCommit,
359
+ }
360
+ : null,
361
+ blockers: mission.blockers ?? [],
362
+ tasks: taskCounts(mission.tasks ?? []),
363
+ scopeGeneration: mission.scopeGeneration ?? 1,
364
+ updatedAt: mission.updatedAt,
365
+ }
366
+ }
367
+
368
+ function fullMission(mission) {
369
+ return {
370
+ ...missionSummary(mission),
371
+ tasks: (mission.tasks ?? []).map((task) => ({ ...task })),
372
+ notes: mission.notes ?? [],
373
+ }
374
+ }
375
+
376
+ export class Tower {
377
+ constructor(repo) {
378
+ this.root = repo.root
379
+ this.commonDir = repo.commonDir
380
+ this.branch = repo.branch
381
+ this.paths = pathsFor(repo.commonDir)
382
+ }
383
+
384
+ static async open(repoRoot) {
385
+ const repo = await resolveRepo(repoRoot)
386
+ return new Tower(repo)
387
+ }
388
+
389
+ async load() {
390
+ if (!(await exists(this.paths.state))) {
391
+ fail(`tower is not initialized for ${this.root} — run tower_init first`)
392
+ }
393
+ const state = await readJson(this.paths.state)
394
+ return validateState(state, this.paths.state)
395
+ }
396
+
397
+ async init(input = {}) {
398
+ await ensureDir(this.paths.dir)
399
+ return withLock(this.paths, async () => {
400
+ if (await exists(this.paths.state)) {
401
+ const state = await this.load()
402
+ return {
403
+ created: false,
404
+ repoRoot: state.repoRoot,
405
+ commonDir: state.commonDir,
406
+ statePath: this.paths.state,
407
+ base: state.base,
408
+ revision: state.revision,
409
+ missions: state.missions.length,
410
+ }
411
+ }
412
+
413
+ const now = Date.now()
414
+ const committed = await hasAnyCommit(this.root)
415
+ let base = typeof input.base === 'string' && input.base.trim() ? input.base.trim() : null
416
+ if (base) {
417
+ if (/^refs\//.test(base) || base.startsWith('origin/')) {
418
+ fail(`base must be a local branch name, not ${base}`)
419
+ }
420
+ if (committed && !(await localBranchExists(this.root, base))) {
421
+ fail(`base branch "${base}" does not exist locally`)
422
+ }
423
+ } else {
424
+ base = this.branch
425
+ if (!base && !committed) base = 'main'
426
+ if (!base) fail('repository is in detached HEAD; pass an explicit local base branch')
427
+ }
428
+
429
+ const state = {
430
+ schemaVersion: SCHEMA_VERSION,
431
+ repoRoot: this.root,
432
+ commonDir: this.commonDir,
433
+ base,
434
+ revision: 0,
435
+ createdAt: now,
436
+ updatedAt: now,
437
+ missions: [],
438
+ }
439
+ validateState(state, this.paths.state)
440
+ await writeJsonAtomic(this.paths.state, state)
441
+ await appendJsonl(this.paths.activity, { at: now, type: 'init', text: `base ${base}` })
442
+ return {
443
+ created: true,
444
+ repoRoot: this.root,
445
+ commonDir: this.commonDir,
446
+ statePath: this.paths.state,
447
+ base,
448
+ revision: 0,
449
+ missions: 0,
450
+ }
451
+ })
452
+ }
453
+
454
+ async plan(input = {}) {
455
+ if (!Array.isArray(input.missions) || input.missions.length === 0) {
456
+ fail('tower_plan needs at least one mission')
457
+ }
458
+ const prepared = input.missions.map((mission, index) => normalizeMissionInput(mission, index))
459
+ return withLock(this.paths, async () => {
460
+ const state = await this.load()
461
+ const now = Date.now()
462
+ const start = nextMissionNumber(state.missions)
463
+ const assigned = prepared.map((mission, index) => ({ ...mission, id: `M${start + index}` }))
464
+
465
+ const known = new Set([...state.missions.map((mission) => mission.id), ...assigned.map((mission) => mission.id)])
466
+ for (const mission of assigned) {
467
+ for (const dep of mission.deps) {
468
+ if (!known.has(dep)) fail(`mission ${mission.id} depends on unknown mission "${dep}"`)
469
+ }
470
+ }
471
+
472
+ addAutoDeps(assigned, state.missions)
473
+ assertAcyclic([...state.missions, ...assigned])
474
+
475
+ const created = assigned.map((mission) => newMission(mission.id, mission, now))
476
+ state.missions.push(...created)
477
+ state.revision += 1
478
+ state.updatedAt = now
479
+
480
+ validateState(state, this.paths.state)
481
+ await writeJsonAtomic(this.paths.state, state)
482
+ await appendJsonl(this.paths.activity, {
483
+ at: now,
484
+ type: 'plan',
485
+ text: `created ${created.map((mission) => mission.id).join(', ')}`,
486
+ })
487
+ return {
488
+ revision: state.revision,
489
+ missions: created.map((mission) => fullMission(mission)),
490
+ }
491
+ })
492
+ }
493
+
494
+ async mission(input = {}) {
495
+ if (typeof input.id !== 'string' || input.id.trim().length === 0) fail('tower_mission requires id')
496
+ return withLock(this.paths, async () => {
497
+ const state = await this.load()
498
+ const mission = state.missions.find((entry) => entry.id === input.id)
499
+ if (!mission) fail(`unknown mission "${input.id}"`)
500
+ const now = Date.now()
501
+ const changes = []
502
+
503
+ if (input.status !== undefined) {
504
+ if (typeof input.status !== 'string' || !MISSION_STATUSES.includes(input.status)) {
505
+ fail(`unknown mission status "${input.status}"`)
506
+ }
507
+ if (input.status === 'merged') fail('merged is recorded only by tower_merge, not by a generic mission patch')
508
+ const allowed = TRANSITIONS[mission.status] ?? []
509
+ if (!allowed.includes(input.status)) {
510
+ fail(`mission ${mission.id} cannot move from ${mission.status} to ${input.status}`)
511
+ }
512
+ mission.status = input.status
513
+ changes.push(`status=${input.status}`)
514
+ }
515
+
516
+ if (input.task_done !== undefined) {
517
+ const needle = String(input.task_done)
518
+ const task = mission.tasks.find(
519
+ (entry) => entry.status === 'open' && entry.text.toLowerCase().includes(needle.toLowerCase()),
520
+ )
521
+ if (!task) fail(`no open task matching "${needle}" in mission ${mission.id}`)
522
+ task.status = 'done'
523
+ changes.push(`task_done="${task.text}"`)
524
+ }
525
+
526
+ if (input.task_drop !== undefined) {
527
+ if (typeof input.task_drop_reason !== 'string' || input.task_drop_reason.trim().length === 0) {
528
+ fail('task_drop requires task_drop_reason')
529
+ }
530
+ const needle = String(input.task_drop)
531
+ const task = mission.tasks.find(
532
+ (entry) => entry.status === 'open' && entry.text.toLowerCase().includes(needle.toLowerCase()),
533
+ )
534
+ if (!task) fail(`no open task matching "${needle}" in mission ${mission.id}`)
535
+ task.status = 'dropped'
536
+ task.note = input.task_drop_reason.trim()
537
+ mission.notes.push(`task dropped: ${task.text} — ${task.note}`)
538
+ changes.push(`task_drop="${task.text}"`)
539
+ }
540
+
541
+ if (input.blocker !== undefined) {
542
+ if (typeof input.blocker !== 'string' || input.blocker.trim().length === 0) {
543
+ fail('blocker must be a non-empty string')
544
+ }
545
+ mission.blockers.push(input.blocker.trim())
546
+ mission.status = 'blocked'
547
+ changes.push('blocker added')
548
+ }
549
+
550
+ if (input.clear_blockers === true) {
551
+ mission.blockers = []
552
+ changes.push('blockers cleared')
553
+ }
554
+
555
+ if (input.note !== undefined) {
556
+ if (typeof input.note !== 'string' || input.note.trim().length === 0) {
557
+ fail('note must be a non-empty string')
558
+ }
559
+ mission.notes.push(input.note.trim())
560
+ changes.push('note added')
561
+ }
562
+
563
+ if (input.scope !== undefined) {
564
+ if (!['active', 'completed'].includes(mission.status)) {
565
+ fail(`scope can only be widened for active or completed missions, not ${mission.status}`)
566
+ }
567
+ const scope = normalizeScope(input.scope, { allowEmpty: mission.kind === 'survey' })
568
+ const others = state.missions.filter(
569
+ (entry) => entry.id !== mission.id && !TERMINAL.has(entry.status) && entry.kind !== 'survey',
570
+ )
571
+ for (const other of others) {
572
+ if (mission.kind !== 'survey' && scopesOverlap(scope, other.scope)) {
573
+ fail(`widened scope overlaps mission ${other.id}; retire it or add an explicit ordering`)
574
+ }
575
+ }
576
+ mission.scope = scope
577
+ mission.scopeGeneration = (mission.scopeGeneration ?? 1) + 1
578
+ mission.status = 'active'
579
+ changes.push('scope widened')
580
+ }
581
+
582
+ if (changes.length === 0) fail('tower_mission requires at least one change')
583
+ mission.updatedAt = now
584
+ state.revision += 1
585
+ state.updatedAt = now
586
+
587
+ validateState(state, this.paths.state)
588
+ await writeJsonAtomic(this.paths.state, state)
589
+ await appendJsonl(this.paths.activity, {
590
+ at: now,
591
+ type: 'mission',
592
+ missionId: mission.id,
593
+ text: changes.join('; '),
594
+ })
595
+ return { revision: state.revision, mission: fullMission(mission) }
596
+ })
597
+ }
598
+
599
+ assertOutside(target) {
600
+ const resolved = path.resolve(target)
601
+ const inside = (parent) => {
602
+ const rel = path.relative(path.resolve(parent), resolved)
603
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)
604
+ }
605
+ if (resolved === path.resolve(this.root) || inside(this.root)) {
606
+ fail(`worktree path must be outside the main checkout: ${resolved}`)
607
+ }
608
+ if (resolved === path.resolve(this.commonDir) || inside(this.commonDir)) {
609
+ fail(`worktree path must be outside Git metadata: ${resolved}`)
610
+ }
611
+ return resolved
612
+ }
613
+
614
+ async assertWorktree(worktree) {
615
+ if (!worktree || typeof worktree.path !== 'string') fail('mission has no worktree')
616
+ const wtPath = path.resolve(worktree.path)
617
+ if (!(await exists(wtPath))) fail(`worktree is missing: ${wtPath}`)
618
+ const common = await currentCommonDir(wtPath)
619
+ if (!common) fail(`worktree ${wtPath} is not a Git worktree`)
620
+ if (path.resolve(common) !== path.resolve(this.commonDir)) {
621
+ fail(`worktree ${wtPath} belongs to a different repository`)
622
+ }
623
+ const branch = await currentBranch(wtPath)
624
+ if (branch !== worktree.branch) {
625
+ fail(`worktree ${wtPath} is on ${branch ?? 'detached HEAD'}, expected ${worktree.branch}`)
626
+ }
627
+ const registered = await listWorktrees(this.root)
628
+ if (!registered.some((entry) => path.resolve(entry.path) === wtPath)) {
629
+ fail(`worktree ${wtPath} is not registered with git`)
630
+ }
631
+ return worktree
632
+ }
633
+
634
+ async provision(input = {}) {
635
+ const missionId = input.missionId
636
+ if (typeof missionId !== 'string' || missionId.trim().length === 0) {
637
+ fail('tower_spawn requires missionId in this version')
638
+ }
639
+ return withLock(this.paths, async () => {
640
+ const state = await this.load()
641
+ const mission = state.missions.find((entry) => entry.id === missionId)
642
+ if (!mission) fail(`unknown mission "${missionId}"`)
643
+ if (mission.worktree) {
644
+ await this.assertWorktree(mission.worktree)
645
+ return { mission, worktree: mission.worktree, created: false }
646
+ }
647
+
648
+ const baseCommit = await revParse(this.root, state.base)
649
+ const branch = `tower/${mission.id.toLowerCase()}-${slugify(mission.title)}`
650
+ const root = input.worktreeRoot
651
+ ? path.resolve(input.worktreeRoot)
652
+ : path.join(path.dirname(this.root), '.dsh-tower-worktrees', shortHash(this.commonDir))
653
+ if (!path.isAbsolute(root)) fail('worktreeRoot must be an absolute path')
654
+ this.assertOutside(root)
655
+ await ensureDir(root)
656
+
657
+ const wtPath = path.join(root, mission.id)
658
+ if (await exists(wtPath)) fail(`worktree path already exists: ${wtPath}`)
659
+ if (await branchExists(this.root, branch)) fail(`branch already exists: ${branch}`)
660
+
661
+ await addWorktree(this.root, { path: wtPath, branch, commit: baseCommit })
662
+ const now = Date.now()
663
+ const worktree = { path: wtPath, branch, baseCommit, createdAt: now }
664
+ mission.worktree = worktree
665
+ mission.baseCommit = baseCommit
666
+ mission.updatedAt = now
667
+ state.revision += 1
668
+ state.updatedAt = now
669
+
670
+ validateState(state, this.paths.state)
671
+ await writeJsonAtomic(this.paths.state, state)
672
+ await appendJsonl(this.paths.activity, {
673
+ at: now,
674
+ type: 'worktree',
675
+ missionId,
676
+ text: `${branch} at ${wtPath}`,
677
+ })
678
+ return { mission, worktree, created: true }
679
+ })
680
+ }
681
+
682
+ async missionContext(missionId) {
683
+ const state = await this.load()
684
+ const mission = state.missions.find((entry) => entry.id === missionId)
685
+ if (!mission) fail(`unknown mission "${missionId}"`)
686
+ const byId = new Map(state.missions.map((entry) => [entry.id, entry]))
687
+ return {
688
+ base: state.base,
689
+ mission: fullMission(mission),
690
+ deps: (mission.deps ?? []).map((id) => {
691
+ const dep = byId.get(id)
692
+ return dep ? { id, title: dep.title, status: dep.status } : { id, title: null, status: 'unknown' }
693
+ }),
694
+ }
695
+ }
696
+
697
+ async recordSpawn(input) {
698
+ return withLock(this.paths, async () => {
699
+ const state = await this.load()
700
+ const mission = state.missions.find((entry) => entry.id === input.missionId)
701
+ if (!mission) fail(`unknown mission "${input.missionId}"`)
702
+ if (!Array.isArray(state.roster)) state.roster = []
703
+ if (state.roster.some((entry) => entry.name === input.name)) {
704
+ fail(`roster name already used: ${input.name}`)
705
+ }
706
+ if (state.roster.some((entry) => entry.agentId === input.agentId)) {
707
+ fail(`agent ${input.agentId} is already in the roster`)
708
+ }
709
+ const now = Date.now()
710
+ const entry = {
711
+ name: input.name,
712
+ role: input.role,
713
+ agentId: input.agentId,
714
+ sessionId: input.sessionId ?? input.agentId,
715
+ parentSessionId: input.parentSessionId,
716
+ missionId: input.missionId,
717
+ cwd: input.cwd ?? null,
718
+ branch: input.branch ?? null,
719
+ state: 'active',
720
+ spawnedAt: now,
721
+ }
722
+ state.roster.push(entry)
723
+ if (input.role === 'worker') {
724
+ mission.owner = input.name
725
+ if (mission.status === 'planned') mission.status = 'active'
726
+ }
727
+ mission.updatedAt = now
728
+ state.revision += 1
729
+ state.updatedAt = now
730
+
731
+ validateState(state, this.paths.state)
732
+ await writeJsonAtomic(this.paths.state, state)
733
+ await appendJsonl(this.paths.activity, {
734
+ at: now,
735
+ type: 'spawn',
736
+ missionId: input.missionId,
737
+ text: `${input.role} ${input.name} (${input.agentId})`,
738
+ })
739
+ return entry
740
+ })
741
+ }
742
+
743
+ async rosterView() {
744
+ const state = await this.load()
745
+ return {
746
+ revision: state.revision,
747
+ roster: (state.roster ?? []).map((entry) => ({ ...entry })),
748
+ missions: state.missions.map((mission) => ({
749
+ id: mission.id,
750
+ status: mission.status,
751
+ owner: mission.owner ?? null,
752
+ worktree: mission.worktree
753
+ ? {
754
+ path: mission.worktree.path,
755
+ branch: mission.worktree.branch,
756
+ baseCommit: mission.worktree.baseCommit,
757
+ }
758
+ : null,
759
+ })),
760
+ }
761
+ }
762
+
763
+ async markRetired(agentIds) {
764
+ if (!Array.isArray(agentIds) || agentIds.length === 0) return { retired: [] }
765
+ return withLock(this.paths, async () => {
766
+ const state = await this.load()
767
+ const retired = []
768
+ const now = Date.now()
769
+ for (const entry of state.roster ?? []) {
770
+ if (entry.state !== 'retired' && agentIds.includes(entry.agentId)) {
771
+ entry.state = 'retired'
772
+ entry.retiredAt = now
773
+ retired.push(entry.agentId)
774
+ }
775
+ }
776
+ if (retired.length > 0) {
777
+ state.revision += 1
778
+ state.updatedAt = now
779
+ validateState(state, this.paths.state)
780
+ await writeJsonAtomic(this.paths.state, state)
781
+ await appendJsonl(this.paths.activity, {
782
+ at: now,
783
+ type: 'adopt',
784
+ text: `retired ${retired.join(', ')}`,
785
+ })
786
+ }
787
+ return { retired }
788
+ })
789
+ }
790
+
791
+ unreadFor(state, name) {
792
+ return (state.messages ?? []).filter((message) => {
793
+ if (message.from === name) return false
794
+ if (message.to !== name && message.to !== 'all') return false
795
+ return !(message.readBy ?? []).includes(name)
796
+ })
797
+ }
798
+
799
+ async recordMessage(input) {
800
+ return withLock(this.paths, async () => {
801
+ const state = await this.load()
802
+ if (!Array.isArray(state.messages)) state.messages = []
803
+ const names = new Set((state.roster ?? []).map((entry) => entry.name))
804
+ names.add('tower')
805
+ if (input.to !== 'all' && !names.has(input.to)) {
806
+ fail(`unknown message recipient "${input.to}" (known: ${[...names].join(', ')}, all)`)
807
+ }
808
+ if (input.to === input.from) fail('refusing to send a message to yourself')
809
+ const now = Date.now()
810
+ const seq = (state.messageSeq ?? 0) + 1
811
+ state.messageSeq = seq
812
+ const message = {
813
+ id: `msg-${seq}`,
814
+ seq,
815
+ from: input.from,
816
+ to: input.to,
817
+ subject: input.subject,
818
+ body: input.body,
819
+ scope: input.scope ?? null,
820
+ at: now,
821
+ readBy: [],
822
+ delivery: [],
823
+ }
824
+ state.messages.push(message)
825
+ state.revision += 1
826
+ state.updatedAt = now
827
+
828
+ validateState(state, this.paths.state)
829
+ await writeJsonAtomic(this.paths.state, state)
830
+ await appendJsonl(this.paths.activity, {
831
+ at: now,
832
+ type: 'message',
833
+ text: `${input.from} -> ${input.to}: ${input.subject}`,
834
+ })
835
+ return { ...message, readBy: [], delivery: [] }
836
+ })
837
+ }
838
+
839
+ async recordDelivery(messageId, results) {
840
+ return withLock(this.paths, async () => {
841
+ const state = await this.load()
842
+ const message = (state.messages ?? []).find((entry) => entry.id === messageId)
843
+ if (!message) fail(`unknown message "${messageId}"`)
844
+ message.delivery = [...(message.delivery ?? []), ...results]
845
+ state.revision += 1
846
+ state.updatedAt = Date.now()
847
+ await writeJsonAtomic(this.paths.state, state)
848
+ return message.delivery
849
+ })
850
+ }
851
+
852
+ async inbox(input) {
853
+ const reader = input.reader
854
+ return withLock(this.paths, async () => {
855
+ const state = await this.load()
856
+ const limit = Math.max(1, Math.min(100, input.limit ?? 20))
857
+ const includeRead = input.includeRead === true
858
+ const visible = [...(state.messages ?? [])]
859
+ .reverse()
860
+ .filter((message) => (message.to === reader || message.to === 'all') && message.from !== reader)
861
+ const unread = visible.filter((message) => !(message.readBy ?? []).includes(reader))
862
+ const page = (includeRead ? visible : unread).slice(0, limit)
863
+
864
+ let changed = false
865
+ for (const message of page) {
866
+ if (!(message.readBy ?? []).includes(reader)) {
867
+ message.readBy = [...(message.readBy ?? []), reader]
868
+ changed = true
869
+ }
870
+ }
871
+ const unreadRemaining = visible.filter((message) => !(message.readBy ?? []).includes(reader)).length
872
+ if (changed) {
873
+ state.revision += 1
874
+ state.updatedAt = Date.now()
875
+ validateState(state, this.paths.state)
876
+ await writeJsonAtomic(this.paths.state, state)
877
+ }
878
+ return {
879
+ reader,
880
+ messages: page.map((message) => ({
881
+ id: message.id,
882
+ from: message.from,
883
+ to: message.to,
884
+ subject: message.subject,
885
+ body: message.body,
886
+ scope: message.scope ?? null,
887
+ at: message.at,
888
+ })),
889
+ pageSize: page.length,
890
+ unreadRemaining,
891
+ }
892
+ })
893
+ }
894
+
895
+ async complete(input) {
896
+ return withLock(this.paths, async () => {
897
+ const state = await this.load()
898
+ const mission = state.missions.find((entry) => entry.id === input.missionId)
899
+ if (!mission) fail(`unknown mission "${input.missionId}"`)
900
+ const worker = (state.roster ?? []).find((entry) => entry.agentId === input.agentId)
901
+ if (!worker || worker.missionId !== mission.id) {
902
+ fail(`agent ${input.agentId} is not assigned to mission ${mission.id}`)
903
+ }
904
+ if (worker.role !== 'worker') fail(`agent ${worker.name} is a ${worker.role}, not a worker`)
905
+ if (mission.status === 'completed') fail(`mission ${mission.id} is already completed`)
906
+ if (!['active', 'planned'].includes(mission.status)) {
907
+ fail(`mission ${mission.id} is ${mission.status}; it cannot be completed from that state`)
908
+ }
909
+ if (typeof input.report !== 'string' || input.report.trim().length === 0) {
910
+ fail('tower_complete requires a non-empty report')
911
+ }
912
+ const openTasks = mission.tasks.filter((task) => task.status === 'open')
913
+ if (openTasks.length > 0) {
914
+ fail(
915
+ `mission ${mission.id} still has ${openTasks.length} open task(s): ${openTasks
916
+ .map((task) => task.text)
917
+ .join('; ')}`,
918
+ )
919
+ }
920
+ if ((mission.blockers ?? []).length > 0) {
921
+ fail(`mission ${mission.id} has unresolved blockers: ${mission.blockers.join('; ')}`)
922
+ }
923
+ if (!mission.worktree) fail(`mission ${mission.id} has no worktree`)
924
+ await this.assertWorktree(mission.worktree)
925
+ const commits = await countCommits(mission.worktree.path, mission.worktree.baseCommit)
926
+ if (commits < 1) {
927
+ fail(`mission branch has no commits since ${String(mission.worktree.baseCommit).slice(0, 12)}`)
928
+ }
929
+ const unread = this.unreadFor(state, worker.name)
930
+ if (unread.length > 0) {
931
+ fail(
932
+ `mission ${mission.id} cannot complete with ${unread.length} unread inbox message(s) for ${worker.name}; call tower_inbox until unread is 0, incorporate them, then retry`,
933
+ )
934
+ }
935
+
936
+ const now = Date.now()
937
+ mission.status = 'completed'
938
+ mission.completionReport = { report: input.report.trim(), by: worker.name, at: now }
939
+ mission.updatedAt = now
940
+ state.revision += 1
941
+ state.updatedAt = now
942
+
943
+ validateState(state, this.paths.state)
944
+ await writeJsonAtomic(this.paths.state, state)
945
+ await appendJsonl(this.paths.activity, {
946
+ at: now,
947
+ type: 'complete',
948
+ missionId: mission.id,
949
+ text: `${worker.name} reported completion (${commits} commit(s))`,
950
+ })
951
+ return { mission: fullMission(mission), commits, unread: 0 }
952
+ })
953
+ }
954
+
955
+ async addFinding(input) {
956
+ return withLock(this.paths, async () => {
957
+ const state = await this.load()
958
+ if (!Array.isArray(state.findings)) state.findings = []
959
+ if (!FINDING_TYPES.includes(input.type)) {
960
+ fail(`finding type must be one of ${FINDING_TYPES.join('|')}`)
961
+ }
962
+ const title = String(input.title ?? '').trim()
963
+ if (!title) fail('finding title is required')
964
+ const summary = String(input.summary ?? '').trim()
965
+ if (!summary) fail('finding summary is required')
966
+ const details = String(input.details ?? '').trim()
967
+ if (!details) fail('finding details are required')
968
+ const suggestedFix = String(input.suggested_fix ?? '').trim()
969
+ if (!suggestedFix) fail('finding suggested_fix is required')
970
+ const severity = input.severity ?? null
971
+ if (severity !== null && !FINDING_SEVERITIES.includes(severity)) {
972
+ fail(`finding severity must be one of ${FINDING_SEVERITIES.join('|')}`)
973
+ }
974
+ let mission = null
975
+ if (input.missionId !== undefined && input.missionId !== null && input.missionId !== '') {
976
+ mission = state.missions.find((entry) => entry.id === input.missionId)
977
+ if (!mission) fail(`unknown mission "${input.missionId}"`)
978
+ }
979
+ const now = Date.now()
980
+ const seq = (state.findingSeq ?? 0) + 1
981
+ state.findingSeq = seq
982
+ const finding = {
983
+ id: `F${seq}`,
984
+ seq,
985
+ type: input.type,
986
+ title,
987
+ severity,
988
+ summary,
989
+ location: typeof input.location === 'string' && input.location.trim() ? input.location.trim() : null,
990
+ details,
991
+ suggested_fix: suggestedFix,
992
+ missionId: mission ? mission.id : null,
993
+ branch: mission && mission.worktree ? mission.worktree.branch : null,
994
+ reportedBy: input.reportedBy,
995
+ at: now,
996
+ status: 'open',
997
+ }
998
+ state.findings.push(finding)
999
+ state.revision += 1
1000
+ state.updatedAt = now
1001
+
1002
+ validateState(state, this.paths.state)
1003
+ await writeJsonAtomic(this.paths.state, state)
1004
+ await appendJsonl(this.paths.activity, {
1005
+ at: now,
1006
+ type: 'finding',
1007
+ missionId: finding.missionId,
1008
+ text: `${finding.id} ${finding.type}: ${finding.title}`,
1009
+ })
1010
+ return finding
1011
+ })
1012
+ }
1013
+
1014
+ async submitReview(input) {
1015
+ return withLock(this.paths, async () => {
1016
+ const state = await this.load()
1017
+ const mission = state.missions.find((entry) => entry.id === input.missionId)
1018
+ if (!mission) fail(`unknown mission "${input.missionId}"`)
1019
+ if (!mission.worktree) fail(`mission ${mission.id} has no worktree to review`)
1020
+
1021
+ const caller = (state.roster ?? []).find((entry) => entry.agentId === input.agentId)
1022
+ let reviewerName
1023
+ let reviewerRole
1024
+ if (caller) {
1025
+ if (caller.role !== 'reviewer') {
1026
+ fail(`agent ${caller.name} is a ${caller.role}; only an assigned reviewer or the tower (break-glass) may review`)
1027
+ }
1028
+ if (caller.missionId !== mission.id) {
1029
+ fail(`reviewer ${caller.name} was not assigned to mission ${mission.id}`)
1030
+ }
1031
+ if (mission.owner && caller.name === mission.owner) fail('the reviewer must differ from the worker')
1032
+ reviewerName = caller.name
1033
+ reviewerRole = 'reviewer'
1034
+ } else {
1035
+ if (typeof input.breakGlassReason !== 'string' || input.breakGlassReason.trim().length === 0) {
1036
+ fail('a tower-submitted review is break-glass and requires a non-empty breakGlassReason')
1037
+ }
1038
+ reviewerName = 'tower'
1039
+ reviewerRole = 'tower'
1040
+ }
1041
+
1042
+ if (mission.status !== 'completed') {
1043
+ fail(`mission ${mission.id} is ${mission.status}; only a completed mission (awaiting review) can be reviewed`)
1044
+ }
1045
+ if (!REVIEW_STATUS_RE.test(String(input.status ?? ''))) {
1046
+ fail('status must be "clean", "p1-Nitems", or "p2-Nitems"')
1047
+ }
1048
+ if (!MERGE_VERDICTS.includes(input.merge)) {
1049
+ fail(`merge verdict must be one of ${MERGE_VERDICTS.join('|')}`)
1050
+ }
1051
+ const findingsText = String(input.findings ?? '').trim()
1052
+ if (!findingsText) fail('findings text is required; write "none" for a clean verdict')
1053
+ if (input.status === 'clean' && findingsText.toLowerCase() !== 'none') {
1054
+ fail('a clean verdict requires findings text "none"')
1055
+ }
1056
+ if (input.status !== 'clean' && findingsText.toLowerCase() === 'none') {
1057
+ fail('a non-clean verdict must describe its findings')
1058
+ }
1059
+ const decision = String(input.decision ?? '').trim()
1060
+ if (!decision) fail('decision (the reasoning behind the verdict) is required')
1061
+ let checks = []
1062
+ if (input.checks !== undefined) {
1063
+ if (!Array.isArray(input.checks)) fail('checks must be an array of strings')
1064
+ checks = input.checks.map((entry) => String(entry))
1065
+ }
1066
+
1067
+ await this.assertWorktree(mission.worktree)
1068
+ const tip = await revParse(mission.worktree.path, 'HEAD')
1069
+ const branch = mission.worktree.branch
1070
+ const prior = (state.reviews ?? []).filter((review) => review.branch === branch)
1071
+ const reviewerRounds = prior.filter((review) => review.reviewer === reviewerName).length
1072
+ if (reviewerRounds >= MAX_REVIEW_ROUNDS) {
1073
+ fail(
1074
+ `reviewer ${reviewerName} reached the ${MAX_REVIEW_ROUNDS}-round cap for ${branch}; continue with a different reviewer`,
1075
+ )
1076
+ }
1077
+ const round = prior.length === 0 ? 1 : Math.max(...prior.map((review) => review.round)) + 1
1078
+
1079
+ const now = Date.now()
1080
+ const seq = (state.reviewSeq ?? 0) + 1
1081
+ state.reviewSeq = seq
1082
+ const review = {
1083
+ id: `R${seq}`,
1084
+ seq,
1085
+ missionId: mission.id,
1086
+ branch,
1087
+ reviewedCommit: tip,
1088
+ status: input.status,
1089
+ mergeVerdict: input.merge,
1090
+ findings: findingsText,
1091
+ checks,
1092
+ decision,
1093
+ reviewer: reviewerName,
1094
+ reviewerRole,
1095
+ round,
1096
+ at: now,
1097
+ ...(reviewerRole === 'tower' ? { breakGlassReason: input.breakGlassReason.trim() } : {}),
1098
+ }
1099
+ if (!Array.isArray(state.reviews)) state.reviews = []
1100
+ state.reviews.push(review)
1101
+
1102
+ if (input.status !== 'clean') {
1103
+ mission.status = 'active'
1104
+ mission.notes.push(
1105
+ `review round ${round} by ${reviewerName}: ${input.status} (${input.merge}) — returned to active`,
1106
+ )
1107
+ } else {
1108
+ mission.notes.push(`review round ${round} by ${reviewerName}: clean (${input.merge})`)
1109
+ }
1110
+ mission.updatedAt = now
1111
+ state.revision += 1
1112
+ state.updatedAt = now
1113
+
1114
+ validateState(state, this.paths.state)
1115
+ await writeJsonAtomic(this.paths.state, state)
1116
+ await appendJsonl(this.paths.activity, {
1117
+ at: now,
1118
+ type: 'review',
1119
+ missionId: mission.id,
1120
+ text: `round ${round} ${reviewerName}: ${input.status} / ${input.merge} @ ${tip.slice(0, 12)}`,
1121
+ })
1122
+ return {
1123
+ review,
1124
+ branchTip: tip,
1125
+ missionStatus: mission.status,
1126
+ round,
1127
+ reviewerRounds: reviewerRounds + 1,
1128
+ }
1129
+ })
1130
+ }
1131
+
1132
+ async enrichedMissions(state) {
1133
+ const out = []
1134
+ for (const mission of state.missions) {
1135
+ const summary = missionSummary(mission)
1136
+ const branch = mission.worktree ? mission.worktree.branch : null
1137
+ const reviews = branch ? (state.reviews ?? []).filter((review) => review.branch === branch) : []
1138
+ const latest = reviews.length > 0 ? reviews.reduce((a, b) => (a.round >= b.round ? a : b)) : null
1139
+ let tipMoved = false
1140
+ if (latest && mission.worktree && (await exists(mission.worktree.path))) {
1141
+ try {
1142
+ const tip = await revParse(mission.worktree.path, 'HEAD')
1143
+ tipMoved = tip !== latest.reviewedCommit
1144
+ } catch {
1145
+ tipMoved = false
1146
+ }
1147
+ }
1148
+ out.push({
1149
+ ...summary,
1150
+ review: latest
1151
+ ? {
1152
+ id: latest.id,
1153
+ round: latest.round,
1154
+ status: latest.status,
1155
+ mergeVerdict: latest.mergeVerdict,
1156
+ reviewer: latest.reviewer,
1157
+ reviewerRole: latest.reviewerRole,
1158
+ reviewedCommit: latest.reviewedCommit,
1159
+ at: latest.at,
1160
+ }
1161
+ : null,
1162
+ tipMoved,
1163
+ })
1164
+ }
1165
+ return out
1166
+ }
1167
+
1168
+ rebaseWaived(mission, review) {
1169
+ const rebase = mission.rebase
1170
+ if (!rebase) return false
1171
+ return review.at <= rebase.at && review.reviewedCommit === rebase.oldTip
1172
+ }
1173
+
1174
+ async evaluateGate(input) {
1175
+ const state = await this.load()
1176
+ const mission = state.missions.find((entry) => entry.id === input.missionId)
1177
+ if (!mission) {
1178
+ return { ok: false, blockers: [{ code: 'mission-missing', detail: `unknown mission "${input.missionId}"` }] }
1179
+ }
1180
+ const activity = input.activity ?? {}
1181
+ const blockers = []
1182
+ const push = (code, detail) => blockers.push({ code, detail })
1183
+
1184
+ if (TERMINAL.has(mission.status)) {
1185
+ push(
1186
+ 'branch-owned-by-closed-missions',
1187
+ `mission ${mission.id} is ${mission.status}; a merge never flips a closed mission — re-plan the work under a new title`,
1188
+ )
1189
+ }
1190
+ if (mission.status !== 'completed') {
1191
+ push('mission-not-completed', `mission ${mission.id} is ${mission.status}; completion (awaiting review) is required`)
1192
+ }
1193
+ const openTasks = mission.tasks.filter((task) => task.status === 'open')
1194
+ if (openTasks.length > 0) push('tasks-open', `${openTasks.length} open task(s): ${openTasks.map((task) => task.text).join('; ')}`)
1195
+ if ((mission.blockers ?? []).length > 0) push('blockers-present', mission.blockers.join('; '))
1196
+
1197
+ const worktree = mission.worktree ?? null
1198
+ let branchTip = null
1199
+ let baseTip = null
1200
+ let changedFiles = []
1201
+ if (!worktree) {
1202
+ push('branch-missing', `mission ${mission.id} has no worktree or branch`)
1203
+ } else {
1204
+ try {
1205
+ await this.assertWorktree(worktree)
1206
+ branchTip = await revParse(worktree.path, 'HEAD')
1207
+ baseTip = await revParse(this.root, state.base)
1208
+ const mergeBase = (await git(worktree.path, ['merge-base', baseTip, branchTip])).trim()
1209
+ changedFiles = (await git(worktree.path, ['diff', '--name-only', `${mergeBase}..${branchTip}`]))
1210
+ .split('\n')
1211
+ .filter(Boolean)
1212
+ if (!(await isAncestor(this.root, baseTip, branchTip))) {
1213
+ push(
1214
+ 'stale-base',
1215
+ `${worktree.branch} does not contain base "${state.base}" tip ${baseTip.slice(0, 12)}; run tower_rebase first`,
1216
+ )
1217
+ }
1218
+ if (mission.kind === 'survey' && changedFiles.length > 0) {
1219
+ push('read-only-survey', `survey ${mission.id} is read-only but ${changedFiles.length} file(s) changed: ${changedFiles.slice(0, 5).join(', ')}`)
1220
+ }
1221
+ if (mission.kind !== 'survey') {
1222
+ const outOfScope = changedFiles.filter((file) => !fileInScope(mission.scope, file))
1223
+ if (outOfScope.length > 0) {
1224
+ push('out-of-scope', `changed files outside scope (${mission.scope.join(', ')}): ${outOfScope.slice(0, 8).join(', ')}`)
1225
+ }
1226
+ }
1227
+ const dirty = (await git(this.root, ['status', '--porcelain']))
1228
+ .split('\n')
1229
+ .filter(Boolean)
1230
+ .map((line) => line.slice(3).trim())
1231
+ const wouldOverwrite = changedFiles.filter((file) => dirty.includes(file))
1232
+ if (wouldOverwrite.length > 0) {
1233
+ push('base-dirty', `main checkout has uncommitted changes this merge would overwrite: ${wouldOverwrite.slice(0, 8).join(', ')}`)
1234
+ }
1235
+ } catch (error) {
1236
+ push('branch-missing', String(error?.message ?? error))
1237
+ }
1238
+ }
1239
+
1240
+ for (const depId of mission.deps ?? []) {
1241
+ const dep = state.missions.find((entry) => entry.id === depId)
1242
+ if (!dep || !['merged', 'abandoned'].includes(dep.status)) {
1243
+ push('deps-unmerged', `${depId} is ${dep ? dep.status : 'missing'}`)
1244
+ }
1245
+ }
1246
+
1247
+ const branch = worktree ? worktree.branch : null
1248
+ const reviews = branch ? (state.reviews ?? []).filter((review) => review.branch === branch) : []
1249
+ const latest = reviews.length > 0 ? reviews.reduce((a, b) => (a.round >= b.round ? a : b)) : null
1250
+ if (!latest) {
1251
+ push('no-review', `branch ${branch ?? '(none)'} has no review; assign a reviewer first`)
1252
+ } else {
1253
+ const waived = this.rebaseWaived(mission, latest)
1254
+ if (latest.missionId !== mission.id) {
1255
+ push('review-mission-mismatch', `latest review belongs to mission ${latest.missionId}`)
1256
+ }
1257
+ if (latest.status !== 'clean') push('not-clean', `latest review round ${latest.round} is "${latest.status}"`)
1258
+ if (latest.mergeVerdict === 'hold') {
1259
+ push('review-hold', `latest review recommends hold — a later clean review must supersede it`)
1260
+ } else if (latest.status === 'clean' && latest.mergeVerdict !== 'merge') {
1261
+ push('review-not-approved', `latest clean review recommends "${latest.mergeVerdict}" — only "merge" approves`)
1262
+ }
1263
+ if (branchTip && latest.reviewedCommit !== branchTip && !waived) {
1264
+ push('tip-moved', `reviewed ${latest.reviewedCommit.slice(0, 7)} but tip is ${branchTip.slice(0, 7)}; re-review required`)
1265
+ }
1266
+ }
1267
+
1268
+ for (const entry of (state.roster ?? []).filter((row) => row.missionId === mission.id && row.state !== 'retired')) {
1269
+ if (activity[entry.agentId] === 'running') push('worker-busy', `agent ${entry.name} is still running`)
1270
+ }
1271
+
1272
+ const checkoutBranch = await currentBranch(this.root)
1273
+ if (checkoutBranch !== state.base) {
1274
+ push('base-wrong-branch', `main checkout is on ${checkoutBranch ?? 'detached HEAD'}, expected "${state.base}"`)
1275
+ }
1276
+
1277
+ return {
1278
+ ok: blockers.length === 0,
1279
+ blockers,
1280
+ mission: fullMission(mission),
1281
+ worktree,
1282
+ branchTip,
1283
+ baseTip,
1284
+ changedFiles,
1285
+ review: latest,
1286
+ }
1287
+ }
1288
+
1289
+ async merge(input) {
1290
+ return withLock(this.paths, async () => {
1291
+ const gate = await this.evaluateGate(input)
1292
+ if (!gate.ok) return { ok: false, blockers: gate.blockers, missionId: input.missionId }
1293
+ const state = await this.load()
1294
+ const mission = state.missions.find((entry) => entry.id === input.missionId)
1295
+ const worktree = mission.worktree
1296
+ const baseTipBefore = await revParse(this.root, state.base)
1297
+ const branchTip = await revParse(worktree.path, 'HEAD')
1298
+
1299
+ try {
1300
+ await git(this.root, ['merge', '--no-ff', worktree.branch, '-m', `tower: merge ${mission.id} — ${mission.title}`])
1301
+ } catch (error) {
1302
+ await git(this.root, ['merge', '--abort']).catch(() => {})
1303
+ const now = Date.now()
1304
+ mission.status = 'blocked'
1305
+ mission.blockers.push(`merge conflict: ${String(error?.message ?? error).slice(0, 240)}`)
1306
+ mission.updatedAt = now
1307
+ state.revision += 1
1308
+ state.updatedAt = now
1309
+ await writeJsonAtomic(this.paths.state, state)
1310
+ await appendJsonl(this.paths.activity, { at: now, type: 'merge', missionId: mission.id, text: 'conflict' })
1311
+ return { ok: false, blockers: [{ code: 'merge-conflict', detail: String(error?.message ?? error) }] }
1312
+ }
1313
+
1314
+ const newTip = await revParse(this.root, 'HEAD')
1315
+ const parentLine = await git(this.root, ['rev-list', '--parents', '-n', '1', 'HEAD'])
1316
+ const parents = parentLine.trim().split(/\s+/).slice(1)
1317
+ if (parents.length !== 2 || parents[0] !== baseTipBefore || parents[1] !== branchTip) {
1318
+ return {
1319
+ ok: false,
1320
+ blockers: [
1321
+ {
1322
+ code: 'merge-shape',
1323
+ detail: `unexpected merge parents [${parents.join(', ')}], expected [${baseTipBefore}, ${branchTip}]`,
1324
+ },
1325
+ ],
1326
+ }
1327
+ }
1328
+
1329
+ const now = Date.now()
1330
+ mission.status = 'merged'
1331
+ mission.mergedAt = now
1332
+ mission.mergedCommit = newTip
1333
+ mission.updatedAt = now
1334
+ mission.notes.push(`merged ${branchTip.slice(0, 7)} into ${state.base} as ${newTip.slice(0, 7)}`)
1335
+ state.revision += 1
1336
+ state.updatedAt = now
1337
+ validateState(state, this.paths.state)
1338
+ await writeJsonAtomic(this.paths.state, state)
1339
+ await appendJsonl(this.paths.activity, {
1340
+ at: now,
1341
+ type: 'merge',
1342
+ missionId: mission.id,
1343
+ text: `${branchTip.slice(0, 7)} -> ${newTip.slice(0, 7)} on ${state.base}`,
1344
+ })
1345
+ return { ok: true, mergedCommit: newTip, baseTip: baseTipBefore, branchTip, parents }
1346
+ })
1347
+ }
1348
+
1349
+ async rebase(input) {
1350
+ return withLock(this.paths, async () => {
1351
+ const state = await this.load()
1352
+ const mission = state.missions.find((entry) => entry.id === input.missionId)
1353
+ if (!mission) fail(`unknown mission "${input.missionId}"`)
1354
+ if (!mission.worktree) fail(`mission ${mission.id} has no worktree to rebase`)
1355
+ const activity = input.activity ?? {}
1356
+ for (const entry of (state.roster ?? []).filter((row) => row.missionId === mission.id && row.state !== 'retired')) {
1357
+ if (activity[entry.agentId] === 'running') {
1358
+ return { ok: false, blockers: [{ code: 'worker-busy', detail: `agent ${entry.name} is running; rebase refused` }] }
1359
+ }
1360
+ }
1361
+ await this.assertWorktree(mission.worktree)
1362
+ if (!(await isClean(mission.worktree.path))) {
1363
+ return { ok: false, blockers: [{ code: 'worktree-dirty', detail: `${mission.worktree.path} has uncommitted changes` }] }
1364
+ }
1365
+ const oldTip = await revParse(mission.worktree.path, 'HEAD')
1366
+ const baseTip = await revParse(this.root, state.base)
1367
+ if (await isAncestor(this.root, baseTip, oldTip)) {
1368
+ return { ok: true, alreadyUpToDate: true, oldTip, newTip: oldTip, baseTip }
1369
+ }
1370
+ const now = Date.now()
1371
+ try {
1372
+ await git(mission.worktree.path, ['rebase', baseTip])
1373
+ } catch (error) {
1374
+ await git(mission.worktree.path, ['rebase', '--abort']).catch(() => {})
1375
+ mission.status = 'blocked'
1376
+ mission.blockers.push(`rebase conflict onto ${state.base} @ ${baseTip.slice(0, 12)}`)
1377
+ mission.updatedAt = now
1378
+ state.revision += 1
1379
+ state.updatedAt = now
1380
+ await writeJsonAtomic(this.paths.state, state)
1381
+ await appendJsonl(this.paths.activity, { at: now, type: 'rebase', missionId: mission.id, text: 'conflict' })
1382
+ return { ok: false, blockers: [{ code: 'rebase-conflict', detail: String(error?.message ?? error) }] }
1383
+ }
1384
+ const newTip = await revParse(mission.worktree.path, 'HEAD')
1385
+ mission.rebase = { at: now, oldTip, newTip, baseTip }
1386
+ if (mission.status === 'blocked') mission.status = 'active'
1387
+ mission.notes.push(
1388
+ `rebased ${oldTip.slice(0, 7)} -> ${newTip.slice(0, 7)} onto ${baseTip.slice(0, 7)}; conflict-free rebase waives re-review`,
1389
+ )
1390
+ mission.updatedAt = now
1391
+ state.revision += 1
1392
+ state.updatedAt = now
1393
+ validateState(state, this.paths.state)
1394
+ await writeJsonAtomic(this.paths.state, state)
1395
+ await appendJsonl(this.paths.activity, {
1396
+ at: now,
1397
+ type: 'rebase',
1398
+ missionId: mission.id,
1399
+ text: `${oldTip.slice(0, 7)} -> ${newTip.slice(0, 7)} onto ${baseTip.slice(0, 7)}`,
1400
+ })
1401
+ return { ok: true, oldTip, newTip, baseTip, reviewWaived: true }
1402
+ })
1403
+ }
1404
+
1405
+ async teardown(input) {
1406
+ return withLock(this.paths, async () => {
1407
+ const state = await this.load()
1408
+ const activity = input.activity ?? {}
1409
+ const exclude = new Set(input.exclude ?? [])
1410
+ const decisions = []
1411
+ const removed = []
1412
+ const now = Date.now()
1413
+
1414
+ for (const mission of state.missions) {
1415
+ if (!mission.worktree || mission.worktreeRemovedAt) continue
1416
+ if (exclude.has(mission.id)) {
1417
+ decisions.push({ missionId: mission.id, action: 'keep', reason: 'excluded' })
1418
+ continue
1419
+ }
1420
+ const live = (state.roster ?? []).some(
1421
+ (entry) => entry.missionId === mission.id && entry.state !== 'retired' && activity[entry.agentId] === 'running',
1422
+ )
1423
+ if (live) {
1424
+ decisions.push({ missionId: mission.id, action: 'keep', reason: 'live agent' })
1425
+ continue
1426
+ }
1427
+ if (!['merged', 'abandoned'].includes(mission.status)) {
1428
+ decisions.push({ missionId: mission.id, action: 'keep', reason: `mission is ${mission.status}` })
1429
+ continue
1430
+ }
1431
+ let dirty = true
1432
+ try {
1433
+ dirty = !(await isClean(mission.worktree.path))
1434
+ } catch {
1435
+ dirty = true
1436
+ }
1437
+ if (dirty && input.force !== true) {
1438
+ decisions.push({ missionId: mission.id, action: 'keep', reason: 'uncommitted changes' })
1439
+ continue
1440
+ }
1441
+ if (input.dryRun === true) {
1442
+ decisions.push({ missionId: mission.id, action: 'remove', reason: 'eligible', forced: dirty })
1443
+ continue
1444
+ }
1445
+ try {
1446
+ await git(this.root, ['worktree', 'remove', ...(dirty ? ['--force'] : []), mission.worktree.path])
1447
+ } catch (error) {
1448
+ decisions.push({ missionId: mission.id, action: 'keep', reason: `remove failed: ${String(error?.message ?? error)}` })
1449
+ continue
1450
+ }
1451
+ await git(this.root, ['branch', '-d', mission.worktree.branch]).catch(() => {})
1452
+ mission.worktreeRemovedAt = now
1453
+ mission.updatedAt = now
1454
+ removed.push(mission.id)
1455
+ decisions.push({ missionId: mission.id, action: 'removed', branch: mission.worktree.branch })
1456
+ await appendJsonl(this.paths.activity, {
1457
+ at: now,
1458
+ type: 'teardown',
1459
+ missionId: mission.id,
1460
+ text: mission.worktree.branch,
1461
+ })
1462
+ }
1463
+
1464
+ if (!input.dryRun && removed.length > 0) {
1465
+ state.revision += 1
1466
+ state.updatedAt = now
1467
+ validateState(state, this.paths.state)
1468
+ await writeJsonAtomic(this.paths.state, state)
1469
+ }
1470
+ return { ok: true, dryRun: input.dryRun === true, removed, decisions }
1471
+ })
1472
+ }
1473
+
1474
+ async status() {
1475
+ const state = await this.load()
1476
+ const activity = await readActivityTail(this.paths.activity, 12)
1477
+ const counts = {}
1478
+ for (const status of MISSION_STATUSES) counts[status] = 0
1479
+ for (const mission of state.missions) counts[mission.status] = (counts[mission.status] ?? 0) + 1
1480
+ const openTasks = state.missions.reduce((sum, mission) => sum + taskCounts(mission.tasks).open, 0)
1481
+ return {
1482
+ repoRoot: state.repoRoot,
1483
+ commonDir: state.commonDir,
1484
+ statePath: this.paths.state,
1485
+ base: state.base,
1486
+ revision: state.revision,
1487
+ counts,
1488
+ openTasks,
1489
+ roster: (state.roster ?? []).length,
1490
+ messages: (state.messages ?? []).length,
1491
+ unreadTower: this.unreadFor(state, 'tower').length,
1492
+ findings: (state.findings ?? []).length,
1493
+ reviews: (state.reviews ?? []).length,
1494
+ recentFindings: (state.findings ?? []).slice(-5).map((finding) => ({
1495
+ id: finding.id,
1496
+ type: finding.type,
1497
+ severity: finding.severity,
1498
+ title: finding.title,
1499
+ missionId: finding.missionId,
1500
+ reportedBy: finding.reportedBy,
1501
+ at: finding.at,
1502
+ })),
1503
+ missions: await this.enrichedMissions(state),
1504
+ activity,
1505
+ }
1506
+ }
1507
+ }