@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.
- package/README.md +3 -1
- package/lib/authority-plugin.js +3 -2
- package/lib/composition/index.js +2 -2
- package/lib/{composition-B_F4TYOD.js → composition-BSqh70z_.js} +1 -1
- package/lib/{ensure-BpVDuDnA.js → ensure-DTCuxAxR.js} +1 -1
- package/lib/{extract-plan-D3ALlAmN.js → extract-plan-CP__XlEs.js} +2 -2
- package/lib/extract.js +4 -4
- package/lib/http-routes.js +3 -2
- package/lib/index.js +15 -15
- package/lib/{io-Cpa8wuvj.js → io-DT4-MXLr.js} +25 -1
- package/lib/io-node.js +1 -1
- package/lib/io-platform.js +163 -0
- package/lib/io-registry.js +10 -0
- package/lib/{mutation-authority-CZpc9F20.js → mutation-authority-C3RYyiaT.js} +66 -41
- package/lib/{mutation-storage-adapter-Cq1bmS1E.js → mutation-storage-adapter-CSVn34dK.js} +327 -210
- package/lib/{mutations-Y-wKod7W.js → mutations-JKFlfhSO.js} +1 -1
- package/lib/policy.js +1 -1
- package/lib/{quality-NPGr3VzA.js → quality-C0ri2SgY.js} +2 -2
- package/lib/restrictor.js +1 -1
- package/lib/result.js +1 -1
- package/lib/{review-context-yNiZadPw.js → review-context-D2LIOEi-.js} +2 -2
- package/lib/runtime/plugin.js +2 -2
- package/lib/{session-projection-DM15fsRp.js → session-projection-Dnmm5bzt.js} +1 -1
- package/lib/{skill-history-BvLWFoOo.js → skill-history-BOZ4HCDB.js} +2 -2
- package/lib/skills.js +268 -37
- package/lib/state/domain/index.js +433 -0
- package/lib/state/index.js +136 -0
- package/lib/state/migrate.js +90 -0
- package/lib/state/storage.js +605 -0
- package/lib/state/store-plugin.js +23 -0
- package/lib/state/store.js +268 -0
- package/lib/subagent/index.js +1 -1
- package/lib/types/authority-plugin.d.ts +1 -1
- package/lib/types/authority-plugin.js +2 -1
- package/lib/types/authority.d.ts +1 -1
- package/lib/types/authority.js +75 -48
- package/lib/types/composition/ensure.js +1 -1
- package/lib/types/contract.d.ts +8 -0
- package/lib/types/http-routes.d.ts +1 -0
- package/lib/types/http-routes.js +2 -1
- package/lib/types/io-platform.d.ts +74 -0
- package/lib/types/io-platform.js +178 -0
- package/lib/types/io-registry.d.ts +4 -0
- package/lib/types/io-registry.js +10 -0
- package/lib/types/io.d.ts +7 -0
- package/lib/types/io.js +25 -1
- package/lib/types/mutation-authority.d.ts +1 -1
- package/lib/types/mutation-storage-adapter.d.ts +1 -1
- package/lib/types/opt-in.js +2 -2
- package/lib/types/params.js +2 -2
- package/lib/types/policy.js +1 -1
- package/lib/types/restrictor.js +2 -2
- package/lib/types/result.d.ts +1 -1
- package/lib/types/result.js +1 -1
- package/lib/types/runtime/coherence.js +1 -1
- package/lib/types/runtime/llm.d.ts +1 -1
- package/lib/types/runtime/llm.js +1 -1
- package/lib/types/runtime/platform.d.ts +3 -3
- package/lib/types/runtime/platform.js +2 -2
- package/lib/types/runtime/projections.d.ts +1 -1
- package/lib/types/scope.js +1 -1
- package/lib/types/session-projection.d.ts +1 -1
- package/lib/types/signals.d.ts +1 -1
- package/lib/types/skill-store.d.ts +37 -4
- package/lib/types/skill-store.js +240 -24
- package/lib/types/skill-write-plan.d.ts +1 -1
- package/lib/types/skill-write-service.js +8 -2
- package/lib/types/state/conformance.d.ts +47 -0
- package/lib/types/state/conformance.js +246 -0
- package/lib/types/state/constants.d.ts +52 -0
- package/lib/types/state/constants.js +52 -0
- package/lib/types/state/domain/compatibility.d.ts +40 -0
- package/lib/types/state/domain/compatibility.js +36 -0
- package/lib/types/state/domain/index.d.ts +81 -0
- package/lib/types/state/domain/index.js +592 -0
- package/lib/types/state/index.d.ts +63 -0
- package/lib/types/state/index.js +174 -0
- package/lib/types/state/medium-declaration.d.ts +37 -0
- package/lib/types/state/medium-declaration.js +53 -0
- package/lib/types/state/migrate.d.ts +34 -0
- package/lib/types/state/migrate.js +103 -0
- package/lib/types/state/record-contract.d.ts +56 -0
- package/lib/types/state/record-contract.js +120 -0
- package/lib/types/state/storage.d.ts +112 -0
- package/lib/types/state/storage.js +178 -0
- package/lib/types/state/store-plugin.d.ts +14 -0
- package/lib/types/state/store-plugin.js +18 -0
- package/lib/types/state/store.d.ts +39 -0
- package/lib/types/state/store.js +270 -0
- package/lib/types/store-ledger.js +2 -2
- package/lib/types/subagent/run.d.ts +1 -1
- package/lib/types/subagent/types.d.ts +4 -4
- package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
- package/lib/types/{write-kernel.js → target-writer.js} +40 -8
- package/lib/types/tool-dispatch.js +6 -3
- package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +40 -13
- package/lib/types/{mutation-unit.js → unit-kernel.js} +155 -118
- package/lib/types/write.d.ts +1 -2
- package/lib/types/write.js +1 -2
- package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
- package/lib/write.js +4 -4
- package/package.json +30 -3
- package/persisted-write-inventory.json +14 -5
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable evolution state consumer.
|
|
3
|
+
*
|
|
4
|
+
* The service owns no medium and performs no IO. It resolves the mounted
|
|
5
|
+
* provider from `ctx.evolutionStateStorage` (see evolution-state-json and
|
|
6
|
+
* evolution-state-domain); `provider` config may pin one by name.
|
|
7
|
+
* @module @lmzhen/dsh-evolution-core/state
|
|
8
|
+
*/
|
|
9
|
+
import { Service } from '@deepseek-ai/cordis';
|
|
10
|
+
import z from '@deepseek-ai/schemastery';
|
|
11
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
12
|
+
import { mkdir } from 'node:fs/promises';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { withFileLock } from '@lmzhen/dsh-evolution-platform/values/fs';
|
|
15
|
+
import { evolutionHome } from "../state-store.js";
|
|
16
|
+
import { PROVIDER_DOMAIN, PROVIDER_STORE, STATE_MIGRATION_MARKER } from "./storage.js";
|
|
17
|
+
export * from "./storage.js";
|
|
18
|
+
export class EvolutionState extends Service {
|
|
19
|
+
static inject = ['evolutionStateStorage'];
|
|
20
|
+
static Config = z.object({
|
|
21
|
+
provider: z.string().default(''),
|
|
22
|
+
home: z.string().default(''),
|
|
23
|
+
});
|
|
24
|
+
providerName;
|
|
25
|
+
home;
|
|
26
|
+
constructor(ctx, config = {}) {
|
|
27
|
+
super(ctx, 'evolutionState');
|
|
28
|
+
this.providerName = config.provider ?? '';
|
|
29
|
+
this.home = config.home !== undefined && config.home !== '' ? config.home : evolutionHome();
|
|
30
|
+
// S-07: a PINNED provider name is verified at mount when any
|
|
31
|
+
// provider is already registered — a config typo used to explode only at
|
|
32
|
+
// the first state access, far away from the mistake (the registry's
|
|
33
|
+
// precise "not registered" error now surfaces at start). With an empty
|
|
34
|
+
// registry (mount order not settled yet) the check stays lazy by design.
|
|
35
|
+
if (this.providerName !== '' && this.providerName !== 'auto' && ctx.evolutionStateStorage.hasProviders()) {
|
|
36
|
+
ctx.evolutionStateStorage.provider(this.providerName);
|
|
37
|
+
}
|
|
38
|
+
// G2b/2b.1: the UNPINNED case, refused at MOUNT. Two media with no pin means the effective one is
|
|
39
|
+
// registration order — enabling the domain row in an overlay rebinds every state op to an empty medium
|
|
40
|
+
// while all json state stays on disk, invisible (/evolution pending shows nothing, approve misses).
|
|
41
|
+
// That used to be a warn-once at the first state access; the judgement is that it belongs here, because
|
|
42
|
+
// after the first read the deployment has already operated on the wrong medium. The pin is THIS row
|
|
43
|
+
// config, which is exactly why the registry cannot make this call itself — it never sees the pin.
|
|
44
|
+
// `auto` may legitimately mount before the store provider row has finished
|
|
45
|
+
// its own async IO wait; the marker/provider check runs on the first state
|
|
46
|
+
// operation, after every row is mounted.
|
|
47
|
+
if (this.providerName !== 'auto')
|
|
48
|
+
this.assertProviderChoice();
|
|
49
|
+
}
|
|
50
|
+
/** P2-5: the multi-provider refusal is not a mount-time-only check. A provider
|
|
51
|
+
* registered after this row mounted used to make registration order the effective
|
|
52
|
+
* medium with no pin — exactly the silent rebind the mount check exists to stop. */
|
|
53
|
+
/** Validate the marker + a real store image before auto may select it. */
|
|
54
|
+
assertMarkerStore() {
|
|
55
|
+
const marker = join(this.home, 'state', STATE_MIGRATION_MARKER);
|
|
56
|
+
if (!existsSync(marker))
|
|
57
|
+
return;
|
|
58
|
+
const storePath = join(this.home, 'state', 'store.json');
|
|
59
|
+
let markerBody;
|
|
60
|
+
let storeBody;
|
|
61
|
+
try {
|
|
62
|
+
markerBody = JSON.parse(readFileSync(marker, 'utf8'));
|
|
63
|
+
storeBody = JSON.parse(readFileSync(storePath, 'utf8'));
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw new Error('evolution-state: the migration marker/store is missing or unreadable: ' + (error instanceof Error ? error.message : String(error)));
|
|
67
|
+
}
|
|
68
|
+
if (typeof markerBody !== 'object' || markerBody === null || markerBody.target !== 'store') {
|
|
69
|
+
throw new Error('evolution-state: the migration marker is invalid (target != store): ' + marker);
|
|
70
|
+
}
|
|
71
|
+
const image = storeBody;
|
|
72
|
+
if (typeof image !== 'object' || image === null || image.version !== 1
|
|
73
|
+
|| typeof image.review !== 'object' || image.review === null || Array.isArray(image.review)
|
|
74
|
+
|| typeof image.pending !== 'object' || image.pending === null || Array.isArray(image.pending)) {
|
|
75
|
+
throw new Error('evolution-state: the migration marker points at an invalid/empty store image: ' + storePath);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
assertProviderChoice() {
|
|
79
|
+
if (this.providerName === 'auto') {
|
|
80
|
+
const names = this.ctx.evolutionStateStorage.providerNames();
|
|
81
|
+
const marker = join(this.home, 'state', STATE_MIGRATION_MARKER);
|
|
82
|
+
if (existsSync(marker)) {
|
|
83
|
+
if (!names.includes(PROVIDER_STORE))
|
|
84
|
+
throw new Error('evolution-state: the migration marker exists but no "' + PROVIDER_STORE + '" provider is registered');
|
|
85
|
+
this.assertMarkerStore();
|
|
86
|
+
}
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (this.providerName !== '')
|
|
90
|
+
return;
|
|
91
|
+
const names = this.ctx.evolutionStateStorage.providerNames();
|
|
92
|
+
if (names.length <= 1)
|
|
93
|
+
return;
|
|
94
|
+
throw new Error('evolution-state: ' + String(names.length) + ' state providers are registered (' + names.join(', ')
|
|
95
|
+
+ ') and this row pins none, so the effective medium would be registration order — a silent'
|
|
96
|
+
+ ' rebind that leaves existing state on disk and unreadable. Pin one: provider: <name>.');
|
|
97
|
+
}
|
|
98
|
+
/** `auto` is the migration switch: the marker is the explicit one-way signal. */
|
|
99
|
+
autoProviderName() {
|
|
100
|
+
const names = this.ctx.evolutionStateStorage.providerNames();
|
|
101
|
+
const marker = join(this.home, 'state', STATE_MIGRATION_MARKER);
|
|
102
|
+
if (existsSync(marker)) {
|
|
103
|
+
// Full image validation: size alone lets a whitespace/truncated file pass.
|
|
104
|
+
this.assertMarkerStore();
|
|
105
|
+
return PROVIDER_STORE;
|
|
106
|
+
}
|
|
107
|
+
if (names.includes(PROVIDER_DOMAIN))
|
|
108
|
+
return PROVIDER_DOMAIN;
|
|
109
|
+
throw new Error('evolution-state: auto has no migration marker and no "' + PROVIDER_DOMAIN + '" provider; refusing to guess a state authority');
|
|
110
|
+
}
|
|
111
|
+
/** Validate synchronously (legacy callers rely on a throw, not a rejected promise). */
|
|
112
|
+
assertResolvable() {
|
|
113
|
+
this.assertProviderChoice();
|
|
114
|
+
if (this.providerName !== '' && this.providerName !== 'auto') {
|
|
115
|
+
// Throws synchronously for an unknown/absent pinned provider; the mount-time
|
|
116
|
+
// check stays lazy only while the registry is empty.
|
|
117
|
+
this.ctx.evolutionStateStorage.provider(this.providerName);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Validate, then serialize against migration across processes. */
|
|
121
|
+
run(task) {
|
|
122
|
+
this.assertResolvable();
|
|
123
|
+
return this.withStateLock(task);
|
|
124
|
+
}
|
|
125
|
+
/** Serialize state operations against the migration command across processes. */
|
|
126
|
+
async withStateLock(task) {
|
|
127
|
+
await mkdir(this.home, { recursive: true });
|
|
128
|
+
return withFileLock(join(this.home, 'state.lock'), task);
|
|
129
|
+
}
|
|
130
|
+
storage() {
|
|
131
|
+
this.assertProviderChoice();
|
|
132
|
+
const name = this.providerName === 'auto' ? this.autoProviderName() : this.providerName;
|
|
133
|
+
return this.ctx.evolutionStateStorage.provider(name || undefined);
|
|
134
|
+
}
|
|
135
|
+
/** A2: refresh the mounted provider before a decision reads pending state. */
|
|
136
|
+
reload() {
|
|
137
|
+
return this.run(async () => this.storage().reload?.() ?? Promise.resolve());
|
|
138
|
+
}
|
|
139
|
+
loadReviewState(sessionId) {
|
|
140
|
+
return this.run(async () => this.storage().loadReviewState(sessionId));
|
|
141
|
+
}
|
|
142
|
+
saveReviewState(sessionId, record) {
|
|
143
|
+
return this.run(async () => this.storage().saveReviewState(sessionId, record));
|
|
144
|
+
}
|
|
145
|
+
loadCuratorState() {
|
|
146
|
+
return this.run(async () => this.storage().loadCuratorState());
|
|
147
|
+
}
|
|
148
|
+
saveCuratorState(record) {
|
|
149
|
+
return this.run(async () => this.storage().saveCuratorState(record));
|
|
150
|
+
}
|
|
151
|
+
/** Atomic read-modify-write the curator-state record (S5.5): `task` returns
|
|
152
|
+
* the next record; returning null keeps the current record unchanged (the
|
|
153
|
+
* seam has no delete semantic). */
|
|
154
|
+
transactCuratorState(task) {
|
|
155
|
+
return this.run(async () => this.storage().transactCuratorState(task));
|
|
156
|
+
}
|
|
157
|
+
listPending(status = 'pending') {
|
|
158
|
+
return this.run(async () => this.storage().listPending(status));
|
|
159
|
+
}
|
|
160
|
+
savePending(record) {
|
|
161
|
+
return this.run(async () => this.storage().savePending(record));
|
|
162
|
+
}
|
|
163
|
+
tryResolvePending(id, status, expectedClaimId) {
|
|
164
|
+
return this.run(async () => this.storage().tryResolvePending(id, status, expectedClaimId));
|
|
165
|
+
}
|
|
166
|
+
claimPending(id, claimId) {
|
|
167
|
+
return this.run(async () => this.storage().claimPending(id, claimId));
|
|
168
|
+
}
|
|
169
|
+
releasePendingClaim(id, claimId) {
|
|
170
|
+
return this.run(async () => this.storage().releasePendingClaim(id, claimId));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
export default EvolutionState;
|
|
174
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G2b/2b.3: which medium carries each record type, and what PROCESS SCOPE that medium actually gives.
|
|
3
|
+
*
|
|
4
|
+
* The shipped IO backend declares single-process: its transaction serializes one process only.
|
|
5
|
+
* The domain medium inherits whatever backend the platform storage facility routes, and that is also
|
|
6
|
+
* single-process in this tree. This file states the weaker truth. processScopeViolations takes the io the
|
|
7
|
+
* provider writes through and reports every claim of cross-process that the io cannot back up.
|
|
8
|
+
*
|
|
9
|
+
* MIGRATION NOTE: when a platform backend carrying its own cross-process guarantee lands, name it here and
|
|
10
|
+
* move the reasoning with it - one declaration, not two.
|
|
11
|
+
*
|
|
12
|
+
* @module @lmzhen/dsh-evolution-core/state/storage/medium-declaration
|
|
13
|
+
*/
|
|
14
|
+
/** One record type: its medium, the process scope claimed for it, and why that is true. */
|
|
15
|
+
export interface MediumProcessClaim {
|
|
16
|
+
/** The record family, named as the domain declares it. */
|
|
17
|
+
readonly record: string;
|
|
18
|
+
readonly medium: 'json' | 'domain';
|
|
19
|
+
/** cross-process is a CLAIM: processScopeViolations refuses it without a backing transact. */
|
|
20
|
+
readonly scope: 'cross-process' | 'single-process';
|
|
21
|
+
readonly because: string;
|
|
22
|
+
}
|
|
23
|
+
/** The declaration. */
|
|
24
|
+
export declare const MEDIUM_PROCESS_DECLARATION: readonly MediumProcessClaim[];
|
|
25
|
+
/** The capability the claims are checked against: the io the medium writes through. */
|
|
26
|
+
export interface ProcessScopeProbe {
|
|
27
|
+
/** The scope the backend actually declares; `transact` alone is not proof. */
|
|
28
|
+
readonly processScope?: 'single-process' | 'cross-process' | undefined;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Falsify the declaration against a capability reading.
|
|
32
|
+
* @param io - the io backend the medium writes through, or undefined when none is mounted.
|
|
33
|
+
* @param declaration - claims to falsify; defaults to the shipped declaration.
|
|
34
|
+
* @returns one message per claim the capability cannot back up; empty when every claim holds.
|
|
35
|
+
*/
|
|
36
|
+
export declare function processScopeViolations(io: ProcessScopeProbe | undefined, declaration?: readonly MediumProcessClaim[]): readonly string[];
|
|
37
|
+
//# sourceMappingURL=medium-declaration.d.ts.map
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* G2b/2b.3: which medium carries each record type, and what PROCESS SCOPE that medium actually gives.
|
|
3
|
+
*
|
|
4
|
+
* The shipped IO backend declares single-process: its transaction serializes one process only.
|
|
5
|
+
* The domain medium inherits whatever backend the platform storage facility routes, and that is also
|
|
6
|
+
* single-process in this tree. This file states the weaker truth. processScopeViolations takes the io the
|
|
7
|
+
* provider writes through and reports every claim of cross-process that the io cannot back up.
|
|
8
|
+
*
|
|
9
|
+
* MIGRATION NOTE: when a platform backend carrying its own cross-process guarantee lands, name it here and
|
|
10
|
+
* move the reasoning with it - one declaration, not two.
|
|
11
|
+
*
|
|
12
|
+
* @module @lmzhen/dsh-evolution-core/state/storage/medium-declaration
|
|
13
|
+
*/
|
|
14
|
+
/** The declaration. */
|
|
15
|
+
export const MEDIUM_PROCESS_DECLARATION = [
|
|
16
|
+
{
|
|
17
|
+
record: 'review_state',
|
|
18
|
+
medium: 'json',
|
|
19
|
+
scope: 'single-process',
|
|
20
|
+
because: 'the shipped IO backend declares single-process; no cross-process medium exists in this tree',
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
record: 'curator_state',
|
|
24
|
+
medium: 'json',
|
|
25
|
+
scope: 'single-process',
|
|
26
|
+
because: 'same provider and same single-process write path as review_state',
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
record: 'pending',
|
|
30
|
+
medium: 'json',
|
|
31
|
+
scope: 'single-process',
|
|
32
|
+
because: 'the shipped IO backend has no cross-process claim primitive; a staged write is serialized only in-process',
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
record: 'evolution-domain',
|
|
36
|
+
medium: 'domain',
|
|
37
|
+
scope: 'single-process',
|
|
38
|
+
because: 'no backend in this tree carries its own cross-process guarantee and none is named, so the domain facility lock semantics stay the backend business and this declares the weaker truth',
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
/**
|
|
42
|
+
* Falsify the declaration against a capability reading.
|
|
43
|
+
* @param io - the io backend the medium writes through, or undefined when none is mounted.
|
|
44
|
+
* @param declaration - claims to falsify; defaults to the shipped declaration.
|
|
45
|
+
* @returns one message per claim the capability cannot back up; empty when every claim holds.
|
|
46
|
+
*/
|
|
47
|
+
export function processScopeViolations(io, declaration = MEDIUM_PROCESS_DECLARATION) {
|
|
48
|
+
const backed = io?.processScope === 'cross-process';
|
|
49
|
+
return declaration
|
|
50
|
+
.filter(claim => claim.scope === 'cross-process' && !backed)
|
|
51
|
+
.map(claim => claim.record + ' claims cross-process (' + claim.because + ') but the mounted io declares ' + (io?.processScope ?? 'no process scope'));
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=medium-declaration.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Explicit one-way migration: old storage-domain tables → file StateStore.
|
|
3
|
+
*
|
|
4
|
+
* This module is intentionally NOT a compatibility reader. It runs once, writes a
|
|
5
|
+
* complete snapshot with create-if-absent, leaves the domain data untouched, and
|
|
6
|
+
* writes a marker. Rolling back is switching the provider back to `domain`.
|
|
7
|
+
* @module @lmzhen/dsh-evolution-core/state/migrate
|
|
8
|
+
*/
|
|
9
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
10
|
+
import type { EvolutionIoLike } from '../io.ts';
|
|
11
|
+
import { STATE_MIGRATION_MARKER } from './index.ts';
|
|
12
|
+
export interface StateMigrationOptions {
|
|
13
|
+
readonly io: EvolutionIoLike;
|
|
14
|
+
/** Evolution home; defaults to `evolutionHome()`. */
|
|
15
|
+
readonly home?: string;
|
|
16
|
+
/** Count and validate only; write neither store nor marker. */
|
|
17
|
+
readonly dryRun?: boolean;
|
|
18
|
+
readonly now?: () => number;
|
|
19
|
+
}
|
|
20
|
+
export interface StateMigrationResult {
|
|
21
|
+
readonly reviewSessions: number;
|
|
22
|
+
readonly pending: number;
|
|
23
|
+
readonly curator: boolean;
|
|
24
|
+
readonly path: string;
|
|
25
|
+
readonly dryRun: boolean;
|
|
26
|
+
}
|
|
27
|
+
export { STATE_MIGRATION_MARKER };
|
|
28
|
+
/**
|
|
29
|
+
* Public entry: hold the same cross-process state.lock every EvolutionState
|
|
30
|
+
* operation holds, so no state write can interleave between the snapshot read
|
|
31
|
+
* and the marker publish.
|
|
32
|
+
*/
|
|
33
|
+
export declare function migrateDomainToStore(ctx: Context, options: StateMigrationOptions): Promise<StateMigrationResult>;
|
|
34
|
+
//# sourceMappingURL=migrate.d.ts.map
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Explicit one-way migration: old storage-domain tables → file StateStore.
|
|
3
|
+
*
|
|
4
|
+
* This module is intentionally NOT a compatibility reader. It runs once, writes a
|
|
5
|
+
* complete snapshot with create-if-absent, leaves the domain data untouched, and
|
|
6
|
+
* writes a marker. Rolling back is switching the provider back to `domain`.
|
|
7
|
+
* @module @lmzhen/dsh-evolution-core/state/migrate
|
|
8
|
+
*/
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { mkdir } from 'node:fs/promises';
|
|
11
|
+
import { storageDomainPort } from '@lmzhen/dsh-evolution-platform/ports';
|
|
12
|
+
import { withFileLock } from '@lmzhen/dsh-evolution-platform/values/fs';
|
|
13
|
+
import { evolutionHome } from "../state-store.js";
|
|
14
|
+
import { writeStateStoreSnapshot } from "./store.js";
|
|
15
|
+
import { EVOLUTION_DOMAIN } from "./domain/index.js";
|
|
16
|
+
import { CURATOR_STATE_KEY, STATE_MIGRATION_MARKER, CURATOR_STATE_TABLE, PENDING_TABLE, REVIEW_STATE_TABLE, PENDING_STATUSES, } from "./index.js";
|
|
17
|
+
export { STATE_MIGRATION_MARKER };
|
|
18
|
+
/**
|
|
19
|
+
* Migrate the three state tables. The store file is published with
|
|
20
|
+
* create-if-absent, so a stale rerun cannot overwrite a newer store.
|
|
21
|
+
*/
|
|
22
|
+
async function migrateDomainToStoreUnlocked(ctx, options) {
|
|
23
|
+
const home = options.home ?? evolutionHome();
|
|
24
|
+
const storePath = join(home, 'state', 'store.json');
|
|
25
|
+
const markerPath = join(home, 'state', STATE_MIGRATION_MARKER);
|
|
26
|
+
const io = options.io;
|
|
27
|
+
if (await io.exists(storePath)) {
|
|
28
|
+
throw new Error('evolution-state-migrate: store already exists; refusing to overwrite it: ' + storePath);
|
|
29
|
+
}
|
|
30
|
+
// Prefer the provider that is already mounted: the host normally has the
|
|
31
|
+
// domain row mounted, and opening the same KV domain a second time fails with
|
|
32
|
+
// already-open. The optional listReviewStates() is the migration read; the
|
|
33
|
+
// fallback is for a host that runs the migration before the state row mounts.
|
|
34
|
+
const mounted = ctx.evolutionStateStorage?.provider?.('domain');
|
|
35
|
+
let review = {};
|
|
36
|
+
let pending = {};
|
|
37
|
+
let curator = null;
|
|
38
|
+
if (mounted?.listReviewStates !== undefined) {
|
|
39
|
+
// The mounted provider is authoritative in memory; another host may have
|
|
40
|
+
// written since its last open. Refresh under the same state lock before the
|
|
41
|
+
// snapshot, otherwise the store is built from a stale domain cache.
|
|
42
|
+
await mounted.reload?.();
|
|
43
|
+
for (const row of await mounted.listReviewStates())
|
|
44
|
+
review[row.sessionId] = row.record;
|
|
45
|
+
for (const status of PENDING_STATUSES) {
|
|
46
|
+
for (const record of await mounted.listPending(status))
|
|
47
|
+
if (pending[record.id] === undefined)
|
|
48
|
+
pending[record.id] = record;
|
|
49
|
+
}
|
|
50
|
+
curator = await mounted.loadCuratorState();
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
const facility = storageDomainPort(ctx);
|
|
54
|
+
if (!facility)
|
|
55
|
+
throw new Error('evolution-state-migrate: @deepseek-ai/dsh-storage-domain is not mounted');
|
|
56
|
+
const domain = await facility.open(EVOLUTION_DOMAIN);
|
|
57
|
+
try {
|
|
58
|
+
review = Object.fromEntries([...domain.table(REVIEW_STATE_TABLE).entries()]);
|
|
59
|
+
pending = {};
|
|
60
|
+
for (const [key, record] of domain.table(PENDING_TABLE).entries()) {
|
|
61
|
+
if (pending[record.id] === undefined)
|
|
62
|
+
pending[record.id] = record;
|
|
63
|
+
else if (key === record.id)
|
|
64
|
+
pending[record.id] = record;
|
|
65
|
+
}
|
|
66
|
+
const curated = domain.table(CURATOR_STATE_TABLE).get(CURATOR_STATE_KEY);
|
|
67
|
+
curator = curated === undefined ? null : curated;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await domain.close();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const result = {
|
|
74
|
+
reviewSessions: Object.keys(review).length,
|
|
75
|
+
pending: Object.keys(pending).length,
|
|
76
|
+
curator: curator !== null,
|
|
77
|
+
path: storePath,
|
|
78
|
+
dryRun: options.dryRun === true,
|
|
79
|
+
};
|
|
80
|
+
if (options.dryRun === true)
|
|
81
|
+
return result;
|
|
82
|
+
await writeStateStoreSnapshot(io, storePath, { review, curator, pending });
|
|
83
|
+
await io.writeText(markerPath, JSON.stringify({
|
|
84
|
+
migratedAt: new Date(options.now?.() ?? Date.now()).toISOString(),
|
|
85
|
+
source: 'domain',
|
|
86
|
+
target: 'store',
|
|
87
|
+
reviewSessions: result.reviewSessions,
|
|
88
|
+
pending: result.pending,
|
|
89
|
+
curator: result.curator,
|
|
90
|
+
}, null, 2) + '\n');
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Public entry: hold the same cross-process state.lock every EvolutionState
|
|
95
|
+
* operation holds, so no state write can interleave between the snapshot read
|
|
96
|
+
* and the marker publish.
|
|
97
|
+
*/
|
|
98
|
+
export async function migrateDomainToStore(ctx, options) {
|
|
99
|
+
const home = options.home ?? evolutionHome();
|
|
100
|
+
await mkdir(home, { recursive: true });
|
|
101
|
+
return withFileLock(join(home, 'state.lock'), () => migrateDomainToStoreUnlocked(ctx, { ...options, home }));
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=migrate.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Record contract of the three seam tables (P2-12/14/15/16/18, v19).
|
|
3
|
+
*
|
|
4
|
+
* The contract belongs to the SEAM, not to each provider: before this module
|
|
5
|
+
* the json provider gated writes with plain field predicates while the domain
|
|
6
|
+
* provider relied on its zod schemas, so the same consumer code behaved
|
|
7
|
+
* differently per medium — `transactCuratorState` skipped validation entirely
|
|
8
|
+
* on domain, unknown fields were stripped by zod but preserved by json,
|
|
9
|
+
* `args` was shared by reference on domain, and a non-cloneable payload
|
|
10
|
+
* poisoned every later read. Both providers now call these functions.
|
|
11
|
+
*
|
|
12
|
+
* @module @lmzhen/dsh-evolution-core/state/storage/src/record-contract
|
|
13
|
+
*/
|
|
14
|
+
import { CURATOR_STATE_TABLE, PENDING_TABLE, REVIEW_STATE_TABLE } from './constants.ts';
|
|
15
|
+
import type { PendingKind, PendingStatus } from '../contract.ts';
|
|
16
|
+
export type { PendingKind, PendingStatus } from '../contract.ts';
|
|
17
|
+
/** The three seam tables a record can belong to. */
|
|
18
|
+
export type SeamRecordTable = typeof REVIEW_STATE_TABLE | typeof CURATOR_STATE_TABLE | typeof PENDING_TABLE;
|
|
19
|
+
/** 0.3.17 (S3.5, D-4): 'skill_batch' is gone — nothing ever created one (a dead enum member). A
|
|
20
|
+
* historic value, if it ever reached disk, is read as an unknown kind by consumers rather than
|
|
21
|
+
* minted here.
|
|
22
|
+
*
|
|
23
|
+
* 0.3.66: 'capability' stays with NO producer — the evolution-capability adapter was removed. It is
|
|
24
|
+
* a read-compatibility member: state written by an install that used that adapter (≤0.3.65) still
|
|
25
|
+
* holds such records, and they must keep loading, listing in `/evolution pending`, and answering
|
|
26
|
+
* approve or reject. Dropping it would strand them two ways: json quarantines the row to
|
|
27
|
+
* `<file>.corrupt` and refuses the resolving write, while the domain provider validates every
|
|
28
|
+
* stored record at mount, so one such row fails the whole domain with `invalid-record`.
|
|
29
|
+
*
|
|
30
|
+
* S2.9/1-10: this array is the ONE source of the vocabulary — the types, the write gate below and
|
|
31
|
+
* the domain provider's schema all derive from it. A second literal copy is the E-10 drift class
|
|
32
|
+
* this module exists to end. */
|
|
33
|
+
export declare const PENDING_KINDS: readonly PendingKind[];
|
|
34
|
+
/** 0.3.17 (S3.3, E-24): 'executing' = claimed, runner in flight — a fresh claim only takes
|
|
35
|
+
* 'pending', and resolve accepts 'pending'/'executing', so a crash mid-approve can never
|
|
36
|
+
* double-execute the runner. Same one-source rule as PENDING_KINDS. */
|
|
37
|
+
export declare const PENDING_STATUSES: readonly PendingStatus[];
|
|
38
|
+
/**
|
|
39
|
+
* The write gate for one record. Both providers call this before persisting,
|
|
40
|
+
* so a record the other provider would refuse can never land.
|
|
41
|
+
* @param table - the seam table the record belongs to.
|
|
42
|
+
* @param record - the candidate record.
|
|
43
|
+
* @returns a human-readable issue, or null when the record is well-formed.
|
|
44
|
+
*/
|
|
45
|
+
export declare function recordIssue(table: SeamRecordTable, record: unknown): string | null;
|
|
46
|
+
/**
|
|
47
|
+
* P2-15 (v19): the value must survive the seam's copy discipline. A payload
|
|
48
|
+
* that cannot be structured-cloned (functions, symbols, class instances with
|
|
49
|
+
* private state) would make every later read throw far away from the write.
|
|
50
|
+
* @param record - the candidate record.
|
|
51
|
+
* @returns a human-readable issue, or null when the value is cloneable.
|
|
52
|
+
*/
|
|
53
|
+
export declare function assertCloneable(record: unknown): string | null;
|
|
54
|
+
/** Deep copy for every boundary crossing (read AND write). @param record - the value to copy. @returns an independent deep copy. */
|
|
55
|
+
export declare function cloneRecord<T>(record: T): T;
|
|
56
|
+
//# sourceMappingURL=record-contract.d.ts.map
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Record contract of the three seam tables (P2-12/14/15/16/18, v19).
|
|
3
|
+
*
|
|
4
|
+
* The contract belongs to the SEAM, not to each provider: before this module
|
|
5
|
+
* the json provider gated writes with plain field predicates while the domain
|
|
6
|
+
* provider relied on its zod schemas, so the same consumer code behaved
|
|
7
|
+
* differently per medium — `transactCuratorState` skipped validation entirely
|
|
8
|
+
* on domain, unknown fields were stripped by zod but preserved by json,
|
|
9
|
+
* `args` was shared by reference on domain, and a non-cloneable payload
|
|
10
|
+
* poisoned every later read. Both providers now call these functions.
|
|
11
|
+
*
|
|
12
|
+
* @module @lmzhen/dsh-evolution-core/state/storage/src/record-contract
|
|
13
|
+
*/
|
|
14
|
+
import { CURATOR_STATE_TABLE, REVIEW_STATE_TABLE } from "./constants.js";
|
|
15
|
+
const isNonNegInt = (value) => typeof value === 'number' && Number.isInteger(value) && value >= 0;
|
|
16
|
+
const optionalString = (value) => value === undefined || typeof value === 'string';
|
|
17
|
+
/** 0.3.17 (S3.5, D-4): 'skill_batch' is gone — nothing ever created one (a dead enum member). A
|
|
18
|
+
* historic value, if it ever reached disk, is read as an unknown kind by consumers rather than
|
|
19
|
+
* minted here.
|
|
20
|
+
*
|
|
21
|
+
* 0.3.66: 'capability' stays with NO producer — the evolution-capability adapter was removed. It is
|
|
22
|
+
* a read-compatibility member: state written by an install that used that adapter (≤0.3.65) still
|
|
23
|
+
* holds such records, and they must keep loading, listing in `/evolution pending`, and answering
|
|
24
|
+
* approve or reject. Dropping it would strand them two ways: json quarantines the row to
|
|
25
|
+
* `<file>.corrupt` and refuses the resolving write, while the domain provider validates every
|
|
26
|
+
* stored record at mount, so one such row fails the whole domain with `invalid-record`.
|
|
27
|
+
*
|
|
28
|
+
* S2.9/1-10: this array is the ONE source of the vocabulary — the types, the write gate below and
|
|
29
|
+
* the domain provider's schema all derive from it. A second literal copy is the E-10 drift class
|
|
30
|
+
* this module exists to end. */
|
|
31
|
+
export const PENDING_KINDS = ['memory', 'skill', 'capability'];
|
|
32
|
+
/** 0.3.17 (S3.3, E-24): 'executing' = claimed, runner in flight — a fresh claim only takes
|
|
33
|
+
* 'pending', and resolve accepts 'pending'/'executing', so a crash mid-approve can never
|
|
34
|
+
* double-execute the runner. Same one-source rule as PENDING_KINDS. */
|
|
35
|
+
export const PENDING_STATUSES = ['pending', 'executing', 'approved', 'rejected'];
|
|
36
|
+
/** Membership test for the write gate (per record per write, so the Set is worth it). */
|
|
37
|
+
const PENDING_KIND_SET = new Set(PENDING_KINDS);
|
|
38
|
+
/** Membership test for the write gate. */
|
|
39
|
+
const PENDING_STATUS_SET = new Set(PENDING_STATUSES);
|
|
40
|
+
/**
|
|
41
|
+
* The write gate for one record. Both providers call this before persisting,
|
|
42
|
+
* so a record the other provider would refuse can never land.
|
|
43
|
+
* @param table - the seam table the record belongs to.
|
|
44
|
+
* @param record - the candidate record.
|
|
45
|
+
* @returns a human-readable issue, or null when the record is well-formed.
|
|
46
|
+
*/
|
|
47
|
+
export function recordIssue(table, record) {
|
|
48
|
+
if (record === null || typeof record !== 'object' || Array.isArray(record))
|
|
49
|
+
return 'record must be a plain object';
|
|
50
|
+
const value = record;
|
|
51
|
+
if (table === REVIEW_STATE_TABLE) {
|
|
52
|
+
if (!isNonNegInt(value.turnsSinceMemory))
|
|
53
|
+
return 'turnsSinceMemory must be a non-negative integer';
|
|
54
|
+
if (!isNonNegInt(value.turnsSinceSkill))
|
|
55
|
+
return 'turnsSinceSkill must be a non-negative integer';
|
|
56
|
+
if (!isNonNegInt(value.lastTurn))
|
|
57
|
+
return 'lastTurn must be a non-negative integer';
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
if (table === CURATOR_STATE_TABLE) {
|
|
61
|
+
if (value.schemaVersion !== undefined && !isNonNegInt(value.schemaVersion))
|
|
62
|
+
return 'schemaVersion must be a non-negative integer when present';
|
|
63
|
+
if (typeof value.lastRunAt !== 'number' || !Number.isFinite(value.lastRunAt) || value.lastRunAt < 0)
|
|
64
|
+
return 'lastRunAt must be a finite non-negative number';
|
|
65
|
+
if (!isNonNegInt(value.runCount))
|
|
66
|
+
return 'runCount must be a non-negative integer';
|
|
67
|
+
if (typeof value.lastSummary !== 'string')
|
|
68
|
+
return 'lastSummary must be a string';
|
|
69
|
+
if (typeof value.paused !== 'boolean')
|
|
70
|
+
return 'paused must be a boolean';
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
if (typeof value.id !== 'string')
|
|
74
|
+
return 'id must be a string';
|
|
75
|
+
if (typeof value.kind !== 'string' || !PENDING_KIND_SET.has(value.kind))
|
|
76
|
+
return `kind must be ${PENDING_KINDS.join('|')}`;
|
|
77
|
+
if (typeof value.summary !== 'string')
|
|
78
|
+
return 'summary must be a string';
|
|
79
|
+
if (!Object.prototype.hasOwnProperty.call(value, 'args'))
|
|
80
|
+
return 'args key is required (may be any cloneable value)';
|
|
81
|
+
// V24-06 (v24): the key-present-but-undefined shape passes this gate, but
|
|
82
|
+
// the json medium persists through JSON.stringify — which DROPS an
|
|
83
|
+
// undefined-valued key — so the record would fail this same gate on the
|
|
84
|
+
// next read, be quarantined, and the staged write would silently vanish
|
|
85
|
+
// from the approval view. `undefined` is the ONE uncloneable-ish value that
|
|
86
|
+
// slipped past `assertCloneable` (structuredClone accepts it); refuse it at
|
|
87
|
+
// the write gate so both media agree and the caller learns immediately.
|
|
88
|
+
if (value.args === undefined)
|
|
89
|
+
return 'args must be a cloneable value — `undefined` is dropped by the json medium and the record would be unreadable after a restart (pass {} instead)';
|
|
90
|
+
if (typeof value.createdAt !== 'string')
|
|
91
|
+
return 'createdAt must be a string';
|
|
92
|
+
if (typeof value.status !== 'string' || !PENDING_STATUS_SET.has(value.status))
|
|
93
|
+
return `status must be ${PENDING_STATUSES.join('|')}`;
|
|
94
|
+
for (const field of ['resolvedAt', 'claimedBy', 'claimedAt', 'origin', 'sessionId']) {
|
|
95
|
+
if (!optionalString(value[field]))
|
|
96
|
+
return `${field} must be a string when present`;
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* P2-15 (v19): the value must survive the seam's copy discipline. A payload
|
|
102
|
+
* that cannot be structured-cloned (functions, symbols, class instances with
|
|
103
|
+
* private state) would make every later read throw far away from the write.
|
|
104
|
+
* @param record - the candidate record.
|
|
105
|
+
* @returns a human-readable issue, or null when the value is cloneable.
|
|
106
|
+
*/
|
|
107
|
+
export function assertCloneable(record) {
|
|
108
|
+
try {
|
|
109
|
+
structuredClone(record);
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
return `record is not structured-cloneable (${error instanceof Error ? error.message : String(error)})`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Deep copy for every boundary crossing (read AND write). @param record - the value to copy. @returns an independent deep copy. */
|
|
117
|
+
export function cloneRecord(record) {
|
|
118
|
+
return structuredClone(record);
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=record-contract.js.map
|