@catamorphic/git 0.0.0-stage → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/dist/checkout-remote-backend.d.ts +12 -0
  4. package/dist/checkout-remote-backend.d.ts.map +1 -0
  5. package/dist/file-reads.d.ts +15 -0
  6. package/dist/file-reads.d.ts.map +1 -0
  7. package/dist/fs-backend.d.ts +30 -0
  8. package/dist/fs-backend.d.ts.map +1 -0
  9. package/dist/fs-remote-backend.d.ts +47 -0
  10. package/dist/fs-remote-backend.d.ts.map +1 -0
  11. package/dist/git-object-codec.d.ts +31 -0
  12. package/dist/git-object-codec.d.ts.map +1 -0
  13. package/dist/git-sync.d.ts +61 -0
  14. package/dist/git-sync.d.ts.map +1 -0
  15. package/dist/in-memory-object-store.d.ts +23 -0
  16. package/dist/in-memory-object-store.d.ts.map +1 -0
  17. package/dist/index.d.ts +24 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4746 -0
  20. package/dist/index.js.map +32 -0
  21. package/dist/migrate-workflow.d.ts +12 -0
  22. package/dist/migrate-workflow.d.ts.map +1 -0
  23. package/dist/native-git.d.ts +25 -0
  24. package/dist/native-git.d.ts.map +1 -0
  25. package/dist/native-project-repo.d.ts +57 -0
  26. package/dist/native-project-repo.d.ts.map +1 -0
  27. package/dist/network-sync.d.ts +58 -0
  28. package/dist/network-sync.d.ts.map +1 -0
  29. package/dist/network.d.ts +81 -0
  30. package/dist/network.d.ts.map +1 -0
  31. package/dist/object-remote-backend.d.ts +95 -0
  32. package/dist/object-remote-backend.d.ts.map +1 -0
  33. package/dist/object-store.d.ts +42 -0
  34. package/dist/object-store.d.ts.map +1 -0
  35. package/dist/origin-draft.d.ts +264 -0
  36. package/dist/origin-draft.d.ts.map +1 -0
  37. package/dist/origin-objects.d.ts +201 -0
  38. package/dist/origin-objects.d.ts.map +1 -0
  39. package/dist/personal-files.d.ts +6 -0
  40. package/dist/personal-files.d.ts.map +1 -0
  41. package/dist/project-manager.d.ts +214 -0
  42. package/dist/project-manager.d.ts.map +1 -0
  43. package/dist/project-repo.d.ts +79 -0
  44. package/dist/project-repo.d.ts.map +1 -0
  45. package/dist/ref-moved-error.d.ts +13 -0
  46. package/dist/ref-moved-error.d.ts.map +1 -0
  47. package/dist/ref-names.d.ts +18 -0
  48. package/dist/ref-names.d.ts.map +1 -0
  49. package/dist/types.d.ts +276 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/workspace-mirror.d.ts +110 -0
  52. package/dist/workspace-mirror.d.ts.map +1 -0
  53. package/package.json +53 -4
  54. package/src/checkout-remote-backend.ts +154 -0
  55. package/src/diff3.d.ts +16 -0
  56. package/src/file-reads.ts +53 -0
  57. package/src/fs-backend.ts +206 -0
  58. package/src/fs-remote-backend.ts +252 -0
  59. package/src/git-object-codec.ts +87 -0
  60. package/src/git-sync.ts +539 -0
  61. package/src/in-memory-object-store.ts +60 -0
  62. package/src/index.ts +110 -0
  63. package/src/migrate-workflow.ts +30 -0
  64. package/src/native-git.ts +177 -0
  65. package/src/native-project-repo.ts +515 -0
  66. package/src/network-sync.ts +239 -0
  67. package/src/network.ts +269 -0
  68. package/src/object-remote-backend.ts +366 -0
  69. package/src/object-store.ts +41 -0
  70. package/src/origin-draft.ts +1033 -0
  71. package/src/origin-objects.ts +906 -0
  72. package/src/personal-files.ts +57 -0
  73. package/src/project-manager.ts +743 -0
  74. package/src/project-repo.ts +800 -0
  75. package/src/ref-moved-error.ts +18 -0
  76. package/src/ref-names.ts +47 -0
  77. package/src/types.ts +289 -0
  78. package/src/workspace-mirror.ts +400 -0
  79. package/README.md +0 -3
