@lmzhen/dsh-evolution-core 0.41.0 → 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 (55) hide show
  1. package/lib/composition/index.js +2 -2
  2. package/lib/{composition-Da8NfRI7.js → composition-CVafrlEw.js} +2 -2
  3. package/lib/guards-3f02mnf2.js +29 -0
  4. package/lib/http-routes.js +205 -1
  5. package/lib/index.js +3587 -15048
  6. package/lib/mutations-jUuOPaCn.js +718 -0
  7. package/lib/platform/index.js +2 -2
  8. package/lib/{platform-CFp373_0.js → platform-B06_h8t-.js} +4 -1
  9. package/lib/runtime/plugin.js +2 -2
  10. package/lib/{session-projection-CXUNPkq9.js → session-projection-EB7mUOlJ.js} +63 -63
  11. package/lib/skill-health-BLGZTIv8.js +3773 -0
  12. package/lib/skill-history-_Cssts5o.js +1912 -0
  13. package/lib/skills.js +4067 -0
  14. package/lib/subagent/index.js +1 -1
  15. package/lib/types/home-fence.d.ts +7 -0
  16. package/lib/types/home-fence.js +58 -3
  17. package/lib/types/index.d.ts +1 -18
  18. package/lib/types/index.js +1 -18
  19. package/lib/types/io.js +1 -1
  20. package/lib/types/mutation-authority.d.ts +14 -37
  21. package/lib/types/mutation-authority.js +16 -103
  22. package/lib/types/mutation-storage-adapter.js +9 -6
  23. package/lib/types/mutation-unit.d.ts +14 -0
  24. package/lib/types/mutation-unit.js +30 -10
  25. package/lib/types/opt-in.js +1 -1
  26. package/lib/types/platform/index.d.ts +8 -1
  27. package/lib/types/platform/index.js +3 -0
  28. package/lib/types/review-channel.js +3 -1
  29. package/lib/types/review-context.js +3 -1
  30. package/lib/types/run-registry.d.ts +2 -24
  31. package/lib/types/scope.js +1 -1
  32. package/lib/types/signals.d.ts +1 -1
  33. package/lib/types/skill-store.d.ts +7 -1
  34. package/lib/types/skill-store.js +43 -80
  35. package/lib/types/skills.d.ts +11 -0
  36. package/lib/types/skills.js +11 -0
  37. package/lib/types/subagent/types.d.ts +3 -3
  38. package/lib/types/tree-lock.js +4 -1
  39. package/lib/types/unit-claim.d.ts +8 -0
  40. package/lib/types/unit-claim.js +3 -0
  41. package/lib/types/unit-journal.d.ts +3 -1
  42. package/lib/types/unit-journal.js +12 -3
  43. package/lib/types/unit-storage.d.ts +1 -0
  44. package/lib/types/write-gates.d.ts +1 -1
  45. package/lib/types/write-gates.js +3 -1
  46. package/lib/types/write.d.ts +11 -0
  47. package/lib/types/write.js +11 -0
  48. package/lib/write.js +357 -0
  49. package/package.json +16 -4
  50. package/lib/http-routes-_anZVlPf.js +0 -233
  51. package/lib/types/unit-backend.d.ts +0 -5
  52. package/lib/types/unit-backend.js +0 -55
  53. package/lib/types/unit-transaction.d.ts +0 -225
  54. package/lib/types/unit-transaction.js +0 -501
  55. package/lib/{ensure-C5Mo1dbB.js → ensure-BjToTMMj.js} +1 -1
