@lmzhen/dsh-evolution-core 0.60.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,6 +48,8 @@ function evolutionRoot(env = process.env) {
48
48
  /** Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
49
49
  * state (reports, activity store, feedback file, state-domain data). */
50
50
  function evolutionHome(env = process.env) {
51
+ const override = env.DSH_EVOLUTION_HOME;
52
+ if (override !== void 0 && override.trim() !== "") return resolve(override.trim());
51
53
  return join(evolutionRoot(env), "evolution");
52
54
  }
53
55
  //#endregion
@@ -59,7 +59,23 @@ export declare class HybridMutationLock implements MutationLockPort {
59
59
  readonly skipped: readonly string[];
60
60
  }>;
61
61
  }
62
+ /** The authority surface as it exists at call time. */
63
+ export interface MutationAuthorityPort {
64
+ readonly mutationLock?: MutationLockPort;
65
+ readonly homeFence?: HomeFence;
66
+ }
67
+ /** Resolve the authority now; callers that live past one apply must re-read this. */
68
+ export declare function mutationAuthorityFrom(ctx: {
69
+ get?(name: string): unknown;
70
+ } | undefined): MutationAuthorityPort | undefined;
62
71
  export declare function mutationLockFrom(ctx: {
63
72
  get?(name: string): unknown;
64
73
  } | undefined): MutationLockPort | undefined;
74
+ export declare function homeFenceFrom(ctx: {
75
+ get?(name: string): unknown;
76
+ } | undefined): HomeFence | undefined;
77
+ /** A stable HomeFence whose target is re-resolved on every use; HMR/late provide heal. */
78
+ export declare function liveHomeFence(ctx: {
79
+ get?(name: string): unknown;
80
+ }, home: string): HomeFence;
65
81
  //# sourceMappingURL=mutation-authority.d.ts.map
@@ -79,10 +79,38 @@ export class HybridMutationLock {
79
79
  return await this.keyedLock.repair();
80
80
  }
81
81
  }
