@lmzhen/dsh-evolution-core 0.40.1 → 0.42.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/lib/composition/index.js +2 -2
- package/lib/{composition-dy0gJWDd.js → composition-CVafrlEw.js} +2 -2
- package/lib/{ensure-B4fjEI0w.js → ensure-BjToTMMj.js} +2 -2
- package/lib/errors-BxzLTVbS.js +399 -0
- package/lib/guards-3f02mnf2.js +29 -0
- package/lib/http-routes.js +205 -1
- package/lib/index.js +3588 -15049
- package/lib/mutations-jUuOPaCn.js +718 -0
- package/lib/platform/index.js +2 -2
- package/lib/{platform-CFp373_0.js → platform-B06_h8t-.js} +4 -1
- package/lib/restrictor.js +1 -1
- package/lib/runtime/plugin.js +2 -2
- package/lib/{session-projection-CXUNPkq9.js → session-projection-EB7mUOlJ.js} +63 -63
- package/lib/skill-health-BLGZTIv8.js +3773 -0
- package/lib/skill-history-_Cssts5o.js +1912 -0
- package/lib/skills.js +4067 -0
- package/lib/subagent/index.js +1 -1
- package/lib/types/errors.d.ts +12 -0
- package/lib/types/errors.js +17 -0
- package/lib/types/generated/errors.localized.d.ts +320 -0
- package/lib/types/generated/errors.localized.js +318 -0
- package/lib/types/home-fence.d.ts +7 -0
- package/lib/types/home-fence.js +58 -3
- package/lib/types/index.d.ts +1 -18
- package/lib/types/index.js +1 -18
- package/lib/types/io.js +1 -1
- package/lib/types/mutation-authority.d.ts +14 -37
- package/lib/types/mutation-authority.js +16 -103
- package/lib/types/mutation-storage-adapter.js +9 -6
- package/lib/types/mutation-unit.d.ts +14 -0
- package/lib/types/mutation-unit.js +30 -10
- package/lib/types/opt-in.js +1 -1
- package/lib/types/platform/index.d.ts +8 -1
- package/lib/types/platform/index.js +3 -0
- package/lib/types/review-channel.js +3 -1
- package/lib/types/review-context.js +3 -1
- package/lib/types/run-registry.d.ts +2 -24
- package/lib/types/scope.js +1 -1
- package/lib/types/signals.d.ts +1 -1
- package/lib/types/skill-store.d.ts +7 -1
- package/lib/types/skill-store.js +43 -80
- package/lib/types/skills.d.ts +11 -0
- package/lib/types/skills.js +11 -0
- package/lib/types/subagent/types.d.ts +3 -3
- package/lib/types/tree-lock.js +4 -1
- package/lib/types/unit-claim.d.ts +8 -0
- package/lib/types/unit-claim.js +3 -0
- package/lib/types/unit-journal.d.ts +3 -1
- package/lib/types/unit-journal.js +12 -3
- package/lib/types/unit-storage.d.ts +1 -0
- package/lib/types/write-gates.d.ts +1 -1
- package/lib/types/write-gates.js +3 -1
- package/lib/types/write.d.ts +11 -0
- package/lib/types/write.js +11 -0
- package/lib/write.js +357 -0
- package/package.json +16 -4
- package/lib/errors-DUcEoTLR.js +0 -58
- package/lib/http-routes-_anZVlPf.js +0 -233
- package/lib/types/unit-backend.d.ts +0 -5
- package/lib/types/unit-backend.js +0 -55
- package/lib/types/unit-transaction.d.ts +0 -225
- package/lib/types/unit-transaction.js +0 -501
|
@@ -0,0 +1,718 @@
|
|
|
1
|
+
import { n as isRecord } from "./guards-3f02mnf2.js";
|
|
2
|
+
import { copyFileSync, existsSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { cp, lstat, mkdir, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
6
|
+
//#region lib/types/probe.js
|
|
7
|
+
function probePresent(value) {
|
|
8
|
+
return {
|
|
9
|
+
kind: "present",
|
|
10
|
+
value
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function probeAbsent() {
|
|
14
|
+
return { kind: "absent" };
|
|
15
|
+
}
|
|
16
|
+
function probeUnknown(reason) {
|
|
17
|
+
return {
|
|
18
|
+
kind: "unknown",
|
|
19
|
+
reason
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function isPresent(probe) {
|
|
23
|
+
return probe.kind === "present";
|
|
24
|
+
}
|
|
25
|
+
function isAbsent(probe) {
|
|
26
|
+
return probe.kind === "absent";
|
|
27
|
+
}
|
|
28
|
+
function isUnknown(probe) {
|
|
29
|
+
return probe.kind === "unknown";
|
|
30
|
+
}
|
|
31
|
+
/** Only a PRESENT probe yields a value; absent and unknown both fall back. */
|
|
32
|
+
function valueOr(probe, fallback) {
|
|
33
|
+
return probe.kind === "present" ? probe.value : fallback;
|
|
34
|
+
}
|
|
35
|
+
function mapProbe(probe, transform) {
|
|
36
|
+
return probe.kind === "present" ? probePresent(transform(probe.value)) : probe;
|
|
37
|
+
}
|
|
38
|
+
/** The reason an `unknown` probe carries (message, never a bare String(object)). */
|
|
39
|
+
function probeReason(error) {
|
|
40
|
+
return error instanceof Error ? error.message : String(error);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* ENOENT/ENOTDIR are the ONE read failure that means "it is not there"; every
|
|
44
|
+
* other failure is an IO error and stays unknown (same split as the node
|
|
45
|
+
* backend's own isMissing, V8-23⑨ for the size probe).
|
|
46
|
+
*/
|
|
47
|
+
function isMissingPath(error) {
|
|
48
|
+
const code = error?.code;
|
|
49
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Three-state directory listing. The node backend already answers `[]` for a
|
|
53
|
+
* MISSING directory (its own rc.50 P2-4 contract) and THROWS for an unreadable
|
|
54
|
+
* one, so the value this adds is the second half: a backend that throws ENOENT
|
|
55
|
+
* reads as absent, an EACCES/EIO reads as unknown — where a bare
|
|
56
|
+
* `catch { return [] }` served a broken store as an empty one (the N14 class).
|
|
57
|
+
*/
|
|
58
|
+
async function probeList(io, dir) {
|
|
59
|
+
try {
|
|
60
|
+
return probePresent(await io.list(dir));
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return isMissingPath(error) ? probeAbsent() : probeUnknown(probeReason(error));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Three-state TEXT read of one file. A missing path (ENOENT/ENOTDIR, or a backend whose read
|
|
67
|
+
* answers null) is `absent`; every other failure is `unknown` with its reason. The distinction is
|
|
68
|
+
* the whole point (N14/O-7): "I could not read this file" and "this file is not there" lead to
|
|
69
|
+
* opposite decisions once a write is about to replace the bytes — treating the first as the
|
|
70
|
+
* second is how a broken store reads as empty and a rescue copy never happens.
|
|
71
|
+
* @param io - the IO seam.
|
|
72
|
+
* @param path - the file to read.
|
|
73
|
+
* @returns the probe.
|
|
74
|
+
*/
|
|
75
|
+
async function probeText(io, path) {
|
|
76
|
+
try {
|
|
77
|
+
const value = await io.readText(path);
|
|
78
|
+
return value === null ? probeAbsent() : probePresent(value);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
return isMissingPath(error) ? probeAbsent() : probeUnknown(probeReason(error));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Three-state mtime read. Absent covers both "the path is missing" and "this
|
|
85
|
+
* backend has no mtime probe" — the seam cannot tell those apart, so consumers
|
|
86
|
+
* that must know say so in their own log line. A stat that FAILS is unknown.
|
|
87
|
+
*/
|
|
88
|
+
async function probeMtime(io, path) {
|
|
89
|
+
try {
|
|
90
|
+
const value = await io.mtime?.(path) ?? null;
|
|
91
|
+
return value === null ? probeAbsent() : probePresent(value);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
return probeUnknown(probeReason(error));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** The timestamp a curator run report DECLARES: `startedAt` (the run's own start), then `at` (the
|
|
97
|
+
* stamp the error writer sets on every report — F-327/P2-4).
|
|
98
|
+
* @param parsed - the parsed report, or anything else.
|
|
99
|
+
* @returns epoch milliseconds, or null when neither field carries a parseable time.
|
|
100
|
+
*/
|
|
101
|
+
function declaredReportStamp(parsed) {
|
|
102
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
103
|
+
const record = parsed;
|
|
104
|
+
for (const value of [record.startedAt, record.at]) {
|
|
105
|
+
if (typeof value !== "string") continue;
|
|
106
|
+
const ms = Date.parse(value);
|
|
107
|
+
if (Number.isFinite(ms)) return ms;
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
/** The time one curator run report is ordered by — ONE口径 for every reader (S2.9/T3-12): the
|
|
112
|
+
* declared stamp above, then the optional mtime probe as the fallback. `null` means "no usable
|
|
113
|
+
* time", and that single answer serves both consumers: such a report is never the LATEST (the
|
|
114
|
+
* panel) and is never DELETED (the retention sweep), which is exactly the pair of answers the two
|
|
115
|
+
* readers disagreed on when one ordered by the declared stamp and the other by mtime alone.
|
|
116
|
+
* @param io - the IO seam; a backend without `mtime` simply has no fallback.
|
|
117
|
+
* @param path - the report file the probe reads.
|
|
118
|
+
* @param parsed - the already-parsed report.
|
|
119
|
+
* @returns epoch milliseconds, or null.
|
|
120
|
+
*/
|
|
121
|
+
async function reportTime(io, path, parsed) {
|
|
122
|
+
const declared = declaredReportStamp(parsed);
|
|
123
|
+
if (declared !== null) return declared;
|
|
124
|
+
const probe = await probeMtime(io, path);
|
|
125
|
+
return isPresent(probe) ? probe.value : null;
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region lib/types/io.js
|
|
129
|
+
/**
|
|
130
|
+
* Structural IO seam for the evolution plugin family.
|
|
131
|
+
*
|
|
132
|
+
* Every evolution package passes `ctx.evolutionIo.provider()`; standalone
|
|
133
|
+
* consumers (and the core's own tests) can use `nodeEvolutionIo`.
|
|
134
|
+
*/
|
|
135
|
+
/**
|
|
136
|
+
* Run `task` inside `io.transact` when the backend provides it; otherwise fall
|
|
137
|
+
* back to a plain read → task → write/remove sequence (no cross-process lock —
|
|
138
|
+
* callers keep their single-process serialize chain as the second layer). A
|
|
139
|
+
* byte-identical task result skips the write (C-07 — parity with the
|
|
140
|
+
* node backend's V5-03 short-circuit).
|
|
141
|
+
*/
|
|
142
|
+
async function transactIo(io, path, task) {
|
|
143
|
+
const committedOnly = (error) => isCommittedWarning(error);
|
|
144
|
+
if (io.transact) try {
|
|
145
|
+
await io.transact(path, task);
|
|
146
|
+
return;
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (!committedOnly(error)) throw error;
|
|
149
|
+
console.warn(`evolution-io: ${path} was written but its directory fsync failed — the bytes are visible, durability is unconfirmed: ${error instanceof Error ? error.message : String(error)}`);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const current = await io.readText(path);
|
|
153
|
+
const next = await task(current);
|
|
154
|
+
if (next === null) await io.remove(path);
|
|
155
|
+
else if (next !== current) try {
|
|
156
|
+
await io.writeText(path, next);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (!committedOnly(error)) throw error;
|
|
159
|
+
console.warn(`evolution-io: ${path} was written but its directory fsync failed — the bytes are visible, durability is unconfirmed: ${error instanceof Error ? error.message : String(error)}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Build a {@link TransactTaskGuard} for one write path. See its doc. */
|
|
163
|
+
function transactTaskGuard(what) {
|
|
164
|
+
let invoked = false;
|
|
165
|
+
return {
|
|
166
|
+
wrap: (task) => (current) => {
|
|
167
|
+
invoked = true;
|
|
168
|
+
return task(current);
|
|
169
|
+
},
|
|
170
|
+
invoked: () => invoked,
|
|
171
|
+
assertInvoked: () => {
|
|
172
|
+
if (invoked) return;
|
|
173
|
+
throw new Error(`internal error: the write transaction for ${what} did not invoke the task; no write was performed`);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/** Lazy adapter over an IO provider registry, shared by every evolution consumer. */
|
|
178
|
+
function evolutionIoAdapter(provider) {
|
|
179
|
+
return {
|
|
180
|
+
get processScope() {
|
|
181
|
+
return provider().processScope;
|
|
182
|
+
},
|
|
183
|
+
readText: (path) => provider().readText(path),
|
|
184
|
+
writeText: (path, content) => provider().writeText(path, content),
|
|
185
|
+
remove: (path) => provider().remove(path),
|
|
186
|
+
list: (path) => provider().list(path),
|
|
187
|
+
exists: (path) => provider().exists(path),
|
|
188
|
+
rename: (path, destination) => provider().rename(path, destination),
|
|
189
|
+
copy: (path, destination) => provider().copy(path, destination),
|
|
190
|
+
size: (path) => {
|
|
191
|
+
const io = provider();
|
|
192
|
+
return io.size ? io.size(path) : Promise.resolve(null);
|
|
193
|
+
},
|
|
194
|
+
transact: (path, task) => {
|
|
195
|
+
const io = provider();
|
|
196
|
+
return io.transact ? io.transact(path, task) : transactIo(io, path, task);
|
|
197
|
+
},
|
|
198
|
+
isSymlink: (path) => {
|
|
199
|
+
const io = provider();
|
|
200
|
+
return io.isSymlink ? io.isSymlink(path) : Promise.resolve(null);
|
|
201
|
+
},
|
|
202
|
+
mtime: (path) => {
|
|
203
|
+
const io = provider();
|
|
204
|
+
return io.mtime ? io.mtime(path) : Promise.resolve(null);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
const RENAME_RETRY_BASE_MS = 50;
|
|
209
|
+
const RENAME_RETRY_MAX_DELAY_MS = 800;
|
|
210
|
+
const RENAME_RETRY_MAX_ATTEMPTS = 6;
|
|
211
|
+
/**
|
|
212
|
+
* Retry a rename that a peer is temporarily holding on Windows (EPERM/EBUSY):
|
|
213
|
+
* exponential backoff (50ms doubling, capped at 800ms) with a ~2s total
|
|
214
|
+
* budget, matching the write-lock cadence (C-28 — the old 3x50ms
|
|
215
|
+
* budget turned a transient antivirus hold into a permanent write failure).
|
|
216
|
+
* A non-transient code surfaces immediately; a persistent EPERM/EBUSY
|
|
217
|
+
* rethrows with a pointer at the usual causes instead of a bare errno.
|
|
218
|
+
* `fn` is the rename primitive, injectable for deterministic tests.
|
|
219
|
+
*
|
|
220
|
+
* v22 (LOCK-5) documented platform limit: POSIX rename-over-existing is
|
|
221
|
+
* atomic for concurrent READERS, but Windows MoveFileExW(REPLACE_EXISTING)
|
|
222
|
+
* can make the target briefly invisible (ENOENT) while the replacement is in
|
|
223
|
+
* flight. The retry budget above covers the WRITE side only — a LOCKLESS
|
|
224
|
+
* reader (`readText`/`readJson` on a path it does not hold the lock for) can
|
|
225
|
+
* observe that window and see "missing" for a file that was just committed.
|
|
226
|
+
* Verified harmless today: every lockless-read consumer treats the transient
|
|
227
|
+
* miss as self-healing state (no consumer persists a read of null into a
|
|
228
|
+
* write), and distinguishing that ENOENT from a genuinely absent file in
|
|
229
|
+
* `readText` would tax every ordinary missing-file probe. Revisit only if a
|
|
230
|
+
* consumer appears that must never transiently miss.
|
|
231
|
+
*
|
|
232
|
+
* @param tmp - the source path to rename.
|
|
233
|
+
* @param target - the destination path.
|
|
234
|
+
* @param fn - the rename primitive (defaults to `node:fs/promises.rename`).
|
|
235
|
+
* @returns a promise that resolves once the rename succeeds.
|
|
236
|
+
*/
|
|
237
|
+
async function renameWithRetry(tmp, target, fn = rename) {
|
|
238
|
+
for (let retry = 0;; retry += 1) try {
|
|
239
|
+
await fn(tmp, target);
|
|
240
|
+
return;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
const code = error?.code;
|
|
243
|
+
if (code !== "EPERM" && code !== "EBUSY") throw error;
|
|
244
|
+
if (retry >= RENAME_RETRY_MAX_ATTEMPTS) {
|
|
245
|
+
const final = error;
|
|
246
|
+
final.message = `${final.message} (persisted after ${retry + 1} rename attempts over ~2s — the target may be held by another process or marked read-only; check antivirus, search indexers and file attributes)`;
|
|
247
|
+
throw final;
|
|
248
|
+
}
|
|
249
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(RENAME_RETRY_BASE_MS * 2 ** retry, RENAME_RETRY_MAX_DELAY_MS)));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* V10-06 (P1-1): the crash-durable tmp half of the upstream storage-json
|
|
254
|
+
* `writeAtomic` protocol (storage-json/src/atomic.ts:24-40): exclusive-create
|
|
255
|
+
* a same-directory tmp (`wx` — never clobbers), write, `handle.sync()`,
|
|
256
|
+
* close, then hand the tmp to `commitTmp` for the rename. Without the fsync a
|
|
257
|
+
* power loss could land the rename (metadata) before the data blocks and
|
|
258
|
+
* leave an empty/truncated target — which the state-json E-9 quarantine then
|
|
259
|
+
* amplifies into a permanent fail-loud. The tmp name keeps the
|
|
260
|
+
* `<target>.<pid>.<rand>.tmp` shape so sweepStaleTmps keeps matching.
|
|
261
|
+
* Mode parity note: no explicit mode is passed (upstream uses 0o600) — this
|
|
262
|
+
* seam also writes operator-editable skill/memory files, so the previous
|
|
263
|
+
* `writeFile` default (0o666 & ~umask) is deliberately preserved.
|
|
264
|
+
* `openImpl` is injectable so the sync-failure regression test can drive a
|
|
265
|
+
* failing `handle.sync()` deterministically.
|
|
266
|
+
*/
|
|
267
|
+
async function writeDurableTmp(target, content, openImpl = open) {
|
|
268
|
+
const tmp = `${target}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
269
|
+
try {
|
|
270
|
+
const handle = await openImpl(tmp, "wx", process.platform === "win32" ? void 0 : await stat(target).then((value) => value.mode & 511).catch(() => void 0));
|
|
271
|
+
try {
|
|
272
|
+
await handle.writeFile(content, "utf8");
|
|
273
|
+
await handle.sync();
|
|
274
|
+
} finally {
|
|
275
|
+
await handle.close();
|
|
276
|
+
}
|
|
277
|
+
return tmp;
|
|
278
|
+
} catch (error) {
|
|
279
|
+
await rm(tmp, { force: true }).catch(() => {});
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/** V10-06 (P1-1): fsync a POSIX directory so a just-renamed entry is
|
|
284
|
+
* crash-durable (upstream atomic.ts `fsyncDirectory`). */
|
|
285
|
+
/* v8 ignore start -- Windows rejects O_RDONLY directory opens; POSIX coverage exercises this. */
|
|
286
|
+
async function fsyncDirectory(path) {
|
|
287
|
+
if (process.platform === "win32") return;
|
|
288
|
+
const handle = await open(path, "r");
|
|
289
|
+
try {
|
|
290
|
+
await handle.sync();
|
|
291
|
+
} finally {
|
|
292
|
+
await handle.close();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/* v8 ignore stop */
|
|
296
|
+
/**
|
|
297
|
+
* F-366: commit a freshly-written tmp to its target inside the write lock. On a
|
|
298
|
+
* still-failing rename the tmp is deleted immediately rather than left for the
|
|
299
|
+
* (1h + dead-pid) sweep, so a live writer never leaks a tmp it abandoned.
|
|
300
|
+
* V10-06 (P1-1): after a successful rename the parent directory is fsynced on
|
|
301
|
+
* POSIX so the new directory entry itself is crash-durable (upstream atomic.ts
|
|
302
|
+
* tail; Windows skips — it rejects O_RDONLY directory opens). A dir-fsync
|
|
303
|
+
* failure propagates like upstream: the data is on disk, but the durability
|
|
304
|
+
* contract failed loud.
|
|
305
|
+
*/
|
|
306
|
+
async function commitTmp(tmp, target) {
|
|
307
|
+
try {
|
|
308
|
+
await renameWithRetry(tmp, target);
|
|
309
|
+
} catch (error) {
|
|
310
|
+
await rm(tmp, { force: true }).catch(() => {});
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
try {
|
|
314
|
+
await fsyncDirectory(dirname(target));
|
|
315
|
+
} catch (error) {
|
|
316
|
+
throw Object.assign(/* @__PURE__ */ new Error(`commitTmp: ${target} was renamed but the directory fsync failed: ${error instanceof Error ? error.message : String(error)}`), {
|
|
317
|
+
committed: true,
|
|
318
|
+
cause: error
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* True when the pid is alive (EPERM = alive but unowned; ESRCH = gone).
|
|
324
|
+
* V18 single source: the node backend's lock takeover and SkillLibrary's
|
|
325
|
+
* stranded-lock sweep must use the same liveness rule.
|
|
326
|
+
*/
|
|
327
|
+
function isProcessAlive(pid) {
|
|
328
|
+
try {
|
|
329
|
+
process.kill(pid, 0);
|
|
330
|
+
return true;
|
|
331
|
+
} catch (error) {
|
|
332
|
+
return error?.code === "EPERM";
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/** How long an abandoned quarantine copy is kept for operator rescue. G2 S4: hoisted to module scope
|
|
336
|
+
* (it used to live inside `nodeEvolutionIo`, in the region the lock protocol occupied). */
|
|
337
|
+
const CORRUPT_SWEEP_AGE_MS = 168 * 36e5;
|
|
338
|
+
/** V27 G1.4: every quarantine-copy name this family has ever produced —
|
|
339
|
+
* `<file>.corrupt` (current fixed name), `<file>.corrupt.<epoch>`, and the
|
|
340
|
+
* v10-05 legacy `<file>.corrupt-<epoch>-<rand>` series. A user support file
|
|
341
|
+
* keeps a final extension (`.corrupt-backup.md`) and therefore stays. */
|
|
342
|
+
const CORRUPT_COPY_RE = /\.corrupt(\.\d+|-\d+-[0-9a-z]+)?$/;
|
|
343
|
+
/**
|
|
344
|
+
* V27 G1.3: the error `commitTmp` throws when the rename landed but the parent
|
|
345
|
+
* directory fsync failed — the bytes ARE visible, only their durability is
|
|
346
|
+
* unconfirmed. A consumer that treats it as a plain failure reports "not
|
|
347
|
+
* written" for a write that happened (and a two-phase caller may try to roll
|
|
348
|
+
* back a visible write). Every transaction consumer must therefore treat this
|
|
349
|
+
* shape as SUCCESS-with-warning, never as a rejection.
|
|
350
|
+
*/
|
|
351
|
+
function isCommittedWarning(error) {
|
|
352
|
+
return error?.committed === true;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Build the Node IO backend: plain fs promises, durable tmp + rename commits (crash atomicity) and
|
|
356
|
+
* ONE concurrency guarantee of its own — writes to the same path are serialized in-process (see
|
|
357
|
+
* `inProcessWrite`). G2 S4 removed the cross-process write lock and its takeover protocol; the
|
|
358
|
+
* plugin path gets cross-process safety from the platform provider (`ctx.fs`).
|
|
359
|
+
*/
|
|
360
|
+
function nodeEvolutionIo() {
|
|
361
|
+
/**
|
|
362
|
+
* v43 S1-4: delegates to the canonical `isMissingPath` (probe.ts) — one
|
|
363
|
+
* definition for the whole family instead of a second copy of the same two
|
|
364
|
+
* codes. EISDIR deliberately stays OUT of that predicate: a directory
|
|
365
|
+
* squatting on a file path is not "absent" — rotation and event reads must
|
|
366
|
+
* still see it as malformed (rc.72 G-2), while the SkillLibrary.read boundary
|
|
367
|
+
* absorbs EISDIR into "absent" for its own surface (E-43).
|
|
368
|
+
* @param error - the caught read failure.
|
|
369
|
+
* @returns true only for ENOENT/ENOTDIR.
|
|
370
|
+
*/
|
|
371
|
+
const isMissing = (error) => isMissingPath(error);
|
|
372
|
+
/** True when the pid is alive (single source: `isProcessAlive`). */
|
|
373
|
+
const isAlive = isProcessAlive;
|
|
374
|
+
/**
|
|
375
|
+
* G2 S4: the family write-lock protocol is retired. Concurrency is the PLATFORM’s job now — the
|
|
376
|
+
* plugin path requires `ctx.fs`, whose writes are versioned — so this backend keeps exactly one
|
|
377
|
+
* guarantee of its own: writes to the SAME path inside THIS process are serialized (a promise
|
|
378
|
+
* chain per path: no timers, no lock files, no takeover windows). Cross-process RMW safety comes
|
|
379
|
+
* from the provider; a standalone caller sharing a directory across processes must not rely on
|
|
380
|
+
* this backend alone. The durable tmp + rename commit stays — crash atomicity and mutual
|
|
381
|
+
* exclusion are different concerns.
|
|
382
|
+
*/
|
|
383
|
+
const queues = /* @__PURE__ */ new Map();
|
|
384
|
+
const inProcessWrite = async (path, run) => {
|
|
385
|
+
const result = (queues.get(path) ?? Promise.resolve()).then(run, run);
|
|
386
|
+
const settled = result.then(() => {}, () => {});
|
|
387
|
+
queues.set(path, settled);
|
|
388
|
+
try {
|
|
389
|
+
return await result;
|
|
390
|
+
} finally {
|
|
391
|
+
if (queues.get(path) === settled) queues.delete(path);
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
/**
|
|
395
|
+
* Sweep transient files a crashed writer left behind, lazily: once per write, for the directory
|
|
396
|
+
* that write is about to touch.
|
|
397
|
+
* `<target>.<pid>.<rand>.tmp` — the durable-write tmp. This process's own leftover is recycled
|
|
398
|
+
* immediately (a live writer's tmp is a current write, not a crash artifact); a foreign tmp
|
|
399
|
+
* needs an age past an hour AND a dead holder.
|
|
400
|
+
* `.corrupt*` — quarantine copies past their rescue window.
|
|
401
|
+
* G2 S4: the lock and takeover-ticket branches are gone with the write-lock protocol.
|
|
402
|
+
*/
|
|
403
|
+
const sweepStaleTmps = async (path) => {
|
|
404
|
+
const dir = dirname(path);
|
|
405
|
+
const base = basename(path);
|
|
406
|
+
let entries;
|
|
407
|
+
try {
|
|
408
|
+
entries = await readdir(dir);
|
|
409
|
+
} catch {
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
for (const name of entries) {
|
|
413
|
+
const tmpMatch = /^(.*)\.(\d+)\.([0-9a-f]+)\.tmp$/.exec(name);
|
|
414
|
+
if (tmpMatch !== null && tmpMatch[1] === base) {
|
|
415
|
+
const tmpPath = join(dir, name);
|
|
416
|
+
const holder = Number(tmpMatch[2]);
|
|
417
|
+
try {
|
|
418
|
+
const st = await stat(tmpPath);
|
|
419
|
+
const deadHolder = !Number.isInteger(holder) || holder <= 0 || !isAlive(holder);
|
|
420
|
+
if (holder === process.pid || Date.now() - st.mtimeMs > 36e5 && deadHolder) await rm(tmpPath, { force: true });
|
|
421
|
+
} catch {}
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
if (name.startsWith(base + ".") && CORRUPT_COPY_RE.test(name)) {
|
|
425
|
+
const corruptPath = join(dir, name);
|
|
426
|
+
try {
|
|
427
|
+
const st = await stat(corruptPath);
|
|
428
|
+
if (Date.now() - st.mtimeMs > CORRUPT_SWEEP_AGE_MS) await rm(corruptPath, { force: true });
|
|
429
|
+
} catch {}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
return {
|
|
434
|
+
processScope: "single-process",
|
|
435
|
+
async readText(path) {
|
|
436
|
+
try {
|
|
437
|
+
return await readFile(path, "utf8");
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (isMissing(error)) return null;
|
|
440
|
+
throw error;
|
|
441
|
+
}
|
|
442
|
+
},
|
|
443
|
+
async writeText(path, content) {
|
|
444
|
+
await mkdir(dirname(path), { recursive: true });
|
|
445
|
+
await inProcessWrite(path, async () => {
|
|
446
|
+
await sweepStaleTmps(path);
|
|
447
|
+
await commitTmp(await writeDurableTmp(path, content), path);
|
|
448
|
+
});
|
|
449
|
+
},
|
|
450
|
+
async transact(path, task) {
|
|
451
|
+
await mkdir(dirname(path), { recursive: true });
|
|
452
|
+
await inProcessWrite(path, async () => {
|
|
453
|
+
await sweepStaleTmps(path);
|
|
454
|
+
let current;
|
|
455
|
+
try {
|
|
456
|
+
current = await readFile(path, "utf8");
|
|
457
|
+
} catch (error) {
|
|
458
|
+
if (isMissing(error)) current = null;
|
|
459
|
+
else throw error;
|
|
460
|
+
}
|
|
461
|
+
const next = await task(current);
|
|
462
|
+
if (next === null) {
|
|
463
|
+
await rm(path, { force: true });
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (next === current) return;
|
|
467
|
+
await commitTmp(await writeDurableTmp(path, next), path);
|
|
468
|
+
});
|
|
469
|
+
},
|
|
470
|
+
async remove(path) {
|
|
471
|
+
await inProcessWrite(path, async () => {
|
|
472
|
+
await rm(path, {
|
|
473
|
+
recursive: true,
|
|
474
|
+
force: true
|
|
475
|
+
});
|
|
476
|
+
});
|
|
477
|
+
},
|
|
478
|
+
async list(path) {
|
|
479
|
+
try {
|
|
480
|
+
return await readdir(path);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
if (isMissing(error)) return [];
|
|
483
|
+
throw error;
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
async exists(path) {
|
|
487
|
+
try {
|
|
488
|
+
await stat(path);
|
|
489
|
+
return true;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (isMissing(error)) return false;
|
|
492
|
+
throw error;
|
|
493
|
+
}
|
|
494
|
+
},
|
|
495
|
+
async rename(path, destination) {
|
|
496
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
497
|
+
await renameWithRetry(path, destination);
|
|
498
|
+
},
|
|
499
|
+
async copy(path, destination) {
|
|
500
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
501
|
+
await cp(path, destination, {
|
|
502
|
+
recursive: true,
|
|
503
|
+
force: true
|
|
504
|
+
});
|
|
505
|
+
},
|
|
506
|
+
async size(path) {
|
|
507
|
+
try {
|
|
508
|
+
return (await stat(path)).size;
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (isMissing(error)) return null;
|
|
511
|
+
throw error;
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
async isSymlink(path) {
|
|
515
|
+
try {
|
|
516
|
+
return (await lstat(path)).isSymbolicLink();
|
|
517
|
+
} catch (error) {
|
|
518
|
+
if (isMissing(error)) return null;
|
|
519
|
+
throw error;
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
async mtime(path) {
|
|
523
|
+
try {
|
|
524
|
+
return (await stat(path)).mtimeMs;
|
|
525
|
+
} catch (error) {
|
|
526
|
+
if (isMissing(error)) return null;
|
|
527
|
+
throw error;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
const defaultFs = {
|
|
533
|
+
writeFileSync: (path, data) => {
|
|
534
|
+
writeFileSync(path, data);
|
|
535
|
+
},
|
|
536
|
+
existsSync: (path) => existsSync(path),
|
|
537
|
+
copyFileSync: (from, to) => {
|
|
538
|
+
copyFileSync(from, to);
|
|
539
|
+
},
|
|
540
|
+
renameSync: (from, to) => {
|
|
541
|
+
renameSync(from, to);
|
|
542
|
+
},
|
|
543
|
+
rmSync: (path, options) => {
|
|
544
|
+
rmSync(path, options);
|
|
545
|
+
},
|
|
546
|
+
mtime: (path) => {
|
|
547
|
+
try {
|
|
548
|
+
return statSync(path).mtimeMs;
|
|
549
|
+
} catch (error) {
|
|
550
|
+
if (isMissingPath(error)) return null;
|
|
551
|
+
throw error;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
/**
|
|
556
|
+
* S6.3 (E-40): atomically replace a set of files within one directory.
|
|
557
|
+
* Each file is staged to a sibling `<name>.tmp`, then renamed into place
|
|
558
|
+
* (atomic on the same filesystem); a pre-existing file keeps a single
|
|
559
|
+
* `<name>.bak`. A failure at ANY staging step removes the staged temps and
|
|
560
|
+
* leaves the previous files untouched — a half-written target is impossible
|
|
561
|
+
* up to the staging and backup phases.
|
|
562
|
+
*
|
|
563
|
+
* F-211: the rename COMMIT phase does not carry the same guarantee. When a
|
|
564
|
+
* filesystem refuses to overwrite the destination, the code removes it and
|
|
565
|
+
* retries the rename; if the retry ALSO fails the destination is gone. The
|
|
566
|
+
* single `.bak` created above still holds the previous content, so the target
|
|
567
|
+
* is restored from it (best-effort) before the original rename error is
|
|
568
|
+
* rethrown, so a failed commit never leaves the file missing.
|
|
569
|
+
*
|
|
570
|
+
* V4-17: the `.bak` is refreshed to the committed content after every
|
|
571
|
+
* successful commit, so a later failed commit always recovers to the most
|
|
572
|
+
* recent good generation (a once-at-first-install `.bak` could otherwise
|
|
573
|
+
* restore content several installs old). The recovery error names the `.bak`
|
|
574
|
+
* source (and mtime when available) so the caller knows the generation it
|
|
575
|
+
* restored from.
|
|
576
|
+
*/
|
|
577
|
+
function atomicWriteFiles(targetDir, writes, fs = defaultFs, logger = console.warn) {
|
|
578
|
+
const stage = (name) => join(targetDir, `${name}.tmp`);
|
|
579
|
+
const dupes = [...new Set(writes.map((write) => write.name).filter((name, index, all) => all.indexOf(name) !== index))];
|
|
580
|
+
if (dupes.length > 0) throw new Error(`atomicWriteFiles: duplicate input names: ${dupes.join(", ")}`);
|
|
581
|
+
try {
|
|
582
|
+
for (const { name, content } of writes) fs.writeFileSync(stage(name), content);
|
|
583
|
+
for (const { name } of writes) {
|
|
584
|
+
const finalPath = join(targetDir, name);
|
|
585
|
+
const bakPath = join(targetDir, `${name}.bak`);
|
|
586
|
+
if (fs.existsSync(finalPath) && !fs.existsSync(bakPath)) fs.copyFileSync(finalPath, bakPath);
|
|
587
|
+
}
|
|
588
|
+
const committed = [];
|
|
589
|
+
for (const { name } of writes) {
|
|
590
|
+
const finalPath = join(targetDir, name);
|
|
591
|
+
const bakPath = join(targetDir, `${name}.bak`);
|
|
592
|
+
const tmp = stage(name);
|
|
593
|
+
try {
|
|
594
|
+
fs.renameSync(tmp, finalPath);
|
|
595
|
+
committed.push(name);
|
|
596
|
+
} catch {
|
|
597
|
+
try {
|
|
598
|
+
fs.rmSync(finalPath, { force: true });
|
|
599
|
+
} catch (removeError) {
|
|
600
|
+
const already = committed.length > 0 ? `; already committed: ${committed.join(", ")}` : "";
|
|
601
|
+
throw new Error(`atomicWriteFiles: could not remove "${name}" to replace it (${removeError instanceof Error ? removeError.message : String(removeError)})${already}`);
|
|
602
|
+
}
|
|
603
|
+
try {
|
|
604
|
+
fs.renameSync(tmp, finalPath);
|
|
605
|
+
committed.push(name);
|
|
606
|
+
} catch (renameError) {
|
|
607
|
+
const already = committed.length > 0 ? `; already committed: ${committed.join(", ")}` : "";
|
|
608
|
+
if (fs.existsSync(bakPath)) {
|
|
609
|
+
try {
|
|
610
|
+
fs.copyFileSync(bakPath, finalPath);
|
|
611
|
+
} catch {
|
|
612
|
+
throw new Error(`atomicWriteFiles: "${name}" was removed but recovery from ${bakPath} failed (${renameError instanceof Error ? renameError.message : String(renameError)}); verify the file manually${already}`);
|
|
613
|
+
}
|
|
614
|
+
const bakMtime = fs.mtime?.(bakPath);
|
|
615
|
+
const when = bakMtime !== null && bakMtime !== void 0 && Number.isFinite(bakMtime) ? ` (bak mtime ${new Date(bakMtime).toISOString()})` : "";
|
|
616
|
+
throw new Error(`atomicWriteFiles: "${name}" was removed during commit and restored from the last good generation ${bakPath}${when}; original error: ${renameError instanceof Error ? renameError.message : String(renameError)}${already}`);
|
|
617
|
+
}
|
|
618
|
+
throw new Error(`${renameError instanceof Error ? renameError.message : String(renameError)}${already}`);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
for (const { name } of writes) {
|
|
623
|
+
const finalPath = join(targetDir, name);
|
|
624
|
+
try {
|
|
625
|
+
if (fs.existsSync(finalPath)) fs.copyFileSync(finalPath, join(targetDir, `${name}.bak`));
|
|
626
|
+
} catch (refreshError) {
|
|
627
|
+
logger(`atomicWriteFiles: committed "${name}" but failed to refresh its .bak (${refreshError instanceof Error ? refreshError.message : String(refreshError)}); a later failed commit will recover to an OLDER generation`);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
} catch (error) {
|
|
631
|
+
const cleanupFailures = [];
|
|
632
|
+
for (const { name } of writes) try {
|
|
633
|
+
fs.rmSync(stage(name), {
|
|
634
|
+
force: true,
|
|
635
|
+
recursive: true
|
|
636
|
+
});
|
|
637
|
+
} catch (cleanupError) {
|
|
638
|
+
cleanupFailures.push(`${name}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
|
|
639
|
+
}
|
|
640
|
+
if (cleanupFailures.length > 0) {
|
|
641
|
+
const original = error instanceof Error ? error.message : String(error);
|
|
642
|
+
throw new Error(`${original} (staged-temp cleanup also failed: ${cleanupFailures.join("; ")})`);
|
|
643
|
+
}
|
|
644
|
+
throw error;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
//#endregion
|
|
648
|
+
//#region lib/types/mutations.js
|
|
649
|
+
/**
|
|
650
|
+
* Curator/author audit trail: `.mutations.json` records every skill mutation
|
|
651
|
+
* with before/after content hashes so any automated edit is reviewable and
|
|
652
|
+
* replayable. Best-effort persistence, mirroring the usage sidecar posture.
|
|
653
|
+
* @module @lmzhen/dsh-evolution-core
|
|
654
|
+
*/
|
|
655
|
+
const DEFAULT_MUTATION_CAP = 500;
|
|
656
|
+
/** Version of the `.mutations.json` file shape; writers always emit the current one. */
|
|
657
|
+
const MUTATIONS_FILE_VERSION = 1;
|
|
658
|
+
function mutationsFile(root) {
|
|
659
|
+
return join(root, ".mutations.json");
|
|
660
|
+
}
|
|
661
|
+
function contentHash(content) {
|
|
662
|
+
return createHash("sha256").update(content.replaceAll("\r\n", "\n")).digest("hex");
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Parse a raw mutations sidecar; malformed content reads as empty (auditing is
|
|
666
|
+
* best-effort). Versioned shape ({ version, records }) with legacy
|
|
667
|
+
* plain-array compat, plus a field-level guard for records without the
|
|
668
|
+
* required identity/timestamp fields (rc.42 audit P2-3).
|
|
669
|
+
*/
|
|
670
|
+
function parseMutationRecords(raw) {
|
|
671
|
+
if (raw === null) return [];
|
|
672
|
+
try {
|
|
673
|
+
return recordsFromParsed(JSON.parse(raw));
|
|
674
|
+
} catch {
|
|
675
|
+
return [];
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
/** Field-level shape guard shared by the parse and the recordMutation write
|
|
679
|
+
* path (P3/v15: the guard's JSON.parse and this parse used to run twice over
|
|
680
|
+
* the same bytes inside one transact). */
|
|
681
|
+
function recordsFromParsed(parsed) {
|
|
682
|
+
return (Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.records) ? parsed.records : []).filter((entry) => typeof entry === "object" && entry !== null && typeof entry.skillName === "string" && typeof entry.action === "string" && typeof entry.at === "string");
|
|
683
|
+
}
|
|
684
|
+
async function loadMutations(root, io = nodeEvolutionIo()) {
|
|
685
|
+
return parseMutationRecords(await io.readText(mutationsFile(root)));
|
|
686
|
+
}
|
|
687
|
+
/** Append one record, trim to `cap`, and write atomically (versioned shape). */
|
|
688
|
+
async function recordMutation(root, io, record, cap = 500, fence) {
|
|
689
|
+
const write = async () => {
|
|
690
|
+
await transactIo(io, mutationsFile(root), (current) => {
|
|
691
|
+
let parsed = [];
|
|
692
|
+
if (current !== null) try {
|
|
693
|
+
parsed = JSON.parse(current);
|
|
694
|
+
} catch {
|
|
695
|
+
console.warn(`mutation audit record dropped: ${mutationsFile(root)} is malformed and was not overwritten`);
|
|
696
|
+
return current;
|
|
697
|
+
}
|
|
698
|
+
if (isRecord(parsed)) {
|
|
699
|
+
const version = parsed.version;
|
|
700
|
+
if (typeof version === "number" && version > 1) {
|
|
701
|
+
console.warn(`mutation audit record dropped: ${mutationsFile(root)} declares version ${version} (newer than 1); not overwritten`);
|
|
702
|
+
return current;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const existing = recordsFromParsed(parsed);
|
|
706
|
+
existing.push(record);
|
|
707
|
+
const trimmed = existing.length > cap ? existing.slice(existing.length - cap) : existing;
|
|
708
|
+
return JSON.stringify({
|
|
709
|
+
version: 1,
|
|
710
|
+
records: trimmed
|
|
711
|
+
}, null, 2);
|
|
712
|
+
});
|
|
713
|
+
};
|
|
714
|
+
if (fence !== void 0) await fence.run(write);
|
|
715
|
+
else await write();
|
|
716
|
+
}
|
|
717
|
+
//#endregion
|
|
718
|
+
export { valueOr as A, probeList as C, probeText as D, probeReason as E, probeUnknown as O, probeAbsent as S, probePresent as T, isAbsent as _, mutationsFile as a, isUnknown as b, evolutionIoAdapter as c, nodeEvolutionIo as d, renameWithRetry as f, declaredReportStamp as g, writeDurableTmp as h, loadMutations as i, reportTime as k, isCommittedWarning as l, transactTaskGuard as m, MUTATIONS_FILE_VERSION as n, recordMutation as o, transactIo as p, contentHash as r, atomicWriteFiles as s, DEFAULT_MUTATION_CAP as t, isProcessAlive as u, isMissingPath as v, probeMtime as w, mapProbe as x, isPresent as y };
|