dsh-recency-guard 0.16.0 → 0.18.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/dist/index.js CHANGED
@@ -75,11 +75,42 @@ function readHostVersion() {
75
75
  }
76
76
  }
77
77
 
78
+ // src/host/core/config-strict.ts
79
+ var ConfigError = class extends Error {
80
+ constructor(message) {
81
+ super(`dsh-recency-guard config: ${message}`);
82
+ this.name = "ConfigError";
83
+ }
84
+ };
85
+ var CONFIG_KNOWN_KEYS = [
86
+ "enabled",
87
+ "includeExperimental",
88
+ "maxAutoDisable",
89
+ "autoRestore",
90
+ "confirmRounds",
91
+ "versionedBackups",
92
+ "backupRetain",
93
+ "backupRoot"
94
+ ];
95
+ var CORDIS_INTERNAL_PREFIX = "$";
96
+ function rejectUnknownConfigKeys(raw, known = CONFIG_KNOWN_KEYS) {
97
+ if (raw === null || raw === void 0) return;
98
+ if (typeof raw !== "object" || Array.isArray(raw)) return;
99
+ const knownSet = new Set(known);
100
+ const unknown = Object.keys(raw).filter(
101
+ (key) => !key.startsWith(CORDIS_INTERNAL_PREFIX) && !knownSet.has(key)
102
+ );
103
+ if (unknown.length === 0) return;
104
+ const unknownList = unknown.map((k) => JSON.stringify(k)).join(", ");
105
+ const knownList = known.map((k) => JSON.stringify(k)).join(", ");
106
+ throw new ConfigError(`unknown key(s) ${unknownList}; accepted keys are ${knownList}`);
107
+ }
108
+
78
109
  // src/host/data/store.ts
79
- import { appendFile, mkdir, readFile as readFile2, readdir, stat, unlink } from "node:fs/promises";
80
- import { appendFileSync, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync2, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
81
- import { isAbsolute, join as join3, resolve } from "node:path";
82
- import { writeFileAtomic as writeFileAtomic2, withFileLock } from "@deepseek-ai/dsh-atomic-write";
110
+ import { appendFile, mkdir, readFile as readFile3, readdir, stat, unlink } from "node:fs/promises";
111
+ import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
112
+ import { isAbsolute, join as join4, resolve } from "node:path";
113
+ import { writeFileAtomic as writeFileAtomic2, withFileLock as withFileLock2 } from "@deepseek-ai/dsh-atomic-write";
83
114
 
84
115
  // src/host/core/atomic-sync.ts
85
116
  import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -102,22 +133,182 @@ function writeFileAtomicSync(path, content) {
102
133
  }
103
134
  }
104
135
 
105
- // src/host/observe/cooccurrence-store.ts
106
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, writeFileSync as writeFileSync2 } from "node:fs";
136
+ // src/host/data/journal-io.ts
137
+ import { existsSync as existsSync2, readFileSync as readTextFileSync, readdirSync, renameSync as renameSync2, unlinkSync } from "node:fs";
107
138
  import { readFile } from "node:fs/promises";