82
- export function mutationLockFrom(ctx) {
82
+ /** Resolve the authority now; callers that live past one apply must re-read this. */
83
+ export function mutationAuthorityFrom(ctx) {
83
84
  if (ctx?.get === undefined)
84
85
  return undefined;
85
- const authority = ctx.get('evolutionMutationAuthority');
86
- return authority?.mutationLock;
86
+ return ctx.get('evolutionMutationAuthority');
87
+ }
88
+ export function mutationLockFrom(ctx) {
89
+ return mutationAuthorityFrom(ctx)?.mutationLock;
90
+ }
91
+ export function homeFenceFrom(ctx) {
92
+ return mutationAuthorityFrom(ctx)?.homeFence;
93
+ }
94
+ /** A stable HomeFence whose target is re-resolved on every use; HMR/late provide heal. */
95
+ class LiveHomeFence extends HomeFence {
96
+ liveCtx;
97
+ homePath;
98
+ fallback;
99
+ constructor(liveCtx, homePath) {
100
+ super({ home: homePath });
101
+ this.liveCtx = liveCtx;
102
+ this.homePath = homePath;
103
+ }
104
+ current() {
105
+ return homeFenceFrom(this.liveCtx) ?? (this.fallback ??= new HomeFence({ home: this.homePath }));
106
+ }
107
+ get releaseFailure() { return this.current().releaseFailure; }
108
+ holdsTree() { return this.current().holdsTree(); }
109
+ async run(body) { return await this.current().run(body); }
110
+ async acquire() { return await this.current().acquire(); }
111
+ }
112
+ /** A stable HomeFence whose target is re-resolved on every use; HMR/late provide heal. */
113
+ export function liveHomeFence(ctx, home) {
114
+ return new LiveHomeFence(ctx, home);
87
115
  }
88
116
  //# sourceMappingURL=mutation-authority.js.map
@@ -162,6 +162,10 @@ export interface RunRegistryOptions {
162
162
  fence?: {
163
163
  run<T>(body: () => Promise<T>): Promise<T>;
164
164
  } | undefined;
165
+ /** Resolve the fence at operation time; preferred over the construction-time snapshot. */
166
+ resolveFence?: () => {
167
+ run<T>(body: () => Promise<T>): Promise<T>;
168
+ } | undefined;
165
169
  /** Clock seam for tests. */
166
170
  now?: () => number;
167
171
  /** Retained records (N3-clamped). */
@@ -126,8 +126,9 @@ export function newRunRegistry(options) {
126
126
  const path = runsFile(options.home);
127
127
  const writeIndex = async (task) => {
128
128
  const run = async () => { await transactIo(options.io, path, task); };
129
- if (options.fence !== undefined)
130
- await options.fence.run(run);
129
+ const fence = options.resolveFence?.() ?? options.fence;
130
+ if (fence !== undefined)
131
+ await fence.run(run);
131
132
  else
132
133
  await run();
133
134
  };
@@ -407,11 +407,13 @@ export declare class SkillLibrary {
407
407
  private readonly authority;
408
408
  /** When supplied by the family MutationAuthority, replaces the per-directory file lock. */
409
409
  private readonly mutationLock;
410
+ private readonly mutationLockResolver;
410
411
  private readonly fence;
412
+ private readonly fenceResolver;
411
413
  /** skill-history.ts: the content history is best-effort, so a failure must not be SILENT —
412
414
  * but it is a deployment condition, not a per-write event, so it warns once per instance. */
413
415
  private historyWarned;
414
- constructor(root?: string, io?: EvolutionIoLike, limits?: SkillLimits, onMutation?: (event: EvolutionSkillMutatedEvent) => void, transact?: typeof transactIo, threatExemptLabels?: readonly string[], authority?: WriteAuthority, mutationLock?: MutationLockPort, fence?: HistoryFence);
416
+ constructor(root?: string, io?: EvolutionIoLike, limits?: SkillLimits, onMutation?: (event: EvolutionSkillMutatedEvent) => void, transact?: typeof transactIo, threatExemptLabels?: readonly string[], authority?: WriteAuthority, mutationLock?: MutationLockPort, fence?: HistoryFence, mutationLockResolver?: () => MutationLockPort | undefined, fenceResolver?: () => HistoryFence | undefined);
415
417
  /**
416
418
  * Transitional root lock for mutators that still own their write path. The
417
419
  * extract/restructure path takes the same lock through UnitKernel, so those
@@ -446,6 +448,10 @@ export declare class SkillLibrary {
446
448
  /** The one frontmatter pipeline for create/update/patch; patch keeps its cap checks outside. */
447
449
  private prepareBody;
448
450
  /** True when the injected lock port is per-target rather than the home fence. */
451
+ /** Resolve the home fence at use time too: it arrives with the same late service. */
452
+ private currentFence;
453
+ /** Resolve at use time: the authority row may provide its lock after this library mounts. */
454
+ private currentMutationLock;
449
455
  private keyedTargetLocks;
450
456
  private lockPort;
451
457
  private recovery;
@@ -544,11 +544,13 @@ export class SkillLibrary {
544
544
  authority;
545
545
  /** When supplied by the family MutationAuthority, replaces the per-directory file lock. */
546
546
  mutationLock;
547
+ mutationLockResolver;
547
548
  fence;
549
+ fenceResolver;
548
550
  /** skill-history.ts: the content history is best-effort, so a failure must not be SILENT —
549
551
  * but it is a deployment condition, not a per-write event, so it warns once per instance. */
550
552
  historyWarned = false;
551
- constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
553
+ constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence, mutationLockResolver, fenceResolver) {
552
554
  this.root = root;
553
555
  this.targetLocks = targetLocksFor(root);
554
556
  this.rootGate = rootGateFor(root);
@@ -558,7 +560,9 @@ export class SkillLibrary {
558
560
  this.threatExemptLabels = threatExemptLabels ?? [];
559
561
  this.authority = authority;
560
562
  this.mutationLock = mutationLock;
563
+ this.mutationLockResolver = mutationLockResolver;
561
564
  this.fence = fence;
565
+ this.fenceResolver = fenceResolver;
562
566
  // V4-20: bind the ONE transaction seam by default. Explicit injection stays
563
567
  // first; a backend without transact keeps the plain read→write (the
564
568
  // in-process serial chain is the second layer). transactIo owns the backend
@@ -748,9 +752,18 @@ export class SkillLibrary {
748
752
  return { ok: true, body, onDisk: body.trimEnd() + '\n', norm };
749
753
  }
750
754
  /** True when the injected lock port is per-target rather than the home fence. */
755
+ /** Resolve the home fence at use time too: it arrives with the same late service. */
756
+ currentFence() {
757
+ return this.fence ?? this.fenceResolver?.();
758
+ }
759
+ /** Resolve at use time: the authority row may provide its lock after this library mounts. */
760
+ currentMutationLock() {
761
+ return this.mutationLock ?? this.mutationLockResolver?.();
762
+ }
751
763
  keyedTargetLocks() {
752
- if (this.mutationLock !== undefined)
753
- return this.mutationLock.keyed === true;
764
+ const lock = this.currentMutationLock();
765
+ if (lock !== undefined)
766
+ return lock.keyed === true;
754
767
  // A test library may have no injected lock (fileMutationLock fallback). A
755
768
  // production library without one must still fail closed, never silently
756
769
  // bypass the fence because the keyed probe swallowed the assembly error.
@@ -759,8 +772,9 @@ export class SkillLibrary {
759
772
  return false;
760
773
  }
761
774
  lockPort() {
762
- if (this.mutationLock !== undefined)
763
- return this.mutationLock;
775
+ const lock = this.currentMutationLock();
776
+ if (lock !== undefined)
777
+ return lock;
764
778
  // Fail loud outside tests: production skill writes must use the family authority fence.
765
779
  if (process.env['VITEST'] === 'true' || process.env['NODE_ENV'] === 'test')
766
780
  return fileMutationLock(this.io, this.root);
@@ -1412,7 +1426,7 @@ export class SkillLibrary {
1412
1426
  supportFiles,
1413
1427
  restructureRounds: 0,
1414
1428
  source,
1415
- }, undefined, fenceHeld ? undefined : this.fence);
1429
+ }, undefined, fenceHeld ? undefined : this.currentFence());
1416
1430
  }
1417
1431
  catch (error) {
1418
1432
  console.warn('skill-store: hard-cap event not recorded for "' + name + '": ' + (error instanceof Error ? error.message : String(error)));
@@ -1448,7 +1462,7 @@ export class SkillLibrary {
1448
1462
  unitId, unitHead, origin, fenceHeld = false, change) {
1449
1463
  // A committed hook or outer tree operation already holds the home fence.
1450
1464
  // Keep per-file transactions, but do not queue behind our own lease.
1451
- const fence = fenceHeld ? undefined : this.fence;
1465
+ const fence = fenceHeld ? undefined : this.currentFence();
1452
1466
  const at = new Date().toISOString();
1453
1467
  const planSummary = PLAN_SUMMARY.getStore();
1454
1468
  const finalSummary = planSummary !== undefined
@@ -4817,7 +4831,7 @@ export function newSkillLibrary(options) {
4817
4831
  return new SkillLibrary(resolveSkillsRoot(config ?? {}), io, limits, ctx ? (event) => { ctx.emit('evolution/skill-mutated', event); } : undefined, transact,
4818
4832
  // Copied once, here: the library holds the array for its lifetime and must
4819
4833
  // not alias a config object the caller still owns.
4820
- [...(threatExemptLabels ?? [])], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.('evolutionMutationAuthority')?.homeFence);
4834
+ [...(threatExemptLabels ?? [])], authority, options.mutationLock, options.fence, options.mutationLock === undefined && ctx !== undefined ? () => mutationLockFrom(ctx) : undefined, options.fence === undefined && ctx !== undefined ? () => ctx.get?.('evolutionMutationAuthority')?.homeFence : undefined);
4821
4835
  }
4822
4836
  export { DEFAULT_SKILL_LIMITS, DEFAULT_CITATION_POLICY, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_SUPPORT_FILE_CHAR_POLICY, POLICY_STAGE_DEFAULTS, policyStageLimits, } from "./limits.js";
4823
4837
  export { authoringFeedback, ensureSkillFrontmatter, frontmatterBlock, frontmatterCatalogInvalid, normalizeFrontmatter, parseFrontmatter, relatedSkillNames, validateFrontmatter, yamlPlainScalarNeedsQuotes } from "./frontmatter.js";
@@ -19,8 +19,6 @@ declare module '@deepseek-ai/cordis' {
19
19
  export interface Config {
20
20
  /** Pin a provider by name; `auto` picks store after the migration marker, else domain. */
21
21
  provider?: string;
22
- /** Evolution home override (tests/migration); defaults to `evolutionHome()`. */
23
- home?: string;
24
22
  }
25
23
  export declare class EvolutionState extends Service {
26
24
  static inject: string[];
@@ -43,6 +41,11 @@ export declare class EvolutionState extends Service {
43
41
  /** Serialize state operations against the migration command across processes. */
44
42
  private withStateLock;
45
43
  private storage;
44
+ /** Effective provider after `auto` resolves, for operator diagnostics. */
45
+ providerSelection(): {
46
+ configured: string;
47
+ effective: string;
48
+ };
46
49
  /** A2: refresh the mounted provider before a decision reads pending state. */
47
50
  reload(): Promise<void>;
48
51
  loadReviewState(sessionId: string): Promise<ReviewStateRecord | null>;
@@ -14,19 +14,19 @@ import { join } from 'node:path';
14
14
  import { withFileLock } from '@lmzhen/dsh-evolution-platform/values/fs';
15
15
  import { evolutionHome } from "../state-store.js";
16
16
  import { PROVIDER_DOMAIN, PROVIDER_STORE, STATE_MIGRATION_MARKER } from "./storage.js";
17
+ import { parseStateStoreImage } from "./store.js";
17
18
  export * from "./storage.js";
18
19
  export class EvolutionState extends Service {
19
20
  static inject = ['evolutionStateStorage'];
20
21
  static Config = z.object({
21
22
  provider: z.string().default(''),
22
- home: z.string().default(''),
23
23
  });
24
24
  providerName;
25
25
  home;
26
26
  constructor(ctx, config = {}) {
27
27
  super(ctx, 'evolutionState');
28
28
  this.providerName = config.provider ?? '';
29
- this.home = config.home !== undefined && config.home !== '' ? config.home : evolutionHome();
29
+ this.home = evolutionHome();
30
30
  // S-07: a PINNED provider name is verified at mount when any
31
31
  // provider is already registered — a config typo used to explode only at
32
32
  // the first state access, far away from the mistake (the registry's
@@ -57,10 +57,12 @@ export class EvolutionState extends Service {
57
57
  return;
58
58
  const storePath = join(this.home, 'state', 'store.json');
59
59
  let markerBody;
60
- let storeBody;
61
60
  try {
62
61
  markerBody = JSON.parse(readFileSync(marker, 'utf8'));
63
- storeBody = JSON.parse(readFileSync(storePath, 'utf8'));
62
+ const storeText = readFileSync(storePath, 'utf8');
63
+ if (storeText.trim() === '')
64
+ throw new Error('store image is empty');
65
+ parseStateStoreImage(storeText);
64
66
  }
65
67
  catch (error) {
66
68
  throw new Error('evolution-state: the migration marker/store is missing or unreadable: ' + (error instanceof Error ? error.message : String(error)));
@@ -68,12 +70,6 @@ export class EvolutionState extends Service {
68
70
  if (typeof markerBody !== 'object' || markerBody === null || markerBody.target !== 'store') {
69
71
  throw new Error('evolution-state: the migration marker is invalid (target != store): ' + marker);
70
72
  }
71
- const image = storeBody;
72
- if (typeof image !== 'object' || image === null || image.version !== 1
73
- || typeof image.review !== 'object' || image.review === null || Array.isArray(image.review)
74
- || typeof image.pending !== 'object' || image.pending === null || Array.isArray(image.pending)) {
75
- throw new Error('evolution-state: the migration marker points at an invalid/empty store image: ' + storePath);
76
- }
77
73
  }
78
74
  assertProviderChoice() {
79
75
  if (this.providerName === 'auto') {
@@ -86,8 +82,15 @@ export class EvolutionState extends Service {
86
82
  }
87
83
  return;
88
84
  }
89
- if (this.providerName !== '')
85
+ if (this.providerName !== '') {
86
+ if (this.providerName === PROVIDER_STORE) {
87
+ const marker = join(this.home, 'state', STATE_MIGRATION_MARKER);
88
+ if (!existsSync(marker))
89
+ throw new Error('evolution-state: provider "' + PROVIDER_STORE + '" is pinned but the migration marker is missing; refusing to read an empty store as authority');
90
+ this.assertMarkerStore();
91
+ }
90
92
  return;
93
+ }
91
94
  const names = this.ctx.evolutionStateStorage.providerNames();
92
95
  if (names.length <= 1)
93
96
  return;
@@ -104,6 +107,10 @@ export class EvolutionState extends Service {
104
107
  this.assertMarkerStore();
105
108
  return PROVIDER_STORE;
106
109
  }
110
+ const storePath = join(this.home, 'state', 'store.json');
111
+ if (existsSync(storePath)) {
112
+ throw new Error('evolution-state: store exists but the migration marker is missing; refusing to silently fall back to domain and lose store-era writes. Pin provider: domain explicitly to roll back.');
113
+ }
107
114
  if (names.includes(PROVIDER_DOMAIN))
108
115
  return PROVIDER_DOMAIN;
109
116
  throw new Error('evolution-state: auto has no migration marker and no "' + PROVIDER_DOMAIN + '" provider; refusing to guess a state authority');
@@ -132,6 +139,12 @@ export class EvolutionState extends Service {
132
139
  const name = this.providerName === 'auto' ? this.autoProviderName() : this.providerName;
133
140
  return this.ctx.evolutionStateStorage.provider(name || undefined);
134
141
  }
142
+ /** Effective provider after `auto` resolves, for operator diagnostics. */
143
+ providerSelection() {
144
+ const configured = this.providerName === '' ? 'auto' : this.providerName;
145
+ this.assertResolvable();
146
+ return { configured, effective: this.providerName === 'auto' ? this.autoProviderName() : this.providerName };
147
+ }
135
148
  /** A2: refresh the mounted provider before a decision reads pending state. */
136
149
  reload() {
137
150
  return this.run(async () => this.storage().reload?.() ?? Promise.resolve());
@@ -11,7 +11,7 @@ import { mkdir } from 'node:fs/promises';
11
11
  import { storageDomainPort } from '@lmzhen/dsh-evolution-platform/ports';
12
12
  import { withFileLock } from '@lmzhen/dsh-evolution-platform/values/fs';
13
13
  import { evolutionHome } from "../state-store.js";
14
- import { writeStateStoreSnapshot } from "./store.js";
14
+ import { readStateStoreSnapshot, writeStateStoreSnapshot } from "./store.js";
15
15
  import { EVOLUTION_DOMAIN } from "./domain/index.js";
16
16
  import { CURATOR_STATE_KEY, STATE_MIGRATION_MARKER, CURATOR_STATE_TABLE, PENDING_TABLE, REVIEW_STATE_TABLE, PENDING_STATUSES, } from "./index.js";
17
17
  export { STATE_MIGRATION_MARKER };
@@ -25,7 +25,34 @@ async function migrateDomainToStoreUnlocked(ctx, options) {
25
25
  const markerPath = join(home, 'state', STATE_MIGRATION_MARKER);
26
26
  const io = options.io;
27
27
  if (await io.exists(storePath)) {
28
- throw new Error('evolution-state-migrate: store already exists; refusing to overwrite it: ' + storePath);
28
+ try {
29
+ const existing = await readStateStoreSnapshot(io, storePath);
30
+ const recovered = {
31
+ reviewSessions: Object.keys(existing.review).length,
32
+ pending: Object.keys(existing.pending).length,
33
+ curator: existing.curator !== null,
34
+ path: storePath,
35
+ dryRun: options.dryRun === true,
36
+ };
37
+ if (options.dryRun === true)
38
+ return recovered;
39
+ if (!(await io.exists(markerPath))) {
40
+ await io.writeText(markerPath, JSON.stringify({
41
+ migratedAt: new Date(options.now?.() ?? Date.now()).toISOString(),
42
+ source: 'domain-store-recovered',
43
+ target: 'store',
44
+ reviewSessions: recovered.reviewSessions,
45
+ pending: recovered.pending,
46
+ curator: recovered.curator,
47
+ }, null, 2) + '\n');
48
+ }
49
+ return recovered;
50
+ }
51
+ catch (error) {
52
+ if (error instanceof Error && error.message.includes('refusing to overwrite'))
53
+ throw error;
54
+ throw new Error('evolution-state-migrate: store already exists; refusing to overwrite it: ' + storePath);
55
+ }
29
56
  }
30
57
  // Prefer the provider that is already mounted: the host normally has the
31
58
  // domain row mounted, and opening the same KV domain a second time fails with
@@ -2,17 +2,13 @@ import { evolutionHome } from "../state-store.js";
2
2
  import { createStateStoreProvider } from "./store.js";
3
3
  export const name = 'evolution-state-store';
4
4
  export const inject = ['evolutionStateStorage', 'evolutionIo'];
5
- /** HMR re-applies the row in the same ctx; the registry only treats the SAME object as
6
- * idempotent, so keep one provider per home instead of constructing a new registrant. */
7
- const providers = new Map();
8
5
  export async function apply(ctx) {
9
6
  await ctx.evolutionIo.whenReady();
10
7
  const home = evolutionHome();
11
- let provider = providers.get(home);
12
- if (provider === undefined) {
13
- provider = createStateStoreProvider({ io: ctx.evolutionIo.provider(), home });
14
- providers.set(home, provider);
15
- }
8
+ // A fresh provider per apply: HMR may replace the IO provider, and a cached
9
+ // provider would keep reading through the disposed one. The effect cleanup
10
+ // unregisters this exact object before the next apply registers its own.
11
+ const provider = createStateStoreProvider({ io: ctx.evolutionIo.provider(), home });
16
12
  ctx.effect(() => ctx.evolutionStateStorage.registerProvider(provider), 'evolution-state-store.provider');
17
13
  }
18
14
  //# sourceMappingURL=store-plugin.js.map
@@ -31,6 +31,10 @@ export interface StateStoreSnapshot {
31
31
  /** Validate and publish a complete store image. The write is create-if-absent:
32
32
  * an existing store is never overwritten by a migration. */
33
33
  export declare function writeStateStoreSnapshot(io: EvolutionIoLike, path: string, snapshot: StateStoreSnapshot): Promise<void>;
34
+ /** Parse a whole store image synchronously; a corrupt store fails loud. */
35
+ export declare function parseStateStoreImage(text: string): StateStoreSnapshot;
36
+ /** Read a validated store image; a corrupt store fails loud. */
37
+ export declare function readStateStoreSnapshot(io: EvolutionIoLike, path: string): Promise<StateStoreSnapshot>;
34
38
  /**
35
39
  * Build the file-backed provider. All mutating methods are a single
36
40
  * `transactIo` RMW; readers parse the current file, never a cached copy.
@@ -34,6 +34,16 @@ export async function writeStateStoreSnapshot(io, path, snapshot) {
34
34
  throw new Error('evolution-state-store: refusing to overwrite an existing store: ' + path);
35
35
  await io.writeText(path, text);
36
36
  }
37
+ /** Parse a whole store image synchronously; a corrupt store fails loud. */
38
+ export function parseStateStoreImage(text) {
39
+ const store = parseStore(text);
40
+ return { review: store.review, curator: store.curator, pending: store.pending };
41
+ }
42
+ /** Read a validated store image; a corrupt store fails loud. */
43
+ export async function readStateStoreSnapshot(io, path) {
44
+ const store = parseStore(await io.readText(path));
45
+ return { review: store.review, curator: store.curator, pending: store.pending };
46
+ }
37
47
  function invalid(message) {
38
48
  throw new Error('evolution-state-store: ' + message);
39
49
  }
@@ -55,6 +55,9 @@ export function evolutionRoot(env = process.env) {
55
55
  /** Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
56
56
  * state (reports, activity store, feedback file, state-domain data). */
57
57
  export function evolutionHome(env = process.env) {
58
+ const override = env.DSH_EVOLUTION_HOME;
59
+ if (override !== undefined && override.trim() !== '')
60
+ return resolve(override.trim());
58
61
  return join(evolutionRoot(env), 'evolution');
59
62
  }
60
63
  //# sourceMappingURL=state-store.js.map
@@ -198,6 +198,7 @@ export declare class UnitKernel {
198
198
  private readonly targetKeyResolver;
199
199
  private readonly journal;
200
200
  private readonly snapshots;
201
+ private readonly preparedStates;
201
202
  private readonly claim;
202
203
  private readonly claimRunId;
203
204
  private readonly hooks;
@@ -104,6 +104,7 @@ export class UnitKernel {
104
104
  targetKeyResolver;
105
105
  journal;
106
106
  snapshots;
107
+ preparedStates = new WeakMap();
107
108
  claim;
108
109
  claimRunId;
109
110
  hooks;
@@ -172,7 +173,14 @@ export class UnitKernel {
172
173
  return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code, message: error instanceof Error ? error.message : String(error) }] };
173
174
  }
174
175
  let claim;
176
+ let handle;
175
177
  const release = async () => {
178
+ if (handle !== undefined) {
179
+ const current = this.preparedStates.get(handle);
180
+ if (current === 'released')
181
+ return;
182
+ this.preparedStates.set(handle, 'released');
183
+ }
176
184
  await claim?.release().catch(() => { });
177
185
  await lease.release();
178
186
  };
@@ -229,10 +237,17 @@ export class UnitKernel {
229
237
  warnings.push(error instanceof Error ? error.message : String(error));
230
238
  }
231
239
  };
232
- return { kind: 'prepared', unitId, request, primary, validation, snapshots, eventOps, changed, warnings, bestEffort, release };
240
+ handle = { kind: 'prepared', unitId, request, primary, validation, snapshots, eventOps, changed, warnings, bestEffort, release };
241
+ this.preparedStates.set(handle, 'prepared');
242
+ return handle;
233
243
  }
234
244
  /** Phase 2: the only durable write phase. Releases the prepare lease in all paths. */
235
245
  async commit(prepared) {
246
+ const current = this.preparedStates.get(prepared);
247
+ if (current !== 'prepared') {
248
+ return { ok: false, unitId: prepared.unitId, dryRun: false, changed: [], errors: [{ code: 'unit-handle-consumed', message: 'prepared mutation is already ' + String(current) }] };
249
+ }
250
+ this.preparedStates.set(prepared, 'committing');
236
251
  const { unitId, request, primary, validation, snapshots, eventOps, changed, warnings, bestEffort } = prepared;
237
252
  const cleanup = request.cleanupPaths === undefined ? {} : { cleanup: request.cleanupPaths };
238
253
  try {
@@ -257,9 +272,18 @@ export class UnitKernel {
257
272
  }
258
273
  }
259
274
  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) }));
275
+ // The snapshot is the recovery authority: only a failed snapshot write may
276
+ // roll the unit back. A journal write after this point is diagnostic; a
277
+ // missing journal record must not turn a committed snapshot into a
278
+ // rollback plus a committed snapshot.
260
279
  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) }));
280
+ await this.snapshots.write({ unitId, journalId: this.journalId, state: 'committed', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() });
281
+ try {
282
+ await 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) });
283
+ }
284
+ catch (error) {
285
+ warnings.push('journal committed write failed: ' + (error instanceof Error ? error.message : String(error)));
286
+ }
263
287
  try {
264
288
  await this.hooks?.committed?.({ unitId, changed, ops: eventOps, roots: validation.roots.map(root => root.name) });
265
289
  }
@@ -279,7 +303,12 @@ export class UnitKernel {
279
303
  }
280
304
  const detail = rollbackFailure === '' ? message : message + '; rollback failed: ' + rollbackFailure;
281
305
  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 });
306
+ try {
307
+ await this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'failed', changed, error: detail });
308
+ }
309
+ catch (journalError) {
310
+ warnings.push('journal failed write failed: ' + (journalError instanceof Error ? journalError.message : String(journalError)));
311
+ }
283
312
  try {
284
313
  await this.hooks?.rolledBack?.({
285
314
  unitId,
package/lib/write.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { r as contentHash } from "./mutations-JKFlfhSO.js";
2
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";
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-B8QoG2Oy.js";
4
4
  //#region lib/types/unit-undo.js
5
5
  /**
6
6
  * Cross-skill unit undo executor.
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.60.0",
4
+ "version": "0.61.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -126,7 +126,7 @@
126
126
  "yaml": "^2.4.2",
127
127
  "zod": "^4.4.3",
128
128
  "@deepseek-ai/schemastery": "^3.18.5",
129
- "@lmzhen/dsh-evolution-platform": "0.60.0"
129
+ "@lmzhen/dsh-evolution-platform": "0.61.0"
130
130
  },
131
131
  "peerDependencies": {
132
132
  "@deepseek-ai/cordis": "^4.0.5"