@lmzhen/dsh-evolution-core 0.59.5 → 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 (111) 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-z1_hyrQn.js → mutation-storage-adapter-CSVn34dK.js} +334 -212
  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 +739 -129
  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-observation.d.ts +4 -5
  65. package/lib/types/skill-observation.js +18 -2
  66. package/lib/types/skill-store.d.ts +73 -4
  67. package/lib/types/skill-store.js +376 -29
  68. package/lib/types/skill-write-plan.d.ts +80 -0
  69. package/lib/types/skill-write-plan.js +2 -0
  70. package/lib/types/skill-write-service.d.ts +84 -2
  71. package/lib/types/skill-write-service.js +214 -35
  72. package/lib/types/skills.d.ts +2 -0
  73. package/lib/types/skills.js +2 -0
  74. package/lib/types/state/conformance.d.ts +47 -0
  75. package/lib/types/state/conformance.js +246 -0
  76. package/lib/types/state/constants.d.ts +52 -0
  77. package/lib/types/state/constants.js +52 -0
  78. package/lib/types/state/domain/compatibility.d.ts +40 -0
  79. package/lib/types/state/domain/compatibility.js +36 -0
  80. package/lib/types/state/domain/index.d.ts +81 -0
  81. package/lib/types/state/domain/index.js +592 -0
  82. package/lib/types/state/index.d.ts +63 -0
  83. package/lib/types/state/index.js +174 -0
  84. package/lib/types/state/medium-declaration.d.ts +37 -0
  85. package/lib/types/state/medium-declaration.js +53 -0
  86. package/lib/types/state/migrate.d.ts +34 -0
  87. package/lib/types/state/migrate.js +103 -0
  88. package/lib/types/state/record-contract.d.ts +56 -0
  89. package/lib/types/state/record-contract.js +120 -0
  90. package/lib/types/state/storage.d.ts +112 -0
  91. package/lib/types/state/storage.js +178 -0
  92. package/lib/types/state/store-plugin.d.ts +14 -0
  93. package/lib/types/state/store-plugin.js +18 -0
  94. package/lib/types/state/store.d.ts +39 -0
  95. package/lib/types/state/store.js +270 -0
  96. package/lib/types/store-ledger.js +2 -2
  97. package/lib/types/subagent/run.d.ts +1 -1
  98. package/lib/types/subagent/types.d.ts +4 -4
  99. package/lib/types/system-skill-writer.d.ts +21 -0
  100. package/lib/types/system-skill-writer.js +15 -0
  101. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  102. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  103. package/lib/types/tool-dispatch.js +6 -3
  104. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +44 -13
  105. package/lib/types/{mutation-unit.js → unit-kernel.js} +163 -120
  106. package/lib/types/write.d.ts +1 -2
  107. package/lib/types/write.js +1 -2
  108. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  109. package/lib/write.js +4 -4
  110. package/package.json +30 -3
  111. package/persisted-write-inventory.json +14 -5
@@ -2,7 +2,7 @@ import { basename, dirname, isAbsolute, join, relative } from 'node:path';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { isCommittedWarning, isProcessAlive, TransactionNotInvokedError, transactIo } from "./io.js";
4
4
  import { exceedsContentLimit } from "./frontmatter.js";
5
- import { WriteKernel } from "./write-kernel.js";
5
+ import { TargetWriter } from "./target-writer.js";
6
6
  function underRoot(rootDir, target) {
7
7
  if (rootDir === undefined || rootDir === '')
8
8
  return false;
@@ -94,13 +94,14 @@ const noLock = {
94
94
  },
95
95
  };
96
96
  const identitySerial = async (task) => await task();
