# Fetching

The sync engine fetches its sources with the helpers in `skillrc/io`. You can call them on their own: a git cache that keeps working offline, an npm download that checks what it gets, and the lock that keeps two syncs apart.

```ts
import { fetchClone, gitUrl } from "skillrc/io";
import { placePaths } from "fleethosts/places";

const clone = await fetchClone(places, gitUrl("acme/skills"), "main", `${placePaths(places).cache()}/git`);
// { dir: ".../cache/git/3f9c...", commit: "9e1d...", collisions: [], refused: [], submodules: [] }
```

## The git cache

`fetchClone(places, url, ref, root, options?)` returns the files of `url` at `ref`, or at the default branch when `ref` is `undefined`. It keeps them under `root` between runs, so a timer run stays cheap and an offline run still has them.

For each repository and ref, the cache keeps three entries, named by `cloneKey(url, ref)`:

| Entry | What it holds |
| --- | --- |
| `<key>.git` | A bare repository. Fetches land under `refs/<program>/`. |
| `<key>` | The files of the current commit, with no `.git` folder |
| `<key>.json` | The commit, and the paths left out of the checkout |

A fetch is shallow: `git fetch --depth 1 --no-tags` of the one ref. When the commit is new, its files are written to a fresh folder and renamed into place, so a killed fetch leaves the old tree or the new one, never half of one. The next call finishes what a killed one left.

A ref that is a commit id, 7 to 40 hex digits, is fetched once. A later call with a cached commit that starts with it doesn't fetch again. A short id the shallow fetch can't find falls back to fetching every branch and tag.

### Offline and read-only

| Option | What it does |
| --- | --- |
| `offline` | Fetches nothing and returns the cached commit |
| `readOnly` | Runs no git at all. A dry run uses it. |
| `check(url, cwd)` | Returns why `url` may not be fetched, asked right before each fetch. With it, git follows no redirects. |
| `signal` | Stops the fetch |

Both `offline` and `readOnly` throw a `UserError` when the repository was never fetched.

### Paths left out

macOS and Windows store names that differ only in case or Unicode form in one folder. Two such paths in a repository would overwrite each other, so the cache keeps the first, byte by byte, and lists the rest under `collisions` on every system. Every machine then gets the same skills.

Paths Windows can't write, such as `aux.txt` or a name ending in a dot, are left out on Windows only and listed under `refused`. Git submodules are listed under `submodules`; their folders stay empty.

To read another commit already in the bare repository without publishing it, use `withGitTree(repo, commit, read)`.

### Repository names

```ts
import { gitUrl, repoKey } from "skillrc/io";

gitUrl("acme/skills"); // "https://github.com/acme/skills.git"
gitUrl("gitlab:acme/skills"); // "https://gitlab.com/acme/skills.git"
repoKey("git@github.com:Acme/skills.git"); // "github.com/acme/skills"
```

`repoKey` reduces a URL to host and path, so its https, ssh and `owner/repo` forms compare equal.

## npm packages

`fetchNpm(places, spec, registry, cacheRoot, options?)` downloads a package and returns the folder it unpacked to. It never runs npm or an install script.

```ts
import { fetchNpm } from "skillrc/io";

const { dir, version } = await fetchNpm(places, "@acme/skills@2.1.0", undefined, cacheRoot);
```

The spec is `name`, `name@version` or `name@tag`, with `latest` as the default. A range such as `^2` is not resolved. The folder is `<cacheRoot>/<registry hash>/<name>@<version>`, with a scoped name's `/` written as `+`. A spec with an exact version whose folder exists returns without a request.

The registry is the `registry` argument, then `npm_config_registry`, then `NPM_CONFIG_REGISTRY`, then `https://registry.npmjs.org`. skillrc reads no `.npmrc`. `NPM_TOKEN` goes to the registry as a bearer token, and to the tarball only on the registry's own origin. Pass `sendToken: false` for a registry the user didn't name.

Each tarball is checked against the registry's `integrity` or `shasum`, and refused without one. Links in the archive and paths that leave it are refused before their bodies are read.

### Limits

A server that stops answering would hold the sync and its lock forever, so every download has limits:

| Limit | Value |
| --- | --- |
| Wait for an answer, or for the next bytes | 30 s |
| One download | 5 minutes |
| All downloads of one source | 15 minutes |
| Downloads of one source at once | 8 |
| A tarball, packed or unpacked | 100 MB |
| Entries in an archive | 50,000 |

`<PROGRAM>_FETCH_WAIT_MS` shortens the 30-second wait, for tests.

`createCappedFetch(places, refused, budget?)` returns a `fetch` with these limits, for code that downloads on its own. Failed downloads go into `refused`. `guardedFetch(problem)` returns a `fetch` that checks every URL it would request, redirects included, and never requests one with a problem.

`tarFileSizes` and `zipEntries` list an archive's files and sizes without reading their bodies.

## The sync lock

One sync at a time may write a state folder. The lock is a file, `<state>/sync.lock`, that holds who took it: pid, command, start time, host, boot and pid namespace.

```ts
import { lockText, takeLock } from "skillrc/io";
import { placePaths } from "fleethosts/places";

const note = takeLock(places, placePaths(places).lock(), lockText("merge"));
```

`takeLock` creates the file whole or not at all. While a live holder has it, it throws `LockHeldError`, such as `another mytool sync is running (pid 4182)`. A stale lock is broken, and the note says why:

- its process is gone, or its pid now belongs to another program
- the machine restarted since it was taken
- it is more than two hours old (`LOCK_MAX_AGE_MS`)

A lock taken on another machine or in another container that shares the folder is held until it is two hours old, since its pid means nothing here. `syncRunning(places)` says whether a live holder has the lock now. Most programs never call `takeLock`: `sync` and [`withSyncLock`](https://skillrc.loadsheet.dev/guide/sync#state) take it for you.

## Hashes and trees

`hashDir(places, dir)` returns the sha256 of every file under a folder, by `/`-separated path. A link hashes its target text. `changedFiles(before, after)` lists the paths whose hash differs. That is how a sync tells an upstream change from a local edit.

<!-- vitehub-docs:section-links -->
## In this section

- [Introduction](https://skillrc.loadsheet.dev/raw/guide.md)
- [Installation](https://skillrc.loadsheet.dev/raw/guide/installation.md)
- [Config files](https://skillrc.loadsheet.dev/raw/guide/config-files.md)
- [Fetching](https://skillrc.loadsheet.dev/raw/guide/fetching.md) (this page)
- [Definitions](https://skillrc.loadsheet.dev/raw/guide/definitions.md)
- [Sync](https://skillrc.loadsheet.dev/raw/guide/sync.md)
- [Coding agents](https://skillrc.loadsheet.dev/raw/guide/agents.md)

Next: [Definitions](https://skillrc.loadsheet.dev/raw/guide/definitions.md)

All pages: [llms.txt](https://skillrc.loadsheet.dev/llms.txt)

Something on this page does not work as written? Tell the user, and draft an issue for them to post: [issue tracker](https://github.com/words-with-agents/skillrc/issues). Report a security vulnerability privately, never in a public issue.
