@lmzhen/dsh-evolution-core 0.39.2 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.js +3544 -3112
- package/lib/platform/index.js +2 -2
- package/lib/{platform-Be-_wSVz.js → platform-CFp373_0.js} +3 -1
- package/lib/runtime/plugin.js +1 -1
- package/lib/types/events.d.ts +1 -1
- package/lib/types/evolution-events.d.ts +3 -1
- package/lib/types/evolution-events.js +65 -59
- package/lib/types/home-fence.d.ts +24 -0
- package/lib/types/home-fence.js +62 -0
- package/lib/types/home-owner.d.ts +4 -0
- package/lib/types/home-owner.js +37 -0
- package/lib/types/index.d.ts +4 -0
- package/lib/types/index.js +4 -0
- package/lib/types/lease-store.d.ts +55 -0
- package/lib/types/lease-store.js +116 -0
- package/lib/types/memory-store.d.ts +6 -0
- package/lib/types/memory-store.js +16 -8
- package/lib/types/mutation-authority.d.ts +59 -0
- package/lib/types/mutation-authority.js +126 -0
- package/lib/types/mutation-storage-adapter.js +7 -3
- package/lib/types/mutation-unit.d.ts +13 -0
- package/lib/types/mutation-unit.js +7 -2
- package/lib/types/mutations.d.ts +3 -1
- package/lib/types/mutations.js +40 -34
- package/lib/types/platform/index.d.ts +5 -2
- package/lib/types/platform/index.js +2 -0
- package/lib/types/platform-services.js +1 -0
- package/lib/types/proposal-report.d.ts +1 -0
- package/lib/types/proposal-report.js +12 -0
- package/lib/types/run-registry.d.ts +4 -0
- package/lib/types/run-registry.js +10 -3
- package/lib/types/skill-history.d.ts +4 -1
- package/lib/types/skill-history.js +24 -29
- package/lib/types/skill-store.d.ts +11 -3
- package/lib/types/skill-store.js +26 -12
- package/lib/types/unit-storage.d.ts +2 -0
- package/lib/types/unit-transaction.d.ts +6 -1
- package/lib/types/unit-transaction.js +20 -6
- package/lib/types/usage.d.ts +4 -0
- package/lib/types/usage.js +84 -78
- package/package.json +2 -2
- package/persisted-write-inventory.json +9 -0
package/lib/platform/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { t as presetsPort } from "../presets-C8vuCuNA.js";
|
|
2
|
-
import { a as
|
|
2
|
+
import { a as defineTool, c as modelRoute, i as createUserMessage, l as projectionPort, n as SessionId, o as EvolutionLlmError, r as createToolResultMessage, s as llmPort, t as BlockAssembler } from "../platform-CFp373_0.js";
|
|
3
3
|
import { n as toolsPort, t as registerEvolutionTool } from "../tools-DzcNFex2.js";
|
|
4
|
-
export { EvolutionLlmError, defineTool, llmPort, modelRoute, presetsPort, projectionPort, registerEvolutionTool, toolsPort };
|
|
4
|
+
export { BlockAssembler, EvolutionLlmError, SessionId, createToolResultMessage, createUserMessage, defineTool, llmPort, modelRoute, presetsPort, projectionPort, registerEvolutionTool, toolsPort };
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
2
|
+
import { BlockAssembler, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
2
4
|
//#region lib/types/platform/projections.js
|
|
3
5
|
function isCallableThenable(value) {
|
|
4
6
|
return typeof value === "function" && typeof value.then === "function";
|
|
@@ -110,4 +112,4 @@ function modelRoute(ctx, agent, session) {
|
|
|
110
112
|
};
|
|
111
113
|
}
|
|
112
114
|
//#endregion
|
|
113
|
-
export {
|
|
115
|
+
export { defineTool as a, modelRoute as c, createUserMessage as i, projectionPort as l, SessionId as n, EvolutionLlmError as o, createToolResultMessage as r, llmPort as s, BlockAssembler as t };
|
package/lib/runtime/plugin.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-CXUNPkq9.js";
|
|
2
2
|
import { t as presetsPort } from "../presets-C8vuCuNA.js";
|
|
3
|
-
import {
|
|
3
|
+
import { c as modelRoute, l as projectionPort, o as EvolutionLlmError, s as llmPort } from "../platform-CFp373_0.js";
|
|
4
4
|
import { n as toolsPort } from "../tools-DzcNFex2.js";
|
|
5
5
|
import { Service } from "@deepseek-ai/cordis";
|
|
6
6
|
//#region lib/types/runtime/llm.js
|
package/lib/types/events.d.ts
CHANGED
|
@@ -38,7 +38,7 @@ export interface EvolutionReviewAction {
|
|
|
38
38
|
readonly type: 'skill' | 'memory' | 'tool';
|
|
39
39
|
readonly action: string;
|
|
40
40
|
readonly target: string;
|
|
41
|
-
readonly status: 'ok' | 'error';
|
|
41
|
+
readonly status: 'ok' | 'staged' | 'error';
|
|
42
42
|
readonly revision?: string | undefined;
|
|
43
43
|
readonly summary?: string | undefined;
|
|
44
44
|
}
|
|
@@ -123,7 +123,9 @@ export declare function listEventArchives(io: EvolutionIoLike, path: string): Pr
|
|
|
123
123
|
* — the active restarts AFTER the highest archived seq, never at 1, so a new
|
|
124
124
|
* event can never shadow an archived one in the seq-deduped timeline.
|
|
125
125
|
*/
|
|
126
|
-
export declare function appendEvolutionEvent(io: EvolutionIoLike, path: string, event: EvolutionEventInput, rotateAt?: number
|
|
126
|
+
export declare function appendEvolutionEvent(io: EvolutionIoLike, path: string, event: EvolutionEventInput, rotateAt?: number, fence?: {
|
|
127
|
+
run<T>(body: () => Promise<T>): Promise<T>;
|
|
128
|
+
}): Promise<number>;
|
|
127
129
|
/**
|
|
128
130
|
* Prune old event archives (rc.71): keep the newest `EVENT_LOG_RETAIN_ARCHIVES`.
|
|
129
131
|
* The name's numeric part is the last archived seq, so ordering is NUMERIC —
|
|
@@ -176,7 +176,7 @@ export async function listEventArchives(io, path) {
|
|
|
176
176
|
* — the active restarts AFTER the highest archived seq, never at 1, so a new
|
|
177
177
|
* event can never shadow an archived one in the seq-deduped timeline.
|
|
178
178
|
*/
|
|
179
|
-
export async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG_ROTATE_AT) {
|
|
179
|
+
export async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG_ROTATE_AT, fence) {
|
|
180
180
|
// I-5 (v18): refuse an unfoldable record at the durable write boundary.
|
|
181
181
|
const issue = evolutionEventPayloadIssue(event);
|
|
182
182
|
if (issue !== null)
|
|
@@ -190,68 +190,74 @@ export async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG
|
|
|
190
190
|
// C-06 (v10 audit): the shape parse below is REUSED for the event list via
|
|
191
191
|
// v1EventRecords — the body used to be JSON.parsed twice per append.
|
|
192
192
|
let parsedBody = null;
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
193
|
+
const write = async () => {
|
|
194
|
+
await transactIo(io, path, async (current) => {
|
|
195
|
+
// A10 (audit P2-14): the lock layer is contractually allowed to re-invoke
|
|
196
|
+
// this task whole (a LostWriteLock converts into a full read-modify-write
|
|
197
|
+
// retry). Closure state captured during a PREVIOUS attempt must reset
|
|
198
|
+
// first, or a log that vanished/was emptied between attempts would skip
|
|
199
|
+
// the re-parse below and fold rotation from the stale previous parse.
|
|
200
|
+
// `assigned` belongs to the same discipline (R2 follow-up): without the
|
|
201
|
+
// reset, attempt 1's seq survives into a refusing attempt 2 and the
|
|
202
|
+
// caller reads a phantom success for an event that never landed.
|
|
203
|
+
parsedBody = null;
|
|
204
|
+
refuseMessage = '';
|
|
205
|
+
assigned = 0;
|
|
206
|
+
// rc.69: a whitespace-only log (crash residue) is rebuildable — treat it
|
|
207
|
+
// as missing; a genuinely corrupt body is still refused.
|
|
208
|
+
if (current !== null && current.trim() !== '') {
|
|
209
|
+
let shape;
|
|
210
|
+
try {
|
|
211
|
+
shape = JSON.parse(current);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return current;
|
|
215
|
+
}
|
|
216
|
+
parsedBody = shape;
|
|
217
|
+
// F-338: a non-v1 body is a FUTURE format. This v1 writer must never
|
|
218
|
+
// rewrite it back down to v1 — refuse and keep the original bytes. (The
|
|
219
|
+
// reader treats it as an empty timeline; only the append refuses.)
|
|
220
|
+
if (shape.version !== undefined && shape.version !== EVENT_LOG_VERSION) {
|
|
221
|
+
const found = typeof shape.version === 'number' || typeof shape.version === 'string' ? String(shape.version) : 'unknown';
|
|
222
|
+
const kind = typeof shape.version === 'number' || typeof shape.version === 'string' ? typeof shape.version : 'unknown';
|
|
223
|
+
// V4-48: a version written as the STRING "1" is statically unequal to
|
|
224
|
+
// the number 1 and is refused, but the old message rendered both as
|
|
225
|
+
// "found 1, expected 1" — type-ambiguous and self-contradictory. Report
|
|
226
|
+
// the type so a manual-editer/heterogeneous writer sees the real cause.
|
|
227
|
+
const rendered = kind === 'string' ? `"${found}"` : found;
|
|
228
|
+
refuseMessage = `evolution event log version mismatch (expected version ${EVENT_LOG_VERSION}, got ${rendered} (${kind})) and was not touched`;
|
|
229
|
+
return current;
|
|
230
|
+
}
|
|
211
231
|
}
|
|
212
|
-
|
|
232
|
+
const rotated = await rotateIfDue(io, path, v1EventRecords(parsedBody), rotateAt);
|
|
233
|
+
if (!rotated.ok) {
|
|
234
|
+
// P2-11: an unmergeable archive collision writes NOTHING — the active
|
|
235
|
+
// keeps the full band and the append reports the refusal.
|
|
236
|
+
refuseMessage = rotated.reason;
|
|
213
237
|
return current;
|
|
214
238
|
}
|
|
215
|
-
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
//
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
refuseMessage = `evolution event log version mismatch (expected version ${EVENT_LOG_VERSION}, got ${rendered} (${kind})) and was not touched`;
|
|
228
|
-
return current;
|
|
239
|
+
const events = rotated.events;
|
|
240
|
+
// P2-1 (v11): a single rotate pass — the second call was either a no-op
|
|
241
|
+
// (production threshold) or a double rotation (small test thresholds).
|
|
242
|
+
// v23 (ML-3): seq continues from the max of BOTH the active file and the
|
|
243
|
+
// archive names. The old `if (maxSeq === 0)` gate only consulted the
|
|
244
|
+
// archives when the active was empty — an active ROLLED BACK to an older
|
|
245
|
+
// backup (manual restore) kept a maxSeq below the archived range, so new
|
|
246
|
+
// events reused archived seqs and the timeline merge's "active wins" rule
|
|
247
|
+
// silently shadowed the archived records.
|
|
248
|
+
let maxSeq = events.reduce((max, entry) => Math.max(max, entry.seq), 0);
|
|
249
|
+
for (const name of await listEventArchives(io, path)) {
|
|
250
|
+
maxSeq = Math.max(maxSeq, Number.parseInt(name.slice(EVENT_ARCHIVE_PREFIX.length, name.length - 5), 10));
|
|
229
251
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
// P2-1 (v11): a single rotate pass — the second call was either a no-op
|
|
240
|
-
// (production threshold) or a double rotation (small test thresholds).
|
|
241
|
-
// v23 (ML-3): seq continues from the max of BOTH the active file and the
|
|
242
|
-
// archive names. The old `if (maxSeq === 0)` gate only consulted the
|
|
243
|
-
// archives when the active was empty — an active ROLLED BACK to an older
|
|
244
|
-
// backup (manual restore) kept a maxSeq below the archived range, so new
|
|
245
|
-
// events reused archived seqs and the timeline merge's "active wins" rule
|
|
246
|
-
// silently shadowed the archived records.
|
|
247
|
-
let maxSeq = events.reduce((max, entry) => Math.max(max, entry.seq), 0);
|
|
248
|
-
for (const name of await listEventArchives(io, path)) {
|
|
249
|
-
maxSeq = Math.max(maxSeq, Number.parseInt(name.slice(EVENT_ARCHIVE_PREFIX.length, name.length - 5), 10));
|
|
250
|
-
}
|
|
251
|
-
const record = { ...event, seq: maxSeq + 1, at: new Date().toISOString() };
|
|
252
|
-
assigned = record.seq;
|
|
253
|
-
return JSON.stringify({ version: EVENT_LOG_VERSION, events: [...events, record] }, null, 2);
|
|
254
|
-
});
|
|
252
|
+
const record = { ...event, seq: maxSeq + 1, at: new Date().toISOString() };
|
|
253
|
+
assigned = record.seq;
|
|
254
|
+
return JSON.stringify({ version: EVENT_LOG_VERSION, events: [...events, record] }, null, 2);
|
|
255
|
+
});
|
|
256
|
+
};
|
|
257
|
+
if (fence !== undefined)
|
|
258
|
+
await fence.run(write);
|
|
259
|
+
else
|
|
260
|
+
await write();
|
|
255
261
|
if (assigned === 0) {
|
|
256
262
|
throw new Error(`${refuseMessage || 'evolution event log is malformed and was not touched'}: ${path}`);
|
|
257
263
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type TreeLock, type TreeLockOptions } from './tree-lock.ts';
|
|
2
|
+
export interface HomeFenceOptions extends TreeLockOptions {
|
|
3
|
+
}
|
|
4
|
+
export interface HomeFenceLease {
|
|
5
|
+
readonly lock: TreeLock;
|
|
6
|
+
release(): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare class HomeFenceError extends Error {
|
|
9
|
+
readonly reason: 'busy' | 'io';
|
|
10
|
+
constructor(reason: 'busy' | 'io', message: string);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* One home-level writer queue. It serializes same-process callers before the
|
|
14
|
+
* tree lock, and the tree lock remains the only cross-process guard the current
|
|
15
|
+
* backend can provide (nodeEvolutionIo is single-process).
|
|
16
|
+
*/
|
|
17
|
+
export declare class HomeFence {
|
|
18
|
+
private tail;
|
|
19
|
+
private readonly options;
|
|
20
|
+
constructor(options: HomeFenceOptions);
|
|
21
|
+
acquire(): Promise<HomeFenceLease>;
|
|
22
|
+
run<T>(body: (lock: TreeLock) => Promise<T>): Promise<T>;
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=home-fence.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { acquireTreeWriteLock } from "./tree-lock.js";
|
|
2
|
+
import { assertHomeOwner } from "./home-owner.js";
|
|
3
|
+
export class HomeFenceError extends Error {
|
|
4
|
+
reason;
|
|
5
|
+
constructor(reason, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'HomeFenceError';
|
|
8
|
+
this.reason = reason;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* One home-level writer queue. It serializes same-process callers before the
|
|
13
|
+
* tree lock, and the tree lock remains the only cross-process guard the current
|
|
14
|
+
* backend can provide (nodeEvolutionIo is single-process).
|
|
15
|
+
*/
|
|
16
|
+
export class HomeFence {
|
|
17
|
+
tail = Promise.resolve();
|
|
18
|
+
options;
|
|
19
|
+
constructor(options) {
|
|
20
|
+
this.options = options;
|
|
21
|
+
}
|
|
22
|
+
async acquire() {
|
|
23
|
+
const previous = this.tail;
|
|
24
|
+
let releaseQueue = () => { };
|
|
25
|
+
this.tail = new Promise(resolve => { releaseQueue = resolve; });
|
|
26
|
+
await previous;
|
|
27
|
+
try {
|
|
28
|
+
const acquired = await acquireTreeWriteLock(this.options);
|
|
29
|
+
if (!acquired.ok) {
|
|
30
|
+
throw new HomeFenceError(acquired.reason, acquired.message ?? 'home fence is ' + acquired.reason);
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
await assertHomeOwner(this.options.io, this.options.home);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
await acquired.lock.release();
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
lock: acquired.lock,
|
|
41
|
+
release: async () => {
|
|
42
|
+
await acquired.lock.release();
|
|
43
|
+
releaseQueue();
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
releaseQueue();
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async run(body) {
|
|
53
|
+
const lease = await this.acquire();
|
|
54
|
+
try {
|
|
55
|
+
return await body(lease.lock);
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
await lease.release();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=home-fence.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { EvolutionIoLike } from './io.ts';
|
|
2
|
+
/** Fail loud when another live process already owns this DSH home. Single-host contract. */
|
|
3
|
+
export declare function assertHomeOwner(io: EvolutionIoLike, home: string): Promise<void>;
|
|
4
|
+
//# sourceMappingURL=home-owner.d.ts.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
const OWNER_FILE = '.evolution-owner.json';
|
|
3
|
+
function isAlive(pid) {
|
|
4
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
5
|
+
return false;
|
|
6
|
+
try {
|
|
7
|
+
process.kill(pid, 0);
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
return error.code === 'EPERM';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Fail loud when another live process already owns this DSH home. Single-host contract. */
|
|
15
|
+
export async function assertHomeOwner(io, home) {
|
|
16
|
+
const path = join(home, OWNER_FILE);
|
|
17
|
+
const raw = await io.readText(path);
|
|
18
|
+
if (raw !== null) {
|
|
19
|
+
let record;
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(raw);
|
|
22
|
+
if (typeof parsed.pid !== 'number' || typeof parsed.startedAt !== 'string')
|
|
23
|
+
throw new Error('bad owner record');
|
|
24
|
+
record = { pid: parsed.pid, startedAt: parsed.startedAt };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
throw new Error('evolution home owner record is unreadable; refusing a second owner (' + path + ')');
|
|
28
|
+
}
|
|
29
|
+
if (record.pid === process.pid)
|
|
30
|
+
return;
|
|
31
|
+
if (isAlive(record.pid)) {
|
|
32
|
+
throw new Error('evolution home is owned by another live process (pid ' + String(record.pid) + '); this deployment is single-host only');
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
await io.writeText(path, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }));
|
|
36
|
+
}
|
|
37
|
+
//# sourceMappingURL=home-owner.js.map
|
package/lib/types/index.d.ts
CHANGED
|
@@ -73,6 +73,10 @@ export * from './review-channel.ts';
|
|
|
73
73
|
export * from './review-context.ts';
|
|
74
74
|
export * from './run-registry.ts';
|
|
75
75
|
export * from './tree-lock.ts';
|
|
76
|
+
export * from './home-fence.ts';
|
|
77
|
+
export * from './home-owner.ts';
|
|
78
|
+
export * from './lease-store.ts';
|
|
79
|
+
export * from './mutation-authority.ts';
|
|
76
80
|
export * from './unit-undo-plan.ts';
|
|
77
81
|
export * from './unit-undo.ts';
|
|
78
82
|
export * from './reports.ts';
|
package/lib/types/index.js
CHANGED
|
@@ -74,6 +74,10 @@ export * from "./review-channel.js";
|
|
|
74
74
|
export * from "./review-context.js";
|
|
75
75
|
export * from "./run-registry.js";
|
|
76
76
|
export * from "./tree-lock.js";
|
|
77
|
+
export * from "./home-fence.js";
|
|
78
|
+
export * from "./home-owner.js";
|
|
79
|
+
export * from "./lease-store.js";
|
|
80
|
+
export * from "./mutation-authority.js";
|
|
77
81
|
export * from "./unit-undo-plan.js";
|
|
78
82
|
export * from "./unit-undo.js";
|
|
79
83
|
export * from "./reports.js";
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { MutationOwner } from '@lmzhen/dsh-evolution-contract';
|
|
2
|
+
import type { EvolutionIoLike } from './io.ts';
|
|
3
|
+
/** One persisted run/claim lease. Epoch increments on every re-acquire. */
|
|
4
|
+
export interface LeaseRecord {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly owner: MutationOwner;
|
|
7
|
+
readonly runId: string;
|
|
8
|
+
readonly pid: number;
|
|
9
|
+
readonly epoch: number;
|
|
10
|
+
readonly issuedAt: number;
|
|
11
|
+
readonly expiresAt: number;
|
|
12
|
+
readonly heartbeatAt: number;
|
|
13
|
+
readonly state: 'active' | 'released';
|
|
14
|
+
}
|
|
15
|
+
/** Caller-held proof of one active lease. */
|
|
16
|
+
export interface LeaseToken {
|
|
17
|
+
readonly id: string;
|
|
18
|
+
readonly owner: MutationOwner;
|
|
19
|
+
readonly runId: string;
|
|
20
|
+
readonly epoch: number;
|
|
21
|
+
}
|
|
22
|
+
export type LeaseAcquireResult = {
|
|
23
|
+
readonly ok: true;
|
|
24
|
+
readonly lease: LeaseRecord;
|
|
25
|
+
readonly token: LeaseToken;
|
|
26
|
+
} | {
|
|
27
|
+
readonly ok: false;
|
|
28
|
+
readonly reason: 'busy';
|
|
29
|
+
readonly holder: LeaseRecord;
|
|
30
|
+
};
|
|
31
|
+
export interface LeaseStoreOptions {
|
|
32
|
+
readonly io: EvolutionIoLike;
|
|
33
|
+
readonly home: string;
|
|
34
|
+
readonly ttlMs?: number;
|
|
35
|
+
readonly now?: () => number;
|
|
36
|
+
readonly pid?: number;
|
|
37
|
+
}
|
|
38
|
+
export declare const DEFAULT_LEASE_TTL_MS = 30000;
|
|
39
|
+
export declare function leaseFile(home: string, runId: string): string;
|
|
40
|
+
/** Durable single-host lease store. One active lease per runId; expired leases are reclaimable. */
|
|
41
|
+
export declare class LeaseStore {
|
|
42
|
+
private readonly io;
|
|
43
|
+
private readonly home;
|
|
44
|
+
private readonly ttlMs;
|
|
45
|
+
private readonly now;
|
|
46
|
+
private readonly pid;
|
|
47
|
+
constructor(options: LeaseStoreOptions);
|
|
48
|
+
private path;
|
|
49
|
+
acquire(owner: MutationOwner, runId: string, ttlMs?: number): Promise<LeaseAcquireResult>;
|
|
50
|
+
get(runId: string): Promise<LeaseRecord | null>;
|
|
51
|
+
active(runId: string): Promise<LeaseRecord | null>;
|
|
52
|
+
renew(token: LeaseToken, ttlMs?: number): Promise<LeaseRecord | null>;
|
|
53
|
+
release(token: LeaseToken): Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=lease-store.d.ts.map
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export const DEFAULT_LEASE_TTL_MS = 30_000;
|
|
4
|
+
export function leaseFile(home, runId) {
|
|
5
|
+
return join(home, 'leases', encodeURIComponent(runId) + '.json');
|
|
6
|
+
}
|
|
7
|
+
function parseLease(raw) {
|
|
8
|
+
if (raw === null)
|
|
9
|
+
return undefined;
|
|
10
|
+
try {
|
|
11
|
+
const value = JSON.parse(raw);
|
|
12
|
+
if (typeof value.id !== 'string' || typeof value.runId !== 'string' || typeof value.owner !== 'string' || typeof value.pid !== 'number' || typeof value.epoch !== 'number' || typeof value.issuedAt !== 'number' || typeof value.expiresAt !== 'number' || typeof value.heartbeatAt !== 'number' || (value.state !== 'active' && value.state !== 'released'))
|
|
13
|
+
return undefined;
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function transact(io, path, task) {
|
|
21
|
+
if (io.transact !== undefined) {
|
|
22
|
+
await io.transact(path, task);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const current = await io.readText(path);
|
|
26
|
+
const next = task(current);
|
|
27
|
+
if (next === null)
|
|
28
|
+
await io.remove(path);
|
|
29
|
+
else if (next !== current)
|
|
30
|
+
await io.writeText(path, next);
|
|
31
|
+
}
|
|
32
|
+
function tokenOf(record) {
|
|
33
|
+
return { id: record.id, owner: record.owner, runId: record.runId, epoch: record.epoch };
|
|
34
|
+
}
|
|
35
|
+
/** Durable single-host lease store. One active lease per runId; expired leases are reclaimable. */
|
|
36
|
+
export class LeaseStore {
|
|
37
|
+
io;
|
|
38
|
+
home;
|
|
39
|
+
ttlMs;
|
|
40
|
+
now;
|
|
41
|
+
pid;
|
|
42
|
+
constructor(options) {
|
|
43
|
+
this.io = options.io;
|
|
44
|
+
this.home = options.home;
|
|
45
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_LEASE_TTL_MS;
|
|
46
|
+
this.now = options.now ?? Date.now;
|
|
47
|
+
this.pid = options.pid ?? process.pid;
|
|
48
|
+
}
|
|
49
|
+
path(runId) {
|
|
50
|
+
if (runId.trim() === '')
|
|
51
|
+
throw new Error('lease runId must not be empty');
|
|
52
|
+
return leaseFile(this.home, runId);
|
|
53
|
+
}
|
|
54
|
+
async acquire(owner, runId, ttlMs = this.ttlMs) {
|
|
55
|
+
if (ttlMs <= 0)
|
|
56
|
+
throw new Error('lease ttl must be positive');
|
|
57
|
+
const path = this.path(runId);
|
|
58
|
+
const now = this.now();
|
|
59
|
+
let created;
|
|
60
|
+
let holder;
|
|
61
|
+
await transact(this.io, path, (raw) => {
|
|
62
|
+
const current = parseLease(raw);
|
|
63
|
+
if (current !== undefined && current.state === 'active' && now < current.expiresAt) {
|
|
64
|
+
holder = current;
|
|
65
|
+
return raw;
|
|
66
|
+
}
|
|
67
|
+
created = {
|
|
68
|
+
id: randomUUID(),
|
|
69
|
+
owner,
|
|
70
|
+
runId,
|
|
71
|
+
pid: this.pid,
|
|
72
|
+
epoch: (current?.epoch ?? 0) + 1,
|
|
73
|
+
issuedAt: now,
|
|
74
|
+
expiresAt: now + ttlMs,
|
|
75
|
+
heartbeatAt: now,
|
|
76
|
+
state: 'active',
|
|
77
|
+
};
|
|
78
|
+
return JSON.stringify(created);
|
|
79
|
+
});
|
|
80
|
+
if (created !== undefined)
|
|
81
|
+
return { ok: true, lease: created, token: tokenOf(created) };
|
|
82
|
+
if (holder !== undefined)
|
|
83
|
+
return { ok: false, reason: 'busy', holder };
|
|
84
|
+
throw new Error('lease acquire did not create or observe a record');
|
|
85
|
+
}
|
|
86
|
+
async get(runId) {
|
|
87
|
+
return parseLease(await this.io.readText(this.path(runId))) ?? null;
|
|
88
|
+
}
|
|
89
|
+
async active(runId) {
|
|
90
|
+
const record = await this.get(runId);
|
|
91
|
+
return record !== null && record.state === 'active' && this.now() < record.expiresAt ? record : null;
|
|
92
|
+
}
|
|
93
|
+
async renew(token, ttlMs = this.ttlMs) {
|
|
94
|
+
const path = this.path(token.runId);
|
|
95
|
+
let next = null;
|
|
96
|
+
await transact(this.io, path, (raw) => {
|
|
97
|
+
const current = parseLease(raw);
|
|
98
|
+
if (current === undefined || current.state !== 'active' || current.id !== token.id || current.epoch !== token.epoch)
|
|
99
|
+
return raw;
|
|
100
|
+
const now = this.now();
|
|
101
|
+
next = { ...current, heartbeatAt: now, expiresAt: now + ttlMs };
|
|
102
|
+
return JSON.stringify(next);
|
|
103
|
+
});
|
|
104
|
+
return next;
|
|
105
|
+
}
|
|
106
|
+
async release(token) {
|
|
107
|
+
const path = this.path(token.runId);
|
|
108
|
+
await transact(this.io, path, (raw) => {
|
|
109
|
+
const current = parseLease(raw);
|
|
110
|
+
if (current === undefined || current.id !== token.id || current.epoch !== token.epoch)
|
|
111
|
+
return raw;
|
|
112
|
+
return JSON.stringify({ ...current, state: 'released', heartbeatAt: this.now() });
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
//# sourceMappingURL=lease-store.js.map
|
|
@@ -23,6 +23,9 @@ export interface MemoryApplyResult {
|
|
|
23
23
|
limit: number;
|
|
24
24
|
}
|
|
25
25
|
export declare function memoryRoot(env?: NodeJS.ProcessEnv): string;
|
|
26
|
+
export interface MemoryFence {
|
|
27
|
+
run<T>(body: () => Promise<T>): Promise<T>;
|
|
28
|
+
}
|
|
26
29
|
export interface MemoryStoreOptions {
|
|
27
30
|
memoryCharLimit?: number;
|
|
28
31
|
userCharLimit?: number;
|
|
@@ -30,6 +33,8 @@ export interface MemoryStoreOptions {
|
|
|
30
33
|
root?: string;
|
|
31
34
|
maxConsolidationFailures?: number;
|
|
32
35
|
io?: EvolutionIoLike;
|
|
36
|
+
/** Optional shared family fence; all single-file RMWs run inside it. */
|
|
37
|
+
fence?: MemoryFence;
|
|
33
38
|
/** V10-03 (P2-18): deployment-declared benign pattern labels (ScanOptions.
|
|
34
39
|
* excludeLabels) applied to every threat check of this store (writes and
|
|
35
40
|
* the renderContext filter). Default empty — the strict ANY-hit-blocks
|
|
@@ -44,6 +49,7 @@ export declare class MemoryStore {
|
|
|
44
49
|
readonly root: string;
|
|
45
50
|
private readonly maxFailures;
|
|
46
51
|
private readonly io;
|
|
52
|
+
private readonly fence;
|
|
47
53
|
/** V10-03 (P2-18): see MemoryStoreOptions.threatExemptLabels. */
|
|
48
54
|
private readonly threatExemptLabels;
|
|
49
55
|
/** V6-16 (0.3.37): same-process RMW serialization (the SkillLibrary queue) —
|
|
@@ -78,6 +78,7 @@ export class MemoryStore {
|
|
|
78
78
|
root;
|
|
79
79
|
maxFailures;
|
|
80
80
|
io;
|
|
81
|
+
fence;
|
|
81
82
|
/** V10-03 (P2-18): see MemoryStoreOptions.threatExemptLabels. */
|
|
82
83
|
threatExemptLabels;
|
|
83
84
|
/** V6-16 (0.3.37): same-process RMW serialization (the SkillLibrary queue) —
|
|
@@ -90,6 +91,7 @@ export class MemoryStore {
|
|
|
90
91
|
lastFailureAt = 0;
|
|
91
92
|
constructor(options = {}) {
|
|
92
93
|
this.io = options.io ?? nodeEvolutionIo();
|
|
94
|
+
this.fence = options.fence;
|
|
93
95
|
this.memoryLimit = options.memoryCharLimit ?? DEFAULT_MEMORY_CHAR_LIMIT;
|
|
94
96
|
this.userLimit = options.userCharLimit ?? DEFAULT_USER_CHAR_LIMIT;
|
|
95
97
|
this.addDatePrefix = options.addDatePrefix ?? false;
|
|
@@ -274,14 +276,20 @@ export class MemoryStore {
|
|
|
274
276
|
}
|
|
275
277
|
}
|
|
276
278
|
let outcome;
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
279
|
+
const run = async () => {
|
|
280
|
+
await transactIo(this.io, fileFor(this.root, target), async (current) => {
|
|
281
|
+
const step = await core(current ?? '');
|
|
282
|
+
outcome = step.result;
|
|
283
|
+
// M-4 (v3 audit): a failure on a MISSING file must keep it missing —
|
|
284
|
+
// returning '' would fabricate an empty file. `null` (DELETE) is safe
|
|
285
|
+
// here: the file does not exist, so the remove is a no-op.
|
|
286
|
+
return step.write ?? (current ?? null);
|
|
287
|
+
});
|
|
288
|
+
};
|
|
289
|
+
if (this.fence !== undefined)
|
|
290
|
+
await this.fence.run(run);
|
|
291
|
+
else
|
|
292
|
+
await run();
|
|
285
293
|
// C-01: a transact backend that violates the contract (never invokes the
|
|
286
294
|
// task) leaves `outcome` undefined — the old `undefined as
|
|
287
295
|
// MemoryApplyResult` cast handed callers an object whose `.ok` dereference
|