97
- export class MutationUnit {
97
+ export class UnitKernel {
98
98
  io;
99
99
  limits;
100
100
  serial;
101
101
  lock;
102
102
  targetKeys;
103
103
  targetKeysForSnapshot;
104
+ targetKeyResolver;
104
105
  journal;
105
106
  snapshots;
106
107
  claim;
@@ -117,7 +118,7 @@ export class MutationUnit {
117
118
  this.limits = options.limits;
118
119
  this.serial = options.serial ?? identitySerial;
119
120
  if (options.lock === undefined && options.nested !== true) {
120
- throw new Error('mutation-unit: a lock (or an explicit nested:true under an outer fence) is required');
121
+ throw new Error('unit-kernel: a lock (or an explicit nested:true under an outer fence) is required');
121
122
  }
122
123
  this.lock = options.lock ?? noLock;
123
124
  this.targetKeys = options.targetKeys;
@@ -133,7 +134,12 @@ export class MutationUnit {
133
134
  this.now = options.now ?? Date.now;
134
135
  this.journalId = 'j-' + String(this.now()) + '-' + Math.random().toString(36).slice(2);
135
136
  const transact = options.transact;
136
- this.kernel = new WriteKernel({ io: this.io, ...(transact === undefined ? {} : { transact }), now: this.now });
137
+ this.kernel = new TargetWriter({ io: this.io, ...(transact === undefined ? {} : { transact }), now: this.now });
138
+ }
139
+ async resolveTargetKeys(keys) {
140
+ if (keys === undefined || this.targetKeyResolver === undefined)
141
+ return keys;
142
+ return await this.targetKeyResolver(keys);
137
143
  }
138
144
  preview(request) {
139
145
  const validation = validateMutationRequest(request, this.limits);
@@ -145,141 +151,173 @@ export class MutationUnit {
145
151
  errors: validation.errors,
146
152
  };
147
153
  }
148
- async apply(request) {
154
+ /**
155
+ * Phase 1: acquire the lease/claim and read every target, verifying CAS and
156
+ * write validation. This performs NO durable write (no journal, snapshot,
157
+ * audit or event). The returned handle holds the lease until commit() or
158
+ * release(); callers must use try/finally.
159
+ */
160
+ async prepare(request) {
149
161
  const primary = request.name.trim();
150
162
  const unitId = request.unitId ?? 'u-' + String(this.now()) + '-' + Math.random().toString(36).slice(2);
151
163
  const validation = validateMutationRequest(request, this.limits);
152
164
  if (!validation.ok)
153
165
  return { ok: false, unitId, dryRun: request.dryRun === true, changed: [], errors: validation.errors };
154
- if (request.dryRun === true)
155
- return { ok: true, unitId, dryRun: true, changed: [], errors: [] };
156
- return await this.serial(async () => {
157
- let lease;
166
+ let lease;
167
+ try {
168
+ lease = await this.lock.acquire(await this.resolveTargetKeys(this.targetKeys));
169
+ }
170
+ catch (error) {
171
+ const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
172
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code, message: error instanceof Error ? error.message : String(error) }] };
173
+ }
174
+ let claim;
175
+ const release = async () => {
176
+ await claim?.release().catch(() => { });
177
+ await lease.release();
178
+ };
179
+ if (this.claim !== undefined) {
158
180
  try {
159
- lease = await this.lock.acquire(this.targetKeys);
181
+ claim = await this.claim.acquire(primary, this.claimRunId ?? this.context?.runId ?? '');
160
182
  }
161
183
  catch (error) {
162
- const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
163
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code, message: error instanceof Error ? error.message : String(error) }] };
184
+ await lease.release();
185
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'claim-failed', message: error instanceof Error ? error.message : String(error) }] };
164
186
  }
165
- let claim;
166
- if (this.claim !== undefined) {
167
- try {
168
- claim = await this.claim.acquire(primary, this.claimRunId ?? this.context?.runId ?? '');
187
+ }
188
+ const snapshots = [];
189
+ try {
190
+ for (const op of validation.ops) {
191
+ const current = await this.io.readText(op.target);
192
+ const baseline = op.expected === undefined ? current : op.expected;
193
+ if (current !== baseline) {
194
+ await release();
195
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'cas-drift', message: 'target changed after plan', target: op.target }] };
169
196
  }
