@lmzhen/dsh-evolution-core 0.60.1 → 0.61.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.
@@ -1,268 +1,2 @@
1
- import { c as transactIo } from "../io-DT4-MXLr.js";
2
- import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
3
- import { CURATOR_STATE_TABLE, PENDING_TABLE, PROVIDER_STORE, REVIEW_STATE_TABLE, assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, selectPendingOverflow, selectSessionOverflow } from "./storage.js";
4
- import "./index.js";
5
- import { join } from "node:path";
6
- //#region lib/types/state/store.js
7
- /**
8
- * File-backed StateStore provider.
9
- *
10
- * This is the first D1 step: the provider owns ONE JSON file and every
11
- * transition is a read-modify-write inside the IO seam's transaction. There is
12
- * no process-local authoritative copy; `reload()` is therefore unnecessary and
13
- * reads always observe the medium.
14
- *
15
- * It is intentionally not mounted by the bundle yet: the domain provider is
16
- * still the shipped one until the migration/rollback path is implemented.
17
- * @module @lmzhen/dsh-evolution-core/state/store
18
- */
19
- const STORE_VERSION = 1;
20
- const emptyStore = () => ({
21
- version: STORE_VERSION,
22
- review: {},
23
- curator: null,
24
- pending: {}
25
- });
26
- /** Validate and publish a complete store image. The write is create-if-absent:
27
- * an existing store is never overwritten by a migration. */
28
- async function writeStateStoreSnapshot(io, path, snapshot) {
29
- const text = serialize({
30
- ...emptyStore(),
31
- ...snapshot
32
- });
33
- parseStore(text);
34
- if (io.exists !== void 0 && await io.exists(path)) throw new Error("evolution-state-store: refusing to overwrite an existing store: " + path);
35
- if (io.createTextIfAbsent !== void 0) {
36
- await io.createTextIfAbsent(path, text);
37
- return;
38
- }
39
- if (io.exists !== void 0 && await io.exists(path)) throw new Error("evolution-state-store: refusing to overwrite an existing store: " + path);
40
- await io.writeText(path, text);
41
- }
42
- function invalid(message) {
43
- throw new Error("evolution-state-store: " + message);
44
- }
45
- /** Parse and validate one whole store image. A corrupt store fails loud: silently
46
- * treating it as empty would overwrite the only copy. */
47
- function parseStore(text) {
48
- if (text === null || text.trim() === "") return emptyStore();
49
- let raw;
50
- try {
51
- raw = JSON.parse(text);
52
- } catch (error) {
53
- invalid("store is not valid JSON: " + (error instanceof Error ? error.message : String(error)));
54
- }
55
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) invalid("store must be an object");
56
- const candidate = raw;
57
- if (candidate.version !== STORE_VERSION) invalid("unsupported store version: " + String(candidate.version));
58
- const review = candidate.review;
59
- const pending = candidate.pending;
60
- if (typeof review !== "object" || review === null || Array.isArray(review)) invalid("review must be an object");
61
- if (typeof pending !== "object" || pending === null || Array.isArray(pending)) invalid("pending must be an object");
62
- const store = emptyStore();
63
- for (const [sessionId, record] of Object.entries(review)) {
64
- const issue = recordIssue(REVIEW_STATE_TABLE, record);
65
- if (issue !== null) invalid(`review[${sessionId}]: ${issue}`);
66
- store.review[sessionId] = cloneRecord(record);
67
- }
68
- for (const [key, record] of Object.entries(pending)) {
69
- const issue = recordIssue(PENDING_TABLE, record);
70
- if (issue !== null) invalid(`pending[${key}]: ${issue}`);
71
- const pendingRecord = cloneRecord(record);
72
- if (pendingRecord.id !== key) {
73
- if (store.pending[pendingRecord.id] === void 0) store.pending[pendingRecord.id] = pendingRecord;
74
- continue;
75
- }
76
- store.pending[pendingRecord.id] = pendingRecord;
77
- }
78
- const curator = candidate.curator;
79
- if (curator !== void 0 && curator !== null) {
80
- const issue = recordIssue(CURATOR_STATE_TABLE, curator);
81
- if (issue !== null) invalid("curator: " + issue);
82
- store.curator = cloneRecord(curator);
83
- }
84
- return store;
85
- }
86
- const serialize = (store) => JSON.stringify(store, null, 2) + "\n";
87
- /**
88
- * Build the file-backed provider. All mutating methods are a single
89
- * `transactIo` RMW; readers parse the current file, never a cached copy.
90
- */
91
- function createStateStoreProvider(options) {
92
- const file = options.path ?? join(options.home ?? evolutionHome(), "state", "store.json");
93
- const io = options.io;
94
- const read = async () => parseStore(await io.readText(file));
95
- const mutate = async (task) => {
96
- let result;
97
- let ran = false;
98
- await transactIo(io, file, (current) => {
99
- const store = parseStore(current);
100
- const outcome = task(store);
101
- if (outcome instanceof Promise) return outcome.then((value) => {
102
- result = value;
103
- ran = true;
104
- const next = serialize(store);
105
- return next === current ? current : next;
106
- });
107
- result = outcome;
108
- ran = true;
109
- const next = serialize(store);
110
- return next === current ? current : next;
111
- });
112
- if (!ran) throw new Error("evolution-state-store: transaction did not run the task");
113
- return result;
114
- };
115
- const savePendingValidated = (record) => {
116
- const issue = recordIssue("pending", record) ?? assertCloneable(record);
117
- if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid pending record: " + issue);
118
- return cloneRecord(record);
119
- };
120
- return {
121
- name: PROVIDER_STORE,
122
- async listReviewStates() {
123
- return Object.entries((await read()).review).map(([sessionId, record]) => {
124
- const { updatedAt, ...consumer } = record;
125
- return {
126
- sessionId,
127
- record: structuredClone(consumer),
128
- ...updatedAt === void 0 ? {} : { updatedAt }
129
- };
130
- });
131
- },
132
- async loadReviewState(sessionId) {
133
- const stored = (await read()).review[sessionId];
134
- if (stored === void 0) return null;
135
- const { updatedAt: _updatedAt, ...consumer } = stored;
136
- return structuredClone(consumer);
137
- },
138
- async saveReviewState(sessionId, record) {
139
- const issue = recordIssue("review_state", record) ?? assertCloneable(record);
140
- if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid review-state record: " + issue);
141
- await mutate((store) => {
142
- store.review[sessionId] = {
143
- ...cloneRecord(record),
144
- updatedAt: Date.now()
145
- };
146
- const entries = Object.entries(store.review).filter(([key]) => key !== sessionId).map(([key, row]) => ({
147
- key,
148
- updatedAt: row.updatedAt ?? 0
149
- }));
150
- for (const victim of selectSessionOverflow(entries, {
151
- keyOf: (entry) => entry.key,
152
- stampOf: (entry) => entry.updatedAt
153
- }, 500)) {
154
- const current = store.review[victim];
155
- if (current === void 0) continue;
156
- if ((current.updatedAt ?? 0) !== entries.find((entry) => entry.key === victim)?.updatedAt) continue;
157
- delete store.review[victim];
158
- }
159
- });
160
- },
161
- async loadCuratorState() {
162
- const curator = (await read()).curator;
163
- return curator === null ? null : structuredClone(curator);
164
- },
165
- async saveCuratorState(record) {
166
- const issue = recordIssue("curator_state", record) ?? assertCloneable(record);
167
- if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid curator-state record: " + issue);
168
- await mutate((store) => {
169
- store.curator = cloneRecord(record);
170
- });
171
- },
172
- async transactCuratorState(task) {
173
- await mutate((store) => {
174
- const next = task(store.curator === null ? null : cloneRecord(store.curator));
175
- if (next === null) return;
176
- const issue = recordIssue("curator_state", next) ?? assertCloneable(next);
177
- if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid curator-state record: " + issue);
178
- store.curator = cloneRecord(next);
179
- });
180
- },
181
- async listPending(status = "pending") {
182
- const store = await read();
183
- const seen = /* @__PURE__ */ new Set();
184
- const out = [];
185
- for (const record of Object.values(store.pending)) {
186
- if (record.status !== status) continue;
187
- if (seen.has(record.id)) continue;
188
- seen.add(record.id);
189
- out.push(structuredClone(record));
190
- }
191
- return out;
192
- },
193
- async savePending(record) {
194
- const valid = savePendingValidated(record);
195
- await mutate((store) => {
196
- store.pending[valid.id] = valid;
197
- });
198
- },
199
- async claimPending(id, claimId) {
200
- let claimed = null;
201
- await mutate((store) => {
202
- const current = store.pending[id];
203
- if (current === void 0 || !canClaimPending(current.status)) return;
204
- const next = {
205
- ...current,
206
- status: "executing",
207
- claimedBy: claimId,
208
- claimedAt: (/* @__PURE__ */ new Date()).toISOString()
209
- };
210
- store.pending[id] = next;
211
- claimed = structuredClone(next);
212
- });
213
- return claimed;
214
- },
215
- async releasePendingClaim(id, claimId) {
216
- await mutate((store) => {
217
- const current = store.pending[id];
218
- if (current === void 0 || current.claimedBy !== claimId) return;
219
- if (current.status !== "pending" && current.status !== "executing") return;
220
- const next = {
221
- ...current,
222
- status: releasedStatus(current.status)
223
- };
224
- delete next.claimedBy;
225
- delete next.claimedAt;
226
- store.pending[id] = next;
227
- });
228
- },
229
- async tryResolvePending(id, status, expectedClaimId) {
230
- let outcome = {
231
- record: null,
232
- applied: false
233
- };
234
- await mutate((store) => {
235
- const current = store.pending[id];
236
- if (current === void 0) return;
237
- if (!canResolvePending(current.status)) {
238
- outcome = {
239
- record: structuredClone(current),
240
- applied: false
241
- };
242
- return;
243
- }
244
- if (expectedClaimId !== void 0 && current.claimedBy !== expectedClaimId) {
245
- outcome = {
246
- record: structuredClone(current),
247
- applied: false
248
- };
249
- return;
250
- }
251
- const resolved = {
252
- ...current,
253
- status,
254
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
255
- };
256
- store.pending[id] = resolved;
257
- outcome = {
258
- record: structuredClone(resolved),
259
- applied: true
260
- };
261
- for (const victim of selectPendingOverflow(Object.values(store.pending), 200)) if (store.pending[victim.id]?.resolvedAt === victim.resolvedAt) delete store.pending[victim.id];
262
- });
263
- return outcome;
264
- }
265
- };
266
- }
267
- //#endregion
268
- export { createStateStoreProvider, writeStateStoreSnapshot };
1
+ import { a as writeStateStoreSnapshot, i as readStateStoreSnapshot, n as createStateStoreProvider, r as parseStateStoreImage } from "../state-BJf0a66B.js";
2
+ export { createStateStoreProvider, parseStateStoreImage, readStateStoreSnapshot, writeStateStoreSnapshot };
@@ -0,0 +1,429 @@
1
+ import { c as transactIo } from "./io-DT4-MXLr.js";
2
+ import { t as evolutionHome } from "./state-store-BLchnUkV.js";
3
+ import { CURATOR_STATE_TABLE, PENDING_TABLE, PROVIDER_DOMAIN, PROVIDER_STORE, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER, assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, selectPendingOverflow, selectSessionOverflow } from "./state/storage.js";
4
+ import { mkdir } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { withFileLock } from "@lmzhen/dsh-evolution-platform/values/fs";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { Service } from "@deepseek-ai/cordis";
9
+ import z from "@deepseek-ai/schemastery";
10
+ //#region lib/types/state/store.js
11
+ /**
12
+ * File-backed StateStore provider.
13
+ *
14
+ * This is the first D1 step: the provider owns ONE JSON file and every
15
+ * transition is a read-modify-write inside the IO seam's transaction. There is
16
+ * no process-local authoritative copy; `reload()` is therefore unnecessary and
17
+ * reads always observe the medium.
18
+ *
19
+ * It is intentionally not mounted by the bundle yet: the domain provider is
20
+ * still the shipped one until the migration/rollback path is implemented.
21
+ * @module @lmzhen/dsh-evolution-core/state/store
22
+ */
23
+ const STORE_VERSION = 1;
24
+ const emptyStore = () => ({
25
+ version: STORE_VERSION,
26
+ review: {},
27
+ curator: null,
28
+ pending: {}
29
+ });
30
+ /** Validate and publish a complete store image. The write is create-if-absent:
31
+ * an existing store is never overwritten by a migration. */
32
+ async function writeStateStoreSnapshot(io, path, snapshot) {
33
+ const text = serialize({
34
+ ...emptyStore(),
35
+ ...snapshot
36
+ });
37
+ parseStore(text);
38
+ if (io.exists !== void 0 && await io.exists(path)) throw new Error("evolution-state-store: refusing to overwrite an existing store: " + path);
39
+ if (io.createTextIfAbsent !== void 0) {
40
+ await io.createTextIfAbsent(path, text);
41
+ return;
42
+ }
43
+ if (io.exists !== void 0 && await io.exists(path)) throw new Error("evolution-state-store: refusing to overwrite an existing store: " + path);
44
+ await io.writeText(path, text);
45
+ }
46
+ /** Parse a whole store image synchronously; a corrupt store fails loud. */
47
+ function parseStateStoreImage(text) {
48
+ const store = parseStore(text);
49
+ return {
50
+ review: store.review,
51
+ curator: store.curator,
52
+ pending: store.pending
53
+ };
54
+ }
55
+ /** Read a validated store image; a corrupt store fails loud. */
56
+ async function readStateStoreSnapshot(io, path) {
57
+ const store = parseStore(await io.readText(path));
58
+ return {
59
+ review: store.review,
60
+ curator: store.curator,
61
+ pending: store.pending
62
+ };
63
+ }
64
+ function invalid(message) {
65
+ throw new Error("evolution-state-store: " + message);
66
+ }
67
+ /** Parse and validate one whole store image. A corrupt store fails loud: silently
68
+ * treating it as empty would overwrite the only copy. */
69
+ function parseStore(text) {
70
+ if (text === null || text.trim() === "") return emptyStore();
71
+ let raw;
72
+ try {
73
+ raw = JSON.parse(text);
74
+ } catch (error) {
75
+ invalid("store is not valid JSON: " + (error instanceof Error ? error.message : String(error)));
76
+ }
77
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) invalid("store must be an object");
78
+ const candidate = raw;
79
+ if (candidate.version !== STORE_VERSION) invalid("unsupported store version: " + String(candidate.version));
80
+ const review = candidate.review;
81
+ const pending = candidate.pending;
82
+ if (typeof review !== "object" || review === null || Array.isArray(review)) invalid("review must be an object");
83
+ if (typeof pending !== "object" || pending === null || Array.isArray(pending)) invalid("pending must be an object");
84
+ const store = emptyStore();
85
+ for (const [sessionId, record] of Object.entries(review)) {
86
+ const issue = recordIssue(REVIEW_STATE_TABLE, record);
87
+ if (issue !== null) invalid(`review[${sessionId}]: ${issue}`);
88
+ store.review[sessionId] = cloneRecord(record);
89
+ }
90
+ for (const [key, record] of Object.entries(pending)) {
91
+ const issue = recordIssue(PENDING_TABLE, record);
92
+ if (issue !== null) invalid(`pending[${key}]: ${issue}`);
93
+ const pendingRecord = cloneRecord(record);
94
+ if (pendingRecord.id !== key) {
95
+ if (store.pending[pendingRecord.id] === void 0) store.pending[pendingRecord.id] = pendingRecord;
96
+ continue;
97
+ }
98
+ store.pending[pendingRecord.id] = pendingRecord;
99
+ }
100
+ const curator = candidate.curator;
101
+ if (curator !== void 0 && curator !== null) {
102
+ const issue = recordIssue(CURATOR_STATE_TABLE, curator);
103
+ if (issue !== null) invalid("curator: " + issue);
104
+ store.curator = cloneRecord(curator);
105
+ }
106
+ return store;
107
+ }
108
+ const serialize = (store) => JSON.stringify(store, null, 2) + "\n";
109
+ /**
110
+ * Build the file-backed provider. All mutating methods are a single
111
+ * `transactIo` RMW; readers parse the current file, never a cached copy.
112
+ */
113
+ function createStateStoreProvider(options) {
114
+ const file = options.path ?? join(options.home ?? evolutionHome(), "state", "store.json");
115
+ const io = options.io;
116
+ const read = async () => parseStore(await io.readText(file));
117
+ const mutate = async (task) => {
118
+ let result;
119
+ let ran = false;
120
+ await transactIo(io, file, (current) => {
121
+ const store = parseStore(current);
122
+ const outcome = task(store);
123
+ if (outcome instanceof Promise) return outcome.then((value) => {
124
+ result = value;
125
+ ran = true;
126
+ const next = serialize(store);
127
+ return next === current ? current : next;
128
+ });
129
+ result = outcome;
130
+ ran = true;
131
+ const next = serialize(store);
132
+ return next === current ? current : next;
133
+ });
134
+ if (!ran) throw new Error("evolution-state-store: transaction did not run the task");
135
+ return result;
136
+ };
137
+ const savePendingValidated = (record) => {
138
+ const issue = recordIssue("pending", record) ?? assertCloneable(record);
139
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid pending record: " + issue);
140
+ return cloneRecord(record);
141
+ };
142
+ return {
143
+ name: PROVIDER_STORE,
144
+ async listReviewStates() {
145
+ return Object.entries((await read()).review).map(([sessionId, record]) => {
146
+ const { updatedAt, ...consumer } = record;
147
+ return {
148
+ sessionId,
149
+ record: structuredClone(consumer),
150
+ ...updatedAt === void 0 ? {} : { updatedAt }
151
+ };
152
+ });
153
+ },
154
+ async loadReviewState(sessionId) {
155
+ const stored = (await read()).review[sessionId];
156
+ if (stored === void 0) return null;
157
+ const { updatedAt: _updatedAt, ...consumer } = stored;
158
+ return structuredClone(consumer);
159
+ },
160
+ async saveReviewState(sessionId, record) {
161
+ const issue = recordIssue("review_state", record) ?? assertCloneable(record);
162
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid review-state record: " + issue);
163
+ await mutate((store) => {
164
+ store.review[sessionId] = {
165
+ ...cloneRecord(record),
166
+ updatedAt: Date.now()
167
+ };
168
+ const entries = Object.entries(store.review).filter(([key]) => key !== sessionId).map(([key, row]) => ({
169
+ key,
170
+ updatedAt: row.updatedAt ?? 0
171
+ }));
172
+ for (const victim of selectSessionOverflow(entries, {
173
+ keyOf: (entry) => entry.key,
174
+ stampOf: (entry) => entry.updatedAt
175
+ }, 500)) {
176
+ const current = store.review[victim];
177
+ if (current === void 0) continue;
178
+ if ((current.updatedAt ?? 0) !== entries.find((entry) => entry.key === victim)?.updatedAt) continue;
179
+ delete store.review[victim];
180
+ }
181
+ });
182
+ },
183
+ async loadCuratorState() {
184
+ const curator = (await read()).curator;
185
+ return curator === null ? null : structuredClone(curator);
186
+ },
187
+ async saveCuratorState(record) {
188
+ const issue = recordIssue("curator_state", record) ?? assertCloneable(record);
189
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid curator-state record: " + issue);
190
+ await mutate((store) => {
191
+ store.curator = cloneRecord(record);
192
+ });
193
+ },
194
+ async transactCuratorState(task) {
195
+ await mutate((store) => {
196
+ const next = task(store.curator === null ? null : cloneRecord(store.curator));
197
+ if (next === null) return;
198
+ const issue = recordIssue("curator_state", next) ?? assertCloneable(next);
199
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid curator-state record: " + issue);
200
+ store.curator = cloneRecord(next);
201
+ });
202
+ },
203
+ async listPending(status = "pending") {
204
+ const store = await read();
205
+ const seen = /* @__PURE__ */ new Set();
206
+ const out = [];
207
+ for (const record of Object.values(store.pending)) {
208
+ if (record.status !== status) continue;
209
+ if (seen.has(record.id)) continue;
210
+ seen.add(record.id);
211
+ out.push(structuredClone(record));
212
+ }
213
+ return out;
214
+ },
215
+ async savePending(record) {
216
+ const valid = savePendingValidated(record);
217
+ await mutate((store) => {
218
+ store.pending[valid.id] = valid;
219
+ });
220
+ },
221
+ async claimPending(id, claimId) {
222
+ let claimed = null;
223
+ await mutate((store) => {
224
+ const current = store.pending[id];
225
+ if (current === void 0 || !canClaimPending(current.status)) return;
226
+ const next = {
227
+ ...current,
228
+ status: "executing",
229
+ claimedBy: claimId,
230
+ claimedAt: (/* @__PURE__ */ new Date()).toISOString()
231
+ };
232
+ store.pending[id] = next;
233
+ claimed = structuredClone(next);
234
+ });
235
+ return claimed;
236
+ },
237
+ async releasePendingClaim(id, claimId) {
238
+ await mutate((store) => {
239
+ const current = store.pending[id];
240
+ if (current === void 0 || current.claimedBy !== claimId) return;
241
+ if (current.status !== "pending" && current.status !== "executing") return;
242
+ const next = {
243
+ ...current,
244
+ status: releasedStatus(current.status)
245
+ };
246
+ delete next.claimedBy;
247
+ delete next.claimedAt;
248
+ store.pending[id] = next;
249
+ });
250
+ },
251
+ async tryResolvePending(id, status, expectedClaimId) {
252
+ let outcome = {
253
+ record: null,
254
+ applied: false
255
+ };
256
+ await mutate((store) => {
257
+ const current = store.pending[id];
258
+ if (current === void 0) return;
259
+ if (!canResolvePending(current.status)) {
260
+ outcome = {
261
+ record: structuredClone(current),
262
+ applied: false
263
+ };
264
+ return;
265
+ }
266
+ if (expectedClaimId !== void 0 && current.claimedBy !== expectedClaimId) {
267
+ outcome = {
268
+ record: structuredClone(current),
269
+ applied: false
270
+ };
271
+ return;
272
+ }
273
+ const resolved = {
274
+ ...current,
275
+ status,
276
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
277
+ };
278
+ store.pending[id] = resolved;
279
+ outcome = {
280
+ record: structuredClone(resolved),
281
+ applied: true
282
+ };
283
+ for (const victim of selectPendingOverflow(Object.values(store.pending), 200)) if (store.pending[victim.id]?.resolvedAt === victim.resolvedAt) delete store.pending[victim.id];
284
+ });
285
+ return outcome;
286
+ }
287
+ };
288
+ }
289
+ //#endregion
290
+ //#region lib/types/state/index.js
291
+ /**
292
+ * Durable evolution state consumer.
293
+ *
294
+ * The service owns no medium and performs no IO. It resolves the mounted
295
+ * provider from `ctx.evolutionStateStorage` (see evolution-state-json and
296
+ * evolution-state-domain); `provider` config may pin one by name.
297
+ * @module @lmzhen/dsh-evolution-core/state
298
+ */
299
+ var EvolutionState = class extends Service {
300
+ static inject = ["evolutionStateStorage"];
301
+ static Config = z.object({ provider: z.string().default("") });
302
+ providerName;
303
+ home;
304
+ constructor(ctx, config = {}) {
305
+ super(ctx, "evolutionState");
306
+ this.providerName = config.provider ?? "";
307
+ this.home = evolutionHome();
308
+ if (this.providerName !== "" && this.providerName !== "auto" && ctx.evolutionStateStorage.hasProviders()) ctx.evolutionStateStorage.provider(this.providerName);
309
+ if (this.providerName !== "auto") this.assertProviderChoice();
310
+ }
311
+ /** P2-5: the multi-provider refusal is not a mount-time-only check. A provider
312
+ * registered after this row mounted used to make registration order the effective
313
+ * medium with no pin — exactly the silent rebind the mount check exists to stop. */
314
+ /** Validate the marker + a real store image before auto may select it. */
315
+ assertMarkerStore() {
316
+ const marker = join(this.home, "state", STATE_MIGRATION_MARKER);
317
+ if (!existsSync(marker)) return;
318
+ const storePath = join(this.home, "state", "store.json");
319
+ let markerBody;
320
+ try {
321
+ markerBody = JSON.parse(readFileSync(marker, "utf8"));
322
+ const storeText = readFileSync(storePath, "utf8");
323
+ if (storeText.trim() === "") throw new Error("store image is empty");
324
+ parseStateStoreImage(storeText);
325
+ } catch (error) {
326
+ throw new Error("evolution-state: the migration marker/store is missing or unreadable: " + (error instanceof Error ? error.message : String(error)));
327
+ }
328
+ if (typeof markerBody !== "object" || markerBody === null || markerBody.target !== "store") throw new Error("evolution-state: the migration marker is invalid (target != store): " + marker);
329
+ }
330
+ assertProviderChoice() {
331
+ if (this.providerName === "auto") {
332
+ const names = this.ctx.evolutionStateStorage.providerNames();
333
+ if (existsSync(join(this.home, "state", ".migrated-from-domain.json"))) {
334
+ if (!names.includes("store")) throw new Error("evolution-state: the migration marker exists but no \"" + PROVIDER_STORE + "\" provider is registered");
335
+ this.assertMarkerStore();
336
+ }
337
+ return;
338
+ }
339
+ if (this.providerName !== "") {
340
+ if (this.providerName === "store") {
341
+ if (!existsSync(join(this.home, "state", ".migrated-from-domain.json"))) throw new Error("evolution-state: provider \"" + PROVIDER_STORE + "\" is pinned but the migration marker is missing; refusing to read an empty store as authority");
342
+ this.assertMarkerStore();
343
+ }
344
+ return;
345
+ }
346
+ const names = this.ctx.evolutionStateStorage.providerNames();
347
+ if (names.length <= 1) return;
348
+ throw new Error("evolution-state: " + String(names.length) + " state providers are registered (" + names.join(", ") + ") and this row pins none, so the effective medium would be registration order — a silent rebind that leaves existing state on disk and unreadable. Pin one: provider: <name>.");
349
+ }
350
+ /** `auto` is the migration switch: the marker is the explicit one-way signal. */
351
+ autoProviderName() {
352
+ const names = this.ctx.evolutionStateStorage.providerNames();
353
+ if (existsSync(join(this.home, "state", ".migrated-from-domain.json"))) {
354
+ this.assertMarkerStore();
355
+ return PROVIDER_STORE;
356
+ }
357
+ if (existsSync(join(this.home, "state", "store.json"))) throw new Error("evolution-state: store exists but the migration marker is missing; refusing to silently fall back to domain and lose store-era writes. Pin provider: domain explicitly to roll back.");
358
+ if (names.includes("domain")) return PROVIDER_DOMAIN;
359
+ throw new Error("evolution-state: auto has no migration marker and no \"" + PROVIDER_DOMAIN + "\" provider; refusing to guess a state authority");
360
+ }
361
+ /** Validate synchronously (legacy callers rely on a throw, not a rejected promise). */
362
+ assertResolvable() {
363
+ this.assertProviderChoice();
364
+ if (this.providerName !== "" && this.providerName !== "auto") this.ctx.evolutionStateStorage.provider(this.providerName);
365
+ }
366
+ /** Validate, then serialize against migration across processes. */
367
+ run(task) {
368
+ this.assertResolvable();
369
+ return this.withStateLock(task);
370
+ }
371
+ /** Serialize state operations against the migration command across processes. */
372
+ async withStateLock(task) {
373
+ await mkdir(this.home, { recursive: true });
374
+ return withFileLock(join(this.home, "state.lock"), task);
375
+ }
376
+ storage() {
377
+ this.assertProviderChoice();
378
+ const name = this.providerName === "auto" ? this.autoProviderName() : this.providerName;
379
+ return this.ctx.evolutionStateStorage.provider(name || void 0);
380
+ }
381
+ /** Effective provider after `auto` resolves, for operator diagnostics. */
382
+ providerSelection() {
383
+ const configured = this.providerName === "" ? "auto" : this.providerName;
384
+ this.assertResolvable();
385
+ return {
386
+ configured,
387
+ effective: this.providerName === "auto" ? this.autoProviderName() : this.providerName
388
+ };
389
+ }
390
+ /** A2: refresh the mounted provider before a decision reads pending state. */
391
+ reload() {
392
+ return this.run(async () => this.storage().reload?.() ?? Promise.resolve());
393
+ }
394
+ loadReviewState(sessionId) {
395
+ return this.run(async () => this.storage().loadReviewState(sessionId));
396
+ }
397
+ saveReviewState(sessionId, record) {
398
+ return this.run(async () => this.storage().saveReviewState(sessionId, record));
399
+ }
400
+ loadCuratorState() {
401
+ return this.run(async () => this.storage().loadCuratorState());
402
+ }
403
+ saveCuratorState(record) {
404
+ return this.run(async () => this.storage().saveCuratorState(record));
405
+ }
406
+ /** Atomic read-modify-write the curator-state record (S5.5): `task` returns
407
+ * the next record; returning null keeps the current record unchanged (the
408
+ * seam has no delete semantic). */
409
+ transactCuratorState(task) {
410
+ return this.run(async () => this.storage().transactCuratorState(task));
411
+ }
412
+ listPending(status = "pending") {
413
+ return this.run(async () => this.storage().listPending(status));
414
+ }
415
+ savePending(record) {
416
+ return this.run(async () => this.storage().savePending(record));
417
+ }
418
+ tryResolvePending(id, status, expectedClaimId) {
419
+ return this.run(async () => this.storage().tryResolvePending(id, status, expectedClaimId));
420
+ }
421
+ claimPending(id, claimId) {
422
+ return this.run(async () => this.storage().claimPending(id, claimId));
423
+ }
424
+ releasePendingClaim(id, claimId) {
425
+ return this.run(async () => this.storage().releasePendingClaim(id, claimId));
426
+ }
427
+ };
428
+ //#endregion
429
+ export { writeStateStoreSnapshot as a, readStateStoreSnapshot as i, createStateStoreProvider as n, parseStateStoreImage as r, EvolutionState as t };