prompt-optimizer-magpie 0.2.4 → 0.2.5

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/README.md CHANGED
@@ -83,6 +83,7 @@ magpie plugin options prompt-optimizer-magpie '{
83
83
  | `deciderGroup` | `group/route-decider` | 决策模型组;留空 `""` = 纯规则模式(长线程全放行,只优化首轮) |
84
84
  | `optimizeGroup` | `group/prompt-optimize` | 优化调用的模型组 |
85
85
  | `minChars` / `maxChars` | `6` / `12000` | 用户原文长度窗口。`<minChars` 同步硬放行;`maxChars` 是防整本书粘贴的绝对上限,正常范围内的长文本交决策模型判断 |
86
+ | `guardRatioLimit` | `10` | 输出护栏上限倍率:改写词元数上限 `clamp(原文词元 × N, 60, 2000)`。默认 ×10(生产实测:52 词元原文的结构化改写 430 词元曾被 ×5 误杀);配置页可改 |
86
87
  | `bypassPrefix` | `["!!", "##"]` | 用户原文以任一前缀开头则原样发送。**推荐用 `##`**:omp/pi 等 TUI 会把 `!!` 当 shell 转义吃掉,根本到不了网关;claude 类 TUI 也把 `!!` 当 bash 输入。`##` 在所有实测 agent 上都能原样到达(claude/grok 已验证 bypass-prefix) |
87
88
  | `bypassModels` | `[]` | 命中这些 `body.model` 直接放行(排除机器任务模型,如 `group/bili-summary`) |
88
89
  | `bypassAgents` | `[]` | 命中这些 `ctx.agent` 直接放行(不想被优化的 agent 白名单,任何网关调用前拦截) |
@@ -105,7 +106,7 @@ magpie plugin options prompt-optimizer-magpie '{
105
106
 
106
107
  ## 日志布局与保留(按天分文件,7 天清理)
107
108
 
108
- 事件写在插件目录 `stats/` 下,**每天一个文件**(`stats/YYYY-MM-DD.ndjson`,UTC)。为什么不是单文件:`record()` 在 magpie plugin-host 进程里 append,而 `prune()` 在服务进程里执行——两个进程对同一个文件做「重写+rename」和「append」存在竞态(rename 瞬间落地的 append 会写进旧 inode 丢一条)。按天分文件后,保留策略变成 **unlink 整个过期日文件**,写者永远只 append 今天的文件,两边操作的 inode 不相交,竞态从结构上消除;单文件也不再无限增长,prune 从全量重写降为删文件。
109
+ 事件写在**包外用户配置区** `~/.config/magpie/prompt-optimizer-magpie/stats/`(`homedir()` 解析;Windows 同样落到 `~/.config/...`),**每天一个文件**(`YYYY-MM-DD.ndjson`,**本地时区**日界;页面时间戳同按本地时区渲染)。数据目录在包外,`magpie plugin update` 重装包目录不再丢数据;环境变量 `POM_STATS_DIR` 可显式覆盖。首次启动时若检测到包内旧 `stats/` 目录,会自动**复制**到新目录(同名文件跳过、不覆盖)并写入 `MIGRATED.txt` 标记,只迁一次。历史存量文件为 UTC 日命名,不重命名不合并——升级当天本地日与 UTC 日可能各有一个文件,属一次性过渡,读端按文件名分组不受影响。为什么不是单文件:`record()` 在 magpie plugin-host 进程里 append,而 `prune()` 在服务进程里执行——两个进程对同一个文件做「重写+rename」和「append」存在竞态(rename 瞬间落地的 append 会写进旧 inode 丢一条)。按天分文件后,保留策略变成 **unlink 整个过期日文件**,写者永远只 append 今天的文件,两边操作的 inode 不相交,竞态从结构上消除;单文件也不再无限增长,prune 从全量重写降为删文件。
109
110
 
110
111
  - `prune` 由共享的 `startStatsService` 在**两个入口**(index.mjs 宿主内服务 + serve.mjs daemon)启动时和每 24 小时执行:删除文件名日期早于 `POM_RETAIN_DAYS`(默认 `7`)的日文件;`0` 或负数 = 永久保留。只跑 in-app 页面、不部署 serve.mjs 的安装也会自动清理。
111
112
  - systemd 部署示例:`Environment=POM_RETAIN_DAYS=7`。
@@ -115,7 +116,7 @@ magpie plugin options prompt-optimizer-magpie '{
115
116
 
116
117
  - 剥离外围代码围栏;新结果和缓存命中都比对 `[REDACTED]`、双花括号占位符和反引号标识符的**数量**;字面比对容错等价写法(`{{ name }}` ≡ `{{name}}`,反引号 token 比内容),数量增减仍拦截;
117
118
  - 长度上下限按**词元数**而非字符数(中文 1 字 = 1 词元,连续英文单词/数字/标识符 = 1 词元,标点空白不计):JS `.length` 按 UTF-16 code unit 计数,天然低估中文、高估英文,同一护栏对两种语言宽严不一;
118
- - 下限 `0.4×` 原文词元(防止越改越短);上限 `clamp(5× 原文词元, 60, 2000)`——短需求给足结构化扩写空间(60 词元保底,实测 17 字需求 → 552 字提示词是期望效果),长输入最多扩 5 倍且封顶 2000 词元。生产事故驱动:182 字中文原文 → 612 字优质改写曾被字符级 ×3 上限误杀;
119
+ - 下限 `0.4×` 原文词元(防止越改越短);上限 `clamp(guardRatioLimit × 原文词元, 60, 2000)`,倍率默认 `10` 可配(配置页 `guardRatioLimit`)——短需求给足结构化扩写空间(60 词元保底,实测 17 字需求 → 552 字提示词是期望效果),长输入最多扩 N 倍且封顶 2000 词元。生产事故驱动:182 字中文原文 → 612 字优质改写曾被字符级 ×3 上限误杀;
119
120
  - 护栏触发细分为三个 reason,统计页红色分组可观测:`output-guard-short`(低于下限)/ `output-guard-long`(超上限)/ `output-guard-tokens`(token 校验失败)。
