Skip to content
Merged
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
5 changes: 4 additions & 1 deletion examples/land/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,10 @@ the first stage.

`mergePolicy.mode` values `approval` and `auto` pass validation; a run
refuses `approval` (`declined`). `auto` needs the repository grant's write
token and `gh` on the runner.
token on stages E and F (Cloud gives A-D a read grant) and `gh` on the runner.
Stage F lands the squash in one atomic push that also deletes the run's land
ref, leased on the pinned head, so a superseded run can never land; the write
grant must therefore be allowed to delete `land/*` branches.

A finding's id is its source, its file and its normalized title.
relay-desktop's `report.json` has no id field. Its verifier moves lines and
Expand Down
23 changes: 23 additions & 0 deletions examples/land/evidence/push-fence/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Stage F push fence: real-Git evidence

`fence-race.py` builds a bare remote and a clone in a temp directory, and adds a
`pre-receive` hook that moves `refs/heads/land/run` to a newer commit *after*
the advertisement and *before* the update: a newer submission arriving while
a superseded stage F pushes.

- `noop`: the previous fence (`<pinned>:refs/heads/land/run` with
`--force-with-lease`). Git drops the up-to-date ref from the transaction, so
the old squash lands on `main` (exit 0). This is the review finding on #695.
- `delete`: the current fence (`:refs/heads/land/run` with the lease). The
delete is a real update carrying the pinned old value, checked inside the
atomic transaction: the push fails and `main` is untouched.
- `delete`, no race: the squash lands and the land ref is deleted.

Run: `python3 -I examples/land/evidence/push-fence/fence-race.py` (local git only).

## Permission the fence needs

