@sentropic/artifacts 0.2.16 → 0.2.18

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 (95) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/adapters/github-forge.d.ts +4 -0
  3. package/dist/adapters/github-forge.js +88 -0
  4. package/dist/adapters/github-git-port.d.ts +5 -0
  5. package/dist/adapters/github-git-port.js +102 -0
  6. package/dist/adapters/github-http.d.ts +5 -0
  7. package/dist/adapters/github-http.js +57 -0
  8. package/dist/adapters/github-receive-pack.d.ts +4 -0
  9. package/dist/adapters/github-receive-pack.js +49 -0
  10. package/dist/adapters/postgres-git-bindings.d.ts +7 -0
  11. package/dist/adapters/postgres-git-bindings.js +110 -0
  12. package/dist/adapters/postgres-live.d.ts +4 -0
  13. package/dist/adapters/postgres-live.js +97 -0
  14. package/dist/adapters/postgres.d.ts +1 -0
  15. package/dist/adapters/postgres.js +1 -0
  16. package/dist/content/handler.d.ts +7 -0
  17. package/dist/content/handler.js +28 -5
  18. package/dist/content/headers.d.ts +13 -0
  19. package/dist/content/headers.js +40 -2
  20. package/dist/git-tool-definitions.d.ts +606 -0
  21. package/dist/git-tool-definitions.js +14 -0
  22. package/dist/http.d.ts +6 -0
  23. package/dist/http.js +20 -2
  24. package/dist/index.d.ts +13 -0
  25. package/dist/index.js +12 -0
  26. package/dist/mcp-core.d.ts +3 -3
  27. package/dist/mcp-core.js +15 -2
  28. package/dist/profile/contracts.d.ts +1 -1
  29. package/dist/profile/contracts.js +4 -0
  30. package/dist/profile/index.js +8 -1
  31. package/dist/profile/schemas.js +19 -0
  32. package/dist/profile/validation.js +5 -1
  33. package/dist/server/build-contract.d.ts +64 -0
  34. package/dist/server/build-contract.js +58 -0
  35. package/dist/server/build-dependencies.d.ts +3 -0
  36. package/dist/server/build-dependencies.js +122 -0
  37. package/dist/server/consent-grant.d.ts +91 -0
  38. package/dist/server/consent-grant.js +89 -0
  39. package/dist/server/consent-screen.d.ts +21 -0
  40. package/dist/server/consent-screen.js +52 -0
  41. package/dist/server/failures.d.ts +3 -2
  42. package/dist/server/failures.js +30 -0
  43. package/dist/server/git-bindings.d.ts +8 -0
  44. package/dist/server/git-bindings.js +113 -0
  45. package/dist/server/git-contracts.d.ts +98 -0
  46. package/dist/server/git-contracts.js +1 -0
  47. package/dist/server/git-port-policy.d.ts +9 -0
  48. package/dist/server/git-port-policy.js +76 -0
  49. package/dist/server/git-port-read.d.ts +3 -0
  50. package/dist/server/git-port-read.js +95 -0
  51. package/dist/server/git-port-session.d.ts +38 -0
  52. package/dist/server/git-port-session.js +59 -0
  53. package/dist/server/git-port-tree.d.ts +8 -0
  54. package/dist/server/git-port-tree.js +92 -0
  55. package/dist/server/git-port-write.d.ts +6 -0
  56. package/dist/server/git-port-write.js +102 -0
  57. package/dist/server/git-port.d.ts +147 -0
  58. package/dist/server/git-port.js +8 -0
  59. package/dist/server/git-projection.d.ts +16 -0
  60. package/dist/server/git-projection.js +20 -0
  61. package/dist/server/git-registry.d.ts +37 -0
  62. package/dist/server/git-registry.js +39 -0
  63. package/dist/server/live-body.d.ts +3 -0
  64. package/dist/server/live-body.js +28 -0
  65. package/dist/server/live-commit-outcome.d.ts +6 -0
  66. package/dist/server/live-commit-outcome.js +10 -0
  67. package/dist/server/live-commit.d.ts +11 -0
  68. package/dist/server/live-commit.js +133 -0
  69. package/dist/server/live-contracts.d.ts +62 -0
  70. package/dist/server/live-contracts.js +8 -0
  71. package/dist/server/live-crypto.d.ts +14 -0
  72. package/dist/server/live-crypto.js +50 -0
  73. package/dist/server/live-drafts.d.ts +61 -0
  74. package/dist/server/live-drafts.js +119 -0
  75. package/dist/server/live-errors.d.ts +23 -0
  76. package/dist/server/live-errors.js +9 -0
  77. package/dist/server/live-mutations.d.ts +18 -0
  78. package/dist/server/live-mutations.js +83 -0
  79. package/dist/server/live-read.d.ts +15 -0
  80. package/dist/server/live-read.js +95 -0
  81. package/dist/server/live-service.d.ts +3 -0
  82. package/dist/server/live-service.js +181 -0
  83. package/dist/server/live-store.d.ts +111 -0
  84. package/dist/server/live-store.js +80 -0
  85. package/dist/server/live-tree.d.ts +22 -0
  86. package/dist/server/live-tree.js +148 -0
  87. package/dist/server/live-worker.d.ts +10 -0
  88. package/dist/server/live-worker.js +55 -0
  89. package/dist/server/mime.d.ts +9 -0
  90. package/dist/server/mime.js +47 -0
  91. package/dist/server/upload-page.d.ts +7 -0
  92. package/dist/server/upload-page.js +16 -1
  93. package/migrations/0010_git_bindings.sql +82 -0
  94. package/migrations/0011_live_drafts.sql +42 -0
  95. package/package.json +13 -1
