Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | #!/usr/bin/env bun |
| 2 | import { createHash, randomUUID } from 'node:crypto'; |
| 3 | import { execFileSync, spawn } from 'node:child_process'; |
| 4 | import fs from 'node:fs'; |
| 5 | import path from 'node:path'; |
| 6 | import type { ChildProcessByStdio } from 'node:child_process'; |
| 7 | import type { Readable } from 'node:stream'; |
| 8 | import { Effect, Option, Runtime } from 'effect'; |
| 9 | import { Argument, Command as CliCommand, Flag } from 'effect/cli'; |
| 10 | import * as BunServices from '@effect/platform-bun/BunServices'; |
| 11 | |
| 12 | type State = 'pending' | 'running' | 'passed' | 'failed' | 'interrupted' | 'stale'; |
| 13 | interface Command { |
| 14 | cwd: string; |
| 15 | argv: string[]; |
| 16 | } |
| 17 | interface Profile { |
| 18 | boundary: string; |
| 19 | commands: Command[]; |
| 20 | } |
| 21 | interface Task { |
| 22 | version: number; |
| 23 | id: string; |
| 24 | goal: string; |
| 25 | profile: string; |
| 26 | source: string | null; |
| 27 | authority: string | null; |
| 28 | nextStep: string | null; |
| 29 | blocker: string | null; |
| 30 | createdAt: string; |
| 31 | } |
| 32 | interface Subject { |
| 33 | head: string; |
| 34 | fingerprint: string; |
| 35 | } |
| 36 | interface CommandResult extends Command { |
| 37 | startedAt: string; |
| 38 | finishedAt: string | null; |
| 39 | exitCode: number | null; |
| 40 | signal: NodeJS.Signals | null; |
| 41 | pid?: number | null; |
| 42 | error?: string; |
| 43 | } |
| 44 | interface Receipt { |
| 45 | version: number; |
| 46 | id: string; |
| 47 | runnerPid: number; |
| 48 | startedAt: string; |
| 49 | finishedAt: string | null; |
| 50 | status: State; |
| 51 | taskDigest: string; |
| 52 | profileDigest: string; |
| 53 | subject: Subject | null; |
| 54 | boundary: string; |
| 55 | commands: CommandResult[]; |
| 56 | bunVersion: string; |
| 57 | error?: string; |
| 58 | logTruncated?: boolean; |
| 59 | } |
| 60 | type StoredReceipt = Partial<Receipt> & Pick<Receipt, 'id' | 'status'> & { file: string }; |
| 61 | interface LockOwner { |
| 62 | pid: number; |
| 63 | task: string; |
| 64 | } |
| 65 | const errorCode = (error: unknown) => |
| 66 | error instanceof Error && 'code' in error ? error.code : undefined; |
| 67 | const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); |
| 68 | |
| 69 | const root = path.resolve(import.meta.dir, '..'); |
| 70 | const tasksRoot = path.join(root, '.artifacts/agent-tasks'); |
| 71 | // Locks live outside the task namespace so no task id can collide with them. |
| 72 | const locksRoot = path.join(root, '.artifacts/agent-locks'); |
| 73 | const logHeadLimit = 16 * 1024; |
| 74 | const logTailLimit = 48 * 1024; |
| 75 | const readJSON = <T>(file: string): T => JSON.parse(fs.readFileSync(file, 'utf8')); |
| 76 | const digest = (value: unknown) => |
| 77 | createHash('sha256') |
| 78 | .update(JSON.stringify(value) ?? 'null') |
| 79 | .digest('hex'); |
| 80 | const taskDigest = ({ version, id, goal, profile, source, authority }: Task) => |
| 81 | digest({ version, id, goal, profile, source, authority }); |
| 82 | const now = () => new Date().toISOString(); |
| 83 | const processGroup = (pid: number) => (process.platform === 'win32' ? pid : -pid); |
| 84 | const print = (value: unknown) => console.log(JSON.stringify(value, null, 2)); |
| 85 | const git = (args: string[], cwd = root) => |
| 86 | execFileSync('git', args, { cwd, maxBuffer: 64 * 1024 * 1024 }); |
| 87 | const writeJSON = (file: string, value: unknown) => { |
| 88 | fs.writeFileSync(`${file}.tmp`, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); |
| 89 | fs.renameSync(`${file}.tmp`, file); |
| 90 | }; |
| 91 | |
| 92 | const taskIdPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; |
| 93 | function taskDirectory(id: string) { |
| 94 | if (!taskIdPattern.test(id ?? '')) |
| 95 | throw new Error( |
| 96 | 'Use a task id of 1-64 letters, digits, dots, underscores or hyphens, starting with a letter or digit.' |
| 97 | ); |
| 98 | return path.join(tasksRoot, id); |
| 99 | } |
| 100 | |
| 101 | function profileFor(task: Task) { |
| 102 | const profile = readJSON<Record<string, Profile>>(path.join(root, 'scripts/agent-profiles.json'))[ |
| 103 | task.profile |
| 104 | ]; |
| 105 | if ( |
| 106 | !profile || |
| 107 | typeof profile.boundary !== 'string' || |
| 108 | !Array.isArray(profile.commands) || |
| 109 | profile.commands.length === 0 |
| 110 | ) |
| 111 | throw new Error(`Unknown or empty profile: ${task.profile}`); |
| 112 | for (const command of profile.commands) { |
| 113 | if ( |
| 114 | !Array.isArray(command.argv) || |
| 115 | command.argv.length === 0 || |
| 116 | command.argv.some(arg => typeof arg !== 'string') || |
| 117 | typeof command.cwd !== 'string' |
| 118 | ) |
| 119 | throw new Error('Profiles require cwd and a nonempty argv array.'); |
| 120 | const relative = path.relative(root, path.resolve(root, command.cwd)); |
| 121 | if (relative.startsWith('..') || path.isAbsolute(relative)) |
| 122 | throw new Error('Profile cwd must stay inside the repository.'); |
| 123 | } |
| 124 | return profile; |
| 125 | } |
| 126 | |
| 127 | function alive(pid: number | null | undefined) { |
| 128 | if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid === 0) return false; |
| 129 | try { |
| 130 | process.kill(pid, 0); |
| 131 | return true; |
| 132 | } catch (error) { |
| 133 | if (errorCode(error) === 'ESRCH') return false; |
| 134 | if (errorCode(error) === 'EPERM') return true; |
| 135 | throw error; |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // Attempts are numbered under the worktree lock, so their order does not depend on the clock. |
| 140 | const attemptNumber = (name: string) => Number.parseInt(name, 10); |
| 141 | function latestAttempt(directory: string) { |
| 142 | const attempts = path.join(directory, 'attempts'); |
| 143 | return fs.existsSync(attempts) |
| 144 | ? fs |
| 145 | .readdirSync(attempts) |
| 146 | .filter(name => Number.isSafeInteger(attemptNumber(name))) |
| 147 | .sort((a, b) => attemptNumber(a) - attemptNumber(b)) |
| 148 | .at(-1) |
| 149 | : undefined; |
| 150 | } |
| 151 | |
| 152 | function latestReceipt(directory: string): StoredReceipt | null { |
| 153 | const attempts = path.join(directory, 'attempts'); |
| 154 | const latest = latestAttempt(directory); |
| 155 | if (!latest) return null; |
| 156 | const file = path.join(attempts, latest, 'receipt.json'); |
| 157 | return fs.existsSync(file) |
| 158 | ? { file, ...readJSON<Receipt>(file) } |
| 159 | : { file, id: latest, status: 'interrupted' }; |
| 160 | } |
| 161 | |
| 162 | function taskIds() { |
| 163 | return fs.existsSync(tasksRoot) |
| 164 | ? fs |
| 165 | .readdirSync(tasksRoot) |
| 166 | .filter( |
| 167 | name => |
| 168 | taskIdPattern.test(name) && |
| 169 | fs.statSync(path.join(tasksRoot, name), { throwIfNoEntry: false })?.isDirectory() |
| 170 | ) |
| 171 | .sort() |
| 172 | : []; |
| 173 | } |
| 174 | |
| 175 | function readLockOwner(file: string): LockOwner | null { |
| 176 | let owner: Partial<LockOwner> | null; |
| 177 | try { |
| 178 | owner = readJSON<Partial<LockOwner> | null>(file); |
| 179 | } catch (error) { |
| 180 | if (error instanceof SyntaxError) return null; |
| 181 | throw error; |
| 182 | } |
| 183 | return typeof owner?.pid === 'number' && |
| 184 | Number.isSafeInteger(owner.pid) && |
| 185 | owner.pid > 0 && |
| 186 | typeof owner.task === 'string' && |
| 187 | taskIdPattern.test(owner.task) |
| 188 | ? { pid: owner.pid, task: owner.task } |
| 189 | : null; |
| 190 | } |
| 191 | |
| 192 | // A command saved without a pid may have started before its runner died, so its group is unknown. |
| 193 | function commandGroupBlocker(receipt: StoredReceipt | null) { |
| 194 | const command = receipt?.commands?.at(-1); |
| 195 | if (!command) return null; |
| 196 | if (command.pid === undefined && !command.finishedAt) |
| 197 | return `command \`${command.argv.join(' ')}\` has no recorded process group and may still be running. Stop any process it started, then remove the lock`; |
| 198 | return alive(command.pid ? processGroup(command.pid) : undefined) |
| 199 | ? `command group ${command.pid} remains. Inspect and stop that group before retrying` |
| 200 | : null; |
| 201 | } |
| 202 | |
| 203 | const groupAlive = (pid: number) => alive(processGroup(pid)); |
| 204 | const signalGroup = (pid: number, signal: NodeJS.Signals) => { |
| 205 | try { |
| 206 | process.kill(processGroup(pid), signal); |
| 207 | } catch (error) { |
| 208 | if (errorCode(error) !== 'ESRCH') throw error; |
| 209 | } |
| 210 | }; |
| 211 | |
| 212 | // A command can exit while workers it started keep running and writing shared outputs. |
| 213 | async function endGroup(pid: number) { |
| 214 | for (const [signal, grace] of [ |
| 215 | ['SIGTERM', 1500], |
| 216 | ['SIGKILL', 5000], |
| 217 | ] as const) { |
| 218 | if (!groupAlive(pid)) return; |
| 219 | signalGroup(pid, signal); |
| 220 | for (let waited = 0; waited < grace && groupAlive(pid); waited += 25) await Bun.sleep(25); |
| 221 | } |
| 222 | if (groupAlive(pid)) throw new Error(`Command group ${pid} survived SIGKILL.`); |
| 223 | } |
| 224 | |
| 225 | // Without a readable owner, only the attempts themselves can show that verification is still live. |
| 226 | function assertNoLiveAttempt(file: string) { |
| 227 | for (const id of taskIds()) { |
| 228 | let receipt: StoredReceipt | null; |
| 229 | try { |
| 230 | receipt = latestReceipt(taskDirectory(id)); |
| 231 | } catch { |
| 232 | continue; |
| 233 | } |
| 234 | if (receipt?.status !== 'running') continue; |
| 235 | if (alive(receipt.runnerPid) || commandGroupBlocker(receipt)) |
| 236 | throw new Error( |
| 237 | `${file} is unreadable and task ${id} still has a running attempt (runner ${receipt.runnerPid}); inspect ${receipt.file} before retrying.` |
| 238 | ); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | function lockTask(task: string) { |
| 243 | const file = path.join(locksRoot, 'verify.lock'); |
| 244 | const acquisitionFile = path.join(locksRoot, 'acquire.lock'); |
| 245 | fs.mkdirSync(locksRoot, { recursive: true, mode: 0o700 }); |
| 246 | const acquisition = fs.openSync(acquisitionFile, 'wx', 0o600); |
| 247 | try { |
| 248 | fs.writeFileSync(acquisition, String(process.pid)); |
| 249 | const owner = fs.existsSync(file) ? readLockOwner(file) : undefined; |
| 250 | if (owner === null) { |
| 251 | assertNoLiveAttempt(file); |
| 252 | console.error(`Replacing unreadable lock ${file}; no task attempt is still running.`); |
| 253 | fs.unlinkSync(file); |
| 254 | } else if (owner) { |
| 255 | if (alive(owner.pid)) |
| 256 | throw new Error( |
| 257 | `Worktree verification is owned by task ${owner.task} (runner ${owner.pid}); inspect ${file} before retrying.` |
| 258 | ); |
| 259 | const previous = latestReceipt(taskDirectory(owner.task)); |
| 260 | const blocker = commandGroupBlocker(previous); |
| 261 | if (blocker) |
| 262 | throw new Error( |
| 263 | `Runner ${owner.pid} ended but its ${blocker}. Lock: ${file}. Receipt: ${previous?.file}.` |
| 264 | ); |
| 265 | fs.unlinkSync(file); |
| 266 | } |
| 267 | const handle = fs.openSync(file, 'wx', 0o600); |
| 268 | try { |
| 269 | fs.writeFileSync(handle, JSON.stringify({ pid: process.pid, task })); |
| 270 | } catch (error) { |
| 271 | fs.unlinkSync(file); |
| 272 | throw error; |
| 273 | } finally { |
| 274 | fs.closeSync(handle); |
| 275 | } |
| 276 | return file; |
| 277 | } finally { |
| 278 | fs.closeSync(acquisition); |
| 279 | fs.unlinkSync(acquisitionFile); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | // Claude Code rewrites this tracked file while sessions run; it is not a verification input. |
| 284 | const volatilePaths = ['.claude/scheduled_tasks.lock']; |
| 285 | |
| 286 | function subject() { |
| 287 | const hash = createHash('sha256'); |
| 288 | const addTree = (cwd: string, prefix = '') => { |
| 289 | const pathspec = prefix ? [] : ['--', '.', ...volatilePaths.map(file => `:(exclude)${file}`)]; |
| 290 | hash.update(git(['ls-files', '--stage', '-z', ...pathspec], cwd)); |
| 291 | const names = new Set( |
| 292 | git(['ls-files', '--cached', '--others', '--exclude-standard', '-z', ...pathspec], cwd) |
| 293 | .toString() |
| 294 | .split('\0') |
| 295 | .filter(Boolean) |
| 296 | ); |
| 297 | for (const name of [...names].sort()) { |
| 298 | hash.update(`${prefix}${name}\0`); |
| 299 | const file = path.join(cwd, name); |
| 300 | try { |
| 301 | const stat = fs.lstatSync(file); |
| 302 | hash.update(`${stat.mode}\0`); |
| 303 | if (stat.isSymbolicLink()) hash.update(fs.readlinkSync(file)); |
| 304 | else if (stat.isFile()) hash.update(fs.readFileSync(file)); |
| 305 | else if (stat.isDirectory() && fs.existsSync(path.join(file, '.git'))) |
| 306 | addTree(file, `${prefix}${name}/`); |
| 307 | } catch (error) { |
| 308 | if (errorCode(error) !== 'ENOENT') throw error; |
| 309 | hash.update('deleted'); |
| 310 | } |
| 311 | hash.update('\0'); |
| 312 | } |
| 313 | }; |
| 314 | addTree(root); |
| 315 | return { head: git(['rev-parse', 'HEAD']).toString().trim(), fingerprint: hash.digest('hex') }; |
| 316 | } |
| 317 | |
| 318 | function status(id: string) { |
| 319 | const directory = taskDirectory(id); |
| 320 | const task = readJSON<Task>(path.join(directory, 'task.json')); |
| 321 | const receipt = latestReceipt(directory); |
| 322 | let state = receipt?.status ?? 'pending'; |
| 323 | if (state === 'running' && receipt && !alive(receipt.runnerPid)) state = 'interrupted'; |
| 324 | if (state === 'passed' && receipt) { |
| 325 | const profile = profileFor(task); |
| 326 | const complete = |
| 327 | receipt.commands?.length === profile.commands.length && |
| 328 | receipt.commands.every(command => command.exitCode === 0 && command.finishedAt); |
| 329 | state = |
| 330 | complete && |
| 331 | receipt.taskDigest === taskDigest(task) && |
| 332 | receipt.profileDigest === digest(profile) && |
| 333 | digest(receipt.subject) === digest(subject()) |
| 334 | ? 'passed' |
| 335 | : 'stale'; |
| 336 | } |
| 337 | return { |
| 338 | task, |
| 339 | status: state, |
| 340 | boundary: receipt?.boundary ?? profileFor(task).boundary, |
| 341 | receipt: receipt ? path.relative(root, receipt.file) : null, |
| 342 | }; |
| 343 | } |
| 344 | |
| 345 | async function verify(id: string) { |
| 346 | const directory = taskDirectory(id); |
| 347 | const task = readJSON<Task>(path.join(directory, 'task.json')); |
| 348 | const profile = profileFor(task); |
| 349 | const lock = lockTask(id); |
| 350 | const attempt = String(attemptNumber(latestAttempt(directory) ?? '0') + 1); |
| 351 | const attemptDirectory = path.join(directory, 'attempts', attempt); |
| 352 | const receiptFile = path.join(attemptDirectory, 'receipt.json'); |
| 353 | const receipt: Receipt = { |
| 354 | version: 1, |
| 355 | id: attempt, |
| 356 | runnerPid: process.pid, |
| 357 | startedAt: now(), |
| 358 | finishedAt: null, |
| 359 | status: 'running', |
| 360 | taskDigest: taskDigest(task), |
| 361 | profileDigest: digest(profile), |
| 362 | subject: null, |
| 363 | boundary: profile.boundary, |
| 364 | commands: [], |
| 365 | bunVersion: Bun.version, |
| 366 | }; |
| 367 | let child: ChildProcessByStdio<null, Readable, Readable> | undefined; |
| 368 | let cancellation: Promise<void> | undefined; |
| 369 | let interrupted: NodeJS.Signals | undefined; |
| 370 | let logBytes = 0; |
| 371 | // The log keeps the start and end of combined output; late failures matter most. |
| 372 | let logHead = 0; |
| 373 | const logTail: Buffer[] = []; |
| 374 | let logTailBytes = 0; |
| 375 | let flushTimer: ReturnType<typeof setTimeout> | undefined; |
| 376 | const flushLog = () => { |
| 377 | clearTimeout(flushTimer); |
| 378 | flushTimer = undefined; |
| 379 | if (logBytes === logHead) return; |
| 380 | const tail = Buffer.concat(logTail).subarray(-logTailLimit); |
| 381 | const omitted = logBytes - logHead - tail.length; |
| 382 | const head = fs.readFileSync(logFile).subarray(0, logHead); |
| 383 | const marker = omitted > 0 ? `\n[agent-task: ${omitted} bytes of output omitted]\n` : ''; |
| 384 | fs.writeFileSync(logFile, Buffer.concat([head, Buffer.from(marker), tail])); |
| 385 | }; |
| 386 | const stop = (signal: NodeJS.Signals) => { |
| 387 | interrupted = signal; |
| 388 | if (!child?.pid || cancellation) return; |
| 389 | const pid = child.pid; |
| 390 | signalGroup(pid, signal); |
| 391 | cancellation = new Promise<void>(resolve => |
| 392 | setTimeout(() => { |
| 393 | // Once the command closes, its group id may be reused; endGroup owns any stragglers. |
| 394 | if (child?.pid === pid) signalGroup(pid, 'SIGKILL'); |
| 395 | resolve(); |
| 396 | }, 1500) |
| 397 | ); |
| 398 | }; |
| 399 | // A closed terminal sends SIGHUP; detached command groups would otherwise outlive the runner. |
| 400 | const stopSignals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const; |
| 401 | for (const signal of stopSignals) process.on(signal, stop); |
| 402 | const logFile = path.join(attemptDirectory, 'output.log'); |
| 403 | try { |
| 404 | fs.mkdirSync(attemptDirectory, { recursive: true, mode: 0o700 }); |
| 405 | fs.writeFileSync(logFile, '', { mode: 0o600 }); |
| 406 | writeJSON(receiptFile, receipt); |
| 407 | receipt.subject = subject(); |
| 408 | writeJSON(receiptFile, receipt); |
| 409 | for (const command of profile.commands) { |
| 410 | if (interrupted) break; |
| 411 | const result: CommandResult = { |
| 412 | ...command, |
| 413 | startedAt: now(), |
| 414 | finishedAt: null, |
| 415 | exitCode: null, |
| 416 | signal: null, |
| 417 | }; |
| 418 | receipt.commands.push(result); |
| 419 | writeJSON(receiptFile, receipt); |
| 420 | await new Promise<void>(resolve => { |
| 421 | child = spawn(command.argv[0], command.argv.slice(1), { |
| 422 | cwd: path.resolve(root, command.cwd), |
| 423 | shell: false, |
| 424 | detached: process.platform !== 'win32', |
| 425 | stdio: ['ignore', 'pipe', 'pipe'], |
| 426 | }); |
| 427 | result.pid = child.pid ?? null; |
| 428 | writeJSON(receiptFile, receipt); |
| 429 | const output = (chunk: Uint8Array) => { |
| 430 | process.stderr.write(chunk); |
| 431 | logBytes += chunk.length; |
| 432 | const head = chunk.subarray(0, logHeadLimit - logHead); |
| 433 | if (head.length > 0) { |
| 434 | fs.appendFileSync(logFile, head); |
| 435 | logHead += head.length; |
| 436 | } |
| 437 | if (head.length === chunk.length) return; |
| 438 | logTail.push(Buffer.from(chunk.subarray(head.length))); |
| 439 | logTailBytes += chunk.length - head.length; |
| 440 | while (logTailBytes - logTail[0]!.length >= logTailLimit) |
| 441 | logTailBytes -= logTail.shift()!.length; |
| 442 | // Save the tail while the command runs so a killed runner keeps recent diagnostics. |
| 443 | flushTimer ??= setTimeout(() => { |
| 444 | try { |
| 445 | flushLog(); |
| 446 | } catch {} |
| 447 | }, 250); |
| 448 | }; |
| 449 | child.stdout.on('data', output); |
| 450 | child.stderr.on('data', output); |
| 451 | child.on('error', error => { |
| 452 | result.error = error.message; |
| 453 | }); |
| 454 | child.on('close', (code, signal) => { |
| 455 | result.exitCode = code; |
| 456 | result.signal = signal; |
| 457 | resolve(); |
| 458 | }); |
| 459 | }); |
| 460 | // Interrupts stop targeting the group here; endGroup signals it only while it still has members. |
| 461 | child = undefined; |
| 462 | if (result.pid) await endGroup(result.pid); |
| 463 | result.finishedAt = now(); |
| 464 | flushLog(); |
| 465 | writeJSON(receiptFile, receipt); |
| 466 | if (result.exitCode !== 0 || result.error) break; |
| 467 | } |
| 468 | receipt.status = interrupted |
| 469 | ? 'interrupted' |
| 470 | : receipt.commands.length === profile.commands.length && |
| 471 | receipt.commands.every(command => command.exitCode === 0 && !command.error) |
| 472 | ? 'passed' |
| 473 | : 'failed'; |
| 474 | if ( |
| 475 | receipt.status === 'passed' && |
| 476 | (digest(receipt.subject) !== digest(subject()) || |
| 477 | receipt.taskDigest !== taskDigest(readJSON<Task>(path.join(directory, 'task.json'))) || |
| 478 | receipt.profileDigest !== digest(profileFor(task))) |
| 479 | ) |
| 480 | receipt.status = 'stale'; |
| 481 | } catch (error) { |
| 482 | receipt.status = 'failed'; |
| 483 | receipt.error = errorMessage(error); |
| 484 | } finally { |
| 485 | await cancellation; |
| 486 | // Release the worktree only once the last command group is gone. A finished command's group |
| 487 | // was already ended, and its id may since belong to an unrelated process group. |
| 488 | let groupEnded = true; |
| 489 | const last = receipt.commands.at(-1); |
| 490 | if (last?.pid && !last.finishedAt) |
| 491 | await endGroup(last.pid).catch((error: unknown) => { |
| 492 | groupEnded = false; |
| 493 | receipt.status = 'failed'; |
| 494 | receipt.error ??= errorMessage(error); |
| 495 | }); |
| 496 | receipt.finishedAt = now(); |
| 497 | receipt.logTruncated = logBytes > logHeadLimit + logTailLimit; |
| 498 | try { |
| 499 | flushLog(); |
| 500 | } catch (error) { |
| 501 | receipt.error ??= `Could not write the output log: ${errorMessage(error)}`; |
| 502 | } |
| 503 | try { |
| 504 | if (fs.existsSync(attemptDirectory)) writeJSON(receiptFile, receipt); |
| 505 | } finally { |
| 506 | if (groupEnded) fs.unlinkSync(lock); |
| 507 | for (const signal of stopSignals) process.off(signal, stop); |
| 508 | } |
| 509 | } |
| 510 | print(status(id)); |
| 511 | if (receipt.status !== 'passed') process.exitCode = 1; |
| 512 | } |
| 513 | |
| 514 | const taskId = Argument.String('id').pipe(Argument.withDescription('Local task identifier')); |
| 515 | const operation = (run: () => void | Promise<void>) => |
| 516 | Effect.tryPromise({ try: async () => run(), catch: (error: unknown) => error }); |
| 517 | const stringFlag = (name: string) => |
| 518 | Flag.String(name).pipe( |
| 519 | Flag.between(1, 1), |
| 520 | Flag.map(values => values[0]!) |
| 521 | ); |
| 522 | |
| 523 | const initFlags = { |
| 524 | goal: stringFlag('goal').pipe(Flag.withDescription('Observable outcome to implement and verify')), |
| 525 | profile: stringFlag('profile').pipe( |
| 526 | Flag.withDescription('Check group from scripts/agent-profiles.json') |
| 527 | ), |
| 528 | source: stringFlag('source').pipe( |
| 529 | Flag.withDescription('Original issue or PR URL'), |
| 530 | Flag.optional |
| 531 | ), |
| 532 | authority: stringFlag('authority').pipe( |
| 533 | Flag.withDescription('User-authorized scope to preserve as context'), |
| 534 | Flag.optional |
| 535 | ), |
| 536 | }; |
| 537 | const initCommand = CliCommand.make( |
| 538 | 'init', |
| 539 | { id: taskId, ...initFlags }, |
| 540 | ({ id, goal, profile, source, authority }) => |
| 541 | operation(() => { |
| 542 | if (!goal.trim() || !profile) |
| 543 | throw new Error('Task initialization requires --goal and --profile.'); |
| 544 | const directory = taskDirectory(id); |
| 545 | const task: Task = { |
| 546 | version: 1, |
| 547 | id, |
| 548 | goal, |
| 549 | profile, |
| 550 | source: Option.getOrNull(source), |
| 551 | authority: Option.getOrNull(authority), |
| 552 | nextStep: null, |
| 553 | blocker: null, |
| 554 | createdAt: now(), |
| 555 | }; |
| 556 | profileFor(task); |
| 557 | // Publish the task folder in one rename so an interrupted init leaves no partial task. |
| 558 | // An empty folder left by an older interrupted init is replaced; a real task is kept. |
| 559 | const staging = path.join(tasksRoot, `.init-${randomUUID()}`); |
| 560 | fs.mkdirSync(staging, { recursive: true, mode: 0o700 }); |
| 561 | try { |
| 562 | writeJSON(path.join(staging, 'task.json'), task); |
| 563 | fs.renameSync(staging, directory); |
| 564 | } catch (error) { |
| 565 | fs.rmSync(staging, { recursive: true, force: true }); |
| 566 | if (errorCode(error) === 'ENOTEMPTY' || errorCode(error) === 'EEXIST') |
| 567 | throw new Error(`Task ${id} already exists.`); |
| 568 | throw error; |
| 569 | } |
| 570 | print(status(id)); |
| 571 | }) |
| 572 | ).pipe( |
| 573 | CliCommand.withDescription('Save a task goal and select its verification checks'), |
| 574 | CliCommand.withExamples([ |
| 575 | { |
| 576 | command: |
| 577 | 'bun run agent:task init cli-fix --goal "Fix the reported CLI behavior" --profile cli', |
| 578 | description: 'Start a CLI task', |
| 579 | }, |
| 580 | ]) |
| 581 | ); |
| 582 | const statusCommand = CliCommand.make('status', { id: taskId }, ({ id }) => |
| 583 | operation(() => print(status(id))) |
| 584 | ).pipe( |
| 585 | CliCommand.withDescription('Read saved context and check whether verification is still current') |
| 586 | ); |
| 587 | const verifyCommand = CliCommand.make('verify', { id: taskId }, ({ id }) => |
| 588 | operation(() => verify(id)) |
| 589 | ).pipe(CliCommand.withDescription('Run the selected checks and retain a revision-bound receipt')); |
| 590 | const listCommand = CliCommand.make('list', {}, () => |
| 591 | operation(() => { |
| 592 | print( |
| 593 | taskIds().map(id => { |
| 594 | try { |
| 595 | return status(id); |
| 596 | } catch (error) { |
| 597 | return { id, status: 'unreadable', error: errorMessage(error) }; |
| 598 | } |
| 599 | }) |
| 600 | ); |
| 601 | }) |
| 602 | ).pipe(CliCommand.withDescription('List saved tasks and their verification status')); |
| 603 | const rootCommand = CliCommand.make('agent:task').pipe( |
| 604 | CliCommand.withDescription('Preserve task context and run repository verification checks'), |
| 605 | CliCommand.withSubcommands([initCommand, statusCommand, verifyCommand, listCommand]), |
| 606 | CliCommand.withExamples([ |
| 607 | { command: 'bun run agent:task status cli-fix', description: 'Resume a saved task' }, |
| 608 | { |
| 609 | command: 'bun run agent:task verify cli-fix', |
| 610 | description: 'Verify the current revision after implementing the fix', |
| 611 | }, |
| 612 | ]) |
| 613 | ); |
| 614 | |
| 615 | function taskArguments(args: readonly string[]): string[] { |
| 616 | const valueFlags = new Set(Object.keys(initFlags).map(name => `--${name}`)); |
| 617 | const result: string[] = []; |
| 618 | const tokens = args[Symbol.iterator](); |
| 619 | for (const token of tokens) { |
| 620 | if (valueFlags.has(token)) { |
| 621 | const value = tokens.next(); |
| 622 | result.push(value.done ? token : `${token}=${value.value}`); |
| 623 | } else result.push(token); |
| 624 | } |
| 625 | return result; |
| 626 | } |
| 627 | |
| 628 | // Bind literal values before Effect scans built-in flags, so task text cannot activate help. |
| 629 | // Verification owns signal cleanup so its command groups stop before the worktree lock is released. |
| 630 | Effect.runPromise( |
| 631 | CliCommand.runWith(rootCommand, { version: '1' })(taskArguments(process.argv.slice(2))).pipe( |
| 632 | Effect.provide(BunServices.layer), |
| 633 | Effect.catchTags({ |
| 634 | ShowHelp: (error: unknown) => |
| 635 | Effect.sync(() => { |
| 636 | process.exitCode = Runtime.getErrorExitCode(error); |
| 637 | }), |
| 638 | UserError: (error: unknown) => |
| 639 | Effect.sync(() => { |
| 640 | process.exitCode = Runtime.getErrorExitCode(error); |
| 641 | }), |
| 642 | }), |
| 643 | Effect.catch(error => |
| 644 | Effect.sync(() => { |
| 645 | console.error(errorMessage(error)); |
| 646 | process.exitCode = Runtime.getErrorExitCode(error); |
| 647 | }) |
| 648 | ) |
| 649 | ) |
| 650 | ).catch((error: unknown) => { |
| 651 | console.error(errorMessage(error)); |
| 652 | process.exitCode = 1; |
| 653 | }); |