@lmzhen/dsh-evolution-core 0.59.6 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +3 -1
  2. package/lib/authority-plugin.js +3 -2
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-B_F4TYOD.js → composition-BSqh70z_.js} +1 -1
  5. package/lib/{ensure-BpVDuDnA.js → ensure-DTCuxAxR.js} +1 -1
  6. package/lib/{extract-plan-D3ALlAmN.js → extract-plan-CP__XlEs.js} +2 -2
  7. package/lib/extract.js +4 -4
  8. package/lib/http-routes.js +3 -2
  9. package/lib/index.js +15 -15
  10. package/lib/{io-Cpa8wuvj.js → io-DT4-MXLr.js} +25 -1
  11. package/lib/io-node.js +1 -1
  12. package/lib/io-platform.js +163 -0
  13. package/lib/io-registry.js +10 -0
  14. package/lib/{mutation-authority-CZpc9F20.js → mutation-authority-C3RYyiaT.js} +66 -41
  15. package/lib/{mutation-storage-adapter-Cq1bmS1E.js → mutation-storage-adapter-CSVn34dK.js} +327 -210
  16. package/lib/{mutations-Y-wKod7W.js → mutations-JKFlfhSO.js} +1 -1
  17. package/lib/policy.js +1 -1
  18. package/lib/{quality-NPGr3VzA.js → quality-C0ri2SgY.js} +2 -2
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +1 -1
  21. package/lib/{review-context-yNiZadPw.js → review-context-D2LIOEi-.js} +2 -2
  22. package/lib/runtime/plugin.js +2 -2
  23. package/lib/{session-projection-DM15fsRp.js → session-projection-Dnmm5bzt.js} +1 -1
  24. package/lib/{skill-history-BvLWFoOo.js → skill-history-BOZ4HCDB.js} +2 -2
  25. package/lib/skills.js +268 -37
  26. package/lib/state/domain/index.js +433 -0
  27. package/lib/state/index.js +136 -0
  28. package/lib/state/migrate.js +90 -0
  29. package/lib/state/storage.js +605 -0
  30. package/lib/state/store-plugin.js +23 -0
  31. package/lib/state/store.js +268 -0
  32. package/lib/subagent/index.js +1 -1
  33. package/lib/types/authority-plugin.d.ts +1 -1
  34. package/lib/types/authority-plugin.js +2 -1
  35. package/lib/types/authority.d.ts +1 -1
  36. package/lib/types/authority.js +75 -48
  37. package/lib/types/composition/ensure.js +1 -1
  38. package/lib/types/contract.d.ts +8 -0
  39. package/lib/types/http-routes.d.ts +1 -0
  40. package/lib/types/http-routes.js +2 -1
  41. package/lib/types/io-platform.d.ts +74 -0
  42. package/lib/types/io-platform.js +178 -0
  43. package/lib/types/io-registry.d.ts +4 -0
  44. package/lib/types/io-registry.js +10 -0
  45. package/lib/types/io.d.ts +7 -0
  46. package/lib/types/io.js +25 -1
  47. package/lib/types/mutation-authority.d.ts +1 -1
  48. package/lib/types/mutation-storage-adapter.d.ts +1 -1
  49. package/lib/types/opt-in.js +2 -2
  50. package/lib/types/params.js +2 -2
  51. package/lib/types/policy.js +1 -1
  52. package/lib/types/restrictor.js +2 -2
  53. package/lib/types/result.d.ts +1 -1
  54. package/lib/types/result.js +1 -1
  55. package/lib/types/runtime/coherence.js +1 -1
  56. package/lib/types/runtime/llm.d.ts +1 -1
  57. package/lib/types/runtime/llm.js +1 -1
  58. package/lib/types/runtime/platform.d.ts +3 -3
  59. package/lib/types/runtime/platform.js +2 -2
  60. package/lib/types/runtime/projections.d.ts +1 -1
  61. package/lib/types/scope.js +1 -1
  62. package/lib/types/session-projection.d.ts +1 -1
  63. package/lib/types/signals.d.ts +1 -1
  64. package/lib/types/skill-store.d.ts +37 -4
  65. package/lib/types/skill-store.js +240 -24
  66. package/lib/types/skill-write-plan.d.ts +1 -1
  67. package/lib/types/skill-write-service.js +8 -2
  68. package/lib/types/state/conformance.d.ts +47 -0
  69. package/lib/types/state/conformance.js +246 -0
  70. package/lib/types/state/constants.d.ts +52 -0
  71. package/lib/types/state/constants.js +52 -0
  72. package/lib/types/state/domain/compatibility.d.ts +40 -0
  73. package/lib/types/state/domain/compatibility.js +36 -0
  74. package/lib/types/state/domain/index.d.ts +81 -0
  75. package/lib/types/state/domain/index.js +592 -0
  76. package/lib/types/state/index.d.ts +63 -0
  77. package/lib/types/state/index.js +174 -0
  78. package/lib/types/state/medium-declaration.d.ts +37 -0
  79. package/lib/types/state/medium-declaration.js +53 -0
  80. package/lib/types/state/migrate.d.ts +34 -0
  81. package/lib/types/state/migrate.js +103 -0
  82. package/lib/types/state/record-contract.d.ts +56 -0
  83. package/lib/types/state/record-contract.js +120 -0
  84. package/lib/types/state/storage.d.ts +112 -0
  85. package/lib/types/state/storage.js +178 -0
  86. package/lib/types/state/store-plugin.d.ts +14 -0
  87. package/lib/types/state/store-plugin.js +18 -0
  88. package/lib/types/state/store.d.ts +39 -0
  89. package/lib/types/state/store.js +270 -0
  90. package/lib/types/store-ledger.js +2 -2
  91. package/lib/types/subagent/run.d.ts +1 -1
  92. package/lib/types/subagent/types.d.ts +4 -4
  93. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  94. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  95. package/lib/types/tool-dispatch.js +6 -3
  96. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +40 -13
  97. package/lib/types/{mutation-unit.js → unit-kernel.js} +155 -118
  98. package/lib/types/write.d.ts +1 -2
  99. package/lib/types/write.js +1 -2
  100. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  101. package/lib/write.js +4 -4
  102. package/package.json +30 -3
  103. package/persisted-write-inventory.json +14 -5
