@sentropic/artifacts 0.2.23 → 0.2.25

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,59 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.25
4
+
5
+ - `@sentropic/artifacts/live-host` ships a generic pending-build reconcile: `reconcilePendingBuilds`
6
+ sweeps the host jobs stuck in `build_pending`/`building` past a threshold with bounded concurrency
7
+ (the threshold is enforced by the sweep on top of the host filter), and `reconcilePendingBuild`
8
+ reconciles one job on demand for the `live_status`, `git_publish` and `artifacts_get` read paths.
9
+ Both read the builder `GET /v1/builds/:artifactId/:jobId` status
10
+ (`build_pending`/`published`/`build_failed`, `code`/`reason`, `releaseId`) through a host status
11
+ client and apply only allowed transitions: the job moves to `build_failed` (with the builder
12
+ `code`/`reason`, blank codes dropped to the `build_failed` default) or to `published` (with the
13
+ `releaseId` from the stored handoff receipt when the receipts port is wired, else from the builder
14
+ status; without either no release is invented), and the git binding moves from `build_pending` to
15
+ `build_failed` under the version CAS (`server/git-bindings.ts:51`, action `publish`), stamping the
16
+ failure code on the binding `stateDetail`. The binding leads so a crash between the two writes still
17
+ converges; terminal rows are never regressed, rows are never deleted, and disagreements fail closed
18
+ (`receipt-conflict`, `binding-conflict`, `binding-still-pending`, `no-release`): a wired ledger
19
+ without a receipt never publishes on the builder word alone, a `build_failed` status is re-read
20
+ before any write (the builder re-admits the same `jobId` and flips `failed` to `published`
21
+ asynchronously), a version race won by the success path leaves the job alone, and a still-pending
22
+ binding leaves the job pending for the next run. The failure idempotency key binds the binding
23
+ version and pending SHA, so a re-pended `jobId` writes anew instead of replaying the older failure.
24
+ `ReconcileJobStore.markFailed` takes `code`/`reason` as optional hints for hosts without those
25
+ columns. Per-item outages report a bounded `error` stage (`store-error` never claims `unchanged`
26
+ for a committed write). Host ports only (`ReconcileJobStore`, `ReconcileStatusClient`,
27
+ the package `GitBindingStore`, optional `HostLedger.find`); no immo code in the package.
28
+ - `ARTIFACTS_PROVIDER_VERSION` follows the package (0.2.25): the APP-P1 manifest digest changes
29
+ through its version field only (four-tool selection and tool definitions unchanged).
30
+
31
+ ## 0.2.24
32
+
33
+ - `artifacts_live_status` and `artifacts_live_control` start no longer walk the repository tree: they
34
+ resolve the head (`git/ref/heads/{branch}`) and read the base tree SHA from one commit lookup, then
35
+ return `liveRevision`, `currentHeadSha`, `bindingGeneration` and the draft state. Only reads that list
36
+ base entries (`live_read`, `live_write`, `live_status` with `includeDiff`/`cursor`) take the snapshot.
37
+ - The tree walk, the base commit lookup and the fast-forward checks no longer run inside the per-artifact
38
+ advisory-locked draft transaction: the draft fence is read in a short transaction, those forge calls run
39
+ outside the lock, and the locked transaction re-checks the fence (bounded retry, then
40
+ `git_live_conflict`/`transition_busy`). Status, start and reset therefore make no forge call under the lock
41
+ (immo preprod 08/11: 502 on live_status, `idle in transaction`, lock timeouts). Still under the lock:
42
+ the base file reads of a `live_read` page and of `live_write` edits, and the host `authorize` callback.
43
+ - Status, start and reset no longer validate the whole tree (walk limits, entry names); those checks stay
44
+ with the reads that list base entries. A host GitPort without `snapshot` now gets `capability_unselected`
45
+ before the transaction.
46
+ - `@sentropic/artifacts/live-host` ships the host live worker: `createLiveWorkerClient` is the HTTP
47
+ `LiveWorkerPort` over the builder host live API (`v1/live/reconcile`, `v1/live/stop`). Before every
48
+ reconcile it stages the current durable draft: `v1/live/draft/page` for each non-empty page (at most
49
+ 1 MiB of file bytes, 32 pages; overlay at most 255 paths, 1 MiB per file, 8 MiB), then
50
+ `v1/live/draft/seal` (a clean draft is `pages: 0`, `deletes: []`, `treeSha` = the live tree). The
51
+ reconcile body carries `ownerId` from the live record runtime. A refused page or seal stops before the
52
+ reconcile (`provider_unavailable`); an overlay over the limits fails before any call (`limit_exceeded`).
53
+ - Host ports of the worker: `fences` (owner and fences of the runtime), `bindings`, `sessionState` and
54
+ `drafts` (the current draft overlay). `liveStoreFences(store)` and `liveStoreDrafts(store, keys)` supply
55
+ them from the package `LiveStore`. `planLiveDraft`, `stageLiveDraft` and `LIVE_DRAFT_LIMITS` are exported.
56
+
3
57
  ## 0.2.23
4
58
 
5
59
  - `createGitHubForge` resolves a branch through `GET /repos/{owner}/{repo}/git/ref/heads/{branch}`
