@lmzhen/dsh-evolution-core 0.39.2 → 0.40.1

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 (42) hide show
  1. package/lib/index.js +3544 -3112
  2. package/lib/platform/index.js +2 -2
  3. package/lib/{platform-Be-_wSVz.js → platform-CFp373_0.js} +3 -1
  4. package/lib/runtime/plugin.js +1 -1
  5. package/lib/types/events.d.ts +1 -1
  6. package/lib/types/evolution-events.d.ts +3 -1
  7. package/lib/types/evolution-events.js +65 -59
  8. package/lib/types/home-fence.d.ts +24 -0
  9. package/lib/types/home-fence.js +62 -0
  10. package/lib/types/home-owner.d.ts +4 -0
  11. package/lib/types/home-owner.js +37 -0
  12. package/lib/types/index.d.ts +4 -0
  13. package/lib/types/index.js +4 -0
  14. package/lib/types/lease-store.d.ts +55 -0
  15. package/lib/types/lease-store.js +116 -0
  16. package/lib/types/memory-store.d.ts +6 -0
  17. package/lib/types/memory-store.js +16 -8
  18. package/lib/types/mutation-authority.d.ts +59 -0
  19. package/lib/types/mutation-authority.js +126 -0
  20. package/lib/types/mutation-storage-adapter.js +7 -3
  21. package/lib/types/mutation-unit.d.ts +13 -0
  22. package/lib/types/mutation-unit.js +7 -2
  23. package/lib/types/mutations.d.ts +3 -1
  24. package/lib/types/mutations.js +40 -34
  25. package/lib/types/platform/index.d.ts +5 -2
  26. package/lib/types/platform/index.js +2 -0
  27. package/lib/types/platform-services.js +1 -0
  28. package/lib/types/proposal-report.d.ts +1 -0
  29. package/lib/types/proposal-report.js +12 -0
  30. package/lib/types/run-registry.d.ts +4 -0
  31. package/lib/types/run-registry.js +10 -3
  32. package/lib/types/skill-history.d.ts +4 -1
  33. package/lib/types/skill-history.js +24 -29
  34. package/lib/types/skill-store.d.ts +11 -3
  35. package/lib/types/skill-store.js +26 -12
  36. package/lib/types/unit-storage.d.ts +2 -0
  37. package/lib/types/unit-transaction.d.ts +6 -1
  38. package/lib/types/unit-transaction.js +20 -6
  39. package/lib/types/usage.d.ts +4 -0
  40. package/lib/types/usage.js +84 -78
  41. package/package.json +2 -2
  42. package/persisted-write-inventory.json +9 -0
@@ -36,12 +36,12 @@ import { type WriteAuthority } from './write-authority.ts';
36
36
  import { transactIo, type EvolutionIoLike } from './io.ts';
37
37
  import { type Probe } from './probe.ts';
38
38
  import type { SkillLimits } from './limits.ts';
39
- import { type MutationResult } from './mutation-unit.ts';
39
+ import { type MutationLockPort, type MutationResult } from './mutation-unit.ts';
40
40
  import { SkillModel } from './skill-model.ts';
41
41
  import { type ExtractPlanDraft } from './extract-plan.ts';
42
42
  import { type MutationRecord } from './mutations.ts';
43
43
  import { type RevisionAnchor, type RevisionFile } from './skill-revision.ts';
44
- import { type UnitHead, type SkillVersion } from './skill-history.ts';
44
+ import { type UnitHead, type HistoryFence, type SkillVersion } from './skill-history.ts';
45
45
  import { type SkillHealthAssessment, type SkillHealthThresholds } from './skill-health.ts';
46
46
  import type { EvolutionSkillMutatedEvent } from './events.ts';
