@lmzhen/dsh-evolution-core 0.59.6 → 0.60.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.
Files changed (103) hide show
  1. package/README.md +3 -1
  2. package/lib/authority-plugin.js +3 -2
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-B_F4TYOD.js → composition-BSqh70z_.js} +1 -1
  5. package/lib/{ensure-BpVDuDnA.js → ensure-DTCuxAxR.js} +1 -1
  6. package/lib/{extract-plan-D3ALlAmN.js → extract-plan-CP__XlEs.js} +2 -2
  7. package/lib/extract.js +4 -4
  8. package/lib/http-routes.js +3 -2
  9. package/lib/index.js +15 -15
  10. package/lib/{io-Cpa8wuvj.js → io-DT4-MXLr.js} +25 -1
  11. package/lib/io-node.js +1 -1
  12. package/lib/io-platform.js +163 -0
  13. package/lib/io-registry.js +10 -0
  14. package/lib/{mutation-authority-CZpc9F20.js → mutation-authority-C3RYyiaT.js} +66 -41
  15. package/lib/{mutation-storage-adapter-Cq1bmS1E.js → mutation-storage-adapter-CSVn34dK.js} +327 -210
  16. package/lib/{mutations-Y-wKod7W.js → mutations-JKFlfhSO.js} +1 -1
  17. package/lib/policy.js +1 -1
  18. package/lib/{quality-NPGr3VzA.js → quality-C0ri2SgY.js} +2 -2
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +1 -1
  21. package/lib/{review-context-yNiZadPw.js → review-context-D2LIOEi-.js} +2 -2
  22. package/lib/runtime/plugin.js +2 -2
  23. package/lib/{session-projection-DM15fsRp.js → session-projection-Dnmm5bzt.js} +1 -1
  24. package/lib/{skill-history-BvLWFoOo.js → skill-history-BOZ4HCDB.js} +2 -2
  25. package/lib/skills.js +268 -37
  26. package/lib/state/domain/index.js +433 -0
  27. package/lib/state/index.js +136 -0
  28. package/lib/state/migrate.js +90 -0
  29. package/lib/state/storage.js +605 -0
  30. package/lib/state/store-plugin.js +23 -0
  31. package/lib/state/store.js +268 -0
  32. package/lib/subagent/index.js +1 -1
  33. package/lib/types/authority-plugin.d.ts +1 -1
  34. package/lib/types/authority-plugin.js +2 -1
  35. package/lib/types/authority.d.ts +1 -1
  36. package/lib/types/authority.js +75 -48
  37. package/lib/types/composition/ensure.js +1 -1
  38. package/lib/types/contract.d.ts +8 -0
  39. package/lib/types/http-routes.d.ts +1 -0
  40. package/lib/types/http-routes.js +2 -1
  41. package/lib/types/io-platform.d.ts +74 -0
  42. package/lib/types/io-platform.js +178 -0
  43. package/lib/types/io-registry.d.ts +4 -0
  44. package/lib/types/io-registry.js +10 -0
  45. package/lib/types/io.d.ts +7 -0
  46. package/lib/types/io.js +25 -1
  47. package/lib/types/mutation-authority.d.ts +1 -1
  48. package/lib/types/mutation-storage-adapter.d.ts +1 -1
  49. package/lib/types/opt-in.js +2 -2
  50. package/lib/types/params.js +2 -2
  51. package/lib/types/policy.js +1 -1
  52. package/lib/types/restrictor.js +2 -2
  53. package/lib/types/result.d.ts +1 -1
  54. package/lib/types/result.js +1 -1
  55. package/lib/types/runtime/coherence.js +1 -1
  56. package/lib/types/runtime/llm.d.ts +1 -1
  57. package/lib/types/runtime/llm.js +1 -1
  58. package/lib/types/runtime/platform.d.ts +3 -3
  59. package/lib/types/runtime/platform.js +2 -2
  60. package/lib/types/runtime/projections.d.ts +1 -1
  61. package/lib/types/scope.js +1 -1
  62. package/lib/types/session-projection.d.ts +1 -1
  63. package/lib/types/signals.d.ts +1 -1
  64. package/lib/types/skill-store.d.ts +37 -4
  65. package/lib/types/skill-store.js +240 -24
  66. package/lib/types/skill-write-plan.d.ts +1 -1
  67. package/lib/types/skill-write-service.js +8 -2
  68. package/lib/types/state/conformance.d.ts +47 -0
  69. package/lib/types/state/conformance.js +246 -0
  70. package/lib/types/state/constants.d.ts +52 -0
  71. package/lib/types/state/constants.js +52 -0
  72. package/lib/types/state/domain/compatibility.d.ts +40 -0
  73. package/lib/types/state/domain/compatibility.js +36 -0
  74. package/lib/types/state/domain/index.d.ts +81 -0
  75. package/lib/types/state/domain/index.js +592 -0
  76. package/lib/types/state/index.d.ts +63 -0
  77. package/lib/types/state/index.js +174 -0
  78. package/lib/types/state/medium-declaration.d.ts +37 -0
  79. package/lib/types/state/medium-declaration.js +53 -0
  80. package/lib/types/state/migrate.d.ts +34 -0
  81. package/lib/types/state/migrate.js +103 -0
  82. package/lib/types/state/record-contract.d.ts +56 -0
  83. package/lib/types/state/record-contract.js +120 -0
  84. package/lib/types/state/storage.d.ts +112 -0
  85. package/lib/types/state/storage.js +178 -0
  86. package/lib/types/state/store-plugin.d.ts +14 -0
  87. package/lib/types/state/store-plugin.js +18 -0
  88. package/lib/types/state/store.d.ts +39 -0
  89. package/lib/types/state/store.js +270 -0
  90. package/lib/types/store-ledger.js +2 -2
  91. package/lib/types/subagent/run.d.ts +1 -1
  92. package/lib/types/subagent/types.d.ts +4 -4
  93. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  94. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  95. package/lib/types/tool-dispatch.js +6 -3
  96. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +40 -13
  97. package/lib/types/{mutation-unit.js → unit-kernel.js} +155 -118
  98. package/lib/types/write.d.ts +1 -2
  99. package/lib/types/write.js +1 -2
  100. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  101. package/lib/write.js +4 -4
  102. package/package.json +30 -3
  103. package/persisted-write-inventory.json +14 -5
