diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a503a7f..e2c2500 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,7 +47,7 @@ cd "" - A task name is one path component in the form `YYYY-MM-DD-short-slug`, and every command that takes one checks it before joining it into a path (`hooks/task-id`). `hooks/task unpromote ` undoes a promotion made under a name you meant to change; it refuses when the directory has been worked on, because at that point undoing it is a Git decision. - Confirm where you are before editing. `git branch --show-current` shows the branch; `bash hooks/repository-check .` reports the local branch and warns with `Base: ambiguous` when no upstream is set. - If a local `bash hooks/smoke-test` is warranted, run it in the worktree whose files changed, not in another checkout — the suite reads the tree it is run from. -- **Keep or remove the worktree separately from branch cleanup.** After archiving and committing a task, retain an idle worktree for reuse through the TaskFlow handoff; confirm it is unoccupied and preserve ignored files and task ledgers. For a merged branch, first verify its commit is contained in the current remote base and that deletion was authorized, switch the worktree safely away from it, and run `git branch -d `. Do not infer a merge into the intended base from `-d` alone: Git can use the branch's upstream. If ancestry is unproven or `-d` refuses, retain the branch. Worktree removal remains an explicitly authorized alternative after inspecting tracked, untracked and ignored files; never force it. +- **Keep or remove the worktree separately from branch cleanup.** After archiving and committing a task, retain an idle worktree for reuse through the TaskFlow handoff; confirm it is unoccupied and preserve ignored files and task ledgers. Before deleting a merged branch that is still checked out, use `bash hooks/reuse-worktree park --root `. The command verifies containment in the current base and retains the archive commit and idle state. Then run `git branch -d ` if deletion was authorized. Do not infer a merge into the intended base from `-d` alone: Git can use the branch's upstream. If ancestry is unproven or `-d` refuses, retain the branch. Worktree removal remains an explicitly authorized alternative after inspecting tracked, untracked and ignored files; never force it. `skills/taskflow/SKILL.md` states the same rule where the phases are defined. diff --git a/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/plan.md b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/plan.md new file mode 100644 index 0000000..d265950 --- /dev/null +++ b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/plan.md @@ -0,0 +1,171 @@ +# Plan — 已归档工作树的安全复用与快照恢复 +> Task version: v1 +> Status: completed + +## Spec Pointers + +- `spec.md` 的架构职责、接口、验证和 Git 状态不变量。 + +## Reference Pointers + +- `reference/verification.md` 记录真实只读核对和五宿主实测配置入口。 +- `TaskFlowDocs/repository-docs/index.md` 指向贡献规范及代码约定。 +- `skills/taskflow/references/runtime.md` 给出五宿主的共享模式、命令和挂钩入口。 +- `hooks/test-reuse-worktree` 包含现有 Windows 可运行的 Git 夹具及故障注入。 + +## Related Tasks + +- `TF-20261202-a2ffc4` 的归档任务修复单纯路径移动后的释放。这次处理本地分支清理、归档归属、快照和失败恢复。 +- `TF-20261201-643914` 定义了逐会话领取、释放和人工核实。 + +## Skills / Tools Used + +- [PRD] Declared `agent-skills:debugging-and-error-recovery` — 用于将四个现象定位到候选归属、实际交接和恢复断点。 +- [Spec] Declared `agent-skills:spec-driven-development` — 用于明确归档证明、新任务基线和恢复快照的职责与校验。 +- [Plan] Declared `agent-skills:planning-and-task-breakdown` — 用于按照依赖顺序分成三个可独立验收的步骤。 +- [Test] Declared `agent-skills:test-driven-development` — 用于先复现失败,再验证 Git 提交、数据与释放状态。 + +## Capability Contributions + +- [PRD] `agent-skills:debugging-and-error-recovery` | prd.md#Acceptance Criteria | 指定被错误接受的任务 A 为反例,并要求拒绝前后 Git 和证据不变。 +- [Spec] `agent-skills:spec-driven-development` | spec.md#Interfaces, Data Flow, and Contracts | 把历史归属与新任务起点分开核实,约束原分支重建和回滚。 +- [Plan] `agent-skills:planning-and-task-breakdown` | plan.md#Steps | 先交付共同归属校验,再连接清理和恢复,最后回归已发布入口。 +- [Test] `agent-skills:test-driven-development` | plan.md#Test Design | 用夹具比较确切 Git 管理目录、证据字节、快照分支与所有权状态。 + +## Preconditions + +- [x] 目标为 `hkwuks/TaskFlow` 的 `main`。新分支建立前远端和本地均为 `dc1e0cfe39cb69f326d5647edef9d233c17df952`。 +- [x] 任务隔离在 `.worktrees/2026-12-03-archive-worktree-handoff` 的 `fix/2026-12-03-archive-worktree-handoff` 分支。 +- [x] 按 `TaskFlowDocs/repository-docs/index.md` 读取 `README.md`、`CONTRIBUTING.md`、`CODE_STYLE.md` 和运行时宿主矩阵。此克隆无本地 `personal.md`。插件行为属贡献规范中的第一行,项目内命令指引随同它使用同一入口。 +- [x] 已确认补认旧 detached 的证据门槛、显式受管理切换及旧快照原分支重建。 +- [x] 用户已批准 v1。已核对 PR 模板和 GitHub 目标,字段映射见下。 + +## Pull request checklist mapping + +- 模板:`.github/pull_request_template.md`。标题和 Summary 概述已归档工作树复用、分支清理及快照恢复。 +- TaskFlow traceability:`TF-20261203-cd3970` 和当前任务目录;范围为归档归属、可信释放、交接恢复、共享入口和相应回归。 +- Base branch / Target repository:`hkwuks/TaskFlow` 的 `main`。2026-12-03 提前核对当前远端和本地远端跟踪分支均为 `dc1e0cfe39cb69f326d5647edef9d233c17df952`。GitHub 返回同名目标仓库且默认分支为 `main`,同名 head 没有开放的 PR。 +- Verification:对 `origin/main...HEAD` 的 `git diff --check` 通过;本地工作树回归、五宿主配置入口夹具和 Skill 校验见 Verification / Review。Hooks CI 由 draft PR 触发,结果在拿到运行记录后更新。 +- Review boundaries:变更仅涉及修复和本任务记录;基线与目标已核实;PR 正文记录真实宿主交互和跨平台 CI 的验证范围。正文只包含可公开的归档拓扑与夹具结果。 + +## Repository Rule Checks + +- host-coverage: applies +- host-coverage/claude-code: Step 3 | 审查 `hooks/hooks.json` 的命令入口和统一 Skill,由隔离仓库实跑共享命令,并注明宿主验证等级。 +- host-coverage/codex: Step 3 | 核对 `.codex-plugin/plugin.json`、`hooks/hooks-codex.json` 和 Windows 命令,通过当前 Codex 会话运行共享命令并记录实际结果。 +- host-coverage/codebuddy: Step 3 | 核对 `.codebuddy-plugin/plugin.json`、`hooks/hooks-codebuddy.json` 与共享命令,运行可用的宿主夹具并注明证据来源。 +- host-coverage/dsh: Step 3 | 核对 `dsh/index.js`、`hooks/hooks-dsh.json` 以及共享命令路径,跑既有 dsh 事件夹具并注明证据来源。 +- host-coverage/trae: Step 3 | 核对安装引用和 `hooks/hooks-trae.json` 到共享命令的入口,以可用宿主夹具和共同命令验证,注明证据来源。 + +## Plan Review + +- Verdict: sound +- Coverage: A1 对应 Step 1,A2 对应 Step 1 和 2,A3/A4 对应 Step 2,A5 对应 Step 3。 +- Verifiability: 检查已归属的归档和证据字节,而非只检查退出码。检查新 HEAD 等于核实的基线、实际复用同一个 Git 管理目录以及快照恢复后确实可查到旧提交。 +- Layer ownership: 在归档和 Git 占用层修复事实,在各入口共用其验证。测试固定实际前置条件,日志和手工确认仅用于真实不确定状态。 + +## Approval + +- Status: approved +- Approved by: user +- Approved at: 2026-12-03 14:31 +0800 +- Approved version: v1 +- Approved scope: PRD / Spec / Plan +- Approved repository checks: ab1f195d065b9e60315607a66628d9e5f1d11d7e + +## Steps + +先证明归档属于哪棵工作树,再用这份证明保障清理和恢复,最后核对五宿主实际使用的入口。 + +### Step 1 — 统一归档归属与候选校验 + +- Goal: 防止扫描从基线猜测任务和命令把旧证据存进错误快照。 +- Dependencies: 使用用户已确认的归属和历史记录边界。 +- Files: `hooks/archive`、`hooks/worktree-owner`、`hooks/start-worktree`、`hooks/reuse-worktree`、`hooks/repository-check`、相关 Git 夹具。 +- Implementation checklist: + - [x] 先写串任务及逾越基线两条最小回归。 + - [x] 建立归档到工作树的可核实关联,让三个入口共用,并在交接锁内重验。 +- Acceptance: 仓库包含多个归档时仍能判定实际归属。不同归属及含糊旧记录不会启动交接。 +- Verification: 在夹具中添加 A 后让 B 成为实际归档。比较候选输出、拒绝前后 HEAD、证据和值班状态。保留既有正常分支交接断言。 +- Rollback: 回退本步代码和测试,保留源工作树与归档证据。 +- Status: done + +### Step 2 — 连接分支清理、快照保护和失败恢复 + +- Goal: 受管理切换能保住释放记录,本地旧提交得到 Git 可达性保护。 +- Dependencies: Step 1 的归属校验可用。清理与恢复边界已由用户确认。 +- Files: `hooks/reuse-worktree`、`hooks/worktree-owner`、`hooks/test-reuse-worktree`、`hooks/test-worktree-ownership`。 +- Implementation checklist: + - [x] 按确认方案实现安全切换和本地存档保护,测试已合并、仅本地归档和多会话场景。 + - [x] 让恢复路径核对快照原分支与提交。验证同名冲突、路径和忽略文件安全。 + - [x] 回滚时仅在记录和现场均匹配的情况下恢复原可信释放。 +- Acceptance: 清理后能复用同一 Git 工作树,历史本地归档和快照仍可访问。恢复不会接管有持有者的工作树。 +- Verification: 分别测试已合入并删分支、独立本地归档、新基线推进、同名目标冲突和注入中断。检查每个状态的完整 Git 对象、目录及会话记录。 +- Rollback: 沿现有交接日志恢复原路径、分支/HEAD、证据和释放状态,保留已创建的本地归档引用。 +- Status: done + +### Step 3 — 验证宿主入口并更新用法 + +- Goal: 五个 Agent 可使用同一交接路径,诊断会说明无法复用的原因。 +- Dependencies: Step 1 和 2 完成。 +- Files: `skills/taskflow/SKILL.md`、`skills/taskflow/references/runtime.md`、`hooks/README.md`、适用的贡献规范和既有 smoke 测试。 +- Implementation checklist: + - [x] 记录归档、释放、清理、复用和恢复的调用顺序。 + - [x] 验证五宿主入口、运行可用的事件夹具,分别记录限制。新回归纳入既有 smoke 路径。 + - [x] 按贡献规范执行适用本地检查,记录尚需 CI 的项。 +- Acceptance: 五行宿主检查都有可追溯证据,流程文档和命令一致。 +- Verification: `hooks/test-reuse-worktree`、`hooks/test-worktree-ownership`、宿主配置检查、适用的宿主夹具、Skill 定义检查和 `git diff --check`。 +- Rollback: 回退对应指引及接入变更,通过保留的 Git 引用和交接日志继续访问旧任务。 +- Status: done + +## Test Design + +- A 和 B 都已归档时,证明误选 A 不改 B 的现场,也不创建错误快照。 +- 同一 Git 工作树从归档提交切换后,使用管理目录路径和精确提交检查是否实际复用。 +- 快照恢复前后比较旧分支、证据值、忽略文件和引用。用已有故障夹具注入切换失败并检查可信与未知两类结果。 +- 以两个会话分别持有、释放及仍有持有者的场景核对原有多会话限制。 + +## Checkpoints + +- 计划批准后开启回归;先证实原缺陷,再在修复分支记录结果。 +- 每步完成时将实测命令和结果写入当前计划。暂停前提交需保留的工作并释放本会话。 + +## Verification / Review + +- 2026-12-03 Step 3: 五个已发布配置入口夹具、宿主 parity 和 Skill 校验通过。 + +- 2026-12-03 Step 2: 受管理清理及本地归档可复用,快照重建和保守回滚均通过。 + +- 2026-12-03 Step 1: 错归属拒绝,诊断和自动交接识别已核实的工作树归档。 + +- `hooks/test-reuse-worktree` 在 Windows Git Bash 通过。覆盖归档 B 拒绝 A、原分支删除后的快照重建、同名不同提交拒绝、恢复时保留占用、受管理停放和清理、仅本地归档的复用,以及 reflog 过期后的正式归档复用。修复前增加的串任务测试能触发明确失败。 +- `hooks/test-worktree-ownership`、`hooks/test-worktree-candidates`、`hooks/test-ledger-lock`、`hooks/test-task-integrity` 和 `hooks/test-write-entry` 均通过。宿主 parity 夹具、Skill 定义和 Bash 语法检查通过。 +- 真实基金估值工作树仅做只读检查,确认归档关联和可信释放。没有在该仓库执行交接。其本地 `main` 有未提交改动,并与本地记录的 `origin/main` 分叉。 +- 重跑的 Ubuntu smoke 通过。macOS 夹具报出归档诊断将实际归档识别为未知。本机复现了调用者字段分隔符为空时旧归档解析失败,为解析器显式指定分隔符并加入对应回归。若诊断仍失败,夹具输出合成工作树的解析路径供定位。 +- 后续 macOS Hooks 运行记录了确切根因:系统 awk 将路径正则字符类里的斜杠解释为正则结束符。归档索引改用斜杠字段划分,只接受 TaskFlowDocs、achieved、任务名和 plan.md 四个字段,仍要求引入提交出现在所属工作树记录中。 +- GitHub Hooks CI 已通过。代码提交 e7cab33 的 Ubuntu、macOS、Windows smoke 及其余已执行检查均成功。正式 CI 结果见 [Hooks run 47056819155](https://github.com/hkwuks/TaskFlow/actions/runs/47056819155)。 +- host-coverage/claude-code: verified | reference/verification.md +- host-coverage/codex: verified | reference/verification.md +- host-coverage/codebuddy: verified | reference/verification.md +- host-coverage/dsh: verified | reference/verification.md +- host-coverage/trae: verified | reference/verification.md +- 五宿主结果来自各配置入口及 Git 工作树夹具,单独标明宿主真实交互覆盖。 +- PR #165 的首轮 Hooks CI 在 Ubuntu 报告归档清理提示缺少远端基线说明,在 macOS 提前退出工作树复用夹具。已恢复基线说明、核对受管理切换入口,并简化历史归属处理中 Bash 与 awk 的数据传递;为工作树夹具增加失败位置和未合入分支保护断言。Windows Git Bash 重跑归档章节及工作树夹具前段通过,覆盖归属诊断、未合入分支拒绝和失败回滚。 + +## Change Log + +- 2026-12-03 v1 草案,录入工作树归档交接缺陷、现有复现和验证安排。 +- 2026-12-03 v1 工作修订,依据用户确认落实旧记录补认、清理时点与原分支重建的三项边界。 +- 2026-12-03 v1 工作修订,归档增加本地归属记录,自动和手动复用共用归属校验,清理和恢复使用可核实的 Git 引用和占用状态。 + +- 2026-12-03 v1 工作修订,记录草稿 PR 的模板字段与远端核对。 + +- 2026-12-03 v1 工作修订,修复 PR #165 的 smoke 回归并增强失败诊断。 + +## Follow-ups + +- 修复后的正式 PR、CI、验收归档与发布按独立授权执行。 + +## Version History + +- v1 — planning. diff --git a/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/prd.md b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/prd.md new file mode 100644 index 0000000..7ce86d0 --- /dev/null +++ b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/prd.md @@ -0,0 +1,59 @@ +# 已归档工作树的安全复用与快照恢复 +> Task version: v1 +> Status: completed + +## Goal + +工作树归档、释放和清理本地分支后,TaskFlow 能定位旧任务的证据,从核实过的基线开始新任务,并在必要时恢复旧任务快照。 + +## Task Kind + +- Kind: defect + +## Background / Confirmed Facts + +- `gold-rl-orderflow` 已释放且干净,停在 detached HEAD `30b5a21`,本地归档引用仍指向该提交。该提交不在所选 `main` 历史中。自动发现要求有分支,显式交接另外要求旧 HEAD 在新基线历史中。 +- TaskFlow 仓库清理后保留了五棵停在同一基线的工作树。把最近一次修改 `TaskFlowDocs/achieved/` 的任务当成当前归档,产生了四项错误归属。 +- 隔离 Git 仓库复现三项断点:指定继承自基线的任务 A 会把任务 B 的证据存入 A 的快照;已合并分支安全删除后恢复报 `Target branch does not exist`;忽略文件冲突使交接失败,回滚成功后释放状态从 `released` 变成 `unknown`。 + +## Requirements + +- R1. 自动发现、显式交接和候选诊断使用同一套可核实任务归属。传入与归属不符的任务时,在切换 Git 或搬移证据前拒绝。 +- R2. 有可信释放和旧任务归档证据的 detached 工作树可复用。旧归档提交需要可恢复。新任务分支以核实的所选基线为起点。 +- R3. 归档、释放、受管理切换和删除本地分支的边界清楚。会话逐个释放。活跃任务、其他会话、未完成交接和脏文件继续阻止自动复用。 +- R4. 快照和原提交仍在时,可显式恢复相关旧任务。恢复不得覆盖冲突分支或忽略文件。 +- R5. 安全失败后能回滚原工作树路径、Git 提交和任务证据。只有原可信释放和当前状态均可核实时,工作树恢复为 `released`。 + +## Acceptance Criteria + +- A1. 隔离仓库中 B 的基线包含 A 的归档。显式请求以 A 交接被拒绝且路径、HEAD 和证据均不变。扫描和诊断都报告 B,包括基线含其他更新归档的情况。 +- A2. 受管理切换后删除已合并的本地分支,自动新任务再次使用同一 Git 管理目录。复现 `gold-rl-orderflow` 的本地归档拓扑,自动和显式路径都从核实的新基线创建分支并保留旧档。无法证明归属或占用状态的历史工作树无需被自动采用。 +- A3. 正常交接后删掉已合并的原分支,显式恢复仍回到快照提交及其证据。同名分支已存在但指向其他提交时,退出且保持现状。 +- A4. 注入忽略文件冲突或交接中断,恢复前的写入被待恢复记录拦截。完全回滚后保护用户文件及证据。测试同时验证可证明的空闲恢复和不可证明时的保守拒绝。 +- A5. Claude Code、Codex、CodeBuddy、dsh 和 Trae 均核对共享命令入口和本次改动,分别记录真机、宿主事件夹具或配置静态检查的证据等级。 + +## External Facts + +- Depends on external facts: no +- Why not: `hooks/start-worktree`、`hooks/reuse-worktree` 和 `hooks/worktree-owner` 定义 TaskFlow 的交接行为,`hooks/test-reuse-worktree` 和隔离 Git 仓库提供复现与验收。真实工作树的只读观察用于确认场景。 + +## In Scope + +- 工作树归档归属、释放与清理的衔接、自动和手动复用、恢复快照和失败回滚。 +- 五个现有 Agent 的共享入口、使用说明和回归验证。 + +## Out of Scope + +- 对基金估值仓库或其他真实工作树执行清理、恢复、强制接管、合并或推送。 +- 自动删除本地或远端分支,修改宿主全局配置,重新定义远端基线规则。 + +## Risks / Deferred Items + +- Git 命令可绕过 TaskFlow 锁。每次切换仍要比较分支、提交、目录及状态,并保护已知用户文件。 +- Git 引用过期或本地数据缺失时,明确报出哪个证明缺失。由下一次显式核实决定是否接管。 + +## Open Questions + +- 用户确认:旧 detached 工作树可在本地归档引用、工作树记录和释放证明一致时补认。证据缺失或冲突时,确需复用才人工核实。 +- 用户确认:释放只解除当前会话占用。清理需要显式受管理切换,沿用现有本地分支删除授权。 +- 用户确认:显式恢复可按可靠快照重建已清理的原本地分支。同名分支指向不同提交则停止。 diff --git a/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/reference/verification.md b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/reference/verification.md new file mode 100644 index 0000000..6085395 --- /dev/null +++ b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/reference/verification.md @@ -0,0 +1,31 @@ +# 工作树归档与交接验证 + +## 本地复现 + +- 修复前的隔离仓库中,实际归档任务 B 传入继承在基线上的 A 后成功交接,B 的证据落到 A 的快照。 +- 修复前已合并分支删除后,快照和原提交可读,恢复却以缺分支被拒。忽略文件冲突触发回滚后,原 Git 与证据恢复,状态从 `released` 变为 `unknown`。 +- 修复版在基金估值仓库只读识别到 `2026-12-02-gold-rl-orderflow`、归档提交 `30b5a214b21002b96a758b287735065cb03e18f8` 和原归档分支 `archive/gold-rl-orderflow-20261202`。占用状态为 `released`。该提交不在该库 `origin/main` 历史里。真实基金估值仓库未执行交接,当前该仓库本地基线有未提交改动且与本地记录的上游分叉。 + +## Five-host entry verification + +在 Windows Git Bash 下从各宿主实际配置渲染 `SessionStart` 命令。隔离的真实 Git 工作树收到模拟宿主事件。通过 `worktree-owner status` 检查恰好登记事件中的会话,再通过共享 `release` 检查释放。下列结果是发布配置入口和 Git 实测,宿主事件由夹具提供。 + +## host-coverage/claude-code + +- Evidence: `hooks/hooks.json` 的 `SessionStart` 经 `run-hook.cmd` 的 Bash 入口返回上下文,并登记且释放夹具会话。未启动 Claude Code 交互会话。 + +## host-coverage/codex + +- Evidence: `.codex-plugin/plugin.json` 指向 `hooks/hooks-codex.json`。该配置的 `commandWindows` 经过 Windows `cmd.exe` 和 `run-hook.cmd` 后返回上下文,并登记且释放夹具会话。本次修复也从当前 Codex 会话执行仓库的共享工作树测试,宿主事件仍由夹具提供。 + +## host-coverage/codebuddy + +- Evidence: `.codebuddy-plugin/plugin.json` 指向 `hooks/hooks-codebuddy.json`。其 Bash `SessionStart` 返回上下文,并登记且释放夹具会话。未启动 CodeBuddy 交互会话。 + +## host-coverage/dsh + +- Evidence: `dsh/index.js` 已挂接 `hooks/hooks-dsh.json` 的 Claude Code 形状配置。渲染后的 Bash 启动命令返回上下文,并登记且释放夹具会话。未启动真实 dsh 桥接会话。 + +## host-coverage/trae + +- Evidence: `hooks/README.md` 指向可安装的 `hooks/hooks-trae.json`。夹具不提供 `cwd`,配置命令通过工作目录回退返回上下文,并登记且释放夹具会话。未启动 Trae 交互会话。 diff --git a/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/spec.md b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/spec.md new file mode 100644 index 0000000..b041308 --- /dev/null +++ b/TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/spec.md @@ -0,0 +1,56 @@ +# Spec — 已归档工作树的安全复用与快照恢复 +> Task version: v1 + +## Objective and Success Criteria + +共享交接命令验证两个独立的 Git 事实。旧任务的归属、证据和提交可恢复。新任务从核实的用户所选基线开始。 + +## Architecture Boundaries and Responsibilities + +| 边界 | 职责 | +| --- | --- | +| 归档与占用 | 归档关联工作树与任务。原工作树提交归档后,最后一个会话的释放提供可信空闲证明。 | +| 候选查询与交接 | 只读查询展示证据来源。实际交接在已有工作树账本锁下重验,并使用交接日志搬移证据和工作树。 | +| Git 清理与快照恢复 | 受管理切换保存可信释放与可恢复提交。显式恢复校验快照、分支和证据,缺失的原分支才可按快照重建。 | + +## Project Structure / Affected Files + +- `hooks/archive`、`hooks/worktree-owner`、`hooks/reuse-worktree`、`hooks/start-worktree` 及 `hooks/repository-check` 的相关工作树交接入口。 +- `hooks/test-reuse-worktree`、`hooks/test-worktree-ownership`、`hooks/smoke-test` 已提供隔离 Git 和发布面回归。 +- 插件指引位于 `skills/taskflow/SKILL.md`、`skills/taskflow/references/runtime.md` 和 `hooks/README.md`。如有必要,把本仓库 `CONTRIBUTING.md` 现行命令更新为同一条受管理入口。 + +## Interfaces, Data Flow, and Contracts + +1. 把当前工作树实际归档的任务与可核实的原分支、旧提交关联,保存在客户端已有的 Git 工作树管理目录或交接日志。归档提交前,仅登记待验证的归档关联。可信释放证明继续使用当前占用账本。 +2. 清理前核实归档已提交、旧提交受 Git 引用保护、工作树无持有者/写入者,且清理满足核实合入和用户授权。受管理切换全程使用已有锁,重验预期 Git 状态并同步释放记录。本地分支删除仍依照原有明确授权。 +3. 自动、显式和诊断共享归属解析。自动候选只能接受唯一的归属和可信空闲。显式路径需要相同的归属证明;保留现有的必要空闲确认方式。旧提交保存在现有确切本地引用或普通分支均可;缺少保留点时用可达的本地 Git 引用固定提交。 +4. 显式 `resume` 根据完成的回执绑定任务、原分支、提交与证据校验值。只有快照指定的原分支缺失时,才按快照的原提交重建。已有同名分支必须处于同一提交;发现冲突、证据错误或目标路径占用,拒绝并保留记录。 +5. 恢复日志保存原 Git 身份与释放证明。在原路径、Git 提交、账本和会话占用都核实后,才允许回滚恢复可信释放。有疑点的情况保持未知或被占用。 + +## Invariants and Compatibility + +- 归档在基线中出现、路径与任务同名、短 SHA 或 Git 干净,单独都无法证明工作树归属或释放。 +- 旧任务的提交及历史无需成为新分支祖先。所选远端基线必须在创建新任务前核实。 +- 无持有者、无待修复交接、工作树与索引安全、忽略文件受保护等既有条件继续有效。 +- 用户批准补认旧 detached 记录。只有本机 Git 工作树历史、已完成归档、可达引用与可信释放记录一致时才补认。旧记录有歧义时停止自动复用。 + +## Validation and Error Semantics + +- 候选不可用时只读报告缺失或冲突的理由。写入、分支切换或账本搬移开始后出错,保留待恢复日志并停止后续候选操作。 +- 旧快照的校验值、完整 Git 提交及原分支均须核实。回滚检查不成功时保留恢复证据。 +- 归档提交需要 Git 可达性。回执中的文本 SHA 无法替代 Git 引用。 + +## Code and Test Constraints + +- 复用现有 Bash、Git 及账本锁。能用已存在的归档引用时复用引用。 +- 集成用例检查新旧 Git 提交、任务名、真实快照内容、会话占用与候选的实际 Git 管理目录。既有五宿主配置和入口纳入检查。 +- 无持有者的判断受现有锁约束。不通过超时、会话单轮结束或工作树干净推断空闲。 + +## Design Decisions and Alternatives + +- 优先保存可验证的任务归属,替换“最近归档”推断。工作树会随任务切换,也可能停在统一基线上。 +- 建新任务和恢复旧任务使用不同的目标提交。迟到的基线检查或自动把旧历史并入基线会改变新任务内容。 + +## Open Questions + +- 三项实施边界已确认,见 `prd.md`。 diff --git a/TaskFlowDocs/todo.md b/TaskFlowDocs/todo.md index 15fbde2..af7aad4 100644 --- a/TaskFlowDocs/todo.md +++ b/TaskFlowDocs/todo.md @@ -35,6 +35,14 @@ has an issue number or URL. +## 修复已归档工作树清理分支后的安全复用、任务证据归属和 + +- ID: TF-20261203-cd3970 +- Status: done +- Goal: 修复已归档工作树清理分支后的安全复用、任务证据归属和快照恢复 +- Task: `TaskFlowDocs/achieved/2026-12-03-archive-worktree-handoff/` +- Next action: None — completed and archived. + ## 修复已归档工作树的空闲识别和复用,保留多会话占用与安 - ID: TF-20261202-a2ffc4 diff --git a/hooks/README.md b/hooks/README.md index 8d37cc2..6fceb0e 100644 --- a/hooks/README.md +++ b/hooks/README.md @@ -27,6 +27,7 @@ taskflow/hooks/ ├── task-workspace # resolve a confirmed Todo or start a development workspace ├── start-worktree # reuse a released archive or create and claim the workspace ├── worktree-owner # per-session membership, release and checked takeover +├── worktree-archive # shared archive association and local commit retention ├── worktree-entry # reclaim before writing; verify external branch ancestry before planning ├── test-worktree-ownership # session and remote-base integration fixtures ├── test-write-entry # resumed writers and external first planning @@ -369,7 +370,7 @@ above is the one this repository documents. Windows, runs the full lifecycle through PowerShell 5.1 + `run-hook.cmd` in a path containing spaces and Chinese characters). -At branch creation, `start-worktree / [base]` and `reuse-worktree start` check the live target of the selected base. A behind local base must fast-forward before planning. `worktree-owner status` lists holders and explains unknown or stale records. The final release enables handoff if the recorded checkout still matches. Moving a trusted, released worktree can preserve that release when Git registers the new path and the old path is gone, with the Git directory, branch, and commit unchanged. See the skill for the claim and release sequence, manual takeover, and crash recovery. +At branch creation, `start-worktree / [base]` and `reuse-worktree start` check the live target of the selected base. A behind local base must fast-forward before planning. `worktree-owner status` lists holders and explains unknown or stale records. The final release enables handoff if the recorded checkout still matches. Moving a trusted, released worktree can preserve that release when Git registers the new path and the old path is gone, with the Git directory, branch, and commit unchanged. Use `reuse-worktree park --root ` to keep the archived commit and idle state while detaching for authorized local branch cleanup. Automatic and explicit handoff check the same archive association. `resume` can restore a deleted original branch from its verified snapshot. See the skill for the claim and release sequence, manual takeover, and crash recovery. Hosts without hooks run the base flow unchanged; hooks are optional. diff --git a/hooks/archive b/hooks/archive index de86ae3..bbfd331 100755 --- a/hooks/archive +++ b/hooks/archive @@ -6,8 +6,8 @@ # active path absent | achieved path exists | achieved root PRD+Plan completed # Approval is never touched. On any failure the directory move and the Todo # rewrite are undone when they had already started; exit 1. -# Git is never invoked: on success the script prints the exact stage lines and -# states that the archive commit belongs on the current branch. +# On success the script records the linked worktree association and prints the +# exact stage lines. The archive commit belongs on the current branch. set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" task="$1"; root="${2:-$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")}" @@ -16,6 +16,20 @@ task="$1"; root="${2:-$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD" # by this script. The `mv` at the end is the one that can carry a directory from # outside this repository into `achieved/`. bash "$HERE/task-id" "$task" || exit 1 +git_dir="$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null || true)" +if [ -n "$git_dir" ] && [ -f "$git_dir/commondir" ]; then + source "$HERE/ledger-lock" + source "$HERE/worktree-archive" + token="${TASKFLOW_WRITER_TOKEN:-}" + if [ "${token%/*}" != "$git_dir/taskflow/.ledger-lock" ] || + [[ "${token##*/}" != writer.* ]] || [ ! -f "$token" ] || [ -L "$token" ]; then + taskflow_ledger_acquire "$git_dir" || { echo 'Worktree busy or handoff pending.' >&2; exit 1; } + trap 'if [ -n "$token" ]; then rm -f "$token"; fi; taskflow_ledger_release' EXIT + token='' + token="$(mktemp "$TASKFLOW_LEDGER_LOCK/writer.XXXXXXXX")" || exit 1 + export TASKFLOW_WRITER_TOKEN="$token" + fi +fi bash "$HERE/worktree-entry" write "$root" || exit 1 docs="$root/TaskFlowDocs" [ -d "$docs/$task" ] || { echo "no active task $docs/$task"; exit 1; } @@ -349,6 +363,12 @@ if [ "$fail" = "0" ]; then s2="$(printf '%s\n' "$entry" | grep -v -e '^- ID: ' -e '^- Status: ' -e '^- Goal: ' -e '^- Task: ' -e '^- Next action: ' || true)" [ -z "$s2" ] || { echo "FAIL: compacted entry kept fields it should have moved:"; printf '%s\n' "$s2"; fail=1; } fi +if [ "$fail" = "0" ] && [ -n "$git_dir" ] && [ -f "$git_dir/commondir" ]; then + branch="$(git -C "$root" symbolic-ref --quiet HEAD)" && + head="$(git -C "$root" rev-parse --verify 'HEAD^{commit}')" && + worktree_archive_write "$git_dir" "$task" "${branch#refs/heads/}" "$head" pending || + { echo 'FAIL: could not record the worktree archive association'; fail=1; } +fi if [ "$fail" != "0" ]; then rollback "$moved" "$todo_bak" "$plan_bak" echo "archive FAILED" @@ -356,7 +376,7 @@ if [ "$fail" != "0" ]; then fi rm -f "$todo_bak" "$plan_bak" echo "archive OK: $task -> achieved, Todo done" -# The hook does not touch Git (design boundary). Print the exact stage so the +# The hook does not stage or commit. Print the exact stage so the # Agent cannot miss the deletion half of the mv, and pin the branch rule: the # archive commit belongs on the current worktree branch, not on main. printf '%s\n' \ @@ -369,5 +389,5 @@ if [ -n "$git_dir" ] && [ -f "$git_dir/commondir" ]; then [ -n "$branch" ] || branch="" printf '%s\n' \ "After the archive is committed, release your session with worktree-owner release. After all sessions release, retain this clean, idle worktree for an explicit reuse handoff." \ - "Local branch cleanup is separate: after verifying '$branch' is included in the current remote base and switching away, use git branch -d '$branch' only with cleanup authorization. Retain it if Git refuses." + "For authorized local branch cleanup, first run reuse-worktree park '$task' --root . It verifies containment in the current remote base, or the selected local base in a repository without a remote. Then use git branch -d '$branch'. Retain the branch if either check refuses." fi diff --git a/hooks/repository-check b/hooks/repository-check index 3b4e453..2659085 100755 --- a/hooks/repository-check +++ b/hooks/repository-check @@ -4,6 +4,7 @@ set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/worktree-archive" root="${1:-$(git rev-parse --show-toplevel 2>/dev/null || true)}" if [ -z "$root" ] || ! git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then echo "STATUS: blocked" @@ -169,15 +170,15 @@ while IFS= read -r line; do candidates=1 continue fi - # Most recently changed archived task is only a lead, not proof of ownership. - task="$(git -C "$path" log -1 --format= --name-only -- TaskFlowDocs/achieved 2>/dev/null | awk -F/ '$1 == "TaskFlowDocs" && $2 == "achieved" && NF > 3 && !seen { print $3; seen=1 }')" || task="" + archive="$(worktree_archive_resolve "$path" 2>/dev/null)" || archive='' + task="${archive%%|*}" if [ -n "$task" ] && [ -f "$path/TaskFlowDocs/achieved/$task/prd.md" ] && [ -f "$path/TaskFlowDocs/achieved/$task/plan.md" ]; then if [ -n "$status" ]; then state='changes present' else ownership="$(bash "$HERE/worktree-owner" status --root "$path")" || ownership=invalid state="clean; idle ${ownership%% *}" fi - printf '%s\n' " candidate: $path: recent archive $task ($state)" + printf '%s\n' " candidate: $path: archive $task ($state)" candidates=1 else printf '%s\n' " candidate: $path (current archived task unknown; inspect)" diff --git a/hooks/reuse-worktree b/hooks/reuse-worktree index c2e1015..df712ce 100644 --- a/hooks/reuse-worktree +++ b/hooks/reuse-worktree @@ -7,7 +7,8 @@ HERE="$(cd "$(dirname "$0")" && pwd)" source "$HERE/ledger-lock" source "$HERE/worktree-owner" source "$HERE/worktree-entry" -usage() { echo 'usage: reuse-worktree start [--confirmed-idle] [--root ] | resume [--confirmed-idle] [--root ] | recover --confirmed-idle [--root ]' >&2; exit 2; } +source "$HERE/worktree-archive" +usage() { echo 'usage: reuse-worktree start [--confirmed-idle] [--root ] | resume [--confirmed-idle] [--root ] | park [--root ] | recover --confirmed-idle [--root ]' >&2; exit 2; } failure_status=1 fail() { echo "$*" >&2; exit "$failure_status"; } [ "$#" -ge 1 ] || usage @@ -26,6 +27,7 @@ case "$command" in if [ "${#args[@]}" -eq 5 ] && [ "${args[4]}" = --confirmed-idle ]; then confirmed=yes elif [ "${#args[@]}" -ne 4 ]; then usage; fi owner_identity || exit 1 ;; + park) [ "${#args[@]}" -eq 2 ] || usage ;; recover) [ "${#args[@]}" -eq 1 ] && [ "${args[0]}" = --confirmed-idle ] || usage ;; *) usage ;; esac @@ -39,7 +41,7 @@ mainroot="$(git -C "$mainroot" rev-parse --show-toplevel 2>/dev/null)" || fail ' maingit="$(git -C "$mainroot" rev-parse --absolute-git-dir 2>/dev/null)" || fail 'Cannot resolve the main Git directory.' [ "$maingit" = "$mainroot/.git" ] && [ ! -L "$mainroot/.git" ] && [ ! -L "$gitdir" ] || fail 'Git metadata is outside the project or uses an unsupported layout.' case "$gitdir" in "$maingit"/worktrees/*) ;; *) fail 'Worktree metadata is outside the project.' ;; esac -if [ "$failure_status" -eq 4 ] && awk -v path="$root" '/^worktree / {current=substr($0,10)} /^locked($| )/ && current == path {found=1} END {exit !found}' <<< "$trees"; then +if { [ "$failure_status" -eq 4 ] || [ "$command" = park ]; } && awk -v path="$root" '/^worktree / {current=substr($0,10)} /^locked($| )/ && current == path {found=1} END {exit !found}' <<< "$trees"; then fail 'Git worktree is locked; preserve it.' fi case "$root$gitdir" in *$'\n'*|*$'\r'*) fail 'Worktree paths with newlines require manual handling.' ;; esac @@ -47,7 +49,7 @@ taskflow_ledger_acquire "$gitdir" allow-pending || fail 'Ledger lock is busy or trap taskflow_ledger_release EXIT [ "$(git -C "$root" rev-parse --absolute-git-dir)" = "$gitdir" ] || fail 'Worktree identity changed before handoff.' store="$gitdir/taskflow"; journal="$store/handoff.pending" -ledgers='evidence released declarations external released.discarded capability-contexts capability-pending capability-revisions' +ledgers='evidence released declarations external released.discarded capability-contexts capability-pending capability-revisions archived-worktree' read_field() { [ -f "$journal/$1" ] && [ ! -L "$journal/$1" ] || fail "Invalid handoff record: $1"; cat "$journal/$1"; } write_field() { printf '%s\n' "$2" > "$journal/$1.tmp"; mv "$journal/$1.tmp" "$journal/$1"; } if [ "$command" = recover ]; then @@ -91,6 +93,21 @@ if [ "$command" = recover ]; then grep -qxF "$digest $name" "$journal/checksums" || fail "Original $name changed; inspect before recovery." fi done + restore_release=no + if [ -e "$journal/old-owner-hash" ] || [ -L "$journal/old-owner-hash" ]; then + old_owner_hash="$(read_field old-owner-hash)" + { [ "$old_owner_hash" = absent ] || [[ "$old_owner_hash" =~ ^[0-9a-f]{40,64}$ ]]; } || fail 'Invalid original ownership hash.' + owner_load || fail 'Live ownership record is invalid.' + live_owner_hash="$observed" + if [ "$live_owner_hash" != "$old_owner_hash" ]; then + [ "$live_owner_hash" = "$(read_field target-owner-hash)" ] || fail 'Live ownership changed during handoff; inspect before recovery.' + fi + if [ -e "$journal/old-ownership" ] || [ -L "$journal/old-ownership" ]; then + [ -f "$journal/old-ownership" ] && [ ! -L "$journal/old-ownership" ] || fail 'Invalid original ownership record.' + [ "$(git -C "$root" hash-object --no-filters "$journal/old-ownership")" = "$old_owner_hash" ] || fail 'Original ownership record changed.' + restore_release=yes + fi + fi if [ "$mode" = resume ]; then for name in $ledgers; do if [ -e "$store/$name" ] || [ -L "$store/$name" ]; then @@ -115,7 +132,7 @@ if [ "$command" = recover ]; then git -C "$root" checkout --no-overwrite-ignore "$old_branch" || fail 'Could not restore original branch.' fi for name in $ledgers; do - case "$name" in evidence|released|declarations|external|released.discarded|capability-contexts|capability-pending|capability-revisions) ;; *) fail 'Invalid ledger name.' ;; esac + if grep -qxF "$name" "$journal/files"; then if [ -f "$snapshot/$name" ] && [ ! -L "$snapshot/$name" ]; then if [ -e "$store/$name" ] || [ -L "$store/$name" ]; then @@ -136,9 +153,16 @@ if [ "$command" = recover ]; then root="$old_root" fi [ ! -e "$snapshot/recovered-journal" ] || fail 'Recovery history already exists.' - # Recovery has no claim on behalf of a live session. Retain the old receipt - # for inspection, but require a fresh idle decision after rollback. - if [ -f "$store/ownership" ]; then mv "$store/ownership" "$journal/ownership-at-recovery"; fi + if [ "$restore_release" = yes ]; then + if [ "$live_owner_hash" != "$old_owner_hash" ]; then + cp -p "$store/ownership" "$journal/ownership-at-recovery" || fail 'Could not preserve handoff ownership.' + cp -p "$journal/old-ownership" "$journal/restored-ownership" && + mv -f "$journal/restored-ownership" "$store/ownership" || fail 'Could not restore original ownership.' + fi + owner_load && [ "$state" = released ] || fail 'Original release is no longer verifiable; inspect before recovery.' + elif [ -f "$store/ownership" ]; then + mv "$store/ownership" "$journal/ownership-at-recovery" + fi mv "$journal" "$snapshot/recovered-journal" || fail 'Could not preserve recovery journal.' printf 'Recovered original task %s; snapshot retained at %s. Any created new branch was retained.\n' "$old_task" "$snapshot" exit 0 @@ -153,6 +177,9 @@ if [ "$command" = start ]; then git -C "$root" check-ref-format --branch "$new_branch" >/dev/null || fail 'Invalid new branch.' git -C "$root" check-ref-format --branch "$base_branch" >/dev/null || fail 'Invalid base branch.' [ "$expected" = auto ] || [[ "$expected" =~ ^[0-9a-f]{40,64}$ ]] || fail 'Expected base must be a full verified commit ID.' +elif [ "$command" = park ]; then + base_branch="${args[1]}" + git -C "$root" check-ref-format --branch "$base_branch" >/dev/null || fail 'Invalid base branch.' else target_task="${args[1]}"; new_branch="${args[2]}"; snapshot_id="${args[3]}" bash "$HERE/task-id" "$target_task" >/dev/null || exit 2 @@ -167,14 +194,23 @@ else [ -f "$target_snapshot/journal/old-sha" ] && [ -f "$target_snapshot/journal/files" ] && [ -f "$target_snapshot/journal/checksums" ] || fail 'Target snapshot metadata is incomplete.' expected="$(cat "$target_snapshot/journal/old-sha")" [[ "$expected" =~ ^[0-9a-f]{40,64}$ ]] || fail 'Invalid target commit.' + saved_branch_file="$target_snapshot/journal/old-branch" + if [ -e "$target_snapshot/journal/archive-branch" ] || [ -L "$target_snapshot/journal/archive-branch" ]; then + saved_branch_file="$target_snapshot/journal/archive-branch" + fi + [ -f "$saved_branch_file" ] && [ ! -L "$saved_branch_file" ] && + [ "$(cat "$saved_branch_file")" = "$new_branch" ] || fail 'Target branch differs from the branch recorded for this snapshot.' base_branch='@resume' fi -[ "${new_branch#*/}" != "$new_branch" ] || fail 'Target branch must have a type prefix and task slug.' -slug="${new_branch#*/}" -[[ "$slug" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || fail 'Target branch task slug must be a single safe directory name.' -target_root="${root%/*}/$slug" -if [ "$target_root" != "$root" ]; then - [ ! -e "$target_root" ] && [ ! -L "$target_root" ] || fail 'Target worktree path already exists.' +target_root="$root" +if [ "$command" != park ]; then + slug="${new_branch#*/}" + [ "$slug" != "$new_branch" ] || fail 'Target branch must have a type prefix and task slug.' + [[ "$slug" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || fail 'Target branch task slug must be a single safe directory name.' + target_root="${root%/*}/$slug" + if [ "$target_root" != "$root" ]; then + [ ! -e "$target_root" ] && [ ! -L "$target_root" ] || fail 'Target worktree path already exists.' + fi fi [ ! -e "$journal" ] && [ ! -L "$journal" ] || fail 'An incomplete handoff needs recovery first.' status="$(git -C "$root" status --porcelain --untracked-files=all --ignore-submodules=none)" || fail 'Cannot inspect worktree status.' @@ -185,18 +221,27 @@ hidden="$(printf '%s\n' "$tracked" | grep -E '^[a-zS] ' || true)" staged="$(git -C "$root" ls-files --stage)" || fail 'Cannot inspect submodules.' if printf '%s\n' "$staged" | awk '$1 == "160000" { found=1 } END { exit !found }'; then fail 'Submodule worktrees require manual isolation; reuse was not started.'; fi old_sha="$(git -C "$root" rev-parse --verify 'HEAD^{commit}')" || fail 'Cannot resolve current HEAD.' -old_branch="$(git -C "$root" symbolic-ref --quiet --short HEAD || true)" -[ -n "$old_branch" ] || old_branch='@detached' -if [ "$command" = start ]; then +old_branch="$(git -C "$root" symbolic-ref --quiet HEAD)" || old_branch=@detached +old_branch="${old_branch#refs/heads/}" +recreate=no +if [ "$command" = start ] || [ "$command" = park ]; then base_sha="$(bash "$HERE/branch-base" "$root" "$base_branch")" || { echo 'Development base is unverified.' >&2; exit 1; } - [ "$expected" != auto ] || expected="$base_sha" - [ "$base_sha" = "$expected" ] || { echo 'Base branch differs from the verified commit.' >&2; exit 1; } [ "$old_branch" != "$base_branch" ] || fail 'The reusable worktree must not be on the base branch.' - if [ "$old_branch" = '@detached' ]; then git -C "$root" merge-base --is-ancestor "$old_sha" "$base_sha" || fail 'Detached HEAD is not contained in the verified base.'; fi - if git -C "$root" show-ref --verify --quiet "refs/heads/$new_branch"; then fail 'New branch already exists.'; fi + if [ "$command" = park ]; then + git -C "$root" merge-base --is-ancestor "$old_sha" "$base_sha" || fail 'Archive commit is not contained in the verified base; keep the local branch.' + else + [ "$expected" != auto ] || expected="$base_sha" + [ "$base_sha" = "$expected" ] || { echo 'Base branch differs from the verified commit.' >&2; exit 1; } + if git -C "$root" show-ref --verify --quiet "refs/heads/$new_branch"; then fail 'New branch already exists.'; fi + fi else - base_sha="$(git -C "$root" rev-parse --verify "refs/heads/$new_branch^{commit}" 2>/dev/null)" || fail 'Target branch does not exist.' - [ "$base_sha" = "$expected" ] || fail 'Target branch differs from its snapshot commit.' + base_sha="$expected" + git -C "$root" cat-file -e "$base_sha:TaskFlowDocs/achieved/$target_task/plan.md" 2>/dev/null || fail 'Snapshot archive commit or task is unavailable.' + if git -C "$root" show-ref --verify --quiet "refs/heads/$new_branch"; then + [ "$(git -C "$root" rev-parse --verify "refs/heads/$new_branch^{commit}")" = "$base_sha" ] || fail 'Target branch differs from its snapshot commit.' + else + recreate=yes + fi [ "$old_branch" != "$new_branch" ] || fail 'Target branch is already checked out.' for name in $ledgers; do if grep -qxF "$name" "$target_snapshot/journal/files"; then @@ -220,6 +265,10 @@ for active in "$root"/TaskFlowDocs/*/plan.md; do fork="$(git -C "$root" merge-base "$old_sha" "$base_sha")" || fail 'Cannot verify active tasks against a common base.' git -C "$root" diff --quiet "$fork" "$old_sha" -- "TaskFlowDocs/$task_name" || fail "Active task $task_name has branch-specific work; choose another worktree." done +archive="$(worktree_archive_resolve "$root")" || fail 'Cannot verify which task was archived in this worktree.' +IFS='|' read -r bound_task archive_sha archive_branch <<< "$archive" +[ "$bound_task" = "$old_task" ] || fail "Worktree archived task is $bound_task, not $old_task." +[ "$archive_sha" = "$old_sha" ] || fail 'Worktree commit changed before validating the archive.' for doc in prd.md plan.md; do path="TaskFlowDocs/achieved/$old_task/$doc" git -C "$root" cat-file -e "HEAD:$path" 2>/dev/null || fail "Archived $doc is not committed." @@ -239,15 +288,39 @@ awk -v needle="- Task: \`TaskFlowDocs/achieved/$old_task/\`" ' for name in $ledgers; do if [ -e "$store/$name" ] || [ -L "$store/$name" ]; then [ -f "$store/$name" ] && [ ! -L "$store/$name" ] || fail "Invalid ledger: $name"; fi done +# Status and archive lookup are also used outside this lock for discovery. +# Recheck after the remote/base and archive validation before changing Git. +original_branch="refs/heads/$old_branch" +[ "$old_branch" != '@detached' ] || original_branch=@detached +original_owner="$observed" +owner_load && [ "$observed" = "$original_owner" ] && [ "$branch" = "$original_branch" ] && + [ "$head" = "$old_sha" ] || fail 'Worktree or ownership changed before handoff.' +failure_status=1 # From here on, failures require inspecting this handoff. +worktree_archive_protect "$root" "$archive_sha" || fail 'Cannot retain the archive commit.' +if [ "$command" = park ]; then + worktree_archive_write "$gitdir" "$old_task" "$archive_branch" "$archive_sha" parked || fail 'Cannot record the parked archive.' + # Keep the exact archive checked out until a new task verifies its own base. + if [ "$old_branch" != '@detached' ]; then + owner_save || fail 'Cannot refresh the release before parking.' + git -C "$root" checkout --no-overwrite-ignore --detach "$archive_sha" || fail 'Cannot detach the archived worktree.' + fi + owner_load && [ "$state" = released ] && [ "$head" = "$archive_sha" ] && + [ "$branch" = '@detached' ] && owner_save || fail 'Cannot verify or record the parked release.' + printf 'Parked archived task %s at %s in %s. Apply authorized local branch cleanup separately.\n' "$old_task" "$archive_sha" "$root" + exit 0 +fi +archive_state=attached +[ "$old_branch" != '@detached' ] || archive_state=parked +worktree_archive_write "$gitdir" "$old_task" "$archive_branch" "$archive_sha" "$archive_state" || fail 'Cannot record the archived worktree.' history="$store/handoff-history" [ ! -L "$history" ] || fail 'Invalid handoff history.' -failure_status=1 # From here on, failures require inspecting this handoff. mkdir -p "$history/$old_task" || fail 'Cannot create task history.' [ ! -L "$history/$old_task" ] || fail 'Invalid task history.' snapshot="$(mktemp -d "$history/$old_task/$old_sha.XXXXXXXX")" || fail 'Cannot reserve snapshot.' pending="$journal" journal="$(mktemp -d "$store/handoff.prepare.XXXXXXXX")" || fail 'Cannot prepare handoff journal.' write_field old-task "$old_task"; write_field old-branch "$old_branch"; write_field old-sha "$old_sha" +write_field archive-branch "$archive_branch" write_field old-root "$root"; write_field target-root "$target_root" write_field base-branch "$base_branch"; write_field base-sha "$base_sha"; write_field new-branch "$new_branch"; write_field snapshot "$snapshot" write_field mode "$command" @@ -263,6 +336,11 @@ for name in $ledgers; do done mv "$journal/files.tmp" "$journal/files" mv "$journal/checksums.tmp" "$journal/checksums" +write_field old-owner-hash "$observed" +if [ "$state" = released ]; then + cp -p "$store/ownership" "$journal/old-ownership" || fail 'Cannot save original ownership.' + [ "$(git -C "$root" hash-object --no-filters "$journal/old-ownership")" = "$observed" ] || fail 'Original ownership changed before handoff.' +fi write_field phase prepared mv "$journal" "$pending" || fail 'Cannot activate handoff journal.' journal="$pending" @@ -280,13 +358,15 @@ if [ "$command" = start ]; then write_field phase detached [ "$(git -C "$root" rev-parse --verify "refs/heads/$base_branch^{commit}")" = "$base_sha" ] || fail 'Base changed; recover the handoff.' git -C "$root" switch --no-track -c "$new_branch" "$base_sha" || fail 'Branch creation failed; recover the handoff.' +elif [ "$recreate" = yes ]; then + git -C "$root" checkout --no-overwrite-ignore --no-track -b "$new_branch" "$base_sha" || fail 'Could not restore the missing branch; recover the handoff.' else [ "$(git -C "$root" rev-parse --verify "refs/heads/$new_branch^{commit}")" = "$base_sha" ] || fail 'Target branch changed; recover the handoff.' git -C "$root" checkout --no-overwrite-ignore "$new_branch" || fail 'Target checkout failed; recover the handoff.' fi write_field phase switched [ "$(git -C "$root" rev-parse --verify HEAD)" = "$base_sha" ] || fail 'HEAD differs from verified target.' -[ "$(git -C "$root" symbolic-ref --quiet --short HEAD)" = "$new_branch" ] || fail 'Branch differs from requested branch.' +[ "$(git -C "$root" symbolic-ref --quiet HEAD)" = "refs/heads/$new_branch" ] || fail 'Branch differs from requested branch.' if [ "$command" = start ]; then [ "$(git -C "$root" rev-parse --verify "refs/heads/$base_branch^{commit}")" = "$base_sha" ] || fail 'Base changed during handoff.'; fi if [ "$old_branch" != '@detached' ]; then [ "$(git -C "$root" rev-parse --verify "refs/heads/$old_branch^{commit}")" = "$old_sha" ] || fail 'Original branch changed during handoff.'; fi for name in $ledgers; do [ ! -e "$store/$name" ] && [ ! -L "$store/$name" ] || fail "Unexpected new ledger $name; inspect journal."; done @@ -305,6 +385,8 @@ fi owner_load || fail 'Could not read ownership at the target; recover the handoff.' trusted=yes owner_save "$owner_id" || fail 'Could not claim the target; recover the handoff.' +owner_hash="$(git -C "$root" hash-object --no-filters "$store/ownership")" || fail 'Cannot verify target ownership.' +write_field target-owner-hash "$owner_hash" if [ "$command" = start ]; then entry_record "$base_branch" "$base_sha" || fail 'Cannot record planning base; recover the handoff.'; fi write_field phase verified mv "$journal" "$snapshot/journal" || fail 'Could not preserve completed handoff journal.' diff --git a/hooks/smoke-test b/hooks/smoke-test index 5c61c9d..3404b4c 100755 --- a/hooks/smoke-test +++ b/hooks/smoke-test @@ -1178,12 +1178,9 @@ awk ' extra && $0 == "tool details" { details = 1 } END { exit !(note && details) } ' "$gate_sections/TaskFlowDocs/achieved/2026-09-08-gate/plan.md" || { echo 'FAIL archive misplaced Todo Record or changed extra content'; exit 1; } -echo "== archive names the worktree teardown only from a linked worktree ==" -# The teardown cannot be acted on when it is printed — `complete` runs before the -# push and the merge — so the instruction carries its own condition and the -# branch name, and it is printed only where there is a directory to remove. -# Measured 2026-10-19: nine merged worktrees had accumulated because nothing said -# this anywhere and nothing ever looked again. +echo "== archive explains how to prepare a linked worktree for local branch cleanup ==" +# Archive runs before the task's branch is merged. The cleanup guidance must +# route a linked worktree through the managed switch and preserve its base check. tear="$tmp/archive-teardown" mkdir -p "$tear/TaskFlowDocs/2026-09-08-tear" "$tear/TaskFlowDocs/achieved" cat > "$tear/TaskFlowDocs/2026-09-08-tear/prd.md" <<'EOF' @@ -1216,6 +1213,8 @@ tear_out="$tmp/archive-teardown-out" bash "$HERE/archive" 2026-09-08-tear "$tear/.worktrees/tear-task" > "$tear_out" 2>&1 \ || { echo "FAIL archive in a linked worktree:"; cat "$tear_out"; exit 1; } grep -q 'retain this clean, idle worktree' "$tear_out" || { echo 'FAIL archive did not retain worktree'; cat "$tear_out"; exit 1; } +grep -Fq "reuse-worktree park '2026-09-08-tear' --root " "$tear_out" \ + || { echo 'FAIL archive did not name the managed switch'; cat "$tear_out"; exit 1; } grep -q "git branch -d 'chore/tear-task'" "$tear_out" || { echo 'FAIL archive did not name branch cleanup'; cat "$tear_out"; exit 1; } grep -q 'current remote base' "$tear_out" || { echo 'FAIL archive did not require base ancestry'; cat "$tear_out"; exit 1; } grep -q 'git branch -D\|git worktree remove' "$tear_out" && { echo 'FAIL archive suggested forced cleanup or worktree deletion'; cat "$tear_out"; exit 1; } @@ -1239,8 +1238,8 @@ bash "$HERE/version-baseline" init "$tear" 2026-09-08-tear-base v1 tear_base_out="$tmp/archive-teardown-base-out" bash "$HERE/archive" 2026-09-08-tear-base "$tear" > "$tear_base_out" 2>&1 \ || { echo "FAIL archive from the main working tree:"; cat "$tear_base_out"; exit 1; } -grep -qi 'worktree remove' "$tear_base_out" \ - && { echo "FAIL archive told a main working tree to remove itself"; cat "$tear_base_out"; exit 1; } +grep -Eqi 'worktree remove|reuse-worktree park' "$tear_base_out" \ + && { echo "FAIL archive suggested linked worktree cleanup in the base checkout"; cat "$tear_base_out"; exit 1; } echo "== archive carries clone-local files to the base checkout ==" # `sessions.md` is excluded rather than tracked, so it is not in the commit that diff --git a/hooks/start-worktree b/hooks/start-worktree index 520d348..93b1092 100755 --- a/hooks/start-worktree +++ b/hooks/start-worktree @@ -5,6 +5,7 @@ HERE="$(cd "$(dirname "$0")" && pwd)" source "$HERE/worktree-owner" source "$HERE/worktree-entry" source "$HERE/ledger-lock" +source "$HERE/worktree-archive" [ "$#" -ge 1 ] && [ "$#" -le 2 ] || { echo 'usage: start-worktree / [base-branch]' >&2; exit 2; } new_branch="$1"; base="${2:-main}" slug="${new_branch#*/}" @@ -45,18 +46,10 @@ while IFS= read -r line; do printf 'Skipping %s: ownership %s%s.\n' "$candidate" "$ownership_state" "$reason" >&2 continue fi - old_task="$(git -C "$candidate" log -1 --format= --name-only -- TaskFlowDocs/achieved | - awk -F/ '$1 == "TaskFlowDocs" && $2 == "achieved" && NF > 3 && !seen { print $3; seen=1 }')" - [ -n "$old_task" ] || { printf 'Skipping %s: no committed task archive.\n' "$candidate" >&2; continue; } - branch="$(git -C "$candidate" symbolic-ref --quiet --short HEAD)" || continue - # An archive inherited from another branch cannot identify this tree's task. - if [ "${branch##*/}" != "$old_task" ] && [ "${candidate##*/}" != "$old_task" ]; then - archive_commit="$(git -C "$candidate" log -1 --format=%H -- "TaskFlowDocs/achieved/$old_task")" - reflog="$(git -C "$candidate" reflog show --format='%H %gs' "$branch")" || continue - if ! grep -q "^$archive_commit commit" <<< "$reflog"; then - printf 'Skipping %s: cannot tie archive %s to this worktree.\n' "$candidate" "$old_task" >&2; continue - fi + if ! archive="$(worktree_archive_resolve "$candidate" 2>/dev/null)"; then + printf 'Skipping %s: cannot verify which task was archived in this worktree.\n' "$candidate" >&2; continue fi + old_task="${archive%%|*}" # Status is a discovery hint. The handoff itself verifies under its lock. if bash "$HERE/reuse-worktree" try-start "$old_task" "$new_branch" "$base" "$sha" --root "$candidate"; then printf 'Task workspace: %s\nBranch: %s\nBase: %s %s\n' "$candidate_dir/$slug" "$new_branch" "$base" "$sha" diff --git a/hooks/test-reuse-worktree b/hooks/test-reuse-worktree index a8a2b93..5f5be12 100644 --- a/hooks/test-reuse-worktree +++ b/hooks/test-reuse-worktree @@ -1,5 +1,6 @@ #!/usr/bin/env bash set -euo pipefail +trap 'printf "FAIL worktree reuse fixture at line %s\n" "$LINENO" >&2' ERR [ "$#" -eq 1 ] || exit 2 export TASKFLOW_SESSION_ID=fixture-owner fixture="$1"; [ ! -e "$fixture" ] || exit 2 @@ -17,6 +18,13 @@ printf 'main content\n' > "$repo/main.txt" printf 'tracked in main\n' > "$repo/blocked.txt" git -C "$repo" add .gitignore main.txt git -C "$repo" add -f blocked.txt +inherited=2025-12-31-inherited +mkdir -p "$repo/TaskFlowDocs/achieved/$inherited" +for doc in prd plan; do + printf '# Archive\n> Task version: v1\n> Status: completed\n' > "$repo/TaskFlowDocs/achieved/$inherited/$doc.md" +done +printf '## Inherited\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$inherited" > "$repo/TaskFlowDocs/todo.md" +git -C "$repo" add TaskFlowDocs git -C "$repo" commit -qm initial base="$(git -C "$repo" rev-parse HEAD)" git -C "$repo" worktree add -q -b feature/old "$wt" main @@ -24,7 +32,7 @@ git -C "$wt" rm -q blocked.txt mkdir -p "$wt/TaskFlowDocs/achieved/$task" printf '# PRD\n> Task version: v1\n> Status: completed\n' > "$wt/TaskFlowDocs/achieved/$task/prd.md" printf '# Plan\n> Task version: v1\n> Status: completed\n' > "$wt/TaskFlowDocs/achieved/$task/plan.md" -printf '## Old\n- ID: TF-20260101-aaaaaa\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$task" > "$wt/TaskFlowDocs/todo.md" +printf '## Old\n- ID: TF-20260101-aaaaaa\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$task" >> "$wt/TaskFlowDocs/todo.md" printf 'old branch only\n' > "$wt/old.txt" printf '## Second\n- ID: TF-20260101-bbbbbb\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$task" >> "$wt/TaskFlowDocs/todo.md" git -C "$wt" add TaskFlowDocs old.txt @@ -49,6 +57,34 @@ if bash "$HERE/reuse-worktree" start "$task" feature/new main "$base" --confirme rmdir "$repo/.worktrees/new" if bash "$HERE/reuse-worktree" start 2026-01-02-missing feature/new main "$base" --confirmed-idle --root "$wt" > "$fixture/missing-out" 2>&1; then echo 'FAIL unarchived task reused'; exit 1; fi [ "$(git -C "$wt" rev-parse HEAD)" = "$old" ] || exit 1 +if bash "$HERE/reuse-worktree" start "$inherited" feature/wrong-archive main "$base" --confirmed-idle --root "$wt" > "$fixture/wrong-archive" 2>&1; then + echo 'FAIL inherited archive accepted as the worktree task'; exit 1 +fi +[ "$(git -C "$wt" rev-parse HEAD)" = "$old" ] +[ "$(cat "$gitdir/taskflow/evidence")" = 'old evidence' ] +[ ! -e "$gitdir/taskflow/handoff.pending" ] +[ ! -e "$gitdir/taskflow/handoff-history/$inherited" ] +# A caller reading Git's worktree list can have its own field separator. +archive="$(IFS=; source "$HERE/worktree-archive"; worktree_archive_resolve "$wt")" +[[ "$archive" = "$task|$old|feature/old" ]] || + { echo 'FAIL archive lookup changed with the caller field separator'; exit 1; } +diagnosis="$(bash "$HERE/repository-check" "$repo" || true)" +if ! grep -Fq "archive $task (" <<< "$diagnosis"; then + echo 'FAIL diagnostic did not identify the worktree archive' + printf '%s\n' "$diagnosis" + bash -x -c 'HERE=$1; source "$HERE/worktree-archive"; worktree_archive_resolve "$2"' _ "$HERE" "$wt" || true + exit 1 +fi +if grep -Fq "archive $inherited (" <<< "$diagnosis"; then + echo 'FAIL diagnostic associated inherited archive with the worktree'; exit 1 +fi +owner() { bash "$HERE/worktree-owner" "$@" --root "$wt"; } +owner claim --confirmed-idle +owner release +if bash "$HERE/reuse-worktree" park "$task" main --root "$wt" > "$fixture/unmerged-park" 2>&1; then + echo 'FAIL park allowed cleanup of an unmerged branch'; exit 1 +fi +grep -Fq 'not contained in the verified base' "$fixture/unmerged-park" printf 'ignored user data\n' > "$wt/blocked.txt" if bash "$HERE/reuse-worktree" start "$task" feature/new main "$base" --confirmed-idle --root "$wt" > "$fixture/collision-out" 2>&1; then echo 'FAIL ignored collision overwritten'; exit 1; fi [ "$(cat "$wt/blocked.txt")" = 'ignored user data' ] || { echo 'FAIL ignored collision lost'; exit 1; } @@ -57,10 +93,19 @@ if bash "$HERE/task" approve "$task" --root "$wt" > "$fixture/pending-out" 2>&1; grep -q 'handoff' "$fixture/pending-out" || { cat "$fixture/pending-out"; exit 1; } # Older handoff records predate directory moves and contain no path fields. rm "$gitdir/taskflow/handoff.pending/old-root" "$gitdir/taskflow/handoff.pending/target-root" +cp "$gitdir/taskflow/ownership" "$fixture/original-ownership" +awk '/^=end$/ {print "new-holder"} {print}' "$fixture/original-ownership" > "$gitdir/taskflow/ownership" +if bash "$HERE/reuse-worktree" recover --confirmed-idle --root "$wt" > "$fixture/recover-owner-changed" 2>&1; then + echo 'FAIL recovery dropped an unexpected owner'; exit 1 +fi +grep -Fxq 'new-holder' "$gitdir/taskflow/ownership" +[ -d "$gitdir/taskflow/handoff.pending" ] +cp "$fixture/original-ownership" "$gitdir/taskflow/ownership" bash "$HERE/reuse-worktree" recover --confirmed-idle --root "$wt" > "$fixture/recover-out" [ "$(git -C "$wt" symbolic-ref --short HEAD)" = feature/old ] || { echo 'FAIL recovery branch'; exit 1; } [ "$(cat "$gitdir/taskflow/evidence")" = 'old evidence' ] || { echo 'FAIL recovery ledger'; exit 1; } [ ! -e "$gitdir/taskflow/handoff.pending" ] || { echo 'FAIL recovery journal not closed'; exit 1; } +[[ "$(owner status)" = 'released '* ]] || { echo 'FAIL original trusted release was lost on rollback'; exit 1; } rm "$wt/blocked.txt" # Simulate Git reporting an error immediately after each checkout boundary. mkdir -p "$fixture/bin" @@ -93,6 +138,7 @@ chmod +x "$fixture/bin/mv" if PATH="$fixture/bin:$PATH" REAL_GIT="$real_git" REAL_MV="$real_mv" FAIL_BOUNDARY=prepare bash "$HERE/reuse-worktree" start "$task" feature/fault-prepare main "$base" --confirmed-idle --root "$wt" > "$fixture/fault-prepare" 2>&1; then echo 'FAIL prepare fault not injected'; exit 1; fi [ ! -e "$gitdir/taskflow/handoff.pending" ] && [ "$(cat "$gitdir/taskflow/evidence")" = 'old evidence' ] && [ "$(git -C "$wt" symbolic-ref --short HEAD)" = feature/old ] || { echo 'FAIL prepare fault changed original state'; exit 1; } for boundary in save detach switch move-before move-after; do + if [ "$boundary" = save ]; then mv "$gitdir/taskflow/ownership" "$fixture/release-before-save"; fi if PATH="$fixture/bin:$PATH" REAL_GIT="$real_git" REAL_MV="$real_mv" FAIL_BOUNDARY="$boundary" bash "$HERE/reuse-worktree" start "$task" "feature/fault-$boundary" main "$base" --confirmed-idle --root "$wt" > "$fixture/fault-$boundary" 2>&1; then echo "FAIL $boundary fault not injected"; exit 1; fi [ -d "$gitdir/taskflow/handoff.pending" ] || { echo "FAIL $boundary journal missing"; exit 1; } recovery_root="$wt" @@ -106,10 +152,14 @@ for boundary in save detach switch move-before move-after; do bash "$HERE/reuse-worktree" recover --confirmed-idle --root "$recovery_root" > "$fixture/recover-$boundary" [ "$(git -C "$wt" symbolic-ref --short HEAD)" = feature/old ] || { echo "FAIL $boundary recovery branch"; exit 1; } [ "$(cat "$gitdir/taskflow/evidence")" = 'old evidence' ] || { echo "FAIL $boundary recovery evidence"; exit 1; } + if [ "$boundary" = save ]; then + [[ "$(owner status)" = 'unknown '* ]] || { echo 'FAIL recovery inferred release without a record'; exit 1; } + owner claim --confirmed-idle + owner release + fi [ "$(git -C "$repo" rev-parse main)" = "$base" ] && [ "$(git -C "$repo" rev-parse feature/old)" = "$old" ] || { echo "FAIL $boundary changed old refs"; exit 1; } done # Ownership and base failures must precede any new branch, archive journal or plan. -owner() { bash "$HERE/worktree-owner" "$@" --root "$wt"; } owner claim --confirmed-idle TASKFLOW_SESSION_ID=peer owner claim owner release @@ -155,7 +205,7 @@ next_task=2026-01-02-next mkdir -p "$wt/TaskFlowDocs/achieved/$next_task" printf '# PRD\n> Task version: v1\n> Status: completed\n' > "$wt/TaskFlowDocs/achieved/$next_task/prd.md" printf '# Plan\n> Task version: v1\n> Status: completed\n' > "$wt/TaskFlowDocs/achieved/$next_task/plan.md" -printf '## Next\n- ID: TF-20260102-bbbbbb\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$next_task" > "$wt/TaskFlowDocs/todo.md" +printf '## Next\n- ID: TF-20260102-bbbbbb\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$next_task" >> "$wt/TaskFlowDocs/todo.md" git -C "$wt" add TaskFlowDocs printf 'new task edit\n' > "$wt/main.txt" git -C "$wt" add main.txt @@ -181,7 +231,17 @@ chmod +x "$fixture/bin/cp" if PATH="$fixture/bin:$PATH" REAL_GIT="$real_git" REAL_MV="$real_mv" REAL_CP="$real_cp" FAIL_BOUNDARY=restore bash "$HERE/reuse-worktree" resume "$next_task" "$task" feature/old "$snapshot_id" --confirmed-idle --root "$wt" > "$fixture/fault-restore" 2>&1; then echo 'FAIL restore fault not injected'; exit 1; fi bash "$HERE/reuse-worktree" recover --confirmed-idle --root "$wt" > "$fixture/recover-restore" [ "$(git -C "$wt" symbolic-ref --short HEAD)" = feature/new ] && [ "$(cat "$gitdir/taskflow/evidence")" = 'next evidence' ] || { echo 'FAIL restore fault recovery'; exit 1; } -bash "$HERE/reuse-worktree" resume "$next_task" "$task" feature/old "$snapshot_id" --confirmed-idle --root "$wt" > "$fixture/resume-out" +git -C "$repo" merge --no-ff --no-edit feature/old +git -C "$repo" branch -d feature/old +git -C "$repo" branch feature/old main +if bash "$HERE/reuse-worktree" resume "$next_task" "$task" feature/old "$snapshot_id" --root "$wt" > "$fixture/conflict-resume" 2>&1; then + echo 'FAIL conflicting existing branch was accepted'; exit 1 +fi +grep -q 'differs from its snapshot commit' "$fixture/conflict-resume" +[ "$(git -C "$wt" rev-parse HEAD)" = "$new_tip" ] +[ "$(cat "$gitdir/taskflow/evidence")" = 'next evidence' ] +git -C "$repo" branch -d feature/old +bash "$HERE/reuse-worktree" resume "$next_task" "$task" feature/old "$snapshot_id" --root "$wt" > "$fixture/resume-out" wt="$repo/.worktrees/old" [ -d "$wt" ] && [ ! -e "$repo/.worktrees/new" ] || { echo 'FAIL resumed worktree not renamed'; exit 1; } [ "$(git -C "$wt" symbolic-ref --short HEAD)" = feature/old ] || { echo 'FAIL original branch not restored'; exit 1; } @@ -204,6 +264,17 @@ mkdir "$previous" rmdir "$previous" [[ "$(owner status)" = 'released '* ]] || { echo 'FAIL same-worktree move lost trusted release'; exit 1; } [ "$(git -C "$wt" hash-object --no-filters "$gitdir/taskflow/ownership")" = "$receipt_before" ] +TASKFLOW_SESSION_ID=peer owner claim +if bash "$HERE/reuse-worktree" park "$task" main --root "$wt" > "$fixture/park-held" 2>&1; then + echo 'FAIL parking while another session holds the worktree'; exit 1 +fi +TASKFLOW_SESSION_ID=peer owner release +bash "$HERE/reuse-worktree" park "$task" main --root "$wt" +[[ "$(owner status)" = 'released '* ]] || { echo 'FAIL parked release'; exit 1; } +if git -C "$wt" symbolic-ref --quiet HEAD; then echo 'FAIL parked worktree is still attached'; exit 1; fi +[ "$(git -C "$wt" rev-parse HEAD)" = "$old" ] +git -C "$repo" branch -d feature/old +[ "$(git -C "$repo" rev-parse "refs/archive/taskflow/commits/$old")" = "$old" ] (cd "$repo" && bash "$HERE/task-workspace" start feature/automatic main) > "$fixture/auto" grep -q 'Handoff start:' "$fixture/auto" automatic="$repo/.worktree/automatic" @@ -212,4 +283,75 @@ grep -Fq "Task workspace: $(git -C "$repo" rev-parse --show-toplevel)/.worktree/ [ "$(git -C "$automatic" rev-parse --absolute-git-dir)" = "$gitdir" ] wt="$automatic" [[ "$(owner status)" = 'occupied '*session=fixture-owner ]] +[ "$(git -C "$wt" rev-parse HEAD)" = "$(git -C "$repo" rev-parse main)" ] +# Model a previously released detached archive whose only branch-independent +# ref is the existing local archive ref and whose commit is outside main. +local_task=2026-01-03-local +mkdir -p "$wt/TaskFlowDocs/achieved/$local_task" +for doc in prd plan; do + printf '# Local archive\n> Task version: v1\n> Status: completed\n' > "$wt/TaskFlowDocs/achieved/$local_task/$doc.md" +done +printf '## Local archive\n- Status: done\n- Task: `TaskFlowDocs/achieved/%s/`\n' "$local_task" >> "$wt/TaskFlowDocs/todo.md" +printf 'local branch only\n' > "$wt/local-only.txt" +git -C "$wt" add TaskFlowDocs local-only.txt +git -C "$wt" commit -qm 'archive local task' +local_sha="$(git -C "$wt" rev-parse HEAD)" +local_ref=refs/archive/taskflow/local-task-20260103 +git -C "$wt" update-ref "$local_ref" "$local_sha" +owner release +git -C "$wt" checkout --detach "$local_sha" +git -C "$repo" update-ref -d refs/heads/feature/automatic "$local_sha" +if git -C "$repo" merge-base --is-ancestor "$local_sha" main; then echo 'FAIL local archive unexpectedly merged'; exit 1; fi +owner claim --confirmed-idle +owner release +printf 'local evidence\n' > "$gitdir/taskflow/evidence" +(cd "$repo" && bash "$HERE/task-workspace" start feature/reuse-local main) > "$fixture/auto-local" +grep -q 'Handoff start:' "$fixture/auto-local" +wt="$repo/.worktree/reuse-local" +[ "$(git -C "$wt" rev-parse --absolute-git-dir)" = "$gitdir" ] +[ "$(git -C "$wt" rev-parse HEAD)" = "$(git -C "$repo" rev-parse main)" ] +[ ! -e "$wt/local-only.txt" ] +[ "$(git -C "$repo" rev-parse "$local_ref")" = "$local_sha" ] +saved_local="$(find "$gitdir/taskflow/handoff-history/$local_task" -name evidence -type f)" +[ "$(cat "$saved_local")" = 'local evidence' ] + +# Use the ordinary archive command, then expire reflogs to prove the +# committed association is sufficient for a later handoff. +managed_task=2026-01-04-managed +managed_docs="$wt/TaskFlowDocs/$managed_task" +mkdir -p "$managed_docs" +printf '# PRD\n> Task version: v1\n> Status: completed\n' > "$managed_docs/prd.md" +cat > "$managed_docs/plan.md" <<'EOF' +# Plan +> Task version: v1 +> Status: completed + +## Approval +- Status: approved +- Approved by: fixture +- Approved at: 2026-01-04 00:00 +0000 +- Approved version: v1 +- Approved scope: PRD / Plan + +## Steps + +### Step 1 — Verify +- Status: done +EOF +printf '## Managed archive\n- ID: TF-20260104-cccccc\n- Status: in_progress\n- Task: \x60TaskFlowDocs/%s/\x60\n' "$managed_task" >> "$wt/TaskFlowDocs/todo.md" +bash "$HERE/version-baseline" init "$wt" "$managed_task" v1 +bash "$HERE/archive" "$managed_task" "$wt" +test -f "$gitdir/taskflow/archived-worktree" +owner release +if bash "$HERE/reuse-worktree" start "$managed_task" feature/managed-next main auto --root "$wt" > "$fixture/uncommitted-managed" 2>&1; then + echo 'FAIL an uncommitted archive became eligible'; exit 1 +fi +owner claim +git -C "$wt" add TaskFlowDocs +git -C "$wt" commit -qm 'commit managed archive' +owner release +git -C "$wt" reflog expire --expire=all HEAD refs/heads/feature/reuse-local +(cd "$repo" && bash "$HERE/task-workspace" start feature/managed-next main) > "$fixture/managed-next" +grep -q 'Handoff start:' "$fixture/managed-next" +[ "$(git -C "$repo/.worktree/managed-next" rev-parse --absolute-git-dir)" = "$gitdir" ] echo 'PASS archived worktree reuse preserves Git and evidence' diff --git a/hooks/test-worktree-candidates b/hooks/test-worktree-candidates index 94527f6..f10d7ff 100644 --- a/hooks/test-worktree-candidates +++ b/hooks/test-worktree-candidates @@ -18,11 +18,11 @@ printf '# Plan\n> Status: completed\n' > "$fixture/archived/TaskFlowDocs/achieve git -C "$fixture/archived" add . git -C "$fixture/archived" commit -qm archive out="$(bash "$HERE/repository-check" "$repo" 2>&1 || true)" -printf '%s\n' "$out" | grep -q 'recent archive 2026-01-01-demo (clean; idle unknown)' || { echo 'FAIL unmerged archive missing'; exit 1; } +printf '%s\n' "$out" | grep -q 'archive 2026-01-01-demo (clean; idle unknown)' || { echo 'FAIL unmerged archive missing'; exit 1; } printf '%s\n' "$out" | grep -q 'Prefer released worktrees' || { echo 'FAIL missing idle warning'; exit 1; } echo dirty > "$fixture/archived/untracked" out="$(bash "$HERE/repository-check" "$repo" 2>&1 || true)" -printf '%s\n' "$out" | grep -q 'recent archive 2026-01-01-demo (changes present)' || { echo 'FAIL dirty candidate'; exit 1; } +printf '%s\n' "$out" | grep -q 'archive 2026-01-01-demo (changes present)' || { echo 'FAIL dirty candidate'; exit 1; } # WSL Git can interpret a Windows absolute gitdir as a relative path. mkdir -p "$fixture/fakebin" REAL_GIT="$(command -v git)"; export REAL_GIT diff --git a/hooks/worktree-archive b/hooks/worktree-archive new file mode 100644 index 0000000..d627d45 --- /dev/null +++ b/hooks/worktree-archive @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# The worktree ledger records the task that archived here, independently of HEAD. +worktree_archive_read() { + local file="$1/taskflow/archived-worktree" extra + [ -f "$file" ] && [ ! -L "$file" ] && [ ! -L "$1/taskflow" ] || return 1 + { + IFS= read -r archive_task && IFS= read -r archive_branch && + IFS= read -r archive_sha && IFS= read -r archive_mode && + ! IFS= read -r extra && [ -z "$extra" ] + } < "$file" || return 1 + bash "$(dirname "${BASH_SOURCE[0]}")/task-id" "$archive_task" >/dev/null 2>&1 && + git check-ref-format "refs/heads/$archive_branch" && + [[ "$archive_sha" =~ ^[0-9a-f]{40,64}$ ]] +} + +worktree_archive_write() { + local file="$1/taskflow/archived-worktree" tmp + [ ! -L "$file" ] && { [ ! -e "$file" ] || [ -f "$file" ]; } || return 1 + tmp="$(mktemp "$1/taskflow/archive.XXXXXXXX")" || return 1 + printf '%s\n' "$2" "$3" "$4" "$5" > "$tmp" && mv -f "$tmp" "$file" || + { rm -f "$tmp"; return 1; } +} + +worktree_archive_retained() { + local refs + refs="$(git -C "$1" for-each-ref --points-at "$2" --format='%(refname) %(symref)' refs/archive/taskflow)" || return 1 + awk 'NF == 1 {found=1} END {exit !found}' <<< "$refs" +} + +worktree_archive_protect() { + worktree_archive_retained "$1" "$2" || + git -C "$1" update-ref --no-deref "refs/archive/taskflow/commits/$2" "$2" '' || + worktree_archive_retained "$1" "$2" +} + +worktree_archive_park_matches() { + local archive_task archive_branch archive_sha archive_mode + worktree_archive_read "$1" && [ "$archive_mode" = parked ] && + [ "refs/heads/$archive_branch" = "$2" ] && [ "$archive_sha" = "$3" ] +} + +worktree_archive_resolve() { + local tree="$1" dir current tip archive_task archive_branch archive_sha archive_mode path + dir="$(git -C "$tree" rev-parse --absolute-git-dir)" || return 1 + tip="$(git -C "$tree" rev-parse --verify 'HEAD^{commit}')" || return 1 + current="$(git -C "$tree" symbolic-ref --quiet HEAD)" || current=@detached + current="${current#refs/heads/}" + if [ -e "$dir/taskflow/archived-worktree" ] || [ -L "$dir/taskflow/archived-worktree" ]; then + worktree_archive_read "$dir" || return 1 + case "$archive_mode" in + pending) + [ "$current" = "$archive_branch" ] && + git -C "$tree" merge-base --is-ancestor "$archive_sha" "$tip" || return 1 + path="TaskFlowDocs/achieved/$archive_task/plan.md" + # The archive must have been committed after its worktree association. + [ "$(git -C "$tree" log -1 --format=%H --diff-filter=A --no-renames "$archive_sha..$tip" -- "$path")" != '' ] || return 1 + archive_sha="$tip" + ;; + parked|attached) + [ "$tip" = "$archive_sha" ] || return 1 + [ "$current" = "$archive_branch" ] || { [ "$current" = @detached ] && [ "$archive_mode" = parked ]; } || return 1 + ;; + *) return 1 ;; + esac + else + local commits branch_commits reflog transition previous introduced matches archive_commit candidate + reflog="$(git -C "$tree" reflog show --format='%H %gs' HEAD)" || return 1 + commits="$(awk '$2 == "commit:" || $2 == "commit" && $3 == "(initial):" {print $1}' <<< "$reflog")" + archive_branch="$current" + if [ "$current" = @detached ]; then + # Older detached archives can be identified only with a surviving exact + # archive ref and this worktree's recorded checkout from the old branch. + worktree_archive_retained "$tree" "$tip" || return 1 + transition="$(sed -n '1p' <<< "$reflog")" + previous="$(sed -n '2p' <<< "$reflog")" + [[ "$transition" = "$tip checkout: moving from "* && "$previous" = "$tip "* ]] || return 1 + archive_branch="${transition#"$tip checkout: moving from "}" + archive_branch="${archive_branch% to *}" + git check-ref-format "refs/heads/$archive_branch" || return 1 + else + branch_commits="$(git -C "$tree" reflog show --format='%H %gs' "refs/heads/$current")" || return 1 + commits="$(printf '%s\n--\n%s\n' "$commits" "$branch_commits" | awk ' + $0 == "--" {branch=1; next} + !branch {seen[$1]; next} + $2 == "commit:" && ($1 in seen) {print $1} + ')" || return 1 + fi + [ -n "$commits" ] || return 1 + introduced="$(git -C "$tree" log --format='commit %H' --name-only --no-renames --diff-filter=A "$tip" -- TaskFlowDocs/achieved)" || return 1 + matches="$(printf '%s\n--\n%s\n' "$commits" "$introduced" | awk -F/ ' + $0 == "--" {history=1; next} + !history {owned[$0]; next} + /^commit / {commit=substr($0, 8); next} + (commit in owned) && NF == 4 && $1 == "TaskFlowDocs" && $2 == "achieved" && $4 == "plan.md" { + print commit, $3 + } + ')" || return 1 + archive_task='' archive_commit='' + while IFS=' ' read -r candidate path; do + bash "$HERE/task-id" "$path" >/dev/null 2>&1 || continue + if [ -n "$archive_task" ]; then + [ "$candidate" != "$archive_commit" ] && break + [ "$path" = "$archive_task" ] || return 1 + fi + archive_task="$path" archive_commit="$candidate" + done <<< "$matches" + [ -n "$archive_task" ] || return 1 + archive_sha="$tip" + fi + git -C "$tree" cat-file -e "$archive_sha:TaskFlowDocs/achieved/$archive_task/plan.md" 2>/dev/null || return 1 + printf '%s|%s|%s\n' "$archive_task" "$archive_sha" "$archive_branch" +} diff --git a/hooks/worktree-owner b/hooks/worktree-owner index e5ca886..c38efa2 100755 --- a/hooks/worktree-owner +++ b/hooks/worktree-owner @@ -1,5 +1,6 @@ #!/usr/bin/env bash # Sourced by reuse-worktree while it holds the same per-worktree ledger lock. +source "$(dirname "${BASH_SOURCE[0]}")/worktree-archive" owner_fail() { printf 'TaskFlow ownership: %s\n' "$*" >&2; return 1; } owner_identity() { owner_id="${TASKFLOW_SESSION_ID:-${CODEX_THREAD_ID:-${CLAUDE_CODE_SESSION_ID:-}}}" @@ -32,7 +33,12 @@ owner_load() { } < "$receipt" [ "$observed" = "$(git -C "$root" hash-object --no-filters "$receipt")" ] || return 1 owner_reason='' - if [ "$saved_dir" != "$gitdir" ] || [ "$saved_branch" != "$branch" ]; then + if [ "$saved_dir" = "$gitdir" ] && [ "$saved_root" = "$root" ] && + [ "$branch" = @detached ] && [ "$saved_head" = "$head" ] && + [ "$trusted" = yes ] && [ -z "${members[*]-}" ] && + worktree_archive_park_matches "$gitdir" "$saved_branch" "$head"; then + state=released + elif [ "$saved_dir" != "$gitdir" ] || [ "$saved_branch" != "$branch" ]; then state=stale; trusted=no; owner_reason=worktree-identity-changed elif [ "$saved_root" != "$root" ]; then # A Git move can preserve an existing release, but cannot establish one. diff --git a/skills/taskflow/SKILL.md b/skills/taskflow/SKILL.md index f120af7..a20de2f 100644 --- a/skills/taskflow/SKILL.md +++ b/skills/taskflow/SKILL.md @@ -445,15 +445,15 @@ Treat achieved tasks as read-only in place. A later request that belongs to one After completion, promote only verified, cross-task rules into the project's shared specification/guides. Leave task-specific decisions, personal preferences, unverified ideas, and temporary workarounds in the task artifacts. -**Keep or remove the working tree independently of its branch.** Once a task is archived and the archive committed, an idle linked worktree may be kept for a later task. Reuse it only through the explicit handoff, once the last participating session has released it with `bash /worktree-owner release --root `. A clean Git status alone cannot establish availability. The handoff checks the committed archive, ordinary and ignored files, submodules, hidden index flags, base and branch identity, and protects ignored files from checkout overwrite. It preserves the old task's capability and external-evidence ledgers separately from the next task, retains version baselines, and stops with a recovery record if interrupted. Never reset the old branch or create a new task from its tip: verify the current base, detach at that exact base commit, then create the new branch at the same commit. If the old task is unmerged, its branch stays available; its changes are not implicitly part of the new task. +**Keep or remove the working tree independently of its branch.** Once a task is archived and the archive committed, an idle linked worktree may be kept for a later task. Reuse it only through the explicit handoff, once the last participating session has released it with `bash /worktree-owner release --root `. A clean Git status alone cannot establish availability. Automatic discovery and explicit handoff verify that the committed archive belongs to this worktree. A legacy detached archive can qualify through an exact local archive ref, this checkout's Git history and a trusted idle record. The handoff also checks ordinary and ignored files, submodules, hidden index flags, base and branch identity, and protects ignored files from checkout overwrite. It preserves the old task's capability and external-evidence ledgers separately from the next task, retains version baselines, and stops with a recovery record if interrupted. Never reset the old branch or create a new task from its tip: verify the current base, detach at that exact base commit, then create the new branch at the same commit. The old archive remains reachable through a local Git ref. A new task starts from the verified base even when the archive commit is outside that base's history. -Run `bash /reuse-worktree start auto --root ` from outside the worktree. The handoff checks the selected remote base and claims the released tree under the ledger lock. Start and resume move the worktree to a sibling directory named for the branch's task slug (`feature/example` becomes `example`); an occupied target stops the handoff. Use the printed path after success. A pending handoff blocks TaskFlow writes; inspect `git worktree list` and use `bash /reuse-worktree recover --confirmed-idle --root ` to restore the old task and path. Save the printed snapshot ID; to return to an old task after archiving and committing the current one, run `bash /reuse-worktree resume --root `. Do not switch tasks with ordinary Git commands: the per-worktree evidence would otherwise remain attached to the wrong task. Submodules and nonstandard linked Git layouts are currently refused. If a process was killed leaving `.ledger-lock`, verify no writer is running before removing the stale lock. A killed task transaction may leave a writer token inside it; inspect that directory and remove only the verified abandoned token before removing the empty lock directory; preserve handoff journals and snapshots. +Run `bash /reuse-worktree start auto --root ` from outside the worktree. The handoff checks the selected remote base and claims the released tree under the ledger lock. Start and resume move the worktree to a sibling directory named for the branch's task slug (`feature/example` becomes `example`); an occupied target stops the handoff. Use the printed path after success. A pending handoff blocks TaskFlow writes; inspect `git worktree list` and use `bash /reuse-worktree recover --confirmed-idle --root ` to restore the old task and path. Save the printed snapshot ID; to return to an old task after archiving and committing the current one, run `bash /reuse-worktree resume --root `. Resume recreates a missing original branch from the verified snapshot commit and refuses an existing branch at another commit. A verified rollback restores an existing trusted release when it can verify the original checkout and ownership record. Use the TaskFlow handoff to keep the per-worktree evidence attached to the right task. Submodules and nonstandard linked Git layouts are currently refused. If a process was killed leaving `.ledger-lock`, verify no writer is running before removing the stale lock. A killed task transaction may leave a writer token inside it; inspect that directory and remove only the verified abandoned token before removing the empty lock directory; preserve handoff journals and snapshots. Use `worktree-owner status --root ` to inspect holders and the reason for an unknown or stale record. A Git-only move preserves a trusted release if the registered location is the only change, the previous location is gone, and no session is recorded. Choose another tree if any session remains. If reuse is necessary and a holder forgot to release, verify that particular session has stopped, then use `worktree-owner forget --session --observed --confirmed-idle --root `. A resumed session or other membership change invalidates the token. Repeat the inspection for each abandoned holder. Missing or stale releases require independent idle confirmation before adding `--confirmed-idle` to start/resume. Old trees first observed with no trusted baseline stay unknown after the last known session leaves. Locks, dirty files, pending handoffs and active holders still block reuse. Ownership covers participating sessions. Check any known external writer separately. -If branch cleanup is needed before another task starts, after confirming the archive is committed and merged, the worktree is idle and clean including untracked files, the index hides no changes, and submodules are safe, check out the verified base commit in detached HEAD using `git checkout --no-overwrite-ignore --detach `. Keep the old task ledger in place and do not start another task by hand; the later `start` handoff snapshots it. If the checkout refuses, preserve the files and branch for inspection. +To prepare an archived worktree for local branch cleanup before reuse, commit the archive, let every session release, and run `bash /reuse-worktree park --root `. Under the worktree lock, `park` checks archive ownership, idle state and containment in the verified base. It retains the old evidence, keeps the archive commit reachable, and detaches at the archive commit while preserving the release. -A completed, merged task's local branch still needs its own cleanup. First establish that the remote-tracking base is sufficiently fresh and verify containment with `git merge-base --is-ancestor `; also confirm no writer is using its worktree. Safely switch the retained worktree away from the old branch through the handoff, then, with the user's existing deletion authorization, use `git branch -d ` and verify the result. Do not infer containment solely from `-d`, which can check the branch's upstream rather than the intended base. If ancestry cannot be established (including a squash or rebase) or Git refuses deletion, keep the branch and report it; never force deletion. Do not ask again for authorization already given. The worktree can remain in place for reuse regardless of whether its former branch can be removed. +A completed, merged task's local branch still needs its own cleanup. Use the verified containment and checkout from `park`, or establish the same facts after a completed reuse handoff. With the user's existing deletion authorization, use `git branch -d ` and verify the result. Do not infer containment solely from `-d`, which can check the branch's upstream rather than the intended base. If ancestry cannot be established (including a squash or rebase) or Git refuses deletion, keep the branch and report it; never force deletion. Do not ask again for authorization already given. The worktree can remain in place for reuse regardless of whether its former branch can be removed. Removing the worktree is an alternative only when authorized: verify the remote base, working tree, untracked and ignored data and any retained task records first, then `git worktree remove ` and clean up a verified merged branch with `git branch -d `. Never force removal. `hooks/repository-check` reports candidates and uncertainty; it neither deletes nor proves that a worktree is safe to reuse. diff --git a/skills/taskflow/references/runtime.md b/skills/taskflow/references/runtime.md index aa1182c..6e6409e 100644 --- a/skills/taskflow/references/runtime.md +++ b/skills/taskflow/references/runtime.md @@ -398,6 +398,7 @@ repo-root/ ├── task-workspace # resolve confirmed Todo identity and workspace ├── start-worktree # reuse an eligible archive or create the workspace ├── worktree-owner # per-session membership, release and checked takeover + ├── worktree-archive # shared archive association and local commit retention ├── worktree-entry # reclaim before writing; verify external branch ancestry before planning ├── test-worktree-ownership # session and remote-base integration fixtures ├── test-write-entry # resumed writers and external first planning @@ -524,4 +525,4 @@ A write timeout can mean success or failure. Inspect the recorded operation befo ### Archived worktree handoff -`reuse-worktree start` verifies a committed archive and snapshots the current worktree's evidence before detaching at a verified base commit and creating a new branch there. Start and resume move the worktree to a sibling named after the target branch's task slug, refusing an occupied destination. Run them from outside the worktree; use the printed path afterwards. `resume` restores a retained task snapshot; `recover` restores the original state and path after an interrupted handoff, using the existing path reported by `git worktree list`. Both new-branch entry points verify the selected base against its live upstream before any plan documents. Every participating session claims on SessionStart or explicitly. The final release binds the checkout, branch and HEAD. The next TaskFlow write registers its writer under the handoff lock. For host edits the event session ID takes precedence. A new external task verifies its base before promotion or explicitly via `worktree-entry verify `; the observable edit gate checks this receipt offline. Inspect or retire a confirmed abandoned holder with `worktree-owner`; see the skill for the observed-token procedure. Evidence hooks skip events rather than wait on the shared ledger lock; task commands and the document gate refuse work while it is held or a handoff is pending. Abrupt termination can leave the lock directory or its short-lived sibling reservation `.ledger-lock.creating`. Confirm no writer or handoff is active before removing a stranded reservation; ordinary Git checkout does not transfer evidence. Version baselines remain in place. Submodules and nonstandard Git metadata layouts require manual isolation. See the skill for commands and authorized cleanup. +`start-worktree`, `repository-check` and `reuse-worktree` read the same worktree archive association. `reuse-worktree start` rechecks it under the ledger lock, protects the old archive commit with a local Git ref and snapshots the worktree's evidence. It then detaches at the independently verified base and creates the new branch there. Start and resume move the worktree to a sibling named after the target branch's task slug, refusing an occupied destination. Run them from outside the worktree; use the printed path afterwards. `park` verifies that the archive is contained in the checked base, detaches at the archive commit and keeps the trusted release for separately authorized branch cleanup. `resume` restores a retained task snapshot and recreates a missing original branch from its commit. `recover` restores the original state and path after an interrupted handoff, using the existing path reported by `git worktree list`. A trusted release is restored only when its original checkout and ownership proof still match. Both new-branch entry points verify the selected base against its live upstream before any plan documents. Every participating session claims on SessionStart or explicitly. The final release binds the checkout, branch and HEAD. The next TaskFlow write registers its writer under the handoff lock. For host edits the event session ID takes precedence. A new external task verifies its base before promotion or explicitly via `worktree-entry verify `; the observable edit gate checks this receipt offline. Inspect or retire a confirmed abandoned holder with `worktree-owner`; see the skill for the observed-token procedure. Evidence hooks skip events rather than wait on the shared ledger lock; task commands and the document gate refuse work while it is held or a handoff is pending. Abrupt termination can leave the lock directory or its short-lived sibling reservation `.ledger-lock.creating`. Confirm no writer or handoff is active before removing a stranded reservation; ordinary Git checkout does not transfer evidence. Version baselines remain in place. Submodules and nonstandard Git metadata layouts require manual isolation. See the skill for commands and authorized cleanup.