Metadata-Version: 2.4
Name: laneguard
Version: 0.3.1
Summary: Coordinate parallel coding agents: disjoint backlogs and conflict prediction for in-flight branches.
License: MIT
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"

# laneguard

Keep parallel coding agents in their lanes.

- `laneguard plan TASKS_DIR` checks a backlog of task files for disjoint file ownership **before** work starts.
- `laneguard scan REPO` compares in-flight branches and predicts merge conflicts **before** integration.
- `laneguard claim`, `release` and `claims` keep a shared ledger of who is changing which files.
- `laneguard mcp` exposes all of them to coding agents as five MCP tools.

Standard library only. Git is used read-only. Output is deterministic and compact; `--json` is the contract.
Runs on Linux, macOS and Windows.

**Status:** v0.3.1 fixes a crash at startup on Windows (0.2.0 and 0.3.0 fail there before running any
command) and is tested on Linux, macOS and Windows. v0.3 added `scan --since`, claims environment
defaults, and in-session claiming. See [docs/spec.md](docs/spec.md) for the specification and
[AGENTS.md](AGENTS.md) if you are an agent working on this repository.

## Install

```bash
pip install laneguard
```

The latest unreleased `main`:

```bash
pip install "laneguard @ git+https://github.com/55kov/laneguard.git"
```

## Platforms

laneguard runs on Linux, macOS and Windows with Python 3.12 or newer. CI runs the full gate on all
three with Python 3.12, 3.13 and 3.14, installs the built wheel on each and runs every command, and a
release is published only after that installed wheel passes on all three. Releases 0.2.0 and 0.3.0
fail at startup on Windows with `ModuleNotFoundError: No module named 'fcntl'`; use 0.3.1 or later
there.

What differs between platforms:

- **Paths** in task files, claims and output use forward slashes everywhere. A backslash is rejected
  as unsupported path syntax, on Windows too.
- **Claims locking.** The lock file and the 10-second retry are the same on every platform; what may
  be removed as stale differs. On Linux and macOS a lock older than 60 seconds is removed, with a
  warning, even if its holder is still running, and that holder's update is then refused
  (`lock was replaced`). On Windows a lock that no process holds open is removed at once, with a
  warning if it is older than 60 seconds, and a lock that a running process holds is never removed.
  Do not use one ledger from Windows and from Linux or macOS processes at the same time, for example
  native Windows tools and WSL on the same directory: the two lock implementations do not fence each
  other's stale-lock removal. The ledger itself is written with LF line endings everywhere.
- **Text output** uses the console's or pipe's encoding (on Windows pipes, the ANSI code page) and
  writes characters that encoding cannot represent as backslash escapes, for example `\u65e5`. For
  machines, use `--json`: it is ASCII on every platform. MCP messages are UTF-8 with LF line endings
  on every platform.
- The **Usage** examples below are Bash. On Windows, run them in Git Bash.

## Dependencies and install footprint

laneguard requires **Python 3.12 or newer** and has **no runtime dependencies**
outside the standard library. `pip install laneguard` installs one package,
`laneguard` (including its JSON schemas), one console script,
`laneguard = laneguard.cli:main`, and distribution metadata.

The wheel is pure Python: installing it runs no project code. There is no
`setup.py`, install hook, `.pth` file, or compiled code. Building from the sdist
uses `setuptools.build_meta`, with `setuptools>=68` as the only declared build
requirement; setuptools is needed only at build time. The optional `dev` extra
(`pip install 'laneguard[dev]'`) adds pytest and ruff for development only.

`git` must be on `PATH` for these commands and MCP tools:

- `laneguard scan` and `laneguard_scan`;
- `laneguard plan TASKS_DIR --repo PATH` and `laneguard_plan` with a `repo` argument.

`plan` without `--repo`, `claim`, `release`, `claims`, and `schema` work without
git. `mcp` also starts without git: `initialize`, `ping`, `tools/list`, and the
tools `laneguard_plan` without `repo`, `laneguard_claim`, `laneguard_release`,
and `laneguard_claims` work without it.

At runtime, laneguard makes no network connections and sends no telemetry; MCP
uses stdin/stdout. Only `laneguard/gitio.py` starts subprocesses, using git's
read-only subcommands: `rev-parse`, `ls-files`, `for-each-ref`, `merge-base`,
`diff`, and `log`.

