# Code repos

> Git repositories your code and agents commit to, with plain git access and export to GitHub.

A **repo** is a git repository NoClick hosts. Your code commits to it through the API, your agents write to it from a [sandbox](https://www.noclick.com/docs/guide/sandboxes.md), and any git client clones it or pushes to it with a short-lived URL. An [app](https://www.noclick.com/docs/guide/apps.md) deploys from one. It's plain git all the way through, so the code can always leave: clone it, or move it to GitHub whole.

## Create a repo

Name it in your code: `from_name` with `create_if_missing=True` creates the repo, empty, the first time it's used and finds it every time after.

```python
import noclick

repo = noclick.Repo.from_name("agent-tools", create_if_missing=True)
print(repo.default_branch)   # main
```

```ts
import { Repo } from "noclick";

const repo = await Repo.fromName("agent-tools", { createIfMissing: true }).hydrate();
console.log(repo.defaultBranch);   // main
```

`create` makes one outright and raises `noclick.Conflict` if the name is taken (its `existing_id` names the one that's there). Pass `default_branch=` for a first branch other than `main`:

```python
site = noclick.Repo.create("portfolio", default_branch="production", user="user_42")
```

```ts
import { Repo } from "noclick";

const site = await Repo.create("portfolio", { defaultBranch: "production", user: "user_42" });
```

Created inside `as_user` (or with `user=`), a repo belongs to that user.

## Commit files

`commit` writes files in one commit. Each path maps to its new content, text or bytes, or to `None` to delete it:

```python
repo = noclick.Repo.from_name("agent-tools")
commit = repo.commit(
    {
        "src/index.ts": "export const lookup = (id: string) => fetch(`/orders/${id}`);\n",
        "assets/logo.png": open("logo.png", "rb").read(),
        "old-notes.txt": None,
    },
    message="Add the lookup route",
)
print(commit.sha, commit.files_changed)
```

```ts
import { readFile } from "node:fs/promises";
import { Repo } from "noclick";

const repo = Repo.fromName("agent-tools");
const commit = await repo.commit(
  {
    "src/index.ts": "export const lookup = (id: string) => fetch(`/orders/${id}`);\n",
    "assets/logo.png": await readFile("logo.png"),
    "old-notes.txt": null,
  },
  { message: "Add the lookup route" },
);
console.log(commit.sha, commit.filesChanged);
```

A commit goes on the default branch unless you pass `branch=`; a branch that doesn't exist yet is made from the default branch's head, which is how you open a branch for a [preview deployment](https://www.noclick.com/docs/guide/apps.md#preview-a-branch). git keeps branch names as paths, so a name can't be both a branch and another branch's folder: with a branch `feature`, a commit to `feature/new-form` raises `noclick.Conflict` (its `existing_branch` is `feature`), so name it `feature-new-form`. `author=` names who made it, as `Name <email>`.

### Commit a file NoClick reads

A file NoClick can already reach goes by reference, and NoClick reads it byte for byte: one of your account's [files](https://www.noclick.com/docs/guide/agents.md#send-it-files) (what your agents' and channels' messages carried, and what you made), the file at an `https` URL, or a file in a [bucket](https://www.noclick.com/docs/guide/storage.md). Its bytes never pass through your code, or through an agent's tool call, so a file too big for one (a page someone sent, a video) still goes in whole:

```python
[page] = noclick.attachments(query="game.html")
site = noclick.Repo.from_name("game", create_if_missing=True)
commit = site.commit(
    {
        "index.html": page,
        "logo.png": {"url": "https://example.com/logo.png"},
        "fonts/brand.woff2": {"bucket_id": noclick.Bucket.from_name("brand"), "key": "fonts/brand.woff2"},
    },
    message="Publish the game",
)
print(commit.sha)
```

```ts
import { Bucket, Repo, attachments } from "noclick";

const [page] = await attachments({ query: "game.html" });
const brand = await Bucket.fromName("brand").hydrate();
const site = Repo.fromName("game", { createIfMissing: true });
const commit = await site.commit(
  {
    "index.html": { attachmentId: page.id! },
    "logo.png": { url: "https://example.com/logo.png" },
    "fonts/brand.woff2": { bucketId: brand.id, key: "fonts/brand.woff2" },
  },
  { message: "Publish the game" },
);
console.log(commit.sha);
```

Over HTTP, a file in `POST /v1/repos/{id}/commits` is `{path, attachment_id}`, `{path, url}` or `{path, bucket_id, key}` in place of `{path, content}`. NoClick reads only what the call itself could: the account's files with a key of the account's (`agents` or `channels` scope; a user's key reaches none of them, and an [app's code](https://www.noclick.com/docs/guide/apps.md#what-the-app-s-code-can-do) only those its own code uploaded), a bucket the call reaches (`storage` scope), and a URL on the public internet (a private or internal address is refused, redirects included). What it reads counts toward the commit's 50 MB, and a file it can't read refuses the whole commit, writing nothing. To put such a file live, commit it to an app's repo and deploy that commit ([Deploy](https://www.noclick.com/docs/guide/apps.md#deploy)).

### Commit a folder

Pass a folder instead and the branch's tree is made to match it, sending only what changed: new and changed files are written, and files the folder no longer has are deleted. So a build can commit its output on every run, and a run that changed nothing makes no commit and returns `None`:

```python
site = noclick.Repo.from_name("marketing-site", create_if_missing=True)
commit = site.commit("./dist", message="Rebuild the site", exclude=["*.map", "node_modules"])
print(commit.sha if commit else "nothing changed")
```

```ts
import { Repo } from "noclick";

const site = Repo.fromName("marketing-site", { createIfMissing: true });
const commit = await site.commit("./dist", { message: "Rebuild the site", exclude: ["*.map", "node_modules"] });
console.log(commit ? commit.sha : "nothing changed");
```

A file counts as changed when its content differs from the branch's copy (the client compares git's blob ids, `RepoFile.sha`, so unchanged files are never uploaded). `.git` is always skipped, and `exclude` globs skip more; a path they match is also left alone in the repo, never deleted. The limits of one commit apply to what changed.

## Read files

```python
repo = noclick.Repo.from_name("booking")
print(repo.read("package.json").decode())

for entry in repo.files("app/"):
    print(entry.type, entry.path, entry.size)   # dir app/routes None, file app/root.tsx 812
```

```ts
import { Repo } from "noclick";

const repo = Repo.fromName("booking");
console.log(await repo.readText("package.json"));

for (const entry of await repo.files("app/")) {
  console.log(entry.type, entry.path, entry.size);   // dir app/routes null, file app/root.tsx 812
}
```

`read` gives a file's bytes, and `files` lists one directory, directories first; `recursive=True` lists every file below it instead. Both read the default branch's head unless you pass `ref=`, a branch, a tag or a commit sha. A path that isn't there raises `noclick.NotFound`: a file, or a folder (git keeps no empty folders, so a folder with nothing in it isn't there either), and its `field` says which was missing, `path`, `prefix` or the `ref`.

## Branches and history

```python
repo = noclick.Repo.from_name("booking")
for branch in repo.branches():
    print(branch.name, branch.head, branch.updated_at)

for commit in repo.commits(branch="main", limit=5):
    print(commit.sha[:7], commit.author, commit.message)
```

```ts
import { Repo } from "noclick";

const repo = Repo.fromName("booking");
for (const branch of await repo.branches()) {
  console.log(branch.name, branch.head, branch.updatedAt);
}

for (const commit of await repo.commits({ branch: "main", limit: 5 })) {
  console.log(commit.sha.slice(0, 7), commit.author, commit.message);
}
```

`last_commit` on the repo is the newest commit on its default branch, and `used_by` lists the apps that deploy it. `commits_page` reads the history a page at a time: pass each page's `next_cursor` back as `cursor`, until it's `None`.

`diff` reads what one commit changed against its first parent, from a full or short sha:

```python
repo = noclick.Repo.from_name("booking")
[latest] = repo.commits(limit=1)
changes = repo.diff(latest.sha)
print(f"+{changes.additions} -{changes.deletions}", changes.parents)
for file in changes.files:
    print(file.status, file.path)  # added, modified, deleted, renamed, copied or type_changed
    print(file.patch or "(not shown)")
```

```ts
import { Repo } from "noclick";

const repo = Repo.fromName("booking");
const [latest] = await repo.commits({ limit: 1 });
const changes = await repo.diff(latest.sha);
console.log(`+${changes.additions} -${changes.deletions}`, changes.parents);
for (const file of changes.files) {
  console.log(file.status, file.path);  // added, modified, deleted, renamed, copied or type_changed
  console.log(file.patch ?? "(not shown)");
}
```

Each file's `patch` is its unified diff in git's format. It's `None`, with no line counts, for a file that isn't text or is too large to show; its `size` still says how big it is.

A `commit` through the API only adds history: the new commit's parent is the branch's head. With git, a push can rewrite a branch (a force-push) or delete one, so NoClick holds agents to two rules:

- **An agent never rewrites or deletes the default branch.** Its pushes may only move the default branch forward; a force-push or a deletion of it is refused in git's own report (`! [remote rejected] main -> main (NoClick: the default branch (main) can't be force-pushed or deleted by an agent; push a new branch instead)`). So is an update NoClick can't show only adds commits: it never guesses.
- **Any other branch an agent rewrites or deletes is kept first.** Before the push goes on, NoClick keeps the branch's old head as a hidden backup, outside the branch list and clones, for 30 days, like the [trash](https://www.noclick.com/docs/guide/undo.md#the-trash). If it can't keep it, the push is refused and nothing moves.

`backups` lists them, newest first, and `restore_backup` makes the branch again at the commit it was kept at. When the repo has a branch by that name again, it comes back as `<branch>-restored-<time>` instead, so nothing that's there moves:

```python
repo = noclick.Repo.from_name("booking")
for backup in repo.backups(branch="agent/new-form"):
    print(backup.reason, backup.sha[:7], backup.created_at, backup.expires_at)  # rewritten or deleted

[latest] = repo.backups(branch="agent/new-form", limit=1)
print(repo.restore_backup(latest).name)
```

```ts
import { Repo } from "noclick";

const repo = Repo.fromName("booking");
for (const backup of await repo.backups({ branch: "agent/new-form" })) {
  console.log(backup.reason, backup.sha.slice(0, 7), backup.createdAt, backup.expiresAt);  // rewritten or deleted
}

const [latest] = await repo.backups({ branch: "agent/new-form", limit: 1 });
console.log((await repo.restoreBackup(latest)).name);
```

An agent here is anything that pushes with a git URL it got through NoClick's [MCP server](https://www.noclick.com/docs/guide/mcp.md) (and the `noclick deploy` command its `repos_push` hands out), the coordinator, or a [platform agent](https://www.noclick.com/docs/guide/agents.md) of yours: its writing URL goes through NoClick, which judges each push before the repo sees it. A URL you ask for with a secret key, a user's session or signed in to the console goes straight to the repo as before, and its pushes are yours: nothing judges them, and nothing is kept. A secret key you hand a coding agent yourself (a setup code's `.env` line, say) is a key like any other, so its pushes aren't covered either; give that agent the MCP server instead.

## Clone and push with git

`clone_url` gives an HTTPS URL with a token inside, for any git client. It reads by default; `write=True` lets it push too. The token works for this repo only and stops after `ttl_s` seconds (an hour by default, a day at most), so treat the URL as a secret until then. An agent's writing URL goes through NoClick, which holds its pushes to the rules in [Branches and history](https://www.noclick.com/docs/guide/repos.md#branches-and-history).

```python
import subprocess

repo = noclick.Repo.from_name("agent-tools")
subprocess.run(["git", "clone", repo.clone_url(), "agent-tools"], check=True)
```

```ts
import { execFileSync } from "node:child_process";
import { Repo } from "noclick";

const repo = Repo.fromName("agent-tools");
execFileSync("git", ["clone", await repo.cloneUrl(), "agent-tools"], { stdio: "inherit" });
```

Code that runs its own sandbox gives it a write URL for as long as the job takes, and it commits and pushes with git like anyone else:

```python
repo = noclick.Repo.from_name("agent-tools")
url = repo.clone_url(write=True, ttl_s=900)
with noclick.Sandbox.create(network=True, timeout_s=900) as sb:
    sb.exec(["git", "clone", url, "/workspace/agent-tools"])
    sb.exec("cd /workspace/agent-tools && npm test")
```

```ts
import { Repo, Sandbox } from "noclick";

const repo = Repo.fromName("agent-tools");
const url = await repo.cloneUrl({ write: true, ttlS: 900 });
const sb = await Sandbox.create({ network: true, timeoutS: 900 });
try {
  // Not in the TypeScript client: an argument list. Pass one quoted string.
  await sb.exec(`git clone '${url}' /workspace/agent-tools`);
  await sb.exec("cd /workspace/agent-tools && npm test");
} finally {
  await sb.terminate();
}
```

## Work in a repo from an agent

A hosted agent gets its repositories with `repos=`: each is cloned into `/workspace/<path>` at a conversation's first turn, on the branch you name (the default branch otherwise), and its git reaches that repository only, through NoClick, with a key made for its sandbox that the model can't turn into the real credential. `connection.checkout("owner/name")` is a repository a `github` connection reaches (see [Give it a repository](https://www.noclick.com/docs/guide/agents.md#give-it-a-repository)), and `repo.checkout()` is one of your own repos, in the agent's scope (the account's for an account agent, a user's for that user's):

```python
import noclick

github = noclick.Connection.from_name("github", integration="github", create_if_missing=True)
site = noclick.Repo.from_name("booking")
writer = noclick.Agent.from_name(
    "docs-writer",
    create_if_missing=True,
    instructions="You fix the docs issues you're given in /workspace/docs, push a branch and open a pull request.",
    harness="claude_code",
    model_connection="claude",
    tools=[github.only("create_pull_request")],
    repos=[
        github.checkout("acme/docs", push="noclick/*"),
        site.checkout(branch="main", path="booking"),
    ],
)
```

```ts
import { Agent, Connection, Repo } from "noclick";

const github = Connection.fromName("github", { integration: "github", createIfMissing: true });
const site = Repo.fromName("booking");
const writer = Agent.fromName("docs-writer", {
  createIfMissing: true,
  instructions: "You fix the docs issues you're given in /workspace/docs, push a branch and open a pull request.",
  harness: "claude_code",
  modelConnection: "claude",
  tools: [github.only("create_pull_request")],
  repos: [
    github.checkout("acme/docs", { push: "noclick/*" }),
    site.checkout({ branch: "main", path: "booking" }),
  ],
});
```

`push` lists the branches the agent may push to: exact names (`"main"`), or a prefix ending in `/*` (`"noclick/*"` reaches `noclick/fix` and `noclick/a/b`), or a list of them. That's the one glob a git endpoint can enforce, so any other (`"fix-*"`, `"**"`) is refused when you make the checkout. NoClick's git endpoint refuses a push to any other branch, and a checkout without `push` is read-only. Whatever `push` allows, the [branch rules](https://www.noclick.com/docs/guide/repos.md#branches-and-history) hold too: the agent can't force-push or delete the repository's default branch (on GitHub, the one GitHub names), and before its push rewrites or deletes any other branch NoClick keeps the old head. On one of your repos that's a hidden backup `repo.backups()` lists and `repo.restore_backup()` makes a branch again. On GitHub it's a ref in the repository itself, `refs/noclick/backups/<branch>/<time>`, made through GitHub's API with the connection's token before the push goes on, and deleted 30 days later; `git ls-remote origin 'refs/noclick/backups/*'` lists them, and `git push origin <sha>:refs/heads/<branch>`, as yourself, restores one. A [policy](https://www.noclick.com/docs/guide/policy.md) can't do this job: a coding harness runs `git push` in its own shell, which is no tool call for a policy to judge, so the limit sits in NoClick's git endpoint itself. `path` is the folder under `/workspace` (the repository's name by default). An agent's commits to one of your repos name it as their author (`docs-writer <noreply@noclick.com>`), so `repo.commits()` shows which agent made each; a repo deleted since the agent was defined stops its next turn with `noclick.Conflict`, saying to restore it from the trash or change the agent's `repos`. A connection from another scope, your account's `github` in a user's agent say, will be shared under the same rules as [in tools](https://www.noclick.com/docs/guide/connections.md#share-one-across-users); today a checkout takes a connection of the agent's own scope.

## Hear about pushes

Every move of a branch, a `git push` or a `commit` through the API, sends a `repo.pushed` [event](https://www.noclick.com/docs/guide/webhooks.md) naming the repo, the `branch`, and its commits `before` and `after` (`before` is `None` for a new branch, `after` for a deleted one). An app can deploy on each push by itself ([`deploy_on_push`](https://www.noclick.com/docs/guide/apps.md#deploy-on-push)); or deploy from the event on your own terms, a preview for every branch say:

```python
import noclick

def on_event(event: noclick.Event) -> None:
    pushed = event.data
    if event.type == "repo.pushed" and pushed["repo"] == "booking" and pushed["after"]:
        noclick.Project.from_name("booking").deploy(branch=pushed["branch"])
```

```ts
import { Project, type Event } from "noclick";

async function onEvent(event: Event): Promise<void> {
  const pushed = event.data;
  if (event.type === "repo.pushed" && pushed.repo === "booking" && pushed.after) {
    await Project.fromName("booking").deploy({ branch: String(pushed.branch) });
  }
}
```

## Move it to GitHub

`export_to_github` copies every branch and tag, with its history, into a new GitHub repository, through a GitHub [connection](https://www.noclick.com/docs/guide/connections.md) you already have: one of the repo's user, or the account's. `owner` is the connected GitHub account's own login, or an organization it may create repositories in. A connection with no GitHub account connected yet raises `noclick.NeedsConnection`, whose `connect_url` connects it.

```python
repo = noclick.Repo.from_name("agent-tools")
try:
    url = repo.export_to_github(connection="github", owner="acme", name="agent-tools").wait()
    print(url)   # https://github.com/acme/agent-tools
except noclick.NeedsConnection as needed:
    print("Connect GitHub first:", needed.connect_url)
```

```ts
import { NeedsConnection, Repo } from "noclick";

const repo = Repo.fromName("agent-tools");
try {
  const url = await (await repo.exportToGithub({ connection: "github", owner: "acme", name: "agent-tools" })).wait();
  console.log(url);   // https://github.com/acme/agent-tools
} catch (needed) {
  if (!(needed instanceof NeedsConnection)) throw needed;
  console.log("Connect GitHub first:", needed.connectUrl);
}
```

The GitHub repository is private unless you pass `private=False`. The copy fails with `noclick.Conflict` when GitHub already has one by that name, and with `noclick.PermissionDenied` when the connected account can't create repositories in `owner`. GitHub takes up to 2 GB in one push. The NoClick repo stays as it was: moving the code doesn't move the apps that deploy it.

## Export and delete

`export` is an [operation](https://www.noclick.com/docs/guide/operations.md) that gives an [export bundle](https://www.noclick.com/docs/guide/export.md): a zip holding `repos/<name>.bundle`, every branch and tag with its history as a git bundle, which `git clone` reads as it is (its default branch checked out), and `git push --mirror` from that clone moves anywhere.

```python
repo = noclick.Repo.from_name("agent-tools")
bundle = repo.export().wait()
print(bundle.url)   # the link expires
```

```ts
import { Repo } from "noclick";

const repo = Repo.fromName("agent-tools");
const bundle = await (await repo.export()).wait();
console.log(bundle.url);   // the link expires
```

`delete` removes the repo and its history. A repo an app deploys from raises `noclick.Conflict` until that app is deleted.

```python
noclick.Repo.from_name("scratch").delete()
```

```ts
import { Repo } from "noclick";

await Repo.fromName("scratch").delete();
```

## Limits and billing

| Limit | Value |
| --- | --- |
| One repo | 5 GB |
| One file | 100 MB |
| One `commit` | 1,000 files, 50 MB |
| A clone URL's lifetime | 60 seconds to 1 day |

A repo is billed for what it stores, its files' content, by the hour at what its git store charges: $0.005 per GB-hour while the repo has changed in the last 7 days, and $0.0002 per GB-hour once it hasn't. Clones and pushes cost nothing extra, within fair use. Spend counts toward the cap of the user the repo belongs to.

## Errors

| Error | When |
| --- | --- |
| `NotFound` | no file or folder at that path, no such ref, no such backup, or no repo by that name or id for the user the call acts for |
| `PermissionDenied` | a commit naming one of the account's files with a user's key, or a file the key lacks the scope to read (`agents` or `channels`, `storage`) |
| `Conflict` | the name is taken; a new branch named as an existing branch's folder, or holding one (`existing_branch`); `delete` on a repo an app deploys from; a GitHub repository that already exists; an export of the repo already running |
| `NeedsConnection` | `export_to_github` through a connection with no GitHub account connected yet (`connect_url`) |
| `PermissionDenied` | `export_to_github` to an `owner` the connected GitHub account can't create repositories in |
| `InvalidRequest` | a commit or file over the limits, a file to read the call can't (not the account's, a private address, a URL that answers an error), a clone URL lifetime out of range, or a `push` pattern that isn't a branch or a `prefix/*` |
| `QuotaExceeded` | a push or commit that would take the repo past 5 GB |

Every method is in the [Repo reference](https://www.noclick.com/docs/reference/python/Repo.md): [`commit`](https://www.noclick.com/docs/reference/python/Repo.md#Repo.commit), [`files`](https://www.noclick.com/docs/reference/python/Repo.md#Repo.files), [`clone_url`](https://www.noclick.com/docs/reference/python/Repo.md#Repo.clone_url), [`backups`](https://www.noclick.com/docs/reference/python/Repo.md#Repo.backups), [`export_to_github`](https://www.noclick.com/docs/reference/python/Repo.md#Repo.export_to_github) and the rest.
