@sentropic/artifacts 0.2.26 → 0.2.28

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 (39) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/adapters/composite-blob.d.ts +35 -0
  3. package/dist/adapters/composite-blob.js +106 -0
  4. package/dist/adapters/db-blob.d.ts +14 -0
  5. package/dist/adapters/db-blob.js +79 -0
  6. package/dist/adapters/local-blob.js +33 -20
  7. package/dist/adapters/postgres-live.js +14 -3
  8. package/dist/adapters/postgres.js +2 -2
  9. package/dist/adapters/s3.js +54 -4
  10. package/dist/adapters/sqlite-blob.d.ts +13 -0
  11. package/dist/adapters/sqlite-blob.js +80 -0
  12. package/dist/adapters/sqlite-store.js +2 -1
  13. package/dist/adapters/sqlite.d.ts +7 -0
  14. package/dist/adapters/sqlite.js +27 -0
  15. package/dist/live-host/worker-client.d.ts +7 -1
  16. package/dist/live-host/worker-client.js +8 -1
  17. package/dist/mcp-core.d.ts +1 -1
  18. package/dist/mcp-core.js +1 -1
  19. package/dist/server/blob-bridge.d.ts +69 -0
  20. package/dist/server/blob-bridge.js +229 -0
  21. package/dist/server/gc.d.ts +4 -2
  22. package/dist/server/gc.js +35 -13
  23. package/dist/server/live-commit.js +3 -3
  24. package/dist/server/live-contracts.d.ts +40 -1
  25. package/dist/server/live-contracts.js +3 -0
  26. package/dist/server/live-invitation-state.d.ts +1 -1
  27. package/dist/server/live-mutations.js +3 -1
  28. package/dist/server/live-service.js +6 -5
  29. package/dist/server/live-store.d.ts +10 -0
  30. package/dist/server/live-store.js +28 -0
  31. package/dist/server/live-worker.d.ts +18 -4
  32. package/dist/server/live-worker.js +235 -40
  33. package/dist/server/preparation-cleanup.d.ts +2 -0
  34. package/dist/server/preparation-cleanup.js +1 -1
  35. package/dist/server/publication.d.ts +34 -2
  36. package/dist/server/publication.js +17 -4
  37. package/migrations/0014_db_blob_placement.sql +32 -0
  38. package/migrations/0014_live_drafts_pending.sql +7 -0
  39. package/package.json +13 -1
@@ -29,8 +29,34 @@ export function openSqliteDatabase(path) {
29
29
  db.exec('PRAGMA foreign_keys = ON');
30
30
  db.exec(DDL_ARTIFACTS);
31
31
  db.exec(DDL_ACTIVATION);
32
+ applySqliteBlobPlacementUpgrade(db);
32
33
  return db;
33
34
  }
35
+ /**
36
+ * CMF-S2 — idempotent DB blob placement upgrade for local files.
37
+ * `CREATE TABLE IF NOT EXISTS` re-runs cleanly on every open; the `blobs`
38
+ * placement column is added only when missing so existing files reopen.
39
+ */
40
+ export function applySqliteBlobPlacementUpgrade(db) {
41
+ db.exec(`CREATE TABLE IF NOT EXISTS blob_bytes (
42
+ storage_scope_id TEXT NOT NULL,
43
+ digest TEXT NOT NULL,
44
+ bytes BLOB NOT NULL,
45
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
46
+ PRIMARY KEY (storage_scope_id, digest)
47
+ )`);
48
+ db.exec(`CREATE TABLE IF NOT EXISTS upload_staging_bytes (
49
+ storage_scope_id TEXT NOT NULL,
50
+ upload_id TEXT NOT NULL,
51
+ bytes BLOB NOT NULL,
52
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
53
+ PRIMARY KEY (storage_scope_id, upload_id)
54
+ )`);
55
+ const columns = db.prepare('SELECT name FROM pragma_table_info(?)').all('blobs');
56
+ if (!columns.some((column) => column.name === 'placement')) {
57
+ db.exec(`ALTER TABLE blobs ADD COLUMN placement TEXT NOT NULL DEFAULT 'object'`);
58
+ }
59
+ }
34
60
  /** Create the serialized writer over one database connection. */
