@sentropic/artifacts 0.2.17 → 0.2.20

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 (118) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +14 -0
  3. package/dist/adapters/github-forge.d.ts +4 -0
  4. package/dist/adapters/github-forge.js +88 -0
  5. package/dist/adapters/github-git-port.d.ts +5 -0
  6. package/dist/adapters/github-git-port.js +102 -0
  7. package/dist/adapters/github-http.d.ts +5 -0
  8. package/dist/adapters/github-http.js +57 -0
  9. package/dist/adapters/github-receive-pack.d.ts +4 -0
  10. package/dist/adapters/github-receive-pack.js +49 -0
  11. package/dist/adapters/postgres-git-bindings.d.ts +7 -0
  12. package/dist/adapters/postgres-git-bindings.js +131 -0
  13. package/dist/adapters/postgres-live.d.ts +4 -0
  14. package/dist/adapters/postgres-live.js +97 -0
  15. package/dist/adapters/postgres.d.ts +1 -0
  16. package/dist/adapters/postgres.js +1 -0
  17. package/dist/git-tool-definitions.d.ts +606 -0
  18. package/dist/git-tool-definitions.js +14 -0
  19. package/dist/http.d.ts +9 -0
  20. package/dist/http.js +31 -2
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.js +13 -0
  23. package/dist/live-host/accept.d.ts +30 -0
  24. package/dist/live-host/accept.js +43 -0
  25. package/dist/live-host/api.d.ts +67 -0
  26. package/dist/live-host/api.js +60 -0
  27. package/dist/live-host/candidate.d.ts +21 -0
  28. package/dist/live-host/candidate.js +41 -0
  29. package/dist/live-host/errors.d.ts +9 -0
  30. package/dist/live-host/errors.js +14 -0
  31. package/dist/live-host/handoff.d.ts +63 -0
  32. package/dist/live-host/handoff.js +66 -0
  33. package/dist/live-host/index.d.ts +10 -0
  34. package/dist/live-host/index.js +10 -0
  35. package/dist/live-host/keys.d.ts +14 -0
  36. package/dist/live-host/keys.js +8 -0
  37. package/dist/live-host/live-format.d.ts +70 -0
  38. package/dist/live-host/live-format.js +100 -0
  39. package/dist/live-host/recheck.d.ts +59 -0
  40. package/dist/live-host/recheck.js +45 -0
  41. package/dist/mcp-core.d.ts +3 -3
  42. package/dist/mcp-core.js +18 -2
  43. package/dist/profile/contracts.d.ts +1 -1
  44. package/dist/profile/contracts.js +4 -0
  45. package/dist/profile/index.js +8 -1
  46. package/dist/profile/schemas.js +19 -0
  47. package/dist/profile/validation.js +5 -1
  48. package/dist/server/build-contract.d.ts +64 -0
  49. package/dist/server/build-contract.js +58 -0
  50. package/dist/server/build-dependencies.d.ts +3 -0
  51. package/dist/server/build-dependencies.js +122 -0
  52. package/dist/server/consent-grant.d.ts +91 -0
  53. package/dist/server/consent-grant.js +89 -0
  54. package/dist/server/consent-screen.d.ts +21 -0
  55. package/dist/server/consent-screen.js +52 -0
  56. package/dist/server/failures.d.ts +3 -2
  57. package/dist/server/failures.js +30 -0
  58. package/dist/server/git-bindings.d.ts +10 -0
  59. package/dist/server/git-bindings.js +138 -0
  60. package/dist/server/git-contracts.d.ts +115 -0
  61. package/dist/server/git-contracts.js +1 -0
  62. package/dist/server/git-port-policy.d.ts +9 -0
  63. package/dist/server/git-port-policy.js +76 -0
  64. package/dist/server/git-port-read.d.ts +3 -0
  65. package/dist/server/git-port-read.js +95 -0
  66. package/dist/server/git-port-session.d.ts +38 -0
  67. package/dist/server/git-port-session.js +59 -0
  68. package/dist/server/git-port-tree.d.ts +8 -0
  69. package/dist/server/git-port-tree.js +92 -0
  70. package/dist/server/git-port-write.d.ts +6 -0
  71. package/dist/server/git-port-write.js +102 -0
  72. package/dist/server/git-port.d.ts +147 -0
  73. package/dist/server/git-port.js +8 -0
  74. package/dist/server/git-projection.d.ts +16 -0
  75. package/dist/server/git-projection.js +20 -0
  76. package/dist/server/git-registry.d.ts +37 -0
  77. package/dist/server/git-registry.js +39 -0
  78. package/dist/server/git-tools-attach.d.ts +8 -0
  79. package/dist/server/git-tools-attach.js +139 -0
  80. package/dist/server/git-tools-contracts.d.ts +59 -0
  81. package/dist/server/git-tools-contracts.js +1 -0
  82. package/dist/server/git-tools-fetch.d.ts +21 -0
  83. package/dist/server/git-tools-fetch.js +65 -0
  84. package/dist/server/git-tools-publish.d.ts +13 -0
  85. package/dist/server/git-tools-publish.js +66 -0
  86. package/dist/server/git-tools.d.ts +4 -0
  87. package/dist/server/git-tools.js +18 -0
  88. package/dist/server/live-body.d.ts +3 -0
  89. package/dist/server/live-body.js +28 -0
  90. package/dist/server/live-commit-outcome.d.ts +6 -0
  91. package/dist/server/live-commit-outcome.js +10 -0
  92. package/dist/server/live-commit.d.ts +11 -0
  93. package/dist/server/live-commit.js +133 -0
  94. package/dist/server/live-contracts.d.ts +62 -0
  95. package/dist/server/live-contracts.js +8 -0
  96. package/dist/server/live-crypto.d.ts +14 -0
  97. package/dist/server/live-crypto.js +50 -0
  98. package/dist/server/live-drafts.d.ts +61 -0
  99. package/dist/server/live-drafts.js +119 -0
  100. package/dist/server/live-errors.d.ts +23 -0
  101. package/dist/server/live-errors.js +9 -0
  102. package/dist/server/live-mutations.d.ts +18 -0
  103. package/dist/server/live-mutations.js +83 -0
  104. package/dist/server/live-read.d.ts +15 -0
  105. package/dist/server/live-read.js +95 -0
  106. package/dist/server/live-service.d.ts +3 -0
  107. package/dist/server/live-service.js +181 -0
  108. package/dist/server/live-store.d.ts +111 -0
  109. package/dist/server/live-store.js +80 -0
  110. package/dist/server/live-tree.d.ts +22 -0
  111. package/dist/server/live-tree.js +148 -0
  112. package/dist/server/live-worker.d.ts +10 -0
  113. package/dist/server/live-worker.js +55 -0
  114. package/dist/server/templates.js +26 -1
  115. package/migrations/0010_git_bindings.sql +82 -0
  116. package/migrations/0011_live_drafts.sql +42 -0
  117. package/migrations/0012_git_attach_intents.sql +19 -0
  118. package/package.json +17 -1
