@spellkave/sdk 0.0.0-stage → 0.1.0
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/LICENSE +89 -0
- package/README.md +155 -2
- package/package.json +63 -4
- package/src/binding_rows.ts +186 -0
- package/src/connection.ts +964 -0
- package/src/core/actor.ts +62 -0
- package/src/core/actor_control.ts +193 -0
- package/src/core/actor_control_query_methods.ts +101 -0
- package/src/core/actor_control_reaction_methods.ts +79 -0
- package/src/core/actor_control_sense_methods.ts +81 -0
- package/src/core/actor_control_source.ts +57 -0
- package/src/core/actor_session_methods.ts +226 -0
- package/src/core/binding_drift.ts +301 -0
- package/src/core/credential.ts +259 -0
- package/src/core/driver_control.ts +54 -0
- package/src/core/effective_environment_state.ts +71 -0
- package/src/core/factored_manipulation_attempt.ts +158 -0
- package/src/core/ids.ts +60 -0
- package/src/core/interaction/canonical.ts +15 -0
- package/src/core/interaction/fingerprint.ts +118 -0
- package/src/core/interaction/index.ts +31 -0
- package/src/core/interaction/intent.ts +284 -0
- package/src/core/interaction/outcome.ts +67 -0
- package/src/core/interaction/rejection_ledger.ts +108 -0
- package/src/core/kernel_contract.generated.ts +10 -0
- package/src/core/log.ts +23 -0
- package/src/core/movement.ts +111 -0
- package/src/core/node-io.ts +208 -0
- package/src/core/paths.ts +220 -0
- package/src/core/profile.ts +270 -0
- package/src/core/profiles.ts +9 -0
- package/src/core/provenance_buffer.ts +102 -0
- package/src/core/readers/_helpers.ts +273 -0
- package/src/core/readers/action_description.ts +17 -0
- package/src/core/readers/action_economy_events.ts +149 -0
- package/src/core/readers/actor_body_swaps.ts +62 -0
- package/src/core/readers/actor_snapshot.ts +197 -0
- package/src/core/readers/actor_states.ts +163 -0
- package/src/core/readers/actors_and_bodies.ts +179 -0
- package/src/core/readers/affordance_cue.ts +59 -0
- package/src/core/readers/affordance_defaults.ts +158 -0
- package/src/core/readers/affordance_group_membership.ts +67 -0
- package/src/core/readers/affordance_input.ts +129 -0
- package/src/core/readers/affordance_reference.ts +41 -0
- package/src/core/readers/apply_consequences.ts +54 -0
- package/src/core/readers/audience_trace_presentation.ts +62 -0
- package/src/core/readers/bounded_collection.ts +29 -0
- package/src/core/readers/bundle_definitions.ts +74 -0
- package/src/core/readers/bundle_entities.ts +62 -0
- package/src/core/readers/co_location.ts +71 -0
- package/src/core/readers/combat_session.ts +124 -0
- package/src/core/readers/combat_session_active.ts +44 -0
- package/src/core/readers/combat_session_feedback.ts +37 -0
- package/src/core/readers/combat_session_grid.ts +117 -0
- package/src/core/readers/combat_session_roster.ts +98 -0
- package/src/core/readers/combat_session_types.ts +51 -0
- package/src/core/readers/condition_deltas.ts +53 -0
- package/src/core/readers/container_contents.ts +92 -0
- package/src/core/readers/dialogue_guide.ts +99 -0
- package/src/core/readers/dialogue_prompt_presentation.ts +90 -0
- package/src/core/readers/driver_control.ts +64 -0
- package/src/core/readers/entity_art.ts +219 -0
- package/src/core/readers/entity_containment.ts +119 -0
- package/src/core/readers/equipment.ts +99 -0
- package/src/core/readers/intervention_windows.ts +136 -0
- package/src/core/readers/inventory_query.ts +145 -0
- package/src/core/readers/item_detail.ts +198 -0
- package/src/core/readers/location_snapshot.ts +216 -0
- package/src/core/readers/manifest_apply_provenance.ts +32 -0
- package/src/core/readers/manifest_export.ts +81 -0
- package/src/core/readers/manipulation_context.ts +475 -0
- package/src/core/readers/map_layers.ts +49 -0
- package/src/core/readers/metadata_rows.ts +56 -0
- package/src/core/readers/object_state.ts +124 -0
- package/src/core/readers/observer_knowledge.ts +41 -0
- package/src/core/readers/observer_place_knowledge.ts +37 -0
- package/src/core/readers/observer_trace_knowledge.ts +45 -0
- package/src/core/readers/outcome_template.ts +41 -0
- package/src/core/readers/place_topology.ts +109 -0
- package/src/core/readers/reaction_options.ts +156 -0
- package/src/core/readers/resource_deltas.ts +47 -0
- package/src/core/readers/scene.ts +275 -0
- package/src/core/readers/seats.ts +33 -0
- package/src/core/readers/self.ts +245 -0
- package/src/core/readers/self_capabilities.ts +159 -0
- package/src/core/readers/self_economy.ts +101 -0
- package/src/core/readers/self_economy_budget.ts +93 -0
- package/src/core/readers/self_evaluations.ts +128 -0
- package/src/core/readers/self_identity.ts +104 -0
- package/src/core/readers/sense_context.ts +112 -0
- package/src/core/readers/session.ts +207 -0
- package/src/core/readers/session_detail.ts +211 -0
- package/src/core/readers/session_status.ts +68 -0
- package/src/core/readers/spatial_environment_state.ts +74 -0
- package/src/core/readers/spatial_niche_attachments.ts +28 -0
- package/src/core/readers/substrate_definitions.ts +27 -0
- package/src/core/readers/suggest_next_action.ts +72 -0
- package/src/core/readers/surface_membership.ts +78 -0
- package/src/core/readers/tag_reads.ts +54 -0
- package/src/core/readers/trace_query.ts +120 -0
- package/src/core/readers/trace_response.ts +80 -0
- package/src/core/readers/traces.ts +124 -0
- package/src/core/readers/travel_session.ts +88 -0
- package/src/core/readers/turn_state.ts +34 -0
- package/src/core/readers/world_events.ts +43 -0
- package/src/core/readers/world_status.ts +63 -0
- package/src/core/reducers/manipulation_args.ts +239 -0
- package/src/core/reducers/manipulation_receipt.ts +66 -0
- package/src/core/reducers/r_actor_wake_up.ts +32 -0
- package/src/core/reducers/r_inscribe_trace.ts +109 -0
- package/src/core/reducers/r_manipulate.ts +163 -0
- package/src/core/reducers/r_move.ts +155 -0
- package/src/core/reducers/r_react.ts +143 -0
- package/src/core/reducers/r_release_claim.ts +81 -0
- package/src/core/reducers/r_sense.ts +84 -0
- package/src/core/reducers/r_session_close.ts +130 -0
- package/src/core/reducers/r_session_move.ts +116 -0
- package/src/core/reducers/r_session_open.ts +91 -0
- package/src/core/reducers/session_lookup.ts +64 -0
- package/src/core/reducers/tick.ts +65 -0
- package/src/core/reducers/trace_lookup.ts +29 -0
- package/src/core/reducers/transport.ts +84 -0
- package/src/core/resolve.ts +228 -0
- package/src/core/shape_telemetry.ts +146 -0
- package/src/core/snapshot_rows.ts +109 -0
- package/src/core/tick_cadence.ts +61 -0
- package/src/core/types.ts +501 -0
- package/src/core/watch_provenance.ts +113 -0
- package/src/core/world-contract/classify.ts +38 -0
- package/src/core/world-contract/index.ts +12 -0
- package/src/core/world-contract/normalise.ts +574 -0
- package/src/core/world-contract/runtime.ts +144 -0
- package/src/core/world-contract/served.ts +173 -0
- package/src/core/world-contract/strict-reducers.ts +14 -0
- package/src/core/world-contract/typetext.ts +94 -0
- package/src/core/world_time.ts +22 -0
- package/src/index.ts +262 -0
- package/src/manifest-apply.ts +497 -0
- package/src/provenance.ts +568 -0
- package/src/reader-manifest.ts +338 -0
- package/src/readers.ts +392 -0
- package/src/replay.ts +515 -0
- package/src/watch-buffer.ts +438 -0
- package/src/world-events/builder.ts +1042 -0
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// Production manifest-apply primitive (sk-0m4.45, ADR-0103 D-2).
|
|
2
|
+
// CLI / sk / Pi / elevated seats / test-lab all resolve on the same two
|
|
3
|
+
// subscribed signals: a new `manifest_apply_digest` seal (ok) or a new
|
|
4
|
+
// `manifest_apply_outcome` verdict row (repeat seal or real MF-APPLY failure).
|
|
5
|
+
//
|
|
6
|
+
// This module is the production path. `enqueueAndWaitManifestApply` stays
|
|
7
|
+
// Result-returning; `applyManifestDeltaOrThrow` unwraps `{ ok: false }` into
|
|
8
|
+
// an Error whose message keeps the MF-* code. Optional MF-APPLY-013 in-flight
|
|
9
|
+
// retry and `tolerateAlreadyApplied` (MF-APPLY-012) default OFF so existing
|
|
10
|
+
// callers are unchanged. Serialization is per caller-owned lane from
|
|
11
|
+
// `createManifestApplyLane()` — never a module-global singleton.
|
|
12
|
+
//
|
|
13
|
+
// test-lab (`applyManifestDelta` / `applyManifestSource` / `runManifestApply`)
|
|
14
|
+
// is a consumer of this primitive: throwing wrappers that keep `world.db()` /
|
|
15
|
+
// `table()` conveniences and a test-only process-wide lane. Do not import
|
|
16
|
+
// test-lab from production hosts.
|
|
17
|
+
//
|
|
18
|
+
// Happy path has no 60s/120s/240s timeout — a long watchdog fires only when
|
|
19
|
+
// neither signal arrives (scheduler dead or a mid-commit wedge).
|
|
20
|
+
|
|
21
|
+
export const MANIFEST_APPLY_WAIT_TABLES = [
|
|
22
|
+
"manifest_apply_digest",
|
|
23
|
+
"manifest_apply_outcome",
|
|
24
|
+
] as const;
|
|
25
|
+
|
|
26
|
+
/** Derived subscribe set — same whole-table query shape as connect()/subscribeReaders. */
|
|
27
|
+
export const MANIFEST_APPLY_WAIT_QUERIES = MANIFEST_APPLY_WAIT_TABLES.map(
|
|
28
|
+
// ci-allow(raw-sql): derived wait-subscribe for the drain seal/outcome tables (sk-0m4.45), same query shape as connect()
|
|
29
|
+
(table) => `SELECT * FROM ${table}`,
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
/** Long bound for a dead scheduler / leftover mid-commit wedge. Not the happy path. */
|
|
33
|
+
export const MANIFEST_APPLY_WATCHDOG_MS = 15 * 60 * 1000;
|
|
34
|
+
|
|
35
|
+
const POLL_MIN_MS = 10;
|
|
36
|
+
const POLL_MAX_MS = 300;
|
|
37
|
+
|
|
38
|
+
/** Notify after the subscribed cache mutation is readable. */
|
|
39
|
+
export type ManifestApplyUpdateSource = (listener: (table?: string) => void) => () => void;
|
|
40
|
+
|
|
41
|
+
export type ManifestApplyHandle = { iter(): Iterable<unknown> } | undefined;
|
|
42
|
+
|
|
43
|
+
export type ManifestApplyVerdict =
|
|
44
|
+
| { status: "pending" }
|
|
45
|
+
| { status: "sealed"; digest?: string }
|
|
46
|
+
| { status: "failed"; code: string; message: string; outcome?: ManifestApplyOutcomeSnap };
|
|
47
|
+
|
|
48
|
+
export interface ManifestApplyOutcomeSnap {
|
|
49
|
+
/** A new successful outcome seals a repeat apply whose digest already exists. */
|
|
50
|
+
ok?: boolean;
|
|
51
|
+
applyId: string;
|
|
52
|
+
/** Present on server outcome rows; optional for older snapshot adapters. */
|
|
53
|
+
digest?: string;
|
|
54
|
+
code: string;
|
|
55
|
+
message: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type ManifestApplyResult =
|
|
59
|
+
| { ok: true; alreadyApplied?: true; digest?: string }
|
|
60
|
+
| { ok: false; detail: string; outcome?: ManifestApplyOutcomeSnap; cause?: unknown };
|
|
61
|
+
|
|
62
|
+
/** Correlated failure without replacing the original transport/cache exception. */
|
|
63
|
+
export class ManifestApplyError extends Error {
|
|
64
|
+
readonly outcome: ManifestApplyOutcomeSnap | undefined;
|
|
65
|
+
|
|
66
|
+
constructor(failure: Extract<ManifestApplyResult, { ok: false }>) {
|
|
67
|
+
const correlation =
|
|
68
|
+
failure.outcome === undefined
|
|
69
|
+
? ""
|
|
70
|
+
: ` [apply_id=${failure.outcome.applyId}, digest=${failure.outcome.digest ?? "unknown"}]`;
|
|
71
|
+
super(`${failure.detail}${correlation}`, { cause: failure.cause });
|
|
72
|
+
this.name = "ManifestApplyError";
|
|
73
|
+
this.outcome = failure.outcome;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface ManifestApplyLane {
|
|
78
|
+
run<T>(task: () => Promise<T>): Promise<T>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface ManifestApplyDeltaPort {
|
|
82
|
+
digestHandle: ManifestApplyHandle;
|
|
83
|
+
outcomeHandle: ManifestApplyHandle;
|
|
84
|
+
enqueueDelta: (toml: string) => Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface EnqueueAndWaitManifestApplyArgs {
|
|
88
|
+
digestHandle: ManifestApplyHandle;
|
|
89
|
+
outcomeHandle: ManifestApplyHandle;
|
|
90
|
+
enqueue: () => Promise<void>;
|
|
91
|
+
label?: string;
|
|
92
|
+
/** Cache observation; when supplied, no polling timer is used. */
|
|
93
|
+
onUpdate?: ManifestApplyUpdateSource;
|
|
94
|
+
/// Bounded retry on MF-APPLY-013 (in-flight collision). Off when omitted
|
|
95
|
+
/// (one attempt). `attempts` is the total try count, matching test-lab's
|
|
96
|
+
/// historical 30× loop. The digest/outcome snapshot is retaken on EVERY
|
|
97
|
+
/// attempt so an unrelated apply sealing between tries is never misread
|
|
98
|
+
/// as this call's success (ADR-0103 D-2).
|
|
99
|
+
retryInFlight?: { attempts: number; delayMs: number };
|
|
100
|
+
/// MF-APPLY-012 / "already applied" resolves `{ ok: true, alreadyApplied: true }`
|
|
101
|
+
/// instead of `{ ok: false }`. Off by default.
|
|
102
|
+
tolerateAlreadyApplied?: boolean;
|
|
103
|
+
/// Caller-owned serialization. Two lanes do not block each other; one lane
|
|
104
|
+
/// does. Never a module-global singleton.
|
|
105
|
+
lane?: ManifestApplyLane;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function verdictFromManifestApplySnapshots(input: {
|
|
109
|
+
beforeDigests: ReadonlySet<string>;
|
|
110
|
+
currentDigests: Iterable<string>;
|
|
111
|
+
beforeOutcomeIds: ReadonlySet<string>;
|
|
112
|
+
currentOutcomes: Iterable<ManifestApplyOutcomeSnap>;
|
|
113
|
+
}): ManifestApplyVerdict {
|
|
114
|
+
for (const digest of input.currentDigests) {
|
|
115
|
+
if (!input.beforeDigests.has(digest)) return { status: "sealed", digest };
|
|
116
|
+
}
|
|
117
|
+
for (const outcome of input.currentOutcomes) {
|
|
118
|
+
if (!input.beforeOutcomeIds.has(outcome.applyId)) {
|
|
119
|
+
if (outcome.ok === true) return { status: "sealed", digest: outcome.digest };
|
|
120
|
+
return { status: "failed", code: outcome.code, message: outcome.message, outcome };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return { status: "pending" };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function formatManifestApplyFailure(code: string, message: string): string {
|
|
127
|
+
return `${code}: ${message}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function isManifestAlreadyApplied(error: unknown): boolean {
|
|
131
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
132
|
+
return message.includes("MF-APPLY-012") || message.includes("already applied");
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function isManifestApplyInFlight(error: unknown): boolean {
|
|
136
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
137
|
+
return message.includes("MANIFEST_APPLY_IN_FLIGHT") || message.includes("MF-APPLY-013");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Caller-owned single-flight lane. Failures do not stall later callers. */
|
|
141
|
+
export function createManifestApplyLane(): ManifestApplyLane {
|
|
142
|
+
let tail: Promise<void> = Promise.resolve();
|
|
143
|
+
return {
|
|
144
|
+
run<T>(task: () => Promise<T>): Promise<T> {
|
|
145
|
+
const run = tail.then(task);
|
|
146
|
+
tail = run.then(
|
|
147
|
+
() => undefined,
|
|
148
|
+
() => undefined,
|
|
149
|
+
);
|
|
150
|
+
return run;
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function waitForManifestApplyVerdict(
|
|
156
|
+
read: () => ManifestApplyVerdict,
|
|
157
|
+
options: { watchdogMs?: number; label?: string; onUpdate?: ManifestApplyUpdateSource } = {},
|
|
158
|
+
): Promise<Exclude<ManifestApplyVerdict, { status: "pending" }>> {
|
|
159
|
+
const watchdogMs = options.watchdogMs ?? MANIFEST_APPLY_WATCHDOG_MS;
|
|
160
|
+
const deadline = Date.now() + watchdogMs;
|
|
161
|
+
if (options.onUpdate !== undefined) {
|
|
162
|
+
const observed: { verdict: ManifestApplyVerdict } = { verdict: { status: "pending" } };
|
|
163
|
+
await waitForApplySignal(
|
|
164
|
+
options.onUpdate,
|
|
165
|
+
deadline,
|
|
166
|
+
options.label,
|
|
167
|
+
() => {
|
|
168
|
+
observed.verdict = read();
|
|
169
|
+
return observed.verdict.status !== "pending";
|
|
170
|
+
},
|
|
171
|
+
watchdogMs,
|
|
172
|
+
);
|
|
173
|
+
if (observed.verdict.status === "pending")
|
|
174
|
+
throw new Error("Apply observation resolved without a verdict");
|
|
175
|
+
return observed.verdict;
|
|
176
|
+
}
|
|
177
|
+
let pollMs = POLL_MIN_MS;
|
|
178
|
+
for (;;) {
|
|
179
|
+
const verdict = read();
|
|
180
|
+
if (verdict.status !== "pending") return verdict;
|
|
181
|
+
if (Date.now() >= deadline) {
|
|
182
|
+
const label = options.label === undefined ? "" : `${options.label}: `;
|
|
183
|
+
throw new Error(
|
|
184
|
+
`${label}manifest apply watchdog: no seal or failure outcome within ${watchdogMs}ms`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
await new Promise<void>((resolve) => setTimeout(resolve, pollMs));
|
|
188
|
+
pollMs = Math.min(pollMs * 2, POLL_MAX_MS);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function rowString(row: Record<string, unknown>, camel: string, snake: string): string {
|
|
193
|
+
return String(row[camel] ?? row[snake] ?? "");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function digestSetFromHandle(handle: ManifestApplyHandle): Set<string> {
|
|
197
|
+
const out = new Set<string>();
|
|
198
|
+
if (handle === undefined) return out;
|
|
199
|
+
for (const raw of handle.iter()) {
|
|
200
|
+
const row = raw as Record<string, unknown>;
|
|
201
|
+
const digest = rowString(row, "manifestDigest", "manifest_digest");
|
|
202
|
+
if (digest.length > 0) out.add(digest);
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function outcomesFromHandle(handle: ManifestApplyHandle): ManifestApplyOutcomeSnap[] {
|
|
208
|
+
if (handle === undefined) return [];
|
|
209
|
+
return Array.from(handle.iter(), (raw) => {
|
|
210
|
+
const row = raw as Record<string, unknown>;
|
|
211
|
+
return {
|
|
212
|
+
...(typeof row.ok === "boolean" ? { ok: row.ok } : {}),
|
|
213
|
+
applyId: rowString(row, "applyId", "apply_id"),
|
|
214
|
+
digest: rowString(row, "digest", "digest"),
|
|
215
|
+
code: rowString(row, "code", "code"),
|
|
216
|
+
message: rowString(row, "message", "message"),
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function subscribeManifestApplyWait(subscriptionBuilder: {
|
|
222
|
+
onApplied(cb: () => void): {
|
|
223
|
+
onError(cb: () => void): { subscribe(queries: string[]): unknown };
|
|
224
|
+
};
|
|
225
|
+
}): Promise<void> {
|
|
226
|
+
return new Promise((resolve, reject) => {
|
|
227
|
+
subscriptionBuilder
|
|
228
|
+
.onApplied(() => resolve())
|
|
229
|
+
.onError(() => reject(new Error("manifest apply wait subscribe failed")))
|
|
230
|
+
.subscribe([...MANIFEST_APPLY_WAIT_QUERIES]);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function errorDetail(err: unknown): string {
|
|
235
|
+
return err instanceof Error ? err.message : String(err);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function sleep(ms: number): Promise<void> {
|
|
239
|
+
if (ms <= 0) return Promise.resolve();
|
|
240
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function snapshotBefore(args: EnqueueAndWaitManifestApplyArgs): {
|
|
244
|
+
beforeDigests: Set<string>;
|
|
245
|
+
beforeOutcomeIds: Set<string>;
|
|
246
|
+
} {
|
|
247
|
+
return {
|
|
248
|
+
beforeDigests: digestSetFromHandle(args.digestHandle),
|
|
249
|
+
beforeOutcomeIds: new Set(outcomesFromHandle(args.outcomeHandle).map((row) => row.applyId)),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function tolerateAlreadyAppliedResult(
|
|
254
|
+
args: EnqueueAndWaitManifestApplyArgs,
|
|
255
|
+
error: unknown,
|
|
256
|
+
): ManifestApplyResult | undefined {
|
|
257
|
+
if (args.tolerateAlreadyApplied === true && isManifestAlreadyApplied(error)) {
|
|
258
|
+
return { ok: true, alreadyApplied: true };
|
|
259
|
+
}
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function enqueueAndWaitManifestApplyOnce(
|
|
264
|
+
args: EnqueueAndWaitManifestApplyArgs,
|
|
265
|
+
): Promise<ManifestApplyResult> {
|
|
266
|
+
const maxAttempts = Math.max(1, args.retryInFlight?.attempts ?? 1);
|
|
267
|
+
const delayMs = args.retryInFlight?.delayMs ?? 0;
|
|
268
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
269
|
+
// Retake on EVERY attempt (ADR-0103 D-2): an unrelated seal landing
|
|
270
|
+
// between tries must not be attributed to this call.
|
|
271
|
+
const { beforeDigests, beforeOutcomeIds } = snapshotBefore(args);
|
|
272
|
+
try {
|
|
273
|
+
await args.enqueue();
|
|
274
|
+
} catch (err) {
|
|
275
|
+
const tolerated = tolerateAlreadyAppliedResult(args, err);
|
|
276
|
+
if (tolerated !== undefined) return tolerated;
|
|
277
|
+
if (isManifestApplyInFlight(err) && attempt < maxAttempts) {
|
|
278
|
+
await sleep(delayMs);
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
return { ok: false, detail: errorDetail(err), cause: err };
|
|
282
|
+
}
|
|
283
|
+
try {
|
|
284
|
+
const verdict = await waitForManifestApplyVerdict(
|
|
285
|
+
() =>
|
|
286
|
+
verdictFromManifestApplySnapshots({
|
|
287
|
+
beforeDigests,
|
|
288
|
+
currentDigests: digestSetFromHandle(args.digestHandle),
|
|
289
|
+
beforeOutcomeIds,
|
|
290
|
+
currentOutcomes: outcomesFromHandle(args.outcomeHandle),
|
|
291
|
+
}),
|
|
292
|
+
{ label: args.label, onUpdate: args.onUpdate },
|
|
293
|
+
);
|
|
294
|
+
if (verdict.status === "failed") {
|
|
295
|
+
const detail = formatManifestApplyFailure(verdict.code, verdict.message);
|
|
296
|
+
const tolerated = tolerateAlreadyAppliedResult(args, detail);
|
|
297
|
+
if (tolerated !== undefined) return tolerated;
|
|
298
|
+
return { ok: false, detail, outcome: verdict.outcome };
|
|
299
|
+
}
|
|
300
|
+
return { ok: true, digest: verdict.status === "sealed" ? verdict.digest : undefined };
|
|
301
|
+
} catch (err) {
|
|
302
|
+
return { ok: false, detail: errorDetail(err), cause: err };
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return { ok: false, detail: "manifest apply exhausted in-flight retries" };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export async function enqueueAndWaitManifestApply(
|
|
309
|
+
args: EnqueueAndWaitManifestApplyArgs,
|
|
310
|
+
): Promise<ManifestApplyResult> {
|
|
311
|
+
if (args.lane === undefined) return enqueueAndWaitManifestApplyOnce(args);
|
|
312
|
+
return args.lane.run(() => enqueueAndWaitManifestApplyOnce(args));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Throwing convenience over `enqueueAndWaitManifestApply`. Keeps the MF-* code. */
|
|
316
|
+
export async function applyManifestDeltaOrThrow(
|
|
317
|
+
port: ManifestApplyDeltaPort,
|
|
318
|
+
toml: string,
|
|
319
|
+
opts: Omit<EnqueueAndWaitManifestApplyArgs, "digestHandle" | "outcomeHandle" | "enqueue"> = {},
|
|
320
|
+
): Promise<void> {
|
|
321
|
+
const result = await enqueueAndWaitManifestApply({
|
|
322
|
+
digestHandle: port.digestHandle,
|
|
323
|
+
outcomeHandle: port.outcomeHandle,
|
|
324
|
+
enqueue: () => port.enqueueDelta(toml),
|
|
325
|
+
label: opts.label,
|
|
326
|
+
onUpdate: opts.onUpdate,
|
|
327
|
+
retryInFlight: opts.retryInFlight,
|
|
328
|
+
tolerateAlreadyApplied: opts.tolerateAlreadyApplied,
|
|
329
|
+
lane: opts.lane,
|
|
330
|
+
});
|
|
331
|
+
if (!result.ok) {
|
|
332
|
+
throw new ManifestApplyError(result);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const APPLY_WAIT_TABLES: ReadonlySet<string> = new Set([
|
|
337
|
+
...MANIFEST_APPLY_WAIT_TABLES,
|
|
338
|
+
// Generated binding accessors (installRefreshHooks prefers snake_case, but
|
|
339
|
+
// some cache wrappers emit camelCase).
|
|
340
|
+
"manifestApplyDigest",
|
|
341
|
+
"manifestApplyOutcome",
|
|
342
|
+
// connection.ts CACHE_APPLIED_MARKER — onApplied after a snapshot apply.
|
|
343
|
+
"__applied",
|
|
344
|
+
]);
|
|
345
|
+
|
|
346
|
+
export interface ManifestApplyObserveArgs extends EnqueueAndWaitManifestApplyArgs {
|
|
347
|
+
/** Post-mutation cache updates. Silent cache changes violate this port's contract. */
|
|
348
|
+
onUpdate: ManifestApplyUpdateSource;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Fire-and-forget ticket (sk-jay0.7.15.15). `result` settles with the
|
|
352
|
+
* ManifestApplyResult; `done` unwraps `{ ok: false }` into a thrown Error
|
|
353
|
+
* (same as `applyManifestDeltaOrThrow`). Returning the ticket is sync —
|
|
354
|
+
* await `done`/`result` only when the caller needs the seal. */
|
|
355
|
+
export interface ManifestApplyTicket {
|
|
356
|
+
readonly result: Promise<ManifestApplyResult>;
|
|
357
|
+
readonly done: Promise<void>;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function isApplyWaitTable(table: string | undefined): boolean {
|
|
361
|
+
return table === undefined || APPLY_WAIT_TABLES.has(table);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function waitForApplySignal(
|
|
365
|
+
onUpdate: ManifestApplyUpdateSource,
|
|
366
|
+
deadlineMs: number,
|
|
367
|
+
label: string | undefined,
|
|
368
|
+
pred?: () => boolean,
|
|
369
|
+
watchdogMs = MANIFEST_APPLY_WATCHDOG_MS,
|
|
370
|
+
): Promise<void> {
|
|
371
|
+
return new Promise((resolve, reject) => {
|
|
372
|
+
let settled = false;
|
|
373
|
+
let unsub: (() => void) | undefined;
|
|
374
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
375
|
+
const finish = (failure?: { cause: unknown }): void => {
|
|
376
|
+
if (settled) return;
|
|
377
|
+
settled = true;
|
|
378
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
379
|
+
unsub?.();
|
|
380
|
+
if (failure === undefined) resolve();
|
|
381
|
+
else reject(failure.cause);
|
|
382
|
+
};
|
|
383
|
+
const check = (): void => {
|
|
384
|
+
if (settled) return;
|
|
385
|
+
try {
|
|
386
|
+
if (pred === undefined || pred()) finish();
|
|
387
|
+
} catch (error) {
|
|
388
|
+
finish({ cause: error });
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
try {
|
|
392
|
+
// Subscribe before reading; an update during registration cannot be lost.
|
|
393
|
+
// Generated table callbacks observe the already-mutated SDK cache.
|
|
394
|
+
unsub = onUpdate((table) => {
|
|
395
|
+
if (isApplyWaitTable(table)) check();
|
|
396
|
+
});
|
|
397
|
+
if (settled) {
|
|
398
|
+
unsub();
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
if (pred !== undefined) check();
|
|
402
|
+
if (settled) return;
|
|
403
|
+
const remain = Math.max(0, deadlineMs - Date.now());
|
|
404
|
+
timer = setTimeout(() => {
|
|
405
|
+
const prefix = label === undefined ? "" : `${label}: `;
|
|
406
|
+
finish({
|
|
407
|
+
cause: new Error(
|
|
408
|
+
`${prefix}manifest apply watchdog: no seal or failure outcome within ${watchdogMs}ms`,
|
|
409
|
+
),
|
|
410
|
+
});
|
|
411
|
+
}, remain);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
finish({ cause: error });
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function ticketFromResult(result: Promise<ManifestApplyResult>): ManifestApplyTicket {
|
|
419
|
+
const done = result.then((value) => {
|
|
420
|
+
if (!value.ok) throw new ManifestApplyError(value);
|
|
421
|
+
});
|
|
422
|
+
return { result, done };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function enqueueManifestApplyObservedOnce(
|
|
426
|
+
args: ManifestApplyObserveArgs,
|
|
427
|
+
): Promise<ManifestApplyResult> {
|
|
428
|
+
const deadlineMs = Date.now() + MANIFEST_APPLY_WATCHDOG_MS;
|
|
429
|
+
for (;;) {
|
|
430
|
+
if (Date.now() >= deadlineMs) {
|
|
431
|
+
const label = args.label === undefined ? "" : `${args.label}: `;
|
|
432
|
+
return {
|
|
433
|
+
ok: false,
|
|
434
|
+
detail: `${label}manifest apply watchdog: no seal or failure outcome within ${MANIFEST_APPLY_WATCHDOG_MS}ms`,
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
const { beforeDigests, beforeOutcomeIds } = snapshotBefore(args);
|
|
438
|
+
try {
|
|
439
|
+
await args.enqueue();
|
|
440
|
+
} catch (err) {
|
|
441
|
+
const tolerated = tolerateAlreadyAppliedResult(args, err);
|
|
442
|
+
if (tolerated !== undefined) return tolerated;
|
|
443
|
+
if (isManifestApplyInFlight(err)) {
|
|
444
|
+
try {
|
|
445
|
+
await waitForApplySignal(args.onUpdate, deadlineMs, args.label);
|
|
446
|
+
} catch (waitErr) {
|
|
447
|
+
return { ok: false, detail: errorDetail(waitErr), cause: waitErr };
|
|
448
|
+
}
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
return { ok: false, detail: errorDetail(err), cause: err };
|
|
452
|
+
}
|
|
453
|
+
try {
|
|
454
|
+
let verdict = verdictFromManifestApplySnapshots({
|
|
455
|
+
beforeDigests,
|
|
456
|
+
currentDigests: digestSetFromHandle(args.digestHandle),
|
|
457
|
+
beforeOutcomeIds,
|
|
458
|
+
currentOutcomes: outcomesFromHandle(args.outcomeHandle),
|
|
459
|
+
});
|
|
460
|
+
while (verdict.status === "pending") {
|
|
461
|
+
await waitForApplySignal(args.onUpdate, deadlineMs, args.label, () => {
|
|
462
|
+
verdict = verdictFromManifestApplySnapshots({
|
|
463
|
+
beforeDigests,
|
|
464
|
+
currentDigests: digestSetFromHandle(args.digestHandle),
|
|
465
|
+
beforeOutcomeIds,
|
|
466
|
+
currentOutcomes: outcomesFromHandle(args.outcomeHandle),
|
|
467
|
+
});
|
|
468
|
+
return verdict.status !== "pending";
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
if (verdict.status === "failed") {
|
|
472
|
+
const detail = formatManifestApplyFailure(verdict.code, verdict.message);
|
|
473
|
+
if (isManifestApplyInFlight(detail)) {
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
const tolerated = tolerateAlreadyAppliedResult(args, detail);
|
|
477
|
+
if (tolerated !== undefined) return tolerated;
|
|
478
|
+
return { ok: false, detail, outcome: verdict.outcome };
|
|
479
|
+
}
|
|
480
|
+
return { ok: true, digest: verdict.status === "sealed" ? verdict.digest : undefined };
|
|
481
|
+
} catch (err) {
|
|
482
|
+
return { ok: false, detail: errorDetail(err), cause: err };
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Enqueue a manifest apply and return immediately. The ticket settles when
|
|
488
|
+
* `verdictFromManifestApplySnapshots` sees a new digest or outcome on the
|
|
489
|
+
* caller's update stream. MF-APPLY-013 re-enqueues from that observer, never
|
|
490
|
+
* from a sleep loop. */
|
|
491
|
+
export function enqueueManifestApplyObserved(args: ManifestApplyObserveArgs): ManifestApplyTicket {
|
|
492
|
+
const result =
|
|
493
|
+
args.lane === undefined
|
|
494
|
+
? enqueueManifestApplyObservedOnce(args)
|
|
495
|
+
: args.lane.run(() => enqueueManifestApplyObservedOnce(args));
|
|
496
|
+
return ticketFromResult(result);
|
|
497
|
+
}
|