@kenz1117/dsh-engram 0.13.6 → 0.13.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -196,6 +196,7 @@ const zh$5 = {
196
196
  "core.observationsHeader": "Consolidated beliefs (distilled from multiple stored memories; verify against sources before high-stakes use):",
197
197
  "core.observationItem": "- {belief} ({count} sources)",
198
198
  "core.reviewDue": "\nPalace review due today: {count}{plus} memories. Use engram_review_queue for active recall (recall beats re-reading).",
199
+ "core.reflectPending": "\n巩固待处理:有 {count} 组会话登记的记忆还没蒸馏。调用 engram_reflect 整理——只摄取不整理,记忆就是散的。",
199
200
  "core.compressSystem": "把记忆条目压缩为更短的一句话表述(每条不超过 40 个字符),保留可跨会话复用的关键信息(事实、偏好、决策、方法)。\n只输出一个 JSON 数组,每项形如 {\"id\": \"原样返回的id\", \"content\": \"压缩后表述\"},条目数量与 id 必须与输入一一对应。\n不要输出 JSON 以外的任何内容。",
200
201
  "core.rationaleHeader": "本轮画像共 {count} 条记忆,挑选理由如下:",
201
202
  "core.rationaleFooter": "如果某条理由错误,请通过 engram_report 反馈,越准的画像越能帮你。",
@@ -231,6 +232,7 @@ const zh$5 = {
231
232
  "core.warnDisposeFinalFailed": "[dsh-engram] 会话结束的收尾处理异常(不影响对话):",
232
233
  "core.warnInjectionSnapshotFailed": "[dsh-engram] 注入快照落库失败(不影响对话):",
233
234
  "core.warnReflectFailed": "[dsh-engram] 会话结束的信念巩固异常({scope},不影响对话):",
235
+ "core.warnIngestWithoutReflect": "[dsh-engram] ingest 开启但 reflect 为 off:记忆只摄取不整理(读起来就是散的)。建议 reflect: auto(或 suggest,靠会话提醒驱动),或定期运行 engram_reflect。",
234
236
  "core.warnReflectBatchDropped": "[dsh-engram] 信念巩固丢弃 {count} 条候选(输出预算/解析失败;未被巩固、下次巩固继续取材)",
235
237
  "core.warnDecayStartupFailed": "[dsh-engram] 启动衰减调度失败(跳过):",
236
238
  "core.warnDecayPeriodicFailed": "[dsh-engram] 周期衰减调度失败(跳过):",
@@ -254,6 +256,8 @@ const en$5 = {
254
256
  "core.observationsHeader": "Consolidated beliefs (distilled from multiple stored memories; verify against sources before high-stakes use):",
255
257
  "core.observationItem": "- {belief} ({count} sources)",
256
258
  "core.reviewDue": "\nPalace review due today: {count}{plus} memories. Use engram_review_queue for active recall (recall beats re-reading).",
259
+ "core.reflectPending": "\nConsolidation pending: {count} session registration(s) hold memories not yet distilled. Call engram_reflect to consolidate them — ingested memories stay scattered until reflected.",
260
+ "core.warnIngestWithoutReflect": "[dsh-engram] ingest is on but reflect is off — memories accumulate without consolidation (they read scattered). Set reflect: auto (or suggest), or run engram_reflect regularly.",
257
261
  "core.compressSystem": "Compress each memory entry into a shorter single-sentence wording (at most 40 characters per entry), keeping the key information that can be reused across sessions (facts, preferences, decisions, methods).\nOutput only one JSON array, each item shaped like {\"id\": \"the id returned verbatim\", \"content\": \"the compressed wording\"}; the number of items and the ids must correspond one-to-one with the input.\nDo not output anything other than JSON.",
258
262
  "core.rationaleHeader": "This profile holds {count} memories in total; they were picked for the following reasons:",
259
263
  "core.rationaleFooter": "If any reason is wrong, report it via engram_report — the more accurate the profile, the better it helps you.",
@@ -1508,6 +1512,7 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
1508
1512
  "autoSlot",
1509
1513
  "reviewScheduling",
1510
1514
  "assessReminder",
1515
+ "reflectReminder",
1511
1516
  "palaceChangeWindowSec",
1512
1517
  "panelAccess",
1513
1518
  "historyBackfillDays",
@@ -1569,6 +1574,7 @@ const Config = z.object({
1569
1574
  panelAccess: z.string(),
1570
1575
  palaceChangeWindowSec: z.number().step(1).min(5).max(600),
1571
1576
  assessReminder: z.boolean(),
1577
+ reflectReminder: z.boolean(),
1572
1578
  historyBackfillDays: z.number().step(1).min(0).max(3650),
1573
1579
  historyBackfillMaxTurnsPerSession: z.number().step(1).min(1).max(500),
1574
1580
  historyBackfillMaxTotalTurns: z.number().step(1).min(1).max(5e3),
@@ -1713,6 +1719,7 @@ function resolveConfig(config = {}) {
1713
1719
  injectItemBudgetDecay: config.injectItemBudgetDecay ?? .9,
1714
1720
  injectItemBudgetFloor: config.injectItemBudgetFloor ?? 24,
1715
1721
  assessReminder: config.assessReminder ?? true,
1722
+ reflectReminder: config.reflectReminder ?? true,
1716
1723
  rankRecencyWeight: config.rankRecencyWeight ?? .2,
1717
1724
  rankProofWeight: config.rankProofWeight ?? .1,
1718
1725
  queryRewrite: config.queryRewrite ?? true,
@@ -2512,6 +2519,7 @@ const en = {
2512
2519
  governanceConflicts: "Conflicts",
2513
2520
  governanceBeliefs: "Beliefs",
2514
2521
  systemRuntime: "Runtime",
2522
+ systemGuardIngestNoReflect: "Ingest is on but consolidation (reflect) is off: memories are collected but never distilled — they read scattered. Set reflect: auto or suggest in the config.",
2515
2523
  systemStorage: "Storage",
2516
2524
  systemModels: "Models & language",
2517
2525
  pageHeaderRuntimeSubtitle: "Plugin and panel versions, the durable job queue, embedding model status.",
@@ -3170,6 +3178,7 @@ const ru = {
3170
3178
  governanceConflicts: "Противоречия",
3171
3179
  governanceBeliefs: "Убеждения",
3172
3180
  systemRuntime: "Время выполнения",
3181
+ systemGuardIngestNoReflect: "Ingest включён, но обобщение (reflect) выключено: воспоминания собираются, но не перегоняются — и читаются разрозненно. Задайте reflect: auto или suggest в конфигурации.",
3173
3182
  systemStorage: "Хранилище",
3174
3183
  systemModels: "Модели и язык",
3175
3184
  pageHeaderRuntimeSubtitle: "Версии плагина и панели, очередь устойчивых заданий, состояние модели эмбеддинга.",
@@ -3826,6 +3835,7 @@ const zh = {
3826
3835
  governanceConflicts: "矛盾",
3827
3836
  governanceBeliefs: "信念",
3828
3837
  systemRuntime: "运行时",
3838
+ systemGuardIngestNoReflect: "摄取已开启但整理(reflect)为关闭:记忆只收集不蒸馏,读起来会是散的。建议在配置里设置 reflect: auto 或 suggest。",
3829
3839
  systemStorage: "存储",
3830
3840
  systemModels: "模型与词典",
3831
3841
  pageHeaderRuntimeSubtitle: "插件与面板版本、持久作业队列、嵌入模型状态。",
@@ -11545,7 +11555,11 @@ function registerEngramRoutes(ctx, deps) {
11545
11555
  return;
11546
11556
  }
11547
11557
  if (req.method === "GET" && route === "version") {
11548
- json(res, 200, { pluginVersion: deps.pluginVersion });
11558
+ json(res, 200, {
11559
+ pluginVersion: deps.pluginVersion,
11560
+ ingest: deps.ingest,
11561
+ reflect: deps.reflect
11562
+ });
11549
11563
  return;
11550
11564
  }
11551
11565
  if (req.method === "GET" && route === "registry") {
@@ -18768,7 +18782,7 @@ function estimateTokens(text) {
18768
18782
  return Math.ceil(wide * WIDE_TOKENS_PER_CHAR + narrow / 4);
18769
18783
  }
18770
18784
  // package.json
18771
- var version = "0.13.6";
18785
+ var version = "0.13.7";
18772
18786
  // src/index.ts
18773
18787
  /**
18774
18788
  * dsh-engram:DeepSeek Harness 跨会话长期记忆插件(host 半)。
@@ -19040,6 +19054,16 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
19040
19054
  const top = await store.topActive("user", resolved.profileTopN);
19041
19055
  if (top.length === 0 && curated === void 0) return decision;
19042
19056
  const dueTotal = resolved.reviewScheduling ? (await Promise.all(["user", "project"].map(async (scope) => (await openStore(scope)).dueReviews(Date.now(), 50)))).reduce((sum, rows) => sum + rows.length, 0) : 0;
19057
+ let reflectPending = 0;
19058
+ if (resolved.reflect === "suggest" && resolved.reflectReminder) reflectPending = (await Promise.all(["user", "project"].map(async (scope) => {
19059
+ return (await (await openStore(scope)).listAuditDetails("reflect-pending")).reduce((total, detail) => {
19060
+ try {
19061
+ return JSON.parse(detail).scope === scope ? total + 1 : total;
19062
+ } catch {
19063
+ return total;
19064
+ }
19065
+ }, 0);
19066
+ }))).reduce((sum, count) => sum + count, 0);
19043
19067
  const itemBudget = {
19044
19068
  start: resolved.injectItemBudgetStart,
19045
19069
  decay: resolved.injectItemBudgetDecay,
@@ -19076,7 +19100,8 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
19076
19100
  count: dueTotal,
19077
19101
  plus: dueTotal >= 50 ? "+" : ""
19078
19102
  });
19079
- const textWithRationale = wrapWithRationale(text, top) + dueLine;
19103
+ const reflectPendingLine = reflectPending === 0 ? "" : message("core.reflectPending", { count: reflectPending });
19104
+ const textWithRationale = wrapWithRationale(text, top) + dueLine + reflectPendingLine;
19080
19105
  const hash = createHash("sha256").update(`${parts.curated ?? ""}\n${textWithRationale}`).digest("hex");
19081
19106
  if (!compacted && hash === sessionState.lastProfileHash) return decision;
19082
19107
  sessionState.lastProfileHash = hash;
@@ -19453,6 +19478,7 @@ async function apply(ctx, config = {}) {
19453
19478
  /** Ожидание базы под текущий язык: пересчитывается, а не берётся из сборки плагина. */
19454
19479
  const baseTargetNow = () => resolveBaseTarget(registry, basesLanguage, resolved.embedder);
19455
19480
  setExtraRedactWords(resolved.redactWords);
19481
+ if (resolved.ingest !== "off" && resolved.reflect === "off") console.warn(message("core.warnIngestWithoutReflect"));
19456
19482
  mkdirSync(resolved.dbDir, {
19457
19483
  recursive: true,
19458
19484
  mode: 448
@@ -20240,6 +20266,8 @@ async function apply(ctx, config = {}) {
20240
20266
  mirrorDir: `${resolved.dbDir}/palaces`,
20241
20267
  dbDir: resolved.dbDir,
20242
20268
  dshHome: resolved.dshHome,
20269
+ ingest: resolved.ingest,
20270
+ reflect: resolved.reflect,
20243
20271
  pluginVersion: VERSION,
20244
20272
  language: resolved.language,
20245
20273
  panelAccess: resolved.panelAccess,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kenz1117/dsh-engram",
3
3
  "description": "Local-first cross-session long-term memory for DeepSeek Harness: dual-scope SQLite stores, hybrid FTS5 + local-vector retrieval with RRF, an evidence gate, provenance audit and SM-2 spaced repetition. 23 narrow tools, zero external services, zero API keys.",
4
- "version": "0.13.6",
4
+ "version": "0.13.8",
5
5
  "icon": "icon.svg",
6
6
  "logo": "icon-256.svg",
7
7
  "publishConfig": {
@@ -61,6 +61,7 @@
61
61
  "coverage": "vitest run --coverage",
62
62
  "check:hooks": "node scripts/check-hook-order.mjs",
63
63
  "check:css": "node scripts/check-css-classes.mjs",
64
+ "check:layout": "node scripts/verify-panel-layout.mjs",
64
65
  "typecheck": "tsc --noEmit",
65
66
  "backfill": "node scripts/backfill-embeddings.mjs"
66
67
  },
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Панельная вёрстка: проверки, которые не ловит ни один другой гейт.
4
+ *
5
+ * 0.13.x выпустил семь патчей подряд почти все по скриншотам пользователя:
6
+ * typecheck / lint / tests / словарь не проверяют рендеринг. Этот скрипт —
7
+ * недостающая ступень лестницы проверки: собирает настоящий CSS модулей
8
+ * + фикстурный DOM из той же разметки, гоняет через headless Chrome и
9
+ * меряет инварианты, нарушение которых уже один раз уехало в релиз.
10
+ *
11
+ * Инварианты (все они реально ломались в 0.13.0–0.13.5):
12
+ * 1. рабочая область панели прокручивается, страница хоста — нет;
13
+ * 2. пункты левого рельса — одна строка текста, рельс не сжимает заголовки в столбик;
14
+ * 3. заголовок рабочей области на странице один, порядок «заголовок → подзаголовок → табы»;
15
+ * 4. длинная подпись кнопки подтверждения не съедает строку (flex:none + max-width);
16
+ * 5. тело ящика на всю ширину, чипы id в одну строку;
17
+ * 6. строки runtime-списка: имя не наезжает на следующие колонки;
18
+ * 7. панель массовых операций: счётчик слева, кнопки нормальной высоты.
19
+ *
20
+ * Ограничение честности: фикстурный DOM повторяет разметку руками и может
21
+ * устареть. Инварианты намеренно грубые (порядок, единственность, «в одну
22
+ * строку», «не наезжает») — они ломаются только вместе с настоящей вёрсткой.
23
+ *
24
+ * Запуск: pnpm check:layout (нужен headless Chrome/Chromium)
25
+ */
26
+
27
+ import { readFileSync } from 'node:fs'
28
+ import { execFileSync } from 'node:child_process'
29
+ import { join, resolve, dirname } from 'node:path'
30
+ import { fileURLToPath } from 'node:url'
31
+ import { existsSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'
32
+ import { tmpdir } from 'node:os'
33
+
34
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
35
+ const css = name => readFileSync(join(ROOT, 'src/client', name), 'utf8')
36
+
37
+ const panel = css('panel.module.css')
38
+ const shell = css('shell/shell.module.css')
39
+ const ui = css('ui/ui.module.css')
40
+
41
+ // Host-переменные, которых в тестовой среде нет: панель читает их из темы DSH.
42
+ const STUB = `
43
+ :root {
44
+ --space-1: 4px; --space-2: 8px; --space-3: 12px; --space-4: 16px; --space-5: 20px; --space-6: 24px; --space-7: 32px;
45
+ --fs-micro: 11px; --fs-body: 13px; --fs-ctrl: 12px; --fs-display: 18px;
46
+ --radius-card: 12px; --radius-control: 8px;
47
+ --dur-fast: 120ms; --dur-base: 200ms; --dur-slow: 320ms;
48
+ --ease-spring: cubic-bezier(.2,.8,.2,1); --ease-out: cubic-bezier(0,0,.2,1);
49
+ --brand-1: #f0a44a; --brand-2: #e05a7a; --brand-grad: linear-gradient(90deg,#f0a44a,#e05a7a); --brand-grad-line: #e05a7a;
50
+ --dsw-alias-bg-base: #fff; --dsw-alias-bg-layer-1: #f7f8fa;
51
+ --dsw-alias-border-l1: #eef0f3; --dsw-alias-border-l2: #dfe3e8;
52
+ --dsw-alias-label-primary: #1d2129; --dsw-alias-label-secondary: #4e5969; --dsw-alias-label-tertiary: #86909c;
53
+ --dsw-alias-state-success-primary: #16a394; --dsw-alias-state-warn-primary: #e08a2e; --dsw-alias-state-danger-primary: #d54941;
54
+ --dsw-alias-brand-primary: #f0a44a; --dsw-alias-fill-tsp-secondary: #f2f3f5;
55
+ --room-fact:#3b6ef5; --room-preference:#a45cf0; --room-decision:#16a394; --room-episode:#e08a2e; --room-skill:#d94f8a;
56
+ --entity-person:#5b8def; --entity-project:#e08a2e; --entity-tool:#3cb489; --entity-concept:#9b6bd9; --entity-other:#7d8590;
57
+ }
58
+ html, body { margin: 0; height: 100%; background: #fff; }
59
+ `
60
+
61
+ const RAIL = ['总览', '召回', '记忆', '治理', '回放', '系统'].map((label, i) =>
62
+ `<button class="railItem" aria-current="${i === 2 ? 'true' : 'false'}">` +
63
+ '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.75"><circle cx="12" cy="12" r="3"/></svg>' +
64
+ `<span>${label}</span></button>`).join('')
65
+
66
+ const TABS = ['记录', '时间线', '实体', '图谱'].map((label, i) =>
67
+ `<button class="contextItem" aria-pressed="${i === 0 ? 'true' : 'false'}">${label}</button>`).join('')
68
+
69
+ const CONTENT = Array.from({ length: 14 }, (_, i) =>
70
+ `<div style="height:180px;border-bottom:1px solid #eee">内容块 ${i + 1}</div>`).join('')
71
+
72
+ const ITEM = (selected) => `
73
+ <div class="item${selected ? ' selected' : ''}"><input class="itemCheck" type="checkbox"${selected ? ' checked' : ''}>
74
+ <div class="itemBody"><div class="itemTags"><span class="pill">对外开放</span><span class="itemStamp">私人 · 6 天前</span></div>
75
+ <div class="content">用户的 macOS 用户名/家目录为 ken (/Users/ken)</div>
76
+ <div class="itemMeta"><span><b>地标亮度</b> 0.40</span><span><b>考据可靠度</b> 0.30</span></div></div>
77
+ <div class="itemOps"><button class="button">参观</button><button class="button">修缮</button><button class="button">封门</button></div></div>`
78
+
79
+ const REFURB_ARMED = `
80
+ <div class="refurbItem"><div class="refurbRow"><button class="refurbBadge">合并</button>
81
+ <div class="refurbReason">与 1 条记忆内容前 20 字重复,建议蒸馏合并。</div>
82
+ <span class="refurbConfidence">60%</span>
83
+ <button class="refurbExec button confirmArmed">确认合并 2 条相似记忆?将触发 engram_distill 把它们归纳为 1 条高层规律。</button></div></div>`
84
+
85
+ const DRAWER = `
86
+ <div class="drawerLayer"><div class="drawer" style="position:relative">
87
+ <header class="drawerHead"><div class="drawerTitle"><h3>记忆铭牌</h3></div><button class="drawerClose">×</button></header>
88
+ <div class="drawerBody"><div class="reviewGrid"><div>
89
+ <div class="identityStrip">
90
+ <span class="identityItem"><span class="identityLabel">稳定身份</span><code class="identityCode">8303a8ec-dbb3-482c-a7d3-d400abae6d23</code></span>
91
+ <span class="identityItem"><span class="identityLabel">当前修订</span><code class="identityCode">8303a8ec-dbb3-482c-a7d3-d400abae6d23</code></span>
92
+ </div>
93
+ <p class="reviewContent">给 DSH desktop profile 装/升级第三方 host+client 插件时:用应用自带 pnpm 直接操作,目录 ~/.dsh/profiles/desktop。要点:① pnpm 11 有 24 小时新包政策;② 每次操作前备份 package.json;③ 应用重启时会 reconcile profile。</p>
94
+ <dl class="attrGrid"><dt>种类</dt><dd>技法坊</dd></dl>
95
+ </div></div></div></div></div>`
96
+
97
+ const SYSROW = `
98
+ <div class="panelCard"><h3 class="cardTitle">嵌入模型</h3><div class="sysList">
99
+ <div class="sysRow"><span class="sysName">bge-small-zh-v1.5-quantized-onnx</span><span class="sysTag">Q8</span><span class="sysNum">512</span></div>
100
+ <div class="sysRow"><span class="sysName">paraphrase-multilingual-MiniLM-L12-v2</span><span class="sysTag">F32</span><span class="sysNum">384</span></div>
101
+ </div></div>`
102
+
103
+ const html = `<!doctype html><html lang="zh"><head><meta charset="utf-8"><title>panel-layout-verify</title>
104
+ <style>${STUB}${panel}${shell}${ui}</style></head><body>
105
+ <div class="panelRoot" style="height:100vh"><div class="panel">
106
+ <div class="panelSticky"><div style="height:64px">HEADER</div></div>
107
+ <div class="console">
108
+ <nav class="rail"><p class="railLabel">工作面</p>${RAIL}</nav>
109
+ <div class="consoleBody">
110
+ <header class="pageHeader"><div class="pageHeaderMain"><h2 class="pageTitle">记忆</h2><p class="pageSubtitle">全量记忆库</p></div></header>
111
+ <nav class="contextNav" aria-label="记忆">${TABS}</nav>
112
+ <div class="panelBody">
113
+ <div class="batchBar"><span>已选 1 条</span><button class="button">本页全选</button><button class="button">批量封门(1)</button></div>
114
+ <div class="itemList">${ITEM(true)}${ITEM(false)}</div>
115
+ <section class="panelCard"><div class="refurb">${REFURB_ARMED}</div></section>
116
+ ${SYSROW}
117
+ ${CONTENT}
118
+ </div>
119
+ </div>
120
+ </div>
121
+ ${DRAWER}
122
+ </div></div>
123
+ <pre id="report"></pre>
124
+ <script>
125
+ const r = {};
126
+ const box = (el) => el.getBoundingClientRect();
127
+ // 1. 滚动收容在工作面内容区
128
+ const body = document.querySelector('.panelBody');
129
+ r.bodyScrollable = body.scrollHeight > body.clientHeight;
130
+ r.documentScrollable = document.documentElement.scrollHeight > document.documentElement.clientHeight;
131
+ // 2. rail:单行文字 + 列宽固定
132
+ const railLabel = document.querySelector('.railItem span');
133
+ r.railTextH = box(railLabel).height;
134
+ r.railW = box(document.querySelector('.rail')).width;
135
+ // 3. 页面标题唯一 + 顺序
136
+ r.titleCount = document.querySelectorAll('.pageTitle').length;
137
+ const title = box(document.querySelector('.pageTitle'));
138
+ const subtitle = box(document.querySelector('.pageSubtitle'));
139
+ const tabs = box(document.querySelector('.contextNav'));
140
+ r.headerOrder = title.top < subtitle.top && subtitle.top < tabs.top;
141
+ // 4. 确认按钮长标签不撑爆行
142
+ const armed = document.querySelector('.confirmArmed');
143
+ r.armedOverflow = box(armed).right > box(armed.closest('.refurbItem')).right;
144
+ r.armedW = box(armed).width;
145
+ // 5. 抽屉正文占满 + id 芯片单行
146
+ const drawerBody = box(document.querySelector('.drawerBody'));
147
+ const reviewContent = box(document.querySelector('.reviewContent'));
148
+ r.drawerContentW = reviewContent.width;
149
+ r.drawerBodyW = drawerBody.width;
150
+ const code = box(document.querySelector('.identityCode'));
151
+ r.identityCodeH = code.height;
152
+ // 6. sysRow 名称列不与后续列重叠
153
+ const row = document.querySelector('.sysRow');
154
+ const name = box(row.querySelector('.sysName'));
155
+ const tag = box(row.querySelector('.sysTag'));
156
+ r.sysNameH = name.height;
157
+ r.sysOverlap = name.right > tag.left;
158
+ // 7. 批量条
159
+ const bar = document.querySelector('.batchBar');
160
+ r.batchBtnH = box(bar.querySelector('.button')).height;
161
+ r.batchCountFont = getComputedStyle(bar.querySelector('span')).fontSize;
162
+ document.getElementById('report').textContent = JSON.stringify(r);
163
+ </script></body></html>`
164
+
165
+ const dir = mkdtempSync(join(tmpdir(), 'engram-layout-'))
166
+ const file = join(dir, 'panel.html')
167
+ writeFileSync(file, html)
168
+
169
+ function findChrome() {
170
+ const candidates = process.platform === 'darwin'
171
+ ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium']
172
+ : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium']
173
+ for (const candidate of candidates) {
174
+ if (existsSync(candidate)) return candidate
175
+ }
176
+ console.error('未找到 headless Chrome/Chromium:本脚本用它做渲染量测(这是 typecheck/tests 拦不住的那层)。')
177
+ process.exit(2)
178
+ }
179
+
180
+ let dom
181
+ try {
182
+ dom = execFileSync(findChrome(), [
183
+ '--headless=new', '--disable-gpu', '--no-sandbox', '--mute-audio',
184
+ '--window-size=1400,900', '--virtual-time-budget=3000', '--dump-dom', file,
185
+ ], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
186
+ } finally {
187
+ rmSync(dir, { recursive: true, force: true })
188
+ }
189
+
190
+ const match = /<pre id="report">([^<]*)<\/pre>/.exec(dom)
191
+ if (match === null) {
192
+ console.error('Chrome 未输出量测结果(页面加载失败?)')
193
+ process.exit(1)
194
+ }
195
+ const r = JSON.parse(match[1])
196
+
197
+ const failures = []
198
+ const check = (ok, label, detail) => {
199
+ if (ok) console.log(` ок ${label}`)
200
+ else failures.push(`${label} — ${detail}`)
201
+ }
202
+
203
+ check(r.bodyScrollable === true, '工作面内容区自滚(内容溢出时出现滚动)', `scrollHeight=${r.bodyScrollable}`)
204
+ check(r.documentScrollable === false, '宿主页面不出现第二条滚动条', `document scrollable=${r.documentScrollable}`)
205
+ check(r.railTextH < 20, 'rail 标题单行(不吃进 18px 图标列变竖排)', `text height=${r.railTextH}`)
206
+ check(r.railW >= 120 && r.railW <= 150, 'rail 列宽固定不塌', `width=${r.railW}`)
207
+ check(r.titleCount === 1, '页面标题唯一(legend 泄漏会变成两个)', `count=${r.titleCount}`)
208
+ check(r.headerOrder === true, '顺序:标题 → 副标题 → 二级导航', `order=${r.headerOrder}`)
209
+ check(r.armedOverflow === false, '确认按钮长标签不撑出所在行', `overflow=${r.armedOverflow}`)
210
+ check(r.armedW <= 280, '确认态按钮宽度有绝对上限(24em 截断,不随标签长度增长)', `width=${r.armedW}`)
211
+ check(r.drawerContentW >= r.drawerBodyW - 40, '抽屉正文占满宽度(容差=两侧 padding)', `content=${r.drawerContentW} body=${r.drawerBodyW}`)
212
+ check(r.identityCodeH < 20, '身份芯片单行(uuid 不拆两行)', `height=${r.identityCodeH}`)
213
+ check(r.sysNameH < 20, 'runtime 列表名称单行(模型名不压成竖排)', `height=${r.sysNameH}`)
214
+ check(r.sysOverlap === false, 'runtime 列表名称不与类型列叠字', `overlap=${r.sysOverlap}`)
215
+ check(r.batchBtnH > 20 && r.batchBtnH < 32, '批量条按钮保持紧凑高度', `height=${r.batchBtnH}`)
216
+ check(r.batchCountFont === '12px', '批量条计数用正文字号', `font=${r.batchCountFont}`)
217
+
218
+ if (failures.length > 0) {
219
+ console.error(`\n布局门禁未过(${failures.length} 项):`)
220
+ for (const failure of failures) console.error(` ✗ ${failure}`)
221
+ process.exit(1)
222
+ }
223
+ console.log('\n布局门禁全绿(headless Chrome 实测)。')