170
- catch (error) {
171
- await lease.release();
172
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'claim-failed', message: error instanceof Error ? error.message : String(error) }] };
197
+ snapshots.push({ target: op.target, before: current, after: op.kind === 'write' ? op.content : null, baseline });
198
+ }
199
+ for (const op of validation.ops) {
200
+ const refusal = this.validateWrite?.(op) ?? null;
201
+ if (refusal !== null) {
202
+ await release();
203
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'write-validation', message: refusal, target: op.target }] };
173
204
  }
174
205
  }
175
- const changed = [];
176
- const warnings = [];
177
- const bestEffort = async (task) => {
206
+ }
207
+ catch (error) {
208
+ await release();
209
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'write-failed', message: error instanceof Error ? error.message : String(error) }] };
210
+ }
211
+ const eventOps = snapshots.map(snapshot => {
212
+ const op = validation.ops.find(entry => entry.target === snapshot.target);
213
+ return {
214
+ target: snapshot.target,
215
+ before: snapshot.before,
216
+ after: op?.kind === 'write' ? op.content : null,
217
+ ...(op?.skill === undefined ? {} : { skill: op.skill }),
218
+ };
219
+ });
220
+ const changed = [];
221
+ const warnings = [];
222
+ const bestEffort = async (task) => {
223
+ try {
224
+ await task();
225
+ }
226
+ catch (error) {
227
+ if (!isCommittedWarning(error))
228
+ throw error;
229
+ warnings.push(error instanceof Error ? error.message : String(error));
230
+ }
231
+ };
232
+ return { kind: 'prepared', unitId, request, primary, validation, snapshots, eventOps, changed, warnings, bestEffort, release };
233
+ }
234
+ /** Phase 2: the only durable write phase. Releases the prepare lease in all paths. */
235
+ async commit(prepared) {
236
+ const { unitId, request, primary, validation, snapshots, eventOps, changed, warnings, bestEffort } = prepared;
237
+ const cleanup = request.cleanupPaths === undefined ? {} : { cleanup: request.cleanupPaths };
238
+ try {
239
+ if (this.snapshots !== undefined)
240
+ await bestEffort(() => this.snapshots.write({ unitId, journalId: this.journalId, state: 'prepared', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
241
+ await bestEffort(async () => this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'prepared', changed: [], target: validation.roots.find(root => root.name === primary)?.name ?? primary, roots: validation.roots.map(root => root.name) }));
242
+ for (const op of validation.ops) {
243
+ const snapshot = snapshots.find(entry => entry.target === op.target);
244
+ if (snapshot === undefined)
245
+ throw new Error('snapshot missing for ' + op.target);
178
246
  try {
179
- await task();
247
+ const opWarnings = await this.applyOp(op, snapshot.baseline);
248
+ warnings.push(...opWarnings);
249
+ changed.push(op.target);
180
250
  }
181
251
  catch (error) {
252
+ if (error?.noWrite !== true)
253
+ changed.push(op.target);
182
254
  if (!isCommittedWarning(error))
183
255
  throw error;
184
256
  warnings.push(error instanceof Error ? error.message : String(error));
185
257
  }
186
- };
187
- const snapshots = [];
258
+ }
259
+ await bestEffort(async () => this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'unit-written', changed, target: primary, roots: validation.roots.map(root => root.name) }));
260
+ if (this.snapshots !== undefined)
261
+ await bestEffort(() => this.snapshots.write({ unitId, journalId: this.journalId, state: 'committed', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
262
+ await bestEffort(async () => this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'committed', changed, target: primary, roots: validation.roots.map(root => root.name) }));
188
263
  try {
189
- for (const op of validation.ops) {
190
- const current = await this.io.readText(op.target);
191
- const baseline = op.expected === undefined ? current : op.expected;
192
- if (current !== baseline) {
193
- return { ok: false, unitId, dryRun: false, changed, errors: [{ code: 'cas-drift', message: 'target changed after plan', target: op.target }] };
194
- }
195
- snapshots.push({ target: op.target, before: current, after: op.kind === 'write' ? op.content : null, baseline });
196
- }
197
- for (const op of validation.ops) {
198
- const refusal = this.validateWrite?.(op) ?? null;
199
- if (refusal !== null)
200
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'write-validation', message: refusal, target: op.target }] };
201
- }
202
- const eventOps = snapshots.map(snapshot => {
203
- const op = validation.ops.find(entry => entry.target === snapshot.target);
204
- return {
205
- target: snapshot.target,
206
- before: snapshot.before,
207
- after: op?.kind === 'write' ? op.content : null,
208
- ...(op?.skill === undefined ? {} : { skill: op.skill }),
209
- };
210
- });
211
- const cleanup = request.cleanupPaths === undefined ? {} : { cleanup: request.cleanupPaths };
212
- if (this.snapshots !== undefined)
213
- await bestEffort(() => this.snapshots.write({ unitId, journalId: this.journalId, state: 'prepared', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
214
- await bestEffort(async () => this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'prepared', changed: [], target: validation.roots.find(root => root.name === primary)?.name ?? primary, roots: validation.roots.map(root => root.name) }));
215
- for (const op of validation.ops) {
216
- const snapshot = snapshots.find(entry => entry.target === op.target);
217
- if (snapshot === undefined)
218
- throw new Error('snapshot missing for ' + op.target);
219
- try {
220
- const opWarnings = await this.applyOp(op, snapshot.baseline);
221
- warnings.push(...opWarnings);
222
- changed.push(op.target);
223
- }
224
- catch (error) {
225
- if (error?.noWrite !== true)
226
- changed.push(op.target);
227
- if (!isCommittedWarning(error))
228
- throw error;
229
- warnings.push(error instanceof Error ? error.message : String(error));
230
- }
231
- }
232
- await bestEffort(async () => this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'unit-written', changed, target: primary, roots: validation.roots.map(root => root.name) }));
233
- // P2-1: the committed snapshot is the recovery authority. Write it BEFORE the journal's
234
- // committed phase so a crash in this window recovers as committed, never rolled back.
235
- if (this.snapshots !== undefined)
236
- await bestEffort(() => this.snapshots.write({ unitId, journalId: this.journalId, state: 'committed', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
237
- await bestEffort(async () => this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'committed', changed, target: primary, roots: validation.roots.map(root => root.name) }));
238
- try {
239
- await this.hooks?.committed?.({ unitId, changed, ops: eventOps, roots: validation.roots.map(root => root.name) });
240
- }
241
- catch {
242
- // Hooks are audit/history/event side effects; a completed write must not be rolled back by one.
243
- }
244
- return { ok: true, unitId, dryRun: false, changed, errors: [], ...(warnings.length === 0 ? {} : { warnings }) };
264
+ await this.hooks?.committed?.({ unitId, changed, ops: eventOps, roots: validation.roots.map(root => root.name) });
245
265
  }