47
47
  export interface SkillSummary {
@@ -349,10 +349,13 @@ export declare class SkillLibrary {
349
349
  /** G1/1.1: default authority; a call may override (origin is per-invocation). */
350
350
  /** G1/1.1/Stage 2: the ONE default every mutator reads. Per-call overrides still win. */
351
351
  private readonly authority;
352
+ /** When supplied by the family MutationAuthority, replaces the per-directory file lock. */
353
+ private readonly mutationLock;
354
+ private readonly fence;
352
355
  /** skill-history.ts: the content history is best-effort, so a failure must not be SILENT —
353
356
  * but it is a deployment condition, not a per-write event, so it warns once per instance. */
354
357
  private historyWarned;
355
- constructor(root?: string, io?: EvolutionIoLike, limits?: SkillLimits, onMutation?: (event: EvolutionSkillMutatedEvent) => void, transact?: typeof transactIo, threatExemptLabels?: readonly string[], authority?: WriteAuthority);
358
+ constructor(root?: string, io?: EvolutionIoLike, limits?: SkillLimits, onMutation?: (event: EvolutionSkillMutatedEvent) => void, transact?: typeof transactIo, threatExemptLabels?: readonly string[], authority?: WriteAuthority, mutationLock?: MutationLockPort, fence?: HistoryFence);
356
359
  /**
357
360
  * Transitional root lock for mutators that still own their write path. The
358
361
  * extract/restructure path takes the same lock through MutationUnit, so those
@@ -360,6 +363,7 @@ export declare class SkillLibrary {
360
363
  */
361
364
  private unitHeadForOps;
362
365
  private withMutationLock;
366
+ private lockPort;
363
367
  private recovery;
364
368
  /** Run the boot recovery once per library instance, before the first write. */
365
369
  private ensureRecovered;
@@ -813,6 +817,7 @@ export declare class SkillLibrary {
813
817
  * `emit`, so core states the contract without importing the platform type. */
814
818
  export interface SkillMutationSink {
815
819
  emit: (type: 'evolution/skill-mutated', event: EvolutionSkillMutatedEvent) => unknown;
820
+ get?(name: string): unknown;
816
821
  }
817
822
  /** V41 P2-26 (0.3.75): the ONE SkillLibrary construction point.
818
823
  *
@@ -835,6 +840,9 @@ export interface NewSkillLibraryOptions {
835
840
  threatExemptLabels?: readonly string[] | undefined;
836
841
  /** G1/1.1: WHO writes through this library. Required: no call site can omit it. */
837
842
  authority: WriteAuthority;
843
+ /** Optional family authority lock; absent falls back to per-directory file lock. */
844
+ mutationLock?: MutationLockPort;
845
+ fence?: HistoryFence;
838
846
  }
839
847
  export declare function newSkillLibrary(options: NewSkillLibraryOptions): SkillLibrary;
840
848
  export { DEFAULT_SKILL_LIMITS, DEFAULT_CITATION_POLICY, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_SUPPORT_FILE_CHAR_POLICY, POLICY_STAGE_DEFAULTS, policyStageLimits, } from './limits.ts';
@@ -50,6 +50,7 @@ import { makeSerialQueue } from "./serial.js";
50
50
  import { supportRefs } from "./support-refs.js";
51
51
  import { selectSections } from "./section-selection.js";
52
52
  import { MutationUnit, fileMutationLock } from "./mutation-unit.js";
53
+ import { mutationLockFrom } from "./mutation-authority.js";
53
54
  import { SkillModel } from "./skill-model.js";
54
55
  import { pruneTreeChangeUnits, unitJournalPort, unitSnapshotPort } from "./mutation-storage-adapter.js";
55
56
  import { projectExtractBodies } from "./extract-plan.js";
@@ -478,16 +479,21 @@ export class SkillLibrary {
478
479
  /** G1/1.1: default authority; a call may override (origin is per-invocation). */
479
480
  /** G1/1.1/Stage 2: the ONE default every mutator reads. Per-call overrides still win. */
480
481
  authority;
482
+ /** When supplied by the family MutationAuthority, replaces the per-directory file lock. */
483
+ mutationLock;
484
+ fence;
481
485
  /** skill-history.ts: the content history is best-effort, so a failure must not be SILENT —
482
486
  * but it is a deployment condition, not a per-write event, so it warns once per instance. */
483
487
  historyWarned = false;
484
- constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY) {
488
+ constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
485
489
  this.root = root;
486
490
  this.io = io;
487
491
  this.limits = limits;
488
492
  this.onMutation = onMutation;
489
493
  this.threatExemptLabels = threatExemptLabels ?? [];
490
494
  this.authority = authority;
495
+ this.mutationLock = mutationLock;
496
+ this.fence = fence;
491
497
  // V4-20: bind the IO backend's own transact by default. Explicit injection
492
498
  // stays first; a backend WITHOUT transact keeps the old plain read→write
493
499
  // (the in-process serial chain is the second layer). The wrapper adapts the
@@ -541,7 +547,7 @@ export class SkillLibrary {
541
547
  async withMutationLock(task) {
542
548
  let lease;
543
549
  try {
544
- lease = await fileMutationLock(this.io, this.root).acquire();
550
+ lease = await this.lockPort().acquire();
545
551
  }
546
552
  catch (error) {
547
553
  const message = error instanceof Error ? error.message : String(error);
@@ -563,6 +569,14 @@ export class SkillLibrary {
563
569
  }
564
570
  }
565
571
  }
572
+ lockPort() {
573
+ if (this.mutationLock !== undefined)
574
+ return this.mutationLock;
575
+ // Fail loud outside tests: production skill writes must use the family authority fence.
576
+ if (process.env['VITEST'] === 'true' || process.env['NODE_ENV'] === 'test')
577
+ return fileMutationLock(this.io, this.root);
578
+ throw new Error('skill-store: no authority mutationLock was supplied; refusing an unfenced production write');
579
+ }
566
580
  recovery;
567
581
  /** Run the boot recovery once per library instance, before the first write. */
568
582
  async ensureRecovered() {
@@ -582,7 +596,7 @@ export class SkillLibrary {
582
596
  io: this.io,
583
597
  limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
584
598
  serial: this.serial,
585
- lock: fileMutationLock(this.io, this.root),
599
+ lock: this.lockPort(),
586
600
  journal: unitJournalPort(this.io, home),
587
601
  snapshots: unitSnapshotPort(this.io, home),
588
602
  });
@@ -1183,7 +1197,7 @@ export class SkillLibrary {
1183
1197
  supportFiles,
1184
1198
  restructureRounds: 0,
1185
1199
  source,
1186
- });
1200
+ }, undefined, this.fence);
1187
1201
  }
