@lmzhen/dsh-evolution-core 0.47.0 → 0.48.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 (58) hide show
  1. package/lib/authority-plugin.js +1 -1
  2. package/lib/index.js +27 -114
  3. package/lib/{io-BCBSr6Ot.js → io-GxghO3Ip.js} +30 -8
  4. package/lib/io-node.js +1 -1
  5. package/lib/io-registry.js +1 -20
  6. package/lib/{mutation-authority-CM6wRgyK.js → mutation-authority-l57R626O.js} +14 -2
  7. package/lib/{mutations-DihgpfgG.js → mutations-DQXddSJd.js} +1 -1
  8. package/lib/{numeric-DLeLvvGb.js → numeric-D8js3sqC.js} +1 -5
  9. package/lib/platform/index.js +1 -1
  10. package/lib/{platform-CFA12Jam.js → platform-Cc9cNt5j.js} +4 -28
  11. package/lib/policy.js +1 -1
  12. package/lib/runtime/plugin.js +21 -43
  13. package/lib/{session-projection-BhlDXqws.js → session-projection-DSXnUNZG.js} +1 -19
  14. package/lib/{skill-health-BzkUQDi7.js → skill-health-DP8z9TPf.js} +3 -3
  15. package/lib/{skill-history-RWt1-kbZ.js → skill-history-CxrDE3Rb.js} +43 -51
  16. package/lib/skills.js +165 -183
  17. package/lib/types/authority.d.ts +2 -0
  18. package/lib/types/authority.js +5 -0
  19. package/lib/types/constants.d.ts +0 -4
  20. package/lib/types/constants.js +0 -4
  21. package/lib/types/contract.d.ts +0 -5
  22. package/lib/types/health-baseline.d.ts +0 -13
  23. package/lib/types/health-baseline.js +0 -20
  24. package/lib/types/home-fence.d.ts +2 -0
  25. package/lib/types/home-fence.js +11 -1
  26. package/lib/types/io-registry.d.ts +0 -16
  27. package/lib/types/io-registry.js +0 -24
  28. package/lib/types/io.d.ts +6 -1
  29. package/lib/types/io.js +35 -9
  30. package/lib/types/memory-store.js +13 -5
  31. package/lib/types/mutation-authority.js +5 -0
  32. package/lib/types/mutation-unit.d.ts +1 -1
  33. package/lib/types/mutation-unit.js +9 -27
  34. package/lib/types/params.d.ts +11 -29
  35. package/lib/types/params.js +13 -60
  36. package/lib/types/platform/llm.d.ts +2 -3
  37. package/lib/types/platform/llm.js +3 -10
  38. package/lib/types/platform/projections.d.ts +4 -5
  39. package/lib/types/platform/projections.js +4 -18
  40. package/lib/types/runtime/llm.js +2 -2
  41. package/lib/types/runtime/platform.d.ts +7 -11
  42. package/lib/types/runtime/platform.js +13 -19
  43. package/lib/types/runtime/plugin.d.ts +1 -1
  44. package/lib/types/runtime/plugin.js +6 -4
  45. package/lib/types/runtime/projections.js +1 -2
  46. package/lib/types/skill-health.d.ts +29 -1
  47. package/lib/types/skill-store.d.ts +6 -0
  48. package/lib/types/skill-store.js +130 -142
  49. package/lib/types/tool-dispatch.d.ts +1 -16
  50. package/lib/types/tool-dispatch.js +0 -18
  51. package/lib/types/unit-journal.js +19 -12
  52. package/lib/types/write-inventory.d.ts +0 -4
  53. package/lib/types/write-inventory.js +0 -9
  54. package/lib/types/write-kernel.d.ts +3 -4
  55. package/lib/types/write-kernel.js +13 -25
  56. package/lib/write.js +2 -2
  57. package/package.json +1 -1
  58. package/persisted-write-inventory.json +31 -13
