@xiangyixie/dsh-superagent 0.14.3 → 0.14.4

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.
@@ -0,0 +1,1705 @@
1
+ /**
2
+ * Long-term goals: one natural-language goal, several phases, each phase run by
3
+ * a fresh team of agents, more than one phase in flight, and a restart that
4
+ * continues where the last host died instead of starting over.
5
+ *
6
+ * This module is deliberately a thin layer above runs. A phase *is* a run: the
7
+ * planner, dependency graph, parallel workers, per-run budget, attention,
8
+ * artifacts and resume path all come from the existing engine. What is new here
9
+ * is the phase graph, the goal-level budget, the stall decisions, and the
10
+ * durable record that ties several runs to one goal.
11
+ *
12
+ * @module dsh-superagent/long-goal
13
+ */
14
+ import { randomUUID } from 'node:crypto'
15
+ import fsp from 'node:fs/promises'
16
+ import path from 'node:path'
17
+ import { normalizeGoalSpec } from './goal.js'
18
+ import { acquireFileLock } from './lock.js'
19
+ import { TERMINAL_STATUSES } from './store.js'
20
+
21
+ /** Phase statuses after which a phase will not change on its own. */
22
+ export const PHASE_TERMINAL = new Set(['completed', 'failed', 'skipped', 'cancelled'])
23
+
24
+ /** Goal statuses that still own work. */
25
+ export const GOAL_ACTIVE = new Set(['planning', 'running'])
26
+
27
+ /** Goal statuses a tick may advance. */
28
+ const GOAL_TICKABLE = new Set(['planning', 'running'])
29
+
30
+ export const MAX_PHASES = 8
31
+ export const DEFAULT_MAX_PARALLEL_PHASES = 2
32
+ export const DEFAULT_MAX_ATTEMPTS_PER_PHASE = 2
33
+ export const DEFAULT_MAX_ROUNDS_PER_PHASE = 3
34
+ export const DEFAULT_NO_PROGRESS_ROUNDS = 2
35
+ export const DEFAULT_STALL_AFTER_MINUTES = 180
36
+ export const DEFAULT_MAX_WALL_CLOCK_MINUTES = 1440
37
+ export const DEFAULT_PHASE_WALL_CLOCK_MINUTES = 120
38
+ export const DEFAULT_TICK_SECONDS = 5
39
+
40
+ const GOAL_ID_PATTERN = /^g-[0-9A-Za-z-]{6,64}$/
41
+ const MAX_EVENTS = 120
42
+ const MAX_DECISIONS = 40
43
+ const MAX_TEXT = 1200
44
+
45
+ function oneLine(value, maxChars = MAX_TEXT) {
46
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
47
+ if (!text) return ''
48
+ return [...text].slice(0, maxChars).join('')
49
+ }
50
+
51
+ function capText(value, maxChars) {
52
+ const text = String(value ?? '')
53
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}\n…`
54
+ }
55
+
56
+ function numberIn(value, fallback, min, max, label) {
57
+ if (value === undefined || value === null || value === '') return fallback
58
+ const number = Number(value)
59
+ if (!Number.isFinite(number)) throw new Error(`${label} must be a number, got ${JSON.stringify(value)}`)
60
+ return Math.min(max, Math.max(min, Math.trunc(number)))
61
+ }
62
+
63
+ function requiredText(value, label) {
64
+ const text = typeof value === 'string' ? value.trim() : ''
65
+ if (!text) throw new Error(`${label} is required`)
66
+ return text
67
+ }
68
+
69
+ /** Null means "no cap", 0 means the same thing at the run layer. */
70
+ function normalizeBudget(raw, label) {
71
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
72
+ const calls = raw.maxModelCalls ?? raw.max_model_calls
73
+ const tokens = raw.maxTokens ?? raw.max_tokens
74
+ const budget = {}
75
+ if (calls !== undefined && calls !== null && calls !== '') {
76
+ const value = numberIn(calls, null, 0, 1e9, `${label}.maxModelCalls`)
77
+ if (value > 0) budget.maxModelCalls = value
78
+ }
79
+ if (tokens !== undefined && tokens !== null && tokens !== '') {
80
+ const value = numberIn(tokens, null, 0, 1e12, `${label}.maxTokens`)
81
+ if (value > 0) budget.maxTokens = value
82
+ }
83
+ return Object.keys(budget).length > 0 ? budget : null
84
+ }
85
+
86
+ function newGoalId(now) {
87
+ const stamp = new Date(now()).toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)
88
+ return `g-${stamp}-${randomUUID().slice(0, 4)}`
89
+ }
90
+
91
+ /** Pull JSON objects out of a fenced block or out of the reply itself. */
92
+ function jsonCandidates(text) {
93
+ const candidates = []
94
+ for (const match of String(text ?? '').matchAll(/```[^\n]*\n([\s\S]*?)```/g)) candidates.push(match[1])
95
+ const first = String(text ?? '').indexOf('{')
96
+ const last = String(text ?? '').lastIndexOf('}')
97
+ if (first >= 0 && last > first) candidates.push(String(text).slice(first, last + 1))
98
+ return candidates
99
+ }
100
+
101
+ /**
102
+ * Sentences that deny the result a phase claims.
103
+ *
104
+ * Only explicit conclusions are matched — "release held", "verification
105
+ * remains blocked", "spawn EPERM", "exit code 1". A bare "failed" is not
106
+ * enough, because a passing report can contain counts such as "0 failed".
107
+ */
108
+ const NEGATIVE_CLAIM = /\brelease (?:is )?(?:held|blocked)\b|\bverification (?:remains?|is|was)? ?(?:blocked|incomplete|unverified)\b|\bremains (?:blocked|unverified)\b|\bcould not verify\b|\bcannot verify\b|\bunable to verify\b|\bnot verified\b|\bdid not verify\b|\bfailed to verify\b|\bcommands? (?:both )?failed\b|\bexit code:? ?1\b|\bexited (?:with )?(?:code )?1\b|\bspawn EPERM\b/i
109
+
110
+ function negativeClaimLines(text, limit = 3) {
111
+ const found = []
112
+ for (const raw of String(text ?? '').split(/\n+|(?<=[.!?])\s+/)) {
113
+ const line = raw.trim()
114
+ if (line.length < 8 || line.length > 600) continue
115
+ if (!NEGATIVE_CLAIM.test(line)) continue
116
+ if (!found.includes(line)) found.push(line)
117
+ if (found.length >= limit) break
118
+ }
119
+ return found
120
+ }
121
+
122
+ function machineEvidence(check) {
123
+ return {
124
+ id: check.id ?? null,
125
+ condition: check.text ?? null,
126
+ source: check.source ?? null,
127
+ command: check.command ?? null,
128
+ path: check.path ?? null,
129
+ exitCode: check.exitCode ?? null,
130
+ ok: check.ok !== false,
131
+ detail: check.detail != null ? oneLine(check.detail, 300) : null,
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Compare what the workers said with what the machine checks measured.
137
+ *
138
+ * The two must agree before a phase counts as achieved. A machine check is an
139
+ * exit code, not an opinion: when one failed, no report can make the phase
140
+ * pass. When every machine check passed but a worker wrote that the work was
141
+ * held, failed, or could not be verified, the phase is contradictory: the two
142
+ * sides saw the same command in different permission contexts (a worker shell
143
+ * that cannot spawn a subprocess reports EPERM while the host-side check exits
144
+ * 0). Guessing which side is right is a person's call, not the scheduler's.
145
+ *
146
+ * @param {object} run - persisted run record.
147
+ * @returns {object | null} conflict, or null when the evidence agrees.
148
+ */
149
+ export function verificationConflict(run) {
150
+ const goalMode = run?.goalMode ?? null
151
+ const lastRound = goalMode?.rounds?.at(-1) ?? null
152
+ const checks = (Array.isArray(lastRound?.checks) ? lastRound.checks : [])
153
+ .filter(check => check && check.source !== 'model')
154
+ if (checks.length === 0) return null
155
+ const machineFailed = checks.filter(check => check.ok === false)
156
+ const achieved = goalMode ? goalMode.achieved === true : run?.status === 'completed'
157
+ if (achieved && machineFailed.length > 0) {
158
+ return {
159
+ kind: 'machine-failed',
160
+ machine: machineFailed.map(machineEvidence),
161
+ worker: collectWorkerClaims(run),
162
+ }
163
+ }
164
+ if (!achieved || machineFailed.length > 0) return null
165
+ const worker = collectWorkerClaims(run)
166
+ if (worker.length === 0) return null
167
+ return { kind: 'claim-contradicts-machine', machine: checks.map(machineEvidence), worker }
168
+ }
169
+
170
+ function collectWorkerClaims(run) {
171
+ const texts = [
172
+ run?.goalMode?.rounds?.at(-1)?.report,
173
+ run?.report,
174
+ ...(Array.isArray(run?.subtasks) ? run.subtasks.map(subtask => subtask?.result) : []),
175
+ ]
176
+ const claims = []
177
+ for (const text of texts) {
178
+ for (const line of negativeClaimLines(text, 3)) {
179
+ if (!claims.includes(line)) claims.push(line)
180
+ if (claims.length >= 3) return claims
181
+ }
182
+ }
183
+ return claims
184
+ }
185
+
186
+ /** One acceptance condition, normalized through the same code goal mode uses. */
187
+ function normalizeAcceptance(raw, index, fallbackText) {
188
+ const entries = Array.isArray(raw) && raw.length > 0
189
+ ? raw
190
+ : [{ id: `a${index + 1}`, text: fallbackText }]
191
+ return entries.map((entry, position) => {
192
+ if (typeof entry === 'string') return { text: entry }
193
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
194
+ throw new Error(`acceptance[${position}] must be a string or an object with "text"`)
195
+ }
196
+ return { ...entry }
197
+ })
198
+ }
199
+
200
+ /**
201
+ * Validate one phase and give it stable defaults.
202
+ *
203
+ * The acceptance list is normalized by goal mode, so a phase cannot use a check
204
+ * shape that goal mode would reject later. `maxRounds` is kept per phase: a
205
+ * read-only phase does not need the same allowance as an implementation phase.
206
+ */
207
+ function normalizePhase(raw, index, defaults, seen) {
208
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
209
+ throw new Error(`phases[${index}] must be an object`)
210
+ }
211
+ const id = oneLine(raw.id, 40) || `p${index + 1}`
212
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/.test(id)) {
213
+ throw new Error(`phases[${index}].id ${JSON.stringify(id)} is not a safe identifier`)
214
+ }
215
+ if (seen.has(id)) throw new Error(`phase ids must be unique; "${id}" appears twice`)
216
+ seen.add(id)
217
+ const title = oneLine(raw.title, 120) || `Phase ${index + 1}`
218
+ const objective = oneLine(raw.objective ?? raw.prompt, 2000)
219
+ if (!objective) throw new Error(`phases[${index}].objective is required`)
220
+ const dependsOn = Array.isArray(raw.dependsOn ?? raw.depends_on)
221
+ ? (raw.dependsOn ?? raw.depends_on).map(item => String(item ?? '').trim()).filter(Boolean)
222
+ : []
223
+ const acceptanceSource = normalizeAcceptance(
224
+ raw.acceptance ?? raw.acceptanceConditions,
225
+ index,
226
+ `The objective of phase "${title}" is achieved: ${objective}`,
227
+ )
228
+ const spec = normalizeGoalSpec({
229
+ acceptance: acceptanceSource,
230
+ maxRounds: numberIn(
231
+ raw.maxRounds ?? raw.max_rounds ?? defaults.maxRoundsPerPhase,
232
+ defaults.maxRoundsPerPhase,
233
+ 1,
234
+ 20,
235
+ `phases[${index}].maxRounds`,
236
+ ),
237
+ maxWallClockMinutes: numberIn(
238
+ raw.maxWallClockMinutes ?? raw.max_wall_clock_minutes ?? defaults.phaseWallClockMinutes,
239
+ defaults.phaseWallClockMinutes,
240
+ 1,
241
+ 720,
242
+ `phases[${index}].maxWallClockMinutes`,
243
+ ),
244
+ noProgressRounds: defaults.noProgressRounds,
245
+ cwd: defaults.cwd,
246
+ })
247
+ return {
248
+ id,
249
+ title,
250
+ objective,
251
+ dependsOn: [...new Set(dependsOn)],
252
+ acceptance: spec.acceptance,
253
+ maxRounds: spec.maxRounds,
254
+ maxWallClockMinutes: spec.maxWallClockMinutes,
255
+ status: 'pending',
256
+ attempts: 0,
257
+ runIds: [],
258
+ currentRunId: null,
259
+ resumeRunId: null,
260
+ deliverables: Array.isArray(raw.deliverables)
261
+ ? raw.deliverables.map(item => oneLine(item, 300)).filter(Boolean).slice(0, 20)
262
+ : [],
263
+ lastOutcome: null,
264
+ lastSignature: null,
265
+ retryNote: null,
266
+ startedAt: null,
267
+ finishedAt: null,
268
+ }
269
+ }
270
+
271
+ /** Unique ids, known dependencies, and no cycle: anything else is rejected now. */
272
+ function validatePhaseGraph(phases) {
273
+ const ids = new Set(phases.map(phase => phase.id))
274
+ for (const phase of phases) {
275
+ for (const dependency of phase.dependsOn) {
276
+ if (!ids.has(dependency)) {
277
+ throw new Error(`phase "${phase.id}" depends on unknown phase "${dependency}"`)
278
+ }
279
+ if (dependency === phase.id) throw new Error(`phase "${phase.id}" depends on itself`)
280
+ }
281
+ }
282
+ const visiting = new Set()
283
+ const done = new Set()
284
+ const walk = phase => {
285
+ if (done.has(phase.id)) return
286
+ if (visiting.has(phase.id)) throw new Error(`phase dependency cycle through "${phase.id}"`)
287
+ visiting.add(phase.id)
288
+ for (const dependency of phase.dependsOn) walk(phases.find(item => item.id === dependency))
289
+ visiting.delete(phase.id)
290
+ done.add(phase.id)
291
+ }
292
+ for (const phase of phases) walk(phase)
293
+ }
294
+
295
+ function goalPrompt(goal, phase, index, total, dependencySummaries) {
296
+ return [
297
+ `Long-term goal: ${goal.goal}`,
298
+ '',
299
+ `This run is phase ${index + 1} of ${total}: ${phase.title}`,
300
+ '',
301
+ 'Phase objective:',
302
+ phase.objective,
303
+ '',
304
+ ...(dependencySummaries.length > 0
305
+ ? [
306
+ 'Results of earlier phases (use them; do not redo that work):',
307
+ ...dependencySummaries,
308
+ '',
309
+ ]
310
+ : []),
311
+ 'Work only on this phase. Later phases depend on what this run leaves on disk, so finish with concrete artifacts,',
312
+ 'not a plan for someone else to execute. The phase acceptance conditions are checked after every round; a round',
313
+ 'that does not meet them is retried with the exact failure instead of repeating the same work.',
314
+ ].join('\n')
315
+ }
316
+
317
+ function decomposePrompt(goal, maxPhases) {
318
+ return [
319
+ 'You are the phase planner of a long-term autonomous goal.',
320
+ '',
321
+ 'Goal:',
322
+ goal.goal,
323
+ '',
324
+ `Split it into 2 to ${maxPhases} phases that a team of agents can execute one after another (or in parallel when`,
325
+ 'their work is truly independent). Each phase is itself handed to a planner and parallel workers, so a phase must',
326
+ 'be a coherent milestone, not a single edit.',
327
+ '',
328
+ 'Return ONLY this JSON object, with no prose and no code fences:',
329
+ '{"phases":[{"id":"p1","title":"short title","objective":"what this phase must produce, in one or two sentences",'
330
+ + '"dependsOn":[],"acceptance":[{"text":"a condition that can be checked","check":{"type":"file","path":"docs/x.md"}}],'
331
+ + '"maxRounds":3}],"questions":[]}',
332
+ '',
333
+ 'Rules:',
334
+ '- Use 2 to ' + maxPhases + ' phases, ordered; ids are p1, p2, ...',
335
+ '- "dependsOn" only when the later phase needs an earlier phase\'s artifact. Independent phases may run at once.',
336
+ '- Every phase needs at least one acceptance condition. Prefer a machine check (file exists, command exits 0);',
337
+ ' a condition without a check is judged by an independent acceptance model from the phase report.',
338
+ '- Never create a dependency cycle. Never reference a phase id that is not in the list.',
339
+ '- The last phase must leave the goal verifiably achieved, not merely describe what remains.',
340
+ '- "questions" is only for a decision no amount of work can resolve; do not use it for planning details.',
341
+ '- Answer from this prompt alone. Do not call tools, read files, or inspect the environment before replying.',
342
+ ].join('\n')
343
+ }
344
+
345
+ function decomposeRepairPrompt(goal, previous) {
346
+ return [
347
+ 'You are the phase planner of a long-term autonomous goal.',
348
+ '',
349
+ 'Goal:',
350
+ goal.goal,
351
+ '',
352
+ 'The previous reply was not a usable phase plan. Here it is:',
353
+ capText(previous, 6000),
354
+ '',
355
+ 'Return ONLY the JSON object described below, with no prose and no code fences:',
356
+ '{"phases":[{"id":"p1","title":"…","objective":"…","dependsOn":[],"acceptance":[{"text":"…"}],"maxRounds":3}],'
357
+ + '"questions":[]}',
358
+ '',
359
+ 'Every phase needs a unique id, an objective, and at least one acceptance condition. No cycles, no unknown',
360
+ 'dependencies, no text outside the JSON object.',
361
+ ].join('\n')
362
+ }
363
+
364
+ /**
365
+ * Durable goal store: one JSON file per goal, atomic replace, Windows retries.
366
+ * Kept in this module because a goal is the only record it owns.
367
+ */
368
+ function createGoalStore(root, { log = () => {}, now = () => Date.now() } = {}) {
369
+ const dir = path.join(root, 'goals')
370
+ let seq = 0
371
+ const file = id => path.join(dir, `${id}.json`)
372
+ return {
373
+ dir,
374
+ async init() {
375
+ await fsp.mkdir(dir, { recursive: true })
376
+ },
377
+ async read(id) {
378
+ if (!GOAL_ID_PATTERN.test(String(id ?? ''))) return null
379
+ try {
380
+ return JSON.parse(await fsp.readFile(file(id), 'utf8'))
381
+ } catch (error) {
382
+ if (error?.code === 'ENOENT') return null
383
+ if (error instanceof SyntaxError) {
384
+ log(`goal ${id} is not valid JSON; left in place for inspection`)
385
+ return null
386
+ }
387
+ throw error
388
+ }
389
+ },
390
+ async write(goal) {
391
+ await fsp.mkdir(dir, { recursive: true })
392
+ const target = file(goal.id)
393
+ const tmp = path.join(dir, `.${goal.id}.${process.pid}.${++seq}.tmp`)
394
+ await fsp.writeFile(tmp, `${JSON.stringify(goal, null, 2)}\n`, 'utf8')
395
+ for (let attempt = 1; ; attempt++) {
396
+ try {
397
+ await fsp.rename(tmp, target)
398
+ return
399
+ } catch (error) {
400
+ if (attempt >= 5 || !['EPERM', 'EACCES', 'EBUSY'].includes(error?.code)) throw error
401
+ await new Promise(resolve => setTimeout(resolve, 20 * attempt))
402
+ }
403
+ }
404
+ },
405
+ async list() {
406
+ await fsp.mkdir(dir, { recursive: true })
407
+ const names = await fsp.readdir(dir)
408
+ const goals = []
409
+ for (const name of names) {
410
+ if (!name.endsWith('.json') || name.startsWith('.')) continue
411
+ try {
412
+ const goal = await this.read(name.slice(0, -'.json'.length))
413
+ if (goal) goals.push(goal)
414
+ } catch (error) {
415
+ log(`skipping goal file ${name}: ${error?.message ?? error}`)
416
+ }
417
+ }
418
+ return goals.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
419
+ },
420
+ file,
421
+ now,
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Create the long-goal manager.
427
+ *
428
+ * `orchestrator` is the only execution surface: this module never spawns a child
429
+ * itself. `resolveOwner` and `notify` are injected so the same code works in a
430
+ * test (fakes) and in the host (the session recovery and outbox the scheduler
431
+ * already uses).
432
+ *
433
+ * @param {object} options - dependencies and defaults.
434
+ * @returns {object} manager API.
435
+ */
436
+ export function createLongGoalManager({
437
+ root,
438
+ orchestrator,
439
+ resolveOwner = async () => null,
440
+ notify = async () => ({ delivered: false }),
441
+ config = {},
442
+ log = () => {},
443
+ now = () => Date.now(),
444
+ tickSeconds = DEFAULT_TICK_SECONDS,
445
+ autoTick = true,
446
+ } = {}) {
447
+ if (!root) throw new Error('long-goal requires a state root')
448
+ if (!orchestrator || typeof orchestrator.start !== 'function') {
449
+ throw new Error('long-goal requires the orchestrator')
450
+ }
451
+ const store = createGoalStore(root, { log, now })
452
+ const defaults = {
453
+ maxParallelPhases: numberIn(
454
+ config.maxParallelPhases,
455
+ DEFAULT_MAX_PARALLEL_PHASES,
456
+ 1,
457
+ MAX_PHASES,
458
+ 'maxParallelPhases',
459
+ ),
460
+ maxAttemptsPerPhase: numberIn(
461
+ config.maxAttemptsPerPhase,
462
+ DEFAULT_MAX_ATTEMPTS_PER_PHASE,
463
+ 1,
464
+ 6,
465
+ 'maxAttemptsPerPhase',
466
+ ),
467
+ maxRoundsPerPhase: numberIn(
468
+ config.maxRoundsPerPhase,
469
+ DEFAULT_MAX_ROUNDS_PER_PHASE,
470
+ 1,
471
+ 20,
472
+ 'maxRoundsPerPhase',
473
+ ),
474
+ noProgressRounds: DEFAULT_NO_PROGRESS_ROUNDS,
475
+ phaseWallClockMinutes: DEFAULT_PHASE_WALL_CLOCK_MINUTES,
476
+ phaseBudget: normalizeBudget(
477
+ config.phaseBudget ?? {
478
+ maxModelCalls: config.maxModelCallsPerRun,
479
+ maxTokens: config.maxTokensPerRun,
480
+ },
481
+ 'phaseBudget',
482
+ ),
483
+ }
484
+ let timer = null
485
+ let ticking = null
486
+ let closed = false
487
+
488
+ function arm(delayMs = tickSeconds * 1000) {
489
+ if (!autoTick || closed || timer) return
490
+ timer = setTimeout(() => {
491
+ timer = null
492
+ tick().catch(error => log(`long-goal tick failed: ${error?.message ?? error}`))
493
+ }, Math.max(200, delayMs))
494
+ if (typeof timer.unref === 'function') timer.unref()
495
+ }
496
+
497
+ function close() {
498
+ closed = true
499
+ if (timer) clearTimeout(timer)
500
+ timer = null
501
+ }
502
+
503
+ function event(goal, type, detail, phaseId = null) {
504
+ goal.events = Array.isArray(goal.events) ? goal.events : []
505
+ goal.events.push({ at: new Date(now()).toISOString(), type, phaseId, detail: oneLine(detail, 400) })
506
+ if (goal.events.length > MAX_EVENTS) goal.events = goal.events.slice(-MAX_EVENTS)
507
+ }
508
+
509
+ function addDecision(goal, spec) {
510
+ goal.decisionSeq = (Number(goal.decisionSeq) || 0) + 1
511
+ const decision = {
512
+ id: `d${goal.decisionSeq}`,
513
+ kind: spec.kind,
514
+ phaseId: spec.phaseId ?? null,
515
+ question: oneLine(spec.question, 900),
516
+ options: spec.options ?? ['continue', 'stop'],
517
+ reason: oneLine(spec.reason ?? '', 600),
518
+ source: spec.source ?? null,
519
+ answer: null,
520
+ answeredAt: null,
521
+ createdAt: new Date(now()).toISOString(),
522
+ }
523
+ goal.decisions = Array.isArray(goal.decisions) ? goal.decisions : []
524
+ goal.decisions.push(decision)
525
+ if (goal.decisions.length > MAX_DECISIONS) goal.decisions = goal.decisions.slice(-MAX_DECISIONS)
526
+ goal.status = 'needs-decision'
527
+ event(goal, 'decision.opened', decision.question, decision.phaseId)
528
+ return decision
529
+ }
530
+
531
+ function openDecisions(goal) {
532
+ return (goal.decisions ?? []).filter(item => !item.answer)
533
+ }
534
+
535
+ function phaseById(goal, id) {
536
+ return (goal.phases ?? []).find(phase => phase.id === id) ?? null
537
+ }
538
+
539
+ function activePhaseCount(goal) {
540
+ return (goal.phases ?? []).filter(phase => phase.status === 'running' || phase.status === 'verifying').length
541
+ }
542
+
543
+ function goalRunIds(goal) {
544
+ const ids = new Set()
545
+ if (goal.decomposeRunId) ids.add(goal.decomposeRunId)
546
+ for (const phase of goal.phases ?? []) {
547
+ for (const runId of phase.runIds ?? []) ids.add(runId)
548
+ if (phase.resumeRunId) ids.add(phase.resumeRunId)
549
+ }
550
+ return [...ids]
551
+ }
552
+
553
+ async function readRun(runId) {
554
+ if (!runId) return null
555
+ try {
556
+ return await orchestrator.status(runId)
557
+ } catch (error) {
558
+ if (!/unknown run/.test(String(error?.message ?? error))) {
559
+ log(`long-goal cannot read run ${runId}: ${error?.message ?? error}`)
560
+ }
561
+ return null
562
+ }
563
+ }
564
+
565
+ /** Sum usage over every run this goal ever started, including retries. */
566
+ async function refreshUsage(goal) {
567
+ let calls = 0
568
+ let tokens = 0
569
+ for (const runId of goalRunIds(goal)) {
570
+ const run = await readRun(runId)
571
+ if (!run?.usage) continue
572
+ calls += Number(run.usage.modelCalls) || 0
573
+ tokens += Number(run.usage.totalTokens) || 0
574
+ }
575
+ const next = { modelCalls: calls, tokens }
576
+ const changed = !goal.usage || goal.usage.modelCalls !== calls || goal.usage.tokens !== tokens
577
+ goal.usage = next
578
+ return changed
579
+ }
580
+
581
+ function remainingBudget(goal, phaseBudget) {
582
+ const cap = goal.budget
583
+ const used = goal.usage ?? { modelCalls: 0, tokens: 0 }
584
+ const remaining = { ...(phaseBudget ?? {}) }
585
+ if (cap?.maxModelCalls) {
586
+ const left = cap.maxModelCalls - used.modelCalls
587
+ remaining.maxModelCalls = Math.min(remaining.maxModelCalls ?? Infinity, left)
588
+ }
589
+ if (cap?.maxTokens) {
590
+ const left = cap.maxTokens - used.tokens
591
+ remaining.maxTokens = Math.min(remaining.maxTokens ?? Infinity, left)
592
+ }
593
+ if (remaining.maxModelCalls !== undefined && (!Number.isFinite(remaining.maxModelCalls) || remaining.maxModelCalls <= 0)) {
594
+ return { exhausted: true, detail: `model-call budget reached (${used.modelCalls}/${cap?.maxModelCalls} calls)` }
595
+ }
596
+ if (remaining.maxTokens !== undefined && (!Number.isFinite(remaining.maxTokens) || remaining.maxTokens <= 0)) {
597
+ return { exhausted: true, detail: `token budget reached (${used.tokens}/${cap?.maxTokens} tokens)` }
598
+ }
599
+ const budget = {}
600
+ if (Number.isFinite(remaining.maxModelCalls)) budget.maxModelCalls = Math.trunc(remaining.maxModelCalls)
601
+ if (Number.isFinite(remaining.maxTokens)) budget.maxTokens = Math.trunc(remaining.maxTokens)
602
+ return { exhausted: false, budget: Object.keys(budget).length > 0 ? budget : null }
603
+ }
604
+
605
+ /** Resolve the session that may own child agents for this goal. */
606
+ async function owner(goal) {
607
+ try {
608
+ const resolved = await resolveOwner(goal)
609
+ const agent = resolved?.agent ?? resolved
610
+ if (agent && typeof agent === 'object' && agent.id) {
611
+ if (resolved?.sessionId && resolved.sessionId !== goal.ownerSessionId) {
612
+ goal.ownerSessionId = resolved.sessionId
613
+ }
614
+ return agent
615
+ }
616
+ } catch (error) {
617
+ log(`long-goal cannot resolve owner for ${goal.id}: ${error?.message ?? error}`)
618
+ }
619
+ return null
620
+ }
621
+
622
+ function announce(goal, kind, message) {
623
+ Promise.resolve()
624
+ .then(() => notify({ goal, event: kind, message }))
625
+ .catch(error => log(`long-goal notify failed for ${goal.id}: ${error?.message ?? error}`))
626
+ }
627
+
628
+ function progressLine(goal) {
629
+ const phases = goal.phases ?? []
630
+ const completed = phases.filter(phase => phase.status === 'completed').length
631
+ const running = phases.filter(phase => phase.status === 'running' || phase.status === 'verifying').length
632
+ const used = goal.usage ?? { modelCalls: 0, tokens: 0 }
633
+ const cap = goal.budget
634
+ return `${completed}/${phases.length} phase(s) complete, ${running} running; `
635
+ + `${used.modelCalls}${cap?.maxModelCalls ? `/${cap.maxModelCalls}` : ''} model calls`
636
+ }
637
+
638
+ async function startDecompose(goal, parent) {
639
+ const attempt = (Number(goal.decomposeAttempts) || 0) + 1
640
+ goal.decomposeAttempts = attempt
641
+ const prompt = attempt === 1
642
+ ? decomposePrompt(goal, MAX_PHASES)
643
+ : decomposeRepairPrompt(goal, goal.decomposeReply ?? '')
644
+ const run = await orchestrator.start({
645
+ goal: prompt,
646
+ parentSessionId: goal.ownerSessionId,
647
+ parent,
648
+ clientTimeZone: null,
649
+ mode: 'direct',
650
+ allowDuplicate: true,
651
+ queue: true,
652
+ muted: true,
653
+ goalMode: null,
654
+ overrides: { deadlineMinutes: 15, maxSubtasks: 2, maxParallel: 1 },
655
+ origin: { kind: 'long-goal', goalId: goal.id, role: 'decompose', attempt },
656
+ })
657
+ goal.decomposeRunId = run.id
658
+ event(goal, 'decompose.started', `attempt ${attempt}: run ${run.id}`)
659
+ await store.write(goal)
660
+ return run
661
+ }
662
+
663
+ async function settleDecompose(goal, run) {
664
+ goal.decomposeRunId = null
665
+ goal.decomposeReply = capText(run.report ?? '', 8000)
666
+ const parsed = parsePhasePlan(run.report ?? '')
667
+ if (parsed.phases) {
668
+ const cwd = goal.cwd
669
+ const seen = new Set()
670
+ const phaseDefaults = {
671
+ maxRoundsPerPhase: goal.maxRoundsPerPhase,
672
+ noProgressRounds: goal.noProgressRounds,
673
+ phaseWallClockMinutes: goal.phaseWallClockMinutes,
674
+ cwd,
675
+ }
676
+ const phases = parsed.phases.map((entry, index) => normalizePhase(entry, index, phaseDefaults, seen))
677
+ validatePhaseGraph(phases)
678
+ goal.phases = phases
679
+ goal.status = 'running'
680
+ goal.startedAt = goal.startedAt ?? new Date(now()).toISOString()
681
+ event(goal, 'decompose.ready', `${phases.length} phase(s): ${phases.map(phase => phase.id).join(', ')}`)
682
+ await store.write(goal)
683
+ announce(goal, 'phases-ready', `长期目标 ${goal.id} 已拆成 ${phases.length} 个阶段:`
684
+ + `${phases.map(phase => `${phase.id} ${phase.title}`).join(';')}。进度用 superagent_goal status 查看。`)
685
+ return
686
+ }
687
+ const reason = parsed.error ?? 'the phase planner returned no usable phases'
688
+ event(goal, 'decompose.invalid', reason)
689
+ if ((Number(goal.decomposeAttempts) || 0) < 2) {
690
+ const parent = await owner(goal)
691
+ if (!parent) {
692
+ goal.status = 'paused'
693
+ goal.pausedReason = 'owner-unavailable'
694
+ await store.write(goal)
695
+ return
696
+ }
697
+ await startDecompose(goal, parent)
698
+ return
699
+ }
700
+ // A plan that cannot be framed is not retried forever: the next attempt
701
+ // would spend the same tokens and fail the same way.
702
+ goal.status = 'failed'
703
+ goal.stoppedReason = { reason: 'decompose-failed', detail: reason, at: new Date(now()).toISOString() }
704
+ goal.finishedAt = new Date(now()).toISOString()
705
+ event(goal, 'goal.failed', reason)
706
+ await store.write(goal)
707
+ announce(goal, 'goal-failed', `长期目标 ${goal.id} 没有启动:阶段规划两次都不可用(${reason})。`
708
+ + '可以改用 superagent_goal 显式传入 phases 重新创建。')
709
+ }
710
+
711
+ /**
712
+ * Reconcile the run behind one phase.
713
+ *
714
+ * `interrupted` is not a failed attempt: the work never got a chance to run
715
+ * after the host went away. The same run is resumed, so completed subtasks are
716
+ * not paid for twice.
717
+ */
718
+ async function reconcilePhase(goal, phase, parent) {
719
+ if (phase.status !== 'running' || !phase.currentRunId) return
720
+ const run = await readRun(phase.currentRunId)
721
+ if (!run) {
722
+ phase.status = 'ready'
723
+ phase.resumeRunId = null
724
+ phase.lastOutcome = { runStatus: 'missing', error: 'the run state file disappeared' }
725
+ event(goal, 'phase.run-missing', `phase ${phase.id} lost run ${phase.currentRunId}`, phase.id)
726
+ return
727
+ }
728
+ if (run.status === 'interrupted') {
729
+ if (!parent) return
730
+ try {
731
+ const resumed = await orchestrator.resume(run.id, parent, null)
732
+ phase.currentRunId = resumed.id
733
+ phase.status = 'running'
734
+ event(goal, 'phase.resumed', `resumed run ${run.id} after interruption`, phase.id)
735
+ } catch (error) {
736
+ phase.status = 'ready'
737
+ phase.resumeRunId = null
738
+ phase.lastOutcome = {
739
+ runStatus: 'interrupted',
740
+ error: oneLine(error?.message ?? error, 500),
741
+ }
742
+ goal.status = 'needs-decision'
743
+ addDecision(goal, {
744
+ kind: 'resume-failed',
745
+ phaseId: phase.id,
746
+ question: `阶段 ${phase.id}「${phase.title}」的原 run ${run.id} 无法恢复。`
747
+ + '重试会新建一次尝试(已完成阶段不会重跑);也可以跳过该阶段或停止目标。',
748
+ options: ['retry', 'skip', 'stop'],
749
+ reason: phase.lastOutcome.error,
750
+ source: { runId: run.id },
751
+ })
752
+ }
753
+ return
754
+ }
755
+ if (!TERMINAL_STATUSES.has(run.status)) return
756
+
757
+ phase.status = 'verifying'
758
+ const goalMode = run.goalMode ?? null
759
+ const lastRound = goalMode?.rounds?.at(-1) ?? null
760
+ const failed = lastRound?.failed ?? []
761
+ const conflict = verificationConflict(run)
762
+ // A failed machine check is final, and a claim that denies a passing check
763
+ // is a contradiction: neither counts as an achieved phase on its own.
764
+ const achieved = conflict === null && (goalMode ? goalMode.achieved === true : run.status === 'completed')
765
+ phase.lastOutcome = {
766
+ runStatus: run.status,
767
+ error: oneLine(run.error, 500) || null,
768
+ failed: failed.map(item => ({ id: item.id, text: item.text, why: item.why })),
769
+ stop: goalMode?.stop ?? null,
770
+ changed: lastRound?.changed ?? null,
771
+ budgetStop: run.budgetStop ?? null,
772
+ conflict: conflict?.kind ?? null,
773
+ }
774
+ if (achieved) {
775
+ phase.status = 'completed'
776
+ phase.finishedAt = new Date(now()).toISOString()
777
+ phase.lastSignature = null
778
+ goal.progressAt = new Date(now()).toISOString()
779
+ goal.noProgressAttempts = 0
780
+ event(goal, 'phase.completed', `run ${run.id} met the acceptance conditions`, phase.id)
781
+ announce(goal, 'phase-completed', `长期目标 ${goal.id}:阶段 ${phase.id}「${phase.title}」完成`
782
+ + `(${progressLine(goal)})。`)
783
+ return
784
+ }
785
+
786
+ if (conflict?.kind === 'claim-contradicts-machine') {
787
+ phase.status = 'needs-decision'
788
+ const machineLine = conflict.machine
789
+ .map(item => `${item.condition ?? item.id}${item.command ? ` (${item.command})` : ''}: `
790
+ + (item.exitCode === null || item.exitCode === undefined ? 'ok' : `exit ${item.exitCode}`))
791
+ .join('; ')
792
+ addDecision(goal, {
793
+ kind: 'verification-conflict',
794
+ phaseId: phase.id,
795
+ question: `阶段 ${phase.id}「${phase.title}」的证据自相矛盾:机器校验通过(${machineLine}),`
796
+ + `但执行 agent 的结论是否定的——「${conflict.worker[0]}」。`
797
+ + '可以选择以机器校验为准(accept)、换人重试(retry),或停止目标(stop)。',
798
+ options: ['accept', 'retry', 'stop'],
799
+ reason: 'the worker reported failure while the machine check passed',
800
+ source: { runId: run.id, machine: conflict.machine, worker: conflict.worker },
801
+ })
802
+ event(goal, 'phase.verification-conflict', conflict.worker[0], phase.id)
803
+ return
804
+ }
805
+
806
+ const open = (run.attention?.items ?? []).filter(item => !item.answer)
807
+ if (open.length > 0) {
808
+ phase.status = 'needs-decision'
809
+ goal.status = 'needs-decision'
810
+ const question = open[0]
811
+ addDecision(goal, {
812
+ kind: 'worker-question',
813
+ phaseId: phase.id,
814
+ question: `阶段 ${phase.id} 的执行 agent 需要你决定:${question.question}`,
815
+ options: ['answer', 'stop'],
816
+ reason: question.reason ?? 'the worker stopped rather than guess',
817
+ source: { runId: run.id, attentionId: question.id },
818
+ })
819
+ return
820
+ }
821
+
822
+ const signature = [
823
+ run.status,
824
+ goalMode?.stop?.reason ?? '',
825
+ failed.map(item => item.id).sort().join('|'),
826
+ run.error ?? '',
827
+ ].join(':')
828
+ const identicalNoChange = phase.lastSignature === signature && lastRound?.changed === false
829
+ const retryable = isRetryable(run)
830
+ const attemptsLeft = phase.attempts < goal.maxAttemptsPerPhase
831
+ phase.lastSignature = signature
832
+ goal.noProgressAttempts = (Number(goal.noProgressAttempts) || 0) + 1
833
+
834
+ if (retryable && attemptsLeft && !identicalNoChange) {
835
+ phase.status = 'ready'
836
+ phase.retryNote = retryInstruction(phase, run, failed)
837
+ event(goal, 'phase.retry', `attempt ${phase.attempts}/${goal.maxAttemptsPerPhase} failed; retrying with a new team`, phase.id)
838
+ return
839
+ }
840
+ phase.status = 'failed'
841
+ phase.finishedAt = new Date(now()).toISOString()
842
+ const why = identicalNoChange
843
+ ? '两次尝试以相同方式失败,且工作区没有变化'
844
+ : !retryable
845
+ ? (phase.lastOutcome.error || 'a failure that a retry cannot fix')
846
+ : `已用尽 ${goal.maxAttemptsPerPhase} 次尝试`
847
+ goal.status = 'needs-decision'
848
+ addDecision(goal, {
849
+ kind: 'phase-exhausted',
850
+ phaseId: phase.id,
851
+ question: `阶段 ${phase.id}「${phase.title}」失败:${why}。`
852
+ + '可以换一种做法重试、跳过该阶段,或停止整个目标。',
853
+ options: ['retry', 'skip', 'stop'],
854
+ reason: why,
855
+ source: { runId: run.id, failed: failed.map(item => item.id) },
856
+ })
857
+ event(goal, 'phase.failed', why, phase.id)
858
+ }
859
+
860
+ function isRetryable(run) {
861
+ if (run.status === 'cancelled') return false
862
+ if (run.budgetStop) return false
863
+ const stopReason = run.goalMode?.stop?.reason
864
+ if (stopReason === 'needs-decision') return true
865
+ if (stopReason === 'budget') return false
866
+ const text = `${run.error ?? ''} ${run.goalMode?.stop?.detail ?? ''}`
867
+ if (/permission policy|refused|not (available|supported)|capability|missing tool|planner did not return|unknown subtask|dependency cycle|duplicate subtask/i.test(text)) {
868
+ return false
869
+ }
870
+ return true
871
+ }
872
+
873
+ function retryInstruction(phase, run, failed) {
874
+ const lines = [
875
+ `This is attempt ${phase.attempts + 1} of phase "${phase.title}". The previous attempt failed.`,
876
+ ]
877
+ if (failed.length > 0) {
878
+ lines.push('Still failing:')
879
+ for (const item of failed) lines.push(`- [${item.id}] ${item.text} — ${item.why ?? 'the condition did not hold'}`)
880
+ }
881
+ if (run.error) lines.push(`The run reported: ${oneLine(run.error, 500)}`)
882
+ if (phase.lastOutcome?.stop?.reason === 'no-changes') {
883
+ lines.push('The previous attempt changed no file. Repeating it cannot pass: change the approach or the files.')
884
+ }
885
+ lines.push('Do this differently from the previous attempt. Do not repeat it.')
886
+ return lines.join('\n')
887
+ }
888
+
889
+ async function dependencySummaries(goal, phase) {
890
+ const lines = []
891
+ for (const id of phase.dependsOn) {
892
+ const dependency = phaseById(goal, id)
893
+ if (!dependency || dependency.status !== 'completed') continue
894
+ const run = await readRun(dependency.runIds.at(-1))
895
+ const summary = oneLine(run?.report ?? '', 700)
896
+ lines.push(`- ${dependency.id} ${dependency.title}: ${summary || 'completed with no written summary'}`)
897
+ }
898
+ return lines
899
+ }
900
+
901
+ async function startPhase(goal, phase, parent) {
902
+ const index = goal.phases.indexOf(phase)
903
+ const remaining = remainingBudget(goal, goal.phaseBudget)
904
+ if (remaining.exhausted) {
905
+ goal.status = 'budget-stopped'
906
+ goal.stoppedReason = { reason: 'budget', detail: remaining.detail, at: new Date(now()).toISOString() }
907
+ goal.finishedAt = new Date(now()).toISOString()
908
+ event(goal, 'goal.budget-stopped', remaining.detail)
909
+ await store.write(goal)
910
+ announce(goal, 'goal-budget-stopped', `长期目标 ${goal.id} 已停止:${remaining.detail}。`
911
+ + '预算不能靠重试绕过;需要更高预算时请新建目标。')
912
+ return false
913
+ }
914
+ const summaries = await dependencySummaries(goal, phase)
915
+ const phaseGoal = goalPrompt(goal, phase, index, goal.phases.length, summaries)
916
+ const retryText = phase.retryNote ? `\n\n${phase.retryNote}` : ''
917
+ const budget = remaining.budget ?? {}
918
+ const run = await orchestrator.start({
919
+ goal: `${phaseGoal}${retryText}`,
920
+ parentSessionId: goal.ownerSessionId,
921
+ parent,
922
+ clientTimeZone: null,
923
+ mode: 'planned',
924
+ allowDuplicate: false,
925
+ queue: true,
926
+ muted: true,
927
+ goalMode: {
928
+ acceptance: phase.acceptance,
929
+ maxRounds: phase.maxRounds,
930
+ maxWallClockMinutes: phase.maxWallClockMinutes,
931
+ noProgressRounds: goal.noProgressRounds,
932
+ budget: Object.keys(budget).length > 0 ? budget : null,
933
+ cwd: goal.cwd,
934
+ },
935
+ overrides: {
936
+ ...(budget.maxModelCalls ? { maxModelCalls: budget.maxModelCalls } : {}),
937
+ ...(budget.maxTokens ? { maxTokens: budget.maxTokens } : {}),
938
+ },
939
+ origin: { kind: 'long-goal', goalId: goal.id, phaseId: phase.id, attempt: phase.attempts + 1 },
940
+ })
941
+ phase.attempts += 1
942
+ phase.runIds = Array.isArray(phase.runIds) ? phase.runIds : []
943
+ phase.runIds.push(run.id)
944
+ phase.currentRunId = run.id
945
+ phase.resumeRunId = null
946
+ phase.status = 'running'
947
+ phase.startedAt = phase.startedAt ?? new Date(now()).toISOString()
948
+ phase.retryNote = null
949
+ event(goal, 'phase.started', `attempt ${phase.attempts}, run ${run.id}`, phase.id)
950
+ await store.write(goal)
951
+ return true
952
+ }
953
+
954
+ async function resumePhase(goal, phase, parent) {
955
+ const runId = phase.resumeRunId
956
+ try {
957
+ const run = await orchestrator.resume(runId, parent, null)
958
+ phase.currentRunId = run.id
959
+ phase.resumeRunId = null
960
+ phase.status = 'running'
961
+ event(goal, 'phase.resumed', `resumed run ${run.id}`, phase.id)
962
+ await store.write(goal)
963
+ return true
964
+ } catch (error) {
965
+ const reason = oneLine(error?.message ?? error, 600)
966
+ phase.resumeRunId = null
967
+ phase.status = 'failed'
968
+ phase.lastOutcome = { runStatus: 'interrupted', error: reason }
969
+ goal.status = 'needs-decision'
970
+ addDecision(goal, {
971
+ kind: 'resume-failed',
972
+ phaseId: phase.id,
973
+ question: `宿主重启后阶段 ${phase.id}「${phase.title}」的原 run ${runId} 无法继续:${reason}。`
974
+ + '重试会从该阶段开头新建一次尝试(已完成的阶段不会重跑);也可以跳过或停止。',
975
+ options: ['retry', 'skip', 'stop'],
976
+ reason,
977
+ source: { runId },
978
+ })
979
+ event(goal, 'phase.resume-failed', reason, phase.id)
980
+ await store.write(goal)
981
+ return false
982
+ }
983
+ }
984
+
985
+ /** Move phases whose dependencies can never complete to `skipped`. */
986
+ function cascadeSkips(goal) {
987
+ let changed = false
988
+ for (const phase of goal.phases) {
989
+ if (phase.status !== 'pending' && phase.status !== 'ready') continue
990
+ const blocked = phase.dependsOn
991
+ .map(id => phaseById(goal, id))
992
+ .filter(dependency => dependency && ['failed', 'skipped', 'cancelled'].includes(dependency.status))
993
+ if (blocked.length === 0) continue
994
+ phase.status = 'skipped'
995
+ phase.finishedAt = new Date(now()).toISOString()
996
+ phase.lastOutcome = {
997
+ runStatus: 'skipped',
998
+ error: `dependency ${blocked.map(item => item.id).join(', ')} did not complete`,
999
+ }
1000
+ event(goal, 'phase.skipped', phase.lastOutcome.error, phase.id)
1001
+ changed = true
1002
+ }
1003
+ return changed
1004
+ }
1005
+
1006
+ async function settleGoal(goal) {
1007
+ const phases = goal.phases ?? []
1008
+ if (phases.length === 0) return false
1009
+ if (phases.some(phase => !PHASE_TERMINAL.has(phase.status))) return false
1010
+ const completed = phases.filter(phase => phase.status === 'completed').length
1011
+ const skipped = phases.filter(phase => phase.status === 'skipped').length
1012
+ const failed = phases.filter(phase => phase.status === 'failed' || phase.status === 'cancelled').length
1013
+ goal.finishedAt = new Date(now()).toISOString()
1014
+ if (completed === phases.length) {
1015
+ goal.status = 'completed'
1016
+ event(goal, 'goal.completed', `${completed} phase(s) complete`)
1017
+ } else if (completed > 0) {
1018
+ goal.status = 'partial'
1019
+ event(goal, 'goal.partial', `${completed} complete, ${skipped} skipped, ${failed} failed`)
1020
+ } else {
1021
+ goal.status = 'failed'
1022
+ event(goal, 'goal.failed', `no phase completed (${skipped} skipped, ${failed} failed)`)
1023
+ }
1024
+ await store.write(goal)
1025
+ const label = goal.status === 'completed' ? '完成' : goal.status === 'partial' ? '部分完成' : '失败'
1026
+ announce(goal, `goal-${goal.status}`, `长期目标 ${goal.id} ${label}:${progressLine(goal)}。`
1027
+ + `完整记录:superagent_goal status goal_id=${goal.id}`)
1028
+ return true
1029
+ }
1030
+
1031
+ function stallReason(goal) {
1032
+ const phases = goal.phases ?? []
1033
+ const unfinished = phases.filter(phase => !PHASE_TERMINAL.has(phase.status))
1034
+ if (unfinished.length === 0) return null
1035
+ const running = unfinished.filter(phase => phase.status === 'running' || phase.status === 'verifying')
1036
+ const ready = unfinished.filter(phase => phase.status === 'ready')
1037
+ if (running.length === 0 && ready.length === 0) {
1038
+ return { reason: 'deadlock', detail: 'every remaining phase is blocked by a failed or skipped dependency' }
1039
+ }
1040
+ const started = Date.parse(goal.startedAt ?? goal.createdAt ?? '')
1041
+ const maxMs = goal.maxWallClockMinutes * 60000
1042
+ if (Number.isFinite(started) && now() - started >= maxMs) {
1043
+ return { reason: 'wall-clock', detail: `wall-clock limit ${goal.maxWallClockMinutes} minute(s) reached` }
1044
+ }
1045
+ const progress = Date.parse(goal.progressAt ?? goal.startedAt ?? goal.createdAt ?? '')
1046
+ if (Number.isFinite(progress) && now() - progress >= goal.stallAfterMinutes * 60000) {
1047
+ return {
1048
+ reason: 'no-progress',
1049
+ detail: `no phase completed in ${goal.stallAfterMinutes} minute(s)`,
1050
+ }
1051
+ }
1052
+ if ((Number(goal.noProgressAttempts) || 0) >= goal.maxAttemptsPerPhase * 2) {
1053
+ return {
1054
+ reason: 'no-progress',
1055
+ detail: `${goal.noProgressAttempts} phase attempt(s) without completing a phase`,
1056
+ }
1057
+ }
1058
+ return null
1059
+ }
1060
+
1061
+ async function tickGoal(goalId) {
1062
+ const release = await acquireFileLock(store.file(goalId).replace(/\.json$/, '.lock'), {
1063
+ staleMs: 60000,
1064
+ now,
1065
+ })
1066
+ if (!release) return
1067
+ try {
1068
+ const goal = await store.read(goalId)
1069
+ if (!goal || !GOAL_TICKABLE.has(goal.status)) return
1070
+ await refreshUsage(goal)
1071
+
1072
+ if (goal.status === 'planning') {
1073
+ if (!goal.decomposeRunId) {
1074
+ const parent = await owner(goal)
1075
+ if (!parent) {
1076
+ goal.status = 'paused'
1077
+ goal.pausedReason = 'owner-unavailable'
1078
+ await store.write(goal)
1079
+ return
1080
+ }
1081
+ await startDecompose(goal, parent)
1082
+ return
1083
+ }
1084
+ const run = await readRun(goal.decomposeRunId)
1085
+ if (!run) {
1086
+ goal.decomposeRunId = null
1087
+ await store.write(goal)
1088
+ return
1089
+ }
1090
+ if (run.status === 'interrupted') {
1091
+ const parent = await owner(goal)
1092
+ if (!parent) return
1093
+ try {
1094
+ await orchestrator.resume(run.id, parent, null)
1095
+ return
1096
+ } catch (error) {
1097
+ // A decompose run that cannot be resumed is restarted; it owns no
1098
+ // workspace artifacts, so this is not redoing finished work.
1099
+ goal.decomposeRunId = null
1100
+ event(goal, 'decompose.resume-failed', oneLine(error?.message ?? error, 400))
1101
+ await store.write(goal)
1102
+ return
1103
+ }
1104
+ }
1105
+ if (!TERMINAL_STATUSES.has(run.status)) return
1106
+ await settleDecompose(goal, run)
1107
+ return
1108
+ }
1109
+
1110
+ // running
1111
+ const parent = await owner(goal)
1112
+ if (!parent) {
1113
+ goal.status = 'paused'
1114
+ goal.pausedReason = 'owner-unavailable'
1115
+ event(goal, 'goal.paused', 'the owning session is not live')
1116
+ await store.write(goal)
1117
+ return
1118
+ }
1119
+
1120
+ let changed = false
1121
+ for (const phase of goal.phases) {
1122
+ if (phase.status === 'running') await reconcilePhase(goal, phase, parent)
1123
+ else if (phase.status === 'needs-decision') {
1124
+ const decision = openDecisions(goal).find(item => item.phaseId === phase.id && item.kind === 'worker-question')
1125
+ if (!decision) {
1126
+ phase.status = 'running'
1127
+ phase.currentRunId = phase.currentRunId ?? phase.runIds.at(-1) ?? null
1128
+ } else {
1129
+ // The question can also be answered from the board through
1130
+ // superagent_answer, which knows nothing about the goal record.
1131
+ // Treat an active run or a run with no open attention as answered.
1132
+ const run = await readRun(phase.currentRunId ?? phase.runIds.at(-1))
1133
+ const openAttention = (run?.attention?.items ?? []).filter(item => !item.answer)
1134
+ if (run && (!TERMINAL_STATUSES.has(run.status) || openAttention.length === 0)) {
1135
+ decision.answer = 'external'
1136
+ decision.answeredAt = new Date(now()).toISOString()
1137
+ phase.status = 'running'
1138
+ phase.currentRunId = run.id
1139
+ event(goal, 'decision.answered', `${decision.id}: answered through the run`, phase.id)
1140
+ }
1141
+ }
1142
+ }
1143
+ if (goal.status === 'needs-decision' && openDecisions(goal).length > 0) break
1144
+ }
1145
+ if (goal.status === 'needs-decision' && openDecisions(goal).length === 0) goal.status = 'running'
1146
+ if (goal.status === 'needs-decision') {
1147
+ await store.write(goal)
1148
+ return
1149
+ }
1150
+
1151
+ if (cascadeSkips(goal)) changed = true
1152
+ if (await settleGoal(goal)) return
1153
+
1154
+ // Resume interrupted work first: it is cheaper and never replays a phase.
1155
+ for (const phase of goal.phases) {
1156
+ if (phase.status !== 'ready' || !phase.resumeRunId) continue
1157
+ if (activePhaseCount(goal) >= goal.maxParallelPhases) break
1158
+ await resumePhase(goal, phase, parent)
1159
+ if (goal.status === 'needs-decision') break
1160
+ }
1161
+ if (goal.status === 'needs-decision') {
1162
+ await store.write(goal)
1163
+ return
1164
+ }
1165
+
1166
+ const ready = goal.phases.filter(phase => phase.status === 'ready' || (
1167
+ phase.status === 'pending'
1168
+ && phase.dependsOn.every(id => phaseById(goal, id)?.status === 'completed')
1169
+ ))
1170
+ for (const phase of ready) {
1171
+ if (activePhaseCount(goal) >= goal.maxParallelPhases) break
1172
+ try {
1173
+ const started = await startPhase(goal, phase, parent)
1174
+ if (!started) break
1175
+ changed = true
1176
+ } catch (error) {
1177
+ event(goal, 'phase.start-failed', oneLine(error?.message ?? error, 400), phase.id)
1178
+ await store.write(goal)
1179
+ break
1180
+ }
1181
+ }
1182
+
1183
+ const stall = goal.status === 'running' ? stallReason(goal) : null
1184
+ if (stall && openDecisions(goal).length === 0) {
1185
+ goal.status = 'needs-decision'
1186
+ addDecision(goal, {
1187
+ kind: 'stalled',
1188
+ question: `长期目标 ${goal.id} 停滞:${stall.detail}。可以继续(重置停滞计数)或停止。`,
1189
+ options: ['continue', 'stop'],
1190
+ reason: stall.reason,
1191
+ })
1192
+ announce(goal, 'goal-stalled', `长期目标 ${goal.id} 停滞:${stall.detail}。`
1193
+ + `用 superagent_goal answer goal_id=${goal.id} decision_id=… 决定继续或停止。`)
1194
+ }
1195
+
1196
+ if (changed) goal.updatedAt = new Date(now()).toISOString()
1197
+ await store.write(goal)
1198
+ } finally {
1199
+ await release()
1200
+ }
1201
+ }
1202
+
1203
+ async function tick() {
1204
+ if (closed) return []
1205
+ if (ticking) return ticking
1206
+ ticking = (async () => {
1207
+ const goals = await store.list()
1208
+ const processed = []
1209
+ for (const goal of goals) {
1210
+ if (!autoResumeFor(goal)) continue
1211
+ try {
1212
+ await tickGoal(goal.id)
1213
+ processed.push(goal.id)
1214
+ } catch (error) {
1215
+ log(`long-goal ${goal.id} tick failed: ${error?.message ?? error}`)
1216
+ }
1217
+ }
1218
+ const after = await store.list()
1219
+ if (after.some(goal => GOAL_ACTIVE.has(goal.status))) arm()
1220
+ return processed
1221
+ })()
1222
+ try {
1223
+ return await ticking
1224
+ } finally {
1225
+ ticking = null
1226
+ }
1227
+ }
1228
+
1229
+ function autoResumeFor(goal) {
1230
+ if (!goal?.autoResume) return false
1231
+ if (GOAL_ACTIVE.has(goal.status)) return true
1232
+ return goal.status === 'paused' && goal.pausedReason !== 'manual'
1233
+ }
1234
+
1235
+ /** Load goals and mark work left active by a dead host as resumable, not failed. */
1236
+ async function init() {
1237
+ await store.init()
1238
+ const goals = await store.list()
1239
+ let changed = 0
1240
+ for (const goal of goals) {
1241
+ let dirty = false
1242
+ if (!goal.autoResume) continue
1243
+ if (goal.status === 'paused' && goal.pausedReason !== 'manual') {
1244
+ goal.status = goal.phases?.length ? 'running' : 'planning'
1245
+ goal.pausedReason = null
1246
+ changed++
1247
+ dirty = true
1248
+ }
1249
+ if (!GOAL_ACTIVE.has(goal.status)) continue
1250
+ for (const phase of goal.phases ?? []) {
1251
+ if (phase.status !== 'running' || !phase.currentRunId) continue
1252
+ const run = await readRun(phase.currentRunId)
1253
+ if (!run) continue
1254
+ if (run.status === 'interrupted') {
1255
+ phase.status = 'ready'
1256
+ phase.resumeRunId = phase.currentRunId
1257
+ phase.currentRunId = null
1258
+ goal.recovery = {
1259
+ at: new Date(now()).toISOString(),
1260
+ reason: 'host-restart',
1261
+ phases: [...(goal.recovery?.phases ?? []), phase.id],
1262
+ }
1263
+ changed++
1264
+ dirty = true
1265
+ } else if (TERMINAL_STATUSES.has(run.status)) {
1266
+ // The run finished but the goal record did not; the next tick settles
1267
+ // it. Leaving the phase as running is what makes that happen.
1268
+ changed++
1269
+ }
1270
+ }
1271
+ if (goal.decomposeRunId) {
1272
+ const run = await readRun(goal.decomposeRunId)
1273
+ if (run?.status === 'interrupted') {
1274
+ goal.recovery = {
1275
+ at: new Date(now()).toISOString(),
1276
+ reason: 'host-restart',
1277
+ phases: goal.recovery?.phases ?? [],
1278
+ decomposeRunId: goal.decomposeRunId,
1279
+ }
1280
+ changed++
1281
+ dirty = true
1282
+ }
1283
+ }
1284
+ if (dirty) await store.write(goal)
1285
+ }
1286
+ changed && log(`long-goal: recovered ${changed} record(s)`)
1287
+ arm(1000)
1288
+ return goals
1289
+ }
1290
+
1291
+ function normalizeCreate(input) {
1292
+ if (!input || typeof input !== 'object') throw new Error('create requires an object')
1293
+ const goalText = requiredText(input.goal, 'goal')
1294
+ const cwd = path.resolve(String(input.cwd ?? input.workspace ?? process.cwd()))
1295
+ const limits = {
1296
+ maxParallelPhases: numberIn(
1297
+ input.maxParallelPhases,
1298
+ defaults.maxParallelPhases,
1299
+ 1,
1300
+ MAX_PHASES,
1301
+ 'maxParallelPhases',
1302
+ ),
1303
+ maxAttemptsPerPhase: numberIn(
1304
+ input.maxAttemptsPerPhase,
1305
+ defaults.maxAttemptsPerPhase,
1306
+ 1,
1307
+ 6,
1308
+ 'maxAttemptsPerPhase',
1309
+ ),
1310
+ maxRoundsPerPhase: numberIn(
1311
+ input.maxRoundsPerPhase,
1312
+ defaults.maxRoundsPerPhase,
1313
+ 1,
1314
+ 20,
1315
+ 'maxRoundsPerPhase',
1316
+ ),
1317
+ noProgressRounds: numberIn(input.noProgressRounds, defaults.noProgressRounds, 1, 10, 'noProgressRounds'),
1318
+ maxWallClockMinutes: numberIn(
1319
+ input.maxWallClockMinutes,
1320
+ DEFAULT_MAX_WALL_CLOCK_MINUTES,
1321
+ 1,
1322
+ 43200,
1323
+ 'maxWallClockMinutes',
1324
+ ),
1325
+ stallAfterMinutes: numberIn(
1326
+ input.stallAfterMinutes,
1327
+ DEFAULT_STALL_AFTER_MINUTES,
1328
+ 1,
1329
+ 10080,
1330
+ 'stallAfterMinutes',
1331
+ ),
1332
+ phaseWallClockMinutes: numberIn(
1333
+ input.phaseWallClockMinutes,
1334
+ defaults.phaseWallClockMinutes,
1335
+ 1,
1336
+ 720,
1337
+ 'phaseWallClockMinutes',
1338
+ ),
1339
+ }
1340
+ const phaseBudget = normalizeBudget(input.phaseBudget, 'phaseBudget') ?? defaults.phaseBudget ?? null
1341
+ const phasesInput = Array.isArray(input.phases) ? input.phases : null
1342
+ let phases = []
1343
+ if (phasesInput) {
1344
+ if (phasesInput.length === 0) throw new Error('phases must contain at least one phase')
1345
+ if (phasesInput.length > MAX_PHASES) throw new Error(`at most ${MAX_PHASES} phases are supported`)
1346
+ const seen = new Set()
1347
+ phases = phasesInput.map((entry, index) => normalizePhase(entry, index, {
1348
+ ...limits,
1349
+ cwd,
1350
+ }, seen))
1351
+ validatePhaseGraph(phases)
1352
+ }
1353
+ const goal = {
1354
+ id: newGoalId(now),
1355
+ schemaVersion: 1,
1356
+ goal: goalText,
1357
+ status: phases.length > 0 ? 'running' : 'planning',
1358
+ createdAt: new Date(now()).toISOString(),
1359
+ updatedAt: null,
1360
+ startedAt: phases.length > 0 ? new Date(now()).toISOString() : null,
1361
+ finishedAt: null,
1362
+ ownerSessionId: String(input.parentSessionId ?? input.ownerSessionId ?? '').trim() || null,
1363
+ cwd,
1364
+ autoResume: input.autoResume !== false,
1365
+ ...limits,
1366
+ phaseBudget,
1367
+ budget: normalizeBudget(input.budget, 'budget'),
1368
+ phases,
1369
+ decomposeRunId: null,
1370
+ decomposeAttempts: 0,
1371
+ decomposeReply: null,
1372
+ decisions: [],
1373
+ decisionSeq: 0,
1374
+ usage: { modelCalls: 0, tokens: 0 },
1375
+ events: [],
1376
+ progressAt: new Date(now()).toISOString(),
1377
+ noProgressAttempts: 0,
1378
+ stoppedReason: null,
1379
+ recovery: null,
1380
+ pausedReason: null,
1381
+ }
1382
+ event(goal, 'goal.created', `${phases.length > 0 ? `${phases.length} explicit phase(s)` : 'phase planning started'}`)
1383
+ return goal
1384
+ }
1385
+
1386
+ async function create(input = {}) {
1387
+ const goal = normalizeCreate(input)
1388
+ if (!goal.ownerSessionId) throw new Error('create requires a live owning session')
1389
+ await store.write(goal)
1390
+ arm(500)
1391
+ log(`long-goal ${goal.id} created (${goal.phases.length} phase(s))`)
1392
+ return goal
1393
+ }
1394
+
1395
+ async function get(goalId) {
1396
+ const goal = await store.read(goalId)
1397
+ if (!goal) throw new Error(`unknown long goal ${goalId}`)
1398
+ return goal
1399
+ }
1400
+
1401
+ async function status(goalId) {
1402
+ const goal = await get(goalId)
1403
+ const runs = {}
1404
+ for (const runId of goalRunIds(goal)) {
1405
+ const run = await readRun(runId)
1406
+ if (run) runs[runId] = run
1407
+ }
1408
+ return { goal, runs }
1409
+ }
1410
+
1411
+ async function list() {
1412
+ return store.list()
1413
+ }
1414
+
1415
+ async function cancelActiveRuns(goal) {
1416
+ const ids = goalRunIds(goal).filter(Boolean)
1417
+ for (const runId of ids) {
1418
+ try {
1419
+ const run = await readRun(runId)
1420
+ if (!run || TERMINAL_STATUSES.has(run.status)) continue
1421
+ await orchestrator.cancel(runId)
1422
+ event(goal, 'run.cancelled', runId)
1423
+ } catch (error) {
1424
+ log(`long-goal cannot cancel run ${runId}: ${error?.message ?? error}`)
1425
+ }
1426
+ }
1427
+ }
1428
+
1429
+ async function pause(goalId) {
1430
+ const goal = await get(goalId)
1431
+ if (!GOAL_ACTIVE.has(goal.status)) throw new Error(`goal ${goal.id} is ${goal.status}; only a running goal can be paused`)
1432
+ goal.status = 'paused'
1433
+ goal.pausedReason = 'manual'
1434
+ event(goal, 'goal.paused', 'paused by the user')
1435
+ await store.write(goal)
1436
+ return goal
1437
+ }
1438
+
1439
+ async function stop(goal, reason, { cancelled = false } = {}) {
1440
+ goal.status = cancelled ? 'cancelled' : 'failed'
1441
+ goal.stoppedReason = { reason, detail: reason, at: new Date(now()).toISOString() }
1442
+ goal.finishedAt = new Date(now()).toISOString()
1443
+ event(goal, cancelled ? 'goal.cancelled' : 'goal.failed', reason)
1444
+ await cancelActiveRuns(goal)
1445
+ await store.write(goal)
1446
+ announce(goal, cancelled ? 'goal-cancelled' : 'goal-failed', `长期目标 ${goal.id} ${cancelled ? '已取消' : '已停止'}(${reason})。`)
1447
+ return goal
1448
+ }
1449
+
1450
+ async function cancel(goalId) {
1451
+ const goal = await get(goalId)
1452
+ if (['completed', 'failed', 'cancelled', 'partial'].includes(goal.status)) return goal
1453
+ return stop(goal, 'cancelled by the user', { cancelled: true })
1454
+ }
1455
+
1456
+ async function resume(goalId) {
1457
+ const goal = await get(goalId)
1458
+ const open = openDecisions(goal)
1459
+ if (open.length > 0) {
1460
+ throw new Error(`goal ${goal.id} has an open decision (${open[0].id}); answer it first`)
1461
+ }
1462
+ if (['completed', 'failed', 'cancelled', 'partial', 'budget-stopped'].includes(goal.status)) {
1463
+ throw new Error(`goal ${goal.id} is ${goal.status} and cannot be resumed`)
1464
+ }
1465
+ goal.status = goal.phases?.length ? 'running' : 'planning'
1466
+ goal.pausedReason = null
1467
+ goal.progressAt = new Date(now()).toISOString()
1468
+ goal.noProgressAttempts = 0
1469
+ event(goal, 'goal.resumed', 'resumed by the user')
1470
+ await store.write(goal)
1471
+ arm(200)
1472
+ return goal
1473
+ }
1474
+
1475
+ /**
1476
+ * Apply one decision.
1477
+ *
1478
+ * A worker question is answered through the run's own attention path, so
1479
+ * there is exactly one place where an answer is validated and recorded.
1480
+ */
1481
+ async function answer(goalId, decisionId, value, { note = null, parent = null, clientTimeZone = null } = {}) {
1482
+ const goal = await get(goalId)
1483
+ const decision = (goal.decisions ?? []).find(item => item.id === decisionId)
1484
+ if (!decision) throw new Error(`unknown decision ${decisionId} on goal ${goalId}`)
1485
+ if (decision.answer) throw new Error(`decision ${decisionId} was already answered with "${decision.answer}"`)
1486
+ const choice = String(value ?? '').trim().toLowerCase()
1487
+ if (!decision.options.includes(choice)) {
1488
+ throw new Error(`decision ${decisionId} accepts ${decision.options.join(', ')}, not ${JSON.stringify(value)}`)
1489
+ }
1490
+ const phase = decision.phaseId ? phaseById(goal, decision.phaseId) : null
1491
+ if (choice === 'answer') {
1492
+ const runId = decision.source?.runId
1493
+ const attentionId = decision.source?.attentionId
1494
+ if (!runId || !attentionId) throw new Error('this decision has no run question to answer')
1495
+ const text = String(note ?? '').trim()
1496
+ if (!text) throw new Error('answer requires note: the answer text for the worker')
1497
+ const agent = parent ?? await owner(goal)
1498
+ if (!agent) throw new Error('no live owning session, so the worker cannot be resumed')
1499
+ await orchestrator.answer(runId, attentionId, text, agent, clientTimeZone)
1500
+ decision.answer = 'answer'
1501
+ decision.answeredAt = new Date(now()).toISOString()
1502
+ if (phase) {
1503
+ phase.status = 'running'
1504
+ phase.currentRunId = runId
1505
+ }
1506
+ goal.status = 'running'
1507
+ goal.progressAt = new Date(now()).toISOString()
1508
+ event(goal, 'decision.answered', `worker question answered on run ${runId}`, phase?.id ?? null)
1509
+ await store.write(goal)
1510
+ arm(200)
1511
+ return goal
1512
+ }
1513
+
1514
+ decision.answer = choice
1515
+ decision.answeredAt = new Date(now()).toISOString()
1516
+ if (note) decision.note = oneLine(note, 600)
1517
+ if (decision.kind === 'verification-conflict') {
1518
+ if (choice === 'accept') {
1519
+ if (phase) {
1520
+ phase.status = 'completed'
1521
+ phase.finishedAt = new Date(now()).toISOString()
1522
+ phase.lastSignature = null
1523
+ phase.lastOutcome = {
1524
+ ...(phase.lastOutcome ?? {}),
1525
+ acceptedByUser: true,
1526
+ acceptanceNote: note ? oneLine(note, 600) : null,
1527
+ }
1528
+ }
1529
+ goal.status = 'running'
1530
+ goal.progressAt = new Date(now()).toISOString()
1531
+ goal.noProgressAttempts = 0
1532
+ event(goal, 'phase.accepted', note ? oneLine(note, 300) : 'the user accepted the machine result', phase?.id ?? null)
1533
+ announce(goal, 'phase-completed', `长期目标 ${goal.id}:阶段 ${phase?.id}「${phase?.title}」按你的判断计为完成`
1534
+ + `(${progressLine(goal)})。`)
1535
+ } else if (choice === 'retry') {
1536
+ if (phase) {
1537
+ phase.status = 'ready'
1538
+ phase.resumeRunId = null
1539
+ phase.attempts = 0
1540
+ phase.lastSignature = null
1541
+ phase.retryNote = note ? oneLine(note, 1200) : phase.retryNote
1542
+ phase.finishedAt = null
1543
+ }
1544
+ goal.status = 'running'
1545
+ goal.progressAt = new Date(now()).toISOString()
1546
+ goal.noProgressAttempts = 0
1547
+ } else {
1548
+ return stop(goal, 'the user chose to stop after a verification conflict')
1549
+ }
1550
+ } else if (decision.kind === 'phase-exhausted' || decision.kind === 'resume-failed') {
1551
+ if (choice === 'retry') {
1552
+ if (phase) {
1553
+ phase.status = 'ready'
1554
+ phase.resumeRunId = null
1555
+ phase.attempts = 0
1556
+ phase.lastSignature = null
1557
+ phase.retryNote = note ? oneLine(note, 1200) : phase.retryNote
1558
+ phase.finishedAt = null
1559
+ }
1560
+ goal.status = 'running'
1561
+ goal.progressAt = new Date(now()).toISOString()
1562
+ goal.noProgressAttempts = 0
1563
+ } else if (choice === 'skip') {
1564
+ if (phase) {
1565
+ phase.status = 'skipped'
1566
+ phase.finishedAt = new Date(now()).toISOString()
1567
+ phase.lastOutcome = { runStatus: 'skipped', error: note ? oneLine(note, 400) : 'skipped by the user' }
1568
+ }
1569
+ goal.status = 'running'
1570
+ goal.progressAt = new Date(now()).toISOString()
1571
+ goal.noProgressAttempts = 0
1572
+ } else {
1573
+ return stop(goal, 'the user chose to stop after a phase failed')
1574
+ }
1575
+ } else if (decision.kind === 'stalled') {
1576
+ if (choice === 'continue') {
1577
+ goal.status = 'running'
1578
+ goal.progressAt = new Date(now()).toISOString()
1579
+ goal.noProgressAttempts = 0
1580
+ goal.stalledAt = null
1581
+ if (note) goal.continueNote = oneLine(note, 600)
1582
+ } else {
1583
+ return stop(goal, 'the user chose to stop a stalled goal')
1584
+ }
1585
+ } else if (decision.kind === 'worker-question') {
1586
+ return stop(goal, 'the user chose to stop after a worker question')
1587
+ }
1588
+ event(goal, 'decision.answered', `${decision.id}: ${choice}`, phase?.id ?? null)
1589
+ await store.write(goal)
1590
+ arm(200)
1591
+ return goal
1592
+ }
1593
+
1594
+ return {
1595
+ init,
1596
+ close,
1597
+ create,
1598
+ get,
1599
+ status,
1600
+ list,
1601
+ tick,
1602
+ answer,
1603
+ resume,
1604
+ pause,
1605
+ cancel,
1606
+ store,
1607
+ formatStatus,
1608
+ }
1609
+ }
1610
+
1611
+ /**
1612
+ * Parse a phase plan out of a planner reply.
1613
+ *
1614
+ * A reply that is JSON but has no usable phases is an error, not an empty plan:
1615
+ * treating it as empty would start a goal with nothing to do and report success.
1616
+ *
1617
+ * @param {string} text - planner reply.
1618
+ * @returns {{ phases: object[] | null, error: string | null }} parsed plan or why not.
1619
+ */
1620
+ export function parsePhasePlan(text) {
1621
+ let lastError = 'the phase planner returned no JSON object'
1622
+ for (const candidate of jsonCandidates(text)) {
1623
+ let parsed
1624
+ try {
1625
+ parsed = JSON.parse(candidate)
1626
+ } catch (error) {
1627
+ lastError = `the phase planner returned invalid JSON: ${error?.message ?? error}`
1628
+ continue
1629
+ }
1630
+ if (!Array.isArray(parsed?.phases)) {
1631
+ lastError = 'the phase planner JSON has no "phases" array'
1632
+ continue
1633
+ }
1634
+ if (parsed.phases.length === 0) {
1635
+ lastError = 'the phase planner returned an empty "phases" array'
1636
+ continue
1637
+ }
1638
+ return { phases: parsed.phases, error: null }
1639
+ }
1640
+ return { phases: null, error: lastError }
1641
+ }
1642
+
1643
+ /**
1644
+ * Render a goal for the tool reply: state, phase table, open decisions, next.
1645
+ *
1646
+ * @param {object} goal - goal record.
1647
+ * @param {Record<string, object>} [runs] - run snapshots keyed by run id.
1648
+ * @returns {string} Markdown.
1649
+ */
1650
+ export function formatStatus(goal, runs = {}) {
1651
+ const phases = goal.phases ?? []
1652
+ const completed = phases.filter(phase => phase.status === 'completed').length
1653
+ const open = (goal.decisions ?? []).filter(item => !item.answer)
1654
+ const used = goal.usage ?? { modelCalls: 0, tokens: 0 }
1655
+ const cap = goal.budget
1656
+ const lines = [
1657
+ `# Long goal ${goal.id} — ${goal.status}`,
1658
+ '',
1659
+ `Goal: ${oneLine(goal.goal, 500)}`,
1660
+ `Progress: ${completed}/${phases.length} phase(s) completed; ${used.modelCalls}`
1661
+ + `${cap?.maxModelCalls ? `/${cap.maxModelCalls}` : ''} model calls`
1662
+ + `${cap?.maxTokens ? `, ${used.tokens}/${cap.maxTokens} tokens` : ''}`,
1663
+ `Workspace: ${goal.cwd}`,
1664
+ ]
1665
+ if (goal.status === 'planning') {
1666
+ lines.push('', `Phase planning: attempt ${goal.decomposeAttempts}`
1667
+ + `${goal.decomposeRunId ? `, run ${goal.decomposeRunId}` : ''}`)
1668
+ }
1669
+ if (phases.length > 0) {
1670
+ lines.push('', 'Phases:')
1671
+ for (const phase of phases) {
1672
+ const runId = phase.currentRunId ?? phase.runIds.at(-1) ?? null
1673
+ const run = runId ? runs[runId] : null
1674
+ const detail = run
1675
+ ? `run ${run.id}: ${run.status}`
1676
+ + (run.goalMode ? `, round ${run.goalMode.rounds?.length ?? 0}/${run.goalMode.maxRounds}` : '')
1677
+ : runId ? `run ${runId}` : 'no run yet'
1678
+ const deps = phase.dependsOn.length > 0 ? `, after ${phase.dependsOn.join(', ')}` : ''
1679
+ lines.push(`- [${phase.status}] ${phase.id} ${phase.title} — attempts ${phase.attempts}, ${detail}${deps}`)
1680
+ if (phase.lastOutcome?.error) lines.push(` last: ${oneLine(phase.lastOutcome.error, 300)}`)
1681
+ }
1682
+ }
1683
+ if (goal.recovery) {
1684
+ lines.push('', `Recovered: ${goal.recovery.reason} at ${goal.recovery.at}`
1685
+ + `${(goal.recovery.phases ?? []).length > 0 ? ` (phases ${goal.recovery.phases.join(', ')})` : ''}`)
1686
+ }
1687
+ if (open.length > 0) {
1688
+ lines.push('', 'Needs your decision:')
1689
+ for (const decision of open) {
1690
+ lines.push(`- ${decision.id} (${decision.kind}): ${decision.question}`)
1691
+ lines.push(` options: ${decision.options.join(', ')}`)
1692
+ lines.push(` answer with: superagent_goal action=answer goal_id=${goal.id} decision_id=${decision.id} answer=<option>`
1693
+ + `${decision.kind === 'worker-question' ? ' note="<your answer>"' : ''}`)
1694
+ }
1695
+ }
1696
+ if (goal.stoppedReason) lines.push('', `Stopped: ${goal.stoppedReason.reason} — ${goal.stoppedReason.detail}`)
1697
+ lines.push('', 'Next:')
1698
+ if (goal.status === 'needs-decision') lines.push('- answer the open decision above; no new phase will start until then')
1699
+ else if (goal.status === 'completed') lines.push('- nothing; every phase met its acceptance conditions')
1700
+ else if (goal.status === 'partial') lines.push('- inspect the skipped phases in the table; start a new goal for the rest')
1701
+ else if (goal.status === 'failed') lines.push('- inspect the report; create a new goal with explicit phases if the framing was wrong')
1702
+ else if (goal.status === 'paused') lines.push('- superagent_goal action=resume when the owning session is available again')
1703
+ else lines.push('- poll with superagent_goal action=status; phase runs continue in the background')
1704
+ return lines.join('\n').trim()
1705
+ }