Stage F deletes the land ref as part of the push, so the auto write grant must
allow deleting `land/*` branches (no branch rule may block their deletion). A
`--dry-run` push cannot prove branch rules, so the preflight does not check
this; a rule that blocks it ends F `needs_human` with GitHub's rejection.
42 changes: 42 additions & 0 deletions examples/land/evidence/push-fence/fence-race.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from pathlib import Path
import subprocess, tempfile, json, os, sys, shlex
SP = sys.argv[1] if len(sys.argv) > 1 else tempfile.mkdtemp(prefix="land-push-fence-")
env = os.environ.copy()
env.update({'GIT_AUTHOR_NAME':'F','GIT_AUTHOR_EMAIL':'f@example.test','GIT_COMMITTER_NAME':'F','GIT_COMMITTER_EMAIL':'f@example.test','GIT_CONFIG_GLOBAL':'/dev/null'})
def trial(variant, race=True):
root = Path(tempfile.mkdtemp(prefix=f'fence-{variant}-', dir=SP))
remote = root/'remote.git'; local = root/'local'; local.mkdir()
def run(*a, cwd=local, input=None):
return subprocess.check_output(['git', *a], cwd=cwd, env=env, input=input, text=True, stderr=subprocess.STDOUT).strip()
run('init', '--bare', '-q', str(remote)); run('init', '-q', '-b', 'main')
(local/'f').write_text('base\n'); run('add', '.'); run('commit', '-qm', 'base'); base = run('rev-parse', 'HEAD')
(local/'f').write_text('pinned\n'); run('commit', '-qam', 'pinned'); pinned = run('rev-parse', 'HEAD'); tree = run('rev-parse', 'HEAD^{tree}')
squash = run('commit-tree', tree, '-p', base, input='squash\n')
(local/'f').write_text('newer\n'); run('commit', '-qam', 'newer'); newer = run('rev-parse', 'HEAD')
run('remote', 'add', 'origin', str(remote))
run('push', '-q', 'origin', f'{base}:refs/heads/main', f'{pinned}:refs/heads/land/run', f'{newer}:refs/heads/successor-source')
# Capture the ref updates the server receives on every trial; with `race`, a
# newer submission also moves the land ref after the advertisement, before the update.
hook = remote/'hooks/pre-receive'
body = '#!/bin/sh\ncat > ' + shlex.quote(str(root/'cmds.txt')) + '\n'
if race:
body += ('env -u GIT_QUARANTINE_PATH -u GIT_OBJECT_DIRECTORY -u GIT_ALTERNATE_OBJECT_DIRECTORIES git --git-dir='
+ shlex.quote(str(remote)) + ' update-ref refs/heads/land/run ' + newer + '\n')
hook.write_text(body)
hook.chmod(0o755)
lease = f'--force-with-lease=refs/heads/land/run:{pinned}'
if variant == 'noop':
cmd = ['git', 'push', '--atomic', lease, 'origin', f'{squash}:refs/heads/main', f'{pinned}:refs/heads/land/run']
else:
cmd = ['git', 'push', '--atomic', lease, 'origin', f'{squash}:refs/heads/main', ':refs/heads/land/run']
r = subprocess.run(cmd, cwd=local, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
main = run('--git-dir='+str(remote), 'rev-parse', 'refs/heads/main')
land = subprocess.run(['git', '--git-dir='+str(remote), 'rev-parse', '-q', '--verify', 'refs/heads/land/run'], env=env, text=True, stdout=subprocess.PIPE).stdout.strip()
sent = (root/'cmds.txt').read_text() if (root/'cmds.txt').exists() else ''
return {'variant': variant, 'race': race, 'exit': r.returncode, 'mainGotSquash': main == squash,
'landRefNow': 'newer' if land == newer else ('deleted' if not land else 'pinned'),
'landRefInTransaction': 'refs/heads/land/run' in sent, 'out': r.stdout.strip().splitlines()[-1:] }
print(subprocess.check_output(['git', '--version'], text=True).strip())
for v in ('noop', 'delete'):
print(json.dumps(trial(v, race=True)))
print(json.dumps(trial('delete', race=False)))
4 changes: 4 additions & 0 deletions examples/land/evidence/push-fence/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
git version 2.50.1 (Apple Git-155)
{"variant": "noop", "race": true, "exit": 0, "mainGotSquash": true, "landRefNow": "newer", "landRefInTransaction": false, "out": [" 00b3772..e3d0dfa e3d0dface811192c00a495144d8824d25ac1dd36 -> main"]}
{"variant": "delete", "race": true, "exit": 1, "mainGotSquash": false, "landRefNow": "newer", "landRefInTransaction": true, "out": ["error: failed to push some refs to '<tmp>/remote.git'"]}
{"variant": "delete", "race": false, "exit": 0, "mainGotSquash": true, "landRefNow": "deleted", "landRefInTransaction": true, "out": [" 0627171..c008e25 c008e25793dc225242ab98174f7542c40181010e -> main"]}
58 changes: 48 additions & 10 deletions examples/land/land.flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ import { flow, type Ctx } from '@relayflows/surface';

class NeedsHuman extends Error {}

/** The stages that push in auto mode; Cloud grants contents:write to these only. */
export const WRITE_STAGES: ReadonlySet<string> = new Set(['E', 'F']);

export const shellWord = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;

// ---------------------------------------------------------------- land.config
Expand Down Expand Up @@ -850,7 +853,30 @@ async function merge(f: Ctx, r: Run): Promise<StageResult> {
const ident = 'GIT_AUTHOR_NAME="${LAND_AUTHOR_NAME:-Agent Relay Land}" GIT_AUTHOR_EMAIL="${LAND_AUTHOR_EMAIL:-land@agentrelay.com}" ' +
'GIT_COMMITTER_NAME="${LAND_AUTHOR_NAME:-Agent Relay Land}" GIT_COMMITTER_EMAIL="${LAND_AUTHOR_EMAIL:-land@agentrelay.com}"';
const commit = (await f.run(`${ident} git commit-tree ${shellWord(plan.tree)} -p ${shellWord(latest)} -m ${shellWord(plan.message)}`)).trim();
const push = await f.run(`git push origin ${shellWord(`${commit}:refs/heads/${s.config.baseBranch}`)}`, { timeout: '5m', onNonZero: 'record' });
// Fence the push on the land ref: superseding this run means a newer push
// to its land ref. The squash goes up atomically with the land ref's
// deletion, leased on the pinned head. A delete is a real ref update with
// an old value, so the server checks it inside the same transaction: if
// the ref moved, the whole push fails and nothing lands on the base —
// however long this stage's sandbox outlives its cancellation. (Pushing the
// ref to its own value would be dropped as up to date and check nothing.)
// A landed run no longer needs its land ref.
const ref = r.input.ref;
const refspecs = [`${commit}:refs/heads/${s.config.baseBranch}`, ...(ref ? [`:refs/heads/${ref}`] : [])];
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
const fence = ref ? ` --atomic --force-with-lease=${shellWord(`refs/heads/${ref}:${s.pinnedSha}`)}` : '';
const push = await f.run(`git push${fence} origin ${refspecs.map(shellWord).join(' ')}`, { timeout: '5m', onNonZero: 'record' });
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
if (!push.ok) {
// A push can land and still fail on the client (the connection drops
// before the server's answer arrives). This run's own Land-Run trailer on
// the fetched base means it landed: record that, never "superseded".
await f.run(`git fetch --no-tags --quiet origin ${shellWord(`+refs/heads/${s.config.baseBranch}:refs/remotes/${r.base}`)}`, { timeout: '10m', onNonZero: 'record' });
const landed = (await f.run(`git log --format=%H --grep=${shellWord(`Land-Run: ${s.runId}$`)} -n 1 ${shellWord(r.base)}`)).trim();
if (landed) return { kind: 'merge', outcome: 'pushed', plan, commit: landed, now: await now(f) };
}
if (!push.ok && ref) {
const refSha = (await f.run(`git ls-remote origin ${shellWord(`refs/heads/${ref}`)} | cut -f1`)).trim() || null;
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
if (refSha !== s.pinnedSha) return { kind: 'superseded', refSha, now: await now(f) };
}
if (!push.ok) {
// Only an actual stale base retries through D; a permission or protected
// branch rejection is permanent and escalates instead of looping.
Expand Down Expand Up @@ -922,15 +948,20 @@ export async function land(f: Ctx, raw: LandInput): Promise<void> {
if (uname.replace('aarch64', 'arm64') !== want) throw new NeedsHuman(`runner is ${uname}; land.config needs ${want}`);
await f.run(config.runner.commands.map(c => `command -v ${shellWord(c)} >/dev/null`).join(' && ') || 'true');
if (config.mergePolicy.mode === 'auto') {
// Preflight, not polling: the GitHub gate and the push need an authed gh
// and a write-capable git credential; prove both at stage one.
// Preflight, not polling: the GitHub gate needs an authed gh on every
// auto stage (a read grant authenticates it too).
const gh = await f.run(`command -v gh >/dev/null && gh auth status`, { onNonZero: 'record' });
if (!gh.ok) throw new NeedsHuman('mergePolicy.mode "auto" needs gh installed and authenticated (a write repository grant); shadow runs do not');
// Write access is proven by dry-running a push to a fresh throwaway ref:
// a create is always a fast-forward, so an advanced base or a rebase
// pending at D/F can never turn this check into a false refusal.
const pushable = await f.run(`git push --dry-run origin HEAD:refs/heads/land-probe/${shellWord(input.runId)}-$$`, { onNonZero: 'record', timeout: '2m' });
if (!pushable.ok) throw new NeedsHuman(`mergePolicy.mode "auto" needs a push-capable git credential (a write repository grant): ${pushable.output.slice(-300)}`);
if (!gh.ok) throw new NeedsHuman('mergePolicy.mode "auto" needs gh installed and authenticated; shadow runs do not');
// Only E (the gate's snapshot branch) and F (the squash) push, and Cloud
// gives only those stages a write grant: A-D, where an agent reviews and
// fixes untrusted change content, run read-only. So write access is
// proven where it is needed, by dry-running a push to a fresh throwaway
// ref: a create is always a fast-forward, so an advanced base or a
// rebase pending at F can never turn this check into a false refusal.
if (WRITE_STAGES.has(input.stage)) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const pushable = await f.run(`git push --dry-run origin HEAD:refs/heads/land-probe/${shellWord(input.runId)}-$$`, { onNonZero: 'record', timeout: '2m' });
if (!pushable.ok) throw new NeedsHuman(`mergePolicy.mode "auto" needs a push-capable git credential at stage ${input.stage} (a write repository grant): ${pushable.output.slice(-300)}`);
}
}
if (!WORKER_HARNESSES.has(config.fixLoop.harness)) {
throw new NeedsHuman(`fixLoop.harness "${config.fixLoop.harness}" is not supported in land; use "codex"`);
Expand All @@ -955,7 +986,14 @@ export async function land(f: Ctx, raw: LandInput): Promise<void> {
owned = state;
if (input.ref) {
const refSha = (await f.run(`git ls-remote origin ${shellWord(`refs/heads/${input.ref}`)} | cut -f1`)).trim() || null;
if (refSha !== state.pinnedSha) return await save(f, stateFile, nextLandStage(state, { kind: 'superseded', refSha, now: await now(f) }));
// Stage F deletes the land ref in the same push that lands the squash,
// so a replayed F (reaped after its push, before its state write) finds
// the ref gone, or recreated by a newer submission: its own Land-Run
// trailer on the base means it landed, and F reconciles that below
// rather than being called superseded.
Comment thread
kjgbot marked this conversation as resolved.
Resolved
const landedHere = refSha !== state.pinnedSha && state.cursor === 'F' &&
!!(await f.run(`git log --format=%H --grep=${shellWord(`Land-Run: ${state.runId}$`)} -n 1 ${shellWord(base)}`)).trim();
if (refSha !== state.pinnedSha && !landedHere) return await save(f, stateFile, nextLandStage(state, { kind: 'superseded', refSha, now: await now(f) }));
}
if (state.headSha !== state.pinnedSha) {
const restored = (await f.run(`git fetch --quiet ${shellWord(`${input.stateDir}/land.bundle`)} HEAD && git checkout --quiet --detach FETCH_HEAD && git rev-parse HEAD`)).trim();
Expand Down
Loading
Loading