@sentropic/artifacts 0.2.18 → 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 (43) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +14 -0
  3. package/dist/adapters/postgres-git-bindings.js +25 -4
  4. package/dist/http.d.ts +3 -0
  5. package/dist/http.js +12 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/live-host/accept.d.ts +30 -0
  9. package/dist/live-host/accept.js +43 -0
  10. package/dist/live-host/api.d.ts +67 -0
  11. package/dist/live-host/api.js +60 -0
  12. package/dist/live-host/candidate.d.ts +21 -0
  13. package/dist/live-host/candidate.js +41 -0
  14. package/dist/live-host/errors.d.ts +9 -0
  15. package/dist/live-host/errors.js +14 -0
  16. package/dist/live-host/handoff.d.ts +63 -0
  17. package/dist/live-host/handoff.js +66 -0
  18. package/dist/live-host/index.d.ts +10 -0
  19. package/dist/live-host/index.js +10 -0
  20. package/dist/live-host/keys.d.ts +14 -0
  21. package/dist/live-host/keys.js +8 -0
  22. package/dist/live-host/live-format.d.ts +70 -0
  23. package/dist/live-host/live-format.js +100 -0
  24. package/dist/live-host/recheck.d.ts +59 -0
  25. package/dist/live-host/recheck.js +45 -0
  26. package/dist/mcp-core.d.ts +1 -1
  27. package/dist/mcp-core.js +4 -1
  28. package/dist/server/git-bindings.d.ts +3 -1
  29. package/dist/server/git-bindings.js +26 -1
  30. package/dist/server/git-contracts.d.ts +18 -1
  31. package/dist/server/git-tools-attach.d.ts +8 -0
  32. package/dist/server/git-tools-attach.js +139 -0
  33. package/dist/server/git-tools-contracts.d.ts +59 -0
  34. package/dist/server/git-tools-contracts.js +1 -0
  35. package/dist/server/git-tools-fetch.d.ts +21 -0
  36. package/dist/server/git-tools-fetch.js +65 -0
  37. package/dist/server/git-tools-publish.d.ts +13 -0
  38. package/dist/server/git-tools-publish.js +66 -0
  39. package/dist/server/git-tools.d.ts +4 -0
  40. package/dist/server/git-tools.js +18 -0
  41. package/dist/server/templates.js +26 -1
  42. package/migrations/0012_git_attach_intents.sql +19 -0
  43. package/package.json +5 -1
