From 5813ed716550a317ea2a89b7aae6b2c8994f8fe5 Mon Sep 17 00:00:00 2001 From: DandreYang <13072547+Dandre126@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:45:08 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E7=BA=BF):=20=E9=80=80=E5=BD=B9=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E8=A2=AB=E5=A4=B1=E8=B4=A5=E4=BB=BB=E5=8A=A1=E4=B8=8E?= =?UTF-8?q?=E5=AD=90=E7=BA=BF=E5=8D=A1=E4=BD=8F=EF=BC=8C=E5=B9=B6=E8=83=BD?= =?UTF-8?q?=E5=AD=98=E6=A1=A3=E8=84=8F=E6=94=B9=E5=8A=A8=E4=B8=8E=E7=BA=BF?= =?UTF-8?q?=E6=A0=B9=E8=B5=84=E6=96=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增任务终态 abandoned 与 `dyro task abandon --reason`;retire 与退役后读取把 done/abandoned 都视为已结束;start 菜单隐藏 abandoned 与已 close 的任务 - 新增 `dyro line reparent <线> --parent X | --detach`,只改清单 parent,写 reparent 事件 - retire 集成判断依次检查父线、命名基线、default_base、origin/main|master|release;钉死的基线 SHA 不再作目标;未集成提示写明 HEAD 与 origin 跟踪 ref 状态 - retire 新增 `--archive-to`:先存档各仓未提交改动(plumbing 补丁、反向应用核对、.partial 原子落盘)与线根非仓库条目,退役后删除只剩生成说明与空目录的线根 - task close 关闭 failed/abandoned 任务时,脏 worktree 需 `--archive-to`,未合入分支 tip 先保全到 refs/dyro/closed/ - 本线仍有任务 worktree 时拒绝退役;Objective 中的 abandoned 任务按 failed 提示人工处理 --- CHANGELOG.md | 11 + .../line-lifecycle-and-cross-line-merge.md | 2 +- src/dyro/cli.py | 58 +++- src/dyro/continuation/planner.py | 5 +- src/dyro/events.py | 1 + src/dyro/home.py | 7 +- src/dyro/line_retire.py | 268 ++++++++++++++++-- src/dyro/tasks.py | 77 ++++- src/dyro/workspace.py | 36 +++ tests/test_line_retire.py | 109 +++++++ tests/test_review_remediation.py | 32 +++ 11 files changed, 560 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 616b85f..5579e13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## Unreleased + +对使用者的影响:失败或不再继续的任务不再永久挡住开发线退役;子线可以改挂父线;退役能自动存档脏改动和线根目录资料,并删掉退役后的空目录。**行为变化**:`dyro task close` 关闭 failed 任务时,worktree 有未提交改动会被拒绝(之前直接丢弃),需要加 `--archive-to <目录>`。新增的任务状态 `abandoned` 写入后,旧版客户端读到会报状态非法,同一工作区的客户端需要一起升级。 + +- 新增任务终态 `abandoned` 与 `dyro task abandon --reason <原因>`:只能从 failed 或 backlog 进入,原因写入 ledger;`dyro task status abandoned` 会被拒绝,以免漏记原因。abandoned 和 done 一样不再阻止 `line retire`,线退役后这些任务仍可读取;`dyro start` 菜单不再列出 abandoned 任务和已经 close 的任务;目标(Objective)里有 abandoned 任务时,会像 failed 一样提示需要人处理。 +- `dyro line retire` 在本线还有任务 worktree 时拒绝退役,并提示先 `dyro task close`:线退役后 `task close` 找不到这条线,任务里的改动就没法再走存档和保全流程。 +- 新增 `dyro line reparent <线> --parent <其他线> | --detach`:只改清单里的父线,分支、基线和 worktree 不动。新父线必须包含本线的全部仓库,且不能成环;写入 `reparent` 事件。 +- `dyro line retire` 新增 `--archive-to <目录>`:退役前把各仓的未提交改动(`changes.patch` 和未跟踪文件)以及线根目录里的非仓库条目移到 `<目录>/<线>/`。补丁不受用户 diff 配置(外部 diff、textconv、颜色)影响,写入前会核对能否反向应用,完整写好后才清理原改动;遇到未跟踪的嵌套仓库直接拒绝。不能与 `--recover` 同用。`--dry-run` 会列出有脏改动的仓和这些条目。退役完成后,如果线根目录只剩 Dyro 生成且未改过的 AGENTS.md/CLAUDE.md 和空目录,就整个删掉;还有其他条目时保留,并在输出里列出。 +- `dyro line retire` 判断"本线已集成"时,不再只看父线或线的基点:依次检查父线、命名基线、`policy.default_base`、`origin/main`、`origin/master`、`origin/release`,任一包含本线 HEAD 即可。基线是固定提交 SHA 时不再拿它当目标(HEAD 不可能被自己的起点包含)。未集成时,提示写明 HEAD、已检查的目标,以及本地 `origin/<分支>` 跟踪 ref 是否与 HEAD 一致。 +- `dyro task close` 可关闭 abandoned 任务。关闭 failed/abandoned 任务时,未合入的任务分支 tip 会先保全为 `refs/dyro/closed/<任务>/` 再删分支;有未提交改动时需要 `--archive-to <目录>`,改动存到 `<目录>/<任务>/<仓>/`。 + ## 0.7.19 - 2026-11-15 对使用者的影响:修复 `line merge` / `line sync` / `task merge` 的 `--push` 在 `push.default=upstream` 且分支上游指向别的远端分支时,会把合并结果推到那个分支(例如 `main`)的问题;新增 `dyro line add-repo`、`dyro line push` 与 `line merge --abort`。推送说明有改动,已 seed 的工作区升级后运行一次 `dyro host seed --force`。 diff --git a/docs/designs/line-lifecycle-and-cross-line-merge.md b/docs/designs/line-lifecycle-and-cross-line-merge.md index 950134a..4a888e5 100644 --- a/docs/designs/line-lifecycle-and-cross-line-merge.md +++ b/docs/designs/line-lifecycle-and-cross-line-merge.md @@ -50,7 +50,7 @@ |------|----------| | per-repo merge session、`--continue` | `--abort` 已落地(见下);`--continue` 不在计划中:冲突仍在进程内回滚,不会留下可 continue 的会话 | | `line add-repo`、`repo remove`/`move` | 多仓配置迁移与 anchor-reference 语义未闭合 | -| retire `--cascade`、unarchive/adopt/reparent | 身份与子孙策略未决 | +| retire `--cascade`、unarchive/adopt | 身份与子孙策略未决;`line reparent` 已落地(只改清单 `parent`,新父线须包含本线全部仓库且不成环) | | manifest 持久 `degraded` | 违背定律 II(`delivery-physics.md:77-78`) | | Console `lineage_edges` | 纯投影可由 events 后做 | | `post_merge` Profile 钩子 | 授权与 A1 门边界未定义(`delivery-physics.md:8-9`) | diff --git a/src/dyro/cli.py b/src/dyro/cli.py index 6afa8dc..1cdf916 100644 --- a/src/dyro/cli.py +++ b/src/dyro/cli.py @@ -217,6 +217,7 @@ import_review_evidence, list_tasks, load_task, + abandon_task, close_task, loop_tasks, merge_task, @@ -265,6 +266,7 @@ merge_line_from, merge_line_into_base, push_line, + reparent_line, observation_timeout_row, recover_line_merge, spawn_line, @@ -3147,6 +3149,13 @@ def cmd_line_add_repo(args: argparse.Namespace) -> None: ) +def cmd_line_reparent(args: argparse.Namespace) -> None: + config = _config(args) + _require_yes(args, "修改开发线父线") + line = reparent_line(config, args.line, "" if args.detach else args.parent, dry_run=args.dry_run) + print(f"{'DRY RUN: ' if args.dry_run else ''}开发线 {line.id} 的父线 -> {line.parent or '(无)'}") + + def cmd_line_push(args: argparse.Namespace) -> None: config = _config(args) _require_yes(args, "推送开发线分支") @@ -3353,6 +3362,7 @@ def cmd_line_retire(args: argparse.Namespace) -> None: keep_branch=args.keep_branch, force=args.force, integration_ref=args.integration_ref, missing_ok=args.missing_ok, recover=args.recover, + archive_to=Path(args.archive_to).expanduser().absolute() if args.archive_to else None, ) if args.dry_run: options = result["effective_options"] @@ -3361,9 +3371,19 @@ def cmd_line_retire(args: argparse.Namespace) -> None: ) print(f"DRY RUN: 退役 {args.id};只读预检,逐仓保全 → 移除 → {branch_action}") for repo_id, snapshot in result["repositories"].items(): - print(f"{repo_id}: {snapshot['path']},集成目标 {snapshot['integration_ref']}") + note = ",有未提交改动(将存档)" if repo_id in result["dirty"] else "" + print(f"{repo_id}: {snapshot['path']},集成目标 {snapshot['integration_ref']}{note}") + if result["extras"]: + action = "将移入 --archive-to 目录" if args.archive_to else "退役后会留在原地;可加 --archive-to <目录>" + print(f"线根目录非仓库条目({action}):") + for entry in result["extras"]: + print(f" {entry}") else: + for row in result.get("archived", []): + print(f"已存档 {row}") print(f"已退役 {args.id};操作 {result['op_id']} ({result['phase']})") + if result.get("line_root_remaining"): + print("线根目录仍有非仓库条目,未删除:" + "、".join(result["line_root_remaining"])) def cmd_line_post(args: argparse.Namespace) -> None: @@ -4113,11 +4133,20 @@ def cmd_task_merge(args: argparse.Namespace) -> None: print(f"已合并 {task.id}" + (" 并推送" if args.push else "")) +def cmd_task_abandon(args: argparse.Namespace) -> None: + config = _config(args) + task = load_task(config, args.id) + abandon_task(config, task, args.reason, dry_run=args.dry_run) + print(f"{'DRY RUN: ' if args.dry_run else ''}{task.id} -> abandoned") + + def cmd_task_close(args: argparse.Namespace) -> None: _require_yes(args, "关闭任务") config = _config(args) task = load_task(config, args.id) - close_task(config, task, dry_run=args.dry_run) + archive_to = Path(args.archive_to).expanduser().absolute() if args.archive_to else None + for row in close_task(config, task, dry_run=args.dry_run, archive_to=archive_to): + print(row) print( f"{'DRY RUN: 将关闭' if args.dry_run else '已关闭'} {task.id} 的任务 worktree" ) @@ -5516,6 +5545,17 @@ def build_parser() -> argparse.ArgumentParser: ) line_add_repo.add_argument("--yes", action="store_true") line_add_repo.set_defaults(func=cmd_line_add_repo) + line_reparent = line_sub.add_parser( + "reparent", help="把开发线改挂到另一条父线,或解除父线(只改清单,不动分支与 worktree)" + ) + line_reparent.add_argument("line", help="开发线 ID") + target = line_reparent.add_mutually_exclusive_group(required=True) + target.add_argument("--parent", help="新的父线 ID") + target.add_argument("--detach", action="store_true", help="解除父线,成为顶层线") + line_reparent.add_argument("--dry-run", dest="dry_run", action="store_true", + default=argparse.SUPPRESS, help="只校验,不改清单(兼容全局 --dry-run)") + line_reparent.add_argument("--yes", action="store_true") + line_reparent.set_defaults(func=cmd_line_reparent) line_push = line_sub.add_parser( "push", help="把开发线分支推到 origin 并设置上游(只推已提交内容;需 policy.allow_push)", @@ -5717,6 +5757,8 @@ def build_parser() -> argparse.ArgumentParser: line_retire.add_argument("--integration-ref", default=None) line_retire.add_argument("--missing-ok", action="store_true", default=None) line_retire.add_argument("--recover", nargs="?", const="", default=None, metavar="OP_ID") + line_retire.add_argument("--archive-to", metavar="DIR", default=None, + help="退役前把各仓未提交改动与线根目录非仓库条目移入 DIR/<线>/") line_retire.add_argument("--yes", action="store_true") line_retire.set_defaults(func=cmd_line_retire) line_inbox.add_argument("--line", help="查看指定线的频道历史;退役线从墓碑读取") @@ -6188,9 +6230,19 @@ def build_parser() -> argparse.ArgumentParser: task_merge.add_argument("--yes", action="store_true") task_merge.add_argument("--push", action="store_true") task_merge.set_defaults(func=cmd_task_merge) - task_close = task_sub.add_parser("close", help="移除已完成或失败任务的 worktree 与任务分支") + task_abandon = task_sub.add_parser( + "abandon", help="把不再继续的 failed/backlog 任务标记为 abandoned(终态,不再阻塞线退役)" + ) + task_abandon.add_argument("id") + task_abandon.add_argument("--reason", required=True) + task_abandon.set_defaults(func=cmd_task_abandon) + task_close = task_sub.add_parser( + "close", help="移除 done/failed/abandoned 任务的 worktree 与任务分支;未合入分支保全到 refs/dyro/closed/" + ) task_close.add_argument("id") task_close.add_argument("--yes", action="store_true") + task_close.add_argument("--archive-to", metavar="DIR", default=None, + help="先把未提交改动与未跟踪文件存档到 DIR/<任务>/<仓>/ 再移除") task_close.set_defaults(func=cmd_task_close) task_sub.add_parser("decisions").set_defaults(func=cmd_task_decisions) task_sub.add_parser("stats").set_defaults(func=cmd_task_stats) diff --git a/src/dyro/continuation/planner.py b/src/dyro/continuation/planner.py index 786c647..554fc86 100644 --- a/src/dyro/continuation/planner.py +++ b/src/dyro/continuation/planner.py @@ -372,10 +372,11 @@ def build_continuation_plan(snapshot: SchedulerSnapshot) -> ContinuationPlan: reason=ReasonCode.ANSWER_REQUIRED, ) ) - elif item.status == "failed": + elif item.status in ("failed", "abandoned"): + # An abandoned target can never become done: the user must re-scope the objective. attention.append( AttentionItem( - id=f"failed:{task_id}", + id=f"{item.status}:{task_id}", kind=AttentionKind.NEEDS_USER, subject_id=task_id, reason=ReasonCode.TASK_FAILED, diff --git a/src/dyro/events.py b/src/dyro/events.py index 173889f..f42dbdb 100644 --- a/src/dyro/events.py +++ b/src/dyro/events.py @@ -32,6 +32,7 @@ "merge_cross", "sync", "retire", + "reparent", "task_status", "objective_wave", "dispatch", diff --git a/src/dyro/home.py b/src/dyro/home.py index 5339a35..3e7eef9 100644 --- a/src/dyro/home.py +++ b/src/dyro/home.py @@ -952,7 +952,12 @@ def _targets(config: Config, record: WorkspaceRecord | None) -> list[HomeTarget] "task", task.id, f"继续任务:{task.id} [{task_status(config, task)}]" ) for task in list_tasks(config) - if worktree_root(config, task).is_dir() + # `task close` leaves the root (receipts, logs); only live repo worktrees count. + if any( + (worktree_root(config, task) / config.repositories[repo_id].mount).is_dir() + for repo_id in task.repositories + ) + and task_status(config, task) != "abandoned" ) if record and record.last_kind and record.last_target: for index, target in enumerate(targets): diff --git a/src/dyro/line_retire.py b/src/dyro/line_retire.py index 620ce1f..2ff36d8 100644 --- a/src/dyro/line_retire.py +++ b/src/dyro/line_retire.py @@ -6,8 +6,11 @@ from __future__ import annotations from dataclasses import asdict +import os from pathlib import Path +import re import shlex +import shutil import uuid from . import events, line_ops @@ -16,10 +19,11 @@ from .process import git, git_read, require_ok from .read_limits import ReadBudget from .state import exclusive_lock, fsync_directory +from .instructions import INSTRUCTION_NAMES, render_line_persona from .workspace import ( Line, MERGE_LOCK_TIMEOUT_SECONDS, _parse_line_content, _state_path, - _worktree_inventory, get_line, line_repository_path, list_lines, load_line_bounded, - merge_lock_path, repository_path, + _worktree_inventory, get_line, line_repository_path, line_root, list_lines, + load_line_bounded, merge_lock_path, repository_path, ) @@ -45,16 +49,166 @@ def load_retired_line(config: Config, line_id: str, *, read_budget: ReadBudget | return line +def archive_worktree_changes(path: Path, destination: Path) -> list[str]: + """Copy uncommitted work (tracked diff plus untracked files) out of a worktree. + + Ignored files are not copied, matching what `git worktree remove` already drops. + Returns the saved paths relative to destination; empty when the worktree is clean. + The copy is built in ``.partial`` and renamed only once complete + and verified, so callers may destroy the originals only after this returns. + """ + dirty = require_ok(git_read(path, "status", "--porcelain=v1", "-uall"), "读取工作区状态").stdout + if not dirty.strip(): + return [] + if destination.resolve().is_relative_to(path.resolve()): + raise DyroError(f"存档目录不能位于将被移除的 worktree 内:{destination}") + if _exists(destination): + raise DyroError(f"存档目录已存在(可能是上次的存档),拒绝覆盖:{destination};核对后移走再重试") + others = [item for item in require_ok( + git_read(path, "ls-files", "-z", "--others", "--exclude-standard"), "列出未跟踪文件", + ).stdout.split("\0") if item] + nested = [item for item in others + if item.endswith("/") or ((path / item).is_dir() and not (path / item).is_symlink())] + if nested: + raise DyroError(f"未跟踪的嵌套仓库无法存档:{', '.join(nested)}({path});请先手工处理") + partial = destination.with_name(destination.name + ".partial") + if _exists(partial): + shutil.rmtree(partial) # our own copy from a failed attempt; the originals were never touched + partial.mkdir(parents=True) + patch = partial / "changes.patch" + # Plumbing ignores diff.external / textconv / color config; --output keeps raw bytes. + require_ok(git_read(path, "diff-index", "-p", "--binary", "--no-ext-diff", "--no-textconv", + "--no-color", f"--output={patch}", "HEAD"), "导出未提交改动") + tracked_changed = any(not row.startswith("??") for row in dirty.splitlines() if row) + if patch.stat().st_size: + require_ok(git_read(path, "apply", "--check", "-R", str(patch)), "核对未提交改动补丁") + elif tracked_changed: + raise DyroError(f"已跟踪文件有改动但补丁为空,拒绝继续:{path}") + else: + patch.unlink() + saved = ["changes.patch"] if patch.exists() else [] + for relative in others: + source, target = path / relative, partial / "untracked" / relative + target.parent.mkdir(parents=True, exist_ok=True) + if source.is_symlink(): + target.symlink_to(os.readlink(source)) + else: + shutil.copy2(source, target) + saved.append(f"untracked/{relative}") + partial.rename(destination) + return saved + + +def _generated_guide(path: Path, line: Line) -> bool: + return (path.name in INSTRUCTION_NAMES and path.is_file() and not path.is_symlink() + and path.read_text(encoding="utf-8", errors="replace") + == render_line_persona(line_id=line.id, branch=line.branch)) + + +def _empty_tree(path: Path) -> bool: + return (path.is_dir() and not path.is_symlink() + and all(_empty_tree(child) for child in path.iterdir())) + + +def line_root_extras(config: Config, line: Line) -> list[Path]: + """Entries under the line root that retire would otherwise leave behind. + + Repository mounts, task worktree roots (if the layout nests them here), + Dyro-generated AGENTS.md/CLAUDE.md and empty directories are not extras; + everything else (notes, outputs, caches) is. + """ + from .tasks import list_tasks, worktree_root + + root = line_root(config, line) + mounts = {line_repository_path(config, line, repo_id).absolute() for repo_id in line.repositories} + mounts |= {worktree_root(config, task).absolute() for task in list_tasks(config) if task.line == line.id} + extras: list[Path] = [] + + def walk(directory: Path) -> None: + for entry in sorted(directory.iterdir()): + if entry.absolute() in mounts or _empty_tree(entry): + continue + if directory == root and _generated_guide(entry, line): + continue + if any(mount.is_relative_to(entry.absolute()) for mount in mounts): + if not entry.is_symlink(): # a symlinked ancestor is left alone, never moved + walk(entry) + else: + extras.append(entry) + + # A mount of "." makes the line root the checkout itself: nothing is extra. + if root.is_dir() and not root.is_symlink() and root.absolute() not in mounts: + walk(root) + return extras + + +def _archive_before_retire(config: Config, line: Line, snapshots: dict, dirty: list[str], + archive_to: Path) -> list[str]: + """Move uncommitted work and line-root extras out, then clean the worktrees.""" + root = line_root(config, line) + if archive_to.resolve().is_relative_to(root.resolve()): + raise DyroError(f"存档目录不能位于线根目录内:{archive_to}") + destination, archived = archive_to / line.id, [] + for repo_id in dirty: + path = Path(snapshots[repo_id]["path"]) + saved = archive_worktree_changes(path, destination / "uncommitted" / repo_id) + # Submodule changes are not in the patch, so never reset into them. + require_ok(git(path, "-c", "submodule.recurse=false", "reset", "--hard", "HEAD"), + "清理已存档的未提交改动") + require_ok(git(path, "clean", "-fd"), "清理已存档的未跟踪文件") + archived.append(f"{repo_id}: {len(saved)} 项未提交改动 -> {destination / 'uncommitted' / repo_id}") + for entry in line_root_extras(config, line): + target = destination / entry.relative_to(root) + if _exists(target): + raise DyroError(f"存档目标已存在,拒绝覆盖:{target}") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(entry), str(target)) + archived.append(f"{entry.relative_to(root)} -> {target}") + return archived + + +def _cleanup_line_root(config: Config, line: Line) -> list[str]: + """Remove the retired line's empty shell; returns entries that keep it alive.""" + root = line_root(config, line) + extras = line_root_extras(config, line) + if extras or not root.is_dir() or root.is_symlink(): + return [str(entry.relative_to(root)) for entry in extras] + for name in INSTRUCTION_NAMES: + if _generated_guide(root / name, line): + (root / name).unlink() + for directory, _, _ in os.walk(root, topdown=False): + try: + os.rmdir(directory) + except OSError: + pass # not empty (e.g. a mount that is still present): leave it + return [] + + def _identity_preflight(config: Config, line_id: str) -> None: - from .tasks import list_tasks, status + from .tasks import FINISHED_STATUSES, list_tasks, status, worktree_root children = sorted(line.id for line in list_lines(config) if line.parent == line_id) if children: - raise DyroError(f"仍有未退役直接子线:{', '.join(children)};请先退役子线") + raise DyroError( + f"仍有未退役直接子线:{', '.join(children)};请先退役子线," + f"或用 dyro line reparent <子线> --parent <其他线>|--detach 改挂" + ) unfinished = [task.id for task in list_tasks(config) - if task.line == line_id and status(config, task) != "done"] + if task.line == line_id and status(config, task) not in FINISHED_STATUSES] if unfinished: - raise DyroError(f"仍有未完成任务引用 {line_id}:{', '.join(unfinished)}") + raise DyroError( + f"仍有未完成任务引用 {line_id}:{', '.join(unfinished)};" + f"不再继续的 failed/backlog 任务可用 dyro task abandon --reason <原因> 结束" + ) + # `task close` needs the live line manifest, so it must run before retirement. + open_worktrees = [task.id for task in list_tasks(config) if task.line == line_id and any( + (worktree_root(config, task) / config.repositories[repo_id].mount).is_dir() + for repo_id in task.repositories)] + if open_worktrees: + raise DyroError( + f"任务 worktree 仍在:{', '.join(open_worktrees)};" + f"请先 dyro task close --yes [--archive-to <目录>]" + ) def _resolve(path: Path, ref: str) -> str: @@ -77,10 +231,11 @@ def _exists(path: Path) -> bool: return path.exists() or path.is_symlink() -def _require_idle_clean(path: Path) -> None: - dirty = require_ok(git_read(path, "status", "--porcelain=v1", "-uall"), "读取工作区状态") - if dirty.stdout.strip(): - raise DyroError(f"工作区不干净:{path}") +def _require_idle_clean(path: Path, *, allow_dirty: bool = False) -> bool: + """Refuse in-progress Git operations; returns whether the worktree is dirty.""" + dirty = bool(require_ok(git_read(path, "status", "--porcelain=v1", "-uall"), "读取工作区状态").stdout.strip()) + if dirty and not allow_dirty: + raise DyroError(f"工作区不干净:{path};新发起的 retire 可用 --archive-to <目录> 先存档未提交改动") for name in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer"): result = require_ok(git_read(path, "rev-parse", "--git-path", name), "读取 Git 操作状态") location = Path(result.stdout.strip()) @@ -88,9 +243,10 @@ def _require_idle_clean(path: Path) -> None: location = path / location if location.exists(): raise DyroError(f"存在进行中的 Git 操作 {name}:{path}") + return dirty -def _check_worktree(snapshot: dict, saved_sha: str) -> None: +def _check_worktree(snapshot: dict, saved_sha: str, *, allow_dirty: bool = False) -> bool: path, anchor = Path(snapshot["path"]), Path(snapshot["anchor"]) expected = snapshot["branch"] if snapshot["storage_mode"] == "anchor-reference": @@ -105,39 +261,81 @@ def _check_worktree(snapshot: dict, saved_sha: str) -> None: f"路径={path}(匹配={matches}),分支={branch or 'DETACHED'},期望={expected}" ) if snapshot["storage_mode"] != "anchor-reference": - _require_idle_clean(path) + return _require_idle_clean(path, allow_dirty=allow_dirty) + return False + +# The usual integration branches (home.py offers the same set as base overrides). +MAINLINE_REFS = ("origin/main", "origin/master", "origin/release") +_SHA = re.compile(r"[0-9a-f]{7,64}") -def _preflight(config: Config, line_id: str, options: dict) -> tuple[Line, dict]: + +def _integration_candidates(config: Config, line: Line, parent: Line | None, repo_id: str) -> list[str]: + """Refs that, if they contain HEAD, prove the line was integrated. + + Any ref containing HEAD is a sufficient proof, so extra candidates only + remove false refusals; a pinned base SHA is skipped because HEAD is never + contained in its own starting point. + """ + base = line.base_for(repo_id) + named_base = [] if _SHA.fullmatch(base) else [base] + return list(dict.fromkeys([*([parent.branch] if parent else []), *named_base, + config.policy.default_base, *MAINLINE_REFS])) + + +def _not_integrated(anchor: Path, repo_id: str, line: Line, tip: str, checked: list[str]) -> DyroError: + remote = _resolve(anchor, f"refs/remotes/origin/{line.branch}") + pushed = ("与 HEAD 一致(已推送但未合入)" if remote == tip + else f"指向 {remote[:12]},与 HEAD 不同" if remote else "不存在") + return DyroError( + f"本线 HEAD 尚未被集成目标包含:{repo_id} HEAD={tip[:12]};已检查:{', '.join(checked)};" + f"本地跟踪 ref origin/{line.branch} {pushed}。" + f"已合入其他分支时用 --integration-ref 指明;只需保全不合入时用 --keep-branch --force" + ) + + +def _preflight(config: Config, line_id: str, options: dict, *, + allow_dirty: bool = False) -> tuple[Line, dict, list[str]]: + """Validate a new retire; returns the line, per-repo snapshots and dirty repo IDs.""" line_ops.require_no_unfinished_op(config, line_id) line = get_line(config, line_id) _identity_preflight(config, line_id) if _exists(retired_path(config, line_id)): raise DyroError(f"现役与退役清单并存:{line_id};请使用 --recover") parent = get_line(config, line.parent) if line.parent and not options["integration_ref"] else None - snapshots = {} + snapshots, dirty = {}, [] for repo_id in sorted(line.repositories): anchor = repository_path(config, repo_id).resolve() path = line_repository_path(config, line, repo_id).absolute() - target = options["integration_ref"] or (parent.branch if parent else line.base_for(repo_id)) tip = _resolve(anchor, f"refs/heads/{line.branch}") + if options["integration_ref"]: + if not _resolve(anchor, options["integration_ref"]): + raise DyroError(f"无法解析集成目标:{repo_id}/{options['integration_ref']}") + candidates = [options["integration_ref"]] + else: + candidates = [ref for ref in _integration_candidates(config, line, parent, repo_id) + if _resolve(anchor, ref)] or [ + ref for ref in (line.base_for(repo_id),) if _resolve(anchor, ref)] + if not candidates: + raise DyroError(f"无法解析集成目标:{repo_id};请用 --integration-ref 指定") + # The first candidate that contains HEAD is journalled and rechecked at R3. + target = next((ref for ref in candidates if tip and git_read( + anchor, "merge-base", "--is-ancestor", tip, _resolve(anchor, ref)).code == 0), "") + if not target and tip and not options["force"]: + raise _not_integrated(anchor, repo_id, line, tip, candidates) + target = target or candidates[0] snapshot = dict(path=str(path), anchor=str(anchor), branch=line.branch, storage_mode=line.storage_for(repo_id), integration_ref=target, integration_sha=_resolve(anchor, target)) - if not snapshot["integration_sha"]: - raise DyroError(f"无法解析集成目标:{repo_id}/{target}") if _exists(path): if not tip: raise DyroError(f"本线分支不存在:{repo_id}/{line.branch}") - _check_worktree(snapshot, tip) + if _check_worktree(snapshot, tip, allow_dirty=allow_dirty): + dirty.append(repo_id) elif not options["missing_ok"]: raise DyroError(f"worktree 缺失:{path};可使用 --missing-ok") - if tip and not options["force"]: - result = git_read(anchor, "merge-base", "--is-ancestor", tip, snapshot["integration_sha"]) - if result.code != 0: - raise DyroError(f"本线尚未被集成目标包含:{repo_id}/{target};可保全后用 --force 退役") snapshots[repo_id] = snapshot - return line, snapshots + return line, snapshots, dirty def _step(config: Config, op: dict, repo_id: str, action: str) -> dict: @@ -372,20 +570,26 @@ def retire_line( config: Config, line_id: str, *, dry_run: bool = False, keep_branch: bool | None = None, force: bool | None = None, integration_ref: str | None = None, missing_ok: bool | None = None, - recover: str | None = None, + recover: str | None = None, archive_to: Path | None = None, ) -> dict: """Retire in repo ID order, or reconcile an existing op forward only. ``recover=None`` starts a new op; ``recover=''`` selects the newest open retire op. None option values mean absent, so recovery can detect conflicts. + ``archive_to`` is not journalled: it runs before a new op starts, and the + originals are cleaned only after their archive is complete, so recovery never + depends on it. A retry after a crash may stop on the earlier archive and ask + the user to move it aside. """ validate_id(line_id, "开发线 ID") + if recover is not None and archive_to is not None: + raise DyroError("--archive-to 只用于新发起的 retire,不能与 --recover 同用") supplied = {key: value for key, value in dict(keep_branch=keep_branch, force=force, integration_ref=integration_ref, missing_ok=missing_ok).items() if value is not None} options = dict(keep_branch=False, force=False, integration_ref="", missing_ok=False) options.update(supplied) if recover is None: - line, _ = _preflight(config, line_id, options) + line, _, _ = _preflight(config, line_id, options, allow_dirty=archive_to is not None) with line_ops.line_identity_lock(config): if recover is not None: op = (line_ops.load_op(config, recover) if recover else @@ -411,7 +615,8 @@ def retire_line( with exclusive_lock(merge_lock_path(config, line_id), timeout_seconds=MERGE_LOCK_TIMEOUT_SECONDS): with line_ops.anchor_locks(config, line.repositories): if recover is None: - checked_line, snapshots = _preflight(config, line_id, options) + checked_line, snapshots, dirty = _preflight( + config, line_id, options, allow_dirty=archive_to is not None) if checked_line != line: raise DyroError("开发线清单在加锁期间变化;请重新执行 retire") targets = {item["integration_ref"] for item in snapshots.values()} @@ -423,7 +628,10 @@ def retire_line( facts = dict(repo_count=len(snapshots), op_id=op_id) events.validate_event_write(**_event_payload(line, facts)) if dry_run: - return dict(dry_run=True, line=line_id, repositories=snapshots, effective_options=options) + return dict(dry_run=True, line=line_id, repositories=snapshots, effective_options=options, + dirty=dirty, extras=[str(path) for path in line_root_extras(config, line)]) + archived = (_archive_before_retire(config, line, snapshots, dirty, archive_to) + if archive_to is not None else []) content = _state_path(config, line.kind, line_id).read_text(encoding="utf-8") op = line_ops.create_op(config, kind="retire", subject_line_ids=[line_id], manifest_snapshot=dict(asdict(line), content=content), @@ -433,8 +641,9 @@ def retire_line( events.validate_event_write(**_event_payload(line, op["event_facts"])) if dry_run: raise DyroError("--recover 不能与 --dry-run 同用") + archived = [] if op["phase"] in line_ops.TERMINAL_PHASES: - return op + return dict(op, archived=archived, line_root_remaining=_cleanup_line_root(config, line)) active = _state_path(config, line.kind, line.id) retired = retired_path(config, line.id) present = [path for path in (active, retired) if _exists(path)] @@ -449,4 +658,5 @@ def retire_line( _publish(config, op, line) except (DyroError, OSError) as exc: raise _report(config, op, exc) from exc - return line_ops.load_op(config, op["op_id"]) + return dict(line_ops.load_op(config, op["op_id"]), archived=archived, + line_root_remaining=_cleanup_line_root(config, line)) diff --git a/src/dyro/tasks.py b/src/dyro/tasks.py index 0b1d877..aea0f12 100644 --- a/src/dyro/tasks.py +++ b/src/dyro/tasks.py @@ -63,17 +63,21 @@ "review_pending_signoff", "done", "failed", + "abandoned", ) +# Terminal statuses that no longer block line retirement. +FINISHED_STATUSES = frozenset({"done", "abandoned"}) QUALITY_GATE_STATUSES = frozenset({"review", "review_pending_signoff", "done"}) TRANSITIONS = { - "backlog": {"assigned"}, + "backlog": {"assigned", "abandoned"}, "assigned": {"in_progress", "failed"}, "in_progress": {"waiting_answer", "review", "failed"}, "waiting_answer": {"assigned", "in_progress", "failed"}, "review": {"review_pending_signoff", "done", "failed"}, "review_pending_signoff": {"done", "failed"}, - "failed": {"assigned"}, + "failed": {"assigned", "abandoned"}, "done": set(), + "abandoned": set(), } RESULT_RE = re.compile(r"^result:\s*(DONE|BLOCKED|QUESTION)\s*$", re.IGNORECASE) VERDICT_RE = re.compile(r"^verdict:\s*(PASS|FAIL)\s*$", re.IGNORECASE) @@ -282,7 +286,7 @@ def load_task(config: Config, task_id: str) -> Task: except DyroError: from .line_retire import load_retired_line - if status(config, task) != "done" or load_retired_line(config, task.line) is None: + if status(config, task) not in FINISHED_STATUSES or load_retired_line(config, task.line) is None: raise return task @@ -404,7 +408,7 @@ def _validate_bounded_task( from .line_retire import load_retired_line current = current_status if current_status is not None else status_bounded(config, task, budget) - if current != "done" or load_retired_line(config, task.line, read_budget=budget) is None: + if current not in FINISHED_STATUSES or load_retired_line(config, task.line, read_budget=budget) is None: raise ValidationError(f"任务 {task.id} 引用了未登记开发线:{task.line}") return task @@ -927,9 +931,12 @@ def set_status( force: bool = False, dry_run: bool = False, _allow_quality_gate: bool = False, + _allow_abandon: bool = False, ) -> None: if next_status not in STATUSES: raise ValidationError(f"非法状态 {next_status},可选:{', '.join(STATUSES)}") + if next_status == "abandoned" and not _allow_abandon: + raise DyroError("放弃任务请用 dyro task abandon --reason <原因>,以便记录原因") if next_status in QUALITY_GATE_STATUSES and not _allow_quality_gate: raise DyroError( "质量门状态只能由执行证据、独立复核或签收流程写入;" @@ -3216,13 +3223,36 @@ def _signoff_evidence_present(task: Task) -> bool: return (task.directory / "signoff.json").is_file() -def close_task(config: Config, task: Task, *, dry_run: bool = False) -> None: +def abandon_task(config: Config, task: Task, reason: str, *, dry_run: bool = False) -> None: + """End a failed or never-started task for good, recording why.""" + reason = reason.strip() + if not reason: + raise ValidationError("放弃任务必须给出原因(--reason)") current = status(config, task) - if current not in {"done", "failed"}: - raise DyroError(f"只能关闭 done 或 failed 任务,当前 {current}") + if current not in ("failed", "backlog"): + raise DyroError(f"只能放弃 failed 或 backlog 任务,当前 {current}") + set_status(config, task, "abandoned", dry_run=dry_run, _allow_abandon=True) + if not dry_run: + ledger(config, task.id, "abandoned", from_status=current, reason=reason) + + +def close_task( + config: Config, task: Task, *, dry_run: bool = False, archive_to: Path | None = None +) -> list[str]: + """Remove task worktrees and branch; returns what was archived or preserved. + + Unfinished work is never dropped silently: dirty worktrees need ``archive_to`` + and an unmerged task branch tip is kept under ``refs/dyro/closed/``. + """ + from .line_retire import archive_worktree_changes + + current = status(config, task) + if current not in {"done", "failed", "abandoned"}: + raise DyroError(f"只能关闭 done、failed 或 abandoned 任务,当前 {current}") line = get_line(config, task.line) branch = f"{config.policy.task_branch_prefix}{task.id}" root = worktree_root(config, task) + dirty_repos: list[tuple[str, Path]] = [] for repo_id in task.repositories: destination = root / config.repositories[repo_id].mount anchor = repository_path(config, repo_id) @@ -3236,6 +3266,13 @@ def close_task(config: Config, task: Task, *, dry_run: bool = False) -> None: ).stdout.strip() if dirty and current == "done": raise DyroError(f"任务 worktree 不干净,拒绝关闭:{destination}") + if dirty and archive_to is None: + raise DyroError( + f"任务 worktree 有未提交改动:{destination};" + f"用 --archive-to <目录> 先存档再关闭" + ) + if dirty: + dirty_repos.append((repo_id, destination)) if current == "done" and git( anchor, "show-ref", "--verify", "--quiet", f"refs/heads/{branch}" ).code == 0: @@ -3244,6 +3281,16 @@ def close_task(config: Config, task: Task, *, dry_run: bool = False) -> None: raise DyroError( f"任务分支 {branch} 尚未合入开发线 {line.branch},拒绝删除" ) + if archive_to is not None and archive_to.resolve().is_relative_to(root.resolve()): + raise DyroError(f"存档目录不能位于任务工作区内:{archive_to}") + preserved: list[str] = [] + for repo_id, destination in dirty_repos: + target = archive_to / task.id / repo_id # type: ignore[operator] + if dry_run: + preserved.append(f"{repo_id}: 将存档未提交改动到 {target}") + else: + saved = archive_worktree_changes(destination, target) + preserved.append(f"{repo_id}: 已存档 {len(saved)} 项未提交改动到 {target}") for repo_id in task.repositories: destination = root / config.repositories[repo_id].mount anchor = repository_path(config, repo_id) @@ -3251,19 +3298,29 @@ def close_task(config: Config, task: Task, *, dry_run: bool = False) -> None: _assert_task_worktree_path(config, task, destination) _validate_task_worktree(config, task, repo_id, destination, branch) remove_args: tuple[str, ...] = ("worktree", "remove") - if current == "failed": + if current != "done": + # Uncommitted work was archived above; the rest is ignored files. remove_args += ("--force",) require_ok( git(anchor, *remove_args, str(destination), dry_run=dry_run), f"移除 {repo_id} 任务 worktree", ) - if git(anchor, "show-ref", "--verify", "--quiet", f"refs/heads/{branch}").code == 0: + tip = git(anchor, "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}^{{commit}}") + if tip.code == 0: + sha = tip.stdout.strip() + if current != "done" and git(anchor, "merge-base", "--is-ancestor", sha, line.branch).code != 0: + # Keyed by tip, so re-closing after a retry never overwrites an older tip. + keep = f"refs/dyro/closed/{task.id}/{sha[:12]}" + require_ok(git(anchor, "update-ref", keep, sha, dry_run=dry_run), + f"保全 {repo_id} 任务分支 {branch}") + preserved.append(f"{repo_id}: 未合入的任务分支{'将' if dry_run else '已'}保全为 {keep}") require_ok( git(anchor, "branch", "-D", branch, dry_run=dry_run), f"删除 {repo_id} 任务分支 {branch}", ) if not dry_run: - ledger(config, task.id, "closed", line=line.id, branch=branch) + ledger(config, task.id, "closed", line=line.id, branch=branch, preserved=preserved) + return preserved def merge_task( diff --git a/src/dyro/workspace.py b/src/dyro/workspace.py index 9b9e51c..79c5995 100644 --- a/src/dyro/workspace.py +++ b/src/dyro/workspace.py @@ -826,6 +826,42 @@ def spawn_line( return line +def reparent_line(config: Config, line_id: str, parent: str, *, dry_run: bool = False) -> Line: + """Move a line under another parent line, or detach it when ``parent`` is empty. + + Only the manifest's ``parent`` changes; branch, bases and worktrees stay put. + """ + from .events import append_event, validate_event_write + + with line_identity_lock(config): + with exclusive_lock( + merge_lock_path(config, line_id), + timeout_seconds=MERGE_LOCK_TIMEOUT_SECONDS, + ): + line = get_line(config, line_id) + require_no_unfinished_op(config, line.id) + new_parent = _validate_parent_link(config, line.id, parent) + if new_parent == line.parent: + raise DyroError(f"开发线 {line.id} 的父线已是 {new_parent or '(无)'}") + if new_parent: + missing = [repo_id for repo_id in line.repositories + if repo_id not in get_line(config, new_parent).repositories] + if missing: + raise ValidationError( + f"子线仓库必须是父线 {new_parent} 仓库的子集:{', '.join(missing)}" + ) + facts = {key: value for key, value in + (("from_parent", line.parent), ("to_parent", new_parent)) if value} + event = dict(kind="reparent", actor=line.id, subject=line.id, + family=new_parent or line.id, facts=facts) + validate_event_write(**event) + updated = replace(line, parent=new_parent) + _write_line(config, updated, dry_run=dry_run) + if not dry_run: + append_event(config, **event) + return updated + + def add_line_repository( config: Config, line_id: str, diff --git a/tests/test_line_retire.py b/tests/test_line_retire.py index 24352c7..7820967 100644 --- a/tests/test_line_retire.py +++ b/tests/test_line_retire.py @@ -554,6 +554,115 @@ def snapshot(): families.ack_channel_message(self.config, message["id"], family="alpha", dry_run=dry_run) self.assertEqual(snapshot(), before) + def test_abandoned_task_unblocks_retire_and_stays_loadable(self) -> None: + task_path = tasks.create_task(self.config, "T1", title="gave up", line_id="alpha", repositories=["api"]) + (task_path / "status").write_text("failed\n") + with self.assertRaisesRegex(DyroError, "未完成任务.*T1.*task abandon"): + line_retire.retire_line(self.config, "alpha", dry_run=True) + task = tasks.load_task(self.config, "T1") + with self.assertRaisesRegex(DyroError, "原因"): + tasks.abandon_task(self.config, task, " ") + with self.assertRaisesRegex(DyroError, "task abandon"): + tasks.set_status(self.config, task, "abandoned", force=True) + tasks.abandon_task(self.config, task, "merged by hand into the line") + self.assertEqual(tasks.status(self.config, task), "abandoned") + with self.assertRaisesRegex(DyroError, "拒绝状态跳转"): + tasks.set_status(self.config, task, "assigned") + mount = tasks.worktree_root(self.config, task) / self.config.repositories["api"].mount + mount.mkdir(parents=True) + with self.assertRaisesRegex(DyroError, "任务 worktree 仍在.*T1.*task close"): + line_retire.retire_line(self.config, "alpha", dry_run=True) + mount.rmdir() + self.assertEqual(line_retire.retire_line(self.config, "alpha")["phase"], "completed") + self.assertEqual([item.id for item in tasks.list_tasks(self.config)], ["T1"]) + ledger = self.config.ledger_file.read_text() + self.assertIn('"phase": "abandoned"', ledger) + self.assertIn("merged by hand", ledger) + + def test_reparent_detach_unblocks_parent_retire(self) -> None: + child = workspace.spawn_line(self.config, "alpha", "child") + with self.assertRaisesRegex(DyroError, "直接子线.*line reparent"): + line_retire.retire_line(self.config, "alpha", dry_run=True) + with self.assertRaisesRegex(DyroError, "成环"): + workspace.reparent_line(self.config, "alpha", child.id) + with self.assertRaisesRegex(DyroError, "已是"): + workspace.reparent_line(self.config, child.id, "alpha") + workspace.create_line(self.config, line_id="beta", branch="feat/beta", base="main") + self.assertEqual(workspace.reparent_line(self.config, child.id, "beta").parent, "beta") + self.assertEqual(workspace.reparent_line(self.config, child.id, "").parent, "") + self.assertEqual(workspace.get_line(self.config, child.id).parent, "") + rows, _ = events.read_events(self.config) + self.assertEqual([row["facts"] for row in rows if row["kind"] == "reparent"], + [{"from_parent": "alpha", "to_parent": "beta"}, {"from_parent": "beta"}]) + self.assertEqual(line_retire.retire_line(self.config, "alpha")["phase"], "completed") + + def test_pinned_base_sha_is_skipped_and_mainline_refs_prove_integration(self) -> None: + workspace._write_line(self.config, replace(self.line, base=self.sha)) + head = self._commit(self.path) + shell("git", "update-ref", "refs/remotes/origin/feat/alpha", head, cwd=self.anchor) + with self.assertRaisesRegex(DyroError, rf"HEAD={head[:12]}.*已推送但未合入") as raised: + line_retire.retire_line(self.config, "alpha", dry_run=True) + self.assertNotIn(self.sha, str(raised.exception)) + shell("git", "update-ref", "refs/remotes/origin/release", head, cwd=self.anchor) + plan = line_retire.retire_line(self.config, "alpha", dry_run=True) + self.assertEqual(plan["repositories"]["api"]["integration_ref"], "origin/release") + + def test_archive_to_saves_dirty_work_and_extras_then_removes_shell(self) -> None: + root = workspace.line_root(self.config, self.line) + self.assertTrue((root / "CLAUDE.md").is_file()) + # User diff config must not empty or colour the archived patch. + shell("git", "config", "diff.external", "/usr/bin/true", cwd=self.anchor) + shell("git", "config", "color.diff", "always", cwd=self.anchor) + (self.path / "README.md").write_text("edited\n") + (self.path / "scratch.txt").write_text("untracked\n") + (self.path / ".venv").symlink_to("/nonexistent/venv") + (root / "notes.md").write_text("keep me\n") + (root / "_workspace").mkdir() + (root / "_workspace/report.md").write_text("report\n") + with self.assertRaisesRegex(DyroError, "不干净.*--archive-to"): + line_retire.retire_line(self.config, "alpha", dry_run=True) + archive = self.root.parent / f"{self.root.name}-archive" + plan = line_retire.retire_line(self.config, "alpha", dry_run=True, archive_to=archive) + self.assertEqual(plan["dirty"], ["api"]) + self.assertEqual(sorted(Path(entry).name for entry in plan["extras"]), ["_workspace", "notes.md"]) + self.assertFalse(archive.exists()) + with self.assertRaisesRegex(DyroError, "线根目录内"): + line_retire.retire_line(self.config, "alpha", archive_to=root / "archive") + with self.assertRaisesRegex(DyroError, "不能与 --recover"): + line_retire.retire_line(self.config, "alpha", recover="", archive_to=archive) + op = line_retire.retire_line(self.config, "alpha", archive_to=archive) + self.assertEqual(op["phase"], "completed") + self.assertEqual(op["line_root_remaining"], []) + self.assertFalse(root.exists()) + saved = archive / "alpha" + patch_text = (saved / "uncommitted/api/changes.patch").read_text() + self.assertIn("+edited", patch_text) + self.assertNotIn("\x1b[", patch_text) + self.assertEqual((saved / "uncommitted/api/untracked/scratch.txt").read_text(), "untracked\n") + self.assertTrue((saved / "uncommitted/api/untracked/.venv").is_symlink()) + self.assertEqual((saved / "notes.md").read_text(), "keep me\n") + self.assertTrue((saved / "_workspace/report.md").is_file()) + + def test_archive_refuses_untracked_nested_repo_without_partial_copy(self) -> None: + nested = self.path / "nested" + nested.mkdir() + shell("git", "init", "-q", cwd=nested) + (nested / "inner.txt").write_text("inner\n") + target = self.root.parent / f"{self.root.name}-nested-archive" + with self.assertRaisesRegex(DyroError, "嵌套仓库.*nested"): + line_retire.archive_worktree_changes(self.path, target) + self.assertFalse(target.exists()) + self.assertFalse(target.with_name(target.name + ".partial").exists()) + self.assertTrue((nested / "inner.txt").is_file()) + + def test_retire_without_archive_keeps_line_root_with_extras(self) -> None: + root = workspace.line_root(self.config, self.line) + (root / "notes.md").write_text("keep me\n") + op = line_retire.retire_line(self.config, "alpha") + self.assertEqual(op["line_root_remaining"], ["notes.md"]) + self.assertEqual((root / "notes.md").read_text(), "keep me\n") + self.assertTrue((root / "CLAUDE.md").is_file()) + def test_cli_flags_and_dry_run_plan(self) -> None: parser = build_parser() args = parser.parse_args(["line", "retire", "alpha", "--dry-run", "--keep-branch"]) diff --git a/tests/test_review_remediation.py b/tests/test_review_remediation.py index eaa0578..77a1361 100644 --- a/tests/test_review_remediation.py +++ b/tests/test_review_remediation.py @@ -425,6 +425,38 @@ def test_task_close_removes_worktree_after_failure(self) -> None: close_task(config, task) self.assertFalse((root / "services/api").exists()) + def test_task_close_failed_archives_dirty_work_and_keeps_unmerged_tip(self) -> None: + from dyro.home import _targets + from dyro.tasks import abandon_task, close_task, load_task, run_task, status, worktree_root + + self._create_named_task() + config = load(self.root) + task = load_task(config, "T1") + self.assertEqual(run_task(config, task), "failed") + mount = worktree_root(config, task) / "services/api" + (mount / "work.txt").write_text("committed\n", encoding="utf-8") + shell("git", "add", "work.txt", cwd=mount) + shell("git", "commit", "-m", "task work", cwd=mount) + tip = shell_stdout("git", "rev-parse", "HEAD", cwd=mount) + (mount / "wip.txt").write_text("uncommitted\n", encoding="utf-8") + self.assertEqual([t.id for t in _targets(config, None) if t.kind == "task"], ["T1"]) + with self.assertRaisesRegex(DyroError, "未提交改动.*--archive-to"): + close_task(config, task) + self.assertTrue(mount.is_dir()) + with self.assertRaisesRegex(DyroError, "任务工作区内"): + close_task(config, task, archive_to=worktree_root(config, task) / "keep") + archive = self.root.parent / f"{self.root.name}-archive" + rows = close_task(config, task, archive_to=archive) + self.assertFalse(mount.exists()) + self.assertEqual((archive / "T1/api/untracked/wip.txt").read_text(), "uncommitted\n") + anchor = repository_path(config, "api") + kept = f"refs/dyro/closed/T1/{tip[:12]}" + self.assertEqual(shell_stdout("git", "rev-parse", kept, cwd=anchor), tip) + self.assertTrue(any(kept in row for row in rows)) + self.assertEqual([t.id for t in _targets(config, None) if t.kind == "task"], []) + abandon_task(config, task, "superseded") + self.assertEqual(status(config, task), "abandoned") + def test_review_fail_verdict_exits_nonzero(self) -> None: from dyro.cli import main from dyro.tasks import load_task, run_task