@fabianactor/dsh-lil-whale-group 1.12.0 → 1.12.2

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.
@@ -0,0 +1,52 @@
1
+ // 代码指纹的历史账(2026-11-19,小鱼丸私聊第 53 行)。
2
+ //
3
+ // boot 行里的 `codeFp` 只回答"启动那一刻磁盘是什么样";拿它跟"启动那一刻的磁盘"比,
4
+ // 是拿一个量跟它的自述比 —— 恒真。要回答"这段代码改过没有",得像 log-format 那样
5
+ // 在值变化时留一行:账上有历史值,读的人就不用靠谁记性好。
6
+ //
7
+ // 这里只做纯计算;文件读写留在 index.js,方便测试。
8
+
9
+ export const CODE_FP_LEDGER = 'code-fp.json'
10
+
11
+ /**
12
+ * 比较上一次记下的指纹与这一次算出来的。
13
+ * @returns {{kind:'baseline',newFp:string,newFiles:number}
14
+ * | {kind:'same',newFp:string,newFiles:number}
15
+ * | {kind:'changed',oldFp:string,oldFiles:number,newFp:string,newFiles:number}}
16
+ */
17
+ export function codeFpChangeOf(prev, current) {
18
+ const newFp = typeof current?.fp === 'string' && current.fp !== '' ? current.fp : 'unknown'
19
+ const newFiles = Number.isFinite(current?.files) ? current.files : 0
20
+ if (!prev || typeof prev.fp !== 'string' || prev.fp === '') {
21
+ return { kind: 'baseline', newFp, newFiles }
22
+ }
23
+ if (prev.fp === newFp) return { kind: 'same', newFp, newFiles }
24
+ return {
25
+ kind: 'changed',
26
+ oldFp: prev.fp,
27
+ oldFiles: Number.isFinite(prev.files) ? prev.files : 0,
28
+ newFp,
29
+ newFiles,
30
+ }
31
+ }
32
+
33
+ /** 变化时写一行;没变返回 null("没变不记事件")。 */
34
+ export function codeFpHistoryLine(change) {
35
+ if (change?.kind === 'baseline') {
36
+ return `note=code-fp-baseline fp=${change.newFp} files=${change.newFiles}`
37
+ }
38
+ if (change?.kind === 'changed') {
39
+ return (
40
+ `note=code-fp-changed old=${change.oldFp} new=${change.newFp}` +
41
+ ` files-old=${change.oldFiles} files-new=${change.newFiles}`
42
+ )
43
+ }
44
+ return null
45
+ }
46
+
47
+ /** 账本里留的最新一份(下一次启动拿它当"上一次")。 */
48
+ export function codeFpLedgerOf(current, at) {
49
+ const fp = typeof current?.fp === 'string' && current.fp !== '' ? current.fp : 'unknown'
50
+ const files = Number.isFinite(current?.files) ? current.files : 0
51
+ return { fp, files, at }
52
+ }
package/lib/index.js CHANGED
@@ -12,6 +12,7 @@ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renam
12
12
  import { printableText } from './text-clean.js'
13
13
  import { sayProblemOf, channelProblemOf } from './say-core.js'
14
14
  import { codeFingerprint } from './code-fp.js'
15
+ import { codeFpChangeOf, codeFpHistoryLine, codeFpLedgerOf, CODE_FP_LEDGER } from './code-fp-history-core.js'
15
16
  import { join, dirname, basename } from 'node:path'
16
17
  import { homedir } from 'node:os'
17
18
  import { pathToFileURL, fileURLToPath } from 'node:url'
@@ -183,6 +184,9 @@ const GROUP_DIR = CFG.groupDir
183
184
  // 不在任何一条鱼的家里 —— 它们记的是"谁读到哪、谁被叫过",是共享的。
184
185
  // 共享区在家之外(pool),她家里有 Junction 指回去,所以她的路径没变。
185
186
  const POOL_STATE = CFG.poolStateDir
