diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 1f6b88f..882d834 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "taskflow", "description": "Plan-and-task workflow: scope/tasks/questions/progress scaffolding split into pull requests under a line budget, acceptance criteria agreed up front, tests red before green, one-task-per-commit cycle, questions answered at the task that needs them, red-first bug fixes, docs-and-diagram sync, standards review.", - "version": "0.8.1", + "version": "0.8.2", "types": "./types/index.d.ts", "author": { "name": "Guilherme Moraes" }, "license": "MIT" diff --git a/panel/data/board.ts b/panel/data/board.ts index 491fc37..3980e2f 100644 --- a/panel/data/board.ts +++ b/panel/data/board.ts @@ -1,14 +1,26 @@ import { atom, read, update } from 'claude-code' import type { EngineInterface } from 'claude-code' -import type { PlanBoard, PlanProject } from '../../types' +import type { PlanBoard, PlanDir, PlanProject, TrashEntry } from '../../types' import { isSafeProjectName, parseProgress, parseWorktrees, repoWebUrl } from '../domain/parse' import { parseWorkflowEnv, resolvePlanDir } from '../domain/plan-dir' +import { + TRASH_DIR, + clearTargets, + isDirectChild, + isPlanFolder, + parseTrashEntry, + recoverDecision, + trashEntryName, +} from '../domain/trash' const board = atom({ plugin: 'taskflow', key: 'board' } as const, null) const selected = atom({ plugin: 'taskflow', key: 'selected' } as const, null) const pendingDelete = atom({ plugin: 'taskflow', key: 'pendingDelete' } as const, null) const notice = atom({ plugin: 'taskflow', key: 'notice' } as const, null) +// null while the trash view is closed, so loadBoard only lists the trash when someone is looking at it. +const trashEntries = atom({ plugin: 'taskflow', key: 'trashEntries' } as const, null) +const pendingClear = atom({ plugin: 'taskflow', key: 'pendingClear' } as const, false) async function repoRoot($: EngineInterface) { const toplevel = await $.process.run(['git', 'rev-parse', '--show-toplevel']) @@ -76,7 +88,7 @@ export async function loadBoard($: EngineInterface) { const projects: PlanProject[] = [] if (planDir !== null && (await $.fs.exists(planDir.base))) { for (const entry of await $.fs.list(planDir.base)) { - if (entry.kind !== 'dir') continue + if (entry.kind !== 'dir' || !isPlanFolder(entry.name)) continue const progressPath = `${planDir.base}/${entry.name}/PROGRESS.md` if (!(await $.fs.exists(progressPath))) continue const { title, rows } = parseProgress(await $.fs.read(progressPath)) @@ -89,6 +101,10 @@ export async function loadBoard($: EngineInterface) { const planDirError = 'error' in resolved ? resolved.error : null const next: PlanBoard = { planDir, planDirError, repoUrl, worktrees, projects } await update($, board, () => next) + if ((await read($, trashEntries)) !== null) { + const listed = planDir === null ? [] : await listTrash($, planDir) + await update($, trashEntries, () => listed) + } const current = await read($, selected) if (!projects.some(project => project.name === current)) { @@ -96,21 +112,117 @@ export async function loadBoard($: EngineInterface) { } } +async function realPath($: EngineInterface, path: string) { + const resolved = await $.process.run(['realpath', '--', path]) + + return resolved.exitCode === 0 ? resolved.stdout.trim() : null +} + +// Both sides resolved, so a symlinked plan or base cannot point a move or removal outside the base. +async function isContained($: EngineInterface, base: string, target: string) { + const [realBase, realTarget] = [await realPath($, base), await realPath($, target)] + + return realBase !== null && realTarget !== null && isDirectChild(realBase, realTarget) +} + +async function finish($: EngineInterface, message: string) { + await update($, pendingClear, () => false) + await update($, notice, () => message) + await loadBoard($) +} + +async function currentPlanDir($: EngineInterface) { + return (await read($, board))?.planDir ?? null +} + export async function deleteProject($: EngineInterface, name: string) { const current = await read($, board) const isKnown = current?.projects.some(project => project.name === name) ?? false const planDir = current?.planDir ?? null + await update($, pendingDelete, () => null) if (planDir === null || !isKnown || !isSafeProjectName(name)) { await update($, notice, () => `Refused to delete "${name}".`) return } const target = `${planDir.base}/${name}` - const removal = await $.process.run(['rm', '-rf', '--', target]) - await update($, pendingDelete, () => null) - await update($, notice, () => - removal.exitCode === 0 ? `Deleted ${planDir.label}/${name}` : `Delete failed: ${removal.stderr.trim()}`, - ) + if (!(await isContained($, planDir.base, target))) { + await update($, notice, () => `Refused to delete "${name}": it is not a plan folder inside ${planDir.label}.`) + return + } + + const trash = `${planDir.base}/${TRASH_DIR}` + const made = await $.process.run(['mkdir', '-p', '--', trash]) + const destination = `${trash}/${trashEntryName(name, new Date())}` + // -n: never overwrite an entry trashed in the same second. + const moved = + made.exitCode === 0 && !(await $.fs.exists(destination)) + ? await $.process.run(['mv', '-n', '--', target, destination]) + : null await update($, selected, () => null) + await finish( + $, + moved?.exitCode === 0 + ? `Moved ${planDir.label}/${name} to the trash` + : `Delete failed: ${moved?.stderr.trim() || made.stderr.trim() || 'the trash entry already exists'}`, + ) +} + +export async function listTrash($: EngineInterface, planDir: PlanDir): Promise { + const trash = `${planDir.base}/${TRASH_DIR}` + if (!(await $.fs.exists(trash))) return [] + const entries = (await $.fs.list(trash)).flatMap(entry => { + const parsed = entry.kind === 'dir' ? parseTrashEntry(entry.name) : null + + return parsed === null ? [] : [parsed] + }) + + return entries.sort((first, second) => second.deletedAt - first.deletedAt) +} + +export async function recoverPlan($: EngineInterface, entry: string) { + const planDir = await currentPlanDir($) + if (planDir === null) return finish($, `Refused to recover "${entry}".`) + const trash = `${planDir.base}/${TRASH_DIR}` + const existing = (await $.fs.list(planDir.base)).map(item => item.name) + const decision = recoverDecision(entry, existing) + if ('error' in decision) return finish($, decision.error) + + const source = `${trash}/${entry}` + if (!(await isContained($, trash, source))) return finish($, `Refused to recover "${entry}".`) + const moved = await $.process.run(['mv', '-n', '--', source, `${planDir.base}/${decision.name}`]) + await finish( + $, + moved.exitCode === 0 && !(await $.fs.exists(source)) + ? `Recovered ${planDir.label}/${decision.name}` + : `Recover failed: ${moved.stderr.trim() || `"${decision.name}" already exists`}`, + ) +} + +// The only permanent delete left: each child of .trash is checked on its real path before removal. +export async function clearTrash($: EngineInterface) { + const planDir = await currentPlanDir($) + const trash = planDir === null ? null : `${planDir.base}/${TRASH_DIR}` + if (planDir === null || trash === null || !(await $.fs.exists(trash))) return finish($, 'The trash is empty.') + if (!(await isContained($, planDir.base, trash))) return finish($, 'Refused to clear the trash.') + + const names = (await $.fs.list(trash)).map(item => item.name) + const targets: string[] = [] + for (const target of clearTargets(planDir.base, names)) { + if (await isContained($, trash, target)) targets.push(target) + } + if (targets.length === 0) return finish($, 'The trash is empty.') + const removal = await $.process.run(['rm', '-rf', '--', ...targets]) + await finish($, removal.exitCode === 0 ? 'Cleared the trash.' : `Clear failed: ${removal.stderr.trim()}`) +} + +export async function openTrash($: EngineInterface) { + await update($, notice, () => null) + await update($, trashEntries, () => []) await loadBoard($) } + +export async function closeTrash($: EngineInterface) { + await update($, pendingClear, () => false) + await update($, trashEntries, () => null) +} diff --git a/panel/domain/trash.test.ts b/panel/domain/trash.test.ts new file mode 100644 index 0000000..f42684a --- /dev/null +++ b/panel/domain/trash.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from 'claude-code/testing' + +import { clearTargets, isDirectChild, isPlanFolder, parseTrashEntry, recoverDecision, trashEntryName } from './trash' + +const BASE = '/vault/plans' + +test('names a trash entry with the plan and timestamp', () => { + const name = trashEntryName('my-plan', new Date(2026, 9, 21, 9, 5, 7)) + + expect(name).toBe('my-plan--20261021-090507') + expect(parseTrashEntry(name)).toEqual({ + entry: name, + name: 'my-plan', + deletedAt: new Date(2026, 9, 21, 9, 5, 7).getTime(), + }) + expect(parseTrashEntry('a--b--20261021-090507')).toEqual(expect.objectContaining({ name: 'a--b' })) + expect(parseTrashEntry('not-a-trash-entry')).toBe(null) +}) + +test('refuses a target outside the base', () => { + expect(isDirectChild(BASE, '/vault/plans/p')).toBe(true) + expect(isDirectChild(`${BASE}/`, '/vault/plans/p')).toBe(true) + expect(isDirectChild(BASE, '/vault/other/p')).toBe(false) + expect(isDirectChild(BASE, '/vault/plans')).toBe(false) + expect(isDirectChild(BASE, '/vault/plans/p/nested')).toBe(false) + expect(isDirectChild(BASE, '/vault/plans-evil/p')).toBe(false) + expect(isDirectChild(BASE, '/vault/plans/..')).toBe(false) +}) + +test('refuses recover onto an existing plan', () => { + expect(recoverDecision('p--20261021-090507', ['p', 'q'])).toEqual({ + error: expect.stringContaining('"p" already exists'), + }) + expect(recoverDecision('p--20261021-090507', ['q'])).toEqual({ name: 'p' }) + expect(recoverDecision('../etc--20261021-090507', [])).toEqual({ error: expect.any(String) }) +}) + +test('scopes clear to the .trash folder', () => { + expect(clearTargets(BASE, ['p--20261021-090507', 'q'])).toEqual([ + '/vault/plans/.trash/p--20261021-090507', + '/vault/plans/.trash/q', + ]) + expect(clearTargets(BASE, ['..', '.', '', 'a/b'])).toEqual([]) +}) + +test('never lists .trash as a plan', () => { + expect(isPlanFolder('.trash')).toBe(false) + expect(isPlanFolder('my-plan')).toBe(true) +}) diff --git a/panel/domain/trash.ts b/panel/domain/trash.ts new file mode 100644 index 0000000..7c68e74 --- /dev/null +++ b/panel/domain/trash.ts @@ -0,0 +1,55 @@ +import type { TrashEntry } from '../../types' +import { isSafeProjectName } from './parse' + +export const TRASH_DIR = '.trash' + +const ENTRY = /^(.+)--(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})$/ + +const pad = (value: number) => String(value).padStart(2, '0') + +// Local time, so the folder name matches the clock the user saw when deleting. +export function trashEntryName(name: string, at: Date) { + const date = `${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}` + const time = `${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}` + + return `${name}--${date}-${time}` +} + +export function parseTrashEntry(entry: string): TrashEntry | null { + const match = entry.match(ENTRY) + if (!match) return null + const part = (index: number) => Number(match[index]) + const deletedAt = new Date(part(2), part(3) - 1, part(4), part(5), part(6), part(7)).getTime() + + return { entry, name: match[1] ?? '', deletedAt } +} + +const trimSlashes = (path: string) => path.replace(/\/+$/, '') + +// Compared on real paths by the caller, so a symlink cannot smuggle a target out of the base. +export function isDirectChild(base: string, target: string) { + const prefix = `${trimSlashes(base)}/` + if (!target.startsWith(prefix)) return false + + return isSafeProjectName(trimSlashes(target).slice(prefix.length)) +} + +export function recoverDecision(entry: string, existingPlans: string[]): { name: string } | { error: string } { + const parsed = parseTrashEntry(entry) + if (parsed === null || !isSafeProjectName(parsed.name) || !isSafeProjectName(entry)) { + return { error: `Refused to recover "${entry}".` } + } + if (existingPlans.includes(parsed.name)) { + return { error: `A plan named "${parsed.name}" already exists - rename or delete it first.` } + } + + return { name: parsed.name } +} + +export function clearTargets(base: string, entries: string[]) { + return entries.filter(isSafeProjectName).map(entry => `${trimSlashes(base)}/${TRASH_DIR}/${entry}`) +} + +export function isPlanFolder(name: string) { + return name !== TRASH_DIR +} diff --git a/panel/ui/components/organisms/PlanDetail.tsx b/panel/ui/components/organisms/PlanDetail.tsx index 039dc5b..d0e723f 100644 --- a/panel/ui/components/organisms/PlanDetail.tsx +++ b/panel/ui/components/organisms/PlanDetail.tsx @@ -69,10 +69,10 @@ export function PlanDetail(props: PlanDetailProps) { {isDeleting ? ( - Delete {board.planDir?.label}/{project.name}? This cannot be undone. + Move {board.planDir?.label}/{project.name} to the trash? You can recover it from the trash. -