@@ -1,4 +1,4 @@
1
- import { h as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-C5Mo1dbB.js";
1
+ import { h as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-BjToTMMj.js";
2
2
  //#region lib/types/subagent/readiness.js
3
3
  function serviceOf$1(ctx, name) {
4
4
  return ctx.get(name);
@@ -13,11 +13,18 @@ export declare class HomeFenceError extends Error {
13
13
  * One home-level writer queue. It serializes same-process callers before the
14
14
  * tree lock, and the tree lock remains the only cross-process guard the current
15
15
  * backend can provide (nodeEvolutionIo is single-process).
16
+ *
17
+ * `acquire` is public only for legacy call sites; W0 keeps it usable but makes a
18
+ * failed release advance the queue and poison the fence instead of wedging every
19
+ * later writer. Nested acquisition is not supported: the state layer must reuse
20
+ * the transaction it is already inside (see evolution-state-json appendArchive).
16
21
  */
17
22
  export declare class HomeFence {
18
23
  private tail;
24
+ private poisoned;
19
25
  private readonly options;
20
26
  constructor(options: HomeFenceOptions);
27
+ private releaseLock;
21
28
  acquire(): Promise<HomeFenceLease>;
22
29
  run<T>(body: (lock: TreeLock) => Promise<T>): Promise<T>;
23
30
  }
@@ -8,18 +8,58 @@ export class HomeFenceError extends Error {
8
8
  this.reason = reason;
9
9
  }
10
10
  }
11
+ /** Unlink races on Windows are transient: a virus scanner or a closing handle can hold the
12
+ * lock file for a few milliseconds. Retry only those, and only inside the fence release:
13
+ * the durable write path has its own rename budget and must not inherit lock semantics. */
14
+ const RELEASE_RETRY_MS = [25, 50, 100];
15
+ function transientReleaseError(error) {
16
+ if (typeof error !== 'object' || error === null)
17
+ return false;
18
+ const code = error.code;
19
+ return code === 'EPERM' || code === 'EBUSY' || code === 'EACCES';
20
+ }
21
+ function asError(error) {
22
+ return error instanceof Error ? error : new Error(String(error));
23
+ }
24
+ function sleep(ms) {
25
+ return new Promise(resolve => setTimeout(resolve, ms));
26
+ }
11
27
  /**
12
28
  * One home-level writer queue. It serializes same-process callers before the
13
29
  * tree lock, and the tree lock remains the only cross-process guard the current
14
30
  * backend can provide (nodeEvolutionIo is single-process).
31
+ *
32
+ * `acquire` is public only for legacy call sites; W0 keeps it usable but makes a
33
+ * failed release advance the queue and poison the fence instead of wedging every
34
+ * later writer. Nested acquisition is not supported: the state layer must reuse
35
+ * the transaction it is already inside (see evolution-state-json appendArchive).
15
36
  */
16
37
  export class HomeFence {
17
38
  tail = Promise.resolve();
39
+ poisoned;
18
40
  options;
19
41
  constructor(options) {
20
42
  this.options = options;
21
43
  }
44
+ async releaseLock(lock) {
45
+ let attempt = 0;
46
+ for (;;) {
47
+ try {
48
+ await lock.release();
49
+ return;
50
+ }
51
+ catch (error) {
52
+ if (!transientReleaseError(error) || attempt >= RELEASE_RETRY_MS.length)
53
+ throw error;
54
+ await sleep(RELEASE_RETRY_MS[attempt] ?? 100);
55
+ attempt += 1;
56
+ }
57
+ }
58
+ }
22
59
  async acquire() {
60
+ if (this.poisoned !== undefined) {
61
+ throw new HomeFenceError('io', 'home fence is poisoned after a failed lock release: ' + this.poisoned.message);
62
+ }
23
63
  const previous = this.tail;
24
64
  let releaseQueue = () => { };
25
65
  this.tail = new Promise(resolve => { releaseQueue = resolve; });
@@ -33,14 +73,29 @@ export class HomeFence {
33
73
  await assertHomeOwner(this.options.io, this.options.home);
34
74
  }
35
75
  catch (error) {
36
- await acquired.lock.release();
76
+ await acquired.lock.release().catch(() => { });
37
77
  throw error;
38
78
  }
79
+ let released = false;
39
80
  return {
40
81
  lock: acquired.lock,
41
82
  release: async () => {
42
- await acquired.lock.release();
43
- releaseQueue();
83
+ if (released)
84
+ return;
85
+ released = true;
86
+ let failure;
87
+ try {
88
+ await this.releaseLock(acquired.lock);
89
+ }
90
+ catch (error) {
91
+ failure = asError(error);
92
+ this.poisoned = failure;
93
+ }
94
+ finally {
95
+ releaseQueue();
96
+ }
97
+ if (failure !== undefined)
98
+ throw failure;
44
99
  },
45
100
  };
46
101
  }
@@ -33,10 +33,7 @@
33
33
  */
34
34
  export * from './citations.ts';
35
35
  export * from './tree-write.ts';
36
- export * from './unit-storage.ts';
37
- export * from './unit-journal.ts';
38
- export * from './unit-transaction.ts';
39
- export * from './unit-backend.ts';
36
+ export * from './limits.ts';
40
37
  export * from './package-identity.ts';
41
38
  export * from './write-authority.ts';
42
39
  export * from './write-gates.ts';
@@ -51,7 +48,6 @@ export * from './proposal-report.ts';
51
48
  export * from './external-support.ts';
52
49
  export * from './extract-prompt.ts';
53
50
  export * from './cost.ts';
54
- export * from './skill-lint.ts';
55
51
  export * from './health-baseline.ts';
56
52
  export * from './curator.ts';
57
53
  export * from './evolution-events.ts';
@@ -77,8 +73,6 @@ export * from './home-fence.ts';
77
73
  export * from './home-owner.ts';
78
74
  export * from './lease-store.ts';
79
75
  export * from './mutation-authority.ts';
80
- export * from './unit-undo-plan.ts';
81
- export * from './unit-undo.ts';
82
76
  export * from './reports.ts';
83
77
  export * from './long-runs.ts';
84
78
  export * from './serial.ts';
@@ -87,25 +81,14 @@ export * from './platform-services.ts';
87
81
  export * from './instance-scope.ts';
88
82
  export * from './write-inventory.ts';
89
83
  export * from './scope.ts';
90
- export * from './skill-health.ts';
91
84
  export * from './signals.ts';
92
- export * from './skill-reads.ts';
93
- export * from './skill-row-cells.ts';
94
85
  export * from './document-body.ts';
95
86
  export * from './evidence.ts';
96
87
  export * from './session-projection.ts';
97
88
  export * from './drift-signals.ts';
98
- export * from './skill-history.ts';
99
- export * from './unit-members.ts';
100
- export * from './skill-store.ts';
101
- export * from './skill-model.ts';
102
- export * from './mutation-unit.ts';
103
- export * from './mutation-storage-adapter.ts';
104
- export * from './skill-revision.ts';
105
89
  export * from './store-ledger.ts';
106
90
  export * from './reachability.ts';
107
91
  export * from './state-store.ts';
108
- export * from './write-kernel.ts';
109
92
  export * from './threats.ts';
110
93
  export * from './tool-dispatch.ts';
111
94
  export * from './usage.ts';
@@ -34,10 +34,7 @@
34
34
  export * from "./citations.js";
35
35
  // G1/1.1: the ONE authority behind a write (its type and the authorityFrom builder).
36
36
  export * from "./tree-write.js";
37
- export * from "./unit-storage.js";
38
- export * from "./unit-journal.js";
39
- export * from "./unit-transaction.js";
40
- export * from "./unit-backend.js";
37
+ export * from "./limits.js";
41
38
  export * from "./package-identity.js";
42
39
  export * from "./write-authority.js";
43
40
  export * from "./write-gates.js";
@@ -52,7 +49,6 @@ export * from "./proposal-report.js";
52
49
  export * from "./external-support.js";
53
50
  export * from "./extract-prompt.js";
54
51
  export * from "./cost.js";
55
- export * from "./skill-lint.js";
56
52
  export * from "./health-baseline.js";
57
53
  export * from "./curator.js";
58
54
  export * from "./evolution-events.js";
@@ -78,8 +74,6 @@ export * from "./home-fence.js";
78
74
  export * from "./home-owner.js";
79
75
  export * from "./lease-store.js";
80
76
  export * from "./mutation-authority.js";
81
- export * from "./unit-undo-plan.js";
82
- export * from "./unit-undo.js";
83
77
  export * from "./reports.js";
84
78
  export * from "./long-runs.js";
85
79
  export * from "./serial.js";
@@ -88,25 +82,14 @@ export * from "./platform-services.js";
88
82
  export * from "./instance-scope.js";
89
83
  export * from "./write-inventory.js";
90
84
  export * from "./scope.js";
91
- export * from "./skill-health.js";
92
85
  export * from "./signals.js";
93
- export * from "./skill-reads.js";
94
- export * from "./skill-row-cells.js";
95
86
  export * from "./document-body.js";
96
87
  export * from "./evidence.js";
97
88
  export * from "./session-projection.js";
98
89
  export * from "./drift-signals.js";
99
- export * from "./skill-history.js";
100
- export * from "./unit-members.js";
101
- export * from "./skill-store.js";
102
- export * from "./skill-model.js";
103
- export * from "./mutation-unit.js";
104
- export * from "./mutation-storage-adapter.js";
105
- export * from "./skill-revision.js";
106
90
  export * from "./store-ledger.js";
107
91
  export * from "./reachability.js";
108
92
  export * from "./state-store.js";
109
- export * from "./write-kernel.js";
110
93
  export * from "./threats.js";
111
94
  export * from "./tool-dispatch.js";
112
95
  export * from "./usage.js";
package/lib/types/io.js CHANGED
@@ -435,7 +435,7 @@ export function nodeEvolutionIo() {
435
435
  });
436
436
  },
437
437
  async remove(path) {
438
- await rm(path, { recursive: true, force: true });
438
+ await inProcessWrite(path, async () => { await rm(path, { recursive: true, force: true }); });
439
439
  },
440
440
  async list(path) {
441
441
  // "Missing" reads as empty; any other failure (EACCES/EIO) surfaces so a
@@ -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>;