35
61
  export function createSqliteWriter(db) {
36
62
  let tail = Promise.resolve();
@@ -81,6 +107,7 @@ export { createSqliteArtifactStore, createSqliteCommitExecutor };
81
107
  export { createSqliteManagementUnit } from './sqlite-management.js';
82
108
  export { createSqliteActivationStore } from './sqlite-activation.js';
83
109
  export { createLocalBlobStore } from './local-blob.js';
110
+ export { createSqliteDbBlobStore } from './sqlite-blob.js';
84
111
  /** One-call wiring: open a file, create the writer, build store + executor. */
85
112
  export function openSqliteArtifacts(path) {
86
113
  const db = openSqliteDatabase(path);
@@ -17,13 +17,19 @@ export interface LiveWorkerFences {
17
17
  routeEpoch: number;
18
18
  } | undefined>;
19
19
  }
20
- /** Builder answer of a reconcile; the package checks it against its own fences before marking the session LIVE. */
20
+ /** Builder answer of a reconcile; the package checks it against its own fences before marking the session LIVE.
21
+ * A terminal `failure` abandons the revive: the package moves the runtime to DORMANT with `code:reason` as
22
+ * stateDetail and stops re-driving it. Unknown failure shapes are ignored, so older builders stay compatible. */
21
23
  export interface LiveBridgeAck {
22
24
  liveSessionId: string;
23
25
  leaseEpoch: number;
24
26
  routeEpoch: number;
25
27
  revision: string;
26
28
  ready: boolean;
29
+ failure?: {
30
+ code: string;
31
+ reason: string;
32
+ };
27
33
  }
28
34
  export interface LiveWorkerClientOptions {
29
35
  /** Builder base URL (https, no query or fragment); absent keeps every call closed with builder_unavailable. */
@@ -54,7 +54,14 @@ function parseAck(raw) {
54
54
  || !count(r.routeEpoch) || typeof r.revision !== 'string' || !REVISION.test(r.revision) || typeof r.ready !== 'boolean') {
55
55
  throw new ArtifactOperationError('provider_unavailable');
56
56
  }
57
- return { liveSessionId: r.liveSessionId, leaseEpoch: r.leaseEpoch, routeEpoch: r.routeEpoch, revision: r.revision, ready: r.ready };
57
+ const ack = { liveSessionId: r.liveSessionId, leaseEpoch: r.leaseEpoch, routeEpoch: r.routeEpoch,
58
+ revision: r.revision, ready: r.ready };
59
+ const failure = r.failure;
60
+ if (failure && typeof failure === 'object' && typeof failure.code === 'string' && failure.code &&
61
+ typeof failure.reason === 'string' && failure.reason) {
62
+ ack.failure = { code: failure.code, reason: failure.reason };
63
+ }
64
+ return ack;
58
65
  }
59
66
  /**
60
67
  * HTTP LiveWorkerPort of the Sentropic builder, composed as the package LiveService `worker`. A reconcile reads the
@@ -10,7 +10,7 @@ export { createRadarKeyDerivation } from './server/command-identity.js';
10
10
  export type { ArtifactKeyDerivationBinding } from './server/command-identity.js';
11
11
  export declare const ARTIFACTS_PROVIDER_ID = "sentropic.artifacts";
12
12
  export declare const ARTIFACTS_APP_ID = "sentropic-artifacts";
13
- export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.26";
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.28";
14
14
  export declare const ARTIFACTS_TOOL_NAMES: readonly ["artifacts_get_template", "artifacts_get_api_guide", "artifacts_ensure", "artifacts_publish", "artifacts_create_upload", "artifacts_commit_upload", "artifacts_list", "artifacts_get", "artifacts_get_source", "artifacts_fork", "artifacts_set_access", "artifacts_promote", "artifacts_renew", "artifacts_delete", "artifacts_restore", "artifacts_list_versions", "artifacts_revert", "artifacts_lookup_people", "artifacts_list_access", "artifacts_publish_bundle", "artifacts_revoke_reader_consent", "artifacts_create_upload_page", "artifacts_list_assets", "artifacts_publish_bundle_v2", "artifacts_list_app_sources", "artifacts_fetch_app_source", "artifacts_git_attach", "artifacts_git_commit", "artifacts_git_publish", "artifacts_git_live", "artifacts_live_write", "artifacts_live_read", "artifacts_live_reset", "artifacts_live_status", "artifacts_live_control", "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 {
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.26';
10
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.28';
11
11
  export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
12
12
  // ---------------------------------------------------------------------------
13
13
  // Byte-stable tool definitions (MCP tool-definition stability rule).
@@ -0,0 +1,69 @@
1
+ import { type PublicationBlobStore } from './publication.js';
2
+ export interface BoundedBlobPage {
3
+ readonly maxItems: number;
4
+ readonly maxEncodedBytes: number;
5
+ readonly continuation?: string;
6
+ }
7
+ export interface BoundedBlobKeys {
8
+ readonly keys: string[];
9
+ readonly continuation?: string;
10
+ }
11
+ /** Clone the caller buffer so verification never observes a mutated view. */
12
+ export declare function cloneBlobBytes(bytes: Uint8Array): Uint8Array;
13
+ /**
14
+ * Fail closed before any I/O when the bytes do not name the key digest.
15
+ * Returns the verified digest (`sha256:<hex>`).
16
+ */
17
+ export declare function verifyBytesForKey(key: string, bytes: Uint8Array): string;
18
+ /** Fail closed when stored bytes no longer name their key (CR-2). */
19
+ export declare function verifyStoredBytesForKey(key: string, bytes: Uint8Array): Uint8Array;
20
+ /**
21
+ * CMF-S1 (CR-4) — sealed page-cursor states. `keyset` resumes after a full
22
+ * key (offset-free, so a byte-trimmed page replays exactly); `offset` serves
23
+ * the in-memory fallback for stores without `listKeysPaged`. Composite stores
24
+ * seal their own dual state (see `composite-blob.ts`). States are opaque to
25
+ * callers and bound to their prefix scope: a foreign or tampered cursor is
26
+ * refused, never applied.
27
+ */
28
+ export type BlobPageCursorState = {
29
+ readonly kind: 'keyset';
30
+ readonly after?: string;
31
+ } | {
32
+ readonly kind: 'offset';
33
+ readonly offset: number;
34
+ };
35
+ /** Seal a cursor state for a prefix scope (opaque, integrity-protected). */
36
+ export declare function sealBlobPageCursor(prefix: string, state: BlobPageCursorState): string;
37
+ /** Open a sealed cursor for a prefix scope (rejects foreign/tampered states). */
38
+ export declare function openBlobPageCursor(continuation: string, prefix: string): BlobPageCursorState;
39
+ /**
40
+ * Trim a key list to the encoded-byte budget (CR-4). The first key is always
41
+ * kept (a single key larger than the budget fails closed instead of looping
42
+ * forever); the caller resumes after the last kept key.
43
+ */
44
+ export declare function cutBlobKeysByBudget(keys: readonly string[], maxEncodedBytes: number): {
45
+ kept: string[];
46
+ dropped: number;
47
+ };
48
+ /**
49
+ * Bounded slice of an ordered key list under one prefix (CR-4).
50
+ * The continuation is opaque to callers, bound to its prefix scope, and
51
+ * integrity-tagged: a foreign or tampered cursor is refused, never applied.
52
+ */
53
+ export declare function pageBlobKeys(all: readonly string[], prefix: string, page: BoundedBlobPage): BoundedBlobKeys;
54
+ /**
55
+ * Bounded key enumeration over any blob store (CR-4).
56
+ * Stores with `listKeysPaged` page at the backend (keyset resume, bounded
57
+ * work per call); the rest fall back to `listKeys` + in-memory slicing.
58
+ * Either way every page honors the item and encoded-byte budgets and carries
59
+ * an opaque scope-bound integrity-protected continuation forward.
60
+ */
61
+ export declare function listBlobKeysPaged(store: Pick<PublicationBlobStore, 'listKeys' | 'listKeysPaged'>, prefix: string, page: BoundedBlobPage): Promise<BoundedBlobKeys>;
62
+ /**
63
+ * Wrap an upstream blob store with the bridge guards.
64
+ * putBlob clones first, verifies before any I/O, then delegates to an
65
+ * upstream that implements create-only writes; a conflicting write is
66
+ * settled by read-back: identical bytes are idempotent, different bytes
67
+ * fail closed without overwriting. getBlob verifies digest before serving.
68
+ */
69
+ export declare function createVerifiedBlobStore(upstream: PublicationBlobStore): PublicationBlobStore;
@@ -0,0 +1,229 @@
1
+ /**
2
+ * CMF-S1 — hardened blob bridge (MODULE_STORAGE CR-1/CR-2/CR-4).
3
+ *
4
+ * Additive on the 0.2.x line: the `PublicationBlobStore` shape is unchanged.
5
+ * This module adds the guard every blob write/read passes through on CM:
6
+ * caller-buffer clone before verification (CR-1), sha256-of-bytes against the
7
+ * key digest before any I/O, create-only writes (identical retry idempotent,
8
+ * different bytes refused without touching the stored object), digest-verified
9
+ * reads (CR-2), and bounded key pages with an opaque scope-bound
10
+ * integrity-tagged continuation (CR-4).
11
+ *
12
+ * The page shape is structural with `CommonBoundedPage`
13
+ * (`@sentropic/cluster-mesh` `storage/common-contract.ts`): same fields, no
14
+ * dependency from this package to cluster-mesh.
15
+ */
16
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
17
+ import { blobDigestOfKey } from './publication.js';
18
+ import { assertBlobPrefix } from './blob-prefix.js';
19
+ /** Per-process pagination secret: cursors are unforgeable without it, invalid after restart. */
20
+ const PAGE_MAC_KEY = randomBytes(32);
21
+ const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
22
+ /** Clone the caller buffer so verification never observes a mutated view. */
23
+ export function cloneBlobBytes(bytes) {
24
+ return new Uint8Array(bytes);
25
+ }
26
+ function sha256Hex(bytes) {
27
+ return createHash('sha256').update(bytes).digest('hex');
28
+ }
29
+ /**
30
+ * Fail closed before any I/O when the bytes do not name the key digest.
31
+ * Returns the verified digest (`sha256:<hex>`).
32
+ */
33
+ export function verifyBytesForKey(key, bytes) {
34
+ if (!BLOB_KEY_PATTERN.test(key))
35
+ throw new Error(`invalid blob key: ${key}`);
36
+ const expected = blobDigestOfKey(key);
37
+ const actual = `sha256:${sha256Hex(bytes)}`;
38
+ if (actual !== expected)
39
+ throw new Error(`digest mismatch for blob key ${key}: content ${actual}`);
40
+ return expected;
41
+ }
42
+ /** Fail closed when stored bytes no longer name their key (CR-2). */
43
+ export function verifyStoredBytesForKey(key, bytes) {
44
+ verifyBytesForKey(key, bytes);
45
+ return bytes;
46
+ }
47
+ function cursorTag(prefix, state) {
48
+ return createHmac('sha256', PAGE_MAC_KEY).update(`blob-page/v1:${prefix}\n${state}`).digest('hex');
49
+ }
50
+ /** Seal a cursor state for a prefix scope (opaque, integrity-protected). */
51
+ export function sealBlobPageCursor(prefix, state) {
52
+ const encoded = JSON.stringify(state);
53
+ const cursor = { v: 1, prefix, state: JSON.parse(encoded),
54
+ tag: cursorTag(prefix, encoded) };
55
+ return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
56
+ }
57
+ /** Open a sealed cursor for a prefix scope (rejects foreign/tampered states). */
58
+ export function openBlobPageCursor(continuation, prefix) {
59
+ let parsed;
60
+ try {
61
+ parsed = JSON.parse(Buffer.from(continuation, 'base64url').toString('utf8'));
62
+ }
63
+ catch {
64
+ throw new Error('invalid blob page continuation');
65
+ }
66
+ const state = parsed?.state;
67
+ const validKind = state?.kind === 'keyset' || state?.kind === 'offset';
68
+ const validOffset = state?.kind !== 'offset' || (typeof state.offset === 'number' &&
69
+ Number.isSafeInteger(state.offset) && state.offset >= 0);
70
+ const validAfter = state?.kind !== 'keyset' || state.after === undefined || typeof state.after === 'string';
71
+ if (parsed?.v !== 1 || !validKind || !validOffset || !validAfter || parsed.prefix !== prefix ||
72
+ parsed.tag !== cursorTag(parsed.prefix, JSON.stringify(state))) {
73
+ throw new Error('invalid blob page continuation');
74
+ }
75
+ return state;
76
+ }
77
+ /**
78
+ * Trim a key list to the encoded-byte budget (CR-4). The first key is always
79
+ * kept (a single key larger than the budget fails closed instead of looping
80
+ * forever); the caller resumes after the last kept key.
81
+ */
82
+ export function cutBlobKeysByBudget(keys, maxEncodedBytes) {
83
+ const kept = [];
84
+ let encoded = 0;
85
+ for (const key of keys) {
86
+ const size = Buffer.byteLength(key, 'utf8');
87
+ if (size > maxEncodedBytes)
88
+ throw new Error('blob key exceeds page byte budget');
89
+ if (kept.length > 0 && encoded + size > maxEncodedBytes)
90
+ break;
91
+ kept.push(key);
92
+ encoded += size;
93
+ }
94
+ return { kept, dropped: keys.length - kept.length };
95
+ }
96
+ function encodeCursor(prefix, offset) {
97
+ return sealBlobPageCursor(prefix, { kind: 'offset', offset });
98
+ }
99
+ function decodeCursor(continuation, prefix) {
100
+ const state = openBlobPageCursor(continuation, prefix);
101
+ if (state.kind !== 'offset')
102
+ throw new Error('invalid blob page continuation');
103
+ return state.offset;
104
+ }
105
+ /**
106
+ * Bounded slice of an ordered key list under one prefix (CR-4).
107
+ * The continuation is opaque to callers, bound to its prefix scope, and
108
+ * integrity-tagged: a foreign or tampered cursor is refused, never applied.
109
+ */
110
+ export function pageBlobKeys(all, prefix, page) {
111
+ assertBlobPrefix(prefix);
112
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
113
+ throw new Error('invalid blob page maxItems');
114
+ if (!Number.isSafeInteger(page.maxEncodedBytes) || page.maxEncodedBytes < 1) {
115
+ throw new Error('invalid blob page maxEncodedBytes');
116
+ }
117
+ const offset = page.continuation === undefined ? 0 : decodeCursor(page.continuation, prefix);
118
+ const keys = [];
119
+ let encoded = 0;
120
+ let index = offset;
121
+ for (; index < all.length && keys.length < page.maxItems; index += 1) {
122
+ const key = all[index];
123
+ const size = Buffer.byteLength(key, 'utf8');
124
+ if (keys.length > 0 && encoded + size > page.maxEncodedBytes)
125
+ break;
126
+ if (size > page.maxEncodedBytes)
127
+ throw new Error('blob key exceeds page byte budget');
128
+ keys.push(key);
129
+ encoded += size;
130
+ }
131
+ if (index >= all.length)
132
+ return { keys };
133
+ return { keys, continuation: encodeCursor(prefix, index) };
134
+ }
135
+ /**
136
+ * Bounded key enumeration over any blob store (CR-4).
137
+ * Stores with `listKeysPaged` page at the backend (keyset resume, bounded
138
+ * work per call); the rest fall back to `listKeys` + in-memory slicing.
139
+ * Either way every page honors the item and encoded-byte budgets and carries
140
+ * an opaque scope-bound integrity-protected continuation forward.
141
+ */
142
+ export async function listBlobKeysPaged(store, prefix, page) {
143
+ assertBlobPrefix(prefix);
144
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
145
+ throw new Error('invalid blob page maxItems');
146
+ if (!Number.isSafeInteger(page.maxEncodedBytes) || page.maxEncodedBytes < 1) {
147
+ throw new Error('invalid blob page maxEncodedBytes');
148
+ }
149
+ if (store.listKeysPaged !== undefined) {
150
+ const after = page.continuation === undefined ? undefined : (() => {
151
+ const state = openBlobPageCursor(page.continuation, prefix);
152
+ if (state.kind !== 'keyset')
153
+ throw new Error('invalid blob page continuation');
154
+ if (state.after !== undefined && !state.after.startsWith(prefix)) {
155
+ throw new Error('invalid blob page continuation');
156
+ }
157
+ return state.after;
158
+ })();
159
+ const side = after === undefined
160
+ ? { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes }
161
+ : { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes, startAfter: after };
162
+ const result = await store.listKeysPaged(prefix, side);
163
+ const capped = result.keys.slice(0, page.maxItems);
164
+ const { kept, dropped } = cutBlobKeysByBudget(capped, page.maxEncodedBytes);
165
+ const done = !result.hasMore && dropped === 0 && result.keys.length === capped.length;
166
+ if (kept.length === 0) {
167
+ if (result.keys.length === 0 && !result.hasMore)
168
+ return { keys: [] };
169
+ throw new Error('blob key exceeds page byte budget');
170
+ }
171
+ if (done)
172
+ return { keys: kept };
173
+ return { keys: kept, continuation: sealBlobPageCursor(prefix, { kind: 'keyset', after: kept[kept.length - 1] }) };
174
+ }
175
+ const all = (await store.listKeys(prefix)).filter((key) => key.startsWith(prefix)).sort();
176
+ return pageBlobKeys(all, prefix, page);
177
+ }
178
+ /**
179
+ * Wrap an upstream blob store with the bridge guards.
180
+ * putBlob clones first, verifies before any I/O, then delegates to an
181
+ * upstream that implements create-only writes; a conflicting write is
182
+ * settled by read-back: identical bytes are idempotent, different bytes
183
+ * fail closed without overwriting. getBlob verifies digest before serving.
184
+ */
185
+ export function createVerifiedBlobStore(upstream) {
186
+ return {
187
+ async putBlob(key, bytes) {
188
+ const snapshot = cloneBlobBytes(bytes);
189
+ verifyBytesForKey(key, snapshot);
190
+ try {
191
+ await upstream.putBlob(key, snapshot);
192
+ }
193
+ catch (error) {
194
+ const stored = await upstream.getBlob(key).catch(() => undefined);
195
+ if (stored !== undefined) {
196
+ verifyStoredBytesForKey(key, stored);
197
+ if (stored.byteLength === snapshot.byteLength &&
198
+ sha256Hex(stored) === sha256Hex(snapshot))
199
+ return;
200
+ }
201
+ throw error;
202
+ }
203
+ const stored = await upstream.getBlob(key);
204
+ if (stored === undefined)
205
+ throw new Error(`blob missing after write: ${key}`);
206
+ verifyStoredBytesForKey(key, stored);
207
+ },
208
+ async getBlob(key) {
209
+ const stored = await upstream.getBlob(key);
210
+ if (stored === undefined)
211
+ return undefined;
212
+ return verifyStoredBytesForKey(key, stored);
213
+ },
214
+ async getBlobRange(key, start, endInclusive) {
215
+ return upstream.getBlobRange?.(key, start, endInclusive);
216
+ },
217
+ async listKeys(prefix) {
218
+ return upstream.listKeys(prefix);
219
+ },
220
+ ...(upstream.listKeysPaged === undefined ? {} : {
221
+ async listKeysPaged(prefix, page) {
222
+ return upstream.listKeysPaged(prefix, page);
223
+ },
224
+ }),
225
+ async deleteBlob(key, transaction) {
226
+ await upstream.deleteBlob(key, transaction);
227
+ },
228
+ };
229
+ }
@@ -22,7 +22,7 @@ export interface GcReport {
22
22
  }[];
23
23
  }
