From 4f2afcbb036514fcd877197c2206f30c12d4fec0 Mon Sep 17 00:00:00 2001 From: DandreYang <13072547+Dandre126@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:48:08 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=BA=BF):=20=E6=96=B0=E5=A2=9E=20dyro=20?= =?UTF-8?q?line=20push=20=E5=B9=B6=E6=9B=B4=E6=96=B0=E6=8E=A8=E9=80=81?= =?UTF-8?q?=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 顶层线此前没有 Dyro 自己的发布路径。新命令在 L1→L2 锁内预检全部 linked-worktree 仓库后,用显式同名 refspec 逐仓推送并设置上游, 锚点取推送前后一致的分支 tip;anchor-reference 仓库跳过。 PUSH_DISABLED_NOTE 同步提到 dyro line push;已 seed 的工作区需运行 dyro host seed --force。 --- CHANGELOG.md | 1 + .../line-aware-next-and-push-contract.md | 6 +- src/dyro/cli.py | 34 ++ src/dyro/config.py | 2 +- .../assets/dyro-control-plane/SKILL.md | 2 +- src/dyro/workspace.py | 97 +++- tests/test_line_next_contract.py | 3 + tests/test_line_push.py | 510 ++++++++++++++++++ 8 files changed, 646 insertions(+), 9 deletions(-) create mode 100644 tests/test_line_push.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a495c2..cd00d87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - 新增 `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` 中途失败回滚时留下本次新建分支的问题:之前用另一个基线重试会静默复用旧分支;现在回滚会删除本次新建的分支,原本就有的分支保持不动。 ## 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 3744f5a..2ff547e 100644 --- a/docs/designs/line-aware-next-and-push-contract.md +++ b/docs/designs/line-aware-next-and-push-contract.md @@ -191,7 +191,7 @@ JSON `next` 继续使用已经跑完 `doctor` 的那只 45 秒预算。增量 Gi `next` 的 `push_note`、工作区 overlay、开发线 overlay、控制面技能资产使用下面三段,字节级相同。`allow_push` 为 true 时也返回这段,不再返回空串。 ```text -Dyro 默认不执行 push。只有命令显式带 `--push` 且 `policy.allow_push = true` 时,Dyro 才会在本地合并成功之后逐仓执行 `git push origin <分支>`;多仓 push 不是原子操作。 +Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓执行 `git push origin <分支>`。多仓 push 不是原子操作。 开发线的期望上游是 `origin/`。本地还没有这条远端分支时,doctor 给出 WARN,工作区仍可打开;这不表示可以推送。 普通 `git push` 仍然能改远端,但不会写入 Dyro 的远端锚点,也不算通过门禁。 ``` @@ -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`。发布姿势仍是:人在终端执行 `git push -u origin `,或在 `policy.allow_push = true` 时对已有的 `line merge` / `line sync` / `task merge` 显式加上 `--push`。`spawn` 不发布。终端里的普通 `git push` 不写 `[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`。 ## 4. 延期 @@ -248,7 +248,7 @@ doctor 的 WARN 原文保持 `WARN :/: missing origin/` 1. **旧 overlay 用 WARN,不自动刷新。** doctor 只报告与当前模板的字节差异,并指向 `dyro host seed --force`。自动覆盖会改掉操作者改过的文件,也会把写操作放进 doctor。 2. **`next` 不做跨分支的提交图遍历。** ahead/behind 只用 doctor 已经挂到 `ReadBudget` 上的 ref。SHA 相同则写 0。不相同则最多 4 次本地 `rev-list`,否则 `null`。兄弟比较和父线提交差不进入 `next`。 -3. **不新增 `line publish`。** 见第 3 节末。`spawn` 不代跑首次发布。 +3. **发布走 `dyro line push`,不新增 `line publish`。** 见第 3 节末。`spawn` 不代跑首次发布。 4. **有锚点表的清单升到 schema_version 4;空表不升。** 防脱落靠两件事:字段进入 `Line` 并由 `_write_line` 写出;旧客户端因版本 4 无法解析而无法走旧的整文件重写。控制面 JSON 的 `schema_version` 保持 1。 第二轮的四项由第 2 节和第 3 节回答。这里不重开上面四条。 diff --git a/src/dyro/cli.py b/src/dyro/cli.py index 3185a20..ae9b839 100644 --- a/src/dyro/cli.py +++ b/src/dyro/cli.py @@ -262,6 +262,7 @@ merge_line, merge_line_from, merge_line_into_base, + push_line, observation_timeout_row, recover_line_merge, spawn_line, @@ -3142,6 +3143,25 @@ def cmd_line_add_repo(args: argparse.Namespace) -> None: ) +def cmd_line_push(args: argparse.Namespace) -> None: + config = _config(args) + _require_yes(args, "推送开发线分支") + line, pushed, skipped = push_line(config, args.line, dry_run=args.dry_run) + if args.dry_run: + linked = ", ".join( + repo_id + for repo_id in line.repositories + if line.storage_for(repo_id) == "linked-worktree" + ) + print(f"DRY RUN: 将推送 {line.kind} {line.id} 分支 {line.branch}:{linked}") + else: + for repo_id in pushed: + sha = line.remote_anchors[repo_id][:12] + print(f"已推送 {line.kind} {line.id} 仓库 {repo_id}:{sha}({line.branch})") + if skipped: + print(f"跳过 anchor-reference 仓库:{', '.join(skipped)}") + + def cmd_line_merge(args: argparse.Namespace) -> None: config = _config(args) if getattr(args, "recover", None) is not None: @@ -5438,6 +5458,20 @@ 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_push = line_sub.add_parser( + "push", + help="把开发线分支推到 origin 并设置上游(只推已提交内容;需 policy.allow_push)", + ) + line_push.add_argument("line", help="开发线 ID") + line_push.add_argument( + "--dry-run", + dest="dry_run", + action="store_true", + default=argparse.SUPPRESS, + help="只预检推送,不推送、不改清单(兼容全局 --dry-run)", + ) + line_push.add_argument("--yes", action="store_true") + line_push.set_defaults(func=cmd_line_push) line_merge = line_sub.add_parser( "merge", help="子线合入父线(--into)、跨线合入(--from)或 --recover 对账", diff --git a/src/dyro/config.py b/src/dyro/config.py index 1c8d138..6881363 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。只有命令显式带 `--push` 且 `policy.allow_push = true` 时,Dyro 才会在本地合并成功之后逐仓执行 `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` 的命令在本地合并成功后逐仓执行 `git push origin <分支>`。多仓 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 88ec5f6..6865965 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。只有命令显式带 `--push` 且 `policy.allow_push = true` 时,Dyro 才会在本地合并成功之后逐仓执行 `git push origin <分支>`;多仓 push 不是原子操作。 +Dyro 默认不执行 push。只有 `policy.allow_push = true` 时才推送:`dyro line push` 推开发线分支;显式带 `--push` 的命令在本地合并成功后逐仓执行 `git push origin <分支>`。多仓 push 不是原子操作。 开发线的期望上游是 `origin/`。本地还没有这条远端分支时,doctor 给出 WARN,工作区仍可打开;这不表示可以推送。 普通 `git push` 仍然能改远端,但不会写入 Dyro 的远端锚点,也不算通过门禁。 diff --git a/src/dyro/workspace.py b/src/dyro/workspace.py index cadac72..88989ce 100644 --- a/src/dyro/workspace.py +++ b/src/dyro/workspace.py @@ -945,9 +945,15 @@ def _require_push_allowed(config: Config, *, push: bool) -> None: def _require_line_worktrees( - config: Config, line: Line, *, clean: bool, label: str + config: Config, + line: Line, + *, + clean: bool, + label: str, + repositories: Iterable[str] | None = None, ) -> None: - for repo_id in line.repositories: + selected = line.repositories if repositories is None else tuple(repositories) + for repo_id in selected: target = line_repository_path(config, line, repo_id) inside = git(target, "rev-parse", "--is-inside-work-tree") if inside.code != 0 or inside.stdout.strip() != "true": @@ -1255,15 +1261,98 @@ def _merge_line_repositories_locked( ) -def record_remote_anchor(config: Config, line: Line, repo_id: str, path: Path) -> Line: +def record_remote_anchor( + config: Config, line: Line, repo_id: str, path: Path, *, sha: str | None = None +) -> Line: if line.storage_for(repo_id) != "linked-worktree": return line - head = require_ok(git_read(path, "rev-parse", "HEAD"), "读取已推送 HEAD").stdout.strip() + head = sha or require_ok(git_read(path, "rev-parse", "HEAD"), "读取已推送 HEAD").stdout.strip() updated = replace(line, remote_anchors={**line.remote_anchors, repo_id: head}) _write_line(config, updated) return updated +def push_line( + config: Config, line_id: str, *, dry_run: bool = False +) -> tuple[Line, list[str], list[str]]: + """Push one line branch to origin and record linked-worktree anchors. + + Holds L1 then L2 like ``line merge --push``. Every linked worktree is + preflighted before any push. Repositories are not atomic: a later failure + keeps anchors already recorded. Anchor-reference repositories are skipped. + Only committed history is pushed. + """ + _require_push_allowed(config, push=True) + 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) + linked = [r for r in line.repositories if line.storage_for(r) == "linked-worktree"] + skipped = [r for r in line.repositories if r not in linked] + if not linked: + raise DyroError(f"开发线 {line.id} 没有可推送的 linked-worktree 仓库") + with anchor_locks(config, linked): + _require_line_worktrees( + config, line, clean=False, label="开发线", repositories=linked + ) + for repo_id in linked: + path = line_repository_path(config, line, repo_id) + if _git_in_progress(path): + raise DyroError(f"{repo_id} 有进行中的 Git 操作,拒绝推送") + require_ok( + git(path, "push", "--dry-run", "origin", f"refs/heads/{line.branch}:refs/heads/{line.branch}"), + f"预检推送 {repo_id}", + ) + if dry_run: + return line, [], skipped + pushed: list[str] = [] + for repo_id in linked: + path = line_repository_path(config, line, repo_id) + branch_ref = f"refs/heads/{line.branch}" + tip = require_ok( + git_read(path, "rev-parse", "--verify", branch_ref), f"读取 {repo_id} 分支" + ).stdout.strip() + # Explicit same-name refspec: push.default=upstream must not redirect + # the destination. Never --force, --force-with-lease, or a "+" refspec. + result = git(path, "push", "-u", "origin", f"{branch_ref}:{branch_ref}") + if result.code != 0: + _line_ledger( + config, + line.id, + "line_push_failed", + repository=repo_id, + branch=line.branch, + pushed_repositories=pushed, + error=result.stdout.strip(), + ) + raise DyroError( + f"推送 {repo_id} 失败;已推送仓库:{', '.join(pushed) or '-'}" + f"\n{result.stdout.strip()}" + ) + pushed.append(repo_id) + try: + # Anchor the branch tip Git pushed, not HEAD (the worktree may + # have moved) and not the tracking ref (a narrow fetch refspec + # leaves it stale). A tip that moved during push is ambiguous. + after = require_ok( + git_read(path, "rev-parse", "--verify", branch_ref), f"读取 {repo_id} 分支" + ).stdout.strip() + if after != tip: + raise DyroError(f"推送期间 {line.branch} 从 {tip[:12]} 移动到 {after[:12]}") + line = record_remote_anchor(config, line, repo_id, path, sha=tip) + _line_ledger( + config, line.id, "line_push", + repository=repo_id, branch=line.branch, head=tip, + ) + except Exception as exc: + raise DyroError( + f"推送 {repo_id} 已发生,但远端锚点或 ledger 未记录完整:{exc};" + f"已推送仓库:{', '.join(pushed)}" + ) from exc + return line, pushed, skipped + def merge_line( config: Config, child_id: str, diff --git a/tests/test_line_next_contract.py b/tests/test_line_next_contract.py index 82f7c53..177b360 100644 --- a/tests/test_line_next_contract.py +++ b/tests/test_line_next_contract.py @@ -1,5 +1,6 @@ """First-wave line observations and push contract regression coverage.""" from dataclasses import replace +from pathlib import Path from unittest.mock import patch from dyro.config import load, Policy, push_policy_fields, PUSH_DISABLED_NOTE @@ -27,6 +28,8 @@ def test_contract_exact_and_enabled(self): self.assertEqual(fields['push_contract_version'], 1) for body in (render_workspace_overlay(), render_line_persona(line_id='core', branch='feat/core')): self.assertIn(PUSH_DISABLED_NOTE, body) + skill = Path(__file__).resolve().parents[1] / 'src/dyro/integrations/assets/dyro-control-plane/SKILL.md' + self.assertIn(PUSH_DISABLED_NOTE, skill.read_text(encoding='utf-8')) def test_manifest_anchors_roundtrip_and_old_schema_rejection(self): for parent in ('', 'parent'): diff --git a/tests/test_line_push.py b/tests/test_line_push.py new file mode 100644 index 0000000..30322cf --- /dev/null +++ b/tests/test_line_push.py @@ -0,0 +1,510 @@ +"""dyro line push publishes a line branch and records linked-worktree anchors.""" +from __future__ import annotations + +import json +from contextlib import redirect_stderr, redirect_stdout +from dataclasses import replace +from io import StringIO +from pathlib import Path +import subprocess +from unittest.mock import patch + +from dyro import line_ops, workspace +from dyro.cli import main +from dyro.config import load +from dyro.errors import DyroError +from dyro.events import read_events_fail_closed +from dyro.process import Result +from dyro.workspace import ( + create_line, + get_line, + line_repository_path, + push_line, + spawn_line, +) + +from .support import WorkspaceCase, publish_origin_branch, shell + + +def _stdout(*args: str, cwd: Path) -> str: + completed = subprocess.run( + args, + cwd=cwd, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + return completed.stdout.strip() + + +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) + shell("git", "commit", "-m", message, cwd=worktree) + return _stdout("git", "rev-parse", "HEAD", cwd=worktree) + + +def _ledger(config) -> list[dict]: + if not config.ledger_file.exists(): + return [] + return [ + json.loads(row) + for row in config.ledger_file.read_text(encoding="utf-8").splitlines() + if row.strip() + ] + + +class LinePushTests(WorkspaceCase): + def _enable_web(self, repo_id="web"): + web = self.root / f"repositories/{repo_id}" + web.mkdir(parents=True) + shell("git", "init", "-b", "main", cwd=web) + shell("git", "config", "user.name", "Test User", cwd=web) + shell("git", "config", "user.email", "test@example.com", cwd=web) + (web / "README.md").write_text("web\n", encoding="utf-8") + shell("git", "add", "README.md", cwd=web) + shell("git", "commit", "-m", "chore: initial", cwd=web) + config_path = self.root / "dyro.toml" + config_path.write_text( + config_path.read_text(encoding="utf-8") + + f'\n[repositories.{repo_id}]\npath = "repositories/{repo_id}"\nmount = "clients/{repo_id}"\n', + encoding="utf-8", + ) + return load(self.root), web + + def _remote(self, worktree: Path, branch: str) -> str: + return _stdout("git", "rev-parse", f"refs/remotes/origin/{branch}", cwd=worktree) + + def _bare(self, anchor: Path, branch: str) -> str: + bare = anchor.parent / f"{anchor.name}.origin.git" + return _stdout("git", "rev-parse", f"refs/heads/{branch}", cwd=bare) + + def _two_linked(self, *, allow_push: bool = False, commit: bool = True): + config, _web = self._enable_web() + publish_origin_branch(self.anchor, "feat/alpha") + publish_origin_branch(self.root / "repositories/web", "feat/alpha") + line = create_line( + config, + line_id="alpha", + branch="feat/alpha", + base="main", + repositories=("api", "web"), + ) + config = load(self.root) + paths = { + repo_id: line_repository_path(config, line, repo_id) + for repo_id in line.repositories + } + if commit: + for repo_id, path in paths.items(): + _commit_text(path, f"{repo_id}.txt", f"{repo_id}\n", f"feat: {repo_id}") + if allow_push: + config = replace(config, policy=replace(config.policy, allow_push=True)) + line = get_line(config, line.id) + return config, line, paths + + def _ops(self, config) -> list[Path]: + directory = config.root / ".dyro" / "ops" + if not directory.exists(): + return [] + return sorted(directory.glob("*.json")) + + def test_two_linked_repos_are_pushed_and_anchored(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + for path in paths.values(): + shell("git", "branch", "--unset-upstream", cwd=path) + events = read_events_fail_closed(config) + + updated, pushed, skipped = push_line(config, line.id) + + self.assertEqual(pushed, ["api", "web"]) + self.assertEqual(skipped, []) + heads = {} + for repo_id, path in paths.items(): + head = _stdout("git", "rev-parse", "HEAD", cwd=path) + heads[repo_id] = head + self.assertEqual( + _stdout("git", "rev-parse", "--abbrev-ref", "@{u}", cwd=path), + f"origin/{line.branch}", + ) + self.assertEqual(self._remote(path, line.branch), head) + anchor = self.anchor if repo_id == "api" else self.root / "repositories/web" + self.assertEqual(self._bare(anchor, line.branch), head) + self.assertEqual(dict(updated.remote_anchors), heads) + reloaded = get_line(config, line.id) + self.assertEqual(dict(reloaded.remote_anchors), heads) + manifest = (config.lines_state_dir / "alpha.toml").read_text(encoding="utf-8") + self.assertIn("schema_version = 4", manifest) + rows = [row for row in _ledger(config) if row["phase"] == "line_push"] + self.assertEqual([row["repository"] for row in rows], ["api", "web"]) + for row in rows: + self.assertEqual(row["task_id"], line.id) + self.assertEqual(row["branch"], line.branch) + self.assertEqual(row["head"], heads[row["repository"]]) + self.assertEqual(read_events_fail_closed(config), events) + self.assertEqual(self._ops(config), []) + + def test_allow_push_false_leaves_remote_refs(self) -> None: + config, line, paths = self._two_linked(allow_push=False) + before = {repo_id: self._remote(path, line.branch) for repo_id, path in paths.items()} + + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn("禁止 push", str(raised.exception)) + for repo_id, path in paths.items(): + self.assertEqual(self._remote(path, line.branch), before[repo_id]) + self.assertNotEqual(before[repo_id], _stdout("git", "rev-parse", "HEAD", cwd=path)) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + self.assertEqual(_ledger(config), []) + + def test_anchor_reference_repo_is_skipped(self) -> None: + config, web = self._enable_web() + publish_origin_branch(self.anchor, "feat/alpha") + shell("git", "checkout", "-b", "feat/alpha", cwd=web) + line = create_line( + config, + line_id="alpha", + branch="feat/alpha", + base="main", + repositories=("api", "web"), + storage_modes={"web": "anchor-reference"}, + ) + config = replace(load(self.root), policy=replace(load(self.root).policy, allow_push=True)) + api = line_repository_path(config, line, "api") + shell("git", "branch", "--unset-upstream", cwd=api) + head = _commit_text(api, "api.txt", "api\n", "feat: api") + + updated, pushed, skipped = push_line(config, line.id) + + self.assertEqual(pushed, ["api"]) + self.assertEqual(skipped, ["web"]) + self.assertEqual(updated.remote_anchors, {"api": head}) + self.assertNotIn("web", get_line(config, line.id).remote_anchors) + self.assertEqual(self._remote(api, line.branch), head) + self.assertEqual( + _stdout("git", "rev-parse", "--abbrev-ref", "@{u}", cwd=api), + f"origin/{line.branch}", + ) + web_remotes = _stdout("git", "remote", cwd=web) + self.assertNotIn("origin", web_remotes.split()) + + def test_preflight_failure_pushes_nothing(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + before = {repo_id: self._remote(path, line.branch) for repo_id, path in paths.items()} + shell( + "git", + "remote", + "set-url", + "origin", + str(self.root / "missing-web.git"), + cwd=paths["web"], + ) + + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn("预检推送 web", str(raised.exception)) + for repo_id, path in paths.items(): + self.assertEqual(self._remote(path, line.branch), before[repo_id]) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + manifest = (config.lines_state_dir / "alpha.toml").read_text(encoding="utf-8") + self.assertIn("schema_version = 2", manifest) + self.assertEqual(_ledger(config), []) + + def test_second_repo_push_failure_keeps_first_anchor(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + web_before = self._remote(paths["web"], line.branch) + api_head = _stdout("git", "rev-parse", "HEAD", cwd=paths["api"]) + real_git = workspace.git + + def fake_git(repo, *args, **kwargs): + if Path(repo) == paths["web"] and args == ("push", "-u", "origin", f"refs/heads/{line.branch}:refs/heads/{line.branch}"): + return Result(("git", "-C", str(repo), *args), 1, "rejected") + return real_git(repo, *args, **kwargs) + + with patch.object(workspace, "git", side_effect=fake_git): + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + message = str(raised.exception) + self.assertIn("web", message) + self.assertIn("api", message) + self.assertIn("rejected", message) + self.assertNotIn("本地合并已保留", message) + reloaded = get_line(config, line.id) + self.assertEqual(reloaded.remote_anchors, {"api": api_head}) + self.assertEqual(self._remote(paths["api"], line.branch), api_head) + self.assertEqual(self._remote(paths["web"], line.branch), web_before) + rows = _ledger(config) + self.assertEqual([row["phase"] for row in rows], ["line_push", "line_push_failed"]) + self.assertEqual(rows[0]["repository"], "api") + self.assertEqual(rows[0]["head"], api_head) + self.assertEqual(rows[1]["repository"], "web") + self.assertEqual(rows[1]["pushed_repositories"], ["api"]) + self.assertEqual(rows[1]["error"], "rejected") + + def test_dry_run_does_not_push_or_write(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + before = {repo_id: self._remote(path, line.branch) for repo_id, path in paths.items()} + events = read_events_fail_closed(config) + + updated, pushed, skipped = push_line(config, line.id, dry_run=True) + + self.assertEqual(pushed, []) + self.assertEqual(skipped, []) + self.assertEqual(updated.remote_anchors, {}) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + for repo_id, path in paths.items(): + self.assertEqual(self._remote(path, line.branch), before[repo_id]) + self.assertNotEqual(before[repo_id], _stdout("git", "rev-parse", "HEAD", cwd=path)) + self.assertEqual(_ledger(config), []) + self.assertEqual(read_events_fail_closed(config), events) + self.assertEqual(self._ops(config), []) + + def test_dry_run_runs_preflight_for_every_repo(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + shell("git", "remote", "set-url", "origin", str(self.root / "missing.git"), cwd=paths["web"]) + + with self.assertRaises(DyroError) as raised: + push_line(config, line.id, dry_run=True) + + self.assertIn("预检推送 web", str(raised.exception)) + + def test_dirty_worktree_still_pushes_committed_head(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + heads = {r: _stdout("git", "rev-parse", "HEAD", cwd=p) for r, p in paths.items()} + (paths["api"] / "untracked.txt").write_text("wip", encoding="utf-8") + (paths["web"] / "web.txt").write_text("edited", encoding="utf-8") + + updated, pushed, _ = push_line(config, line.id) + + self.assertEqual(pushed, ["api", "web"]) + self.assertEqual(dict(updated.remote_anchors), heads) + + def test_anchor_is_pushed_sha_even_if_worktree_moves(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + pushed_head = _stdout("git", "rev-parse", "HEAD", cwd=paths["api"]) + real_git = workspace.git + + def move_after_push(repo, *args, **kwargs): + result = real_git(repo, *args, **kwargs) + if args == ("push", "-u", "origin", f"refs/heads/{line.branch}:refs/heads/{line.branch}") and Path(repo) == paths["api"]: + shell("git", "checkout", "-q", "-b", "elsewhere", cwd=paths["api"]) + _commit_text(paths["api"], "moved.txt", "moved", "moved") + return result + + with patch.object(workspace, "git", side_effect=move_after_push): + updated, _, _ = push_line(config, line.id) + + self.assertNotEqual(_stdout("git", "rev-parse", "HEAD", cwd=paths["api"]), pushed_head) + self.assertEqual(updated.remote_anchors["api"], pushed_head) + self.assertEqual(self._bare(self.root / "repositories/api", line.branch), pushed_head) + + def test_branch_moving_during_push_refuses_anchor(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + real_git = workspace.git + + def commit_after_push(repo, *args, **kwargs): + result = real_git(repo, *args, **kwargs) + if args == ("push", "-u", "origin", f"refs/heads/{line.branch}:refs/heads/{line.branch}") and Path(repo) == paths["api"]: + _commit_text(paths["api"], "late.txt", "late", "late") + return result + + with patch.object(workspace, "git", side_effect=commit_after_push): + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn("推送期间", str(raised.exception)) + self.assertIn("已推送仓库:api", str(raised.exception)) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + + def test_narrow_fetch_refspec_still_anchors_pushed_tip(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + api = paths["api"] + stale = _stdout("git", "rev-parse", f"refs/remotes/origin/{line.branch}", cwd=api) + shell("git", "config", "remote.origin.fetch", "+refs/heads/main:refs/remotes/origin/main", cwd=api) + head = _stdout("git", "rev-parse", "HEAD", cwd=api) + self.assertNotEqual(stale, head) + + updated, _, _ = push_line(config, line.id) + + self.assertEqual(updated.remote_anchors["api"], head) + self.assertEqual(self._bare(self.root / "repositories/api", line.branch), head) + + def test_push_default_upstream_cannot_redirect_destination(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + api = paths["api"] + bare = self.root / "repositories/api" + publish_origin_branch(bare, "main") + main_before = self._bare(bare, "main") + shell("git", "config", "push.default", "upstream", cwd=api) + shell("git", "branch", "--set-upstream-to=origin/main", line.branch, cwd=api) + head = _stdout("git", "rev-parse", "HEAD", cwd=api) + + updated, _, _ = push_line(config, line.id) + + self.assertEqual(self._bare(bare, "main"), main_before) + self.assertEqual(self._bare(bare, line.branch), head) + self.assertEqual(updated.remote_anchors["api"], head) + self.assertEqual( + _stdout("git", "rev-parse", "--abbrev-ref", "@{u}", cwd=api), f"origin/{line.branch}" + ) + + def test_unfinished_merge_op_refuses_before_push(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + before = {repo_id: self._remote(path, line.branch) for repo_id, path in paths.items()} + op = line_ops.create_op( + config, + kind="merge", + subject_line_ids=(line.id,), + manifest_snapshot={"target": line.id}, + repos_ordered=line.repositories, + effective_options={"integration": "into"}, + ) + + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn("未完成操作", str(raised.exception)) + self.assertIn(op["op_id"], str(raised.exception)) + for repo_id, path in paths.items(): + self.assertEqual(self._remote(path, line.branch), before[repo_id]) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + self.assertEqual(_ledger(config), []) + + def test_unfinished_retire_op_refuses_before_push(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + op = line_ops.create_op( + config, + kind="retire", + subject_line_ids=(line.id,), + manifest_snapshot={"line": line.id}, + repos_ordered=line.repositories, + effective_options={}, + ) + + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn(op["op_id"], str(raised.exception)) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + self.assertEqual(_ledger(config), []) + + def test_wrong_branch_refuses_before_push(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + before = {repo_id: self._remote(path, line.branch) for repo_id, path in paths.items()} + shell("git", "checkout", "-b", "wrong", cwd=paths["web"]) + + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn("仓库分支错误", str(raised.exception)) + self.assertIn(line.branch, str(raised.exception)) + for repo_id, path in paths.items(): + self.assertEqual(self._remote(path, line.branch), before[repo_id]) + self.assertEqual(get_line(config, line.id).remote_anchors, {}) + self.assertEqual(_ledger(config), []) + + def test_anchor_record_failure_reports_push_already_happened(self) -> None: + config, line, paths = self._two_linked(allow_push=True) + api_head = _stdout("git", "rev-parse", "HEAD", cwd=paths["api"]) + web_head = _stdout("git", "rev-parse", "HEAD", cwd=paths["web"]) + real_record = workspace.record_remote_anchor + + def boom(config, line, repo_id, path, **kwargs): + if repo_id == "web": + raise RuntimeError("disk full") + return real_record(config, line, repo_id, path, **kwargs) + + with patch.object(workspace, "record_remote_anchor", side_effect=boom): + with self.assertRaises(DyroError) as raised: + push_line(config, line.id) + + self.assertIn("已发生", str(raised.exception)) + self.assertIn("web", str(raised.exception)) + self.assertIn("远端锚点或 ledger 未记录完整", str(raised.exception)) + self.assertIn("已推送仓库:api, web", str(raised.exception)) + self.assertIsInstance(raised.exception.__cause__, RuntimeError) + reloaded = get_line(config, line.id) + self.assertEqual(reloaded.remote_anchors, {"api": api_head}) + self.assertEqual(self._remote(paths["web"], line.branch), web_head) + self.assertEqual(self._bare(self.root / "repositories/web", line.branch), web_head) + rows = [row for row in _ledger(config) if row["phase"] == "line_push"] + self.assertEqual([row["repository"] for row in rows], ["api"]) + + def test_cli_requires_yes(self) -> None: + _, line, paths = self._two_linked(allow_push=False) + before = {repo_id: self._remote(path, line.branch) for repo_id, path in paths.items()} + toml = self.root / "dyro.toml" + toml.write_text( + toml.read_text(encoding="utf-8").replace( + "allow_push = false", "allow_push = true", 1 + ), + encoding="utf-8", + ) + stderr = StringIO() + with redirect_stderr(stderr): + with self.assertRaises(SystemExit) as raised: + main(["--root", str(self.root), "line", "push", line.id]) + self.assertEqual(raised.exception.code, 2) + self.assertIn("--yes", stderr.getvalue()) + for repo_id, path in paths.items(): + self.assertEqual(self._remote(path, line.branch), before[repo_id]) + self.assertEqual(get_line(load(self.root), line.id).remote_anchors, {}) + + for path in paths.values(): + shell("git", "branch", "--unset-upstream", cwd=path) + stdout = StringIO() + with redirect_stdout(stdout): + main(["--root", str(self.root), "line", "push", line.id, "--yes"]) + text = stdout.getvalue() + reloaded = get_line(load(self.root), line.id) + for repo_id, path in paths.items(): + head = _stdout("git", "rev-parse", "HEAD", cwd=path) + self.assertIn( + f"已推送 line {line.id} 仓库 {repo_id}:{head[:12]}({line.branch})", + text, + ) + self.assertEqual( + _stdout("git", "rev-parse", "--abbrev-ref", "@{u}", cwd=path), + f"origin/{line.branch}", + ) + self.assertEqual(self._remote(path, line.branch), head) + self.assertEqual(reloaded.remote_anchors[repo_id], head) + + def test_child_line_can_be_pushed(self) -> None: + publish_origin_branch(self.anchor, "feat/alpha") + config = load(self.root) + parent = create_line(config, line_id="alpha", branch="feat/alpha", base="main") + child = spawn_line(config, parent.id, "child") + self.assertEqual(child.id, "alpha_child") + self.assertEqual(child.branch, "feat/alpha_child") + path = line_repository_path(config, child, "api") + head = _commit_text(path, "child.txt", "child\n", "feat: child") + config = replace(load(self.root), policy=replace(load(self.root).policy, allow_push=True)) + events = read_events_fail_closed(config) + + updated, pushed, skipped = push_line(config, child.id) + + self.assertEqual(pushed, ["api"]) + self.assertEqual(skipped, []) + self.assertEqual(updated.remote_anchors, {"api": head}) + self.assertEqual( + _stdout("git", "rev-parse", "--abbrev-ref", "@{u}", cwd=path), + "origin/feat/alpha_child", + ) + self.assertEqual(self._remote(path, child.branch), head) + self.assertEqual(self._bare(self.anchor, child.branch), head) + manifest = (config.lines_state_dir / "alpha_child.toml").read_text(encoding="utf-8") + self.assertIn("schema_version = 4", manifest) + parent_manifest = (config.lines_state_dir / "alpha.toml").read_text(encoding="utf-8") + self.assertIn("schema_version = 2", parent_manifest) + self.assertEqual(get_line(config, parent.id).remote_anchors, {}) + self.assertEqual([event["kind"] for event in read_events_fail_closed(config)], ["spawn"]) + self.assertEqual(read_events_fail_closed(config), events) + rows = [row for row in _ledger(config) if row["phase"] == "line_push"] + self.assertEqual(rows[0]["task_id"], child.id) + self.assertEqual(rows[0]["head"], head) + self.assertEqual(self._ops(config), [])