@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,592 @@
1
+ /**
2
+ * storage-domain provider for evolution state.
3
+ *
4
+ * When this provider is mounted, review/curator/pending records live in the
5
+ * DSH storage-domain data form: schema-validated, change-emitting, durable KV
6
+ * with whatever backend the domain facility routes (`json`, `sqlite`, remote
7
+ * RPC, …). The provider is one of several implementations of the same seam.
8
+ * @module @lmzhen/dsh-evolution-core/state/domain
9
+ */
10
+ import { z } from 'zod';
11
+ import { storageDomainPort } from '@lmzhen/dsh-evolution-platform/ports';
12
+ import { defineDomain, domainTable, DomainError } from '@lmzhen/dsh-evolution-platform/values';
13
+ import { assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, CURATOR_STATE_KEY, CURATOR_STATE_TABLE, PENDING_KINDS, PENDING_RESOLVED_CAP as SEAM_PENDING_RESOLVED_CAP, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, REVIEW_STATE_SESSION_CAP, REVIEW_STATE_TABLE, selectPendingOverflow, selectSessionOverflow, } from "../index.js";
14
+ export const name = 'evolution-state-domain';
15
+ export const inject = ['evolutionStateStorage', 'storageDomain'];
16
+ /**
17
+ * The domain package can be loaded twice (host + plugin copy, or a test tree
18
+ * that imports source and lib side by side), so `instanceof DomainError` is not
19
+ * a reliable seam. The stable contract is the name+code pair.
20
+ * @param error - the thrown value.
21
+ * @param code - the stable DomainError code to match.
22
+ * @returns whether this is a DomainError with that code.
23
+ */
24
+ function isDomainErrorCode(error, code) {
25
+ if (error instanceof DomainError)
26
+ return error.code === code;
27
+ if (typeof error !== 'object' || error === null)
28
+ return false;
29
+ const candidate = error;
30
+ return candidate.name === 'DomainError' && candidate.code === code;
31
+ }
32
+ /**
33
+ * Review-state record schema of the storage-domain table.
34
+ * @internal Referenced only by this package's own tests and EVOLUTION_DOMAIN
35
+ * below — not public API surface (audit v10 S-03); the record contract lives
36
+ * in `@lmzhen/dsh-evolution-core/state-storage` types.
37
+ */
38
+ export const reviewStateSchema = z.object({
39
+ turnsSinceMemory: z.number().int().nonnegative(),
40
+ turnsSinceSkill: z.number().int().nonnegative(),
41
+ lastTurn: z.number().int().nonnegative(),
42
+ }).loose();
43
+ /**
44
+ * Curator-state record schema of the storage-domain table.
45
+ * @internal Referenced only by this package's own tests and EVOLUTION_DOMAIN
46
+ * below — not public API surface (audit v10 S-03).
47
+ */
48
+ export const curatorStateSchema = z.object({
49
+ /** Optional record-shape version; legacy records without it stay compatible. */
50
+ schemaVersion: z.number().int().nonnegative().optional(),
51
+ lastRunAt: z.number().nonnegative(),
52
+ runCount: z.number().int().nonnegative(),
53
+ lastSummary: z.string(),
54
+ paused: z.boolean(),
55
+ }).loose();
56
+ /**
57
+ * Pending record schema of the storage-domain table.
58
+ * @internal Referenced only by this package's own tests and EVOLUTION_DOMAIN
59
+ * below — not public API surface (audit v10 S-03).
60
+ */
61
+ export const pendingSchema = z.object({
62
+ id: z.string(),
63
+ // S2.9/1-10: both vocabularies come from the seam contract (ONE source); the
64
+ // read-compatibility note for the producerless 'capability' member travels with
65
+ // PENDING_KINDS. This schema is what `open()` validates every stored record
66
+ // against, so one historic row must not fail the whole domain at mount.
67
+ kind: z.enum(PENDING_KINDS),
68
+ summary: z.string(),
69
+ args: z.unknown(),
70
+ createdAt: z.string(),
71
+ status: z.enum(PENDING_STATUSES),
72
+ resolvedAt: z.string().optional(),
73
+ claimedBy: z.string().optional(),
74
+ claimedAt: z.string().optional(),
75
+ // 0.3.22 (F-214): origin/sessionId were missing, so zod's default strip
76
+ // dropped them on the domain read path — a resolved audit record reopened
77
+ // from the medium lost its attribution. Added so the round-trip keeps them.
78
+ origin: z.string().optional(),
79
+ sessionId: z.string().optional(),
80
+ }).loose();
81
+ /**
82
+ * The evolution storage-domain spec: three schema-validated KV tables.
83
+ * @internal Referenced only by this package's own tests and `open()` — not
84
+ * public API surface (audit v10 S-03).
85
+ */
86
+ export const EVOLUTION_DOMAIN = defineDomain({
87
+ name: 'evolution',
88
+ version: 1,
89
+ tables: {
90
+ [REVIEW_STATE_TABLE]: domainTable(reviewStateSchema),
91
+ [CURATOR_STATE_TABLE]: domainTable(curatorStateSchema),
92
+ [PENDING_TABLE]: domainTable(pendingSchema),
93
+ },
94
+ });
95
+ /**
96
+ * Bounded open() retry (rc.42 audit P1-4, package-private): a rejected open
97
+ * used to poison the shared `opening` promise forever, so one transient
98
+ * backend failure (lock, busy) took the provider down until process restart.
99
+ * Only transient failures retry (v37 S2.5): a deterministic failure surfaces
100
+ * at once instead of re-running the whole-domain loadAll three times, and the
101
+ * cleared promise lets a later call start a fresh budget.
102
+ */
103
+ const OPEN_MAX_ATTEMPTS = 3;
104
+ const OPEN_RETRY_BASE_MS = 100;
105
+ /** Retry cannot heal these — the stored record or the medium fails its own
106
+ * schema/version, or the backend cannot serve the domain at all. Both storage
107
+ * vocabularies (DomainError, StorageError) carry the code as stable API.
108
+ * S1-D3: `already-open` (DomainError, upstream open()'s single-open constraint)
109
+ * is deterministic too — a competing consumer of the `evolution` domain never
110
+ * goes away on retry, so burning the full backoff budget (3× loadAll) and then
111
+ * leaving `opening` cleared only re-runs the same futile budget on every later
112
+ * call. */
113
+ const DETERMINISTIC_OPEN_CODES = new Set([
114
+ 'invalid-record',
115
+ 'malformed-medium',
116
+ 'version-mismatch',
117
+ 'facet-unsupported',
118
+ 'backend-not-found',
119
+ 'already-open',
120
+ 'closed',
121
+ ]);
122
+ function isTransientOpenFailure(error) {
123
+ if (typeof error !== 'object' || error === null)
124
+ return true;
125
+ const code = error.code;
126
+ return typeof code !== 'string' || !DETERMINISTIC_OPEN_CODES.has(code);
127
+ }
128
+ export function apply(ctx) {
129
+ let domain = null;
130
+ let opening = null;
131
+ async function ensure() {
132
+ if (domain)
133
+ return domain;
134
+ if (!opening) {
135
+ opening = (async () => {
136
+ const facility = storageDomainPort(ctx);
137
+ if (!facility)
138
+ throw new Error('evolution-state-domain requires @deepseek-ai/dsh-storage-domain');
139
+ let lastError;
140
+ for (let attempt = 1; attempt <= OPEN_MAX_ATTEMPTS; attempt += 1) {
141
+ try {
142
+ return await facility.open(EVOLUTION_DOMAIN);
143
+ }
144
+ catch (error) {
145
+ lastError = error;
146
+ // P2-6 (v37): retrying a deterministic failure only re-runs the
147
+ // whole-domain loadAll and delays the same rejection.
148
+ if (!isTransientOpenFailure(error) || attempt === OPEN_MAX_ATTEMPTS)
149
+ break;
150
+ await new Promise(resolve => setTimeout(resolve, OPEN_RETRY_BASE_MS * 2 ** (attempt - 1)));
151
+ }
152
+ }
153
+ throw lastError;
154
+ })();
155
+ // Clear on rejection so the next provider call starts a fresh budget.
156
+ void opening.catch(() => { opening = null; });
157
+ }
158
+ domain = await opening;
159
+ return domain;
160
+ }
161
+ async function reload() {
162
+ const current = domain;
163
+ domain = null;
164
+ opening = null;
165
+ if (current !== null)
166
+ await current.close();
167
+ }
168
+ // S1-D2: one warn per provider instance for the pending re-key repair
169
+ // (same latch discipline as the json provider's P2-5 warn).
170
+ let pendingKeyWarned = false;
171
+ const rawProvider = {
172
+ name: PROVIDER_DOMAIN,
173
+ reload,
174
+ async listReviewStates() {
175
+ const table = (await ensure()).table(REVIEW_STATE_TABLE);
176
+ return [...table.entries()].map(([sessionId, record]) => {
177
+ const { updatedAt, ...consumer } = record;
178
+ return { sessionId, record: structuredClone(consumer), ...(updatedAt === undefined ? {} : { updatedAt }) };
179
+ });
180
+ },
181
+ async loadReviewState(sessionId) {
182
+ // C-2 (v18): return a DEEP copy — the caller (advanceReview) mutates the
183
+ // record before save, and `args`-carrying records share nested objects
184
+ // with the domain map; a rejected save must not leave the domain's
185
+ // in-memory record ahead of the medium (the json provider serializes, so
186
+ // it is deep by construction).
187
+ const record = (await ensure()).table(REVIEW_STATE_TABLE).get(sessionId);
188
+ if (record === undefined)
189
+ return null;
190
+ // V24-08 (v24): strip the provider-internal eviction stamp on read so
191
+ // the consumer-facing record shape is unchanged (json parity).
192
+ const { updatedAt: _stamp, ...rest } = record;
193
+ return structuredClone(rest);
194
+ },
195
+ async saveReviewState(sessionId, record) {
196
+ // P2-1 (v18): upstream storage-domain validates stored records only on
197
+ // open(); a blind put here would persist a bad record and make the WHOLE
198
+ // evolution domain fail to open with `invalid-record` on the next mount.
199
+ // P2-12/15 (v19): the gate is the SEAM's shared contract (same one the
200
+ // json provider applies), and the stored value is a deep copy so the
201
+ // caller cannot mutate the authoritative in-memory record afterwards.
202
+ const issue = recordIssue(REVIEW_STATE_TABLE, record) ?? assertCloneable(record);
203
+ if (issue !== null)
204
+ throw new Error(`evolution-state-domain: refusing to persist an invalid review-state record: ${issue}`);
205
+ const parsed = reviewStateSchema.safeParse(record);
206
+ if (!parsed.success) {
207
+ throw new Error(`evolution-state-domain: refusing to persist an invalid review-state record: ${parsed.error.issues[0]?.message ?? 'schema mismatch'}`);
208
+ }
209
+ const table = (await ensure()).table(REVIEW_STATE_TABLE);
210
+ // V24-08 (v24): store WITH the eviction stamp — the `.loose()` schema
211
+ // passes the extra field through, and loadReviewState strips it on read
212
+ // (json parity), so the consumer-facing record shape is unchanged. The
213
+ // gate above runs on the CONSUMER record, not the stamp.
214
+ const stamped = { ...cloneRecord(parsed.data), updatedAt: Date.now() };
215
+ await table.put(sessionId, stamped);
216
+ // V24-08 (v24): session cap — the review pipeline saves on every
217
+ // turn/end and nothing pruned rows, so the table grew with the deploy's
218
+ // whole session history. Same cap discipline as the pending table
219
+ // (SEAM constant, enforced by json too). Eviction is best-effort (the
220
+ // save has already committed; a delete failure warns and retries on the
221
+ // next save). A row without `updatedAt` (pre-0.3.67 writer) sorts as
222
+ // oldest and evicts first — unlike pending's resolvedAt convention —
223
+ // because an active session re-stamps its row on its very next save, so
224
+ // the "unknown" state is always stale by construction.
225
+ const entries = [...table.entries()]
226
+ .map(([key, row]) => ({ key, updatedAt: row.updatedAt ?? 0 }))
227
+ .filter(entry => entry.key !== sessionId);
228
+ // V27 G2.2: which rows to evict is the SEAM's pure rule (shared with the
229
+ // json provider) — this provider supplies keys and stamps only.
230
+ const victims = new Set(selectSessionOverflow(entries, {
231
+ keyOf: entry => entry.key,
232
+ stampOf: entry => entry.updatedAt,
233
+ }, REVIEW_STATE_SESSION_CAP));
234
+ for (const entry of entries.filter(candidate => victims.has(candidate.key))) {
235
+ const current = table.get(entry.key);
236
+ // C-5 pattern: re-read between the snapshot and the delete — a
237
+ // concurrent save may have refreshed (or removed) the row the
238
+ // snapshot measured; only evict the exact staleness we saw.
239
+ if (current === undefined || (current.updatedAt ?? 0) !== entry.updatedAt)
240
+ continue;
241
+ await table.delete(entry.key).catch((error) => {
242
+ 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)}`);
243
+ });
244
+ }
245
+ },
246
+ async loadCuratorState() {
247
+ const record = (await ensure()).table(CURATOR_STATE_TABLE).get(CURATOR_STATE_KEY);
248
+ return record === undefined ? null : structuredClone(record);
249
+ },
250
+ async saveCuratorState(record) {
251
+ // P2-1 (v18): same write-boundary validation as saveReviewState — the
252
+ // domain `put` itself does not parse, only `open()` does.
253
+ // P2-12/15 (v19): shared seam gate + deep copy.
254
+ const issue = recordIssue(CURATOR_STATE_TABLE, record) ?? assertCloneable(record);
255
+ if (issue !== null)
256
+ throw new Error(`evolution-state-domain: refusing to persist an invalid curator-state record: ${issue}`);
257
+ const parsed = curatorStateSchema.safeParse(record);
258
+ if (!parsed.success) {
259
+ throw new Error(`evolution-state-domain: refusing to persist an invalid curator-state record: ${parsed.error.issues[0]?.message ?? 'schema mismatch'}`);
260
+ }
261
+ await (await ensure()).table(CURATOR_STATE_TABLE).put(CURATOR_STATE_KEY, cloneRecord(parsed.data));
262
+ },
263
+ async transactCuratorState(task) {
264
+ const table = (await ensure()).table(CURATOR_STATE_TABLE);
265
+ // P2-12 (v19): the task's output is validated with the SAME seam gate as
266
+ // the direct save paths — this fourth write path used to bypass every
267
+ // check, so a consumer returning a malformed record persisted it and the
268
+ // next `open()` failed the whole domain with `invalid-record`.
269
+ const guarded = (current) => {
270
+ // V27 S4: hand the task a COPY. The storage-domain update callback
271
+ // receives the live stored object (upstream requires it not be mutated
272
+ // in place), and a task that mutated it and then failed the validation
273
+ // below would leave the mutation in the provider's in-memory store
274
+ // while the write was refused. json already hands a freshly parsed
275
+ // object, so this also aligns the two providers (transactCuratorState
276
+ // contract in evolution-state-storage).
277
+ const next = task(current === null ? null : cloneRecord(current));
278
+ if (next === null)
279
+ return null;
280
+ const issue = recordIssue(CURATOR_STATE_TABLE, next) ?? assertCloneable(next);
281
+ if (issue !== null)
282
+ throw new Error(`evolution-state-domain: refusing to persist an invalid curator-state record: ${issue}`);
283
+ return cloneRecord(next);
284
+ };
285
+ // Atomic read-modify-write on the domain write chain: `task` sees the
286
+ // record current at its queue slot, so a setPaused racing the run-core
287
+ // bookkeeping write never interleaves. task returns null to keep the
288
+ // record unchanged (the domain update primitive cannot delete).
289
+ try {
290
+ await table.update(CURATOR_STATE_KEY, current => guarded(current) ?? current);
291
+ return;
292
+ }
293
+ catch (error) {
294
+ if (!isDomainErrorCode(error, 'missing-key'))
295
+ throw error;
296
+ }
297
+ // P2-4: fresh-install missing-key recovery now retries the
298
+ // SAME atomic update ONCE before seeding. The old shape (update reject →
299
+ // task(null) → bare put) computed the seed from a stale null basis: a
300
+ // concurrent first-writer that created the key between our failed
301
+ // update and our put was silently OVERWRITTEN (lost update), violating
302
+ // the seam's "whole RMW inside one transact" contract. The optimistic
303
+ // retry re-enters the domain write chain: if the concurrent writer has
304
+ // created the key meanwhile, `task` runs on the FRESH basis and nothing
305
+ // is lost. Only a SECOND missing-key proves the key still absent, so the
306
+ // seed below is safe against the common race — the residual window
307
+ // between that second missing-key and the put is a narrow lost-update
308
+ // possibility (no conditional-put primitive on the domain seam), not a
309
+ // "races no third party" guarantee.
310
+ try {
311
+ await table.update(CURATOR_STATE_KEY, current => guarded(current) ?? current);
312
+ return;
313
+ }
314
+ catch (error) {
315
+ if (!isDomainErrorCode(error, 'missing-key'))
316
+ throw error;
317
+ }
318
+ // Fresh install, still no record: seed by applying the task to null and
319
+ // putting the result (delete when null) — same seam gate as above.
320
+ const next = guarded(null);
321
+ if (next !== null)
322
+ await table.put(CURATOR_STATE_KEY, next);
323
+ else
324
+ await table.delete(CURATOR_STATE_KEY);
325
+ },
326
+ async listPending(status = 'pending') {
327
+ const table = (await ensure()).table(PENDING_TABLE);
328
+ // C-2 (v18): deep copies, so a consumer cannot mutate the domain map
329
+ // (including the nested `args` object of a pending record).
330
+ // P2-15 (v19): filter BEFORE cloning — the v18 shape cloned every record
331
+ // first, so one non-cloneable record (a function in `args`, which the
332
+ // write gate now refuses) would have thrown for every status.
333
+ // S1-D2: a table entry whose KEY drifted from `record.id` used to be
334
+ // listed here yet was unreachable by claim/resolve (they look the record
335
+ // up by id) — and, being `pending`, it was never evicted: a permanent
336
+ // zombie in the approval view. Parity with the json provider's P2-5
337
+ // re-key: the read repairs the drift (canonical slot re-put, drifted key
338
+ // deleted) and warns once. PLAN S3.1 (2026-09-16): on a same-id twin the
339
+ // tie-break is the json keyPendingById rule — canonical slot wins, else
340
+ // the first entry in file order; a drifted row never overwrites it.
341
+ const entries = [...table.entries()];
342
+ const drifted = [];
343
+ for (const [key, record] of entries) {
344
+ if (key !== record.id && typeof record.id === 'string' && record.id !== '')
345
+ drifted.push({ key, record });
346
+ }
347
+ if (drifted.length > 0) {
348
+ if (!pendingKeyWarned) {
349
+ pendingKeyWarned = true;
350
+ 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`);
351
+ }
352
+ for (const { key, record } of drifted) {
353
+ try {
354
+ // PLAN S3.1 (2026-09-16): canonical slot wins on drift repair —
355
+ // matches json keyPendingById ("the canonical slot wins, else the
356
+ // first entry in file order"). When a canonical entry for this id
357
+ // already exists (a pre-existing resolved row, or a drifted
358
+ // sibling repaired earlier in this same loop), the drifted row is
359
+ // residue: delete it, never overwrite the canonical record (the
360
+ // unconditional put used to let a stale `pending` twin silently
361
+ // replace a resolved record under the shared id).
362
+ if (table.get(record.id) !== undefined) {
363
+ await table.delete(key);
364
+ continue;
365
+ }
366
+ await table.put(record.id, structuredClone(record));
367
+ await table.delete(key);
368
+ }
369
+ catch (error) {
370
+ 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)}`);
371
+ break;
372
+ }
373
+ }
374
+ }
375
+ // Post-repair snapshot: a repaired row now lives under its canonical id
376
+ // (and only there), so a plain status filter over the fresh read is the
377
+ // same list claim/resolve can address. S2-O3: if a repair's delete half
378
+ // failed, both rows (drifted key + canonical id) can coexist — dedupe by
379
+ // record.id so the approval view never lists one record twice.
380
+ const final = drifted.length > 0 ? [...table.entries()] : entries;
381
+ // PLAN S3.1 (audit 1-1, P1): the STATUS filter runs FIRST, the id dedupe second. The old
382
+ // order consumed the id before judging the status, so when a repair's delete half had
383
+ // failed and a `pending` twin was listed before the canonical `approved` row, the twin ate
384
+ // the id and the approved record vanished from the approval view — listed nowhere, reported
385
+ // nowhere. (The json provider never had this shape: it converges by id into a map first and
386
+ // filters that map afterwards.)
387
+ const seen = new Set();
388
+ return final
389
+ .filter(([, value]) => value.status === status)
390
+ .filter(([, value]) => {
391
+ if (seen.has(value.id))
392
+ return false;
393
+ seen.add(value.id);
394
+ return true;
395
+ })
396
+ .map(([, value]) => structuredClone(value));
397
+ },
398
+ async savePending(record) {
399
+ // C-3 (v18) + P2-12/15 (v19): the seam's shared gate covers the required
400
+ // `args` key, every field type and cloneability — the same checks the
401
+ // json provider applies, so neither medium can persist what the other
402
+ // would refuse. The stored value is a deep copy (P2-14: `args` used to be
403
+ // shared by reference with the caller).
404
+ const issue = recordIssue(PENDING_TABLE, record) ?? assertCloneable(record);
405
+ if (issue !== null)
406
+ throw new Error(`evolution-state-domain: refusing to persist an invalid pending record: ${issue}`);
407
+ const parsed = pendingSchema.safeParse(record);
408
+ if (!parsed.success) {
409
+ throw new Error(`evolution-state-domain: refusing to persist an invalid pending record: ${parsed.error.issues[0]?.message ?? 'schema mismatch'}`);
410
+ }
411
+ await (await ensure()).table(PENDING_TABLE).put(record.id, cloneRecord(parsed.data));
412
+ },
413
+ async claimPending(id, claimId) {
414
+ // v20 (A-4) provider contract, applies to EVERY guarded RMW below
415
+ // (claim/resolve/release/transact): a REJECTED transition returns
416
+ // `current` unchanged, and the upstream domain `update` primitive
417
+ // persists unconditionally — so a rejection still costs one no-op
418
+ // backend write plus one `domain/changed` event. This is accepted
419
+ // seam behavior, NOT a bug: the seam has no conditional-write
420
+ // primitive, short-circuiting here would break the atomicity the
421
+ // update callback provides, and the json provider's byte-identical
422
+ // short-circuit (core io.ts `next !== current`) is the documented
423
+ // asymmetry between the two media. Consequences: duplicate approve/
424
+ // resolve clicks and "null = keep" transacts churn one write each;
425
+ // `domain/changed` listeners must tolerate no-op puts.
426
+ const table = (await ensure()).table(PENDING_TABLE);
427
+ try {
428
+ const slot = { record: null };
429
+ const now = Date.now();
430
+ await table.update(id, (current) => {
431
+ // 0.3.17 (S3.3, E-24): SAME transition table as the json provider
432
+ // (state-storage helpers) — claim atomically moves to 'executing' so
433
+ // a crash mid-approve can never double-execute the runner.
434
+ if (!canClaimPending(current.status))
435
+ return current;
436
+ slot.record = { ...current, status: 'executing', claimedBy: claimId, claimedAt: new Date(now).toISOString() };
437
+ return slot.record;
438
+ });
439
+ // V6-33 (0.3.37): return a copy — the update callback's no-change
440
+ // paths may hand back the internal record object; an in-place mutation
441
+ // by the caller would silently poison the domain map (the json
442
+ // provider returns copies).
443
+ return slot.record === null ? null : structuredClone(slot.record);
444
+ }
445
+ catch (error) {
446
+ // Missing key is the benign "no such pending record" outcome; a
447
+ // closed domain or backend failure must surface so approval reports
448
+ // the real cause instead of "already being resolved" (v3-round self-check).
449
+ if (isDomainErrorCode(error, 'missing-key'))
450
+ return null;
451
+ throw error;
452
+ }
453
+ },
454
+ async releasePendingClaim(id, claimId) {
455
+ const table = (await ensure()).table(PENDING_TABLE);
456
+ try {
457
+ await table.update(id, (current) => {
458
+ if (current.status !== 'pending' && current.status !== 'executing')
459
+ return current;
460
+ if (current.claimedBy !== claimId)
461
+ return current;
462
+ const released = { ...current, status: releasedStatus(current.status) };
463
+ delete released.claimedBy;
464
+ delete released.claimedAt;
465
+ return released;
466
+ });
467
+ }
468
+ catch (error) {
469
+ // 0.3.22 (F-332): release is a no-op on a record that never existed,
470
+ // matching the json provider (and the claimPending/tryResolvePending
471
+ // benign-vs-malign split); a closed/backend error still surfaces.
472
+ if (isDomainErrorCode(error, 'missing-key'))
473
+ return;
474
+ throw error;
475
+ }
476
+ },
477
+ async tryResolvePending(id, status, expectedClaimId) {
478
+ const table = (await ensure()).table(PENDING_TABLE);
479
+ try {
480
+ const resolved = { record: null };
481
+ const record = await table.update(id, (current) => {
482
+ if (!canResolvePending(current.status))
483
+ return current;
484
+ // P2-2 (v14): claim-scoped resolve — refuse once the record is no
485
+ // longer ours (same rule as the json provider).
486
+ if (expectedClaimId !== undefined && current.claimedBy !== expectedClaimId)
487
+ return current;
488
+ resolved.record = { ...current, status, resolvedAt: new Date().toISOString() };
489
+ return resolved.record;
490
+ });
491
+ // P2-4 (v15): the live pending table is bounded by the seam contract
492
+ // (`PENDING_RESOLVED_CAP`, the same number the json provider enforces)
493
+ // — the domain table used to grow without bound because json's
494
+ // cap/archive had no domain counterpart. json's audit ARCHIVE sidecar
495
+ // stays json-specific (no sidecar facility on the domain seam).
496
+ // P2 (v16): three corrections to the first cut — (1) the budget counts
497
+ // RESOLVED records only (pending/executing no longer shrink it), which
498
+ // is what the seam JSDoc and json's `enforceResolvedCap` already say;
499
+ // (2) a missing/unparseable resolvedAt sorts LAST (json parity — an
500
+ // unknown time must not make a record the oldest), via Date.parse
501
+ // instead of localeCompare so both providers agree on ordering;
502
+ // (3) eviction is best-effort: the resolve has already committed, so a
503
+ // delete failure warns instead of surfacing as a failed approve.
504
+ // P2-13 (v19) residual, stated precisely: upstream `Table.delete`
505
+ // decides existence at its own queue slot, so a `savePending` enqueued
506
+ // AFTER the synchronous `table.get` re-check below but BEFORE the
507
+ // delete job would be deleted. Closing that window needs a conditional
508
+ // delete primitive the seam does not have (the audit's C-5 direction);
509
+ // the re-check narrows it and in-tree mounts use randomUUID ids, so it
510
+ // requires a third-party/hand-written id reused across the window.
511
+ if (resolved.record !== null) {
512
+ // V27 G2.2: eligibility + ordering come from the SEAM's pure rule
513
+ // (shared with the json provider); this provider keeps only its
514
+ // medium-specific part — the C-5 re-read guard before each delete.
515
+ const evictedRecords = new Set(selectPendingOverflow([...table.entries()].map(([, record]) => record), SEAM_PENDING_RESOLVED_CAP));
516
+ const evicted = [...table.entries()]
517
+ .filter(([, record]) => evictedRecords.has(record))
518
+ .map(([key, record]) => ({ key, record }));
519
+ for (const entry of evicted) {
520
+ // C-5 (v18): the entries() snapshot and this delete are separate
521
+ // operations, and the domain seam has no conditional write — a
522
+ // concurrent savePending can re-mount the SAME key as a live
523
+ // pending record in between (third-party/hand-written ids; in-tree
524
+ // mounts use randomUUID). Re-read and refuse to evict unless the
525
+ // record is still the resolved one the snapshot measured.
526
+ const current = table.get(entry.key);
527
+ const stillResolved = current !== undefined
528
+ && (current.status === 'approved' || current.status === 'rejected')
529
+ && current.resolvedAt === entry.record.resolvedAt;
530
+ if (!stillResolved)
531
+ continue;
532
+ await table.delete(entry.key).catch((error) => {
533
+ 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)}`);
534
+ });
535
+ }
536
+ }
537
+ const rawRecord = record;
538
+ if (resolved.record === null) {
539
+ return { record: rawRecord === null ? null : structuredClone(rawRecord), applied: false };
540
+ }
541
+ return { record: structuredClone(resolved.record), applied: true };
542
+ }
543
+ catch (error) {
544
+ // v3-round self-check: only missing-key is benign; closed/backend errors propagate.
545
+ if (isDomainErrorCode(error, 'missing-key'))
546
+ return { record: null, applied: false };
547
+ throw error;
548
+ }
549
+ },
550
+ };
551
+ // A2: every provider call and a reload share one queue, and an idle queue starts a call
552
+ // synchronously so an in-flight open is visible to the dispose hook (E-17).
553
+ let providerQueue = Promise.resolve();
554
+ let providerBusy = false;
555
+ function withProvider(task) {
556
+ if (!providerBusy) {
557
+ providerBusy = true;
558
+ const run = task();
559
+ providerQueue = run.then(() => { providerBusy = false; }, () => { providerBusy = false; });
560
+ return run;
561
+ }
562
+ const run = providerQueue.then(task, task);
563
+ providerQueue = run.then(() => undefined, () => undefined);
564
+ return run;
565
+ }
566
+ const provider = new Proxy(rawProvider, {
567
+ get(target, key) {
568
+ const value = Reflect.get(target, key);
569
+ if (typeof value !== 'function')
570
+ return value;
571
+ return (...args) => withProvider(async () => await value.apply(target, args));
572
+ },
573
+ });
574
+ ctx.effect(() => {
575
+ const dispose = ctx.evolutionStateStorage.registerProvider(provider);
576
+ return async () => {
577
+ dispose();
578
+ await providerQueue.catch(() => { });
579
+ // 0.3.17 (E-17): an in-flight open (still inside its retry budget) used
580
+ // to resolve AFTER disposal and left the freshly opened domain unclosed —
581
+ // a fast enable/disable cycle leaked a handle. Wait for it, then close.
582
+ if (opening)
583
+ await opening.catch(() => null);
584
+ if (domain)
585
+ await domain.close();
586
+ domain = null;
587
+ opening = null;
588
+ };
589
+ }, 'evolution-state-domain.provider');
590
+ }
591
+ export * from "./compatibility.js";
592
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Durable evolution state consumer.
3
+ *
4
+ * The service owns no medium and performs no IO. It resolves the mounted
5
+ * provider from `ctx.evolutionStateStorage` (see evolution-state-json and
6
+ * evolution-state-domain); `provider` config may pin one by name.
7
+ * @module @lmzhen/dsh-evolution-core/state
8
+ */
9
+ import { Context, Service } from '@deepseek-ai/cordis';
10
+ import type Schema from '@deepseek-ai/schemastery';
11
+ import type { CuratorStateRecord, PendingRecord, PendingStatus, ReviewStateRecord } from './storage.ts';
12
+ export * from './storage.ts';
13
+ export type { CuratorStateRecord, EvolutionStateStorage, PendingRecord, PendingStatus, ReviewStateRecord, } from './storage.ts';
14
+ declare module '@deepseek-ai/cordis' {
15
+ interface Context {
16
+ evolutionState: EvolutionState;
17
+ }
18
+ }
19
+ export interface Config {
20
+ /** Pin a provider by name; `auto` picks store after the migration marker, else domain. */
21
+ provider?: string;
22
+ /** Evolution home override (tests/migration); defaults to `evolutionHome()`. */
23
+ home?: string;
24
+ }
25
+ export declare class EvolutionState extends Service {
26
+ static inject: string[];
27
+ static Config: Schema<Config>;
28
+ private readonly providerName;
29
+ private readonly home;
30
+ constructor(ctx: Context, config?: Config);
31
+ /** P2-5: the multi-provider refusal is not a mount-time-only check. A provider
32
+ * registered after this row mounted used to make registration order the effective
33
+ * medium with no pin — exactly the silent rebind the mount check exists to stop. */
34
+ /** Validate the marker + a real store image before auto may select it. */
35
+ private assertMarkerStore;
36
+ private assertProviderChoice;
37
+ /** `auto` is the migration switch: the marker is the explicit one-way signal. */
38
+ private autoProviderName;
39
+ /** Validate synchronously (legacy callers rely on a throw, not a rejected promise). */
40
+ private assertResolvable;
41
+ /** Validate, then serialize against migration across processes. */
42
+ private run;
43
+ /** Serialize state operations against the migration command across processes. */
44
+ private withStateLock;
45
+ private storage;
46
+ /** A2: refresh the mounted provider before a decision reads pending state. */
47
+ reload(): Promise<void>;
48
+ loadReviewState(sessionId: string): Promise<ReviewStateRecord | null>;
49
+ saveReviewState(sessionId: string, record: ReviewStateRecord): Promise<void>;
50
+ loadCuratorState(): Promise<CuratorStateRecord | null>;
51
+ saveCuratorState(record: CuratorStateRecord): Promise<void>;
52
+ /** Atomic read-modify-write the curator-state record (S5.5): `task` returns
53
+ * the next record; returning null keeps the current record unchanged (the
54
+ * seam has no delete semantic). */
55
+ transactCuratorState(task: (current: CuratorStateRecord | null) => CuratorStateRecord | null): Promise<void>;
56
+ listPending(status?: PendingStatus): Promise<PendingRecord[]>;
57
+ savePending(record: PendingRecord): Promise<void>;
58
+ tryResolvePending(id: string, status: 'approved' | 'rejected', expectedClaimId?: string): Promise<import("./storage.ts").PendingResolution>;
59
+ claimPending(id: string, claimId: string): Promise<PendingRecord | null>;
60
+ releasePendingClaim(id: string, claimId: string): Promise<void>;
61
+ }
62
+ export default EvolutionState;
63
+ //# sourceMappingURL=index.d.ts.map