@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.18
4
+
5
+ - Export the canonical MIME helpers through `server/mime` and the generic
6
+ reader-consent service, typed refusal, navigation and neutral screen through
7
+ `server/consent-grant`; the app retains its existing grant behavior.
8
+ - Add scope-bound Git bindings, a closed host repository registry, durable
9
+ Postgres lifecycle and replay records, and immutable release-index readers.
10
+ Git metadata is projected only with the caller's current repository code right.
11
+ - Add the GitHub GitPort with injected cluster-mesh installation leases,
12
+ SHA-pinned reads, bounded source pagination and atomic multi-file commits.
13
+ Commits retain server-resolved human authorship and an App committer.
14
+ - Export build descriptor and locked dependency validation through
15
+ `@sentropic/artifacts/server/build-contract`. Validation executes no build
16
+ or lifecycle script; executor and live activation keep their separate gates.
17
+ - Integrate SG0-app, SG1, GB1 and SG2 on one release train after 0.2.17.
18
+ Existing MCP definitions and the APP-P1 four-tool selection are unchanged.
19
+ SQLite Git-binding parity and real forge qualification remain separate lots.
20
+
21
+ ## 0.2.17
22
+
23
+ - Application assets carry the worker's own same-origin/no-eval CSP; HTML inline hashes stay confined to HTML responses.
24
+ - Application content mode (host-configured, owner decision 05/11): the
25
+ generic host offers `safe` (historic strict regime, default, bit-for-bit
26
+ unchanged) and `application` (binding J1.0 policy: same-origin workers,
27
+ runtime-injected styles, history fallback to `index.html` for
28
+ extensionless HTML navigations). Service workers stay refused in both
29
+ modes; a missing asset stays 404, never the fallback. The policy lives in
30
+ one constant so the conductor can relay adjustments.
31
+ - Generic extension to MIME map: `.geojson` → `application/json`,
32
+ `.mjs` → `text/javascript`, `.woff2` → `font/woff2`; `.wasm` →
33
+ `application/wasm` and `.pbf` → `application/x-protobuf` stay mapped as
34
+ the owner asked. No `wasm-unsafe-eval` in any served policy.
35
+ - Generic grant contract (J1.3b): first-party grant route wired to
36
+ `grantWithFreshRights`, neutral host-parameterizable consent screen,
37
+ typed 403 `{ code, scopeId, retryable: false }` with a single prescribed
38
+ screen navigation, scopes and versions host-declared.
39
+ - No MCP tool definition changes (the 17 pre-existing definitions stay
40
+ byte-identical). Stays in `0.2.x` (cluster-mesh peer `>=0.2.0 <0.3.0`).
41
+
3
42
  ## 0.2.16
4
43
 
5
44
  - Upload channel integrity, fail-closed (immo preprod, OVH S3 403): the
