Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,9 @@ version.
Loop-zero serves internal projects only and does not target tamper resistance for outside users.
Freeze new work on Codex evidence projections. Simplify or delete them when they break or obstruct delivery.

- One primary and at most one delta per PR. The delta reads only
changes since the primary; unresolved primary findings still count under
Blockers.
- One primary and at most one delta per PR. After a base merge, the delta covers first-parent topic changes and
edits to each automatic remerge. The reviewed commit must be on the first-parent history, and merged parents
must come from the verified base. Unresolved primary findings still count under Blockers.
- Default: one writing model family per PR, including delegates and repairs;
another may advise read-only and review independently. Before committing
imported work, record every actual writing delegate in truthful
Expand Down
16 changes: 12 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,11 @@ The CLI also writes a head-bound checks receipt and saved review output in
`.loopzero/` for local readiness and reposting. They do not form a second authoritative delivery history; new Codex native audit
receipts have the restricted retention requirement described below. Local readiness requires
its current successful check receipt; hosted eligibility evaluates GitHub
review evidence using trusted base configuration. Losing local artifacts may
require rerunning checks or review, and never creates a hosted approval.
review evidence using trusted base configuration. Local readiness and merge fetch
the configured origin base once at startup before loading its publisher policy.
A receipt bound to the base may require a new check after that base advances.
Losing local artifacts may require rerunning checks or review, and never creates
a hosted approval.
Saved runner artifacts also retain the repository, PR and actual request publisher
before publication. A lost POST reply triggers a read-only reconciliation bounded
by one 30-second transport deadline, with no read retries. Recovery regenerates
Expand Down Expand Up @@ -76,8 +79,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
source sandbox. It inventories Git object stores only when alternates may be
present. Its simple-command preflight catches missing local scripts,
prepares recognized uv dependency groups offline in that sandbox and prints
progress before each command, metadata-only stage heartbeats every 30 seconds
(including silent children), and exit code/duration immediately after each stage.
progress before each command, a metadata-only heartbeat after 30 seconds and every
five minutes thereafter, and exit code/duration immediately after each stage.
Heartbeats stop on completion or cancellation and never supply a verdict.
Local stages drain merged child output and retain a bounded diagnostic tail.
Trusted-base commands remain authoritative;
Expand All @@ -103,6 +106,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
the PR-wide cap of one primary and one delta across head rewrites, and the
[owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception),
which changes neither the selector nor the budget.
The delta requires the reviewed commit on the current head's first-parent
history and verifies merged parents against the live configured base. The
runner receives topic patches in first-parent order and the difference
between each automatic remerge and its recorded tree. Isolated Git verifies
the history and builds the patch, excluding unrelated base changes.
5. `ready` derives readiness from the current head, its check receipt, an eligible review at that
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
Expand Down
4 changes: 3 additions & 1 deletion src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]:
}
deadline = time.monotonic() + _TREE_SECONDS