@@ -0,0 +1,433 @@
1
+ import { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, PENDING_KINDS, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, REVIEW_STATE_TABLE, assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, selectPendingOverflow, selectSessionOverflow } from "../storage.js";
2
+ import "../index.js";
3
+ import { z } from "zod";
4
+ import { storageDomainPort } from "@lmzhen/dsh-evolution-platform/ports";
5
+ import { DomainError, defineDomain, domainTable } from "@lmzhen/dsh-evolution-platform/values";
6
+ //#region lib/types/state/domain/compatibility.js
7
+ /**
8
+ * G2b/2b.4: the domain compatibility declaration (S1-07).
9
+ *
10
+ * A domain spec says WHAT is stored; nothing said what happens to records the CURRENT schema rejects,
11
+ * nor which earlier versions stay readable. Today the answer is implicit and unstated: 0 declared
12
+ * compatibility surface. This file is the ONE place that states it.
13
+ *
14
+ * MIGRATION NOTE: upstream P2-E1 (docs/v33-no-action-register.md) asks storage-domain to add optional
15
+ * `layout` / `compatibleVersions` / `invalidRecords` fields to `DomainSpec`. When that lands, this
16
+ * declaration MOVES onto the platform spec - the fields exist precisely so a domain can state this once.
17
+ * It must not then live in two places.
18
+ *
19
+ * @module @lmzhen/dsh-evolution-core/state/domain/compatibility
20
+ */
21
+ /** The evolution domain's statement. Absence of this constant is what the criterion calls red. */
22
+ const EVOLUTION_DOMAIN_COMPATIBILITY = {
23
+ invalidRecords: [
24
+ {
25
+ table: "review_state",
26
+ tier: "regenerable",
27
+ why: "turn counters are observations of a session; a lost row costs one session its counters and the next run rewrites it"
28
+ },
29
+ {
30
+ table: "curator_state",
31
+ tier: "regenerable",
32
+ why: "run bookkeeping only — runCount/lastRunAt are re-derived from the run records on the next run"
33
+ },
34
+ {
35
+ table: "pending",
36
+ tier: "irreplaceable",
37
+ why: "a staged write is the ONLY copy of an approved-but-unapplied change; losing it loses the operator decision"
38
+ }
39
+ ],
40
+ compatibleVersions: [1]
41
+ };
42
+ //#endregion
43
+ //#region lib/types/state/domain/index.js
44
+ /**
45
+ * storage-domain provider for evolution state.
46
+ *
47
+ * When this provider is mounted, review/curator/pending records live in the
48
+ * DSH storage-domain data form: schema-validated, change-emitting, durable KV
49
+ * with whatever backend the domain facility routes (`json`, `sqlite`, remote
50
+ * RPC, …). The provider is one of several implementations of the same seam.
51
+ * @module @lmzhen/dsh-evolution-core/state/domain
52
+ */
53
+ const name = "evolution-state-domain";
54
+ const inject = ["evolutionStateStorage", "storageDomain"];
55
+ /**
56
+ * The domain package can be loaded twice (host + plugin copy, or a test tree
57
+ * that imports source and lib side by side), so `instanceof DomainError` is not
58
+ * a reliable seam. The stable contract is the name+code pair.
59
+ * @param error - the thrown value.
60
+ * @param code - the stable DomainError code to match.
61
+ * @returns whether this is a DomainError with that code.
62
+ */
63
+ function isDomainErrorCode(error, code) {
64
+ if (error instanceof DomainError) return error.code === code;
65
+ if (typeof error !== "object" || error === null) return false;
66
+ const candidate = error;
67
+ return candidate.name === "DomainError" && candidate.code === code;
68
+ }
69
+ /**
70
+ * Review-state record schema of the storage-domain table.
71
+ * @internal Referenced only by this package's own tests and EVOLUTION_DOMAIN
72
+ * below — not public API surface (audit v10 S-03); the record contract lives
73
+ * in `@lmzhen/dsh-evolution-core/state-storage` types.
74
+ */
75
+ const reviewStateSchema = z.object({
76
+ turnsSinceMemory: z.number().int().nonnegative(),
77
+ turnsSinceSkill: z.number().int().nonnegative(),
78
+ lastTurn: z.number().int().nonnegative()
79
+ }).loose();
80
+ /**
81
+ * Curator-state record schema of the storage-domain table.
82
+ * @internal Referenced only by this package's own tests and EVOLUTION_DOMAIN
83
+ * below — not public API surface (audit v10 S-03).
84
+ */
85
+ const curatorStateSchema = z.object({
86
+ /** Optional record-shape version; legacy records without it stay compatible. */
87
+ schemaVersion: z.number().int().nonnegative().optional(),
88
+ lastRunAt: z.number().nonnegative(),
89
+ runCount: z.number().int().nonnegative(),
90
+ lastSummary: z.string(),
91
+ paused: z.boolean()
92
+ }).loose();
93
+ /**
94
+ * Pending record schema of the storage-domain table.
95
+ * @internal Referenced only by this package's own tests and EVOLUTION_DOMAIN
96
+ * below — not public API surface (audit v10 S-03).
97
+ */
98
+ const pendingSchema = z.object({
99
+ id: z.string(),
100
+ kind: z.enum(PENDING_KINDS),
101
+ summary: z.string(),
102
+ args: z.unknown(),
103
+ createdAt: z.string(),
104
+ status: z.enum(PENDING_STATUSES),
105
+ resolvedAt: z.string().optional(),
106
+ claimedBy: z.string().optional(),
107
+ claimedAt: z.string().optional(),
108
+ origin: z.string().optional(),
109
+ sessionId: z.string().optional()
110
+ }).loose();
111
+ /**
112
+ * The evolution storage-domain spec: three schema-validated KV tables.
113
+ * @internal Referenced only by this package's own tests and `open()` — not
114
+ * public API surface (audit v10 S-03).
115
+ */
116
+ const EVOLUTION_DOMAIN = defineDomain({
117
+ name: "evolution",
118
+ version: 1,
119
+ tables: {
120
+ [REVIEW_STATE_TABLE]: domainTable(reviewStateSchema),
121
+ [CURATOR_STATE_TABLE]: domainTable(curatorStateSchema),
122
+ [PENDING_TABLE]: domainTable(pendingSchema)
123
+ }
124
+ });
125
+ /**
126
+ * Bounded open() retry (rc.42 audit P1-4, package-private): a rejected open
127
+ * used to poison the shared `opening` promise forever, so one transient
128
+ * backend failure (lock, busy) took the provider down until process restart.
129
+ * Only transient failures retry (v37 S2.5): a deterministic failure surfaces
130
+ * at once instead of re-running the whole-domain loadAll three times, and the
131
+ * cleared promise lets a later call start a fresh budget.
132
+ */
133
+ const OPEN_MAX_ATTEMPTS = 3;
134
+ const OPEN_RETRY_BASE_MS = 100;
135
+ /** Retry cannot heal these — the stored record or the medium fails its own
136
+ * schema/version, or the backend cannot serve the domain at all. Both storage
137
+ * vocabularies (DomainError, StorageError) carry the code as stable API.
138
+ * S1-D3: `already-open` (DomainError, upstream open()'s single-open constraint)
139
+ * is deterministic too — a competing consumer of the `evolution` domain never
140
+ * goes away on retry, so burning the full backoff budget (3× loadAll) and then
141
+ * leaving `opening` cleared only re-runs the same futile budget on every later
142
+ * call. */
143
+ const DETERMINISTIC_OPEN_CODES = new Set([
144
+ "invalid-record",
145
+ "malformed-medium",
146
+ "version-mismatch",
147
+ "facet-unsupported",
148
+ "backend-not-found",
149
+ "already-open",
150
+ "closed"
151
+ ]);
152
+ function isTransientOpenFailure(error) {
153
+ if (typeof error !== "object" || error === null) return true;
154
+ const code = error.code;
155
+ return typeof code !== "string" || !DETERMINISTIC_OPEN_CODES.has(code);
156
+ }
157
+ function apply(ctx) {
158
+ let domain = null;
159
+ let opening = null;
160
+ async function ensure() {
161
+ if (domain) return domain;
162
+ if (!opening) {
163
+ opening = (async () => {
164
+ const facility = storageDomainPort(ctx);
165
+ if (!facility) throw new Error("evolution-state-domain requires @deepseek-ai/dsh-storage-domain");
166
+ let lastError;
167
+ for (let attempt = 1; attempt <= OPEN_MAX_ATTEMPTS; attempt += 1) try {
168
+ return await facility.open(EVOLUTION_DOMAIN);
169
+ } catch (error) {
170
+ lastError = error;
171
+ if (!isTransientOpenFailure(error) || attempt === OPEN_MAX_ATTEMPTS) break;
172
+ await new Promise((resolve) => setTimeout(resolve, OPEN_RETRY_BASE_MS * 2 ** (attempt - 1)));
173
+ }
174
+ throw lastError;
175
+ })();
176
+ opening.catch(() => {
177
+ opening = null;
178
+ });
179
+ }
180
+ domain = await opening;
181
+ return domain;
182
+ }
183
+ async function reload() {
184
+ const current = domain;
185
+ domain = null;
186
+ opening = null;
187
+ if (current !== null) await current.close();
188
+ }
189
+ let pendingKeyWarned = false;
190
+ const rawProvider = {
191
+ name: PROVIDER_DOMAIN,
192
+ reload,
193
+ async listReviewStates() {
194
+ return [...(await ensure()).table(REVIEW_STATE_TABLE).entries()].map(([sessionId, record]) => {
195
+ const { updatedAt, ...consumer } = record;
196
+ return {
197
+ sessionId,
198
+ record: structuredClone(consumer),
199
+ ...updatedAt === void 0 ? {} : { updatedAt }
200
+ };
201
+ });
202
+ },
203
+ async loadReviewState(sessionId) {
204
+ const record = (await ensure()).table(REVIEW_STATE_TABLE).get(sessionId);
205
+ if (record === void 0) return null;
206
+ const { updatedAt: _stamp, ...rest } = record;
207
+ return structuredClone(rest);
208
+ },
209
+ async saveReviewState(sessionId, record) {
210
+ const issue = recordIssue("review_state", record) ?? assertCloneable(record);
211
+ if (issue !== null) throw new Error(`evolution-state-domain: refusing to persist an invalid review-state record: ${issue}`);
212
+ const parsed = reviewStateSchema.safeParse(record);
213
+ if (!parsed.success) throw new Error(`evolution-state-domain: refusing to persist an invalid review-state record: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`);
214
+ const table = (await ensure()).table(REVIEW_STATE_TABLE);
215
+ const stamped = {
216
+ ...cloneRecord(parsed.data),
217
+ updatedAt: Date.now()
218
+ };
219
+ await table.put(sessionId, stamped);
220
+ const entries = [...table.entries()].map(([key, row]) => ({
221
+ key,
222
+ updatedAt: row.updatedAt ?? 0
223
+ })).filter((entry) => entry.key !== sessionId);
224
+ const victims = new Set(selectSessionOverflow(entries, {
225
+ keyOf: (entry) => entry.key,
226
+ stampOf: (entry) => entry.updatedAt
227
+ }, 500));
228
+ for (const entry of entries.filter((candidate) => victims.has(candidate.key))) {
229
+ const current = table.get(entry.key);
230
+ if (current === void 0 || (current.updatedAt ?? 0) !== entry.updatedAt) continue;
231
+ await table.delete(entry.key).catch((error) => {
232
+ ctx.logger.warn(`evolution-state-domain: review-state session-cap eviction for "${entry.key}" failed (will retry on the next save): ${error instanceof Error ? error.message : String(error)}`);
233
+ });
234
+ }
235
+ },
236
+ async loadCuratorState() {
237
+ const record = (await ensure()).table(CURATOR_STATE_TABLE).get(CURATOR_STATE_KEY);
238
+ return record === void 0 ? null : structuredClone(record);
239
+ },
240
+ async saveCuratorState(record) {
241
+ const issue = recordIssue("curator_state", record) ?? assertCloneable(record);
242
+ if (issue !== null) throw new Error(`evolution-state-domain: refusing to persist an invalid curator-state record: ${issue}`);
243
+ const parsed = curatorStateSchema.safeParse(record);
244
+ if (!parsed.success) throw new Error(`evolution-state-domain: refusing to persist an invalid curator-state record: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`);
245
+ await (await ensure()).table(CURATOR_STATE_TABLE).put(CURATOR_STATE_KEY, cloneRecord(parsed.data));
246
+ },
247
+ async transactCuratorState(task) {
248
+ const table = (await ensure()).table(CURATOR_STATE_TABLE);
249
+ const guarded = (current) => {
250
+ const next = task(current === null ? null : cloneRecord(current));
251
+ if (next === null) return null;
252
+ const issue = recordIssue("curator_state", next) ?? assertCloneable(next);
253
+ if (issue !== null) throw new Error(`evolution-state-domain: refusing to persist an invalid curator-state record: ${issue}`);
254
+ return cloneRecord(next);
255
+ };
256
+ try {
257
+ await table.update(CURATOR_STATE_KEY, (current) => guarded(current) ?? current);
258
+ return;
259
+ } catch (error) {
260
+ if (!isDomainErrorCode(error, "missing-key")) throw error;
261
+ }
262
+ try {
263
+ await table.update(CURATOR_STATE_KEY, (current) => guarded(current) ?? current);
264
+ return;
265
+ } catch (error) {
266
+ if (!isDomainErrorCode(error, "missing-key")) throw error;
267
+ }
268
+ const next = guarded(null);
269
+ if (next !== null) await table.put(CURATOR_STATE_KEY, next);
270
+ else await table.delete(CURATOR_STATE_KEY);
271
+ },
272
+ async listPending(status = "pending") {
273
+ const table = (await ensure()).table(PENDING_TABLE);
274
+ const entries = [...table.entries()];
275
+ const drifted = [];
276
+ for (const [key, record] of entries) if (key !== record.id && typeof record.id === "string" && record.id !== "") drifted.push({
277
+ key,
278
+ record
279
+ });
280
+ if (drifted.length > 0) {
281
+ if (!pendingKeyWarned) {
282
+ pendingKeyWarned = true;
283
+ ctx.logger.warn(`evolution-state-domain: ${drifted.length} pending table entr(ies) were keyed by something other than record.id — re-keyed by id, so a drifted row is reachable by claim/resolve again`);
284
+ }
285
+ for (const { key, record } of drifted) try {
286
+ if (table.get(record.id) !== void 0) {
287
+ await table.delete(key);
288
+ continue;
289
+ }
290
+ await table.put(record.id, structuredClone(record));
291
+ await table.delete(key);
292
+ } catch (error) {
293
+ ctx.logger.warn(`evolution-state-domain: pending re-key for "${key}" failed (will retry on the next list): ${error instanceof Error ? error.message : String(error)}`);
294
+ break;
295
+ }
296
+ }
297
+ const final = drifted.length > 0 ? [...table.entries()] : entries;
298
+ const seen = /* @__PURE__ */ new Set();
299
+ return final.filter(([, value]) => value.status === status).filter(([, value]) => {
300
+ if (seen.has(value.id)) return false;
301
+ seen.add(value.id);
302
+ return true;
303
+ }).map(([, value]) => structuredClone(value));
304
+ },
305
+ async savePending(record) {
306
+ const issue = recordIssue("pending", record) ?? assertCloneable(record);
307
+ if (issue !== null) throw new Error(`evolution-state-domain: refusing to persist an invalid pending record: ${issue}`);
308
+ const parsed = pendingSchema.safeParse(record);
309
+ if (!parsed.success) throw new Error(`evolution-state-domain: refusing to persist an invalid pending record: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`);
310
+ await (await ensure()).table(PENDING_TABLE).put(record.id, cloneRecord(parsed.data));
311
+ },
312
+ async claimPending(id, claimId) {
313
+ const table = (await ensure()).table(PENDING_TABLE);
314
+ try {
315
+ const slot = { record: null };
316
+ const now = Date.now();
317
+ await table.update(id, (current) => {
318
+ if (!canClaimPending(current.status)) return current;
319
+ slot.record = {
320
+ ...current,
321
+ status: "executing",
322
+ claimedBy: claimId,
323
+ claimedAt: new Date(now).toISOString()
324
+ };
325
+ return slot.record;
326
+ });
327
+ return slot.record === null ? null : structuredClone(slot.record);
328
+ } catch (error) {
329
+ if (isDomainErrorCode(error, "missing-key")) return null;
330
+ throw error;
331
+ }
332
+ },
333
+ async releasePendingClaim(id, claimId) {
334
+ const table = (await ensure()).table(PENDING_TABLE);
335
+ try {
336
+ await table.update(id, (current) => {
337
+ if (current.status !== "pending" && current.status !== "executing") return current;
338
+ if (current.claimedBy !== claimId) return current;
339
+ const released = {
340
+ ...current,
341
+ status: releasedStatus(current.status)
342
+ };
343
+ delete released.claimedBy;
344
+ delete released.claimedAt;
345
+ return released;
346
+ });
347
+ } catch (error) {
348
+ if (isDomainErrorCode(error, "missing-key")) return;
349
+ throw error;
350
+ }
351
+ },
352
+ async tryResolvePending(id, status, expectedClaimId) {
353
+ const table = (await ensure()).table(PENDING_TABLE);
354
+ try {
355
+ const resolved = { record: null };
356
+ const record = await table.update(id, (current) => {
357
+ if (!canResolvePending(current.status)) return current;
358
+ if (expectedClaimId !== void 0 && current.claimedBy !== expectedClaimId) return current;
359
+ resolved.record = {
360
+ ...current,
361
+ status,
362
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
363
+ };
364
+ return resolved.record;
365
+ });
366
+ if (resolved.record !== null) {
367
+ const evictedRecords = new Set(selectPendingOverflow([...table.entries()].map(([, record]) => record), 200));
368
+ const evicted = [...table.entries()].filter(([, record]) => evictedRecords.has(record)).map(([key, record]) => ({
369
+ key,
370
+ record
371
+ }));
372
+ for (const entry of evicted) {
373
+ const current = table.get(entry.key);
374
+ if (!(current !== void 0 && (current.status === "approved" || current.status === "rejected") && current.resolvedAt === entry.record.resolvedAt)) continue;
375
+ await table.delete(entry.key).catch((error) => {
376
+ ctx.logger.warn(`evolution-state-domain: pending-cap eviction for "${entry.key}" failed (will retry on the next resolve): ${error instanceof Error ? error.message : String(error)}`);
377
+ });
378
+ }
379
+ }
380
+ const rawRecord = record;
381
+ if (resolved.record === null) return {
382
+ record: rawRecord === null ? null : structuredClone(rawRecord),
383
+ applied: false
384
+ };
385
+ return {
386
+ record: structuredClone(resolved.record),
387
+ applied: true
388
+ };
389
+ } catch (error) {
390
+ if (isDomainErrorCode(error, "missing-key")) return {
391
+ record: null,
392
+ applied: false
393
+ };
394
+ throw error;
395
+ }
396
+ }
397
+ };
398
+ let providerQueue = Promise.resolve();
399
+ let providerBusy = false;
400
+ function withProvider(task) {
401
+ if (!providerBusy) {
402
+ providerBusy = true;
403
+ const run = task();
404
+ providerQueue = run.then(() => {
405
+ providerBusy = false;
406
+ }, () => {
407
+ providerBusy = false;
408
+ });
409
+ return run;
410
+ }
411
+ const run = providerQueue.then(task, task);
412
+ providerQueue = run.then(() => void 0, () => void 0);
413
+ return run;
414
+ }
415
+ const provider = new Proxy(rawProvider, { get(target, key) {
416
+ const value = Reflect.get(target, key);
417
+ if (typeof value !== "function") return value;
418
+ return (...args) => withProvider(async () => await value.apply(target, args));
419
+ } });
420
+ ctx.effect(() => {
421
+ const dispose = ctx.evolutionStateStorage.registerProvider(provider);
422
+ return async () => {
423
+ dispose();
424
+ await providerQueue.catch(() => {});
425
+ if (opening) await opening.catch(() => null);
426
+ if (domain) await domain.close();
427
+ domain = null;
428
+ opening = null;
429
+ };
430
+ }, "evolution-state-domain.provider");
431
+ }
432
+ //#endregion
433
+ export { EVOLUTION_DOMAIN, EVOLUTION_DOMAIN_COMPATIBILITY, apply, curatorStateSchema, inject, name, pendingSchema, reviewStateSchema };
@@ -0,0 +1,136 @@
1
+ import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
2
+ import { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, EvolutionStateStorageRegistry, MEDIUM_PROCESS_DECLARATION, PENDING_KINDS, PENDING_RESOLVED_CAP, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, PROVIDER_STORE, REVIEW_STATE_SESSION_CAP, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER, assertCloneable, canClaimPending, canResolvePending, cloneRecord, processScopeViolations, recordIssue, releasedStatus, runStateProviderConsistency, selectPendingOverflow, selectSessionOverflow } from "./storage.js";
3
+ import { mkdir } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { withFileLock } from "@lmzhen/dsh-evolution-platform/values/fs";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import { Service } from "@deepseek-ai/cordis";
8
+ import z from "@deepseek-ai/schemastery";
9
+ //#region lib/types/state/index.js
10
+ /**
11
+ * Durable evolution state consumer.
12
+ *
13
+ * The service owns no medium and performs no IO. It resolves the mounted
14
+ * provider from `ctx.evolutionStateStorage` (see evolution-state-json and
15
+ * evolution-state-domain); `provider` config may pin one by name.
16
+ * @module @lmzhen/dsh-evolution-core/state
17
+ */
18
+ var EvolutionState = class extends Service {
19
+ static inject = ["evolutionStateStorage"];
20
+ static Config = z.object({
21
+ provider: z.string().default(""),
22
+ home: z.string().default("")
23
+ });
24
+ providerName;
25
+ home;
26
+ constructor(ctx, config = {}) {
27
+ super(ctx, "evolutionState");
28
+ this.providerName = config.provider ?? "";
29
+ this.home = config.home !== void 0 && config.home !== "" ? config.home : evolutionHome();
30
+ if (this.providerName !== "" && this.providerName !== "auto" && ctx.evolutionStateStorage.hasProviders()) ctx.evolutionStateStorage.provider(this.providerName);
31
+ if (this.providerName !== "auto") this.assertProviderChoice();
32
+ }
33
+ /** P2-5: the multi-provider refusal is not a mount-time-only check. A provider
34
+ * registered after this row mounted used to make registration order the effective
35
+ * medium with no pin — exactly the silent rebind the mount check exists to stop. */
36
+ /** Validate the marker + a real store image before auto may select it. */
37
+ assertMarkerStore() {
38
+ const marker = join(this.home, "state", STATE_MIGRATION_MARKER);
39
+ if (!existsSync(marker)) return;
40
+ const storePath = join(this.home, "state", "store.json");
41
+ let markerBody;
42
+ let storeBody;
43
+ try {
44
+ markerBody = JSON.parse(readFileSync(marker, "utf8"));
45
+ storeBody = JSON.parse(readFileSync(storePath, "utf8"));
46
+ } catch (error) {
47
+ throw new Error("evolution-state: the migration marker/store is missing or unreadable: " + (error instanceof Error ? error.message : String(error)));
48
+ }
49
+ if (typeof markerBody !== "object" || markerBody === null || markerBody.target !== "store") throw new Error("evolution-state: the migration marker is invalid (target != store): " + marker);
50
+ const image = storeBody;
51
+ if (typeof image !== "object" || image === null || image.version !== 1 || typeof image.review !== "object" || image.review === null || Array.isArray(image.review) || typeof image.pending !== "object" || image.pending === null || Array.isArray(image.pending)) throw new Error("evolution-state: the migration marker points at an invalid/empty store image: " + storePath);
52
+ }
53
+ assertProviderChoice() {
54
+ if (this.providerName === "auto") {
55
+ const names = this.ctx.evolutionStateStorage.providerNames();
56
+ if (existsSync(join(this.home, "state", ".migrated-from-domain.json"))) {
57
+ if (!names.includes("store")) throw new Error("evolution-state: the migration marker exists but no \"" + PROVIDER_STORE + "\" provider is registered");
58
+ this.assertMarkerStore();
59
+ }
60
+ return;
61
+ }
62
+ if (this.providerName !== "") return;
63
+ const names = this.ctx.evolutionStateStorage.providerNames();
64
+ if (names.length <= 1) return;
65
+ 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>.");
66
+ }
67
+ /** `auto` is the migration switch: the marker is the explicit one-way signal. */
68
+ autoProviderName() {
69
+ const names = this.ctx.evolutionStateStorage.providerNames();
70
+ if (existsSync(join(this.home, "state", ".migrated-from-domain.json"))) {
71
+ this.assertMarkerStore();
72
+ return PROVIDER_STORE;
73
+ }
74
+ if (names.includes("domain")) return PROVIDER_DOMAIN;
75
+ throw new Error("evolution-state: auto has no migration marker and no \"" + PROVIDER_DOMAIN + "\" provider; refusing to guess a state authority");
76
+ }
77
+ /** Validate synchronously (legacy callers rely on a throw, not a rejected promise). */
78
+ assertResolvable() {
79
+ this.assertProviderChoice();
80
+ if (this.providerName !== "" && this.providerName !== "auto") this.ctx.evolutionStateStorage.provider(this.providerName);
81
+ }
82
+ /** Validate, then serialize against migration across processes. */
83
+ run(task) {
84
+ this.assertResolvable();
85
+ return this.withStateLock(task);
86
+ }
87
+ /** Serialize state operations against the migration command across processes. */
88
+ async withStateLock(task) {
89
+ await mkdir(this.home, { recursive: true });
90
+ return withFileLock(join(this.home, "state.lock"), task);
91
+ }
92
+ storage() {
93
+ this.assertProviderChoice();
94
+ const name = this.providerName === "auto" ? this.autoProviderName() : this.providerName;
95
+ return this.ctx.evolutionStateStorage.provider(name || void 0);
96
+ }
97
+ /** A2: refresh the mounted provider before a decision reads pending state. */
98
+ reload() {
99
+ return this.run(async () => this.storage().reload?.() ?? Promise.resolve());
100
+ }
101
+ loadReviewState(sessionId) {
102
+ return this.run(async () => this.storage().loadReviewState(sessionId));
103
+ }
104
+ saveReviewState(sessionId, record) {
105
+ return this.run(async () => this.storage().saveReviewState(sessionId, record));
106
+ }
107
+ loadCuratorState() {
108
+ return this.run(async () => this.storage().loadCuratorState());
109
+ }
110
+ saveCuratorState(record) {
111
+ return this.run(async () => this.storage().saveCuratorState(record));
112
+ }
113
+ /** Atomic read-modify-write the curator-state record (S5.5): `task` returns
114
+ * the next record; returning null keeps the current record unchanged (the
115
+ * seam has no delete semantic). */
116
+ transactCuratorState(task) {
117
+ return this.run(async () => this.storage().transactCuratorState(task));
118
+ }
119
+ listPending(status = "pending") {
120
+ return this.run(async () => this.storage().listPending(status));
121
+ }
122
+ savePending(record) {
123
+ return this.run(async () => this.storage().savePending(record));
124
+ }
125
+ tryResolvePending(id, status, expectedClaimId) {
126
+ return this.run(async () => this.storage().tryResolvePending(id, status, expectedClaimId));
127
+ }
128
+ claimPending(id, claimId) {
129
+ return this.run(async () => this.storage().claimPending(id, claimId));
130
+ }
131
+ releasePendingClaim(id, claimId) {
132
+ return this.run(async () => this.storage().releasePendingClaim(id, claimId));
133
+ }
134
+ };
135
+ //#endregion
136
+ export { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, EvolutionState, EvolutionState as default, EvolutionStateStorageRegistry, MEDIUM_PROCESS_DECLARATION, PENDING_KINDS, PENDING_RESOLVED_CAP, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, PROVIDER_STORE, REVIEW_STATE_SESSION_CAP, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER, assertCloneable, canClaimPending, canResolvePending, cloneRecord, processScopeViolations, recordIssue, releasedStatus, runStateProviderConsistency, selectPendingOverflow, selectSessionOverflow };
@@ -0,0 +1,90 @@
1
+ import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
2
+ import { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, PENDING_STATUSES, PENDING_TABLE, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER } from "./storage.js";
3
+ import "./index.js";
4
+ import { EVOLUTION_DOMAIN } from "./domain/index.js";
5
+ import { writeStateStoreSnapshot } from "./store.js";
6
+ import { mkdir } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { withFileLock } from "@lmzhen/dsh-evolution-platform/values/fs";
9
+ import { storageDomainPort } from "@lmzhen/dsh-evolution-platform/ports";
10
+ //#region lib/types/state/migrate.js
11
+ /**
12
+ * Explicit one-way migration: old storage-domain tables → file StateStore.
13
+ *
14
+ * This module is intentionally NOT a compatibility reader. It runs once, writes a
15
+ * complete snapshot with create-if-absent, leaves the domain data untouched, and
16
+ * writes a marker. Rolling back is switching the provider back to `domain`.
17
+ * @module @lmzhen/dsh-evolution-core/state/migrate
18
+ */
19
+ /**
20
+ * Migrate the three state tables. The store file is published with
21
+ * create-if-absent, so a stale rerun cannot overwrite a newer store.
22
+ */
23
+ async function migrateDomainToStoreUnlocked(ctx, options) {
24
+ const home = options.home ?? evolutionHome();
25
+ const storePath = join(home, "state", "store.json");
26
+ const markerPath = join(home, "state", STATE_MIGRATION_MARKER);
27
+ const io = options.io;
28
+ if (await io.exists(storePath)) throw new Error("evolution-state-migrate: store already exists; refusing to overwrite it: " + storePath);
29
+ const mounted = ctx.evolutionStateStorage?.provider?.("domain");
30
+ let review = {};
31
+ let pending = {};
32
+ let curator = null;
33
+ if (mounted?.listReviewStates !== void 0) {
34
+ await mounted.reload?.();
35
+ for (const row of await mounted.listReviewStates()) review[row.sessionId] = row.record;
36
+ for (const status of PENDING_STATUSES) for (const record of await mounted.listPending(status)) if (pending[record.id] === void 0) pending[record.id] = record;
37
+ curator = await mounted.loadCuratorState();
38
+ } else {
39
+ const facility = storageDomainPort(ctx);
40
+ if (!facility) throw new Error("evolution-state-migrate: @deepseek-ai/dsh-storage-domain is not mounted");
41
+ const domain = await facility.open(EVOLUTION_DOMAIN);
42
+ try {
43
+ review = Object.fromEntries([...domain.table(REVIEW_STATE_TABLE).entries()]);
44
+ pending = {};
45
+ for (const [key, record] of domain.table(PENDING_TABLE).entries()) if (pending[record.id] === void 0) pending[record.id] = record;
46
+ else if (key === record.id) pending[record.id] = record;
47
+ const curated = domain.table(CURATOR_STATE_TABLE).get(CURATOR_STATE_KEY);
48
+ curator = curated === void 0 ? null : curated;
49
+ } finally {
50
+ await domain.close();
51
+ }
52
+ }
53
+ const result = {
54
+ reviewSessions: Object.keys(review).length,
55
+ pending: Object.keys(pending).length,
56
+ curator: curator !== null,
57
+ path: storePath,
58
+ dryRun: options.dryRun === true
59
+ };
60
+ if (options.dryRun === true) return result;
61
+ await writeStateStoreSnapshot(io, storePath, {
62
+ review,
63
+ curator,
64
+ pending
65
+ });
66
+ await io.writeText(markerPath, JSON.stringify({
67
+ migratedAt: new Date(options.now?.() ?? Date.now()).toISOString(),
68
+ source: "domain",
69
+ target: "store",
70
+ reviewSessions: result.reviewSessions,
71
+ pending: result.pending,
72
+ curator: result.curator
73
+ }, null, 2) + "\n");
74
+ return result;
75
+ }
76
+ /**
77
+ * Public entry: hold the same cross-process state.lock every EvolutionState
78
+ * operation holds, so no state write can interleave between the snapshot read
79
+ * and the marker publish.
80
+ */
81
+ async function migrateDomainToStore(ctx, options) {
82
+ const home = options.home ?? evolutionHome();
83
+ await mkdir(home, { recursive: true });
84
+ return withFileLock(join(home, "state.lock"), () => migrateDomainToStoreUnlocked(ctx, {
85
+ ...options,
86
+ home
87
+ }));
88
+ }
89
+ //#endregion
90
+ export { STATE_MIGRATION_MARKER, migrateDomainToStore };