@@ -0,0 +1,110 @@
1
+ import type { GitCredentials } from "./types.js";
2
+ /**
3
+ * A session workspace's base (ADR 0178): the ref a caller asked for on the
4
+ * project's linked remote and the commit it named when fetched.
5
+ */
6
+ export interface WorkspaceBase {
7
+ ref: string;
8
+ commit: string;
9
+ }
10
+ /**
11
+ * Validate a ref a caller names: a branch, a tag, a full ref such as
12
+ * `refs/pull/42/head`, or a full commit id. Anything that could be read as
13
+ * an option or a refspec (`-x`, `a:b`, `+a`) is refused.
14
+ */
15
+ export declare function parseWorkspaceRef(value: string): string;
16
+ /** Whether a ref names a commit id rather than a ref name. */
17
+ export declare function isCommitId(ref: string): boolean;
18
+ /**
19
+ * Fetch `ref` from a network remote into the host's bare mirror of it and
20
+ * pin the commit under `pin` (for example `refs/sessions/<id>`). The fetch
21
+ * is incremental: the mirror keeps what earlier sessions fetched, so a pull
22
+ * request head costs only its new objects. Credentials are sent as a header
23
+ * for this one command and never written to the mirror's configuration.
24
+ */
25
+ export declare function fetchIntoMirror(opts: {
26
+ mirrorPath: string;
27
+ url: string;
28
+ credentials?: GitCredentials;
29
+ ref: string;
30
+ pin: string;
31
+ }): Promise<{
32
+ commit: string;
33
+ }>;
34
+ /** Drop a pin (a closed session's base). Missing is a no-op. */
35
+ export declare function unpinMirrorRef(opts: {
36
+ mirrorPath: string;
37
+ pin: string;
38
+ }): Promise<void>;
39
+ /** Files that differ between two commits of the mirror, at most `limit`. */
40
+ export declare function mirrorChangedFiles(opts: {
41
+ mirrorPath: string;
42
+ from: string;
43
+ to: string;
44
+ limit?: number;
45
+ }): Promise<{
46
+ files: string[];
47
+ total: number;
48
+ }>;
49
+ /**
50
+ * Copy a pinned commit, with its history, from the mirror into a working
51
+ * copy under `into`. Native Git negotiates what the copy already has, so a
52
+ * copy seeded from the project's main receives only the difference.
53
+ */
54
+ export declare function copyFromMirror(opts: {
55
+ mirrorPath: string;
56
+ pin: string;
57
+ repoPath: string;
58
+ into: string;
59
+ }): Promise<void>;
60
+ /** How a base move ended (ADR 0178). */
61
+ export type BaseMoveOutcome = {
62
+ status: "moved";
63
+ head: string;
64
+ }
65
+ /** The rebase stopped on conflicts and was undone; `head` is unchanged. */
66
+ | {
67
+ status: "conflict";
68
+ head: string;
69
+ files: string[];
70
+ };
71
+ /**
72
+ * Move a checkout from base `from` to base `to`, a commit pinned in the
73
+ * mirror. `reset` discards the checkout's own commits and changes; `rebase`
74
+ * replays its commits since `from` onto `to` (keeping uncommitted changes)
75
+ * and, when that conflicts, puts everything back as it was so the caller
76
+ * can tell the agent instead of losing work.
77
+ */
78
+ export declare function moveCheckoutBase(opts: {
79
+ repoPath: string;
80
+ mirrorPath: string;
81
+ pin: string;
82
+ from: string;
83
+ to: string;
84
+ update: "reset" | "rebase";
85
+ }): Promise<BaseMoveOutcome>;
86
+ /**
87
+ * A packfile holding `head` and its history back to `base`, and the
88
+ * commits a receiver must record as shallow. A sandbox seeded from it has
89
+ * the real commits (so `git log`, `diff`, and pushes of new branches work)
90
+ * without the repository's whole history.
91
+ */
92
+ export declare function buildSeedPack(opts: {
93
+ repoPath: string;
94
+ head: string;
95
+ base: string;
96
+ }): Promise<{
97
+ pack: Uint8Array;
98
+ shallow: string[];
99
+ }>;
100
+ /**
101
+ * Shell that installs a seed pack uploaded as base64 at `packFile` into the
102
+ * repository in the current directory and records `shallow` commits. It
103
+ * leaves refs and the working tree to the caller.
104
+ */
105
+ export declare function seedPackInstallScript(opts: {
106
+ packFile: string;
107
+ shallow: readonly string[];
108
+ }): string;
109
+ export declare function shellQuote(value: string): string;
110
+ //# sourceMappingURL=workspace-mirror.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-mirror.d.ts","sourceRoot":"","sources":["../src/workspace-mirror.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;CAChB;AAID;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAsBvD;AAED,8DAA8D;AAC9D,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAE/C;AAuCD;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE;IAC1C,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,CAAC,EAAE,cAAc,CAAC;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CA4C9B;AAED,gEAAgE;AAChE,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhB;AAED,4EAA4E;AAC5E,wBAAsB,kBAAkB,CAAC,IAAI,EAAE;IAC7C,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAW9C;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,GAAG,OAAO,CAAC,IAAI,CAAC,CAahB;AAED,wCAAwC;AACxC,MAAM,MAAM,eAAe,GACvB;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE;AACnC,2EAA2E;GACzE;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAS1D;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,OAAO,GAAG,QAAQ,CAAC;CAC5B,GAAG,OAAO,CAAC,eAAe,CAAC,CAsC3B;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd,GAAG,OAAO,CAAC;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAuCnD;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B,GAAG,MAAM,CAgBT;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD"}
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@catamorphic/git",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.30",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "bun": "./src/index.ts",
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "bun ../../scripts/build-package.ts && tsc --project tsconfig.json --noEmit false --emitDeclarationOnly",
16
+ "dev": "bun ../../scripts/build-package.ts --watch",
17
+ "test": "bun ../../scripts/tool-runtime.ts vitest --tool-cwd packages/git --config ../../vitest.config.ts",
18
+ "typecheck": "bun check --project ./tsconfig.json"
19
+ },
20
+ "bundle": {
21
+ "entry": [
22
+ "src/index.ts"
23
+ ]
24
+ },
25
+ "dependencies": {
26
+ "@catamorphic/workflow": "0.1.0-alpha.30",
27
+ "diff3": "0.0.3",
28
+ "ignore": "^5.3.2",
29
+ "isomorphic-git": "^1.38.6"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^26.1.1"
33
+ },
34
+ "license": "Apache-2.0",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/opencx-labs/catamorphic.git",
38
+ "directory": "packages/git"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "registry": "https://registry.npmjs.org"
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "src",
47
+ "LICENSE.txt",
48
+ "NOTICE.txt",
49
+ "!**/*.test.*",
50
+ "!**/*.spec.*",
51
+ "!**/__tests__/**",
52
+ "!**/__fixtures__/**",
53
+ "!**/fixtures/**"
54
+ ]
55
+ }
@@ -0,0 +1,154 @@
1
+ import { PUBLISHED_REF_PREFIX } from "@catamorphic/workflow/project-layout";
2
+ import { hasLocalGit, nativeGit, nativeGitBytes } from "./native-git.js";
3
+ import { NativeProjectRepo } from "./native-project-repo.js";
4
+ import type {
5
+ CommitInfo,
6
+ OriginRepo,
7
+ ProjectPathResolver,
8
+ RemoteBackend,
9
+ } from "./types.js";
10
+
11
+ /** Local publications reuse the checkout's object database; shared projects keep the host's backend. */
12
+ export class CheckoutRemoteBackend implements RemoteBackend {
13
+ constructor(
14
+ private readonly roots: ProjectPathResolver,
15
+ private readonly shared: RemoteBackend,
16
+ ) {}
17
+
18
+ async initRemote(tenantId: string, projectId: string): Promise<void> {
19
+ if (!(await this.roots(tenantId, projectId)))
20
+ await this.shared.initRemote(tenantId, projectId);
21
+ }
22
+ async deleteRemote(tenantId: string, projectId: string): Promise<void> {
23
+ // An attached checkout and its retained commits belong to its owner.
24
+ if (!(await this.roots(tenantId, projectId)))
25
+ await this.shared.deleteRemote(tenantId, projectId);
26
+ }
27
+ async exists(tenantId: string, projectId: string): Promise<boolean> {
28
+ return (
29
+ Boolean(await this.roots(tenantId, projectId)) ||
30
+ this.shared.exists(tenantId, projectId)
31
+ );
32
+ }
33
+ async withOrigin<T>(
34
+ tenantId: string,
35
+ projectId: string,
36
+ fn: (origin: OriginRepo) => Promise<T>,
37
+ ): Promise<T> {
38
+ const root = await this.roots(tenantId, projectId);
39
+ return root
40
+ ? fn(new CheckoutOrigin(root, projectId))
41
+ : this.shared.withOrigin(tenantId, projectId, fn);
42
+ }
43
+ }
44
+
45
+ class CheckoutOrigin implements OriginRepo {
46
+ readonly gitdir: string;
47
+ constructor(
48
+ private readonly root: string,
49
+ private readonly projectId: string,
50
+ ) {
51
+ this.gitdir = root;
52
+ }
53
+ private publicationRef(ref: string): string {
54
+ if (!ref.startsWith("refs/heads/"))
55
+ throw new Error(`Unsupported publication ref: ${ref}`);
56
+ return `${PUBLISHED_REF_PREFIX}/${ref.slice("refs/heads/".length)}`;
57
+ }
58
+ async resolveRef(ref: string): Promise<string | null> {
59
+ return nativeGit(this.root, [
60
+ "rev-parse",
61
+ "--verify",
62
+ this.publicationRef(ref),
63
+ ]).then(
64
+ (s) => s.trim(),
65
+ () => null,
66
+ );
67
+ }
68
+ async listRefs(prefix: string): Promise<Array<{ ref: string; sha: string }>> {
69
+ if (!(await hasLocalGit({ path: this.root }))) return [];
70
+ const output = await nativeGit(this.root, [
71
+ "for-each-ref",
72
+ "--format=%(refname)%09%(objectname)",
73
+ `${PUBLISHED_REF_PREFIX}/`,
74
+ ]);
75
+ return output
76
+ .trim()
77
+ .split("\n")
78
+ .filter(Boolean)
79
+ .flatMap((line) => {
80
+ const [name, sha] = line.split("\t");
81
+ const ref = name?.replace(`${PUBLISHED_REF_PREFIX}/`, "refs/heads/");
82
+ return ref?.startsWith(prefix) && sha ? [{ ref, sha }] : [];
83
+ });
84
+ }
85
+ async updateRef(input: {
86
+ ref: string;
87
+ sha: string;
88
+ expected?: string | null;
89
+ }): Promise<void> {
90
+ await nativeGit(this.root, [
91
+ "update-ref",
92
+ this.publicationRef(input.ref),
93
+ input.sha,
94
+ ...(input.expected !== undefined
95
+ ? [input.expected ?? "0000000000000000000000000000000000000000"]
96
+ : []),
97
+ ]);
98
+ }
99
+ async deleteRef(input: { ref: string; expected?: string }): Promise<void> {
100
+ await nativeGit(this.root, [
101
+ "update-ref",
102
+ "-d",
103
+ this.publicationRef(input.ref),
104
+ ...(input.expected !== undefined ? [input.expected] : []),
105
+ ]);
106
+ }
107
+ async hasObject(sha: string): Promise<boolean> {
108
+ return nativeGit(this.root, ["cat-file", "-e", sha]).then(
109
+ () => true,
110
+ () => false,
111
+ );
112
+ }
113
+ async readObject(
114
+ sha: string,
115
+ ): Promise<{ type: "blob" | "tree" | "commit" | "tag"; data: Uint8Array }> {
116
+ const type = (await nativeGit(this.root, ["cat-file", "-t", sha])).trim();
117
+ if (
118
+ type !== "blob" &&
119
+ type !== "tree" &&
120
+ type !== "commit" &&
121
+ type !== "tag"
122
+ )
123
+ throw new Error(`Unsupported Git object: ${type}`);
124
+ return {
125
+ type,
126
+ data: await nativeGitBytes(this.root, ["cat-file", type, sha]),
127
+ };
128
+ }
129
+ async writeObject(input: {
130
+ type: "blob" | "tree" | "commit" | "tag";
131
+ data: Uint8Array;
132
+ }): Promise<string> {
133
+ // Explicit authoring (for example, a temporary watcher checkout) can
134
+ // introduce new objects. Retain them in the same database as the project.
135
+ return new TextDecoder()
136
+ .decode(
137
+ await nativeGitBytes(
138
+ this.root,
139
+ ["hash-object", "-w", "--stdin", "-t", input.type],
140
+ input.data,
141
+ ),
142
+ )
143
+ .trim();
144
+ }
145
+
146
+ async log(ref: string, maxCount?: number): Promise<CommitInfo[]> {
147
+ const repo = new NativeProjectRepo(
148
+ this.projectId,
149
+ this.root,
150
+ async () => {},
151
+ );
152
+ return repo.log({ ref: this.publicationRef(ref), maxCount });
153
+ }
154
+ }
package/src/diff3.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /** The line-level three-way merge isomorphic-git uses (`diff3` on npm). */
2
+ declare module "diff3" {
3
+ export type Diff3Block<T> =
4
+ | { ok: T[] }
5
+ | {
6
+ conflict: {
7
+ a: T[];
8
+ aIndex: number;
9
+ o: T[];
10
+ oIndex: number;
11
+ b: T[];
12
+ bIndex: number;
13
+ };
14
+ };
15
+ export default function diff3Merge<T>(a: T[], o: T[], b: T[]): Diff3Block<T>[];
16
+ }
@@ -0,0 +1,53 @@
1
+ /** Bulk snapshots are bounded; oversized projects fail instead of exhausting the host. */
2
+ export interface FileReadOptions {
3
+ filter?: (path: string) => boolean;
4
+ excludeNestedRepositories?: boolean;
5
+ maxFileBytes?: number;
6
+ maxTotalBytes?: number;
7
+ }
8
+
9
+ export const MAX_SNAPSHOT_FILE_BYTES = 8 * 1024 * 1024;
10
+ export const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
11
+
12
+ export async function readFileSnapshot({
13
+ paths,
14
+ read,
15
+ options = {},
16
+ }: {
17
+ paths: readonly string[];
18
+ read: (path: string, maxBytes: number) => Promise<string | null>;
19
+ options?: FileReadOptions;
20
+ }): Promise<Record<string, string>> {
21
+ const selected = paths.filter((path) => options.filter?.(path) ?? true);
22
+ const files: Record<string, string> = {};
23
+ const maxFileBytes = options.maxFileBytes ?? MAX_SNAPSHOT_FILE_BYTES;
24
+ const maxTotalBytes = options.maxTotalBytes ?? MAX_SNAPSHOT_BYTES;
25
+ for (const limit of [maxFileBytes, maxTotalBytes]) {
26
+ if (!Number.isSafeInteger(limit) || limit < 1)
27
+ throw new Error("Snapshot byte limits must be positive integers");
28
+ }
29
+ let total = 0;
30
+ // A failed batch settles before returning, so it cannot leave background reads.
31
+ for (let offset = 0; offset < selected.length; offset += 8) {
32
+ const batch = await Promise.allSettled(
33
+ selected.slice(offset, offset + 8).map(async (path) => {
34
+ const content = await read(path, maxFileBytes);
35
+ if (content === null) return;
36
+ const bytes = Buffer.byteLength(content);
37
+ if (bytes > maxFileBytes)
38
+ throw new Error(
39
+ `Project file '${path}' exceeds the ${maxFileBytes}-byte snapshot limit`,
40
+ );
41
+ total += bytes;
42
+ if (total > maxTotalBytes)
43
+ throw new Error(
44
+ `Project snapshot exceeds the ${maxTotalBytes}-byte limit; narrow the source selection or exclude generated files`,
45
+ );
46
+ files[path] = content;
47
+ }),
48
+ );
49
+ for (const result of batch)
50
+ if (result.status === "rejected") throw result.reason;
51
+ }
52
+ return files;
53
+ }
@@ -0,0 +1,206 @@
1
+ import nodeFs from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import git from "isomorphic-git";
5
+ import { ensurePersonalFilesExcluded } from "./personal-files.js";
6
+ import type {
7
+ InitProjectOptions,
8
+ ProjectPathResolver,
9
+ StorageBackend,
10
+ } from "./types.js";
11
+
12
+ const UUID_RE =
13
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
+
15
+ function assertUuid(value: string): void {
16
+ if (!UUID_RE.test(value)) {
17
+ throw new Error(`Invalid UUID: ${value}`);
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Filesystem-backed project storage. When a `pathResolver` maps a project to
23
+ * an explicit root directory (a user-visible folder), that folder IS the
24
+ * working copy — shared by all users of this single-machine backend.
25
+ * Otherwise dev working copies live under the internal layout:
26
+ * <basePath>/<tenantId>/<projectId>/dev/<externalUserId>/
27
+ * When `externalUserId` is omitted, falls back to the legacy layout
28
+ * <basePath>/<tenantId>/<projectId>/
29
+ * so older tests and single-user usage remain compatible.
30
+ */
31
+ export class FsBackend implements StorageBackend {
32
+ // initProject(rootPath) establishes the working copy immediately. The host's
33
+ // durable resolver may publish that mapping after creation/provisioning hooks;
34
+ // requests during that interval must never write into an internal fallback.
35
+ private readonly initializedRoots = new Map<string, string>();
36
+ constructor(
37
+ private readonly basePath: string,
38
+ private readonly pathResolver?: ProjectPathResolver,
39
+ ) {}
40
+
41
+ private resolveInternalPath(
42
+ tenantId: string,
43
+ projectId: string,
44
+ externalUserId?: string,
45
+ ): string {
46
+ assertUuid(tenantId);
47
+ assertUuid(projectId);
48
+ const base = path.join(this.basePath, tenantId, projectId);
49
+ const dir = externalUserId
50
+ ? path.join(base, "dev", sanitizeUserId(externalUserId))
51
+ : base;
52
+ if (!path.resolve(dir).startsWith(path.resolve(this.basePath))) {
53
+ throw new Error("Path traversal detected");
54
+ }
55
+ return dir;
56
+ }
57
+
58
+ private async resolveProjectPath(
59
+ tenantId: string,
60
+ projectId: string,
61
+ externalUserId?: string,
62
+ ): Promise<string> {
63
+ const rootPath = await this.pathResolver?.(tenantId, projectId);
64
+ if (rootPath) return rootPath;
65
+ const initializedRoot = this.initializedRoots.get(
66
+ `${tenantId}:${projectId}`,
67
+ );
68
+ if (initializedRoot) return initializedRoot;
69
+ return this.resolveInternalPath(tenantId, projectId, externalUserId);
70
+ }
71
+
72
+ async acquireProject(
73
+ tenantId: string,
74
+ projectId: string,
75
+ externalUserId?: string,
76
+ ): Promise<{ repoPath: string; release: () => Promise<void> }> {
77
+ const projectPath = await this.resolveProjectPath(
78
+ tenantId,
79
+ projectId,
80
+ externalUserId,
81
+ );
82
+ try {
83
+ await fs.access(projectPath);
84
+ } catch {
85
+ throw new Error(`Project not found: ${projectId}`);
86
+ }
87
+ await ensurePersonalFilesExcluded({ repoPath: projectPath });
88
+ return {
89
+ repoPath: projectPath,
90
+ release: async () => {},
91
+ };
92
+ }
93
+
94
+ async initProject(
95
+ tenantId: string,
96
+ projectId: string,
97
+ opts?: InitProjectOptions,
98
+ ): Promise<string> {
99
+ const projectPath =
100
+ opts?.rootPath ??
101
+ (await this.resolveProjectPath(
102
+ tenantId,
103
+ projectId,
104
+ opts?.externalUserId,
105
+ ));
106
+ if (opts?.rootPath)
107
+ this.initializedRoots.set(`${tenantId}:${projectId}`, projectPath);
108
+ await fs.mkdir(projectPath, { recursive: true });
109
+ const gitDir = path.join(projectPath, ".git");
110
+ const hasRepo = await fs.access(gitDir).then(
111
+ () => true,
112
+ () => false,
113
+ );
114
+ if (!hasRepo) {
115
+ await git.init({ fs: nodeFs, dir: projectPath, defaultBranch: "main" });
116
+ }
117
+ await ensurePersonalFilesExcluded({ repoPath: projectPath });
118
+ return projectPath;
119
+ }
120
+
121
+ mirrorPath(tenantId: string, projectId: string): string {
122
+ assertUuid(tenantId);
123
+ assertUuid(projectId);
124
+ return path.join(this.basePath, ".mirrors", tenantId, `${projectId}.git`);
125
+ }
126
+
127
+ cachePath(tenantId: string, projectId: string, name: string): string {
128
+ assertUuid(tenantId);
129
+ assertUuid(projectId);
130
+ return path.join(
131
+ this.basePath,
132
+ tenantId,
133
+ projectId,
134
+ "cache",
135
+ sanitizeUserId(name),
136
+ );
137
+ }
138
+
139
+ async deleteProject(tenantId: string, projectId: string): Promise<void> {
140
+ // Only internal storage is removed. Explicitly-rooted folders belong to
141
+ // the user; the host decides separately whether to trash them.
142
+ const projectRoot = path.join(this.basePath, tenantId, projectId);
143
+ await fs.rm(projectRoot, { recursive: true, force: true });
144
+ await fs.rm(this.mirrorPath(tenantId, projectId), {
145
+ recursive: true,
146
+ force: true,
147
+ });
148
+ this.initializedRoots.delete(`${tenantId}:${projectId}`);
149
+ }
150
+
151
+ async deleteCopy(
152
+ tenantId: string,
153
+ projectId: string,
154
+ externalUserId: string,
155
+ ): Promise<void> {
156
+ // A mapped project folder is every user's copy; it belongs to the user.
157
+ if (
158
+ (await this.pathResolver?.(tenantId, projectId)) ||
159
+ this.initializedRoots.has(`${tenantId}:${projectId}`)
160
+ )
161
+ return;
162
+ await fs.rm(this.resolveInternalPath(tenantId, projectId, externalUserId), {
163
+ recursive: true,
164
+ force: true,
165
+ });
166
+ }
167
+
168
+ async exists(
169
+ tenantId: string,
170
+ projectId: string,
171
+ externalUserId?: string,
172
+ ): Promise<boolean> {
173
+ const projectPath = await this.resolveProjectPath(
174
+ tenantId,
175
+ projectId,
176
+ externalUserId,
177
+ );
178
+ try {
179
+ await fs.access(projectPath);
180
+ return true;
181
+ } catch {
182
+ return false;
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * One directory name per identity. Principals such as the project's own
189
+ * (`catamorphic:project`, ADR 0156) carry characters that are not safe in
190
+ * every filesystem, so they are percent-encoded.
191
+ */
192
+ function sanitizeUserId(value: string): string {
193
+ // Ids that differ only by case must not share a folder on a
194
+ // case-insensitive disk: every byte outside `[a-z0-9._-]`, upper-case
195
+ // letters included, becomes `%xx` (lower-case hex), one to one.
196
+ let encoded = "";
197
+ for (const byte of new TextEncoder().encode(value)) {
198
+ const char = String.fromCharCode(byte);
199
+ encoded += /[a-z0-9._-]/.test(char)
200
+ ? char
201
+ : `%${byte.toString(16).padStart(2, "0")}`;
202
+ }
203
+ if (!encoded || encoded === "." || encoded === "..")
204
+ throw new Error(`Invalid externalUserId: ${value}`);
205
+ return encoded;
206
+ }