@lmzhen/dsh-evolution-core 0.40.1 → 0.42.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 (62) hide show
  1. package/lib/composition/index.js +2 -2
  2. package/lib/{composition-dy0gJWDd.js → composition-CVafrlEw.js} +2 -2
  3. package/lib/{ensure-B4fjEI0w.js → ensure-BjToTMMj.js} +2 -2
  4. package/lib/errors-BxzLTVbS.js +399 -0
  5. package/lib/guards-3f02mnf2.js +29 -0
  6. package/lib/http-routes.js +205 -1
  7. package/lib/index.js +3588 -15049
  8. package/lib/mutations-jUuOPaCn.js +718 -0
  9. package/lib/platform/index.js +2 -2
  10. package/lib/{platform-CFp373_0.js → platform-B06_h8t-.js} +4 -1
  11. package/lib/restrictor.js +1 -1
  12. package/lib/runtime/plugin.js +2 -2
  13. package/lib/{session-projection-CXUNPkq9.js → session-projection-EB7mUOlJ.js} +63 -63
  14. package/lib/skill-health-BLGZTIv8.js +3773 -0
  15. package/lib/skill-history-_Cssts5o.js +1912 -0
  16. package/lib/skills.js +4067 -0
  17. package/lib/subagent/index.js +1 -1
  18. package/lib/types/errors.d.ts +12 -0
  19. package/lib/types/errors.js +17 -0
  20. package/lib/types/generated/errors.localized.d.ts +320 -0
  21. package/lib/types/generated/errors.localized.js +318 -0
  22. package/lib/types/home-fence.d.ts +7 -0
  23. package/lib/types/home-fence.js +58 -3
  24. package/lib/types/index.d.ts +1 -18
  25. package/lib/types/index.js +1 -18
  26. package/lib/types/io.js +1 -1
  27. package/lib/types/mutation-authority.d.ts +14 -37
  28. package/lib/types/mutation-authority.js +16 -103
  29. package/lib/types/mutation-storage-adapter.js +9 -6
  30. package/lib/types/mutation-unit.d.ts +14 -0
  31. package/lib/types/mutation-unit.js +30 -10
  32. package/lib/types/opt-in.js +1 -1
  33. package/lib/types/platform/index.d.ts +8 -1
  34. package/lib/types/platform/index.js +3 -0
  35. package/lib/types/review-channel.js +3 -1
  36. package/lib/types/review-context.js +3 -1
  37. package/lib/types/run-registry.d.ts +2 -24
  38. package/lib/types/scope.js +1 -1
  39. package/lib/types/signals.d.ts +1 -1
  40. package/lib/types/skill-store.d.ts +7 -1
  41. package/lib/types/skill-store.js +43 -80
  42. package/lib/types/skills.d.ts +11 -0
  43. package/lib/types/skills.js +11 -0
  44. package/lib/types/subagent/types.d.ts +3 -3
  45. package/lib/types/tree-lock.js +4 -1
  46. package/lib/types/unit-claim.d.ts +8 -0
  47. package/lib/types/unit-claim.js +3 -0
  48. package/lib/types/unit-journal.d.ts +3 -1
  49. package/lib/types/unit-journal.js +12 -3
  50. package/lib/types/unit-storage.d.ts +1 -0
  51. package/lib/types/write-gates.d.ts +1 -1
  52. package/lib/types/write-gates.js +3 -1
  53. package/lib/types/write.d.ts +11 -0
  54. package/lib/types/write.js +11 -0
  55. package/lib/write.js +357 -0
  56. package/package.json +16 -4
  57. package/lib/errors-DUcEoTLR.js +0 -58
  58. package/lib/http-routes-_anZVlPf.js +0 -233
  59. package/lib/types/unit-backend.d.ts +0 -5
  60. package/lib/types/unit-backend.js +0 -55
  61. package/lib/types/unit-transaction.d.ts +0 -225
  62. package/lib/types/unit-transaction.js +0 -501
@@ -1,26 +1,7 @@
1
- import type { MutationOwner } from '@lmzhen/dsh-evolution-contract';
2
1
  import { HomeFence } from './home-fence.ts';
3
- import { LeaseStore, type LeaseToken } from './lease-store.ts';
2
+ import { LeaseStore } from './lease-store.ts';
4
3
  import type { EvolutionIoLike } from './io.ts';
