A desktop coding agent with free access to frontier models.
TypeScript
fix(archive): never archive gitignored content
Samrat Talukdar88176e34a1bc
diff --git a/apps/server/src/session-archive/README.md b/apps/server/src/session-archive/README.mdindex b4ceadc0..31a97e48 100644--- a/apps/server/src/session-archive/README.md+++ b/apps/server/src/session-archive/README.md@@ -6,7 +6,8 @@ all-folders policy on, any other folder too, see "All folders" below; withthe touched-files policy on, any other folder gets only the files the agenttouched there, see "Touched files" below):-- at session start: a **base** archive, including `.git/` and gitignored content;+- at session start: a **base** archive, including `.git/` and without anything+ git ignores (see "Gitignored content" below);- after every completed turn that changed anything: a **delta** archive with theadded and modified entries plus the deleted paths;- once more after the last completed turn, when the folder changed since the@@ -36,6 +37,7 @@ The user-facing description is `docs/project-archive.md`.| `detect.ts` | `isArchivableProject(root, detectors?, options?)`, `gitMarkerDetector` and `gitParentDetector` (section 4). A pluggable gate; the `.git` marker, in the root or (`git_parent`) in the nearest parent (a `.git` folder there must hold `HEAD`), never at any account's home on any volume or share, a filesystem, drive, share or mount root, or in a system or app directory (on a UNC share such as `\\wsl$\<distro>`, also `usr`, `etc`, `var`, `opt` and `root`). A `git_parent` root is archived alone, without the parent's `.git`. `folderDetector` / `folderRootRefusal` / `refusedFolderRoot` for the all-folders and touched-files policies (4.4): markers `folder` and `touched` || `policy.ts` | `parseArchivePolicy`: `policy.all_folders` and `policy.touched_files` from the GET /archives/key body; anything but `true` is off || `touched.ts` | Touched-files mode: `TouchedPathStore` (each session's touched paths, appended to `touched/<session>.jsonl`), `scanTouchedFiles` (pass 1 over those paths only: lstat from the root, never through a link out of it, a touched folder never expanded) and `touchedChange` (the delta and the next baseline) |+| `ignore.ts` | Gitignored content: `ArchiveIgnore` (the scan's per-folder ignore scopes: `git ls-files --others --ignored --exclude-standard --directory` in the root's repository, in a nested repository, or with a private empty `GIT_DIR` for a folder in none; the collector's walkFallback `.gitignore` rules without git) and `touchedIgnoredPaths` (`git check-ignore` over touched files only) || `manifest.ts` | Scan with the exclusions and credential filter (5.2, 5.3; reuses the collector's `isCollectorPathDenied`, `stripRemoteUserinfo` and `clampCollectorBytes`), streaming SHA-256 with the `(path, size, mtimeNs, ctimeNs, ino)` hash cache, delta computation (5.8), `manifest.json` (5.6) and the git block (`path` from `git rev-parse --show-prefix`; git runs with `GIT_CEILING_DIRECTORIES` set to the real home so it never climbs into home) || `pack.ts` | Streaming pax tar writer (5.5) with unstable-entry detection (5.9), and the file -> tar -> zstd -> ORSEAL01 -> temp file pipeline (5.10, 13.1) || `seal.ts` | Streaming ORSEAL01 sealer and opener (section 6) over Node `crypto` |@@ -323,6 +325,15 @@ against a loopback sink).- **What is archived.** `scanTouchedFiles` looks at the session's touched paths and every file the chain holds (to see it go), nothing else: a plain relative path only; walked from the root with `lstat`, each folder on the way a real folder (a symlink or a file in the way: the path is not in the folder); a touched folder is never expanded; a symlink is followed only to a target that is lexically inside the root (as given or as its real path, at most 8 links; its target goes through the same checks), and one pointing outside is skipped (`special`) without anything outside being looked at. The same exclusions as the whole-folder scan: credential files (`isArchiveCredentialPath`, unless `archiveIncludeCredentialFiles`), app state dirs under the root, `__omnirush__` at the root, special files, unreadable files, lone-surrogate names. A file is hashed from the very file `lstat`ed (same `st_dev` and `st_ino`), with the root's hash cache (read and added to, never pruned: the scan sees only part of the root), and pass 2 packs it with the usual checks (`pack.ts`). Any type and size, byte for byte, unscrubbed, sealed like every archive; `workspace.git` is `null`.- **Manifest.** `"scope": "touched"` in the sealed `manifest.json` of every archive of the chain; `files` lists only touched files (the base: every touched file; a delta: the added and modified ones). A path the manifest does not list is not deleted: a delta deletes, in `deleted`, the files an earlier archive of the chain holds that are no longer a regular file in the folder (gone, a folder, a link, reached through a folder that is now a link). A file that cannot be read for now stays in the baseline as it was.- **Policy off.** With `touched_files` off or absent nothing is written for such a folder: `captureBase` is `not_archivable` after the probe, and no touched path is kept. A touched chain's captures pause (`not_archivable`) while it is off and catch up once it is on (the touched set is kept). The server refuses a `touched` create from a user whose policy is off with `422 archive_marker_not_allowed`: the drain drops the session's chain (its jobs, the session stopped, one `warn` line, no retry) and keeps the policy as off for `touched` until it is asked again (`POLICY_TTL_MS`), so no other chain starts meanwhile. The same holds for `folder`.+- **Gitignored content.** Nothing git ignores is archived: base, delta and final archives, whole-folder and touched-files alike (`ignore.ts`). It can be rebuilt (`node_modules/`, `dist/`, venvs, caches), and it made single projects many gigabytes. Git decides, with all its rules (every `.gitignore`, `.git/info/exclude`, `core.excludesFile`):+ - **A root in a repository** (a `.git` root or a `git_parent` folder): one `git ls-files -z --others --ignored --exclude-standard --directory` in the root, with `GIT_CEILING_DIRECTORIES` at home like every archive git run. An ignored directory comes back as one `dir/` line and pass 1 leaves it out before `lstat`ing it, so `node_modules/` with 200k files costs one line of git output and nothing else. Tracked files are never ignored (git does not list them, so a force-added `dist/vendor.js` stays). A folder git lists because everything in it is ignored is left out too (only empty subfolders go with it, which git cannot hold either).+ - **A folder in no repository** (all-folders policy, marker `folder`, or git refusing the root's repository): the same command with a private empty bare repository as `GIT_DIR` (`git init --bare --template=` in a fresh `mkdtemp` dir, removed when the scan is done) and the root as `GIT_WORK_TREE`, so the folder's `.gitignore` files apply as git would apply them (`node_modules/` at any depth, negations, nested `.gitignore` files). Nothing is written in the folder.+ - **A nested repository** (a folder below the root holding `.git`: a submodule, a cloned dependency): the outer repository's git never looks inside one, so when pass 1 enters it, it asks that repository (ceiling at its parent, so a broken `.git` there never climbs to the outer one) and uses its answer below it.+ - **Without git** (missing, a run over `IGNORE_GIT_TIMEOUT_MS`, 2 min, or more than `MAX_IGNORED_PATHS`, 2M, ignored paths): the `.gitignore` files, applied with the collector's walkFallback rules (`scopedIgnoreRules`, `ignoredByRules`; a directory also matches as `dir/`, so `dist/` prunes `dist`).+ - **Never ignored:** `.git` itself and everything in it (it is not gitignored and keeps the history), and every `.gitignore` file.+ - **Touched files.** `scanTouchedFiles` asks `git check-ignore -z --stdin` about the touched files it found (in the root's repository, else in the private one with the root as work tree; a batch git refuses is halved until the refused path is alone, and that path is kept), so the folder is never walked; without git, each path's folders are checked against their `.gitignore` rules. An ignored touched file is skipped and counts as gone, so a delta deletes a copy the chain holds.+ - **Deltas.** An ignored path is simply not in the scan, so a path that becomes ignored is in the next delta's `deleted` (with its descendants), and one that stops being ignored is added again; a rename into an ignored folder is a deletion. The hash cache drops ignored paths at the end of the scan.+ - **Wire format unchanged.** The manifest's `excluded` object keeps its six counters (section 5.6); the number of ignored entries left out (an ignored directory counts once) is in `ScanResult.ignored` / `TouchedScanResult.ignored` and the `gitignored` field of the "archive queued" log line. The backend's section 5.1 still says gitignored content is included; see the PR for the doc change.- **Part order.** Parts are uploaded one at a time, in order, streamed from the sealed file. The spec allows up to 4 in parallel; that is a possible later optimisation.- **Pass 2 never reads outside the root.** Node has no `openat`, so pass 2 cannot pin a directory handle. Instead it `lstat`s each directory once, parents first, when the walk enters it. If a directory is no longer a real directory (for example it was swapped for a symlink by `npm link` or a tool), nothing below it is read. Each file is opened with `O_NOFOLLOW | O_NONBLOCK | O_NOCTTY`, so a FIFO swapped in never blocks the capture. The handle's `fstat` must show a regular file with the `st_dev` and `st_ino` that pass 1 `lstat`ed, which catches a swap made after the directory check. Otherwise the member is zero-filled at its manifest size and listed in `unstable.json`, and the next delta sends it again. A changed size or mtime on the same inode still copies the bytes (5.9). This adds about 3% to pass 2 on a 56k-entry tree.- **Memory.** Pass 2 streams through a pool of four 1 MiB tar blocks, recycled once zstd has consumed them. The sealer holds one 1 MiB chunk, and the sink awaits each file write. The manifest is serialised on the fly: once to learn its size, once while it is written. Short-lived zstd and AES-GCM output buffers are the remaining churn. An upload holds the part it is sending (the server's part size, 64 MiB by default). In Bun, a full GC is requested every 64 MiB, every 10k files and around each capture (about 2 ms each at these heap sizes); elsewhere this is a no-op.@@ -357,8 +368,8 @@ cd apps/server && bun --conditions=development test src/session-archive- a directory swapped for a symlink to an outside folder, before pass 2 and while pass 2 is inside it: zero-filled, nothing from outside in the tar; a file swapped for a FIFO does not block;- pax header edge cases;- a multi-MiB `writeSealedArchive` round trip checked with the `zstd` CLI, and a stopped writer rejecting.-- `manifest.test.ts`: UTF-8 byte order; the credential filter; the exclusions (credential, FIFO, app state, `__omnirush__`, unreadable, non-UTF-8); the hash cache; a stopped scan reading nothing; delta for add, modify (content and mode), delete, rename, file to dir, dir to file and symlink retarget; unstable re-send; `.git` changes; manifest JSON, with a delta's `trigger` and a final archive's `reason`; the git block and its `path`; `git status` never rewriting `.git/index`.-- `touched.test.ts`: `scanTouchedFiles` with a binary, a PDF, an untouched file, a touched folder (never expanded), a credential file, `__omnirush__`, an app dir, a symlink inside (followed), links out of the root and a folder linked out of it (skipped; every path the scan looked at is inside the root), a missing file and a FIFO; the hash cache used and kept; plain relative paths only; `touchedChange` (added, modified, gone, unreadable kept); `TouchedPathStore` (paths in memory until tracked, the file read back by a new store, a torn line, forget, a session that is something else, clear).+- `manifest.test.ts`: UTF-8 byte order; the credential filter; the exclusions (credential, FIFO, app state, `__omnirush__`, unreadable, non-UTF-8) with gitignored `node_modules/`, `.venv/` and `dist/` absent; gitignored content: a repository with a nested `.gitignore`, `.git/info/exclude`, a negation, an ignored file beside a tracked one, a force-added tracked file in an ignored folder (kept) and a nested repository with its own `.gitignore`; an ignored folder of 5,000 files pruned (not one of them `lstat`ed); a folder in no repository with nested `.gitignore` files and a negation; git missing (walkFallback rules); deltas when files become ignored, stop being ignored, or move into an ignored folder; the hash cache; a stopped scan reading nothing; delta for add, modify (content and mode), delete, rename, file to dir, dir to file and symlink retarget; unstable re-send; `.git` changes; manifest JSON, with a delta's `trigger` and a final archive's `reason`; the git block and its `path`; `git status` never rewriting `.git/index`.+- `touched.test.ts`: `scanTouchedFiles` skipping touched files git ignores (root and nested `.gitignore`, an ignored folder, a nested repository) and a delta deleting a file that became ignored; `scanTouchedFiles` with a binary, a PDF, an untouched file, a touched folder (never expanded), a credential file, `__omnirush__`, an app dir, a symlink inside (followed), links out of the root and a folder linked out of it (skipped; every path the scan looked at is inside the root), a missing file and a FIFO; the hash cache used and kept; plain relative paths only; `touchedChange` (added, modified, gone, unreadable kept); `TouchedPathStore` (paths in memory until tracked, the file read back by a new store, a torn line, forget, a session that is something else, clear).- `detect.test.ts`: a `.git` dir; a gitfile; no `.git`; an invalid gitfile; a `.git` symlink; home, `/` and app dirs refused; `root_not_directory`; detector plug-ins; `git_parent` (nearest parent wins, a `.git` folder without `HEAD` there qualifies nothing, root `.git` preferred, dotfiles home, system dirs, posix and `path.win32` walks including `/Volumes/<disk>` homes and WSL shares); the all-folders gate: policy off and on, git first, every refusal on macOS, Linux and Windows paths, credential and app-data folders anywhere and in other accounts, Windows device, long and trailing-dot paths, and credential folders on disk and through a link refused without asking the policy.- `upload.test.ts` (in-process fake API and S3):- the happy path;@@ -384,9 +395,9 @@ cd apps/server && bun --conditions=development test src/session-archive- `../omnirush-gateway-broker.test.ts`: `archiveRequest` URL, bearer, 401 refresh and path allowlist.- `../workspace-collector.server.e2e.test.ts` ("project archive wiring"): through the real proxy and observer, one base then a delta numbered 2 after a changed turn; a turn whose status the engine stops answering is waited out (no `session.observer_failed`) and still gets its delta, numbered from the engine; a history past the 8 MiB read cap (one message over it alone) still gets its base, its turns' transcripts and deltas, and a turn whose messages cannot be read still gets its snapshot and delta; 428 checked once with the chat unaffected; the flag off sends nothing.- `index.test.ts`:- - the whole folder: `.git/` and gitignored `node_modules/` and `dist/` present, `.env` and `id_rsa` absent unless `archiveIncludeCredentialFiles`; the base then a delta, each decrypted and checked;+ - the whole folder: `.git/` present, gitignored `node_modules/` and `dist/` absent (also when a turn rebuilds them), `.env` and `id_rsa` absent unless `archiveIncludeCredentialFiles`; the base then a delta, each decrypted and checked;- no delta when nothing changed, `stale_turn` and `exists`;- - no `.git`: not archived with the policy off, absent or not a boolean (only the key read); with it on, archived whole with binaries and ignored-looking files, credentials left out, then a delta; home, userData and a system dir refused without a request; sessions in `~/.gnupg`, `~/.aws/sso/cache`, `~/.docker`, `~/.ssh`, `~/.kube`, `~/.config/gh`, `~/Library/Keychains`, Chrome's profile, `AppData` and a `secrets` folder refused without a request; a git project still archived as git; the policy off with the API failing (502, 401, 428, 503, network): one probe per burst, no sleep, no refresh, nothing written or disabled, and the next git session unchanged; the answer kept for `POLICY_TTL_MS`, turned on and off on the server, deltas pausing and catching up, forgotten at sign-out; a folder inside a larger repository sent with `workspace.git: null`;+ - no `.git`: not archived with the policy off, absent or not a boolean (only the key read); with it on, archived whole with binaries, its `.gitignore` applied (`node_modules/`, `dist/`, `*.blend1` absent), credentials left out, then a delta; home, userData and a system dir refused without a request; sessions in `~/.gnupg`, `~/.aws/sso/cache`, `~/.docker`, `~/.ssh`, `~/.kube`, `~/.config/gh`, `~/Library/Keychains`, Chrome's profile, `AppData` and a `secrets` folder refused without a request; a git project still archived as git; the policy off with the API failing (502, 401, 428, 503, network): one probe per burst, no sleep, no refresh, nothing written or disabled, and the next git session unchanged; the answer kept for `POLICY_TTL_MS`, turned on and off on the server, deltas pausing and catching up, forgotten at sign-out; a folder inside a larger repository sent with `workspace.git: null`;- consent off at the key route and during a drain;- app restart resuming a half-uploaded archive;- a crashed commit discarded;diff --git a/apps/server/src/session-archive/ignore.ts b/apps/server/src/session-archive/ignore.tsnew file mode 100644index 00000000..568b63df--- /dev/null+++ b/apps/server/src/session-archive/ignore.ts@@ -0,0 +1,355 @@+/**+ * Gitignored content is never archived (README "Gitignored content"): what+ * git would ignore can be reproduced (`node_modules/`, build output, venvs,+ * caches), so base, delta and final archives leave it out, and so does a+ * touched-files capture.+ *+ * Git answers with its own rules (every `.gitignore`, `.git/info/exclude`,+ * `core.excludesFile`), once per repository:+ *+ * - a root inside a git work tree: `git ls-files --others --ignored+ * --exclude-standard --directory` in the root. An ignored directory comes+ * back as one `dir/` line, so the scan prunes it without walking it. A+ * tracked file is never ignored (git does not list it);+ * - any other root (an all-folders or touched-files folder): the same command+ * with a private, empty bare repository as `GIT_DIR` (a fresh temp dir,+ * removed once the scan is done) and the root as the work tree, so the+ * folder's `.gitignore` files apply exactly as git would apply them, and+ * nothing is written in the folder;+ * - a nested repository (a folder below the root holding `.git`, such as a+ * submodule or a cloned dependency) gets its own answer, from its own+ * repository, when the scan enters it: git never looks inside it from the+ * outer one;+ * - without a working git (missing, timed out, too many ignored paths): the+ * `.gitignore` files, applied with the collector's walkFallback rules.+ *+ * `.git` itself and the `.gitignore` files are never ignored.+ */+import { spawn } from "node:child_process";+import { constants as fsConstants, realpathSync } from "node:fs";+import { mkdtemp, open, rm } from "node:fs/promises";+import { homedir, tmpdir } from "node:os";+import { delimiter, join } from "node:path";++import { ignoredByRules, parseGitignoreRules, scopedIgnoreRules } from "../workspace-collector.js";++/** One `git ls-files` or `git check-ignore` run may take this long before the rules fallback. */+export const IGNORE_GIT_TIMEOUT_MS = 120_000;+/** More ignored paths than this from one repository and git's answer is dropped for the rules fallback. */+export const MAX_IGNORED_PATHS = 2_000_000;+const MAX_GITIGNORE_BYTES = 1024 * 1024;+const PROBE_TIMEOUT_MS = 15_000;+const READ_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0) | (fsConstants.O_NOCTTY ?? 0);++/**+ * GIT_CEILING_DIRECTORIES with the real home directory appended: git never+ * climbs into home, so a folder whose nearest `.git` git rejects (an empty+ * folder, say) cannot pick up a dotfiles repository there.+ */+export function gitCeilingDirectories(): string {+ let home = homedir();+ try {+ home = realpathSync(home);+ } catch {+ // An unreadable home is used as given.+ }+ const existing = process.env.GIT_CEILING_DIRECTORIES;+ if (!home) return existing ?? "";+ return existing ? `${existing}${delimiter}${home}` : home;+}++/** The environment of every archive git run: never above home, no prompt, no optional lock, no pager, C locale. */+export function archiveGitEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ GIT_CEILING_DIRECTORIES: gitCeilingDirectories(),+ GIT_TERMINAL_PROMPT: "0",+ GIT_OPTIONAL_LOCKS: "0",+ GIT_PAGER: "cat",+ PAGER: "cat",+ LC_ALL: "C",+ };+ // A repository chosen by the caller's environment never answers for the root.+ for (const name of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY"]) delete env[name];+ return { ...env, ...extra };+}++type NulRun = { status: "ok" | "failed" | "timeout" | "overflow"; code: number | null; paths: Set<string> };++/**+ * Runs git and collects its NUL-separated output as a set, streaming (a+ * listing of a million ignored files is never one string). A trailing `/`+ * (an ignored directory) is dropped. At most MAX_IGNORED_PATHS are kept.+ */+function gitNulSet(cwd: string, args: readonly string[], env: NodeJS.ProcessEnv, timeoutMs: number, input?: string, signal?: AbortSignal): Promise<NulRun> {+ return new Promise((resolvePromise) => {+ const paths = new Set<string>();+ let pending: Buffer | null = null;+ let settled = false;+ let child: ReturnType<typeof spawn> | null = null;+ const finish = (status: NulRun["status"], code: number | null) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ signal?.removeEventListener("abort", onAbort);+ resolvePromise({ status, code, paths });+ };+ const onAbort = () => {+ child?.kill("SIGKILL");+ finish("failed", null);+ };+ const timer = setTimeout(() => {+ child?.kill("SIGKILL");+ finish("timeout", null);+ }, timeoutMs);+ timer.unref?.();+ if (signal?.aborted) {+ finish("failed", null);+ return;+ }+ signal?.addEventListener("abort", onAbort, { once: true });+ try {+ child = spawn("git", ["-C", cwd, "-c", "core.fsmonitor=false", "-c", "core.quotePath=false", ...args], {+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "ignore"],+ windowsHide: true,+ env,+ });+ } catch {+ finish("failed", null);+ return;+ }+ child.stdout?.on("data", (chunk: Buffer) => {+ if (settled) return;+ let data = pending ? Buffer.concat([pending, chunk]) : chunk;+ let start = 0;+ for (let end = data.indexOf(0, start); end !== -1; end = data.indexOf(0, start)) {+ let path = data.toString("utf8", start, end);+ start = end + 1;+ if (path.endsWith("/")) path = path.slice(0, -1);+ if (path) paths.add(path);+ }+ data = data.subarray(start);+ pending = data.length > 0 ? Buffer.from(data) : null;+ if (paths.size > MAX_IGNORED_PATHS) {+ child?.kill("SIGKILL");+ finish("overflow", null);+ }+ });+ child.on("error", () => finish("failed", null));+ child.on("close", (code) => finish(code === 0 ? "ok" : "failed", code));+ if (input !== undefined) {+ child.stdin?.on("error", () => undefined);+ child.stdin?.end(input);+ }+ });+}++// --- the private repository for folders that are not in one -----------------------------++/**+ * Runs `use` with an empty bare repository in a fresh private temp dir+ * (null without a working git), removed afterwards.+ */+async function withScratchRepository<T>(use: (gitDir: string | null) => Promise<T>): Promise<T> {+ let dir: string | null = null;+ try {+ dir = await mkdtemp(join(tmpdir(), "omnirush-archive-ignore-"));+ } catch {+ return use(null);+ }+ try {+ const init = await gitNulSet(dir, ["init", "-q", "--bare", "--template=", dir], archiveGitEnv(), PROBE_TIMEOUT_MS);+ return await use(init.status === "ok" ? dir : null);+ } finally {+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);+ }+}++// --- scopes ---------------------------------------------------------------------------++/**+ * What decides ignoring below a directory: git's answer for a repository+ * (paths relative to `prefix`, the repository's folder under the root, with a+ * trailing `/` unless it is the root), the `.gitignore` rules in force+ * (fallback), or nothing (inside `.git`).+ */+export type IgnoreScope =+ | { kind: "git"; prefix: string; ignored: ReadonlySet<string> }+ | { kind: "rules"; rules: readonly string[] }+ | { kind: "none" };++const NO_IGNORE: IgnoreScope = { kind: "none" };+const NO_RULES: IgnoreScope = { kind: "rules", rules: [] };++function isGitName(part: string): boolean {+ return part.toLowerCase() === ".git";+}++/** How the root's answer was worked out: its repository, the private one, the .gitignore rules, or nothing to go on. */+export type IgnoreSource = "repository" | "folder" | "rules";++/**+ * Whether `scope` ignores `rel` (a root-relative path whose parent the scope+ * belongs to). `.git` and `.gitignore` never are.+ */+export function scopeIgnores(scope: IgnoreScope, rel: string, isDir: boolean): boolean {+ if (scope.kind === "none") return false;+ const slash = rel.lastIndexOf("/");+ const name = slash === -1 ? rel : rel.slice(slash + 1);+ if (isGitName(name) || name === ".gitignore") return false;+ if (scope.kind === "git") return rel.startsWith(scope.prefix) && scope.ignored.has(rel.slice(scope.prefix.length));+ if (scope.rules.length === 0) return false;+ return ignoredByRules(rel, scope.rules) || (isDir && ignoredByRules(`${rel}/`, scope.rules));+}++/** A folder's `.gitignore` rules; none when it is missing, not a regular file, or too large. */+async function readGitignoreRules(absDir: string): Promise<string[]> {+ let handle: Awaited<ReturnType<typeof open>>;+ try {+ handle = await open(join(absDir, ".gitignore"), READ_FLAGS);+ } catch {+ return [];+ }+ try {+ const stats = await handle.stat();+ if (!stats.isFile() || stats.size > MAX_GITIGNORE_BYTES) return [];+ return parseGitignoreRules(await handle.readFile("utf8"));+ } catch {+ return [];+ } finally {+ await handle.close().catch(() => undefined);+ }+}++/** `git ls-files` listing every untracked ignored path, an ignored directory as one line. */+const LIST_IGNORED = ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"] as const;++/**+ * The ignore decisions of one scan of a root. `rootScope` is asked once, at+ * the root; `enter` for each folder the scan walks into, with what its+ * listing showed (`.git`, `.gitignore`).+ */+export class ArchiveIgnore {+ /** Entries left out as ignored (whole directories count once). */+ ignored = 0;+ source: IgnoreSource = "rules";++ constructor(private readonly root: string, private readonly signal?: AbortSignal) {}++ /** The root's scope: its repository's answer, the private repository's, or its `.gitignore` rules. */+ async rootScope(hasGitignore: boolean): Promise<IgnoreScope> {+ const own = await gitNulSet(this.root, LIST_IGNORED, archiveGitEnv(), IGNORE_GIT_TIMEOUT_MS, undefined, this.signal);+ this.signal?.throwIfAborted();+ if (own.status === "ok") {+ this.source = "repository";+ return { kind: "git", prefix: "", ignored: own.paths };+ }+ if (own.status === "failed") {+ const folder = await withScratchRepository(async (scratch) => scratch+ ? gitNulSet(this.root, LIST_IGNORED, archiveGitEnv({ GIT_DIR: scratch, GIT_WORK_TREE: this.root }), IGNORE_GIT_TIMEOUT_MS, undefined, this.signal)+ : null);+ this.signal?.throwIfAborted();+ if (folder?.status === "ok") {+ this.source = "folder";+ return { kind: "git", prefix: "", ignored: folder.paths };+ }+ }+ this.source = "rules";+ return hasGitignore ? { kind: "rules", rules: scopedIgnoreRules("", await readGitignoreRules(this.root)) } : NO_RULES;+ }++ /** The scope below `rel` (not the root), a folder whose parent had `parent`. */+ async enter(rel: string, abs: string, parent: IgnoreScope, listing: { git: boolean; gitignore: boolean }): Promise<IgnoreScope> {+ if (parent.kind === "none" || rel.split("/").some(isGitName)) return NO_IGNORE;+ if (listing.git) {+ const nested = await gitNulSet(abs, LIST_IGNORED, archiveGitEnv({ GIT_CEILING_DIRECTORIES: `${gitCeilingDirectories()}${delimiter}${join(abs, "..")}` }), IGNORE_GIT_TIMEOUT_MS, undefined, this.signal);+ this.signal?.throwIfAborted();+ if (nested.status === "ok") return { kind: "git", prefix: `${rel}/`, ignored: nested.paths };+ }+ if (parent.kind === "rules" && listing.gitignore) {+ const local = await readGitignoreRules(abs);+ if (local.length > 0) return { kind: "rules", rules: [...parent.rules, ...scopedIgnoreRules(rel, local)] };+ }+ return parent;+ }+}++/**+ * The touched files (root-relative, each a regular file the scan lstat'ed)+ * that git ignores: `git check-ignore` over just those paths, in the root's+ * repository or, for a folder in none, in the private repository with the+ * root as work tree (a nested repository's `.gitignore` files apply there+ * too). Nothing but those paths is looked at, so the folder is never walked.+ * Without git, each path's folders are checked against their `.gitignore`+ * rules. A path git refuses on its own (a race with a symlink swap) is kept.+ */+export async function touchedIgnoredPaths(root: string, paths: readonly string[], signal?: AbortSignal): Promise<Set<string>> {+ if (paths.length === 0) return new Set();+ const inRepository = await gitNulSet(root, ["rev-parse", "--is-inside-work-tree"], archiveGitEnv(), PROBE_TIMEOUT_MS, undefined, signal);+ signal?.throwIfAborted();+ const answer = inRepository.status === "ok"+ ? await checkIgnoreIsolated(root, [...paths], archiveGitEnv(), signal)+ : await withScratchRepository(async (scratch) => scratch ? checkIgnoreIsolated(root, [...paths], archiveGitEnv({ GIT_DIR: scratch, GIT_WORK_TREE: root }), signal) : null);+ signal?.throwIfAborted();+ return answer ?? rulesIgnoredPaths(root, paths);+}++/** `git check-ignore` for a batch, halved around a path git refuses (exit 128) so one never changes the others' answer. */+async function checkIgnoreIsolated(root: string, paths: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<Set<string> | null> {+ const ask = async (batch: string[]): Promise<Set<string> | null> => {+ const run = await gitNulSet(root, ["check-ignore", "-z", "--stdin"], env, IGNORE_GIT_TIMEOUT_MS, `${batch.join("\0")}\0`, signal);+ if (run.status === "ok" || (run.status === "failed" && run.code === 1)) return run.paths;+ if (run.status === "failed" && run.code === 128) return null;+ throw new Error("git check-ignore failed");+ };+ const ignored = new Set<string>();+ const isolate = async (batch: string[]): Promise<void> => {+ signal?.throwIfAborted();+ const answer = await ask(batch);+ if (answer) {+ for (const path of answer) ignored.add(path);+ return;+ }+ if (batch.length === 1) return;+ const middle = batch.length >> 1;+ await isolate(batch.slice(0, middle));+ await isolate(batch.slice(middle));+ };+ try {+ await isolate(paths);+ } catch {+ return null;+ }+ return ignored;+}++/** The walkFallback decision for single paths: a path is ignored when it, or a folder above it, matches the rules in force there. */+async function rulesIgnoredPaths(root: string, paths: readonly string[]): Promise<Set<string>> {+ const rulesByDirectory = new Map<string, Promise<IgnoreScope>>();+ const scopeAt = (directory: string): Promise<IgnoreScope> => {+ let scope = rulesByDirectory.get(directory);+ if (!scope) {+ scope = (async (): Promise<IgnoreScope> => {+ if (directory === "") return { kind: "rules", rules: scopedIgnoreRules("", await readGitignoreRules(root)) };+ const slash = directory.lastIndexOf("/");+ const parent = await scopeAt(slash === -1 ? "" : directory.slice(0, slash));+ if (parent.kind !== "rules" || directory.split("/").some(isGitName)) return NO_IGNORE;+ const local = await readGitignoreRules(join(root, ...directory.split("/")));+ return local.length > 0 ? { kind: "rules", rules: [...parent.rules, ...scopedIgnoreRules(directory, local)] } : parent;+ })();+ rulesByDirectory.set(directory, scope);+ }+ return scope;+ };+ const ignored = new Set<string>();+ for (const path of paths) {+ const parts = path.split("/");+ for (let depth = 1; depth <= parts.length; depth += 1) {+ if (scopeIgnores(await scopeAt(parts.slice(0, depth - 1).join("/")), parts.slice(0, depth).join("/"), depth < parts.length)) {+ ignored.add(path);+ break;+ }+ }+ }+ return ignored;+}diff --git a/apps/server/src/session-archive/index.test.ts b/apps/server/src/session-archive/index.test.tsindex 757244a0..b1da82b4 100644--- a/apps/server/src/session-archive/index.test.ts+++ b/apps/server/src/session-archive/index.test.ts@@ -56,7 +56,7 @@ async function project(): Promise<{ root: string; blend: Buffer; head: string }>}describe("SessionArchiver", () => {- test("whole folder: base with .git and ignored content, credentials left out, then a delta after a change", async () => {+ test("whole folder: base with .git and without gitignored content, credentials left out, then a delta after a change", async () => {const server = new FakeArchiveServer();const { root, blend, head } = await project();const state = await tempDir("state");@@ -73,9 +73,13 @@ describe("SessionArchiver", () => {expect(first!.request.sha256).toBe(sha256(first!.object!));const members = await openArchive(first!.object!);const names = members.map((member) => member.name);- for (const present of [".git/HEAD", ".git/config", ".git/refs/heads/main", ".git/refs/heads/token-fix", "node_modules/left-pad/index.js", "dist/bundle.js", "assets/scene.blend", "src/app.ts", ".gitignore"]) {+ for (const present of [".git/HEAD", ".git/config", ".git/refs/heads/main", ".git/refs/heads/token-fix", "assets/scene.blend", "src/app.ts", ".gitignore"]) {expect(names).toContain(present);}+ // Gitignored content can be reproduced: none of it is archived.+ for (const ignored of ["node_modules", "node_modules/left-pad", "node_modules/left-pad/index.js", "dist", "dist/bundle.js"]) {+ expect(names).not.toContain(ignored);+ }expect(names).not.toContain(".env");expect(names).not.toContain("id_rsa");expect(members.find((member) => member.name === "assets/scene.blend")!.content.equals(blend)).toBe(true);@@ -94,11 +98,15 @@ describe("SessionArchiver", () => {expect("deleted" in manifest).toBe(false);expect(Array.isArray(manifest.files) ? manifest.files.length : -1).toBe(members.length - 1);- // A turn edits, adds, deletes and commits.+ // A turn edits, adds, deletes and commits, and rebuilds ignored content.await writeFile(join(root, "src/app.ts"), "export const app = 2;\n");await writeFile(join(root, "src/new.ts"), "export const added = true;\n");+ await rm(join(root, "assets/scene.blend"));await rm(join(root, "dist/bundle.js"));- await git(root, "add", "src");+ await writeFile(join(root, "dist/bundle.2.js"), "console.log(2);\n");+ await mkdir(join(root, "node_modules/is-odd"), { recursive: true });+ await writeFile(join(root, "node_modules/is-odd/index.js"), "module.exports = (n) => n % 2;\n");+ await git(root, "add", "-A", "src", "assets");await git(root, "commit", "-q", "-m", "turn one");const delta = await subject.captureDelta("ses_whole_folder", root, 1);expect(delta).toMatchObject({ status: "queued", kind: "delta", sequence: 1 });@@ -107,11 +115,10 @@ describe("SessionArchiver", () => {expect(second.request).toMatchObject({ kind: "delta", sequence: 1, turn: 1, parent_archive_id: first!.request.archive_id });const deltaMembers = await openArchive(second.object!);const deltaManifest = manifestOf(deltaMembers);- expect(deltaManifest).toMatchObject({ kind: "delta", sequence: 1, turn: 1, parent_archive_id: first!.request.archive_id, deleted: ["dist/bundle.js"] });+ expect(deltaManifest).toMatchObject({ kind: "delta", sequence: 1, turn: 1, parent_archive_id: first!.request.archive_id, deleted: ["assets/scene.blend"] });const changed = deltaMembers.slice(1).map((member) => member.name);expect(changed).toEqual(expect.arrayContaining(["src/app.ts", "src/new.ts", ".git/refs/heads/main", ".git/index"]));- expect(changed).not.toContain("node_modules/left-pad/index.js");- expect(changed).not.toContain("assets/scene.blend");+ expect(changed.filter((name) => name.startsWith("node_modules") || name.startsWith("dist"))).toEqual([]);expect(deltaMembers.find((member) => member.name === "src/app.ts")!.content.toString()).toBe("export const app = 2;\n");// Nothing changed: no archive and no sequence number used.@@ -181,8 +188,10 @@ describe("SessionArchiver", () => {await mkdir(join(root, "node_modules/dep"), { recursive: true });await writeFile(join(root, "node_modules/dep/index.js"), "module.exports = 1;\n");await mkdir(join(root, "dist"));+ await writeFile(join(root, "dist/app.js"), "built\n");+ await mkdir(join(root, "wasm"));const binary = randomBytes(200 * 1024);- await writeFile(join(root, "dist/app.wasm"), binary);+ await writeFile(join(root, "wasm/app.wasm"), binary);await writeFile(join(root, ".env"), "TOKEN=abc\n");await mkdir(join(repo, "packages/other"), { recursive: true });await writeFile(join(repo, "packages/other/sibling.ts"), "export {};\n");@@ -196,11 +205,13 @@ describe("SessionArchiver", () => {expect(first!.request).toMatchObject({ kind: "base", marker: ".git" });const members = await openArchive(first!.object!);const names = members.map((member) => member.name);- expect(names).toEqual(expect.arrayContaining(["src/main.ts", "src/deep/deeper/data.bin", "node_modules/dep/index.js", "dist/app.wasm"]));+ expect(names).toEqual(expect.arrayContaining(["src/main.ts", "src/deep/deeper/data.bin", "wasm/app.wasm"]));+ // The repository's .gitignore (node_modules/, dist/ at any depth) applies to the folder inside it.+ expect(names.filter((name) => name.startsWith("node_modules") || name.startsWith("dist"))).toEqual([]);expect(names.filter((name) => name.split("/").includes(".git"))).toEqual([]);for (const outside of ["src/app.ts", ".gitignore", "assets/scene.blend", "sibling.ts", "packages/other/sibling.ts", ".env"]) expect(names).not.toContain(outside);expect(names.every((name) => !name.startsWith("/") && !name.split("/").includes(".."))).toBe(true);- expect(members.find((member) => member.name === "dist/app.wasm")!.content.equals(binary)).toBe(true);+ expect(members.find((member) => member.name === "wasm/app.wasm")!.content.equals(binary)).toBe(true);expect(manifestOf(members)).toMatchObject({workspace: { label: "app", marker: ".git", git: { head, branch: "main", remote: "https://github.com/acme/app.git", dirty: true, path: "packages/app" } },excluded: { credential: 1 },@@ -247,7 +258,7 @@ describe("SessionArchiver", () => {expect(JSON.parse(stdout)).toEqual([null, null]);});- test("with the all-folders policy on, a folder without .git is archived whole: binaries and ignored-looking files kept, credentials left out", async () => {+ test("with the all-folders policy on, a folder without .git is archived whole: binaries kept, its .gitignore applied, credentials left out", async () => {const server = new FakeArchiveServer();server.policy = { all_folders: true };const home = await tempDir("home");@@ -260,8 +271,7 @@ describe("SessionArchiver", () => {await mkdir(join(root, "assets"));const blend = randomBytes(300 * 1024);await writeFile(join(root, "assets/scene.blend"), blend);- const backup = randomBytes(64 * 1024);- await writeFile(join(root, "assets/scene.blend1"), backup);+ await writeFile(join(root, "assets/scene.blend1"), randomBytes(64 * 1024));await writeFile(join(root, ".env"), "API_KEY=sk-live-1234567890\n");await writeFile(join(root, "id_rsa"), "-----BEGIN OPENSSH PRIVATE KEY-----\n");const subject = archiver(server, await tempDir("state"), { folderGate: { homeDir: home } });@@ -276,11 +286,11 @@ describe("SessionArchiver", () => {expect(first!.request).toMatchObject({ session_id: "ses_plain_folder", kind: "base", sequence: 0, marker: "folder" });const members = await openArchive(first!.object!);const names = members.map((member) => member.name);- expect(names).toEqual(expect.arrayContaining([".gitignore", "node_modules/left-pad/index.js", "dist/bundle.js", "assets/scene.blend", "assets/scene.blend1"]));+ expect(names).toEqual(expect.arrayContaining([".gitignore", "assets/scene.blend"]));+ for (const ignored of ["node_modules", "node_modules/left-pad/index.js", "dist", "dist/bundle.js", "assets/scene.blend1"]) expect(names).not.toContain(ignored);expect(names).not.toContain(".env");expect(names).not.toContain("id_rsa");expect(members.find((member) => member.name === "assets/scene.blend")!.content.equals(blend)).toBe(true);- expect(members.find((member) => member.name === "assets/scene.blend1")!.content.equals(backup)).toBe(true);expect(manifestOf(members)).toMatchObject({ kind: "base", workspace: { label: "render-job", marker: "folder", git: null }, excluded: { credential: 2 } });const edited = randomBytes(1024);diff --git a/apps/server/src/session-archive/index.ts b/apps/server/src/session-archive/index.tsindex 3264e191..f9bd0152 100644--- a/apps/server/src/session-archive/index.ts+++ b/apps/server/src/session-archive/index.ts@@ -857,6 +857,8 @@ export class SessionArchiver {let files: ScannedEntry[];let deleted: string[] | undefined;let excluded: ExcludedCounts;+ /** Entries left out because git ignores them (logged; not in the manifest). */+ let ignored: number;/** The chain's entry list after this archive: the next baseline. */let next: readonly ArchiveEntry[];let git: ArchiveGit | null = null;@@ -879,6 +881,7 @@ export class SessionArchiver {files = change.files;deleted = kind === "delta" ? change.deleted : undefined;excluded = scan.excluded;+ ignored = scan.ignored;next = change.next;} else {const scanning = scanArchiveTree(state.root, { excludedDirs: this.appDirs, includeCredentialFiles: this.includeCredentials, hashCache: cache, ...(signal ? { signal } : {}) });@@ -888,6 +891,7 @@ export class SessionArchiver {const scan = await scanning;files = scan.entries;excluded = scan.excluded;+ ignored = scan.ignored;next = scan.entries;if (kind === "delta") {const baseline = await this.readBaseline(state);@@ -1009,6 +1013,7 @@ export class SessionArchiver {bytes: sealed.size,files: files.length,...(deleted ? { deleted: deleted.length } : {}),+ ...(ignored > 0 ? { gitignored: ignored } : {}),...(unstable.size > 0 ? { unstable: unstable.size } : {}),});return { status: "queued", archiveId, kind, sequence, size: sealed.size };diff --git a/apps/server/src/session-archive/manifest.test.ts b/apps/server/src/session-archive/manifest.test.tsindex 77039a94..f61e534b 100644--- a/apps/server/src/session-archive/manifest.test.ts+++ b/apps/server/src/session-archive/manifest.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, test } from "bun:test";import { execFile } from "node:child_process";-import { chmod, mkdir, rename, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";+import { appendFile, chmod, mkdir, readdir, rename, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";import { join } from "node:path";import { promisify } from "node:util";@@ -60,7 +61,7 @@ describe("credential filter", () => {});describe("scan", () => {- test("the whole folder: .git, ignored and build content present; exclusions counted", async () => {+ test("the whole folder: .git and unignored build content present, gitignored content absent; exclusions counted", async () => {const root = await tempDir("scan");const state = join(root, ".omnirush-state");await mkdir(join(root, ".git/refs/heads"), { recursive: true });@@ -70,11 +71,13 @@ describe("scan", () => {await writeFile(join(root, "node_modules/js-tokens/index.js"), "module.exports = 1;\n");await mkdir(join(root, ".venv/bin"), { recursive: true });await symlink("/usr/bin/python3", join(root, ".venv/bin/python"));+ await mkdir(join(root, "tools"), { recursive: true });+ await symlink("/usr/bin/python3", join(root, "tools/python"));await mkdir(join(root, "dist"), { recursive: true });await writeFile(join(root, "dist/out.js"), "built\n");await mkdir(join(root, "build"), { recursive: true });await writeFile(join(root, "build/app.o"), Buffer.from([0, 1, 2, 3]));- await writeFile(join(root, ".gitignore"), "node_modules/\ndist/\nbuild/\n.venv/\n");+ await writeFile(join(root, ".gitignore"), "node_modules/\ndist/\n.venv/\n");await writeFile(join(root, ".env"), "SECRET=1\n");await writeFile(join(root, "id_rsa"), "key\n");await mkdir(join(root, ".ssh"));@@ -87,20 +90,25 @@ describe("scan", () => {await writeFile(join(root, "locked/inner/file.txt"), "x");await chmod(join(root, "locked"), 0o000);try {- const { entries, excluded } = await scanArchiveTree(root, { excludedDirs: [state] });+ const { entries, excluded, ignored } = await scanArchiveTree(root, { excludedDirs: [state] });const listed = paths(entries);- for (const present of [".git", ".git/HEAD", ".git/refs/heads/token-fix", "node_modules/js-tokens/index.js", ".venv/bin/python", "dist/out.js", "build/app.o", ".gitignore", ".ssh", "locked"]) {+ for (const present of [".git", ".git/HEAD", ".git/refs/heads/token-fix", "tools/python", "build", "build/app.o", ".gitignore", ".ssh", "locked"]) {expect(listed).toContain(present);}+ // The .gitignore applies (git reads this folder's rules even where its .git is not a repository).+ for (const absent of ["node_modules", "node_modules/js-tokens/index.js", ".venv", ".venv/bin/python", "dist", "dist/out.js"]) {+ expect(listed).not.toContain(absent);+ }+ expect(ignored).toBe(3);for (const absent of [".env", "id_rsa", ".ssh/config", "__omnirush__", ".omnirush-state", "pipe", "locked/inner"]) {expect(listed).not.toContain(absent);}const running = typeof process.getuid === "function" ? process.getuid() : -1;expect(excluded).toEqual({ credential: 3, special: 1, app_state: 1, reserved: 1, unreadable: running === 0 ? 0 : 1, non_utf8: 0 });expect(listed).toEqual([...listed].sort(compareArchivePaths));- const link = entries.find((entry) => entry.path === ".venv/bin/python")!;+ const link = entries.find((entry) => entry.path === "tools/python")!;expect(link).toMatchObject({ type: "symlink", size: 0, sha256: null, target: "/usr/bin/python3" });- const dir = entries.find((entry) => entry.path === "dist")!;+ const dir = entries.find((entry) => entry.path === "build")!;expect(dir).toMatchObject({ type: "dir", size: 0, sha256: null });const file = entries.find((entry) => entry.path === "build/app.o")!;expect(file).toMatchObject({ type: "file", size: 4, sha256: "054edec1d0211f624fed0cbca9d4f9400b0e491c43742af2c5b0abebf0c990d8" });@@ -296,3 +304,157 @@ describe("manifest and git block", () => {expect(computeArchiveDelta(before, after.entries)).toEqual({ files: [], deleted: [] });});});++describe("gitignored content", () => {+ test("a repository: nested .gitignore, .git/info/exclude, an ignored file beside a tracked one; tracked, .git and .gitignore kept", async () => {+ const root = await tempDir("ignored-repo");+ await git(root, "init", "-q", "-b", "main");+ await writeFile(join(root, ".gitignore"), "node_modules/\ndist/\n*.log\nbuild/*\n!build/keep.txt\n");+ await mkdir(join(root, "src/generated"), { recursive: true });+ await writeFile(join(root, "src/app.ts"), "export {};\n");+ await writeFile(join(root, "src/app.log"), "noise\n");+ await writeFile(join(root, "src/.gitignore"), "generated/\n*.tmp\n");+ await writeFile(join(root, "src/generated/types.ts"), "export {};\n");+ await writeFile(join(root, "src/cache.tmp"), "tmp\n");+ await writeFile(join(root, "README.tmp"), "only src/ ignores *.tmp\n");+ await mkdir(join(root, "node_modules/left-pad"), { recursive: true });+ await writeFile(join(root, "node_modules/left-pad/index.js"), "module.exports = 1;\n");+ await mkdir(join(root, "dist"));+ await writeFile(join(root, "dist/bundle.js"), "built\n");+ await writeFile(join(root, "dist/vendor.js"), "force-added\n");+ await mkdir(join(root, "build"));+ await writeFile(join(root, "build/out.o"), "o");+ await writeFile(join(root, "build/keep.txt"), "kept by a negation\n");+ await writeFile(join(root, "local-notes.md"), "excluded locally\n");+ await appendFile(join(root, ".git/info/exclude"), "local-notes.md\n");+ await git(root, "add", ".gitignore", "src/app.ts", "src/.gitignore");+ await git(root, "add", "-f", "dist/vendor.js");+ await git(root, "commit", "-q", "-m", "initial");+ // A nested repository answers for itself: the outer one never looks inside it.+ await mkdir(join(root, "vendor/lib/node_modules/dep"), { recursive: true });+ await git(join(root, "vendor/lib"), "init", "-q");+ await writeFile(join(root, "vendor/lib/.gitignore"), "node_modules/\n");+ await writeFile(join(root, "vendor/lib/index.js"), "module.exports = 2;\n");+ await writeFile(join(root, "vendor/lib/node_modules/dep/index.js"), "module.exports = 3;\n");++ const { entries, ignored, ignoreSource } = await scanArchiveTree(root);+ const listed = paths(entries);+ expect(ignoreSource).toBe("repository");+ for (const present of [".git", ".git/HEAD", ".git/info/exclude", ".gitignore", "src", "src/.gitignore", "src/app.ts", "README.tmp", "dist", "dist/vendor.js", "build", "build/keep.txt", "vendor/lib/.git/HEAD", "vendor/lib/.gitignore", "vendor/lib/index.js"]) {+ expect(listed).toContain(present);+ }+ for (const absent of ["node_modules", "node_modules/left-pad/index.js", "dist/bundle.js", "src/app.log", "src/generated", "src/generated/types.ts", "src/cache.tmp", "build/out.o", "local-notes.md", "vendor/lib/node_modules", "vendor/lib/node_modules/dep/index.js"]) {+ expect(listed).not.toContain(absent);+ }+ expect(ignored).toBe(8);+ });++ test("an ignored directory with thousands of files is pruned, never walked", async () => {+ const root = await tempDir("ignored-big");+ await git(root, "init", "-q", "-b", "main");+ await writeFile(join(root, ".gitignore"), "node_modules/\n");+ await writeFile(join(root, "index.js"), "require('dep');\n");+ for (let pkg = 0; pkg < 50; pkg += 1) {+ const dir = join(root, "node_modules", `pkg-${pkg}`, "lib");+ await mkdir(dir, { recursive: true });+ await Promise.all(Array.from({ length: 100 }, (_, file) => writeFile(join(dir, `f${file}.js`), `module.exports = ${file};\n`)));+ }+ const metrics = emptyScanMetrics();+ const started = performance.now();+ const { entries, ignored } = await scanArchiveTree(root, { metrics });+ const elapsed = performance.now() - started;+ expect(paths(entries).filter((path) => !path.startsWith(".git/") && path !== ".git")).toEqual([".gitignore", "index.js"]);+ expect(ignored).toBe(1);+ // Only the root's names are looked at outside .git: none of the 5,000 ignored files, nor their 100 folders.+ const gitEntries = entries.filter((entry) => entry.path === ".git" || entry.path.startsWith(".git/")).length;+ expect(metrics.stats).toBe(gitEntries + 2);+ expect(metrics.fileReads).toBeLessThanOrEqual(gitEntries + 2);+ expect(elapsed).toBeLessThan(5_000);+ });++ test("a folder that is not a repository: its .gitignore files apply as git applies them", async () => {+ const root = await tempDir("ignored-folder");+ await writeFile(join(root, ".gitignore"), "node_modules/\n.venv/\n__pycache__/\n*.blend1\n!keep.blend1\n");+ await mkdir(join(root, "app/node_modules/dep"), { recursive: true });+ await writeFile(join(root, "app/node_modules/dep/index.js"), "nested node_modules\n");+ await mkdir(join(root, ".venv/bin"), { recursive: true });+ await writeFile(join(root, ".venv/bin/activate"), "venv\n");+ await mkdir(join(root, "app/__pycache__"), { recursive: true });+ await writeFile(join(root, "app/__pycache__/m.pyc"), "pyc");+ await writeFile(join(root, "app/main.py"), "print(1)\n");+ await writeFile(join(root, "app/.gitignore"), "renders/\n");+ await mkdir(join(root, "app/renders"), { recursive: true });+ await writeFile(join(root, "app/renders/frame.exr"), "exr");+ await writeFile(join(root, "scene.blend"), "blend");+ await writeFile(join(root, "scene.blend1"), "backup");+ await writeFile(join(root, "keep.blend1"), "kept");++ const scratchDirs = async () => (await readdir(tmpdir())).filter((name) => name.startsWith("omnirush-archive-ignore-")).length;+ const scratchBefore = await scratchDirs();+ const { entries, ignored, ignoreSource } = await scanArchiveTree(root);+ const listed = paths(entries);+ expect(ignoreSource).toBe("folder");+ // The private repository is gone once the scan is done.+ expect(await scratchDirs()).toBeLessThanOrEqual(scratchBefore);+ expect(listed).toEqual([".gitignore", "app", "app/.gitignore", "app/main.py", "keep.blend1", "scene.blend"]);+ expect(ignored).toBe(5);+ // The scan writes nothing into the folder.+ expect(listed).not.toContain(".git");+ });++ test("without git, the folder's .gitignore files still apply (the collector's walkFallback rules)", async () => {+ const root = await tempDir("ignored-nogit");+ await writeFile(join(root, ".gitignore"), "node_modules/\ndist/\n*.log\n");+ await mkdir(join(root, "node_modules/dep"), { recursive: true });+ await writeFile(join(root, "node_modules/dep/index.js"), "x");+ await mkdir(join(root, "dist"));+ await writeFile(join(root, "dist/out.js"), "x");+ await writeFile(join(root, "run.log"), "x");+ await mkdir(join(root, "src"));+ await writeFile(join(root, "src/.gitignore"), "gen/\n");+ await mkdir(join(root, "src/gen"));+ await writeFile(join(root, "src/gen/a.ts"), "x");+ await writeFile(join(root, "src/a.ts"), "x");+ const path = process.env.PATH;+ process.env.PATH = "/nonexistent";+ try {+ const metrics = emptyScanMetrics();+ const { entries, ignoreSource } = await scanArchiveTree(root, { metrics });+ expect(ignoreSource).toBe("rules");+ expect(paths(entries)).toEqual([".gitignore", "src", "src/.gitignore", "src/a.ts"]);+ } finally {+ process.env.PATH = path;+ }+ });++ test("deltas: a file that becomes ignored is deleted, one that is un-ignored comes back, a rename into an ignored folder is a deletion", async () => {+ const root = await tempDir("ignored-delta");+ await git(root, "init", "-q", "-b", "main");+ await writeFile(join(root, ".gitignore"), "dist/\n");+ await writeFile(join(root, "notes.txt"), "notes\n");+ await writeFile(join(root, "debug.log"), "log\n");+ await mkdir(join(root, "out"));+ await writeFile(join(root, "out/report.html"), "<p>\n");+ await writeFile(join(root, "move-me.txt"), "moving\n");+ await mkdir(join(root, "dist"));+ await writeFile(join(root, "dist/bundle.js"), "built\n");+ const scan = async () => (await scanArchiveTree(root)).entries.filter((entry) => entry.path !== ".git" && !entry.path.startsWith(".git/"));+ const base = (await scan()).map(archiveEntry);+ expect(paths(base)).toEqual([".gitignore", "debug.log", "move-me.txt", "notes.txt", "out", "out/report.html"]);++ // The rules change: *.log and out/ become ignored, dist/ no longer is.+ await writeFile(join(root, ".gitignore"), "*.log\nout/\n");+ await rename(join(root, "move-me.txt"), join(root, "out/move-me.txt"));+ const current = await scan();+ const delta = computeArchiveDelta(base, current);+ expect(paths(delta.files)).toEqual([".gitignore", "dist", "dist/bundle.js"]);+ expect(delta.deleted).toEqual(["debug.log", "move-me.txt", "out", "out/report.html"]);++ // And back: the next delta restores what is no longer ignored.+ const next = current.map(archiveEntry);+ await writeFile(join(root, ".gitignore"), "dist/\n");+ const back = computeArchiveDelta(next, await scan());+ expect(paths(back.files)).toEqual([".gitignore", "debug.log", "out", "out/move-me.txt", "out/report.html"]);+ expect(back.deleted).toEqual(["dist", "dist/bundle.js"]);+ });+});diff --git a/apps/server/src/session-archive/manifest.ts b/apps/server/src/session-archive/manifest.tsindex d70283d2..379170b9 100644--- a/apps/server/src/session-archive/manifest.ts+++ b/apps/server/src/session-archive/manifest.ts@@ -1,19 +1,20 @@/*** Scanning a session root for the project archive (sections 5.2 to 5.8): the- * whole folder, `.git/` and ignored content included, minus the exclusions of- * 5.2; streaming SHA-256 with a (path, size, mtimeNs, ctimeNs, ino) cache;+ * whole folder, `.git/` included, minus the exclusions of 5.2 and minus every+ * gitignored path (`ignore.ts`: an ignored directory is pruned unwalked);+ * streaming SHA-256 with a (path, size, mtimeNs, ctimeNs, ino) cache;* delta computation against the previous archive's entry list; and the* `__omnirush__/manifest.json` document.*/import { spawn } from "node:child_process";import { createHash } from "node:crypto";-import { constants as fsConstants, realpathSync, type BigIntStats } from "node:fs";+import { constants as fsConstants, type BigIntStats } from "node:fs";import { lstat, open, readdir, readlink, realpath } from "node:fs/promises";-import { homedir } from "node:os";-import { basename, delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";+import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";import { clampCollectorBytes, isCollectorPathDenied, stripRemoteUserinfo } from "../workspace-collector.js";import { hintGarbageCollection } from "./files.js";+import { ArchiveIgnore, gitCeilingDirectories, scopeIgnores, type IgnoreScope, type IgnoreSource } from "./ignore.js";export const ARCHIVE_SCHEMA = "omnirush.archive.v1";export const RESERVED_ROOT_NAME = "__omnirush__";@@ -340,7 +341,13 @@ export type ScanOptions = {signal?: AbortSignal;};-export type ScanResult = { entries: ScannedEntry[]; excluded: ExcludedCounts };+/**+ * `ignored`: entries left out because git ignores them (an ignored directory+ * counts once, its content is never walked), and where the root's answer came+ * from. Not part of the manifest's `excluded` object (section 5.6 is+ * unchanged); the archiver logs it.+ */+export type ScanResult = { entries: ScannedEntry[]; excluded: ExcludedCounts; ignored: number; ignoreSource: IgnoreSource };/*** Runs `operation` over `items` with at most `limit` in flight. The workers@@ -446,8 +453,9 @@ async function hashFile(absolute: string, size: number, buffer: Buffer, metrics:/*** Pass 1: walks the root with lstat (never following a symlink), applies the- * exclusions of section 5.2 and hashes every file whose cache key changed.- * Entries come back sorted by UTF-8 bytes.+ * exclusions of section 5.2, leaves out what git ignores (a whole ignored+ * directory without walking it) and hashes every file whose cache key+ * changed. Entries come back sorted by UTF-8 bytes.*/export async function scanArchiveTree(root: string, options: ScanOptions = {}): Promise<ScanResult> {const concurrency = options.statConcurrency ?? STAT_CONCURRENCY;@@ -459,11 +467,17 @@ export async function scanArchiveTree(root: string, options: ScanOptions = {}):const includeCredentials = options.includeCredentialFiles === true;const entries: ScannedEntry[] = [];const toHash: ScannedEntry[] = [];+ const ignore = new ArchiveIgnore(resolve(root), signal);- const inspect = async (relDir: string, absDir: string, name: string, next: Array<{ rel: string; abs: string }>): Promise<void> => {+ const inspect = async (relDir: string, absDir: string, name: string, scope: IgnoreScope, next: Array<{ rel: string; abs: string; scope: IgnoreScope }>): Promise<void> => {signal?.throwIfAborted();const rel = relDir ? [relDir, name].join("/") : name;const abs = join(absDir, name);+ // Git's answer names ignored directories and files alike: no lstat needed.+ if (scope.kind === "git" && scopeIgnores(scope, rel, false)) {+ ignore.ignored += 1;+ return;+ }let stats: BigIntStats;try {stats = await lstat(abs, { bigint: true });@@ -473,13 +487,17 @@ export async function scanArchiveTree(root: string, options: ScanOptions = {}):excluded.unreadable += 1;return;}+ if (scope.kind === "rules" && scopeIgnores(scope, rel, stats.isDirectory())) {+ ignore.ignored += 1;+ return;+ }if (stats.isDirectory()) {if (prunedDirs.has(rel)) {excluded.app_state += 1;return;}entries.push({ path: rel, type: "dir", size: 0, sha256: null, ...statFields(stats) });- next.push({ rel, abs });+ next.push({ rel, abs, scope });return;}if (!stats.isFile() && !stats.isSymbolicLink()) {@@ -518,9 +536,12 @@ export async function scanArchiveTree(root: string, options: ScanOptions = {}):// Breadth-first, one directory level at a time: list the level's// directories, then lstat every name found, both with bounded concurrency.- let level: Array<{ rel: string; abs: string }> = [{ rel: "", abs: resolve(root) }];+ // Each directory carries its parent's ignore scope; listing it works out+ // its own (a nested repository, a .gitignore under the rules fallback).+ let level: Array<{ rel: string; abs: string; scope: IgnoreScope }> = [{ rel: "", abs: resolve(root), scope: { kind: "none" } }];+ let ignoreSource: IgnoreSource = "rules";while (level.length > 0) {- const names: Array<{ relDir: string; absDir: string; name: string }> = [];+ const names: Array<{ relDir: string; absDir: string; name: string; scope: IgnoreScope }> = [];await forEachBounded(level, concurrency, async (dir) => {signal?.throwIfAborted();let raw: Buffer[];@@ -532,15 +553,29 @@ export async function scanArchiveTree(root: string, options: ScanOptions = {}):excluded.unreadable += 1;return;}+ const listed: string[] = [];+ let hasGit = false;+ let hasGitignore = false;for (const bytes of raw) {const name = decodeName(bytes);if (name === null) excluded.non_utf8 += 1;else if (!dir.rel && name === RESERVED_ROOT_NAME) excluded.reserved += 1;- else names.push({ relDir: dir.rel, absDir: dir.abs, name });+ else {+ listed.push(name);+ if (name.toLowerCase() === ".git") hasGit = true;+ else if (name === ".gitignore") hasGitignore = true;+ }+ }+ let scope: IgnoreScope;+ if (dir.rel) scope = await ignore.enter(dir.rel, dir.abs, dir.scope, { git: hasGit, gitignore: hasGitignore });+ else {+ scope = await ignore.rootScope(hasGitignore);+ ignoreSource = ignore.source;}+ for (const name of listed) names.push({ relDir: dir.rel, absDir: dir.abs, name, scope });});- const next: Array<{ rel: string; abs: string }> = [];- await forEachBounded(names, concurrency, (item) => inspect(item.relDir, item.absDir, item.name, next));+ const next: Array<{ rel: string; abs: string; scope: IgnoreScope }> = [];+ await forEachBounded(names, concurrency, (item) => inspect(item.relDir, item.absDir, item.name, item.scope, next));level = next;}@@ -567,7 +602,7 @@ export async function scanArchiveTree(root: string, options: ScanOptions = {}):const kept = unreadable.size > 0 ? entries.filter((entry) => !unreadable.has(entry)) : entries;kept.sort((left, right) => compareArchivePaths(left.path, right.path));cache?.commitScan();- return { entries: kept, excluded };+ return { entries: kept, excluded, ignored: ignore.ignored, ignoreSource };}// --- delta ----------------------------------------------------------------------@@ -702,23 +737,6 @@ export function buildManifestBytes(input: ManifestInput): Buffer {type GitRun = { ok: boolean; stdout: string; truncated: boolean };-/**- * GIT_CEILING_DIRECTORIES with the real home directory appended: git never- * climbs into home, so a folder whose nearest `.git` git rejects (an empty- * folder, say) cannot pick up a dotfiles repository there.- */-function gitCeilingDirectories(): string {- let home = homedir();- try {- home = realpathSync(home);- } catch {- // An unreadable home is used as given.- }- const existing = process.env.GIT_CEILING_DIRECTORIES;- if (!home) return existing ?? "";- return existing ? `${existing}${delimiter}${home}` : home;-}-/** Runs git in the root without locks, prompts or fsmonitor hooks, never above home; reads at most `maxBytes` of stdout. */function runGit(root: string, args: string[], maxBytes = 64 * 1024): Promise<GitRun> {return new Promise((resolvePromise) => {diff --git a/apps/server/src/session-archive/touched.test.ts b/apps/server/src/session-archive/touched.test.tsindex fcb1b655..84ee6fcf 100644--- a/apps/server/src/session-archive/touched.test.ts+++ b/apps/server/src/session-archive/touched.test.ts@@ -89,6 +89,40 @@ describe("scanTouchedFiles", () => {});});+describe("scanTouchedFiles and gitignored files", () => {+ test("a touched file git ignores is skipped (nested .gitignore, an ignored folder, a nested repository), and deletes the chain's copy", async () => {+ const root = await tempDir("touched-ignored");+ await writeFile(join(root, ".gitignore"), "node_modules/\n*.log\n");+ await mkdir(join(root, "node_modules/dep"), { recursive: true });+ await writeFile(join(root, "node_modules/dep/index.js"), "dep");+ await writeFile(join(root, "run.log"), "log");+ await writeFile(join(root, "report.pdf"), "pdf");+ await mkdir(join(root, "app/cache"), { recursive: true });+ await writeFile(join(root, "app/.gitignore"), "cache/\n");+ await writeFile(join(root, "app/cache/blob"), "cached");+ await writeFile(join(root, "app/main.py"), "print(1)");+ await mkdir(join(root, "clone/build"), { recursive: true });+ await execFileAsync("git", ["-C", join(root, "clone"), "init", "-q"]);+ await writeFile(join(root, "clone/.gitignore"), "build/\n");+ await writeFile(join(root, "clone/build/out.o"), "o");+ await writeFile(join(root, "clone/src.c"), "int main;");+ const touched = ["node_modules/dep/index.js", "run.log", "report.pdf", "app/cache/blob", "app/main.py", "clone/build/out.o", "clone/src.c", ".gitignore"];++ const scan = await scanTouchedFiles(root, touched);+ expect(scan.entries.map((entry) => entry.path)).toEqual([".gitignore", "app/main.py", "clone/src.c", "report.pdf"]);+ expect(scan.ignored).toBe(4);+ for (const path of ["node_modules/dep/index.js", "run.log", "app/cache/blob", "clone/build/out.o"]) expect(scan.gone.has(path)).toBe(true);++ // A file archived before it became ignored is deleted by the next delta.+ const baseline = scan.entries.map((entry): ArchiveEntry => ({ path: entry.path, type: "file", mode: entry.mode, size: entry.size, sha256: entry.sha256 }));+ await appendFile(join(root, ".gitignore"), "*.pdf\n");+ const change = touchedChange(baseline, await scanTouchedFiles(root, [...touched, ...baseline.map((entry) => entry.path)]));+ expect(change.deleted).toEqual(["report.pdf"]);+ expect(change.files.map((entry) => entry.path)).toEqual([".gitignore"]);+ expect(change.next.map((entry) => entry.path)).toEqual([".gitignore", "app/main.py", "clone/src.c"]);+ });+});+describe("touchedChange", () => {test("a delta carries added and modified files, deletes only what is gone, and keeps what it could not read", () => {const entry = (path: string, sha: string): ArchiveEntry => ({ path, type: "file", mode: 0o644, size: 1, sha256: sha.repeat(64) });@@ -97,6 +131,7 @@ describe("touchedChange", () => {const change = touchedChange(baseline, {entries: [scanned("doc.pdf", "e"), scanned("new.txt", "f"), scanned("same.png", "d")],gone: new Set(["gone.txt", "never-archived.txt"]),+ ignored: 0,excluded: { credential: 0, special: 0, app_state: 0, reserved: 0, unreadable: 1, non_utf8: 0 },});expect(change.files.map((file) => file.path)).toEqual(["doc.pdf", "new.txt"]);diff --git a/apps/server/src/session-archive/touched.ts b/apps/server/src/session-archive/touched.tsindex 5f523d15..40396476 100644--- a/apps/server/src/session-archive/touched.ts+++ b/apps/server/src/session-archive/touched.ts@@ -7,7 +7,7 @@* disk, and scanTouchedFiles turns them into archive entries at capture* time: regular files inside the root only, never through a symlinked* folder, a touched folder never expanded, with the whole-folder scan's- * exclusions. Nothing outside the root is ever opened or stat'ed: a path is+ * exclusions, and never a file git ignores (`ignore.ts`). Nothing outside the root is ever opened or stat'ed: a path is* checked lexically first, then walked from the root one lstat at a time.*/import { createHash } from "node:crypto";@@ -37,6 +37,7 @@ import {type ScannedEntry,} from "./manifest.js";import { stateKey } from "./files.js";+import { touchedIgnoredPaths } from "./ignore.js";import type { ArchiveLog } from "./upload.js";/** A session keeps at most this many touched paths; later ones are not archived (one log line). */@@ -69,10 +70,13 @@ export type TouchedScanResult = {/*** Touched paths that hold no regular file inside the root any more: gone,* a folder, a symlink, a special file, or reached through a folder that is- * no longer a real folder. A delta deletes those it archived before.+ * no longer a real folder, or a file git now ignores. A delta deletes+ * those it archived before.*/gone: Set<string>;excluded: ExcludedCounts;+ /** Touched files left out because git ignores them (not in `excluded`, section 5.6 is unchanged). */+ ignored: number;};/** A touched path's components when it is a plain relative path (portable `/`), else null. */@@ -112,7 +116,8 @@ function linkTargetInside(path: string, target: string, roots: readonly string[]* inside the root it leads to) walked from the root with lstat, never* following a link, then hashed; excluded like the whole-folder scan* (credential files, app state, reserved names, special files, unreadable- * and non-UTF-8 names). A path that is not plain, or whose link leads out of+ * and non-UTF-8 names), and a file git ignores is left out (and deletes a+ * copy the chain holds, like a gone file). A path that is not plain, or whose link leads out of* the root, is skipped without touching the file system outside the root.*/export async function scanTouchedFiles(root: string, paths: Iterable<string>, options: TouchedScanOptions = {}): Promise<TouchedScanResult> {@@ -230,6 +235,18 @@ export async function scanTouchedFiles(root: string, paths: Iterable<string>, opawait forEachBounded([...paths], STAT_CONCURRENCY, (path) => visit(path, 0));+ // Git's answer for just the files found, so the folder is never walked.+ const ignoredPaths = await touchedIgnoredPaths(base, entries.map((entry) => entry.path), signal);+ signal?.throwIfAborted();+ if (ignoredPaths.size > 0) {+ let kept = 0;+ for (const entry of entries) {+ if (ignoredPaths.has(entry.path)) gone.add(entry.path);+ else entries[kept++] = entry;+ }+ entries.length = kept;+ }+const unreadable = new Set<ScannedEntry>();const buffers: Buffer[] = [];await forEachBounded(entries, HASH_CONCURRENCY, async (entry) => {@@ -260,7 +277,7 @@ export async function scanTouchedFiles(root: string, paths: Iterable<string>, opexcluded.unreadable += unreadable.size;const kept = unreadable.size > 0 ? entries.filter((entry) => !unreadable.has(entry)) : entries;kept.sort((left, right) => compareArchivePaths(left.path, right.path));- return { entries: kept, gone, excluded };+ return { entries: kept, gone, excluded, ignored: ignoredPaths.size };}/** SHA-256 of the first entry.size bytes of the very file pass 1 lstat'ed (same st_dev and st_ino), else null. */diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.tsindex cd4d1f44..c623011f 100644--- a/apps/server/src/workspace-collector.ts+++ b/apps/server/src/workspace-collector.ts@@ -1448,19 +1448,24 @@ function pathCandidates(value: unknown, key = "", output: string[] = [], depth =return output;}+/** The rules of a .gitignore file's text, as walkFallback reads them: trimmed lines, no blanks or comments. */+export function parseGitignoreRules(text: string): string[] {+ return text+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter((line) => line && !line.startsWith("#"));+}+async function readGitignoreFile(directory: string): Promise<string[]> {try {- return (await readFile(resolve(directory, ".gitignore"), "utf8"))- .split(/\r?\n/)- .map((line) => line.trim())- .filter((line) => line && !line.startsWith("#"));+ return parseGitignoreRules(await readFile(resolve(directory, ".gitignore"), "utf8"));} catch {return [];}}/** A directory's .gitignore rules re-rooted at the workspace, as walkFallback applies them. */-function scopedIgnoreRules(prefix: string, localRules: string[]): string[] {+export function scopedIgnoreRules(prefix: string, localRules: string[]): string[] {return localRules.map((rule) => {const negated = rule.startsWith("!");const body = negated ? rule.slice(1) : rule;@@ -1469,7 +1474,7 @@ function scopedIgnoreRules(prefix: string, localRules: string[]): string[] {});}-function ignoredByRules(path: string, rules: string[]): boolean {+export function ignoredByRules(path: string, rules: readonly string[]): boolean {let ignored = false;for (const raw of rules) {const negated = raw.startsWith("!");diff --git a/docs/project-archive.md b/docs/project-archive.mdindex a9005971..5a858010 100644--- a/docs/project-archive.md+++ b/docs/project-archive.md@@ -85,8 +85,8 @@ it (the 2026-09-24 version or later); everyone else stays on git projectsonly. While it is off for your account, no folder without `.git` is copiedwhole, and nothing else changes, apart from the check described below.Once it is on for your account, a chat folder without `.git` is archived-the same way as a git project, including binaries, large files and files-git would ignore.+the same way as a git project, including binaries and large files. Files+its `.gitignore` files exclude are left out, as in a git project.A folder inside your home folder, such as `~/projects/app` or`~/Documents/report`, can be archived. A folder without `.git` is neverarchived when it is your home folder or a folder above it, the root of a@@ -139,8 +139,12 @@ there, as described in [Other folders](#other-folders): nothing is uploadedwhen the chat starts, and each upload holds only touched files.- **When the chat starts:** the whole folder as it is on disk. That- includes the `.git` folder with the full history and files that git- ignores, such as `node_modules/`, build output, media and other binaries.+ includes the `.git` folder with the full history, media and other+ binaries. Files and folders that git ignores (your `.gitignore` files,+ `.git/info/exclude` and your global excludes file), such as+ `node_modules/`, build output, virtual environments and caches, are left+ out: they can be rebuilt from the project. The `.gitignore` files+ themselves are kept.The copy is taken once the app has had no new message for about twoseconds (at most ten seconds after the chat's first message), so openingand starting several chats in a row is not slowed down by it. If the@@ -197,6 +201,15 @@ are still archived.## What is left out+- **Files git ignores.** Anything your `.gitignore` files,+ `.git/info/exclude` or your global git excludes file exclude, such as+ `node_modules/`, `dist/`, virtual environments and caches, because it can+ be rebuilt. An ignored folder is skipped as a whole without being read.+ Files git tracks are always kept, even when an ignore rule matches them,+ and so are the `.git` folder and the `.gitignore` files. In a folder+ without `.git`, its `.gitignore` files apply the same way. A file that+ becomes ignored during a chat is removed from the copy with the next+ upload; one that stops being ignored is added back.- **Credential files.** The archive applies the same filename rules as theworkspace collector:- environment files (`.env`, `.env.local`, ...);