@@ -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>;
@@ -0,0 +1,39 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ /** Host-only registry. No enrollment/credential material is accepted by any tool. */
3
+ export function createGitRepositoryRegistry(entries) {
4
+ const records = new Map();
5
+ for (const input of entries) {
6
+ const policy = input.publicationPolicy;
7
+ const record = structuredClone({ ...input, canWrite: input.canWrite ?? false,
8
+ writablePaths: input.writablePaths ?? [], refusedWritePaths: input.refusedWritePaths ?? [],
9
+ publicationPolicy: { personalBranchPrefix: 'artifact/p/', sharedPublishers: [],
10
+ ...policy, delegatedPublication: policy?.delegatedPublication ?? 'none' } });
11
+ const key = JSON.stringify([record.storageScopeId, record.repoId]);
12
+ if (!record.repoId || !record.storageScopeId || record.branchPrefix !== 'artifact/' ||
13
+ record.publicationPolicy.personalBranchPrefix !== 'artifact/p/' ||
14
+ !['none', 'personal-only', 'designated-shared'].includes(record.publicationPolicy.delegatedPublication) ||
15
+ records.has(key))
16
+ throw new ArtifactOperationError('invalid_request');
17
+ records.set(key, record);
18
+ }
19
+ return { async get(scope, repoId) {
20
+ const record = records.get(JSON.stringify([scope, repoId]));
21
+ return record === undefined ? undefined : structuredClone(record);
22
+ } };
23
+ }
24
+ /** Git ref grammar, restricted to the host namespace; accepts branch names, never refs/heads aliases. */
25
+ export function isAllowedGitBranch(branch) {
26
+ return branch.startsWith('artifact/') && !/[\x00-\x20\x7f~^:?*\[\\]/.test(branch) &&
27
+ !branch.includes('..') && !branch.includes('@{') && !branch.endsWith('.') &&
28
+ branch.split('/').every(part => part.length > 0 && !part.startsWith('.') && !part.endsWith('.lock'));
29
+ }
30
+ export async function validateGitBindingTarget(registry, scope, repoId, branch, subPath) {
31
+ const record = await registry.get(scope, repoId);
32
+ if (!record || record.storageScopeId !== scope)
33
+ throw new ArtifactOperationError('git_repo_not_registered');
34
+ if (!record.canWrite || !isAllowedGitBranch(branch) || !record.allowedSubPaths.includes(subPath) ||
35
+ (subPath !== '' && subPath.split('/').some(part => !part || part === '.' || part === '..')) ||
36
+ subPath.includes('\\') || subPath.includes('\0'))
37
+ throw new ArtifactOperationError('git_ref_not_allowed');
38
+ return record;
39
+ }
@@ -0,0 +1,8 @@
1
+ import type { GitBinding } from './git-contracts.js';
2
+ import type { GitToolInvocation, GitToolsDeps } from './git-tools-contracts.js';
3
+ /** G0 v3 §1.2 Tool 3 / A-LIVE S03: attach, configure, pause, resume or detach one binding. */
4
+ export declare function attachGit(deps: GitToolsDeps, args: Record<string, any>, inv: GitToolInvocation): Promise<{
5
+ artifactId: any;
6
+ git: GitBinding;
7
+ replayed: boolean;
8
+ }>;
@@ -0,0 +1,139 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { orderedDigest } from '../profile/json.js';
3
+ import { ArtifactOperationError } from './failures.js';
4
+ import { validateGitBindingTarget } from './git-registry.js';
5
+ import { requireCodeRight, requireOwner } from './git-tools-publish.js';
6
+ const FIELDS = ['repoId', 'branch', 'baseRef', 'subPath', 'autoPublish', 'executor', 'pause'];
7
+ const id8 = (value) => createHash('sha256').update(value).digest('hex').slice(0, 8);
8
+ const notFound = (error) => error instanceof ArtifactOperationError && error.kind === 'not_found';
9
+ /** G0 v3 §1.2 Tool 3 / A-LIVE S03: attach, configure, pause, resume or detach one binding. */
10
+ export async function attachGit(deps, args, inv) {
11
+ await requireOwner(deps, inv, args.artifactId, true);
12
+ const scope = inv.storageScopeId;
13
+ const before = await deps.bindings.get(scope, args.artifactId);
14
+ const active = before !== undefined && before.state !== 'detached';
15
+ const given = FIELDS.filter(field => args[field] !== undefined);
16
+ const now = (deps.now?.() ?? new Date()).toISOString();
17
+ const hash = orderedDigest({ operation: 'git_attach', args });
18
+ const write = async (binding, action, afterSha, branchCreated = false) => {
19
+ const out = await deps.bindings.write({ binding, expectedVersion: before?.version ?? null, actorId: inv.actorId,
20
+ idempotencyKey: args.idempotencyKey, commandHash: hash,
21
+ event: { action, beforeSha: before?.headCommitSha ?? undefined, afterSha, invocationId: inv.invocationId,
22
+ ...(branchCreated ? { branchCreated: true } : {}) } });
23
+ return { artifactId: args.artifactId, git: out.binding, replayed: out.replayed };
24
+ };
25
+ const base = before && { ...before, version: before.version + 1, updatedAt: now };
26
+ if (args.detach !== undefined) {
27
+ if (args.detach !== true || given.length)
28
+ throw new ArtifactOperationError('invalid_request');
29
+ if (!active)
30
+ throw new ArtifactOperationError('git_not_attached');
31
+ await requireCodeRight(deps, inv, before.repoId);
32
+ return write({ ...base, state: 'detached', generation: before.generation + 1,
33
+ pendingJobId: null, pendingCommitSha: null }, 'detach');
34
+ }
35
+ if (args.pause !== undefined) {
36
+ if (given.length !== 1)
37
+ throw new ArtifactOperationError('invalid_request');
38
+ if (!active)
39
+ throw new ArtifactOperationError('git_not_attached');
40
+ await requireCodeRight(deps, inv, before.repoId);
41
+ if (args.pause)
42
+ return write({ ...base, state: 'paused', generation: before.generation + 1,
43
+ pendingJobId: null, pendingCommitSha: null }, 'pause');
44
+ const target = await attachTarget(deps, before, inv);
45
+ await deps.git.resolveRef(target, before.branch).catch(error => {
46
+ throw notFound(error) ? new ArtifactOperationError('git_branch_missing') : error;
47
+ });
48
+ return write({ ...base, state: 'attached' }, 'resume');
49
+ }
50
+ const repoId = active ? before.repoId : args.repoId;
51
+ if (repoId === undefined)
52
+ throw new ArtifactOperationError('invalid_request');
53
+ await requireCodeRight(deps, inv, repoId);
54
+ const executor = args.executor ?? (active ? before.executor : 'caller');
55
+ await admitExecutor(deps, executor);
56
+ if (active) {
57
+ if ((args.repoId ?? before.repoId) !== before.repoId || (args.branch ?? before.branch) !== before.branch ||
58
+ (args.subPath ?? before.subPath) !== before.subPath || executor !== before.executor) {
59
+ throw new ArtifactOperationError('git_binding_conflict', { publicDetails: { artifactId: args.artifactId } });
60
+ }
61
+ const autoPublish = args.autoPublish ?? before.autoPublish;
62
+ if (autoPublish && !before.autoPublish)
63
+ await assertAutoPublish(deps, before.repoId, before.branch, before.channel, inv);
64
+ return write({ ...base, autoPublish }, 'attach', before.headCommitSha ?? undefined);
65
+ }
66
+ const principal = id8(`${scope}\0${inv.actorId}`);
67
+ const branch = args.branch ?? `artifact/p/${principal}/app-${id8(args.artifactId)}`;
68
+ const subPath = args.subPath ?? '';
69
+ const repo = await validateGitBindingTarget(deps.registry, scope, repoId, branch, subPath);
70
+ const personal = branch.startsWith('artifact/p/');
71
+ if (personal && !branch.startsWith(`artifact/p/${principal}/`))
72
+ throw new ArtifactOperationError('git_ref_not_allowed');
73
+ const channel = personal ? 'personal' : 'shared';
74
+ if (args.autoPublish === true)
75
+ await assertAutoPublish(deps, repoId, branch, channel, inv);
76
+ const target = { storageScopeId: scope, repoId, branch, subPath,
77
+ principalId: inv.actorId, outputDir: deps.outputDir ?? 'dist' };
78
+ const { head, created } = await attachHead(deps, target, args, inv, hash, now);
79
+ if (args.autoPublish === true && !created) {
80
+ throw new ArtifactOperationError('git_auto_publish_refused', { publicDetails: { reason: 'initial_pre_existing_branch' } });
81
+ }
82
+ const defaulted = created && channel === 'personal' && repo.publicationPolicy.delegatedPublication === 'personal-only';
83
+ const binding = { artifactId: args.artifactId, storageScopeId: scope, repoId, branch,
84
+ channel, personalPrincipalId: personal ? inv.actorId : null, subPath, baseCommitSha: head, headCommitSha: head,
85
+ releaseCommitSha: before?.releaseCommitSha ?? null, autoPublish: args.autoPublish ?? defaulted, executor,
86
+ pendingJobId: null, pendingCommitSha: null, state: 'attached', generation: before ? before.generation + 1 : 1,
87
+ version: before ? before.version + 1 : 1, attachedBy: inv.actorId, attachedAt: now, updatedAt: now };
88
+ return write(binding, 'attach', head, created);
89
+ }
90
+ /**
91
+ * A-LIVE v2 §5.3.1: « created by this command » is the durable intent written before createBranch, never a forge
92
+ * guess. A same-key retry after a lost binding write keeps the outcome; a moved head or a foreign branch does not.
93
+ */
94
+ async function attachHead(deps, target, args, inv, hash, now) {
95
+ const current = await deps.git.resolveRef(target, target.branch).catch(error => {
96
+ if (notFound(error))
97
+ return undefined;
98
+ throw error;
99
+ });
100
+ const prior = await deps.bindings.attachIntent(inv.storageScopeId, inv.actorId, args.idempotencyKey);
101
+ if (prior && prior.commandHash !== hash)
102
+ throw new ArtifactOperationError('command_conflict');
103
+ if (current !== undefined)
104
+ return { head: current, created: prior?.baseCommitSha === current };
105
+ if (args.baseRef === undefined)
106
+ throw new ArtifactOperationError('git_branch_missing');
107
+ const intent = prior ?? await deps.bindings.reserveAttachIntent({ storageScopeId: inv.storageScopeId,
108
+ artifactId: args.artifactId, actorId: inv.actorId, idempotencyKey: args.idempotencyKey, commandHash: hash,
109
+ repoId: target.repoId, branch: target.branch, baseCommitSha: await deps.git.resolveRef(target, args.baseRef),
110
+ createdAt: now });
111
+ if (intent.commandHash !== hash)
112
+ throw new ArtifactOperationError('command_conflict');
113
+ await deps.git.createBranch(target, intent.baseCommitSha);
114
+ return { head: intent.baseCommitSha, created: true };
115
+ }
116
+ /** G0 v3 §1.2 / A-LIVE S03: the host build port admits every executor, the omitted caller default included. */
117
+ async function admitExecutor(deps, executor) {
118
+ const open = executor !== 'ci' && (deps.build
119
+ ? await deps.build.admits(executor).then(value => value === true, () => false) : executor === 'caller');
120
+ if (!open)
121
+ throw new ArtifactOperationError('builder_unavailable', { publicDetails: { executor,
122
+ reason: executor === 'ci' ? 'executor_retired' : 'executor_unavailable' } });
123
+ }
124
+ async function attachTarget(deps, binding, inv) {
125
+ await validateGitBindingTarget(deps.registry, binding.storageScopeId, binding.repoId, binding.branch, binding.subPath);
126
+ return { storageScopeId: binding.storageScopeId, repoId: binding.repoId, branch: binding.branch,
127
+ subPath: binding.subPath, principalId: inv.actorId, outputDir: deps.outputDir ?? 'dist' };
128
+ }
129
+ /** OD2 (G0 v3 §1.2): delegated publication is host policy, never a caller claim. */
130
+ async function assertAutoPublish(deps, repoId, branch, channel, inv) {
131
+ const repo = await deps.registry.get(inv.storageScopeId, repoId);
132
+ const policy = repo?.publicationPolicy;
133
+ const designated = policy?.sharedPublishers.some(entry => entry.branch === branch &&
134
+ entry.principalIds.includes(inv.actorId));
135
+ const ok = policy?.delegatedPublication === 'personal-only' ? channel === 'personal'
136
+ : policy?.delegatedPublication === 'designated-shared' ? channel === 'personal' || designated === true : false;
137
+ if (!ok)
138
+ throw new ArtifactOperationError('git_auto_publish_refused', { publicDetails: { reason: 'delegation_policy' } });
139
+ }
@@ -0,0 +1,59 @@
1
+ import type { GitBindingStore, GitCodeRightsPort } from './git-contracts.js';
2
+ import type { GitRepositoryRegistry } from './git-registry.js';
3
+ import type { GitPort } from './git-port.js';
4
+ export interface GitToolInvocation {
5
+ actorId: string;
6
+ storageScopeId: string;
7
+ invocationId: string;
8
+ }
9
+ /** Server-resolved artifact authority; never a tool argument. G0 v3 §1.4: owner + host write scope. */
10
+ export interface GitToolAuthority {
11
+ ownerId: string;
12
+ canWrite: boolean;
13
+ }
14
+ export type GitBuildJobState = 'build_pending' | 'building' | 'published' | 'build_failed' | 'cancelled';
15
+ /** G0 v3 §2.6: the persisted job identity; the release CAS and the SHA are never caller-editable later. */
16
+ export interface GitBuildJobRequest {
17
+ storageScopeId: string;
18
+ artifactId: string;
19
+ repoId: string;
20
+ branch: string;
21
+ subPath: string;
22
+ commitSha: string;
23
+ bindingGeneration: number;
24
+ expectedCurrentReleaseId: string | null;
25
+ executor: 'caller' | 'ci' | 'sandbox';
26
+ requestedBy: string;
27
+ idempotencyKey: string;
28
+ }
29
+ /** Build executor port: persists the job before returning its id; the same principal key returns the same job. */
30
+ export interface GitBuildPort {
31
+ /** Executor gate (G0 v3 §3.3, A-LIVE S03): false closes the executor with builder_unavailable. */
32
+ admits(executor: 'caller' | 'ci' | 'sandbox'): Promise<boolean>;
33
+ request(job: GitBuildJobRequest): Promise<{
34
+ jobId: string;
35
+ state: GitBuildJobState;
36
+ }>;
37
+ }
38
+ export interface GitToolsDeps {
39
+ bindings: GitBindingStore;
40
+ registry: GitRepositoryRegistry;
41
+ codeRights: GitCodeRightsPort;
42
+ git: GitPort;
43
+ authorize(invocation: GitToolInvocation, artifactId: string): Promise<GitToolAuthority>;
44
+ /** Absent ⇒ git_publish fails closed with provider_unavailable (503 capability_unavailable). */
45
+ build?: GitBuildPort;
46
+ /** Descriptor output subtree resolved by the host; excluded from writes. */
47
+ outputDir?: string;
48
+ /** Journal of every source read: repoId + resolved SHA (G0 v3 §1.4). */
49
+ journal?: (entry: {
50
+ actorId: string;
51
+ repoId: string;
52
+ commitSha: string;
53
+ invocationId: string;
54
+ }) => void | Promise<void>;
55
+ now?: () => Date;
56
+ }
57
+ export interface GitToolService {
58
+ execute(operation: string, args: Record<string, unknown>, invocation: GitToolInvocation): Promise<Record<string, any>>;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { GitToolInvocation, GitToolsDeps } from './git-tools-contracts.js';
2
+ /** G0 v3 §1.4 fetch_app_source: code right on the resolved repo; the cursor pins the commit across pages. */
3
+ export declare function fetchAppSource(deps: GitToolsDeps, args: Record<string, any>, inv: GitToolInvocation): Promise<{
4
+ repoId: string;
5
+ commitSha: string;
6
+ treeSha: string;
7
+ descriptor: unknown;
8
+ files: ({
9
+ path: string;
10
+ text: string;
11
+ encoding: "utf-8";
12
+ } | {
13
+ path: string;
14
+ base64: string;
15
+ encoding: "base64";
16
+ } | {
17
+ path: string;
18
+ omitted: "too_large" | "over_total_budget";
19
+ })[];
20
+ nextCursor: string | null;
21
+ }>;
@@ -0,0 +1,65 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { assertGitReadRef, assertGitSha } from './git-port-policy.js';
3
+ import { requireCodeRight } from './git-tools-publish.js';
4
+ const missing = (error) => error instanceof ArtifactOperationError &&
5
+ ['not_found', 'git_path_refused'].includes(error.kind);
6
+ function decodeCursor(cursor) {
7
+ if (cursor === undefined)
8
+ return {};
9
+ try {
10
+ const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
11
+ if (typeof value?.s !== 'string' || typeof value.c !== 'string')
12
+ throw new Error();
13
+ assertGitSha(value.s);
14
+ return { sha: value.s, port: value.c };
15
+ }
16
+ catch {
17
+ throw new ArtifactOperationError('invalid_request');
18
+ }
19
+ }
20
+ /** G0 v3 §1.4 fetch_app_source: code right on the resolved repo; the cursor pins the commit across pages. */
21
+ export async function fetchAppSource(deps, args, inv) {
22
+ const cursor = decodeCursor(args.cursor);
23
+ const scope = inv.storageScopeId;
24
+ const binding = args.artifactId === undefined ? undefined : await deps.bindings.get(scope, args.artifactId);
25
+ if (args.artifactId !== undefined && binding && args.repoId !== undefined && args.repoId !== binding.repoId) {
26
+ throw new ArtifactOperationError('invalid_request');
27
+ }
28
+ const repoId = binding?.repoId ?? args.repoId;
29
+ if (repoId === undefined)
30
+ throw new ArtifactOperationError('git_not_attached');
31
+ await requireCodeRight(deps, inv, repoId);
32
+ if (args.artifactId !== undefined && (!binding || binding.state === 'detached')) {
33
+ throw new ArtifactOperationError('git_not_attached');
34
+ }
35
+ const repo = await deps.registry.get(scope, repoId);
36
+ if (!repo)
37
+ throw new ArtifactOperationError('git_repo_not_registered');
38
+ const branch = binding?.branch ?? args.ref;
39
+ if (branch === undefined)
40
+ throw new ArtifactOperationError('invalid_request');
41
+ assertGitReadRef(branch);
42
+ const target = { storageScopeId: scope, repoId, branch, principalId: inv.actorId,
43
+ subPath: binding?.subPath ?? (repo.allowedSubPaths.includes('') ? '' : repo.allowedSubPaths[0] ?? ''),
44
+ outputDir: deps.outputDir ?? 'dist' };
45
+ const commitSha = cursor.sha ?? await deps.git.resolveRef(target, branch);
46
+ assertGitSha(commitSha);
47
+ const page = await deps.git.read(target, { commitSha, ...(args.paths ? { paths: args.paths } : {}),
48
+ ...(cursor.port === undefined ? {} : { cursor: cursor.port }) });
49
+ await deps.journal?.({ actorId: inv.actorId, repoId, commitSha: page.commitSha, invocationId: inv.invocationId });
50
+ let descriptor = null;
51
+ try {
52
+ const file = (await deps.git.read(target, { commitSha, paths: ['sentropic.artifact.json'] })).files[0];
53
+ const parsed = file && 'text' in file ? JSON.parse(file.text) : null;
54
+ if (parsed?.version === 1 && typeof parsed.buildScript === 'string' && typeof parsed.outputDir === 'string' &&
55
+ typeof parsed.lockfilePath === 'string')
56
+ descriptor = parsed;
57
+ }
58
+ catch (error) {
59
+ if (!missing(error) && !(error instanceof SyntaxError))
60
+ throw error;
61
+ }
62
+ return { repoId, commitSha: page.commitSha, treeSha: page.treeSha, descriptor, files: page.files,
63
+ nextCursor: page.nextCursor === null ? null :
64
+ Buffer.from(JSON.stringify({ s: page.commitSha, c: page.nextCursor })).toString('base64url') };
65
+ }
@@ -0,0 +1,13 @@
1
+ import type { GitToolInvocation, GitToolsDeps } from './git-tools-contracts.js';
2
+ /** Owner + host write scope + current code right; refusals carry no git detail. */
3
+ export declare function requireOwner(deps: GitToolsDeps, inv: GitToolInvocation, artifactId: string, write: boolean): Promise<void>;
4
+ /** Current repository code right (G0 v3 §1.4); a port failure is a denial. Runs before any registry or forge call. */
5
+ export declare function requireCodeRight(deps: GitToolsDeps, inv: GitToolInvocation, repoId: string): Promise<void>;
6
+ /** G0 v3 §2.6 git_publish: pin one reachable SHA, persist the build job, move the binding to build_pending. */
7
+ export declare function publishGit(deps: GitToolsDeps, args: Record<string, any>, inv: GitToolInvocation): Promise<{
8
+ artifactId: any;
9
+ jobId: string | null;
10
+ state: string;
11
+ commitSha: any;
12
+ replayed: boolean;
13
+ }>;
@@ -0,0 +1,66 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { assertGitSha } from './git-port-policy.js';
3
+ import { orderedDigest } from '../profile/json.js';
4
+ /** Owner + host write scope + current code right; refusals carry no git detail. */
5
+ export async function requireOwner(deps, inv, artifactId, write) {
6
+ const authority = await deps.authorize(inv, artifactId);
7
+ if (authority.ownerId !== inv.actorId || (write && !authority.canWrite))
8
+ throw new ArtifactOperationError('access_denied');
9
+ }
10
+ /** Current repository code right (G0 v3 §1.4); a port failure is a denial. Runs before any registry or forge call. */
11
+ export async function requireCodeRight(deps, inv, repoId) {
12
+ const allowed = await deps.codeRights.canReadCode({ storageScopeId: inv.storageScopeId, repoId, actorId: inv.actorId })
13
+ .then(value => value === true, () => false);
14
+ if (!allowed)
15
+ throw new ArtifactOperationError('access_denied');
16
+ }
17
+ /** G0 v3 §2.6 git_publish: pin one reachable SHA, persist the build job, move the binding to build_pending. */
18
+ export async function publishGit(deps, args, inv) {
19
+ await requireOwner(deps, inv, args.artifactId, true);
20
+ assertGitSha(args.commitSha);
21
+ const scope = inv.storageScopeId;
22
+ const binding = await deps.bindings.get(scope, args.artifactId);
23
+ if (!binding || binding.state === 'detached')
24
+ throw new ArtifactOperationError('git_not_attached');
25
+ await requireCodeRight(deps, inv, binding.repoId);
26
+ if (binding.state === 'paused')
27
+ throw new ArtifactOperationError('git_binding_paused', { publicDetails: { state: 'paused' } });
28
+ if (binding.state === 'diverged')
29
+ throw new ArtifactOperationError('git_diverged', {
30
+ publicDetails: { headCommitSha: binding.headCommitSha, releaseCommitSha: binding.releaseCommitSha }
31
+ });
32
+ if (binding.state === 'build_pending' && binding.pendingCommitSha === args.commitSha) {
33
+ return { artifactId: args.artifactId, jobId: binding.pendingJobId, state: 'build_pending', commitSha: args.commitSha, replayed: true };
34
+ }
35
+ if (!['attached', 'build_failed'].includes(binding.state)) {
36
+ throw new ArtifactOperationError('git_binding_conflict', { publicDetails: { artifactId: args.artifactId } });
37
+ }
38
+ const build = deps.build;
39
+ if (!build)
40
+ throw new ArtifactOperationError('provider_unavailable');
41
+ if (!await build.admits(binding.executor))
42
+ throw new ArtifactOperationError('builder_unavailable', {
43
+ publicDetails: { executor: binding.executor, reason: 'executor_unavailable' }
44
+ });
45
+ const target = { storageScopeId: scope, repoId: binding.repoId, branch: binding.branch,
46
+ subPath: binding.subPath, principalId: inv.actorId, outputDir: deps.outputDir ?? 'dist' };
47
+ const head = await deps.git.resolveRef(target, binding.branch);
48
+ if (head !== args.commitSha && !await deps.git.isAncestor(target, args.commitSha, head)) {
49
+ throw new ArtifactOperationError('git_sha_not_on_branch', { publicDetails: { commitSha: args.commitSha } });
50
+ }
51
+ const job = await build.request({ storageScopeId: scope, artifactId: args.artifactId, repoId: binding.repoId,
52
+ branch: binding.branch, subPath: binding.subPath, commitSha: args.commitSha, bindingGeneration: binding.generation,
53
+ expectedCurrentReleaseId: args.expectedCurrentReleaseId, executor: binding.executor, requestedBy: inv.actorId,
54
+ idempotencyKey: args.idempotencyKey });
55
+ const now = (deps.now?.() ?? new Date()).toISOString();
56
+ const out = await deps.bindings.write({
57
+ binding: { ...binding, state: 'build_pending', headCommitSha: head, pendingJobId: job.jobId,
58
+ pendingCommitSha: args.commitSha, version: binding.version + 1, updatedAt: now },
59
+ expectedVersion: binding.version, actorId: inv.actorId, idempotencyKey: args.idempotencyKey,
60
+ commandHash: orderedDigest({ operation: 'git_publish', args }),
61
+ event: { action: 'publish', beforeSha: binding.releaseCommitSha ?? undefined, afterSha: args.commitSha,
62
+ invocationId: inv.invocationId }
63
+ });
64
+ return { artifactId: args.artifactId, jobId: out.binding.pendingJobId ?? job.jobId, state: out.binding.state,
65
+ commitSha: args.commitSha, replayed: out.replayed };
66
+ }
@@ -0,0 +1,4 @@
1
+ import type { GitToolService, GitToolsDeps } from './git-tools-contracts.js';
2
+ export type * from './git-tools-contracts.js';
3
+ /** SG3 executors for the three tools routed by createHttpArtifactApp; every port is injected by the host. */
4
+ export declare function createGitToolService(deps: GitToolsDeps): GitToolService;