1188
1202
  catch (error) {
1189
1203
  console.warn('skill-store: hard-cap event not recorded for "' + name + '": ' + (error instanceof Error ? error.message : String(error)));
@@ -1220,7 +1234,7 @@ export class SkillLibrary {
1220
1234
  ...unitId === undefined ? {} : { unitId },
1221
1235
  ...unitHead === undefined ? {} : { unitHead },
1222
1236
  };
1223
- versions = await recordVersions(this.root, this.io, input, keep);
1237
+ versions = await recordVersions(this.root, this.io, input, keep, this.fence);
1224
1238
  }
1225
1239
  catch (error) {
1226
1240
  if (!this.historyWarned) {
@@ -1265,7 +1279,7 @@ export class SkillLibrary {
1265
1279
  summary: summary + healthNote + danglingNote,
1266
1280
  at,
1267
1281
  ...origin === undefined ? {} : { origin },
1268
- });
1282
+ }, undefined, this.fence);
1269
1283
  }
1270
1284
  catch {
1271
1285
  // Auditing is best-effort; a transient disk failure must not surface
@@ -1693,7 +1707,7 @@ export class SkillLibrary {
1693
1707
  const unit = new MutationUnit({
1694
1708
  io: this.io,
1695
1709
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
1696
- lock: fileMutationLock(this.io, this.root),
1710
+ lock: this.lockPort(),
1697
1711
  journal: unitJournalPort(this.io, dirname(this.root)),
1698
1712
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1699
1713
  ...(this.transact === undefined ? {} : { transact: this.transact }),
@@ -1871,7 +1885,7 @@ export class SkillLibrary {
1871
1885
  const unit = new MutationUnit({
1872
1886
  io: this.io,
1873
1887
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
1874
- lock: fileMutationLock(this.io, this.root),
1888
+ lock: this.lockPort(),
1875
1889
  journal: unitJournalPort(this.io, dirname(this.root)),
1876
1890
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1877
1891
  ...(this.transact === undefined ? {} : { transact: this.transact }),
@@ -2926,7 +2940,7 @@ export class SkillLibrary {
2926
2940
  io: this.io,
2927
2941
  limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
2928
2942
  serial: this.serial,
2929
- lock: fileMutationLock(this.io, this.root),
2943
+ lock: this.lockPort(),
2930
2944
  journal: unitJournalPort(this.io, home),
2931
2945
  snapshots: unitSnapshotPort(this.io, home),
2932
2946
  hooks,
@@ -3059,7 +3073,7 @@ export class SkillLibrary {
3059
3073
  io: this.io,
3060
3074
  limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
3061
3075
  serial: this.serial,
3062
- lock: fileMutationLock(this.io, this.root),
3076
+ lock: this.lockPort(),
3063
3077
  journal: unitJournalPort(this.io, home),
3064
3078
  snapshots: unitSnapshotPort(this.io, home),
3065
3079
  hooks,
@@ -3440,7 +3454,7 @@ export class SkillLibrary {
3440
3454
  io: this.io,
3441
3455
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
3442
3456
  serial: this.serial,
3443
- lock: fileMutationLock(this.io, this.root),
3457
+ lock: this.lockPort(),
3444
3458
  journal: unitJournalPort(this.io, dirname(this.root)),
3445
3459
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
3446
3460
  ...(this.transact === undefined ? {} : { transact: this.transact }),
@@ -4187,7 +4201,7 @@ export function newSkillLibrary(options) {
4187
4201
  return new SkillLibrary(resolveSkillsRoot(config ?? {}), io, limits, ctx ? (event) => { ctx.emit('evolution/skill-mutated', event); } : undefined, transact,
4188
4202
  // Copied once, here: the library holds the array for its lifetime and must
4189
4203
  // not alias a config object the caller still owns.
4190
- [...(threatExemptLabels ?? [])], authority);
4204
+ [...(threatExemptLabels ?? [])], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.('evolutionMutationAuthority')?.homeFence);
4191
4205
  }
4192
4206
  export { DEFAULT_SKILL_LIMITS, DEFAULT_CITATION_POLICY, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_SUPPORT_FILE_CHAR_POLICY, POLICY_STAGE_DEFAULTS, policyStageLimits, } from "./limits.js";
4193
4207
  export { authoringFeedback, ensureSkillFrontmatter, frontmatterBlock, frontmatterCatalogInvalid, normalizeFrontmatter, parseFrontmatter, relatedSkillNames, validateFrontmatter, yamlPlainScalarNeedsQuotes } from "./frontmatter.js";
@@ -22,6 +22,8 @@ export interface UnitSnapshot {
22
22
  body: string;
23
23
  }[];
24
24
  readonly origin: string;
25
+ /** Optional lease identity for tree-change snapshots; legacy units omit it. */
26
+ readonly leaseId?: string;
25
27
  readonly summary: string;
26
28
  /** Tree-change units reuse this store; merge snapshots leave these absent. */
27
29
  readonly kind?: 'merge' | 'tree-change';
@@ -1,4 +1,5 @@
1
1
  import type { EvolutionIoLike } from "./io.ts";
2
+ import type { HomeFence } from './home-fence.ts';
2
3
  import { type UnitEvidenceRecord } from "./unit-storage.ts";
3
4
  import { type UnitJournalPhase } from "./unit-journal.ts";
4
5
  export interface UnitSupportFile {
@@ -78,8 +79,12 @@ export interface UnitTransactionOptions {
78
79
  readonly onPhase?: (phase: UnitJournalPhase) => void | Promise<void>;
79
80
  /** Gate instrumentation: tree fence then target claim. */
80
81
  readonly onLock?: (lock: "tree" | "claim") => void;
82
+ /** One home fence owned by authority; when set, UnitTransactions must not acquire tree-lock itself. */
83
+ readonly fence?: HomeFence;
84
+ /** Optional run liveness gate: false means the run is terminal and must not commit. */
85
+ readonly isActive?: (runId: string) => boolean | Promise<boolean>;
81
86
  }
82
- export type UnitErrorCode = "unit-plan-missing" | "unit-conflict" | "unit-committed" | "unit-prepare-failed" | "unit-commit-failed" | "unit-claim-failed" | "unit-fence-failed" | "unit-rollback-blocked" | "target-changed" | "source-changed" | "support-changed";
87
+ export type UnitErrorCode = "unit-plan-missing" | "unit-conflict" | "unit-committed" | "unit-prepare-failed" | "unit-commit-failed" | "unit-claim-failed" | "unit-fence-failed" | "unit-run-inactive" | "unit-rollback-blocked" | "target-changed" | "source-changed" | "support-changed";
83
88
  export interface UnitFailure {
84
89
  readonly ok: false;
85
90
  readonly code: UnitErrorCode;
@@ -136,6 +136,9 @@ export class UnitTransactions {
136
136
  };
137
137
  if (options?.signal?.aborted === true)
138
138
  return { ok: false, code: "unit-commit-failed", message: "cancelled before commit" };
139
+ if (this.options.isActive !== undefined && !(await this.options.isActive(stored.plan.runId))) {
140
+ return { ok: false, code: "unit-run-inactive", message: "run is no longer active; refusing to commit" };
141
+ }
139
142
  const journalBase = {
140
143
  schemaVersion: 1,
141
144
  unitId: prepared.unitId,
@@ -148,6 +151,7 @@ export class UnitTransactions {
148
151
  updatedAt: this.now(),
149
152
  };
150
153
  let lock;
154
+ let fenceLease;
151
155
  let claim;
152
156
  const checkpoints = [];
153
157
  const writePhase = async (phase, checkpointsNext = checkpoints) => {
@@ -161,13 +165,20 @@ export class UnitTransactions {
161
165
  await this.options.onPhase?.(phase);
162
166
  };
163
167
  try {
164
- const acquired = await acquireTreeWriteLock({ io: this.options.io, home: this.options.home, waitMs: this.options.waitMs ?? 5000 });
165
- if (!acquired.ok)
166
- return { ok: false, code: "unit-fence-failed", message: acquired.message ?? acquired.reason };
167
- lock = acquired.lock;
168
+ if (this.options.fence !== undefined) {
169
+ fenceLease = await this.options.fence.acquire();
170
+ lock = fenceLease.lock;
171
+ this.options.onLock?.("tree");
172
+ }
173
+ else {
174
+ const acquired = await acquireTreeWriteLock({ io: this.options.io, home: this.options.home, waitMs: this.options.waitMs ?? 5000 });
175
+ if (!acquired.ok)
176
+ return { ok: false, code: "unit-fence-failed", message: acquired.message ?? acquired.reason };
177
+ lock = acquired.lock;
178
+ this.options.onLock?.("tree");
179
+ }
168
180
  if (!(await lock.assertHeld()))
169
181
  return { ok: false, code: "unit-fence-failed", message: "tree fence lost" };
170
- this.options.onLock?.("tree");
171
182
  claim = await this.options.claim.acquire(stored.plan.target, stored.plan.runId);
172
183
  this.options.onLock?.("claim");
173
184
  await writeUnitJournal(this.options.io, this.options.home, { ...journalBase, phase: "target-pending" });
@@ -260,7 +271,10 @@ export class UnitTransactions {
260
271
  }
261
272
  finally {
262
273
  await claim?.release();
263
- await lock?.release();
274
+ if (fenceLease !== undefined)
275
+ await fenceLease.release();
276
+ else
277
+ await lock?.release();
264
278
  }
265
279
  }
266
280
  async verify(ref) {
@@ -60,6 +60,10 @@ export declare function loadUsage(root: string, io?: EvolutionIoLike): Promise<U
60
60
  * single-process serialize chain as the second layer.
61
61
  */
62
62
  export interface UsageMutateOptions {
63
+ /** Optional family fence; all usage RMW runs inside it. */
64
+ fence?: {
65
+ run<T>(body: () => Promise<T>): Promise<T>;
66
+ } | undefined;
63
67
  /** P2-9 (v19): called when malformed entries had to be quarantined before the
64
68
  * task could run. The guard preserves bytes AND keeps the facility working;
65
69
  * this callback is how that stays observable. */
@@ -128,92 +128,98 @@ export async function loadUsage(root, io = nodeEvolutionIo()) {
128
128
  return parseUsage(await io.readText(usageFile(root)));
129
129
  }
130
130
  export async function mutateUsage(root, io, task, options = {}) {
131
- await transactIo(io, usageFile(root), async (current) => {
132
- // P3 (v3 audit): a malformed sidecar is never overwritten by the RMW —
133
- // JSON.parse swallow→empty then persist would destroy recoverable telemetry.
134
- // P3 (v17): the same preserve applies to "valid JSON, wrong top-level
135
- // shape" (array/scalar) — parseUsage folds those to an empty map, and
136
- // persisting that would DESTROY the original bytes (mutations.ts and the
137
- // suppression sidecar both keep array compat; usage is the odd one out).
138
- // v21 (L-1): the WHOLE-FILE branches (unparsable JSON / array / scalar)
139
- // used to freeze every later RMW as a SILENT no-op — telemetry counts,
140
- // feedback and the curator's lifecycle fold all stopped landing with no
141
- // throw and no warn (the exact defect shape the v19 P2-9 note fixed for
142
- // the malformed-ENTRIES case). Same healing posture as state-json's E-9:
143
- // quarantine the original bytes, warn via onQuarantine, continue with an
144
- // empty map. A FAILED quarantine copy keeps the freeze but says so — the
145
- // bytes on disk stay the only recovery source, so overwriting them is
146
- // refused (v21 L-2, the P2-17 discipline state-json already follows).
147
- let shapePreserved = false;
148
- let recovered = null;
149
- const quarantineCopy = async () => {
150
- const corruptPath = `${usageFile(root)}.corrupt`;
151
- return io.writeText(corruptPath, current).then(() => true, () => false);
152
- };
153
- if (current !== null) {
154
- let parsed = null;
155
- try {
156
- const probe = JSON.parse(current);
157
- if (isRecord(probe))
158
- parsed = probe;
159
- }
160
- catch {
161
- parsed = null;
162
- }
163
- if (parsed === null) {
164
- // Whole-file corruption (unparsable JSON) or wrong top-level shape
165
- // (array/scalar): quarantine + warn + restart empty (parseUsage folds
166
- // the preserved bytes to an empty map below).
167
- const copied = await quarantineCopy();
168
- if (!copied) {
169
- options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable (telemetry is frozen until the file is recovered manually)`);
170
- return current;
131
+ const run = async () => {
132
+ await transactIo(io, usageFile(root), async (current) => {
133
+ // P3 (v3 audit): a malformed sidecar is never overwritten by the RMW —
134
+ // JSON.parse swallow→empty then persist would destroy recoverable telemetry.
135
+ // P3 (v17): the same preserve applies to "valid JSON, wrong top-level
136
+ // shape" (array/scalar) — parseUsage folds those to an empty map, and
137
+ // persisting that would DESTROY the original bytes (mutations.ts and the
138
+ // suppression sidecar both keep array compat; usage is the odd one out).
139
+ // v21 (L-1): the WHOLE-FILE branches (unparsable JSON / array / scalar)
140
+ // used to freeze every later RMW as a SILENT no-op — telemetry counts,
141
+ // feedback and the curator's lifecycle fold all stopped landing with no
142
+ // throw and no warn (the exact defect shape the v19 P2-9 note fixed for
143
+ // the malformed-ENTRIES case). Same healing posture as state-json's E-9:
144
+ // quarantine the original bytes, warn via onQuarantine, continue with an
145
+ // empty map. A FAILED quarantine copy keeps the freeze but says so — the
146
+ // bytes on disk stay the only recovery source, so overwriting them is
147
+ // refused (v21 L-2, the P2-17 discipline state-json already follows).
148
+ let shapePreserved = false;
149
+ let recovered = null;
150
+ const quarantineCopy = async () => {
151
+ const corruptPath = `${usageFile(root)}.corrupt`;
152
+ return io.writeText(corruptPath, current).then(() => true, () => false);
153
+ };
154
+ if (current !== null) {
155
+ let parsed = null;
156
+ try {
157
+ const probe = JSON.parse(current);
158
+ if (isRecord(probe))
159
+ parsed = probe;
171
160
  }
172
- options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${usageFile(root)}.corrupt and the sidecar restarts empty`);
173
- }
174
- else {
175
- const record = parsed;
176
- const isMalformed = (value) => value === null || typeof value !== 'object' || Array.isArray(value);
177
- // A2-11 (v18): a newer on-disk version is never downgraded by this
178
- // writer (a skill literally named `version` holds an object, not a
179
- // number, so this cannot false-positive on a usage map). v21 (L-1):
180
- // the freeze now says so — the old silence was indistinguishable from
181
- // a dead pipeline.
182
- if (typeof record.version === 'number' && record.version > 1) {
183
- // S3-5 (J-6): the SAME refusal its siblings report. Handing the message
184
- // to `onQuarantine` alone made the freeze silent whenever the caller had
185
- // no callback — the one artifact of the four whose version refusal could
186
- // go unreported (pinned by tests/version-policy-uniformity.spec.ts).
187
- const message = `usage sidecar ${usageFile(root)} carries schema version ${String(record.version)} (> this runtime) — writes stay frozen and the bytes preserved until the runtime is upgraded`;
188
- if (options.onQuarantine !== undefined)
189
- options.onQuarantine(message);
190
- else
191
- console.warn(message);
192
- shapePreserved = true;
161
+ catch {
162
+ parsed = null;
193
163
  }
194
- else if (Object.values(record).some(isMalformed)) {
195
- // P2-9 (v19): keep the original bytes in a quarantine copy, warn,
196
- // and continue with the good entries so the facility heals itself.
197
- // v21 (L-2): when the rescue copy ITSELF fails, refuse the write
198
- // instead of destroying the only recoverable bytes — and never
199
- // claim a copy exists when it does not.
200
- const bad = Object.keys(record).filter(key => isMalformed(record[key]));
164
+ if (parsed === null) {
165
+ // Whole-file corruption (unparsable JSON) or wrong top-level shape
166
+ // (array/scalar): quarantine + warn + restart empty (parseUsage folds
167
+ // the preserved bytes to an empty map below).
201
168
  const copied = await quarantineCopy();
202
169
  if (!copied) {
203
- options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? 'y' : 'ies'} (${bad.slice(0, 5).join(', ')}); the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
170
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable (telemetry is frozen until the file is recovered manually)`);
204
171
  return current;
205
172
  }
206
- recovered = JSON.stringify(Object.fromEntries(Object.entries(record).filter(([, value]) => !isMalformed(value))));
207
- options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? 'y' : 'ies'} (${bad.slice(0, 5).join(', ')}); the original bytes were copied to ${usageFile(root)}.corrupt and the remaining entries continue to be served`);
173
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${usageFile(root)}.corrupt and the sidecar restarts empty`);
174
+ }
175
+ else {
176
+ const record = parsed;
177
+ const isMalformed = (value) => value === null || typeof value !== 'object' || Array.isArray(value);
178
+ // A2-11 (v18): a newer on-disk version is never downgraded by this
179
+ // writer (a skill literally named `version` holds an object, not a
180
+ // number, so this cannot false-positive on a usage map). v21 (L-1):
181
+ // the freeze now says so — the old silence was indistinguishable from
182
+ // a dead pipeline.
183
+ if (typeof record.version === 'number' && record.version > 1) {
184
+ // S3-5 (J-6): the SAME refusal its siblings report. Handing the message
185
+ // to `onQuarantine` alone made the freeze silent whenever the caller had
186
+ // no callback — the one artifact of the four whose version refusal could
187
+ // go unreported (pinned by tests/version-policy-uniformity.spec.ts).
188
+ const message = `usage sidecar ${usageFile(root)} carries schema version ${String(record.version)} (> this runtime) — writes stay frozen and the bytes preserved until the runtime is upgraded`;
189
+ if (options.onQuarantine !== undefined)
190
+ options.onQuarantine(message);
191
+ else
192
+ console.warn(message);
193
+ shapePreserved = true;
194
+ }
195
+ else if (Object.values(record).some(isMalformed)) {
196
+ // P2-9 (v19): keep the original bytes in a quarantine copy, warn,
197
+ // and continue with the good entries so the facility heals itself.
198
+ // v21 (L-2): when the rescue copy ITSELF fails, refuse the write
199
+ // instead of destroying the only recoverable bytes — and never
200
+ // claim a copy exists when it does not.
201
+ const bad = Object.keys(record).filter(key => isMalformed(record[key]));
202
+ const copied = await quarantineCopy();
203
+ if (!copied) {
204
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? 'y' : 'ies'} (${bad.slice(0, 5).join(', ')}); the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
205
+ return current;
206
+ }
207
+ recovered = JSON.stringify(Object.fromEntries(Object.entries(record).filter(([, value]) => !isMalformed(value))));
208
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? 'y' : 'ies'} (${bad.slice(0, 5).join(', ')}); the original bytes were copied to ${usageFile(root)}.corrupt and the remaining entries continue to be served`);
209
+ }
208
210
  }
209
211
  }
210
- }
211
- if (shapePreserved)
212
- return current;
213
- const map = parseUsage(recovered ?? current);
214
- await task(map);
215
- return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
216
- });
212
+ if (shapePreserved)
213
+ return current;
214
+ const map = parseUsage(recovered ?? current);
215
+ await task(map);
216
+ return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
217
+ });
218
+ };
219
+ if (options.fence !== undefined)
220
+ await options.fence.run(run);
221
+ else
222
+ await run();
217
223
  }
218
224
  /** Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
219
225
  * lifecycle state, archive stamp, the six-factor quality pair, and the
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-core",
3
3
  "description": "Shared stores, prompts, signals and lifecycle logic for the dsh-evolution plugin family (community build)",
4
- "version": "0.39.2",
4
+ "version": "0.40.1",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -57,7 +57,7 @@
57
57
  "yaml": "^2.4.2",
58
58
  "zod": "^4.4.3",
59
59
  "js-yaml": "^4.1.0",
60
- "@lmzhen/dsh-evolution-contract": "^0.39.2"
60
+ "@lmzhen/dsh-evolution-contract": "^0.40.1"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "@deepseek-ai/cordis": "^4.0.5",
@@ -127,6 +127,15 @@
127
127
  "state": [],
128
128
  "note": "The skill tree itself. G1: ordinary byte writers take the root mutation lock (fileMutationLock) and still run their per-file read-modify-write through `transact`; the root lock is what keeps extract/restructure/update/patch/create from interleaving. Destructive movers refuse only when a support directory cannot be listed (fail-closed)."
129
129
  },
130
+ {
131
+ "id": "activity-log-fenced",
132
+ "path": "<evolutionHome>/activity.json",
133
+ "writer": "evolution-activity/src/index.ts",
134
+ "serializedBy": "transact",
135
+ "marker": "transactIo(io, path, task)",
136
+ "state": [],
137
+ "note": "The same activity sidecar through the authority-fence wrapper; the helper is the one transactIo call site."
138
+ },
130
139
  {
131
140
  "id": "activity-log",
132
141
  "path": "<evolutionHome>/activity.json",