24
24
  export interface GcService {
25
- collect(blobs: PublicationBlobStore, prefix: string, claims: DeletionClaimStore): Promise<GcReport>;
25
+ collect(blobs: PublicationBlobStore, prefix: string, claims: DeletionClaimStore, transaction?: FinalizeTxClient): Promise<GcReport>;
26
26
  }
27
27
  /**
28
28
  * Durable exclusive deletion claims (spec r2 A4/A6). Purge claims a digest
@@ -33,7 +33,9 @@ export interface DeletionClaimStore {
33
33
  /** Share this exclusion across claims, reference/pin creation and erasure. */
34
34
  withDigestLock<T>(digest: string, action: (locked: DeletionClaimAccess) => Promise<T>): Promise<T>;
35
35
  /** Exclusive claim; throws when the digest is already claimed. */
36
- claim(digest: string, holder: string): Promise<void>;
36
+ claim(digest: string, holder: string, blobKey?: string): Promise<void>;
37
+ /** Bounded recovery independent of the physical object listing. */
38
+ listPendingKeys?(prefix: string, limit: number): Promise<string[]>;
37
39
  /** Release the claim after the blob is gone (or the purge aborts). */
38
40
  releaseClaim(digest: string): Promise<void>;
39
41
  isClaimed(digest: string): Promise<boolean>;
