@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
@@ -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
@@ -545,28 +545,15 @@ export class SkillLibrary {
545
545
  return { moves, sources: roots.map(skill => ({ skill })) };
546
546
  }
547
547
  async withMutationLock(task) {
548
- let lease;
549
- try {
550
- lease = await this.lockPort().acquire();
551
- }
552
- catch (error) {
553
- const message = error instanceof Error ? error.message : String(error);
554
- if (message.startsWith('mutation-lock-busy'))
555
- throw error;
556
- // Coordination failure: the per-file transact/serial path remains the
557
- // fallback; a lock sidecar must not change the mutation's business result.
558
- return await task();
559
- }
548
+ // Fail closed: a missing authority/lock is an assembly error, not a reason to run
549
+ // the write outside the fence. The old catch-and-fallback inverted this guard: the
550
+ // "refusing an unfenced production write" error itself took the fallback path.
551
+ const lease = await this.lockPort().acquire();
560
552
  try {
561
553
  return await task();
562
554
  }
563
555
  finally {
564
- try {
565
- await lease.release();
566
- }
567
- catch {
568
- // A failed lock cleanup is a coordination degradation, not a write failure.
569
- }
556
+ await lease.release();
570
557
  }
571
558
  }
572
559
  lockPort() {
@@ -1550,7 +1537,7 @@ export class SkillLibrary {
1550
1537
  const unit = new MutationUnit({
1551
1538
  io: this.io,
1552
1539
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
1553
- lock: { acquire: async () => ({ release: async () => { } }) },
1540
+ nested: true,
1554
1541
  journal: unitJournalPort(this.io, dirname(this.root)),
1555
1542
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1556
1543
  transactGuard: false,
@@ -2144,7 +2131,9 @@ export class SkillLibrary {
2144
2131
  * Every failure rolls back what already landed; a rollback failure names the
2145
2132
  * unrestored skills instead of claiming success.
2146
2133
  */
2147
- async commitMerge(plan) {
2134
+ /** Expose the store's writer queue so a caller can acquire it BEFORE the home fence. */
2135
+ async runSerial(task) { return await this.serial(task); }
2136
+ async commitMerge(plan, options) {
2148
2137
  const target = plan.target.trim();
2149
2138
  const sources = [...new Set(plan.sources.map(name => name.trim()))].filter(name => name !== target);
2150
2139
  if (sources.length === 0)
@@ -2160,7 +2149,7 @@ export class SkillLibrary {
2160
2149
  if (protectedSource !== undefined)
2161
2150
  return { ok: false, message: `来源技能「${protectedSource}」是受保护的内置技能。` };
2162
2151
  const limits = plan.limits ?? this.limits;
2163
- return await this.serial(async () => {
2152
+ const run = async () => {
2164
2153
  const dir = this.dirOf(target);
2165
2154
  const targetPath = join(dir, 'SKILL.md');
2166
2155
  if (!plan.targetExists && await this.io.exists(dir)) {
@@ -2312,6 +2301,7 @@ export class SkillLibrary {
2312
2301
  name: target,
2313
2302
  origin: plan.origin,
2314
2303
  protection: 'write',
2304
+ nested: plan.nested === true,
2315
2305
  writes,
2316
2306
  auditAction: 'merge-rollback',
2317
2307
  auditSummary: 'merge rollback: restore target snapshot',
@@ -2348,6 +2338,7 @@ export class SkillLibrary {
2348
2338
  name: target,
2349
2339
  origin: plan.origin,
2350
2340
  protection: 'write',
2341
+ nested: plan.nested === true,
2351
2342
  writes,
2352
2343
  auditAction: 'merge',
2353
2344
  auditSummary: plan.summary,
@@ -2458,6 +2449,7 @@ export class SkillLibrary {
2458
2449
  name: target,
2459
2450
  origin: plan.origin,
2460
2451
  protection: 'write',
2452
+ nested: plan.nested === true,
2461
2453
  writes,
2462
2454
  auditAction: 'merge',
2463
2455
  auditSummary: plan.summary,
@@ -2477,7 +2469,8 @@ export class SkillLibrary {
2477
2469
  await plan.onPhase?.('sources-archived');
2478
2470
  await plan.onPhase?.('unit-written');
2479
2471
  return { ok: true, message: `已把 ${sources.join(', ')} 合并进「${target}」。`, unitId, targetPath: dir, archived, mutations: 1 + sources.length };
2480
- });
2472
+ };
2473
+ return options?.serialized === true ? await run() : await this.serial(run);
2481
2474
  }
2482
2475
  /**
2483
2476
  * V2 (design §16.7): what an apply-mode consolidation would do for ONE source,
@@ -3157,63 +3150,32 @@ export class SkillLibrary {
3157
3150
  const rel = relative(owner.dir, op.target).split(String.fromCharCode(92)).join('/');
3158
3151
  landing.push({ kind: op.kind, target: op.target, content: op.kind === 'write' ? op.content : null, previous, expected: op.expected, skill, dir: owner.dir, rel });
3159
3152
  }
3160
- const written = [];
3161
- let durabilityWarning = '';
3162
- try {
3163
- for (const entry of landing) {
3164
- try {
3165
- if (this.transact) {
3166
- const baseline = entry.expected === undefined ? entry.previous : entry.expected;
3167
- const drift = { seen: false };
3168
- const ran = { done: false };
3169
- await this.transact(this.io, entry.target, (current) => {
3170
- drift.seen = false;
3171
- ran.done = true;
3172
- if (current !== baseline) {
3173
- drift.seen = true;
3174
- return current;
3175
- }
3176
- return entry.kind === 'delete' ? null : entry.content;
3177
- });
3178
- if (!ran.done)
3179
- throw new Error('internal error: the write transaction for ' + entry.target + ' did not invoke the task; nothing was written');
3180
- if (drift.seen)
3181
- throw new Error('concurrent modification detected: ' + entry.target + ' changed after the plan was computed (a concurrent writer won the race); no further writes were performed');
3182
- }
3183
- else if (entry.kind === 'delete') {
3184
- await this.io.remove(entry.target);
3185
- }
3186
- else {
3187
- await this.io.writeText(entry.target, entry.content ?? '');
3188
- }
3189
- }
3190
- catch (error) {
3191
- if (!isCommittedOnly(error))
3192
- throw error;
3193
- durabilityWarning = error instanceof Error ? error.message : String(error);
3194
- }
3195
- written.push({ target: entry.target, previous: entry.previous });
3196
- }
3197
- }
3198
- catch (error) {
3199
- const stuck = [];
3200
- for (const entry of written.reverse()) {
3201
- try {
3202
- if (entry.previous === null)
3203
- await this.io.remove(entry.target);
3204
- else
3205
- await this.io.writeText(entry.target, entry.previous);
3206
- }
3207
- catch {
3208
- stuck.push(entry.target);
3209
- }
3210
- }
3211
- const reason = error instanceof Error ? error.message : String(error);
3212
- if (stuck.length === 0)
3213
- return { ok: false, message: '目录树变更失败,已回滚:' + reason };
3214
- return { ok: false, message: '目录树变更失败:' + reason + '。回滚无法恢复 ' + stuck.join(', ') + ':可恢复性由当前快照决定:' + (await this.snapshotRecoveryAvailability()) + ' —— 若上面不是「最新快照」,请重新应用这次变更。' };
3215
- }
3216
3153
  const unitId = plan.unitId ?? 'u-' + Date.now().toString(36) + '-' + (nextUnitSeq += 1).toString(36);
3154
+ const unit = new MutationUnit({
3155
+ io: this.io,
3156
+ limits: this.limits,
3157
+ ...(plan.nested === true ? { nested: true } : { lock: this.lockPort() }),
3158
+ journal: unitJournalPort(this.io, dirname(this.root)),
3159
+ snapshots: unitSnapshotPort(this.io, dirname(this.root)),
3160
+ ...(this.transact === undefined ? {} : { transact: this.transact }),
3161
+ now: () => Date.now(),
3162
+ });
3163
+ const applied = await unit.apply({
3164
+ name: primaryName,
3165
+ roots: roots.map(root => ({ name: root.name, protection: root.protection })),
3166
+ ops: landing.map(entry => entry.kind === 'delete'
3167
+ ? { kind: 'delete', target: entry.target, ...(entry.expected === undefined ? {} : { expected: entry.expected }) }
3168
+ : { kind: 'write', target: entry.target, content: entry.content ?? '', ...(entry.expected === undefined ? {} : { expected: entry.expected }) }),
3169
+ rootDirs: Object.fromEntries(roots.map(root => [root.name, root.dir])),
3170
+ origin: plan.origin,
3171
+ auditAction: plan.auditAction,
3172
+ auditSummary: plan.auditSummary,
3173
+ eventAction: plan.eventAction,
3174
+ unitId,
3175
+ });
3176
+ if (!applied.ok) {
3177
+ return { ok: false, message: '目录树变更失败:' + applied.errors.map(error => error.message).join('; ') };
3178
+ }
3217
3179
  const defaultHead = {
3218
3180
  moves: landing
3219
3181
  .filter(entry => basename(entry.target) !== 'SKILL.md')
@@ -3239,11 +3201,12 @@ export class SkillLibrary {
3239
3201
  this.notifyMutation({ action: plan.eventAction, name: skill, skillDir: dir });
3240
3202
  }
3241
3203
  const primaryDir = roots.find(root => root.name === primaryName)?.dir ?? roots[0]?.dir ?? '';
3204
+ const warnings = applied.warnings ?? [];
3242
3205
  return {
3243
3206
  ok: true,
3244
- message: durabilityWarning === ''
3207
+ message: warnings.length === 0
3245
3208
  ? plan.eventAction + ' "' + primaryName + '" succeeded.'
3246
- : plan.eventAction + ' "' + primaryName + '" succeeded (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:' + durabilityWarning + ')',
3209
+ : plan.eventAction + ' "' + primaryName + '" succeeded (警告:' + warnings.join('; ') + ')',
3247
3210
  path: primaryDir,
3248
3211
  };
3249
3212
  }
@@ -0,0 +1,11 @@
1
+ /** Skill-domain surface. Consumers import it from the documented subpath. */
2
+ export * from './skill-lint.ts';
3
+ export * from './skill-health.ts';
4
+ export * from './skill-reads.ts';
5
+ export * from './skill-row-cells.ts';
6
+ export * from './skill-history.ts';
7
+ export * from './skill-store.ts';
8
+ export * from './skill-model.ts';
9
+ export * from './skill-revision.ts';
10
+ export * from './frontmatter.ts';
11
+ //# sourceMappingURL=skills.d.ts.map
@@ -0,0 +1,11 @@
1
+ /** Skill-domain surface. Consumers import it from the documented subpath. */
2
+ export * from "./skill-lint.js";
3
+ export * from "./skill-health.js";
4
+ export * from "./skill-reads.js";
5
+ export * from "./skill-row-cells.js";
6
+ export * from "./skill-history.js";
7
+ export * from "./skill-store.js";
8
+ export * from "./skill-model.js";
9
+ export * from "./skill-revision.js";
10
+ export * from "./frontmatter.js";
11
+ //# sourceMappingURL=skills.js.map
@@ -1,6 +1,6 @@
1
- import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent';
2
- import type { SessionId } from '@deepseek-ai/dsh-session';
3
- import type { SubagentStopReason } from '@deepseek-ai/dsh-subagent';
1
+ import type { Agent, AgentOptions } from '../platform/index.ts';
2
+ import type { SessionId } from '../platform/index.ts';
3
+ import type { SubagentStopReason } from '../platform/index.ts';
4
4
  import type { ObjectJsonSchema } from '../platform/index.ts';
5
5
  export type ChannelCode = 'E-323' | 'E-324';
6
6
  export type ChannelKind = 'reviewer' | 'maintainer';
@@ -89,11 +89,14 @@ export async function acquireTreeWriteLock(options) {
89
89
  async release() {
90
90
  if (released)
91
91
  return;
92
- released = true;
93
92
  await transactIo(options.io, path, (current) => {
94
93
  const existing = parseLock(current);
95
94
  return existing?.token === token && existing.epoch === epoch ? null : current;
96
95
  });
96
+ // Mark released only after the delete committed. Marking first made every retry a
97
+ // silent no-op, so a transient unlink failure left the lock on disk while the
98
+ // caller believed it was released.
99
+ released = true;
97
100
  },
98
101
  };
99
102
  return { ok: true, lock };
@@ -0,0 +1,8 @@
1
+ /** Shared target-claim port: one live unit per target across processes. */
2
+ export interface UnitClaim {
3
+ release(): Promise<void>;
4
+ }
5
+ export interface UnitClaimPort {
6
+ acquire(target: string, runId: string): Promise<UnitClaim>;
7
+ }
8
+ //# sourceMappingURL=unit-claim.d.ts.map
@@ -0,0 +1,3 @@
1
+ /** Shared target-claim port: one live unit per target across processes. */
2
+ export {};
3
+ //# sourceMappingURL=unit-claim.js.map
@@ -1,6 +1,6 @@
1
1
  import type { EvolutionIoLike } from './io.ts';
2
2
  export declare const UNIT_JOURNAL_SCHEMA_VERSION = 1;
3
- export declare const UNIT_JOURNAL_PHASES: readonly ["prepared", "target-pending", "target-written", "source-archiving", "sources-archived", "support-pending", "unit-written", "committed", "failed", "rolled-back"];
3
+ export declare const UNIT_JOURNAL_PHASES: readonly ["prepared", "target-pending", "target-written", "source-archiving", "support-pending", "sources-archived", "unit-written", "committed", "failed", "rolled-back"];
4
4
  export type UnitJournalPhase = typeof UNIT_JOURNAL_PHASES[number];
5
5
  export interface UnitJournalCheckpoint {
6
6
  readonly source: string;
@@ -11,6 +11,8 @@ export interface UnitJournalCheckpoint {
11
11
  export interface UnitJournal {
12
12
  readonly schemaVersion: typeof UNIT_JOURNAL_SCHEMA_VERSION;
13
13
  readonly unitId: string;
14
+ /** Nested journal key; unitId stays the user-visible identity. */
15
+ readonly journalId?: string;
14
16
  readonly runId: string;
15
17
  readonly planDigest: string;
16
18
  readonly target: string;
@@ -7,8 +7,8 @@ export const UNIT_JOURNAL_PHASES = [
7
7
  'target-pending',
8
8
  'target-written',
9
9
  'source-archiving',
10
- 'sources-archived',
11
10
  'support-pending',
11
+ 'sources-archived',
12
12
  'unit-written',
13
13
  'committed',
14
14
  'failed',
@@ -22,15 +22,24 @@ export function unitJournalPhaseRank(phase) {
22
22
  return UNIT_JOURNAL_PHASES.indexOf(phase);
23
23
  }
24
24
  export function assertUnitJournalTransition(from, to) {
25
+ if (from === to)
26
+ return;
27
+ // A committed unit is final: a late failure must never rewrite its journal.
28
+ if (from === 'committed')
29
+ throw new Error('unit-journal-terminal:' + from);
25
30
  if (to === 'failed' || to === 'rolled-back')
26
31
  return;
27
- if (from === 'failed' || from === 'rolled-back' || from === 'committed')
32
+ if (from === 'failed' || from === 'rolled-back')
28
33
  throw new Error('unit-journal-terminal:' + from);
29
34
  if (unitJournalPhaseRank(to) <= unitJournalPhaseRank(from))
30
35
  throw new Error('unit-journal-nonmonotonic:' + from + '->' + to);
31
36
  }
32
37
  export async function writeUnitJournal(io, home, journal, scope = 'merge') {
33
- const path = unitJournalPath(home, journal.unitId, scope);
38
+ const key = journal.journalId ?? journal.unitId;
39
+ const path = unitJournalPath(home, key, scope);
40
+ const existing = await readUnitJournal(io, home, key, scope);
41
+ if (existing !== null)
42
+ assertUnitJournalTransition(existing.phase, journal.phase);
34
43
  const content = JSON.stringify(journal, null, 2) + '\n';
35
44
  if (io.transact !== undefined)
36
45
  await io.transact(path, () => content);
@@ -3,6 +3,7 @@ export declare const UNIT_STORAGE_SCHEMA_VERSION = 1;
3
3
  export interface UnitSnapshot {
4
4
  readonly schemaVersion: typeof UNIT_STORAGE_SCHEMA_VERSION;
5
5
  readonly unitId: string;
6
+ readonly journalId?: string;
6
7
  readonly planDigest: string;
7
8
  readonly runId: string;
8
9
  readonly target: string;
@@ -24,7 +24,7 @@
24
24
  */
25
25
  import { type WriteConfirm, type WriteConfirmMode } from './write-authority.ts';
26
26
  import type { ConfirmContext } from './write-authority.ts';
27
- import { type WriteOrigin } from './index.ts';
27
+ import type { WriteOrigin } from './skill-store.ts';
28
28
  /** The point whose verdict is being taken. */
29
29
  export type WriteGatePoint = 'admission' | 'execution';
30
30
  /** What every gate reads. */
@@ -23,7 +23,9 @@
23
23
  * @module @lmzhen/dsh-evolution-core/write-gates
24
24
  */
25
25
  import { DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS } from "./write-authority.js";
26
- import { SKILL_ACTION_REQUIRED_FIELDS, errorText, isUnreadWrite } from "./index.js";
26
+ import { SKILL_ACTION_REQUIRED_FIELDS } from "./constants.js";
27
+ import { errorText } from "./errors.js";
28
+ import { isUnreadWrite } from "./skill-reads.js";
27
29
  /** The confirm question's stable id — one question per write, so an answer to an earlier prompt
28
30
  * can never be read as the answer to a later one. */
29
31
  const CONFIRM_QUESTION_ID = 'evolution-skill-write';