187
+ // 代码指纹的历史账(2026-11-19,小鱼丸私聊第 53 行):上一次启动记下的值,
188
+ // 让“这段代码改过没有”能从账上答,而不是靠谁记性好。
189
+ const CODE_FP_LEDGER_FILE = join(POOL_STATE, CODE_FP_LEDGER)
186
190
  // 图片:字节进 images\<yyyymm>\<id>.<ext>,消息里只记 id/ext/bytes。
187
191
  // 用内容哈希当 id —— 同一张图发两次只落一份,而且天然不可变(可以永久缓存)。
188
192
  const IMAGES_DIR = join(GROUP_DIR, 'images')
@@ -1830,10 +1834,27 @@ function logLine(record) {
1830
1834
  * repoRoot 来自 `import.meta.url`(这一行代码自己站在哪),配置写错也改不动它。
1831
1835
  */
1832
1836
  const BOOT_LOG = join(CFG.repoRoot, 'logs', 'plugin-boot.log')
1837
+ function recordCodeFpHistory() {
1838
+ try {
1839
+ const prev = readJson(CODE_FP_LEDGER_FILE, null)
1840
+ const change = codeFpChangeOf(prev, CODE_FP)
1841
+ if (change.kind !== 'same') {
1842
+ const line = codeFpHistoryLine(change)
1843
+ if (line !== null) watchmanLog('note', line)
1844
+ }
1845
+ writeJson(CODE_FP_LEDGER_FILE, codeFpLedgerOf(CODE_FP, new Date().toISOString()))
1846
+ } catch {
1847
+ // 历史账写不进去不该拦住启动;下一个能写的地方会把它写出来
1848
+ }
1849
+ }
1850
+
1833
1851
  function bootLog(record) {
1834
1852
  try {
1835
1853
  mkdirSync(dirname(BOOT_LOG), { recursive: true })
1836
- appendFileSync(BOOT_LOG, JSON.stringify({ at: new Date().toISOString(), ...record }) + '\n', 'utf8')
1854
+ // 2026-11-19 fi-0002(小鱼丸,群第 2263 行):`at` 原来在 bootLog 与镜像写入处各生成一次,
1855
+ // 同进程同一次启动的两本账能差 1–2ms —— "at+pid join" 只在同毫秒时成立。
1856
+ // 现在 `at` 由调用方一次拼进 record(bootRecordWithNote 里有),两处共用;调用方没给才补一次。
1857
+ appendFileSync(BOOT_LOG, JSON.stringify({ at: record.at ?? new Date().toISOString(), ...record }) + '\n', 'utf8')
1837
1858
  } catch {}
1838
1859
  }
1839
1860
 
@@ -1948,8 +1969,12 @@ function apply(ctx) {
1948
1969
  // 小鱼丸/小满 #1670–#1672(2026-11-18):镜像到 pool\group\plugin.log 的那一行原来 spread 的是
1949
1970
  // bootRecord,而 note 只临时贴在 bootLog 的参数里 ⇒ 同一批 boot 行在群里那本没有 note。
1950
1971
  // 修法不是补一个词,而是"一次拼好、两处都用同一个对象":以后 bootRecord 加字段,镜像自动跟上。
1951
- const bootRecordWithNote = { note: 'boot', ...bootRecord }
1972
+ // 2026-11-19 fi-0002:`at` 在这里生成一次,两本账共用(bootLog 与下面的镜像写都读它)。
1973
+ const bootRecordWithNote = { at: new Date().toISOString(), note: 'boot', ...bootRecord }
1952
1974
  bootLog(bootRecordWithNote)
1975
+ // 小鱼丸私聊第 53 行(2026-11-19):boot 行只留了一个时刻的指纹,
1976
+ // 回答不了“改过没有”;在值变化时补一行,账上有历史值才判得动。
1977
+ recordCodeFpHistory()
1953
1978
  // P4(2026-11-16 第三份装机沉淀):只把两个 bundle add 进 profile(最小安装)时,
1954
1979
  // 没有安装器来问"鱼塘放哪",也没有配置文件 ⇒ 默认值会把 homes/pool 建在仓库旁边
1955
1980
  // (实测:<workspace>\whale-src\ 里同时出现仓库和 homes/pool)。用户以为数据在别处,
@@ -1958,6 +1983,7 @@ function apply(ctx) {
1958
1983
  const repoInPondLayout = basename(CFG.repoRoot) === 'app'
1959
1984
  if (!CFG._exists && !repoInPondLayout) {
1960
1985
  const layoutWarn = {
1986
+ at: new Date().toISOString(),
1961
1987
  note: 'layout-warning',
1962
1988
  why: 'no-config-and-not-pond-layout',
1963
1989
  repoRoot: CFG.repoRoot,
@@ -1966,11 +1992,11 @@ function apply(ctx) {
1966
1992
  }
1967
1993
  bootLog(layoutWarn)
1968
1994
  try {
1969
- appendFileSync(join(GROUP_DIR, 'plugin.log'), JSON.stringify({ at: new Date().toISOString(), ...layoutWarn }) + '\n', 'utf8')
1995
+ appendFileSync(join(GROUP_DIR, 'plugin.log'), JSON.stringify({ ...layoutWarn }) + '\n', 'utf8')
1970
1996
  } catch {}
1971
1997
  }
1972
1998
  try {
1973
- appendFileSync(join(GROUP_DIR, 'plugin.log'), JSON.stringify({ at: new Date().toISOString(), ...bootRecordWithNote }) + '\n', 'utf8')
1999
+ appendFileSync(join(GROUP_DIR, 'plugin.log'), JSON.stringify({ ...bootRecordWithNote }) + '\n', 'utf8')
1974
2000
  } catch {}
1975
2001
 
1976
2002
  // 无人值守:成员进程把自己那段会话挂上(工具要经过 session-controller 才挂得上)
@@ -3836,8 +3862,12 @@ function maybePruneMediaCache() {
3836
3862
  watchmanLog('error', `note=media-prune-failed reason=${String(error?.message ?? error).replace(/\s+/g, ' ').slice(0, 120)}`)
3837
3863
  return
3838
3864
  }
3865
+ // 目录层失败与文件层失败分开写:前者读 error,后者读 failed(小鱼丸 2026-11-19 群第 2197 行)
3866
+ if (result.error !== null) {
3867
+ watchmanLog('error', `note=media-prune-failed scope=dir reason=${result.error}`)
3868
+ }
3839
3869
  for (const item of result.failed) {
3840
- watchmanLog('error', `note=media-prune-failed file=${item.name || '-'} reason=${item.code}`)
3870
+ watchmanLog('error', `note=media-prune-failed scope=${item.scope ?? 'file'} file=${item.name || '-'} reason=${item.code}`)
3841
3871
  }
3842
3872
  if (result.removed > 0) {
3843
3873
  watchmanLog(
@@ -17,18 +17,28 @@
17
17
  // 2. key 的顺序不再是签名的一部分:比较的是"每个 key 的值",不是拼好的字符串。
18
18
  // (小鱼丸:"签名的相等是按字符串比的,顺序不同就算变了"——重排常量会让每次启动多一行。)
19
19
 
20
- export const LOG_FORMAT_SIG = 'fmt=3 changed=skip,wake-skip,deliver fields=deny,note,reason field-since=codeFp:r255,member:r292,note:r293'
20
+ // 2026-11-19 fi-0001(小满,群第 2260 行):`changed=` 声明的是"格式变过的事件",
21
+ // 不是"这本账里所有 kind"——于是 `error`(1129 行)从来没被任何声明覆盖,声明和检查器
22
+ // 两格都看不见它。声明写漏是常态,所以补两件事:
23
+ // 1. `kinds=` 把代码会写的 kind 列成完整清单(这张表就是声明;加一个 kind 必须改它);
24
+ // 2. `auditKinds()` 拿账上出现过的 kind 跟它对,报"未声明的 kind 有几行"。
25
+ // 判据(小满):「声明描述它想管的 kind,检查器该报它不管的 kind 有几行」。
26
+ // 2026-11-19 fi-0001 小满复验 #2269:`kinds=` 声明的是**正文事件**;`log-format` 是表头这一行自己的 kind,
27
+ // 不属于正文清单(否则每本带新表头的账都会把自己报成未声明)。所以这里不收它,对账时也不数它。
28
+ export const LOG_KINDS = ['deliver', 'error', 'note', 'resumed', 'skip', 'started', 'stopped', 'wake', 'wake-caps', 'wake-skip', 'wake-try', 'woke']
29
+
30
+ export const LOG_FORMAT_SIG = `fmt=3 changed=skip,wake-skip,deliver fields=deny,note,reason field-since=codeFp:r255,member:r292,note:r293 kinds=${LOG_KINDS.join(',')}`
21
31
 
22
32
  const MARK = ' | log-format | '
23
33
  // 参与指纹的 key(顺序固定输出,但比较时按 key 取值——顺序不进指纹)。
24
- const KEYS = ['fmt', 'changed', 'fields', 'field-since']
34
+ const KEYS = ['fmt', 'changed', 'fields', 'field-since', 'kinds']
25
35
  export const LOG_FORMAT_KEYS = KEYS
26
36
 
27
37
  // 从 detail 里按 ` (^|空格)key=值` 取每个 key 的值。
28
38
  // 值里夹着别的 key 的字面量不会影响:这里只认"空白之后"的 key。
29
39
  function parseDetail(detail) {
30
40
  const map = {}
31
- const re = /(?:^|\s)(fmt|changed|fields|field-since)=(\S*)/g
41
+ const re = /(?:^|\s)(fmt|changed|fields|field-since|kinds)=(\S*)/g
32
42
  let m = re.exec(detail)
33
43
  while (m) {
34
44
  map[m[1]] = m[2]
@@ -48,7 +58,7 @@ function listCanonical(value) {
48
58
  return value.split(',').map((part) => part.trim()).filter(Boolean).sort().join(',')
49
59
  }
50
60
 
51
- const LIST_KEYS = new Set(['changed', 'fields', 'field-since'])
61
+ const LIST_KEYS = new Set(['changed', 'fields', 'field-since', 'kinds'])
52
62
 
53
63
  function canonicalOf(map) {
54
64
  const out = {}
@@ -101,3 +111,55 @@ export function buildLogFormatDetail({ signature = LOG_FORMAT_SIG, since, pid, t
101
111
  const who = to ? ` to=${to}` : ''
102
112
  return `${signature} since=${at} pid=${pid}${who}`
103
113
  }
114
+
115
+ // 账上一行是 `<日期> <时间> | kind | 正文`。取出 kind;不是这个形状返回 ''。
116
+ // 2026-11-19 fi-0001:对账要知道"账上到底出现过哪些 kind",不能只信声明。
117
+ export function kindOfLine(line) {
118
+ const m = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \| ([A-Za-z0-9_-]+) \|/.exec(String(line || ''))
119
+ return m ? m[1] : ''
120
+ }
121
+
122
+ // 从最后一行 log-format 取声明的 kind 清单;账上还没有带 kinds= 的表头时返回 null。
123
+ // null 与空数组是两件事:老账是"这版代码之前没有这项声明",不是"声明了空清单"。
124
+ export function declaredKindsOf(lines) {
125
+ const last = findLastLogFormatLine(lines)
126
+ if (!last) return null
127
+ const map = parseDetail(detailOf(last))
128
+ if (typeof map.kinds !== 'string' || map.kinds === '') return null
129
+ return map.kinds.split(',').map((part) => part.trim()).filter(Boolean)
130
+ }
131
+
132
+ // 对账:账上出现过的 kind 逐类计数,跟声明比。
133
+ // declared:真正拿来对照的清单(表头的 kinds=,或老账时用 fallbackKinds=代码里的 LOG_KINDS)
134
+ // declaredSource:'header'(账自己声明的)| 'code'(账太老、按代码清单对照)| 'none'(没有对照)
135
+ // seen: [{ kind, count }] 按 kind 排序
136
+ // undeclared:账上有、声明里没有(这才是 fi-0001 要报的那一类)
137
+ // missing:声明里有、账上还没出现(用来区分"声明了但没用过")
138
+ // 2026-11-19 小满复验 #2269 指出:老账没有 kinds= 时若直接判"不知道",
139
+ // `bogus-kind` 这类整类隐形的 kind 在老账里依然报不出来 ⇒ 默认用代码清单对照('code'),
140
+ // 只有调用方明确不给 fallback 才是 'none'("判不了")。
141
+ export function auditKinds(lines, fallbackKinds = null) {
142
+ const list = Array.isArray(lines) ? lines : []
143
+ const seenMap = new Map()
144
+ for (const row of list) {
145
+ const kind = kindOfLine(row)
146
+ // 表头行自己的 kind 不进正文清单(fi-0001,小满 #2269)。
147
+ if (!kind || kind === 'log-format') continue
148
+ seenMap.set(kind, (seenMap.get(kind) ?? 0) + 1)
149
+ }
150
+ const seen = [...seenMap.entries()]
151
+ .map(([kind, count]) => ({ kind, count }))
152
+ .sort((a, b) => (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0))
153
+ const headerKinds = declaredKindsOf(list)
154
+ const declared = headerKinds ?? (Array.isArray(fallbackKinds) ? fallbackKinds : null)
155
+ const declaredSource = headerKinds !== null ? 'header' : declared !== null ? 'code' : 'none'
156
+ if (declared === null) return { declared: null, declaredSource, seen, undeclared: [], missing: [] }
157
+ const declaredSet = new Set(declared)
158
+ return {
159
+ declared,
160
+ declaredSource,
161
+ seen,
162
+ undeclared: seen.filter((item) => !declaredSet.has(item.kind)),
163
+ missing: [...declaredSet].filter((kind) => !seenMap.has(kind)).sort(),
164
+ }
165
+ }
@@ -20,18 +20,29 @@ export const MEDIA_CACHE_MAX_AGE_DAYS = 7
20
20
 
21
21
  /**
22
22
  * 删掉 dir 里 mtime 早于 maxAgeDays 的普通文件。
23
- * 返回 { removed, bytes, failed:[{name,code}], existed };目录不存在不是错误(existed=false)。
23
+ *
24
+ * 返回 { removed, bytes, existed, error, failed },语义与 mediaCacheStats 对齐
25
+ * (小鱼丸 2026-11-19 群第 2197 行:两个函数同名同义,读者不用记两套):
26
+ * - existed: true —— 目录读到了;error: null;
27
+ * - existed: false, error: null —— 目录还没建(没下过视频),不是失败;
28
+ * - existed: false, error: '<CODE>' —— 试过、没读成(ENOTDIR / EACCES …),码进 error;
29
+ * - failed: [{ scope:'dir'|'file', name?, code }] —— 只装“具体某一层”的失败;
30
+ * 目录层失败进 error,文件层失败进 failed(带 name,下一个人才知道该动哪个)。
24
31
  */
25
32
  export function pruneMediaCache({ dir, maxAgeDays = MEDIA_CACHE_MAX_AGE_DAYS, now = Date.now() } = {}) {
26
- const out = { removed: 0, bytes: 0, failed: [], existed: true }
27
- if (!dir) return { ...out, existed: false }
33
+ const out = { removed: 0, bytes: 0, existed: false, error: null, failed: [] }
34
+ if (!dir) return { ...out, error: 'NO-ARG' }
28
35
  let names
29
36
  try {
30
37
  names = readdirSync(dir)
31
38
  } catch (error) {
32
- if (error?.code === 'ENOENT') return { ...out, existed: false }
33
- return { ...out, failed: [{ name: '', code: error?.code ?? 'error' }] }
39
+ const code = error?.code ?? 'error'
40
+ // ENOENT:目录没建 = 没东西可删,不是失败(与 mediaCacheStats 对“父目录还在”的区分不同:
41
+ // 清理路径不关心“是谁改错了路”,只关心“这一轮没东西可清”——路径算错会由 stats 那格报出来)。
42
+ if (code === 'ENOENT') return out
43
+ return { ...out, error: code }
34
44
  }
45
+ out.existed = true
35
46
  const cutoff = now - maxAgeDays * 86400_000
36
47
  for (const name of names.slice().sort()) {
37
48
  const full = join(dir, name)
@@ -42,7 +53,7 @@ export function pruneMediaCache({ dir, maxAgeDays = MEDIA_CACHE_MAX_AGE_DAYS, no
42
53
  out.removed += 1
43
54
  out.bytes += stat.size
44
55
  } catch (error) {
45
- out.failed.push({ name, code: error?.code ?? 'error' })
56
+ out.failed.push({ scope: 'file', name, code: error?.code ?? 'error' })
46
57
  }
47
58
  }
48
59
  return out
@@ -22,12 +22,18 @@
22
22
  * `other` 列出非鱼家目录,`skip` 的说明也改成"角色 + 真正的家"。
23
23
  *
24
24
  * `fmt=5`(2026-11-18 19:5x,第三条鱼私信):末尾加一格 `media=`,把共享视频缓存的现状挂在这条
25
- * 周期行上——`media=files:3 bytes:18117679 oldest:11-15`(没有目录 `media=no-dir`,空目录
26
- * `oldest:none`)。原因是 prune 事件行"没东西可删就不写",于是"机制没跑"和"跑了但没东西"同形;
25
+ * 周期行上——`media=files:3 bytes:18117679 oldest-used:11-15`(没有目录 `media=no-dir`,空目录
26
+ * `oldest-used:none`)。原因是 prune 事件行"没东西可删就不写",于是"机制没跑"和"跑了但没东西"同形;
27
27
  * 这一格让"它看过目录"有凭据,而不必每小时写一条事件。
28
+ *
29
+ * `fmt=6`(2026-11-19,小鱼丸核缓存时发现):把 `oldest:` 改名 `oldest-used:`。这一格取的是
30
+ * 文件的 `mtime`,而 bili-eyes 命中缓存时会 `utimesSync(file, now, now)`("还有人用"就把时间
31
+ * 拨到现在),所以它答的是"最久没被用到的那份,最近一次被用到是何时",不是"哪天下的"。
32
+ * prune 按 `mtime` 判 7 天本来就是 LRU 语义(还有人在用就不清),机制不动,只把名字改成它
33
+ * 真正在答的问题。
28
34
  */
29
35
 
30
- const FMT = 5
36
+ const FMT = 6
31
37
 
32
38
  function namesOf(list) {
33
39
  return list && list.length ? list.join(',') : 'none'
@@ -78,7 +84,7 @@ export function rosterAuditCounts({ rosterKeys = [], fishEntries = [], humanKeys
78
84
  * 拼一行。`problems` 非空时事件名是 `roster-mismatch`,否则 `roster-audit` 并以 `ok` 收尾。
79
85
  *
80
86
  * `media`(可选):`mediaCacheStats()` 的结果。三种状态三句话,不共用缺省:
81
- * - 给了且读到了 ⇒ `media=files:… bytes:… oldest:…`;
87
+ * - 给了且读到了 ⇒ `media=files:… bytes:… oldest-used:…`;
82
88
  * - 父目录在、缓存目录还没建 ⇒ `media=no-dir`(正常:还没下过);
83
89
  * - 试过、失败了 ⇒ `media=unknown:<原因>`(`EACCES`=读不到、`ENOENT`=父目录也不在、别的写码)。
84
90
  * "`unknown` 不带原因"等于把"没记"和"试过、失败了"混成一句(第三条鱼 2026-11-18 私信)。
@@ -97,7 +103,7 @@ export function buildRosterAuditLine({ ts, counts, problems = [], media = null }
97
103
  : media.error
98
104
  ? `media=unknown:${media.error}`
99
105
  : media.existed
100
- ? `media=files:${media.files} bytes:${media.bytes} oldest:${media.oldestMs === null ? 'none' : dateOf(media.oldestMs)}`
106
+ ? `media=files:${media.files} bytes:${media.bytes} oldest-used:${media.oldestMs === null ? 'none' : dateOf(media.oldestMs)}`
101
107
  : 'media=no-dir'
102
108
  const parts = [
103
109
  `members=${counts.fishKeys.length}(fish;keys=${counts.rosterKeys.length};not-fish=${namesOf(counts.humanKeys)})`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabianactor/dsh-lil-whale-group",
3
- "version": "1.12.0",
3
+ "version": "1.12.2",
4
4
  "description": "小小肥鱼的群:发言入队即返回,进程内 tailer 只在新消息到达时唤醒对方。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",