5
- import { type MutationLockPort, type MutationLimits, type MutationResult, type MutationSnapshotPort, type MutationUnitOptions, type MutationRequest } from './mutation-unit.ts';
6
- export interface MutationAuthorityContext {
7
- readonly owner: MutationOwner;
8
- readonly runId: string;
9
- readonly lease: LeaseToken;
10
- readonly signal?: AbortSignal;
11
- }
12
- export type MutationAuthorityApplyOptions = Omit<MutationUnitOptions, 'io' | 'lock' | 'serial' | 'context'>;
13
- export interface RecoveryReport {
14
- readonly recovered: readonly MutationResult[];
15
- readonly blocked: readonly {
16
- readonly unitId: string;
17
- readonly runId?: string;
18
- }[];
19
- }
20
- export declare class MutationAuthorityError extends Error {
21
- readonly code: 'lease-missing' | 'lease-mismatch' | 'fence-busy' | 'fence-io' | 'transact-failed';
22
- constructor(code: MutationAuthorityError['code'], message: string);
23
- }
4
+ import type { MutationLockPort } from './mutation-unit.ts';
24
5
  export interface MutationAuthorityOptions {
25
6
  readonly io: EvolutionIoLike;
26
7
  readonly home: string;
@@ -30,30 +11,26 @@ export interface MutationAuthorityOptions {
30
11
  readonly now?: () => number;
31
12
  }
32
13
  /**
33
- * Plugin-side write authority: one home fence + one active lease before any
34
- * multi-file unit or single-file transaction. Domain code never takes a second
35
- * lock; MutationUnit remains the only multi-file transaction engine.
14
+ * The family's write authority. It owns the one home fence and the per-run lease store.
15
+ *
16
+ * The lease is a per-run mutex for long-running review/approval work; foreground writes
17
+ * have no run identity and are serialized by the fence. The former apply/transact/recover
18
+ * facade claimed to gate every write on a lease but had no production caller, so it was
19
+ * removed rather than kept as a false narrow waist.
36
20
  */
37
- export declare function mutationLockFrom(ctx: {
38
- get?(name: string): unknown;
39
- } | undefined): MutationLockPort | undefined;
40
21
  export declare class MutationAuthority {
41
- private readonly io;
42
22
  private readonly leases;
43
23
  private readonly fence;
44
- /** Lease primitives for domain run/claim owners. */
24
+ /** Lease primitives for run/claim owners (review, approval). */
45
25
  get lease(): LeaseStore;
46
26
  /** The one home fence domain unit engines must reuse instead of taking tree-lock themselves. */
47
27
  get homeFence(): HomeFence;
48
- /** Adapter for legacy MutationUnit call sites that accept a lock port. */
28
+ /** Adapter for MutationUnit call sites that accept a lock port. It is the fence, no more. */
49
29
  get mutationLock(): MutationLockPort;
50
30
  constructor(options: MutationAuthorityOptions);
51
- private assertLease;
52
- apply(request: MutationRequest, context: MutationAuthorityContext, options: MutationAuthorityApplyOptions): Promise<MutationResult>;
53
- transact(path: string, task: (current: string | null) => Promise<string | null> | string | null, context: MutationAuthorityContext): Promise<void>;
54
- recover(options: {
55
- readonly snapshots: MutationSnapshotPort;
56
- readonly limits: MutationLimits;
57
- }): Promise<RecoveryReport>;
58
31
  }
32
+ /** Read the authority's fence adapter from a context; undefined means no authority is mounted. */
33
+ export declare function mutationLockFrom(ctx: {
34
+ get?(name: string): unknown;
35
+ } | undefined): MutationLockPort | undefined;
59
36
  //# sourceMappingURL=mutation-authority.d.ts.map
@@ -1,40 +1,21 @@
1
- import { HomeFence, HomeFenceError } from "./home-fence.js";
1
+ import { HomeFence } from "./home-fence.js";
2
2
  import { LeaseStore } from "./lease-store.js";
3
- import { MutationUnit, } from "./mutation-unit.js";
4
- export class MutationAuthorityError extends Error {
5
- code;
6
- constructor(code, message) {
7
- super(message);
8
- this.name = 'MutationAuthorityError';
9
- this.code = code;
10
- }
11
- }
12
- const passiveLock = {
13
- async acquire() {
14
- return { async release() { } };
15
- },
16
- };
17
- const identitySerial = async (task) => await task();
18
3
  /**
19
- * Plugin-side write authority: one home fence + one active lease before any
20
- * multi-file unit or single-file transaction. Domain code never takes a second
21
- * lock; MutationUnit remains the only multi-file transaction engine.
4
+ * The family's write authority. It owns the one home fence and the per-run lease store.
5
+ *
6
+ * The lease is a per-run mutex for long-running review/approval work; foreground writes
7
+ * have no run identity and are serialized by the fence. The former apply/transact/recover
8
+ * facade claimed to gate every write on a lease but had no production caller, so it was
9
+ * removed rather than kept as a false narrow waist.
22
10
  */
23
- export function mutationLockFrom(ctx) {
24
- if (ctx?.get === undefined)
25
- return undefined;
26
- const authority = ctx.get('evolutionMutationAuthority');
27
- return authority?.mutationLock;
28
- }
29
11
  export class MutationAuthority {
30
- io;
31
12
  leases;
32
13
  fence;
33
- /** Lease primitives for domain run/claim owners. */
14
+ /** Lease primitives for run/claim owners (review, approval). */
34
15
  get lease() { return this.leases; }
35
16
  /** The one home fence domain unit engines must reuse instead of taking tree-lock themselves. */
36
17
  get homeFence() { return this.fence; }
37
- /** Adapter for legacy MutationUnit call sites that accept a lock port. */
18
+ /** Adapter for MutationUnit call sites that accept a lock port. It is the fence, no more. */
38
19
  get mutationLock() {
39
20
  return {
40
21
  acquire: async () => {
@@ -44,83 +25,15 @@ export class MutationAuthority {
44
25
  };
45
26
  }
46
27
  constructor(options) {
47
- this.io = options.io;
48
28
  this.leases = options.leases ?? new LeaseStore({ io: options.io, home: options.home, ...(options.now === undefined ? {} : { now: options.now }) });
49
29
  this.fence = options.fence ?? new HomeFence({ io: options.io, home: options.home, ...(options.waitMs === undefined ? {} : { waitMs: options.waitMs }), ...(options.now === undefined ? {} : { now: options.now }) });
50
30
  }
51
- async assertLease(context) {
52
- const current = await this.leases.active(context.runId);
53
- if (current === null)
54
- throw new MutationAuthorityError('lease-missing', 'mutation lease is not active for ' + context.runId);
55
- if (current.id !== context.lease.id || current.epoch !== context.lease.epoch || current.owner !== context.owner) {
56
- throw new MutationAuthorityError('lease-mismatch', 'mutation lease does not own ' + context.runId);
57
- }
58
- }
59
- async apply(request, context, options) {
60
- if (context.signal?.aborted === true)
61
- throw new MutationAuthorityError('transact-failed', 'mutation aborted before apply');
62
- await this.assertLease(context);
63
- try {
64
- return await this.fence.run(async () => {
65
- await this.assertLease(context);
66
- const unitContext = { owner: context.owner, runId: context.runId, leaseId: context.lease.id };
67
- const unit = new MutationUnit({ io: this.io, lock: passiveLock, serial: identitySerial, context: unitContext, ...options });
68
- return await unit.apply(request);
69
- });
70
- }
71
- catch (error) {
72
- if (error instanceof HomeFenceError) {
73
- throw new MutationAuthorityError(error.reason === 'busy' ? 'fence-busy' : 'fence-io', error.message);
74
- }
75
- throw error;
76
- }
77
- }
78
- async transact(path, task, context) {
79
- await this.assertLease(context);
80
- try {
81
- return await this.fence.run(async () => {
82
- await this.assertLease(context);
83
- const body = async (current) => await task(current);
84
- if (this.io.transact !== undefined)
85
- await this.io.transact(path, body);
86
- else {
87
- const current = await this.io.readText(path);
88
- const next = await body(current);
89
- if (next === null)
90
- await this.io.remove(path);
91
- else if (next !== current)
92
- await this.io.writeText(path, next);
93
- }
94
- return;
95
- });
96
- }
97
- catch (error) {
98
- if (error instanceof HomeFenceError) {
99
- throw new MutationAuthorityError(error.reason === 'busy' ? 'fence-busy' : 'fence-io', error.message);
100
- }
101
- throw error;
102
- }
103
- }
104
- async recover(options) {
105
- return await this.fence.run(async () => {
106
- const unit = new MutationUnit({ io: this.io, snapshots: options.snapshots, limits: options.limits, lock: passiveLock, serial: identitySerial });
107
- const prepared = await options.snapshots.listPrepared?.() ?? [];
108
- const recovered = [];
109
- const blocked = [];
110
- for (const snapshot of prepared) {
111
- if (snapshot.runId === undefined) {
112
- blocked.push({ unitId: snapshot.unitId });
113
- continue;
114
- }
115
- const lease = await this.leases.active(snapshot.runId);
116
- if (lease !== null) {
117
- blocked.push({ unitId: snapshot.unitId, runId: snapshot.runId });
118
- continue;
119
- }
120
- recovered.push(await unit.recover(snapshot.unitId));
121
- }
122
- return { recovered, blocked };
123
- });
124
- }
31
+ }
32
+ /** Read the authority's fence adapter from a context; undefined means no authority is mounted. */
33
+ export function mutationLockFrom(ctx) {
34
+ if (ctx?.get === undefined)
35
+ return undefined;
36
+ const authority = ctx.get('evolutionMutationAuthority');
37
+ return authority?.mutationLock;
125
38
  }
126
39
  //# sourceMappingURL=mutation-authority.js.map
@@ -14,6 +14,7 @@ export function unitSnapshotPort(io, home) {
14
14
  const body = {
15
15
  schemaVersion: 1,
16
16
  unitId: snapshot.unitId,
17
+ ...(snapshot.journalId === undefined ? {} : { journalId: snapshot.journalId }),
17
18
  planDigest: contentHash(JSON.stringify(snapshot.ops)),
18
19
  runId: snapshot.runId ?? snapshot.unitId,
19
20
  target: first?.target ?? '',
@@ -45,6 +46,7 @@ export function unitSnapshotPort(io, home) {
45
46
  return null;
46
47
  return {
47
48
  unitId,
49
+ ...(snapshot.journalId === undefined ? {} : { journalId: snapshot.journalId }),
48
50
  state: snapshot.mutationState ?? 'committed',
49
51
  ops: snapshot.ops,
50
52
  ...(snapshot.cleanup === undefined ? {} : { cleanup: snapshot.cleanup }),
@@ -77,7 +79,7 @@ export function unitSnapshotPort(io, home) {
77
79
  if (seen.has(snapshot.unitId))
78
80
  continue;
79
81
  seen.add(snapshot.unitId);
80
- out.push({ unitId: snapshot.unitId, state: 'prepared', ops: snapshot.ops, ...(snapshot.cleanup === undefined ? {} : { cleanup: snapshot.cleanup }), createdAt: snapshot.createdAt, ...(snapshot.origin === 'foreground' || snapshot.origin === 'background_review' ? { owner: snapshot.origin } : {}), runId: snapshot.runId, ...(snapshot.leaseId === undefined ? {} : { leaseId: snapshot.leaseId }) });
82
+ out.push({ unitId: snapshot.unitId, ...(snapshot.journalId === undefined ? {} : { journalId: snapshot.journalId }), state: 'prepared', ops: snapshot.ops, ...(snapshot.cleanup === undefined ? {} : { cleanup: snapshot.cleanup }), createdAt: snapshot.createdAt, ...(snapshot.origin === 'foreground' || snapshot.origin === 'background_review' ? { owner: snapshot.origin } : {}), runId: snapshot.runId, ...(snapshot.leaseId === undefined ? {} : { leaseId: snapshot.leaseId }) });
81
83
  }
82
84
  }
83
85
  return out;
@@ -98,7 +100,7 @@ export async function pruneTreeChangeUnits(io, home, keep = 500) {
98
100
  const snapshot = JSON.parse(await io.readText(join(dir, name)) ?? '');
99
101
  if (snapshot.kind !== 'tree-change' || snapshot.mutationState === 'prepared')
100
102
  continue;
101
- terminal.push({ name, unitId: snapshot.unitId, createdAt: snapshot.createdAt });
103
+ terminal.push({ name, unitId: snapshot.unitId, ...(snapshot.journalId === undefined ? {} : { journalId: snapshot.journalId }), createdAt: snapshot.createdAt });
102
104
  }
103
105
  catch {
104
106
  // unreadable files are left for the explicit recovery/audit path
@@ -108,7 +110,7 @@ export async function pruneTreeChangeUnits(io, home, keep = 500) {
108
110
  let removed = 0;
109
111
  for (const entry of terminal.slice(keep)) {
110
112
  await io.remove(join(dir, entry.name));
111
- await io.remove(unitJournalPath(home, entry.unitId, 'skill')).catch(() => { });
113
+ await io.remove(unitJournalPath(home, entry.journalId ?? entry.unitId, 'skill')).catch(() => { });
112
114
  removed += 1;
113
115
  }
114
116
  return removed;
@@ -131,13 +133,14 @@ export function unitJournalPort(io, home) {
131
133
  const journal = {
132
134
  schemaVersion: 1,
133
135
  unitId: record.unitId,
134
- runId: record.unitId,
135
- planDigest: contentHash(JSON.stringify(record)),
136
+ ...(record.journalId === undefined ? {} : { journalId: record.journalId }),
137
+ runId: record.runId ?? record.unitId,
138
+ planDigest: contentHash(JSON.stringify({ unitId: record.unitId, target: record.target ?? record.changed[0] ?? '', roots: record.roots ?? [], changed: record.changed })),
136
139
  target: record.target ?? record.changed[0] ?? '',
137
140
  sources: record.roots ?? [],
138
141
  phase: PHASE[record.phase],
139
142
  storageKey: unitStorageKey(record.unitId),
140
- snapshotSha256: contentHash(JSON.stringify(record)),
143
+ snapshotSha256: contentHash(JSON.stringify({ unitId: record.unitId, target: record.target ?? record.changed[0] ?? '', roots: record.roots ?? [] })),
141
144
  kind: 'tree-change',
142
145
  updatedAt: Date.now(),
143
146
  };
@@ -1,4 +1,5 @@
1
1
  import { type transactIo } from './io.ts';
2
+ import type { UnitClaimPort } from './unit-claim.ts';
2
3
  import type { MutationOwner } from '@lmzhen/dsh-evolution-contract';
3
4
  export interface MutationRoot {
4
5
  name: string;
@@ -54,6 +55,10 @@ export interface MutationValidation {
54
55
  export declare function validateMutationRequest(request: MutationRequest, limits: MutationLimits): MutationValidation;
55
56
  export interface MutationJournalRecord {
56
57
  unitId: string;
58
+ /** Unique journal key for this nested unit; unitId may be shared by a merge's sub-writes. */
59
+ journalId?: string;
60
+ /** Run that owns this unit; absent for a foreground tree-change without a run. */
61
+ runId?: string;
57
62
  phase: 'prepared' | 'unit-written' | 'committed' | 'failed' | 'undone';
58
63
  changed: readonly string[];
59
64
  target?: string;
@@ -77,6 +82,7 @@ export interface MutationSnapshotOp {
77
82
  }
78
83
  export interface MutationSnapshot {
79
84
  unitId: string;
85
+ journalId?: string;
80
86
  state: 'prepared' | 'committed' | 'undone';
81
87
  ops: readonly MutationSnapshotOp[];
82
88
  cleanup?: readonly string[];
@@ -112,8 +118,13 @@ export interface MutationUnitOptions {
112
118
  limits: MutationLimits;
113
119
  serial?: <T>(task: () => Promise<T>) => Promise<T>;
114
120
  lock?: MutationLockPort;
121
+ /** Explicit escape for a caller that already holds the home fence (nested merge/skill write). */
122
+ nested?: boolean;
115
123
  journal?: MutationJournalPort;
116
124
  snapshots?: MutationSnapshotPort;
125
+ /** Optional merge target claim, acquired after the fence and released in finally. */
126
+ claim?: UnitClaimPort;
127
+ claimRunId?: string;
117
128
  hooks?: MutationUnitHooks;
118
129
  context?: MutationUnitContext;
119
130
  validateWrite?: (op: TreeChangeOp) => string | null;
@@ -144,12 +155,15 @@ export declare class MutationUnit {
144
155
  private readonly lock;
145
156
  private readonly journal;
146
157
  private readonly snapshots;
158
+ private readonly claim;
159
+ private readonly claimRunId;
147
160
  private readonly hooks;
148
161
  private readonly context;
149
162
  private readonly validateWrite;
150
163
  private readonly kernel;
151
164
  private readonly transactGuard;
152
165
  private readonly now;
166
+ private readonly journalId;
153
167
  constructor(options: MutationUnitOptions);
154
168
  preview(request: MutationRequest): MutationPreviewResult;
155
169
  apply(request: MutationRequest): Promise<MutationResult>;
@@ -100,24 +100,33 @@ export class MutationUnit {
100
100
  lock;
101
101
  journal;
102
102
  snapshots;
103
+ claim;
104
+ claimRunId;
103
105
  hooks;
104
106
  context;
105
107
  validateWrite;
106
108
  kernel;
107
109
  transactGuard;
108
110
  now;
111
+ journalId;
109
112
  constructor(options) {
110
113
  this.io = options.io;
111
114
  this.limits = options.limits;
112
115
  this.serial = options.serial ?? identitySerial;
116
+ if (options.lock === undefined && options.nested !== true) {
117
+ throw new Error('mutation-unit: a lock (or an explicit nested:true under an outer fence) is required');
118
+ }
113
119
  this.lock = options.lock ?? noLock;
114
120
  this.journal = options.journal;
115
121
  this.snapshots = options.snapshots;
122
+ this.claim = options.claim;
123
+ this.claimRunId = options.claimRunId;
116
124
  this.hooks = options.hooks;
117
125
  this.context = options.context;
118
126
  this.validateWrite = options.validateWrite;
119
127
  this.transactGuard = options.transactGuard !== false;
120
128
  this.now = options.now ?? Date.now;
129
+ this.journalId = 'j-' + String(this.now()) + '-' + Math.random().toString(36).slice(2);
121
130
  const transact = options.transact;
122
131
  this.kernel = new WriteKernel({ io: this.io, ...(transact === undefined ? {} : { transact }), now: this.now });
123
132
  }
@@ -145,7 +154,17 @@ export class MutationUnit {
145
154
  lease = await this.lock.acquire();
146
155
  }
147
156
  catch (error) {
148
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'lock-failed', message: error instanceof Error ? error.message : String(error) }] };
157
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'unit-fence-failed', message: error instanceof Error ? error.message : String(error) }] };
158
+ }
159
+ let claim;
160
+ if (this.claim !== undefined) {
161
+ try {
162
+ claim = await this.claim.acquire(primary, this.claimRunId ?? this.context?.runId ?? '');
163
+ }
164
+ catch (error) {
165
+ await lease.release();
166
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'claim-failed', message: error instanceof Error ? error.message : String(error) }] };
167
+ }
149
168
  }
150
169
  const changed = [];
151
170
  const warnings = [];
@@ -185,8 +204,8 @@ export class MutationUnit {
185
204
  });
186
205
  const cleanup = request.cleanupPaths === undefined ? {} : { cleanup: request.cleanupPaths };
187
206
  if (this.snapshots !== undefined)
188
- await bestEffort(() => this.snapshots.write({ unitId, state: 'prepared', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
189
- await bestEffort(async () => this.journal?.write({ unitId, phase: 'prepared', changed: [], target: validation.roots.find(root => root.name === primary)?.name ?? primary, roots: validation.roots.map(root => root.name) }));
207
+ await bestEffort(() => this.snapshots.write({ unitId, journalId: this.journalId, state: 'prepared', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
208
+ 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) }));
190
209
  for (const op of validation.ops) {
191
210
  const snapshot = snapshots.find(entry => entry.target === op.target);
192
211
  if (snapshot === undefined)
@@ -204,12 +223,12 @@ export class MutationUnit {
204
223
  warnings.push(error instanceof Error ? error.message : String(error));
205
224
  }
206
225
  }
207
- await bestEffort(async () => this.journal?.write({ unitId, phase: 'unit-written', changed, target: primary, roots: validation.roots.map(root => root.name) }));
226
+ 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) }));
208
227
  // P2-1: the committed snapshot is the recovery authority. Write it BEFORE the journal's
209
228
  // committed phase so a crash in this window recovers as committed, never rolled back.
210
229
  if (this.snapshots !== undefined)
211
- await bestEffort(() => this.snapshots.write({ unitId, state: 'committed', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
212
- await bestEffort(async () => this.journal?.write({ unitId, phase: 'committed', changed, target: primary, roots: validation.roots.map(root => root.name) }));
230
+ await bestEffort(() => this.snapshots.write({ unitId, journalId: this.journalId, state: 'committed', ops: eventOps, ...cleanup, createdAt: this.now(), ...this.contextFields() }));
231
+ 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) }));
213
232
  try {
214
233
  await this.hooks?.committed?.({ unitId, changed, ops: eventOps, roots: validation.roots.map(root => root.name) });
215
234
  }
@@ -228,7 +247,7 @@ export class MutationUnit {
228
247
  rollbackFailure = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
229
248
  }
230
249
  const detail = rollbackFailure === '' ? message : message + '; rollback failed: ' + rollbackFailure;
231
- await this.journal?.write({ unitId, phase: 'failed', changed, error: detail });
250
+ await this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'failed', changed, error: detail });
232
251
  try {
233
252
  await this.hooks?.rolledBack?.({
234
253
  unitId,
@@ -251,6 +270,7 @@ export class MutationUnit {
251
270
  return { ok: false, unitId, dryRun: false, changed, errors: [{ code: 'write-failed', message: detail }] };
252
271
  }
253
272
  finally {
273
+ await claim?.release().catch(() => { });
254
274
  await lease.release();
255
275
  }
256
276
  });
@@ -278,7 +298,7 @@ export class MutationUnit {
278
298
  lease = await this.lock.acquire();
279
299
  }
280
300
  catch (error) {
281
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'lock-failed', message: error instanceof Error ? error.message : String(error) }] };
301
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'unit-fence-failed', message: error instanceof Error ? error.message : String(error) }] };
282
302
  }