@@ -0,0 +1,64 @@
1
+ import type { LiveKeyPort } from '../server/live-crypto.js';
2
+ import type { LiveIdentity, LiveOverlayEntry, LiveStore } from '../server/live-store.js';
3
+ /** Builder draft paths of the host live API (s-archi contract 07/11): pages in order, then the seal, both answering 204. */
4
+ export declare const LIVE_DRAFT_PATHS: Readonly<{
5
+ page: "v1/live/draft/page";
6
+ seal: "v1/live/draft/seal";
7
+ }>;
8
+ /** A-LIVE §3.2 overlay (255 paths, 1 MiB per file, 8 MiB), pushed as at most 32 non-empty pages of at most 1 MiB of file bytes. */
9
+ export declare const LIVE_DRAFT_LIMITS: Readonly<{
10
+ paths: 255;
11
+ fileBytes: number;
12
+ totalBytes: number;
13
+ pageBytes: number;
14
+ pages: 32;
15
+ }>;
16
+ /** The current durable draft of a live identity: an overlay on `baseHeadSha` whose resulting tree is `liveTreeSha`. */
17
+ export interface LiveDraftSnapshot {
18
+ readonly revision: string;
19
+ readonly baseHeadSha: string;
20
+ readonly liveTreeSha: string;
21
+ /** `text: null` is a deletion; `mode` is the git tree mode (`100644` or `100755`). */
22
+ readonly overlay: readonly LiveOverlayEntry[];
23
+ }
24
+ /** Host port: the current durable draft of the package store; undefined when the identity has no draft record. */
25
+ export interface LiveDraftSource {
26
+ current(identity: LiveIdentity): Promise<LiveDraftSnapshot | undefined>;
27
+ }
28
+ export interface LiveDraftPageFile {
29
+ readonly path: string;
30
+ readonly mode: number;
31
+ readonly data: string;
32
+ }
33
+ /** Closed PAGE body: artifactId, bindingGeneration, revision, page, files. */
34
+ export interface LiveDraftPageBody {
35
+ readonly artifactId: string;
36
+ readonly bindingGeneration: number;
37
+ readonly revision: string;
38
+ readonly page: number;
39
+ readonly files: readonly LiveDraftPageFile[];
40
+ }
41
+ /** Closed SEAL body: an empty overlay is `pages: 0, deletes: []` with `treeSha` = the live tree. */
42
+ export interface LiveDraftSealBody {
43
+ readonly artifactId: string;
44
+ readonly bindingGeneration: number;
45
+ readonly revision: string;
46
+ readonly pages: number;
47
+ readonly baseHeadSha: string;
48
+ readonly treeSha: string;
49
+ readonly deletes: readonly string[];
50
+ }
51
+ export interface LiveDraftPlan {
52
+ readonly pages: readonly LiveDraftPageBody[];
53
+ readonly seal: LiveDraftSealBody;
54
+ }
55
+ /** Splits a draft into wire pages and deletes within LIVE_DRAFT_LIMITS. A duplicate path or a non-regular mode fails closed. */
56
+ export declare function planLiveDraft(draft: LiveDraftSnapshot, identity: LiveIdentity): LiveDraftPlan;
57
+ /** Posts one body to a builder path and returns its HTTP status; a transport failure throws. */
58
+ export type LiveDraftSend = (path: string, body: unknown) => Promise<{
59
+ status: number;
60
+ }>;
61
+ /** Stages the current draft: every page in order, then the seal. Anything but 204 is provider_unavailable. */
62
+ export declare function stageLiveDraft(source: LiveDraftSource, identity: LiveIdentity, send: LiveDraftSend): Promise<void>;
63
+ /** The LiveDraftSource of a host on the package LiveStore: the decrypted overlay of the current record. */
64
+ export declare function liveStoreDrafts(store: LiveStore, keys: LiveKeyPort, now?: () => number): LiveDraftSource;
@@ -0,0 +1,74 @@
1
+ import { ArtifactOperationError } from '../server/failures.js';
2
+ import { createLiveDraftVault } from '../server/live-drafts.js';
3
+ /** Builder draft paths of the host live API (s-archi contract 07/11): pages in order, then the seal, both answering 204. */
4
+ export const LIVE_DRAFT_PATHS = Object.freeze({ page: 'v1/live/draft/page', seal: 'v1/live/draft/seal' });
5
+ /** A-LIVE §3.2 overlay (255 paths, 1 MiB per file, 8 MiB), pushed as at most 32 non-empty pages of at most 1 MiB of file bytes. */
6
+ export const LIVE_DRAFT_LIMITS = Object.freeze({ paths: 255, fileBytes: 1024 * 1024, totalBytes: 8 * 1024 * 1024,
7
+ pageBytes: 1024 * 1024, pages: 32 });
8
+ /** Regular git file modes only; a symlink or submodule entry cannot be staged. */
9
+ const modeOf = (mode) => (mode === '100644' ? 0o644 : mode === '100755' ? 0o755 : unavailable());
10
+ const limit = () => { throw new ArtifactOperationError('limit_exceeded'); };
11
+ const unavailable = () => { throw new ArtifactOperationError('provider_unavailable'); };
12
+ /** Splits a draft into wire pages and deletes within LIVE_DRAFT_LIMITS. A duplicate path or a non-regular mode fails closed. */
13
+ export function planLiveDraft(draft, identity) {
14
+ const head = { artifactId: identity.artifactId, bindingGeneration: identity.bindingGeneration, revision: draft.revision };
15
+ const pages = [];
16
+ const deletes = [];
17
+ const seen = new Set();
18
+ let files = [];
19
+ let pageBytes = 0;
20
+ let total = 0;
21
+ const flush = () => {
22
+ if (files.length)
23
+ pages.push({ ...head, page: pages.length, files });
24
+ files = [];
25
+ pageBytes = 0;
26
+ };
27
+ for (const entry of draft.overlay) {
28
+ if (seen.has(entry.path))
29
+ unavailable();
30
+ seen.add(entry.path);
31
+ if (seen.size > LIVE_DRAFT_LIMITS.paths)
32
+ limit();
33
+ if (entry.text === null) {
34
+ deletes.push(entry.path);
35
+ continue;
36
+ }
37
+ const mode = modeOf(entry.mode);
38
+ const bytes = Buffer.from(entry.text, 'utf8');
39
+ if (bytes.byteLength > LIVE_DRAFT_LIMITS.fileBytes)
40
+ limit();
41
+ total += bytes.byteLength;
42
+ if (total > LIVE_DRAFT_LIMITS.totalBytes)
43
+ limit();
44
+ if (files.length && pageBytes + bytes.byteLength > LIVE_DRAFT_LIMITS.pageBytes)
45
+ flush();
46
+ files.push({ path: entry.path, mode, data: bytes.toString('base64') });
47
+ pageBytes += bytes.byteLength;
48
+ }
49
+ flush();
50
+ if (pages.length > LIVE_DRAFT_LIMITS.pages)
51
+ limit();
52
+ return { pages, seal: { ...head, pages: pages.length, baseHeadSha: draft.baseHeadSha, treeSha: draft.liveTreeSha, deletes } };
53
+ }
54
+ /** Stages the current draft: every page in order, then the seal. Anything but 204 is provider_unavailable. */
55
+ export async function stageLiveDraft(source, identity, send) {
56
+ const draft = await source.current(identity) ?? unavailable();
57
+ const plan = planLiveDraft(draft, identity);
58
+ for (const page of plan.pages)
59
+ if ((await send(LIVE_DRAFT_PATHS.page, page)).status !== 204)
60
+ unavailable();
61
+ if ((await send(LIVE_DRAFT_PATHS.seal, plan.seal)).status !== 204)
62
+ unavailable();
63
+ }
64
+ /** The LiveDraftSource of a host on the package LiveStore: the decrypted overlay of the current record. */
65
+ export function liveStoreDrafts(store, keys, now) {
66
+ const vault = createLiveDraftVault({ store, keys, ...(now ? { now } : {}) });
67
+ return {
68
+ async current(identity) {
69
+ const draft = await vault.read(identity);
70
+ return draft ? { revision: draft.revision, baseHeadSha: draft.baseHeadSha, liveTreeSha: draft.liveTreeSha, overlay: draft.overlay }
71
+ : undefined;
72
+ },
73
+ };
74
+ }
@@ -8,3 +8,6 @@ export { publicationRecheck, RECHECK_REFUSALS, resolvePendingJob, type AttemptFe
8
8
  export { acceptHandoff, type AcceptOptions, type HostLedger } from './accept.js';
9
9
  export { encodeHandoffRequest, HOST_BUILD_PATHS, JOB_REQUEST_LIFETIME_MS, parseHandoffRequest, refusalFrom, refusalOf, sealJobRequest, verifyJobRequest, type HostBuildRefusal, type HostCandidateFile, type HostHandoffRequest, type HostHandoffResponse, type HostJobClaims, type HostJobRequest, type HostJobResponse, } from './api.js';
10
10
  export { ASSERTION_HEADER, CONTROL_HEADER, FENCE_HEADER, MAX_ASSERTION_SECONDS, MAX_CONTROL_SECONDS, MAX_SKEW_SECONDS, MAX_SOURCE_REVISION_LENGTH, MIN_KEY_BYTES, signLiveAssertion, signLiveControl, signLiveFence, verifyLiveAssertion, verifyLiveControl, verifyLiveFence, type LiveAssertionClaims, type LiveControlClaims, type LiveFenceClaims, type VerifyOptions, } from './live-format.js';
11
+ export { LIVE_DRAFT_LIMITS, LIVE_DRAFT_PATHS, liveStoreDrafts, planLiveDraft, stageLiveDraft, type LiveDraftPageBody, type LiveDraftPageFile, type LiveDraftPlan, type LiveDraftSealBody, type LiveDraftSend, type LiveDraftSnapshot, type LiveDraftSource, } from './draft-stager.js';
12
+ export { createLiveWorkerClient, LIVE_WORKER_PATHS, liveStoreFences, type LiveBridgeAck, type LiveWorkerClientOptions, type LiveWorkerFences, } from './worker-client.js';
13
+ export { parseReconcileBuilderStatus, reconcilePendingBuild, reconcilePendingBuilds, RECONCILE_DEFAULTS, RECONCILE_ERROR_CODES, RECONCILE_ERROR_STAGES, RECONCILE_OUTCOMES, ReconcileError, type ReconcileBuilderStatus, type ReconcileErrorCode, type ReconcileErrorStage, type ReconcileItemResult, type ReconcileJobStore, type ReconcileOptions, type ReconcileOutcome, type ReconcilePendingJob, type ReconcileReport, type ReconcileStatusClient, } from './reconcile.js';
@@ -8,3 +8,6 @@ export { publicationRecheck, RECHECK_REFUSALS, resolvePendingJob, } from './rech
8
8
  export { acceptHandoff } from './accept.js';
9
9
  export { encodeHandoffRequest, HOST_BUILD_PATHS, JOB_REQUEST_LIFETIME_MS, parseHandoffRequest, refusalFrom, refusalOf, sealJobRequest, verifyJobRequest, } from './api.js';
10
10
  export { ASSERTION_HEADER, CONTROL_HEADER, FENCE_HEADER, MAX_ASSERTION_SECONDS, MAX_CONTROL_SECONDS, MAX_SKEW_SECONDS, MAX_SOURCE_REVISION_LENGTH, MIN_KEY_BYTES, signLiveAssertion, signLiveControl, signLiveFence, verifyLiveAssertion, verifyLiveControl, verifyLiveFence, } from './live-format.js';
11
+ export { LIVE_DRAFT_LIMITS, LIVE_DRAFT_PATHS, liveStoreDrafts, planLiveDraft, stageLiveDraft, } from './draft-stager.js';
12
+ export { createLiveWorkerClient, LIVE_WORKER_PATHS, liveStoreFences, } from './worker-client.js';
13
+ export { parseReconcileBuilderStatus, reconcilePendingBuild, reconcilePendingBuilds, RECONCILE_DEFAULTS, RECONCILE_ERROR_CODES, RECONCILE_ERROR_STAGES, RECONCILE_OUTCOMES, ReconcileError, } from './reconcile.js';
@@ -0,0 +1,145 @@
1
+ import type { GitBindingStore } from '../server/git-contracts.js';
2
+ import type { HostLedger } from './accept.js';
3
+ /** Builder status answer of `GET /v1/builds/:artifactId/:jobId` (contract #969): the host-facing
4
+ * `GitBuildJobState` vocabulary, never the builder ledger states. A `published` status carries the
5
+ * receipt `releaseId`; a `build_failed` status carries a closed builder `code` and its `reason`. */
6
+ export interface ReconcileBuilderStatus {
7
+ readonly jobId: string;
8
+ readonly state: 'build_pending' | 'published' | 'build_failed';
9
+ readonly code?: string | undefined;
10
+ readonly reason?: string | undefined;
11
+ readonly releaseId?: string | undefined;
12
+ }
13
+ /** Pending host job the sweep may touch. `updatedAtMs` drives the older-than threshold, enforced by
14
+ * the sweep itself on top of the host filter, so a host that ignores the filter cannot fail fresh jobs. */
15
+ export interface ReconcilePendingJob {
16
+ readonly scopeId: string;
17
+ readonly artifactId: string;
18
+ readonly jobId: string;
19
+ readonly updatedAtMs: number;
20
+ }
21
+ /** Host port: the pending-job store. Updates move a pending job to a terminal state only
22
+ * (compare-and-swap on the pending state); rows are never deleted. */
23
+ export interface ReconcileJobStore {
24
+ /** Jobs still pending, oldest first, bounded by `limit`. The host filters on `updatedAtMs`; the sweep
25
+ * re-checks the threshold itself, so a host that ignores the filter only wastes a status call. */
26
+ listPending(input: {
27
+ nowMs: number;
28
+ olderThanMs: number;
29
+ limit: number;
30
+ }): Promise<readonly ReconcilePendingJob[]>;
31
+ /** Current row, whatever its state; undefined when the host never recorded the job. */
32
+ read(input: {
33
+ scopeId: string;
34
+ artifactId: string;
35
+ jobId: string;
36
+ }): Promise<{
37
+ state: string;
38
+ } | undefined>;
39
+ /** Pending to `build_failed` only; answers whether the row moved. Never regresses a terminal row.
40
+ * `code`/`reason` are hints: a host without those columns ignores them — the failure code is also
41
+ * stamped on the binding `stateDetail` (package store), so it is never lost. */
42
+ markFailed(input: {
43
+ scopeId: string;
44
+ artifactId: string;
45
+ jobId: string;
46
+ code?: string | undefined;
47
+ reason?: string | undefined;
48
+ }): Promise<'updated' | 'already-terminal' | 'not-found'>;
49
+ /** Pending to `published` with the receipt `releaseId`; answers whether the row moved. Never invents a release. */
50
+ markPublished(input: {
51
+ scopeId: string;
52
+ artifactId: string;
53
+ jobId: string;
54
+ releaseId: string;
55
+ }): Promise<'updated' | 'already-terminal' | 'not-found'>;
56
+ }
57
+ /** Host port: the builder status client (immo `createHostBuildApiClient.status`). A transport
58
+ * failure throws (the item is skipped as `status-unavailable`); an unknown job answers undefined.
59
+ * `unknown-job` writes nothing and never converges by design (reconcile never deletes): the host must
60
+ * bound such rows itself (alert or escalate after N sweeps) — e.g. a job recorded but never POSTed. */
61
+ export interface ReconcileStatusClient {
62
+ status(input: {
63
+ scopeId: string;
64
+ artifactId: string;
65
+ jobId: string;
66
+ }): Promise<ReconcileBuilderStatus | undefined>;
67
+ }
68
+ /** Closed per-item outcome of one reconciled job. `store-error` is a per-item host-store outage:
69
+ * the item is skipped and the sweep continues; only invalid options and the initial pending
70
+ * listing throw. */
71
+ export declare const RECONCILE_OUTCOMES: readonly ["job-build-failed", "job-published", "still-pending", "already-terminal", "unknown-job", "status-unavailable", "status-invalid", "no-release", "receipt-conflict", "job-not-found", "binding-still-pending", "binding-conflict", "store-error"];
72
+ export type ReconcileOutcome = typeof RECONCILE_OUTCOMES[number];
73
+ /** Bounded pipeline stage where a `store-error` struck. The stage names the throwing call without
74
+ * exposing store internals, so a perpetual outage is alertable instead of silent. */
75
+ export declare const RECONCILE_ERROR_STAGES: readonly ["list-pending", "read-job", "read-status", "read-receipt", "confirm-status", "write-binding", "write-job", "read-binding"];
76
+ export type ReconcileErrorStage = typeof RECONCILE_ERROR_STAGES[number];
77
+ export interface ReconcileItemResult {
78
+ readonly scopeId: string;
79
+ readonly artifactId: string;
80
+ readonly jobId: string;
81
+ readonly outcome: ReconcileOutcome;
82
+ /** Whether the job row moved to its terminal state. On `store-error` this reports the writes that
83
+ * already committed before the failure, so a committed row is never reported `unchanged`. */
84
+ readonly job: 'updated' | 'unchanged';
85
+ /** Whether the binding moved from `build_pending` to `build_failed`. Unchanged by reconcile on
86
+ * the published path: the host publish transaction owns that transition, and a still-pending
87
+ * binding leaves the job pending too, reported as `binding-still-pending` for the next run. */
88
+ readonly binding: 'updated' | 'unchanged';
89
+ /** Present only on `store-error`: the stage that threw. */
90
+ readonly error?: ReconcileErrorStage | undefined;
91
+ }
92
+ export interface ReconcileReport {
93
+ readonly checked: number;
94
+ readonly updated: number;
95
+ readonly items: readonly ReconcileItemResult[];
96
+ }
97
+ export interface ReconcileOptions {
98
+ /** Pending-job store of the host. */
99
+ readonly jobs: ReconcileJobStore;
100
+ /** Builder status client of the host. */
101
+ readonly status: ReconcileStatusClient;
102
+ /** Package git binding store; only `build_pending` to `build_failed` is ever written. */
103
+ readonly bindings: Pick<GitBindingStore, 'get' | 'write'>;
104
+ /** Optional receipt read: a builder `published` applies the stored receipt `releaseId` first. */
105
+ readonly receipts?: Pick<HostLedger, 'find'> | undefined;
106
+ /** Actor stamped on the binding `publish` event (default `system:reconcile-pending-builds`). */
107
+ readonly systemActorId?: string | undefined;
108
+ readonly now?: () => number;
109
+ /** A pending job older than this is reconciled by the sweep (default 10 min). */
110
+ readonly olderThanMs?: number | undefined;
111
+ /** Upper bound of jobs per sweep (default 100, at most 500). */
112
+ readonly limit?: number | undefined;
113
+ /** Parallel status reads (default 4, at most 8). Store writes stay sequential per job. */
114
+ readonly concurrency?: number | undefined;
115
+ }
116
+ /** Closed reconcile input errors; per-item builder outcomes stay data, never throws. */
117
+ export declare const RECONCILE_ERROR_CODES: readonly ["reconcile_invalid_options"];
118
+ export type ReconcileErrorCode = typeof RECONCILE_ERROR_CODES[number];
119
+ export declare class ReconcileError extends Error {
120
+ readonly code: ReconcileErrorCode;
121
+ constructor(code: ReconcileErrorCode, detail?: string);
122
+ }
123
+ export declare const RECONCILE_DEFAULTS: Readonly<{
124
+ olderThanMs: 600000;
125
+ limit: 100;
126
+ concurrency: 4;
127
+ }>;
128
+ /** Bounded builder status shape (length-bounded strings over the exact contract state set); anything
129
+ * else is `status-invalid` and writes nothing. Extra keys are ignored: the builder is an
130
+ * authenticated peer, so unknown fields stay data, never a refusal. A `published` status may carry
131
+ * `code`/`reason` (ignored); a blank `code`/`reason` is dropped at the call site, and a `build_failed`
132
+ * status without `code` gets the `build_failed` default there. */
133
+ export declare function parseReconcileBuilderStatus(raw: unknown, jobId: string): ReconcileBuilderStatus | undefined;
134
+ /** On-demand reconcile of one pending job for the host read paths (`live_status`, `git_publish`,
135
+ * `artifacts_get`). No age check; terminal rows and unknown builders write nothing. */
136
+ export declare function reconcilePendingBuild(options: ReconcileOptions, key: {
137
+ scopeId: string;
138
+ artifactId: string;
139
+ jobId: string;
140
+ }): Promise<ReconcileItemResult>;
141
+ /** Sweep of the host pending jobs older than the threshold. One per-item failure never aborts the
142
+ * sweep: store and builder outages surface per item as `store-error`/`status-unavailable`. Only
143
+ * invalid options and the initial pending listing throw. Rows are only moved to terminal states,
144
+ * never deleted. */
145
+ export declare function reconcilePendingBuilds(options: ReconcileOptions): Promise<ReconcileReport>;
@@ -0,0 +1,304 @@
1
+ import { orderedDigest } from '../profile/json.js';
2
+ import { ArtifactOperationError } from '../server/failures.js';
3
+ import { jobKey } from './handoff.js';
4
+ /** Closed per-item outcome of one reconciled job. `store-error` is a per-item host-store outage:
5
+ * the item is skipped and the sweep continues; only invalid options and the initial pending
6
+ * listing throw. */
7
+ export const RECONCILE_OUTCOMES = ['job-build-failed', 'job-published', 'still-pending', 'already-terminal',
8
+ 'unknown-job', 'status-unavailable', 'status-invalid', 'no-release', 'receipt-conflict', 'job-not-found',
9
+ 'binding-still-pending', 'binding-conflict', 'store-error'];
10
+ /** Bounded pipeline stage where a `store-error` struck. The stage names the throwing call without
11
+ * exposing store internals, so a perpetual outage is alertable instead of silent. */
12
+ export const RECONCILE_ERROR_STAGES = ['list-pending', 'read-job', 'read-status', 'read-receipt', 'confirm-status',
13
+ 'write-binding', 'write-job', 'read-binding'];
14
+ /** Closed reconcile input errors; per-item builder outcomes stay data, never throws. */
15
+ export const RECONCILE_ERROR_CODES = ['reconcile_invalid_options'];
16
+ export class ReconcileError extends Error {
17
+ code;
18
+ constructor(code, detail) {
19
+ super(detail ? `${code}: ${detail}` : code);
20
+ this.code = code;
21
+ this.name = 'ReconcileError';
22
+ }
23
+ }
24
+ export const RECONCILE_DEFAULTS = Object.freeze({ olderThanMs: 600_000, limit: 100, concurrency: 4 });
25
+ const MAX_LIMIT = 500;
26
+ const MAX_CONCURRENCY = 8;
27
+ /** A builder failure without a machine code is still a builder failure, never an outage: the transport
28
+ * answered. `builder_unavailable` is reserved for thrown transports (`status-unavailable`). */
29
+ const DEFAULT_CODE = 'build_failed';
30
+ const CODE_MAX = 128;
31
+ const REASON_MAX = 1024;
32
+ const RELEASE_MAX = 256;
33
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
34
+ const text = (value, max) => typeof value === 'string' && value.length >= 1 && value.length <= max;
35
+ /** Builder padding carries no signal: a blank code/reason is absent, so the default applies. */
36
+ const clean = (value) => {
37
+ const trimmed = value?.trim();
38
+ return trimmed ? trimmed : undefined;
39
+ };
40
+ /** Bounded builder status shape (length-bounded strings over the exact contract state set); anything
41
+ * else is `status-invalid` and writes nothing. Extra keys are ignored: the builder is an
42
+ * authenticated peer, so unknown fields stay data, never a refusal. A `published` status may carry
43
+ * `code`/`reason` (ignored); a blank `code`/`reason` is dropped at the call site, and a `build_failed`
44
+ * status without `code` gets the `build_failed` default there. */
45
+ export function parseReconcileBuilderStatus(raw, jobId) {
46
+ if (!raw || typeof raw !== 'object')
47
+ return undefined;
48
+ const body = raw;
49
+ if (body.jobId !== jobId || (body.state !== 'build_pending' && body.state !== 'published' && body.state !== 'build_failed')) {
50
+ return undefined;
51
+ }
52
+ if (body.code !== undefined && !text(body.code, CODE_MAX))
53
+ return undefined;
54
+ if (body.reason !== undefined && !text(body.reason, REASON_MAX))
55
+ return undefined;
56
+ if (body.releaseId !== undefined && !text(body.releaseId, RELEASE_MAX))
57
+ return undefined;
58
+ return { jobId, state: body.state,
59
+ ...(body.code !== undefined ? { code: body.code } : {}),
60
+ ...(body.reason !== undefined ? { reason: body.reason } : {}),
61
+ ...(body.releaseId !== undefined ? { releaseId: body.releaseId } : {}) };
62
+ }
63
+ function optionsOf(options) {
64
+ if (!options || typeof options !== 'object')
65
+ throw new ReconcileError('reconcile_invalid_options', 'options are required');
66
+ const ports = options;
67
+ if (!ports.jobs || !ports.status || !ports.bindings) {
68
+ throw new ReconcileError('reconcile_invalid_options', 'jobs, status and bindings are required');
69
+ }
70
+ const olderThanMs = ports.olderThanMs ?? RECONCILE_DEFAULTS.olderThanMs;
71
+ const limit = ports.limit ?? RECONCILE_DEFAULTS.limit;
72
+ const concurrency = ports.concurrency ?? RECONCILE_DEFAULTS.concurrency;
73
+ if (!Number.isFinite(olderThanMs) || olderThanMs < 0)
74
+ throw new ReconcileError('reconcile_invalid_options', 'olderThanMs');
75
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT)
76
+ throw new ReconcileError('reconcile_invalid_options', 'limit');
77
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
78
+ throw new ReconcileError('reconcile_invalid_options', 'concurrency');
79
+ }
80
+ const systemActorId = ports.systemActorId ?? 'system:reconcile-pending-builds';
81
+ if (typeof systemActorId !== 'string' || !systemActorId.trim()) {
82
+ throw new ReconcileError('reconcile_invalid_options', 'systemActorId');
83
+ }
84
+ return { olderThanMs, limit, concurrency, systemActorId };
85
+ }
86
+ /** Binding `build_pending` to `build_failed` under the version CAS (`server/git-bindings.ts:51`,
87
+ * action `publish`). The failure code is stamped on the binding `stateDetail`, so hosts without
88
+ * job `code`/`reason` columns lose nothing. The idempotency key and the command hash bind the
89
+ * binding version and pending SHA: a re-pended job (the same `jobId` admitted again) writes anew
90
+ * instead of replaying the older failure, and the `write()` result is verified so a stale replay
91
+ * can never report `updated`. The `live` key is never written (`validateGitBindingWrite` admits only
92
+ * an absent `live`). A concurrent move answers `binding-conflict`, except when the winner is the
93
+ * success path (`attached`): then the publish owns the job close and the job is left alone. */
94
+ async function failBinding(options, key, stamp) {
95
+ const before = await options.bindings.get(key.scopeId, key.artifactId);
96
+ if (!before || before.state !== 'build_pending' || before.pendingJobId !== key.jobId)
97
+ return 'unchanged';
98
+ const { live: _dropped, ...rest } = before;
99
+ void _dropped;
100
+ const idempotencyKey = `reconcile-build-failed:${key.scopeId}:${key.artifactId}:${key.jobId}:v${before.version}:${before.pendingCommitSha ?? ''}`;
101
+ try {
102
+ const written = await options.bindings.write({
103
+ binding: { ...rest, state: 'build_failed', stateDetail: stamp.code, version: before.version + 1, updatedAt: stamp.nowIso },
104
+ expectedVersion: before.version, actorId: options.systemActorId, idempotencyKey,
105
+ commandHash: orderedDigest({ operation: 'reconcile_build_failed', ...key,
106
+ expectedVersion: before.version, pendingCommitSha: before.pendingCommitSha }),
107
+ event: { action: 'publish', beforeSha: before.releaseCommitSha ?? undefined, afterSha: before.pendingCommitSha ?? undefined,
108
+ invocationId: `reconcile:${key.jobId}` },
109
+ });
110
+ // A replay answers inside `write`: it is only truthful for this exact version and SHA.
111
+ const binding = written.binding;
112
+ if (binding.state !== 'build_failed' || binding.version !== before.version + 1 || binding.pendingJobId !== key.jobId) {
113
+ return 'binding-conflict';
114
+ }
115
+ return 'updated';
116
+ }
117
+ catch (error) {
118
+ // A concurrent move fails the version CAS. Re-read before touching the job: when the winner is
119
+ // the success path, failing the job would close a published artifact as failed.
120
+ if (error instanceof ArtifactOperationError &&
121
+ (error.kind === 'pointer_conflict' || error.kind === 'git_binding_conflict' || error.kind === 'command_conflict')) {
122
+ const current = await options.bindings.get(key.scopeId, key.artifactId);
123
+ if (current && current.state === 'attached')
124
+ return 'binding-moved-on';
125
+ return 'binding-conflict';
126
+ }
127
+ throw error;
128
+ }
129
+ }
130
+ async function reconcileOne(options, key) {
131
+ const nowMs = options.now();
132
+ if (!Number.isFinite(nowMs))
133
+ throw new ReconcileError('reconcile_invalid_options', 'now');
134
+ // Moved flags tracked across the catch: a failure after a committed write reports what committed.
135
+ let job = 'unchanged';
136
+ let binding = 'unchanged';
137
+ let error = 'read-job';
138
+ try {
139
+ const stored = await options.jobs.read(key);
140
+ if (!stored)
141
+ return { ...key, outcome: 'job-not-found', job, binding };
142
+ if (stored.state !== 'build_pending' && stored.state !== 'building')
143
+ return { ...key, outcome: 'already-terminal', job, binding };
144
+ error = 'read-status';
145
+ let answer;
146
+ try {
147
+ answer = await options.status.status(key);
148
+ }
149
+ catch {
150
+ return { ...key, outcome: 'status-unavailable', job, binding };
151
+ }
152
+ if (answer === undefined)
153
+ return { ...key, outcome: 'unknown-job', job, binding };
154
+ let parsed = parseReconcileBuilderStatus(answer, key.jobId);
155
+ if (!parsed)
156
+ return { ...key, outcome: 'status-invalid', job, binding };
157
+ if (parsed.state === 'build_pending')
158
+ return { ...key, outcome: 'still-pending', job, binding };
159
+ // The stored handoff receipt is host proof of publication. When the receipts port is wired it is
160
+ // read once for both terminal branches: a receipt overrides a stale builder `build_failed` (the
161
+ // builder flips `failed` to `published` asynchronously in `record(receipt)`), and a missing
162
+ // receipt fails a builder `published` closed (the builder word alone never publishes a job).
163
+ let receipt;
164
+ if (options.receipts) {
165
+ error = 'read-receipt';
166
+ receipt = await options.receipts.find(jobKey(key));
167
+ if (receipt && !text(receipt.releaseId, RELEASE_MAX))
168
+ return { ...key, outcome: 'receipt-conflict', job, binding };
169
+ // A committed receipt overrides a stale builder `build_failed`: publication happened host-side.
170
+ if (receipt && parsed.state === 'build_failed') {
171
+ parsed = { jobId: key.jobId, state: 'published', releaseId: receipt.releaseId };
172
+ }
173
+ }
174
+ if (parsed.state === 'build_failed' && !receipt) {
175
+ // The builder ledger is not terminal on `failed`: `admit` re-runs the same `jobId` after a
176
+ // failure, and a run in flight may still publish. Re-read the status just before the writes;
177
+ // the fresher answer wins. `published` is terminal builder-side, so it needs no confirm.
178
+ error = 'confirm-status';
179
+ let confirm;
180
+ try {
181
+ confirm = await options.status.status(key);
182
+ }
183
+ catch {
184
+ return { ...key, outcome: 'status-unavailable', job, binding };
185
+ }
186
+ if (confirm === undefined)
187
+ return { ...key, outcome: 'unknown-job', job, binding };
188
+ const fresh = parseReconcileBuilderStatus(confirm, key.jobId);
189
+ if (!fresh)
190
+ return { ...key, outcome: 'status-invalid', job, binding };
191
+ if (fresh.state !== 'build_failed')
192
+ parsed = fresh;
193
+ if (parsed.state === 'build_pending')
194
+ return { ...key, outcome: 'still-pending', job, binding };
195
+ }
196
+ if (parsed.state === 'build_failed') {
197
+ // The binding leads: a crash between the two writes still converges, because a rerun finds the
198
+ // job pending and the binding already failed, then finishes the job move.
199
+ error = 'write-binding';
200
+ const code = clean(parsed.code) ?? DEFAULT_CODE;
201
+ const reason = clean(parsed.reason);
202
+ const failed = await failBinding({ bindings: options.bindings, systemActorId: options.systemActorId }, key, { code, nowIso: new Date(nowMs).toISOString() });
203
+ if (failed === 'binding-moved-on') {
204
+ return { ...key, outcome: 'binding-conflict', job, binding };
205
+ }
206
+ if (failed === 'binding-conflict') {
207
+ error = 'write-job';
208
+ const moved = await options.jobs.markFailed({ ...key, code, ...(reason !== undefined ? { reason } : {}) });
209
+ if (moved === 'updated')
210
+ job = 'updated';
211
+ return { ...key, outcome: 'binding-conflict', job, binding };
212
+ }
213
+ binding = failed;
214
+ error = 'write-job';
215
+ const moved = await options.jobs.markFailed({ ...key, code, ...(reason !== undefined ? { reason } : {}) });
216
+ if (moved === 'not-found')
217
+ return { ...key, outcome: 'job-not-found', job, binding };
218
+ if (moved === 'already-terminal')
219
+ return { ...key, outcome: 'already-terminal', job, binding };
220
+ job = 'updated';
221
+ return { ...key, outcome: 'job-build-failed', job, binding };
222
+ }
223
+ // Builder `published`: the releaseId comes from the stored handoff receipt when the receipts port
224
+ // is wired (a wired ledger without a receipt is `no-release`: the host never published), else
225
+ // from the builder status; without either the job stays pending and no release is invented.
226
+ let releaseId = parsed.releaseId;
227
+ if (options.receipts) {
228
+ if (!receipt)
229
+ return { ...key, outcome: 'no-release', job, binding };
230
+ if (releaseId !== undefined && receipt.releaseId !== releaseId)
231
+ return { ...key, outcome: 'receipt-conflict', job, binding };
232
+ releaseId = receipt.releaseId;
233
+ }
234
+ if (releaseId === undefined)
235
+ return { ...key, outcome: 'no-release', job, binding };
236
+ // The binding is read, never written, on this path — and before the job move: a still-pending
237
+ // binding for this job leaves the job pending too, so the next run reconverges instead of
238
+ // terminalizing the job over a lost binding write. A receipt that disagrees with the binding on
239
+ // the commit SHA fails closed, as `publicationRecheck` would refuse it.
240
+ error = 'read-binding';
241
+ const current = await options.bindings.get(key.scopeId, key.artifactId);
242
+ if (current && current.state === 'build_pending' && current.pendingJobId === key.jobId) {
243
+ if (receipt && receipt.commitSha !== current.pendingCommitSha)
244
+ return { ...key, outcome: 'receipt-conflict', job, binding };
245
+ return { ...key, outcome: 'binding-still-pending', job, binding };
246
+ }
247
+ error = 'write-job';
248
+ const moved = await options.jobs.markPublished({ ...key, releaseId });
249
+ if (moved === 'not-found')
250
+ return { ...key, outcome: 'job-not-found', job, binding };
251
+ if (moved === 'already-terminal')
252
+ return { ...key, outcome: 'already-terminal', job, binding };
253
+ job = 'updated';
254
+ return { ...key, outcome: 'job-published', job, binding };
255
+ }
256
+ catch {
257
+ return { ...key, outcome: 'store-error', job, binding, error };
258
+ }
259
+ }
260
+ /** On-demand reconcile of one pending job for the host read paths (`live_status`, `git_publish`,
261
+ * `artifacts_get`). No age check; terminal rows and unknown builders write nothing. */
262
+ export async function reconcilePendingBuild(options, key) {
263
+ const { systemActorId } = optionsOf(options);
264
+ if (!key || !ID.test(key.scopeId) || !ID.test(key.artifactId) || !ID.test(key.jobId)) {
265
+ throw new ReconcileError('reconcile_invalid_options', 'scopeId, artifactId and jobId are required');
266
+ }
267
+ return reconcileOne({ ...options, now: options.now ?? Date.now, systemActorId }, key);
268
+ }
269
+ /** Sweep of the host pending jobs older than the threshold. One per-item failure never aborts the
270
+ * sweep: store and builder outages surface per item as `store-error`/`status-unavailable`. Only
271
+ * invalid options and the initial pending listing throw. Rows are only moved to terminal states,
272
+ * never deleted. */
273
+ export async function reconcilePendingBuilds(options) {
274
+ const { olderThanMs, limit, concurrency, systemActorId } = optionsOf(options);
275
+ const now = options.now ?? Date.now;
276
+ const nowMs = now();
277
+ const pending = (await options.jobs.listPending({ nowMs, olderThanMs, limit })).slice(0, limit);
278
+ const items = new Array(pending.length);
279
+ let cursor = 0;
280
+ const workers = Array.from({ length: Math.min(concurrency, Math.max(pending.length, 1)) }, async () => {
281
+ for (;;) {
282
+ const index = cursor++;
283
+ if (index >= pending.length)
284
+ return;
285
+ const row = pending[index];
286
+ const key = { scopeId: String(row?.scopeId), artifactId: String(row?.artifactId), jobId: String(row?.jobId) };
287
+ // The sweep validates what the host listed: malformed ids are a host-store defect, surfaced
288
+ // per item instead of aborting the sweep.
289
+ if (!row || !ID.test(row.scopeId) || !ID.test(row.artifactId) || !ID.test(row.jobId)) {
290
+ items[index] = { ...key, outcome: 'store-error', job: 'unchanged', binding: 'unchanged', error: 'list-pending' };
291
+ continue;
292
+ }
293
+ // The threshold is enforced here too, not only by the host filter: a listed job that is not
294
+ // stale yet (or carries no usable age) is left pending without a single builder call.
295
+ if (!Number.isFinite(row.updatedAtMs) || nowMs - row.updatedAtMs < olderThanMs) {
296
+ items[index] = { ...key, outcome: 'still-pending', job: 'unchanged', binding: 'unchanged' };
297
+ continue;
298
+ }
299
+ items[index] = await reconcileOne({ ...options, now, systemActorId }, key);
300
+ }
301
+ });
302
+ await Promise.all(workers);
303
+ return { checked: items.length, updated: items.filter(item => item.job === 'updated' || item.binding === 'updated').length, items };
304
+ }
@@ -0,0 +1,58 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import type { GitBindingStore } from '../server/git-contracts.js';
3
+ import type { LiveInvitationState, LiveWorkerPort } from '../server/live-contracts.js';
4
+ import type { LiveIdentity, LiveStore } from '../server/live-store.js';
5
+ import { type LiveDraftSource } from './draft-stager.js';
6
+ /** Builder control paths of the host live API (s-archi contract 07/11), relative to the builder base URL. */
7
+ export declare const LIVE_WORKER_PATHS: Readonly<{
8
+ reconcile: "v1/live/reconcile";
9
+ stop: "v1/live/stop";
10
+ }>;
11
+ /** Host port: the live runtime of the package store record (owner, session and fences); undefined without a runtime. */
12
+ export interface LiveWorkerFences {
13
+ current(identity: LiveIdentity): Promise<{
14
+ ownerId: string;
15
+ liveSessionId: string;
16
+ leaseEpoch: number;
17
+ routeEpoch: number;
18
+ } | undefined>;
19
+ }
20
+ /** Builder answer of a reconcile; the package checks it against its own fences before marking the session LIVE. */
21
+ export interface LiveBridgeAck {
22
+ liveSessionId: string;
23
+ leaseEpoch: number;
24
+ routeEpoch: number;
25
+ revision: string;
26
+ ready: boolean;
27
+ }
28
+ export interface LiveWorkerClientOptions {
29
+ /** Builder base URL (https, no query or fragment); absent keeps every call closed with builder_unavailable. */
30
+ readonly baseUrl?: string | undefined;
31
+ /** S2S credential of the host (scope artifacts:builder); the builder takes the storage scope from it, never from a body. */
32
+ readonly identity?: {
33
+ authorization(): Promise<string>;
34
+ } | undefined;
35
+ readonly fetch?: typeof fetch;
36
+ /** Page, seal and stop calls (default 10 s). */
37
+ readonly timeoutMs?: number;
38
+ /** Reconcile call (default 30 s): the builder answers within its live wait (25 s in the product builder). */
39
+ readonly reconcileTimeoutMs?: number;
40
+ /** Host port: owner and fences of the current live runtime (see liveStoreFences). */
41
+ readonly fences: LiveWorkerFences;
42
+ /** Host port: the git binding of the artifact; only an attached binding of the exact generation is sent. */
43
+ readonly bindings: Pick<GitBindingStore, 'get'>;
44
+ /** Host port: the session invitation state of the live session (LiveSessionService.liveInvitationState). */
45
+ readonly sessionState: (identity: LiveIdentity, liveSessionId: string) => Promise<LiveInvitationState>;
46
+ /** Host port: the current durable draft, staged (pages, then seal) before every reconcile (see liveStoreDrafts). */
47
+ readonly drafts: LiveDraftSource;
48
+ }
49
+ /** The LiveWorkerFences of a host on the package LiveStore: ownerId and fences come from the record runtime. */
50
+ export declare function liveStoreFences(store: LiveStore): LiveWorkerFences;
51
+ /**
52
+ * HTTP LiveWorkerPort of the Sentropic builder, composed as the package LiveService `worker`. A reconcile reads the
53
+ * attached binding of the exact generation (else git_not_attached before any call), the runtime owner and fences,
54
+ * stages the current draft (pages, then seal), then posts the closed RECONCILE body; a stop posts the closed STOP body.
55
+ * Unconfigured: builder_unavailable. Transport error, non-200 reconcile, non-204 stop or page/seal, malformed ACK:
56
+ * provider_unavailable (the package keeps the durable intent for the fenced reconciliation).
57
+ */
58
+ export declare function createLiveWorkerClient(options: LiveWorkerClientOptions): LiveWorkerPort;
@@ -0,0 +1,143 @@
1
+ import { ArtifactOperationError } from '../server/failures.js';
2
+ import { stageLiveDraft } from './draft-stager.js';
3
+ /** Builder control paths of the host live API (s-archi contract 07/11), relative to the builder base URL. */
4
+ export const LIVE_WORKER_PATHS = Object.freeze({ reconcile: 'v1/live/reconcile', stop: 'v1/live/stop' });
5
+ const MAX_ANSWER_BYTES = 64 * 1024;
6
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
7
+ const REVISION = /^[\x21-\x7e]{1,256}$/;
8
+ /** The LiveWorkerFences of a host on the package LiveStore: ownerId and fences come from the record runtime. */
9
+ export function liveStoreFences(store) {
10
+ return {
11
+ async current(identity) {
12
+ const runtime = await store.transaction(identity, async (tx) => tx.record?.runtime ?? undefined);
13
+ return runtime ? { ownerId: runtime.ownerId, liveSessionId: runtime.liveSessionId, leaseEpoch: runtime.leaseEpoch,
14
+ routeEpoch: runtime.routeEpoch } : undefined;
15
+ },
16
+ };
17
+ }
18
+ function builderBase(raw) {
19
+ const base = new URL(raw);
20
+ if (base.protocol !== 'https:' || base.search || base.hash)
21
+ throw new ArtifactOperationError('builder_unavailable');
22
+ return new URL(base.pathname.endsWith('/') ? base.href : `${base.href}/`);
23
+ }
24
+ /** Reads the answer to completion and parses at most MAX_ANSWER_BYTES of JSON; anything else is undefined. */
25
+ async function boundedJson(response) {
26
+ if (!response.body)
27
+ return undefined;
28
+ const reader = response.body.getReader();
29
+ const chunks = [];
30
+ let size = 0;
31
+ try {
32
+ for (;;) {
33
+ const { done, value } = await reader.read();
34
+ if (done)
35
+ break;
36
+ size += value.byteLength;
37
+ if (size > MAX_ANSWER_BYTES) {
38
+ await reader.cancel().catch(() => undefined);
39
+ return undefined;
40
+ }
41
+ chunks.push(value);
42
+ }
43
+ const text = Buffer.concat(chunks).toString('utf8');
44
+ return text ? JSON.parse(text) : undefined;
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ const count = (value) => Number.isSafeInteger(value) && value >= 0;
51
+ function parseAck(raw) {
52
+ const r = raw;
53
+ if (!r || typeof r !== 'object' || typeof r.liveSessionId !== 'string' || !ID.test(r.liveSessionId) || !count(r.leaseEpoch)
54
+ || !count(r.routeEpoch) || typeof r.revision !== 'string' || !REVISION.test(r.revision) || typeof r.ready !== 'boolean') {
55
+ throw new ArtifactOperationError('provider_unavailable');
56
+ }
57
+ return { liveSessionId: r.liveSessionId, leaseEpoch: r.leaseEpoch, routeEpoch: r.routeEpoch, revision: r.revision, ready: r.ready };
58
+ }
59
+ /**
60
+ * HTTP LiveWorkerPort of the Sentropic builder, composed as the package LiveService `worker`. A reconcile reads the
61
+ * attached binding of the exact generation (else git_not_attached before any call), the runtime owner and fences,
62
+ * stages the current draft (pages, then seal), then posts the closed RECONCILE body; a stop posts the closed STOP body.
63
+ * Unconfigured: builder_unavailable. Transport error, non-200 reconcile, non-204 stop or page/seal, malformed ACK:
64
+ * provider_unavailable (the package keeps the durable intent for the fenced reconciliation).
65
+ */
66
+ export function createLiveWorkerClient(options) {
67
+ const base = options.baseUrl !== undefined && options.identity !== undefined ? builderBase(options.baseUrl) : undefined;
68
+ const bounded = (map, key, value) => {
69
+ if (!map.has(key) && map.size >= 4096)
70
+ map.delete(map.keys().next().value);
71
+ map.set(key, value);
72
+ };
73
+ /** Session epoch floor per binding generation: never lower than an epoch already sent (409 stale_invitation). */
74
+ const floors = new Map();
75
+ const floor = (identity, epoch) => {
76
+ const key = JSON.stringify([identity.storageScopeId, identity.artifactId, identity.bindingGeneration]);
77
+ const next = Math.max(floors.get(key) ?? 0, epoch);
78
+ bounded(floors, key, next);
79
+ return next;
80
+ };
81
+ /** One stage+reconcile or stop at a time per artifact in this client: a late seal never overwrites a newer revision. */
82
+ const lanes = new Map();
83
+ function serial(identity, run) {
84
+ const key = JSON.stringify([identity.storageScopeId, identity.artifactId]);
85
+ const next = (lanes.get(key) ?? Promise.resolve()).then(run);
86
+ const tail = next.then(() => undefined, () => undefined);
87
+ lanes.set(key, tail);
88
+ void tail.then(() => { if (lanes.get(key) === tail)
89
+ lanes.delete(key); });
90
+ return next;
91
+ }
92
+ async function call(path, body, timeoutMs = options.timeoutMs ?? 10_000) {
93
+ if (!base)
94
+ throw new ArtifactOperationError('builder_unavailable');
95
+ try {
96
+ const response = await (options.fetch ?? fetch)(new URL(path, base), { method: 'POST', redirect: 'error',
97
+ headers: { 'content-type': 'application/json', authorization: await options.identity.authorization() },
98
+ body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
99
+ return { status: response.status, payload: await boundedJson(response) };
100
+ }
101
+ catch (error) {
102
+ if (error instanceof ArtifactOperationError)
103
+ throw error;
104
+ throw new ArtifactOperationError('provider_unavailable');
105
+ }
106
+ }
107
+ async function reconcile(identity) {
108
+ const record = await options.bindings.get(identity.storageScopeId, identity.artifactId);
109
+ if (!record || record.state === 'detached' || record.generation !== identity.bindingGeneration) {
110
+ throw new ArtifactOperationError('git_not_attached');
111
+ }
112
+ const fences = await options.fences.current(identity);
113
+ if (!fences)
114
+ throw new ArtifactOperationError('provider_unavailable');
115
+ await stageLiveDraft(options.drafts, identity, (path, body) => call(path, body));
116
+ const session = await options.sessionState(identity, fences.liveSessionId);
117
+ const answer = await call(LIVE_WORKER_PATHS.reconcile, { artifactId: identity.artifactId,
118
+ bindingGeneration: identity.bindingGeneration, ownerId: fences.ownerId, liveSessionId: fences.liveSessionId,
119
+ leaseEpoch: fences.leaseEpoch, routeEpoch: fences.routeEpoch,
120
+ binding: { repoId: record.repoId, branch: record.branch, subPath: record.subPath },
121
+ invitation: { epoch: floor(identity, session.epoch), expiresAt: session.expiresAt } }, options.reconcileTimeoutMs ?? 30_000);
122
+ if (answer.status !== 200)
123
+ throw new ArtifactOperationError('provider_unavailable');
124
+ return parseAck(answer.payload);
125
+ }
126
+ return {
127
+ async reconcile(identity) {
128
+ if (!base)
129
+ throw new ArtifactOperationError('builder_unavailable');
130
+ return serial(identity, () => reconcile(identity));
131
+ },
132
+ async stop(input) {
133
+ if (!base)
134
+ throw new ArtifactOperationError('builder_unavailable');
135
+ await serial(input, async () => {
136
+ const answer = await call(LIVE_WORKER_PATHS.stop, { artifactId: input.artifactId, bindingGeneration: input.bindingGeneration,
137
+ liveSessionId: input.liveSessionId, leaseEpoch: input.leaseEpoch });
138
+ if (answer.status !== 204)
139
+ throw new ArtifactOperationError('provider_unavailable');
140
+ });
141
+ },
142
+ };
143
+ }
@@ -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.23";
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.25";
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.23';
10
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.25';
11
11
  export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
12
12
  // ---------------------------------------------------------------------------
13
13
  // Byte-stable tool definitions (MCP tool-definition stability rule).
@@ -116,69 +116,82 @@ export function createLiveService(deps) {
116
116
  throw new ArtifactOperationError('invalid_request');
117
117
  if (args.expectedHeadSha && args.expectedHeadSha !== head)
118
118
  throw new ArtifactOperationError('git_head_moved', { publicDetails: { expectedHeadSha: args.expectedHeadSha, actualHeadSha: head } });
119
+ if (!deps.git.snapshot && !stop)
120
+ throw new ArtifactOperationError('capability_unselected');
121
+ // Only reads that list base entries walk the tree; status, start and reset need the base tree SHA only.
122
+ const fullTree = operation === 'live_write' || operation === 'live_read' ||
123
+ (operation === 'live_status' && Boolean(args.includeDiff || args.cursor));
119
124
  let action = null;
120
- const result = await deps.store.transaction(identity, async (tx) => {
121
- const current = await deps.authorize(invocation, args.artifactId);
122
- if (!stop && current.binding.generation !== identity.bindingGeneration || current.ownerId !== invocation.actorId &&
123
- !(operation === 'live_read' && current.invited && current.canReadCode) ||
124
- (!stop && !current.canReadCode))
125
- throw new ArtifactOperationError('access_denied');
126
- if (writer && !stop && (!current.canWrite || !current.humanLinked || current.binding.state !== 'attached'))
127
- throw new ArtifactOperationError('access_denied');
128
- if ((operation === 'live_write' || operation === 'live_control' && !stop) && !current.qualified)
129
- throw new ArtifactOperationError('builder_unavailable');
130
- authority = current;
131
- if (command) {
132
- const prior = await tx.receipt(command.actorId, command.key);
133
- if (prior) {
134
- if (prior.hash !== command.hash)
135
- throw new ArtifactOperationError('command_conflict');
136
- return { ...prior.result, replayed: true };
125
+ let result;
126
+ for (let attempt = 0; !result; attempt++) {
127
+ if (attempt === LIVE_PREFETCH_ATTEMPTS)
128
+ liveBusy('transition_busy');
129
+ // Base tree and ancestry forge calls run here, before the per-artifact advisory lock.
130
+ const prefetch = stop ? undefined : await prefetchLiveBase(deps, authority.target, identity, operation, head, fullTree);
131
+ const outcome = await deps.store.transaction(identity, async (tx) => {
132
+ const current = await deps.authorize(invocation, args.artifactId);
133
+ if (!stop && current.binding.generation !== identity.bindingGeneration || current.ownerId !== invocation.actorId &&
134
+ !(operation === 'live_read' && current.invited && current.canReadCode) ||
135
+ (!stop && !current.canReadCode))
136
+ throw new ArtifactOperationError('access_denied');
137
+ if (writer && !stop && (!current.canWrite || !current.humanLinked || current.binding.state !== 'attached'))
138
+ throw new ArtifactOperationError('access_denied');
139
+ if ((operation === 'live_write' || operation === 'live_control' && !stop) && !current.qualified)
140
+ throw new ArtifactOperationError('builder_unavailable');
141
+ authority = current;
142
+ if (command) {
143
+ const prior = await tx.receipt(command.actorId, command.key);
144
+ if (prior) {
145
+ if (prior.hash !== command.hash)
146
+ throw new ArtifactOperationError('command_conflict');
147
+ return { ...prior.result, replayed: true };
148
+ }
137
149
  }
138
- }
139
- const baseSha = tx.record?.changedPaths ? tx.record.baseHeadSha : head;
140
- if (!deps.git.snapshot && !stop)
141
- throw new ArtifactOperationError('capability_unselected');
142
- const base = stop ? { treeSha: tx.record?.baseTreeSha ?? '', entries: [] } : await deps.git.snapshot(authority.target, operation === 'live_reset' ? head : baseSha);
143
- if (!tx.record)
144
- tx.record = cleanLiveRecord(identity, head, base.treeSha, now());
145
- const record = tx.record;
146
- if (!stop && operation !== 'live_reset' && record.expiresAt && Date.parse(record.expiresAt) <= now())
147
- throw new ArtifactOperationError('git_live_draft_expired');
148
- if (!stop && record.latestVerifiedHeadSha !== head) {
149
- const fastForward = await deps.git.isAncestor(authority.target, record.latestVerifiedHeadSha, head);
150
- if (!fastForward && writer)
151
- throw new ArtifactOperationError('git_diverged');
152
- if (fastForward) {
153
- record.latestVerifiedHeadSha = head;
154
- record.progressSeq++;
155
- record.lastProgressEventId = 'head:' + head;
150
+ if (prefetch && !prefetch.covers(tx.record))
151
+ return LIVE_PREFETCH_STALE;
152
+ const base = stop ? { treeSha: tx.record?.baseTreeSha ?? '', entries: [] } : prefetch.base();
153
+ if (!tx.record)
154
+ tx.record = cleanLiveRecord(identity, head, base.treeSha, now());
155
+ const record = tx.record;
156
+ if (!stop && operation !== 'live_reset' && record.expiresAt && Date.parse(record.expiresAt) <= now())
157
+ throw new ArtifactOperationError('git_live_draft_expired');
158
+ if (!stop && record.latestVerifiedHeadSha !== head) {
159
+ const fastForward = prefetch.ancestor(record.latestVerifiedHeadSha);
160
+ if (!fastForward && writer)
161
+ throw new ArtifactOperationError('git_diverged');
162
+ if (fastForward) {
163
+ record.latestVerifiedHeadSha = head;
164
+ record.progressSeq++;
165
+ record.lastProgressEventId = 'head:' + head;
166
+ }
156
167
  }
157
- }
158
- if (!stop && record.baseHeadSha !== head && !record.changedPaths) {
159
- if (!await deps.git.isAncestor(authority.target, record.baseHeadSha, head))
168
+ if (!stop && record.baseHeadSha !== head && !record.changedPaths) {
169
+ if (!prefetch.ancestor(record.baseHeadSha))
170
+ throw new ArtifactOperationError('git_diverged');
171
+ Object.assign(record, { revision: randomUUID(), baseHeadSha: head, baseTreeSha: base.treeSha, liveTreeSha: base.treeSha,
172
+ });
173
+ }
174
+ if (operation === 'live_reset' && record.baseHeadSha !== head &&
175
+ !prefetch.ancestor(record.baseHeadSha))
160
176
  throw new ArtifactOperationError('git_diverged');
161
- Object.assign(record, { revision: randomUUID(), baseHeadSha: head, baseTreeSha: base.treeSha, liveTreeSha: base.treeSha,
162
- });
163
- }
164
- if (operation === 'live_reset' && record.baseHeadSha !== head &&
165
- !await deps.git.isAncestor(authority.target, record.baseHeadSha, head))
166
- throw new ArtifactOperationError('git_diverged');
167
- const overlay = stop ? [] : operation === 'live_reset' && expired ? [] : await readLiveOverlay(tx, deps.keys);
168
- if (operation === 'live_read' || operation === 'live_status')
169
- return { ...liveResponse(record, head),
170
- dirty: record.changedPaths > 0, changedPaths: record.changedPaths, draftBytes: record.draftBytes,
171
- jobId: binding.pendingJobId, publicationIntent: record.progressSeq > record.publicationBaselineSeq && binding.autoPublish ? 'deferred' : null,
172
- retentionWarning: record.expiresAt && Date.parse(record.expiresAt) - now() < 86400000 ? 'expires_within_24_hours' : null,
173
- ...(operation === 'live_read' || args.includeDiff || args.cursor ? await readLivePage({ git: deps.git, authority, record,
174
- overlay, base, args, invocation, kind: operation === 'live_read' ? 'read' : 'diff', now: now() }) : { nextCursor: null }) };
175
- if (stop && !authority.canReadCode)
176
- args.expectedLiveRevision = record.revision;
177
- const mutation = await mutateLive({ deps, tx, authority, operation, args, base, overlay, currentHeadSha: head, now: now() });
178
- action = mutation.action;
179
- await tx.complete(command, { ...mutation.result, revision: tx.record.revision });
180
- return mutation.result;
181
- });
177
+ const overlay = stop ? [] : operation === 'live_reset' && expired ? [] : await readLiveOverlay(tx, deps.keys);
178
+ if (operation === 'live_read' || operation === 'live_status')
179
+ return { ...liveResponse(record, head),
180
+ dirty: record.changedPaths > 0, changedPaths: record.changedPaths, draftBytes: record.draftBytes,
181
+ jobId: binding.pendingJobId, publicationIntent: record.progressSeq > record.publicationBaselineSeq && binding.autoPublish ? 'deferred' : null,
182
+ retentionWarning: record.expiresAt && Date.parse(record.expiresAt) - now() < 86400000 ? 'expires_within_24_hours' : null,
183
+ ...(operation === 'live_read' || args.includeDiff || args.cursor ? await readLivePage({ git: deps.git, authority, record,
184
+ overlay, base, args, invocation, kind: operation === 'live_read' ? 'read' : 'diff', now: now() }) : { nextCursor: null }) };
185
+ if (stop && !authority.canReadCode)
186
+ args.expectedLiveRevision = record.revision;
187
+ const mutation = await mutateLive({ deps, tx, authority, operation, args, base, overlay, currentHeadSha: head, now: now() });
188
+ action = mutation.action;
189
+ await tx.complete(command, { ...mutation.result, revision: tx.record.revision });
190
+ return mutation.result;
191
+ });
192
+ if (outcome !== LIVE_PREFETCH_STALE)
193
+ result = outcome;
194
+ }
182
195
  if (!result.replayed && action) {
183
196
  const settling = settleLiveWorker({ deps, identity, action, result, now: now() });
184
197
  if (action === 'stop')
@@ -189,3 +202,36 @@ export function createLiveService(deps) {
189
202
  return narrowStop ? { liveSessionId: result.liveSessionId, state: result.state } : result;
190
203
  } };
191
204
  }
205
+ const LIVE_PREFETCH_ATTEMPTS = 3;
206
+ // A string (not a symbol): store adapters clone transaction results.
207
+ const LIVE_PREFETCH_STALE = 'live-prefetch-stale';
208
+ const settle = (pending) => pending.then(value => ({ ok: true, value }), error => ({ ok: false, error }));
209
+ const take = (settled) => { if (!settled.ok)
210
+ throw settled.error; return settled.value; };
211
+ /** Reads the draft fence in a short transaction, then performs every forge call outside the advisory lock.
212
+ * Failures are replayed at their original use site inside the locked transaction, so error precedence is unchanged. */
213
+ async function prefetchLiveBase(deps, target, identity, operation, head, fullTree) {
214
+ const fence = (record) => record ? JSON.stringify([record.changedPaths > 0, record.baseHeadSha,
215
+ record.latestVerifiedHeadSha]) : null;
216
+ const peek = await deps.store.transaction(identity, async (tx) => tx.record ? structuredClone(tx.record) : undefined);
217
+ const baseSha = operation === 'live_reset' || !peek?.changedPaths ? head : peek.baseHeadSha;
218
+ const ancestors = [...new Set([peek?.latestVerifiedHeadSha,
219
+ peek && (!peek.changedPaths || operation === 'live_reset') ? peek.baseHeadSha : undefined])]
220
+ .filter((sha) => Boolean(sha) && sha !== head);
221
+ const [base, ...ancestry] = await Promise.all([
222
+ settle(fullTree ? deps.git.snapshot(target, baseSha) :
223
+ deps.git.inspectCommit(target, baseSha).then(commit => ({ treeSha: commit.treeSha, entries: [] }))),
224
+ ...ancestors.map(sha => settle(deps.git.isAncestor(target, sha, head))),
225
+ ]);
226
+ const known = new Map(ancestors.map((sha, index) => [sha, ancestry[index]]));
227
+ return {
228
+ covers: (record) => fence(record) === fence(peek),
229
+ base: () => take(base),
230
+ ancestor(sha) {
231
+ const settled = known.get(sha);
232
+ if (!settled)
233
+ liveBusy('stale_fence');
234
+ return take(settled);
235
+ },
236
+ };
237
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/artifacts",
3
- "version": "0.2.23",
3
+ "version": "0.2.25",
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",