246
- catch (error) {
247
- const message = error instanceof Error ? error.message : String(error);
248
- let rollbackFailure = '';
249
- try {
250
- await this.rollback(snapshots.filter(snapshot => changed.includes(snapshot.target)));
251
- }
252
- catch (rollbackError) {
253
- rollbackFailure = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
254
- }
255
- const detail = rollbackFailure === '' ? message : message + '; rollback failed: ' + rollbackFailure;
256
- const failureCode = error?.code === 'transact-not-invoked' ? 'transact-not-invoked' : 'write-failed';
257
- await this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'failed', changed, error: detail });
258
- try {
259
- await this.hooks?.rolledBack?.({
260
- unitId,
261
- changed,
262
- ops: snapshots.map(snapshot => {
263
- const op = validation.ops.find(entry => entry.target === snapshot.target);
264
- return {
265
- target: snapshot.target,
266
- before: snapshot.before,
267
- after: op?.kind === 'write' ? op.content : null,
268
- ...(op?.skill === undefined ? {} : { skill: op.skill }),
269
- };
270
- }),
271
- roots: validation.roots.map(root => root.name),
272
- });
273
- }
274
- catch {
275
- // best-effort hook; the structured write error remains authoritative
276
- }
277
- return { ok: false, unitId, dryRun: false, changed, errors: [{ code: failureCode, message: detail }] };
266
+ catch {
267
+ // Hooks are audit/history/event side effects; a completed write must not be rolled back by one.
278
268
  }