283
303
  const reverted = [];
284
304
  try {
@@ -298,7 +318,7 @@ export class MutationUnit {
298
318
  for (const path of snapshot.cleanup ?? [])
299
319
  await this.io.remove(path).catch(() => { });
300
320
  await this.snapshots?.write({ ...snapshot, state: 'undone' });
301
- await this.journal?.write({ unitId, phase: 'undone', changed: reverted, ...(snapshot.ops[0]?.target === undefined ? {} : { target: snapshot.ops[0].target }), roots: [...new Set(snapshot.ops.map(op => op.skill).filter((skill) => skill !== undefined))] });
321
+ await this.journal?.write({ unitId, journalId: snapshot.journalId ?? this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'undone', changed: reverted, ...(snapshot.ops[0]?.target === undefined ? {} : { target: snapshot.ops[0].target }), roots: [...new Set(snapshot.ops.map(op => op.skill).filter((skill) => skill !== undefined))] });
302
322
  try {
303
323
  await this.hooks?.undone?.({ unitId, changed: reverted, ops: snapshot.ops, roots: [...new Set(snapshot.ops.map(op => op.skill).filter((skill) => skill !== undefined))] });
304
324
  }
@@ -354,7 +374,7 @@ export class MutationUnit {
354
374
  }
355
375
  for (const path of snapshot.cleanup ?? [])
356
376
  await this.io.remove(path).catch(() => { });
357
- await this.journal?.write({ unitId, phase: 'undone', changed: undone, ...(snapshot.ops[0]?.target === undefined ? {} : { target: snapshot.ops[0].target }), roots: [...new Set(snapshot.ops.map(op => op.skill).filter((skill) => skill !== undefined))] });
377
+ await this.journal?.write({ unitId, journalId: snapshot.journalId === undefined ? this.journalId : snapshot.journalId + ':undo', ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'undone', changed: undone, ...(snapshot.ops[0]?.target === undefined ? {} : { target: snapshot.ops[0].target }), roots: [...new Set(snapshot.ops.map(op => op.skill).filter((skill) => skill !== undefined))] });
358
378
  await this.snapshots?.write({ ...snapshot, state: 'undone' });
359
379
  try {
360
380
  await this.hooks?.undone?.({ unitId, changed: undone, ops: snapshot.ops, roots: [...new Set(snapshot.ops.map(op => op.skill).filter((skill) => skill !== undefined))] });
@@ -1,4 +1,4 @@
1
- import { scopeOf } from '@deepseek-ai/dsh-scope';
1
+ import { scopeOf } from "./platform/index.js";
2
2
  /**
3
3
  * Tool names only a session that mounted the family's MODEL rows can see.
4
4
  *
@@ -7,11 +7,18 @@
7
7
  export { defineTool } from '@deepseek-ai/dsh-tools';
8
8
  export type { ObjectJsonSchema, ToolDefinition, ToolGuard, ToolRestriction, } from '@deepseek-ai/dsh-tools';
9
9
  export type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands';
10
+ export { scopeOf } from '@deepseek-ai/dsh-scope';
11
+ export { defineDomain, domainTable, DomainError } from '@deepseek-ai/dsh-storage-domain';
12
+ export { escapeText } from '@deepseek-ai/dsh-skill';
13
+ export type { SkillCandidate, SkillDefinition, SkillInvocationPolicy, SkillLookupOptions, SkillProvider, SkillProviderControl, SkillProviderObservation, SkillSummary, } from '@deepseek-ai/dsh-skill';
14
+ export type { Domain } from '@deepseek-ai/dsh-storage-domain';
10
15
  export { BlockAssembler, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm';
11
16
  export type { ContentBlock, ContextFormed, GenerateOptions, Message, RequestMessage, StreamChunk, ToolCallBlock, ToolCallId, ToolHistory, ToolSchema, } from '@deepseek-ai/dsh-llm';
12
17
  export { SessionId } from '@deepseek-ai/dsh-session';
13
18
  export type { EpochHeader, Session, SessionEvent } from '@deepseek-ai/dsh-session';
14
- export type { Agent } from '@deepseek-ai/dsh-agent';
19
+ export type { Agent, AgentOptions, PreStepDecision } from '@deepseek-ai/dsh-agent';
20
+ export type { SubagentStopReason } from '@deepseek-ai/dsh-subagent';
21
+ export type { UserMessage } from '@deepseek-ai/dsh-llm';
15
22
  export type { PromptContext, PromptSection } from '@deepseek-ai/dsh-system-prompt';
16
23
  export { presetsPort } from './presets.ts';
17
24
  export type { PresetDefinitionLike, PresetDocument, PresetsPort } from './presets.ts';
@@ -5,6 +5,9 @@
5
5
  * the platform-boundary gate keeps @deepseek-ai/dsh-* imports inside core/platform.
6
6
  */
7
7
  export { defineTool } from '@deepseek-ai/dsh-tools';
8
+ export { scopeOf } from '@deepseek-ai/dsh-scope';
9
+ export { defineDomain, domainTable, DomainError } from '@deepseek-ai/dsh-storage-domain';
10
+ export { escapeText } from '@deepseek-ai/dsh-skill';
8
11
  export { BlockAssembler, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm';
9
12
  export { SessionId } from '@deepseek-ai/dsh-session';
10
13
  export { presetsPort } from "./presets.js";
@@ -15,7 +15,9 @@
15
15
  * @module @lmzhen/dsh-evolution-core/review-channel
16
16
  */
17
17
  /** Session ids currently executing a review prompt, oldest delivery first. */
18
- const markedSessions = new Set();
18
+ const MARK_KEY = Symbol.for('dsh.evolution.review-channel.marked');
19
+ const registry = globalThis;
20
+ const markedSessions = registry[MARK_KEY] ?? (registry[MARK_KEY] = new Set());
19
21
  /**
20
22
  * Mark one session as running the review channel's prompt; idempotent, and
21
23
  * keyed by session so a mark can never leak into another session.
@@ -8,7 +8,9 @@
8
8
  * @module @lmzhen/dsh-evolution-core/review-context
9
9
  */
10
10
  import { AsyncLocalStorage } from 'node:async_hooks';
11
- const storage = new AsyncLocalStorage();
11
+ const STORAGE_KEY = Symbol.for('dsh.evolution.review-context.storage');
12
+ const registry = globalThis;
13
+ const storage = registry[STORAGE_KEY] ?? (registry[STORAGE_KEY] = new AsyncLocalStorage());
12
14
  /**
13
15
  * Run one review tool loop under the review write context.
14
16
  * @param context - review/run identity.
@@ -38,6 +38,8 @@
38
38
  * @module
39
39
  */
40
40
  import type { EvolutionIoLike } from './io.ts';
41
+ import type { RunOutcome } from '@lmzhen/dsh-evolution-contract';
42
+ export type { RunOutcome } from '@lmzhen/dsh-evolution-contract';
41
43
  /** The kinds of long-running work the registry tracks. */
42
44
  export type RunKind = 'maintain' | 'merge';
43
45
  /** Which merge command opened a run. `kind` stays the work family; this is the command. */
@@ -75,14 +77,6 @@ export interface RunRecord {
75
77
  supersededAt?: number | undefined;
76
78
  /** The run this run was spawned from (approve/resume after an earlier command). */
77
79
  parentRunId?: string | undefined;
78
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
79
- mergeStatus?: 'running' | 'succeeded' | 'failed' | 'cancelled' | 'awaiting-approval' | 'undone' | 'superseded' | 'interrupted' | 'orphan' | undefined;
80
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
81
- stagingRef?: string | undefined;
82
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
83
- pairKey?: string | undefined;
84
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
85
- pairs?: readonly unknown[] | undefined;
86
80
  }
87
81
  /** What a started run gets: its id and the signal its work must honour. */
88
82
  export interface RunHandle {
@@ -93,22 +87,6 @@ export interface RunHandle {
93
87
  readonly startedAt: number;
94
88
  readonly command?: RunCommand | undefined;
95
89
  readonly parentRunId?: string | undefined;
96
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
97
- readonly mergeStatus?: 'running' | 'succeeded' | 'failed' | 'cancelled' | 'awaiting-approval' | 'undone' | 'superseded' | 'interrupted' | 'orphan' | undefined;
98
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
99
- readonly stagingRef?: string | undefined;
100
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
101
- readonly pairKey?: string | undefined;
102
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
103
- readonly pairs?: readonly unknown[] | undefined;
104
- }
105
- /** How a run ended, as reported by its owner. */
106
- export interface RunOutcome {
107
- state: 'succeeded' | 'failed' | 'cancelled' | 'interrupted';
108
- resultRef?: string | undefined;
109
- failure?: string | undefined;
110
- /** @deprecated Legacy merge projection; read-only compatibility, never written. */
111
- mergeStatus?: 'running' | 'succeeded' | 'failed' | 'cancelled' | 'awaiting-approval' | 'undone' | 'superseded' | 'interrupted' | 'orphan' | undefined;
112
90
  }
113
91
  /** The registry surface the commands row drives. */
114
92
  export interface RunRegistry {
@@ -1,4 +1,4 @@
1
- import { scopeOf } from '@deepseek-ai/dsh-scope';
1
+ import { scopeOf } from "./platform/index.js";
2
2
  export function callingScope(ctx, held) {
3
3
  if (held !== undefined)
4
4
  return held;
@@ -5,7 +5,7 @@
5
5
  * is spent. `turn/end` calls `observeEvent`; the returned review kind is
6
6
  * accumulated until a configured interval fires.
7
7
  */
8
- import type { SessionEvent } from '@deepseek-ai/dsh-session';
8
+ import type { SessionEvent } from './platform/index.ts';
9
9
  export type ReviewKind = 'memory' | 'skill' | 'combined';
10
10
  export interface SignalConfig {
11
11
  memoryInterval: number;
@@ -185,6 +185,8 @@ export interface ArchiveOptions {
185
185
  }
186
186
  /** One multi-skill merge commit: target body + support files, with the source names it absorbs. */
187
187
  export interface CommitMergePlan {
188
+ /** The merge UnitTransaction already holds the home fence; nested tree writes must not re-acquire it. */
189
+ readonly nested?: boolean;
188
190
  readonly runId?: string;
189
191
  /** The unit transaction id; history must record this exact id for undo. */
190
192
  readonly unitId?: string;
@@ -635,7 +637,11 @@ export declare class SkillLibrary {
635
637
  * Every failure rolls back what already landed; a rollback failure names the
636
638
  * unrestored skills instead of claiming success.
637
639
  */
638
- commitMerge(plan: CommitMergePlan): Promise<CommitMergeResult>;
640
+ /** Expose the store's writer queue so a caller can acquire it BEFORE the home fence. */
641
+ runSerial<T>(task: () => Promise<T>): Promise<T>;
642
+ commitMerge(plan: CommitMergePlan, options?: {
643
+ readonly serialized?: boolean;
644
+ }): Promise<CommitMergeResult>;
639
645
  /**
640
646
  * V2 (design §16.7): what an apply-mode consolidation would do for ONE source,
641
647
  * computed BEFORE any side effect. `blocked` means behaviour is exactly the