@@ -0,0 +1,4 @@
1
+ import type { GitForge } from '../server/git-port.js';
2
+ import type { GitHubFetch } from './github-http.js';
3
+ /** Fixed public GitHub origins. The SG0-net host owns network admission and egress receipts. */
4
+ export declare function createGitHubForge(fetcher?: GitHubFetch): GitForge;
@@ -0,0 +1,88 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { GitForgeError } from '../server/git-port.js';
3
+ import { githubApi } from './github-http.js';
4
+ import { githubReceivePack } from './github-receive-pack.js';
5
+ import { assertGitBranch } from '../server/git-port-policy.js';
6
+ const sha = (value) => {
7
+ if (typeof value !== 'string' || !/^[0-9a-f]{40}$/.test(value))
8
+ throw new GitForgeError('unavailable');
9
+ return value;
10
+ };
11
+ /** Fixed public GitHub origins. The SG0-net host owns network admission and egress receipts. */
12
+ export function createGitHubForge(fetcher = globalThis.fetch) {
13
+ const api = githubApi(fetcher);
14
+ return {
15
+ async repositoryId(context) {
16
+ const result = await api(context, '');
17
+ if (!Number.isSafeInteger(result?.id) || result.id <= 0 ||
18
+ typeof result.full_name !== 'string' || result.full_name.toLowerCase() !== context.locator.toLowerCase())
19
+ throw new GitForgeError('unavailable');
20
+ return String(result.id);
21
+ },
22
+ async resolve(context, ref) {
23
+ const result = await api(context, `/commits/${encodeURIComponent(ref)}`);
24
+ if (!Array.isArray(result?.parents) || typeof result?.commit?.message !== 'string' ||
25
+ [result.commit.author, result.commit.committer].some(person => typeof person?.name !== 'string' || typeof person?.email !== 'string')) {
26
+ throw new GitForgeError('unavailable');
27
+ }
28
+ return { sha: sha(result.sha), treeSha: sha(result.commit.tree?.sha), parents: result.parents.map((p) => sha(p?.sha)),
29
+ message: result.commit.message, author: { name: result.commit.author.name, email: result.commit.author.email },
30
+ committer: { name: result.commit.committer.name, email: result.commit.committer.email } };
31
+ },
32
+ async tree(context, treeSha) {
33
+ const result = await api(context, `/git/trees/${sha(treeSha)}`); // Never use recursive=1 (silent truncation).
34
+ if (result?.truncated !== false || sha(result?.sha) !== treeSha || !Array.isArray(result.tree))
35
+ throw new GitForgeError('unavailable');
36
+ return result.tree.map((entry) => {
37
+ if (typeof entry?.path !== 'string' || !['tree', 'blob', 'commit'].includes(entry.type) ||
38
+ !['040000', '100644', '100755', '120000', '160000'].includes(entry.mode) ||
39
+ (entry.size !== undefined && (!Number.isSafeInteger(entry.size) || entry.size < 0)))
40
+ throw new GitForgeError('unavailable');
41
+ return { path: entry.path, sha: sha(entry.sha), type: entry.type, mode: entry.mode,
42
+ ...(entry.size === undefined ? {} : { size: entry.size }) };
43
+ });
44
+ },
45
+ async blob(context, blobSha) {
46
+ const result = await api(context, `/git/blobs/${sha(blobSha)}`);
47
+ if (sha(result?.sha) !== blobSha || result.encoding !== 'base64' || typeof result.content !== 'string')
48
+ throw new GitForgeError('unavailable');
49
+ const content = result.content.replace(/\n/g, '');
50
+ const bytes = Buffer.from(content, 'base64');
51
+ if (bytes.toString('base64') !== content || result.size !== bytes.length ||
52
+ createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex') !== blobSha)
53
+ throw new GitForgeError('unavailable');
54
+ return bytes;
55
+ },
56
+ async createTree(context, baseTreeSha, changes) {
57
+ const result = await api(context, '/git/trees', { base_tree: sha(baseTreeSha), tree: changes.map(change => ({
58
+ path: change.path, mode: change.mode, type: 'blob',
59
+ ...(change.text === null ? { sha: null } : { content: change.text }),
60
+ })) });
61
+ return sha(result?.sha);
62
+ },
63
+ async createCommit(context, input) {
64
+ const result = await api(context, '/git/commits', { message: input.message, tree: sha(input.treeSha),
65
+ parents: [sha(input.parentSha)], author: { ...input.author, date: input.createdAt },
66
+ committer: { ...input.committer, date: input.createdAt } });
67
+ return sha(result?.sha);
68
+ },
69
+ async advance(context, branch, expectedSha, commitSha) {
70
+ assertGitBranch(branch);
71
+ sha(expectedSha);
72
+ sha(commitSha);
73
+ await githubReceivePack(fetcher, context, branch, expectedSha, commitSha);
74
+ },
75
+ async createBranch(context, branch, baseSha) {
76
+ assertGitBranch(branch);
77
+ const result = await api(context, '/git/refs', { ref: `refs/heads/${branch}`, sha: sha(baseSha) });
78
+ if (result?.ref !== `refs/heads/${branch}` || result?.object?.sha !== baseSha)
79
+ throw new GitForgeError('unavailable');
80
+ },
81
+ async isAncestor(context, ancestor, descendant) {
82
+ const result = await api(context, `/compare/${sha(ancestor)}...${sha(descendant)}`);
83
+ if (!['identical', 'ahead', 'behind', 'diverged'].includes(result?.status) || result?.base_commit?.sha !== ancestor)
84
+ throw new GitForgeError('unavailable');
85
+ return result.status === 'identical' || result.status === 'ahead';
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,5 @@
1
+ import type { GitPort } from '../server/git-port.js';
2
+ import { gitSessions } from '../server/git-port-session.js';
3
+ import type { GitPortOptions } from '../server/git-port-session.js';
4
+ /** Trusted SG0-net composition only. Inject SG0-app's lease port, never an App key or PAT. */
5
+ export declare function createGitPort(options: GitPortOptions): GitPort & Pick<ReturnType<typeof gitSessions>, 'invalidate'>;
@@ -0,0 +1,102 @@
1
+ import { ArtifactOperationError } from '../server/failures.js';
2
+ import { GitForgeError } from '../server/git-port.js';
3
+ import { assertGitReadRef, assertGitSha } from '../server/git-port-policy.js';
4
+ import { gitSessions } from '../server/git-port-session.js';
5
+ import { gitSourceReader } from '../server/git-port-read.js';
6
+ import { gitWriter } from '../server/git-port-write.js';
7
+ import { gitTrees } from '../server/git-port-tree.js';
8
+ /** Trusted SG0-net composition only. Inject SG0-app's lease port, never an App key or PAT. */
9
+ export function createGitPort(options) {
10
+ if (options.cursorKey.byteLength < 32 || !Number.isInteger(options.pageSize ?? 100) ||
11
+ (options.pageSize ?? 100) < 1 || (options.pageSize ?? 100) > 255 ||
12
+ [options.maxFileBytes ?? 1, options.maxTotalBytes ?? 1].some(n => !Number.isSafeInteger(n) || n < 1)) {
13
+ throw new ArtifactOperationError('invalid_request');
14
+ }
15
+ const sessions = gitSessions(options);
16
+ const reader = gitSourceReader(options, sessions.open);
17
+ const writer = gitWriter(options, sessions);
18
+ async function safe(action) {
19
+ try {
20
+ return await action();
21
+ }
22
+ catch (error) {
23
+ if (error instanceof ArtifactOperationError)
24
+ throw error;
25
+ if (error instanceof GitForgeError && error.code === 'missing')
26
+ throw new ArtifactOperationError('not_found');
27
+ if (error instanceof GitForgeError && error.code === 'conflict')
28
+ throw new ArtifactOperationError('git_ref_not_allowed');
29
+ throw new ArtifactOperationError('provider_unavailable');
30
+ }
31
+ }
32
+ return {
33
+ invalidate: sessions.invalidate,
34
+ snapshot: (target, commitSha) => safe(async () => {
35
+ const repo = await sessions.admit(target, false);
36
+ assertGitSha(commitSha);
37
+ const trees = gitTrees(await sessions.open(repo));
38
+ const root = await trees.root(commitSha);
39
+ const entries = [];
40
+ async function walk(sha, prefix, depth) {
41
+ if (depth > 128)
42
+ throw new ArtifactOperationError('limit_exceeded');
43
+ for (const entry of await trees.tree(sha)) {
44
+ if (entries.length >= 1_000_000)
45
+ throw new ArtifactOperationError('limit_exceeded');
46
+ if (entry.type === 'tree') {
47
+ const children = await trees.tree(entry.sha);
48
+ if (!children.length)
49
+ entries.push({ ...entry, path: prefix + entry.path });
50
+ else
51
+ await walk(entry.sha, prefix + entry.path + '/', depth + 1);
52
+ }
53
+ else
54
+ entries.push({ ...entry, path: prefix + entry.path });
55
+ }
56
+ }
57
+ await walk(root, '', 0);
58
+ return { treeSha: root, entries };
59
+ }),
60
+ resolveRef: (target, ref) => safe(async () => {
61
+ const repo = await sessions.admit(target, false);
62
+ assertGitReadRef(ref);
63
+ const session = await sessions.open(repo);
64
+ let result;
65
+ try {
66
+ result = await session.call((forge, context) => forge.resolve(context, ref));
67
+ }
68
+ catch (error) {
69
+ if (ref === target.branch && error instanceof GitForgeError && error.code === 'missing') {
70
+ throw new ArtifactOperationError('git_branch_missing', { publicDetails: { branch: target.branch } });
71
+ }
72
+ throw error;
73
+ }
74
+ assertGitSha(result.sha);
75
+ return result.sha;
76
+ }),
77
+ read: (target, input) => safe(async () => reader(await sessions.admit(target, false), target, input)),
78
+ inspectCommit: (target, commitSha) => safe(async () => {
79
+ const repo = await sessions.admit(target, false);
80
+ assertGitSha(commitSha);
81
+ const session = await sessions.open(repo);
82
+ const result = await session.call((forge, context) => forge.resolve(context, commitSha));
83
+ if (result.sha !== commitSha)
84
+ throw new ArtifactOperationError('provider_unavailable');
85
+ return result;
86
+ }),
87
+ commit: input => safe(() => writer(input)),
88
+ isAncestor: (target, ancestor, descendant) => safe(async () => {
89
+ const repo = await sessions.admit(target, false);
90
+ assertGitSha(ancestor);
91
+ assertGitSha(descendant);
92
+ const session = await sessions.open(repo);
93
+ return session.call((forge, context) => forge.isAncestor(context, ancestor, descendant));
94
+ }),
95
+ createBranch: (target, baseSha) => safe(async () => {
96
+ const repo = await sessions.admit(target, true);
97
+ assertGitSha(baseSha);
98
+ const session = await sessions.open(repo);
99
+ await session.call((forge, context) => forge.createBranch(context, target.branch, baseSha));
100
+ }),
101
+ };
102
+ }
@@ -0,0 +1,5 @@
1
+ import type { GitForgeContext } from '../server/git-port.js';
2
+ export type GitHubFetch = typeof globalThis.fetch;
3
+ /** No redirects, driver text or response headers can carry an installation token out of this adapter. */
4
+ export declare function githubBytes(fetcher: GitHubFetch, url: string, init: RequestInit, maxBytes?: number): Promise<Uint8Array>;
5
+ export declare function githubApi(fetcher: GitHubFetch): (context: GitForgeContext, path: string, body?: unknown) => Promise<any>;
@@ -0,0 +1,57 @@
1
+ import { GitForgeError } from '../server/git-port.js';
2
+ /** No redirects, driver text or response headers can carry an installation token out of this adapter. */
3
+ export async function githubBytes(fetcher, url, init, maxBytes = 16 * 1024 * 1024) {
4
+ let response;
5
+ try {
6
+ response = await fetcher(url, { ...init, redirect: 'error', signal: AbortSignal.timeout(15_000) });
7
+ }
8
+ catch {
9
+ throw new GitForgeError('unavailable');
10
+ }
11
+ if (!response.ok) {
12
+ await response.body?.cancel();
13
+ throw new GitForgeError(response.status === 404 ? 'missing' : [409, 422].includes(response.status) ? 'conflict' : 'unavailable');
14
+ }
15
+ if (Number(response.headers.get('content-length')) > maxBytes) {
16
+ await response.body?.cancel();
17
+ throw new GitForgeError('unavailable');
18
+ }
19
+ if (!response.body)
20
+ throw new GitForgeError('unavailable');
21
+ const reader = response.body.getReader();
22
+ const chunks = [];
23
+ let count = 0;
24
+ try {
25
+ for (;;) {
26
+ const { done, value } = await reader.read();
27
+ if (done)
28
+ break;
29
+ count += value.length;
30
+ if (count > maxBytes) {
31
+ await reader.cancel();
32
+ throw new GitForgeError('unavailable');
33
+ }
34
+ chunks.push(value);
35
+ }
36
+ }
37
+ catch {
38
+ throw new GitForgeError('unavailable');
39
+ }
40
+ return Buffer.concat(chunks);
41
+ }
42
+ export function githubApi(fetcher) {
43
+ return async (context, path, body) => {
44
+ const bytes = await githubBytes(fetcher, `https://api.github.com/repos/${context.locator}${path}`, {
45
+ method: body === undefined ? 'GET' : 'POST',
46
+ headers: { authorization: `Bearer ${context.token}`, accept: 'application/vnd.github+json',
47
+ 'x-github-api-version': '2022-11-28', 'content-type': 'application/json' },
48
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
49
+ });
50
+ try {
51
+ return JSON.parse(Buffer.from(bytes).toString('utf8'));
52
+ }
53
+ catch {
54
+ throw new GitForgeError('unavailable');
55
+ }
56
+ };
57
+ }
@@ -0,0 +1,4 @@
1
+ import type { GitForgeContext } from '../server/git-port.js';
2
+ import type { GitHubFetch } from './github-http.js';
3
+ /** Smart HTTP old-id/new-id update, not REST's fast-forward-only approximation to CAS. */
4
+ export declare function githubReceivePack(fetcher: GitHubFetch, context: GitForgeContext, branch: string, expectedSha: string, commitSha: string): Promise<void>;
@@ -0,0 +1,49 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { GitForgeError } from '../server/git-port.js';
3
+ import { githubBytes } from './github-http.js';
4
+ const packet = (text) => {
5
+ const data = Buffer.from(text);
6
+ return Buffer.concat([Buffer.from((data.length + 4).toString(16).padStart(4, '0')), data]);
7
+ };
8
+ /** Smart HTTP old-id/new-id update, not REST's fast-forward-only approximation to CAS. */
9
+ export async function githubReceivePack(fetcher, context, branch, expectedSha, commitSha) {
10
+ const ref = `refs/heads/${branch}`;
11
+ const pack = Buffer.from('5041434b0000000200000000', 'hex'); // Version 2, zero objects: REST already uploaded them.
12
+ const body = Buffer.concat([packet(`${expectedSha} ${commitSha} ${ref}\0report-status\n`), Buffer.from('0000'),
13
+ pack, createHash('sha1').update(pack).digest()]);
14
+ let bytes;
15
+ try {
16
+ bytes = await githubBytes(fetcher, `https://github.com/${context.locator}.git/git-receive-pack`, {
17
+ method: 'POST', headers: {
18
+ authorization: `Basic ${Buffer.from(`x-access-token:${context.token}`).toString('base64')}`,
19
+ 'content-type': 'application/x-git-receive-pack-request', accept: 'application/x-git-receive-pack-result',
20
+ }, body,
21
+ }, 64 * 1024);
22
+ }
23
+ catch {
24
+ throw new GitForgeError('unknown');
25
+ }
26
+ const result = Buffer.from(bytes);
27
+ const lines = [];
28
+ let offset = 0;
29
+ while (offset < result.length) {
30
+ const header = result.subarray(offset, offset + 4).toString('ascii');
31
+ if (!/^[0-9a-f]{4}$/.test(header))
32
+ throw new GitForgeError('unknown');
33
+ const length = parseInt(header, 16);
34
+ offset += 4;
35
+ if (length === 0)
36
+ break;
37
+ if (length < 4 || offset + length - 4 > result.length)
38
+ throw new GitForgeError('unknown');
39
+ lines.push(result.subarray(offset, offset + length - 4).toString('utf8').replace(/\n$/, ''));
40
+ offset += length - 4;
41
+ }
42
+ if (lines[0] !== 'unpack ok')
43
+ throw new GitForgeError('unknown');
44
+ if (lines.length === 2 && lines[1] === `ok ${ref}`)
45
+ return;
46
+ if (lines.length === 2 && lines[1].startsWith(`ng ${ref} `))
47
+ throw new GitForgeError('conflict');
48
+ throw new GitForgeError('unknown');
49
+ }
@@ -0,0 +1,7 @@
1
+ import type { Pool } from 'pg';
2
+ import { type GitBindingStore } from '../server/git-bindings.js';
3
+ import type { GitReleaseIndexStore } from '../server/git-contracts.js';
4
+ /** Injected pool, no import-time I/O/DDL. All mutation work shares one transaction. */
5
+ export declare function createPostgresGitBindingStore(pool: Pool): GitBindingStore;
6
+ /** Read-only SG1 port. SG4 writes both surfaces in the release transaction. */
7
+ export declare function createPostgresGitReleaseIndexStore(pool: Pool): GitReleaseIndexStore;
@@ -0,0 +1,110 @@
1
+ import { ArtifactOperationError } from '../server/failures.js';
2
+ import { gitBindingEvent, gitBindingReceiptKey, validateGitBindingWrite } from '../server/git-bindings.js';
3
+ const fields = ['artifactId', 'storageScopeId', 'repoId', 'branch', 'channel', 'personalPrincipalId', 'subPath',
4
+ 'baseCommitSha', 'headCommitSha', 'releaseCommitSha', 'autoPublish', 'executor', 'pendingJobId',
5
+ 'pendingCommitSha', 'state', 'stateDetail', 'generation', 'version', 'attachedBy', 'attachedAt', 'updatedAt'];
6
+ const column = (key) => key.replace(/[A-Z]/g, c => '_' + c.toLowerCase());
7
+ function bindingRow(row) {
8
+ return Object.fromEntries(fields.flatMap(key => {
9
+ const value = row[column(key)];
10
+ return key === 'stateDetail' && value === null ? [] : [[key, value instanceof Date ? value.toISOString() : value]];
11
+ }));
12
+ }
13
+ /** Injected pool, no import-time I/O/DDL. All mutation work shares one transaction. */
14
+ export function createPostgresGitBindingStore(pool) {
15
+ return {
16
+ async get(scope, id) {
17
+ const { rows } = await pool.query('SELECT * FROM artifacts.git_bindings WHERE storage_scope_id=$1 AND artifact_id=$2', [scope, id]);
18
+ return rows[0] ? bindingRow(rows[0]) : undefined;
19
+ },
20
+ async events(scope, id) {
21
+ const { rows } = await pool.query(`SELECT * FROM artifacts.git_binding_events
22
+ WHERE storage_scope_id=$1 AND artifact_id=$2 ORDER BY id`, [scope, id]);
23
+ return rows.map(row => {
24
+ const event = { id: String(row.id), artifactId: row.artifact_id,
25
+ storageScopeId: row.storage_scope_id, actorId: row.actor_id, action: row.action,
26
+ createdAt: row.created_at.toISOString() };
27
+ for (const key of ['beforeSha', 'afterSha', 'deliveryId', 'invocationId']) {
28
+ if (row[column(key)] !== null)
29
+ event[key] = row[column(key)];
30
+ }
31
+ return event;
32
+ });
33
+ },
34
+ async write(input) {
35
+ const snapshot = structuredClone(input);
36
+ const binding = snapshot.binding;
37
+ const scope = binding.storageScopeId;
38
+ const key = gitBindingReceiptKey(snapshot);
39
+ const client = await pool.connect();
40
+ try {
41
+ await client.query('BEGIN');
42
+ // Serialize absent receipts as well as replays across processes.
43
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [key]);
44
+ const parent = await client.query(`SELECT id FROM artifacts.artifacts
45
+ WHERE storage_scope_id=$1 AND id=$2 FOR UPDATE`, [scope, binding.artifactId]);
46
+ if (!parent.rows[0])
47
+ throw new ArtifactOperationError('not_found');
48
+ const receipt = await client.query('SELECT params_hash,result FROM artifacts.idempotency_keys WHERE key=$1', [key]);
49
+ if (receipt.rows[0]) {
50
+ if (receipt.rows[0].params_hash !== snapshot.commandHash)
51
+ throw new ArtifactOperationError('command_conflict');
52
+ await client.query('COMMIT');
53
+ return { binding: receipt.rows[0].result, replayed: true };
54
+ }
55
+ const before = await client.query(`SELECT * FROM artifacts.git_bindings
56
+ WHERE storage_scope_id=$1 AND artifact_id=$2 FOR UPDATE`, [scope, binding.artifactId]);
57
+ validateGitBindingWrite(before.rows[0] ? bindingRow(before.rows[0]) : undefined, snapshot);
58
+ const columns = fields.map(column);
59
+ const values = fields.map(key => binding[key] ?? null);
60
+ await client.query(`INSERT INTO artifacts.git_bindings (${columns.join(',')})
61
+ VALUES (${fields.map((_, i) => '$' + (i + 1)).join(',')})
62
+ ON CONFLICT (artifact_id) DO UPDATE SET ${columns.slice(1).map(c => `${c}=EXCLUDED.${c}`).join(',')}
63
+ WHERE git_bindings.storage_scope_id=EXCLUDED.storage_scope_id`, values);
64
+ const event = gitBindingEvent(snapshot);
65
+ await client.query(`INSERT INTO artifacts.git_binding_events
66
+ (artifact_id,storage_scope_id,actor_id,action,before_sha,after_sha,delivery_id,invocation_id,created_at)
67
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [binding.artifactId, scope, snapshot.actorId,
68
+ event.action, event.beforeSha ?? null, event.afterSha ?? null,
69
+ event.deliveryId ?? null, event.invocationId ?? null, event.createdAt]);
70
+ await client.query('INSERT INTO artifacts.idempotency_keys(key,params_hash,result) VALUES ($1,$2,$3)', [key, snapshot.commandHash, JSON.stringify(binding)]);
71
+ await client.query('COMMIT');
72
+ return { binding, replayed: false };
73
+ }
74
+ catch (error) {
75
+ await client.query('ROLLBACK').catch(() => undefined);
76
+ if (typeof error === 'object' && error !== null && 'code' in error && error.code === '23505' &&
77
+ 'constraint' in error && ['git_bindings_active_branch', 'git_bindings_active_artifact'].includes(String(error.constraint))) {
78
+ throw new ArtifactOperationError('git_binding_conflict', { publicDetails: { artifactId: binding.artifactId } });
79
+ }
80
+ throw error;
81
+ }
82
+ finally {
83
+ client.release();
84
+ }
85
+ },
86
+ };
87
+ }
88
+ const indexFields = ['releaseId', 'artifactId', 'repoId', 'branch', 'commitSha', 'treeSha', 'manifestDigest',
89
+ 'candidateDigest', 'executor', 'verification', 'receiptId', 'jobId', 'buildRunId', 'attempt', 'createdAt'];
90
+ function indexRow(row) {
91
+ return Object.fromEntries(indexFields.flatMap(key => {
92
+ const value = row[column(key)];
93
+ return value === null ? [] : [[key, value instanceof Date ? value.toISOString() : value]];
94
+ }));
95
+ }
96
+ /** Read-only SG1 port. SG4 writes both surfaces in the release transaction. */
97
+ export function createPostgresGitReleaseIndexStore(pool) {
98
+ return {
99
+ async get(scope, releaseId) {
100
+ const { rows } = await pool.query(`SELECT * FROM artifacts.git_release_index
101
+ WHERE storage_scope_id=$1 AND release_id=$2`, [scope, releaseId]);
102
+ return rows[0] ? indexRow(rows[0]) : undefined;
103
+ },
104
+ async forCommit(scope, artifactId, commitSha) {
105
+ const { rows } = await pool.query(`SELECT * FROM artifacts.git_release_index
106
+ WHERE storage_scope_id=$1 AND artifact_id=$2 AND commit_sha=$3 ORDER BY created_at,release_id`, [scope, artifactId, commitSha]);
107
+ return rows.map(indexRow);
108
+ },
109
+ };
110
+ }
@@ -0,0 +1,4 @@
1
+ import type { Pool } from 'pg';
2
+ import { type LiveStore } from '../server/live-store.js';
3
+ /** No import-time I/O. PostgreSQL owns lease serialization, private objects and replay durability. */
4
+ export declare function createPostgresLiveStore(pool: Pool): LiveStore;
@@ -0,0 +1,97 @@
1
+ import { ArtifactOperationError } from '../server/failures.js';
2
+ import { liveIdentityKey } from '../server/live-store.js';
3
+ /** No import-time I/O. PostgreSQL owns lease serialization, private objects and replay durability. */
4
+ export function createPostgresLiveStore(pool) {
5
+ return {
6
+ async sessionIdentity(scope, artifactId, sessionId) {
7
+ const result = await pool.query(`SELECT binding_generation FROM artifacts.live_drafts
8
+ WHERE storage_scope_id=$1 AND artifact_id=$2 AND record #>> '{runtime,liveSessionId}'=$3`, [scope, artifactId, sessionId]);
9
+ return result.rows[0] ? { storageScopeId: scope, artifactId, bindingGeneration: Number(result.rows[0].binding_generation) } : undefined;
10
+ },
11
+ async transaction(identity, action) {
12
+ const client = await pool.connect();
13
+ const values = [identity.storageScopeId, identity.artifactId, identity.bindingGeneration];
14
+ try {
15
+ await client.query('BEGIN');
16
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [JSON.stringify(['live', identity.storageScopeId, identity.artifactId])]);
17
+ const before = await client.query(`SELECT record FROM artifacts.live_drafts
18
+ WHERE storage_scope_id=$1 AND artifact_id=$2 AND binding_generation=$3 FOR UPDATE`, values);
19
+ const tx = {
20
+ record: before.rows[0]?.record,
21
+ async getObject(ref) {
22
+ const result = await client.query(`SELECT envelope FROM artifacts.live_draft_objects
23
+ WHERE storage_scope_id=$1 AND artifact_id=$2 AND binding_generation=$3 AND object_ref=$4`, [...values, ref]);
24
+ return result.rows[0]?.envelope;
25
+ },
26
+ async putObject(ref, envelope) {
27
+ await client.query(`INSERT INTO artifacts.live_draft_objects
28
+ (storage_scope_id,artifact_id,binding_generation,object_ref,envelope) VALUES ($1,$2,$3,$4,$5)`, [...values, ref, JSON.stringify(envelope)]);
29
+ },
30
+ async collectObjects() {
31
+ const result = await client.query(`DELETE FROM artifacts.live_draft_objects
32
+ WHERE storage_scope_id=$1 AND artifact_id=$2 AND binding_generation=$3
33
+ AND object_ref IS DISTINCT FROM $4::uuid`, [...values, tx.record?.objectRef ?? null]);
34
+ return result.rowCount ?? 0;
35
+ },
36
+ async receipt(actor, key) {
37
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [JSON.stringify(['live-command', identity.storageScopeId, actor, key])]);
38
+ const result = await client.query(`SELECT command_hash,result FROM artifacts.live_commands
39
+ WHERE storage_scope_id=$1 AND actor_id=$2 AND command_key=$3`, [identity.storageScopeId, actor, key]);
40
+ return result.rows[0] ? { hash: result.rows[0].command_hash, result: result.rows[0].result } : undefined;
41
+ },
42
+ async complete(command, result) {
43
+ await client.query(`INSERT INTO artifacts.live_commands(storage_scope_id,actor_id,command_key,command_hash,result)
44
+ VALUES ($1,$2,$3,$4,$5)`, [identity.storageScopeId, command.actorId, command.key, command.hash, JSON.stringify(result)]);
45
+ },
46
+ async reserveCommit(actor, invocation, now) {
47
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [JSON.stringify(['live-quota', identity.storageScopeId, actor])]);
48
+ const prior = await client.query(`SELECT 1 FROM artifacts.live_commit_quota
49
+ WHERE storage_scope_id=$1 AND actor_id=$2 AND invocation_id=$3`, [identity.storageScopeId, actor, invocation]);
50
+ if (prior.rows.length)
51
+ return;
52
+ const counts = await client.query(`SELECT count(*) FILTER (WHERE actor_id=$2)::int AS principal,
53
+ count(*) FILTER (WHERE artifact_id=$3)::int AS artifact FROM artifacts.live_commit_quota
54
+ WHERE storage_scope_id=$1 AND created_at > $4::timestamptz - interval '1 hour'`, [identity.storageScopeId, actor, identity.artifactId, now]);
55
+ if (counts.rows[0].principal >= 30 || counts.rows[0].artifact >= 60)
56
+ throw new ArtifactOperationError('limit_exceeded', { publicDetails: { quota: 'git_write', scope: counts.rows[0].principal >= 30 ? 'principal' : 'artifact' } });
57
+ await client.query(`INSERT INTO artifacts.live_commit_quota
58
+ (storage_scope_id,actor_id,artifact_id,invocation_id,created_at) VALUES ($1,$2,$3,$4,$5)`, [identity.storageScopeId, actor, identity.artifactId, invocation, now]);
59
+ },
60
+ async advanceBinding(input) {
61
+ const result = await client.query(`UPDATE artifacts.git_bindings SET head_commit_sha=$4,
62
+ state='attached', version=version+1, updated_at=$5
63
+ WHERE storage_scope_id=$1 AND artifact_id=$2 AND generation=$3 AND head_commit_sha=$6
64
+ AND state='attached' RETURNING artifact_id`, [...values, input.commitSha, input.now, input.expectedHeadSha]);
65
+ if (!result.rows.length)
66
+ throw new ArtifactOperationError('git_live_conflict', { publicDetails: { reason: 'stale_fence' } });
67
+ await client.query(`INSERT INTO artifacts.git_binding_events
68
+ (storage_scope_id,artifact_id,actor_id,action,before_sha,after_sha,invocation_id,created_at)
69
+ VALUES ($1,$2,$3,'commit',$4,$5,$6,$7)`, [identity.storageScopeId, identity.artifactId,
70
+ input.actorId, input.expectedHeadSha, input.commitSha, input.invocationId, input.now]);
71
+ },
72
+ };
73
+ const original = JSON.stringify(tx.record);
74
+ const result = await action(tx);
75
+ if (tx.record && JSON.stringify(tx.record) !== original) {
76
+ tx.record.rowVersion = (before.rows[0]?.record?.rowVersion ?? 0) + 1;
77
+ if (liveIdentityKey(tx.record) !== liveIdentityKey(identity))
78
+ throw new ArtifactOperationError('access_denied');
79
+ await client.query(`INSERT INTO artifacts.live_drafts(storage_scope_id,artifact_id,binding_generation,record)
80
+ VALUES ($1,$2,$3,$4) ON CONFLICT (storage_scope_id,artifact_id,binding_generation)
81
+ DO UPDATE SET record=EXCLUDED.record`, [...values, JSON.stringify(tx.record)]);
82
+ }
83
+ await client.query('COMMIT');
84
+ return result;
85
+ }
86
+ catch (cause) {
87
+ await client.query('ROLLBACK').catch(() => undefined);
88
+ if (cause instanceof ArtifactOperationError)
89
+ throw cause;
90
+ throw new ArtifactOperationError('git_live_draft_unavailable', { cause });
91
+ }
92
+ finally {
93
+ client.release();
94
+ }
95
+ }
96
+ };
97
+ }
@@ -35,4 +35,5 @@ export interface PostgresArtifactStore extends PostgresArtifactBasics, Publicati
35
35
  listRegisteredBlobs(storageScopeId: string): Promise<string[]>;
36
36
  }
37
37
  /** Create the Postgres-backed store over an injected pool (no DDL). */
38
+ export { createPostgresGitBindingStore, createPostgresGitReleaseIndexStore } from './postgres-git-bindings.js';
38
39
  export declare function createPostgresArtifactStore(pool: Pool): PostgresArtifactStore;
@@ -33,6 +33,7 @@ function toRelease(row) {
33
33
  };
34
34
  }
