@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,59 @@
1
+ import type { GitBindingStore, GitCodeRightsPort } from './git-contracts.js';
2
+ import type { GitRepositoryRegistry } from './git-registry.js';
3
+ import type { GitPort } from './git-port.js';
4
+ export interface GitToolInvocation {
5
+ actorId: string;
6
+ storageScopeId: string;
7
+ invocationId: string;
8
+ }
9
+ /** Server-resolved artifact authority; never a tool argument. G0 v3 §1.4: owner + host write scope. */
10
+ export interface GitToolAuthority {
11
+ ownerId: string;
12
+ canWrite: boolean;
13
+ }
14
+ export type GitBuildJobState = 'build_pending' | 'building' | 'published' | 'build_failed' | 'cancelled';
15
+ /** G0 v3 §2.6: the persisted job identity; the release CAS and the SHA are never caller-editable later. */
16
+ export interface GitBuildJobRequest {
17
+ storageScopeId: string;
18
+ artifactId: string;
19
+ repoId: string;
20
+ branch: string;
21
+ subPath: string;
22
+ commitSha: string;
23
+ bindingGeneration: number;
24
+ expectedCurrentReleaseId: string | null;
25
+ executor: 'caller' | 'ci' | 'sandbox';
26
+ requestedBy: string;
27
+ idempotencyKey: string;
28
+ }
29
+ /** Build executor port: persists the job before returning its id; the same principal key returns the same job. */
30
+ export interface GitBuildPort {
31
+ /** Executor gate (G0 v3 §3.3, A-LIVE S03): false closes the executor with builder_unavailable. */
32
+ admits(executor: 'caller' | 'ci' | 'sandbox'): Promise<boolean>;
33
+ request(job: GitBuildJobRequest): Promise<{
34
+ jobId: string;
35
+ state: GitBuildJobState;
36
+ }>;
37
+ }
38
+ export interface GitToolsDeps {
39
+ bindings: GitBindingStore;
40
+ registry: GitRepositoryRegistry;
41
+ codeRights: GitCodeRightsPort;
42
+ git: GitPort;
43
+ authorize(invocation: GitToolInvocation, artifactId: string): Promise<GitToolAuthority>;
44
+ /** Absent ⇒ git_publish fails closed with provider_unavailable (503 capability_unavailable). */
45
+ build?: GitBuildPort;
46
+ /** Descriptor output subtree resolved by the host; excluded from writes. */
47
+ outputDir?: string;
48
+ /** Journal of every source read: repoId + resolved SHA (G0 v3 §1.4). */
49
+ journal?: (entry: {
50
+ actorId: string;
51
+ repoId: string;
52
+ commitSha: string;
53
+ invocationId: string;
54
+ }) => void | Promise<void>;
55
+ now?: () => Date;
56
+ }
57
+ export interface GitToolService {
58
+ execute(operation: string, args: Record<string, unknown>, invocation: GitToolInvocation): Promise<Record<string, any>>;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { GitToolInvocation, GitToolsDeps } from './git-tools-contracts.js';
2
+ /** G0 v3 §1.4 fetch_app_source: code right on the resolved repo; the cursor pins the commit across pages. */
3
+ export declare function fetchAppSource(deps: GitToolsDeps, args: Record<string, any>, inv: GitToolInvocation): Promise<{
4
+ repoId: string;
5
+ commitSha: string;
6
+ treeSha: string;
7
+ descriptor: unknown;
8
+ files: ({
9
+ path: string;
10
+ text: string;
11
+ encoding: "utf-8";
12
+ } | {
13
+ path: string;
14
+ base64: string;
15
+ encoding: "base64";
16
+ } | {
17
+ path: string;
18
+ omitted: "too_large" | "over_total_budget";
19
+ })[];
20
+ nextCursor: string | null;
21
+ }>;
@@ -0,0 +1,65 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { assertGitReadRef, assertGitSha } from './git-port-policy.js';
3
+ import { requireCodeRight } from './git-tools-publish.js';
4
+ const missing = (error) => error instanceof ArtifactOperationError &&
5
+ ['not_found', 'git_path_refused'].includes(error.kind);
6
+ function decodeCursor(cursor) {
7
+ if (cursor === undefined)
8
+ return {};
9
+ try {
10
+ const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
11
+ if (typeof value?.s !== 'string' || typeof value.c !== 'string')
12
+ throw new Error();
13
+ assertGitSha(value.s);
14
+ return { sha: value.s, port: value.c };
15
+ }
16
+ catch {
17
+ throw new ArtifactOperationError('invalid_request');
18
+ }
19
+ }
20
+ /** G0 v3 §1.4 fetch_app_source: code right on the resolved repo; the cursor pins the commit across pages. */
21
+ export async function fetchAppSource(deps, args, inv) {
22
+ const cursor = decodeCursor(args.cursor);
23
+ const scope = inv.storageScopeId;
24
+ const binding = args.artifactId === undefined ? undefined : await deps.bindings.get(scope, args.artifactId);
25
+ if (args.artifactId !== undefined && binding && args.repoId !== undefined && args.repoId !== binding.repoId) {
26
+ throw new ArtifactOperationError('invalid_request');
27
+ }
28
+ const repoId = binding?.repoId ?? args.repoId;
29
+ if (repoId === undefined)
30
+ throw new ArtifactOperationError('git_not_attached');
31
+ await requireCodeRight(deps, inv, repoId);
32
+ if (args.artifactId !== undefined && (!binding || binding.state === 'detached')) {
33
+ throw new ArtifactOperationError('git_not_attached');
34
+ }
35
+ const repo = await deps.registry.get(scope, repoId);
36
+ if (!repo)
37
+ throw new ArtifactOperationError('git_repo_not_registered');
38
+ const branch = binding?.branch ?? args.ref;
39
+ if (branch === undefined)
40
+ throw new ArtifactOperationError('invalid_request');
41
+ assertGitReadRef(branch);
42
+ const target = { storageScopeId: scope, repoId, branch, principalId: inv.actorId,
43
+ subPath: binding?.subPath ?? (repo.allowedSubPaths.includes('') ? '' : repo.allowedSubPaths[0] ?? ''),
44
+ outputDir: deps.outputDir ?? 'dist' };
45
+ const commitSha = cursor.sha ?? await deps.git.resolveRef(target, branch);
46
+ assertGitSha(commitSha);
47
+ const page = await deps.git.read(target, { commitSha, ...(args.paths ? { paths: args.paths } : {}),
48
+ ...(cursor.port === undefined ? {} : { cursor: cursor.port }) });
49
+ await deps.journal?.({ actorId: inv.actorId, repoId, commitSha: page.commitSha, invocationId: inv.invocationId });
50
+ let descriptor = null;
51
+ try {
52
+ const file = (await deps.git.read(target, { commitSha, paths: ['sentropic.artifact.json'] })).files[0];
53
+ const parsed = file && 'text' in file ? JSON.parse(file.text) : null;
54
+ if (parsed?.version === 1 && typeof parsed.buildScript === 'string' && typeof parsed.outputDir === 'string' &&
55
+ typeof parsed.lockfilePath === 'string')
56
+ descriptor = parsed;
57
+ }
58
+ catch (error) {
59
+ if (!missing(error) && !(error instanceof SyntaxError))
60
+ throw error;
61
+ }
62
+ return { repoId, commitSha: page.commitSha, treeSha: page.treeSha, descriptor, files: page.files,
63
+ nextCursor: page.nextCursor === null ? null :
64
+ Buffer.from(JSON.stringify({ s: page.commitSha, c: page.nextCursor })).toString('base64url') };
65
+ }
@@ -0,0 +1,13 @@
1
+ import type { GitToolInvocation, GitToolsDeps } from './git-tools-contracts.js';
2
+ /** Owner + host write scope + current code right; refusals carry no git detail. */
3
+ export declare function requireOwner(deps: GitToolsDeps, inv: GitToolInvocation, artifactId: string, write: boolean): Promise<void>;
4
+ /** Current repository code right (G0 v3 §1.4); a port failure is a denial. Runs before any registry or forge call. */
5
+ export declare function requireCodeRight(deps: GitToolsDeps, inv: GitToolInvocation, repoId: string): Promise<void>;
6
+ /** G0 v3 §2.6 git_publish: pin one reachable SHA, persist the build job, move the binding to build_pending. */
7
+ export declare function publishGit(deps: GitToolsDeps, args: Record<string, any>, inv: GitToolInvocation): Promise<{
8
+ artifactId: any;
9
+ jobId: string | null;
10
+ state: string;
11
+ commitSha: any;
12
+ replayed: boolean;
13
+ }>;
@@ -0,0 +1,66 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { assertGitSha } from './git-port-policy.js';
3
+ import { orderedDigest } from '../profile/json.js';
4
+ /** Owner + host write scope + current code right; refusals carry no git detail. */
5
+ export async function requireOwner(deps, inv, artifactId, write) {
6
+ const authority = await deps.authorize(inv, artifactId);
7
+ if (authority.ownerId !== inv.actorId || (write && !authority.canWrite))
8
+ throw new ArtifactOperationError('access_denied');
9
+ }
10
+ /** Current repository code right (G0 v3 §1.4); a port failure is a denial. Runs before any registry or forge call. */
11
+ export async function requireCodeRight(deps, inv, repoId) {
12
+ const allowed = await deps.codeRights.canReadCode({ storageScopeId: inv.storageScopeId, repoId, actorId: inv.actorId })
13
+ .then(value => value === true, () => false);
14
+ if (!allowed)
15
+ throw new ArtifactOperationError('access_denied');
16
+ }
17
+ /** G0 v3 §2.6 git_publish: pin one reachable SHA, persist the build job, move the binding to build_pending. */
18
+ export async function publishGit(deps, args, inv) {
19
+ await requireOwner(deps, inv, args.artifactId, true);
20
+ assertGitSha(args.commitSha);
21
+ const scope = inv.storageScopeId;
22
+ const binding = await deps.bindings.get(scope, args.artifactId);
23
+ if (!binding || binding.state === 'detached')
24
+ throw new ArtifactOperationError('git_not_attached');
25
+ await requireCodeRight(deps, inv, binding.repoId);
26
+ if (binding.state === 'paused')
27
+ throw new ArtifactOperationError('git_binding_paused', { publicDetails: { state: 'paused' } });
28
+ if (binding.state === 'diverged')
29
+ throw new ArtifactOperationError('git_diverged', {
30
+ publicDetails: { headCommitSha: binding.headCommitSha, releaseCommitSha: binding.releaseCommitSha }
31
+ });
32
+ if (binding.state === 'build_pending' && binding.pendingCommitSha === args.commitSha) {
33
+ return { artifactId: args.artifactId, jobId: binding.pendingJobId, state: 'build_pending', commitSha: args.commitSha, replayed: true };
34
+ }
35
+ if (!['attached', 'build_failed'].includes(binding.state)) {
36
+ throw new ArtifactOperationError('git_binding_conflict', { publicDetails: { artifactId: args.artifactId } });
37
+ }
38
+ const build = deps.build;
39
+ if (!build)
40
+ throw new ArtifactOperationError('provider_unavailable');
41
+ if (!await build.admits(binding.executor))
42
+ throw new ArtifactOperationError('builder_unavailable', {
43
+ publicDetails: { executor: binding.executor, reason: 'executor_unavailable' }
44
+ });
45
+ const target = { storageScopeId: scope, repoId: binding.repoId, branch: binding.branch,
46
+ subPath: binding.subPath, principalId: inv.actorId, outputDir: deps.outputDir ?? 'dist' };
47
+ const head = await deps.git.resolveRef(target, binding.branch);
48
+ if (head !== args.commitSha && !await deps.git.isAncestor(target, args.commitSha, head)) {
49
+ throw new ArtifactOperationError('git_sha_not_on_branch', { publicDetails: { commitSha: args.commitSha } });
50
+ }
51
+ const job = await build.request({ storageScopeId: scope, artifactId: args.artifactId, repoId: binding.repoId,
52
+ branch: binding.branch, subPath: binding.subPath, commitSha: args.commitSha, bindingGeneration: binding.generation,
53
+ expectedCurrentReleaseId: args.expectedCurrentReleaseId, executor: binding.executor, requestedBy: inv.actorId,
54
+ idempotencyKey: args.idempotencyKey });
55
+ const now = (deps.now?.() ?? new Date()).toISOString();
56
+ const out = await deps.bindings.write({
57
+ binding: { ...binding, state: 'build_pending', headCommitSha: head, pendingJobId: job.jobId,
58
+ pendingCommitSha: args.commitSha, version: binding.version + 1, updatedAt: now },
59
+ expectedVersion: binding.version, actorId: inv.actorId, idempotencyKey: args.idempotencyKey,
60
+ commandHash: orderedDigest({ operation: 'git_publish', args }),
61
+ event: { action: 'publish', beforeSha: binding.releaseCommitSha ?? undefined, afterSha: args.commitSha,
62
+ invocationId: inv.invocationId }
63
+ });
64
+ return { artifactId: args.artifactId, jobId: out.binding.pendingJobId ?? job.jobId, state: out.binding.state,
65
+ commitSha: args.commitSha, replayed: out.replayed };
66
+ }
@@ -0,0 +1,4 @@
1
+ import type { GitToolService, GitToolsDeps } from './git-tools-contracts.js';
2
+ export type * from './git-tools-contracts.js';
3
+ /** SG3 executors for the three tools routed by createHttpArtifactApp; every port is injected by the host. */
4
+ export declare function createGitToolService(deps: GitToolsDeps): GitToolService;
@@ -0,0 +1,18 @@
1
+ import { GIT_TOOL_DEFINITIONS } from '../git-tool-definitions.js';
2
+ import { matchesSchema } from '../profile/validation.js';
3
+ import { ArtifactOperationError } from './failures.js';
4
+ import { attachGit } from './git-tools-attach.js';
5
+ import { fetchAppSource } from './git-tools-fetch.js';
6
+ import { publishGit } from './git-tools-publish.js';
7
+ const OPERATIONS = { fetch_app_source: fetchAppSource, git_attach: attachGit, git_publish: publishGit };
8
+ /** SG3 executors for the three tools routed by createHttpArtifactApp; every port is injected by the host. */
9
+ export function createGitToolService(deps) {
10
+ return { async execute(operation, raw, invocation) {
11
+ const run = Object.hasOwn(OPERATIONS, operation) ? OPERATIONS[operation] : undefined;
12
+ const args = structuredClone(raw);
13
+ if (!run || !matchesSchema(args, GIT_TOOL_DEFINITIONS[`artifacts_${operation}`].inputSchema)) {
14
+ throw new ArtifactOperationError('invalid_request');
15
+ }
16
+ return run(deps, args, invocation);
17
+ } };
18
+ }
@@ -91,7 +91,8 @@ const GUIDE_V1 = [
91
91
  ' release, for editing. Text mime types come back as `text` with',
92
92
  ' `encoding: "utf8"`; every other file as `base64` with `encoding: "base64"` —',
93
93
  ' never an integer array. The result carries a `guideRef` (tool + version),',
94
- ' never the guide body. Per call: at most 32 files and 256 KiB decoded.',
94
+ ' never the guide body. Per call: at most 32 files; the byte caps are the',
95
+ ' active profile\'s (generic maxima: 1 MiB per file, 2 MiB total).',
95
96
  '- `artifacts_revert`: make an earlier release current again as a NEW',
96
97
  ' release that copies its content — the artifact URL stays stable and',
97
98
  ' history only grows. Purged releases are refused with `release_unavailable`.',
@@ -135,6 +136,30 @@ const GUIDE_V1 = [
135
136
  'available for small text edits; the upload channel exists precisely so',
136
137
  'bulk bytes skip the model.',
137
138
  '',
139
+ '## Git-backed applications',
140
+ '',
141
+ 'When the host registers a repository, build an application from its source',
142
+ 'instead of publishing files (contracts G0 v3 §1.4/§2.6, A-LIVE v2). Only',
143
+ 'the tools your host selected are available:',
144
+ '',
145
+ '1. `artifacts_fetch_app_source {repoId, ref}` (or `{artifactId}` once',
146
+ ' attached): read the repository source at a server-resolved commit,',
147
+ ' with the parsed build descriptor; page with `nextCursor`. Oversized',
148
+ ' files come back as omitted entries.',
149
+ '2. `artifacts_git_attach {artifactId, repoId, baseRef, idempotencyKey}`:',
150
+ ' bind the artifact to a dedicated `artifact/` branch (created from',
151
+ ' `baseRef` when missing). Also pauses, resumes or detaches the binding.',
152
+ '3. `artifacts_git_commit`, then `artifacts_git_publish {artifactId,',
153
+ ' commitSha, expectedCurrentReleaseId, idempotencyKey}`: the server builds',
154
+ ' that commit from the descriptor recipe and publishes only the build',
155
+ ' output after validation. The built output is never committed.',
156
+ '',
157
+ 'Git-backed releases carry the repository build output, so they are not',
158
+ 'bound by the inline `files` caps. Inline `files` publication keeps the',
159
+ 'profile budget (generic maxima: 255 files, 16 MiB per file, 64 MiB per',
160
+ 'release). Source-code rights are per repository and independent of page',
161
+ 'sharing.',
162
+ '',
138
163
  'Tool definitions are stable: names, descriptions and schemas never change',
139
164
  'between versions or profiles, so host permissions (for example claude.ai',
140
165
  '"Always allow") survive upgrades. The active profile revision and result',
@@ -0,0 +1,19 @@
1
+ -- SG3 git_attach, A-LIVE v2 §5.3.1. Additive only: one nullable audit column and one intent table.
2
+ -- branch_created is true only on the attach event that verified creation of its branch.
3
+ ALTER TABLE artifacts.git_binding_events ADD COLUMN branch_created BOOLEAN NULL;
4
+ ALTER TABLE artifacts.git_binding_events ADD CONSTRAINT git_binding_events_branch_created
5
+ CHECK (branch_created IS NULL OR (branch_created AND action = 'attach'));
6
+ -- Written before the forge createBranch, keyed like the replay receipt (scope, actor, key).
7
+ CREATE TABLE artifacts.git_attach_intents (
8
+ storage_scope_id TEXT NOT NULL,
9
+ actor_id TEXT NOT NULL,
10
+ idempotency_key TEXT NOT NULL,
11
+ command_hash TEXT NOT NULL,
12
+ artifact_id UUID NOT NULL,
13
+ repo_id TEXT NOT NULL,
14
+ branch TEXT NOT NULL CHECK (branch LIKE 'artifact/%'),
15
+ base_commit_sha TEXT NOT NULL,
16
+ created_at TIMESTAMPTZ NOT NULL,
17
+ PRIMARY KEY (storage_scope_id, actor_id, idempotency_key),
18
+ FOREIGN KEY (artifact_id, storage_scope_id) REFERENCES artifacts.artifacts(id, storage_scope_id)
19
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/artifacts",
3
- "version": "0.2.18",
3
+ "version": "0.2.20",
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",
@@ -222,6 +222,10 @@
222
222
  "./client": {
223
223
  "types": "./dist/client.d.ts",
224
224
  "import": "./dist/client.js"
225
+ },
226
+ "./live-host": {
227
+ "types": "./dist/live-host/index.d.ts",
228
+ "import": "./dist/live-host/index.js"
225
229
  }
226
230
  },
227
231
  "files": [