/** * ============================================================ * plugins/workflow-runner/src/workflowState.ts —— 任务状态持久化 * ------------------------------------------------------------ * 自 legacy 移植**持久化那一半**。legacy 版 1178 行里另一半是按「步骤索引 / * 循环迭代 / VarStack 快照 / capture 变量」做的断点定位 —— 那些概念在代码 * 编排里不存在,由 `journal.ts` 的「调用序号 + 内容指纹」整体取代。 * * 本文件负责的是**跨进程活得下来的东西**: * - 目录布局与四态判定(fresh / new-task / completed / resume) * - 声明产物的「先归档再清理」(含 glob 展开) * - 用户补充要求(supplements)的持久化 * - 人类可读的 progress 日志 * * ------------------------------------------------------------ * ⚠️ **清理必须先归档,不能直接 rm** —— 这条是实战事故换来的: * 同主题重跑时 LLM 仲裁误判成 new-task,11 个声明产物被静默直接删除、不可找回。 * 现在一律先 `rename` 进 `<实例目录>.trash//`(保留相对路径结构), * rm 只作为 rename 失败的兜底。`.trash/` 是状态目录的 sibling,跨任务留存 * (淘汰策略暂未实现,需要时由用户手动清)。 * * ⚠️ 归档失败时**绝不谎报归档位置** —— 一个文件都没成功移走就返回 undefined。 * 报了位置用户会去回收站找,找不到比一开始就说「已删除」更糟。 * ============================================================ */ import { type Dirent, existsSync } from 'node:fs'; import { appendFile, mkdir, readFile, readdir, rename, rm, writeFile, } from 'node:fs/promises'; import { dirname, join, relative } from 'node:path'; import { type TaskArbitrator, computeTaskId, extractGoal, sanitizeWorkflowDirName, sessionStateDir, taskInstanceDir, } from './taskIdentity.js'; import type { InputDef } from './types.js'; import { safeArtifactPath } from './util.js'; import { atomicWriteJson, publishCheckpoint } from './runtime/fs.js'; const DONE_SUFFIX = '.done'; const TRASH_SUFFIX = '.trash'; /** 四态:首次 / 换了任务 / 同任务已完成 / 同任务未完成可续跑。 */ export type TaskResumeMode = 'fresh' | 'new-task' | 'completed' | 'resume'; export interface TaskResumeInfo { mode: TaskResumeMode; /** fresh/new-task:旧产物归档到哪(相对 cwd)。归档一个都没成功时**不填**。 */ archivedTo?: string; /** fresh/new-task:归档失败后被 rm 兜底删掉的路径。非空通常意味着归档出了问题。 */ cleanedArtifacts?: string[]; /** * new-task:同一个 taskId,但**脚本内容变了**(指纹不匹配)→ 旧断点作废。 * 调用方据此向用户明示原因,而不是静默从头跑。 */ scriptChanged?: boolean; /** completed:磁盘上**实际存在**的产物(不是声明了就报)。 */ artifacts?: string[]; /** resume:上次失败的原因。 */ lastError?: string; /** * resume(仲裁判定的延续):旧任务的原始 goal。 * * 本次输入是「继续」这类延续指令,**不能拿它当目标锚** —— 那会让后续每次 * 调用都把「继续」当成要达成的事。锚必须是旧任务的真实目标。 */ prevGoal?: string; /** resume(仲裁判定的延续):本次新输入,作为旧目标的补充要求并入锚。 */ supplementaryGoal?: string; } export interface AbandonWorkflowResult { workflowName: string; sessionId: string; taskId: string; goal?: string; archivedTo?: string; cleanedState: boolean; } /** `current.json` 的形状。 */ interface CurrentState { name: string; taskId: string; status: 'running' | 'failed' | 'done'; startedAt: string; goal: string; lastError?: string; /** 声明产物(相对 cwd):new-task 清理与 completed 报告用。 */ artifacts?: string[]; /** Exact successful outputs, including owned descendants; declarations may include failed optional outputs. */ completion?: { artifacts: string[]; stateFiles: string[] }; /** * 编排脚本全文的哈希。取代 legacy 的 `defFingerprint`(那是按步骤骨架算的)。 * * 作用相同:同一个 taskId 但脚本改过 → 旧 journal 的调用序号对不上新脚本的 * 控制流 → 断点作废、明示原因、全新开始。legacy 曾因索引断点在 yaml 重构后 * 错跳步,被误读成 bug(真实发生过)。 */ scriptHash?: string; } /** 把 glob 段翻成正则片段(`*` 不跨目录分隔符,`?` 单字符)。 */ function artifactSegToPattern(seg: string): string { return seg .split(/([*?])/) .map((part) => { if (part === '*') return '[^/]*'; if (part === '?') return '[^/]'; return part.replace(/[.+^${}()|[\]\\]/g, '\\$&'); }) .join(''); } export class WorkflowState { /** 任务实例目录(绝对路径)。init 里确定 taskId 后才有值。 */ dir = ''; /** 当前 session 的目录(其下按 taskId 分实例)。 */ readonly sessionDir: string; readonly workingDir: string; readonly workflowName: string; private readonly taskIdOverride?: string; readonly sessionId: string; /** init 里算出的任务身份。 */ taskId = ''; /** * 输入声明。用于让 `extractGoal` 优先取作者标了 `required` 的那个输入 —— * 任务身份与目标锚必须用**同一份**取值规则,否则「拿来算 taskId 的目标」 * 和「注入给模型的目标」会指向不同的东西。 */ private readonly defs?: InputDef[]; private progressWrites: Promise = Promise.resolve(); private eventWrites: Promise = Promise.resolve(); constructor( workingDir: string, workflowName: string, sessionId: string, defs?: InputDef[], taskIdOverride?: string, private readonly parentStateDir?: string, ) { this.workingDir = workingDir; this.workflowName = workflowName; this.sessionId = sanitizeWorkflowDirName(sessionId); this.sessionDir = parentStateDir ? join(parentStateDir, 'children', workflowName) : sessionStateDir(workingDir, workflowName, sessionId); this.defs = defs; this.taskIdOverride = taskIdOverride; } /** journal 落盘位置(由 journal.ts 消费,见任务 5)。 */ get journalPath(): string { return join(this.dir, 'journal.jsonl'); } private get supplementsPath(): string { return join(this.dir, 'supplements.json'); } private get progressPath(): string { return join(this.dir, 'progress.md'); } private get eventsPath(): string { return join(this.dir, 'events.jsonl'); } /** * 判定本次运行属于四态里的哪一种,并把实例目录准备好。 * * @param inputs 本次调用的输入(用于算 taskId 与 goal) * @param scriptHash 编排脚本全文哈希(脚本改了 → 断点作废) * @param declaredArtifacts meta.artifacts 种子(运行时还会经 declareArtifact 增长) * @param arbitrate 可选的语义仲裁器;不传则 hash 不等一律 new-task */ async init( inputs: Record, scriptHash: string, declaredArtifacts: string[], arbitrate?: TaskArbitrator, ): Promise { const goal = extractGoal(inputs, this.defs); this.taskId = this.taskIdOverride ? sanitizeWorkflowDirName(this.taskIdOverride) : computeTaskId(this.workflowName, inputs, this.defs); const taskDir = this.parentStateDir ? join(this.sessionDir, this.taskId) : taskInstanceDir( this.workingDir, this.workflowName, this.sessionId, this.taskId, ); const doneDir = taskDir + DONE_SUFFIX; // Both a completed receipt and a resumable journal need a verifiable owner. const completed = existsSync(doneDir); if (completed || existsSync(taskDir)) { this.dir = completed ? doneDir : taskDir; const prev = await this.readCurrent(); if (!prev?.scriptHash) throw new Error(`无法核实工作流断点版本:${join(this.dir, 'current.json')}。已保留现场;请先核对已有产物和外部操作,再决定是否用新会话重跑。`); if (prev.scriptHash !== scriptHash || !(await this.treeIntact())) { const info = await this.restartChanged( goal, scriptHash, declaredArtifacts, taskDir, ); return { ...info, mode: 'new-task', scriptChanged: true }; } if (completed) return { mode: 'completed', artifacts: await this.allArtifacts() }; await this.writeCurrent({ name: this.workflowName, taskId: this.taskId, status: 'running', startedAt: new Date().toISOString(), goal: prev.goal ?? goal, artifacts: [ ...new Set([...(prev.artifacts ?? []), ...declaredArtifacts]), ], scriptHash, }); return { mode: 'resume', lastError: prev.lastError }; } // ③ 本 taskId 没有目录。看看同 session 下有没有**未完成的兄弟任务**可以仲裁延续。 const sibling = await this.findIncompleteSibling(); // Bound resources and their declared parameters are an exact contract. // A different task hash must not be overridden by a semantic guess based // only on the (possibly identical) human-readable goal. if (sibling && arbitrate && !inputs.__resource_fingerprint) { const prev = await this.readCurrentAt(sibling); const verdict = await arbitrate({ workflowName: this.workflowName, prevGoal: prev?.goal ?? '', newGoal: goal, completedCalls: await this.countJournalEntries(sibling), artifacts: await this.existingArtifacts(prev?.artifacts ?? []), }); if (verdict === 'resume') { // 采纳旧实例目录继续跑:本次输入降级成补充要求,目标锚仍指向旧目标。 this.dir = sibling; if (!prev?.scriptHash || prev.scriptHash !== scriptHash || !(await this.treeIntact())) throw new Error(`旧任务版本或产物与当前工作流不一致,不能按补充指令续跑:${sibling}。请核对已执行的操作,再用原始完整目标重新发起。`); this.taskId = prev?.taskId ?? this.taskId; return { mode: 'resume', prevGoal: prev?.goal, supplementaryGoal: goal, lastError: prev?.lastError, }; } } // ④ 全新任务(或首次运行)。 this.dir = taskDir; const info = await this.startFresh(goal, scriptHash, declaredArtifacts); return { ...info, mode: sibling ? 'new-task' : 'fresh' }; } /** 建实例目录、归档并清理旧产物残留、写 current.json。 */ /** Retire the actual old journal AND dynamic outputs, not only the status flag. * A completed directory must also be retired, otherwise it shadows the fresh * incomplete attempt on the next resume. Nothing is deleted on this path. */ private async restartChanged( goal: string, scriptHash: string, declaredArtifacts: string[], taskDir: string, ): Promise { const stamp = new Date().toISOString().replace(/[:.]/g, '-'); const archiveRoot = join(this.dir + TRASH_SUFFIX, stamp); const existing = [ ...new Set([ ...(await this.allArtifacts()), ...(await this.existingArtifacts(declaredArtifacts)), ]), ]; await this.archiveDeclaredArtifacts(existing, stamp); const remaining = existing.filter((path) => existsSync(join(this.workingDir, path)), ); if (remaining.length) throw new Error(`旧产物归档失败,停止覆盖:${remaining.join('、')}`); await mkdir(archiveRoot, { recursive: true }); const oldDir = this.dir; await rename(oldDir, join(archiveRoot, 'state')); // Older versions could leave both .done and an incomplete directory. if (oldDir !== taskDir && existsSync(taskDir)) { await rename(taskDir, join(archiveRoot, 'incomplete-state')); } this.dir = taskDir; const info = await this.startFresh(goal, scriptHash, declaredArtifacts); return { ...info, archivedTo: relative(this.workingDir, archiveRoot) }; } private async startFresh( goal: string, scriptHash: string, declaredArtifacts: string[], ): Promise { // 时间戳只用作回收目录名,不参与任何身份判定 —— 故这里用真实时间是安全的。 const stamp = new Date().toISOString().replace(/[:.]/g, '-'); const { cleaned, archivedTo } = await this.archiveThenClean( declaredArtifacts, stamp, ); await mkdir(this.dir, { recursive: true }); await writeFile(this.supplementsPath, '[]', 'utf8'); await this.writeCurrent({ name: this.workflowName, taskId: this.taskId, status: 'running', startedAt: new Date().toISOString(), goal, artifacts: declaredArtifacts, scriptHash, }); const info: TaskResumeInfo = { mode: 'fresh' }; if (cleaned.length > 0) info.cleanedArtifacts = cleaned; if (archivedTo) info.archivedTo = archivedTo; return info; } /** 同 session 下另一个**未完成**任务的目录(有多个时取最近修改的)。 */ private async findIncompleteSibling(): Promise { let entries: Dirent[]; try { entries = await readdir(this.sessionDir, { withFileTypes: true }); } catch { return null; } const candidates = entries .filter( (e) => e.isDirectory() && !e.name.endsWith(DONE_SUFFIX) && !e.name.endsWith(TRASH_SUFFIX) && e.name !== this.taskId, ) .map((e) => join(this.sessionDir, e.name)) .filter((d) => existsSync(join(d, 'current.json'))); if (candidates.length === 0) return null; // 多个未完成实例时取最近的那个 —— 用户嘴里的「继续」几乎总是指最近一次。 let newest = candidates[0]; let newestAt = ''; for (const dir of candidates) { const cur = await this.readCurrentAt(dir); const at = cur?.startedAt ?? ''; if (at >= newestAt) { newestAt = at; newest = dir; } } return newest; } private async countJournalEntries(dir: string): Promise { try { const raw = await readFile(join(dir, 'journal.jsonl'), 'utf8'); return raw.split('\n').filter((l) => l.trim() !== '').length; } catch { return 0; } } // ---- current.json ---- private async readCurrent(): Promise { return this.readCurrentAt(this.dir); } private async readCurrentAt(dir: string): Promise { try { return JSON.parse( await readFile(join(dir, 'current.json'), 'utf8'), ) as CurrentState; } catch { return null; } } private async writeCurrent(state: CurrentState): Promise { await publishCheckpoint(() => atomicWriteJson(this.dir, 'current.json', state)); } /** 记一次失败原因(下次 resume 时报给用户 / 喂给模型)。 */ async recordFailure(error: string, artifacts?: string[]): Promise { const cur = await this.readCurrent(); if (!cur) return; await this.writeCurrent({ ...cur, status: 'failed', lastError: error, ...(artifacts ? { artifacts: [...new Set(artifacts)] } : {}), }); } /** * 标记完成(随后 archive() 把目录改名成 `.done`)。 * * @param artifacts 本次运行**最终**的声明产物集合。必须传 —— `meta.artifacts` * 只是静态种子,循环体里经 `declareArtifact()` 登记的逐迭代产物只活在内存里。 * 不在这里落盘的话,下次 completed 判定会报「本次运行没有声明产物」, * new-task 清理也会漏掉它们 —— 而且**表现为静默漏档而不是报错**。 * (这条是端到端实跑抓到的:上一轮明明 declareArtifact 了,重跑却报 0 产物。) */ async markDone(artifacts?: string[]): Promise { const cur = await this.readCurrent(); if (!cur) return; if (!existsSync(join(this.dir, 'return.json'))) await this.writeResult(null); const owned = artifacts ?? cur.artifacts ?? []; const records = await this.treeRecords(); const treeArtifacts = [ ...owned, ...records .filter((r) => r.dir !== this.dir) .flatMap((r) => r.state.artifacts ?? []), ]; await this.writeCurrent({ ...cur, status: 'done', ...(artifacts ? { artifacts: [...new Set(artifacts)] } : {}), completion: { artifacts: await this.existingArtifacts(treeArtifacts), stateFiles: [ 'return.json', ...records .filter((r) => r.dir !== this.dir) .map((r) => relative(this.dir, join(r.dir, 'current.json'))), ], }, }); } async writeResult(value: unknown): Promise { const json = JSON.stringify(value ?? null, (_key, v) => { if ( typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint' || (typeof v === 'number' && !Number.isFinite(v)) ) throw new Error('工作流返回值必须为JSON数据'); return v; }); await writeFile(join(this.dir, 'return.json'), json, 'utf8'); return JSON.parse(json); } async readResult(): Promise { try { return JSON.parse(await readFile(join(this.dir, 'return.json'), 'utf8')); } catch (error) { if (!(await this.readCurrent())?.completion) return null; // pre-composition state throw error; } } /** Children live inside the parent's state directory. Moving the parent also * archives all child journals, never another standalone run of the same name. */ private async treeRecords(): Promise<{ dir: string; state: CurrentState }[]> { const records: { dir: string; state: CurrentState }[] = []; const own = await this.readCurrent(); if (own) records.push({ dir: this.dir, state: own }); const visit = async (dir: string, depth: number): Promise => { if (depth > 24) throw new Error('子工作流状态目录嵌套异常'); let entries: Dirent[]; try { entries = await readdir(dir, { withFileTypes: true }); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; } for (const e of entries) { if (!e.isDirectory() || e.name.endsWith(TRASH_SUFFIX)) continue; const childDir = join(dir, e.name); const current = await this.readCurrentAt(childDir); if (current) { records.push({ dir: childDir, state: current }); await visit(join(childDir, 'children'), depth + 1); } else await visit(childDir, depth + 1); } }; await visit(join(this.dir, 'children'), 0); return records; } async allArtifacts(): Promise { return this.existingArtifacts( (await this.treeRecords()).flatMap((r) => r.state.artifacts ?? []), ); } private async treeIntact(): Promise { for (const { dir, state } of await this.treeRecords()) { if (!state.completion) continue; if ( state.completion.artifacts.some((p) => { const safe = safeArtifactPath(this.workingDir, p); return !safe || !existsSync(join(this.workingDir, safe)); }) ) return false; if ( state.completion.stateFiles.some((p) => { const safe = safeArtifactPath(dir, p); return !safe || !existsSync(join(dir, safe)); }) ) return false; try { JSON.parse(await readFile(join(dir, 'return.json'), 'utf8')); } catch { return false; } } return true; } // ---- 补充要求 ---- /** * 追加一条用户补充要求。去重:已有条目的前缀重复不再追加。 * * 持久化的理由:补充要求要与原始目标**同等贯穿始终**,跨进程 resume 时不能丢。 */ async appendSupplement(text: string): Promise { const t = text.trim(); if (!t) return; const list = await this.readSupplements(); if (list.some((s) => s.startsWith(t.slice(0, 240)))) return; list.push(t); await mkdir(this.dir, { recursive: true }); await writeFile( this.supplementsPath, JSON.stringify(list, null, 2), 'utf8', ); } async readSupplements(): Promise { try { const parsed = JSON.parse(await readFile(this.supplementsPath, 'utf8')); return Array.isArray(parsed) ? parsed.map((s) => String(s)) : []; } catch { return []; } } // ---- 人类可读进度 ---- /** * 追加一行进度。 * * 存在理由:TUI 的 scrollback 会被刷掉,而排障常常发生在「跑完之后」。 * 落盘的 progress.md 是唯一还能回看的现场(provider 的真实报错也写在这里)。 */ async appendProgress(line: string): Promise { this.progressWrites = this.progressWrites.then(async () => { try { await mkdir(this.dir, { recursive: true }); await appendFile(this.progressPath, `${line}\n`, 'utf8'); } catch { // 进度日志写失败不该影响任务本身 } }); await this.progressWrites; } async appendEvent(event: unknown): Promise { this.eventWrites = this.eventWrites.then(async () => { try { await mkdir(this.dir, { recursive: true }); await appendFile(this.eventsPath, `${JSON.stringify(event)}\n`, 'utf8'); } catch { // Structured diagnostics must never fail the workflow itself. } }); await this.eventWrites; } /** * 等待所有已排队的 progress/event 写入落盘(不做归档,无其它副作用)。 * * `journaled()`(`runtime/context.ts`)里的 appendProgress 调用是 fire-and-forget * ——生产路径的落盘保证来自 `archive()` 在 `runner.ts` 终止路径上对同一条 * `progressWrites`/`eventWrites` 链的 await。**绕开 `runner.ts` 直接调用能力对象 * 的测试**(例如只起 `createWorkflowContext()` 就调 `wf.model.generate()`)没有 * 这条终态保证,读 `progress.md`/`events.jsonl` 前必须显式调用这个方法。 */ async flush(): Promise { await Promise.all([this.progressWrites, this.eventWrites]); } // ---- 归档与清理 ---- /** 成功收尾:`/` → `.done/`。 */ async archive(): Promise { await this.flush(); if (!this.dir || !existsSync(this.dir)) return; const dest = this.dir.endsWith(DONE_SUFFIX) ? this.dir : this.dir + DONE_SUFFIX; if (dest === this.dir) return; try { await rm(dest, { recursive: true, force: true }); await rename(this.dir, dest); this.dir = dest; } catch { // 归档失败不影响任务结论,下次 init 会按未完成处理 } } /** 删掉本实例的状态目录(不碰 `.trash/`,那是用户的找回通道)。 */ async cleanup(): Promise { if (!this.dir) return; try { await rm(this.dir, { recursive: true, force: true }); } catch { /* 忽略 */ } } /** * 彻底放弃一个已经存在的任务实例:先把工作流登记的中间产物移入 sibling * `.trash/`,再删除该实例的 journal/progress/current 等断点状态。 * * 这与 ESC/action=pause 有意不同:pause 保留现场可续跑;abandon 不再可 * resume。产物仍进可恢复的回收目录,避免误删用户原有文件。 */ async abandon(): Promise { if (!this.dir || !existsSync(this.dir)) { throw new Error('工作流任务实例不存在或已经放弃。'); } await this.flush(); const current = await this.readCurrent(); const existing = [ ...new Set([ ...(await this.allArtifacts()), ...(await this.existingArtifacts(current?.artifacts ?? [])), ]), ]; const stamp = new Date().toISOString().replace(/[:.]/g, '-'); const archivedTo = await this.archiveDeclaredArtifacts(existing, stamp); const remaining = existing.filter((path) => existsSync(join(this.workingDir, path)), ); if (remaining.length > 0) { throw new Error( `放弃已停止:中间产物未能完整移入回收目录:${remaining.join('、')}`, ); } await rm(this.dir, { recursive: true, force: true }); return { workflowName: this.workflowName, sessionId: this.sessionId, taskId: this.taskId || current?.taskId || '', ...(current?.goal ? { goal: current.goal } : {}), ...(archivedTo ? { archivedTo } : {}), cleanedState: true, }; } // ---- 声明产物的生命周期 ---- /** * 把声明里的 glob(`research/04-*.md`)展开成 cwd 下实际匹配的相对路径; * 非 glob 原样保留。越界路径被过滤(fail-closed)。 * 声明里写了 glob 却一个都不匹配 → 该声明被丢弃(不存在的产物不参与清理/报告)。 */ private async expandDeclaredArtifacts(paths: string[]): Promise { const out: string[] = []; for (const p of paths) { const safe = safeArtifactPath(this.workingDir, p); if (safe === null) continue; if (!/[*?]/.test(safe)) { // ⚠️ 必须归一成 `/`:`safeArtifactPath` 返回的是**平台分隔符**,而下面 // glob 分支里 walkGlob 拼出来的一律是 `/`。两个分支不统一的话,同一份 // 声明列表在 Windows 上会同时产出 `out\a.md` 与 `out/b.md` —— 去重 // (new Set)失效、与 current.json 里存的旧值比不上、报给用户的路径 // 时而斜杠时而反斜杠。`join()` 吃 `/` 没问题,所以统一到 `/` 是安全的。 out.push(safe.replace(/\\/g, '/')); continue; } const segs = safe.replace(/\\/g, '/').split('/'); const fullRe = new RegExp( `^${segs.map(artifactSegToPattern).join('/')}$`, ); out.push(...(await this.walkGlob(this.workingDir, segs, fullRe, ''))); } return out; } private async walkGlob( absDir: string, segs: string[], fullRe: RegExp, relPrefix: string, ): Promise { const [head, ...rest] = segs; if (!head) return []; let entries: Dirent[]; try { entries = await readdir(absDir, { withFileTypes: true }); } catch { return []; } const headRe = new RegExp(`^${artifactSegToPattern(head)}$`); const results: string[] = []; for (const e of entries) { if (!headRe.test(e.name)) continue; const rel = relPrefix ? `${relPrefix}/${e.name}` : e.name; if (rest.length === 0) { if (e.isFile() && fullRe.test(rel)) results.push(rel); } else if (e.isDirectory()) { results.push( ...(await this.walkGlob(join(absDir, e.name), rest, fullRe, rel)), ); } } return results; } /** 声明产物里**实际存在**的那些(completed 报告用;越界的视为不存在)。 */ private async existingArtifacts(paths: string[]): Promise { const expanded = await this.expandDeclaredArtifacts(paths); return [...new Set(expanded)].filter((rel) => existsSync(join(this.workingDir, rel)), ); } /** * 把实际存在的声明产物移入 `<实例目录>.trash//`,保留相对路径结构。 * 一个都没成功移走时返回 undefined —— **绝不谎报归档位置**(见文件头注)。 */ private async archiveDeclaredArtifacts( existingRels: string[], stamp: string, ): Promise { if (existingRels.length === 0) return undefined; const trashRoot = join(this.dir + TRASH_SUFFIX, stamp); let archived = 0; for (const rel of existingRels) { const dest = join(trashRoot, rel); try { await mkdir(dirname(dest), { recursive: true }); await rename(join(this.workingDir, rel), dest); archived++; } catch { // 单个失败不阻断,残留交给后续 rm 兜底 } } if (archived === 0) return undefined; const display = relative(this.workingDir, trashRoot); return display.startsWith('..') ? trashRoot : display; } /** rm 兜底:只删工作流自己声明的产物,且路径强制在 cwd 内。 */ private async cleanupDeclaredArtifacts(paths: string[]): Promise { const done: string[] = []; for (const rel of await this.expandDeclaredArtifacts(paths)) { const abs = join(this.workingDir, rel); if (!existsSync(abs)) continue; try { await rm(abs, { force: true }); done.push(rel); } catch { /* 单个失败不影响整体 */ } } return done; } /** 「先归档再清理」组合。fresh/new-task 的启动清理统一走这里。 */ private async archiveThenClean( paths: string[], stamp: string, ): Promise<{ cleaned: string[]; archivedTo?: string }> { const existing = await this.existingArtifacts(paths); const archivedTo = await this.archiveDeclaredArtifacts(existing, stamp); const cleaned = await this.cleanupDeclaredArtifacts(paths); return { cleaned, archivedTo }; } } /** * 查找并放弃某个 session 的活动任务。未指定 taskId 时只选最近活动的一项, * 避免一次命令误清理多个并行任务;有多个任务时把候选列在错误里让用户明确指定。 */ export async function abandonWorkflowTask(options: { workingDir: string; workflowName: string; sessionId: string; taskId?: string; }): Promise { const sessionDir = sessionStateDir( options.workingDir, options.workflowName, options.sessionId, ); let entries: Dirent[]; try { entries = await readdir(sessionDir, { withFileTypes: true }); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') { throw new Error(`当前 Session 没有工作流「${options.workflowName}」的活动任务。`); } throw error; } const candidates: { dir: string; taskId: string; current: CurrentState }[] = []; for (const entry of entries) { if (!entry.isDirectory() || entry.name.endsWith(DONE_SUFFIX) || entry.name.endsWith(TRASH_SUFFIX)) continue; const dir = join(sessionDir, entry.name); try { const current = JSON.parse(await readFile(join(dir, 'current.json'), 'utf8')) as CurrentState; if (current.status !== 'done') candidates.push({ dir, taskId: entry.name, current }); } catch { // Ignore directories that are not task instances. } } const wanted = options.taskId?.trim() ? sanitizeWorkflowDirName(options.taskId.trim()) : undefined; const matching = wanted ? candidates.filter((candidate) => candidate.taskId === wanted) : candidates; if (matching.length === 0) { throw new Error( wanted ? `未找到活动任务「${options.workflowName}/${wanted}」。` : `当前 Session 没有工作流「${options.workflowName}」的活动任务。`, ); } if (!wanted && matching.length > 1) { throw new Error( `检测到多个活动任务,请用 --input task_id=... 明确指定:${matching.map((item) => item.taskId).join('、')}`, ); } const selected = matching[0]!; const state = new WorkflowState( options.workingDir, options.workflowName, options.sessionId, undefined, selected.taskId, ); state.dir = selected.dir; return state.abandon(); }