laneguard writes application files only for `claim` and `release` (and MCP
`laneguard_claim` and `laneguard_release`). The ledger is chosen with `--ledger`,
`LANEGUARD_LEDGER`, or the MCP `ledger` argument. For its resolved path `FILE`,
the lock is `FILE.lock`; updates use `tempfile.NamedTemporaryFile` in the same
directory with `prefix=f".{ledger.name}."` and no suffix, then atomically replace
`FILE` with `os.replace`. For example, the files are `claims.json`,
`claims.json.lock`, and `.claims.json.<random>`. The `claims` command and
`laneguard_claims` tool only read the ledger.

Verify it yourself against the published 0.3.1 wheel:

```bash
python -m pip download laneguard==0.3.1 --no-deps -d laneguard-dl
python -m zipfile -l laneguard-dl/laneguard-0.3.1-py3-none-any.whl
python - <<'PY'
from zipfile import ZipFile

with ZipFile("laneguard-dl/laneguard-0.3.1-py3-none-any.whl") as wheel:
    metadata = wheel.read("laneguard-0.3.1.dist-info/METADATA").decode("utf-8")
for line in metadata.splitlines():
    if line.startswith("Requires-Dist:"):
        print(line)
PY
```

## Usage

Run these Bash examples from the repository root with Python 3.12+ available
as `python3` and Git installed. Setup creates only disposable files under `/tmp`;
`laneguard` itself uses Git read-only. Run the blocks in order. Each output block
contains actual stdout, including the exit status printed by `printf`.

### Plan: explicit task ownership

Create two disjoint tasks, including one file that does not exist yet:

```bash
example_dir=$(mktemp -d)
mkdir "$example_dir/tasks"
printf 'Files: README.md\n' > "$example_dir/tasks/docs.md"
printf 'Files: future.py\n' > "$example_dir/tasks/feature.md"
python3 -m laneguard plan "$example_dir/tasks"
printf 'exit: %s\n' "$?"
```

```text
plan: disjoint
exit: 0
```

The default text is concise. Use `--repo .` to classify claims against Git's
tracked files, and `--json` for the structured `exists`/`new` arrays (`--repo`
also prints classifications in text mode). New files are allowed:

```bash
python3 -m laneguard plan "$example_dir/tasks" --repo . --json
printf 'exit: %s\n' "$?"
```

```json
{"kind":"plan","version":1,"tasks":[{"id":"docs","files":["README.md"],"exists":["README.md"],"new":[]},{"id":"feature","files":["future.py"],"exists":[],"new":["future.py"]}],"overlaps":[],"warnings":[]}
```

```text
exit: 0
```

Add a competing claim to see an overlap:

```bash
printf 'Files: README.md\n' > "$example_dir/tasks/other.md"
python3 -m laneguard plan "$example_dir/tasks"
printf 'exit: %s\n' "$?"
```

```text
overlap docs other: README.md
exit: 2
```

### Scan: a fully specified clean fixture

This creates a temporary repository with a working tree, an empty base commit,
and two local task branches pointing to it. Neither branch has changes. Pass the
working tree root to `scan`; subdirectories, `.git` directories, and bare
repositories are rejected. Fixture setup writes only inside `example_dir`:

```bash
git init --quiet "$example_dir/repo"
git -C "$example_dir/repo" fast-import --quiet <<'GIT'
commit refs/heads/main
mark :1
committer Example <example@example.com> 0 +0000
data 7
fixture

reset refs/heads/task/one
from :1

reset refs/heads/task/two
from :1

GIT
python3 -m laneguard scan "$example_dir/repo" --base main --branches 'task/*' --detail
printf 'exit: %s\n' "$?"
```

```text
scan: no likely conflicts
task/one: (no changes)
task/two: (no changes)
exit: 0
```

`--detail` lists each selected branch's changed files; omit it for compact
findings only. Use `--json` for structured hunk ranges and merge-base hashes.
Branches editing the same file in separate regions receive an informational
`shared-file` verdict, which does not cause exit 2. Overlapping ranges or ranges
within `--near` lines (default 3), and delete/rename versus modify cases, can
produce `likely-conflict` and exit 2.

For both `plan` and `scan`, exit **0** means no overlaps or likely conflicts,
**2** means overlaps or likely conflicts were found, and **1** means a usage,
input, or Git error. Exit 2 is a finding, not a command failure.