def git(*args: str, command_env: dict[str, str] = env) -> str:
def git(*args: str, command_env: dict[str, str] = env, preserve_newlines: bool = False) -> str:
with (root / "output").open("w+b") as output:
process = subprocess.Popen(
[sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES),
Expand Down Expand Up @@ -353,6 +353,8 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish
output.seek(0)
result = output.read(_TREE_OUTPUT + 1)
_require(len(result) <= _TREE_OUTPUT, "Git object/output bound exceeded")
if preserve_newlines:
return result.decode("utf-8", errors="surrogateescape")
return result.decode().strip()
finally:
if process.poll() is None:
Expand Down
94 changes: 55 additions & 39 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,15 @@ def _repo_root(wt: Path) -> Path:

def _load_config(
args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None,
refresh: bool = False,
) -> Config:
path = args.config or root / "workflow.toml"
if not pin_checks:
return config_mod.load(path)
if args.config:
print("checks are unpinned because --config was provided")
return config_mod.load(path)
config = config_mod.load_trusted(root, previous=previous)
config = config_mod.load_trusted(root, previous=previous, refresh=refresh)
if args.command == "check":
if not config.checks:
raise config_mod.ConfigError(
Expand All @@ -147,7 +148,9 @@ def _load_config(

def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Path, Config]:
wt = _toplevel()
return wt, _load_config(args, wt, pin_checks=pin_checks)
return wt, _load_config(
args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"},
)


def _is_ancestor(wt: Path, sha: str, head: str) -> bool:
Expand Down Expand Up @@ -626,6 +629,20 @@ def cmd_start(args: argparse.Namespace) -> int:
return 0


def _check_failure_preview(tail: str, limit: int = 1536) -> str:
if len(tail.encode()) <= limit:
return tail
edge = limit // 8
lines = (line.encode() for line in tail.splitlines())
preview = b"\n".join(
line if len(line) <= 2 * edge else line[:edge] + b" [...] " + line[-edge:]
for line in lines
)
if len(preview) > limit:
preview = b"[...]\n" + preview[6 - limit:]
return preview.decode(errors="ignore")


def cmd_check(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
if not config.checks:
Expand All @@ -639,32 +656,30 @@ def cmd_check(args: argparse.Namespace) -> int:
except sandbox.SandboxUnavailable as exc:
print(f"sandbox unavailable: {exc}", file=sys.stderr)
return 2
shortened = False
for result in report.results:
if result.exit_code != 0:
print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr)
tail = _proc.tail(result.tail)
print(tail, file=sys.stderr)
preview = _check_failure_preview(tail)
shortened |= preview != tail
print(preview, file=sys.stderr)
if not config.network and (result.command.startswith("uv sync --offline --locked")
or OFFLINE_FAILURE_RE.search(tail)):
env = {
**sandbox.SANDBOX_ENV,
**_proc.build_env(config.env_allowlist),
**dict(config.env),
}
env = sandbox.SANDBOX_ENV | _proc.build_env(config.env_allowlist) | dict(config.env)
print(
"\nThe sandbox has no network because `[checks] network = false`; "
f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. "
"To prepare offline, run UV_CACHE_DIR=<effective-cache> uv sync --group dev "
"(use the groups your checks require) on the host, or the same commands, so the cache "
"under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to "
"that cache.",
file=sys.stderr,
"Run UV_CACHE_DIR=<effective-cache> uv sync --group dev on the host "
"(use the required groups) so the cache under `[checks] writable` is warm, "
"or set `[checks] env` UV_CACHE_DIR to a warm cache.", file=sys.stderr,
)
current_head = _save_report(wt, report)
if current_head is not None:
if (current_head := _save_report(wt, report)) is not None:
print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}",
file=sys.stderr)
return 1
if shortened:
print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr)
if report.ok and report.settings_sha256 is None:
print("check stages passed but the receipt is unverified; rerun loopzero check from the task "
"worktree with a stable, readable configured runner before running ready", file=sys.stderr)
Expand Down Expand Up @@ -835,11 +850,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
# Exact read-back above may confirm an older published note; a new post needs the current form.
if result.fallback and not _published_fallback(result.fallback, candidates, excluded):
raise CliError("saved fallback note is not in the published form; run without --repost")
allowed, _ = _decide_kind(
allowed, reviewed = _decide_kind(
_pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head
)
if allowed != kind:
raise CliError("saved review kind differs from the remaining review budget")
_delta_patch(wt, config, reviewed, head, pr.number)
else:
if args.model is None and args.effort is None and _has_recoverable_review(
wt, config, head, kind, publication_context,
Expand Down Expand Up @@ -1035,12 +1051,27 @@ def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResul
return True


def _delta_merge_recovery(wt: Path, reviewed: str, merge: str) -> str:
pre_merge = _git(wt, "rev-parse", f"{merge}^1")
if not _is_ancestor(wt, reviewed, pre_merge):
return f"replay the fixes on the reviewed head {reviewed[:12]}"
return (f"save the current tip on a backup branch, use `git reset --hard {pre_merge}`, "
"and cherry-pick any later fixes from the backup")
def _delta_patch(wt: Path, config: Config, since: str | None, head: str, number: int | None) -> bytes:
if since is None:
return b""
if not _is_ancestor(wt, since, head):
raise CliError(
f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original tip with `git reflog`. "
"Back up your branch, reset to that tip and replay later fixes. To publish the restored head, "
f"run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR"
)
if not worktree.merges_since(wt, since):
return worktree.diff_since(wt, since)
patch = (eligibility.base_merge_material(config.repo, number, since, head, config.base_branch, clean=False)
if number is not None else None)
if patch is None:
raise CliError(
f"could not verify merge history: {since[:12]} must be on the first-parent history and "
f"merged parents must come from {config.base_branch}. Save your work, then replay the fixes "
f"on the reviewed head {since[:12]}, including resolution edits. Push with `loopzero pr` "
"and run `loopzero review`, or open a new PR"
)
return patch


def _run_review(
Expand All @@ -1050,23 +1081,8 @@ def _run_review(
) -> ReviewResult:
lineage_base = _primary_base(wt, config)
since = reviewed if kind == "delta" else lineage_base
if kind == "delta" and not _is_ancestor(wt, since, head):
raise CliError(
f"reviewed head {since[:12]} is not an ancestor of this branch. Find the original "
"branch tip with `git reflog`. Save the current tip on a backup branch, then use "
"`git reset --hard <original-tip>` and replay any later fixes. To publish the restored "
f"head, run `loopzero pr`, then `loopzero review` before merging {config.base_branch}, or open a new PR "
"from the current branch"
)
if kind == "delta" and (merges := worktree.merges_since(wt, since)):
recovery = _delta_merge_recovery(wt, since, merges[0])
raise CliError(
f"merge commit {merges[0][:12]} since the reviewed head {since[:12]} would put the "
f"merged-in changes in the delta material. To recover, {recovery}. "
f"To publish the recovered head, run `loopzero pr`, then `loopzero review` "
f"before merging {config.base_branch} again"
)
patch = worktree.diff_since(wt, since)
patch = (_delta_patch(wt, config, since, head, publication[1] if publication else None)
if kind == "delta" else worktree.diff_since(wt, since))
diff = runners.render_patch(patch)
task = worktree.task_text(wt)
authors = runners.author_families(wt, head, lineage_base)
Expand Down
19 changes: 14 additions & 5 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,21 @@ def _has_replacement_refs(common_dir: Path) -> bool:
return b" refs/replace/" in packed


def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]:
def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, refresh: bool) -> tuple[Config, str]:
source = f"origin/{branch}:workflow.toml"
hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override."
ref = f"refs/remotes/origin/{branch}"
if refresh:
fetched = _proc.run(
["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules",
"--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if fetched.exit_code != 0:
raise ConfigError(f"could not refresh origin/{branch}. {hint}")
directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else []
resolved = _proc.run(
["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"],
["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if resolved.exit_code != 0:
Expand All @@ -140,7 +149,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu
raise ConfigError(f"{source}: {exc}. {hint}") from None


def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config:
def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> Config:
"""Select delivery policy using Git's origin default and its trusted workflow."""
prefix = "refs/remotes/origin/"
default = _proc.run(
Expand All @@ -154,10 +163,10 @@ def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config:
"or supply --config for bootstrap or an override."
)
branch = ref.removeprefix(prefix)
policy, revision = _remote_workflow(worktree, branch, previous)
policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh)
if policy.base_branch == branch:
return replace(policy, trusted_base_revision=revision)
base, revision = _remote_workflow(worktree, policy.base_branch, previous)
base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh)
if base.base_branch != policy.base_branch:
raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config")
return replace(base, trusted_base_revision=revision)
Expand Down
Loading
Loading