108
- import { dirname as dirname2, join } from "node:path";
139
+ import { join } from "node:path";
140
+ import { withFileLock } from "@deepseek-ai/dsh-atomic-write";
141
+ var JOURNAL_MAX_LINES = 1e3;
142
+ var JOURNAL_ACTIVE_NAME = "journal.jsonl";
143
+ var ROTATED_PREFIX = "journal.";
144
+ var ROTATED_SUFFIX = ".jsonl";
145
+ function journalLines(raw) {
146
+ return raw ? raw.split("\n").filter(Boolean) : [];
147
+ }
148
+ function parseJournalLines(raw, limit) {
149
+ const lines = journalLines(raw);
150
+ const take = Number.isFinite(limit) && limit > 0 ? Math.min(Math.floor(limit), lines.length) : 0;
151
+ const out = [];
152
+ for (const line of lines.slice(lines.length - take)) {
153
+ try {
154
+ out.push(JSON.parse(line));
155
+ } catch {
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+ function rotatedJournalPaths(dir) {
161
+ let names;
162
+ try {
163
+ names = readdirSync(dir);
164
+ } catch {
165
+ return [];
166
+ }
167
+ const epochs = [];
168
+ for (const name2 of names) {
169
+ if (!name2.startsWith(ROTATED_PREFIX) || !name2.endsWith(ROTATED_SUFFIX)) continue;
170
+ const middle = name2.slice(ROTATED_PREFIX.length, name2.length - ROTATED_SUFFIX.length);
171
+ const epoch = Number(middle);
172
+ if (!Number.isFinite(epoch) || middle === "") continue;
173
+ epochs.push({ epoch, name: name2 });
174
+ }
175
+ return epochs.sort((a, b) => a.epoch - b.epoch).map((e) => join(dir, e.name));
176
+ }
177
+ function activeJournalPath(dir) {
178
+ return join(dir, JOURNAL_ACTIVE_NAME);
179
+ }
180
+ async function trimJournalFile(dir, readText = (path) => readFile(path, "utf8")) {
181
+ const journalPath = activeJournalPath(dir);
182
+ try {
183
+ if (!existsSync2(journalPath)) return;
184
+ if (journalLines(await readText(journalPath)).length <= JOURNAL_MAX_LINES) return;
185
+ await withFileLock(
186
+ journalPath,
187
+ async () => {
188
+ const latest = journalLines(await readText(journalPath));
189
+ if (latest.length <= JOURNAL_MAX_LINES) return;
190
+ let epoch = Date.now();
191
+ let target = join(dir, `${ROTATED_PREFIX}${epoch}${ROTATED_SUFFIX}`);
192
+ while (existsSync2(target)) {
193
+ epoch += 1;
194
+ target = join(dir, `${ROTATED_PREFIX}${epoch}${ROTATED_SUFFIX}`);
195
+ }
196
+ renameSync2(journalPath, target);
197
+ enforceRotatedLimit(dir);
198
+ },
199
+ { waitMs: 3e3 }
200
+ );
201
+ } catch {
202
+ }
203
+ }
204
+ var MAX_ROTATED_FILES = 3;
205
+ function enforceRotatedLimit(dir) {
206
+ const rotated = rotatedJournalPaths(dir);
207
+ const excess = rotated.length - MAX_ROTATED_FILES;
208
+ for (let i = 0; i < excess; i += 1) {
209
+ try {
210
+ unlinkSync(rotated[i]);
211
+ } catch {
212
+ }
213
+ }
214
+ }
215
+ async function readMergedJournal(dir, limit) {
216
+ const files = [...rotatedJournalPaths(dir), activeJournalPath(dir)];
217
+ const existing = files.filter((f) => existsSync2(f));
218
+ if (existing.length === 0) return [];
219
+ const parts = [];
220
+ for (const file of existing) {
221
+ try {
222
+ parts.push(await readFile(file, "utf8"));
223
+ } catch {
224
+ }
225
+ }
226
+ return parseJournalLines(parts.join("\n"), limit);
227
+ }
228
+ function readMergedJournalSync(dir, limit) {
229
+ const files = [...rotatedJournalPaths(dir), activeJournalPath(dir)];
230
+ const existing = files.filter((f) => existsSync2(f));
231
+ if (existing.length === 0) return [];
232
+ const parts = [];
233
+ for (const file of existing) {
234
+ try {
235
+ parts.push(readTextFileSync(file, "utf8"));
236
+ } catch {
237
+ }
238
+ }
239
+ return parseJournalLines(parts.join("\n"), limit);
240
+ }
241
+
242
+ // src/host/data/schema-version.ts
243
+ var SCHEMA_VERSION = 1;
244
+ function parseStateText(text) {
245
+ const parsed = JSON.parse(text);
246
+ if (parsed.schemaVersion !== void 0 && parsed.schemaVersion !== SCHEMA_VERSION) {
247
+ return { corruptVersion: parsed.schemaVersion };
248
+ }
249
+ return {
250
+ state: Object.assign(
251
+ { bootMarker: null, crashSeq: 0, autoDisabled: [], stabilized: false, restored: [] },
252
+ parsed
253
+ )
254
+ };
255
+ }
256
+ function parseDecisionText(text) {
257
+ const parsed = JSON.parse(text);
258
+ if (parsed.schemaVersion !== void 0 && parsed.schemaVersion !== SCHEMA_VERSION) {
259
+ return { corruptVersion: parsed.schemaVersion };
260
+ }
261
+ return { decision: parsed };
262
+ }
263
+ function unsupportedVersionDetail(file, version) {
264
+ return `[recency-guard] ${file} \u7684 schemaVersion=${String(version)} \u4E0D\u53D7\u652F\u6301\uFF08\u672C\u5B9E\u73B0\u53EA\u8BA4 ${SCHEMA_VERSION}\uFF09\uFF1B\u6587\u4EF6\u672A\u88AB\u4FEE\u6539\uFF0C\u6309\u5B89\u5168\u7A7A\u6001\u964D\u7EA7\u3002`;
265
+ }
266
+
267
+ // src/host/observe/cooccurrence-store.ts
268
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, writeFileSync as writeFileSync2 } from "node:fs";
269
+ import { readFile as readFile2 } from "node:fs/promises";
270
+ import { dirname as dirname2, join as join2 } from "node:path";
109
271
  import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
272
+
273
+ // src/host/core/path-safe.ts
274
+ import { createHash } from "node:crypto";
275
+ var SAFE_CHARS = /[^A-Za-z0-9._@-]/g;
276
+ var SEPARATORS = /[\\/]+/g;
277
+ var DOT_RUNS = /\.{2,}/g;
278
+ function pathSafeName(name2) {
279
+ const flat = name2.replace(SEPARATORS, "_").replace(DOT_RUNS, "_").replace(SAFE_CHARS, "_");
280
+ if (flat === name2) return flat;
281
+ return `${flat}-${fingerprint(name2, 16)}`;
282
+ }
283
+ function legacyFingerprintName(name2) {
284
+ const flat = name2.replace(SEPARATORS, "_").replace(DOT_RUNS, "_").replace(SAFE_CHARS, "_");
285
+ if (flat === name2) return flat;
286
+ return `${flat}-${fingerprint(name2, 8)}`;
287
+ }
288
+ function candidateNames(name2) {
289
+ const modern = pathSafeName(name2);
290
+ const legacy = legacyFingerprintName(name2);
291
+ return modern === legacy ? [modern] : [modern, legacy];
292
+ }
293
+ function fingerprint(name2, width) {
294
+ return createHash("sha256").update(name2).digest("hex").slice(0, width);
295
+ }
296
+ function legacyUnsafeName(name2) {
297
+ return name2.replace(/[^A-Za-z0-9._@/-]/g, "_");
298
+ }
299
+
300
+ // src/host/observe/cooccurrence-store.ts
110
301
  function emptyStoredCooccurrence() {
111
302
  return { schemaVersion: 1, samples: [] };
112
303
  }
113
304
  var COOCCURRENCE_RELATIVE_PATH = "cooccurrence.json";
114
305
  function cooccurrencePath(partitionDir2) {
115
- return join(partitionDir2, COOCCURRENCE_RELATIVE_PATH);
306
+ return join2(partitionDir2, COOCCURRENCE_RELATIVE_PATH);
116
307
  }
117
308
  function readCooccurrenceSync(partitionDir2) {
118
309
  try {
119
310
  const file = cooccurrencePath(partitionDir2);
120
- if (!existsSync2(file)) return emptyStoredCooccurrence();
311
+ if (!existsSync3(file)) return emptyStoredCooccurrence();
121
312
  const parsed = JSON.parse(readFileSync(file, "utf8"));
122
313
  if (!Array.isArray(parsed.samples)) return emptyStoredCooccurrence();
123
314
  const samples = [];
@@ -141,7 +332,7 @@ function writeCooccurrenceSync(partitionDir2, store) {
141
332
  try {
142
333
  const file = cooccurrencePath(partitionDir2);
143
334
  const dir = dirname2(file);
144
- if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
335
+ if (!existsSync3(dir)) mkdirSync2(dir, { recursive: true });
145
336
  writeFileSync2(file, JSON.stringify(store, null, 2), "utf8");
146
337
  } catch {
147
338
  }
@@ -151,7 +342,10 @@ function asStringArray(value) {
151
342
  return value.filter((item) => typeof item === "string");
152
343
  }
153
344
  function observationPath(partitionDir2, name2) {
154
- return join(partitionDir2, `observation-${sanitizeName(name2)}.json`);
345
+ return join2(partitionDir2, `observation-${pathSafeName(name2)}.json`);
346
+ }
347
+ function observationCandidatePaths(partitionDir2, name2) {
348
+ return candidateNames(name2).map((n) => join2(partitionDir2, `observation-${n}.json`));
155
349
  }
156
350
  function toObservationMap(parsed) {
157
351
  const out = /* @__PURE__ */ new Map();
@@ -168,18 +362,22 @@ function toObservationMap(parsed) {
168
362
  }
169
363
  function readObservationSync(partitionDir2, name2) {
170
364
  try {
171
- const file = observationPath(partitionDir2, name2);
172
- if (!existsSync2(file)) return /* @__PURE__ */ new Map();
173
- return toObservationMap(JSON.parse(readFileSync(file, "utf8")));
365
+ for (const file of observationCandidatePaths(partitionDir2, name2)) {
366
+ if (!existsSync3(file)) continue;
367
+ return toObservationMap(JSON.parse(readFileSync(file, "utf8")));
368
+ }
369
+ return /* @__PURE__ */ new Map();
174
370
  } catch {
175
371
  return /* @__PURE__ */ new Map();
176
372
  }
177
373
  }
178
374
  async function readObservation(partitionDir2, name2) {
179
375
  try {
180
- const file = observationPath(partitionDir2, name2);
181
- if (!existsSync2(file)) return /* @__PURE__ */ new Map();
182
- return toObservationMap(JSON.parse(await readFile(file, "utf8")));
376
+ for (const file of observationCandidatePaths(partitionDir2, name2)) {
377
+ if (!existsSync3(file)) continue;
378
+ return toObservationMap(JSON.parse(await readFile2(file, "utf8")));
379
+ }
380
+ return /* @__PURE__ */ new Map();
183
381
  } catch {
184
382
  return /* @__PURE__ */ new Map();
185
383
  }
@@ -188,18 +386,15 @@ async function writeObservation(partitionDir2, name2, state) {
188
386
  try {
189
387
  const file = observationPath(partitionDir2, name2);
190
388
  const dir = dirname2(file);
191
- if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
389
+ if (!existsSync3(dir)) mkdirSync2(dir, { recursive: true });
192
390
  await writeFileAtomic(file, JSON.stringify(Object.fromEntries(state), null, 2), { mode: 420 });
193
391
  } catch {
194
392
  }
195
393
  }
196
- function sanitizeName(name2) {
197
- return name2.replace(/[^A-Za-z0-9._@/-]/g, "_");
198
- }
199
394
 
200
395
  // src/host/data/lock-hygiene.ts
201
- import { readdirSync, readFileSync as readFileSync2, rmSync as rmSync2, statSync } from "node:fs";
202
- import { join as join2 } from "node:path";
396
+ import { readdirSync as readdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync } from "node:fs";
397
+ import { join as join3 } from "node:path";
203
398
  var STALE_LOCK_MIN_AGE_MS = 5e3;
204
399
  function processAlive(pid) {
205
400
  try {
@@ -213,13 +408,13 @@ function cleanStaleLocks(dir, now = Date.now()) {
213
408
  const report = { removed: [], kept: [] };
214
409
  let entries;
215
410
  try {
216
- entries = readdirSync(dir);
411
+ entries = readdirSync2(dir);
217
412
  } catch {
218
413
  return report;
219
414
  }
220
415
  for (const name2 of entries) {
221
416
  if (!name2.endsWith(".lock")) continue;
222
- const path = join2(dir, name2);
417
+ const path = join3(dir, name2);
223
418
  try {
224
419
  if (now - statSync(path).mtimeMs < STALE_LOCK_MIN_AGE_MS) {
225
420
  report.kept.push(name2);
@@ -252,7 +447,6 @@ function isLockTimeout(error) {
252
447
 
253
448
  // src/host/data/store.ts
254
449
  var STATE_DIRNAME = ".recency-guard";
255
- var JOURNAL_MAX_LINES = 1e3;
256
450
  function emptyState() {
257
451
  return { bootMarker: null, crashSeq: 0, autoDisabled: [], stabilized: false, restored: [] };
258
452
  }
@@ -276,18 +470,57 @@ var Store = class {
276
470
  get backupsRoot() {
277
471
  return this.backupsDir;
278
472
  }
473
+ /**
474
+ * 读写降级记录(T15-03)。
475
+ *
476
+ * - `state` / `decision`:读到未知 schemaVersion 即置 true(安全空态);
477
+ * - 供 status / 面板投影成 `corrupt` 字段,让「文件坏了」可被看见,
478
+ * 而不是只能从「怎么突然什么都没了」反推。
479
+ */
480
+ corruption = { state: false, decision: false };
481
+ /** 已知损坏的文件路径(面板/工具展示用,去重)。 */
482
+ corruptionPaths = /* @__PURE__ */ new Set();
483
+ /** 已写过 journal 的版本组合:避免每次读盘都追加同一条 note(快照每 5s 读一次)。 */
484
+ reportedCorruption = /* @__PURE__ */ new Set();
485
+ /** 可注入的文本读(T15-02):只为测试能覆盖 `trimJournalIfNeeded` 的失败分支。 */
486
+ readText;
279
487
  /**
280
488
  * @param profileDir profile 目录
281
489
  * @param partitionKey 分区键;缺省时用 `default`(单项目 profile)。
490
+ * @param backupRootOverride 备份根覆盖(环境变量/配置)。
491
+ * @param io 可注入 IO(**默认走真实 fs,行为逐位不变**;仅供测试注入失败)。
282
492
  */
283
- constructor(profileDir, partitionKey = "default", backupRootOverride) {
284
- this.rootDir = join3(profileDir, STATE_DIRNAME);
285
- this.dir = join3(this.rootDir, "projects", partitionKey);
286
- this.journalPath = join3(this.dir, "journal.jsonl");
287
- this.snapshotPath = join3(this.dir, "snapshot.json");
288
- this.statePath = join3(this.dir, "state.json");
289
- this.decisionPath = join3(this.dir, "decision.json");
493
+ constructor(profileDir, partitionKey = "default", backupRootOverride, io) {
494
+ this.rootDir = join4(profileDir, STATE_DIRNAME);
495
+ this.dir = join4(this.rootDir, "projects", partitionKey);
496
+ this.journalPath = join4(this.dir, "journal.jsonl");
497
+ this.snapshotPath = join4(this.dir, "snapshot.json");
498
+ this.statePath = join4(this.dir, "state.json");
499
+ this.decisionPath = join4(this.dir, "decision.json");
290
500
  this.backupsDir = resolveBackupsDir(backupRootOverride, this.dir, partitionKey);
501
+ this.readText = io?.readFile ?? ((path) => readFile3(path, "utf8"));
502
+ }
503
+ /** 损坏事实的快照(只读投影:status / 面板用)。 */
504
+ corruptionReport() {
505
+ return { state: this.corruption.state, decision: this.corruption.decision, files: [...this.corruptionPaths] };
506
+ }
507
+ /**
508
+ * 记录一次「未知 schemaVersion」降级:置标记 + 首次写 journal note。
509
+ *
510
+ * 为什么去重:快照每 5 秒读一次 state,若每次都写一条 note,一天能写
511
+ * 一万条同一事实的日志,把真正的证据冲掉。每个 (文件, 版本) 只报一次。
512
+ */
513
+ noteCorruption(kind, file, version) {
514
+ this.corruption[kind] = true;
515
+ this.corruptionPaths.add(file);
516
+ const key = `${kind}:${String(version)}`;
517
+ if (this.reportedCorruption.has(key)) return;
518
+ this.reportedCorruption.add(key);
519
+ this.appendSync({
520
+ kind: "note",
521
+ detail: unsupportedVersionDetail(file, version),
522
+ degraded: true
523
+ });
291
524
  }
292
525
  async init() {
293
526
  await mkdir(this.backupsDir, { recursive: true });
@@ -339,20 +572,7 @@ var Store = class {
339
572
  * 而裁剪要读全文件再原子替换。崩溃路径改用纯追加,把上限交给这里。
340
573
  */
341
574
  async trimJournalIfNeeded() {
342
- try {
343
- if (!existsSync3(this.journalPath)) return;
344
- if (journalLines(await readFile2(this.journalPath, "utf8")).length <= JOURNAL_MAX_LINES) return;
345
- await withFileLock(
346
- this.journalPath,
347
- async () => {
348
- const latest = journalLines(await readFile2(this.journalPath, "utf8"));
349
- if (latest.length <= JOURNAL_MAX_LINES) return;
350
- await writeFileAtomic2(this.journalPath, serializeJournal(latest), { mode: 420 });
351
- },
352
- { waitMs: 3e3 }
353
- );
354
- } catch {
355
- }
575
+ await trimJournalFile(this.dir, this.readText);
356
576
  }
357
577
  /**
358
578
  * Write a journal event synchronously.
@@ -367,7 +587,7 @@ var Store = class {
367
587
  */
368
588
  appendSync(event) {
369
589
  try {
370
- if (!existsSync3(this.dir)) mkdirSync3(this.dir, { recursive: true });
590
+ if (!existsSync4(this.dir)) mkdirSync3(this.dir, { recursive: true });
371
591
  const record = { ...event, t: (/* @__PURE__ */ new Date()).toISOString() };
372
592
  appendFileSync(this.journalPath, `${JSON.stringify(record)}
373
593
  `, "utf8");
@@ -375,14 +595,13 @@ var Store = class {
375
595
  }
376
596
  }
377
597
  async readJournal(limit = 100) {
378
- if (!existsSync3(this.journalPath)) return [];
379
- return parseJournalLines(await readFile2(this.journalPath, "utf8"), limit);
598
+ return readMergedJournal(this.dir, limit);
380
599
  }
381
600
  // ---------- snapshot (version tracking) ----------
382
601
  async readSnapshot() {
383
- if (!existsSync3(this.snapshotPath)) return {};
602
+ if (!existsSync4(this.snapshotPath)) return {};
384
603
  try {
385
- return JSON.parse(await readFile2(this.snapshotPath, "utf8"));
604
+ return JSON.parse(await readFile3(this.snapshotPath, "utf8"));
386
605
  } catch {
387
606
  return {};
388
607
  }
@@ -425,17 +644,16 @@ var Store = class {
425
644
  /** Read the version snapshot synchronously. */
426
645
  readSnapshotSync() {
427
646
  try {
428
- if (!existsSync3(this.snapshotPath)) return {};
647
+ if (!existsSync4(this.snapshotPath)) return {};
429
648
  return JSON.parse(readFileSync3(this.snapshotPath, "utf8"));
430
649
  } catch {
431
650
  return {};
432
651
  }
433
652
  }
434
- /** Read the journal synchronously. */
653
+ /** Read the journal synchronously.(轮转透明:活动 + 轮转文件合并) */
435
654
  readJournalSync(limit = 100) {
436
655
  try {
437
- if (!existsSync3(this.journalPath)) return [];
438
- return parseJournalLines(readFileSync3(this.journalPath, "utf8"), limit);
656
+ return readMergedJournalSync(this.dir, limit);
439
657
  } catch {
440
658
  return [];
441
659
  }
@@ -443,35 +661,52 @@ var Store = class {
443
661
  /** Write the state file synchronously. */
444
662
  writeStateSync(state) {
445
663
  try {
446
- if (!existsSync3(this.dir)) mkdirSync3(this.dir, { recursive: true });
447
- writeFileAtomicSync(this.statePath, JSON.stringify(state, null, 2));
664
+ if (!existsSync4(this.dir)) mkdirSync3(this.dir, { recursive: true });
665
+ writeFileAtomicSync(this.statePath, JSON.stringify({ ...state, schemaVersion: SCHEMA_VERSION }, null, 2));
448
666
  } catch {
449
667
  }
450
668
  }
451
669
  /** Write the version snapshot synchronously. */
452
670
  writeSnapshotSync(snap) {
453
671
  try {
454
- if (!existsSync3(this.dir)) mkdirSync3(this.dir, { recursive: true });
672
+ if (!existsSync4(this.dir)) mkdirSync3(this.dir, { recursive: true });
455
673
  writeFileSync3(this.snapshotPath, JSON.stringify(snap, null, 2), "utf8");
456
674
  } catch {
457
675
  }
458
676
  }
459
677
  // ---------- state ----------
460
678
  async readState() {
461
- if (!existsSync3(this.statePath)) return emptyState();
679
+ if (!existsSync4(this.statePath)) return emptyState();
462
680
  try {
463
- const parsed = JSON.parse(await readFile2(this.statePath, "utf8"));
464
- return { ...emptyState(), ...parsed };
681
+ return this.parseState(await this.readText(this.statePath));
465
682
  } catch {
466
683
  return emptyState();
467
684
  }
468
685
  }
469
686
  async writeState(state) {
470
- await writeFileAtomic2(this.statePath, JSON.stringify(state, null, 2), { mode: 420 });
687
+ await writeFileAtomic2(this.statePath, JSON.stringify({ ...state, schemaVersion: SCHEMA_VERSION }, null, 2), { mode: 420 });
688
+ }
689
+ /**
690
+ * 解析 state 文本(v1 宽容读;未知版本安全降级)。
691
+ *
692
+ * 三条路径(T15-03 判据):
693
+ * - `schemaVersion === 1` ⇒ 正常;
694
+ * - **缺失** ⇒ 按 v1 读(v0.16 及更早的文件没有该字段,老 profile 必须能读);
695
+ * - **其它值** ⇒ 返回 `{...emptyState(), corrupt:true}`(**不覆盖文件**)、
696
+ * 写一条 degraded journal note。为什么不能「尽力解释」:`crashSeq` /
697
+ * `autoDisabled` 的语义可能在新版本里已变,按旧语义解释会做出错误恢复决策。
698
+ */
699
+ parseState(text) {
700
+ const parsed = parseStateText(text);
701
+ if (parsed.corruptVersion !== void 0) {
702
+ this.noteCorruption("state", "state.json", parsed.corruptVersion);
703
+ return { ...emptyState(), corrupt: true };
704
+ }
705
+ return parsed.state ?? emptyState();
471
706
  }
472
707
  /** Serialized read-modify-write across processes. */
473
708
  async updateState(mutate) {
474
- const run = () => withFileLock(
709
+ const run = () => withFileLock2(
475
710
  this.statePath,
476
711
  async () => {
477
712
  const cur = await this.readState();
@@ -508,20 +743,34 @@ var Store = class {
508
743
  crashedRun: true
509
744
  };
510
745
  const tmp = `${this.statePath}.tmp`;
511
- writeFileSync3(tmp, JSON.stringify(next, null, 2), "utf8");
512
- renameSync2(tmp, this.statePath);
746
+ writeFileSync3(tmp, JSON.stringify({ ...next, schemaVersion: SCHEMA_VERSION }, null, 2), "utf8");
747
+ renameSync3(tmp, this.statePath);
513
748
  } catch {
514
749
  }
515
750
  }
516
751
  /** Read the state file synchronously. */
517
752
  readStateSync() {
518
753
  try {
519
- if (!existsSync3(this.statePath)) return emptyState();
520
- return { ...emptyState(), ...JSON.parse(readFileSync3(this.statePath, "utf8")) };
754
+ if (!existsSync4(this.statePath)) return emptyState();
755
+ return this.parseState(readFileSync3(this.statePath, "utf8"));
521
756
  } catch {
522
757
  return emptyState();
523
758
  }
524
759
  }
760
+ /** Read the decision file synchronously(v1 宽容读;未知版本 ⇒ null + 留痕)。 */
761
+ readDecisionSync() {
762
+ try {
763
+ if (!existsSync4(this.decisionPath)) return null;
764
+ const parsed = parseDecisionText(readFileSync3(this.decisionPath, "utf8"));
765
+ if (parsed.corruptVersion !== void 0) {
766
+ this.noteCorruption("decision", "decision.json", parsed.corruptVersion);
767
+ return null;
768
+ }
769
+ return parsed.decision ?? null;
770
+ } catch {
771
+ return null;
772
+ }
773
+ }
525
774
  // ---------- pre-boot decision ----------
526
775
  /**
527
776
  * Publish the decision the guarded patch rows read BEFORE their modules load.
@@ -532,8 +781,8 @@ var Store = class {
532
781
  */
533
782
  writeDecisionSync(decision) {
534
783
  try {
535
- if (!existsSync3(this.dir)) mkdirSync3(this.dir, { recursive: true });
536
- writeFileAtomicSync(this.decisionPath, JSON.stringify(decision, null, 2));
784
+ if (!existsSync4(this.dir)) mkdirSync3(this.dir, { recursive: true });
785
+ writeFileAtomicSync(this.decisionPath, JSON.stringify({ ...decision, schemaVersion: SCHEMA_VERSION }, null, 2));
537
786
  } catch {
538
787
  }
539
788
  }
@@ -568,29 +817,22 @@ var Store = class {
568
817
  */
569
818
  async updateDecisionLocked(mutate) {
570
819
  await mkdir(this.dir, { recursive: true });
571
- return withFileLock(
820
+ return withFileLock2(
572
821
  this.decisionPath,
573
822
  async () => {
574
823
  const current = this.readDecisionSync();
575
824
  const next = mutate(current);
576
- await writeFileAtomic2(this.decisionPath, JSON.stringify(next, null, 2), { mode: 420 });
825
+ await writeFileAtomic2(this.decisionPath, JSON.stringify({ ...next, schemaVersion: SCHEMA_VERSION }, null, 2), { mode: 420 });
577
826
  return next;
578
827
  },
579
828
  { waitMs: 3e3 }
580
829
  );
581
830
  }
582
831
  /** Read the decision file synchronously. */
583
- readDecisionSync() {
584
- try {
585
- if (!existsSync3(this.decisionPath)) return null;
586
- return JSON.parse(readFileSync3(this.decisionPath, "utf8"));
587
- } catch {
588
- return null;
589
- }
590
- }
832
+ // 实现集中在 state 段落(`readDecisionSync` 的 v1/未知版本判据与 state 同源)。
591
833
  // ---------- config backups ----------
592
834
  async writeBackup(bundle, config) {
593
- const file = join3(this.backupsDir, `${sanitize(bundle)}.json`);
835
+ const file = join4(this.backupsDir, `${pathSafeName(bundle)}.json`);
594
836
  await writeFileAtomic2(
595
837
  file,
596
838
  JSON.stringify({ bundle, savedAt: (/* @__PURE__ */ new Date()).toISOString(), config }, null, 2),
@@ -621,10 +863,10 @@ var Store = class {
621
863
  */
622
864
  async writeVersionedBackup(bundle, version, config, options = {}) {
623
865
  try {
624
- const dir = join3(this.backupsDir, "versions", sanitize(bundle));
866
+ const dir = join4(this.backupsDir, "versions", pathSafeName(bundle));
625
867
  await mkdir(dir, { recursive: true });
626
868
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
627
- const file = join3(dir, `${sanitize(version) || "unknown"}@${stamp}.json`);
869
+ const file = join4(dir, `${pathSafeName(version) || "unknown"}@${stamp}.json`);
628
870
  await writeFileAtomic2(
629
871
  file,
630
872
  JSON.stringify({ bundle, version, savedAt: (/* @__PURE__ */ new Date()).toISOString(), config }, null, 2),
@@ -638,8 +880,8 @@ var Store = class {
638
880
  }
639
881
  /** 一个插件的时间线备份清单(旧 → 新),供工具与面板对账。 */
640
882
  async listVersionedBackups(bundle) {
641
- const dir = join3(this.backupsDir, "versions", sanitize(bundle));
642
- if (!existsSync3(dir)) return [];
883
+ const dir = join4(this.backupsDir, "versions", pathSafeName(bundle));
884
+ if (!existsSync4(dir)) return [];
643
885
  let files;
644
886
  try {
645
887
  files = await readdir(dir);
@@ -649,10 +891,10 @@ var Store = class {
649
891
  const rows = [];
650
892
  for (const f of files.filter((x) => x.endsWith(".json")).sort()) {
651
893
  try {
652
- const parsed = JSON.parse(await readFile2(join3(dir, f), "utf8"));
894
+ const parsed = JSON.parse(await readFile3(join4(dir, f), "utf8"));
653
895
  rows.push({
654
896
  // 完整路径:调用方(prune、工具层)不再自己拼路径,避免两处路径规则漂移。
655
- file: join3(dir, f),
897
+ file: join4(dir, f),
656
898
  version: typeof parsed.version === "string" ? parsed.version : "unknown",
657
899
  savedAt: typeof parsed.savedAt === "string" ? parsed.savedAt : ""
658
900
  });
@@ -663,8 +905,8 @@ var Store = class {
663
905
  }
664
906
  /** 按插件清点全部时间线备份(工具 backups 用)。 */
665
907
  async listVersionedBackupBundles() {
666
- const root = join3(this.backupsDir, "versions");
667
- if (!existsSync3(root)) return [];
908
+ const root = join4(this.backupsDir, "versions");
909
+ if (!existsSync4(root)) return [];
668
910
  let names;
669
911
  try {
670
912
  names = await readdir(root);
@@ -695,68 +937,49 @@ var Store = class {
695
937
  }
696
938
  }
697
939
  async readBackup(bundle) {
698
- const file = join3(this.backupsDir, `${sanitize(bundle)}.json`);
699
- if (!existsSync3(file)) return null;
700
- try {
701
- return JSON.parse(await readFile2(file, "utf8"));
702
- } catch {
703
- return null;
940
+ const candidates = candidateNames(bundle).flatMap((n) => [join4(this.backupsDir, `${n}.json`)]);
941
+ candidates.push(join4(this.backupsDir, `${legacyUnsafeName(bundle)}.json`));
942
+ for (const file of candidates) {
943
+ if (!existsSync4(file)) continue;
944
+ try {
945
+ return JSON.parse(await readFile3(file, "utf8"));
946
+ } catch {
947
+ }
704
948
  }
949
+ return null;
705
950
  }
706
951
  async listBackups() {
707
- if (!existsSync3(this.backupsDir)) return [];
952
+ if (!existsSync4(this.backupsDir)) return [];
708
953
  const files = await readdir(this.backupsDir);
709
954
  return files.filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, ""));
710
955
  }
711
956
  };
712
- function journalLines(raw) {
713
- return raw ? raw.split("\n").filter(Boolean) : [];
714
- }
715
- function serializeJournal(lines) {
716
- return `${lines.slice(-JOURNAL_MAX_LINES).join("\n")}
717
- `;
718
- }
719
- function parseJournalLines(raw, limit) {
720
- const lines = journalLines(raw);
721
- const take = Number.isFinite(limit) && limit > 0 ? Math.min(Math.floor(limit), lines.length) : 0;
722
- const out = [];
723
- for (const line of lines.slice(lines.length - take)) {
724
- try {
725
- out.push(JSON.parse(line));
726
- } catch {
727
- }
728
- }
729
- return out;
730
- }
731
- function sanitize(name2) {
732
- return name2.replace(/[^A-Za-z0-9._@/-]/g, "_");
733
- }
734
957
  function resolveBackupsDir(override, partitionDir2, partitionKey) {
735
958
  const custom = (override ?? "").trim();
736
- if (custom === "") return join3(partitionDir2, "backups");
959
+ if (custom === "") return join4(partitionDir2, "backups");
737
960
  try {
738
961
  const resolved = resolve(custom);
739
- if (!isAbsolute(custom)) return join3(partitionDir2, "backups");
962
+ if (!isAbsolute(custom)) return join4(partitionDir2, "backups");
740
963
  void resolved;
741
- return join3(resolved, partitionKey);
964
+ return join4(resolved, partitionKey);
742
965
  } catch {
743
- return join3(partitionDir2, "backups");
966
+ return join4(partitionDir2, "backups");
744
967
  }
745
968
  }
746
969
  function bundleVersionsSync(profileDir) {
747
970
  const out = {};
748
971
  const declared = declaredDependenciesSync(profileDir);
749
- const nm = join3(profileDir, "node_modules");
750
- if (!existsSync3(nm)) return out;
972
+ const nm = join4(profileDir, "node_modules");
973
+ if (!existsSync4(nm)) return out;
751
974
  for (const name2 of declared) {
752
- const version = readPackageVersion(join3(nm, ...name2.split("/")));
975
+ const version = readPackageVersion(join4(nm, ...name2.split("/")));
753
976
  if (version) out[name2] = version;
754
977
  }
755
978
  return out;
756
979
  }
757
980
  function declaredDependenciesSync(profileDir) {
758
981
  try {
759
- const manifest = JSON.parse(readFileSync3(join3(profileDir, "package.json"), "utf8"));
982
+ const manifest = JSON.parse(readFileSync3(join4(profileDir, "package.json"), "utf8"));
760
983
  const deps = manifest?.dependencies;
761
984
  return deps && typeof deps === "object" ? Object.keys(deps) : [];
762
985
  } catch {
@@ -765,7 +988,7 @@ function declaredDependenciesSync(profileDir) {
765
988
  }
766
989
  function readPackageVersion(dir) {
767
990
  try {
768
- const manifest = JSON.parse(readFileSync3(join3(dir, "package.json"), "utf8"));
991
+ const manifest = JSON.parse(readFileSync3(join4(dir, "package.json"), "utf8"));
769
992
  return typeof manifest.version === "string" ? manifest.version : void 0;
770
993
  } catch {
771
994
  return void 0;
@@ -773,19 +996,19 @@ function readPackageVersion(dir) {
773
996
  }
774
997
  function bundleMtimesSync(profileDir) {
775
998
  const out = {};
776
- const nm = join3(profileDir, "node_modules");
999
+ const nm = join4(profileDir, "node_modules");
777
1000
  for (const name2 of declaredDependenciesSync(profileDir)) {
778
1001
  try {
779
- out[name2] = statSync2(join3(nm, ...name2.split("/"))).mtimeMs;
1002
+ out[name2] = statSync2(join4(nm, ...name2.split("/"))).mtimeMs;
780
1003
  } catch {
781
1004
  }
782
1005
  }
783
1006
  return out;
784
1007
  }
785
1008
  async function bundleMtimes(profileDir) {
786
- const nm = join3(profileDir, "node_modules");
1009
+ const nm = join4(profileDir, "node_modules");
787
1010
  const out = {};
788
- if (!existsSync3(nm)) return out;
1011
+ if (!existsSync4(nm)) return out;
789
1012
  let scopes;
790
1013
  try {
791
1014
  scopes = await readdir(nm);
@@ -795,7 +1018,7 @@ async function bundleMtimes(profileDir) {
795
1018
  for (const entry of scopes) {
796
1019
  if (entry.startsWith(".")) continue;
797
1020
  if (entry.startsWith("@")) {
798
- const scopeDir = join3(nm, entry);
1021
+ const scopeDir = join4(nm, entry);
799
1022
  let children = [];
800
1023
  try {
801
1024
  children = await readdir(scopeDir);
@@ -803,7 +1026,7 @@ async function bundleMtimes(profileDir) {
803
1026
  continue;
804
1027
  }
805
1028
  for (const child of children) {
806
- const pkgDir = join3(scopeDir, child);
1029
+ const pkgDir = join4(scopeDir, child);
807
1030
  try {
808
1031
  const s = await stat(pkgDir);
809
1032
  out[`${entry}/${child}`] = s.mtimeMs;
@@ -811,7 +1034,7 @@ async function bundleMtimes(profileDir) {
811
1034
  }
812
1035
  }
813
1036
  } else {
814
- const pkgDir = join3(nm, entry);
1037
+ const pkgDir = join4(nm, entry);
815
1038
  try {
816
1039
  const s = await stat(pkgDir);
817
1040
  out[entry] = s.mtimeMs;
@@ -897,7 +1120,7 @@ function describeError(err) {
897
1120
  }
898
1121
 
899
1122
  // src/host/core/change-guard.ts
900
- import { createHash } from "node:crypto";
1123
+ import { createHash as createHash2 } from "node:crypto";
901
1124
  function encodeList(label, items) {
902
1125
  const body = items.map((s) => `${Buffer.byteLength(s, "utf8")}:${s}`).join("|");
903
1126
  return `${label}[${items.length}]=${body}`;
@@ -912,7 +1135,7 @@ function computeRevision(facts) {
912
1135
  encodeList("decision", facts.decisionDisable),
913
1136
  `tail=${facts.journalTail}`
914
1137
  ].join("#");
915
- return createHash("sha256").update(canonical, "utf8").digest("hex").slice(0, 12);
1138
+ return createHash2("sha256").update(canonical, "utf8").digest("hex").slice(0, 12);
916
1139
  }
917
1140
  function checkRevision(current, expected) {
918
1141
  if (typeof expected !== "string" || expected === "") return { ok: true, stale: false, unchecked: true };
@@ -931,14 +1154,14 @@ function auditEnvelope(actor, action, reason) {
931
1154
  }
932
1155
 
933
1156
  // src/host/guard/decision.ts
934
- import { join as join4 } from "node:path";
1157
+ import { join as join5 } from "node:path";
935
1158
  var DECISION_RELATIVE_PATH = "decision.json";
936
1159
  var POINTER_RELATIVE_PATH = ".recency-guard/current.json";
937
1160
  function decisionPath(partitionDir2) {
938
- return join4(partitionDir2, ...DECISION_RELATIVE_PATH.split("/"));
1161
+ return join5(partitionDir2, ...DECISION_RELATIVE_PATH.split("/"));
939
1162
  }
940
1163
  function pointerPath(profileDir) {
941
- return join4(profileDir, ...POINTER_RELATIVE_PATH.split("/"));
1164
+ return join5(profileDir, ...POINTER_RELATIVE_PATH.split("/"));
942
1165
  }
943
1166
  function writePointer(profileDir, partitionKey, partitionDir2) {
944
1167
  try {
@@ -2002,7 +2225,12 @@ var FLOW_BY_KIND = {
2002
2225
  "auto-disable": { action: "auto-disable", actionLabel: "\u81EA\u52A8\u5173\u95ED\u5ACC\u7591\u63D2\u4EF6", from: "node:decider", to: "node:disabled", tone: "error", stage: "deciding" },
2003
2226
  recover: { action: "recover", actionLabel: "\u6267\u884C\u6062\u590D", from: "node:decider", to: "node:runtime", tone: "success", stage: "stabilizing" },
2004
2227
  restore: { action: "restore", actionLabel: "\u6062\u590D\u63D2\u4EF6", from: "node:guard", to: "node:runtime", tone: "success", stage: "stabilizing" },
2005
- "config-backup": { action: "backup", actionLabel: "\u5907\u4EFD\u914D\u7F6E", from: "node:profile", to: "node:backups", tone: "neutral", stage: "stabilizing" }
2228
+ "config-backup": { action: "backup", actionLabel: "\u5907\u4EFD\u914D\u7F6E", from: "node:profile", to: "node:backups", tone: "neutral", stage: "stabilizing" },
2229
+ // v0.18 T16-12:级联刹车回滚。语义上是「恢复」的受限形态(只放回误伤、
2230
+ // 保留头号嫌疑),但动作与语气都不同:它是崩溃循环的**兜底自救**,
2231
+ // 用 success 但阶段是 stabilizing(不是 post-crash 的 recovered 语义),
2232
+ // 让事件流能区分「用户触发的恢复」与「升级到顶后自动回滚」。
2233
+ rollback: { action: "rollback", actionLabel: "\u7EA7\u8054\u5239\u8F66\u56DE\u6EDA", from: "node:guard", to: "node:runtime", tone: "success", stage: "stabilizing" }
2006
2234
  };
2007
2235
  var UNKNOWN_FLOW = {
2008
2236
  action: "unknown",
@@ -2151,12 +2379,12 @@ function rankForDecision(ranked, events, now = Date.now()) {
2151
2379
  }
2152
2380
 
2153
2381
  // src/host/guard/guarded-rows.ts
2154
- import { existsSync as existsSync5, readFileSync as readFileSync5, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "node:fs";
2155
- import { join as join6 } from "node:path";
2382
+ import { existsSync as existsSync6, readFileSync as readFileSync5, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
2383
+ import { join as join7 } from "node:path";
2156
2384
 
2157
2385
  // src/host/profile/patch.ts
2158
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
2159
- import { dirname as dirname3, join as join5 } from "node:path";
2386
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
2387
+ import { dirname as dirname3, join as join6 } from "node:path";
2160
2388
 
2161
2389
  // src/host/profile/patch-scalar.ts
2162
2390
  function yamlScalar(value) {
@@ -2488,15 +2716,15 @@ function readPatchRowsFromText(text) {
2488
2716
  var GUARD_DIR_NAME = ".recency-guard";
2489
2717
  var PATCH_BACKUP_NAME = "cordis.patch.yml.orig";
2490
2718
  function patchBackupPath(patchPath) {
2491
- return join5(dirname3(patchPath), GUARD_DIR_NAME, PATCH_BACKUP_NAME);
2719
+ return join6(dirname3(patchPath), GUARD_DIR_NAME, PATCH_BACKUP_NAME);
2492
2720
  }
2493
2721
  function ensurePatchBackup(patchPath, current) {
2494
2722
  try {
2495
2723
  if (current.trim() === "") return;
2496
2724
  const backupPath = patchBackupPath(patchPath);
2497
- if (existsSync4(backupPath)) return;
2725
+ if (existsSync5(backupPath)) return;
2498
2726
  const dir = dirname3(backupPath);
2499
- if (!existsSync4(dir)) mkdirSync4(dir, { recursive: true });
2727
+ if (!existsSync5(dir)) mkdirSync4(dir, { recursive: true });
2500
2728
  writeFileSync4(backupPath, current, "utf8");
2501
2729
  } catch {
2502
2730
  }
@@ -2509,7 +2737,7 @@ function findGuardableRows(profileDir) {
2509
2737
  for (const bundleName of declaredDependenciesSync(profileDir)) {
2510
2738
  if (isOfficial(bundleName)) continue;
2511
2739
  if (bundleName === GUARD_PACKAGE_NAME) continue;
2512
- const bundleDir = join6(profileDir, "node_modules", ...bundleName.split("/"));
2740
+ const bundleDir = join7(profileDir, "node_modules", ...bundleName.split("/"));
2513
2741
  const patchFile = resolveBundlePatch(bundleDir);
2514
2742
  if (patchFile === void 0) continue;
2515
2743
  for (const row of readPatchRows(patchFile)) {
@@ -2521,9 +2749,9 @@ function findGuardableRows(profileDir) {
2521
2749
  }
2522
2750
  function resolveBundlePatch(bundleDir) {
2523
2751
  try {
2524
- const manifest = JSON.parse(readFileSync5(join6(bundleDir, "package.json"), "utf8"));
2752
+ const manifest = JSON.parse(readFileSync5(join7(bundleDir, "package.json"), "utf8"));
2525
2753
  const patch = manifest?.dsh?.bundle?.patch;
2526
- return typeof patch === "string" ? join6(bundleDir, patch) : void 0;
2754
+ return typeof patch === "string" ? join7(bundleDir, patch) : void 0;
2527
2755
  } catch {
2528
2756
  return void 0;
2529
2757
  }
@@ -2629,20 +2857,20 @@ function appendPatchText(patchPath, text) {
2629
2857
  function writeAtomic(path, content) {
2630
2858
  const tmp = `${path}.rg-tmp`;
2631
2859
  writeFileSync5(tmp, content, "utf8");
2632
- renameSync3(tmp, path);
2860
+ renameSync4(tmp, path);
2633
2861
  }
2634
2862
 
2635
2863
  // src/host/guard/sentinel.ts
2636
- import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "node:fs";
2637
- import { join as join7 } from "node:path";
2864
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync as renameSync5, writeFileSync as writeFileSync6 } from "node:fs";
2865
+ import { join as join8 } from "node:path";
2638
2866
  var SENTINEL_NAME = "crashed";
2639
2867
  function sentinelPath(partitionDir2) {
2640
- return join7(partitionDir2, SENTINEL_NAME);
2868
+ return join8(partitionDir2, SENTINEL_NAME);
2641
2869
  }
2642
2870
  function readSentinel(partitionDir2) {
2643
2871
  try {
2644
2872
  const path = sentinelPath(partitionDir2);
2645
- if (!existsSync6(path)) return null;
2873
+ if (!existsSync7(path)) return null;
2646
2874
  return JSON.parse(readFileSync6(path, "utf8"));
2647
2875
  } catch {
2648
2876
  return null;
@@ -2651,7 +2879,7 @@ function readSentinel(partitionDir2) {
2651
2879
  function clearSentinel(partitionDir2) {
2652
2880
  try {
2653
2881
  const path = sentinelPath(partitionDir2);
2654
- if (existsSync6(path)) renameSync4(path, `${path}.consumed`);
2882
+ if (existsSync7(path)) renameSync5(path, `${path}.consumed`);
2655
2883
  } catch {
2656
2884
  }
2657
2885
  }
@@ -2669,8 +2897,8 @@ function pidAlive(pid) {
2669
2897
  function writeSentinel(partitionDir2, exitCode) {
2670
2898
  try {
2671
2899
  const dir = partitionDir2;
2672
- if (!existsSync6(dir)) mkdirSync5(dir, { recursive: true });
2673
- writeFileSync6(join7(dir, SENTINEL_NAME), JSON.stringify({ exitCode, at: (/* @__PURE__ */ new Date()).toISOString(), pid: process.pid }), "utf8");
2900
+ if (!existsSync7(dir)) mkdirSync5(dir, { recursive: true });
2901
+ writeFileSync6(join8(dir, SENTINEL_NAME), JSON.stringify({ exitCode, at: (/* @__PURE__ */ new Date()).toISOString(), pid: process.pid }), "utf8");
2674
2902
  } catch {
2675
2903
  }
2676
2904
  }
@@ -2946,18 +3174,27 @@ function shouldRestoreAfterBoot(input) {
2946
3174
  }
2947
3175
  function abnormalExitDecision(abnormalSeq, confirmRounds, maxAutoDisable) {
2948
3176
  const required = Math.max(1, confirmRounds);
2949
- if (abnormalSeq < required) return { act: false, targets: 0, rounds: abnormalSeq, required };
3177
+ if (abnormalSeq < required) return { act: false, targets: 0, rounds: abnormalSeq, required, rollback: false };
2950
3178
  const over = abnormalSeq - required;
3179
+ const cap = Math.max(1, maxAutoDisable);
3180
+ const rollback = over >= cap;
2951
3181
  return {
2952
- act: true,
2953
- targets: Math.min(1 + over, Math.max(1, maxAutoDisable)),
3182
+ act: !rollback,
3183
+ targets: rollback ? 0 : Math.min(1 + over, cap),
2954
3184
  rounds: abnormalSeq,
2955
- required
3185
+ required,
3186
+ rollback
2956
3187
  };
2957
3188
  }
3189
+ function escalationExhausted(seq, confirmRounds, maxAutoDisable) {
3190
+ const required = Math.max(1, confirmRounds);
3191
+ const cap = Math.max(1, maxAutoDisable);
3192
+ return seq >= required + cap;
3193
+ }
2958
3194
  function assessConfidence(history, currentSuspects, options = {}) {
2959
3195
  const confirmRounds = Math.max(1, options.confirmRounds ?? 2);
2960
3196
  const names = currentSuspects.map((s) => s.bundle);
3197
+ const rollback = options.maxAutoDisable !== void 0 && escalationExhausted(options.crashSeq ?? 0, confirmRounds, options.maxAutoDisable);
2961
3198
  if (names.length === 0) {
2962
3199
  return { act: false, evidence: "probabilistic", rounds: 0, required: confirmRounds, label: "\u6CA1\u6709\u5ACC\u7591\u63D2\u4EF6\uFF0C\u65E0\u9700\u6062\u590D" };
2963
3200
  }
@@ -2994,16 +3231,17 @@ function assessConfidence(history, currentSuspects, options = {}) {
2994
3231
  const hazardRounds = hazardAdjustedRounds(confirmRounds, options.hazardDirection);
2995
3232
  const calibration = options.falsePositiveStats === void 0 ? void 0 : calibratedConfirmRounds(hazardRounds, options.falsePositiveStats);
2996
3233
  const adjustedRounds = calibration === void 0 ? hazardRounds : calibration.required;
2997
- const act = streak >= adjustedRounds || escalated;
2998
3234
  const hazardNote = hazardRounds === confirmRounds ? "" : `\uFF08\u95F4\u9694\u5206\u5E03\u5F62\u6001\u4F7F\u9608\u503C\u8C03\u6574\u4E3A ${hazardRounds} \u8F6E\uFF09`;
2999
3235
  const calibrationNote = calibration === void 0 || calibration.delta === 0 ? "" : `\uFF08\u8BEF\u4F24\u53CD\u9988\u4F7F\u9608\u503C ${hazardRounds} \u8C03\u6574\u4E3A ${calibration.required} \u8F6E\uFF09`;
3000
3236
  const notes = `${hazardNote}${calibrationNote}`;
3237
+ const act = !rollback && (streak >= adjustedRounds || escalated);
3001
3238
  return {
3002
3239
  act,
3003
3240
  evidence: "probabilistic",
3004
3241
  rounds: streak,
3005
3242
  required: adjustedRounds,
3006
- label: act ? streak >= adjustedRounds ? `\u5934\u53F7\u5ACC\u7591 ${head} \u8FDE\u7EED ${streak} \u8F6E\u590D\u73B0\uFF08\u2265 ${adjustedRounds}\uFF09\uFF1A\u8FBE\u5230\u884C\u52A8\u9608\u503C${notes}` : `\u8FDE\u7EED ${options.crashSeq} \u6B21\u5D29\u6E83\u4ECD\u672A\u6062\u590D\uFF1A\u515C\u5E95\u5347\u7EA7\u4E3A\u884C\u52A8\uFF08\u5B89\u5168\u7F51\uFF09` : `\u5934\u53F7\u5ACC\u7591 ${head} \u590D\u73B0 ${streak}/${adjustedRounds} \u8F6E\uFF1A\u89C2\u5BDF\u4E2D\uFF0C\u672C\u8F6E\u53EA\u8BB0\u5F55\u4E0D\u5173\u95ED${notes}`
3243
+ label: rollback ? `\u5934\u53F7\u5ACC\u7591 ${head} \u8FDE\u7EED ${streak} \u8F6E\u590D\u73B0\uFF0C\u7981\u7528\u5347\u7EA7\u5DF2\u5230\u9876\uFF08${options.maxAutoDisable}\uFF09\u21D2 \u7EA7\u8054\u5239\u8F66\uFF0C\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u542F\u52A8\u72B6\u6001\uFF08\u4EC5\u4FDD\u7559 ${head}\uFF09` : act ? streak >= adjustedRounds ? `\u5934\u53F7\u5ACC\u7591 ${head} \u8FDE\u7EED ${streak} \u8F6E\u590D\u73B0\uFF08\u2265 ${adjustedRounds}\uFF09\uFF1A\u8FBE\u5230\u884C\u52A8\u9608\u503C${notes}` : `\u8FDE\u7EED ${options.crashSeq} \u6B21\u5D29\u6E83\u4ECD\u672A\u6062\u590D\uFF1A\u515C\u5E95\u5347\u7EA7\u4E3A\u884C\u52A8\uFF08\u5B89\u5168\u7F51\uFF09` : `\u5934\u53F7\u5ACC\u7591 ${head} \u590D\u73B0 ${streak}/${adjustedRounds} \u8F6E\uFF1A\u89C2\u5BDF\u4E2D\uFF0C\u672C\u8F6E\u53EA\u8BB0\u5F55\u4E0D\u5173\u95ED${notes}`,
3244
+ ...rollback ? { rollback: true } : {}
3007
3245
  };
3008
3246
  }
3009
3247
  function hazardAdjustedRounds(confirmRounds, hazard) {
@@ -3070,9 +3308,11 @@ function assessAbnormalExit(input, previousSeq = 0, now = Date.now()) {
3070
3308
  }
3071
3309
  function abnormalRecoveryVerdict(nextSeq, confirmRounds, maxAutoDisable, headSuspect, now = Date.now()) {
3072
3310
  const decision = abnormalExitDecision(nextSeq, confirmRounds, maxAutoDisable);
3311
+ const rollback = decision.rollback;
3073
3312
  return {
3074
3313
  act: decision.act,
3075
3314
  targets: decision.targets,
3315
+ rollback,
3076
3316
  verdict: {
3077
3317
  at: new Date(now).toISOString(),
3078
3318
  crashSeq: nextSeq,
@@ -3080,10 +3320,11 @@ function abnormalRecoveryVerdict(nextSeq, confirmRounds, maxAutoDisable, headSus
3080
3320
  rounds: decision.rounds,
3081
3321
  required: decision.required,
3082
3322
  act: decision.act,
3083
- label: decision.act ? `\u5F02\u5E38\u7EC8\u6B62\u7D2F\u8BA1 ${decision.rounds} \u8F6E \u21D2 \u5173\u95ED ${decision.targets} \u4E2A` : `\u5F02\u5E38\u7EC8\u6B62\u89C2\u5BDF\u4E2D\uFF08${decision.rounds}/${decision.required} \u8F6E\uFF09`,
3084
- headSuspect
3323
+ label: rollback ? `\u5F02\u5E38\u7EC8\u6B62\u7D2F\u8BA1 ${decision.rounds} \u8F6E\uFF0C\u7981\u7528\u5DF2\u5230\u9876 \u21D2 \u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u542F\u52A8\u72B6\u6001\uFF08\u4FDD\u7559\u5934\u53F7\u5ACC\u7591\uFF09` : decision.act ? `\u5F02\u5E38\u7EC8\u6B62\u7D2F\u8BA1 ${decision.rounds} \u8F6E \u21D2 \u5173\u95ED ${decision.targets} \u4E2A` : `\u5F02\u5E38\u7EC8\u6B62\u89C2\u5BDF\u4E2D\uFF08${decision.rounds}/${decision.required} \u8F6E\uFF09`,
3324
+ headSuspect,
3325
+ ...rollback ? { rollback: true } : {}
3085
3326
  },
3086
- detail: decision.act ? `\u5F02\u5E38\u7EC8\u6B62\u5224\u5B9A\uFF1A\u8FDE\u7EED ${decision.rounds}/${decision.required} \u8F6E \u21D2 \u884C\u52A8\uFF0C\u672C\u8F6E\u5173\u95ED ${decision.targets} \u4E2A\uFF08\u5934\u53F7\u5ACC\u7591 ${headSuspect ?? "\u65E0"}\uFF09` : `\u5F02\u5E38\u7EC8\u6B62\u5224\u5B9A\uFF1A\u89C2\u5BDF\u4E2D ${decision.rounds}/${decision.required} \u8F6E\uFF08\u6B8B\u7559\u6807\u8BB0\u4E5F\u53EF\u80FD\u662F\u4EBA\u4E3A\u6740\u8FDB\u7A0B\uFF0C\u4E0D\u52A8\u624B\uFF09`
3327
+ detail: rollback ? `\u5F02\u5E38\u7EC8\u6B62\u5224\u5B9A\uFF1A\u8FDE\u7EED ${decision.rounds}/${decision.required} \u8F6E\uFF0C\u5DF2\u8FDE\u7EED ${maxAutoDisable} \u8F6E\u7981\u7528\u672A\u751F\u6548 \u21D2 \u7EA7\u8054\u5239\u8F66\uFF0C\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u542F\u52A8\u72B6\u6001\uFF08\u4EC5\u4FDD\u7559\u5934\u53F7\u5ACC\u7591 ${headSuspect ?? "\u65E0"} \u5173\u95ED\uFF09` : decision.act ? `\u5F02\u5E38\u7EC8\u6B62\u5224\u5B9A\uFF1A\u8FDE\u7EED ${decision.rounds}/${decision.required} \u8F6E \u21D2 \u884C\u52A8\uFF0C\u672C\u8F6E\u5173\u95ED ${decision.targets} \u4E2A\uFF08\u5934\u53F7\u5ACC\u7591 ${headSuspect ?? "\u65E0"}\uFF09` : `\u5F02\u5E38\u7EC8\u6B62\u5224\u5B9A\uFF1A\u89C2\u5BDF\u4E2D ${decision.rounds}/${decision.required} \u8F6E\uFF08\u6B8B\u7559\u6807\u8BB0\u4E5F\u53EF\u80FD\u662F\u4EBA\u4E3A\u6740\u8FDB\u7A0B\uFF0C\u4E0D\u52A8\u624B\uFF09`
3087
3328
  };
3088
3329
  }
3089
3330
  function holdReason(input) {
@@ -3181,6 +3422,51 @@ async function reenableOne(deps, bundle) {
3181
3422
  const backup = await deps.store.readBackup(bundle);
3182
3423
  return { bundle, reenabled: applied, hasConfigBackup: backup !== null };
3183
3424
  }
3425
+ async function rollbackToPreCrash(deps, headSuspect) {
3426
+ const state = await deps.store.readState();
3427
+ const auto = state.autoDisabled;
3428
+ deps.transition("stabilizing", "\u7EA7\u8054\u5239\u8F66\uFF1A\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u7684\u63D2\u4EF6\u542F\u52A8\u72B6\u6001");
3429
+ if (auto.length === 0) {
3430
+ return { reenabled: [], keptDisabled: [], failed: [], note: "\u6CA1\u6709\u81EA\u52A8\u5173\u95ED\u8BB0\u5F55\uFF0C\u65E0\u9700\u56DE\u6EDA\u3002" };
3431
+ }
3432
+ const head = headSuspect ?? auto[auto.length - 1]?.name ?? null;
3433
+ const reenabled = [];
3434
+ const keptDisabled = [];
3435
+ const failed = [];
3436
+ for (const d of auto) {
3437
+ if (d.name === head) {
3438
+ keptDisabled.push(d.name);
3439
+ continue;
3440
+ }
3441
+ const result = await reenableOne(deps, d.name);
3442
+ if (result?.reenabled === true) reenabled.push(d.name);
3443
+ else failed.push(d.name);
3444
+ }
3445
+ await deps.store.updateState((s) => ({
3446
+ ...s,
3447
+ autoDisabled: s.autoDisabled.filter((d) => d.name === head || failed.includes(d.name)),
3448
+ stabilized: false,
3449
+ rollbackArmed: void 0
3450
+ }));
3451
+ await deps.store.append({
3452
+ kind: "rollback",
3453
+ bundles: [...reenabled],
3454
+ detail: `\u7EA7\u8054\u5239\u8F66\u56DE\u6EDA\uFF1A\u91CD\u65B0\u542F\u7528 ${reenabled.join(", ") || "\u65E0"}${keptDisabled.length > 0 ? `\uFF1B\u4FDD\u7559\u5934\u53F7\u5ACC\u7591 ${keptDisabled.join(", ")} \u5173\u95ED` : ""}${failed.length > 0 ? `\uFF1B\u672A\u80FD\u6062\u590D\uFF08\u5F85\u91CD\u8BD5\uFF09 ${failed.join(", ")}` : ""}`
3455
+ });
3456
+ deps.transition("recovered", `\u5DF2\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u542F\u52A8\u72B6\u6001\uFF08\u4FDD\u7559 ${keptDisabled.length} \u4E2A\u5ACC\u7591\u5173\u95ED\uFF09`);
3457
+ await deps.publishDecision(
3458
+ [...auto].map((d) => ({ bundle: d.name, lastChangeAt: "", lastKind: "install" })),
3459
+ [...keptDisabled, ...failed],
3460
+ keptDisabled.length || failed.length ? "crash-recovery" : "none"
3461
+ );
3462
+ const kept = [...keptDisabled, ...failed];
3463
+ return {
3464
+ reenabled,
3465
+ keptDisabled: kept,
3466
+ failed,
3467
+ note: kept.length > 0 ? `\u5DF2\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u7684\u542F\u52A8\u72B6\u6001\uFF1B\u4EC5\u4FDD\u7559\u5ACC\u7591\u63D2\u4EF6 ${kept.join(", ")} \u5173\u95ED\u3002` : "\u5DF2\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u7684\u542F\u52A8\u72B6\u6001\uFF0C\u65E0\u4FDD\u7559\u5173\u95ED\u3002"
3468
+ };
3469
+ }
3184
3470
 
3185
3471
  // src/host/guard/official-observe.ts
3186
3472
  function pickOfficialExperimental(bundles) {
@@ -3437,14 +3723,14 @@ function watchPluginChanges(ctx, detect, onWatched, onError) {
3437
3723
  }
3438
3724
 
3439
3725
  // src/host/guard/conflict-declarations.ts
3440
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
3441
- import { join as join8 } from "node:path";
3726
+ import { existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
3727
+ import { join as join9 } from "node:path";
3442
3728
  var COMPAT_KEYS = ["dshCompat", "compat"];
3443
3729
  function readDeclaredPluginsSync(profileDir, options = {}) {
3444
3730
  const out = [];
3445
3731
  for (const name2 of declaredDependenciesSync(profileDir)) {
3446
- const dir = join8(profileDir, "node_modules", ...name2.split("/"));
3447
- const packageFile = join8(dir, "package.json");
3732
+ const dir = join9(profileDir, "node_modules", ...name2.split("/"));
3733
+ const packageFile = join9(dir, "package.json");
3448
3734
  let manifest = null;
3449
3735
  let text = "";
3450
3736
  try {
@@ -3476,8 +3762,8 @@ function readOnePlugin(name2, manifest, packageText, packageFile, dir, enabled)
3476
3762
  enabled
3477
3763
  };
3478
3764
  }
3479
- const pluginFile = join8(dir, "dsh-plugin.json");
3480
- if (existsSync7(pluginFile)) {
3765
+ const pluginFile = join9(dir, "dsh-plugin.json");
3766
+ if (existsSync8(pluginFile)) {
3481
3767
  try {
3482
3768
  const pluginText = readFileSync7(pluginFile, "utf8");
3483
3769
  const pluginManifest = JSON.parse(pluginText);
@@ -3849,7 +4135,10 @@ function verdictPatch(seq, verdict, targets, deterministicEvidence, at = (/* @__
3849
4135
  act: verdict.act,
3850
4136
  label: verdict.label,
3851
4137
  headSuspect: targets[0]?.bundle ?? null,
3852
- ...deterministicEvidence === void 0 ? {} : { deterministic: deterministicEvidence }
4138
+ ...deterministicEvidence === void 0 ? {} : { deterministic: deterministicEvidence },
4139
+ // 级联刹车标志随判定一起落盘(v0.18 T16-12):面板/工具要能看见
4140
+ // 「这一轮为什么不再禁用」。缺省 = 未刹车,与旧 state 兼容。
4141
+ ...verdict.rollback === true ? { rollback: true } : {}
3853
4142
  };
3854
4143
  }
3855
4144
  function composeCrashDecision(input) {
@@ -3861,7 +4150,9 @@ function composeCrashDecision(input) {
3861
4150
  confirmRounds: input.confirmRounds,
3862
4151
  crashSeq: input.seq,
3863
4152
  hazardDirection: input.hazardDirection,
3864
- deterministicEvidence
4153
+ deterministicEvidence,
4154
+ // v0.18 T16-12:级联刹车判据需要封顶数(升级步数用满 ⇒ rollback)。
4155
+ maxAutoDisable: input.maxAutoDisable
3865
4156
  });
3866
4157
  const planned = plan.quarantine.map((name2) => input.ranked.find((entry) => entry.bundle === name2)).filter((entry) => entry !== void 0);
3867
4158
  const n = Math.min(Math.max(1, input.seq), Math.max(1, input.maxAutoDisable));
@@ -3916,11 +4207,11 @@ function reconcileCrashedState(state, decision, sentinelPresent, now = (/* @__PU
3916
4207
  }
3917
4208
 
3918
4209
  // src/host/core/isolation.ts
3919
- import { createHash as createHash2 } from "node:crypto";
3920
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync8 } from "node:fs";
4210
+ import { createHash as createHash3 } from "node:crypto";
4211
+ import { existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync8 } from "node:fs";
3921
4212
  import { mkdir as mkdir2, rename, writeFile } from "node:fs/promises";
3922
- import { join as join9 } from "node:path";
3923
- import { withFileLock as withFileLock2 } from "@deepseek-ai/dsh-atomic-write";
4213
+ import { join as join10 } from "node:path";
4214
+ import { withFileLock as withFileLock3 } from "@deepseek-ai/dsh-atomic-write";
3924
4215
  function normalizeWorkspace(workspace) {
3925
4216
  let normalized = workspace.replace(/\\/g, "/");
3926
4217
  const isWindowsDrive = /^[A-Za-z]:/.test(normalized);
@@ -3943,7 +4234,7 @@ function normalizeWorkspace(workspace) {
3943
4234
  return joined === "" ? "." : joined;
3944
4235
  }
3945
4236
  function projectKey(workspace) {
3946
- return createHash2("sha256").update(normalizeWorkspace(workspace)).digest("hex").slice(0, 16);
4237
+ return createHash3("sha256").update(normalizeWorkspace(workspace)).digest("hex").slice(0, 16);
3947
4238
  }
3948
4239
  function projectLabel(workspace) {
3949
4240
  const raw = workspace.replace(/\\/g, "/").replace(/\/+$/, "");
@@ -3951,10 +4242,10 @@ function projectLabel(workspace) {
3951
4242
  return segments.length === 0 ? raw : segments[segments.length - 1];
3952
4243
  }
3953
4244
  function partitionsRoot(profileDir) {
3954
- return join9(profileDir, ".recency-guard", "projects");
4245
+ return join10(profileDir, ".recency-guard", "projects");
3955
4246
  }
3956
4247
  function partitionDir(profileDir, key) {
3957
- return join9(partitionsRoot(profileDir), key);
4248
+ return join10(partitionsRoot(profileDir), key);
3958
4249
  }
3959
4250
  function emptyPartitionIndex() {
3960
4251
  return { schemaVersion: 1, partitions: [] };
@@ -3993,7 +4284,7 @@ function registerPartition(index, workspace, now = (/* @__PURE__ */ new Date()).
3993
4284
  var PARTITION_INDEX_FILENAME = "partitions.json";
3994
4285
  function readPartitionIndex(profileDir) {
3995
4286
  try {
3996
- const raw = readFileSync8(join9(profileDir, ".recency-guard", PARTITION_INDEX_FILENAME), "utf8");
4287
+ const raw = readFileSync8(join10(profileDir, ".recency-guard", PARTITION_INDEX_FILENAME), "utf8");
3997
4288
  const parsed = JSON.parse(raw);
3998
4289
  if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.partitions)) return emptyPartitionIndex();
3999
4290
  return parsed;
@@ -4003,9 +4294,9 @@ function readPartitionIndex(profileDir) {
4003
4294
  }
4004
4295
  function writePartitionIndex(profileDir, index) {
4005
4296
  try {
4006
- const dir = join9(profileDir, ".recency-guard");
4007
- if (!existsSync8(dir)) mkdirSync6(dir, { recursive: true });
4008
- const path = join9(dir, PARTITION_INDEX_FILENAME);
4297
+ const dir = join10(profileDir, ".recency-guard");
4298
+ if (!existsSync9(dir)) mkdirSync6(dir, { recursive: true });
4299
+ const path = join10(dir, PARTITION_INDEX_FILENAME);
4009
4300
  const merged = mergePartitionIndexes(readPartitionIndex(profileDir), index);
4010
4301
  writeFileAtomicSync(path, JSON.stringify(merged, null, 2));
4011
4302
  } catch {
@@ -4013,10 +4304,10 @@ function writePartitionIndex(profileDir, index) {
4013
4304
  }
4014
4305
  async function writePartitionIndexLocked(profileDir, index) {
4015
4306
  try {
4016
- const dir = join9(profileDir, ".recency-guard");
4307
+ const dir = join10(profileDir, ".recency-guard");
4017
4308
  await mkdir2(dir, { recursive: true });
4018
- const path = join9(dir, PARTITION_INDEX_FILENAME);
4019
- await withFileLock2(
4309
+ const path = join10(dir, PARTITION_INDEX_FILENAME);
4310
+ await withFileLock3(
4020
4311
  path,
4021
4312
  async () => {
4022
4313
  const merged = mergePartitionIndexes(readPartitionIndex(profileDir), index);
@@ -4093,7 +4384,7 @@ function buildGuardIsolationView(input) {
4093
4384
  function partitionArtifacts(profileDir, key) {
4094
4385
  const dir = partitionDir(profileDir, key);
4095
4386
  return ["journal.jsonl", "snapshot.json", "state.json", "decision.json", "backups"].map(
4096
- (name2) => join9(dir, name2)
4387
+ (name2) => join10(dir, name2)
4097
4388
  );
4098
4389
  }
4099
4390
 
@@ -4137,6 +4428,13 @@ async function runBootOrchestration(deps) {
4137
4428
  const exitClass = abnormal.exitClass;
4138
4429
  deps.reconcilePrepared();
4139
4430
  const recovering = state.autoDisabled.length > 0;
4431
+ if (state.rollbackArmed) {
4432
+ deps.store.appendSync({
4433
+ kind: "note",
4434
+ detail: `[recency-guard] \u542F\u52A8\u68C0\u6D4B\u5230\u7EA7\u8054\u5239\u8F66\u56DE\u6EDA\u6807\u8BB0\uFF08\u4E0A\u4E00\u8F6E\u5347\u7EA7\u5230\u9876\uFF09\u21D2 \u6267\u884C\u56DE\u6EDA\u5230\u5D29\u6E83\u524D\u542F\u52A8\u72B6\u6001`
4435
+ });
4436
+ await deps.executeRollback();
4437
+ }
4140
4438
  if (crashedLastRun) {
4141
4439
  deps.machine.transition("crashed", `\u4E0A\u6B21\u8FD0\u884C\u4EE5\u9000\u51FA\u7801 ${sentinel?.exitCode ?? "\u672A\u77E5"} \u7ED3\u675F`);
4142
4440
  } else {
@@ -5332,6 +5630,229 @@ function pctText(rate, digits) {
5332
5630
  return `${(rate * 100).toFixed(digits)}%`;
5333
5631
  }
5334
5632
 
5633
+ // src/host/observe/preventive.ts
5634
+ var MAD_TO_SIGMA = 1.4826;
5635
+ var IQR_TO_SIGMA = 1.349;
5636
+ var MAD_FROM_MEAN_ABS = 1.2533;
5637
+ var MOVING_RANGE_D2 = 1.128;
5638
+ function levelScale(values) {
5639
+ const sigma = MAD_TO_SIGMA * medianAbsoluteDeviation(values);
5640
+ return sigma > 0 ? { sigma, estimator: "mad" } : iqrScale(values);
5641
+ }
5642
+ function iqrScale(values) {
5643
+ const iqr = quantile(values, 0.75) - quantile(values, 0.25);
5644
+ if (iqr > 0) return { sigma: iqr / IQR_TO_SIGMA, estimator: "iqr" };
5645
+ return meanAbsDevScale(values);
5646
+ }
5647
+ function meanAbsDevScale(values) {
5648
+ const mid = median(values);
5649
+ const meanAbsDev = values.reduce((sum, v) => sum + Math.abs(v - mid), 0) / values.length;
5650
+ return meanAbsDev > 0 ? { sigma: MAD_FROM_MEAN_ABS * meanAbsDev, estimator: "meanAbsDev" } : { sigma: 0, estimator: "none" };
5651
+ }
5652
+ function movingRangeScale(values) {
5653
+ if (values.length < 2) return { sigma: 0, estimator: "none" };
5654
+ let sum = 0;
5655
+ for (let i = 1; i < values.length; i += 1) sum += Math.abs(values[i] - values[i - 1]);
5656
+ const sigma = sum / (values.length - 1) / MOVING_RANGE_D2;
5657
+ return sigma > 0 ? { sigma, estimator: "movingRange" } : { sigma: 0, estimator: "none" };
5658
+ }
5659
+ var LOAD_BAND_SIGMA_LIMIT = 3;
5660
+ var LOAD_BAND_MIN_SAMPLES = 5;
5661
+ function loadTimeEwma(loadTimesMs, halfLife = 3, sigmaLimit = LOAD_BAND_SIGMA_LIMIT) {
5662
+ const samples = loadTimesMs.filter((value2) => Number.isFinite(value2) && value2 >= 0);
5663
+ const lambda = ewmaAlpha(halfLife);
5664
+ const bandFactor = Math.sqrt(lambda / (2 - lambda));
5665
+ const formula = "L_t = \u03BB\xB7x_t + (1\u2212\u03BB)\xB7L_{t\u22121}\uFF08\u6309 1\u2212(1\u2212\u03BB)^n \u53BB\u6696\u673A\u504F\u7F6E\uFF09\uFF1B\u03BC\u0302 = med(x)\uFF1B\u03C3\u0302 = 1.4826\xB7MAD(x)\uFF1BUCL/LCL = \u03BC\u0302 \xB1 L\xB7\u03C3\u0302\xB7\u221A(\u03BB/(2\u2212\u03BB))";
5666
+ const meta = (inputs, n) => ({
5667
+ formula,
5668
+ inputs,
5669
+ sampleSize: n,
5670
+ confidence: sampleConfidence(n)
5671
+ });
5672
+ const minSamples = Number.isFinite(lambda) && lambda > 0 ? Math.max(LOAD_BAND_MIN_SAMPLES, Math.ceil(1 / lambda)) : Number.POSITIVE_INFINITY;
5673
+ if (samples.length < minSamples) {
5674
+ return undefinedMetric(
5675
+ `\u81F3\u5C11\u9700\u8981 ${Number.isFinite(minSamples) ? minSamples : "\u221E"} \u6B21\u52A0\u8F7D\u6837\u672C\uFF08\u2248 \u4E00\u4E2A EWMA \u8BB0\u5FC6\u957F\u5EA6 1/\u03BB\uFF09\u624D\u80FD\u7ACB\u63A7\u5236\u5E26\uFF0C\u5F53\u524D ${samples.length} \u6B21`,
5676
+ "\u4E0D\u53EF\u5224\u5B9A",
5677
+ meta({ samples: samples.length, halfLife, lambda: round42(lambda) }, samples.length)
5678
+ );
5679
+ }
5680
+ const baseline = median(samples);
5681
+ if (!(baseline > 0)) {
5682
+ return undefinedMetric("\u4E2D\u4F4D\u52A0\u8F7D\u8017\u65F6\u4E3A 0\uFF0C\u5E26\u5BBD\u4E0E\u6BD4\u503C\u90FD\u5931\u53BB\u5C3A\u5EA6\uFF08\u4E0D\u7B49\u4E8E\u300C\u52A0\u8F7D\u5F88\u5FEB\u300D\uFF09", "\u4E0D\u53EF\u5224\u5B9A", meta({ samples: samples.length, baselineMs: 0, halfLife }, samples.length));
5683
+ }
5684
+ const scale = levelScale(samples);
5685
+ const sigma = scale.sigma;
5686
+ const level = ewmaLevel(samples, halfLife);
5687
+ const band = sigmaLimit * sigma * bandFactor;
5688
+ const upper = baseline + band;
5689
+ const lower = Math.max(0, baseline - band);
5690
+ const ratio = round42(level / baseline);
5691
+ const alert = sigma > 0 && level > upper;
5692
+ const value = {
5693
+ levelMs: Math.round(level),
5694
+ baselineMs: Math.round(baseline),
5695
+ upperMs: Math.round(upper),
5696
+ lowerMs: Math.round(lower),
5697
+ sigmaMs: round42(sigma),
5698
+ sigmaEstimator: scale.estimator,
5699
+ bandFactor: round42(bandFactor),
5700
+ ratio,
5701
+ alert
5702
+ };
5703
+ const label = sigma <= 0 ? `\u52A0\u8F7D\u8017\u65F6\u5B8C\u5168\u89C4\u5219\uFF08\u03C3\u0302=0\uFF0C${samples.length} \u6B21\uFF09\uFF1A\u96F6\u5BBD\u5E26\u65E0\u533A\u5206\u5EA6\uFF0C\u4E0D\u9884\u8B66` : alert ? `\u52A0\u8F7D\u53D8\u6162\u9884\u8B66\uFF1AEWMA ${value.levelMs}ms \u8D8A\u8FC7 UCL ${value.upperMs}ms\uFF08\u57FA\u7EBF ${value.baselineMs}ms\u3001\u03C3\u0302 ${value.sigmaMs}ms\u3014${scale.estimator}\u3015\u3001${samples.length} \u6B21\u6837\u672C\uFF09` : `\u52A0\u8F7D\u8017\u65F6\u53D7\u63A7\uFF1AEWMA ${value.levelMs}ms \u5728 [${value.lowerMs}, ${value.upperMs}]ms \u5E26\u5185\uFF08\u57FA\u7EBF ${value.baselineMs}ms\u3001${samples.length} \u6B21\u6837\u672C\uFF09`;
5704
+ return definedMetric(value, label, meta({ samples: samples.length, halfLife, lambda: round42(lambda), baselineMs: value.baselineMs, sigmaMs: value.sigmaMs, upperMs: value.upperMs, estimator: scale.estimator, ratio, alerted: alert ? 1 : 0 }, samples.length));
5705
+ }
5706
+ var CONFIG_CUSUM_REFERENCE = 0.5;
5707
+ var CONFIG_CUSUM_THRESHOLD = 5;
5708
+ var CONFIG_CUSUM_MIN_INTERVALS = 5;
5709
+ function configChangeCusum(changeTimesMs, reference = CONFIG_CUSUM_REFERENCE, threshold = CONFIG_CUSUM_THRESHOLD) {
5710
+ const times = changeTimesMs.filter((t) => Number.isFinite(t)).sort((a, b) => a - b);
5711
+ const gaps = [];
5712
+ for (let i = 1; i < times.length; i += 1) {
5713
+ const gap = times[i] - times[i - 1];
5714
+ if (gap > 0) gaps.push(gap);
5715
+ }
5716
+ const formula = "S_i = max(0, S_{i\u22121} + z_i \u2212 k)\uFF0Cz_i = (\u03BC\u0302 \u2212 g_i)/\u03C3\u0302\uFF0C\u03BC\u0302 = med(g)\uFF0C\u03C3\u0302 = MR\u0304/1.128\uFF0Ck = 0.5\uFF0Ch = 5";
5717
+ const meta = (inputs, n) => ({
5718
+ formula,
5719
+ inputs,
5720
+ sampleSize: n,
5721
+ confidence: sampleConfidence(n)
5722
+ });
5723
+ if (gaps.length < CONFIG_CUSUM_MIN_INTERVALS) {
5724
+ return undefinedMetric(
5725
+ `\u81F3\u5C11\u9700\u8981 ${CONFIG_CUSUM_MIN_INTERVALS} \u4E2A\u53D8\u66F4\u95F4\u9694\uFF08${CONFIG_CUSUM_MIN_INTERVALS + 1} \u6B21\u53D8\u66F4\uFF09\u624D\u80FD\u5224\u5B9A\u9891\u7387\u6F02\u79FB\uFF0C\u5F53\u524D ${gaps.length} \u4E2A`,
5726
+ "\u4E0D\u53EF\u5224\u5B9A",
5727
+ meta({ changes: times.length, gaps: gaps.length, reference, threshold }, gaps.length)
5728
+ );
5729
+ }
5730
+ const baseline = median(gaps);
5731
+ if (!(baseline > 0)) {
5732
+ return undefinedMetric("\u4E2D\u4F4D\u53D8\u66F4\u95F4\u9694\u4E3A 0\uFF08\u591A\u6570\u53D8\u66F4\u6324\u5728\u540C\u4E00\u65F6\u523B\uFF09\uFF0C\u6CA1\u6709\u300C\u9891\u7387\u300D\u53EF\u5224", "\u4E0D\u53EF\u5224\u5B9A", meta({ changes: times.length, gaps: gaps.length, baselineMs: 0 }, gaps.length));
5733
+ }
5734
+ const scale = movingRangeScale(gaps);
5735
+ const sigma = scale.sigma;
5736
+ if (!(sigma > 0)) {
5737
+ return undefinedMetric("\u53D8\u66F4\u95F4\u9694\u5B8C\u5168\u89C4\u5219\uFF08\u03C3\u0302=0\uFF09\uFF0C\u6807\u51C6\u5316\u589E\u91CF\u7684\u5C3A\u5EA6\u65E0\u5B9A\u4E49", "\u4E0D\u53EF\u5224\u5B9A", meta({ changes: times.length, gaps: gaps.length, baselineMs: Math.round(baseline), sigmaMs: 0 }, gaps.length));
5738
+ }
5739
+ let statistic = 0;
5740
+ let breachIndex = null;
5741
+ for (let i = 0; i < gaps.length; i += 1) {
5742
+ const z = (baseline - gaps[i]) / sigma;
5743
+ statistic = Math.max(0, statistic + z - reference);
5744
+ if (breachIndex === null && statistic > threshold) breachIndex = i;
5745
+ }
5746
+ const alert = breachIndex !== null;
5747
+ const value = {
5748
+ statistic: round42(statistic),
5749
+ threshold,
5750
+ reference,
5751
+ baselineMs: Math.round(baseline),
5752
+ sigmaMs: round42(sigma),
5753
+ sigmaEstimator: scale.estimator,
5754
+ intervals: gaps.length,
5755
+ breachIndex,
5756
+ alert
5757
+ };
5758
+ const label = alert ? `\u914D\u7F6E\u53D8\u66F4\u53D8\u5BC6\u9884\u8B66\uFF1ACUSUM S=${value.statistic} \u8D8A\u8FC7 h=${threshold}\uFF08\u7B2C ${(breachIndex ?? 0) + 1} \u4E2A\u95F4\u9694\u8D77\uFF0C\u57FA\u7EBF ${(baseline / 1e3).toFixed(1)}s\u3001\u03C3\u0302 ${(sigma / 1e3).toFixed(1)}s\u3014${scale.estimator}\u3015\u3001${gaps.length} \u4E2A\u95F4\u9694\uFF09` : `\u914D\u7F6E\u53D8\u66F4\u9891\u7387\u672A\u89C1\u4E0A\u884C\uFF1AS=${value.statistic} \u2264 h=${threshold}\uFF08\u57FA\u7EBF ${(baseline / 1e3).toFixed(1)}s\u3001\u03C3\u0302 ${(sigma / 1e3).toFixed(1)}s\u3001${gaps.length} \u4E2A\u95F4\u9694\uFF09`;
5759
+ return definedMetric(value, label, meta({ changes: times.length, gaps: gaps.length, baselineMs: value.baselineMs, sigmaMs: value.sigmaMs, statistic: value.statistic, threshold, reference, breachIndex, alerted: alert ? 1 : 0 }, gaps.length));
5760
+ }
5761
+
5762
+ // src/host/surface/preventive-view.ts
5763
+ var BOOT_NOTE_PREFIX = "dsh \u542F\u52A8 pid=";
5764
+ function bootTimestamps(journal) {
5765
+ const times = [];
5766
+ for (const record of journal) {
5767
+ if (record.kind !== "note") continue;
5768
+ if (typeof record.detail !== "string" || !record.detail.startsWith(BOOT_NOTE_PREFIX)) continue;
5769
+ const parsed = Date.parse(record.t);
5770
+ if (Number.isFinite(parsed)) times.push(parsed);
5771
+ }
5772
+ return times.sort((a, b) => a - b);
5773
+ }
5774
+ function configChangeTimestamps(journal) {
5775
+ const times = [];
5776
+ for (const record of journal) {
5777
+ if (record.kind !== "install" && record.kind !== "update") continue;
5778
+ const parsed = Date.parse(record.t);
5779
+ if (Number.isFinite(parsed)) times.push(parsed);
5780
+ }
5781
+ return times.sort((a, b) => a - b);
5782
+ }
5783
+ function bootIntervals(boots) {
5784
+ const gaps = [];
5785
+ let previous;
5786
+ for (const current of boots) {
5787
+ if (previous !== void 0) {
5788
+ const gap = current - previous;
5789
+ if (Number.isFinite(gap) && gap > 0) gaps.push(gap);
5790
+ }
5791
+ previous = current;
5792
+ }
5793
+ return gaps;
5794
+ }
5795
+ function frequencyPerMinute(intervalsMs) {
5796
+ return intervalsMs.map((gap) => 6e4 / gap);
5797
+ }
5798
+ function projectBand(band) {
5799
+ const value = band.value;
5800
+ return {
5801
+ defined: band.defined,
5802
+ label: band.label,
5803
+ reason: band.reason ?? (band.defined ? null : "\u4E0D\u53EF\u5224\u5B9A"),
5804
+ samples: band.sampleSize ?? 0,
5805
+ value: value === null ? null : {
5806
+ current: value.levelMs,
5807
+ baseline: value.baselineMs,
5808
+ upper: value.upperMs,
5809
+ lower: value.lowerMs,
5810
+ sigma: value.sigmaMs,
5811
+ sigmaEstimator: value.sigmaEstimator,
5812
+ ratio: value.ratio,
5813
+ alert: value.alert
5814
+ }
5815
+ };
5816
+ }
5817
+ function projectCusum(metric) {
5818
+ const value = metric.value;
5819
+ return {
5820
+ defined: metric.defined,
5821
+ label: metric.label,
5822
+ reason: metric.reason ?? (metric.defined ? null : "\u4E0D\u53EF\u5224\u5B9A"),
5823
+ samples: metric.sampleSize ?? 0,
5824
+ value: value === null ? null : {
5825
+ statistic: value.statistic,
5826
+ threshold: value.threshold,
5827
+ reference: value.reference,
5828
+ baselineMs: value.baselineMs,
5829
+ sigmaMs: value.sigmaMs,
5830
+ sigmaEstimator: value.sigmaEstimator,
5831
+ intervals: value.intervals,
5832
+ breachIndex: value.breachIndex,
5833
+ alert: value.alert
5834
+ }
5835
+ };
5836
+ }
5837
+ function emptyPreventive() {
5838
+ return projectPreventive([]);
5839
+ }
5840
+ function projectPreventive(journal) {
5841
+ const boots = bootTimestamps(journal);
5842
+ const intervals = bootIntervals(boots);
5843
+ const changes = configChangeTimestamps(journal);
5844
+ return {
5845
+ loadTime: projectBand(loadTimeEwma(frequencyPerMinute(intervals))),
5846
+ configChanges: projectCusum(configChangeCusum(changes)),
5847
+ source: {
5848
+ bootSamples: boots.length,
5849
+ changeSamples: changes.length,
5850
+ units: "per-minute",
5851
+ note: "\u542F\u52A8\u9891\u7387\uFF08\u6B21/\u5206\u949F\uFF09= \u76F8\u90BB\u542F\u52A8 note \u65F6\u523B\u5DEE\u7684\u5012\u6570\uFF1B\u4EE3\u7406\u4E0D\u662F\u771F\u5B9E\u52A0\u8F7D\u8017\u65F6\uFF08\u95F4\u9694\u91CC\u6DF7\u7740\u4F1A\u8BDD\u957F\u5EA6\u4E0E\u505C\u673A\u65F6\u95F4\uFF09\u3002\u53EA\u9884\u8B66\uFF0C\u4E0D\u5173\u95ED\u4EFB\u4F55\u63D2\u4EF6\u3002"
5852
+ }
5853
+ };
5854
+ }
5855
+
5335
5856
  // src/host/surface/snapshot.ts
5336
5857
  var EVENT_FLOW_LIMIT = 64;
5337
5858
  function buildPanelSnapshot(input, now = Date.now()) {
@@ -5411,6 +5932,11 @@ function buildPanelSnapshot(input, now = Date.now()) {
5411
5932
  // 这一点必须诚实:空数组只表示「没有可展示的 finding」,不区分原因。
5412
5933
  conflicts: [...input.conflicts ?? []],
5413
5934
  unresolved: [...input.unresolved ?? []],
5935
+ // RQ3 预防性读数(T15-01):只预警不行动,见 preventive-view.ts 头注。
5936
+ // 调用方没传 ⇒ 退回空读数(defined:false + reason),不伪装成「无预警」。
5937
+ preventive: input.preventive ?? emptyPreventive(),
5938
+ // T15-03:未知 schemaVersion 的降级必须与状态同屏(缺省 = 未读到损坏)。
5939
+ corrupt: input.corruption ?? { state: false, decision: false },
5414
5940
  // revision 是**派生**的:同一份事实重算必得同一枚值(哈希而非计数器),
5415
5941
  // 所以它不需要持久化位点,也不会在崩溃后说谎。字段装配唯一在
5416
5942
  // Guard.revisionFactsFrom(见 SnapshotInput 注释)—— 本函数只投影不拼字段。
@@ -5516,6 +6042,10 @@ function buildStatusOutput(input) {
5516
6042
  // 「已经试过但治不了」混成一件事,用户无法判断下一步该做什么。
5517
6043
  conflicts: input.conflicts ?? [],
5518
6044
  unresolved: input.unresolved ?? [],
6045
+ // RQ3 预防性读数(T15-01):缺省 ⇒ 空读数(不可判定,不是「无预警」)。
6046
+ preventive: input.preventive ?? emptyPreventive(),
6047
+ // T15-03:未知 schemaVersion 的降级必须与状态同屏,否则会被读成「干净启动」。
6048
+ corrupt: input.corruption ?? { state: false, decision: false },
5519
6049
  lifecycle: {
5520
6050
  stage: lifecycle.stage,
5521
6051
  stabilityScore: lifecycle.stabilityScore,
@@ -5699,10 +6229,10 @@ async function buildPartitionSnapshot(input, key) {
5699
6229
  }
5700
6230
 
5701
6231
  // src/host/data/archive.ts
5702
- import { existsSync as existsSync9, mkdirSync as mkdirSync7, readdirSync as readdirSync2, readFileSync as readFileSync9, renameSync as renameSync5, statSync as statSync3, writeFileSync as writeFileSync7 } from "node:fs";
5703
- import { join as join10 } from "node:path";
6232
+ import { existsSync as existsSync10, mkdirSync as mkdirSync7, readdirSync as readdirSync3, readFileSync as readFileSync9, renameSync as renameSync6, statSync as statSync3, writeFileSync as writeFileSync7 } from "node:fs";
6233
+ import { join as join11 } from "node:path";
5704
6234
  function classify(name2) {
5705
- if (name2 === "journal.jsonl") return "journal";
6235
+ if (/^journal(\.\d+)?\.jsonl$/.test(name2)) return "journal";
5706
6236
  if (name2 === "state.json") return "state";
5707
6237
  if (name2 === "decision.json") return "decision";
5708
6238
  if (name2 === "backups") return "backup";
@@ -5711,34 +6241,40 @@ function classify(name2) {
5711
6241
  function archiveAndReset(partitionDir2, workspace, reason, now = /* @__PURE__ */ new Date()) {
5712
6242
  const stateDir = partitionDir2;
5713
6243
  const stamp = now.toISOString().replace(/[:.]/g, "-");
5714
- const archiveRoot = join10(stateDir, "archive", stamp);
5715
- const archiveDir = join10(archiveRoot, "artifacts");
6244
+ const archiveRoot = join11(stateDir, "archive", stamp);
6245
+ const archiveDir = join11(archiveRoot, "artifacts");
5716
6246
  const entries = [];
5717
6247
  const skipped = [];
5718
6248
  let crashSeq = 0;
5719
6249
  let autoDisabled = [];
5720
6250
  let journalEvents = 0;
5721
6251
  try {
5722
- const raw = readFileSync9(join10(stateDir, "state.json"), "utf8");
6252
+ const raw = readFileSync9(join11(stateDir, "state.json"), "utf8");
5723
6253
  const state = JSON.parse(raw);
5724
6254
  crashSeq = state.crashSeq ?? 0;
5725
6255
  autoDisabled = (state.autoDisabled ?? []).map((d) => d.name);
5726
6256
  } catch {
5727
6257
  }
5728
6258
  try {
5729
- const raw = readFileSync9(join10(stateDir, "journal.jsonl"), "utf8");
5730
- journalEvents = raw.split("\n").filter(Boolean).length;
6259
+ const journalNames = readdirSync3(stateDir).filter((n) => /^journal(\.\d+)?\.jsonl$/.test(n));
6260
+ for (const name2 of journalNames) {
6261
+ try {
6262
+ const raw = readFileSync9(join11(stateDir, name2), "utf8");
6263
+ journalEvents += raw.split("\n").filter(Boolean).length;
6264
+ } catch {
6265
+ }
6266
+ }
5731
6267
  } catch {
5732
6268
  }
5733
- if (existsSync9(stateDir)) {
6269
+ if (existsSync10(stateDir)) {
5734
6270
  mkdirSync7(archiveDir, { recursive: true });
5735
- for (const name2 of readdirSync2(stateDir)) {
6271
+ for (const name2 of readdirSync3(stateDir)) {
5736
6272
  if (name2 === "archive") continue;
5737
- const source = join10(stateDir, name2);
5738
- const target = join10(archiveDir, name2);
6273
+ const source = join11(stateDir, name2);
6274
+ const target = join11(archiveDir, name2);
5739
6275
  try {
5740
6276
  const bytes = statSync3(source).isDirectory() ? directoryBytes(source) : statSync3(source).size;
5741
- renameSync5(source, target);
6277
+ renameSync6(source, target);
5742
6278
  entries.push({ path: name2, bytes, kind: classify(name2) });
5743
6279
  } catch {
5744
6280
  skipped.push(name2);
@@ -5756,20 +6292,20 @@ function archiveAndReset(partitionDir2, workspace, reason, now = /* @__PURE__ */
5756
6292
  summary: { crashSeq, autoDisabled, journalEvents }
5757
6293
  };
5758
6294
  mkdirSync7(archiveRoot, { recursive: true });
5759
- writeFileSync7(join10(archiveRoot, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
6295
+ writeFileSync7(join11(archiveRoot, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
5760
6296
  resetArtifacts(stateDir, now);
5761
6297
  return { archiveDir, manifest, count: entries.length, skipped };
5762
6298
  }
5763
6299
  function resetArtifacts(stateDir, now = /* @__PURE__ */ new Date()) {
5764
- mkdirSync7(join10(stateDir, "backups"), { recursive: true });
6300
+ mkdirSync7(join11(stateDir, "backups"), { recursive: true });
5765
6301
  writeFileSync7(
5766
- join10(stateDir, "decision.json"),
5767
- JSON.stringify({ capturedAt: now.toISOString(), suspects: [], disable: [], reason: "none" }, null, 2),
6302
+ join11(stateDir, "decision.json"),
6303
+ JSON.stringify({ schemaVersion: SCHEMA_VERSION, capturedAt: now.toISOString(), suspects: [], disable: [], reason: "none" }, null, 2),
5768
6304
  "utf8"
5769
6305
  );
5770
6306
  writeFileSync7(
5771
- join10(stateDir, "state.json"),
5772
- JSON.stringify({ bootMarker: null, crashSeq: 0, autoDisabled: [], stabilized: false, restored: [] }, null, 2),
6307
+ join11(stateDir, "state.json"),
6308
+ JSON.stringify({ schemaVersion: SCHEMA_VERSION, bootMarker: null, crashSeq: 0, autoDisabled: [], stabilized: false, restored: [] }, null, 2),
5773
6309
  "utf8"
5774
6310
  );
5775
6311
  }
@@ -5777,12 +6313,12 @@ function directoryBytes(dir) {
5777
6313
  let total = 0;
5778
6314
  let names;
5779
6315
  try {
5780
- names = readdirSync2(dir);
6316
+ names = readdirSync3(dir);
5781
6317
  } catch {
5782
6318
  return 0;
5783
6319
  }
5784
6320
  for (const name2 of names) {
5785
- const path = join10(dir, name2);
6321
+ const path = join11(dir, name2);
5786
6322
  try {
5787
6323
  const info = statSync3(path);
5788
6324
  total += info.isDirectory() ? directoryBytes(path) : info.size;
@@ -5792,14 +6328,18 @@ function directoryBytes(dir) {
5792
6328
  }
5793
6329
  return total;
5794
6330
  }
5795
- function listArchives(partitionDir2) {
5796
- const archiveRoot = join10(partitionDir2, "archive");
5797
- if (!existsSync9(archiveRoot)) return [];
6331
+ function listArchives(partitionDir2, onUnsupportedVersion) {
6332
+ const archiveRoot = join11(partitionDir2, "archive");
6333
+ if (!existsSync10(archiveRoot)) return [];
5798
6334
  const out = [];
5799
- for (const name2 of readdirSync2(archiveRoot)) {
5800
- const dir = join10(archiveRoot, name2);
6335
+ for (const name2 of readdirSync3(archiveRoot)) {
6336
+ const dir = join11(archiveRoot, name2);
5801
6337
  try {
5802
- const manifest = JSON.parse(readFileSync9(join10(dir, "manifest.json"), "utf8"));
6338
+ const manifest = JSON.parse(readFileSync9(join11(dir, "manifest.json"), "utf8"));
6339
+ if (manifest?.schemaVersion !== void 0 && manifest.schemaVersion !== SCHEMA_VERSION) {
6340
+ onUnsupportedVersion?.(dir, manifest.schemaVersion);
6341
+ continue;
6342
+ }
5803
6343
  out.push({
5804
6344
  dir,
5805
6345
  archivedAt: manifest.archivedAt,
@@ -5815,7 +6355,9 @@ function listArchives(partitionDir2) {
5815
6355
  }
5816
6356
  function readArchiveManifest(archiveDir) {
5817
6357
  try {
5818
- return JSON.parse(readFileSync9(join10(archiveDir, "manifest.json"), "utf8"));
6358
+ const parsed = JSON.parse(readFileSync9(join11(archiveDir, "manifest.json"), "utf8"));
6359
+ if (parsed?.schemaVersion !== void 0 && parsed.schemaVersion !== SCHEMA_VERSION) return null;
6360
+ return parsed;
5819
6361
  } catch {
5820
6362
  return null;
5821
6363
  }
@@ -6248,6 +6790,16 @@ function formatStatus(s) {
6248
6790
  facts.push([v.act ? "\u6062\u590D\u5224\u5B9A\uFF08\u5DF2\u884C\u52A8\uFF09" : "\u6062\u590D\u5224\u5B9A\uFF08\u89C2\u5BDF\u4E2D\uFF09", v.label]);
6249
6791
  facts.push(["\u5224\u5B9A\u8F6E\u6B21", v.rounds + "/" + v.required]);
6250
6792
  }
6793
+ if (s.preventive !== void 0) {
6794
+ const rows = [
6795
+ ["\u542F\u52A8\u9891\u7387\uFF08\u4EE3\u7406\uFF09", s.preventive.loadTime],
6796
+ ["\u914D\u7F6E\u53D8\u66F4\u9891\u7387", s.preventive.configChanges]
6797
+ ];
6798
+ for (const [key, metric] of rows) {
6799
+ if (metric === void 0) continue;
6800
+ facts.push([key, metric.defined ? metric.label : `\u4E0D\u53EF\u5224\u5B9A\uFF08${metric.reason ?? "\u539F\u56E0\u7F3A\u5931"}\uFF09`]);
6801
+ }
6802
+ }
6251
6803
  if (s.pluginVersion !== void 0 && s.pluginVersion !== null) {
6252
6804
  facts.push(["\u63D2\u4EF6\u7248\u672C", s.pluginVersion]);
6253
6805
  }
@@ -6670,6 +7222,7 @@ var Config = SchemaFactory ? SchemaFactory.object({
6670
7222
  }) : fallbackConfigSchema();
6671
7223
  var inject = ["tools", "pluginManager", "profileContext"];
6672
7224
  function apply(ctx, config) {
7225
+ rejectUnknownConfigKeys(config);
6673
7226
  const services = ctx;
6674
7227
  const pm = services.pluginManager;
6675
7228
  const profile = services.profileContext;
@@ -7258,13 +7811,15 @@ var Guard = class {
7258
7811
  exitCode,
7259
7812
  suspects: targets.map((t) => t.bundle)
7260
7813
  });
7814
+ const headSuspect = decision.targets[0]?.bundle ?? decision.disable[0] ?? null;
7815
+ const disableList = verdict.rollback ? headSuspect !== null ? [headSuspect] : [] : decision.disable;
7261
7816
  this.recordCooccurrenceSync(ranked, verdict.act ? targets.map((t) => t.bundle) : []);
7262
7817
  this.store.writeDecisionSync({
7263
7818
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
7264
7819
  suspects: this.decisionSuspectsFor(ranked, history),
7265
- disable: decision.disable,
7820
+ disable: disableList,
7266
7821
  reason: "crash-recovery",
7267
- phase: verdict.act ? "quarantined" : "prepared",
7822
+ phase: verdict.rollback ? "rollback" : verdict.act ? "quarantined" : "prepared",
7268
7823
  crashSeq: seq,
7269
7824
  ...decision.deterministicEvidence === void 0 ? {} : { deterministicEvidence: decision.deterministicEvidence },
7270
7825
  ...decision.unresolved.length === 0 ? {} : { unresolved: decision.unresolved }
@@ -7282,13 +7837,20 @@ var Guard = class {
7282
7837
  ...state,
7283
7838
  crashSeq: seq,
7284
7839
  stabilized: false,
7285
- autoDisabled: targets.map((t) => ({
7840
+ autoDisabled: verdict.rollback ? headSuspect !== null ? targets.filter((t) => t.bundle === headSuspect).map((t) => ({
7841
+ name: t.bundle,
7842
+ version: t.version,
7843
+ disabledAt: (/* @__PURE__ */ new Date()).toISOString(),
7844
+ reason: "auto-recency",
7845
+ crashSeq: seq
7846
+ })) : [] : targets.map((t) => ({
7286
7847
  name: t.bundle,
7287
7848
  version: t.version,
7288
7849
  disabledAt: (/* @__PURE__ */ new Date()).toISOString(),
7289
7850
  reason: "auto-recency",
7290
7851
  crashSeq: seq
7291
- }))
7852
+ })),
7853
+ ...verdict.rollback ? { rollbackArmed: true } : {}
7292
7854
  });
7293
7855
  this.recordStep("crash-decision", true, `\u7B2C ${seq} \u6B21\u5D29\u6E83 \u2192 \u5173\u95ED ${targets.map((t) => t.bundle).join(", ") || "\u65E0"}`);
7294
7856
  } catch (error) {
@@ -7336,9 +7898,36 @@ ${error?.stack ?? ""}
7336
7898
  recordChanges: () => this.recordChanges(),
7337
7899
  observeOfficialExperimental: () => this.observeOfficialExperimental(),
7338
7900
  scheduleAutoRestore: () => this.scheduleAutoRestore(),
7339
- applyAbnormalRecovery: (next) => this.applyAbnormalRecovery(next)
7901
+ applyAbnormalRecovery: (next) => this.applyAbnormalRecovery(next),
7902
+ executeRollback: () => this.executeRollback()
7340
7903
  });
7341
7904
  }
7905
+ /**
7906
+ * 级联刹车回滚的执行体(v0.18 T16-12)。
7907
+ *
7908
+ * 由 boot 编排在检测到 `rollbackArmed` 时调用:把被自动禁用的插件
7909
+ * 恢复到崩溃前启动状态,只保留头号嫌疑。投影实现在 recovery-actions.ts
7910
+ * 的 `rollbackToPreCrash`,这里只做依赖绑定与头号嫌疑的确定。
7911
+ *
7912
+ * ## 为什么在启动路径执行而不是崩溃路径
7913
+ *
7914
+ * 回滚要调插件管理器的 `setBundleEnabled`(异步、HMR 事务),崩溃路径
7915
+ * (process exit 处理器)只有同步 IO 预算。崩溃路径能做的只是**置标记 +
7916
+ * 落决策**,真正启用插件只能延后到下一轮启动 —— 与 autoRestore 的
7917
+ * 1.5s 延后同源(HMR 事务不能嵌套)。
7918
+ */
7919
+ async executeRollback() {
7920
+ const state = await this.store.readState();
7921
+ const decision = this.store.readDecisionSync();
7922
+ const head = decision?.disable?.[0] ?? state.autoDisabled[state.autoDisabled.length - 1]?.name ?? null;
7923
+ try {
7924
+ const result = await rollbackToPreCrash(this.recoveryDeps(), head);
7925
+ this.endStep("rollback", true, `\u56DE\u6EDA\uFF1A\u91CD\u65B0\u542F\u7528 ${result.reenabled.length} \u4E2A\uFF0C\u4FDD\u7559 ${result.keptDisabled.length} \u4E2A\u5ACC\u7591`);
7926
+ } catch (error) {
7927
+ this.endStep("rollback", false, describeError(error));
7928
+ throw error;
7929
+ }
7930
+ }
7342
7931
  /**
7343
7932
  * 延后执行自动恢复(v0.11.2 的时序约束,抽出来供两个调用点共用)。
7344
7933
  *
@@ -7376,6 +7965,17 @@ ${error?.stack ?? ""}
7376
7965
  );
7377
7966
  this.store.appendSync({ kind: "note", detail: judged.detail });
7378
7967
  await this.store.updateState((s) => ({ ...s, lastRecoveryVerdict: judged.verdict }));
7968
+ if (judged.rollback) {
7969
+ const state = await this.store.readState();
7970
+ if (state.autoDisabled.length === 0) return;
7971
+ const headEntry = state.autoDisabled.find((d) => d.name === head) ?? state.autoDisabled[state.autoDisabled.length - 1];
7972
+ await this.store.updateState((s) => ({
7973
+ ...s,
7974
+ autoDisabled: s.autoDisabled.filter((d) => d.name === headEntry?.name),
7975
+ rollbackArmed: true
7976
+ }));
7977
+ return;
7978
+ }
7379
7979
  if (judged.act && head !== null) {
7380
7980
  await this.recover(judged.targets);
7381
7981
  }
@@ -7733,6 +8333,10 @@ ${error?.stack ?? ""}
7733
8333
  // 声明式冲突(T14-03):面板与命令窗口看同一份数据面字段。
7734
8334
  conflicts: this.scanConflictsSync(),
7735
8335
  unresolved: this.store.readDecisionSync()?.unresolved ?? [],
8336
+ // RQ3 预防性读数(T15-01):journal 是唯一事实源;只预警不行动。
8337
+ preventive: projectPreventive(journalTail),
8338
+ // T15-03:schema 版本降级事实(未知版本 ⇒ 安全空态,必须可见)。
8339
+ corruption: this.store.corruptionReport(),
7736
8340
  // revision 的事实基座(v0.12 乐观并发):全部取自上面已经读过的状态,
7737
8341
  // 只多一次 readDecisionSync —— 决策文件是几十十字节的小 JSON,
7738
8342
  // 而它是「下次启动会不会拦住插件」的真值,不读它就等于用一份
@@ -7895,7 +8499,13 @@ ${error?.stack ?? ""}
7895
8499
  /** 列出归档(带 manifest 摘要 —— 举他对照时的事实基线)。 */
7896
8500
  async archives() {
7897
8501
  return {
7898
- archives: listArchives(this.store.partitionPath).map((a) => ({
8502
+ archives: listArchives(this.store.partitionPath, (dir, version) => {
8503
+ this.store.appendSync({
8504
+ kind: "note",
8505
+ detail: `[recency-guard] \u5F52\u6863\u6E05\u5355 ${dir} \u7684 schemaVersion=${String(version)} \u4E0D\u53D7\u652F\u6301\uFF08\u53EA\u8BA4 1\uFF09\uFF1B\u5DF2\u8DF3\u8FC7\u89E3\u91CA\uFF0C\u6587\u4EF6\u672A\u88AB\u4FEE\u6539\u3002`,
8506
+ degraded: true
8507
+ });
8508
+ }).map((a) => ({
7899
8509
  ...a,
7900
8510
  summary: readArchiveManifest(a.dir)?.summary
7901
8511
  }))
@@ -7944,7 +8554,11 @@ ${error?.stack ?? ""}
7944
8554
  configEditorAvailable: this.configEditorAvailable,
7945
8555
  // 数据面全量(不切片):截断是渲染策略,不是数据策略。
7946
8556
  conflicts: this.scanConflictsSync(),
7947
- unresolved: this.store.readDecisionSync()?.unresolved ?? []
8557
+ unresolved: this.store.readDecisionSync()?.unresolved ?? [],
8558
+ // RQ3 预防性读数(T15-01):与面板快照同一投影函数(口径不漂移)。
8559
+ preventive: projectPreventive(this.store.readJournalSync(1e3)),
8560
+ // T15-03:schema 版本降级事实(与面板同源)。
8561
+ corruption: this.store.corruptionReport()
7948
8562
  });
7949
8563
  }
7950
8564
  };