Repository navigation
Expand file tree
/
Copy pathgoal.ts
More file actions
251 lines (227 loc) · 10.3 KB
/
Copy pathgoal.ts
File metadata and controls
251 lines (227 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import { randomBytes } from 'node:crypto'
import { tool, type ToolDefinition } from './tool'
import type { ToolContext } from './types'
import { slugify } from '../utils/logger'
import { findCurrentGoalChunk } from '../utils/goal-chunks'
import { DEFAULT_GOAL_MAX_CHUNKS, MAX_GOAL_MAX_CHUNKS } from '../constants/goal'
import type { GoalChunkRow, GoalRow, GoalTask } from '../storage/repos/goals-repo'
const z = tool.schema
function generateGoalId(title: string): string {
return `${slugify(title).slice(0, 40)}-${randomBytes(3).toString('hex')}`
}
function iso(timestamp: number | null): string {
return timestamp === null ? 'unknown' : new Date(timestamp).toISOString()
}
function firstLine(text: string): string {
return text.split('\n')[0].trim()
}
function goalModelsLine(goal: GoalRow): string {
const execution = goal.executionModel ?? 'default'
const auditor = goal.auditorModel ?? 'default'
return `Models: execution ${execution} (variant ${goal.executionVariant ?? 'default'}) | auditor ${auditor} (variant ${goal.auditorVariant ?? 'default'})`
}
/** One task-list bullet, shared by the goal-write response and the goal detail view. */
function formatGoalTaskLine(task: GoalTask): string {
return task.ref ? `- [${task.ref}] ${task.title}` : `- ${task.title}`
}
type LoopStatusLookup = (loopName: string) => string | null
/**
* A note appended when a chunk's loop is no longer running, so the reader knows
* the chunk stalled and how to recover it. Null while the loop runs (or is
* unknown), leaving the plain "loop <name>" text.
*/
function stalledLoopNote(loopName: string | null, loopStatus: LoopStatusLookup): string | null {
if (!loopName) return null
const status = loopStatus(loopName)
if (!status || status === 'running') return null
return `(loop ${loopName}: ${status} — restart it with loop-status restart=true)`
}
function formatGoalListItem(goal: GoalRow, chunks: GoalChunkRow[], loopStatus: LoopStatusLookup): string[] {
const completed = chunks.filter((chunk) => chunk.stage === 'completed').length
const lines = [
`- ${goal.title} (${goal.goalId})`,
` Status: ${goal.status} | Chunks: ${completed}/${chunks.length} | Tasks: ${goal.tasks.length}`,
]
const current = findCurrentGoalChunk(chunks)
if (current) {
const note = stalledLoopNote(current.loopName, loopStatus)
if (note) lines.push(` Current: chunk ${current.chunkIndex + 1} ${current.stage} ${note}`)
else lines.push(` Current: chunk ${current.chunkIndex + 1} ${current.stage}${current.loopName ? ` loop ${current.loopName}` : ''}`)
}
if (goal.error) lines.push(` Error: ${goal.error}`)
return lines
}
function formatGoalDetail(goal: GoalRow, chunks: GoalChunkRow[], loopStatus: LoopStatusLookup): string {
const lines = [
`Goal: ${goal.goalId}`,
`Title: ${goal.title}`,
`Status: ${goal.status}`,
`Created: ${iso(goal.createdAt)}`,
]
if (goal.completedAt !== null) lines.push(`Completed: ${iso(goal.completedAt)}`)
if (goal.error) lines.push(`Error: ${goal.error}`)
lines.push(`Max chunks: ${goal.maxChunks}`, goalModelsLine(goal), `Objective: ${goal.objective}`, '', 'Tasks:')
if (goal.tasks.length === 0) {
lines.push('- (none)')
} else {
for (const task of goal.tasks) {
lines.push(formatGoalTaskLine(task))
}
}
const current = findCurrentGoalChunk(chunks)
lines.push('', 'Chunks:')
if (chunks.length === 0) {
lines.push('- (none)')
} else {
for (const chunk of chunks) {
lines.push(`${chunk.chunkIndex + 1}. ${chunk.title ?? '(planning)'} — ${chunk.stage}`)
if (chunk.loopName) {
const note = chunk === current ? stalledLoopNote(chunk.loopName, loopStatus) : null
lines.push(note ? ` Loop: ${chunk.loopName} ${note}` : ` Loop: ${chunk.loopName}`)
}
if (chunk.branch) lines.push(` Branch: ${chunk.branch}`)
if (chunk.summary) lines.push(` Summary: ${firstLine(chunk.summary)}`)
}
}
return lines.join('\n')
}
export function createGoalTools(ctx: ToolContext): Record<string, ToolDefinition> {
const loopStatus: LoopStatusLookup = (loopName) => ctx.loop?.inspect(loopName)?.status ?? null
return {
'goal-write': tool({
description:
'Save the ordered goal (objective and task list) for this session as a draft. The next loop launched from this session becomes chunk 1; later chunks are planned and launched automatically, each stacked on the previous chunk branch, until every task is done.',
args: {
title: z.string().describe('Short title for the goal; also seeds the generated goal id.'),
objective: z.string().describe('The goal objective, verbatim plus any clarified scope.'),
tasks: z
.array(
z.object({
ref: z.string().optional().describe('Ticket or issue identifier, when the task maps to one.'),
title: z.string().describe('Short task title.'),
details: z
.string()
.optional()
.describe('Self-contained summary of the task including its acceptance criteria.'),
}),
)
.optional()
.describe('The ordered task list; each task becomes its own chunk.'),
maxChunks: z
.number()
.int()
.min(1)
.max(MAX_GOAL_MAX_CHUNKS)
.optional()
.describe(`Maximum number of chunks to run. Defaults to ${DEFAULT_GOAL_MAX_CHUNKS}.`),
},
execute: async (args, context) => {
const title = args.title.trim()
if (!title) return 'goal-write failed: title is required.'
const objective = args.objective.trim()
if (!objective) return 'goal-write failed: objective is required.'
const rawTasks = args.tasks ?? []
for (let i = 0; i < rawTasks.length; i++) {
if (!rawTasks[i].title.trim()) {
return `goal-write failed: task ${i + 1} has an empty title.`
}
}
const maxChunks = args.maxChunks ?? DEFAULT_GOAL_MAX_CHUNKS
if (maxChunks < 1 || maxChunks > MAX_GOAL_MAX_CHUNKS) {
return `goal-write failed: maxChunks must be between 1 and ${MAX_GOAL_MAX_CHUNKS}.`
}
const active = ctx.goalsRepo.getActiveForSession(ctx.projectId, context.sessionID)
if (active) {
return `This session already has goal ${active.goalId} (${active.status}). Cancel it before defining a new goal.`
}
const tasks: GoalTask[] = rawTasks.map((task) => {
const ref = task.ref?.trim()
const details = task.details?.trim()
return {
title: task.title.trim(),
...(ref ? { ref } : {}),
...(details ? { details } : {}),
}
})
const goal = ctx.goalsRepo.saveDraft({
projectId: ctx.projectId,
goalId: generateGoalId(title),
title,
objective,
tasks,
hostSessionId: context.sessionID,
maxChunks,
})
ctx.logger.log(`goal-write: saved draft goal ${goal.goalId} for session ${context.sessionID}`)
const lines = [
`Goal draft saved: ${goal.goalId}`,
`Title: ${goal.title}`,
`Tasks: ${goal.tasks.length}`,
]
for (const task of goal.tasks) {
lines.push(formatGoalTaskLine(task))
}
lines.push(
`Max chunks: ${goal.maxChunks}`,
'Next: write the detailed loop plan for chunk 1 (the first task) with plan-write. When the user launches it as a loop, it becomes chunk 1 of this goal; later chunks are planned and launched automatically with the same models and sandbox settings.',
)
return lines.join('\n')
},
}),
'goal-status': tool({
description:
'Lists goals when called with no arguments. Pass goalId for details. Use restart to resume a paused goal (optionally raising maxChunks) or to recover an interrupted one; force discards planning that is still marked in flight.',
args: {
goalId: z.string().optional().describe('Goal id to show in detail, or to restart when restart=true.'),
restart: z.boolean().optional().default(false).describe('Restart a paused or interrupted goal. Requires goalId.'),
force: z.boolean().optional().default(false).describe('Discard planning that is still marked in flight when restarting.'),
maxChunks: z
.number()
.int()
.min(1)
.max(MAX_GOAL_MAX_CHUNKS)
.optional()
.describe('Raise the goal chunk limit when restarting.'),
},
execute: async (args) => {
if (args.restart) {
if (!args.goalId) {
return 'Specify a goal id to restart. Use goal-status to see available goals.'
}
return ctx.goalOrchestrator.restart(args.goalId, { maxChunks: args.maxChunks, force: args.force ?? false })
}
if (args.goalId) {
const goal = ctx.goalsRepo.getGoal(ctx.projectId, args.goalId)
if (!goal) return `Goal ${args.goalId} not found.`
return formatGoalDetail(goal, ctx.goalsRepo.listChunks(ctx.projectId, goal.goalId), loopStatus)
}
const goals = ctx.goalsRepo.listGoals(ctx.projectId)
if (goals.length === 0) return 'No goals found.'
const chunksByGoal = ctx.goalsRepo.listChunksByProject(ctx.projectId)
const lines = [`Goals (${goals.length})`, '']
for (const goal of goals) {
lines.push(...formatGoalListItem(goal, chunksByGoal.get(goal.goalId) ?? [], loopStatus))
lines.push('')
}
lines.push('Use goal-status <goalId> for details, or goal-cancel <goalId> to cancel a goal.')
return lines.join('\n')
},
}),
'goal-cancel': tool({
description: 'Cancel a goal by goalId. Optionally cancel its running chunk loop.',
args: {
goalId: z.string().describe('Goal id to cancel.'),
cancelRunningLoops: z
.boolean()
.optional()
.default(false)
.describe('Also cancel the goal chunk loop that is currently running.'),
},
execute: async (args) => {
const goal = ctx.goalsRepo.getGoal(ctx.projectId, args.goalId)
if (!goal) return `Goal ${args.goalId} not found.`
return ctx.goalOrchestrator.cancel(args.goalId, { cancelRunningLoops: args.cancelRunningLoops ?? false })
},
}),
}
}