120
121
 
121
122
  替换只动最后一条 user 消息中**唯一匹配**的用户原文 span:先逐字匹配,失败后空白规范化匹配;零命中或多重命中一律放行,绝不用 `ctx.query` 整段覆盖。
@@ -128,7 +129,7 @@ magpie plugin options prompt-optimizer-magpie '{
128
129
 
129
130
  例如 `"overrides":[{"agent":"cli","model":"group/interactive","budgetMs":350},{"agent":"batch","optimizerMode":"merged"}]`。350 毫秒从进入 hook 起算,判定和改写共用;耗尽时放行原文并记录 `budget-exhausted`,0 表示直接放行。目标模型匹配的是入站 `body.model`。实验组优先选择模式,预算仍生效;线程保留原有门禁。没有匹配项使用全局配置。
130
131
 
131
- 钩子将审计事件写入插件目录 `stats/YYYY-MM-DD.ndjson`(UTC 日文件,按事件追加,写失败静默)。默认在 `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` 事件上附带先脱敏、再截断的文本(`orig`/`rewritten`,默认 600 字),插件层可直接审计每次改写质量;`logRewrites: false` 可关闭。`action`/`reason` 覆盖:`pass`(disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error)、`decide`(decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence)、`optimize`(dry-run / optimized / merged-optimized / cache-hit / no-span)。
132
+ 钩子将审计事件写入 `~/.config/magpie/prompt-optimizer-magpie/stats/YYYY-MM-DD.ndjson`(本地时区日文件,按事件追加,写失败静默;数据目录在包外,update 不丢)。默认在 `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` 事件上附带先脱敏、再截断的文本(`orig`/`rewritten`,默认 600 字),插件层可直接审计每次改写质量;`logRewrites: false` 可关闭。`action`/`reason` 覆盖:`pass`(disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error)、`decide`(decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence)、`optimize`(dry-run / optimized / merged-optimized / cache-hit / no-span)。
132
133
 
133
134
  决策失败后,已有助手回复的线程直接放行;首轮按实际降级路径记录 `decider-fail-rule` 或 `decider-fail-merged`。Responses 携带 `previous_response_id` 时直接放行。每个请求只上报一次终态;实际回写报 `ready` 并附返回请求体的 UTF-8 字节数,干跑或普通放行报 `skipped, 0`,最终模型调用失败报 `unavailable, 0`。
134
135
 
package/README_EN.md CHANGED
@@ -83,6 +83,7 @@ magpie plugin options prompt-optimizer-magpie '{
83
83
  | `cacheTtlMs` | `60000` | Atomically published rewrites in `.cache.json.d/` are keyed by agent, original text, gateway, optimize group, configured and effective modes, tier and dry-run state. A value ≤0 disables cache I/O. The old `.cache.json` stays on disk and is ignored. |
84
84
  | `debugDump` | off | Append a redacted copy of candidate requests to a file. Set a path or use `true` for `debug-dump.log` beside the hook. Sensitive fields become `[REDACTED]` before clipping. |
85
85
  | `minChars` / `maxChars` | `6` / `12000` | user-text length window. `<minChars` is a sync hard pass; `maxChars` is an absolute ceiling against book-length pastes — in-range long text is left to the decider |
86
+ | `guardRatioLimit` | `10` | output-guard ceiling ratio: rewrite unit ceiling is `clamp(orig units × N, 60, 2000)`. Default ×10 (in production a 430-unit structured rewrite of a 52-unit prompt was killed by ×5); editable on the config page |
86
87
  | `bypassPrefix` | `["!!", "##"]` | user text starting with either prefix is sent verbatim |
87
88
  | `bypassModels` | `[]` | requests whose `body.model` matches pass through (machine-task models, e.g. `group/bili-summary`) |
88
89
  | `allowedOrigins` | `[]` | when non-empty, only these `ctx.origin` values pass; a missing origin is fail-open (not blocked) |
@@ -103,7 +104,7 @@ An optimized result is only substituted after passing the guardrails, otherwise
103
104
 
104
105
  - strip surrounding code fences and verify **counts** of `[REDACTED]`, double-brace placeholders and backticked identifiers, including on cache hits; literal comparison tolerates equivalent spelling (`{{ name }}` ≡ `{{name}}`, backtick tokens compare their content), while any count change still trips the guard;
105
106
  - length bounds use **token units**, not chars (each CJK ideograph = 1 unit, each contiguous word/number/identifier run = 1, punctuation/whitespace = 0): JS `.length` counts UTF-16 code units, under-measuring CJK and over-measuring English, so one char-based rule was strict for Chinese and loose for English;
106
- - lower bound `0.4×` original units (prevents over-shrinking); upper bound `clamp(5× original units, 60, 2000)` — short prompts get room for structured expansion (60-unit floor; measured: a 17-char request → a 552-char prompt is the desired outcome), long inputs may expand at most 5× capped at 2000 units. Production-incident driven: a 182-char Chinese orig → 612-char good rewrite was killed by the char-based ×3 ceiling;
107
+ - lower bound `0.4×` original units (prevents over-shrinking); upper bound `clamp(guardRatioLimit × original units, 60, 2000)` — ratio defaults to `10` and is configurable (config page `guardRatioLimit`). Short prompts get room for structured expansion (60-unit floor; measured: a 17-char request → a 552-char prompt is the desired outcome); long inputs may expand at most N× capped at 2000 units. Production-incident driven: a 182-char Chinese orig → 612-char good rewrite was killed by the char-based ×3 ceiling;
107
108
  - guard trips split into three red-group reasons on the stats page: `output-guard-short` (below floor) / `output-guard-long` (above ceiling) / `output-guard-tokens` (token check failed).
108
109
 
109
110
  Substitution touches only the **uniquely matched** user-text span in the last user message: verbatim match first, then whitespace-normalized; zero or multiple hits → pass through. `ctx.query` is never used to overwrite the whole message.
@@ -116,7 +117,7 @@ Enable `rollout` only for agents whose `ctx.session` is stable across retries. E
116
117
 
