From 12dee710f780e78bf45afc0963e5ae357d69b64e Mon Sep 17 00:00:00 2001 From: DandreYang <13072547+Dandre126@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:23:35 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E7=BA=BF):=20merge/sync/task=20merge=20--p?= =?UTF-8?q?ush=20=E9=92=89=E4=BD=8F=E5=88=86=E6=94=AF=20tip=20=E6=8E=A8?= =?UTF-8?q?=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此前三条 --push 路径执行裸 git push origin ,锚点取推送后 的 HEAD。push.default=upstream 且上游指向别的远端分支时会推到错误 分支(git 2.49 实测 feat -> main),推送后工作区被切走时锚点也会 与实际推送不一致。 现在推送前钉住 refs/heads/ 的 tip,执行 git push origin :refs/heads/,锚点和 journal 都记这个 SHA;预检、--recover 手动命令、建线发布提示与推送说明也不再给出 裸 git push origin <分支>。dyro line push 不变。 --- CHANGELOG.md | 1 + .../line-aware-next-and-push-contract.md | 10 +- src/dyro/cli.py | 4 +- src/dyro/config.py | 2 +- .../assets/dyro-control-plane/SKILL.md | 2 +- src/dyro/tasks.py | 12 +- src/dyro/workspace.py | 50 ++++-- tests/test_line_merge_cross.py | 23 ++- tests/test_line_next_contract.py | 8 +- tests/test_merge_push_refspec.py | 149 ++++++++++++++++++ tests/test_review_remediation.py | 2 +- 11 files changed, 227 insertions(+), 36 deletions(-) create mode 100644 tests/test_merge_push_refspec.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5900626..f9f1672 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - 新增 `dyro line add-repo`:把一个已经登记的仓库加入现有开发线。已有子线保持不变;子线只能加入父线里已经有的仓库。 - 新增 `dyro line push`:把开发线分支推到 origin 并设置上游。只推已提交内容,需 `policy.allow_push`;`anchor-reference` 仓库会跳过。推送说明(`next` 的 `push_note`、工作区和开发线说明、控制面技能)同步提到这条命令;已 seed 的工作区 doctor 会报模板不一致,运行一次 `dyro host seed --force` 即可。 - 修复 `dyro line create` / `dyro line spawn` 中途失败回滚时留下本次新建分支的问题:之前用另一个基线重试会静默复用旧分支;现在回滚会删除本次新建的分支,原本就有的分支保持不动。 +- 修复 `line merge` / `line sync` / `task merge` 的 `--push`:推送前钉住分支 tip,用显式 refspec `git push origin :refs/heads/` 推送,并把远端锚点记成恰好这个 SHA。此前在 `push.default=upstream` 且分支上游指向别的远端分支时,会把合并结果推到那个分支上(例如 `main`);推送后工作区被切走时,锚点也可能和实际推送的提交不一致。`--recover` 打印的手动推送命令、建线后的发布提示和推送说明也不再给出裸的 `git push origin <分支>`。 ## 0.7.18 - 2026-11-14 diff --git a/docs/designs/line-aware-next-and-push-contract.md b/docs/designs/line-aware-next-and-push-contract.md index 2ff547e..9712a1d 100644 --- a/docs/designs/line-aware-next-and-push-contract.md +++ b/docs/designs/line-aware-next-and-push-contract.md @@ -26,7 +26,7 @@ 推送句子今天有三套。工作区 overlay(`instructions.py:31`)禁止绕过门禁做 `git merge` / `git push`。线 overlay(`instructions.py:41-46`)要求必须跟踪 `origin/`。`PUSH_DISABLED_NOTE` 是「Dyro 不会 push;普通 `git push` 仍可用。」(`config.py:23`)。`allow_push` 为 true 时 `push_disclosure` 返回空串(`config.py:133-137`),`push_policy_fields` 不带 `push_note`(`config.py:140-143`)。 -会执行 `git push origin ` 的位置是线 merge/sync(`workspace.py`)和 `task merge`(`tasks.py`)。都要显式 `--push`,并且 `policy.allow_push`。本地合并成功后才逐仓 push。`--push` 前已有 `git push --dry-run`(`workspace.py:825-836`)。清单不写远端 SHA。 +线 merge/sync(`workspace.py`)和 `task merge`(`tasks.py`)在显式 `--push` 且 `policy.allow_push` 时,本地合并成功后才逐仓推送。推送前把 `refs/heads/` 钉成 tip,执行 `git push origin :refs/heads/`(不用 `-u`,不用 `--force` / `--force-with-lease` / `+`)。预检是 `git push --dry-run origin refs/heads/:refs/heads/`。成功后 `[remote_anchors]` 记的是这次推送的 tip,不是事后的 HEAD。 `seed_overlay_files` 在文件已存在且未 `--force` 时跳过(`instructions.py:94-96`)。`overlay_instruction_warning` 只在工作区文件缺失时发 WARN(`instructions.py:62-67`),`doctor` 调用它(`workspace.py:1439-1443`),不比较正文。 @@ -191,7 +191,7 @@ JSON `next` 继续使用已经跑完 `doctor` 的那只 45 秒预算。增量 Gi `next` 的 `push_note`、工作区 overlay、开发线 overlay、控制面技能资产使用下面三段,字节级相同。`allow_push` 为 true 时也返回这段,不再返回空串。 ```text -Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓执行 `git push origin <分支>`。多仓 push 不是原子操作。 +Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓推送该分支的 tip。多仓 push 不是原子操作。 开发线的期望上游是 `origin/`。本地还没有这条远端分支时,doctor 给出 WARN,工作区仍可打开;这不表示可以推送。 普通 `git push` 仍然能改远端,但不会写入 Dyro 的远端锚点,也不算通过门禁。 ``` @@ -227,7 +227,7 @@ doctor 的 WARN 原文保持 `WARN :/: missing origin/` ### push 成功后的远端 SHA -在 `workspace.py` 与 `tasks.py` 两处,每一仓 `git push` 成功后,把该仓 HEAD 的全文 SHA 写入该线的 `[remote_anchors]`。只记录 `linked-worktree`。`anchor-reference` 不写入。后一仓失败时,已成功仓的锚点保留。清单写入失败要报出来,因为 push 已经发生。 +在 `workspace.py` 与 `tasks.py` 两处,每一仓按 `git push origin :refs/heads/` 推送成功后,把这次钉住并推送的 `refs/heads/` tip 写入该线的 `[remote_anchors]`,不用事后的 HEAD。只记录 `linked-worktree`。`anchor-reference` 不写入。后一仓失败时,已成功仓的锚点保留。清单写入失败要报出来,因为 push 已经发生。 持久化规则: @@ -237,7 +237,7 @@ doctor 的 WARN 原文保持 `WARN :/: missing origin/` - 旧 Dyro 遇到版本 4 会在 `workspace.py:109-110` 拒绝解析,因此旧的 `_write_line` 不会拿到 `Line`,也不会把表抹掉。代价是:第一次写下锚点之后,旧二进制不能再加载这条线。没有锚点的线保持版本 2 或 3,旧二进制仍可读写。 - 新的 `_write_line` 从字段写出该表。任何会持久化的 `Line(` 构造都必须带上读到的 `remote_anchors`。默认空映射只用于新建的线。漏带字段再写回,新二进制自己也会抹掉该表。 -不新增名为 `line publish` 的命令。顶层线和子线用 `dyro line push` 发布自己的分支:先确认 `policy.allow_push`,再取与 `line merge --push`、`retire` 相同的 L1 合并锁;再按仓库 ID 升序取 L2 anchor 锁;锁内重读清单,并拒绝该线任何未完成的操作(merge、merge-into-base、retire)。只推 `linked-worktree`。全部这类仓库预检通过后(工作树存在且是 Git、当前分支就是线分支、没有进行中的 Git 操作、同一 refspec 的 `git push --dry-run` 成功),才按清单顺序执行 `git push -u origin refs/heads/:refs/heads/`(显式同名 refspec,`push.default=upstream` 也不能把目标改到别的远端分支;`-u` 同时把上游纠正为 `origin/`)。不使用 `--force`、`--force-with-lease` 或 `+refspec`,也不要求工作树干净,只推已提交内容。成功一仓就为该仓写 `[remote_anchors]`,取值是推送前后各读一次、两次一致的 `refs/heads/` tip;不用事后的 HEAD(工作树可能已切走),也不用 `refs/remotes/origin/`(窄 fetch refspec 下不会更新);推送期间分支移动则不写该仓锚点并报错;`anchor-reference` 跳过、不写锚点。跨仓不原子:后一仓失败时,已成功仓的锚点保留。锚点写入失败要报出来,因为 push 已经发生。`spawn` 不发布。终端里的普通 `git push` 不写 `[remote_anchors]`。`policy.allow_push = true` 时,`line merge` / `line sync` / `task merge` 仍可显式加 `--push`。 +不新增名为 `line publish` 的命令。顶层线和子线用 `dyro line push` 发布自己的分支:先确认 `policy.allow_push`,再取与 `line merge --push`、`retire` 相同的 L1 合并锁;再按仓库 ID 升序取 L2 anchor 锁;锁内重读清单,并拒绝该线任何未完成的操作(merge、merge-into-base、retire)。只推 `linked-worktree`。全部这类仓库预检通过后(工作树存在且是 Git、当前分支就是线分支、没有进行中的 Git 操作、同一 refspec 的 `git push --dry-run` 成功),才按清单顺序执行 `git push -u origin refs/heads/:refs/heads/`(显式同名 refspec,`push.default=upstream` 也不能把目标改到别的远端分支;`-u` 同时把上游纠正为 `origin/`)。不使用 `--force`、`--force-with-lease` 或 `+refspec`,也不要求工作树干净,只推已提交内容。成功一仓就为该仓写 `[remote_anchors]`,取值是推送前后各读一次、两次一致的 `refs/heads/` tip;不用事后的 HEAD(工作树可能已切走),也不用 `refs/remotes/origin/`(窄 fetch refspec 下不会更新);推送期间分支移动则不写该仓锚点并报错;`anchor-reference` 跳过、不写锚点。跨仓不原子:后一仓失败时,已成功仓的锚点保留。锚点写入失败要报出来,因为 push 已经发生。`spawn` 不发布。终端里的普通 `git push` 不写 `[remote_anchors]`。`policy.allow_push = true` 时,`line merge` / `line sync` / `task merge` 仍可显式加 `--push`:推送前钉住 `refs/heads/` 的 tip,执行 `git push origin :refs/heads/`(不用 `-u`),并把 `[remote_anchors]` 记成这个 tip。 ## 4. 延期 @@ -270,7 +270,7 @@ doctor 的 WARN 原文保持 `WARN :/: missing origin/` - doctor 对与模板不同的已有 `AGENTS.md` / `CLAUDE.md` 发 WARN;缺失文件仍是原来的缺失 WARN;doctor 不改文件。不带 `--force` 的 seed 保持原字节。 - 已有 overlay 超过单文件上限(`FILE_TOO_LARGE`),或这一份文件为 `UNSAFE_FILE`:一条「无法核对」WARN,doctor 继续并返回其余 findings。`AGGREGATE_BYTES_EXCEEDED` 与 `DEADLINE_EXCEEDED` 不降级成这条 WARN。截止仍由 doctor 收成 partial 返回;aggregate 在保存 findings 后重新抛出,且不会继续读清单和 Git。 - 三段口径在 `push_note` 与两套模板中逐字相同。`allow_push=true` 时 `push_note` 仍非空。 -- 线 merge `--push` 成功后,`remote_anchors` 等于该仓 HEAD,清单为 schema_version 4。第二仓失败时第一仓锚点仍在。`anchor-reference` 不出现在表里。无锚点的旧清单仍是版本 2 或 3 且能加载。版本 4 能往返 `_parse_line_content` 与 `_write_line` 而不丢表。构造 `Line` 时漏掉该字段再写回,测试要失败。 +- 线 merge `--push` 成功后,`remote_anchors` 等于这次推送钉住的 `refs/heads/` tip(`git push origin :refs/heads/`),清单为 schema_version 4。第二仓失败时第一仓锚点仍在。`anchor-reference` 不出现在表里。无锚点的旧清单仍是版本 2 或 3 且能加载。版本 4 能往返 `_parse_line_content` 与 `_write_line` 而不丢表。构造 `Line` 时漏掉该字段再写回,测试要失败。 ## 7. 实现边界 diff --git a/src/dyro/cli.py b/src/dyro/cli.py index c251dc3..6afa8dc 100644 --- a/src/dyro/cli.py +++ b/src/dyro/cli.py @@ -3102,7 +3102,9 @@ def _create_line(args: argparse.Namespace, kind: str) -> None: f"{'DRY RUN: ' if args.dry_run else ''}已创建 {line.kind} {line.id},分支 {line.branch},仓库基线:{bases}" ) if not args.dry_run: - print(f"发布此线(Dyro 不会代你执行):git push -u origin {line.branch}") + ref = f"refs/heads/{line.branch}" + # Explicit refspec: a bare branch obeys push.default=upstream. + print(f"发布此线:dyro line push {line.id} --yes(需 policy.allow_push),或 git push -u origin {ref}:{ref}") def cmd_line_create(args: argparse.Namespace) -> None: diff --git a/src/dyro/config.py b/src/dyro/config.py index 6881363..28c5e76 100644 --- a/src/dyro/config.py +++ b/src/dyro/config.py @@ -20,7 +20,7 @@ OBJECTIVES_DIR = ".dyro/objectives" SAFE_ID = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$") -PUSH_DISABLED_NOTE = 'Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓执行 `git push origin <分支>`。多仓 push 不是原子操作。\n开发线的期望上游是 `origin/`。本地还没有这条远端分支时,doctor 给出 WARN,工作区仍可打开;这不表示可以推送。\n普通 `git push` 仍然能改远端,但不会写入 Dyro 的远端锚点,也不算通过门禁。' +PUSH_DISABLED_NOTE = 'Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓推送该分支的 tip。多仓 push 不是原子操作。\n开发线的期望上游是 `origin/`。本地还没有这条远端分支时,doctor 给出 WARN,工作区仍可打开;这不表示可以推送。\n普通 `git push` 仍然能改远端,但不会写入 Dyro 的远端锚点,也不算通过门禁。' @dataclass(frozen=True) diff --git a/src/dyro/integrations/assets/dyro-control-plane/SKILL.md b/src/dyro/integrations/assets/dyro-control-plane/SKILL.md index 6865965..7fd6bdd 100644 --- a/src/dyro/integrations/assets/dyro-control-plane/SKILL.md +++ b/src/dyro/integrations/assets/dyro-control-plane/SKILL.md @@ -50,7 +50,7 @@ Only hand off a workspace-scoped mutation when the returned command retains an e If the user asks for 会审, 对抗, or Go/No-Go, follow the `dyro-board` protocol (human command `/dyro-review-board`) instead of inventing P0 here. A CLI summary alone is never final runtime or production acceptance. -Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓执行 `git push origin <分支>`。多仓 push 不是原子操作。 +Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓推送该分支的 tip。多仓 push 不是原子操作。 开发线的期望上游是 `origin/`。本地还没有这条远端分支时,doctor 给出 WARN,工作区仍可打开;这不表示可以推送。 普通 `git push` 仍然能改远端,但不会写入 Dyro 的远端锚点,也不算通过门禁。 diff --git a/src/dyro/tasks.py b/src/dyro/tasks.py index cc4fd70..0b1d877 100644 --- a/src/dyro/tasks.py +++ b/src/dyro/tasks.py @@ -3039,7 +3039,7 @@ def _prepare_merge( "push", "--dry-run", "origin", - line.branch, + f"refs/heads/{line.branch}:refs/heads/{line.branch}", ), f"预检推送 {plan.repository}", ) @@ -3161,8 +3161,11 @@ def _merge_task_repositories_locked( pushed: list[str] = [] if push: + from .workspace import _branch_tip, record_remote_anchor + for plan in plans: - result = git(plan.target, "push", "origin", line.branch) + tip = _branch_tip(plan.target, line.branch) + result = git(plan.target, "push", "origin", f"{tip}:refs/heads/{line.branch}") if result.code != 0: ledger( config, @@ -3177,8 +3180,9 @@ def _merge_task_repositories_locked( f"\n{result.stdout.strip()}" ) pushed.append(plan.repository) - from .workspace import record_remote_anchor - line = record_remote_anchor(config, line, plan.repository, plan.target) + line = record_remote_anchor( + config, line, plan.repository, plan.target, sha=tip + ) for plan in plans: result_head = require_ok( diff --git a/src/dyro/workspace.py b/src/dyro/workspace.py index 1e7f8c8..9b9e51c 100644 --- a/src/dyro/workspace.py +++ b/src/dyro/workspace.py @@ -1022,7 +1022,7 @@ def _prepare_line_merge_plans( "push", "--dry-run", "origin", - target.branch, + f"refs/heads/{target.branch}:refs/heads/{target.branch}", ), f"预检推送 {plan.repository}", ) @@ -1220,7 +1220,8 @@ def _merge_line_repositories_locked( pushed: list[str] = [] if push: for plan in plans: - result = git(plan.target, "push", "origin", target.branch) + tip = _branch_tip(plan.target, target.branch) + result = git(plan.target, "push", "origin", f"{tip}:refs/heads/{target.branch}") if result.code != 0: _line_ledger( config, @@ -1236,7 +1237,9 @@ def _merge_line_repositories_locked( f"\n{result.stdout.strip()}" ) pushed.append(plan.repository) - target = record_remote_anchor(config, target, plan.repository, plan.target) + target = record_remote_anchor( + config, target, plan.repository, plan.target, sha=tip + ) changeset_id = "" if not dry_run: @@ -1506,6 +1509,13 @@ def _head_sha(repo: Path) -> str: return require_ok(git(repo, "rev-parse", "HEAD"), f"读取 {repo} HEAD").stdout.strip() +def _branch_tip(repo: Path, branch: str) -> str: + return require_ok( + git(repo, "rev-parse", "--verify", f"refs/heads/{branch}"), + f"读取 {branch} 分支", + ).stdout.strip() + + def _has_merge_head(repo: Path) -> bool: return git(repo, "rev-parse", "--verify", "-q", "MERGE_HEAD").code == 0 @@ -2088,8 +2098,15 @@ def _run_journaled_line_merge( ) if push: for plan in plans: + branch = branches[plan.repository] require_ok( - git(plan.target, "push", "--dry-run", "origin", branches[plan.repository]), + git( + plan.target, + "push", + "--dry-run", + "origin", + f"refs/heads/{branch}:refs/heads/{branch}", + ), f"预检推送 {plan.repository}", ) if dry_run: @@ -2144,26 +2161,32 @@ def _run_journaled_line_merge( if push: pushed: list[str] = [] for index, plan in enumerate(plans): - push_head = _head_sha(plan.target) + branch = branches[plan.repository] + tip = _branch_tip(plan.target, branch) record_repo_intent( config, op_id, plan.repository, "push", - original_head=plan.original_head, target_sha=push_head, - branch=branches[plan.repository], remote="origin", + original_head=plan.original_head, target_sha=tip, + branch=branch, remote="origin", ) - result = git(plan.target, "push", "origin", branches[plan.repository]) + result = git(plan.target, "push", "origin", f"{tip}:refs/heads/{branch}") if result.code == 0: - target = record_remote_anchor(config, target, plan.repository, plan.target) + target = record_remote_anchor( + config, target, plan.repository, plan.target, sha=tip + ) record_repo_result( config, op_id, plan.repository, "push", outcome="pushed" if result.code == 0 else "push_failed", - new_tip=push_head if result.code == 0 else "", + new_tip=tip if result.code == 0 else "", error=result.stdout.strip() if result.code != 0 else "", ) if result.code != 0: for remaining in plans[index + 1:]: record_repo_intent( config, op_id, remaining.repository, "push", - original_head=remaining.original_head, target_sha=_head_sha(remaining.target), + original_head=remaining.original_head, + target_sha=_branch_tip( + remaining.target, branches[remaining.repository] + ), branch=branches[remaining.repository], remote="origin", ) record_repo_result( @@ -2659,8 +2682,9 @@ def recover_line_merge( ) if push_step is not None: path = shlex.quote(str(repo["snapshot"]["path"])) - branch = shlex.quote(str(push_step["intent"]["branch"])) - report.append(f" 手动:git -C {path} push origin {branch}") + ref = f"refs/heads/{push_step['intent']['branch']}" + # Explicit refspec: a bare branch obeys push.default=upstream. + report.append(f" 手动:git -C {path} push origin {shlex.quote(f'{ref}:{ref}')}") outcomes[repo_id] = ( op["repositories"][repo_id]["outcome"] if terminal else _reconcile_merge_repo(config, op, repo_id, report=report) diff --git a/tests/test_line_merge_cross.py b/tests/test_line_merge_cross.py index 7c11167..5d55feb 100644 --- a/tests/test_line_merge_cross.py +++ b/tests/test_line_merge_cross.py @@ -38,6 +38,15 @@ def _stdout(*args: str, cwd: Path) -> str: return completed.stdout.strip() +def _is_real_branch_push(args: tuple, branch: str) -> bool: + return ( + len(args) == 3 + and args[0] == "push" + and args[1] == "origin" + and args[2].endswith(f":refs/heads/{branch}") + ) + + def _commit_text(worktree: Path, filename: str, content: str, message: str) -> str: (worktree / filename).write_text(content, encoding="utf-8") shell("git", "add", filename, cwd=worktree) @@ -772,7 +781,7 @@ def test_into_push_journals_before_push_and_completes_after_anchors(self) -> Non pushed = [] def observe_push(repo, *args, **kwargs): - if args == ("push", "origin", parent.branch): + if _is_real_branch_push(args, parent.branch): op = line_ops.find_unfinished_op(config, parent.id) self.assertIsNotNone(op) repo_id = next(r for r in parent.repositories @@ -813,9 +822,9 @@ def test_into_push_failure_keeps_anchor_and_can_rerun(self) -> None: original_git = workspace.git def fail_second_push(repo, *args, **kwargs): - if args == ("push", "origin", parent.branch): + if _is_real_branch_push(args, parent.branch): self.assertNotEqual(repo, line_repository_path(config, parent, "worker")) - if repo == line_repository_path(config, parent, "web") and args == ("push", "origin", parent.branch): + if repo == line_repository_path(config, parent, "web") and _is_real_branch_push(args, parent.branch): return Result(("git", *args), 1, "rejected") return original_git(repo, *args, **kwargs) @@ -853,14 +862,14 @@ def _assert_into_push_crash_recovery(self, *, after_push: bool, after_anchor: bo original_anchor = workspace.record_remote_anchor def crash_second_push(repo, *args, **kwargs): - if not after_anchor and repo == line_repository_path(config, parent, "web") and args == ("push", "origin", parent.branch): + if not after_anchor and repo == line_repository_path(config, parent, "web") and _is_real_branch_push(args, parent.branch): if after_push: self.assertEqual(original_git(repo, *args, **kwargs).code, 0) raise SystemExit("power loss during push") return original_git(repo, *args, **kwargs) - def crash_second_anchor(config, line, repo_id, path): - updated = original_anchor(config, line, repo_id, path) + def crash_second_anchor(config, line, repo_id, path, sha=None): + updated = original_anchor(config, line, repo_id, path, sha=sha) if after_anchor and repo_id == "web": raise SystemExit("power loss after anchor") return updated @@ -890,7 +899,7 @@ def read_only_git(repo, *args, **kwargs): self.assertEqual(set(recovered.outcomes.values()), {"committed"}) self.assertIn("web: push unknown", output.getvalue()) self.assertIn(f"dyro line merge {child.id} --into {parent.id} --push", output.getvalue()) - self.assertIn(f"git -C {line_repository_path(config, parent, 'web')} push origin {parent.branch}", output.getvalue()) + self.assertIn(f"git -C {line_repository_path(config, parent, 'web')} push origin refs/heads/{parent.branch}:refs/heads/{parent.branch}", output.getvalue()) self.assertIsNone(line_ops.find_unfinished_op(config, parent.id)) closed = line_ops.load_op(config, op["op_id"]) self.assertEqual(closed["phase"], "completed") diff --git a/tests/test_line_next_contract.py b/tests/test_line_next_contract.py index 177b360..d0c6557 100644 --- a/tests/test_line_next_contract.py +++ b/tests/test_line_next_contract.py @@ -186,11 +186,13 @@ def test_successful_push_anchor_survives_later_push_failure(self): target = replace(self.line, repositories=('api', 'web')) plans = tuple(_LineMergePlan(r, self.root / r, 'a'*40, 'b'*40) for r in target.repositories) def fake_git(path, *argv, **kwargs): + if argv[:2] == ('rev-parse', '--verify') and str(argv[-1]).startswith('refs/heads/'): + return Mock(code=0, stdout='c' * 40 + '\n', argv=argv) if argv[:2] == ('rev-parse', '--verify'): - return Mock(code=1, stdout='') + return Mock(code=1, stdout='', argv=argv) if argv[0] == 'push' and path.name == 'web': - return Mock(code=1, stdout='rejected') - return Mock(code=0, stdout='') + return Mock(code=1, stdout='rejected', argv=argv) + return Mock(code=0, stdout='', argv=argv) with patch('dyro.workspace._prepare_line_merge_plans', return_value=plans), patch('dyro.workspace.git', side_effect=fake_git), patch('dyro.workspace.git_read', return_value=Mock(code=0, stdout='c'*40)), patch('dyro.workspace._line_ledger'): with self.assertRaisesRegex(Exception, '推送 web 失败'): _merge_line_repositories_locked(self.config, target=target, source=self.line, diff --git a/tests/test_merge_push_refspec.py b/tests/test_merge_push_refspec.py new file mode 100644 index 0000000..6e87d4a --- /dev/null +++ b/tests/test_merge_push_refspec.py @@ -0,0 +1,149 @@ +"""Merge --push paths pin the branch tip and push that SHA with an explicit refspec.""" +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path +from unittest.mock import patch + +from dyro import line_ops, workspace +from dyro.config import load +from dyro.errors import DyroError +from dyro.tasks import answer_task, load_task, merge_task, review_task, run_task, task_template +from dyro.workspace import create_line, get_line, line_repository_path + +from .support import WorkspaceCase, executor_writes_receipt, publish_origin_branch, shell +from .test_line_merge_cross import _commit_text, _stdout +from .test_tasks import TaskTests + + +def _track_main(path: Path, branch: str) -> None: + shell("git", "config", "push.default", "upstream", cwd=path) + shell("git", "config", f"branch.{branch}.remote", "origin", cwd=path) + shell("git", "config", f"branch.{branch}.merge", "refs/heads/main", cwd=path) + + +def _bare_sha(bare: Path, branch: str) -> str: + return _stdout("git", "rev-parse", f"refs/heads/{branch}", cwd=bare) + + +def _allow_push(config): + return replace(config, policy=replace(config.policy, allow_push=True)) + + +class MergePushRefspecTests(WorkspaceCase): + def _published_parent_child(self): + bare = publish_origin_branch(self.anchor, "main") + publish_origin_branch(self.anchor, "feat/alpha") + config = load(self.root) + parent = create_line(config, line_id="alpha", branch="feat/alpha", base="main") + child = workspace.spawn_line(config, parent.id, "child") + return _allow_push(config), parent, child, bare + + def test_line_merge_into_push_pins_tip_despite_upstream(self) -> None: + config, parent, child, bare = self._published_parent_child() + _commit_text(line_repository_path(config, child, "api"), "child.txt", "child\n", "child") + parent_repo = line_repository_path(config, parent, "api") + _track_main(parent_repo, parent.branch) + main_before = _bare_sha(bare, "main") + + workspace.merge_line(config, child.id, parent.id, push=True) + + tip = _stdout("git", "rev-parse", f"refs/heads/{parent.branch}", cwd=parent_repo) + self.assertNotEqual(tip, main_before) + self.assertEqual(_bare_sha(bare, "main"), main_before) + self.assertEqual(_bare_sha(bare, parent.branch), tip) + self.assertEqual(get_line(config, parent.id).remote_anchors["api"], tip) + op_path = next((self.root / ".dyro/ops").glob("*.json")) + step = line_ops.load_op(config, op_path.stem)["repositories"]["api"]["steps"]["push"] + self.assertEqual(step["intent"]["target_sha"], tip) + self.assertEqual(step["result"]["new_tip"], tip) + + def test_line_sync_push_pins_child_tip_despite_upstream(self) -> None: + config, parent, child, bare = self._published_parent_child() + _commit_text(line_repository_path(config, parent, "api"), "parent.txt", "parent\n", "parent") + child_repo = line_repository_path(config, child, "api") + _track_main(child_repo, child.branch) + main_before = _bare_sha(bare, "main") + + workspace.sync_line(config, child.id, push=True) + + tip = _stdout("git", "rev-parse", f"refs/heads/{child.branch}", cwd=child_repo) + self.assertNotEqual(tip, main_before) + self.assertEqual(_bare_sha(bare, "main"), main_before) + self.assertEqual(_bare_sha(bare, child.branch), tip) + self.assertEqual(get_line(config, child.id).remote_anchors["api"], tip) + + def test_task_merge_push_pins_line_tip_despite_upstream(self) -> None: + bare = publish_origin_branch(self.anchor, "main") + publish_origin_branch(self.anchor, "feat/alpha") + main_before = _bare_sha(bare, "main") + config = load(self.root) + create_line(config, line_id="alpha", branch="feat/alpha", base="main") + task_path = config.task_specs_dir / "TASK-1" + task_path.mkdir(parents=True) + task_path.joinpath("task.toml").write_text( + task_template("TASK-1", "verify task lifecycle", "alpha", "api", "services/api").replace( + 'agent = "codex"', 'agent = "noop"' + ), + encoding="utf-8", + ) + task_path.joinpath("handoff.md").write_text("# handoff\n", encoding="utf-8") + task = load_task(config, "TASK-1") + with executor_writes_receipt(task.directory, "result: QUESTION\n"): + self.assertEqual(run_task(config, task), "waiting_answer") + task_repository = self.root / "worktrees/alpha/TASK-1/services/api" + _commit_text(task_repository, "README.md", "task change\n", "feat: task change") + task_path.joinpath("receipt.md").write_text("result: DONE\n", encoding="utf-8") + self.assertEqual(answer_task(config, task, "continue"), "review") + TaskTests._write_bound_review(task_path) + self.assertEqual(review_task(config, task), "done") + config = _allow_push(config) + line_repository = self.root / "versions/alpha/services/api" + _track_main(line_repository, "feat/alpha") + + merge_task(config, task, push=True) + + tip = _stdout("git", "rev-parse", "refs/heads/feat/alpha", cwd=line_repository) + self.assertNotEqual(tip, main_before) + self.assertEqual(_bare_sha(bare, "main"), main_before) + self.assertEqual(_bare_sha(bare, "feat/alpha"), tip) + self.assertEqual(get_line(config, "alpha").remote_anchors["api"], tip) + + def test_journaled_push_keeps_pinned_tip_when_branch_moves(self) -> None: + config, parent, child, bare = self._published_parent_child() + _commit_text(line_repository_path(config, child, "api"), "child.txt", "child\n", "child") + parent_repo = line_repository_path(config, parent, "api") + main_before = _bare_sha(bare, "main") + original_git = workspace.git + seen: dict[str, str] = {} + + def race_before_push(repo, *args, **kwargs): + if args[:1] == ("push",) and "--dry-run" not in args: + pinned = _stdout( + "git", "rev-parse", f"refs/heads/{parent.branch}", cwd=Path(repo) + ) + seen["tip"] = pinned + seen["refspec"] = args[2] + _commit_text(Path(repo), "race.txt", "race\n", "race") + return original_git(repo, *args, **kwargs) + + # The injected commit moves HEAD after the merge snapshot. The existing + # ledger check compares HEAD with that snapshot and raises. The push and + # the anchor are already recorded from the pinned tip. + with patch.object(workspace, "git", side_effect=race_before_push): + with self.assertRaisesRegex(DyroError, "committed 记录与 HEAD 不一致"): + workspace.merge_line(config, child.id, parent.id, push=True) + + tip = seen["tip"] + self.assertEqual(seen["refspec"], f"{tip}:refs/heads/{parent.branch}") + self.assertEqual(_bare_sha(bare, "main"), main_before) + self.assertEqual(_bare_sha(bare, parent.branch), tip) + self.assertNotEqual( + _stdout("git", "rev-parse", "HEAD", cwd=parent_repo), + tip, + ) + self.assertEqual(get_line(config, parent.id).remote_anchors["api"], tip) + op_path = next((self.root / ".dyro/ops").glob("*.json")) + step = line_ops.load_op(config, op_path.stem)["repositories"]["api"]["steps"]["push"] + self.assertEqual(step["intent"]["target_sha"], tip) + self.assertEqual(step["result"]["new_tip"], tip) diff --git a/tests/test_review_remediation.py b/tests/test_review_remediation.py index 20c3d68..eaa0578 100644 --- a/tests/test_review_remediation.py +++ b/tests/test_review_remediation.py @@ -79,7 +79,7 @@ def test_line_create_prints_publish_hint(self) -> None: output = StringIO() with redirect_stdout(output): main(["--root", str(self.root), "line", "create", "local-only", "--yes"]) - self.assertIn("git push -u origin feat/local-only", output.getvalue()) + self.assertIn("git push -u origin refs/heads/feat/local-only:refs/heads/feat/local-only", output.getvalue()) class SpawnBaseTests(WorkspaceCase):