Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
126 changes: 119 additions & 7 deletions panel/data/board.ts
Original file line number Diff line number Diff line change
@@ -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'])
Expand Down Expand Up @@ -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))
Expand All @@ -89,28 +101,128 @@ 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)) {
await update($, selected, () => null)
}
}

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<TrashEntry[]> {
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)
}
49 changes: 49 additions & 0 deletions panel/domain/trash.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
55 changes: 55 additions & 0 deletions panel/domain/trash.ts
Original file line number Diff line number Diff line change
@@ -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
}
12 changes: 9 additions & 3 deletions panel/ui/components/organisms/PlanDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ export function PlanDetail(props: PlanDetailProps) {
{isDeleting ? (
<Box flexDirection="column">
<Text color="error" weight="bold">
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.
</Text>
<Box gap={2}>
<Button key="confirm-delete" hotkey="y" label="Yes, delete (y)" onPress={props.onConfirmDelete} />
<Button key="confirm-delete" hotkey="y" label="Yes, move to trash (y)" onPress={props.onConfirmDelete} />
<Button key="cancel-delete" hotkey="n" label="Cancel (n)" onPress={props.onCancelDelete} />
</Box>
</Box>
Expand All @@ -91,7 +91,13 @@ export function PlanDetail(props: PlanDetailProps) {
ui={ui}
items={[
{ key: 'refresh', icon: '🔄', label: 'Refresh (r)', hotkey: 'r', onPress: props.onRefresh },
{ key: 'delete', icon: '🗑️', label: 'Delete workspace (x)', hotkey: 'x', onPress: props.onAskDelete },
{
key: 'delete',
icon: '🗑️',
label: 'Move workspace to trash (x)',
hotkey: 'x',
onPress: props.onAskDelete,
},
]}
/>
)}
Expand Down
8 changes: 6 additions & 2 deletions panel/ui/components/organisms/PlanList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ type PlanListProps = {
message: string | null
onOpen: (name: string) => void
onRefresh: () => void
onOpenTrash: () => void
}

export function PlanList({ ui, projects, message, onOpen, onRefresh }: PlanListProps) {
export function PlanList({ ui, projects, message, onOpen, onRefresh, onOpenTrash }: PlanListProps) {
const { Box, Text, Button } = ui

return (
Expand All @@ -19,7 +20,10 @@ export function PlanList({ ui, projects, message, onOpen, onRefresh }: PlanListP
<Text weight="bold">
Plans <Text dimColor>{projects.length}</Text>
</Text>
<Button key="refresh" hotkey="r" label="🔄" onPress={onRefresh} />
<Box gap={1}>
<Button key="trash" hotkey="t" label="🗑️ Trash (t)" onPress={onOpenTrash} />
<Button key="refresh" hotkey="r" label="🔄" onPress={onRefresh} />
</Box>
</Box>
{projects.slice(0, 9).map((project, index) => (
<PlanCard
Expand Down
Loading
Loading