@sentropic/artifacts 0.2.21 → 0.2.23

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.23
4
+
5
+ - `createGitHubForge` resolves a branch through `GET /repos/{owner}/{repo}/git/ref/heads/{branch}`
6
+ (each ref segment encoded on its own, so `artifact/p/<id>/<app>` keeps its slashes) and reads the
7
+ exact `refs/heads/<branch>` commit `object.sha`; a full 40-hex commit SHA goes straight to
8
+ `/commits/<sha>`. Another registered ref (a tag, an abbreviated SHA) that is not a branch still
9
+ resolves through `/commits/{ref}` (per-segment encoding); an `artifact/` branch never does.
10
+ - An absent ref is `missing` on every lookup: GitHub answers 422 « No commit found » (not 404) for an
11
+ unknown ref, and that 422 no longer maps to `conflict`/`git_ref_not_allowed`. `resolveRef` on the
12
+ bound branch reports `git_branch_missing` and `artifacts_git_attach` now treats it as an absent
13
+ branch, so a new personal branch is created from `baseRef` instead of failing the attach.
14
+ `createBranch` on an existing branch stays `conflict`.
15
+ - `ARTIFACTS_PROVIDER_VERSION` follows the package (0.2.23): the APP-P1 manifest digest changes through
16
+ its version field only (four-tool selection and tool definitions unchanged).
17
+
18
+ ## 0.2.22
19
+
20
+ - Generic live invitations through MCP (A-LIVE v2 §8.2, §9): four tools appended last and frozen at
21
+ birth, routed to `LiveService.execute`. `artifacts_live_invite` (owner only, invitee resolved from
22
+ a `userRef` and holding current code rights, 300..86400 s), `artifacts_live_accept_invitation` and
23
+ `artifacts_live_revoke_invitation` (the owner or the invitee; the session epoch rises and every open
24
+ invitation adopts it; `onRevoked` runs once after the commit) and `artifacts_live_invitations`
25
+ (owner sees all, an invitee only their own, as `userRef`/`displayName`). At most 16 open
26
+ invitations per session; an invitation ceases on a new live session or generation and expires at
27
+ its deadline. `LIVE_INVITATION_TOOL_CLASSES` maps each tool to a host read/write class.
28
+ - `createLiveService` returns `liveInvitationState(identity)` (`{ epoch, expiresAt }`, the latest
29
+ active expiry in ms) and `liveViewer(identity, principalId)`. Optional `LiveServiceDeps.invitations`
30
+ host port (`qualified`, `resolvePrincipal`, `describePrincipal`, `onRevoked`); without a qualified
31
+ port every invitation tool refuses with `builder_unavailable` and live stays owner-only.
32
+ - The postgres-live adapter persists invitations; host migration `0013_live_invitations.sql` adds
33
+ `artifacts.live_invitations` and `artifacts.live_invitation_epochs` and ends with a guard that
34
+ raises on any foreign column or index (a same-named table from another schema is refused).
35
+ - The 35 previous tool definitions are byte-identical. `ARTIFACTS_PROVIDER_VERSION` follows the
36
+ package (0.2.22): the APP-P1 manifest digest changes through its version field only (the four-tool
37
+ APP-P1 selection is unchanged; the same manifest at version 0.2.21 still hashes to the 0.2.21 pin).
38
+ `@sentropic/artifacts/live-host` is unchanged.
39
+
3
40
  ## 0.2.21
4
41
 
5
42
  - Add the GB1 build validators on `@sentropic/artifacts/server/build-contract`: full dependency
@@ -8,9 +8,38 @@ const sha = (value) => {
8
8
  throw new GitForgeError('unavailable');
9
9
  return value;
10
10
  };
11
+ /** GitHub answers 422 « No commit found » (not 404) for an unknown ref: both mean absent, never a ref refusal. */
12
+ async function absentAsMissing(request) {
13
+ try {
14
+ return await request;
15
+ }
16
+ catch (error) {
17
+ if (error instanceof GitForgeError && (error.code === 'missing' || error.code === 'conflict'))
18
+ throw new GitForgeError('missing');
19
+ throw error;
20
+ }
21
+ }
11
22
  /** Fixed public GitHub origins. The SG0-net host owns network admission and egress receipts. */
