diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 5bc57ce..1f6b88f 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.7.3", + "version": "0.8.1", "types": "./types/index.d.ts", "author": { "name": "Guilherme Moraes" }, "license": "MIT" diff --git a/.claude/.gitignore b/.claude/.gitignore new file mode 100644 index 0000000..2dcb490 --- /dev/null +++ b/.claude/.gitignore @@ -0,0 +1 @@ +workflow.env diff --git a/hooks/progress-reminder.py b/hooks/progress-reminder.py index d34570f..d6dba65 100755 --- a/hooks/progress-reminder.py +++ b/hooks/progress-reminder.py @@ -11,32 +11,114 @@ import re import sys -DEFAULT_PROJECTS_DIRS = ("docs/projects", "src/docs/projects", ".planning") +DEFAULT_PROJECTS_DIR = "docs/projects" +ENV_KEYS = ( + "TASKFLOW_PLANS_SOURCE", + "TASKFLOW_OBSIDIAN_VAULT", + "TASKFLOW_OBSIDIAN_VAULT_PATH", + "TASKFLOW_OBSIDIAN_PATH", +) -def projects_dirs(cwd): +def basename(path): + return path.rstrip("/").split("/")[-1] + + +def read_projects_dir(cwd): config = os.path.join(cwd, ".claude", "workflow.json") try: with open(config) as fh: - configured = json.load(fh).get("projectsDir") - if configured: - return (configured,) - except (OSError, json.JSONDecodeError): - pass - return DEFAULT_PROJECTS_DIRS + return json.load(fh).get("projectsDir") or None + except (OSError, json.JSONDecodeError, AttributeError): + return None + + +# workflow.env is untracked, so only the keys that pick the plan source are read. +def parse_workflow_env(text): + env = {} + for line in text.split("\n"): + line = line.strip() + separator = line.find("=") + if line.startswith("#") or separator < 1: + continue + key = line[:separator].strip() + if key in ENV_KEYS: + env[key] = line[separator + 1 :].strip() + return env + + +def read_workflow_env(cwd): + try: + with open(os.path.join(cwd, ".claude", "workflow.env")) as fh: + return parse_workflow_env(fh.read()) + except OSError: + return {} + + +# None when obsidian.json is missing or unreadable. +def read_obsidian_vaults(): + config = os.path.expanduser("~/Library/Application Support/obsidian/obsidian.json") + try: + with open(config) as fh: + vaults = json.load(fh).get("vaults") or {} + return [ + v["path"] + for v in vaults.values() + if isinstance(v, dict) and isinstance(v.get("path"), str) + ] + except (OSError, json.JSONDecodeError, AttributeError): + return None + + +def vault_path(env, vaults): + explicit = env.get("TASKFLOW_OBSIDIAN_VAULT_PATH") + if explicit: + return explicit if explicit.startswith("/") else None + + name = env.get("TASKFLOW_OBSIDIAN_VAULT") + if not name or vaults is None: + return None + + matches = [path for path in vaults if basename(path) == name] + return matches[0] if len(matches) == 1 else None + + +# Mirrors resolvePlanDir in panel/domain/plan-dir.ts. With Obsidian as the +# source a problem yields None (the hook stays silent), never a repo fallback. +def resolve_plan_dir(cwd): + env = read_workflow_env(cwd) + if env.get("TASKFLOW_PLANS_SOURCE") != "obsidian": + projects_dir = read_projects_dir(cwd) or DEFAULT_PROJECTS_DIR + return os.path.join(cwd, projects_dir), projects_dir + + inner = env.get("TASKFLOW_OBSIDIAN_PATH", "").rstrip("/") + if inner.startswith("/") or ".." in inner.split("/"): + return None + + explicit = env.get("TASKFLOW_OBSIDIAN_VAULT_PATH") + root = vault_path(env, None if explicit else read_obsidian_vaults()) + if root is None: + return None + + root = root.rstrip("/") + shown = basename(root) + "/" + inner if inner else basename(root) + return (root + "/" + inner if inner else root), "Obsidian · " + shown def in_progress_files(cwd): + resolved = resolve_plan_dir(cwd) + if resolved is None: + return [] + + base, label = resolved found = [] - for base in projects_dirs(cwd): - pattern = os.path.join(cwd, base, "*", "PROGRESS.md") - for path in glob.glob(pattern): - try: - with open(path) as fh: - if "🔄" in fh.read(): - found.append(os.path.relpath(path, cwd)) - except OSError: - continue + for path in glob.glob(os.path.join(base, "*", "PROGRESS.md")): + try: + with open(path) as fh: + if "🔄" in fh.read(): + found.append("%s/%s/PROGRESS.md" % (label, basename(os.path.dirname(path)))) + except OSError: + continue return found diff --git a/panel/data/board.ts b/panel/data/board.ts index 3df0ab0..491fc37 100644 --- a/panel/data/board.ts +++ b/panel/data/board.ts @@ -3,14 +3,13 @@ import type { EngineInterface } from 'claude-code' import type { PlanBoard, PlanProject } from '../../types' import { isSafeProjectName, parseProgress, parseWorktrees, repoWebUrl } from '../domain/parse' +import { parseWorkflowEnv, resolvePlanDir } from '../domain/plan-dir' 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) -const DEFAULT_PROJECTS_DIR = '.planning/projects' - async function repoRoot($: EngineInterface) { const toplevel = await $.process.run(['git', 'rev-parse', '--show-toplevel']) @@ -21,26 +20,64 @@ async function readProjectsDir($: EngineInterface, root: string) { try { const config = JSON.parse(await $.fs.read(`${root}/.claude/workflow.json`)) - return typeof config.projectsDir === 'string' ? config.projectsDir : DEFAULT_PROJECTS_DIR + return typeof config.projectsDir === 'string' ? config.projectsDir : null } catch { - return DEFAULT_PROJECTS_DIR + return null } } +async function readWorkflowEnv($: EngineInterface, root: string) { + const path = `${root}/.claude/workflow.env` + + return parseWorkflowEnv((await $.fs.exists(path)) ? await $.fs.read(path) : '') +} + +// null when obsidian.json is missing or unreadable, so the resolver can name that as the problem. +async function readObsidianVaults($: EngineInterface) { + const home = await $.process.run(['printenv', 'HOME']) + if (home.exitCode !== 0) return null + try { + const config = JSON.parse( + await $.fs.read(`${home.stdout.trim()}/Library/Application Support/obsidian/obsidian.json`), + ) + const vaults: unknown[] = Object.values(config.vaults ?? {}) + + return vaults.flatMap(vault => + typeof vault === 'object' && vault !== null && 'path' in vault && typeof vault.path === 'string' + ? [vault.path] + : [], + ) + } catch { + return null + } +} + +async function readPlanDir($: EngineInterface, root: string) { + const env = await readWorkflowEnv($, root) + const needsVaults = env.TASKFLOW_PLANS_SOURCE === 'obsidian' && !env.TASKFLOW_OBSIDIAN_VAULT_PATH + + return resolvePlanDir({ + projectsDir: await readProjectsDir($, root), + env, + obsidianVaults: needsVaults ? await readObsidianVaults($) : null, + repoRoot: root, + }) +} + export async function loadBoard($: EngineInterface) { const root = await repoRoot($) - const projectsDir = await readProjectsDir($, root) - const projectsPath = `${root}/${projectsDir}` + const resolved = await readPlanDir($, root) + const planDir = 'error' in resolved ? null : resolved const remote = await $.process.run(['git', 'remote', 'get-url', 'origin'], { cwd: root }) const repoUrl = remote.exitCode === 0 ? repoWebUrl(remote.stdout) : null const worktreeList = await $.process.run(['git', 'worktree', 'list', '--porcelain'], { cwd: root }) const worktrees = worktreeList.exitCode === 0 ? parseWorktrees(worktreeList.stdout) : {} const projects: PlanProject[] = [] - if (await $.fs.exists(projectsPath)) { - for (const entry of await $.fs.list(projectsPath)) { + if (planDir !== null && (await $.fs.exists(planDir.base))) { + for (const entry of await $.fs.list(planDir.base)) { if (entry.kind !== 'dir') continue - const progressPath = `${projectsPath}/${entry.name}/PROGRESS.md` + const progressPath = `${planDir.base}/${entry.name}/PROGRESS.md` if (!(await $.fs.exists(progressPath))) continue const { title, rows } = parseProgress(await $.fs.read(progressPath)) const { mtimeMs } = await $.fs.stat(progressPath) @@ -49,7 +86,8 @@ export async function loadBoard($: EngineInterface) { } projects.sort((first, second) => second.updatedAt - first.updatedAt) - const next: PlanBoard = { projectsDir, repoUrl, worktrees, projects } + const planDirError = 'error' in resolved ? resolved.error : null + const next: PlanBoard = { planDir, planDirError, repoUrl, worktrees, projects } await update($, board, () => next) const current = await read($, selected) @@ -61,16 +99,17 @@ export async function loadBoard($: EngineInterface) { export async function deleteProject($: EngineInterface, name: string) { const current = await read($, board) const isKnown = current?.projects.some(project => project.name === name) ?? false - if (current === null || !isKnown || !isSafeProjectName(name)) { + const planDir = current?.planDir ?? null + if (planDir === null || !isKnown || !isSafeProjectName(name)) { await update($, notice, () => `Refused to delete "${name}".`) return } - const target = `${await repoRoot($)}/${current.projectsDir}/${name}` + const target = `${planDir.base}/${name}` const removal = await $.process.run(['rm', '-rf', '--', target]) await update($, pendingDelete, () => null) await update($, notice, () => - removal.exitCode === 0 ? `Deleted ${current.projectsDir}/${name}` : `Delete failed: ${removal.stderr.trim()}`, + removal.exitCode === 0 ? `Deleted ${planDir.label}/${name}` : `Delete failed: ${removal.stderr.trim()}`, ) await update($, selected, () => null) await loadBoard($) diff --git a/panel/domain/plan-dir.test.ts b/panel/domain/plan-dir.test.ts new file mode 100644 index 0000000..0114e5d --- /dev/null +++ b/panel/domain/plan-dir.test.ts @@ -0,0 +1,85 @@ +import { expect, test } from 'claude-code/testing' + +import { parseWorkflowEnv, resolvePlanDir } from './plan-dir' + +const REPO = '/code/myrepo' +const OBSIDIAN = 'TASKFLOW_PLANS_SOURCE=obsidian\nTASKFLOW_OBSIDIAN_PATH=taskflow/myrepo\n' + +test('keeps a relative projectsDir under the repo', () => { + expect(resolvePlanDir({ projectsDir: 'docs/projects', env: {}, obsidianVaults: null, repoRoot: REPO })).toEqual({ + base: '/code/myrepo/docs/projects', + label: 'docs/projects', + }) +}) + +test('defaults to docs/projects', () => { + expect(resolvePlanDir({ projectsDir: null, env: {}, obsidianVaults: null, repoRoot: REPO })).toEqual({ + base: '/code/myrepo/docs/projects', + label: 'docs/projects', + }) +}) + +test('resolves a vault by folder name', () => { + const env = parseWorkflowEnv(`# plans live in Obsidian\n${OBSIDIAN}TASKFLOW_OBSIDIAN_VAULT=Work\n`) + const obsidianVaults = ['/Users/me/Notes/Personal', '/Users/me/Notes/Work'] + + expect(resolvePlanDir({ projectsDir: 'docs/projects', env, obsidianVaults, repoRoot: REPO })).toEqual({ + base: '/Users/me/Notes/Work/taskflow/myrepo', + label: 'Obsidian · Work/taskflow/myrepo', + }) +}) + +test('prefers an absolute vault path over the name', () => { + const env = parseWorkflowEnv(`${OBSIDIAN}TASKFLOW_OBSIDIAN_VAULT=Other\nTASKFLOW_OBSIDIAN_VAULT_PATH=/abs/Work\n`) + + expect(resolvePlanDir({ projectsDir: null, env, obsidianVaults: null, repoRoot: REPO })).toEqual({ + base: '/abs/Work/taskflow/myrepo', + label: 'Obsidian · Work/taskflow/myrepo', + }) +}) + +test('errors on a missing or ambiguous vault', () => { + const env = parseWorkflowEnv(`${OBSIDIAN}TASKFLOW_OBSIDIAN_VAULT=Work\n`) + const resolve = (obsidianVaults: string[] | null) => + resolvePlanDir({ projectsDir: 'docs/projects', env, obsidianVaults, repoRoot: REPO }) + + expect(resolve(null)).toEqual({ error: expect.stringContaining('obsidian.json') }) + expect(resolve(['/a/Personal'])).toEqual({ error: expect.stringContaining('No Obsidian vault named "Work"') }) + expect(resolve(['/a/Work', '/b/Work'])).toEqual({ + error: expect.stringContaining('2 Obsidian vaults are named "Work"'), + }) + expect( + resolvePlanDir({ projectsDir: null, env: parseWorkflowEnv(OBSIDIAN), obsidianVaults: [], repoRoot: REPO }), + ).toEqual({ error: expect.stringContaining('TASKFLOW_OBSIDIAN_VAULT') }) +}) + +test('uses the repo unless source is obsidian', () => { + for (const source of ['', 'TASKFLOW_PLANS_SOURCE=repo\n', 'TASKFLOW_PLANS_SOURCE=vault\n']) { + const env = parseWorkflowEnv(`${source}TASKFLOW_OBSIDIAN_VAULT_PATH=/abs/Work\nTASKFLOW_OBSIDIAN_PATH=plans\n`) + + expect(resolvePlanDir({ projectsDir: 'plans', env, obsidianVaults: ['/abs/Work'], repoRoot: REPO })).toEqual({ + base: '/code/myrepo/plans', + label: 'plans', + }) + } +}) + +test('refuses .. and absolute inner paths', () => { + for (const inner of ['../escape', 'taskflow/../../escape', '/etc']) { + const env = parseWorkflowEnv( + `TASKFLOW_PLANS_SOURCE=obsidian\nTASKFLOW_OBSIDIAN_VAULT_PATH=/abs/Work\nTASKFLOW_OBSIDIAN_PATH=${inner}\n`, + ) + + expect(resolvePlanDir({ projectsDir: null, env, obsidianVaults: null, repoRoot: REPO })).toEqual({ + error: expect.stringContaining('TASKFLOW_OBSIDIAN_PATH'), + }) + } +}) + +test('ignores keys outside the allow-list', () => { + expect( + parseWorkflowEnv('TASKFLOW_GATES_LINT=rm -rf /\nPROJECTS_DIR=/tmp\nTASKFLOW_PLANS_SOURCE = obsidian \n'), + ).toEqual({ + TASKFLOW_PLANS_SOURCE: 'obsidian', + }) +}) diff --git a/panel/domain/plan-dir.ts b/panel/domain/plan-dir.ts new file mode 100644 index 0000000..24a8b19 --- /dev/null +++ b/panel/domain/plan-dir.ts @@ -0,0 +1,76 @@ +import type { PlanDir } from '../../types' + +const ENV_KEYS = [ + 'TASKFLOW_PLANS_SOURCE', + 'TASKFLOW_OBSIDIAN_VAULT', + 'TASKFLOW_OBSIDIAN_VAULT_PATH', + 'TASKFLOW_OBSIDIAN_PATH', +] as const + +export type WorkflowEnv = Partial> + +export const DEFAULT_PROJECTS_DIR = 'docs/projects' + +const isEnvKey = (key: string): key is (typeof ENV_KEYS)[number] => ENV_KEYS.some(allowed => allowed === key) + +const basename = (path: string) => path.replace(/\/+$/, '').split('/').pop() ?? '' + +// workflow.env is untracked, so only the keys that pick the plan source are read - never gates or models. +export function parseWorkflowEnv(text: string): WorkflowEnv { + const env: WorkflowEnv = {} + for (const line of text.split('\n')) { + const trimmed = line.trim() + const separator = trimmed.indexOf('=') + if (trimmed.startsWith('#') || separator < 1) continue + const key = trimmed.slice(0, separator).trim() + if (isEnvKey(key)) env[key] = trimmed.slice(separator + 1).trim() + } + + return env +} + +function vaultPath(env: WorkflowEnv, obsidianVaults: string[] | null): { path: string } | { error: string } { + const explicit = env.TASKFLOW_OBSIDIAN_VAULT_PATH + if (explicit) { + return explicit.startsWith('/') ? { path: explicit } : { error: 'TASKFLOW_OBSIDIAN_VAULT_PATH must be absolute.' } + } + + const name = env.TASKFLOW_OBSIDIAN_VAULT + if (!name) return { error: 'Set TASKFLOW_OBSIDIAN_VAULT or TASKFLOW_OBSIDIAN_VAULT_PATH in .claude/workflow.env.' } + if (obsidianVaults === null) return { error: 'Cannot read Obsidian’s obsidian.json to find the vault.' } + + const matches = obsidianVaults.filter(path => basename(path) === name) + if (matches.length === 0) return { error: `No Obsidian vault named "${name}".` } + if (matches.length > 1) { + return { error: `${matches.length} Obsidian vaults are named "${name}" - set TASKFLOW_OBSIDIAN_VAULT_PATH.` } + } + + return { path: matches[0] ?? '' } +} + +// With Obsidian as the source a problem is an error, never a fallback: the repo folder may hold other plans. +export function resolvePlanDir(input: { + projectsDir: string | null + env: WorkflowEnv + obsidianVaults: string[] | null + repoRoot: string +}): PlanDir | { error: string } { + const { env, repoRoot } = input + if (env.TASKFLOW_PLANS_SOURCE !== 'obsidian') { + const projectsDir = input.projectsDir ?? DEFAULT_PROJECTS_DIR + + return { base: `${repoRoot}/${projectsDir}`, label: projectsDir } + } + + const inner = (env.TASKFLOW_OBSIDIAN_PATH ?? '').replace(/\/+$/, '') + if (inner.startsWith('/') || inner.split('/').includes('..')) { + return { error: `TASKFLOW_OBSIDIAN_PATH "${inner}" must stay inside the vault.` } + } + + const vault = vaultPath(env, input.obsidianVaults) + if ('error' in vault) return vault + const root = vault.path.replace(/\/+$/, '') + const shown = inner ? `${basename(root)}/${inner}` : basename(root) + + return { base: inner ? `${root}/${inner}` : root, label: `Obsidian · ${shown}` } +} diff --git a/panel/ui/components/organisms/PlanDetail.tsx b/panel/ui/components/organisms/PlanDetail.tsx index 2c5585c..039dc5b 100644 --- a/panel/ui/components/organisms/PlanDetail.tsx +++ b/panel/ui/components/organisms/PlanDetail.tsx @@ -69,7 +69,7 @@ export function PlanDetail(props: PlanDetailProps) { {isDeleting ? ( - Delete {board.projectsDir}/{project.name}? This cannot be undone. + Delete {board.planDir?.label}/{project.name}? This cannot be undone.