117
118
  Example: `"overrides":[{"agent":"cli","model":"group/interactive","budgetMs":350},{"agent":"batch","optimizerMode":"merged"}]`. The 350 ms budget starts at hook entry and is shared by decision and rewrite calls. Exhaustion passes the original with reason `budget-exhausted`; zero passes immediately. Model selectors match inbound `body.model`. Rollout arms take precedence over the first-turn mode override, while the budget still applies. Threads keep their existing gates; unmatched requests use global settings.
118
119
 
119
- The hook appends audit events to the daily file `stats/YYYY-MM-DD.ndjson` in the plugin directory (UTC, append-only, write failures are silent). By default `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` events carry redacted, clipped prompt text (`orig`/`rewritten`, 600 chars by default) so every rewrite can be audited at the plugin layer; set `logRewrites: false` to log lengths only. `action`/`reason` cover: `pass` (disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error), `decide` (decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence), `optimize` (dry-run / optimized / merged-optimized / cache-hit / no-span).
120
+ The hook appends audit events to the daily file `YYYY-MM-DD.ndjson` under `~/.config/magpie/prompt-optimizer-magpie/stats/` (resolved from `homedir()`; Windows uses `~/.config/...` too — local-timezone day boundaries, append-only, write failures are silent; page timestamps render in local time). The data dir lives **outside the package**, so `magpie plugin update` reinstalls no longer wipe it; set `POM_STATS_DIR` to override. On first start, a legacy package-internal `stats/` dir is **copied** to the new location (same-name files skipped, never overwritten; a `MIGRATED.txt` marker makes it one-shot). Existing files are UTC-day named and are neither renamed nor merged — on upgrade day a local-day and a UTC-day file may coexist; a one-off transition, harmless to the filename-grouped reader. By default `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` events carry redacted, clipped prompt text (`orig`/`rewritten`, 600 chars by default) so every rewrite can be audited at the plugin layer; set `logRewrites: false` to log lengths only. `action`/`reason` cover: `pass` (disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error), `decide` (decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence), `optimize` (dry-run / optimized / merged-optimized / cache-hit / no-span).
120
121
 
121
122
  Retention: the active listener (embedded service or standalone daemon) prunes day files older than `POM_RETAIN_DAYS` (default `7`) at startup and every 24h; `0`/negative keeps everything. Installs that only use the in-app page never grow `stats/` unbounded either. The legacy single-file `stats.ndjson` is no longer read — archive it yourself if you want the history.
122
123
 
package/hooks.mjs CHANGED
@@ -26,6 +26,9 @@ const DEFAULTS = {
26
26
  skipToolless: true,
27
27
  cacheTtlMs: 60000,
28
28
  deciderTimeoutMs: 1500,
29
+ // 输出护栏上限倍率:clamp(origUnits * guardRatioLimit, 60, 2000)。生产
30
+ // 案例 2026-11-22:52 词元原文 ×5 上限 260 误杀 430 词元改写 → 默认 ×10。
31
+ guardRatioLimit: 10,
29
32
  optimizeTimeoutMs: 15000,
30
33
  // merged 模式:单次 optimize 调用同时完成模板选择 + 改写(首行标记协议)。
31
34
  // optimizerMode: "auto"(默认,现行为)| "merged"(跳过 decider,首轮直接 merged)。
@@ -74,6 +77,8 @@ export async function onRequest(body, ctx) {
74
77
  durationMs: Date.now() - t0,
75
78
  inputChars: x.in || 0,
76
79
  outputChars: x.out || 0,
80
+ ...(x.inUnits !== undefined && { inputUnits: x.inUnits }),
81
+ ...(x.outUnits !== undefined && { outputUnits: x.outUnits }),
77
82
  dryRun: !!o.dryRun,
78
83
  ...(x.decideMs !== undefined && { decideMs: x.decideMs }),
79
84
  ...(x.optimizeMs !== undefined && { optimizeMs: x.optimizeMs }),
@@ -124,10 +129,10 @@ export async function onRequest(body, ctx) {
124
129
  } catch {}
125
130
  }
126
131
  if (prefixes.some((p) => orig.startsWith(p))) return pass("bypass-prefix");
127
- if (orig.length < o.minChars) return pass("short-text", { in: orig.length });
128
- if (orig.length > o.maxChars) return pass("too-long", { in: orig.length });
132
+ if (orig.length < o.minChars) return pass("short-text", { in: orig.length, inUnits: countUnits(orig) });
133
+ if (orig.length > o.maxChars) return pass("too-long", { in: orig.length, inUnits: countUnits(orig) });
129
134
 
130
- const size = { in: orig.length };
135
+ const size = { in: orig.length, inUnits: countUnits(orig) };
131
136
  const input = { ...size, origText: orig };
132
137
  if (protocol === "responses" && body.previous_response_id) return pass("no-decider-followup", size);
133
138
  const thread = hasAssistantReply(body, protocol);
@@ -233,9 +238,9 @@ export async function onRequest(body, ctx) {
233
238
  }
234
239
  }
235
240
 
236
- const audit = { ...input, out: out.length, newText: out, markCache: fromCache };
237
241
  const origUnits = countUnits(orig), outUnits = countUnits(out);
238
- const maxUnits = Math.min(Math.max(origUnits * 5, 60), 2000);
242
+ const audit = { ...input, out: out.length, outUnits, newText: out, markCache: fromCache };
243
+ const maxUnits = Math.min(Math.max(origUnits * (o.guardRatioLimit || 10), 60), 2000);
239
244
  if (outUnits < origUnits * 0.4) return pass("output-guard-short", audit);
240
245
  if (outUnits > maxUnits) return pass("output-guard-long", audit);
241
246
  if (!preservesTokens(orig, out)) return pass("output-guard-tokens", audit);
package/index.mjs CHANGED
@@ -10,6 +10,7 @@ import { writeFileSync } from "node:fs";
10
10
  import { join, dirname } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { startStatsService } from "./lib/stats-service.mjs";
13
+ import { resolveStatsDir, migrateLegacyStats } from "./lib/stats.mjs";
13
14
 
14
15
  const PAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), "page");