12
23
  export function createGitHubForge(fetcher = globalThis.fetch) {
13
24
  const api = githubApi(fetcher);
25
+ /** Each ref segment is encoded on its own so « artifact/p/x » keeps its path slashes. */
26
+ const segments = (ref) => ref.split('/').map(encodeURIComponent).join('/');
27
+ /** Exact branch lookup first; artifact branches never resolve as anything else. */
28
+ async function refHead(context, ref) {
29
+ try {
30
+ const result = await absentAsMissing(api(context, `/git/ref/heads/${segments(ref)}`));
31
+ if (result?.ref !== `refs/heads/${ref}` || result?.object?.type !== 'commit')
32
+ throw new GitForgeError('unavailable');
33
+ return sha(result.object.sha);
34
+ }
35
+ catch (error) {
36
+ if (ref.startsWith('artifact/') || !(error instanceof GitForgeError && error.code === 'missing'))
37
+ throw error;
38
+ }
39
+ // Registered sources may also be read at a tag or an abbreviated commit SHA (docs/git-port.md).
40
+ const result = await absentAsMissing(api(context, `/commits/${segments(ref)}`));
41
+ return sha(result?.sha);
42
+ }
14
43
  return {
15
44
  async repositoryId(context) {
16
45
  const result = await api(context, '');
@@ -20,8 +49,9 @@ export function createGitHubForge(fetcher = globalThis.fetch) {
20
49
  return String(result.id);
21
50
  },
22
51
  async resolve(context, ref) {
23
- const result = await api(context, `/commits/${encodeURIComponent(ref)}`);
24
- if (!Array.isArray(result?.parents) || typeof result?.commit?.message !== 'string' ||
52
+ const commitSha = /^[0-9a-f]{40}$/.test(ref) ? ref : await refHead(context, ref);
53
+ const result = await absentAsMissing(api(context, `/commits/${commitSha}`));
54
+ if (result?.sha !== commitSha || !Array.isArray(result?.parents) || typeof result?.commit?.message !== 'string' ||
25
55
  [result.commit.author, result.commit.committer].some(person => typeof person?.name !== 'string' || typeof person?.email !== 'string')) {
26
56
  throw new GitForgeError('unavailable');
27
57
  }
@@ -1,5 +1,45 @@
1
1
  import { ArtifactOperationError } from '../server/failures.js';
2
2
  import { liveIdentityKey } from '../server/live-store.js';
3
+ const INVITATION_COLUMNS = `storage_scope_id,artifact_id,binding_generation,live_session_id,invitation_id,principal_id,
4
+ created_by,status,epoch,expires_at,accepted_at,revoked_at,created_at,row_version`;
5
+ const iso = (value) => value === null ? null : new Date(value).toISOString();
6
+ /** Live invitations (migration 0013) under the transaction's advisory lock on the artifact. */
7
+ function postgresInvitations(client, identity) {
8
+ const own = [identity.storageScopeId, identity.artifactId];
9
+ return {
10
+ async list() {
11
+ const result = await client.query(`SELECT ${INVITATION_COLUMNS} FROM artifacts.live_invitations
12
+ WHERE storage_scope_id=$1 AND artifact_id=$2`, own);
13
+ return result.rows.map(row => ({ storageScopeId: row.storage_scope_id, artifactId: row.artifact_id,
14
+ bindingGeneration: Number(row.binding_generation), liveSessionId: row.live_session_id, invitationId: row.invitation_id,
15
+ principalId: row.principal_id, createdBy: row.created_by, status: row.status, epoch: Number(row.epoch),
16
+ expiresAt: iso(row.expires_at), acceptedAt: iso(row.accepted_at), revokedAt: iso(row.revoked_at),
17
+ createdAt: iso(row.created_at), rowVersion: Number(row.row_version) }));
18
+ },
19
+ async save(row) {
20
+ if (row.storageScopeId !== identity.storageScopeId || row.artifactId !== identity.artifactId)
21
+ throw new ArtifactOperationError('access_denied');
22
+ const result = row.rowVersion === 1 ? await client.query(`INSERT INTO artifacts.live_invitations (${INVITATION_COLUMNS})
23
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) ON CONFLICT DO NOTHING`, [...own, row.bindingGeneration,
24
+ row.liveSessionId, row.invitationId, row.principalId, row.createdBy, row.status, row.epoch, row.expiresAt,
25
+ row.acceptedAt, row.revokedAt, row.createdAt, row.rowVersion])
26
+ : await client.query(`UPDATE artifacts.live_invitations SET status=$4, epoch=$5, accepted_at=$6, revoked_at=$7,
27
+ row_version=$8 WHERE storage_scope_id=$1 AND artifact_id=$2 AND invitation_id=$3 AND row_version=$9`, [...own, row.invitationId, row.status, row.epoch, row.acceptedAt, row.revokedAt, row.rowVersion, row.rowVersion - 1]);
28
+ if (!result.rowCount)
29
+ throw new ArtifactOperationError('git_live_conflict', { publicDetails: { reason: row.rowVersion === 1 ? 'active_session' : 'stale_fence' } });
30
+ },
31
+ async epoch(generation, session) {
32
+ const result = await client.query(`SELECT epoch FROM artifacts.live_invitation_epochs WHERE storage_scope_id=$1
33
+ AND artifact_id=$2 AND binding_generation=$3 AND live_session_id=$4`, [...own, generation, session]);
34
+ return result.rows[0] ? Number(result.rows[0].epoch) : 0;
35
+ },
36
+ async setEpoch(generation, session, epoch) {
37
+ await client.query(`INSERT INTO artifacts.live_invitation_epochs
38
+ (storage_scope_id,artifact_id,binding_generation,live_session_id,epoch) VALUES ($1,$2,$3,$4,$5)
39
+ ON CONFLICT (storage_scope_id,artifact_id,binding_generation,live_session_id) DO UPDATE SET epoch=EXCLUDED.epoch`, [...own, generation, session, epoch]);
40
+ },
41
+ };
42
+ }
3
43
  /** No import-time I/O. PostgreSQL owns lease serialization, private objects and replay durability. */
4
44
  export function createPostgresLiveStore(pool) {
5
45
  return {
@@ -18,6 +58,7 @@ export function createPostgresLiveStore(pool) {
18
58
  WHERE storage_scope_id=$1 AND artifact_id=$2 AND binding_generation=$3 FOR UPDATE`, values);
19
59
  const tx = {
20
60
  record: before.rows[0]?.record,
61
+ invitations: postgresInvitations(client, identity),
21
62
  async getObject(ref) {
22
63
  const result = await client.query(`SELECT envelope FROM artifacts.live_draft_objects
23
64
  WHERE storage_scope_id=$1 AND artifact_id=$2 AND binding_generation=$3 AND object_ref=$4`, [...values, ref]);
@@ -1,4 +1,5 @@
1
- /** Frozen G0 v3 and A-LIVE v2 definition values; generated from the signed JSON blocks. */
1
+ /** Frozen G0 v3 and A-LIVE v2 definition values; generated from the signed JSON blocks. The four live invitation
2
+ * tools (A-LIVE v2 §9, contract 2026-11-07) are appended last and frozen at birth. */
2
3
  export declare const GIT_TOOL_DEFINITIONS: {
3
4
  artifacts_list_app_sources: {
4
5
  description: string;
@@ -603,4 +604,170 @@ export declare const GIT_TOOL_DEFINITIONS: {
603
604
  type: string;
604
605
  };
605
606
  };
607
+ artifacts_live_invite: {
608
+ description: string;
609
+ gates: {
610
+ requiresElicitation: false;
611
+ requiresHumanConfirmation: false;
612
+ requiresPrincipalGate: false;
613
+ };
614
+ idempotency: {
615
+ required: true;
616
+ scope: "principal";
617
+ };
618
+ inputSchema: {
619
+ additionalProperties: boolean;
620
+ properties: {
621
+ artifactId: {
622
+ pattern: string;
623
+ type: string;
624
+ };
625
+ expiresInSeconds: {
626
+ maximum: number;
627
+ minimum: number;
628
+ type: string;
629
+ };
630
+ idempotencyKey: {
631
+ description: string;
632
+ minLength: number;
633
+ type: string;
634
+ };
635
+ liveSessionId: {
636
+ description: string;
637
+ pattern: string;
638
+ type: string;
639
+ };
640
+ userRef: {
641
+ description: string;
642
+ maxLength: number;
643
+ minLength: number;
644
+ type: string;
645
+ };
646
+ };
647
+ required: string[];
648
+ type: string;
649
+ };
650
+ mutability: "state-transition";
651
+ outputSchema: {
652
+ additionalProperties: boolean;
653
+ type: string;
654
+ };
655
+ };
656
+ artifacts_live_accept_invitation: {
657
+ description: string;
658
+ gates: {
659
+ requiresElicitation: false;
660
+ requiresHumanConfirmation: false;
661
+ requiresPrincipalGate: false;
662
+ };
663
+ idempotency: {
664
+ required: true;
665
+ scope: "principal";
666
+ };
667
+ inputSchema: {
668
+ additionalProperties: boolean;
669
+ properties: {
670
+ artifactId: {
671
+ pattern: string;
672
+ type: string;
673
+ };
674
+ idempotencyKey: {
675
+ description: string;
676
+ minLength: number;
677
+ type: string;
678
+ };
679
+ invitationId: {
680
+ pattern: string;
681
+ type: string;
682
+ };
683
+ };
684
+ required: string[];
685
+ type: string;
686
+ };
687
+ mutability: "state-transition";
688
+ outputSchema: {
689
+ additionalProperties: boolean;
690
+ type: string;
691
+ };
692
+ };
693
+ artifacts_live_revoke_invitation: {
694
+ description: string;
695
+ gates: {
696
+ requiresElicitation: false;
697
+ requiresHumanConfirmation: false;
698
+ requiresPrincipalGate: false;
699
+ };
700
+ idempotency: {
701
+ required: true;
702
+ scope: "principal";
703
+ };
704
+ inputSchema: {
705
+ additionalProperties: boolean;
706
+ properties: {
707
+ artifactId: {
708
+ pattern: string;
709
+ type: string;
710
+ };
711
+ idempotencyKey: {
712
+ description: string;
713
+ minLength: number;
714
+ type: string;
715
+ };
716
+ invitationId: {
717
+ pattern: string;
718
+ type: string;
719
+ };
720
+ };
721
+ required: string[];
722
+ type: string;
723
+ };
724
+ mutability: "state-transition";
725
+ outputSchema: {
726
+ additionalProperties: boolean;
727
+ type: string;
728
+ };
729
+ };
730
+ artifacts_live_invitations: {
731
+ description: string;
732
+ gates: {
733
+ requiresElicitation: false;
734
+ requiresHumanConfirmation: false;
735
+ requiresPrincipalGate: false;
736
+ };
737
+ idempotency: {
738
+ required: false;
739
+ };
740
+ inputSchema: {
741
+ additionalProperties: boolean;
742
+ properties: {
743
+ artifactId: {
744
+ pattern: string;
745
+ type: string;
746
+ };
747
+ cursor: {
748
+ maxLength: number;
749
+ minLength: number;
750
+ type: string;
751
+ };
752
+ liveSessionId: {
753
+ pattern: string;
754
+ type: string;
755
+ };
756
+ };
757
+ required: string[];
758
+ type: string;
759
+ };
760
+ mutability: "read-only";
761
+ outputSchema: {
762
+ additionalProperties: boolean;
763
+ type: string;
764
+ };
765
+ };
766
+ };
767
+ /** Access class per invitation tool; each host maps a class to its own scope (no new scope). */
768
+ export declare const LIVE_INVITATION_TOOL_CLASSES: {
769
+ readonly artifacts_live_invite: "write";
770
+ readonly artifacts_live_accept_invitation: "read";
771
+ readonly artifacts_live_revoke_invitation: "read";
772
+ readonly artifacts_live_invitations: "read";
606
773
  };
@@ -1,4 +1,5 @@
1
- /** Frozen G0 v3 and A-LIVE v2 definition values; generated from the signed JSON blocks. */
1
+ /** Frozen G0 v3 and A-LIVE v2 definition values; generated from the signed JSON blocks. The four live invitation
2
+ * tools (A-LIVE v2 §9, contract 2026-11-07) are appended last and frozen at birth. */
2
3
  export const GIT_TOOL_DEFINITIONS = {
3
4
  artifacts_list_app_sources: { "description": "Artifacts list app sources: list the registered application sources and repositories visible to the caller. Opaque repoIds only; a source registered for reading is not necessarily writable (canWrite).", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": false }, "inputSchema": { "additionalProperties": false, "properties": { "cursor": { "maxLength": 4096, "minLength": 1, "type": "string" } }, "required": [], "type": "object" }, "mutability": "read-only", "outputSchema": { "additionalProperties": true, "type": "object" } },
4
5
  artifacts_fetch_app_source: { "description": "Artifacts fetch app source: read application source files at a server-resolved commit. artifactId resolves the bound branch; otherwise repoId and ref select the source. Oversized files are reported as omitted entries, never as failures.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": false }, "inputSchema": { "additionalProperties": false, "anyOf": [{ "required": ["artifactId"] }, { "required": ["repoId"] }], "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "cursor": { "maxLength": 4096, "minLength": 1, "type": "string" }, "paths": { "items": { "description": "Repository path relative to the binding sub-path; the active profile bounds its byte length and forbids reserved or dot segments, enforced server-side with typed errors.", "minLength": 1, "type": "string" }, "maxItems": 255, "minItems": 1, "type": "array" }, "ref": { "minLength": 1, "type": "string" }, "repoId": { "minLength": 1, "type": "string" } }, "required": [], "type": "object" }, "mutability": "read-only", "outputSchema": { "additionalProperties": true, "type": "object" } },
@@ -11,4 +12,13 @@ export const GIT_TOOL_DEFINITIONS = {
11
12
  artifacts_live_reset: { "description": "Artifacts live reset: discard the complete uncommitted draft and reset the live source tree to the verified bound branch head under a revision comparison. Do not move a git ref or publish.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": true, "scope": "principal" }, "inputSchema": { "additionalProperties": false, "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "expectedHeadSha": { "description": "Full commit SHA of the bound branch head; the server verifies the repository object format and compares the current head.", "minLength": 1, "type": "string" }, "expectedLiveRevision": { "description": "Opaque revision returned by live read or status; the server compares the complete binding generation, draft revision and base head.", "minLength": 1, "type": "string" }, "idempotencyKey": { "description": "Nonblank by JavaScript trim(); the active profile bounds its length in UTF-16 units; original bytes retained.", "minLength": 1, "type": "string" } }, "required": ["artifactId", "expectedHeadSha", "expectedLiveRevision", "idempotencyKey"], "type": "object" }, "mutability": "state-transition", "outputSchema": { "additionalProperties": true, "type": "object" } },
12
13
  artifacts_live_status: { "description": "Artifacts live status: inspect the binding's live state and optionally page the complete source diff against its base head. Report external head changes separately. Do not start a worker, commit or publish.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": false }, "inputSchema": { "additionalProperties": false, "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "cursor": { "minLength": 1, "type": "string" }, "includeDiff": { "type": "boolean" } }, "required": ["artifactId"], "type": "object" }, "mutability": "read-only", "outputSchema": { "additionalProperties": true, "type": "object" } },
13
14
  artifacts_live_write: { "description": "Artifacts live write: atomically apply text edits, full text files and deletes to the bound owner's live source tree. Revive the live worker when needed. Persist the draft before acknowledging; do not commit or publish.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": true, "scope": "principal" }, "inputSchema": { "additionalProperties": false, "anyOf": [{ "required": ["edits"] }, { "required": ["files"] }, { "required": ["deletes"] }], "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "deletes": { "items": { "description": "Repository path relative to the binding sub-path; the active profile bounds its byte length and forbids reserved or dot segments, enforced server-side with typed errors.", "minLength": 1, "type": "string" }, "minItems": 1, "type": "array" }, "edits": { "items": { "additionalProperties": false, "properties": { "newStr": { "type": "string" }, "oldStr": { "minLength": 1, "type": "string" }, "path": { "description": "Repository path relative to the binding sub-path; the active profile bounds its byte length and forbids reserved or dot segments, enforced server-side with typed errors.", "minLength": 1, "type": "string" } }, "required": ["path", "oldStr", "newStr"], "type": "object" }, "minItems": 1, "type": "array" }, "expectedHeadSha": { "description": "Full commit SHA of the bound branch head; the server verifies the repository object format and compares the current head.", "minLength": 1, "type": "string" }, "expectedLiveRevision": { "description": "Opaque revision returned by live read or status; the server compares the complete binding generation, draft revision and base head.", "minLength": 1, "type": "string" }, "files": { "items": { "additionalProperties": false, "properties": { "path": { "description": "Repository path relative to the binding sub-path; the active profile bounds its byte length and forbids reserved or dot segments, enforced server-side with typed errors.", "minLength": 1, "type": "string" }, "text": { "type": "string" } }, "required": ["path", "text"], "type": "object" }, "minItems": 1, "type": "array" }, "idempotencyKey": { "description": "Nonblank by JavaScript trim(); the active profile bounds its length in UTF-16 units; original bytes retained.", "minLength": 1, "type": "string" } }, "required": ["artifactId", "expectedHeadSha", "expectedLiveRevision", "idempotencyKey"], "type": "object" }, "mutability": "state-transition", "outputSchema": { "additionalProperties": true, "type": "object" } },
15
+ artifacts_live_invite: { "description": "Artifacts live invite: invite one person, named by an opaque userRef from artifacts_lookup_people, to view the bound owner's current live session until an expiry. The invitee must hold current code rights and accept; an invitation never grants editing, publication or release access.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": true, "scope": "principal" }, "inputSchema": { "additionalProperties": false, "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "expiresInSeconds": { "maximum": 86400, "minimum": 300, "type": "integer" }, "idempotencyKey": { "description": "Nonblank by JavaScript trim(); the active profile bounds its length in UTF-16 units; original bytes retained.", "minLength": 1, "type": "string" }, "liveSessionId": { "description": "Server-issued identifier of the current live session.", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "userRef": { "description": "Opaque userRef returned by artifacts_lookup_people.", "maxLength": 256, "minLength": 1, "type": "string" } }, "required": ["artifactId", "liveSessionId", "userRef", "expiresInSeconds", "idempotencyKey"], "type": "object" }, "mutability": "state-transition", "outputSchema": { "additionalProperties": true, "type": "object" } },
16
+ artifacts_live_accept_invitation: { "description": "Artifacts live accept invitation: accept, as the invited person, a pending invitation to the current live session before its expiry. Current code rights are checked again; acceptance grants viewing of that live session only.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": true, "scope": "principal" }, "inputSchema": { "additionalProperties": false, "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "idempotencyKey": { "description": "Nonblank by JavaScript trim(); the active profile bounds its length in UTF-16 units; original bytes retained.", "minLength": 1, "type": "string" }, "invitationId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" } }, "required": ["artifactId", "invitationId", "idempotencyKey"], "type": "object" }, "mutability": "state-transition", "outputSchema": { "additionalProperties": true, "type": "object" } },
17
+ artifacts_live_revoke_invitation: { "description": "Artifacts live revoke invitation: revoke a live invitation. The binding owner may revoke any invitation of the session and an invitee their own; revocation raises the session invitation epoch and closes the invitee's live connections.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": true, "scope": "principal" }, "inputSchema": { "additionalProperties": false, "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "idempotencyKey": { "description": "Nonblank by JavaScript trim(); the active profile bounds its length in UTF-16 units; original bytes retained.", "minLength": 1, "type": "string" }, "invitationId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" } }, "required": ["artifactId", "invitationId", "idempotencyKey"], "type": "object" }, "mutability": "state-transition", "outputSchema": { "additionalProperties": true, "type": "object" } },
18
+ artifacts_live_invitations: { "description": "Artifacts live invitations: list the invitations of the current or a named live session. The binding owner sees every invitation and an invitee only their own; people appear as opaque userRefs, never as internal principals.", "gates": { "requiresElicitation": false, "requiresHumanConfirmation": false, "requiresPrincipalGate": false }, "idempotency": { "required": false }, "inputSchema": { "additionalProperties": false, "properties": { "artifactId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" }, "cursor": { "maxLength": 4096, "minLength": 1, "type": "string" }, "liveSessionId": { "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "type": "string" } }, "required": ["artifactId"], "type": "object" }, "mutability": "read-only", "outputSchema": { "additionalProperties": true, "type": "object" } },
19
+ };
20
+ /** Access class per invitation tool; each host maps a class to its own scope (no new scope). */
21
+ export const LIVE_INVITATION_TOOL_CLASSES = {
22
+ artifacts_live_invite: 'write', artifacts_live_accept_invitation: 'read',
23
+ artifacts_live_revoke_invitation: 'read', artifacts_live_invitations: 'read',
14
24
  };
package/dist/http.js CHANGED
@@ -51,7 +51,8 @@ export function assertArtifactsTransportProfile(value) {
51
51
  'artifacts_create_upload_page', 'artifacts_list_assets', 'artifacts_publish_bundle_v2',
52
52
  'artifacts_revoke_reader_consent', 'artifacts_git_commit', 'artifacts_live_write',
53
53
  'artifacts_live_read', 'artifacts_live_reset', 'artifacts_live_status', 'artifacts_live_control',
54
- 'artifacts_fetch_app_source', 'artifacts_git_attach', 'artifacts_git_publish'];
54
+ 'artifacts_fetch_app_source', 'artifacts_git_attach', 'artifacts_git_publish', 'artifacts_live_invite',
55
+ 'artifacts_live_accept_invitation', 'artifacts_live_revoke_invitation', 'artifacts_live_invitations'];
55
56
  if (value.selectedCapabilities.some((name) => !supported.includes(name))) {
56
57
  throw new Error('unsupported artifacts transport capability');
57
58
  }
@@ -557,7 +558,7 @@ export function createHttpArtifactApp(deps) {
557
558
  phase = 'dispatch';
558
559
  const result = await deps.live.execute(operation, normalized, invocation);
559
560
  return { ok: true, invocationId: invocation.invocationId,
560
- commitState: ['live_read', 'live_status'].includes(operation) ? 'not_committed' : 'committed',
561
+ commitState: ['live_read', 'live_status', 'live_invitations'].includes(operation) ? 'not_committed' : 'committed',
561
562
  replayed: result.replayed === true, result: { status: 200, body: result } };
562
563
  }
563
564
  const command = ['artifacts_ensure', 'artifacts_publish', 'artifacts_set_access', 'artifacts_delete', 'artifacts_revert',
@@ -10,8 +10,8 @@ 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.21";
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"];
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.23";
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", "artifacts_live_invite", "artifacts_live_accept_invitation", "artifacts_live_revoke_invitation", "artifacts_live_invitations"];
15
15
  export type ArtifactsToolName = (typeof ARTIFACTS_TOOL_NAMES)[number];
16
16
  export interface ArtifactsToolDefinition {
17
17
  readonly description: string;
@@ -24,7 +24,7 @@ export interface ArtifactsToolDefinition {
24
24
  /** Static wire definitions for every artifacts tool; identical across deployments and profiles. */
25
25
  export declare const ARTIFACTS_TOOL_DEFINITIONS: Readonly<Record<ArtifactsToolName, ArtifactsToolDefinition>>;
26
26
  export declare const ARTIFACTS_TOOL_SPECS: {
27
- name: "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";
27
+ name: "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" | "artifacts_live_invite" | "artifacts_live_accept_invitation" | "artifacts_live_revoke_invitation" | "artifacts_live_invitations";
28
28
  description: string;
29
29
  mutability: import("@sentropic/mcp-platform").Mutability;
30
30
  }[];
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.21';
10
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.23';
11
11
  export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
12
12
  // ---------------------------------------------------------------------------
13
13
  // Byte-stable tool definitions (MCP tool-definition stability rule).
@@ -222,6 +222,10 @@ export function createArtifactsToolExecutor(deps) {
222
222
  case 'artifacts_fetch_app_source':
223
223
  case 'artifacts_git_attach':
224
224
  case 'artifacts_git_publish':
225
+ case 'artifacts_live_invite':
226
+ case 'artifacts_live_accept_invitation':
227
+ case 'artifacts_live_revoke_invitation':
228
+ case 'artifacts_live_invitations':
225
229
  request = { method: 'POST', path: '/' + input.tool.slice(10), body: args };
226
230
  break;
227
231
  case 'artifacts_ensure':
@@ -1,7 +1,7 @@
1
1
  import type { JsonValue } from '../contracts.js';
2
2
  import type { EffectiveArtifactCommand } from '../server/command-identity.js';
3
3
  export declare const PROFILE_CONTRACT_VERSION: "artifacts-profile/v1";
4
- export declare const ARTIFACT_CAPABILITY_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"];
4
+ export declare const ARTIFACT_CAPABILITY_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", "artifacts_live_invite", "artifacts_live_accept_invitation", "artifacts_live_revoke_invitation", "artifacts_live_invitations"];
5
5
  export type ArtifactCapabilityName = (typeof ARTIFACT_CAPABILITY_NAMES)[number];
6
6
  export type ArtifactSchema = Readonly<Record<string, unknown>>;
7
7
  export interface OperationProfile {
@@ -16,6 +16,9 @@ export const ARTIFACT_CAPABILITY_NAMES = [
16
16
  'artifacts_git_attach', 'artifacts_git_commit', 'artifacts_git_publish', 'artifacts_git_live',
17
17
  'artifacts_live_write', 'artifacts_live_read', 'artifacts_live_reset',
18
18
  'artifacts_live_status', 'artifacts_live_control',
19
+ // Live invitations (A-LIVE v2 §9) — appended last; frozen at birth.
20
+ 'artifacts_live_invite', 'artifacts_live_accept_invitation', 'artifacts_live_revoke_invitation',
21
+ 'artifacts_live_invitations',
19
22
  ];
20
23
  /** Projection fields are data-only; invocation correlation is added by L6. */
21
24
  export const PRECONDITION_REQUIRED_MESSAGE = 'expectedCurrentReleaseId is required by the active artifact profile. Re-read this artifact with artifacts_get or artifacts_list, then send expectedCurrentReleaseId using the currentReleaseId returned by that read. Send null only if the read confirms that there is no current release. Before editing an existing release, read it with artifacts_get_source and use that releaseId. The server will not infer this value.';
@@ -127,7 +127,8 @@ export function compileArtifactsProfile(input) {
127
127
  if (['artifacts_ensure', 'artifacts_publish', 'artifacts_commit_upload', 'artifacts_publish_bundle',
128
128
  'artifacts_publish_bundle_v2', 'artifacts_set_access', 'artifacts_delete', 'artifacts_revert',
129
129
  'artifacts_git_attach', 'artifacts_git_commit', 'artifacts_git_publish', 'artifacts_git_live',
130
- 'artifacts_live_write', 'artifacts_live_reset', 'artifacts_live_control'].includes(name)) {
130
+ 'artifacts_live_write', 'artifacts_live_reset', 'artifacts_live_control', 'artifacts_live_invite',
131
+ 'artifacts_live_accept_invitation', 'artifacts_live_revoke_invitation'].includes(name)) {
131
132
  idempotency[name] = { required: true, scope: 'principal' };
132
133
  }
133
134
  }
@@ -149,7 +150,8 @@ export function compileArtifactsProfile(input) {
149
150
  capabilityForRoute(method, path) {
150
151
  let name;
151
152
  const gitRoutes = ['list_app_sources', 'fetch_app_source', 'git_attach', 'git_commit', 'git_publish',
152
- 'live_write', 'live_read', 'live_reset', 'live_status', 'live_control'];
153
+ 'live_write', 'live_read', 'live_reset', 'live_status', 'live_control',
154
+ 'live_invite', 'live_accept_invitation', 'live_revoke_invitation', 'live_invitations'];
153
155
  if (method === 'POST' && gitRoutes.some(route => path === '/' + route)) {
154
156
  name = `artifacts_${path.slice(1)}`;
155
157
  }
@@ -24,6 +24,9 @@ export function assertCompleteOperation(config) {
24
24
  live_write: { limits: ['idempotencyKeyMaxUnits'], defaults: [] },
25
25
  live_reset: { limits: ['idempotencyKeyMaxUnits'], defaults: [] },
26
26
  live_control: { limits: ['idempotencyKeyMaxUnits'], defaults: [] },
27
+ live_invite: { limits: ['idempotencyKeyMaxUnits'], defaults: [] },
28
+ live_accept_invitation: { limits: ['idempotencyKeyMaxUnits'], defaults: [] },
29
+ live_revoke_invitation: { limits: ['idempotencyKeyMaxUnits'], defaults: [] },
27
30
  ensure: { limits: ['bindingNameMinUnits', 'bindingNameMaxUnits', 'idempotencyKeyMaxUnits'],
28
31
  defaults: ['parameters'] },
29
32
  // publish additionally accepts the optional release-budget keys
@@ -104,7 +104,8 @@ export function normalizeArguments(profile, name, input, schema, envelopeKey, op
104
104
  const normalized = { ...copyJson(defaults), ...args };
105
105
  if (['ensure', 'publish', 'commit_upload', 'publish_bundle', 'publish_bundle_v2',
106
106
  'set_access', 'delete', 'revert', 'git_attach', 'git_commit', 'git_publish', 'git_live',
107
- 'live_write', 'live_reset', 'live_control'].includes(operation)) {
107
+ 'live_write', 'live_reset', 'live_control', 'live_invite', 'live_accept_invitation',
108
+ 'live_revoke_invitation'].includes(operation)) {
108
109
  const key = args.idempotencyKey;
109
110
  requireInput(typeof key === 'string' && key.trim().length > 0 && key.length <= limits.idempotencyKeyMaxUnits);
110
111
  requireInput(envelopeKey === undefined || envelopeKey === key);
@@ -5,7 +5,9 @@ import { validateGitBindingTarget } from './git-registry.js';
5
5
  import { requireCodeRight, requireOwner } from './git-tools-publish.js';
6
6
  const FIELDS = ['repoId', 'branch', 'baseRef', 'subPath', 'autoPublish', 'executor', 'pause'];
7
7
  const id8 = (value) => createHash('sha256').update(value).digest('hex').slice(0, 8);
8
- const notFound = (error) => error instanceof ArtifactOperationError && error.kind === 'not_found';
8
+ /** The git port reports an absent bound branch as git_branch_missing and any other absent ref as not_found. */
9
+ const notFound = (error) => error instanceof ArtifactOperationError &&
10
+ (error.kind === 'not_found' || error.kind === 'git_branch_missing');
9
11
  /** G0 v3 §1.2 Tool 3 / A-LIVE S03: attach, configure, pause, resume or detach one binding. */
10
12
  export async function attachGit(deps, args, inv) {
11
13
  await requireOwner(deps, inv, args.artifactId, true);
@@ -2,6 +2,7 @@ import type { GitBinding } from './git-contracts.js';
2
2
  import type { GitPort, GitPortRepository, GitPortTarget } from './git-port.js';
3
3
  import type { LiveKeyPort } from './live-crypto.js';
4
4
  import type { LiveDraftRecord, LiveIdentity, LiveStore, LiveTransaction } from './live-store.js';
5
+ import type { PrincipalDirectoryPort } from './ports.js';
5
6
  export interface LiveInvocation {
6
7
  actorId: string;
7
8
  storageScopeId: string;
@@ -33,6 +34,36 @@ export interface LiveWorkerPort {
33
34
  leaseEpoch: number;
34
35
  }): Promise<void>;
35
36
  }
37
+ export interface LiveInvitationRevoked {
38
+ storageScopeId: string;
39
+ artifactId: string;
40
+ liveSessionId: string;
41
+ bindingGeneration: number;
42
+ invitationId: string;
43
+ epoch: number;
44
+ }
45
+ /** Host invitation port. Invited live readers stay opt-in: `qualified !== true` keeps live owner-only. */
46
+ export interface LiveInvitationPort extends Pick<PrincipalDirectoryPort, 'resolvePrincipal' | 'describePrincipal'> {
47
+ qualified: boolean;
48
+ /** Called once after the revocation commit: close the proxied sockets, then push c1 revoke_invitation.
49
+ * Idempotent; the host retries the push until 204. */
50
+ onRevoked(e: LiveInvitationRevoked): Promise<void>;
51
+ }
52
+ /** The `invitation` object of the reconcile and grant bodies; `expiresAt` is the latest active expiry (ms). */
53
+ export interface LiveInvitationState {
54
+ epoch: number;
55
+ expiresAt: number | null;
56
+ }
57
+ export type LiveViewer = {
58
+ role: 'binding_owner';
59
+ } | {
60
+ role: 'invitee';
61
+ invitation: {
62
+ id: string;
63
+ epoch: number;
64
+ expiresAt: number;
65
+ };
66
+ } | null;
36
67
  export interface LiveServiceDeps {
37
68
  store: LiveStore;
38
69
  keys: LiveKeyPort;
@@ -45,10 +76,16 @@ export interface LiveServiceDeps {
45
76
  commitBytesMax?: number;
46
77
  gitMessageMaxUnits?: number;
47
78
  idempotencyKeyMaxUnits?: number;
79
+ invitations?: LiveInvitationPort;
48
80
  }
49
81
  export interface LiveService {
50
82
  execute(operation: string, args: Record<string, unknown>, invocation: LiveInvocation): Promise<Record<string, any>>;
51
83
  }
84
+ /** Session state exports for the host reconcile, grant and live proxy paths. */
85
+ export interface LiveSessionService extends LiveService {
86
+ liveInvitationState(identity: LiveIdentity): Promise<LiveInvitationState>;
87
+ liveViewer(identity: LiveIdentity, principalId: string): Promise<LiveViewer>;
88
+ }
52
89
  export declare function liveResponse(record: LiveDraftRecord, currentHeadSha: string, now?: number): Record<string, unknown>;
53
90
  export type LiveSessionTransaction = LiveTransaction;
54
91
  export type LiveSnapshot = {
@@ -0,0 +1,9 @@
1
+ import type { LiveServiceDeps, LiveSessionService } from './live-contracts.js';
2
+ import type { LiveDraftRecord, LiveIdentity, LiveInvitationRecord, LiveTransaction } from './live-store.js';
3
+ export declare const isOpenInvitation: (row: LiveInvitationRecord) => boolean;
4
+ /** The session an invitation binds: the binding generation's current runtime, never a stopped (DORMANT) one. */
5
+ export declare const currentLiveSession: (record: LiveDraftRecord | undefined) => string | null;
6
+ /** Projects ceased (other session or generation) and expired invitations; writers persist the transitions. */
7
+ export declare function sweepInvitations(tx: LiveTransaction, identity: LiveIdentity, now: number, persist: boolean): Promise<LiveInvitationRecord[]>;
8
+ /** `liveInvitationState` and `liveViewer` read the committed state; they never write. */
9
+ export declare function liveInvitationViews(deps: LiveServiceDeps): Omit<LiveSessionService, 'execute'>;
@@ -0,0 +1,44 @@
1
+ export const isOpenInvitation = (row) => row.status === 'pending' || row.status === 'active';
2
+ /** The session an invitation binds: the binding generation's current runtime, never a stopped (DORMANT) one. */
3
+ export const currentLiveSession = (record) => record?.runtime && record.runtime.phase !== 'DORMANT' ? record.runtime.liveSessionId : null;
4
+ /** Projects ceased (other session or generation) and expired invitations; writers persist the transitions. */
5
+ export async function sweepInvitations(tx, identity, now, persist) {
6
+ const rows = (await tx.invitations.list()).sort((a, b) => a.createdAt.localeCompare(b.createdAt) ||
7
+ a.invitationId.localeCompare(b.invitationId));
8
+ for (const row of rows) {
9
+ if (!isOpenInvitation(row))
10
+ continue;
11
+ const status = row.bindingGeneration !== identity.bindingGeneration || row.liveSessionId !== currentLiveSession(tx.record)
12
+ ? 'ceased' : Date.parse(row.expiresAt) <= now ? 'expired' : row.status;
13
+ if (status === row.status)
14
+ continue;
15
+ Object.assign(row, { status, rowVersion: row.rowVersion + 1 });
16
+ if (persist)
17
+ await tx.invitations.save(row);
18
+ }
19
+ return rows;
20
+ }
21
+ /** `liveInvitationState` and `liveViewer` read the committed state; they never write. */
22
+ export function liveInvitationViews(deps) {
23
+ const qualified = () => deps.invitations?.qualified === true;
24
+ const read = (identity, empty, action) => deps.store.transaction(identity, async (tx) => {
25
+ const session = currentLiveSession(tx.record);
26
+ if (!session)
27
+ return empty;
28
+ return action(qualified() && tx.invitations ? await sweepInvitations(tx, identity, (deps.now ?? Date.now)(), false) : [], session, tx);
29
+ });
30
+ return {
31
+ liveInvitationState: identity => read(identity, { epoch: 0, expiresAt: null }, async (rows, session, tx) => {
32
+ const active = rows.filter(row => row.liveSessionId === session && row.status === 'active').map(row => Date.parse(row.expiresAt));
33
+ return { epoch: qualified() && tx.invitations ? await tx.invitations.epoch(identity.bindingGeneration, session) : 0,
34
+ expiresAt: active.length ? Math.max(...active) : null };
35
+ }),
36
+ liveViewer: (identity, principalId) => read(identity, null, async (rows, session, tx) => {
37
+ if (principalId === tx.record.runtime.ownerId)
38
+ return { role: 'binding_owner' };
39
+ const row = rows.find(entry => entry.liveSessionId === session && entry.principalId === principalId && entry.status === 'active');
40
+ return row ? { role: 'invitee', invitation: { id: row.invitationId, epoch: row.epoch,
41
+ expiresAt: Date.parse(row.expiresAt) } } : null;
42
+ }),
43
+ };
44
+ }
@@ -0,0 +1,5 @@
1
+ import type { LiveInvocation, LiveServiceDeps } from './live-contracts.js';
2
+ /** Generic live invitations (A-LIVE v2 §8.2, §9; contract 2026-11-07). Viewing only: no edit, publication or release grant. */
3
+ export declare const LIVE_INVITATION_OPERATIONS: readonly ["live_invite", "live_accept_invitation", "live_revoke_invitation", "live_invitations"];
4
+ export declare const LIVE_INVITATIONS_OPEN_MAX = 16;
5
+ export declare function executeLiveInvitation(deps: LiveServiceDeps, operation: string, args: Record<string, any>, invocation: LiveInvocation): Promise<Record<string, any>>;
@@ -0,0 +1,178 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { orderedDigest } from '../profile/json.js';
3
+ import { ArtifactOperationError } from './failures.js';
4
+ import { liveBusy } from './live-mutations.js';
5
+ import { UNKNOWN_USER_REF } from './ports.js';
6
+ import { currentLiveSession as currentSession, isOpenInvitation as open, sweepInvitations as sweep } from './live-invitation-state.js';
7
+ /** Generic live invitations (A-LIVE v2 §8.2, §9; contract 2026-11-07). Viewing only: no edit, publication or release grant. */
8
+ export const LIVE_INVITATION_OPERATIONS = ['live_invite', 'live_accept_invitation', 'live_revoke_invitation', 'live_invitations'];
9
+ export const LIVE_INVITATIONS_OPEN_MAX = 16;
10
+ const PAGE = 50;
11
+ const denied = () => new ArtifactOperationError('access_denied');
12
+ const iso = (ms) => new Date(ms).toISOString();
13
+ function admit(authority, invocation, artifactId) {
14
+ const { binding, target } = authority;
15
+ if (target.storageScopeId !== binding.storageScopeId || target.repoId !== binding.repoId || target.branch !== binding.branch ||
16
+ target.subPath !== binding.subPath || target.principalId !== invocation.actorId ||
17
+ binding.storageScopeId !== invocation.storageScopeId || binding.artifactId !== artifactId)
18
+ throw denied();
19
+ }
20
+ const terminal = (row) => {
21
+ if (row.status === 'ceased')
22
+ liveBusy('stale_session');
23
+ throw new ArtifactOperationError(row.status === 'expired' ? 'gone' : 'access_denied');
24
+ };
25
+ /** The onRevoked event of a revoked row; its epoch is frozen once the row leaves the open set. */
26
+ const revokedEvent = (row) => ({ storageScopeId: row.storageScopeId,
27
+ artifactId: row.artifactId, liveSessionId: row.liveSessionId, bindingGeneration: row.bindingGeneration,
28
+ invitationId: row.invitationId, epoch: row.epoch });
29
+ const cursorOf = (session, offset) => Buffer.from(JSON.stringify([session, offset])).toString('base64url');
30
+ function offsetOf(cursor, session) {
31
+ if (cursor === undefined)
32
+ return 0;
33
+ try {
34
+ const [owner, offset] = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8'));
35
+ if (owner === session && Number.isSafeInteger(offset) && offset > 0)
36
+ return offset;
37
+ }
38
+ catch { /* closed refusal below */ }
39
+ throw new ArtifactOperationError('invalid_request');
40
+ }
41
+ export async function executeLiveInvitation(deps, operation, args, invocation) {
42
+ const port = deps.invitations;
43
+ if (port?.qualified !== true)
44
+ throw new ArtifactOperationError('builder_unavailable');
45
+ const now = (deps.now ?? Date.now)();
46
+ const writer = operation !== 'live_invitations';
47
+ if (writer && (!args.idempotencyKey.trim() || args.idempotencyKey.length > (deps.idempotencyKeyMaxUnits ?? 256))) {
48
+ throw new ArtifactOperationError('invalid_request');
49
+ }
50
+ const authority = await deps.authorize(invocation, args.artifactId);
51
+ admit(authority, invocation, args.artifactId);
52
+ const owner = authority.ownerId === invocation.actorId;
53
+ const identity = { storageScopeId: invocation.storageScopeId, artifactId: authority.binding.artifactId,
54
+ bindingGeneration: authority.binding.generation };
55
+ let principalId;
56
+ if (operation === 'live_invite') {
57
+ if (!owner || !authority.canReadCode || !authority.canWrite || !authority.humanLinked)
58
+ throw denied();
59
+ if (!authority.qualified)
60
+ throw new ArtifactOperationError('builder_unavailable');
61
+ principalId = await port.resolvePrincipal(invocation.storageScopeId, args.userRef);
62
+ if (!principalId)
63
+ throw denied();
64
+ if (principalId === authority.ownerId)
65
+ throw new ArtifactOperationError('invalid_request');
66
+ const invitee = await deps.authorize({ ...invocation, actorId: principalId }, args.artifactId);
67
+ if (!invitee.canReadCode || !invitee.humanLinked || invitee.binding.generation !== identity.bindingGeneration)
68
+ throw denied();
69
+ }
70
+ if (operation === 'live_accept_invitation' && (!authority.canReadCode || !authority.humanLinked))
71
+ throw denied();
72
+ const command = writer ? { actorId: invocation.actorId, key: args.idempotencyKey,
73
+ hash: orderedDigest({ operation, args }), operation } : undefined;
74
+ let revoked;
75
+ const result = await deps.store.transaction(identity, async (tx) => {
76
+ const ledger = tx.invitations;
77
+ if (!ledger)
78
+ throw new ArtifactOperationError('capability_unselected');
79
+ if (command) {
80
+ const prior = await tx.receipt(command.actorId, command.key);
81
+ if (prior && prior.hash !== command.hash)
82
+ throw new ArtifactOperationError('command_conflict');
83
+ if (prior) {
84
+ // A replayed revoke re-invokes the idempotent onRevoked: the first push may have failed after the commit.
85
+ if (operation === 'live_revoke_invitation' && prior.result.status === 'revoked') {
86
+ const row = (await ledger.list()).find(entry => entry.invitationId === args.invitationId && entry.status === 'revoked');
87
+ if (row)
88
+ revoked = revokedEvent(row);
89
+ }
90
+ return { ...prior.result, replayed: true };
91
+ }
92
+ }
93
+ const rows = await sweep(tx, identity, now, writer);
94
+ const session = currentSession(tx.record);
95
+ let out;
96
+ if (operation === 'live_invite') {
97
+ if (!session || args.liveSessionId !== session)
98
+ liveBusy('stale_session');
99
+ const opened = rows.filter(row => open(row) && row.liveSessionId === session);
100
+ if (opened.some(row => row.principalId === principalId))
101
+ liveBusy('active_session');
102
+ if (opened.length >= LIVE_INVITATIONS_OPEN_MAX)
103
+ throw new ArtifactOperationError('limit_exceeded');
104
+ let epoch = await ledger.epoch(identity.bindingGeneration, session);
105
+ if (epoch === 0) {
106
+ epoch = 1;
107
+ await ledger.setEpoch(identity.bindingGeneration, session, epoch);
108
+ }
109
+ const row = { ...identity, liveSessionId: session, invitationId: randomUUID(), principalId: principalId,
110
+ createdBy: invocation.actorId, status: 'pending', epoch, expiresAt: iso(now + args.expiresInSeconds * 1000),
111
+ acceptedAt: null, revokedAt: null, createdAt: iso(now), rowVersion: 1 };
112
+ await ledger.save(row);
113
+ out = { invitationId: row.invitationId, status: 'pending', liveSessionId: row.liveSessionId,
114
+ bindingGeneration: row.bindingGeneration, epoch, expiresAt: row.expiresAt };
115
+ }
116
+ else if (operation === 'live_invitations') {
117
+ const sessionId = args.liveSessionId ?? session;
118
+ const own = rows.filter(row => row.liveSessionId === sessionId);
119
+ const visible = owner ? own : own.filter(row => row.principalId === invocation.actorId);
120
+ if (!owner && !visible.length)
121
+ throw denied();
122
+ const generation = own[0]?.bindingGeneration ?? identity.bindingGeneration;
123
+ const offset = offsetOf(args.cursor, sessionId);
124
+ return { liveSessionId: sessionId, bindingGeneration: generation,
125
+ epoch: sessionId ? await ledger.epoch(generation, sessionId) : 0, rows: visible.slice(offset, offset + PAGE),
126
+ next: offset + PAGE < visible.length ? cursorOf(sessionId, offset + PAGE) : null };
127
+ }
128
+ else {
129
+ const row = rows.find(entry => entry.invitationId === args.invitationId);
130
+ if (!row)
131
+ throw denied();
132
+ if (operation === 'live_accept_invitation') {
133
+ if (row.principalId !== invocation.actorId)
134
+ throw denied();
135
+ if (row.status === 'active')
136
+ liveBusy('active_session');
137
+ if (row.status !== 'pending')
138
+ terminal(row);
139
+ Object.assign(row, { status: 'active', acceptedAt: iso(now), rowVersion: row.rowVersion + 1 });
140
+ await ledger.save(row);
141
+ out = { invitationId: row.invitationId, status: 'active', liveSessionId: row.liveSessionId, epoch: row.epoch,
142
+ expiresAt: row.expiresAt };
143
+ }
144
+ else {
145
+ if (!owner && row.principalId !== invocation.actorId)
146
+ throw denied();
147
+ if (row.status !== 'revoked') {
148
+ if (!open(row))
149
+ terminal(row);
150
+ const epoch = await ledger.epoch(row.bindingGeneration, row.liveSessionId) + 1;
151
+ await ledger.setEpoch(row.bindingGeneration, row.liveSessionId, epoch);
152
+ for (const other of rows.filter(entry => open(entry) && entry.liveSessionId === row.liveSessionId)) {
153
+ if (other === row)
154
+ Object.assign(other, { status: 'revoked', revokedAt: iso(now) });
155
+ Object.assign(other, { epoch, rowVersion: other.rowVersion + 1 });
156
+ await ledger.save(other);
157
+ }
158
+ revoked = revokedEvent(row);
159
+ }
160
+ out = { invitationId: row.invitationId, status: 'revoked', epoch: row.epoch };
161
+ }
162
+ }
163
+ out.replayed = false;
164
+ await tx.complete(command, out);
165
+ return out;
166
+ });
167
+ if (revoked)
168
+ await port.onRevoked(revoked);
169
+ if (operation !== 'live_invitations')
170
+ return result;
171
+ const { rows, ...page } = result;
172
+ return { ...page, invitations: await Promise.all(rows.map(async (row) => {
173
+ const person = await port.describePrincipal(invocation.storageScopeId, row.principalId);
174
+ const userRef = person?.userRef ?? UNKNOWN_USER_REF;
175
+ return { invitationId: row.invitationId, invitee: { userRef, displayName: person?.displayName ?? userRef },
176
+ status: row.status, expiresAt: row.expiresAt, acceptedAt: row.acceptedAt };
177
+ })) };
178
+ }
@@ -1,3 +1,6 @@
1
- import { type LiveService, type LiveServiceDeps } from './live-contracts.js';
1
+ import { type LiveServiceDeps, type LiveSessionService } from './live-contracts.js';
2
2
  export type * from './live-contracts.js';
3
- export declare function createLiveService(deps: LiveServiceDeps): LiveService;
3
+ export type { LiveInvitationLedger, LiveInvitationRecord, LiveInvitationStatus } from './live-store.js';
4
+ export { LIVE_INVITATIONS_OPEN_MAX } from './live-invitations.js';
5
+ export { LIVE_INVITATION_TOOL_CLASSES } from '../git-tool-definitions.js';
6
+ export declare function createLiveService(deps: LiveServiceDeps): LiveSessionService;
@@ -11,10 +11,20 @@ import { liveBusy, mutateLive } from './live-mutations.js';
11
11
  import { executeLiveCommit } from './live-commit.js';
12
12
  import { settleLiveWorker } from './live-worker.js';
13
13
  import { liveResponse } from './live-contracts.js';
14
+ import { executeLiveInvitation, LIVE_INVITATION_OPERATIONS } from './live-invitations.js';
15
+ import { liveInvitationViews } from './live-invitation-state.js';
16
+ export { LIVE_INVITATIONS_OPEN_MAX } from './live-invitations.js';
17
+ export { LIVE_INVITATION_TOOL_CLASSES } from '../git-tool-definitions.js';
14
18
  export function createLiveService(deps) {
15
19
  const now = deps.now ?? Date.now;
16
- return { async execute(operation, raw, invocation) {
20
+ return { ...liveInvitationViews(deps), async execute(operation, raw, invocation) {
17
21
  const args = structuredClone(raw);
22
+ if (LIVE_INVITATION_OPERATIONS.includes(operation)) {
23
+ if (!matchesSchema(args, GIT_TOOL_DEFINITIONS[`artifacts_${operation}`].inputSchema)) {
24
+ throw new ArtifactOperationError('invalid_request');
25
+ }
26
+ return executeLiveInvitation(deps, operation, args, invocation);
27
+ }
18
28
  if (!['live_write', 'live_read', 'live_reset', 'live_status', 'live_control', 'git_commit'].includes(operation) ||
19
29
  !matchesSchema(args, GIT_TOOL_DEFINITIONS[`artifacts_${operation}`].inputSchema)) {
20
30
  throw new ArtifactOperationError('invalid_request');
@@ -86,6 +86,31 @@ export interface LiveReceipt {
86
86
  hash: string;
87
87
  result: LiveResult;
88
88
  }
89
+ export type LiveInvitationStatus = 'pending' | 'active' | 'revoked' | 'expired' | 'ceased';
90
+ /** Dedicated session-bound live authorization record (A-LIVE v2 §8.2, §9); never a release grant. */
91
+ export interface LiveInvitationRecord extends LiveIdentity {
92
+ liveSessionId: string;
93
+ invitationId: string;
94
+ principalId: string;
95
+ createdBy: string;
96
+ status: LiveInvitationStatus;
97
+ epoch: number;
98
+ expiresAt: string;
99
+ acceptedAt: string | null;
100
+ revokedAt: string | null;
101
+ createdAt: string;
102
+ rowVersion: number;
103
+ }
104
+ /** Invitations of the transaction's artifact, serialized by the same lock as its live record. */
105
+ export interface LiveInvitationLedger {
106
+ /** Every invitation of the artifact in this storage scope, across generations and sessions. */
107
+ list(): Promise<LiveInvitationRecord[]>;
108
+ /** Insert at rowVersion 1, otherwise compare-and-swap on rowVersion - 1. */
109
+ save(record: LiveInvitationRecord): Promise<void>;
110
+ /** The session invitation epoch; 0 before the first invitation. */
111
+ epoch(bindingGeneration: number, liveSessionId: string): Promise<number>;
112
+ setEpoch(bindingGeneration: number, liveSessionId: string, epoch: number): Promise<void>;
113
+ }
89
114
  export interface LiveTransaction {
90
115
  record: LiveDraftRecord | undefined;
91
116
  getObject(ref: string): Promise<LiveEnvelope | undefined>;
@@ -102,6 +127,8 @@ export interface LiveTransaction {
102
127
  actorId: string;
103
128
  now: string;
104
129
  }): Promise<void>;
130
+ /** Live invitations (A-LIVE v2 §9); absent when the adapter does not qualify them. */
131
+ invitations?: LiveInvitationLedger;
105
132
  }
106
133
  export interface LiveStore {
107
134
  transaction<T>(identity: LiveIdentity, action: (tx: LiveTransaction) => Promise<T>): Promise<T>;
@@ -5,12 +5,43 @@ export const LIVE_IDLE_THRESHOLD_MS = 900_000;
5
5
  export const liveIdentityKey = (identity) => JSON.stringify([
6
6
  identity.storageScopeId, identity.artifactId, identity.bindingGeneration
7
7
  ]);
8
+ const openInvitation = (row) => row.status === 'pending' || row.status === 'active';
9
+ function memoryInvitations(identity, rows, epochs) {
10
+ const pending = new Map();
11
+ const pendingEpochs = new Map();
12
+ const epochKey = (generation, session) => JSON.stringify([identity.storageScopeId, identity.artifactId, generation, session]);
13
+ const own = () => [...new Map([...rows, ...pending]).values()].filter(row => row.storageScopeId === identity.storageScopeId && row.artifactId === identity.artifactId);
14
+ const ledger = {
15
+ list: async () => structuredClone(own()),
16
+ async save(row) {
17
+ const prior = pending.get(row.invitationId) ?? rows.get(row.invitationId);
18
+ if (row.storageScopeId !== identity.storageScopeId || row.artifactId !== identity.artifactId || (prior &&
19
+ (prior.storageScopeId !== row.storageScopeId || prior.artifactId !== row.artifactId)))
20
+ throw new ArtifactOperationError('access_denied');
21
+ if ((prior?.rowVersion ?? 0) + 1 !== row.rowVersion)
22
+ throw new ArtifactOperationError('git_live_conflict', { publicDetails: { reason: 'stale_fence' } });
23
+ if (openInvitation(row) && own().some(other => other.invitationId !== row.invitationId && openInvitation(other) &&
24
+ other.bindingGeneration === row.bindingGeneration && other.liveSessionId === row.liveSessionId &&
25
+ other.principalId === row.principalId))
26
+ throw new ArtifactOperationError('git_live_conflict', { publicDetails: { reason: 'active_session' } });
27
+ pending.set(row.invitationId, structuredClone(row));
28
+ },
29
+ epoch: async (generation, session) => pendingEpochs.get(epochKey(generation, session)) ?? epochs.get(epochKey(generation, session)) ?? 0,
30
+ async setEpoch(generation, session, epoch) { pendingEpochs.set(epochKey(generation, session), epoch); },
31
+ };
32
+ const commit = () => { for (const [k, v] of pending)
33
+ rows.set(k, v); for (const [k, v] of pendingEpochs)
34
+ epochs.set(k, v); };
35
+ return { ledger, commit };
36
+ }
8
37
  /** Atomic fake; the persisted representation contains encrypted objects and metadata only. */
9
38
  export function createMemoryLiveStore() {
10
39
  const records = new Map();
11
40
  const objects = new Map();
12
41
  const receipts = new Map();
13
42
  const quota = [];
43
+ const invitations = new Map();
44
+ const epochs = new Map();
14
45
  const mutex = createKeyMutex();
15
46
  return {
16
47
  async sessionIdentity(scope, artifactId, sessionId) {
@@ -23,9 +54,11 @@ export function createMemoryLiveStore() {
23
54
  const pendingObjects = new Map();
24
55
  const pendingReceipts = new Map();
25
56
  const pendingQuota = [];
57
+ const invitationTx = memoryInvitations(identity, invitations, epochs);
26
58
  const receiptKey = (actor, key) => JSON.stringify([identity.storageScopeId, actor, key]);
27
59
  const tx = {
28
60
  record: structuredClone(records.get(id)),
61
+ invitations: invitationTx.ledger,
29
62
  getObject: async (ref) => structuredClone(pendingObjects.get(id + ref) ?? objects.get(id + ref)),
30
63
  async putObject(ref, value) {
31
64
  if (objects.has(id + ref) || pendingObjects.has(id + ref))
@@ -76,6 +109,7 @@ export function createMemoryLiveStore() {
76
109
  for (const [key, receipt] of pendingReceipts)
77
110
  receipts.set(key, receipt);
78
111
  quota.push(...pendingQuota);
112
+ invitationTx.commit();
79
113
  return structuredClone(result);
80
114
  })
81
115
  };
@@ -0,0 +1,101 @@
1
+ -- A-LIVE v2 §8.2/§9 generic live invitations (contract 2026-11-07): session-bound, viewing only, never a release grant.
2
+ -- Additive. The final guard refuses a pre-existing table of the same name with any other column or index, because
3
+ -- CREATE TABLE IF NOT EXISTS alone would silently keep a foreign schema.
4
+ CREATE TABLE IF NOT EXISTS artifacts.live_invitations (
5
+ storage_scope_id text NOT NULL,
6
+ artifact_id uuid NOT NULL,
7
+ binding_generation bigint NOT NULL CHECK (binding_generation > 0),
8
+ live_session_id uuid NOT NULL,
9
+ invitation_id uuid NOT NULL,
10
+ principal_id text NOT NULL,
11
+ created_by text NOT NULL,
12
+ status text NOT NULL CHECK (status IN ('pending', 'active', 'revoked', 'expired', 'ceased')),
13
+ epoch bigint NOT NULL CHECK (epoch > 0),
14
+ expires_at timestamptz NOT NULL,
15
+ accepted_at timestamptz,
16
+ revoked_at timestamptz,
17
+ created_at timestamptz NOT NULL,
18
+ row_version bigint NOT NULL CHECK (row_version > 0),
19
+ CONSTRAINT live_invitations_pkey PRIMARY KEY (invitation_id),
20
+ CONSTRAINT live_invitations_artifact_fk FOREIGN KEY (artifact_id, storage_scope_id)
21
+ REFERENCES artifacts.artifacts (id, storage_scope_id),
22
+ CONSTRAINT live_invitations_invitee_check CHECK (principal_id <> created_by),
23
+ CONSTRAINT live_invitations_accepted_check CHECK ((status <> 'pending' OR accepted_at IS NULL)
24
+ AND (status <> 'active' OR accepted_at IS NOT NULL)),
25
+ CONSTRAINT live_invitations_revoked_check CHECK ((status = 'revoked') = (revoked_at IS NOT NULL))
26
+ );
27
+ CREATE INDEX IF NOT EXISTS live_invitations_session_idx
28
+ ON artifacts.live_invitations (storage_scope_id, artifact_id, binding_generation, live_session_id);
29
+ CREATE UNIQUE INDEX IF NOT EXISTS live_invitations_open_principal_uq
30
+ ON artifacts.live_invitations (storage_scope_id, artifact_id, binding_generation, live_session_id, principal_id)
31
+ WHERE status IN ('pending', 'active');
32
+
33
+ -- One epoch row per live session: a revocation raises it and every open invitation of the session adopts it.
34
+ CREATE TABLE IF NOT EXISTS artifacts.live_invitation_epochs (
35
+ storage_scope_id text NOT NULL,
36
+ artifact_id uuid NOT NULL,
37
+ binding_generation bigint NOT NULL CHECK (binding_generation > 0),
38
+ live_session_id uuid NOT NULL,
39
+ epoch bigint NOT NULL CHECK (epoch > 0),
40
+ CONSTRAINT live_invitation_epochs_pkey PRIMARY KEY (storage_scope_id, artifact_id, binding_generation, live_session_id),
41
+ CONSTRAINT live_invitation_epochs_artifact_fk FOREIGN KEY (artifact_id, storage_scope_id)
42
+ REFERENCES artifacts.artifacts (id, storage_scope_id)
43
+ );
44
+
45
+ -- Mandatory guard: the exact columns (information_schema.columns) and indexes (pg_indexes) of both tables.
46
+ DO $$
47
+ DECLARE drift text;
48
+ BEGIN
49
+ WITH expected (table_name, column_name, data_type, is_nullable) AS (VALUES
50
+ ('live_invitations', 'storage_scope_id', 'text', 'NO'), ('live_invitations', 'artifact_id', 'uuid', 'NO'),
51
+ ('live_invitations', 'binding_generation', 'bigint', 'NO'), ('live_invitations', 'live_session_id', 'uuid', 'NO'),
52
+ ('live_invitations', 'invitation_id', 'uuid', 'NO'), ('live_invitations', 'principal_id', 'text', 'NO'),
53
+ ('live_invitations', 'created_by', 'text', 'NO'), ('live_invitations', 'status', 'text', 'NO'),
54
+ ('live_invitations', 'epoch', 'bigint', 'NO'), ('live_invitations', 'expires_at', 'timestamp with time zone', 'NO'),
55
+ ('live_invitations', 'accepted_at', 'timestamp with time zone', 'YES'),
56
+ ('live_invitations', 'revoked_at', 'timestamp with time zone', 'YES'),
57
+ ('live_invitations', 'created_at', 'timestamp with time zone', 'NO'), ('live_invitations', 'row_version', 'bigint', 'NO'),
58
+ ('live_invitation_epochs', 'storage_scope_id', 'text', 'NO'), ('live_invitation_epochs', 'artifact_id', 'uuid', 'NO'),
59
+ ('live_invitation_epochs', 'binding_generation', 'bigint', 'NO'),
60
+ ('live_invitation_epochs', 'live_session_id', 'uuid', 'NO'), ('live_invitation_epochs', 'epoch', 'bigint', 'NO')
61
+ ), actual AS (
62
+ SELECT c.table_name::text AS table_name, c.column_name::text AS column_name, c.data_type::text AS data_type,
63
+ c.is_nullable::text AS is_nullable
64
+ FROM information_schema.columns c
65
+ WHERE c.table_schema = 'artifacts' AND c.table_name IN ('live_invitations', 'live_invitation_epochs')
66
+ )
67
+ SELECT string_agg(coalesce(e.table_name, a.table_name) || '.' || coalesce(e.column_name, a.column_name), ', ') INTO drift
68
+ FROM expected e FULL JOIN actual a ON a.table_name = e.table_name AND a.column_name = e.column_name
69
+ AND a.data_type = e.data_type AND a.is_nullable = e.is_nullable
70
+ WHERE e.table_name IS NULL OR a.table_name IS NULL;
71
+ IF drift IS NOT NULL THEN
72
+ RAISE EXCEPTION 'live invitations schema mismatch (columns): %', drift;
73
+ END IF;
74
+ WITH expected (table_name, index_name, is_unique, is_partial, key_columns) AS (VALUES
75
+ ('live_invitations', 'live_invitations_pkey', true, false, 'invitation_id'),
76
+ ('live_invitations', 'live_invitations_session_idx', false, false,
77
+ 'storage_scope_id,artifact_id,binding_generation,live_session_id'),
78
+ ('live_invitations', 'live_invitations_open_principal_uq', true, true,
79
+ 'storage_scope_id,artifact_id,binding_generation,live_session_id,principal_id'),
80
+ ('live_invitation_epochs', 'live_invitation_epochs_pkey', true, false,
81
+ 'storage_scope_id,artifact_id,binding_generation,live_session_id')
82
+ ), actual AS (
83
+ SELECT p.tablename::text AS table_name, p.indexname::text AS index_name, x.indisunique AS is_unique,
84
+ x.indpred IS NOT NULL AS is_partial,
85
+ (SELECT string_agg(att.attname::text, ',' ORDER BY k.ord)
86
+ FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
87
+ JOIN pg_attribute att ON att.attrelid = x.indrelid AND att.attnum = k.attnum) AS key_columns
88
+ FROM pg_indexes p
89
+ JOIN pg_class i ON i.relname = p.indexname AND i.relnamespace = 'artifacts'::regnamespace
90
+ JOIN pg_index x ON x.indexrelid = i.oid
91
+ WHERE p.schemaname = 'artifacts' AND p.tablename IN ('live_invitations', 'live_invitation_epochs')
92
+ )
93
+ SELECT string_agg(coalesce(e.table_name, a.table_name) || '.' || coalesce(e.index_name, a.index_name), ', ') INTO drift
94
+ FROM expected e FULL JOIN actual a ON a.table_name = e.table_name AND a.index_name = e.index_name
95
+ AND a.is_unique = e.is_unique AND a.is_partial = e.is_partial AND a.key_columns = e.key_columns
96
+ WHERE e.index_name IS NULL OR a.index_name IS NULL;
97
+ IF drift IS NOT NULL THEN
98
+ RAISE EXCEPTION 'live invitations schema mismatch (indexes): %', drift;
99
+ END IF;
100
+ END
101
+ $$;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/artifacts",
3
- "version": "0.2.21",
3
+ "version": "0.2.23",
4
4
  "description": "Generic configurable artifacts MCP and artifact service: StorageScope/Artifact/Binding/Release model, canonical manifests, object authorization, idempotent intents (spec-v8 §9).",
5
5
  "type": "module",
6
6
  "license": "MIT",