@@ -61,6 +61,8 @@ export declare class HomeAuthority {
61
61
  get releaseFailure(): AuthorityReleaseFailure | undefined;
62
62
  /** True while the current call context (or this instance) holds `scope`. */
63
63
  assertHeld(scope: LockScope): boolean;
64
+ /** True only when THIS async call context already holds `scope` (re-entrant nesting). */
65
+ holdsInContext(scope: LockScope): boolean;
64
66
  /** True while this instance holds the home lock for any scope. */
65
67
  get holding(): boolean;
66
68
  /**
@@ -93,6 +93,11 @@ export class HomeAuthority {
93
93
  return context.scopes.has(scope);
94
94
  return (this.held.get(scope) ?? 0) > 0;
95
95
  }
96
+ /** True only when THIS async call context already holds `scope` (re-entrant nesting). */
97
+ holdsInContext(scope) {
98
+ const context = CONTEXT.getStore();
99
+ return context?.owner === this && context.scopes.has(scope);
100
+ }
96
101
  /** True while this instance holds the home lock for any scope. */
97
102
  get holding() {
98
103
  return this.held.size > 0;
@@ -75,7 +75,6 @@ export declare const UPSTREAM_LIMIT_CHARS_PER_TOKEN = 2.75;
75
75
  * tokenization is needed"), matching upstream's ESTIMATE-side heuristic — "~4
76
76
  * chars/token is the usual English heuristic" (\`agent/prompt_builder.py:1179\`).
77
77
  * Estimates use this; limits use the constant above. */
78
- export declare const PLATFORM_ESTIMATE_CHARS_PER_TOKEN = 4;
79
78
  export declare const MAX_SKILL_FILE_BYTES = 1048576;
80
79
  export declare const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
81
80
  export declare const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
@@ -112,8 +111,6 @@ export declare const DEFAULT_SKILL_CONTENT_CHARS = 100000;
112
111
  /** P3-19 (v14): defaults that were written twice (schema `.default()` AND the
113
112
  * clamp fallback literal) now have one home per value. */
114
113
  export declare const DEFAULT_REVIEW_TIMEOUT_MS = 120000;
115
- export declare const DEFAULT_REVIEW_CONTEXT_MESSAGES = 60;
116
- export declare const DEFAULT_REVIEW_MESSAGE_CHARS = 2000;
117
114
  export declare const DEFAULT_CURATOR_BOOT_GRACE_SECONDS = 10;
118
115
  export declare const DEFAULT_CURATOR_REVIEW_MAX_TOKENS = 2048;
119
116
  /** Threat-scan WINDOW SIZE (not a total cap — E-12: the whole text is scanned in
@@ -147,7 +144,6 @@ export declare const AUTHORING_DESCRIPTION_BAR = 60;
147
144
  * this default only governs compositions that do not override it. It is NOT a refusal threshold:
148
145
  * the only refusal is `MAX_DESCRIPTION_LENGTH` / the row's `maxDescriptionLength`, and the catalog
149
146
  * cut is a view, not a validation. See tool-skill-manage/README.md for the three-number table. */
150
- export declare const PLATFORM_CATALOG_DESCRIPTION_DEFAULT = 500;
151
147
  /** The split hint both size refusals share (0.5.0 V1). The same sentence used to
152
148
  * be copied into validateFrontmatter AND the patch path, and neither copy named
153
149
  * where the content should go — the upstream cap message names the destination
@@ -91,7 +91,6 @@ export const UPSTREAM_LIMIT_CHARS_PER_TOKEN = 2.75;
91
91
  * tokenization is needed"), matching upstream's ESTIMATE-side heuristic — "~4
92
92
  * chars/token is the usual English heuristic" (\`agent/prompt_builder.py:1179\`).
93
93
  * Estimates use this; limits use the constant above. */
94
- export const PLATFORM_ESTIMATE_CHARS_PER_TOKEN = 4;
95
94
  export const MAX_SKILL_FILE_BYTES = 1_048_576;
96
95
  // ── Cross-package shared tunable defaults ────────────────────────────────────
97
96
  // Fallback defaults when no config override is set. Single-sourced here;
@@ -131,8 +130,6 @@ export const DEFAULT_SKILL_CONTENT_CHARS = MAX_SKILL_CONTENT_CHARS;
131
130
  /** P3-19 (v14): defaults that were written twice (schema `.default()` AND the
132
131
  * clamp fallback literal) now have one home per value. */
133
132
  export const DEFAULT_REVIEW_TIMEOUT_MS = 120_000;
134
- export const DEFAULT_REVIEW_CONTEXT_MESSAGES = 60;
135
- export const DEFAULT_REVIEW_MESSAGE_CHARS = 2_000;
136
133
  export const DEFAULT_CURATOR_BOOT_GRACE_SECONDS = 10;
137
134
  export const DEFAULT_CURATOR_REVIEW_MAX_TOKENS = 2_048;
138
135
  /** Threat-scan WINDOW SIZE (not a total cap — E-12: the whole text is scanned in
@@ -166,7 +163,6 @@ export const AUTHORING_DESCRIPTION_BAR = 60;
166
163
  * this default only governs compositions that do not override it. It is NOT a refusal threshold:
167
164
  * the only refusal is `MAX_DESCRIPTION_LENGTH` / the row's `maxDescriptionLength`, and the catalog
168
165
  * cut is a view, not a validation. See tool-skill-manage/README.md for the three-number table. */
169
- export const PLATFORM_CATALOG_DESCRIPTION_DEFAULT = 500;
170
166
  /** The split hint both size refusals share (0.5.0 V1). The same sentence used to
171
167
  * be copied into validateFrontmatter AND the patch path, and neither copy named
172
168
  * where the content should go — the upstream cap message names the destination
@@ -21,11 +21,6 @@ export interface EvolutionEvent<TPayload = unknown> {
21
21
  readonly version: 1;
22
22
  readonly payload: TPayload;
23
23
  }
24
- /** A lifecycle service implemented by a capability package. */
25
- export interface EvolutionLifecycleService {
26
- /** Stable service name used in diagnostics. */
27
- readonly name: string;
28
- }
29
24
  /** Legal kind of one pending write. The runtime source stays in state-storage. */
30
25
  export type PendingKind = 'memory' | 'skill' | 'capability';
31
26
  /** Legal status of one pending write. */
@@ -20,18 +20,5 @@ export interface HealthBaseline {
20
20
  };
21
21
  values: Record<string, RuleAdmission>;
22
22
  }
23
- export interface AdmissionThresholds {
24
- /** A user-library hit rate below this is too rare to be worth a rule. */
25
- minUserHitRate: number;
26
- /** …and above this it is furniture (every skill trips it, so it carries no signal). */
27
- maxUserHitRate: number;
28
- }
29
- export declare const DEFAULT_ADMISSION: AdmissionThresholds;
30
23
  export declare function buildHealthBaseline(skills: readonly CorpusSkill[]): HealthBaseline;
31
- /** The admission verdict for ONE rule id (contract §4): platform corpus must not trip it, and the
32
- * user-library hit rate must land inside the band. Every failure names the number it failed on. */
33
- export declare function admissionVerdict(baseline: HealthBaseline, ruleId: string, thresholds?: AdmissionThresholds): {
34
- admitted: boolean;
35
- failures: string[];
36
- };
37
24
  //# sourceMappingURL=health-baseline.d.ts.map
@@ -10,7 +10,6 @@
10
10
  * Pure: no IO. `values` is keyed by rule id so a diff between two baselines is a map diff.
11
11
  */
12
12
  import { lintSkill, RULES } from "./skill-lint.js";
13
- export const DEFAULT_ADMISSION = { minUserHitRate: 0.05, maxUserHitRate: 0.25 };
14
13
  export function buildHealthBaseline(skills) {
15
14
  const values = {};
16
15
  for (const rule of RULES)
@@ -41,23 +40,4 @@ export function buildHealthBaseline(skills) {
41
40
  values,
42
41
  };
43
42
  }
44
- /** The admission verdict for ONE rule id (contract §4): platform corpus must not trip it, and the
45
- * user-library hit rate must land inside the band. Every failure names the number it failed on. */
46
- export function admissionVerdict(baseline, ruleId, thresholds = DEFAULT_ADMISSION) {
47
- const row = baseline.values[ruleId];
48
- const failures = [];
49
- if (row === undefined)
50
- return { admitted: false, failures: ['rule ' + ruleId + ' has no baseline row'] };
51
- if (baseline.corpora.platform === 0)
52
- failures.push('no platform-corpus skills measured — a vacuous 0-hit count admits any rule');
53
- else if (row.platformHits !== 0)
54
- failures.push('platform corpus trips ' + ruleId + ' ' + String(row.platformHits) + ' time(s) — a rule the shipped library violates is unsatisfiable');
55
- if (baseline.corpora.user === 0)
56
- failures.push('no user-library skills measured — a rate over an empty corpus proves nothing');
57
- else if (row.userHitRate < thresholds.minUserHitRate)
58
- failures.push(ruleId + ' hits ' + row.userHitRate.toFixed(3) + ' of the user library, below ' + String(thresholds.minUserHitRate) + ' — too rare to be worth a rule');
59
- else if (row.userHitRate > thresholds.maxUserHitRate)
60
- failures.push(ruleId + ' hits ' + row.userHitRate.toFixed(3) + ' of the user library, above ' + String(thresholds.maxUserHitRate) + ' — furniture, no signal');
61
- return { admitted: failures.length === 0, failures };
62
- }
63
43
  //# sourceMappingURL=health-baseline.js.map
@@ -33,6 +33,8 @@ export declare class HomeFence {
33
33
  constructor(options: HomeFenceOptions);
34
34
  /** The last release failure, if any; diagnostics only. */
35
35
  get releaseFailure(): AuthorityReleaseFailure | undefined;
36
+ /** True only when this async call context already holds the home tree scope. */
37
+ holdsTree(): boolean;
36
38
  run<T>(body: (lock: TreeLock) => Promise<T>): Promise<T>;
37
39
  acquire(): Promise<HomeFenceLease>;
38
40
  }
@@ -43,9 +43,19 @@ export class HomeFence {
43
43
  get releaseFailure() {
44
44
  return this.authority.releaseFailure;
45
45
  }
46
+ /** True only when this async call context already holds the home tree scope. */
47
+ holdsTree() {
48
+ return this.authority.holdsInContext('tree');
49
+ }
46
50
  async run(body) {
51
+ const invoke = async () => await body(lockView(this.authority));
47
52
  try {
48
- return await this.authority.runExclusive('tree', async () => await body(lockView(this.authority)));
53
+ // Bookkeeping called from inside a write already holds the tree scope. It must
54
+ // run inline rather than request the same fence again (that is an undeclared
55
+ // re-entry). A caller that does NOT hold it still acquires normally.
56
+ if (this.authority.holdsInContext('tree'))
57
+ return await this.authority.runNested('tree', invoke);
58
+ return await this.authority.runExclusive('tree', invoke);
49
59
  }
50
60
  catch (error) {
51
61
  throw classify(error);
@@ -51,21 +51,5 @@ export declare class EvolutionIoRegistry extends Service {
51
51
  }): () => void;
52
52
  provider(name?: string): EvolutionIo;
53
53
  }
54
- /**
55
- * Resolve the seam implementation for a consumer, preferring a backend the deployment mounted.
56
- *
57
- * Contract C2 (declared gaps) has no other shape: a consumer that can work on either medium asks for
58
- * its preference and the DEPLOYMENT decides which backends exist. The lookup is contained here because
59
- * the registry deliberately has no presence probe (v20 A-3 removed `hasProvider`; a presence probe goes
60
- * through `provider(name)`, which fails loud) — so this function is the ONE sanctioned place that turns
61
- * that failure into a fallback. A caller that needs a SPECIFIC backend must call `provider(name)` and
62
- * take the error.
63
- * @param registry - the seam registry (`ctx.evolutionIo`).
64
- * @param names - preferred provider names, most preferred first.
65
- * @returns the first registered preference, else the registry default.
66
- */
67
- export declare function preferProvider<T>(registry: {
68
- provider(name?: string): T;
69
- }, names: readonly string[]): T;
70
54
  export default EvolutionIoRegistry;
71
55
  //# sourceMappingURL=io-registry.d.ts.map
@@ -95,29 +95,5 @@ export class EvolutionIoRegistry extends Service {
95
95
  return first;
96
96
  }
97
97
  }
98
- /**
99
- * Resolve the seam implementation for a consumer, preferring a backend the deployment mounted.
100
- *
101
- * Contract C2 (declared gaps) has no other shape: a consumer that can work on either medium asks for
102
- * its preference and the DEPLOYMENT decides which backends exist. The lookup is contained here because
103
- * the registry deliberately has no presence probe (v20 A-3 removed `hasProvider`; a presence probe goes
104
- * through `provider(name)`, which fails loud) — so this function is the ONE sanctioned place that turns
105
- * that failure into a fallback. A caller that needs a SPECIFIC backend must call `provider(name)` and
106
- * take the error.
107
- * @param registry - the seam registry (`ctx.evolutionIo`).
108
- * @param names - preferred provider names, most preferred first.
109
- * @returns the first registered preference, else the registry default.
110
- */
111
- export function preferProvider(registry, names) {
112
- for (const name of names) {
113
- try {
114
- return registry.provider(name);
115
- }
116
- catch {
117
- // Not registered: this name is a preference, not a requirement (see the JSDoc).
118
- }
119
- }
120
- return registry.provider();
121
- }
122
98
  export default EvolutionIoRegistry;
123
99
  //# sourceMappingURL=io-registry.js.map
package/lib/types/io.d.ts CHANGED
@@ -67,6 +67,11 @@ export interface EvolutionIoLike {
67
67
  */
68
68
  mtime?(this: void, path: string): Promise<number | null>;
69
69
  }
70
+ /** A backend's transact returned without ever calling the task; nothing was written. */
71
+ export declare class TransactionNotInvokedError extends Error {
72
+ readonly code = "transact-not-invoked";
73
+ constructor(path: string);
74
+ }
70
75
  /**
71
76
  * Run `task` inside `io.transact` when the backend provides it; otherwise fall
72
77
  * back to a plain read → task → write/remove sequence (no cross-process lock —
@@ -74,7 +79,7 @@ export interface EvolutionIoLike {
74
79
  * byte-identical task result skips the write (C-07 — parity with the
75
80
  * node backend's V5-03 short-circuit).
76
81
  */
77
- export declare function transactIo(io: EvolutionIoLike, path: string, task: (current: string | null) => string | null | Promise<string | null>): Promise<void>;
82
+ export declare function transactIo(io: EvolutionIoLike, path: string, task: (current: string | null) => string | null | Promise<string | null>): Promise<readonly string[] | undefined>;
78
83
  /** Lazy adapter over an IO provider registry, shared by every evolution consumer. */
79
84
  export declare function evolutionIoAdapter(provider: () => EvolutionIoLike): EvolutionIoLike;
80
85
  /**
package/lib/types/io.js CHANGED
@@ -12,6 +12,14 @@ import { randomBytes } from 'node:crypto';
12
12
  // there" lives in probe.ts; this backend delegates instead of keeping a second
13
13
  // copy of the same two codes.
14
14
  import { isMissingPath } from "./probe.js";
15
+ /** A backend's transact returned without ever calling the task; nothing was written. */
16
+ export class TransactionNotInvokedError extends Error {
17
+ code = 'transact-not-invoked';
18
+ constructor(path) {
19
+ super('transact-not-invoked: ' + path);
20
+ this.name = 'TransactionNotInvokedError';
21
+ }
22
+ }
15
23
  /**
16
24
  * Run `task` inside `io.transact` when the backend provides it; otherwise fall
17
25
  * back to a plain read → task → write/remove sequence (no cross-process lock —
@@ -26,22 +34,36 @@ export async function transactIo(io, path, task) {
26
34
  // packages: propagating it made memory/usage/mutations/state/activity/
27
35
  // feedback/events report "not written" for a write that happened, and a
28
36
  // two-phase caller could then roll back a visible write. The durability loss
29
- // is still observable — it is logged, not swallowed.
37
+ // is still observable — it is logged AND returned so a two-phase caller can
38
+ // report it instead of silently losing the warning.
30
39
  const committedOnly = (error) => isCommittedWarning(error);
40
+ const warnings = [];
41
+ const warnCommitted = (error) => {
42
+ const message = error instanceof Error ? error.message : String(error);
43
+ warnings.push(message);
44
+ console.warn(`evolution-io: ${path} was written but its directory fsync failed — the bytes are visible, durability is unconfirmed: ${message}`);
45
+ };
46
+ let invoked = false;
47
+ const invoke = async (current) => {
48
+ invoked = true;
49
+ return await task(current);
50
+ };
31
51
  if (io.transact) {
32
52
  try {
33
- await io.transact(path, task);
34
- return;
53
+ await io.transact(path, invoke);
54
+ if (!invoked)
55
+ throw new TransactionNotInvokedError(path);
56
+ return undefined;
35
57
  }
36
58
  catch (error) {
37
59
  if (!committedOnly(error))
38
60
  throw error;
39
- console.warn(`evolution-io: ${path} was written but its directory fsync failed — the bytes are visible, durability is unconfirmed: ${error instanceof Error ? error.message : String(error)}`);
40
- return;
61
+ warnCommitted(error);
62
+ return warnings;
41
63
  }
42
64
  }
43
65
  const current = await io.readText(path);
44
- const next = await task(current);
66
+ const next = await invoke(current);
45
67
  if (next === null)
46
68
  await io.remove(path);
47
69
  // C-07: a byte-identical result is a no-op — the same V5-03
@@ -55,9 +77,10 @@ export async function transactIo(io, path, task) {
55
77
  catch (error) {
56
78
  if (!committedOnly(error))
57
79
  throw error;
58
- console.warn(`evolution-io: ${path} was written but its directory fsync failed — the bytes are visible, durability is unconfirmed: ${error instanceof Error ? error.message : String(error)}`);
80
+ warnCommitted(error);
59
81
  }
60
82
  }
83
+ return warnings.length === 0 ? undefined : warnings;
61
84
  }
62
85
  /** Lazy adapter over an IO provider registry, shared by every evolution consumer. */
63
86
  export function evolutionIoAdapter(provider) {
@@ -77,9 +100,12 @@ export function evolutionIoAdapter(provider) {
77
100
  },
78
101
  // Transact and symlink probes are forwarding-only: the fallback semantics
79
102
  // live in the consumer helper / the backend itself.
80
- transact: (path, task) => {
103
+ transact: async (path, task) => {
81
104
  const io = provider();
82
- return io.transact ? io.transact(path, task) : transactIo(io, path, task);
105
+ if (io.transact)
106
+ await io.transact(path, task);
107
+ else
108
+ await transactIo(io, path, task);
83
109
  },
84
110
  isSymlink: (path) => {
85
111
  const io = provider();
@@ -3,7 +3,7 @@
3
3
  * Stores are MEMORY.md and USER.md under $DSH_HOME/memories (~/.dsh/memories).
4
4
  */
5
5
  import { basename, join } from 'node:path';
6
- import { nodeEvolutionIo, transactIo } from "./io.js";
6
+ import { nodeEvolutionIo, TransactionNotInvokedError, transactIo } from "./io.js";
7
7
  import { evolutionRoot } from "./state-store.js";
8
8
  import { makeSerialQueue } from "./serial.js";
9
9
  import { payloadText } from "./payload.js";
@@ -285,10 +285,18 @@ export class MemoryStore {
285
285
  return step.write ?? (current ?? null);
286
286
  });
287
287
  };
288
- if (this.fence !== undefined)
289
- await this.fence.run(run);
290
- else
291
- await run();
288
+ try {
289
+ if (this.fence !== undefined)
290
+ await this.fence.run(run);
291
+ else
292
+ await run();
293
+ }
294
+ catch (error) {
295
+ // C-01: the transact seam now reports a contract-violating backend with a
296
+ // typed error; memory's contract is a structured refusal, not a throw.
297
+ if (!(error instanceof TransactionNotInvokedError))
298
+ throw error;
299
+ }
292
300
  // C-01: a transact backend that violates the contract (never invokes the
293
301
  // task) leaves `outcome` undefined — the old `undefined as
294
302
  // MemoryApplyResult` cast handed callers an object whose `.ok` dereference
@@ -19,6 +19,11 @@ export class MutationAuthority {
19
19
  get mutationLock() {
20
20
  return {
21
21
  acquire: async () => {
22
+ // A nested writer running inside an already-held home fence must reuse that
23
+ // exclusion, not queue behind its own lease (merge undo/consolidate call public
24
+ // mutators under one pass-level fence). A caller outside the fence still acquires.
25
+ if (this.fence.holdsTree())
26
+ return { release: async () => { } };
22
27
  const lease = await this.fence.acquire();
23
28
  return { release: async () => { await lease.release(); } };
24
29
  },
@@ -1,4 +1,4 @@
1
- import { type transactIo } from './io.ts';
1
+ import { transactIo } from './io.ts';
2
2
  import type { UnitClaimPort } from './unit-claim.ts';
3
3
  import type { MutationOwner } from './contract.ts';
4
4
  export interface MutationRoot {
@@ -1,6 +1,6 @@
1
1
  import { basename, dirname, isAbsolute, join, relative } from 'node:path';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { isCommittedWarning, isProcessAlive } from "./io.js";
3
+ import { isCommittedWarning, isProcessAlive, TransactionNotInvokedError, transactIo } from "./io.js";
4
4
  import { WriteKernel } from "./write-kernel.js";
5
5
  function underRoot(rootDir, target) {
6
6
  if (rootDir === undefined || rootDir === '')
@@ -154,7 +154,8 @@ export class MutationUnit {
154
154
  lease = await this.lock.acquire();
155
155
  }
156
156
  catch (error) {
157
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'unit-fence-failed', message: error instanceof Error ? error.message : String(error) }] };
157
+ const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
158
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code, message: error instanceof Error ? error.message : String(error) }] };
158
159
  }
159
160
  let claim;
160
161
  if (this.claim !== undefined) {
@@ -247,6 +248,7 @@ export class MutationUnit {
247
248
  rollbackFailure = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
248
249
  }
249
250
  const detail = rollbackFailure === '' ? message : message + '; rollback failed: ' + rollbackFailure;
251
+ const failureCode = error?.code === 'transact-not-invoked' ? 'transact-not-invoked' : 'write-failed';
250
252
  await this.journal?.write({ unitId, journalId: this.journalId, ...(this.context?.runId === undefined ? {} : { runId: this.context.runId }), phase: 'failed', changed, error: detail });
251
253
  try {
252
254
  await this.hooks?.rolledBack?.({
@@ -267,7 +269,7 @@ export class MutationUnit {
267
269
  catch {
268
270
  // best-effort hook; the structured write error remains authoritative
269
271
  }
270
- return { ok: false, unitId, dryRun: false, changed, errors: [{ code: 'write-failed', message: detail }] };
272
+ return { ok: false, unitId, dryRun: false, changed, errors: [{ code: failureCode, message: detail }] };
271
273
  }
272
274
  finally {
273
275
  await claim?.release().catch(() => { });
@@ -298,7 +300,8 @@ export class MutationUnit {
298
300
  lease = await this.lock.acquire();
299
301
  }
300
302
  catch (error) {
301
- return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'unit-fence-failed', message: error instanceof Error ? error.message : String(error) }] };
303
+ const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
304
+ return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code, message: error instanceof Error ? error.message : String(error) }] };
302
305
  }