@@ -0,0 +1,95 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { ArtifactOperationError } from './failures.js';
3
+ import { assertGitSha, gitPath } from './git-port-policy.js';
4
+ import { gitTrees } from './git-port-tree.js';
5
+ export function gitSourceReader(options, open) {
6
+ const mac = (data) => createHmac('sha256', options.cursorKey).update(data).digest('base64url');
7
+ return async (repo, target, input) => {
8
+ assertGitSha(input.commitSha);
9
+ if (input.paths && (!input.paths.length || input.paths.length > 255 || new Set(input.paths).size !== input.paths.length)) {
10
+ throw new ArtifactOperationError('invalid_request');
11
+ }
12
+ input.paths?.forEach(path => gitPath(repo, target, path, false));
13
+ const identity = mac(JSON.stringify([target, input.commitSha, input.paths ?? null]));
14
+ let offset = 0;
15
+ let total = 0;
16
+ if (input.cursor) {
17
+ try {
18
+ if (input.cursor.length > 4096)
19
+ throw new Error();
20
+ const parts = input.cursor.split('.');
21
+ if (parts.length !== 2 || !timingSafeEqual(Buffer.from(mac(parts[0])), Buffer.from(parts[1])))
22
+ throw new Error();
23
+ const data = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
24
+ if (data.identity !== identity || !Number.isSafeInteger(data.offset) || data.offset < 0 ||
25
+ !Number.isSafeInteger(data.total) || data.total < 0)
26
+ throw new Error();
27
+ offset = data.offset;
28
+ total = data.total;
29
+ }
30
+ catch {
31
+ throw new ArtifactOperationError('invalid_request');
32
+ }
33
+ }
34
+ const session = await open(repo);
35
+ const trees = gitTrees(session);
36
+ const root = await trees.root(input.commitSha);
37
+ let entries;
38
+ if (input.paths) {
39
+ entries = [];
40
+ for (const path of input.paths) {
41
+ const entry = await trees.lookup(root, gitPath(repo, target, path, false));
42
+ if (!entry)
43
+ throw new ArtifactOperationError('not_found');
44
+ if (entry.type !== 'blob')
45
+ throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason: 'not_file' } });
46
+ entries.push({ ...entry, path });
47
+ }
48
+ }
49
+ else
50
+ entries = await trees.enumerate(root, target);
51
+ if (offset > entries.length)
52
+ throw new ArtifactOperationError('invalid_request');
53
+ const files = [];
54
+ const page = entries.slice(offset, offset + (options.pageSize ?? 100));
55
+ for (const entry of page) {
56
+ let reason;
57
+ const maxFile = options.maxFileBytes ?? 1024 * 1024;
58
+ const maxTotal = options.maxTotalBytes ?? 8 * 1024 * 1024;
59
+ if ((entry.size ?? 0) > maxFile)
60
+ reason = 'too_large';
61
+ else if (total + (entry.size ?? 0) > maxTotal)
62
+ reason = 'over_total_budget';
63
+ if (reason) {
64
+ files.push({ path: entry.path, omitted: reason });
65
+ continue;
66
+ }
67
+ const bytes = await session.call((forge, context) => forge.blob(context, entry.sha));
68
+ if (bytes.length > maxFile)
69
+ reason = 'too_large';
70
+ else if (total + bytes.length > maxTotal)
71
+ reason = 'over_total_budget';
72
+ if (reason) {
73
+ files.push({ path: entry.path, omitted: reason });
74
+ continue;
75
+ }
76
+ if (/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/.test(Buffer.from(bytes).toString('utf8'))) {
77
+ throw new ArtifactOperationError('git_path_refused', { publicDetails: { path: entry.path, reason: 'private_key' } });
78
+ }
79
+ total += bytes.length;
80
+ try {
81
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
82
+ if (bytes.includes(0))
83
+ throw new Error();
84
+ files.push({ path: entry.path, text, encoding: 'utf-8' });
85
+ }
86
+ catch {
87
+ files.push({ path: entry.path, base64: Buffer.from(bytes).toString('base64'), encoding: 'base64' });
88
+ }
89
+ }
90
+ const next = offset + page.length;
91
+ const payload = Buffer.from(JSON.stringify({ identity, offset: next, total })).toString('base64url');
92
+ return { commitSha: input.commitSha, treeSha: root, files,
93
+ nextCursor: next < entries.length ? `${payload}.${mac(payload)}` : null };
94
+ };
95
+ }
@@ -0,0 +1,38 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import type { GitForge, GitForgeContext, GitHumanDirectory, GitIdentity, GitInstallationLeasePort, GitPortRepository, GitPortTarget } from './git-port.js';
3
+ export interface GitPortOptions {
4
+ registry: {
5
+ get(scope: string, repoId: string): Promise<GitPortRepository | undefined>;
6
+ };
7
+ leases?: GitInstallationLeasePort;
8
+ forge: GitForge;
9
+ directory: GitHumanDirectory;
10
+ committer: GitIdentity;
11
+ /** Current code rights, plus owner-only on writes; host resolves identity and binding. */
12
+ authorize(target: GitPortTarget, write: boolean): Promise<boolean>;
13
+ /** Host-owned stable cursor MAC key; never a forge/App credential. */
14
+ cursorKey: Uint8Array;
15
+ now?: () => number;
16
+ pageSize?: number;
17
+ maxFileBytes?: number;
18
+ maxTotalBytes?: number;
19
+ }
20
+ export interface GitPortSession {
21
+ repo: GitPortRepository;
22
+ call<T>(action: (forge: GitForge, context: GitForgeContext) => Promise<T>): Promise<T>;
23
+ }
24
+ /** A lost receive-pack acknowledgement must be reconciled by SG3, never retried as a new invocation. */
25
+ export declare class GitPortAdvanceUnknown extends ArtifactOperationError {
26
+ readonly commitState = "unknown";
27
+ constructor();
28
+ }
29
+ export declare function gitSessions(options: GitPortOptions): {
30
+ admit: (target: GitPortTarget, write: boolean) => Promise<GitPortRepository>;
31
+ open: (repo: GitPortRepository) => Promise<GitPortSession>;
32
+ invalidate(input: {
33
+ storageScopeId: string;
34
+ repoId: string;
35
+ installationRef: string;
36
+ credentialVersion: string;
37
+ }): void;
38
+ };
@@ -0,0 +1,59 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { GitForgeError } from './git-port.js';
3
+ import { assertGitTarget } from './git-port-policy.js';
4
+ /** A lost receive-pack acknowledgement must be reconciled by SG3, never retried as a new invocation. */
5
+ export class GitPortAdvanceUnknown extends ArtifactOperationError {
6
+ commitState = 'unknown';
7
+ constructor() { super('provider_unavailable'); }
8
+ }
9
+ export function gitSessions(options) {
10
+ const invalidated = new Set();
11
+ const key = (target, version) => JSON.stringify([target.storageScopeId, target.repoId, target.installationRef, version]);
12
+ async function admit(target, write) {
13
+ if (!await options.authorize(target, write))
14
+ throw new ArtifactOperationError('access_denied');
15
+ const repo = await options.registry.get(target.storageScopeId, target.repoId);
16
+ if (!repo)
17
+ throw new ArtifactOperationError('git_repo_not_registered');
18
+ assertGitTarget(repo, target, write);
19
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo.locator) || !repo.installationRef)
20
+ throw new ArtifactOperationError('provider_unavailable');
21
+ return repo;
22
+ }
23
+ async function open(repo) {
24
+ if (!options.leases)
25
+ throw new ArtifactOperationError('provider_unavailable');
26
+ let lease;
27
+ try {
28
+ lease = await options.leases.acquire({ storageScopeId: repo.storageScopeId, repoId: repo.repoId, installationRef: repo.installationRef });
29
+ }
30
+ catch (error) {
31
+ // SG0-app errors cross a structural port; never carry their message/body/cause onward.
32
+ throw new ArtifactOperationError(error?.code === 'access_denied' ? 'access_denied' : 'provider_unavailable');
33
+ }
34
+ const valid = () => lease && typeof lease.token === 'string' && !!lease.token &&
35
+ typeof lease.repositoryId === 'string' && !!lease.repositoryId && typeof lease.credentialVersion === 'string' && !!lease.credentialVersion &&
36
+ Date.parse(lease.expiresAt) > (options.now?.() ?? Date.now()) + 30_000 &&
37
+ lease.permissions?.contents === 'write' && lease.permissions.metadata === 'read' &&
38
+ Object.keys(lease.permissions).length === 2 && !invalidated.has(key(repo, lease.credentialVersion));
39
+ const session = { repo, async call(action) {
40
+ if (!valid())
41
+ throw new ArtifactOperationError('provider_unavailable');
42
+ try {
43
+ return await action(options.forge, { locator: repo.locator, token: lease.token });
44
+ }
45
+ catch (error) {
46
+ if (error instanceof GitForgeError)
47
+ throw error;
48
+ throw new ArtifactOperationError('provider_unavailable');
49
+ }
50
+ } };
51
+ if (await session.call((forge, context) => forge.repositoryId(context)) !== lease.repositoryId) {
52
+ throw new ArtifactOperationError('access_denied');
53
+ }
54
+ return session;
55
+ }
56
+ return { admit, open, invalidate(input) {
57
+ invalidated.add(key(input, input.credentialVersion));
58
+ } };
59
+ }
@@ -0,0 +1,8 @@
1
+ import type { GitPortTarget, GitTreeEntry } from './git-port.js';
2
+ import type { GitPortSession } from './git-port-session.js';
3
+ export declare function gitTrees(session: GitPortSession): {
4
+ root: (commitSha: string) => Promise<string>;
5
+ tree: (sha: string) => Promise<GitTreeEntry[]>;
6
+ lookup: (treeSha: string, path: string) => Promise<GitTreeEntry | undefined>;
7
+ enumerate: (treeSha: string, target: GitPortTarget) => Promise<GitTreeEntry[]>;
8
+ };
@@ -0,0 +1,92 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { GitForgeError } from './git-port.js';
3
+ import { assertGitSha, gitPath } from './git-port-policy.js';
4
+ export function gitTrees(session) {
5
+ const cache = new Map();
6
+ let entries = 0;
7
+ async function tree(sha) {
8
+ assertGitSha(sha);
9
+ if (!cache.has(sha)) {
10
+ if (cache.size >= 4096)
11
+ throw new ArtifactOperationError('limit_exceeded');
12
+ const result = await session.call((forge, context) => forge.tree(context, sha));
13
+ entries += result.length;
14
+ if (entries > 1_000_000)
15
+ throw new ArtifactOperationError('limit_exceeded');
16
+ const names = new Set();
17
+ for (const entry of result) {
18
+ if (!entry.path || entry.path.includes('/') || names.has(entry.path))
19
+ throw new ArtifactOperationError('provider_unavailable');
20
+ names.add(entry.path);
21
+ assertGitSha(entry.sha);
22
+ }
23
+ cache.set(sha, result);
24
+ }
25
+ return cache.get(sha);
26
+ }
27
+ async function root(commitSha) {
28
+ try {
29
+ const commit = await session.call((forge, context) => forge.resolve(context, commitSha));
30
+ if (commit.sha !== commitSha)
31
+ throw new ArtifactOperationError('provider_unavailable');
32
+ assertGitSha(commit.treeSha);
33
+ return commit.treeSha;
34
+ }
35
+ catch (error) {
36
+ if (error instanceof GitForgeError && error.code === 'missing')
37
+ throw new ArtifactOperationError('not_found');
38
+ throw error;
39
+ }
40
+ }
41
+ async function lookup(treeSha, path) {
42
+ const parts = path.split('/');
43
+ for (const [i, part] of parts.entries()) {
44
+ const entry = (await tree(treeSha)).find(e => e.path === part);
45
+ if (!entry)
46
+ return undefined;
47
+ if (!['040000', '100644', '100755'].includes(entry.mode) || entry.type === 'commit') {
48
+ throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason: 'path_alias' } });
49
+ }
50
+ if (i === parts.length - 1)
51
+ return entry;
52
+ if (entry.type !== 'tree' || entry.mode !== '040000') {
53
+ throw new ArtifactOperationError('git_path_refused', { publicDetails: { path, reason: 'not_directory' } });
54
+ }
55
+ treeSha = entry.sha;
56
+ }
57
+ }
58
+ async function enumerate(treeSha, target) {
59
+ if (target.subPath) {
60
+ const base = await lookup(treeSha, target.subPath);
61
+ if (!base || base.type !== 'tree')
62
+ throw new ArtifactOperationError('not_found');
63
+ treeSha = base.sha;
64
+ }
65
+ const files = [];
66
+ let traversed = 0;
67
+ async function walk(sha, prefix, depth) {
68
+ if (depth > 128)
69
+ throw new ArtifactOperationError('limit_exceeded');
70
+ for (const entry of await tree(sha)) {
71
+ if (++traversed > 1_000_000)
72
+ throw new ArtifactOperationError('limit_exceeded');
73
+ const path = `${prefix}${entry.path}`;
74
+ try {
75
+ gitPath(session.repo, target, path, false);
76
+ }
77
+ catch (error) {
78
+ if (error instanceof ArtifactOperationError && error.kind === 'git_path_refused')
79
+ continue;
80
+ throw error;
81
+ }
82
+ if (entry.type === 'tree' && entry.mode === '040000')
83
+ await walk(entry.sha, `${path}/`, depth + 1);
84
+ else if (entry.type === 'blob' && ['100644', '100755'].includes(entry.mode))
85
+ files.push({ ...entry, path });
86
+ }
87
+ }
88
+ await walk(treeSha, '', 0);
89
+ return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
90
+ }
91
+ return { root, tree, lookup, enumerate };
92
+ }
@@ -0,0 +1,6 @@
1
+ import type { GitCommitInput } from './git-port.js';
2
+ import type { GitPortOptions, gitSessions } from './git-port-session.js';
3
+ export declare function gitWriter(options: GitPortOptions, sessions: ReturnType<typeof gitSessions>): (input: GitCommitInput) => Promise<{
4
+ commitSha: string;
5
+ treeSha: string;
6
+ }>;
@@ -0,0 +1,102 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { GitForgeError } from './git-port.js';
3
+ import { GitPortAdvanceUnknown } from './git-port-session.js';
4
+ import { assertGitSha, gitPath } from './git-port-policy.js';
5
+ import { gitTrees } from './git-port-tree.js';
6
+ const validIdentity = (identity) => !!identity &&
7
+ !!identity.name.trim() && identity.name.length <= 256 && /^[^\s<>@]+@[^\s<>@]+$/.test(identity.email) &&
8
+ !/[\r\n\x00<>]/.test(identity.name);
9
+ export function gitWriter(options, sessions) {
10
+ return async (input) => {
11
+ const { target, expectedHeadSha } = input;
12
+ const repo = await sessions.admit(target, true);
13
+ assertGitSha(expectedHeadSha);
14
+ if (!input.files.length || input.files.length > 255 || !input.message.trim() || input.message.length > 16384 ||
15
+ /^Artifacts-(?:Artifact|Invocation|Base):/mi.test(input.message) ||
16
+ !Number.isFinite(Date.parse(input.createdAt)) || new Date(input.createdAt).toISOString() !== input.createdAt ||
17
+ !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(input.artifactId) ||
18
+ !/^[\w.-]{1,128}$/.test(input.invocationId))
19
+ throw new ArtifactOperationError('invalid_request');
20
+ const paths = input.files.map(file => gitPath(repo, target, file.path, true));
21
+ if (new Set(paths).size !== paths.length)
22
+ throw new ArtifactOperationError('invalid_request');
23
+ let bytes = 0;
24
+ for (const file of input.files) {
25
+ if (file.text === null)
26
+ continue;
27
+ if (typeof file.text !== 'string' || /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/.test(file.text) ||
28
+ file.text.includes('\0') || Buffer.from(file.text).toString('utf8') !== file.text) {
29
+ throw new ArtifactOperationError('git_path_refused', { publicDetails: { path: file.path, reason: 'not_source_text' } });
30
+ }
31
+ const size = Buffer.byteLength(file.text);
32
+ bytes += size;
33
+ if (size > (options.maxFileBytes ?? 1024 * 1024) || bytes > (options.maxTotalBytes ?? 8 * 1024 * 1024)) {
34
+ throw new ArtifactOperationError('limit_exceeded');
35
+ }
36
+ }
37
+ let author;
38
+ try {
39
+ author = await options.directory.resolve({ storageScopeId: target.storageScopeId, principalId: target.principalId });
40
+ }
41
+ catch {
42
+ throw new ArtifactOperationError('access_denied');
43
+ }
44
+ if (!validIdentity(author))
45
+ throw new ArtifactOperationError('access_denied');
46
+ if (!validIdentity(options.committer))
47
+ throw new ArtifactOperationError('provider_unavailable');
48
+ const session = await sessions.open(repo);
49
+ const head = async () => {
50
+ try {
51
+ return await session.call((forge, context) => forge.resolve(context, target.branch));
52
+ }
53
+ catch (error) {
54
+ if (error instanceof GitForgeError && error.code === 'missing') {
55
+ throw new ArtifactOperationError('git_branch_missing', { publicDetails: { branch: target.branch } });
56
+ }
57
+ throw error;
58
+ }
59
+ };
60
+ const moved = (actualHeadSha) => new ArtifactOperationError('git_head_moved', {
61
+ publicDetails: { expectedHeadSha, actualHeadSha },
62
+ });
63
+ const observed = await head();
64
+ if (observed.sha !== expectedHeadSha)
65
+ throw moved(observed.sha);
66
+ const trees = gitTrees(session);
67
+ const baseTree = await trees.root(expectedHeadSha);
68
+ const changes = [];
69
+ for (const [i, file] of input.files.entries()) {
70
+ const existing = await trees.lookup(baseTree, paths[i]);
71
+ if (existing?.type === 'tree')
72
+ throw new ArtifactOperationError('git_path_refused', { publicDetails: { path: file.path, reason: 'not_file' } });
73
+ if (!existing && file.text === null)
74
+ throw new ArtifactOperationError('invalid_request');
75
+ changes.push({ path: paths[i], text: file.text, mode: existing?.mode ?? '100644' });
76
+ }
77
+ if (!await options.authorize(target, true))
78
+ throw new ArtifactOperationError('access_denied');
79
+ const treeSha = await session.call((forge, context) => forge.createTree(context, baseTree, changes));
80
+ assertGitSha(treeSha);
81
+ const message = `${input.message}\n\nArtifacts-Artifact: ${input.artifactId}\nArtifacts-Invocation: ${input.invocationId}\nArtifacts-Base: ${expectedHeadSha}`;
82
+ const commitSha = await session.call((forge, context) => forge.createCommit(context, { parentSha: expectedHeadSha, treeSha, message, author, committer: options.committer, createdAt: input.createdAt }));
83
+ assertGitSha(commitSha);
84
+ if (!await options.authorize(target, true))
85
+ throw new ArtifactOperationError('access_denied');
86
+ let submitted = false;
87
+ try {
88
+ await session.call((forge, context) => { submitted = true; return forge.advance(context, target.branch, expectedHeadSha, commitSha); });
89
+ }
90
+ catch (error) {
91
+ if (!submitted)
92
+ throw error;
93
+ if (error instanceof GitForgeError && error.code === 'conflict') {
94
+ const actual = (await head()).sha;
95
+ throw actual === expectedHeadSha ? new ArtifactOperationError('git_ref_not_allowed') : moved(actual);
96
+ }
97
+ // A transport failure after submission cannot prove whether the ref advanced.
98
+ throw new GitPortAdvanceUnknown();
99
+ }
100
+ return { commitSha, treeSha };
101
+ };
102
+ }
@@ -0,0 +1,147 @@
1
+ /** Trusted server surface, G0 v3 §2.5/§2.7. Never expose forge locators or leases to tools. */
2
+ export interface GitInstallationLeasePort {
3
+ acquire(input: {
4
+ storageScopeId: string;
5
+ repoId: string;
6
+ installationRef: string;
7
+ }): Promise<{
8
+ token: string;
9
+ expiresAt: string;
10
+ repositoryId: string;
11
+ permissions: {
12
+ contents: 'write';
13
+ metadata: 'read';
14
+ };
15
+ credentialVersion: string;
16
+ }>;
17
+ }
18
+ /** Structural subset of SG1's registry; policy and identity come only from host composition. */
19
+ export interface GitPortRepository {
20
+ storageScopeId: string;
21
+ repoId: string;
22
+ locator: string;
23
+ installationRef: string;
24
+ branchPrefix: 'artifact/';
25
+ allowedSubPaths: string[];
26
+ canWrite: boolean;
27
+ writablePaths: string[];
28
+ refusedWritePaths: string[];
29
+ }
30
+ export interface GitPortTarget {
31
+ storageScopeId: string;
32
+ repoId: string;
33
+ branch: string;
34
+ subPath: string;
35
+ principalId: string;
36
+ /** Descriptor output subtree resolved by the host, relative to subPath. */
37
+ outputDir: string;
38
+ }
39
+ export interface GitIdentity {
40
+ name: string;
41
+ email: string;
42
+ }
43
+ export interface GitHumanDirectory {
44
+ /** Null means no authenticated human linkage. Emails must follow the host's noreply/service policy. */
45
+ resolve(input: {
46
+ storageScopeId: string;
47
+ principalId: string;
48
+ }): Promise<GitIdentity | null>;
49
+ }
50
+ export interface GitSourcePage {
51
+ commitSha: string;
52
+ treeSha: string;
53
+ files: ({
54
+ path: string;
55
+ text: string;
56
+ encoding: 'utf-8';
57
+ } | {
58
+ path: string;
59
+ base64: string;
60
+ encoding: 'base64';
61
+ } | {
62
+ path: string;
63
+ omitted: 'too_large' | 'over_total_budget';
64
+ })[];
65
+ nextCursor: string | null;
66
+ }
67
+ export interface GitCommitInput {
68
+ target: GitPortTarget;
69
+ expectedHeadSha: string;
70
+ artifactId: string;
71
+ invocationId: string;
72
+ /** Persisted with SG3's durable intent, reused verbatim for object replay. */
73
+ createdAt: string;
74
+ message: string;
75
+ /** Fully materialized changes after SG3's exactly-once edit application; null deletes. */
76
+ files: {
77
+ path: string;
78
+ text: string | null;
79
+ }[];
80
+ }
81
+ export interface GitPort {
82
+ /** Trusted metadata only: complete immutable repository tree, including excluded base entries. */
83
+ snapshot?(target: GitPortTarget, commitSha: string): Promise<{
84
+ treeSha: string;
85
+ entries: GitTreeEntry[];
86
+ }>;
87
+ resolveRef(target: GitPortTarget, ref: string): Promise<string>;
88
+ inspectCommit(target: GitPortTarget, commitSha: string): Promise<GitResolvedCommit>;
89
+ read(target: GitPortTarget, input: {
90
+ commitSha: string;
91
+ paths?: string[];
92
+ cursor?: string;
93
+ }): Promise<GitSourcePage>;
94
+ commit(input: GitCommitInput): Promise<{
95
+ commitSha: string;
96
+ treeSha: string;
97
+ }>;
98
+ isAncestor(target: GitPortTarget, ancestorSha: string, descendantSha: string): Promise<boolean>;
99
+ createBranch(target: GitPortTarget, baseCommitSha: string): Promise<void>;
100
+ }
101
+ export interface GitForgeContext {
102
+ locator: string;
103
+ token: string;
104
+ }
105
+ export interface GitResolvedCommit {
106
+ sha: string;
107
+ treeSha: string;
108
+ parents: string[];
109
+ message: string;
110
+ author: GitIdentity;
111
+ committer: GitIdentity;
112
+ }
113
+ export interface GitTreeEntry {
114
+ path: string;
115
+ sha: string;
116
+ type: 'tree' | 'blob' | 'commit';
117
+ mode: string;
118
+ size?: number;
119
+ }
120
+ /** Transport failures contain stable codes only. Driver bodies/headers must never escape. */
121
+ export declare class GitForgeError extends Error {
122
+ readonly code: 'missing' | 'conflict' | 'unavailable' | 'unknown';
123
+ constructor(code: 'missing' | 'conflict' | 'unavailable' | 'unknown');
124
+ }
125
+ export interface GitForge {
126
+ repositoryId(context: GitForgeContext): Promise<string>;
127
+ resolve(context: GitForgeContext, ref: string): Promise<GitResolvedCommit>;
128
+ tree(context: GitForgeContext, treeSha: string): Promise<GitTreeEntry[]>;
129
+ blob(context: GitForgeContext, sha: string): Promise<Uint8Array>;
130
+ createTree(context: GitForgeContext, baseTreeSha: string, changes: {
131
+ path: string;
132
+ text: string | null;
133
+ mode: string;
134
+ }[]): Promise<string>;
135
+ createCommit(context: GitForgeContext, input: {
136
+ parentSha: string;
137
+ treeSha: string;
138
+ message: string;
139
+ author: GitIdentity;
140
+ committer: GitIdentity;
141
+ createdAt: string;
142
+ }): Promise<string>;
143
+ /** Must compare the old SHA atomically. REST update-ref(force=false) alone is insufficient. */
144
+ advance(context: GitForgeContext, branch: string, expectedSha: string, commitSha: string): Promise<void>;
145
+ createBranch(context: GitForgeContext, branch: string, baseSha: string): Promise<void>;
146
+ isAncestor(context: GitForgeContext, ancestorSha: string, descendantSha: string): Promise<boolean>;
147
+ }
@@ -0,0 +1,8 @@
1
+ /** Transport failures contain stable codes only. Driver bodies/headers must never escape. */
2
+ export class GitForgeError extends Error {
3
+ code;
4
+ constructor(code) {
5
+ super(code);
6
+ this.code = code;
7
+ }
8
+ }
@@ -0,0 +1,16 @@
1
+ import type { GitBindingStore, GitCodeRightsPort } from './git-contracts.js';
2
+ export interface GitProjectionPorts {
3
+ bindings: GitBindingStore;
4
+ codeRights: GitCodeRightsPort;
5
+ }
6
+ /** Artifact visibility is checked by the caller; repository rights are a separate live host decision. */
7
+ export declare function projectGitBinding(ports: GitProjectionPorts | undefined, input: {
8
+ storageScopeId: string;
9
+ artifactId: string;
10
+ actorId: string;
11
+ ownerId: string;
12
+ }): Promise<{
13
+ git?: undefined;
14
+ } | {
15
+ git: import("./git-contracts.js").GitBinding;
16
+ }>;
@@ -0,0 +1,20 @@
1
+ /** Artifact visibility is checked by the caller; repository rights are a separate live host decision. */
2
+ export async function projectGitBinding(ports, input) {
3
+ if (!ports)
4
+ return {};
5
+ const binding = await ports.bindings.get(input.storageScopeId, input.artifactId);
6
+ if (!binding || binding.storageScopeId !== input.storageScopeId || binding.artifactId !== input.artifactId)
7
+ return {};
8
+ let allowed = false;
9
+ try {
10
+ allowed = await ports.codeRights.canReadCode({ storageScopeId: input.storageScopeId,
11
+ repoId: binding.repoId, actorId: input.actorId }) === true;
12
+ }
13
+ catch { /* Fail closed on unavailable rights. */ }
14
+ if (!allowed)
15
+ return {};
16
+ const projected = structuredClone(binding);
17
+ if (input.actorId !== input.ownerId)
18
+ delete projected.live;
19
+ return { git: projected };
20
+ }
@@ -0,0 +1,37 @@
1
+ export interface GitRepository {
2
+ repoId: string;
3
+ storageScopeId: string;
4
+ forge: 'github-app' | 'git-ssh';
5
+ locator: string;
6
+ installationRef: string;
7
+ webhookSecretRef: string;
8
+ branchPrefix: 'artifact/';
9
+ allowedSubPaths: string[];
10
+ writablePaths: string[];
11
+ refusedWritePaths: string[];
12
+ publicationPolicy: {
13
+ personalBranchPrefix: 'artifact/p/';
14
+ sharedPublishers: {
15
+ branch: string;
16
+ principalIds: string[];
17
+ designationRef: string;
18
+ }[];
19
+ delegatedPublication: 'none' | 'personal-only' | 'designated-shared';
20
+ };
21
+ canWrite: boolean;
22
+ codePolicyRef: string;
23
+ }
24
+ export interface GitRepositoryRegistry {
25
+ get(storageScopeId: string, repoId: string): Promise<GitRepository | undefined>;
26
+ }
27
+ export type GitRepositoryInput = Omit<GitRepository, 'publicationPolicy' | 'canWrite' | 'writablePaths' | 'refusedWritePaths'> & {
28
+ publicationPolicy?: Partial<GitRepository['publicationPolicy']>;
29
+ canWrite?: boolean;
30
+ writablePaths?: string[];
31
+ refusedWritePaths?: string[];
32
+ };
33
+ /** Host-only registry. No enrollment/credential material is accepted by any tool. */
34
+ export declare function createGitRepositoryRegistry(entries: readonly GitRepositoryInput[]): GitRepositoryRegistry;
35
+ /** Git ref grammar, restricted to the host namespace; accepts branch names, never refs/heads aliases. */
36
+ export declare function isAllowedGitBranch(branch: string): boolean;
37
+ export declare function validateGitBindingTarget(registry: GitRepositoryRegistry, scope: string, repoId: string, branch: string, subPath: string): Promise<GitRepository>;