Skip to content
31 changes: 31 additions & 0 deletions config/repo_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,37 @@ def get_auth_mode(repo: str) -> str:
return cast(str, auth_mode)


def assert_uniform_auth(repos: list[str]) -> None:
"""Require a single uniform auth mode across a run's repos (#3393).

Multi-repo pipelines v1 require every repo in one run to share one auth
mode — all ``bot`` or all ``user``. Mixed auth is where the gateway session
model gets genuinely complex and is deferred to a later phase (see issue
#3393 "Hard parts"). This is the canonical per-run auth-uniformity guard,
living beside :func:`get_auth_mode`; it is importable from both the gateway
and the orchestrator (``config/repo_config.py`` is bundled into both
images).

Args:
repos: Repositories in ``owner/name`` format. A single repo (or an
empty list) is trivially uniform.

Raises:
ValueError: when the repos resolve to more than one auth mode. The
message names the offending repos grouped by mode so the operator
can see exactly which side diverges.
"""
modes: dict[str, list[str]] = {}
for repo in repos:
modes.setdefault(get_auth_mode(repo), []).append(repo)
if len(modes) > 1:
groups = "; ".join(f"{mode}: {', '.join(sorted(rs))}" for mode, rs in sorted(modes.items()))
raise ValueError(
"Mixed auth modes across the pipeline's repos are not supported in v1 "
"(a run must be uniformly 'bot' or 'user'). Diverging repos — " + groups + "."
)