15
16
 
@@ -19,7 +20,10 @@ export default {
19
20
  id: "prompt-optimizer-magpie",
20
21
  server: async (_input, options) => {
21
22
  if (!started) {
23
+ // One-shot: bring package-internal legacy stats/ over (survives updates).
24
+ if (migrateLegacyStats()) console.log("pom: migrated legacy stats/ to " + resolveStatsDir());
22
25
  started = startStatsService({
26
+ statsDir: resolveStatsDir(),
23
27
  // options.port: magpie.page.service.option "port" in package.json;
24
28
  // 0 = ephemeral — `|| 3497` would silently swallow it.
25
29
  port: Number.isFinite(Number(options?.port)) ? Number(options.port) : 3497,
@@ -47,6 +47,7 @@ export const CONFIG_FIELDS = [
47
47
  { key: "optimizerMode", type: "enum", def: "auto", choices: ["auto", "merged"] },
48
48
  { key: "minChars", type: "int", def: 6, min: 1, max: 200 },
49
49
  { key: "maxChars", type: "int", def: 12000, min: 1000, max: 100000 },
50
+ { key: "guardRatioLimit", type: "int", def: 10, min: 1, max: 100 },
50
51
  { key: "logSkips", type: "bool", def: true },
51
52
  { key: "logOptimizes", type: "bool", def: true },
52
53
  { key: "deciderGroup", type: "string", def: "group/route-decider", maxLen: 200 },
@@ -47,7 +47,7 @@ export const T = {
47
47
  colAction: ["动作", "action"],
48
48
  colReason: ["reason", "reason"],
49
49
  skippedAsIs: ["原样跳过", "skipped as-is"],
50
- colInOut: ["输入/输出字符", "in/out"],
50
+ colInOut: ["输入/输出词元", "in/out units"],
51
51
  colView: ["详情", "view"],
52
52
  prev: ["上一页", "prev"],
53
53
  next: ["下一页", "next"],
@@ -90,6 +90,7 @@ export const T = {
90
90
  cfgOptimizerMode: ["优化模式", "optimizer mode"],
91
91
  cfgMinChars: ["最小字符数", "min chars"],
92
92
  cfgMaxChars: ["最大字符数", "max chars"],
93
+ cfgGuardRatioLimit: ["护栏上限倍率", "guard ratio limit"],
93
94
  cfgLogSkips: ["记录跳过事件", "log skipped events"],
94
95
  cfgLogOptimizes: ["记录改写事件", "log optimize events"],
95
96
  cfgDeciderGroup: ["判定模型组", "decider model group"],
@@ -102,6 +103,7 @@ export const T = {
102
103
  hintOptimizerMode: ["auto = 判定+改写按各自模型组两段式;merged = 单次合并调用(决策组可空)", "auto = decide+rewrite as two calls per their groups; merged = single combined call (decider group may be empty)"],
103
104
  hintMinChars: ["短于该字符数的提示词不优化(默认 6)", "prompts shorter than this are skipped (default 6)"],
104
105
  hintMaxChars: ["超过该字符数的提示词不优化(默认 12000)", "prompts longer than this are skipped (default 12000)"],
106
+ hintGuardRatioLimit: ["改写词元数的上限倍率 clamp(原文词元 × N, 60, 2000)(默认 10)", "ceiling for rewrite units: clamp(orig units × N, 60, 2000) (default 10)"],
105
107
  hintLogSkips: ["跳过事件是否记入统计文件", "whether skipped events are written to stats"],
106
108
  hintLogOptimizes: ["改写事件是否记入统计文件", "whether optimize events are written to stats"],
107
109
  hintDeciderGroup: ["判定「新任务还是追问」所用模型组", "model group used to decide new-task vs follow-up"],
@@ -157,7 +159,16 @@ export const T = {
157
159
  "This path does not record prompt text: pass / decide paths log metadata only; the rewrite path records orig/rewritten (controlled by logRewrites). What is shown is the audit clip (first 600 chars).",
158
160
  ],
159
161
  all: ["全部", "all"],
162
+ tzNote: ["时间为本地时区({tz})", "times are in the local timezone ({tz})"],
160
163
  };
164
+
165
+ // Local-timezone `YYYY-MM-DD HH:mm:ss` — the page used to show UTC, 8h
166
+ // behind CST day boundaries. Day-file names went local in the same change.
167
+ export function localStamp(ts) {
168
+ const d = new Date(ts);
169
+ const p = (n) => String(n).padStart(2, "0");
170
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
171
+ }
161
172
  // 双语文案 helper:zh 恒为 [0],en 恒为 [1]。
162
173
  const zh = (k, ...a) => (typeof T[k] === "function" ? T[k](...a)[0] : T[k][0]);
163
174
  const en = (k, ...a) => (typeof T[k] === "function" ? T[k](...a)[1] : T[k][1]);
@@ -165,9 +176,21 @@ const en = (k, ...a) => (typeof T[k] === "function" ? T[k](...a)[1] : T[k][1]);
165
176
  const bi = (k, ...a) => `<span data-lang="zh">${esc(zh(k, ...a))}</span><span data-lang="en">${esc(en(k, ...a))}</span>`;
166
177
 
167
178
  const VARS = "bg,card,fg,fg-2,muted,faint,line,accent,accent-fg,green,red,amber".split(",");
168
- const css = () => `
179
+ export const css = () => `
169
180
  :root { color-scheme: light dark;
170
- --space-1: .25rem; --space-2: .5rem; --space-3: 1rem; --space-4: 1.5rem; }
181
+ --space-1: .25rem; --space-2: .5rem; --space-3: 1rem; --space-4: 1.5rem;
182
+ /* Semantic pairs: stats runs on its own port, host --magpie-* never
183
+ exists, and the old CanvasText fallback collapsed every tag to white
184
+ in dark theme. light-dark() adapts without JS; a host that injects
185
+ --magpie-* still wins. Dark side is the 300 ramp for ≥4.5:1 on #121212. */
186
+ --green-l: #15803d; --green-d: #4ade80;
187
+ --amber-l: #b45309; --amber-d: #fbbf24;
188
+ --red-l: #b91c1c; --red-d: #f87171;
189
+ --accent-l: #1d4ed8; --accent-d: #60a5fa;
190
+ --sem-green: var(--magpie-green, light-dark(var(--green-l), var(--green-d)));
191
+ --sem-amber: var(--magpie-amber, light-dark(var(--amber-l), var(--amber-d)));
192
+ --sem-red: var(--magpie-red, light-dark(var(--red-l), var(--red-d)));
193
+ --sem-accent: var(--magpie-accent, light-dark(var(--accent-l), var(--accent-d))); }
171
194
  html[data-lang="zh"] [data-lang="en"], html[data-lang="en"] [data-lang="zh"] { display: none; }
172
195
  body { font: 13px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; margin: 0;
173
196
  padding: var(--space-4) var(--space-3) 3rem; max-width: 64rem; margin-inline: auto;
@@ -179,8 +202,8 @@ const css = () => `
179
202
  border-radius: 8px; padding: var(--space-2) var(--space-3); min-width: 9rem; }
180
203
  .kpi b { font-size: 1.35rem; display: block; font-variant-numeric: tabular-nums; }
181
204
  /* KPI semantic colors on the value text only; cards stay neutral. */
182
- .kpi b.v-amber { color: var(--magpie-amber, var(--magpie-warn, #b45309)); }
183
- .kpi b.v-green { color: var(--magpie-green, var(--magpie-success, #15803d)); }
205
+ .kpi b.v-amber { color: var(--sem-amber); }
206
+ .kpi b.v-green { color: var(--sem-green); }
184
207
  .kpi b.v-muted { color: var(--magpie-muted, GrayText); }
185
208
  .kpi span { color: var(--magpie-muted, GrayText); font-size: 11px; }
186
209
  /* A. semantic nav, underline tabs via pseudo-element — no size change on state,
@@ -191,14 +214,14 @@ const css = () => `
191
214
  text-decoration: none; border-block-end: 2px solid transparent; }
192
215
  nav.tabs a:hover { color: var(--magpie-fg, CanvasText); }
193
216
  nav.tabs a[aria-current="page"] { color: var(--magpie-fg, CanvasText); font-weight: 600;
194
- border-block-end-color: var(--magpie-accent, AccentColor); }
217
+ border-block-end-color: var(--sem-accent); }
195
218
  /* percentile switcher: same underline-tab affordance as nav.tabs, compact */
196
219
  nav.pct-switch { display: flex; gap: var(--space-2); }
197
220
  nav.pct-switch a { padding: var(--space-1) var(--space-2); color: var(--magpie-fg-2, GrayText);
198
221
  text-decoration: none; border-block-end: 2px solid transparent; font-variant-numeric: tabular-nums; }
199
222
  nav.pct-switch a:hover { color: var(--magpie-fg, CanvasText); }
200
223
  nav.pct-switch a[aria-current="true"] { color: var(--magpie-fg, CanvasText); font-weight: 600;
201
- border-block-end-color: var(--magpie-accent, AccentColor); }
224
+ border-block-end-color: var(--sem-accent); }
202
225
  /* B. responsive tables: wrapper region + sticky head + stacked cards under 40em. */
203
226
  .table-wrapper { container-type: inline-size; overflow-x: auto; }
204
227
  table { border-collapse: separate; border-spacing: 0; width: 100%; font-size: 12px; margin-top: var(--space-1); font-variant-numeric: tabular-nums; }
@@ -222,22 +245,22 @@ const css = () => `
222
245
  border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 4px; padding: .25rem var(--space-2); }
223
246
  button { cursor: pointer; }
224
247
  .pager { display: flex; gap: var(--space-3); align-items: center; margin: var(--space-3) 0; font-size: 12px; }
225
- .pager a { color: var(--magpie-accent, LinkText); }
226
- td a { color: var(--magpie-accent, LinkText); }
248
+ .pager a { color: var(--sem-accent); }
249
+ td a { color: var(--sem-accent); }
227
250
  .detail-cols { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-3); margin-top: var(--space-2); }
228
251
  .detail-cols h3 { margin: 0 0 var(--space-1); font-size: .85rem; color: var(--magpie-fg-2, GrayText); }
229
252
  .detail-cols pre { margin: 0; padding: var(--space-2); overflow: auto; max-height: 24rem; white-space: pre-wrap;
230
253
  word-break: break-word; background: var(--magpie-card, Canvas); font-family: ui-monospace, monospace;
231
254
  border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 8px; font-size: 12px; }
232
255
  @media (max-width: 60rem) { .detail-cols { grid-template-columns: 1fr; } }
233
- .warn { color: var(--magpie-amber, CanvasText); }
256
+ .warn { color: var(--sem-amber); }
234
257
  .tag { display: inline-block; border-radius: 4px; padding: 0 .4rem; font-size: 11px;
235
258
  border: 1px solid var(--magpie-line, ButtonBorder); }
236
- .tag-green { color: var(--magpie-green, CanvasText); border-color: var(--magpie-green, CanvasText); }
237
- .tag-amber { color: var(--magpie-amber, CanvasText); border-color: var(--magpie-amber, CanvasText); }
238
- .tag-red { color: var(--magpie-red, CanvasText); border-color: var(--magpie-red, CanvasText); }
259
+ .tag-green { color: var(--sem-green); border-color: var(--sem-green); }
260
+ .tag-amber { color: var(--sem-amber); border-color: var(--sem-amber); }
261
+ .tag-red { color: var(--sem-red); border-color: var(--sem-red); }
239
262
  .tag-muted { color: var(--magpie-muted, GrayText); }
240
- .tag-accent { color: var(--magpie-accent, LinkText); border-color: var(--magpie-accent, LinkText); }
263
+ .tag-accent { color: var(--sem-accent); border-color: var(--sem-accent); }
241
264
  .legend { margin-top: var(--space-3); }
242
265
  .legend summary { cursor: pointer; color: var(--magpie-fg-2, GrayText); font-size: 12px; }
243
266
  .legend dl { display: grid; grid-template-columns: max-content 1fr; gap: var(--space-1) var(--space-3); margin: var(--space-2) 0 0; font-size: 12px; }
@@ -246,15 +269,15 @@ const css = () => `
246
269
  form[method="POST"] label { display: flex; gap: var(--space-2); align-items: center; margin: .35rem 0; }
247
270
  form[method="POST"] .k { min-width: 11rem; font-family: ui-monospace, monospace; font-size: 12px; }
248
271
  form[method="POST"] input[type="text"], form[method="POST"] select { background: var(--magpie-bg-2, Canvas); color: var(--magpie-fg, CanvasText); border: 1px solid var(--magpie-border, CanvasText); border-radius: 4px; padding: .2rem .4rem; }
249
- .cfg-saved { color: var(--magpie-success, var(--magpie-green, #16a34a)); border: 1px solid var(--magpie-success, var(--magpie-green, #16a34a)); border-radius: 4px; padding: var(--space-1) var(--space-2); max-width: 46rem; }
272
+ .cfg-saved { color: var(--sem-green); border: 1px solid var(--sem-green); border-radius: 4px; padding: var(--space-1) var(--space-2); max-width: 46rem; }
250
273
  .skipped { color: var(--magpie-muted, GrayText); }
251
- .cfg-err input[type="text"], .cfg-err select { border-color: var(--magpie-danger, var(--magpie-red, #dc2626)); }
252
- .cfg-errmsg { color: var(--magpie-danger, var(--magpie-red, #dc2626)); font-style: normal; font-size: 12px; }
274
+ .cfg-err input[type="text"], .cfg-err select { border-color: var(--sem-red); }
275
+ .cfg-errmsg { color: var(--sem-red); font-style: normal; font-size: 12px; }
253
276
  .field-hint { display: block; font-size: 12px; color: var(--magpie-fg-2, var(--magpie-muted, GrayText)); margin: var(--space-1) 0 0; }
254
277
  /* C. focus ring on every focusable element. */
255
278
  a:focus-visible, button:focus-visible, select:focus-visible, input:focus-visible,
256
279
  summary:focus-visible, [tabindex]:focus-visible {
257
- outline: 2px solid var(--magpie-accent, AccentColor); outline-offset: 2px; }
280
+ outline: 2px solid var(--sem-accent); outline-offset: 2px; }
258
281
  `;
259
282
 
260
283
  // ── day files & detail ids ─────────────────────────────────────────────────
@@ -409,7 +432,7 @@ function reasonLegend() {
409
432
  .map((k) => `<dt>${tag(k.slice(2), group)}</dt><dd>${bi(k)}</dd>`).join("");
410
433
  return `<details class="legend"><summary>${bi("legendTitle")}</summary>
411
434
  ${LEGEND_GROUPS.map(([titleKey, group]) => `<h3>${bi(titleKey)}</h3><dl>${section(group)}</dl>`).join("\n")}
412
- <p class="empty">${bi("legendNote")}</p></details>`;
435
+ <p class="empty">${bi("legendNote")}</p><p class="empty">${bi("tzNote").replaceAll("{tz}", Intl.DateTimeFormat().resolvedOptions().timeZone || "local")}</p></details>`;
413
436
  }
414
437
 
415
438
  // Main list page: KPI cards, both summary tables (with empty-state notes),
@@ -472,9 +495,9 @@ export function renderPage(stats, events, q = {}) {
472
495
  const rowsHtml = rows.length
473
496
  ? rows.map((e) => `<tr>
474
497
  <td><a href="${qs(q, { detail: e._id })}">${shortId(e._id)}</a></td>
475
- <td style="--label:var(--label-1)">${esc(new Date(e.ts).toISOString().replace("T", " ").slice(0, 19))}</td>
498
+ <td style="--label:var(--label-1)">${esc(localStamp(e.ts))}</td>
476
499
  <td style="--label:var(--label-2)">${esc(e.agent)}</td><td style="--label:var(--label-3)">${tag(e.action, ACTION_TAG[e.action] ?? "muted", actionLabel(e.action), actionTitle(e.action, lang))}</td><td style="--label:var(--label-4)">${tag(e.reason, reasonGroup(e.reason), reasonLabel(e.reason), reasonTitle(e.reason, lang))}</td>
477
- <td style="--label:var(--label-5)">${e.action === "pass" ? `<span class="skipped">${bi("skippedAsIs")}</span>` : `${e.inputChars ?? ""}/${e.outputChars ?? ""}`}</td><td style="--label:var(--label-6)">${fmtDur(e.durationMs)}</td></tr>`).join("")
500
+ <td style="--label:var(--label-5)">${e.action === "pass" ? `<span class="skipped">${bi("skippedAsIs")}</span>` : `${e.inputUnits ?? e.inputChars ?? ""}/${e.outputUnits ?? e.outputChars ?? ""}`}</td><td style="--label:var(--label-6)">${fmtDur(e.durationMs)}</td></tr>`).join("")
478
501
  : `<tr><td colspan="7" class="empty">${bi("noEvents")}</td></tr>`;
479
502
 
480
503
  const pager = `
@@ -589,9 +612,9 @@ export function renderDetail(event, q = {}) {
589
612
  <p class="empty warn">${bi("notFound")}</p>
590
613
  <p><a href="${qs(q, { detail: null })}">${bi("back")}</a></p>
591
614
  </body></html>`;
592
- const META_KEYS = ["ts", "agent", "action", "reason", "durationMs", "inputChars", "outputChars", "dryRun", "fromCache", "model", "group", "experimentId", "version", "bucket", "turn", "assignment", "finalAction", "mode", "fallbackFrom", "modelCalls"];
615
+ const META_KEYS = ["ts", "agent", "action", "reason", "durationMs", "inputChars", "outputChars", "inputUnits", "outputUnits", "dryRun", "fromCache", "model", "group", "experimentId", "version", "bucket", "turn", "assignment", "finalAction", "mode", "fallbackFrom", "modelCalls"];
593
616
  const meta = META_KEYS.filter((k) => event[k] !== undefined)
594
- .map((k) => `<tr><th>${esc(k)}</th><td>${k === "action" ? tag(event[k], ACTION_TAG[event[k]] ?? "muted", actionLabel(event[k]), actionTitle(event[k], lang)) : k === "reason" ? tag(event[k], reasonGroup(event[k]), reasonLabel(event[k]), reasonTitle(event[k], lang)) : k === "durationMs" ? fmtDur(event[k]) : esc(k === "ts" ? new Date(event.ts).toISOString() : event[k])}</td></tr>`).join("");
617
+ .map((k) => `<tr><th>${esc(k)}</th><td>${k === "action" ? tag(event[k], ACTION_TAG[event[k]] ?? "muted", actionLabel(event[k]), actionTitle(event[k], lang)) : k === "reason" ? tag(event[k], reasonGroup(event[k]), reasonLabel(event[k]), reasonTitle(event[k], lang)) : k === "durationMs" ? fmtDur(event[k]) : esc(k === "ts" ? localStamp(event.ts) : event[k])}</td></tr>`).join("");
595
618
  const extra = Object.keys(event).filter((k) => !META_KEYS.includes(k) && k !== "orig" && k !== "rewritten" && !k.startsWith("_"))
596
619
  .map((k) => `<tr><th>${esc(k)}</th><td>${esc(event[k])}</td></tr>`).join("");
597
620
  return `${head(lang)}
@@ -14,7 +14,7 @@ import { once } from "node:events";
14
14
  import { dirname, join, resolve } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import os from "node:os";
17
- import { readEvents, prune } from "./stats.mjs";
17
+ import { readEvents, prune, resolveStatsDir } from "./stats.mjs";
18
18
  import { readFileSync } from "node:fs";
19
19
  import { eventsByDay, parseDetailId, renderPage, renderDetail, renderConfigPage, renderConfigDisabled, renderConfigError } from "./stats-page.mjs";
20
20
  export { renderPage, renderDetail } from "./stats-page.mjs";
@@ -136,7 +136,7 @@ export function readProviderGroups(providersFile = join(os.homedir(), ".config",
136
136
  // /api/recent last n events (1..500)
137
137
  export function makeStatsServer({ statsDir, recentDefault = 50, bind = "127.0.0.1", retainDays = process.env.POM_RETAIN_DAYS ?? 7, pluginsFile = join(os.homedir(), ".config/magpie/plugins.json"), providersFile, options = {} } = {}) {
138
138
  const GROUPS = () => readProviderGroups(providersFile); // per-render read: picks up magpie edits without restart
139
- const STATS = statsDir || join(ROOT, "stats");
139
+ const STATS = statsDir || resolveStatsDir();
140
140
  const RECENT_DEFAULT = recentDefault;
141
141
  const server = createServer((req, res) => {
142
142
  if (!hostAllowed(req.headers.host, bind)) {
package/lib/stats.mjs CHANGED
@@ -1,24 +1,69 @@
1
- // Append-only daily event logs under stats/ next to the plugin root
2
- // (import.meta.url based, never cwd). Silent on failure: stats must never
3
- // break a request.
1
+ // Append-only daily event logs, one ndjson file per day. Stats live OUTSIDE
2
+ // the package dir: `magpie plugin update` wipes node_modules reinstalls and
3
+ // took the whole stats/ dir with it twice on prod. New home (design:
4
+ // ~/.config/magpie/prompt-optimizer-magpie/stats). Silent on failure: stats
5
+ // must never break a request.
4
6
  //
5
7
  // Why daily files: record() runs in the magpie plugin-host process while
6
8
  // prune() runs in serve.mjs (systemd) — two OS processes. A read→tmp→rename
7
9
  // rewrite races with a concurrent append (the append lands in the unlinked
8
- // old inode). With one file per UTC day, retention is an unlink of *old*
10
+ // old inode). With one file per local day, retention is an unlink of *old*
9
11
  // files and writers only ever append to *today's* file: the two operations
10
- // touch disjoint inodes, so the race cannot drop data. It also caps any
12
+ // touch disjoint inodes, so no lock protocol is needed. It also bounds a
11
13
  // single file's growth and makes prune O(files), not O(bytes).
12
- import { appendFileSync, readFileSync, readdirSync, unlinkSync, mkdirSync } from "node:fs";
14
+ import { appendFileSync, readFileSync, readdirSync, unlinkSync, mkdirSync, copyFileSync, writeFileSync, existsSync } from "node:fs";
13
15
  import { dirname, join } from "node:path";
14
16
  import { fileURLToPath } from "node:url";
17
+ import { homedir } from "node:os";
15
18
 
16
19
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
17
- const DIR = join(ROOT, "stats");
20
+ const LEGACY_DIR = join(ROOT, "stats"); // pre-0.2.5 location, wiped by plugin updates
18
21
 
19
- // statsDir lets serve.mjs target its POM_DATA_DIR, tests target a tmp dir.
22
+ // One resolver for record/read/prune defaults and both entries (index.mjs,
23
+ // serve.mjs). POM_STATS_DIR explicitly overrides; no XDG dependency — Windows
24
+ // falls back to ~/.config/... too (documented in README).
25
+ export function resolveStatsDir() {
26
+ if (process.env.POM_STATS_DIR) return process.env.POM_STATS_DIR;
27
+ return join(homedir(), ".config", "magpie", "prompt-optimizer-magpie", "stats");
28
+ }
29
+
30
+ // One-shot legacy migration (called from both entries at startup): if the
31
+ // package-internal stats/ dir survived and the new dir would lose data, COPY
32
+ // day files over (never overwrite; the legacy dir is left in place) and drop
33
+ // a MIGRATED.txt marker so it never runs twice. Copy-once beats move: on 70
34
+ // the old dir has manually-restored history an update must not re-destroy.
35
+ // Silent-fail — stats can never block a request.
36
+ export function migrateLegacyStats(oldDir = process.env.POM_LEGACY_STATS_DIR || LEGACY_DIR, newDir = resolveStatsDir()) {
37
+ try {
38
+ if (!existsSync(oldDir)) return false;
39
+ if (existsSync(join(oldDir, "MIGRATED.txt"))) return false;
40
+ mkdirSync(newDir, { recursive: true });
41
+ for (const name of readdirSync(oldDir)) {
42
+ if (!/^\d{4}-\d{2}-\d{2}\.ndjson$/.test(name)) continue;
43
+ const dest = join(newDir, name);
44
+ if (existsSync(dest)) continue; // never overwrite newer data
45
+ copyFileSync(join(oldDir, name), dest);
46
+ }
47
+ writeFileSync(join(oldDir, "MIGRATED.txt"), `migrated to ${newDir} at ${new Date().toISOString()}\n`);
48
+ return true;
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ const DIR = resolveStatsDir();
55
+
56
+ // Local-timezone YYYY-MM-DD (not toISOString's UTC): CST 0:00–8:00 events
57
+ // belong to today's local file, not yesterday's UTC one.
58
+ export function localDay(d = new Date()) {
59
+ const p = (n) => String(n).padStart(2, "0");
60
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
61
+ }
62
+
63
+ // statsDir lets serve.mjs target its data dir, tests target a tmp dir.
20
64
  const dayFile = (d = new Date(), statsDir = DIR) =>
21
- join(statsDir, d.toISOString().slice(0, 10) + ".ndjson");
65
+ join(statsDir, localDay(d) + ".ndjson");
66
+
22
67
 
23
68
  export function record(ev, statsDir = DIR) {
24
69
  try {
@@ -48,7 +93,7 @@ export function validEvent(ev) {
48
93
  && typeof ev.fromCache === "boolean" && Number.isSafeInteger(ev.modelCalls) && ev.modelCalls >= 0
49
94
  && Number.isFinite(ev.durationMs) && ev.durationMs >= 0;
50
95
  }
51
- return ["durationMs", "inputChars", "outputChars"].every((k) => ev[k] === undefined || Number.isFinite(ev[k]))
96
+ return ["durationMs", "inputChars", "outputChars", "inputUnits", "outputUnits"].every((k) => ev[k] === undefined || Number.isFinite(ev[k]))
52
97
  && ["agent", "orig", "rewritten"].every((k) => ev[k] === undefined || typeof ev[k] === "string")
53
98
  && ["dryRun", "fromCache"].every((k) => ev[k] === undefined || typeof ev[k] === "boolean");
54
99
  }
@@ -93,10 +138,10 @@ export function prune(retainDays, now = Date.now(), statsDir = DIR) {
93
138
  } catch {
94
139
  return 0;
95
140
  }
96
- // files strictly older than the cutoff date (UTC) are unlinked
141
+ // files strictly older than the cutoff date (local day) are unlinked
97
142
  const date = new Date(now - retainDays * 86400_000);
98
143
  if (!Number.isFinite(date.getTime())) return 0;
99
- const cutoff = date.toISOString().slice(0, 10);
144
+ const cutoff = localDay(date);
100
145
  let removed = 0;
101
146
  for (const name of names) {
102
147
  if (!/^\d{4}-\d{2}-\d{2}\.ndjson$/.test(name)) continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prompt-optimizer-magpie",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Self-contained Magpie gateway request hook that rewrites vague first-turn prompts into precise ones before they reach your model. Fail-open by design.",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
@@ -78,7 +78,8 @@
78
78
  "bind": "127.0.0.1",
79
79
  "configPage": false,
80
80
  "minChars": 6,
81
- "maxChars": 12000
81
+ "maxChars": 12000,
82
+ "guardRatioLimit": 10
82
83
  }
83
84
  },
84
85
  "engines": {
package/serve.mjs CHANGED
@@ -1,16 +1,20 @@
1
1
  // v0.2 standalone stats daemon (design §6). All HTTP logic lives in
2
2
  // lib/stats-service.mjs, shared with index.mjs (magpie plugin host entry).
3
- // This file adds: env overrides (PORT, POM_DATA_DIR, POM_BIND), service.json
4
- // discovery for systemd and EADDRINUSE retry+fallback.
3
+ // This file adds: env overrides (PORT, POM_DATA_DIR for service.json, POM_BIND,
4
+ // POM_STATS_DIR for day-files), service.json discovery for systemd and
5
+ // EADDRINUSE retry+fallback.
5
6
  import { writeFileSync, rmSync, readFileSync, symlinkSync, renameSync } from "node:fs";
6
7
  import { randomUUID } from "node:crypto";
7
8
  import { join, dirname, basename } from "node:path";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { makeStatsServer } from "./lib/stats-service.mjs";
11
+ import { resolveStatsDir, migrateLegacyStats } from "./lib/stats.mjs";
10
12
 
11
13
  const ROOT = join(dirname(fileURLToPath(import.meta.url)));
14
+ // Stats moved out of the package dir (survives `magpie plugin update`);
15
+ // POM_DATA_DIR only relocates service.json/instance records (systemd units).
12
16
  const DATA_DIR = process.env.POM_DATA_DIR || ROOT;
13
- const STATS = join(DATA_DIR, "stats"); // daily day-files (lib/stats.mjs)
17
+ const STATS = resolveStatsDir(); // env POM_STATS_DIR > ~/.config/magpie/prompt-optimizer-magpie/stats
14
18
  const SERVICE = join(DATA_DIR, "service.json");
15
19
  const instanceRecord = join(DATA_DIR, `.service-${randomUUID()}.json`);
16
20
  const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).version;
@@ -18,6 +22,8 @@ const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).ver
18
22
  // (stats 日志里有截断后的提示词原文,对内网可见——见 README 隐私说明)。
19
23
  const BIND = process.env.POM_BIND || "127.0.0.1";
20
24
 
25
+ // One-shot: bring package-internal legacy stats/ over before first read.
26
+ if (migrateLegacyStats()) console.log("serve: migrated legacy stats/ to " + STATS);
21
27
  const server = makeStatsServer({ statsDir: STATS, bind: BIND });
22
28
  // design §6: ephemeral (PORT=0) is the norm; a fixed PORT may hit EADDRINUSE —
23
29
  // per candidate: same-port retry 16×100ms (a leaving process's socket often