@@ -0,0 +1,14 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import type { KeyObject } from 'node:crypto';
3
+ /** Key id carried in every signed live-host message, so a verifier accepts old and new keys during a rotation overlap. */
4
+ export declare const LIVE_KEY_ID: RegExp;
5
+ export declare const liveKeyId: (kid: unknown) => kid is string;
6
+ /** Current signing key and its id. */
7
+ export interface SigningKey {
8
+ readonly kid: string;
9
+ readonly key: KeyObject;
10
+ }
11
+ /** Verifier key set: returns the public key of a known id, undefined otherwise. */
12
+ export type KeyResolver = (kid: string) => KeyObject | undefined;
13
+ export declare const ed25519: (key: KeyObject | undefined, type: 'private' | 'public') => key is KeyObject;
14
+ export declare function assertSigner(signer: SigningKey): void;
@@ -0,0 +1,8 @@
1
+ /** Key id carried in every signed live-host message, so a verifier accepts old and new keys during a rotation overlap. */
2
+ export const LIVE_KEY_ID = /^[A-Za-z0-9._:-]{1,128}$/;
3
+ export const liveKeyId = (kid) => typeof kid === 'string' && LIVE_KEY_ID.test(kid);
4
+ export const ed25519 = (key, type) => !!key && key.asymmetricKeyType === 'ed25519' && (key.type === type || (type === 'public' && key.type === 'private'));
5
+ export function assertSigner(signer) {
6
+ if (!signer || !liveKeyId(signer.kid) || !ed25519(signer.key, 'private'))
7
+ throw new TypeError('Signer must be an Ed25519 private key with a valid kid');
8
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * A-LIVE §8.2 live edge wire format (W9 / M4-E), pure and dependency-free so the host (immo), the controller
3
+ * (Sentropic API) and `artifact-content` sign and verify with the same code. Three HMAC-SHA256 message kinds, each
4
+ * with its own MAC-bound prefix so none can be replayed as another:
5
+ * - `v1` host assertion (immo → artifact-content), on every live request and websocket upgrade;
6
+ * - `c1` host control (immo → artifact-content): session or invitation revocation;
7
+ * - `f1` controller fence (Sentropic API → artifact-content): generation and route-epoch floor.
8
+ */
9
+ export declare const ASSERTION_HEADER = "x-live-host-assertion";
10
+ export declare const CONTROL_HEADER = "x-live-host-control";
11
+ export declare const FENCE_HEADER = "x-live-controller-fence";
12
+ export declare const MIN_KEY_BYTES = 32;
13
+ export declare const MAX_ASSERTION_SECONDS = 3600;
14
+ export declare const MAX_CONTROL_SECONDS = 300;
15
+ export declare const MAX_SKEW_SECONDS = 30;
16
+ /** The live source revision is an opaque string (A-LIVE live revisions), compared, never parsed. */
17
+ export declare const MAX_SOURCE_REVISION_LENGTH = 256;
18
+ export interface LiveAssertionClaims {
19
+ v: 1;
20
+ kid: string;
21
+ host: string;
22
+ artifactId: string;
23
+ storageScopeId: string;
24
+ sessionId: string;
25
+ generation: number;
26
+ routeEpoch: number;
27
+ podUid: string;
28
+ podName: string;
29
+ sourceRevision: string;
30
+ principalId: string;
31
+ role: 'binding_owner' | 'invitee';
32
+ invitationId: string;
33
+ invitationEpoch: number;
34
+ invitationExp: number;
35
+ iat: number;
36
+ exp: number;
37
+ }
38
+ /** Host revocation; `epoch` is the invitation's new floor: every assertion below it is refused. */
39
+ export interface LiveControlClaims {
40
+ v: 1;
41
+ kid: string;
42
+ host: string;
43
+ artifactId: string;
44
+ op: 'revoke_session' | 'revoke_invitation';
45
+ sessionId: string;
46
+ invitationId: string;
47
+ epoch: number;
48
+ iat: number;
49
+ exp: number;
50
+ }
51
+ /** Controller fence: routes below this generation, or below this route epoch within it, are refused. */
52
+ export interface LiveFenceClaims {
53
+ v: 1;
54
+ kid: string;
55
+ artifactId: string;
56
+ generation: number;
57
+ routeEpoch: number;
58
+ iat: number;
59
+ exp: number;
60
+ }
61
+ export interface VerifyOptions {
62
+ key(kid: string): Uint8Array | undefined;
63
+ now(): number;
64
+ }
65
+ export declare function signLiveAssertion(claims: LiveAssertionClaims, key: Uint8Array): string;
66
+ export declare const signLiveControl: (claims: LiveControlClaims, key: Uint8Array) => string;
67
+ export declare const signLiveFence: (claims: LiveFenceClaims, key: Uint8Array) => string;
68
+ export declare function verifyLiveAssertion(token: string, options: VerifyOptions): LiveAssertionClaims | undefined;
69
+ export declare function verifyLiveControl(token: string, options: VerifyOptions): LiveControlClaims | undefined;
70
+ export declare function verifyLiveFence(token: string, options: VerifyOptions): LiveFenceClaims | undefined;
@@ -0,0 +1,100 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * A-LIVE §8.2 live edge wire format (W9 / M4-E), pure and dependency-free so the host (immo), the controller
4
+ * (Sentropic API) and `artifact-content` sign and verify with the same code. Three HMAC-SHA256 message kinds, each
5
+ * with its own MAC-bound prefix so none can be replayed as another:
6
+ * - `v1` host assertion (immo → artifact-content), on every live request and websocket upgrade;
7
+ * - `c1` host control (immo → artifact-content): session or invitation revocation;
8
+ * - `f1` controller fence (Sentropic API → artifact-content): generation and route-epoch floor.
9
+ */
10
+ export const ASSERTION_HEADER = 'x-live-host-assertion';
11
+ export const CONTROL_HEADER = 'x-live-host-control';
12
+ export const FENCE_HEADER = 'x-live-controller-fence';
13
+ export const MIN_KEY_BYTES = 32;
14
+ export const MAX_ASSERTION_SECONDS = 3600;
15
+ export const MAX_CONTROL_SECONDS = 300;
16
+ export const MAX_SKEW_SECONDS = 30;
17
+ /** The live source revision is an opaque string (A-LIVE live revisions), compared, never parsed. */
18
+ export const MAX_SOURCE_REVISION_LENGTH = 256;
19
+ const revision = (value) => typeof value === 'string' && value.length >= 1 && value.length <= MAX_SOURCE_REVISION_LENGTH;
20
+ const ASSERTION_FIELDS = {
21
+ v: 'number', kid: 'string', host: 'string', artifactId: 'string', storageScopeId: 'string', sessionId: 'string',
22
+ generation: 'number', routeEpoch: 'number', podUid: 'string', podName: 'string', sourceRevision: 'string',
23
+ principalId: 'string', role: 'string', invitationId: 'string', invitationEpoch: 'number', invitationExp: 'number', iat: 'number', exp: 'number',
24
+ };
25
+ const CONTROL_FIELDS = {
26
+ v: 'number', kid: 'string', host: 'string', artifactId: 'string', op: 'string', sessionId: 'string',
27
+ invitationId: 'string', epoch: 'number', iat: 'number', exp: 'number',
28
+ };
29
+ const FENCE_FIELDS = {
30
+ v: 'number', kid: 'string', artifactId: 'string', generation: 'number', routeEpoch: 'number', iat: 'number', exp: 'number',
31
+ };
32
+ const mac = (key, prefix, body) => createHmac('sha256', key).update(`${prefix}.${body}`).digest();
33
+ function sign(prefix, claims, key) {
34
+ if (key.length < MIN_KEY_BYTES)
35
+ throw new Error('Live key must contain at least 32 bytes');
36
+ const body = Buffer.from(JSON.stringify(claims)).toString('base64url');
37
+ return `${prefix}.${body}.${mac(key, prefix, body).toString('base64url')}`;
38
+ }
39
+ function verify(prefix, fields, maxSeconds, token, options) {
40
+ const parts = token.split('.');
41
+ if (parts.length !== 3 || parts[0] !== prefix || token.length > 2048)
42
+ return;
43
+ let claims;
44
+ try {
45
+ claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
46
+ if (!claims || typeof claims !== 'object' || claims.v !== 1
47
+ || Object.keys(claims).sort().join() !== Object.keys(fields).sort().join()
48
+ || Object.entries(fields).some(([name, type]) => {
49
+ const value = claims[name];
50
+ return typeof value !== type || (type === 'number' && (!Number.isSafeInteger(value) || value < 0));
51
+ }))
52
+ return;
53
+ }
54
+ catch {
55
+ return;
56
+ }
57
+ const key = options.key(claims.kid);
58
+ if (!key || key.length < MIN_KEY_BYTES)
59
+ return;
60
+ const given = Buffer.from(parts[2], 'base64url');
61
+ const expected = mac(key, prefix, parts[1]);
62
+ if (given.length !== expected.length || !timingSafeEqual(given, expected))
63
+ return;
64
+ const now = options.now() / 1000;
65
+ if (claims.exp <= now || claims.iat > now + MAX_SKEW_SECONDS || claims.exp - claims.iat > maxSeconds)
66
+ return;
67
+ return claims;
68
+ }
69
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
70
+ /** Owner claims carry no invitation; an invitee claim must name a live invitation that outlasts the assertion. */
71
+ function validRole(c, now) {
72
+ if (c.role === 'binding_owner')
73
+ return c.invitationId === '' && c.invitationEpoch === 0 && c.invitationExp === 0;
74
+ return c.role === 'invitee' && ID.test(c.invitationId) && c.invitationEpoch >= 1
75
+ && c.invitationExp > now && c.exp <= c.invitationExp;
76
+ }
77
+ function validControl(c) {
78
+ if (c.op === 'revoke_session')
79
+ return ID.test(c.sessionId) && c.invitationId === '' && c.epoch === 0;
80
+ return c.op === 'revoke_invitation' && ID.test(c.invitationId) && c.epoch >= 1 && c.sessionId === '';
81
+ }
82
+ export function signLiveAssertion(claims, key) {
83
+ if (!revision(claims.sourceRevision))
84
+ throw new TypeError('Live source revision must be a string of 1 to 256 characters');
85
+ return sign('v1', claims, key);
86
+ }
87
+ export const signLiveControl = (claims, key) => sign('c1', claims, key);
88
+ export const signLiveFence = (claims, key) => sign('f1', claims, key);
89
+ export function verifyLiveAssertion(token, options) {
90
+ const claims = verify('v1', ASSERTION_FIELDS, MAX_ASSERTION_SECONDS, token, options);
91
+ return claims && revision(claims.sourceRevision) && validRole(claims, options.now() / 1000) ? claims : undefined;
92
+ }
93
+ export function verifyLiveControl(token, options) {
94
+ const claims = verify('c1', CONTROL_FIELDS, MAX_CONTROL_SECONDS, token, options);
95
+ return claims && validControl(claims) ? claims : undefined;
96
+ }
97
+ export function verifyLiveFence(token, options) {
98
+ const claims = verify('f1', FENCE_FIELDS, MAX_CONTROL_SECONDS, token, options);
99
+ return claims && claims.generation >= 1 ? claims : undefined;
100
+ }
@@ -0,0 +1,59 @@
1
+ import type { HandoffClaims } from './handoff.js';
2
+ /** Host state read INSIDE the host publication transaction, on the locked binding and job rows (A-LIVE §8.3). */
3
+ export interface AttemptFence {
4
+ runId: string;
5
+ attempt: number;
6
+ }
7
+ export interface HostRecheckView {
8
+ /** Authenticated host scope; never taken from the handoff. */
9
+ scopeId: string;
10
+ /** Operator pause or kill switch for sandbox publication. */
11
+ killSwitch: boolean;
12
+ /** Exact builder image digest strings (A-LIVE §8.1). */
13
+ imageAllowlist: readonly string[];
14
+ currentReleaseId: string | null;
15
+ /** The required head is reachable on the bound branch, observed in this transaction. */
16
+ headReachable: boolean;
17
+ binding: {
18
+ artifactId: string;
19
+ state: string;
20
+ generation: number;
21
+ executor: string;
22
+ autoPublish: boolean;
23
+ pendingJobId: string | null;
24
+ pendingCommitSha: string | null;
25
+ };
26
+ /** The persisted G0 v3 §2.6 job; `fence` is the attempt last admitted by `resolvePendingJob`. */
27
+ job: {
28
+ jobId: string;
29
+ state: string;
30
+ bindingGeneration: number;
31
+ commitSha: string;
32
+ expectedCurrentReleaseId: string | null;
33
+ fence: AttemptFence | null;
34
+ } | undefined;
35
+ /** Current owner/code rights and host write scope; the automatic policy and the §5.3.1 progress predicate or the
36
+ * separately recorded initial exception. */
37
+ policy: {
38
+ ownerAuthorized: boolean;
39
+ automaticAuthorized: boolean;
40
+ automaticEligible: boolean;
41
+ };
42
+ }
43
+ export declare const RECHECK_REFUSALS: readonly ["scope_mismatch", "publication_paused", "generation_mismatch", "job_not_pending", "attempt_fenced", "policy_refused", "head_unreachable", "release_conflict", "image_not_allowed"];
44
+ export type RecheckRefusal = typeof RECHECK_REFUSALS[number];
45
+ /** The host job the builder may build (A-LIVE §8.4 server-resolved commit), from `resolvePendingJob`. */
46
+ export interface HostJob {
47
+ jobId: string;
48
+ generation: number;
49
+ headSha: string;
50
+ expectedReleaseId: string | null;
51
+ }
52
+ /** Every §8.3 final recheck, in order; null admits. acceptHandoff applies it; the host only supplies the view. */
53
+ export declare function publicationRecheck(view: HostRecheckView, claims: HandoffClaims): RecheckRefusal | null;
54
+ /** Host side of the builder's job resolution: only the binding's pending job at its generation, never a caller SHA.
55
+ * The attempt fence is monotonic; the host persists the returned fence on the job in the same transaction. */
56
+ export declare function resolvePendingJob(view: HostRecheckView, jobId: string, fence: AttemptFence): {
57
+ job: HostJob;
58
+ fence: AttemptFence;
59
+ } | null;
@@ -0,0 +1,45 @@
1
+ export const RECHECK_REFUSALS = ['scope_mismatch', 'publication_paused', 'generation_mismatch', 'job_not_pending',
2
+ 'attempt_fenced', 'policy_refused', 'head_unreachable', 'release_conflict', 'image_not_allowed'];
3
+ function pending(view, jobId, generation) {
4
+ const { binding, job } = view;
5
+ return job !== undefined && ['build_pending', 'building'].includes(job.state) && binding.state === 'build_pending'
6
+ && binding.executor === 'sandbox' && binding.pendingJobId === jobId && job.jobId === jobId
7
+ && binding.generation === generation && job.bindingGeneration === generation
8
+ && binding.pendingCommitSha === job.commitSha ? job : undefined;
9
+ }
10
+ /** Every §8.3 final recheck, in order; null admits. acceptHandoff applies it; the host only supplies the view. */
11
+ export function publicationRecheck(view, claims) {
12
+ if (claims.scopeId !== view.scopeId || claims.artifactId !== view.binding.artifactId)
13
+ return 'scope_mismatch';
14
+ if (view.killSwitch || view.binding.state === 'paused')
15
+ return 'publication_paused';
16
+ if (claims.generation !== view.binding.generation)
17
+ return 'generation_mismatch';
18
+ const job = pending(view, claims.jobId, claims.generation);
19
+ if (!job || job.commitSha !== claims.commitSha)
20
+ return 'job_not_pending';
21
+ if (job.fence?.runId !== claims.runId || job.fence.attempt !== claims.attempt)
22
+ return 'attempt_fenced';
23
+ if (claims.kind === 'explicit' ? view.policy.ownerAuthorized !== true
24
+ : !(view.binding.autoPublish === true && view.policy.automaticAuthorized === true && view.policy.automaticEligible === true)) {
25
+ return 'policy_refused';
26
+ }
27
+ if (view.headReachable !== true)
28
+ return 'head_unreachable';
29
+ if (claims.expectedReleaseId !== job.expectedCurrentReleaseId || view.currentReleaseId !== job.expectedCurrentReleaseId)
30
+ return 'release_conflict';
31
+ if (!view.imageAllowlist.includes(claims.tuple.builderImageDigest))
32
+ return 'image_not_allowed';
33
+ return null;
34
+ }
35
+ /** Host side of the builder's job resolution: only the binding's pending job at its generation, never a caller SHA.
36
+ * The attempt fence is monotonic; the host persists the returned fence on the job in the same transaction. */
37
+ export function resolvePendingJob(view, jobId, fence) {
38
+ const job = pending(view, jobId, view.binding.generation);
39
+ if (!job || typeof fence?.runId !== 'string' || !fence.runId || !Number.isSafeInteger(fence.attempt) || fence.attempt < 1
40
+ || (job.fence && (fence.attempt < job.fence.attempt || (fence.attempt === job.fence.attempt && fence.runId !== job.fence.runId)))) {
41
+ return null;
42
+ }
43
+ return { job: { jobId, generation: job.bindingGeneration, headSha: job.commitSha, expectedReleaseId: job.expectedCurrentReleaseId },
44
+ fence: { runId: fence.runId, attempt: fence.attempt } };
45
+ }
@@ -10,7 +10,7 @@ export { createRadarKeyDerivation } from './server/command-identity.js';
10
10
  export type { ArtifactKeyDerivationBinding } from './server/command-identity.js';
11
11
  export declare const ARTIFACTS_PROVIDER_ID = "sentropic.artifacts";
12
12
  export declare const ARTIFACTS_APP_ID = "sentropic-artifacts";
13
- export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.18";
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.20";
14
14
  export declare const ARTIFACTS_TOOL_NAMES: readonly ["artifacts_get_template", "artifacts_get_api_guide", "artifacts_ensure", "artifacts_publish", "artifacts_create_upload", "artifacts_commit_upload", "artifacts_list", "artifacts_get", "artifacts_get_source", "artifacts_fork", "artifacts_set_access", "artifacts_promote", "artifacts_renew", "artifacts_delete", "artifacts_restore", "artifacts_list_versions", "artifacts_revert", "artifacts_lookup_people", "artifacts_list_access", "artifacts_publish_bundle", "artifacts_revoke_reader_consent", "artifacts_create_upload_page", "artifacts_list_assets", "artifacts_publish_bundle_v2", "artifacts_list_app_sources", "artifacts_fetch_app_source", "artifacts_git_attach", "artifacts_git_commit", "artifacts_git_publish", "artifacts_git_live", "artifacts_live_write", "artifacts_live_read", "artifacts_live_reset", "artifacts_live_status", "artifacts_live_control"];
15
15
  export type ArtifactsToolName = (typeof ARTIFACTS_TOOL_NAMES)[number];
16
16
  export interface ArtifactsToolDefinition {
package/dist/mcp-core.js CHANGED
@@ -7,7 +7,7 @@ export * from './profile/index.js';
7
7
  export { createRadarKeyDerivation } from './server/command-identity.js';
8
8
  export const ARTIFACTS_PROVIDER_ID = 'sentropic.artifacts';
9
9
  export const ARTIFACTS_APP_ID = 'sentropic-artifacts';
10
- export const ARTIFACTS_PROVIDER_VERSION = '0.2.18';
10
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.20';
11
11
  export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
12
12
  // ---------------------------------------------------------------------------
13
13
  // Byte-stable tool definitions (MCP tool-definition stability rule).
@@ -219,6 +219,9 @@ export function createArtifactsToolExecutor(deps) {
219
219
  case 'artifacts_live_status':
220
220
  case 'artifacts_live_control':
221
221
  case 'artifacts_git_commit':
222
+ case 'artifacts_fetch_app_source':
223
+ case 'artifacts_git_attach':
224
+ case 'artifacts_git_publish':
222
225
  request = { method: 'POST', path: '/' + input.tool.slice(10), body: args };
223
226
  break;
224
227
  case 'artifacts_ensure':
@@ -1,8 +1,10 @@
1
- import type { GitBinding, GitBindingEvent, GitBindingStore, GitBindingWrite } from './git-contracts.js';
1
+ import type { GitAttachIntent, GitBinding, GitBindingEvent, GitBindingStore, GitBindingWrite } from './git-contracts.js';
2
2
  export type * from './git-contracts.js';
3
3
  export declare function gitBindingReceiptKey(input: GitBindingWrite): string;
4
4
  /** Shared invariants run inside the adapter transaction, after receipt replay and before mutation. */
5
5
  export declare function validateGitBindingWrite(before: GitBinding | undefined, input: GitBindingWrite): void;
6
6
  export declare function gitBindingEvent(input: GitBindingWrite): GitBindingEvent;
7
+ /** Shared attach-intent admission for every adapter, before the put-if-absent. */
8
+ export declare function validateGitAttachIntent(intent: GitAttachIntent): void;
7
9
  /** Atomic single-process fake tenant. Outputs never expose mutable internal records. */
8
10
  export declare function createMemoryGitBindingStore(): GitBindingStore;
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { ArtifactOperationError } from './failures.js';
3
3
  import { createKeyMutex } from './ports.js';
4
4
  import { isAllowedGitBranch } from './git-registry.js';
5
+ import { isGitSha } from './git-port-policy.js';
5
6
  export function gitBindingReceiptKey(input) {
6
7
  return 'git-binding:' + createHash('sha256').update(JSON.stringify([
7
8
  input.binding.storageScopeId, input.actorId, input.idempotencyKey,
@@ -34,6 +35,9 @@ export function validateGitBindingWrite(before, input) {
34
35
  const action = input.event.action;
35
36
  const active = before !== undefined && before.state !== 'detached';
36
37
  const configuring = action === 'attach' && active;
38
+ if (input.event.branchCreated !== undefined && (input.event.branchCreated !== true || action !== 'attach' || active)) {
39
+ throw new ArtifactOperationError('invalid_request');
40
+ }
37
41
  const transition = action === 'attach' ? (configuring ? next.state === before.state : next.state === 'attached')
38
42
  : action === 'pause' ? active && next.state === 'paused'
39
43
  : action === 'resume' ? before?.state === 'paused' && next.state === 'attached' &&
@@ -71,13 +75,23 @@ export function gitBindingEvent(input) {
71
75
  return { id: randomUUID(), artifactId: input.binding.artifactId, storageScopeId: input.binding.storageScopeId,
72
76
  actorId: input.actorId, action: input.event.action, beforeSha: input.event.beforeSha,
73
77
  afterSha: input.event.afterSha, deliveryId: input.event.deliveryId,
74
- invocationId: input.event.invocationId, createdAt: input.binding.updatedAt };
78
+ invocationId: input.event.invocationId, ...(input.event.branchCreated ? { branchCreated: true } : {}),
79
+ createdAt: input.binding.updatedAt };
75
80
  }
81
+ /** Shared attach-intent admission for every adapter, before the put-if-absent. */
82
+ export function validateGitAttachIntent(intent) {
83
+ if (!isAllowedGitBranch(intent.branch) || !intent.idempotencyKey.trim() || !intent.commandHash || !intent.actorId ||
84
+ !intent.storageScopeId || !intent.artifactId || !intent.repoId || !isGitSha(intent.baseCommitSha)) {
85
+ throw new ArtifactOperationError('invalid_request');
86
+ }
87
+ }
88
+ const intentKey = (scope, actorId, key) => JSON.stringify([scope, actorId, key]);
76
89
  /** Atomic single-process fake tenant. Outputs never expose mutable internal records. */
77
90
  export function createMemoryGitBindingStore() {
78
91
  const rows = new Map();
79
92
  const audit = [];
80
93
  const receipts = new Map();
94
+ const intents = new Map();
81
95
  const mutex = createKeyMutex();
82
96
  return {
83
97
  async get(scope, id) {
@@ -87,6 +101,17 @@ export function createMemoryGitBindingStore() {
87
101
  async events(scope, id) {
88
102
  return structuredClone(audit.filter(event => event.storageScopeId === scope && event.artifactId === id));
89
103
  },
104
+ async reserveAttachIntent(intent) {
105
+ validateGitAttachIntent(intent);
106
+ const key = intentKey(intent.storageScopeId, intent.actorId, intent.idempotencyKey);
107
+ if (!intents.has(key))
108
+ intents.set(key, structuredClone(intent));
109
+ return structuredClone(intents.get(key));
110
+ },
111
+ async attachIntent(scope, actorId, idempotencyKey) {
112
+ const intent = intents.get(intentKey(scope, actorId, idempotencyKey));
113
+ return intent && structuredClone(intent);
114
+ },
90
115
  async write(input) {
91
116
  const snapshot = structuredClone(input);
92
117
  return mutex.runSerialized('git-bindings', async () => {
@@ -46,6 +46,8 @@ export interface GitBindingEvent {
46
46
  afterSha?: string;
47
47
  deliveryId?: string;
48
48
  invocationId?: string;
49
+ /** A-LIVE §5.3.1: only on the attach event that verified creation of the branch; initialUnpublishedBranchEligible input. */
50
+ branchCreated?: true;
49
51
  createdAt: string;
50
52
  }
51
53
  export interface GitReleaseIndex {
@@ -72,7 +74,19 @@ export interface GitBindingWrite {
72
74
  actorId: string;
73
75
  idempotencyKey: string;
74
76
  commandHash: string;
75
- event: Pick<GitBindingEvent, 'action' | 'beforeSha' | 'afterSha' | 'deliveryId' | 'invocationId'>;
77
+ event: Pick<GitBindingEvent, 'action' | 'beforeSha' | 'afterSha' | 'deliveryId' | 'invocationId' | 'branchCreated'>;
78
+ }
79
+ /** Written before createBranch, keyed like the replay receipt, so a same-key retry knows the branch is its own. */
80
+ export interface GitAttachIntent {
81
+ storageScopeId: string;
82
+ artifactId: string;
83
+ actorId: string;
84
+ idempotencyKey: string;
85
+ commandHash: string;
86
+ repoId: string;
87
+ branch: string;
88
+ baseCommitSha: string;
89
+ createdAt: string;
76
90
  }
77
91
  export interface GitBindingStore {
78
92
  get(storageScopeId: string, artifactId: string): Promise<GitBinding | undefined>;
@@ -82,6 +96,9 @@ export interface GitBindingStore {
82
96
  replayed: boolean;
83
97
  }>;
84
98
  events(storageScopeId: string, artifactId: string): Promise<GitBindingEvent[]>;
99
+ /** Durable put-if-absent by (scope, actor, key); returns the stored intent, which wins over the input. */
100
+ reserveAttachIntent(intent: GitAttachIntent): Promise<GitAttachIntent>;
101
+ attachIntent(storageScopeId: string, actorId: string, idempotencyKey: string): Promise<GitAttachIntent | undefined>;
85
102
  }
86
103
  /** SG4 writes the index using its release-transaction client; SG1 provides the record/read port. */
87
104
  export interface GitReleaseIndexStore {
@@ -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
+ }