@ericality/dsh-notice-banner 0.11.1 → 0.11.7

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/history.js ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * W7 历史条幅归档读取器(2026-11-12)—— **插件自有数据面的只读口**
3
+ *
4
+ * §g 目的与背景(要解决或预防的问题):
5
+ * 0.2.2 的 v0→v1 迁移链**必须**把自定义事件 `notice/banner` / `notice/banner-replace` 从会话日志里
6
+ * 清洗掉(改名冒充已收录类型已被判死 —— `仲裁档案 A-018`)。用户令「**历史记录不能丢**」并且明写
7
+ * **不接受「清洗时丢弃横幅事件」的口径** ⇒ 交付形态是「**归档 + 可显**」两半(`任务档案 §1.2`)。
8
+ * W2 已把 3520 条 / 130 会话归档到 `log/0.2.2升级/archive/`;**本模块是该归档的唯一读取口**:
9
+ * 它把「某会话的历史条幅事件」按 `turn` 分组吐给 `notice/history` 端点(`lib/index.js`),
10
+ * 再由客户端按轮渲染到 `conversation.chat.turnTail` 槽(`lib/client.js`)。
11
+ * 没有本模块时,归档只是死文件 —— 「可显」这半条用户诉求落不了地,W6 runbook 也无消费方凭证。
12
+ *
13
+ * 边界(写死,改需先问用户):
14
+ * · **只读**:不改归档、不写任何文件、不碰宿主数据(`ENV §一.7③` 中间件不持业务数据)。
15
+ * · **永不 throw 到宿主**:任何异常 ⇒ 结构化 `{ok:false, degraded:true, reason}`。
16
+ * · **降级必须可见**:归档不可读 ≠ 无归档(前者 `degraded:true`,后者 `ok:true, hasArchive:false`),
17
+ * 客户端据此分别渲染「归档不可用」与「无归档」两类提示(`ENV §一.6②` 禁「报 OK 而功能坏」)。
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ import { readFileSync, statSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { join } from "node:path";
23
+
24
+ /** 响应 schema 版本(键集变更须 +1,客户端与载荷对撞按它判代) */
25
+ export const HISTORY_SCHEMA_VERSION = 1;
26
+
27
+ /** 默认归档目录(生产/VM 场的插件自有数据目录;W7 只读副本落此) */
28
+ export const DEFAULT_ARCHIVE_DIR = join(process.env.DSH_HOME || join(homedir(), ".dsh"), "plugin-data", "notice-banner", "notice-history");
29
+
30
+ /** 归档解析缓存(键 = 两文件的 size+mtime;归档是只读基线,命中即可复用) */
31
+ let cache = { key: "", archive: null };
32
+
33
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
34
+
35
+ /** 指纹:`index.json` / `events.jsonl` 的 size+mtime(缺一则记 `missing`,交给读路径如实降级) */
36
+ function fingerprint(dir) {
37
+ const parts = [];
38
+ for (const f of ["index.json", "events.jsonl"]) {
39
+ try {
40
+ const st = statSync(join(dir, f));
41
+ parts.push(`${f}:${st.size}:${st.mtimeMs}`);
42
+ } catch {
43
+ parts.push(`${f}:missing`);
44
+ }
45
+ }
46
+ return parts.join("|");
47
+ }
48
+
49
+ /**
50
+ * 目录解析优先级:显式配置 > 环境变量 `DSH_NOTICE_HISTORY_DIR` > 默认目录。
51
+ * (VM 场与生产都不用配;环境变量只服务测试与 A/B。)
52
+ */
53
+ export function resolveArchiveDir(configured) {
54
+ const v = typeof configured === "string" ? configured.trim() : "";
55
+ if (v) return v;
56
+ const env = typeof process !== "undefined" && process.env ? process.env.DSH_NOTICE_HISTORY_DIR : "";
57
+ const e = typeof env === "string" ? env.trim() : "";
58
+ return e || DEFAULT_ARCHIVE_DIR;
59
+ }
60
+
61
+ /**
62
+ * 读归档并建索引(只读、幂等、带缓存)。
63
+ * 返回 `{ready, dir, schemaVersion, indexSha256, builtAt, totalEvents, totalSessions, withTurn, nullTurn, bySid, eventCount}`;
64
+ * 读失败 ⇒ throw(由 `historyFor` 归一为 `degraded` 响应 —— 这里 throw 是因为调用点唯一且必须区分「不可读」与「无归档」)。
65
+ */
66
+ function readArchive(dir) {
67
+ const key = fingerprint(dir);
68
+ if (cache.archive && cache.key === key) return cache.archive;
69
+ const indexRaw = readFileSync(join(dir, "index.json"), "utf8");
70
+ const index = JSON.parse(indexRaw);
71
+ const eventsRaw = readFileSync(join(dir, "events.jsonl"), "utf8");
72
+ const bySid = new Map();
73
+ let eventCount = 0;
74
+ let nullTurn = 0;
75
+ for (const line of eventsRaw.split("\n")) {
76
+ if (!line) continue;
77
+ let e;
78
+ try {
79
+ e = JSON.parse(line);
80
+ } catch {
81
+ continue; // 坏行跳过但计数会与 index 不符 ⇒ 由 totals 暴露(不静默:archive.eventCount vs index.totalEvents)
82
+ }
83
+ eventCount += 1;
84
+ if (e && e.turn === null) nullTurn += 1;
85
+ const sid = e && typeof e.sid === "string" ? e.sid : "";
86
+ if (!sid) continue;
87
+ let arr = bySid.get(sid);
88
+ if (!arr) {
89
+ arr = [];
90
+ bySid.set(sid, arr);
91
+ }
92
+ arr.push(e);
93
+ }
94
+ for (const arr of bySid.values()) arr.sort((a, b) => (Number(a.seq) || 0) - (Number(b.seq) || 0));
95
+ // 索引内的会话集合:`hasArchive` 的判据是「**该会话被归档器收录**」,与「本次读到几条」分开
96
+ // (否则「会话不在索引里」会被误报成 hasArchive:true + count:0 ⇒ 客户端静默空白,正是 P4 负控要抓的假绿)
97
+ const sids = new Set();
98
+ if (Array.isArray(index.sessions)) for (const s of index.sessions) if (s && typeof s.sid === "string") sids.add(s.sid);
99
+ const archive = {
100
+ ready: true,
101
+ dir,
102
+ schemaVersion: Number(index.schemaVersion) || 1,
103
+ indexSha256: sha256(indexRaw),
104
+ builtAt: new Date().toISOString(),
105
+ totalEvents: Number(index.totalEvents) || eventCount,
106
+ totalSessions: Number(index.totalSessions) || bySid.size,
107
+ withTurn: eventCount - nullTurn,
108
+ nullTurn,
109
+ eventCount,
110
+ bySid,
111
+ sids
112
+ };
113
+ cache = { key, archive };
114
+ return archive;
115
+ }
116
+
117
+ /** 单条归档事件的**下发投影**:身份(seq/turn)+ 展示面(data 原样保留 = 「可显」不失真) */
118
+ function projectEvent(e) {
119
+ return {
120
+ seq: Number(e.seq) || 0,
121
+ type: String(e.type || ""),
122
+ turn: e.turn === null || e.turn === undefined ? null : Number(e.turn),
123
+ turnFrom: e.turnFrom === undefined ? null : e.turnFrom,
124
+ afterTurnEnd: e.afterTurnEnd === undefined ? null : e.afterTurnEnd,
125
+ time: Number(e.time) || 0,
126
+ data: e && typeof e.data === "object" && e.data !== null ? e.data : {}
127
+ };
128
+ }
129
+
130
+ /**
131
+ * 端点主函数:`historyFor(dir, sid)` ⇒ 响应对象(键集见 `计划.md §4.2`)。
132
+ * 三态:① `ok:true, hasArchive:true` ② `ok:true, hasArchive:false`(会话不在索引内 = 「无归档」)③ `ok:false, degraded:true`(归档不可读)。
133
+ */
134
+ export function historyFor(archiveDir, sid) {
135
+ const dir = resolveArchiveDir(archiveDir);
136
+ const sidOk = typeof sid === "string" && /^session-[0-9a-z-]{8,}$/i.test(sid) ? sid : null;
137
+ const base = {
138
+ ok: false,
139
+ sid: sidOk,
140
+ schemaVersion: HISTORY_SCHEMA_VERSION,
141
+ hasArchive: false,
142
+ count: 0,
143
+ groups: [],
144
+ archive: { ready: false, dir, indexSha256: "", builtAt: null, totalSessions: 0, totalEvents: 0 },
145
+ totals: { allSessions: 0, allEvents: 0, withTurn: 0, nullTurn: 0 },
146
+ degraded: true,
147
+ reason: ""
148
+ };
149
+ if (sidOk === null) return { ...base, degraded: false, reason: "bad-request" };
150
+ let a;
151
+ try {
152
+ a = readArchive(dir);
153
+ } catch (err) {
154
+ return { ...base, reason: `history-archive-unavailable:${String(err?.message ?? err).slice(0, 160)}` };
155
+ }
156
+ const events = a.bySid.get(sidOk) || [];
157
+ const archivedSid = a.sids.has(sidOk) || events.length > 0;
158
+ // 分组:数值回合升序,`turn === null` 单独一组且恒排**最后**(「无回合落点」组,P3② 要求它可见且不并入任何回合)
159
+ const byTurn = new Map();
160
+ const nulls = [];
161
+ for (const e of events) {
162
+ if (e.turn === null || e.turn === undefined) {
163
+ nulls.push(projectEvent(e));
164
+ continue;
165
+ }
166
+ const t = Number(e.turn);
167
+ let g = byTurn.get(t);
168
+ if (!g) {
169
+ g = [];
170
+ byTurn.set(t, g);
171
+ }
172
+ g.push(projectEvent(e));
173
+ }
174
+ const groups = [];
175
+ for (const t of Array.from(byTurn.keys()).sort((x, y) => x - y)) {
176
+ const evs = byTurn.get(t);
177
+ groups.push({ turn: t, count: evs.length, events: evs });
178
+ }
179
+ if (nulls.length) groups.push({ turn: null, count: nulls.length, events: nulls });
180
+ return {
181
+ ok: true,
182
+ sid: sidOk,
183
+ schemaVersion: HISTORY_SCHEMA_VERSION,
184
+ hasArchive: archivedSid,
185
+ count: events.length,
186
+ groups,
187
+ archive: {
188
+ ready: true,
189
+ dir: a.dir,
190
+ indexSha256: a.indexSha256,
191
+ builtAt: a.builtAt,
192
+ totalSessions: a.totalSessions,
193
+ totalEvents: a.totalEvents
194
+ },
195
+ totals: { allSessions: a.totalSessions, allEvents: a.totalEvents, withTurn: a.withTurn, nullTurn: a.nullTurn },
196
+ degraded: false,
197
+ reason: ""
198
+ };
199
+ }
200
+
201
+ /** 供探针/自检用:只回全库口径(不拖单会话明细);失败同样归一为 degraded */
202
+ export function archiveSummary(archiveDir) {
203
+ const dir = resolveArchiveDir(archiveDir);
204
+ try {
205
+ const a = readArchive(dir);
206
+ return {
207
+ ok: true,
208
+ degraded: false,
209
+ dir: a.dir,
210
+ schemaVersion: a.schemaVersion,
211
+ indexSha256: a.indexSha256,
212
+ builtAt: a.builtAt,
213
+ totals: { allSessions: a.totalSessions, allEvents: a.totalEvents, withTurn: a.withTurn, nullTurn: a.nullTurn, eventsJsonlCount: a.eventCount }
214
+ };
215
+ } catch (err) {
216
+ return { ok: false, degraded: true, reason: `history-archive-unavailable:${String(err?.message ?? err).slice(0, 160)}`, dir };
217
+ }
218
+ }