def is_user_mode_repo(repo: str) -> bool:
"""
Check if a repository is configured to use user mode.
Expand Down
2 changes: 1 addition & 1 deletion docs/guides/sdlc-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -961,7 +961,7 @@ All three keys (`tests_globs`, `code_globs`, `docs_globs`) are optional. Unset k

The conflict-resolver role's allow list is the union of all three glob lists, so any of these keys also widens what the conflict-resolver can write.

**Security boundary:** Security-relevant blocklists (`.egg-state/contracts/`, `.github/`) are hard-coded and cannot be relaxed by repo config. Only the language-convention globs are configurable.
**Security boundary:** Security-relevant blocklists (the whole `.egg-state/` tree, `.github/`) are hard-coded and cannot be relaxed by repo config. Only the language-convention globs are configurable.

The orchestrator pre-resolves the override at spawn time and passes it to sandbox containers via the `EGG_PIPELINE_REPO_PATTERNS_JSON` environment variable. The gateway reads the override directly from `repositories.yaml` at push time. Validation behavior differs slightly between paths: `config/repo_config.py::get_repo_role_patterns` (the orchestrator/gateway path that reads `repositories.yaml`) emits a WARNING log on invalid root type, unknown keys, non-list values, and non-string list entries; `shared/egg_restrictions/patterns.py::load_repo_pattern_override` (the env-var path used inside the sandbox) only logs on invalid JSON and silently filters the rest. In practice the operator still sees diagnostic warnings at orchestrator spawn time because the orchestrator runs `get_repo_role_patterns` before serializing into the env var.

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/agent-roles.md
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ The gateway's `get_attributed_changed_files_in_push()` walks the unpushed range

For the exact allowed and blocked patterns per role, see `shared/egg_restrictions/patterns.py` (canonical source). The gateway imports from this shared package for push-time validation.

**Per-repo overrides (#2528):** The test/code/docs glob lists described above are the *defaults*. Repositories with non-Python file conventions (Go, JS/TS, etc.) can override them via a `role_patterns:` block in `repositories.yaml`. Only the language-convention globs (`tests_globs`, `code_globs`, `docs_globs`) are configurable; security-relevant blocklists (`.egg-state/contracts/`, `.github/`) are hard-coded and cannot be relaxed. See [Per-Repository Role Patterns](../guides/sdlc-pipeline.md#per-repository-role-patterns) for the configuration schema.
**Per-repo overrides (#2528):** The test/code/docs glob lists described above are the *defaults*. Repositories with non-Python file conventions (Go, JS/TS, etc.) can override them via a `role_patterns:` block in `repositories.yaml`. Only the language-convention globs (`tests_globs`, `code_globs`, `docs_globs`) are configurable; security-relevant blocklists (the whole `.egg-state/` tree, `.github/`) are hard-coded and cannot be relaxed. See [Per-Repository Role Patterns](../guides/sdlc-pipeline.md#per-repository-role-patterns) for the configuration schema.

## Per-Agent Git Identity

Expand Down
182 changes: 180 additions & 2 deletions gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -4532,6 +4532,176 @@ def gh_list_open_prs() -> tuple[Response, int] | Response:
return make_success("Open PR list complete", {"prs": prs})


@app.route("/api/v1/gh/pr/merge_state", methods=["POST"])
@require_launcher_auth
def gh_pr_merge_state() -> tuple[Response, int] | Response:
"""Control-plane PR merge-state read: return ``state`` + ``mergedAt`` (#3393).

An **orchestrator-only** route gated by ``@require_launcher_auth``
rather than ``@require_session_auth`` — the caller is the control
plane (the orchestrator holds the launcher secret), not a sandboxed
agent. It is the read half of the cq-1 cross-repo merge-sequencing
gate: the orchestrator polls an upstream slice PR's merge state to
decide when to mark a downstream draft PR ready. Modelled on
``gh_find_open_pr`` / ``gh_list_open_prs`` (#2925): the orchestrator
is the server that manages pipelines, not an ``AgentRole``, so it
authenticates as the control plane and uses a purpose-built,
fixed-argv read-only endpoint (no general gh surface here).

Merge detection deliberately keys off the PR's ``mergedAt`` /
``state`` — NOT head-SHA equality: a squash/rebase merge produces a
merge-commit SHA that differs from the PR head, so a SHA comparison
would misfire (#3393 task-5-1 pin (a)).

Request body:
{"repo": "owner/name", "pr_number": <int>}

Returns:
``{"state": "OPEN|CLOSED|MERGED"|null, "mergedAt": "<ISO-8601>"|null}``.
"""
data = request.get_json()
if not data or not isinstance(data, dict):
return make_error("Invalid body: must be a JSON object")

repo = data.get("repo")
if not isinstance(repo, str) or not repo.strip():
return make_error("Missing or invalid repo: must be a non-empty string")
repo = repo.strip()
if OWNER_REPO_PATTERN.match(repo) is None:
return make_error("Invalid repo: must be 'owner/name'")

# ``bool`` is a subclass of ``int``; reject it explicitly so ``True``
# cannot slip through as ``pr_number=1``.
pr_number = data.get("pr_number")
if isinstance(pr_number, bool) or not isinstance(pr_number, int) or pr_number < 1:
return make_error("Invalid pr_number: must be a positive integer")

args = [
"pr",
"view",
str(pr_number),
"--repo",
repo,
"--json",
"state,mergedAt",
]

auth_mode = get_auth_mode(repo)
github = get_github_client(mode=auth_mode)
result = github.execute(args, timeout=60, mode=auth_mode)

if not result.success:
stderr_excerpt = (result.stderr or "")[:500]
audit_log(
"gh_pr_merge_state_failed",
"gh_pr_merge_state",
success=False,
details={"repo": repo, "pr_number": pr_number, "stderr": stderr_excerpt},
)
return make_error(
f"Command failed: {result.stderr}",
status_code=500,
details=result.to_dict(),
)

state_val: Any = None
merged_at: Any = None
stdout = (result.stdout or "").strip()
if stdout:
try:
parsed = json.loads(stdout)
except ValueError, TypeError:
parsed = None
if isinstance(parsed, dict):
state_val = parsed.get("state")
merged_at = parsed.get("mergedAt")

audit_log(
"gh_pr_merge_state",
"gh_pr_merge_state",
success=True,
details={"repo": repo, "pr_number": pr_number, "state": state_val},
)
return make_success(
"PR merge-state lookup complete",
{"state": state_val, "mergedAt": merged_at},
)


@app.route("/api/v1/gh/pr/ready", methods=["POST"])
@require_launcher_auth
def gh_pr_ready() -> tuple[Response, int] | Response:
"""Control-plane PR draft→ready transition: wrap ``gh pr ready`` (#3393).

An **orchestrator-only** route gated by ``@require_launcher_auth`` —
the write half of the cq-1 cross-repo merge-sequencing gate. When the
upstream slice PR merges, the orchestrator transitions the downstream
cross-repo dependent PR from draft to ready. Like the sibling
control-plane PR routes (``gh_find_open_pr`` / ``gh_list_open_prs``),
the caller is the control plane, so it authenticates with the
launcher secret and this route constructs a **fixed, narrow argv**
server-side (``pr ready <n> --repo <repo>``) — there is no arbitrary
gh-command surface on the launcher-auth path, only this single
ready-transition. ``pr ready`` is already on ``ALLOWED_GH_COMMANDS``
(github_client.py) so the underlying ``gh`` invocation re-validates
through the same allowlist floor.

Request body:
{"repo": "owner/name", "pr_number": <int>}

Returns:
``{"stdout": "<gh output>"}`` on success.
"""
data = request.get_json()
if not data or not isinstance(data, dict):
return make_error("Invalid body: must be a JSON object")

repo = data.get("repo")
if not isinstance(repo, str) or not repo.strip():
return make_error("Missing or invalid repo: must be a non-empty string")
repo = repo.strip()
if OWNER_REPO_PATTERN.match(repo) is None:
return make_error("Invalid repo: must be 'owner/name'")

pr_number = data.get("pr_number")
if isinstance(pr_number, bool) or not isinstance(pr_number, int) or pr_number < 1:
return make_error("Invalid pr_number: must be a positive integer")

args = [
"pr",
"ready",
str(pr_number),
"--repo",
repo,
]

auth_mode = get_auth_mode(repo)
github = get_github_client(mode=auth_mode)
result = github.execute(args, timeout=60, mode=auth_mode)

if not result.success:
stderr_excerpt = (result.stderr or "")[:500]
audit_log(
"gh_pr_ready_failed",
"gh_pr_ready",
success=False,
details={"repo": repo, "pr_number": pr_number, "stderr": stderr_excerpt},
)
return make_error(
f"Failed to mark PR ready: {result.stderr}",
status_code=500,
details=result.to_dict(),
)

audit_log(
"gh_pr_ready",
"gh_pr_ready",
success=True,
details={"repo": repo, "pr_number": pr_number},
)
return make_success("PR marked ready", {"stdout": result.stdout})


# =============================================================================
# Jira REST Endpoints
# =============================================================================
Expand Down Expand Up @@ -7763,8 +7933,16 @@ def worktree_create() -> tuple[Response, int] | Response:
assigned_branch=assigned_branch,
repo_slug=repo,
)
# Translate container path to host path for egg launcher mount sources
worktrees[repo_name] = translate_to_host_path(str(info.worktree_path))
# Translate container path to host path for egg launcher mount sources.
# Key by the full ``owner/repo`` slug (#3393 slice-3, operator
# ruling #6) so two repos with the same short name under different
# owners (``ownerA/foo`` vs ``ownerB/foo``) no longer collide on a
# single map entry. When the caller passed a bare repo name (no
# ``/``), ``repo`` equals ``repo_name`` so bare-name callers are
# unaffected. The on-disk worktree directory (and the container
# mount target) stays the bare ``repo_name`` — only the map KEY
# carries the owner prefix.
worktrees[repo] = translate_to_host_path(str(info.worktree_path))
except (ValueError, RuntimeError) as e:
# Capture full traceback so operators can diagnose without
# re-instrumenting the gateway. See #2186.
Expand Down
Loading