package/dist/server/gc.js CHANGED
@@ -68,7 +68,7 @@ export function createPostgresGcService(executor, refsForTransaction) {
68
68
  try {
69
69
  const refs = refsForTransaction(client);
70
70
  const claims = createPostgresDeletionClaimStore(client);
71
- const report = await createGcService(refs).collect(blobs, prefix, claims);
71
+ const report = await createGcService(refs).collect(blobs, prefix, claims, client);
72
72
  await client.commit();
73
73
  return report;
74
74
  }
@@ -122,11 +122,11 @@ export function createPostgresDeletionClaimStore(client) {
122
122
  const { rows } = await client.query(`SELECT EXISTS (SELECT 1 FROM artifacts.object_intents WHERE ${predicate}) AS present`, [digest]);
123
123
  return rows[0]?.present === true;
124
124
  },
125
- async claim(digest, holder) {
125
+ async claim(digest, holder, blobKey) {
126
126
  if (await access.isClaimed(digest))
127
127
  throw new Error(`deletion already claimed: ${digest}`);
128
128
  await client.query(`INSERT INTO artifacts.object_intents (id, kind, payload)
129
- VALUES ($1, 'delete-blob', $2::jsonb)`, [crypto.randomUUID(), JSON.stringify({ deletionClaim: true, digest, holder })]);
129
+ VALUES ($1, 'delete-blob', $2::jsonb)`, [crypto.randomUUID(), JSON.stringify({ deletionClaim: true, digest, holder, blobKey })]);
130
130
  },
131
131
  async releaseClaim(digest) {
132
132
  const { rowCount } = await client.query(`UPDATE artifacts.object_intents SET state = 'done', updated_at = now() WHERE ${predicate}`, [digest]);
@@ -136,16 +136,28 @@ export function createPostgresDeletionClaimStore(client) {
136
136
  };
137
137
  const withDigestLock = async (digest, action) => {
138
138
  await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`artifacts-blob:${digest}`]);
139
+ // Always acquire the digest lock before locking a reservation row.
140
+ // Re-check pending state here and persist retry rotation under that lock.
141
+ await client.query(`UPDATE artifacts.object_intents SET updated_at = clock_timestamp()
142
+ WHERE ${predicate}`, [digest]);
139
143
  return action(access);
140
144
  };
141
145
  return { ...access, withDigestLock,
146
+ async listPendingKeys(prefix, limit) {
147
+ // Enumeration must not lock rows: physical listing can reach the same keys.
148
+ const { rows } = await client.query(`SELECT payload->>'blobKey' AS key FROM artifacts.object_intents
149
+ WHERE kind = 'delete-blob' AND state = 'pending' AND payload->>'deletionClaim' = 'true'
150
+ AND starts_with(payload->>'blobKey', $1)
151
+ ORDER BY updated_at, id LIMIT $2`, [prefix, limit]);
152
+ return rows.map(row => row.key);
153
+ },
142
154
  async listClaims() {
143
155
  const { rows } = await client.query(`SELECT id, state, payload->>'digest' AS digest, payload->>'holder' AS holder
144
156
  FROM artifacts.object_intents WHERE kind = 'delete-blob'
145
157
  AND payload->>'deletionClaim' = 'true' ORDER BY created_at, id`, []);
146
158
  return rows.map((row) => ({ claimId: row.id, digest: row.digest, holder: row.holder, state: row.state }));
147
159
  },
148
- claim: (digest, holder) => withDigestLock(digest, (locked) => locked.claim(digest, holder)),
160
+ claim: (digest, holder, blobKey) => withDigestLock(digest, (locked) => locked.claim(digest, holder, blobKey)),
149
161
  releaseClaim: (digest) => withDigestLock(digest, (locked) => locked.releaseClaim(digest)) };
150
162
  }
151
163
  export function createMemoryDeletionClaimStore() {
@@ -207,17 +219,22 @@ export function createClaimGuardedRefs(refs, claims) {
207
219
  /** Create a GC service over an injected refcount store (no driver imports). */
208
220
  export function createGcService(refs) {
209
221
  return {
210
- async collect(blobs, prefix, claims) {
222
+ async collect(blobs, prefix, claims, transaction) {
211
223
  const report = { deleted: [], retained: [], failures: [] };
212
- for (const key of await blobs.listKeys(prefix)) {
213
- let digest;
224
+ const pending = await claims.listPendingKeys?.(prefix, 100) ?? [];
225
+ const candidates = [];
226
+ for (const key of new Set([...pending, ...await blobs.listKeys(prefix)])) {
214
227
  try {
215
- digest = blobDigestOfKey(key);
228
+ candidates.push({ key, digest: blobDigestOfKey(key) });
216
229
  }
217
230
  catch {
218
231
  report.retained.push(key);
219
- continue;
220
232
  }
233
+ }
234
+ // Transactional digest locks survive each deletion: order the entire union,
235
+ // independent of reservation priority, physical listing order and scope.
236
+ candidates.sort((a, b) => a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0);
237
+ for (const { key, digest } of candidates) {
221
238
  if ((await refs.count(digest)) !== 0 || (await refs.isPinned(digest))) {
222
239
  report.retained.push(key);
223
240
  continue;
@@ -226,20 +243,25 @@ export function createGcService(refs) {
226
243
  await claims.withDigestLock(digest, async (locked) => {
227
244
  const alreadyClaimed = await locked.isClaimed(digest);
228
245
  if (!alreadyClaimed)
229
- await locked.claim(digest, 'gc');
246
+ await locked.claim(digest, 'gc', key);
230
247
  let deleted = false;
248
+ let deleting = false;
231
249
  try {
232
250
  if ((await refs.count(digest)) !== 0 || (await refs.isPinned(digest))) {
233
251
  report.retained.push(key);
234
252
  return;
235
253
  }
236
- await blobs.deleteBlob(key);
254
+ deleting = true;
255
+ // Retry a lost DELETE response even when neither placement has bytes left.
256
+ if (!alreadyClaimed || (await blobs.listKeys(key)).includes(key)) {
257
+ await blobs.deleteBlob(key, transaction);
258
+ }
237
259
  deleted = true;
238
260
  report.deleted.push(key);
239
261
  }
240
262
  finally {
241
- // Preserve a purge claim until erasure; always release our GC claim.
242
- if (!alreadyClaimed || deleted)
263
+ // Failed erasure keeps durable debt for the next collection.
264
+ if (deleted || (!alreadyClaimed && !deleting))
243
265
  await locked.releaseClaim(digest);
244
266
  }
245
267
  });
@@ -4,7 +4,7 @@ import { readLiveOverlay } from './live-drafts.js';
4
4
  import { applyLiveMutation, liveTreeSha, validateLiveMutation } from './live-tree.js';
5
5
  import { orderedDigest } from '../profile/json.js';
6
6
  import { liveBusy } from './live-mutations.js';
7
- import { liveResponse } from './live-contracts.js';
7
+ import { liveResponse, liveWritable } from './live-contracts.js';
8
8
  import { LiveCommitUnknownError } from './live-commit-outcome.js';
9
9
  import { isGitSha } from './git-port-policy.js';
10
10
  import { settleLiveWorker } from './live-worker.js';
@@ -21,7 +21,7 @@ export async function executeLiveCommit(input) {
21
21
  throw new ArtifactOperationError('git_live_no_changes');
22
22
  const current = await deps.authorize(invocation, identity.artifactId);
23
23
  if (!current.canReadCode || !current.canWrite || !current.humanLinked || current.ownerId !== invocation.actorId ||
24
- current.binding.generation !== identity.bindingGeneration || current.binding.state !== 'attached')
24
+ current.binding.generation !== identity.bindingGeneration || !liveWritable(current.binding.state))
25
25
  throw new ArtifactOperationError('access_denied');
26
26
  validateLiveMutation(current.repository, current.target, args, 255, 8 * 1024 * 1024);
27
27
  const prior = await tx.receipt(command.actorId, command.key);
@@ -108,7 +108,7 @@ export async function executeLiveCommit(input) {
108
108
  const current = await deps.authorize(invocation, identity.artifactId);
109
109
  if (!current.canReadCode || !current.canWrite || !current.humanLinked || current.ownerId !== invocation.actorId)
110
110
  throw new ArtifactOperationError('access_denied');
111
- if (current.binding.generation !== identity.bindingGeneration || current.binding.state !== 'attached')
111
+ if (current.binding.generation !== identity.bindingGeneration || !liveWritable(current.binding.state))
112
112
  liveBusy('stale_fence');
113
113
  await tx.advanceBinding?.({ expectedHeadSha: intent.expectedHeadSha, commitSha: committed.commitSha,
114
114
  invocationId: intent.invocationId, actorId: invocation.actorId, now: new Date(now).toISOString() });
@@ -19,6 +19,13 @@ export interface LiveAuthority {
19
19
  repository: GitPortRepository;
20
20
  target: GitPortTarget;
21
21
  }
22
+ /** A binding accepts live writers while attached, and after a terminal build failure: the failed job is over, and
23
+ * only edits and a new commit can repair the build (a pending job still refuses with pending_publication). */
24
+ export declare const liveWritable: (state: GitBinding['state']) => boolean;
25
+ export interface LiveWorkerFailure {
26
+ code: string;
27
+ reason: string;
28
+ }
22
29
  export interface LiveWorkerPort {
23
30
  /** Trusted controller reads the authoritative store; no draft key or store API enters the worker. */
24
31
  reconcile(identity: LiveIdentity): Promise<void | {
@@ -27,8 +34,11 @@ export interface LiveWorkerPort {
27
34
  routeEpoch: number;
28
35
  revision: string;
29
36
  ready: boolean;
37
+ failure?: LiveWorkerFailure;
30
38
  }>;
31
- /** Confirms quiescence, durable checkpoint and complete pod/volume decommissioning. */
39
+ /** Confirms quiescence, durable checkpoint and complete pod/volume decommissioning. A total stop
40
+ * answers without touching the runtime when it holds no (or no longer this) session, so a re-driven
41
+ * stop converges instead of replaying a refusal. */
32
42
  stop(input: LiveIdentity & {
33
43
  liveSessionId: string;
34
44
  leaseEpoch: number;
@@ -77,6 +87,32 @@ export interface LiveServiceDeps {
77
87
  gitMessageMaxUnits?: number;
78
88
  idempotencyKeyMaxUnits?: number;
79
89
  invitations?: LiveInvitationPort;
90
+ /** Observer of every worker settle that did not complete: 'failed' carries the typed code of the refusal, 'pending'
91
+ * a worker that is not ready yet. A terminal builder failure also carries its reason and moves the runtime to
92
+ * DORMANT with `code:reason` as stateDetail, so the host stops re-driving it. The host logs it; a throw is ignored. */
93
+ onWorkerEvent?(event: LiveWorkerEvent): void;
94
+ /** Bounded re-drive tuning. Defaults keep the 60 s host timer safe: at most 4 worker calls in flight,
95
+ * each abandoned after 35 s. Hosts with a faster builder may raise the concurrency; a slower one lowers it. */
96
+ redriveConcurrency?: number;
97
+ /** Per-item settle budget in milliseconds for redriveLiveWorkers (default 35000). Never throws: an expired
98
+ * item reports 'failed' with code 'timeout' and stays pending for the next tick, unless it already moved. */
99
+ redriveItemTimeoutMs?: number;
100
+ }
101
+ /** 'settled': the worker confirmed and the runtime moved; 'pending': not ready yet; 'failed': the worker refused,
102
+ * was unreachable, timed out, or abandoned the revive (terminal: the runtime moved to DORMANT with the failure as
103
+ * stateDetail and the host stops re-driving it); 'skipped': nothing to do (no worker, or the session is no longer
104
+ * the current one, or a concurrent settle already moved it). */
105
+ export type LiveWorkerOutcome = 'settled' | 'pending' | 'failed' | 'skipped';
106
+ export interface LiveWorkerEvent {
107
+ identity: LiveIdentity;
108
+ action: 'project' | 'stop';
109
+ outcome: 'failed' | 'pending';
110
+ code?: string;
111
+ reason?: string;
112
+ }
113
+ export interface LiveRedriveItem extends LiveIdentity {
114
+ action: 'project' | 'stop';
115
+ outcome: LiveWorkerOutcome;
80
116
  }
81
117
  export interface LiveService {
82
118
  execute(operation: string, args: Record<string, unknown>, invocation: LiveInvocation): Promise<Record<string, any>>;
@@ -85,6 +121,9 @@ export interface LiveService {
85
121
  export interface LiveSessionService extends LiveService {
86
122
  liveInvitationState(identity: LiveIdentity): Promise<LiveInvitationState>;
87
123
  liveViewer(identity: LiveIdentity, principalId: string): Promise<LiveViewer>;
124
+ /** Settles again every runtime of the scope that still waits for the worker (see redriveLiveWorkers). Never throws
125
+ * for a worker refusal; empty without a worker or without 'LiveStore.pending'. */
126
+ redrive(storageScopeId: string, limit?: number): Promise<LiveRedriveItem[]>;
88
127
  }
89
128
  export declare function liveResponse(record: LiveDraftRecord, currentHeadSha: string, now?: number): Record<string, unknown>;
90
129
  export type LiveSessionTransaction = LiveTransaction;
@@ -1,3 +1,6 @@
1
+ /** A binding accepts live writers while attached, and after a terminal build failure: the failed job is over, and
2
+ * only edits and a new commit can repair the build (a pending job still refuses with pending_publication). */
3
+ export const liveWritable = (state) => state === 'attached' || state === 'build_failed';
1
4
  export function liveResponse(record, currentHeadSha, now = Date.now()) {
2
5
  return { artifactId: record.artifactId, bindingGeneration: record.bindingGeneration,
3
6
  liveRevision: record.revision, revision: record.revision, baseHeadSha: record.baseHeadSha, currentHeadSha,
@@ -6,4 +6,4 @@ export declare const currentLiveSession: (record: LiveDraftRecord | undefined) =
6
6
  /** Projects ceased (other session or generation) and expired invitations; writers persist the transitions. */
7
7
  export declare function sweepInvitations(tx: LiveTransaction, identity: LiveIdentity, now: number, persist: boolean): Promise<LiveInvitationRecord[]>;
8
8
  /** `liveInvitationState` and `liveViewer` read the committed state; they never write. */
9
- export declare function liveInvitationViews(deps: LiveServiceDeps): Omit<LiveSessionService, 'execute'>;
9
+ export declare function liveInvitationViews(deps: LiveServiceDeps): Omit<LiveSessionService, 'execute' | 'redrive'>;