Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(archive): guard homes per volume, keep git below home, record workspace.git.path

ogsamrat275f41be9fc1
diff --git a/apps/server/src/session-archive/README.md b/apps/server/src/session-archive/README.md
index 5da2f169..84c24203 100644
--- a/apps/server/src/session-archive/README.md
+++ b/apps/server/src/session-archive/README.md
@@ -25,8 +25,8 @@ The user-facing description is `docs/project-archive.md`.
| File | Responsibility |
| --- | --- |
-| `detect.ts` | `isArchivableProject(root, detectors?, options?)`, `gitMarkerDetector` and `gitParentDetector` (section 4). A pluggable gate; only the `.git` marker is enabled, in the root or (`git_parent`) in the nearest parent, never at home, a filesystem, drive, share or mount root, or in a system or app directory. A `git_parent` root is archived alone, without the parent's `.git` |
-| `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 |
+| `detect.ts` | `isArchivableProject(root, detectors?, options?)`, `gitMarkerDetector` and `gitParentDetector` (section 4). A pluggable gate; only the `.git` marker is enabled, 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` |
+| `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` |
| `upload.ts` | Multipart upload client over an injectable `fetch` (sections 7 and 13.5) |
@@ -297,8 +297,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.
-- `manifest.test.ts`: UTF-8 byte order; the credential filter; the exclusions (credential, FIFO, app state, `__omnirush__`, unreadable, non-UTF-8); the hash cache; 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; the git block; `git status` never rewriting `.git/index`.
-- `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, root `.git` preferred, dotfiles home, system dirs, posix and `path.win32` walks).
+- `manifest.test.ts`: UTF-8 byte order; the credential filter; the exclusions (credential, FIFO, app state, `__omnirush__`, unreadable, non-UTF-8); the hash cache; 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; the git block and its `path`; `git status` never rewriting `.git/index`.
+- `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).
- `upload.test.ts` (in-process fake API and S3):
- the happy path;
- resume after a failed part;
diff --git a/apps/server/src/session-archive/detect.test.ts b/apps/server/src/session-archive/detect.test.ts
index 05b3c558..53417146 100644
--- a/apps/server/src/session-archive/detect.test.ts
+++ b/apps/server/src/session-archive/detect.test.ts
@@ -85,9 +85,15 @@ describe("project gate", () => {
// Temp folders live under /private or /var on macOS, which the walk never enters; systemDirs: [] lifts that here.
const anyDir = { systemDirs: [] as string[] };
+ /** A `.git` folder git accepts as a parent repository: one with HEAD. */
+ async function gitDirWithHead(dir: string): Promise<void> {
+ await mkdir(join(dir, ".git"), { recursive: true });
+ await writeFile(join(dir, ".git/HEAD"), "ref: refs/heads/main\n");
+ }
+
test("a folder inside a repository is archivable as git_parent, from a .git directory or gitfile at the nearest parent", async () => {
const repo = await tempDir("gate-parent");
- await mkdir(join(repo, ".git"));
+ await gitDirWithHead(repo);
await mkdir(join(repo, "packages/app/src"), { recursive: true });
const git_parent = { archivable: true, reason: "git_parent", marker: ".git" };
expect(await isArchivableProject(join(repo, "packages/app"), undefined, anyDir)).toEqual(git_parent);
@@ -101,6 +107,11 @@ describe("project gate", () => {
await rm(join(repo, "packages/.git"));
await symlink(join(repo, ".git"), join(repo, "packages/.git"));
expect((await isArchivableProject(join(repo, "packages/app"), undefined, anyDir)).reason).toBe("no_marker");
+ // So does a .git folder without HEAD, which git would skip on its way up to the repository above.
+ await rm(join(repo, "packages/.git"));
+ await mkdir(join(repo, "packages/.git"));
+ expect((await isArchivableProject(join(repo, "packages/app"), undefined, anyDir)).reason).toBe("no_marker");
+ await rm(join(repo, "packages/.git"), { recursive: true });
// A root inside the repository's own .git never qualifies: that would upload its history.
await mkdir(join(repo, ".git/hooks"));
expect((await isArchivableProject(join(repo, ".git/hooks"), undefined, anyDir)).reason).toBe("no_marker");
@@ -110,7 +121,7 @@ describe("project gate", () => {
test("a .git in the root itself is still preferred, and an invalid one there is not overridden by a parent", async () => {
const repo = await tempDir("gate-prefer");
- await mkdir(join(repo, ".git"));
+ await gitDirWithHead(repo);
await mkdir(join(repo, "vendor/lib/.git"), { recursive: true });
await mkdir(join(repo, "tools/cli"), { recursive: true });
expect(await isArchivableProject(join(repo, "vendor/lib"), undefined, anyDir)).toEqual({ archivable: true, reason: "git_dir", marker: ".git" });
@@ -129,13 +140,13 @@ describe("project gate", () => {
await rm(join(home, ".git"), { recursive: true });
expect((await isArchivableProject(join(home, "code/app"), undefined, { ...anyDir, homeDir: home })).reason).toBe("no_marker");
// A real project inside home still qualifies.
- await mkdir(join(home, "code/.git"));
+ await gitDirWithHead(join(home, "code"));
expect((await isArchivableProject(join(home, "code/app"), undefined, { ...anyDir, homeDir: home })).reason).toBe("git_parent");
});
test("a repository in a system or app directory does not qualify a folder inside it", async () => {
const repo = await tempDir("gate-system");
- await mkdir(join(repo, ".git"));
+ await gitDirWithHead(repo);
await mkdir(join(repo, "Contents/Resources"), { recursive: true });
expect((await isArchivableProject(join(repo, "Contents/Resources"), undefined, { systemDirs: [repo] })).reason).toBe("no_marker");
expect((await isArchivableProject(join(repo, "Contents/Resources"), undefined, { systemDirs: [join(repo, "..")] })).reason).toBe("no_marker");
@@ -155,6 +166,10 @@ describe("project gate", () => {
expect(gitParentCandidates("/proj", home, posix)).toEqual([]);
expect(gitParentCandidates("/Volumes/Backup/proj/app", home, posix)).toEqual(["/Volumes/Backup/proj"]);
expect(gitParentCandidates("/Volumes/Backup/app", home, posix)).toEqual([]);
+ // Homes on another volume: the rule is relative to the volume root, not to /.
+ expect(gitParentCandidates("/Volumes/Ext/Users/other/code/app", home, posix)).toEqual(["/Volumes/Ext/Users/other/code"]);
+ expect(gitParentCandidates("/Volumes/Ext/home/sam/app", home, posix)).toEqual([]);
+ expect(gitParentCandidates("/Volumes/Ext/srv/proj/app", home, posix)).toEqual(["/Volumes/Ext/srv/proj", "/Volumes/Ext/srv"]);
for (const guarded of ["/System/Volumes/Data/x/app", "/Library/Developer/x/app", "/Applications/Foo.app/Contents/Resources/app", "/usr/local/proj/app", "/private/tmp/proj/app", "/private/var/folders/xy/T/proj/app", "/var/www/site/app", "/etc/nixos/app", "/opt/homebrew/Library/Taps", "/USR/local/x/app"]) {
expect(gitParentCandidates(guarded, home, posix)).toEqual([]);
}
@@ -172,7 +187,16 @@ describe("project gate", () => {
expect(gitParentCandidates("\\\\server\\share\\app", home, win32)).toEqual([]);
expect(gitParentCandidates("\\\\?\\UNC\\server\\share\\app", home, win32)).toEqual([]);
expect(gitParentCandidates("\\\\?\\C:\\src\\proj\\app", home, win32)).toEqual(["C:\\src\\proj", "C:\\src"]);
- for (const guarded of ["C:\\Windows\\System32\\x\\app", "c:\\windows\\x\\app", "C:\\Program Files\\App\\resources\\app", "D:\\Program Files (x86)\\App\\x", "C:\\ProgramData\\chocolatey\\lib\\x", "\\\\server\\share\\Windows\\x\\app"]) {
+ expect(gitParentCandidates("D:\\Users\\other\\proj\\app", home, win32)).toEqual(["D:\\Users\\other\\proj"]);
+ // A WSL distro is a UNC share: its homes and Linux system folders are guarded against the share root.
+ expect(gitParentCandidates("\\\\wsl$\\Ubuntu\\home\\sam\\code\\app", home, win32)).toEqual(["\\\\wsl$\\Ubuntu\\home\\sam\\code"]);
+ expect(gitParentCandidates("\\\\wsl.localhost\\Ubuntu\\home\\sam\\code\\app", home, win32)).toEqual(["\\\\wsl.localhost\\Ubuntu\\home\\sam\\code"]);
+ expect(gitParentCandidates("//wsl$/Ubuntu/home/sam/code/app", home, win32)).toEqual(["//wsl$/Ubuntu/home/sam/code"]);
+ expect(gitParentCandidates("\\\\wsl$\\Ubuntu\\srv\\proj\\app", home, win32)).toEqual(["\\\\wsl$\\Ubuntu\\srv\\proj", "\\\\wsl$\\Ubuntu\\srv"]);
+ // A share of home folders.
+ expect(gitParentCandidates("\\\\nas\\homes\\sam\\proj\\app", home, win32)).toEqual(["\\\\nas\\homes\\sam\\proj"]);
+ expect(gitParentCandidates("\\\\server\\Users\\sam\\app", home, win32)).toEqual([]);
+ for (const guarded of ["C:\\Windows\\System32\\x\\app", "c:\\windows\\x\\app", "C:\\Program Files\\App\\resources\\app", "D:\\Program Files (x86)\\App\\x", "C:\\ProgramData\\chocolatey\\lib\\x", "\\\\server\\share\\Windows\\x\\app", "\\\\wsl.localhost\\Ubuntu\\etc\\x", "\\\\wsl.localhost\\Ubuntu\\etc\\nixos\\app", "\\\\wsl$\\Ubuntu\\usr\\local\\x\\app", "\\\\wsl$\\Ubuntu\\var\\www\\app", "\\\\wsl$\\Ubuntu\\opt\\x\\app", "\\\\wsl$\\Ubuntu\\root\\proj\\app"]) {
expect(gitParentCandidates(guarded, home, win32)).toEqual([]);
}
});
diff --git a/apps/server/src/session-archive/detect.ts b/apps/server/src/session-archive/detect.ts
index 6ba1da31..78324ccb 100644
--- a/apps/server/src/session-archive/detect.ts
+++ b/apps/server/src/session-archive/detect.ts
@@ -126,20 +126,38 @@ function sameOrInsideFolded(child: string, parent: string, p: PathApi): boolean
return rel === "" || (!rel.startsWith(`..${p.sep}`) && rel !== ".." && !p.isAbsolute(rel));
}
+/** Linux system folders guarded under a UNC share root too (a WSL distro: \\wsl$\<distro>\etc, \\wsl.localhost\<distro>\root). */
+const UNC_POSIX_SYSTEM_NAMES = ["usr", "etc", "var", "opt", "root"];
+
+/** The root that `dir`'s home and system folders hang off: its drive or UNC share root, or /Volumes/<name>/ on posix. */
+function volumeRoot(dir: string, p: PathApi): string {
+ if (p.sep === "/") {
+ const mounted = /^\/Volumes\/[^/]+/i.exec(dir);
+ if (mounted) return `${mounted[0]}/`;
+ }
+ return p.parse(dir).root;
+}
+
/** Why the parent walk must stop at `dir` without looking for `.git` in it, or null. Case-insensitive, so it errs on the side of stopping. */
function parentWalkStop(dir: string, homes: readonly string[], p: PathApi, systemDirs?: readonly string[]): string | null {
- if (p.parse(dir).root === dir || (p.sep === "/" && /^\/Volumes(?:\/[^/]+)?\/?$/.test(dir))) return "filesystem_root";
+ if (p.parse(dir).root === dir || (p.sep === "/" && /^\/Volumes(?:\/[^/]+)?\/?$/i.test(dir))) return "filesystem_root";
if (homes.some((home) => p.relative(home.toLowerCase(), dir.toLowerCase()) === "")) return "home";
- // Another account's home: /Users/<name>, /home/<name>, <drive>:\Users\<name>.
- if (/^(?:\/users|\/home|[a-z]:\\users)$/i.test(p.dirname(dir))) return "home";
- const system = systemDirs ?? (p.sep === "/" ? POSIX_SYSTEM_DIRS : WIN32_SYSTEM_NAMES.map((name) => p.join(p.parse(dir).root, name)));
+ // Any account's home on any volume: /Users/<name>, /home/<name>, <drive>:\Users\<name>,
+ // /Volumes/<disk>/Users/<name>, \\wsl$\<distro>\home\<name>.
+ const vroot = volumeRoot(dir, p);
+ if (/^(?:users|home)$/i.test(p.relative(vroot, p.dirname(dir)))) return "home";
+ const unc = p.sep === "\\" && /^[\\/]{2}[^\\/?.]/.test(vroot);
+ // A share of home folders: \\nas\homes\<name>, \\server\users\<name>.
+ if (unc && p.relative(vroot, p.dirname(dir)) === "" && /[\\/](?:users|homes?)[\\/]?$/i.test(vroot)) return "home";
+ const system =
+ systemDirs ?? (p.sep === "/" ? POSIX_SYSTEM_DIRS : [...WIN32_SYSTEM_NAMES, ...(unc ? UNC_POSIX_SYSTEM_NAMES : [])].map((name) => p.join(vroot, name)));
if (system.some((guarded) => sameOrInsideFolded(dir, guarded, p))) return "system_dir";
return null;
}
/**
* The parents of `root` that gitParentDetector may look in for `.git`,
- * nearest first. The walk stops before the home directory (dotfiles repos),
+ * nearest first. The walk stops before the home directory or any account's home on any volume (dotfiles repos),
* a filesystem, drive or UNC share root, or a system or app directory, so
* none of those, nor anything above them, can qualify the root.
*/
@@ -174,7 +192,7 @@ async function isMountPoint(dir: string): Promise<boolean> {
/**
* A root without `.git` that sits inside a repository, e.g. `~/proj/packages/app`
* with `~/proj/.git`: archivable as git_parent when the nearest parent holding
- * `.git` (a directory or a valid gitfile) lies before any stop of
+ * `.git` (a directory with HEAD, or a valid gitfile) lies before any stop of
* gitParentCandidates or a mount point. Only the root is archived; the
* parent's `.git` is not. A `.git` of any other kind in the root, or at the
* nearest parent, and a root inside that `.git`, qualify nothing.
@@ -190,7 +208,10 @@ export const gitParentDetector: ProjectMarkerDetector = async (root, options = {
// A root inside the repository's own .git (hooks, worktrees) would upload its history.
if (relative(dir, start).split(sep).some((part) => part.toLowerCase() === ".git")) return null;
const found = await gitMarkerDetector(dir);
- return found?.archivable ? { archivable: true, reason: "git_parent", marker: ".git" } : null;
+ if (!found?.archivable) return null;
+ // A .git folder without HEAD is one git itself skips, walking on up to a repository the walk never reached.
+ if (found.reason === "git_dir" && !(await lstat(join(dir, ".git", "HEAD")).then((stats) => stats.isFile(), () => false))) return null;
+ return { archivable: true, reason: "git_parent", marker: ".git" };
}
return null;
} catch {
diff --git a/apps/server/src/session-archive/index.test.ts b/apps/server/src/session-archive/index.test.ts
index c6c16beb..4a253715 100644
--- a/apps/server/src/session-archive/index.test.ts
+++ b/apps/server/src/session-archive/index.test.ts
@@ -88,7 +88,7 @@ describe("SessionArchiver", () => {
sequence: 0,
turn: 0,
parent_archive_id: null,
- workspace: { label: basename(root), marker: ".git", git: { head, branch: "main", remote: "https://github.com/acme/app.git", dirty: true } },
+ workspace: { label: basename(root), marker: ".git", git: { head, branch: "main", remote: "https://github.com/acme/app.git", dirty: true, path: "" } },
excluded: { credential: 2, special: 0, app_state: 0, reserved: 0, unreadable: 0, non_utf8: 0 },
});
expect("deleted" in manifest).toBe(false);
@@ -182,7 +182,7 @@ describe("SessionArchiver", () => {
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(manifestOf(members)).toMatchObject({
- workspace: { label: "app", marker: ".git", git: { head, branch: "main", remote: "https://github.com/acme/app.git", dirty: true } },
+ workspace: { label: "app", marker: ".git", git: { head, branch: "main", remote: "https://github.com/acme/app.git", dirty: true, path: "packages/app" } },
excluded: { credential: 1 },
});
@@ -193,7 +193,37 @@ describe("SessionArchiver", () => {
await subject.drain();
const deltaMembers = await openArchive(server.objects()[1]!.object!);
expect(deltaMembers.slice(1).map((member) => member.name)).toEqual(["src/main.ts"]);
- expect(manifestOf(deltaMembers)).toMatchObject({ workspace: { git: { head: await git(repo, "rev-parse", "HEAD"), branch: "main" } } });
+ expect(manifestOf(deltaMembers)).toMatchObject({ workspace: { git: { head: await git(repo, "rev-parse", "HEAD"), branch: "main", path: "packages/app" } } });
+ });
+
+ test("an empty .git between the folder and a dotfiles repository at home: nothing archived, and git never reports the dotfiles repository", async () => {
+ const server = new FakeArchiveServer();
+ const home = await tempDir("dotfiles-home");
+ await git(home, "init", "-q", "-b", "dotfiles");
+ await writeFile(join(home, ".zshrc"), "export EDITOR=vi\n");
+ await git(home, "add", ".zshrc");
+ await git(home, "commit", "-q", "-m", "dotfiles");
+ await git(home, "remote", "add", "origin", "https://example.com/me/dotfiles.git");
+ await mkdir(join(home, "proj/.git"), { recursive: true });
+ const root = join(home, "proj/packages/app");
+ await mkdir(root, { recursive: true });
+ await writeFile(join(root, "main.ts"), "export {};\n");
+ // Plain git skips the empty .git and climbs to the dotfiles repository.
+ expect(await git(root, "symbolic-ref", "--short", "HEAD")).toBe("dotfiles");
+
+ const detectors = [gitMarkerDetector, (dir: string) => gitParentDetector(dir, { systemDirs: [], homeDir: home })];
+ const subject = archiver(server, await tempDir("state"), { detectors });
+ expect(await subject.captureBase("ses_empty_git", root)).toEqual({ status: "skipped", reason: "not_archivable" });
+ expect(server.calls).toEqual([]);
+
+ // The archive's git, with this folder as the OS home, stops below home: no git block for the folder, nor for
+ // proj itself, whose empty .git passes the gate as git_dir.
+ const script = `const { readArchiveGit } = await import(${JSON.stringify(join(import.meta.dir, "manifest.ts"))});
+ console.log(JSON.stringify(await Promise.all(JSON.parse(process.env.ARCHIVE_GIT_ROOTS).map((dir) => readArchiveGit(dir)))));`;
+ const { stdout } = await execFileAsync(process.execPath, ["-e", script], {
+ env: { ...process.env, HOME: home, ARCHIVE_GIT_ROOTS: JSON.stringify([root, join(home, "proj")]) },
+ });
+ expect(JSON.parse(stdout)).toEqual([null, null]);
});
test("428 at /archives/key: nothing is packed, archiving stays off until a later captureBase succeeds", async () => {
diff --git a/apps/server/src/session-archive/manifest.test.ts b/apps/server/src/session-archive/manifest.test.ts
index 3badd6ae..92aeeadd 100644
--- a/apps/server/src/session-archive/manifest.test.ts
+++ b/apps/server/src/session-archive/manifest.test.ts
@@ -248,14 +248,16 @@ describe("manifest and git block", () => {
const root = await tempDir("git-block");
expect(await readArchiveGit(root)).toBeNull();
await git(root, "init", "-q", "-b", "main");
- expect(await readArchiveGit(root)).toEqual({ head: null, branch: "main", remote: null, dirty: false });
+ expect(await readArchiveGit(root)).toEqual({ head: null, branch: "main", remote: null, dirty: false, path: "" });
await writeFile(join(root, "a.txt"), "a");
await git(root, "add", "a.txt");
await git(root, "commit", "-q", "-m", "one");
await git(root, "remote", "add", "upstream", "https://example.com/upstream.git");
await git(root, "remote", "add", "origin", "https://user:[email protected]/acme/my-app.git");
const head = await git(root, "rev-parse", "HEAD");
- expect(await readArchiveGit(root)).toEqual({ head, branch: "main", remote: "https://github.com/acme/my-app.git", dirty: false });
+ expect(await readArchiveGit(root)).toEqual({ head, branch: "main", remote: "https://github.com/acme/my-app.git", dirty: false, path: "" });
+ await mkdir(join(root, "packages/my app"), { recursive: true });
+ expect((await readArchiveGit(join(root, "packages/my app")))!.path).toBe("packages/my app");
await writeFile(join(root, "untracked.txt"), "u");
expect((await readArchiveGit(root))!.dirty).toBe(true);
await git(root, "checkout", "-q", "--detach");
diff --git a/apps/server/src/session-archive/manifest.ts b/apps/server/src/session-archive/manifest.ts
index 14ffa31c..ce6804f2 100644
--- a/apps/server/src/session-archive/manifest.ts
+++ b/apps/server/src/session-archive/manifest.ts
@@ -7,9 +7,10 @@
*/
import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
-import { constants as fsConstants, type BigIntStats } from "node:fs";
+import { constants as fsConstants, realpathSync, type BigIntStats } from "node:fs";
import { lstat, open, readdir, readlink, realpath } from "node:fs/promises";
-import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { homedir } from "node:os";
+import { basename, delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";
import { clampCollectorBytes, isCollectorPathDenied, stripRemoteUserinfo } from "../workspace-collector.js";
import { hintGarbageCollection } from "./files.js";
@@ -75,7 +76,14 @@ export type ExcludedCounts = {
non_utf8: number;
};
-export type ArchiveGit = { head: string | null; branch: string | null; remote: string | null; dirty: boolean };
+export type ArchiveGit = {
+ head: string | null;
+ branch: string | null;
+ remote: string | null;
+ dirty: boolean;
+ /** The root's path inside the repository (`git rev-parse --show-prefix` without the trailing `/`), "" at its top level. */
+ path?: string;
+};
export type ArchiveManifest = {
schema: typeof ARCHIVE_SCHEMA;
@@ -660,7 +668,24 @@ export function buildManifestBytes(input: ManifestInput): Buffer {
type GitRun = { ok: boolean; stdout: string; truncated: boolean };
-/** Runs git in the root without locks, prompts or fsmonitor hooks; reads at most `maxBytes` of stdout. */
+/**
+ * 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) => {
const chunks: Buffer[] = [];
@@ -683,7 +708,15 @@ function runGit(root: string, args: string[], maxBytes = 64 * 1024): Promise<Git
child = spawn("git", ["-C", root, "-c", "core.fsmonitor=false", "-c", "core.quotePath=false", ...args], {
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_PAGER: "cat", PAGER: "cat", LC_ALL: "C" },
+ env: {
+ ...process.env,
+ GIT_CEILING_DIRECTORIES: gitCeilingDirectories(),
+ GIT_TERMINAL_PROMPT: "0",
+ GIT_OPTIONAL_LOCKS: "0",
+ GIT_PAGER: "cat",
+ PAGER: "cat",
+ LC_ALL: "C",
+ },
});
} catch {
finish(false);
@@ -716,18 +749,21 @@ async function gitLine(root: string, args: string[]): Promise<string | null> {
/**
* workspace.git (section 5.6): HEAD, branch, the origin (else first) remote
- * without userinfo, and whether `git status --porcelain` prints anything.
+ * without userinfo, whether `git status --porcelain` prints anything, and the
+ * root's path inside the repository ("" at its top level; a git_parent root
+ * is a folder inside it).
* Null when git cannot read the repository. GIT_OPTIONAL_LOCKS=0 keeps
* `git status` from rewriting .git/index, which would otherwise show up as a
* change in the next delta.
*/
export async function readArchiveGit(root: string): Promise<ArchiveGit | null> {
if (!(await runGit(root, ["rev-parse", "--git-dir"])).ok) return null;
- const [head, branch, remotes, status] = await Promise.all([
+ const [head, branch, remotes, status, prefix] = await Promise.all([
gitLine(root, ["rev-parse", "--verify", "-q", "HEAD"]),
gitLine(root, ["symbolic-ref", "--short", "-q", "HEAD"]),
gitLine(root, ["remote"]),
runGit(root, ["status", "--porcelain", "--untracked-files=normal"], 1),
+ runGit(root, ["rev-parse", "--show-prefix"]),
]);
const names = remotes?.split(/\r?\n/).map((name) => name.trim()).filter(Boolean) ?? [];
const remoteName = names.includes("origin") ? "origin" : names[0];
@@ -737,5 +773,6 @@ export async function readArchiveGit(root: string): Promise<ArchiveGit | null> {
branch,
remote: remoteUrl ? stripRemoteUserinfo(remoteUrl) : null,
dirty: status.ok && status.stdout.length > 0,
+ ...(prefix.ok && !prefix.truncated ? { path: prefix.stdout.replace(/\r?\n$/, "").replace(/\/$/, "") } : {}),
};
}
diff --git a/docs/project-archive.md b/docs/project-archive.md
index c1173fe7..9ff87601 100644
--- a/docs/project-archive.md
+++ b/docs/project-archive.md
@@ -25,11 +25,13 @@ All of these must be true:
`packages/app` in a repository whose `.git` is two folders up. In that
case only the chat's folder is archived, with all its subfolders; the
repository's `.git` and the rest of the repository are not; only its
- current branch, commit, remote address (without any login in it) and
- whether it has uncommitted changes are recorded. A `.git` in
- your home folder (a dotfiles repository), at the root of a disk or
- network share, or in a system or application folder (such as `/usr`,
- `/Applications`, `C:\Windows` or `C:\Program Files`) does not count.
+ current branch, commit, remote address (without any login in it),
+ whether it has uncommitted changes and the folder's path inside it
+ are recorded. A `.git` in any account's home folder (a dotfiles
+ repository), on this disk, another disk, a network share or a WSL
+ distribution, at the root of a disk or network share, or in a system
+ or application folder (such as `/usr`, `/Applications`, `C:\Windows`,
+ `C:\Program Files` or a WSL distribution's `/etc`) does not count.
Nothing is archived for other folders.
- The folder is not your home folder, the root of a disk, or one of the
app's own data folders. If the chat's folder is a symbolic link, the