35
35
  /** Create the Postgres-backed store over an injected pool (no DDL). */
36
+ export { createPostgresGitBindingStore, createPostgresGitReleaseIndexStore } from './postgres-git-bindings.js';
36
37
  export function createPostgresArtifactStore(pool) {
37
38
  return {
38
39
  async ensureArtifact(input) {
@@ -4,6 +4,7 @@ import type { LifecycleService } from '../server/lifecycle.js';
4
4
  import { type SharingPolicyPort } from '../server/ports.js';
5
5
  import type { PublicationBlobStore, PublicationService } from '../server/publication.js';
6
6
  import { type GrantSigner, type TicketService } from './grants.js';
7
+ import { type ContentMode } from './headers.js';
7
8
  export interface ContentRequest {
8
9
  method: string;
9
10
  host: string;
@@ -14,6 +15,8 @@ export interface ContentRequest {
14
15
  ticket?: string;
15
16
  /** Raw HTTP Range header, mapped by the host; absent ⇒ whole file. */
16
17
  range?: string;
18
+ /** Raw HTTP Accept header, mapped by the host; absent ⇒ navigation fallback allowed. */
19
+ accept?: string;
17
20
  }
18
21
  export interface ContentResponse {
19
22
  status: number;
@@ -37,6 +40,10 @@ export interface ContentHandlerDeps {
37
40
  /** G1 lock 1 (deployment capability), absent ⇒ closed. */
38
41
  allowPublicSharing?: boolean;
39
42
  assetCacheSeconds?: number;
43
+ /** Host-configured mode (owner decision 05/11): `safe` default, `application` for real SPAs. */
44
+ contentMode?: ContentMode;
45
+ /** Per-release inline script hashes for the served HTML file, application mode only. */
46
+ getScriptHashes?: (filePath: string) => readonly string[] | undefined;
40
47
  }
41
48
  /** Create the content handler over injected host ports (no server). */
42
49
  export declare function createContentHandler(deps: ContentHandlerDeps): {