303
306
  const reverted = [];
304
307
  try {
@@ -411,7 +414,7 @@ export class MutationUnit {
411
414
  async applyOp(op, baseline) {
412
415
  const result = await this.kernel.writeOne({ path: op.target, expected: baseline, next: op.kind === 'delete' ? null : op.content, ...op.skill === undefined ? {} : { skill: op.skill } }, { guardBaseline: this.transactGuard });
413
416
  if (!result.ok)
414
- throw Object.assign(new Error(result.errors[0]?.message ?? 'write failed: ' + op.target), { noWrite: true });
417
+ throw Object.assign(new Error(result.errors[0]?.message ?? 'write failed: ' + op.target), { noWrite: true, code: result.errors[0]?.code });
415
418
  return [...(result.warnings ?? [])];
416
419
  }
417
420
  async rollback(snapshots) {
@@ -448,28 +451,7 @@ export function fileMutationLock(io, root, options = {}) {
448
451
  const now = options.now ?? Date.now;
449
452
  const sleep = options.sleep ?? defaultSleep;
450
453
  const update = async (task) => {
451
- if (io.transact !== undefined) {
452
- let ran = false;
453
- await io.transact(path, current => {
454
- ran = true;
455
- return task(current);
456
- });
457
- if (!ran)
458
- throw new Error('mutation-lock-transact-not-run: ' + path);
459
- return;
460
- }
461
- const current = await io.readText(path);
462
- const next = task(current);
463
- try {
464
- if (next === null)
465
- await io.remove(path);
466
- else
467
- await io.writeText(path, next);
468
- }
469
- catch (error) {
470
- if (!isCommittedWarning(error))
471
- throw error;
472
- }
454
+ await transactIo(io, path, task);
473
455
  };
474
456
  return {
475
457
  async acquire() {
@@ -5,16 +5,16 @@
5
5
  * the SAME name in two carriers (reviewMode, staleAfterDays, archiveAfterDays —
6
6
  * resolved by the existing policy-shadows-row rule) and six use DIFFERENT names.
7
7
  * This module owns the six: the policy/snapshot name is the canonical id, the
8
- * plugin-row name is a deprecated alias kept readable since 0.6.x. Removal was
9
- * planned for 0.7.0 and is deferred: the aliases still ship, so no later version
10
- * is claimed here.
8
+ * plugin-row name is a deprecated alias. The alias table survives only for the one-time
9
+ * legacy-document migration and the doctor's old-key report; live readers use the
10
+ * canonical id and its carrier no longer falls back to the legacy spelling.
11
11
  *
12
- * Reading stays compatible (a carrier still spelling the legacy name resolves),
13
- * writing is strict (the write path accepts canonical ids only, so no new
14
- * document is created under a deprecated name).
12
+ * Writing is canonical-only (a deprecated name is not a live row field in 0.48).
15
13
  * @module
16
14
  */
17
- /** Deprecated alias (plugin-row name) -> canonical id (policy/snapshot name). */
15
+ /** Deprecated alias (plugin-row name) -> canonical id (policy/snapshot name).
16
+ * Retained for the one-time legacy-document migration and the doctor's old-key report;
17
+ * live readers use the canonical id only. */
18
18
  export declare const PARAM_ALIASES: Readonly<Record<string, string>>;
19
19
  /**
20
20
  * Resolve any parameter id to its canonical form.
@@ -29,17 +29,10 @@ export declare function resolveParamId(id: string): string;
29
29
  */
30
30
  export declare function isDeprecatedParamId(id: string): boolean;
31
31
  /**
32
- * Guard for the write path: only canonical ids may be written.
33
- * @param id - parameter id a caller intends to write.
34
- * @returns the canonical id.
35
- * @throws {Error} when the id is a deprecated alias; the message names both ids.
36
- */
37
- export declare function canonicalWriteId(id: string): string;
38
- /**
39
- * Read a parameter from a carrier that may still spell the legacy name.
32
+ * Read a parameter by its canonical id.
40
33
  * @param carrier - config/snapshot object to read from, or undefined.
41
- * @param id - canonical id (a deprecated alias is accepted and resolved first).
42
- * @returns the canonical value when present, else the alias value, else undefined.
34
+ * @param id - canonical id (an alias is resolved first, for migration callers).
35
+ * @returns the canonical value, or undefined.
43
36
  */
44
37
  export declare function readParam(carrier: object | undefined, id: string): unknown;
45
38
  /** Exposure group (design §7.2): the unit a developer changes together.
@@ -159,17 +152,6 @@ export declare const NAMESPACE_MIGRATIONS: readonly {
159
152
  readonly namespace: string;
160
153
  readonly rowId: string;
161
154
  }[];
162
- /**
163
- * The LEGACY settings namespace one owner package used to register through the family's
164
- * own seam (0.1.x). It is no longer what the platform calls the section: the platform
165
- * derives a settings namespace from the Loader entry id, and this registry's `owner` field
166
- * IS that row id, so a live lookup uses {@link paramRowId}. What remains here is the
167
- * migration SOURCE (G3 moves a user layer out of this string and into the row id).
168
- * @param owner - owner package directory name (the map's key).
169
- * @returns the legacy namespace that owner registered.
170
- * @throws when the owner has no entry in {@link PARAM_NAMESPACES}.
171
- */
172
- export declare function paramNamespace(owner: string): string;
173
155
  /**
174
156
  * The settings id one row's user layer lives under, or undefined when the owner publishes
175
157
  * no user layer at all (a deployment-only row: its knobs are E2 and never reach a settings
@@ -177,7 +159,7 @@ export declare function paramNamespace(owner: string): string;
177
159
  * it in `settings.describe()` / `configForms.get(entryId)`, and an owner package's row id is
178
160
  * its own name — spelled the same in every bundle patch.
179
161
  *
180
- * This is the id to LOOK UP with; {@link paramNamespace} keeps the legacy string the 0.1.x
162
+ * This is the id to LOOK UP with; {@link PARAM_NAMESPACES} keeps the legacy string the 0.1.x
181
163
  * seam registered, which is the G3 migration source and never a live lookup key.
182
164
  * @param owner - owner package directory name (the row id).
183
165
  * @returns the entry id the platform reports for that row, or undefined for a row without