279
- finally {
280
- await claim?.release().catch(() => { });
281
- await lease.release();
269
+ return { ok: true, unitId, dryRun: false, changed, errors: [], ...(warnings.length === 0 ? {} : { warnings }) };
270
+ }
271
+ catch (error) {
272
+ const message = error instanceof Error ? error.message : String(error);
273
+ let rollbackFailure = '';
274
+ try {
275
+ await this.rollback(snapshots.filter(snapshot => changed.includes(snapshot.target)));
276
+ }
277
+ catch (rollbackError) {
278
+ rollbackFailure = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
279
+ }
280
+ const detail = rollbackFailure === '' ? message : message + '; rollback failed: ' + rollbackFailure;
281
+ const failureCode = error?.code === 'transact-not-invoked' ? 'transact-not-invoked' : 'write-failed';
282
+ await this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'failed', changed, error: detail });
283
+ try {
284
+ await this.hooks?.rolledBack?.({
285
+ unitId,
286
+ changed,
287
+ ops: snapshots.map(snapshot => {
288
+ const op = validation.ops.find(entry => entry.target === snapshot.target);
289
+ return {
290
+ target: snapshot.target,
291
+ before: snapshot.before,
292
+ after: op?.kind === 'write' ? op.content : null,
293
+ ...(op?.skill === undefined ? {} : { skill: op.skill }),
294
+ };
295
+ }),
296
+ roots: validation.roots.map(root => root.name),
297
+ });
298
+ }
299
+ catch {
300
+ // best-effort hook; the structured write error remains authoritative
282
301
  }
302
+ return { ok: false, unitId, dryRun: false, changed, errors: [{ code: failureCode, message: detail }] };
303
+ }
304
+ finally {
305
+ await prepared.release();
306
+ }
307
+ }
308
+ async apply(request) {
309
+ if (request.dryRun === true) {
310
+ const unitId = request.unitId ?? 'u-' + String(this.now()) + '-' + Math.random().toString(36).slice(2);
311
+ const validation = validateMutationRequest(request, this.limits);
312
+ return validation.ok
313
+ ? { ok: true, unitId, dryRun: true, changed: [], errors: [] }
314
+ : { ok: false, unitId, dryRun: true, changed: [], errors: validation.errors };
315
+ }
316
+ return await this.serial(async () => {
317
+ const prepared = await this.prepare(request);
318
+ if (prepared.kind !== 'prepared')
319
+ return prepared;
320
+ return await this.commit(prepared);
283
321
  });
284
322
  }
285
323
  /** Recover every prepared snapshot known to the port; safe to call at boot. */