@@ -0,0 +1,268 @@
1
+ import { c as transactIo } from "../io-DT4-MXLr.js";
2
+ import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
3
+ import { CURATOR_STATE_TABLE, PENDING_TABLE, PROVIDER_STORE, REVIEW_STATE_TABLE, assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, selectPendingOverflow, selectSessionOverflow } from "./storage.js";
4
+ import "./index.js";
5
+ import { join } from "node:path";
6
+ //#region lib/types/state/store.js
7
+ /**
8
+ * File-backed StateStore provider.
9
+ *
10
+ * This is the first D1 step: the provider owns ONE JSON file and every
11
+ * transition is a read-modify-write inside the IO seam's transaction. There is
12
+ * no process-local authoritative copy; `reload()` is therefore unnecessary and
13
+ * reads always observe the medium.
14
+ *
15
+ * It is intentionally not mounted by the bundle yet: the domain provider is
16
+ * still the shipped one until the migration/rollback path is implemented.
17
+ * @module @lmzhen/dsh-evolution-core/state/store
18
+ */
19
+ const STORE_VERSION = 1;
20
+ const emptyStore = () => ({
21
+ version: STORE_VERSION,
22
+ review: {},
23
+ curator: null,
24
+ pending: {}
25
+ });
26
+ /** Validate and publish a complete store image. The write is create-if-absent:
27
+ * an existing store is never overwritten by a migration. */
28
+ async function writeStateStoreSnapshot(io, path, snapshot) {
29
+ const text = serialize({
30
+ ...emptyStore(),
31
+ ...snapshot
32
+ });
33
+ parseStore(text);
34
+ if (io.exists !== void 0 && await io.exists(path)) throw new Error("evolution-state-store: refusing to overwrite an existing store: " + path);
35
+ if (io.createTextIfAbsent !== void 0) {
36
+ await io.createTextIfAbsent(path, text);
37
+ return;
38
+ }
39
+ if (io.exists !== void 0 && await io.exists(path)) throw new Error("evolution-state-store: refusing to overwrite an existing store: " + path);
40
+ await io.writeText(path, text);
41
+ }
42
+ function invalid(message) {
43
+ throw new Error("evolution-state-store: " + message);
44
+ }
45
+ /** Parse and validate one whole store image. A corrupt store fails loud: silently
46
+ * treating it as empty would overwrite the only copy. */
47
+ function parseStore(text) {
48
+ if (text === null || text.trim() === "") return emptyStore();
49
+ let raw;
50
+ try {
51
+ raw = JSON.parse(text);
52
+ } catch (error) {
53
+ invalid("store is not valid JSON: " + (error instanceof Error ? error.message : String(error)));
54
+ }
55
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) invalid("store must be an object");
56
+ const candidate = raw;
57
+ if (candidate.version !== STORE_VERSION) invalid("unsupported store version: " + String(candidate.version));
58
+ const review = candidate.review;
59
+ const pending = candidate.pending;
60
+ if (typeof review !== "object" || review === null || Array.isArray(review)) invalid("review must be an object");
61
+ if (typeof pending !== "object" || pending === null || Array.isArray(pending)) invalid("pending must be an object");
62
+ const store = emptyStore();
63
+ for (const [sessionId, record] of Object.entries(review)) {
64
+ const issue = recordIssue(REVIEW_STATE_TABLE, record);
65
+ if (issue !== null) invalid(`review[${sessionId}]: ${issue}`);
66
+ store.review[sessionId] = cloneRecord(record);
67
+ }
68
+ for (const [key, record] of Object.entries(pending)) {
69
+ const issue = recordIssue(PENDING_TABLE, record);
70
+ if (issue !== null) invalid(`pending[${key}]: ${issue}`);
71
+ const pendingRecord = cloneRecord(record);
72
+ if (pendingRecord.id !== key) {
73
+ if (store.pending[pendingRecord.id] === void 0) store.pending[pendingRecord.id] = pendingRecord;
74
+ continue;
75
+ }
76
+ store.pending[pendingRecord.id] = pendingRecord;
77
+ }
78
+ const curator = candidate.curator;
79
+ if (curator !== void 0 && curator !== null) {
80
+ const issue = recordIssue(CURATOR_STATE_TABLE, curator);
81
+ if (issue !== null) invalid("curator: " + issue);
82
+ store.curator = cloneRecord(curator);
83
+ }
84
+ return store;
85
+ }
86
+ const serialize = (store) => JSON.stringify(store, null, 2) + "\n";
87
+ /**
88
+ * Build the file-backed provider. All mutating methods are a single
89
+ * `transactIo` RMW; readers parse the current file, never a cached copy.
90
+ */
91
+ function createStateStoreProvider(options) {
92
+ const file = options.path ?? join(options.home ?? evolutionHome(), "state", "store.json");
93
+ const io = options.io;
94
+ const read = async () => parseStore(await io.readText(file));
95
+ const mutate = async (task) => {
96
+ let result;
97
+ let ran = false;
98
+ await transactIo(io, file, (current) => {
99
+ const store = parseStore(current);
100
+ const outcome = task(store);
101
+ if (outcome instanceof Promise) return outcome.then((value) => {
102
+ result = value;
103
+ ran = true;
104
+ const next = serialize(store);
105
+ return next === current ? current : next;
106
+ });
107
+ result = outcome;
108
+ ran = true;
109
+ const next = serialize(store);
110
+ return next === current ? current : next;
111
+ });
112
+ if (!ran) throw new Error("evolution-state-store: transaction did not run the task");
113
+ return result;
114
+ };
115
+ const savePendingValidated = (record) => {
116
+ const issue = recordIssue("pending", record) ?? assertCloneable(record);
117
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid pending record: " + issue);
118
+ return cloneRecord(record);
119
+ };
120
+ return {
121
+ name: PROVIDER_STORE,
122
+ async listReviewStates() {
123
+ return Object.entries((await read()).review).map(([sessionId, record]) => {
124
+ const { updatedAt, ...consumer } = record;
125
+ return {
126
+ sessionId,
127
+ record: structuredClone(consumer),
128
+ ...updatedAt === void 0 ? {} : { updatedAt }
129
+ };
130
+ });
131
+ },
132
+ async loadReviewState(sessionId) {
133
+ const stored = (await read()).review[sessionId];
134
+ if (stored === void 0) return null;
135
+ const { updatedAt: _updatedAt, ...consumer } = stored;
136
+ return structuredClone(consumer);
137
+ },
138
+ async saveReviewState(sessionId, record) {
139
+ const issue = recordIssue("review_state", record) ?? assertCloneable(record);
140
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid review-state record: " + issue);
141
+ await mutate((store) => {
142
+ store.review[sessionId] = {
143
+ ...cloneRecord(record),
144
+ updatedAt: Date.now()
145
+ };
146
+ const entries = Object.entries(store.review).filter(([key]) => key !== sessionId).map(([key, row]) => ({
147
+ key,
148
+ updatedAt: row.updatedAt ?? 0
149
+ }));
150
+ for (const victim of selectSessionOverflow(entries, {
151
+ keyOf: (entry) => entry.key,
152
+ stampOf: (entry) => entry.updatedAt
153
+ }, 500)) {
154
+ const current = store.review[victim];
155
+ if (current === void 0) continue;
156
+ if ((current.updatedAt ?? 0) !== entries.find((entry) => entry.key === victim)?.updatedAt) continue;
157
+ delete store.review[victim];
158
+ }
159
+ });
160
+ },
161
+ async loadCuratorState() {
162
+ const curator = (await read()).curator;
163
+ return curator === null ? null : structuredClone(curator);
164
+ },
165
+ async saveCuratorState(record) {
166
+ const issue = recordIssue("curator_state", record) ?? assertCloneable(record);
167
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid curator-state record: " + issue);
168
+ await mutate((store) => {
169
+ store.curator = cloneRecord(record);
170
+ });
171
+ },
172
+ async transactCuratorState(task) {
173
+ await mutate((store) => {
174
+ const next = task(store.curator === null ? null : cloneRecord(store.curator));
175
+ if (next === null) return;
176
+ const issue = recordIssue("curator_state", next) ?? assertCloneable(next);
177
+ if (issue !== null) throw new Error("evolution-state-store: refusing to persist an invalid curator-state record: " + issue);
178
+ store.curator = cloneRecord(next);
179
+ });
180
+ },
181
+ async listPending(status = "pending") {
182
+ const store = await read();
183
+ const seen = /* @__PURE__ */ new Set();
184
+ const out = [];
185
+ for (const record of Object.values(store.pending)) {
186
+ if (record.status !== status) continue;
187
+ if (seen.has(record.id)) continue;
188
+ seen.add(record.id);
189
+ out.push(structuredClone(record));
190
+ }
191
+ return out;
192
+ },
193
+ async savePending(record) {
194
+ const valid = savePendingValidated(record);
195
+ await mutate((store) => {
196
+ store.pending[valid.id] = valid;
197
+ });
198
+ },
199
+ async claimPending(id, claimId) {
200
+ let claimed = null;
201
+ await mutate((store) => {
202
+ const current = store.pending[id];
203
+ if (current === void 0 || !canClaimPending(current.status)) return;
204
+ const next = {
205
+ ...current,
206
+ status: "executing",
207
+ claimedBy: claimId,
208
+ claimedAt: (/* @__PURE__ */ new Date()).toISOString()
209
+ };
210
+ store.pending[id] = next;
211
+ claimed = structuredClone(next);
212
+ });
213
+ return claimed;
214
+ },
215
+ async releasePendingClaim(id, claimId) {
216
+ await mutate((store) => {
217
+ const current = store.pending[id];
218
+ if (current === void 0 || current.claimedBy !== claimId) return;
219
+ if (current.status !== "pending" && current.status !== "executing") return;
220
+ const next = {
221
+ ...current,
222
+ status: releasedStatus(current.status)
223
+ };
224
+ delete next.claimedBy;
225
+ delete next.claimedAt;
226
+ store.pending[id] = next;
227
+ });
228
+ },
229
+ async tryResolvePending(id, status, expectedClaimId) {
230
+ let outcome = {
231
+ record: null,
232
+ applied: false
233
+ };
234
+ await mutate((store) => {
235
+ const current = store.pending[id];
236
+ if (current === void 0) return;
237
+ if (!canResolvePending(current.status)) {
238
+ outcome = {
239
+ record: structuredClone(current),
240
+ applied: false
241
+ };
242
+ return;
243
+ }
244
+ if (expectedClaimId !== void 0 && current.claimedBy !== expectedClaimId) {
245
+ outcome = {
246
+ record: structuredClone(current),
247
+ applied: false
248
+ };
249
+ return;
250
+ }
251
+ const resolved = {
252
+ ...current,
253
+ status,
254
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
255
+ };
256
+ store.pending[id] = resolved;
257
+ outcome = {
258
+ record: structuredClone(resolved),
259
+ applied: true
260
+ };
261
+ for (const victim of selectPendingOverflow(Object.values(store.pending), 200)) if (store.pending[victim.id]?.resolvedAt === victim.resolvedAt) delete store.pending[victim.id];
262
+ });
263
+ return outcome;
264
+ }
265
+ };
266
+ }
267
+ //#endregion
268
+ export { createStateStoreProvider, writeStateStoreSnapshot };
@@ -1,4 +1,4 @@
1
- import { h as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-BpVDuDnA.js";
1
+ import { h as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-DTCuxAxR.js";
2
2
  //#region lib/types/subagent/readiness.js
3
3
  /** Pure derivation (no side effects): the doctor reads this, the channel re-probes on every run. */
4
4
  function probeChannelState(ctx, kind) {
@@ -14,5 +14,5 @@ export declare const Config: Schema<Config>;
14
14
  export declare const name = "evolution-authority";
15
15
  export declare const inject: string[];
16
16
  /** Expose the single home/run-fenced mutation authority to domain packages. */
17
- export declare function apply(ctx: Context, config?: Config): void;
17
+ export declare function apply(ctx: Context, config?: Config): Promise<void>;
18
18
  //# sourceMappingURL=authority-plugin.d.ts.map
@@ -7,7 +7,8 @@ export const Config = z.object({
7
7
  export const name = 'evolution-authority';
8
8
  export const inject = ['evolutionIo'];
9
9
  /** Expose the single home/run-fenced mutation authority to domain packages. */
10
- export function apply(ctx, config = { keyedSkillLocks: false }) {
10
+ export async function apply(ctx, config = { keyedSkillLocks: false }) {
11
+ await ctx.evolutionIo.whenReady();
11
12
  const authority = new MutationAuthority({
12
13
  io: ctx.evolutionIo.provider(),
13
14
  home: evolutionHome(),
@@ -1,4 +1,4 @@
1
- import { withFileLock as platformFileLock } from '@lmzhen/dsh-evolution-adapter/values';
1
+ import { withFileLock as platformFileLock } from '@lmzhen/dsh-evolution-platform/values/fs';
2
2
  /** The lock handle a serialized body receives; `release` is a no-op when a scope owns it. */
3
3
  export interface TreeLock {
4
4
  readonly token: string;
@@ -18,9 +18,9 @@
18
18
  */
19
19
  import { AsyncLocalStorage } from 'node:async_hooks';
20
20
  import { createHash } from 'node:crypto';
21
- import { mkdir, readFile, rm } from 'node:fs/promises';
21
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
22
22
  import { dirname, join } from 'node:path';
23
- import { withFileLock as platformFileLock } from '@lmzhen/dsh-evolution-adapter/values';
23
+ import { withFileLock as platformFileLock } from '@lmzhen/dsh-evolution-platform/values/fs';
24
24
  import { isProcessAlive } from "./io.js";
25
25
  /** Who holds the home lock right now, for doctor rows; `undefined` means free or unreadable. */
26
26
  export async function authorityHolder(home) {
@@ -213,44 +213,19 @@ export class TargetLockSet {
213
213
  const skipped = [];
214
214
  for (const key of [...this.brokenKeys]) {
215
215
  const path = this.lockPath(key) + '.lock';
216
- let raw;
216
+ let removed = false;
217
217
  try {
218
- raw = await readFile(path, 'utf8');
218
+ removed = await removeExitedLock(path);
219
219
  }
220
- catch (error) {
221
- if (error.code === 'ENOENT') {
222
- this.brokenKeys.delete(key);
223
- repaired.push(key);
224
- }
225
- else {
226
- skipped.push(key);
227
- }
228
- continue;
229
- }
230
- const pid = Number.parseInt(raw.trim(), 10);
231
- if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && isProcessAlive(pid)) {
232
- skipped.push(key);
233
- continue;
220
+ catch {
221
+ removed = false;
234
222
  }
235
- try {
236
- await rm(path, { force: true });
237
- try {
238
- await readFile(path, 'utf8');
239
- skipped.push(key);
240
- }
241
- catch (error) {
242
- if (error.code === 'ENOENT') {
243
- this.brokenKeys.delete(key);
244
- repaired.push(key);
245
- }
246
- else {
247
- skipped.push(key);
248
- }
249
- }
223
+ if (removed) {
224
+ this.brokenKeys.delete(key);
225
+ repaired.push(key);
250
226
  }
251
- catch {
227
+ else
252
228
  skipped.push(key);
253
- }
254
229
  }
255
230
  return { repaired, skipped };
256
231
  }
@@ -264,6 +239,70 @@ export class TargetLockSet {
264
239
  return await this.lock(path, body, { waitMs: this.waitMs });
265
240
  }
266
241
  }
242
+ /**
243
+ * Remove a lock file only through the platform's takeover claim protocol: write a claim named
244
+ * after the exact recorded holder, re-read under it, then remove only if the record and its dead
245
+ * PID are unchanged. A repair that rm()s directly can delete a lock another contender acquired
246
+ * after the dead holder's.
247
+ * @param lockPath - the lock file to remove.
248
+ * @returns true when this call removed it (or it was already absent).
249
+ */
250
+ async function removeExitedLock(lockPath) {
251
+ let record;
252
+ try {
253
+ record = await readFile(lockPath, 'utf8');
254
+ }
255
+ catch (error) {
256
+ if (error.code === 'ENOENT')
257
+ return true;
258
+ throw error;
259
+ }
260
+ const pid = Number.parseInt(record.trim(), 10);
261
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && isProcessAlive(pid))
262
+ return false;
263
+ const claim = lockPath + '.takeover-' + createHash('sha256').update(record).digest('hex').slice(0, 16);
264
+ try {
265
+ await writeFile(claim, String(process.pid) + '\n', { mode: 0o600, flag: 'wx' });
266
+ }
267
+ catch (error) {
268
+ const code = error.code;
269
+ if (code === 'EEXIST' || code === 'EPERM')
270
+ return false;
271
+ throw error;
272
+ }
273
+ try {
274
+ let again;
275
+ try {
276
+ again = await readFile(lockPath, 'utf8');
277
+ }
278
+ catch (error) {
279
+ if (error.code === 'ENOENT')
280
+ return true;
281
+ throw error;
282
+ }
283
+ if (again !== record)
284
+ return false;
285
+ const againPid = Number.parseInt(again.trim(), 10);
286
+ if (Number.isInteger(againPid) && againPid > 0 && againPid !== process.pid && isProcessAlive(againPid))
287
+ return false;
288
+ try {
289
+ await rm(lockPath, { force: true });
290
+ }
291
+ catch {
292
+ return false;
293
+ }
294
+ try {
295
+ await readFile(lockPath, 'utf8');
296
+ return false;
297
+ }
298
+ catch (error) {
299
+ return error.code === 'ENOENT';
300
+ }
301
+ }
302
+ finally {
303
+ await rm(claim, { force: true }).catch(() => { });
304
+ }
305
+ }
267
306
  export class HomeAuthority {
268
307
  options;
269
308
  held = new Map();
@@ -404,20 +443,8 @@ export class HomeAuthority {
404
443
  if (this.pending === undefined || this.held.size > 0)
405
444
  return 'noop';
406
445
  const lockPath = this.lockBase + '.lock';
407
- let holder;
408
- try {
409
- const raw = await readFile(lockPath, 'utf8');
410
- const pid = Number.parseInt(raw.trim(), 10);
411
- holder = Number.isInteger(pid) && pid > 0 ? pid : undefined;
412
- }
413
- catch (error) {
414
- if (error.code !== 'ENOENT')
415
- throw error;
416
- holder = undefined;
417
- }
418
- if (holder !== undefined && holder !== process.pid && isProcessAlive(holder))
446
+ if (!await removeExitedLock(lockPath))
419
447
  return 'noop';
420
- await rm(lockPath, { force: true });
421
448
  this.pending = undefined;
422
449
  return 'repaired';
423
450
  }
@@ -1,4 +1,4 @@
1
- import { presetsPort } from '@lmzhen/dsh-evolution-adapter/ports';
1
+ import { presetsPort } from '@lmzhen/dsh-evolution-platform/ports';
2
2
  import { normalizeAllow } from "./preset-ids.js";
3
3
  import { composeRestrictedPresetDefinition, } from "./restricted-preset.js";
4
4
  const SLOTS = new WeakMap();
@@ -73,6 +73,14 @@ export interface PendingResolution {
73
73
  /** Provider seam for durable evolution state; implementations own the medium. */
74
74
  export interface EvolutionStateStorage {
75
75
  readonly name: string;
76
+ /** Re-read the durable medium; providers authoritative in memory omit this. */
77
+ reload?(): Promise<void>;
78
+ /** Migration/diagnostics only: all review rows with their eviction stamps. */
79
+ listReviewStates?(): Promise<readonly {
80
+ sessionId: string;
81
+ record: ReviewStateRecord;
82
+ updatedAt?: number;
83
+ }[]>;
76
84
  loadReviewState(sessionId: string): Promise<ReviewStateRecord | null>;
77
85
  saveReviewState(sessionId: string, record: ReviewStateRecord): Promise<void>;
78
86
  loadCuratorState(): Promise<CuratorStateRecord | null>;
@@ -62,6 +62,7 @@ export declare const HOST_ROUTES: {
62
62
  readonly runs: "/api/dsh-evolution/merge/runs";
63
63
  readonly body: "/api/dsh-evolution/merge/body";
64
64
  readonly history: "/api/dsh-evolution/merge/history";
65
+ readonly decision: "/api/dsh-evolution/merge/decision";
65
66
  };
66
67
  readonly diagnostics: {
67
68
  readonly view: "/api/dsh-evolution/diagnostics";
@@ -11,7 +11,7 @@
11
11
  * @module @lmzhen/dsh-evolution-core/http-routes
12
12
  */
13
13
  import { isRecord } from "./guards.js";
14
- import { connectionPort } from '@lmzhen/dsh-evolution-adapter/ports';
14
+ import { connectionPort } from '@lmzhen/dsh-evolution-platform/ports';
15
15
  /** Largest request body a family route accepts; a bigger one reads as "no body" (400 from the handler). */
16
16
  export const MAX_REQUEST_BODY_BYTES = 64 * 1024;
17
17
  /**
@@ -60,6 +60,7 @@ export const HOST_ROUTES = {
60
60
  runs: '/api/dsh-evolution/merge/runs',
61
61
  body: '/api/dsh-evolution/merge/body',
62
62
  history: '/api/dsh-evolution/merge/history',
63
+ decision: '/api/dsh-evolution/merge/decision',
63
64
  },
64
65
  diagnostics: {
65
66
  view: '/api/dsh-evolution/diagnostics',
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Platform-backed `EvolutionIo` provider.
3
+ *
4
+ * This is the Phase-B bridge: business code keeps its existing `EvolutionIoLike`
5
+ * seam, while the production backend becomes the platform filesystem
6
+ * (`ctx.fs`, implemented by `@deepseek-ai/dsh-fs-local`) instead of the family's
7
+ * own `node:fs` writer. Target identity, per-target locks and atomic publication
8
+ * therefore have one owner: the platform.
9
+ *
10
+ * Structural `PlatformFs` is deliberate: this package consumes the platform
11
+ * service shape without adding a runtime dependency; every operation is a
12
+ * one-to-one mapping, and no plugin-local write primitive is introduced.
13
+ *
14
+ * @module @lmzhen/dsh-evolution-core/io-platform
15
+ */
16
+ import type { Context } from '@deepseek-ai/cordis';
17
+ import type { EvolutionIo } from './io-registry.ts';
18
+ interface PlatformTarget {
19
+ readonly targetKey: string;
20
+ readonly displayPath: string;
21
+ }
22
+ interface PlatformInfo {
23
+ readonly version: string;
24
+ readonly type: string;
25
+ readonly size?: number;
26
+ }
27
+ interface PlatformWriteIntent {
28
+ readonly kind: 'createIfAbsent' | 'replaceIfVersion';
29
+ readonly version?: string;
30
+ }
31
+ interface PlatformEdit {
32
+ readonly oldString: string;
33
+ readonly newString: string;
34
+ readonly replaceAll: boolean;
35
+ }
36
+ /** The public subset of `ctx.fs` this adapter consumes. */
37
+ export interface PlatformFs {
38
+ resolve(path: string): Promise<PlatformTarget>;
39
+ stat(target: PlatformTarget): Promise<PlatformInfo | undefined>;
40
+ readText(target: PlatformTarget): Promise<string>;
41
+ writeText(target: PlatformTarget, content: string, expected?: PlatformWriteIntent): Promise<unknown>;
42
+ editText(target: PlatformTarget, edit: PlatformEdit, expected?: {
43
+ readonly version: string;
44
+ }): Promise<unknown>;
45
+ deleteFile(target: PlatformTarget, expected?: {
46
+ readonly version: string;
47
+ }): Promise<unknown>;
48
+ listDir(target: PlatformTarget): Promise<Array<{
49
+ readonly name: string;
50
+ }>>;
51
+ moveFile(source: PlatformTarget, destination: PlatformTarget, options: unknown): Promise<{
52
+ readonly sourceDeleted: boolean;
53
+ }>;
54
+ lstat(path: string): Promise<{
55
+ readonly type: string;
56
+ } | undefined>;
57
+ }
58
+ /**
59
+ * Adapt one platform filesystem service to the family's existing IO seam.
60
+ * @param fs - the platform filesystem service (structurally `ctx.fs`).
61
+ * @returns the provider, ready for `ctx.evolutionIo.registerProvider`.
62
+ */
63
+ export declare function platformEvolutionIo(fs: PlatformFs, options?: {
64
+ readonly withFileLock?: <T>(path: string, task: () => Promise<T>) => Promise<T>;
65
+ }): EvolutionIo;
66
+ export declare const name = "evolution-io-platform";
67
+ export declare const inject: string[];
68
+ /**
69
+ * Register the platform provider as the default IO backend.
70
+ * @param ctx - plugin context carrying `evolutionIo` and `fs`.
71
+ */
72
+ export declare function apply(ctx: Context): void;
73
+ export {};
74
+ //# sourceMappingURL=io-platform.d.ts.map