### MCP: tools for agents

`laneguard mcp` is a stdio MCP server: newline-delimited JSON-RPC 2.0, one UTF-8 message per line. It
implements `initialize`, `ping`, `tools/list` and `tools/call`, and ignores notifications. Pipe a
concrete `ping` request; closing stdin terminates the server at EOF:

```bash
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"ping"}' | python3 -m laneguard mcp
printf 'exit: %s\n' "$?"
```

```text
{"jsonrpc":"2.0","id":1,"result":{}}
exit: 0
```

The server offers five tools. Each result is the same JSON document the matching CLI command prints
with `--json`, given both as `structuredContent` and as JSON text in `content`. Findings (overlaps,
likely conflicts, refused claims) are in the document, because MCP has no exit codes. An input, Git
or ledger error is a result with `isError: true` and the message as its text. An unknown tool or an
invalid argument is a JSON-RPC error with code `-32602`.

| Tool | Arguments (defaults) | Result |
|---|---|---|
| `laneguard_plan` | `tasks_dir` (required), `repo` | `plan` document, as `laneguard plan --json` |
| `laneguard_scan` | `repo` (required), `base` (`"main"`), `branches` (`"task/*"`), `near` (`3`), `detail` (`false`), `since` | `scan` document, as `laneguard scan --json` |
| `laneguard_claim` | `paths` (required, at least one), `ledger`, `owner` | `claims` document; refused paths are in `refused` |
| `laneguard_release` | `paths` (every path the owner holds when omitted), `ledger`, `owner` | `claims` document; released paths are in `released` |
| `laneguard_claims` | `ledger`, `owner` (a filter) | `claims` document |

`ledger` and `owner` default to `LANEGUARD_LEDGER` and `LANEGUARD_OWNER` in the server's
environment; a missing required value is an error result. `tools/list` returns each tool's input
schema, and `laneguard schema plan|scan|claims` prints each result document's JSON Schema. List the
tools by name:

```bash
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | python3 -m laneguard mcp | python3 -c 'import json, sys; print(*(tool["name"] for tool in json.load(sys.stdin)["result"]["tools"]), sep="\n")'
printf 'exit: %s\n' "$?"
```

```text
laneguard_plan
laneguard_scan
laneguard_claim
laneguard_release
laneguard_claims
exit: 0
```

Claim a file through the server, with the ledger and owner taken from its environment:

```bash
printf '%s\n' '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"laneguard_claim","arguments":{"paths":["README.md"]}}}' | LANEGUARD_LEDGER="$example_dir/mcp-claims.json" LANEGUARD_OWNER=docs python3 -m laneguard mcp | python3 -c 'import json, sys; result = json.load(sys.stdin)["result"]; print(result["isError"], [(claim["owner"], claim["path"]) for claim in result["structuredContent"]["claims"]])'
printf 'exit: %s\n' "$?"
```

```text
False [('docs', 'README.md')]
exit: 0
```

#### Connect it to Codex

Register the server once with the Codex CLI. `laneguard` must be on `PATH`, as it is after
`pip install laneguard`; for an installation that is not, give the full path of its `laneguard`
executable instead:

```bash
codex mcp add laneguard -- laneguard mcp
```

To give the claim tools a default ledger and owner, set them in the server's environment:

```bash
codex mcp add laneguard --env LANEGUARD_LEDGER=/path/to/board/claims.json --env LANEGUARD_OWNER=agent-1 -- laneguard mcp
```

That command writes this table to `~/.codex/config.toml` (codex-cli 0.163.0, on Linux and on Windows),
which you can also write by hand. `codex mcp list` shows the server and `codex mcp remove laneguard`
removes it:

```toml
[mcp_servers.laneguard]
command = "laneguard"
args = ["mcp"]

[mcp_servers.laneguard.env]
LANEGUARD_LEDGER = "/path/to/board/claims.json"
LANEGUARD_OWNER = "agent-1"
```

If a `scan` of a large repository needs more time than Codex allows a tool call, add
`tool_timeout_sec = 120` (or more) to the `[mcp_servers.laneguard]` table.

### Claims

