@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,605 @@
1
+ import { Service } from "@deepseek-ai/cordis";
2
+ //#region lib/types/state/constants.js
3
+ /**
4
+ * Single source for the state-stack magic strings (audit v10 S-06).
5
+ *
6
+ * The singleton curator key, the on-disk state file names, the provider names
7
+ * and the domain table names live here so the two providers (json/domain)
8
+ * cannot drift a literal independently — a drifted literal is exactly the
9
+ * E-10 divergence class both providers already guard against elsewhere.
10
+ * These values are FORMAT-STABLE: the file names and the `'primary'` key are
11
+ * on-disk contracts, the provider names are registry keys, and the table
12
+ * names are domain-spec keys — renaming any of them orphans data or breaks
13
+ * the seam, never rename casually.
14
+ * @module @lmzhen/dsh-evolution-core/state/storage/src/constants
15
+ */
16
+ /** Singleton curator-state record key in both providers (the json map key and
17
+ * the domain table key). */
18
+ const CURATOR_STATE_KEY = "primary";
19
+ /** Provider names as registered on the `evolutionStateStorage` seam. */
20
+ const PROVIDER_DOMAIN = "domain";
21
+ const PROVIDER_STORE = "store";
22
+ /** Marker written after an explicit domain→store migration; `auto` uses it to pick the authority. */
23
+ const STATE_MIGRATION_MARKER = ".migrated-from-domain.json";
24
+ /** Domain table names of the evolution storage-domain spec. */
25
+ const REVIEW_STATE_TABLE = "review_state";
26
+ const CURATOR_STATE_TABLE = "curator_state";
27
+ const PENDING_TABLE = "pending";
28
+ /** P2-4 (v15): the live pending map/table is BOUNDED on the RESOLVE path —
29
+ * `tryResolvePending` drops the oldest resolved (approved/rejected) records by
30
+ * `resolvedAt` once more than this many exist. Single source (the v15 audit
31
+ * found the bound was json-only, so domain deployments grew the table without
32
+ * bound).
33
+ *
34
+ * C-6 (v18) contract precision: a direct `savePending` of an already-resolved
35
+ * record does NOT trigger eviction (the cap is maintained by the resolve
36
+ * operation, not by the writer), and pending/executing records are never
37
+ * trimmed. Callers that write resolved audit records themselves own that
38
+ * growth; the seam's resolve path is what keeps the table bounded.
39
+ * The audit ARCHIVE sidecar that json maintains beyond the cap stays
40
+ * json-specific (domain has no sidecar facility) — declared in both READMEs. */
41
+ const PENDING_RESOLVED_CAP = 200;
42
+ /**
43
+ * V24-08 (v24): session rows in the review-state table, per session id. The
44
+ * review pipeline saves on EVERY turn/end of EVERY session and nothing ever
45
+ * deleted rows, so the file grew (and was fully rewritten) with the deploy's
46
+ * whole session history — the same unbounded-growth class the pending cap
47
+ * above already fixed for approvals. A review row is advisory cadence state:
48
+ * evicting the least-recently-active session merely lets that session's next
49
+ * review fire from a fresh counter, so a generous cap is loss-less in
50
+ * practice. Enforced by BOTH providers inside their save path (no seam
51
+ * interface change, no background sweeper).
52
+ */
53
+ const REVIEW_STATE_SESSION_CAP = 500;
54
+ //#endregion
55
+ //#region lib/types/state/record-contract.js
56
+ /**
57
+ * Record contract of the three seam tables (P2-12/14/15/16/18, v19).
58
+ *
59
+ * The contract belongs to the SEAM, not to each provider: before this module
60
+ * the json provider gated writes with plain field predicates while the domain
61
+ * provider relied on its zod schemas, so the same consumer code behaved
62
+ * differently per medium — `transactCuratorState` skipped validation entirely
63
+ * on domain, unknown fields were stripped by zod but preserved by json,
64
+ * `args` was shared by reference on domain, and a non-cloneable payload
65
+ * poisoned every later read. Both providers now call these functions.
66
+ *
67
+ * @module @lmzhen/dsh-evolution-core/state/storage/src/record-contract
68
+ */
69
+ const isNonNegInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
70
+ const optionalString = (value) => value === void 0 || typeof value === "string";
71
+ /** 0.3.17 (S3.5, D-4): 'skill_batch' is gone — nothing ever created one (a dead enum member). A
72
+ * historic value, if it ever reached disk, is read as an unknown kind by consumers rather than
73
+ * minted here.
74
+ *
75
+ * 0.3.66: 'capability' stays with NO producer — the evolution-capability adapter was removed. It is
76
+ * a read-compatibility member: state written by an install that used that adapter (≤0.3.65) still
77
+ * holds such records, and they must keep loading, listing in `/evolution pending`, and answering
78
+ * approve or reject. Dropping it would strand them two ways: json quarantines the row to
79
+ * `<file>.corrupt` and refuses the resolving write, while the domain provider validates every
80
+ * stored record at mount, so one such row fails the whole domain with `invalid-record`.
81
+ *
82
+ * S2.9/1-10: this array is the ONE source of the vocabulary — the types, the write gate below and
83
+ * the domain provider's schema all derive from it. A second literal copy is the E-10 drift class
84
+ * this module exists to end. */
85
+ const PENDING_KINDS = [
86
+ "memory",
87
+ "skill",
88
+ "capability"
89
+ ];
90
+ /** 0.3.17 (S3.3, E-24): 'executing' = claimed, runner in flight — a fresh claim only takes
91
+ * 'pending', and resolve accepts 'pending'/'executing', so a crash mid-approve can never
92
+ * double-execute the runner. Same one-source rule as PENDING_KINDS. */
93
+ const PENDING_STATUSES = [
94
+ "pending",
95
+ "executing",
96
+ "approved",
97
+ "rejected"
98
+ ];
99
+ /** Membership test for the write gate (per record per write, so the Set is worth it). */
100
+ const PENDING_KIND_SET = new Set(PENDING_KINDS);
101
+ /** Membership test for the write gate. */
102
+ const PENDING_STATUS_SET = new Set(PENDING_STATUSES);
103
+ /**
104
+ * The write gate for one record. Both providers call this before persisting,
105
+ * so a record the other provider would refuse can never land.
106
+ * @param table - the seam table the record belongs to.
107
+ * @param record - the candidate record.
108
+ * @returns a human-readable issue, or null when the record is well-formed.
109
+ */
110
+ function recordIssue(table, record) {
111
+ if (record === null || typeof record !== "object" || Array.isArray(record)) return "record must be a plain object";
112
+ const value = record;
113
+ if (table === "review_state") {
114
+ if (!isNonNegInt(value.turnsSinceMemory)) return "turnsSinceMemory must be a non-negative integer";
115
+ if (!isNonNegInt(value.turnsSinceSkill)) return "turnsSinceSkill must be a non-negative integer";
116
+ if (!isNonNegInt(value.lastTurn)) return "lastTurn must be a non-negative integer";
117
+ return null;
118
+ }
119
+ if (table === "curator_state") {
120
+ if (value.schemaVersion !== void 0 && !isNonNegInt(value.schemaVersion)) return "schemaVersion must be a non-negative integer when present";
121
+ if (typeof value.lastRunAt !== "number" || !Number.isFinite(value.lastRunAt) || value.lastRunAt < 0) return "lastRunAt must be a finite non-negative number";
122
+ if (!isNonNegInt(value.runCount)) return "runCount must be a non-negative integer";
123
+ if (typeof value.lastSummary !== "string") return "lastSummary must be a string";
124
+ if (typeof value.paused !== "boolean") return "paused must be a boolean";
125
+ return null;
126
+ }
127
+ if (typeof value.id !== "string") return "id must be a string";
128
+ if (typeof value.kind !== "string" || !PENDING_KIND_SET.has(value.kind)) return `kind must be ${PENDING_KINDS.join("|")}`;
129
+ if (typeof value.summary !== "string") return "summary must be a string";
130
+ if (!Object.prototype.hasOwnProperty.call(value, "args")) return "args key is required (may be any cloneable value)";
131
+ if (value.args === void 0) return "args must be a cloneable value — `undefined` is dropped by the json medium and the record would be unreadable after a restart (pass {} instead)";
132
+ if (typeof value.createdAt !== "string") return "createdAt must be a string";
133
+ if (typeof value.status !== "string" || !PENDING_STATUS_SET.has(value.status)) return `status must be ${PENDING_STATUSES.join("|")}`;
134
+ for (const field of [
135
+ "resolvedAt",
136
+ "claimedBy",
137
+ "claimedAt",
138
+ "origin",
139
+ "sessionId"
140
+ ]) if (!optionalString(value[field])) return `${field} must be a string when present`;
141
+ return null;
142
+ }
143
+ /**
144
+ * P2-15 (v19): the value must survive the seam's copy discipline. A payload
145
+ * that cannot be structured-cloned (functions, symbols, class instances with
146
+ * private state) would make every later read throw far away from the write.
147
+ * @param record - the candidate record.
148
+ * @returns a human-readable issue, or null when the value is cloneable.
149
+ */
150
+ function assertCloneable(record) {
151
+ try {
152
+ structuredClone(record);
153
+ return null;
154
+ } catch (error) {
155
+ return `record is not structured-cloneable (${error instanceof Error ? error.message : String(error)})`;
156
+ }
157
+ }
158
+ /** Deep copy for every boundary crossing (read AND write). @param record - the value to copy. @returns an independent deep copy. */
159
+ function cloneRecord(record) {
160
+ return structuredClone(record);
161
+ }
162
+ //#endregion
163
+ //#region lib/types/state/conformance.js
164
+ /**
165
+ * Published conformance suite for `EvolutionStateStorage` providers (J-5 / S3-2).
166
+ *
167
+ * A third-party provider (or a new medium inside this family) runs ONE call to
168
+ * check the seam contract end to end: field-complete round-trips, claim/resolve
169
+ * rollback, refusal at the write boundary, clone/alias independence, unknown-field
170
+ * preservation, and the two seam caps (the resolved pending tail and the
171
+ * review-state session rows).
172
+ *
173
+ * The assertion surface is INJECTED ({@link ConformanceAssert}) rather than
174
+ * imported: vitest satisfies it in-tree, and a host that only has node:assert can
175
+ * wrap it in a few lines. That keeps this module free of any test-runner import,
176
+ * so it ships inside the published package.
177
+ */
178
+ /**
179
+ * Cross-provider consistency harness (G7.4, 0.3.22; V4-07 0.3.28).
180
+ *
181
+ * Runs the SAME observable operation sequence against an
182
+ * `EvolutionStateStorage` provider (json or domain) and asserts both yield the
183
+ * same field-complete result. Every pending-record field that is carried
184
+ * through a round-trip is compared field by field: id, kind, status, summary,
185
+ * args, createdAt, origin, sessionId, claimedBy. The wall-clock holder stamps
186
+ * (claimedAt, resolvedAt) are generated by each provider at its own transact
187
+ * time and legitimately differ in value between the two claims, so they are
188
+ * asserted only for presence/type (a string), never for equality — and
189
+ * claimedAt is asserted to be cleared on release. Status filtering / release
190
+ * rollback must agree. S2-4 (v29): the two seam caps — the resolved pending
191
+ * tail (P2-4) and the review-state session rows (V24-08) — are exercised through
192
+ * the same public operations on both providers, so neither medium can keep the
193
+ * bound to itself.
194
+ */
195
+ /** Build a fixture pending record, optionally carrying origin/sessionId. The suite's own stamp and
196
+ * namespace come from {@link ConformanceOptions} — see `basePendingOf`'s call sites. */
197
+ const basePendingOf = (id, kind = "memory", attribution = {}) => ({
198
+ id,
199
+ kind,
200
+ summary: `${kind}:${id}`,
201
+ args: {},
202
+ createdAt: "now",
203
+ status: "pending",
204
+ ...attribution
205
+ });
206
+ /** Every non-holder pending field must equal the input, field by field. */
207
+ const expectPendingCarried = (assert, actual, input) => {
208
+ assert(actual).toBeDefined();
209
+ const carried = actual;
210
+ assert(carried.id).toBe(input.id);
211
+ assert(carried.kind).toBe(input.kind);
212
+ assert(carried.summary).toBe(input.summary);
213
+ assert(carried.args).toEqual(input.args);
214
+ assert(carried.createdAt).toBe(input.createdAt);
215
+ assert(carried.origin).toBe(input.origin);
216
+ assert(carried.sessionId).toBe(input.sessionId);
217
+ };
218
+ /** The listing must contain `id`; a missing row fails the SUITE, not the runner. */
219
+ const findRecord = (records, id) => {
220
+ const found = records.find((record) => record.id === id);
221
+ if (found === void 0) throw new Error(`conformance: pending record "${id}" missing from the listing`);
222
+ return found;
223
+ };
224
+ async function runStateProviderConsistency(provider, assert, options = {}) {
225
+ const idPrefix = options.idPrefix ?? "c-";
226
+ const claimPrefix = options.claimPrefix ?? "claim-";
227
+ const stamp = options.createdAt ?? "now";
228
+ const sessionId = options.sessionId ?? "s-consistent";
229
+ const attributionSessionId = options.attributionSessionId ?? "sess-attrib";
230
+ const reviewSessionPrefix = options.reviewSessionPrefix ?? "s-cap-";
231
+ /** This run's fixture record: the module helper's fields under THIS run's namespace and stamp. */
232
+ const pending = (id, kind = "memory", attribution = {}) => ({
233
+ ...basePendingOf(id, kind, attribution),
234
+ createdAt: stamp
235
+ });
236
+ await provider.saveReviewState(sessionId, {
237
+ turnsSinceMemory: 1,
238
+ turnsSinceSkill: 2,
239
+ lastTurn: 3
240
+ });
241
+ assert(await provider.loadReviewState(sessionId)).toEqual({
242
+ turnsSinceMemory: 1,
243
+ turnsSinceSkill: 2,
244
+ lastTurn: 3
245
+ });
246
+ assert(await provider.loadCuratorState()).toBeNull();
247
+ await provider.transactCuratorState(() => ({
248
+ lastRunAt: 10,
249
+ runCount: 0,
250
+ lastSummary: "seed",
251
+ paused: false
252
+ }));
253
+ assert(await provider.loadCuratorState()).toEqual({
254
+ lastRunAt: 10,
255
+ runCount: 0,
256
+ lastSummary: "seed",
257
+ paused: false
258
+ });
259
+ await provider.transactCuratorState(() => null);
260
+ assert(await provider.loadCuratorState()).toEqual({
261
+ lastRunAt: 10,
262
+ runCount: 0,
263
+ lastSummary: "seed",
264
+ paused: false
265
+ });
266
+ await provider.transactCuratorState((current) => ({
267
+ ...current,
268
+ lastSummary: "updated"
269
+ }));
270
+ assert(await provider.loadCuratorState()).toEqual({
271
+ lastRunAt: 10,
272
+ runCount: 0,
273
+ lastSummary: "updated",
274
+ paused: false
275
+ });
276
+ await provider.transactCuratorState((current) => {
277
+ if (current !== null) {
278
+ current.runCount = 999;
279
+ current.paused = true;
280
+ }
281
+ return null;
282
+ });
283
+ assert(await provider.loadCuratorState()).toEqual({
284
+ lastRunAt: 10,
285
+ runCount: 0,
286
+ lastSummary: "updated",
287
+ paused: false
288
+ });
289
+ const live = pending(`${idPrefix}live`);
290
+ await provider.savePending(live);
291
+ assert((await provider.listPending("pending")).map((record) => record.id)).toContain(`${idPrefix}live`);
292
+ const claimed = await provider.claimPending(`${idPrefix}live`, `${claimPrefix}a`);
293
+ assert(claimed?.status).toBe("executing");
294
+ assert(claimed?.claimedBy).toBe(`${claimPrefix}a`);
295
+ expectPendingCarried(assert, claimed, live);
296
+ assert(typeof claimed?.claimedAt).toBe("string");
297
+ const resolved = await provider.tryResolvePending(`${idPrefix}live`, "approved");
298
+ assert(resolved.applied).toBe(true);
299
+ assert(resolved.record?.id).toBe(`${idPrefix}live`);
300
+ assert(resolved.record?.status).toBe("approved");
301
+ expectPendingCarried(assert, resolved.record, live);
302
+ assert(resolved.record?.claimedBy).toBe(`${claimPrefix}a`);
303
+ assert(typeof resolved.record?.claimedAt).toBe("string");
304
+ assert(typeof resolved.record?.resolvedAt).toBe("string");
305
+ assert((await provider.listPending("approved")).map((record) => record.id)).toContain(`${idPrefix}live`);
306
+ assert((await provider.listPending("pending")).map((record) => record.id)).not.toContain(`${idPrefix}live`);
307
+ const attrib = pending(`${idPrefix}attrib`, "memory", {
308
+ origin: "background_review",
309
+ sessionId: attributionSessionId
310
+ });
311
+ await provider.savePending(attrib);
312
+ expectPendingCarried(assert, await provider.claimPending(`${idPrefix}attrib`, `${claimPrefix}a`), attrib);
313
+ const attribResolved = await provider.tryResolvePending(`${idPrefix}attrib`, "approved");
314
+ expectPendingCarried(assert, attribResolved.record, attrib);
315
+ assert(attribResolved.record?.origin).toBe("background_review");
316
+ assert(attribResolved.record?.sessionId).toBe(attributionSessionId);
317
+ assert(typeof attribResolved.record?.resolvedAt).toBe("string");
318
+ const rel = pending(`${idPrefix}release`, "skill");
319
+ await provider.savePending(rel);
320
+ assert((await provider.claimPending(`${idPrefix}release`, `${claimPrefix}b`))?.status).toBe("executing");
321
+ await provider.releasePendingClaim(`${idPrefix}release`, `${claimPrefix}b`);
322
+ const released = (await provider.listPending("pending")).find((record) => record.id === `${idPrefix}release`);
323
+ assert(released?.status).toBe("pending");
324
+ expectPendingCarried(assert, released, rel);
325
+ assert(released?.claimedBy).toBeUndefined();
326
+ assert(released?.claimedAt).toBeUndefined();
327
+ const scoped = pending(`${idPrefix}scoped`);
328
+ await provider.savePending(scoped);
329
+ await provider.claimPending(`${idPrefix}scoped`, `${claimPrefix}owner`);
330
+ assert((await provider.tryResolvePending(`${idPrefix}scoped`, "approved", `${claimPrefix}foreign`)).applied).toBe(false);
331
+ assert((await provider.listPending("executing")).map((record) => record.id)).toContain(`${idPrefix}scoped`);
332
+ const ownerScope = await provider.tryResolvePending(`${idPrefix}scoped`, "approved", `${claimPrefix}owner`);
333
+ assert(ownerScope.applied).toBe(true);
334
+ assert(ownerScope.record?.status).toBe("approved");
335
+ const filt = pending(`${idPrefix}filter`);
336
+ await provider.savePending(filt);
337
+ assert((await provider.listPending("pending")).map((record) => record.id)).toContain(`${idPrefix}filter`);
338
+ assert((await provider.listPending("approved")).map((record) => record.id)).not.toContain(`${idPrefix}filter`);
339
+ const post = pending(`${idPrefix}post-resolve`, "memory");
340
+ await provider.savePending(post);
341
+ await provider.claimPending(`${idPrefix}post-resolve`, `${claimPrefix}c`);
342
+ await provider.tryResolvePending(`${idPrefix}post-resolve`, "rejected");
343
+ await provider.releasePendingClaim(`${idPrefix}post-resolve`, `${claimPrefix}c`);
344
+ const postResolved = (await provider.listPending("rejected")).find((record) => record.id === `${idPrefix}post-resolve`);
345
+ assert(postResolved?.status).toBe("rejected");
346
+ assert(postResolved?.claimedBy).toBe(`${claimPrefix}c`);
347
+ assert(typeof postResolved?.claimedAt).toBe("string");
348
+ assert(typeof postResolved?.resolvedAt).toBe("string");
349
+ await assert(provider.savePending({
350
+ id: `${idPrefix}bad`,
351
+ kind: "memory",
352
+ summary: "bad",
353
+ createdAt: stamp,
354
+ status: "pending"
355
+ })).rejects.toThrow();
356
+ const poison = pending(`${idPrefix}poison`);
357
+ poison.args = { nested: { value: 1 } };
358
+ await provider.savePending(poison);
359
+ const returned = findRecord(await provider.listPending("pending"), `${idPrefix}poison`);
360
+ returned.summary = "poisoned";
361
+ returned.args.nested.value = 99;
362
+ const reread = findRecord(await provider.listPending("pending"), `${idPrefix}poison`);
363
+ assert(reread.summary).toBe(`memory:${idPrefix}poison`);
364
+ assert(reread.args.nested.value).toBe(1);
365
+ const uncloneable = {
366
+ ...pending(`${idPrefix}uncloneable`),
367
+ args: { fn: () => {} }
368
+ };
369
+ await assert(provider.savePending(uncloneable)).rejects.toThrow();
370
+ const aliased = pending(`${idPrefix}alias`);
371
+ aliased.args = { nested: { value: 1 } };
372
+ await provider.savePending(aliased);
373
+ aliased.args.nested.value = 99;
374
+ assert(findRecord(await provider.listPending("pending"), `${idPrefix}alias`).args.nested.value).toBe(1);
375
+ await assert(provider.saveCuratorState({
376
+ lastRunAt: 1,
377
+ runCount: 0,
378
+ lastSummary: "x",
379
+ paused: false,
380
+ schemaVersion: -1
381
+ })).rejects.toThrow();
382
+ await provider.savePending({
383
+ ...pending(`${idPrefix}extra`),
384
+ extraField: "kept"
385
+ });
386
+ assert((await provider.listPending("pending")).find((record) => record.id === `${idPrefix}extra`).extraField).toBe("kept");
387
+ const capPrefix = `${idPrefix}cap-`;
388
+ await provider.savePending(pending(`${idPrefix}cap-live`, "skill"));
389
+ for (let index = 0; index <= 201; index += 1) {
390
+ const id = capPrefix + String(index).padStart(3, "0");
391
+ await provider.savePending(pending(id));
392
+ await provider.claimPending(id, `${claimPrefix}cap`);
393
+ await provider.tryResolvePending(id, "approved");
394
+ }
395
+ const resolvedNow = (await provider.listPending("approved")).concat(await provider.listPending("rejected")).filter((record) => record.kind !== "capability");
396
+ assert(resolvedNow).toHaveLength(200);
397
+ const resolvedIds = resolvedNow.map((record) => record.id);
398
+ assert(resolvedIds).not.toContain(capPrefix + "000");
399
+ assert(resolvedIds).not.toContain(capPrefix + "001");
400
+ assert(resolvedIds).toContain(capPrefix + String(201).padStart(3, "0"));
401
+ assert((await provider.listPending("pending")).map((record) => record.id)).toContain(`${idPrefix}cap-live`);
402
+ const sessionPrefix = reviewSessionPrefix;
403
+ const reviewStateOf = (turns) => ({
404
+ turnsSinceMemory: turns,
405
+ turnsSinceSkill: 0,
406
+ lastTurn: turns
407
+ });
408
+ for (let index = 0; index <= 500; index += 1) await provider.saveReviewState(sessionPrefix + String(index), reviewStateOf(index));
409
+ assert(await provider.loadReviewState(sessionPrefix + "0")).toBeNull();
410
+ assert(await provider.loadReviewState(sessionPrefix + "1")).toEqual(reviewStateOf(1));
411
+ assert(await provider.loadReviewState(sessionPrefix + String(500))).toEqual(reviewStateOf(500));
412
+ await provider.saveReviewState(sessionPrefix + "0", reviewStateOf(999));
413
+ assert(await provider.loadReviewState(sessionPrefix + "0")).toEqual(reviewStateOf(999));
414
+ }
415
+ //#endregion
416
+ //#region lib/types/state/medium-declaration.js
417
+ /**
418
+ * G2b/2b.3: which medium carries each record type, and what PROCESS SCOPE that medium actually gives.
419
+ *
420
+ * The shipped IO backend declares single-process: its transaction serializes one process only.
421
+ * The domain medium inherits whatever backend the platform storage facility routes, and that is also
422
+ * single-process in this tree. This file states the weaker truth. processScopeViolations takes the io the
423
+ * provider writes through and reports every claim of cross-process that the io cannot back up.
424
+ *
425
+ * MIGRATION NOTE: when a platform backend carrying its own cross-process guarantee lands, name it here and
426
+ * move the reasoning with it - one declaration, not two.
427
+ *
428
+ * @module @lmzhen/dsh-evolution-core/state/storage/medium-declaration
429
+ */
430
+ /** The declaration. */
431
+ const MEDIUM_PROCESS_DECLARATION = [
432
+ {
433
+ record: "review_state",
434
+ medium: "json",
435
+ scope: "single-process",
436
+ because: "the shipped IO backend declares single-process; no cross-process medium exists in this tree"
437
+ },
438
+ {
439
+ record: "curator_state",
440
+ medium: "json",
441
+ scope: "single-process",
442
+ because: "same provider and same single-process write path as review_state"
443
+ },
444
+ {
445
+ record: "pending",
446
+ medium: "json",
447
+ scope: "single-process",
448
+ because: "the shipped IO backend has no cross-process claim primitive; a staged write is serialized only in-process"
449
+ },
450
+ {
451
+ record: "evolution-domain",
452
+ medium: "domain",
453
+ scope: "single-process",
454
+ because: "no backend in this tree carries its own cross-process guarantee and none is named, so the domain facility lock semantics stay the backend business and this declares the weaker truth"
455
+ }
456
+ ];
457
+ /**
458
+ * Falsify the declaration against a capability reading.
459
+ * @param io - the io backend the medium writes through, or undefined when none is mounted.
460
+ * @param declaration - claims to falsify; defaults to the shipped declaration.
461
+ * @returns one message per claim the capability cannot back up; empty when every claim holds.
462
+ */
463
+ function processScopeViolations(io, declaration = MEDIUM_PROCESS_DECLARATION) {
464
+ const backed = io?.processScope === "cross-process";
465
+ return declaration.filter((claim) => claim.scope === "cross-process" && !backed).map((claim) => claim.record + " claims cross-process (" + claim.because + ") but the mounted io declares " + (io?.processScope ?? "no process scope"));
466
+ }
467
+ //#endregion
468
+ //#region lib/types/state/storage.js
469
+ /**
470
+ * Provider seam for durable evolution state.
471
+ *
472
+ * The state CONSUMER (`@lmzhen/dsh-evolution-core/state`) never touches a
473
+ * medium. Providers register here: `domain` (storage-domain KV) and `json`
474
+ * (IO-seam files) are the two shipped providers.
475
+ * @module @lmzhen/dsh-evolution-core/state/storage
476
+ */
477
+ /** 0.3.17 (S3.3): the claim lifecycle as ONE transition table — BOTH
478
+ * providers (json/domain) must use these, never a hand-written copy (a second
479
+ * copy is exactly the E-10 drift class). */
480
+ const canClaimPending = (status) => status === "pending";
481
+ const canResolvePending = (status) => status === "pending" || status === "executing";
482
+ /** Releasing a claim on an executing record rolls it back to pending (a
483
+ * runner FAILURE is retryable); other statuses pass through unchanged. */
484
+ const releasedStatus = (status) => status === "executing" ? "pending" : status;
485
+ /**
486
+ * V27 G2.2: WHICH pending records the audit cap evicts, as one pure rule both
487
+ * providers apply (the two implementations had drifted into separate files and
488
+ * only one of them was ever updated by a later fix).
489
+ *
490
+ * Eligible = resolved (`approved`/`rejected`) and NOT a capability approval:
491
+ * v23 (AP-1) exempts those because the Creator-mode contract reads the LIVE
492
+ * approved list and a capability cannot be re-submitted for the same package,
493
+ * so eviction would make an approved capability permanently unactivatable.
494
+ * Ordering = oldest `resolvedAt` first; a missing or unparseable timestamp sorts
495
+ * LAST (json parity, v16), and pending/executing rows are live work that is
496
+ * never trimmed. v28 G2.4 (STATE-03) — the previous wording promised "an
497
+ * unknown time must never make a record the victim"; that is only true while
498
+ * the overflow fits within the KNOWN-timestamp records. When the overflow
499
+ * exceeds them (corruption-level data: most resolved rows with broken
500
+ * timestamps), `slice` necessarily reaches into the unknown-timestamp tail —
501
+ * the cap must be enforced, so there is no alternative. The guarantee is
502
+ * therefore: unknown-timestamp records are evicted LAST, after every known
503
+ * timestamp, in insertion order among themselves (Array#sort stability).
504
+ *
505
+ * @param records - every pending record currently in the live table.
506
+ * @param cap - how many resolved records may be kept.
507
+ * @returns the records to evict, oldest first (empty when within the cap).
508
+ */
509
+ function selectPendingOverflow(records, cap = 200) {
510
+ const resolved = records.filter((record) => (record.status === "approved" || record.status === "rejected") && record.kind !== "capability");
511
+ const overflow = resolved.length - cap;
512
+ if (overflow <= 0) return [];
513
+ const resolvedAtMs = (record) => {
514
+ if (!record.resolvedAt) return Number.MAX_SAFE_INTEGER;
515
+ const parsed = Date.parse(record.resolvedAt);
516
+ return Number.isNaN(parsed) ? Number.MAX_SAFE_INTEGER : parsed;
517
+ };
518
+ return [...resolved].sort((a, b) => resolvedAtMs(a) - resolvedAtMs(b)).slice(0, overflow);
519
+ }
520
+ /**
521
+ * V27 G2.2: which review-state session rows a save evicts, as one pure rule
522
+ * both providers apply. The saving session is never a candidate (it is the most
523
+ * recent write by definition); the rest are ordered by their provider stamp
524
+ * ascending, with a missing stamp read as 0 = oldest, because an active session
525
+ * re-stamps its row on its next save and an unknown stamp is stale by
526
+ * construction. Exactly one row is dropped per over-cap save, which keeps the
527
+ * table at the cap in steady state.
528
+ *
529
+ * @param rows - the other sessions' rows, with their stamps.
530
+ * @param cap - how many session rows may exist.
531
+ * @returns the keys to delete, oldest first.
532
+ */
533
+ function selectSessionOverflow(rows, options, cap = 500) {
534
+ const overflow = rows.length - cap + 1;
535
+ if (overflow <= 0) return [];
536
+ return [...rows].sort((a, b) => options.stampOf(a) - options.stampOf(b)).slice(0, overflow).map((row) => options.keyOf(row));
537
+ }
538
+ var EvolutionStateStorageRegistry = class extends Service {
539
+ providers = /* @__PURE__ */ new Map();
540
+ /** C-7 (v18): per-name dispose, mirroring the evolution-io registry. */
541
+ disposals = /* @__PURE__ */ new Map();
542
+ /** v28 G3.1 (STATE-04): the multi-provider warn fires once per ambiguous
543
+ * period, not once per state op (provider() runs on every read/write). */
544
+ ambiguousWarned = false;
545
+ constructor(ctx) {
546
+ super(ctx, "evolutionStateStorage");
547
+ }
548
+ /** C-7 (v18): re-registering the IDENTICAL provider object is idempotent and
549
+ * returns the original dispose (HMR / re-mounted row); a DIFFERENT object
550
+ * under a registered name still fails loud. The dispose carries a generation
551
+ * guard so a stale handle cannot remove a newer registration. */
552
+ registerProvider(provider) {
553
+ const idempotent = this.providers.get(provider.name) === provider;
554
+ if (!idempotent && this.providers.has(provider.name)) throw new Error(`evolution state storage provider "${provider.name}" already registered`);
555
+ if (idempotent) {
556
+ const existing = this.disposals.get(provider.name);
557
+ if (existing !== void 0) return existing;
558
+ }
559
+ const dispose = () => {
560
+ if (this.disposals.get(provider.name) !== dispose) return;
561
+ this.providers.delete(provider.name);
562
+ this.disposals.delete(provider.name);
563
+ };
564
+ this.providers.set(provider.name, provider);
565
+ this.disposals.set(provider.name, dispose);
566
+ return dispose;
567
+ }
568
+ /** S-07: whether ANY provider is registered. Lets the state
569
+ * consumer precheck a pinned `provider` config at mount time (a typo fails
570
+ * at start with the registry's precise message) while staying lazy when no
571
+ * provider has registered yet (mount order not settled). */
572
+ hasProviders() {
573
+ return this.providers.size > 0;
574
+ }
575
+ /**
576
+ * G2b/2b.1: the registered provider names, in registration order.
577
+ *
578
+ * A consumer needs the COUNT to refuse an unpinned choice while more than one medium is mounted:
579
+ * this registry cannot make that call itself, because the pin lives in the consumer's config and the
580
+ * registry never sees it. Read-only, and it exists so the refusal can happen at mount instead of at the
581
+ * first read (where the state is already half-consumed and the message arrives too late to act on).
582
+ */
583
+ providerNames() {
584
+ return [...this.providers.keys()];
585
+ }
586
+ provider(name) {
587
+ if (name) {
588
+ this.ambiguousWarned = false;
589
+ const provider = this.providers.get(name);
590
+ if (provider) return provider;
591
+ throw new Error(`evolution state storage provider "${name}" is not registered`);
592
+ }
593
+ const first = this.providers.values().next().value;
594
+ if (!first) throw new Error("no evolution state storage provider registered; mount @lmzhen/dsh-evolution-core/state/domain or @lmzhen/dsh-evolution-core/state/domain");
595
+ if (this.providers.size > 1) {
596
+ if (!this.ambiguousWarned) {
597
+ this.ambiguousWarned = true;
598
+ this.ctx.logger.warn(`evolution state storage: ${this.providers.size} providers registered (${[...this.providers.keys()].join(", ")}), none pinned — the effective provider is "${first.name}" (registration order). Existing state under the other provider is now invisible. Pin config: { provider: json|domain } on the evolution-state row to make the choice explicit.`);
599
+ }
600
+ } else this.ambiguousWarned = false;
601
+ return first;
602
+ }
603
+ };
604
+ //#endregion
605
+ export { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, EvolutionStateStorageRegistry, EvolutionStateStorageRegistry as default, 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,23 @@
1
+ import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
2
+ import { createStateStoreProvider } from "./store.js";
3
+ //#region lib/types/state/store-plugin.js
4
+ const name = "evolution-state-store";
5
+ const inject = ["evolutionStateStorage", "evolutionIo"];
6
+ /** HMR re-applies the row in the same ctx; the registry only treats the SAME object as
7
+ * idempotent, so keep one provider per home instead of constructing a new registrant. */
8
+ const providers = /* @__PURE__ */ new Map();
9
+ async function apply(ctx) {
10
+ await ctx.evolutionIo.whenReady();
11
+ const home = evolutionHome();
12
+ let provider = providers.get(home);
13
+ if (provider === void 0) {
14
+ provider = createStateStoreProvider({
15
+ io: ctx.evolutionIo.provider(),
16
+ home
17
+ });
18
+ providers.set(home, provider);
19
+ }
20
+ ctx.effect(() => ctx.evolutionStateStorage.registerProvider(provider), "evolution-state-store.provider");
21
+ }
22
+ //#endregion
23
+ export { apply, inject, name };