@lmzhen/dsh-evolution-core 0.59.6 → 0.60.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 (103) hide show
  1. package/README.md +3 -1
  2. package/lib/authority-plugin.js +3 -2
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-B_F4TYOD.js → composition-BSqh70z_.js} +1 -1
  5. package/lib/{ensure-BpVDuDnA.js → ensure-DTCuxAxR.js} +1 -1
  6. package/lib/{extract-plan-D3ALlAmN.js → extract-plan-CP__XlEs.js} +2 -2
  7. package/lib/extract.js +4 -4
  8. package/lib/http-routes.js +3 -2
  9. package/lib/index.js +15 -15
  10. package/lib/{io-Cpa8wuvj.js → io-DT4-MXLr.js} +25 -1
  11. package/lib/io-node.js +1 -1
  12. package/lib/io-platform.js +163 -0
  13. package/lib/io-registry.js +10 -0
  14. package/lib/{mutation-authority-CZpc9F20.js → mutation-authority-C3RYyiaT.js} +66 -41
  15. package/lib/{mutation-storage-adapter-Cq1bmS1E.js → mutation-storage-adapter-CSVn34dK.js} +327 -210
  16. package/lib/{mutations-Y-wKod7W.js → mutations-JKFlfhSO.js} +1 -1
  17. package/lib/policy.js +1 -1
  18. package/lib/{quality-NPGr3VzA.js → quality-C0ri2SgY.js} +2 -2
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +1 -1
  21. package/lib/{review-context-yNiZadPw.js → review-context-D2LIOEi-.js} +2 -2
  22. package/lib/runtime/plugin.js +2 -2
  23. package/lib/{session-projection-DM15fsRp.js → session-projection-Dnmm5bzt.js} +1 -1
  24. package/lib/{skill-history-BvLWFoOo.js → skill-history-BOZ4HCDB.js} +2 -2
  25. package/lib/skills.js +268 -37
  26. package/lib/state/domain/index.js +433 -0
  27. package/lib/state/index.js +136 -0
  28. package/lib/state/migrate.js +90 -0
  29. package/lib/state/storage.js +605 -0
  30. package/lib/state/store-plugin.js +23 -0
  31. package/lib/state/store.js +268 -0
  32. package/lib/subagent/index.js +1 -1
  33. package/lib/types/authority-plugin.d.ts +1 -1
  34. package/lib/types/authority-plugin.js +2 -1
  35. package/lib/types/authority.d.ts +1 -1
  36. package/lib/types/authority.js +75 -48
  37. package/lib/types/composition/ensure.js +1 -1
  38. package/lib/types/contract.d.ts +8 -0
  39. package/lib/types/http-routes.d.ts +1 -0
  40. package/lib/types/http-routes.js +2 -1
  41. package/lib/types/io-platform.d.ts +74 -0
  42. package/lib/types/io-platform.js +178 -0
  43. package/lib/types/io-registry.d.ts +4 -0
  44. package/lib/types/io-registry.js +10 -0
  45. package/lib/types/io.d.ts +7 -0
  46. package/lib/types/io.js +25 -1
  47. package/lib/types/mutation-authority.d.ts +1 -1
  48. package/lib/types/mutation-storage-adapter.d.ts +1 -1
  49. package/lib/types/opt-in.js +2 -2
  50. package/lib/types/params.js +2 -2
  51. package/lib/types/policy.js +1 -1
  52. package/lib/types/restrictor.js +2 -2
  53. package/lib/types/result.d.ts +1 -1
  54. package/lib/types/result.js +1 -1
  55. package/lib/types/runtime/coherence.js +1 -1
  56. package/lib/types/runtime/llm.d.ts +1 -1
  57. package/lib/types/runtime/llm.js +1 -1
  58. package/lib/types/runtime/platform.d.ts +3 -3
  59. package/lib/types/runtime/platform.js +2 -2
  60. package/lib/types/runtime/projections.d.ts +1 -1
  61. package/lib/types/scope.js +1 -1
  62. package/lib/types/session-projection.d.ts +1 -1
  63. package/lib/types/signals.d.ts +1 -1
  64. package/lib/types/skill-store.d.ts +37 -4
  65. package/lib/types/skill-store.js +240 -24
  66. package/lib/types/skill-write-plan.d.ts +1 -1
  67. package/lib/types/skill-write-service.js +8 -2
  68. package/lib/types/state/conformance.d.ts +47 -0
  69. package/lib/types/state/conformance.js +246 -0
  70. package/lib/types/state/constants.d.ts +52 -0
  71. package/lib/types/state/constants.js +52 -0
  72. package/lib/types/state/domain/compatibility.d.ts +40 -0
  73. package/lib/types/state/domain/compatibility.js +36 -0
  74. package/lib/types/state/domain/index.d.ts +81 -0
  75. package/lib/types/state/domain/index.js +592 -0
  76. package/lib/types/state/index.d.ts +63 -0
  77. package/lib/types/state/index.js +174 -0
  78. package/lib/types/state/medium-declaration.d.ts +37 -0
  79. package/lib/types/state/medium-declaration.js +53 -0
  80. package/lib/types/state/migrate.d.ts +34 -0
  81. package/lib/types/state/migrate.js +103 -0
  82. package/lib/types/state/record-contract.d.ts +56 -0
  83. package/lib/types/state/record-contract.js +120 -0
  84. package/lib/types/state/storage.d.ts +112 -0
  85. package/lib/types/state/storage.js +178 -0
  86. package/lib/types/state/store-plugin.d.ts +14 -0
  87. package/lib/types/state/store-plugin.js +18 -0
  88. package/lib/types/state/store.d.ts +39 -0
  89. package/lib/types/state/store.js +270 -0
  90. package/lib/types/store-ledger.js +2 -2
  91. package/lib/types/subagent/run.d.ts +1 -1
  92. package/lib/types/subagent/types.d.ts +4 -4
  93. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  94. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  95. package/lib/types/tool-dispatch.js +6 -3
  96. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +40 -13
  97. package/lib/types/{mutation-unit.js → unit-kernel.js} +155 -118
  98. package/lib/types/write.d.ts +1 -2
  99. package/lib/types/write.js +1 -2
  100. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  101. package/lib/write.js +4 -4
  102. package/package.json +30 -3
  103. package/persisted-write-inventory.json +14 -5
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Provider seam for durable evolution state.
3
+ *
4
+ * The state CONSUMER (`@lmzhen/dsh-evolution-core/state`) never touches a
5
+ * medium. Providers register here: `domain` (storage-domain KV) and `json`
6
+ * (IO-seam files) are the two shipped providers.
7
+ * @module @lmzhen/dsh-evolution-core/state/storage
8
+ */
9
+ import { Context, Service } from '@deepseek-ai/cordis';
10
+ import type { EvolutionStateStorage, PendingRecord, PendingStatus } from '../contract.ts';
11
+ export type { CuratorStateRecord, EvolutionStateStorage, PendingKind, PendingRecord, PendingResolution, PendingStatus, ReviewStateRecord } from '../contract.ts';
12
+ export * from './constants.ts';
13
+ export * from './record-contract.ts';
14
+ export * from './conformance.ts';
15
+ export * from './medium-declaration.ts';
16
+ /** 0.3.17 (S3.3): the claim lifecycle as ONE transition table — BOTH
17
+ * providers (json/domain) must use these, never a hand-written copy (a second
18
+ * copy is exactly the E-10 drift class). */
19
+ export declare const canClaimPending: (status: PendingStatus) => boolean;
20
+ export declare const canResolvePending: (status: PendingStatus) => boolean;
21
+ /** Releasing a claim on an executing record rolls it back to pending (a
22
+ * runner FAILURE is retryable); other statuses pass through unchanged. */
23
+ export declare const releasedStatus: (status: PendingStatus) => PendingStatus;
24
+ /**
25
+ * V27 G2.2: WHICH pending records the audit cap evicts, as one pure rule both
26
+ * providers apply (the two implementations had drifted into separate files and
27
+ * only one of them was ever updated by a later fix).
28
+ *
29
+ * Eligible = resolved (`approved`/`rejected`) and NOT a capability approval:
30
+ * v23 (AP-1) exempts those because the Creator-mode contract reads the LIVE
31
+ * approved list and a capability cannot be re-submitted for the same package,
32
+ * so eviction would make an approved capability permanently unactivatable.
33
+ * Ordering = oldest `resolvedAt` first; a missing or unparseable timestamp sorts
34
+ * LAST (json parity, v16), and pending/executing rows are live work that is
35
+ * never trimmed. v28 G2.4 (STATE-03) — the previous wording promised "an
36
+ * unknown time must never make a record the victim"; that is only true while
37
+ * the overflow fits within the KNOWN-timestamp records. When the overflow
38
+ * exceeds them (corruption-level data: most resolved rows with broken
39
+ * timestamps), `slice` necessarily reaches into the unknown-timestamp tail —
40
+ * the cap must be enforced, so there is no alternative. The guarantee is
41
+ * therefore: unknown-timestamp records are evicted LAST, after every known
42
+ * timestamp, in insertion order among themselves (Array#sort stability).
43
+ *
44
+ * @param records - every pending record currently in the live table.
45
+ * @param cap - how many resolved records may be kept.
46
+ * @returns the records to evict, oldest first (empty when within the cap).
47
+ */
48
+ export declare function selectPendingOverflow(records: readonly PendingRecord[], cap?: number): PendingRecord[];
49
+ /**
50
+ * V27 G2.2: which review-state session rows a save evicts, as one pure rule
51
+ * both providers apply. The saving session is never a candidate (it is the most
52
+ * recent write by definition); the rest are ordered by their provider stamp
53
+ * ascending, with a missing stamp read as 0 = oldest, because an active session
54
+ * re-stamps its row on its next save and an unknown stamp is stale by
55
+ * construction. Exactly one row is dropped per over-cap save, which keeps the
56
+ * table at the cap in steady state.
57
+ *
58
+ * @param rows - the other sessions' rows, with their stamps.
59
+ * @param cap - how many session rows may exist.
60
+ * @returns the keys to delete, oldest first.
61
+ */
62
+ export declare function selectSessionOverflow<T>(rows: readonly T[], options: {
63
+ keyOf(row: T): string;
64
+ stampOf(row: T): number;
65
+ }, cap?: number): string[];
66
+ /**
67
+ * Claim lifecycle (S3.3): pending →(claim)→ executing →(resolve)→ approved/rejected.
68
+ * release() rolls executing back to pending (failure path). A crash between
69
+ * the runner execution and the resolve leaves the record executing+claimed,
70
+ * and NO later claim is ever accepted (claim only takes pending, so a crashed
71
+ * approve can never double-execute a non-idempotent runner). Only the operator
72
+ * acts on such a record: reject (cleanup, no runner) or — since S2-P2-22
73
+ * (0.3.80) — `/evolution release <id>` (the stored `claimedBy` rides along as
74
+ * the release credential; a record whose approve runs in this process is
75
+ * refused) followed by a deliberate re-approve or reject.
76
+ */
77
+ declare module '@deepseek-ai/cordis' {
78
+ interface Context {
79
+ evolutionStateStorage: EvolutionStateStorageRegistry;
80
+ }
81
+ }
82
+ export declare class EvolutionStateStorageRegistry extends Service {
83
+ private readonly providers;
84
+ /** C-7 (v18): per-name dispose, mirroring the evolution-io registry. */
85
+ private readonly disposals;
86
+ /** v28 G3.1 (STATE-04): the multi-provider warn fires once per ambiguous
87
+ * period, not once per state op (provider() runs on every read/write). */
88
+ private ambiguousWarned;
89
+ constructor(ctx: Context);
90
+ /** C-7 (v18): re-registering the IDENTICAL provider object is idempotent and
91
+ * returns the original dispose (HMR / re-mounted row); a DIFFERENT object
92
+ * under a registered name still fails loud. The dispose carries a generation
93
+ * guard so a stale handle cannot remove a newer registration. */
94
+ registerProvider(provider: EvolutionStateStorage): () => void;
95
+ /** S-07: whether ANY provider is registered. Lets the state
96
+ * consumer precheck a pinned `provider` config at mount time (a typo fails
97
+ * at start with the registry's precise message) while staying lazy when no
98
+ * provider has registered yet (mount order not settled). */
99
+ hasProviders(): boolean;
100
+ /**
101
+ * G2b/2b.1: the registered provider names, in registration order.
102
+ *
103
+ * A consumer needs the COUNT to refuse an unpinned choice while more than one medium is mounted:
104
+ * this registry cannot make that call itself, because the pin lives in the consumer's config and the
105
+ * registry never sees it. Read-only, and it exists so the refusal can happen at mount instead of at the
106
+ * first read (where the state is already half-consumed and the message arrives too late to act on).
107
+ */
108
+ providerNames(): readonly string[];
109
+ provider(name?: string): EvolutionStateStorage;
110
+ }
111
+ export default EvolutionStateStorageRegistry;
112
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Provider seam for durable evolution state.
3
+ *
4
+ * The state CONSUMER (`@lmzhen/dsh-evolution-core/state`) never touches a
5
+ * medium. Providers register here: `domain` (storage-domain KV) and `json`
6
+ * (IO-seam files) are the two shipped providers.
7
+ * @module @lmzhen/dsh-evolution-core/state/storage
8
+ */
9
+ import { Service } from '@deepseek-ai/cordis';
10
+ // S3-2: the two caps live in ./constants.ts (the conformance suite reads them
11
+ // without importing this entry); the local import feeds the pure rules below.
12
+ import { PENDING_RESOLVED_CAP, REVIEW_STATE_SESSION_CAP } from "./constants.js";
13
+ // S-06: the state-stack magic strings (singleton key, file names,
14
+ // provider names, table names) are single-sourced here.
15
+ export * from "./constants.js";
16
+ // P2-12/14/15/16/18 (v19): the record contract both providers consume.
17
+ export * from "./record-contract.js";
18
+ // S3-2 (J-5): the published conformance suite — a provider (in-tree or third
19
+ // party) runs `runStateProviderConsistency(provider, expect)` to check the whole
20
+ // seam contract. It imports no test runner; the assert surface is injected, and
21
+ // U-2 added an optional options bag (namespace, stamp, session ids) for a medium
22
+ // that cannot use the in-tree literals.
23
+ export * from "./conformance.js";
24
+ export * from "./medium-declaration.js";
25
+ /** 0.3.17 (S3.3): the claim lifecycle as ONE transition table — BOTH
26
+ * providers (json/domain) must use these, never a hand-written copy (a second
27
+ * copy is exactly the E-10 drift class). */
28
+ export const canClaimPending = (status) => status === 'pending';
29
+ export const canResolvePending = (status) => status === 'pending' || status === 'executing';
30
+ /** Releasing a claim on an executing record rolls it back to pending (a
31
+ * runner FAILURE is retryable); other statuses pass through unchanged. */
32
+ export const releasedStatus = (status) => status === 'executing' ? 'pending' : status;
33
+ // S3-2: the two caps moved to ./constants.ts so the published conformance suite
34
+ // can read them without importing this module (a value import back into the
35
+ // entry would be a cycle). `export * from './constants.ts'` keeps the surface.
36
+ /**
37
+ * V27 G2.2: WHICH pending records the audit cap evicts, as one pure rule both
38
+ * providers apply (the two implementations had drifted into separate files and
39
+ * only one of them was ever updated by a later fix).
40
+ *
41
+ * Eligible = resolved (`approved`/`rejected`) and NOT a capability approval:
42
+ * v23 (AP-1) exempts those because the Creator-mode contract reads the LIVE
43
+ * approved list and a capability cannot be re-submitted for the same package,
44
+ * so eviction would make an approved capability permanently unactivatable.
45
+ * Ordering = oldest `resolvedAt` first; a missing or unparseable timestamp sorts
46
+ * LAST (json parity, v16), and pending/executing rows are live work that is
47
+ * never trimmed. v28 G2.4 (STATE-03) — the previous wording promised "an
48
+ * unknown time must never make a record the victim"; that is only true while
49
+ * the overflow fits within the KNOWN-timestamp records. When the overflow
50
+ * exceeds them (corruption-level data: most resolved rows with broken
51
+ * timestamps), `slice` necessarily reaches into the unknown-timestamp tail —
52
+ * the cap must be enforced, so there is no alternative. The guarantee is
53
+ * therefore: unknown-timestamp records are evicted LAST, after every known
54
+ * timestamp, in insertion order among themselves (Array#sort stability).
55
+ *
56
+ * @param records - every pending record currently in the live table.
57
+ * @param cap - how many resolved records may be kept.
58
+ * @returns the records to evict, oldest first (empty when within the cap).
59
+ */
60
+ export function selectPendingOverflow(records, cap = PENDING_RESOLVED_CAP) {
61
+ const resolved = records.filter(record => (record.status === 'approved' || record.status === 'rejected') && record.kind !== 'capability');
62
+ const overflow = resolved.length - cap;
63
+ if (overflow <= 0)
64
+ return [];
65
+ const resolvedAtMs = (record) => {
66
+ if (!record.resolvedAt)
67
+ return Number.MAX_SAFE_INTEGER;
68
+ const parsed = Date.parse(record.resolvedAt);
69
+ return Number.isNaN(parsed) ? Number.MAX_SAFE_INTEGER : parsed;
70
+ };
71
+ return [...resolved].sort((a, b) => resolvedAtMs(a) - resolvedAtMs(b)).slice(0, overflow);
72
+ }
73
+ /**
74
+ * V27 G2.2: which review-state session rows a save evicts, as one pure rule
75
+ * both providers apply. The saving session is never a candidate (it is the most
76
+ * recent write by definition); the rest are ordered by their provider stamp
77
+ * ascending, with a missing stamp read as 0 = oldest, because an active session
78
+ * re-stamps its row on its next save and an unknown stamp is stale by
79
+ * construction. Exactly one row is dropped per over-cap save, which keeps the
80
+ * table at the cap in steady state.
81
+ *
82
+ * @param rows - the other sessions' rows, with their stamps.
83
+ * @param cap - how many session rows may exist.
84
+ * @returns the keys to delete, oldest first.
85
+ */
86
+ export function selectSessionOverflow(rows, options, cap = REVIEW_STATE_SESSION_CAP) {
87
+ const overflow = rows.length - cap + 1;
88
+ if (overflow <= 0)
89
+ return [];
90
+ return [...rows]
91
+ .sort((a, b) => options.stampOf(a) - options.stampOf(b))
92
+ .slice(0, overflow)
93
+ .map(row => options.keyOf(row));
94
+ }
95
+ export class EvolutionStateStorageRegistry extends Service {
96
+ providers = new Map();
97
+ /** C-7 (v18): per-name dispose, mirroring the evolution-io registry. */
98
+ disposals = new Map();
99
+ /** v28 G3.1 (STATE-04): the multi-provider warn fires once per ambiguous
100
+ * period, not once per state op (provider() runs on every read/write). */
101
+ ambiguousWarned = false;
102
+ constructor(ctx) {
103
+ super(ctx, 'evolutionStateStorage');
104
+ }
105
+ /** C-7 (v18): re-registering the IDENTICAL provider object is idempotent and
106
+ * returns the original dispose (HMR / re-mounted row); a DIFFERENT object
107
+ * under a registered name still fails loud. The dispose carries a generation
108
+ * guard so a stale handle cannot remove a newer registration. */
109
+ registerProvider(provider) {
110
+ const idempotent = this.providers.get(provider.name) === provider;
111
+ if (!idempotent && this.providers.has(provider.name))
112
+ throw new Error(`evolution state storage provider "${provider.name}" already registered`);
113
+ if (idempotent) {
114
+ const existing = this.disposals.get(provider.name);
115
+ if (existing !== undefined)
116
+ return existing;
117
+ }
118
+ const dispose = () => {
119
+ if (this.disposals.get(provider.name) !== dispose)
120
+ return;
121
+ this.providers.delete(provider.name);
122
+ this.disposals.delete(provider.name);
123
+ };
124
+ this.providers.set(provider.name, provider);
125
+ this.disposals.set(provider.name, dispose);
126
+ return dispose;
127
+ }
128
+ /** S-07: whether ANY provider is registered. Lets the state
129
+ * consumer precheck a pinned `provider` config at mount time (a typo fails
130
+ * at start with the registry's precise message) while staying lazy when no
131
+ * provider has registered yet (mount order not settled). */
132
+ hasProviders() {
133
+ return this.providers.size > 0;
134
+ }
135
+ /**
136
+ * G2b/2b.1: the registered provider names, in registration order.
137
+ *
138
+ * A consumer needs the COUNT to refuse an unpinned choice while more than one medium is mounted:
139
+ * this registry cannot make that call itself, because the pin lives in the consumer's config and the
140
+ * registry never sees it. Read-only, and it exists so the refusal can happen at mount instead of at the
141
+ * first read (where the state is already half-consumed and the message arrives too late to act on).
142
+ */
143
+ providerNames() {
144
+ return [...this.providers.keys()];
145
+ }
146
+ provider(name) {
147
+ if (name) {
148
+ this.ambiguousWarned = false;
149
+ const provider = this.providers.get(name);
150
+ if (provider)
151
+ return provider;
152
+ throw new Error(`evolution state storage provider "${name}" is not registered`);
153
+ }
154
+ const first = this.providers.values().next().value;
155
+ if (!first)
156
+ throw new Error('no evolution state storage provider registered; mount @lmzhen/dsh-evolution-core/state/domain or @lmzhen/dsh-evolution-core/state/domain');
157
+ // v28 G3.1 (STATE-04): the io registry refuses multi-default ambiguity;
158
+ // here two providers can silently coexist and the effective one is
159
+ // REGISTRATION ORDER — enabling the domain row in an overlay rebinds every
160
+ // evolutionState op to an empty medium while all json state stays on disk,
161
+ // invisible (/evolution pending shows nothing, approve misses). Warn ONCE
162
+ // per ambiguous period at the un-pinned selection point, naming both the
163
+ // effective provider and the escape hatch (a pinned selection takes the
164
+ // `name` branch above and never warns).
165
+ if (this.providers.size > 1) {
166
+ if (!this.ambiguousWarned) {
167
+ this.ambiguousWarned = true;
168
+ this.ctx.logger.warn(`evolution state storage: ${this.providers.size} providers registered (${[...this.providers.keys()].join(', ')}), none pinned — the effective provider is "${first.name}" (registration order). Existing state under the other provider is now invisible. Pin config: { provider: json|domain } on the evolution-state row to make the choice explicit.`);
169
+ }
170
+ }
171
+ else {
172
+ this.ambiguousWarned = false;
173
+ }
174
+ return first;
175
+ }
176
+ }
177
+ export default EvolutionStateStorageRegistry;
178
+ //# sourceMappingURL=storage.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Cordis row for the file StateStore provider.
3
+ *
4
+ * The provider is registered but not selected until `EvolutionState` sees the
5
+ * migration marker (or is pinned to `store`). This lets `/evolution migrate state`
6
+ * publish the snapshot while the host is still running on the old domain, then
7
+ * the next restart selects the store without a second command.
8
+ * @module @lmzhen/dsh-evolution-core/state/store-plugin
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis';
11
+ export declare const name = "evolution-state-store";
12
+ export declare const inject: string[];
13
+ export declare function apply(ctx: Context): Promise<void>;
14
+ //# sourceMappingURL=store-plugin.d.ts.map
@@ -0,0 +1,18 @@
1
+ import { evolutionHome } from "../state-store.js";
2
+ import { createStateStoreProvider } from "./store.js";
3
+ export const name = 'evolution-state-store';
4
+ export const inject = ['evolutionStateStorage', 'evolutionIo'];
5
+ /** HMR re-applies the row in the same ctx; the registry only treats the SAME object as
6
+ * idempotent, so keep one provider per home instead of constructing a new registrant. */
7
+ const providers = new Map();
8
+ export async function apply(ctx) {
9
+ await ctx.evolutionIo.whenReady();
10
+ const home = evolutionHome();
11
+ let provider = providers.get(home);
12
+ if (provider === undefined) {
13
+ provider = createStateStoreProvider({ io: ctx.evolutionIo.provider(), home });
14
+ providers.set(home, provider);
15
+ }
16
+ ctx.effect(() => ctx.evolutionStateStorage.registerProvider(provider), 'evolution-state-store.provider');
17
+ }
18
+ //# sourceMappingURL=store-plugin.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * File-backed StateStore provider.
3
+ *
4
+ * This is the first D1 step: the provider owns ONE JSON file and every
5
+ * transition is a read-modify-write inside the IO seam's transaction. There is
6
+ * no process-local authoritative copy; `reload()` is therefore unnecessary and
7
+ * reads always observe the medium.
8
+ *
9
+ * It is intentionally not mounted by the bundle yet: the domain provider is
10
+ * still the shipped one until the migration/rollback path is implemented.
11
+ * @module @lmzhen/dsh-evolution-core/state/store
12
+ */
13
+ import { type EvolutionIoLike } from '../io.ts';
14
+ import { type CuratorStateRecord, type EvolutionStateStorage, type PendingRecord, type ReviewStateRecord } from './index.ts';
15
+ export type StoredReviewState = ReviewStateRecord & {
16
+ updatedAt?: number;
17
+ };
18
+ export interface StateStoreOptions {
19
+ readonly io: EvolutionIoLike;
20
+ /** Evolution home (the parent of `state/`); defaults to `evolutionHome()`. */
21
+ readonly home?: string;
22
+ /** Override the store file path; used by migration/fixture tests. */
23
+ readonly path?: string;
24
+ }
25
+ /** A complete store image, built by migration or by the provider itself. */
26
+ export interface StateStoreSnapshot {
27
+ readonly review: Record<string, StoredReviewState>;
28
+ readonly curator: CuratorStateRecord | null;
29
+ readonly pending: Record<string, PendingRecord>;
30
+ }
31
+ /** Validate and publish a complete store image. The write is create-if-absent:
32
+ * an existing store is never overwritten by a migration. */
33
+ export declare function writeStateStoreSnapshot(io: EvolutionIoLike, path: string, snapshot: StateStoreSnapshot): Promise<void>;
34
+ /**
35
+ * Build the file-backed provider. All mutating methods are a single
36
+ * `transactIo` RMW; readers parse the current file, never a cached copy.
37
+ */
38
+ export declare function createStateStoreProvider(options: StateStoreOptions): EvolutionStateStorage;
39
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1,270 @@
1
+ /**
2
+ * File-backed StateStore provider.
3
+ *
4
+ * This is the first D1 step: the provider owns ONE JSON file and every
5
+ * transition is a read-modify-write inside the IO seam's transaction. There is
6
+ * no process-local authoritative copy; `reload()` is therefore unnecessary and
7
+ * reads always observe the medium.
8
+ *
9
+ * It is intentionally not mounted by the bundle yet: the domain provider is
10
+ * still the shipped one until the migration/rollback path is implemented.
11
+ * @module @lmzhen/dsh-evolution-core/state/store
12
+ */
13
+ import { join } from 'node:path';
14
+ import { evolutionHome } from "../state-store.js";
15
+ import { transactIo } from "../io.js";
16
+ import { assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, CURATOR_STATE_TABLE, PENDING_RESOLVED_CAP, PENDING_TABLE, PROVIDER_STORE, REVIEW_STATE_SESSION_CAP, REVIEW_STATE_TABLE, selectPendingOverflow, selectSessionOverflow, } from "./index.js";
17
+ const STORE_VERSION = 1;
18
+ const emptyStore = () => ({ version: STORE_VERSION, review: {}, curator: null, pending: {} });
19
+ /** Validate and publish a complete store image. The write is create-if-absent:
20
+ * an existing store is never overwritten by a migration. */
21
+ export async function writeStateStoreSnapshot(io, path, snapshot) {
22
+ const store = { ...emptyStore(), ...snapshot };
23
+ const text = serialize(store);
24
+ // Parsing our own image catches a migration source that produced a bad record
25
+ // before the first byte reaches the medium.
26
+ parseStore(text);
27
+ if (io.exists !== undefined && await io.exists(path))
28
+ throw new Error('evolution-state-store: refusing to overwrite an existing store: ' + path);
29
+ if (io.createTextIfAbsent !== undefined) {
30
+ await io.createTextIfAbsent(path, text);
31
+ return;
32
+ }
33
+ if (io.exists !== undefined && await io.exists(path))
34
+ throw new Error('evolution-state-store: refusing to overwrite an existing store: ' + path);
35
+ await io.writeText(path, text);
36
+ }
37
+ function invalid(message) {
38
+ throw new Error('evolution-state-store: ' + message);
39
+ }
40
+ /** Parse and validate one whole store image. A corrupt store fails loud: silently
41
+ * treating it as empty would overwrite the only copy. */
42
+ function parseStore(text) {
43
+ if (text === null || text.trim() === '')
44
+ return emptyStore();
45
+ let raw;
46
+ try {
47
+ raw = JSON.parse(text);
48
+ }
49
+ catch (error) {
50
+ invalid('store is not valid JSON: ' + (error instanceof Error ? error.message : String(error)));
51
+ }
52
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
53
+ invalid('store must be an object');
54
+ const candidate = raw;
55
+ if (candidate.version !== STORE_VERSION)
56
+ invalid('unsupported store version: ' + String(candidate.version));
57
+ const review = candidate.review;
58
+ const pending = candidate.pending;
59
+ if (typeof review !== 'object' || review === null || Array.isArray(review))
60
+ invalid('review must be an object');
61
+ if (typeof pending !== 'object' || pending === null || Array.isArray(pending))
62
+ invalid('pending must be an object');
63
+ const store = emptyStore();
64
+ for (const [sessionId, record] of Object.entries(review)) {
65
+ const issue = recordIssue(REVIEW_STATE_TABLE, record);
66
+ if (issue !== null)
67
+ invalid(`review[${sessionId}]: ${issue}`);
68
+ store.review[sessionId] = cloneRecord(record);
69
+ }
70
+ for (const [key, record] of Object.entries(pending)) {
71
+ const issue = recordIssue(PENDING_TABLE, record);
72
+ if (issue !== null)
73
+ invalid(`pending[${key}]: ${issue}`);
74
+ const pendingRecord = cloneRecord(record);
75
+ // A hand-written/legacy slot whose key drifted from record.id is reachable
76
+ // by claim/resolve only after re-keying; the canonical id wins.
77
+ if (pendingRecord.id !== key) {
78
+ if (store.pending[pendingRecord.id] === undefined)
79
+ store.pending[pendingRecord.id] = pendingRecord;
80
+ continue;
81
+ }
82
+ store.pending[pendingRecord.id] = pendingRecord;
83
+ }
84
+ const curator = candidate.curator;
85
+ if (curator !== undefined && curator !== null) {
86
+ const issue = recordIssue(CURATOR_STATE_TABLE, curator);
87
+ if (issue !== null)
88
+ invalid('curator: ' + issue);
89
+ store.curator = cloneRecord(curator);
90
+ }
91
+ return store;
92
+ }
93
+ const serialize = (store) => JSON.stringify(store, null, 2) + '\n';
94
+ /**
95
+ * Build the file-backed provider. All mutating methods are a single
96
+ * `transactIo` RMW; readers parse the current file, never a cached copy.
97
+ */
98
+ export function createStateStoreProvider(options) {
99
+ const file = options.path ?? join(options.home ?? evolutionHome(), 'state', 'store.json');
100
+ const io = options.io;
101
+ const read = async () => parseStore(await io.readText(file));
102
+ const mutate = async (task) => {
103
+ let result;
104
+ let ran = false;
105
+ await transactIo(io, file, (current) => {
106
+ const store = parseStore(current);
107
+ // The task assigns the result; it cannot throw with a half-written file
108
+ // because the transaction only writes after this callback resolves.
109
+ const outcome = task(store);
110
+ if (outcome instanceof Promise) {
111
+ return outcome.then((value) => {
112
+ result = value;
113
+ ran = true;
114
+ const next = serialize(store);
115
+ return next === current ? current : next;
116
+ });
117
+ }
118
+ result = outcome;
119
+ ran = true;
120
+ const next = serialize(store);
121
+ return next === current ? current : next;
122
+ });
123
+ if (!ran)
124
+ throw new Error('evolution-state-store: transaction did not run the task');
125
+ return result;
126
+ };
127
+ const savePendingValidated = (record) => {
128
+ const issue = recordIssue(PENDING_TABLE, record) ?? assertCloneable(record);
129
+ if (issue !== null)
130
+ throw new Error('evolution-state-store: refusing to persist an invalid pending record: ' + issue);
131
+ return cloneRecord(record);
132
+ };
133
+ return {
134
+ name: PROVIDER_STORE,
135
+ async listReviewStates() {
136
+ return Object.entries((await read()).review).map(([sessionId, record]) => {
137
+ const { updatedAt, ...consumer } = record;
138
+ return { sessionId, record: structuredClone(consumer), ...(updatedAt === undefined ? {} : { updatedAt }) };
139
+ });
140
+ },
141
+ async loadReviewState(sessionId) {
142
+ const stored = (await read()).review[sessionId];
143
+ if (stored === undefined)
144
+ return null;
145
+ const { updatedAt: _updatedAt, ...consumer } = stored;
146
+ return structuredClone(consumer);
147
+ },
148
+ async saveReviewState(sessionId, record) {
149
+ const issue = recordIssue(REVIEW_STATE_TABLE, record) ?? assertCloneable(record);
150
+ if (issue !== null)
151
+ throw new Error('evolution-state-store: refusing to persist an invalid review-state record: ' + issue);
152
+ await mutate((store) => {
153
+ store.review[sessionId] = { ...cloneRecord(record), updatedAt: Date.now() };
154
+ const entries = Object.entries(store.review)
155
+ .filter(([key]) => key !== sessionId)
156
+ .map(([key, row]) => ({ key, updatedAt: row.updatedAt ?? 0 }));
157
+ for (const victim of selectSessionOverflow(entries, {
158
+ keyOf: entry => entry.key,
159
+ stampOf: entry => entry.updatedAt,
160
+ }, REVIEW_STATE_SESSION_CAP)) {
161
+ // Re-read the stamp immediately before deleting; the transaction
162
+ // already serializes writers, so this is only for a value the task
163
+ // itself changed earlier in this same callback.
164
+ const current = store.review[victim];
165
+ if (current === undefined)
166
+ continue;
167
+ if ((current.updatedAt ?? 0) !== entries.find(entry => entry.key === victim)?.updatedAt)
168
+ continue;
169
+ delete store.review[victim];
170
+ }
171
+ });
172
+ },
173
+ async loadCuratorState() {
174
+ const curator = (await read()).curator;
175
+ return curator === null ? null : structuredClone(curator);
176
+ },
177
+ async saveCuratorState(record) {
178
+ const issue = recordIssue(CURATOR_STATE_TABLE, record) ?? assertCloneable(record);
179
+ if (issue !== null)
180
+ throw new Error('evolution-state-store: refusing to persist an invalid curator-state record: ' + issue);
181
+ await mutate((store) => { store.curator = cloneRecord(record); });
182
+ },
183
+ async transactCuratorState(task) {
184
+ await mutate((store) => {
185
+ const current = store.curator === null ? null : cloneRecord(store.curator);
186
+ const next = task(current);
187
+ // The seam contract: null means "keep the current record", not delete.
188
+ if (next === null)
189
+ return;
190
+ const issue = recordIssue(CURATOR_STATE_TABLE, next) ?? assertCloneable(next);
191
+ if (issue !== null)
192
+ throw new Error('evolution-state-store: refusing to persist an invalid curator-state record: ' + issue);
193
+ store.curator = cloneRecord(next);
194
+ });
195
+ },
196
+ async listPending(status = 'pending') {
197
+ const store = await read();
198
+ const seen = new Set();
199
+ const out = [];
200
+ for (const record of Object.values(store.pending)) {
201
+ if (record.status !== status)
202
+ continue;
203
+ if (seen.has(record.id))
204
+ continue;
205
+ seen.add(record.id);
206
+ out.push(structuredClone(record));
207
+ }
208
+ return out;
209
+ },
210
+ async savePending(record) {
211
+ const valid = savePendingValidated(record);
212
+ await mutate((store) => { store.pending[valid.id] = valid; });
213
+ },
214
+ async claimPending(id, claimId) {
215
+ let claimed = null;
216
+ await mutate((store) => {
217
+ const current = store.pending[id];
218
+ if (current === undefined || !canClaimPending(current.status))
219
+ return;
220
+ const next = {
221
+ ...current,
222
+ status: 'executing',
223
+ claimedBy: claimId,
224
+ claimedAt: new Date().toISOString(),
225
+ };
226
+ store.pending[id] = next;
227
+ claimed = structuredClone(next);
228
+ });
229
+ return claimed;
230
+ },
231
+ async releasePendingClaim(id, claimId) {
232
+ await mutate((store) => {
233
+ const current = store.pending[id];
234
+ if (current === undefined || current.claimedBy !== claimId)
235
+ return;
236
+ if (current.status !== 'pending' && current.status !== 'executing')
237
+ return;
238
+ const next = { ...current, status: releasedStatus(current.status) };
239
+ delete next.claimedBy;
240
+ delete next.claimedAt;
241
+ store.pending[id] = next;
242
+ });
243
+ },
244
+ async tryResolvePending(id, status, expectedClaimId) {
245
+ let outcome = { record: null, applied: false };
246
+ await mutate((store) => {
247
+ const current = store.pending[id];
248
+ if (current === undefined)
249
+ return;
250
+ if (!canResolvePending(current.status)) {
251
+ outcome = { record: structuredClone(current), applied: false };
252
+ return;
253
+ }
254
+ if (expectedClaimId !== undefined && current.claimedBy !== expectedClaimId) {
255
+ outcome = { record: structuredClone(current), applied: false };
256
+ return;
257
+ }
258
+ const resolved = { ...current, status, resolvedAt: new Date().toISOString() };
259
+ store.pending[id] = resolved;
260
+ outcome = { record: structuredClone(resolved), applied: true };
261
+ for (const victim of selectPendingOverflow(Object.values(store.pending), PENDING_RESOLVED_CAP)) {
262
+ if (store.pending[victim.id]?.resolvedAt === victim.resolvedAt)
263
+ delete store.pending[victim.id];
264
+ }
265
+ });
266
+ return outcome;
267
+ },
268
+ };
269
+ }
270
+ //# sourceMappingURL=store.js.map
@@ -58,7 +58,7 @@ export const STORE_LEDGER = [
58
58
  cutoff: 'resolved records beyond the cap',
59
59
  trigger: 'write',
60
60
  artifact: 'resolved record count',
61
- declare: [{ kind: 'named', module: 'evolution-state/src/constants.ts', name: 'PENDING_RESOLVED_CAP', value: 200 }],
61
+ declare: [{ kind: 'named', module: 'evolution-core/src/state/constants.ts', name: 'PENDING_RESOLVED_CAP', value: 200 }],
62
62
  },
63
63
  {
64
64
  id: 'review-session',
@@ -68,7 +68,7 @@ export const STORE_LEDGER = [
68
68
  cutoff: 'rows beyond the session cap',
69
69
  trigger: 'write',
70
70
  artifact: 'review state row count',
71
- declare: [{ kind: 'named', module: 'evolution-state/src/constants.ts', name: 'REVIEW_STATE_SESSION_CAP', value: 500 }],
71
+ declare: [{ kind: 'named', module: 'evolution-core/src/state/constants.ts', name: 'REVIEW_STATE_SESSION_CAP', value: 500 }],
72
72
  },
73
73
  {
74
74
  id: 'reports',
@@ -4,7 +4,7 @@
4
4
  * handle owns the continuation lifecycle and the end-event wait.
5
5
  */
6
6
  import type { Context } from '@deepseek-ai/cordis';
7
- import type { Agent, ContentBlock, SessionId, SubagentStopReason } from '@lmzhen/dsh-evolution-platform-contract';
7
+ import type { Agent, ContentBlock, SessionId, SubagentStopReason } from '@lmzhen/dsh-evolution-platform/contract';
8
8
  export interface ActivationResultLike {
9
9
  readonly output?: unknown;
10
10
  readonly structured?: unknown;