Claim your task's files in a shared ledger before starting work.
If another owner holds an overlapping path, wait for their release before claiming
it and making changes.
Concurrent writers are serialized by an exclusive `FILE.lock` (retrying for up to
10 seconds and reclaiming locks older than 60 seconds; on Windows, reclaiming at
once any lock that no process holds open, see [Platforms](#platforms)), and writes
atomically replace the ledger using a temporary file in the same directory.

```bash
python3 -m laneguard claim --ledger "$example_dir/claims.json" --owner docs README.md
printf 'exit: %s\n' "$?"
python3 -m laneguard claim --ledger "$example_dir/claims.json" --owner feature README.md
printf 'exit: %s\n' "$?"
python3 -m laneguard release --ledger "$example_dir/claims.json" --owner docs README.md
printf 'exit: %s\n' "$?"
```

```text
claimed docs: README.md
exit: 0
refused feature README.md: held by docs (README.md)
exit: 2
released docs: README.md
exit: 0
```

List the live claims as JSON, trimming the temporary ledger path from the output:

```bash
python3 -m laneguard claims --ledger "$example_dir/claims.json" --json | python3 -c 'import json, sys; d = json.load(sys.stdin); del d["ledger"]; print(json.dumps(d, separators=(",", ":")))'
printf 'exit: %s\n' "$?"
```

```json
{"kind":"claims","version":1,"claims":[],"refused":[],"released":[],"warnings":[]}
```

```text
exit: 0
```

#### Claiming files from inside an agent session

Before changing a file outside your task's `Files:` list, a sandboxed writer
claims it through the CLI using a ledger in the writable shared board directory:

```text
laneguard claim --ledger <board>/claims.json --owner <task-id> <path>
```

Replace the placeholders with the board directory, your task ID, and the
repository-relative path. Exit **0** means the file is yours to edit. Exit **2**
means another writer holds an overlapping claim: do not touch the file, explain
the refusal in your task summary, and stop. The harness releases all your task's
claims when the run ends.

Set `LANEGUARD_LEDGER` and `LANEGUARD_OWNER` once to use `laneguard claim <path>`
without flags. `claim`, `release`, and `claims` use these defaults; explicit
`--ledger` and `--owner` flags take precedence. `claims` uses the default owner as
a filter, or lists all owners when none is set. Missing required values cause
exit **1**. The MCP claim tools use the same defaults from the server process's
environment; sandboxed writers use the CLI to reach their shared board.

This reproduced example uses `python3 -m laneguard` from the checkout, equivalent
to the installed `laneguard` command:

```bash
mkdir "$example_dir/board"
export LANEGUARD_LEDGER="$example_dir/board/claims.json"
export LANEGUARD_OWNER=docs
python3 -m laneguard claim src/x.py
printf 'exit: %s\n' "$?"
python3 -m laneguard claim --owner other src/x.py
printf 'exit: %s\n' "$?"
python3 -m laneguard release
printf 'exit: %s\n' "$?"
python3 -m laneguard claims
printf 'exit: %s\n' "$?"
unset LANEGUARD_LEDGER LANEGUARD_OWNER
```

```text
claimed docs: src/x.py
exit: 0
refused other src/x.py: held by docs (src/x.py)
exit: 2
released docs: src/x.py
exit: 0
claims: none
exit: 0
```

### Schemas

Print the packaged JSON Schema for `plan`, `scan`, or `claims`; here are the first
ten lines for `plan`:

```bash
python3 -m laneguard schema plan | head -n 10
printf 'exit: %s\n' "$?"
```

```text
{
  "$id": "https://laneguard.dev/schemas/plan.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "additionalProperties": false,
  "properties": {
    "kind": {
      "const": "plan",
      "type": "string"
    },
    "overlaps": {
exit: 0
```

In CI, save the full `laneguard schema <kind>` output and validate the corresponding
`--json` output with a JSON Schema draft 2020-12 validator.

Remove the disposable fixtures when finished:

```bash
rm -rf "$example_dir"
```

## Development

```bash
python -m venv .venv && .venv/bin/pip install -e '.[dev]'
PY=.venv/bin/python sh check.sh
```

On Windows, in Git Bash, the environment's programs are under `.venv/Scripts`:

```bash
python -m venv .venv && .venv/Scripts/pip install -e '.[dev]'
PY=.venv/Scripts/python sh check.sh
```

`python tests/installed_smoke.py DIST_DIR` installs the wheel in `DIST_DIR` into a fresh virtual
environment outside the source tree and runs every command against it; CI and the release
workflow run it on all three platforms.