@@ -302,7 +340,7 @@ export class MutationUnit {
302
340
  return await this.serial(async () => {
303
341
  let lease;
304
342
  try {
305
- lease = await this.lock.acquire(this.targetKeysForSnapshot?.(snapshot) ?? this.targetKeys);
343
+ lease = await this.lock.acquire(await this.resolveTargetKeys(this.targetKeysForSnapshot?.(snapshot) ?? this.targetKeys));
306
344
  }
307
345
  catch (error) {
308
346
  const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
@@ -360,7 +398,7 @@ export class MutationUnit {
360
398
  return await this.serial(async () => {
361
399
  let lease;
362
400
  try {
363
- lease = await this.lock.acquire(this.targetKeys);
401
+ lease = await this.lock.acquire(await this.resolveTargetKeys(this.targetKeys));
364
402
  }
365
403
  catch (error) {
366
404
  return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'lock-failed', message: error instanceof Error ? error.message : String(error) }] };
@@ -423,11 +461,16 @@ export class MutationUnit {
423
461
  return [...(result.warnings ?? [])];
424
462
  }
425
463
  async rollback(snapshots) {
464
+ // A5: one blocked target must not stop compensation of the others. A later target whose bytes
465
+ // still match this unit is restorable; only the blocked one is left for the prepared snapshot.
466
+ const errors = [];
426
467
  for (const snapshot of [...snapshots].reverse()) {
427
468
  const result = await this.kernel.restore({ path: snapshot.target, before: snapshot.before, after: snapshot.after });
428
469
  if (!result.ok)
429
- throw new Error(result.errors[0]?.message ?? 'rollback failed: ' + snapshot.target);
470
+ errors.push(snapshot.target + ': ' + (result.errors[0]?.message ?? 'rollback failed'));
430
471
  }
472
+ if (errors.length > 0)
473
+ throw new Error('rollback incomplete: ' + errors.join('; '));
431
474
  }
432
475
  }
433
476
  function parseFileLock(raw) {
@@ -492,4 +535,4 @@ export function fileMutationLock(io, root, options = {}) {
492
535
  },
493
536
  };
494
537
  }
495
- //# sourceMappingURL=mutation-unit.js.map
538
+ //# sourceMappingURL=unit-kernel.js.map
@@ -1,6 +1,5 @@
1
1
  /** The one byte-write engine surface. Consumers must import it from the documented subpath. */
2
- export * from './write-kernel.ts';
3
- export * from './mutation-unit.ts';
2
+ export * from './unit-kernel.ts';
4
3
  export * from './mutation-storage-adapter.ts';
5
4
  export * from './unit-claim.ts';
6
5
  export * from './unit-journal.ts';
@@ -1,6 +1,5 @@
1
1
  /** The one byte-write engine surface. Consumers must import it from the documented subpath. */
2
- export * from "./write-kernel.js";
3
- export * from "./mutation-unit.js";
2
+ export * from "./unit-kernel.js";
4
3
  export * from "./mutation-storage-adapter.js";
5
4
  export * from "./unit-claim.js";
6
5
  export * from "./unit-journal.js";
@@ -1,7 +1,7 @@
1
- import { c as transactIo, o as nodeEvolutionIo } from "./io-Cpa8wuvj.js";
1
+ import { c as transactIo, o as nodeEvolutionIo } from "./io-DT4-MXLr.js";
2
2
  import { o as resolveCitations } from "./citations-CZKTUGQF.js";
3
3
  import { n as isRecord } from "./guards-3f02mnf2.js";
4
- import { p as parseFrontmatter, u as frontmatterBlock } from "./mutations-Y-wKod7W.js";
4
+ import { p as parseFrontmatter, u as frontmatterBlock } from "./mutations-JKFlfhSO.js";
5
5
  import { join } from "node:path";
6
6
  //#region lib/types/reference-rewrite.js
7
7
  /**
package/lib/write.js CHANGED
@@ -1,6 +1,6 @@
1
- import { r as contentHash } from "./mutations-Y-wKod7W.js";
2
- import { p as entryTarget } from "./skill-history-BvLWFoOo.js";
3
- import { C as writeUnitEvidence, D as fileMutationLock, E as MutationUnit, O as validateMutationRequest, S as upsertUnitIndex, T as writeUnitSnapshot, _ as unitIndexPath, a as UNIT_JOURNAL_SCHEMA_VERSION, b as unitSnapshotsDir, c as unitJournalPath, d as UNIT_STORAGE_SCHEMA_VERSION, f as readUnitEvidence, g as unitEvidencePath, h as readUnitSnapshot, i as UNIT_JOURNAL_PHASES, k as WriteKernel, l as unitJournalPhaseRank, m as readUnitReceipt, n as unitJournalPort, o as assertUnitJournalTransition, p as readUnitIndex, r as unitSnapshotPort, s as readUnitJournal, t as pruneTreeChangeUnits, u as writeUnitJournal, v as unitReceiptPath, w as writeUnitReceipt, x as unitStorageKey, y as unitSnapshotPath } from "./mutation-storage-adapter-z1_hyrQn.js";
1
+ import { r as contentHash } from "./mutations-JKFlfhSO.js";
2
+ import { p as entryTarget } from "./skill-history-BOZ4HCDB.js";
3
+ import { C as writeUnitEvidence, D as fileMutationLock, E as UnitKernel, O as validateMutationRequest, S as upsertUnitIndex, T as writeUnitSnapshot, _ as unitIndexPath, a as UNIT_JOURNAL_SCHEMA_VERSION, b as unitSnapshotsDir, c as unitJournalPath, d as UNIT_STORAGE_SCHEMA_VERSION, f as readUnitEvidence, g as unitEvidencePath, h as readUnitSnapshot, i as UNIT_JOURNAL_PHASES, l as unitJournalPhaseRank, m as readUnitReceipt, n as unitJournalPort, o as assertUnitJournalTransition, p as readUnitIndex, r as unitSnapshotPort, s as readUnitJournal, t as pruneTreeChangeUnits, u as writeUnitJournal, v as unitReceiptPath, w as writeUnitReceipt, x as unitStorageKey, y as unitSnapshotPath } from "./mutation-storage-adapter-CSVn34dK.js";
4
4
  //#region lib/types/unit-undo.js
5
5
  /**
6
6
  * Cross-skill unit undo executor.
@@ -355,4 +355,4 @@ function staleRouteStubs(indexes) {
355
355
  return out.sort((a, b) => a.skill.localeCompare(b.skill) || a.v - b.v || a.owner.localeCompare(b.owner));
356
356
  }
357
357
  //#endregion
358
- export { MutationUnit, UNIT_JOURNAL_PHASES, UNIT_JOURNAL_SCHEMA_VERSION, UNIT_STORAGE_SCHEMA_VERSION, WriteKernel, assertUnitJournalTransition, candidateSkills, executeUnitUndo, fileMutationLock, isLandmark, landmarkVerdict, planUnitUndoAcross, pruneTreeChangeUnits, readUnitEvidence, readUnitIndex, readUnitJournal, readUnitReceipt, readUnitSnapshot, resolveUnitMembers, resolveUnitMembersFromIndexes, staleRouteStubs, unitEvidencePath, unitIndexPath, unitJournalPath, unitJournalPhaseRank, unitJournalPort, unitMembersAreComplete, unitReceiptPath, unitSnapshotPath, unitSnapshotPort, unitSnapshotsDir, unitStorageKey, upsertUnitIndex, validateMutationRequest, writeUnitEvidence, writeUnitJournal, writeUnitReceipt, writeUnitSnapshot };
358
+ export { UNIT_JOURNAL_PHASES, UNIT_JOURNAL_SCHEMA_VERSION, UNIT_STORAGE_SCHEMA_VERSION, UnitKernel, assertUnitJournalTransition, candidateSkills, executeUnitUndo, fileMutationLock, isLandmark, landmarkVerdict, planUnitUndoAcross, pruneTreeChangeUnits, readUnitEvidence, readUnitIndex, readUnitJournal, readUnitReceipt, readUnitSnapshot, resolveUnitMembers, resolveUnitMembersFromIndexes, staleRouteStubs, unitEvidencePath, unitIndexPath, unitJournalPath, unitJournalPhaseRank, unitJournalPort, unitMembersAreComplete, unitReceiptPath, unitSnapshotPath, unitSnapshotPort, unitSnapshotsDir, unitStorageKey, upsertUnitIndex, validateMutationRequest, writeUnitEvidence, writeUnitJournal, writeUnitReceipt, writeUnitSnapshot };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-core",
3
3
  "description": "Shared stores, prompts, signals and lifecycle logic for the dsh-evolution plugin family (community build)",
4
- "version": "0.59.5",
4
+ "version": "0.60.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -75,6 +75,10 @@
75
75
  "types": "./lib/types/io-node.d.ts",
76
76
  "default": "./lib/io-node.js"
77
77
  },
78
+ "./io-platform": {
79
+ "types": "./lib/types/io-platform.d.ts",
80
+ "default": "./lib/io-platform.js"
81
+ },
78
82
  "./authority-plugin": {
79
83
  "types": "./lib/types/authority-plugin.d.ts",
80
84
  "default": "./lib/authority-plugin.js"
@@ -82,6 +86,30 @@
82
86
  "./policy": {
83
87
  "types": "./lib/types/policy.d.ts",
84
88
  "default": "./lib/policy.js"
89
+ },
90
+ "./state": {
91
+ "types": "./lib/types/state/index.d.ts",
92
+ "default": "./lib/state/index.js"
93
+ },
94
+ "./state/storage": {
95
+ "types": "./lib/types/state/storage.d.ts",
96
+ "default": "./lib/state/storage.js"
97
+ },
98
+ "./state/domain": {
99
+ "types": "./lib/types/state/domain/index.d.ts",
100
+ "default": "./lib/state/domain/index.js"
101
+ },
102
+ "./state/store": {
103
+ "types": "./lib/types/state/store.d.ts",
104
+ "default": "./lib/state/store.js"
105
+ },
106
+ "./state/migrate": {
107
+ "types": "./lib/types/state/migrate.d.ts",
108
+ "default": "./lib/state/migrate.js"
109
+ },
110
+ "./state/store-plugin": {
111
+ "types": "./lib/types/state/store-plugin.d.ts",
112
+ "default": "./lib/state/store-plugin.js"
85
113
  }
86
114
  },
87
115
  "files": [
@@ -98,8 +126,7 @@
98
126
  "yaml": "^2.4.2",
99
127
  "zod": "^4.4.3",
100
128
  "@deepseek-ai/schemastery": "^3.18.5",
101
- "@lmzhen/dsh-evolution-adapter": "0.59.5",
102
- "@lmzhen/dsh-evolution-platform-contract": "0.59.5"
129
+ "@lmzhen/dsh-evolution-platform": "0.60.0"
103
130
  },
104
131
  "peerDependencies": {
105
132
  "@deepseek-ai/cordis": "^4.0.5"
@@ -317,18 +317,18 @@
317
317
  "note": "Lease acquire/heartbeat/release all use transactIo now: the old private fallback did not tolerate a committed-fsync warning, so acquire could report failure after the active lease had landed."
318
318
  },
319
319
  {
320
- "id": "write-kernel-run",
320
+ "id": "unit-kernel-run",
321
321
  "path": "<evolutionHome>/units/**",
322
- "writer": "evolution-core/src/write-kernel.ts",
322
+ "writer": "evolution-core/src/target-writer.ts",
323
323
  "serializedBy": "transact",
324
324
  "marker": "transactIo(this.io, target.path, invoke)",
325
325
  "state": [],
326
326
  "note": "Run/task path: the kernel no longer carries its own direct-write fallback; transactIo is the one seam and reports a typed not-invoked error."
327
327
  },
328
328
  {
329
- "id": "write-kernel-write-one",
329
+ "id": "unit-kernel-write-one",
330
330
  "path": "<evolutionHome>/units/**",
331
- "writer": "evolution-core/src/write-kernel.ts",
331
+ "writer": "evolution-core/src/target-writer.ts",
332
332
  "serializedBy": "transact",
333
333
  "marker": "transactIo(this.io, target.path, task)",
334
334
  "state": [],
@@ -337,11 +337,20 @@
337
337
  {
338
338
  "id": "mutation-lock",
339
339
  "path": "<evolutionHome>/.mutation-lock",
340
- "writer": "evolution-core/src/mutation-unit.ts",
340
+ "writer": "evolution-core/src/unit-kernel.ts",
341
341
  "serializedBy": "transact",
342
342
  "marker": "transactIo(io, path, task)",
343
343
  "state": [],
344
344
  "note": "fileMutationLock updates the lock record through transactIo; no private direct-write fallback remains."
345
+ },
346
+ {
347
+ "id": "state-store",
348
+ "path": "<evolutionHome>/state/store.json",
349
+ "writer": "evolution-core/src/state/store.ts",
350
+ "serializedBy": "transact",
351
+ "marker": "transactIo(io, file",
352
+ "state": [],
353
+ "note": "File-backed StateStore provider (D1a, not mounted yet): every mutation is one transactIo read-modify-write; no process-local authority."
345
354
  }
346
355
  ]
347
356
  }