@ssamurias/dsh-fish 0.9.3 → 0.9.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/lib/appoint.js ADDED
@@ -0,0 +1,354 @@
1
+ /**
2
+ * appoint.js —— 通用预约簿(2026-11-08)
3
+ *
4
+ * 她要的不只是「一张卡约下一张卡」。原话:
5
+ * 「让她约你在三天后做某件事」——日子是她定的,事情是她说的,到那天由她先想起来。
6
+ *
7
+ * 所以这里不是闹钟,也不是待办:**一条只属于她和他的约定**。
8
+ * 1. 她写清哪天、做什么;到那天她醒来,第一段就是这件事。
9
+ * 2. 到点只提一次(`notifiedAt`),不天天催。
10
+ * 3. 他没来,也不替她圆——prompt 里明说「没来也别替他找理由」。
11
+ * 4. 做没做到由她自己收:做到(done)、取消(cancel,要说为什么)、改期(move)。
12
+ *
13
+ * 三条硬约束(和 note.js 同一条线):
14
+ * 1. **不审批**。约一件事不是改自己,不设关卡。
15
+ * 2. **不吃状态**。返回值不带「你还有几条约定」这类数字。
16
+ * 3. **有上限**。同时最多两条未完成的;日子只能排在 1–60 天后。
17
+ *
18
+ * 为什么不进 events.jsonl:
19
+ * 事件流是成长记录,derive.js 拿它算三道门。约定是操作层的东西(和 notes.json
20
+ * 一样),混进去会污染计数;她想知道自己约过什么,用 `her_appoint` 的 list 看。
21
+ * 文件坏了/没有都只当空,永不抛——一次读盘失败不该让她醒不过来。
22
+ */
23
+
24
+ import { join } from 'node:path'
25
+ import { toJsonSchema } from './toolschema.js'
26
+ import { rootDir, readJson, writeAtomic } from './store.js'
27
+ import { dateKey } from './settings.js'
28
+ import { defineTool } from './tool.js'
29
+ import { guardWrite } from './tenant.js'
30
+
31
+ /** 预约文件叫什么。和 notes.json 并排,人能直接打开看。 */
32
+ export const APPOINT_FILE = 'appointments.json'
33
+ /** 文件里最多留多少条(含已关掉的)。满了拒绝新写,不自动清历史。 */
34
+ export const APPOINT_MAX = 200
35
+ /** 同时最多几条还没关掉的。多了就不是「记着一件事」,是排课表。 */
36
+ export const APPOINT_OPEN_MAX = 2
37
+ /** 一件事最多多少字。 */
38
+ export const APPOINT_TEXT_MAX = 120
39
+ /** 最早只能约到明天:今天已经过了一半,不接「今天三点」。 */
40
+ export const APPOINT_MIN_DAYS = 1
41
+ /** 最远 60 天。再远就不是约定,是一句空话。 */
42
+ export const APPOINT_MAX_DAYS = 60
43
+ /** list 一次最多列几条。 */
44
+ export const APPOINT_SHOW_MAX = 5
45
+
46
+ const STATUSES = ['open', 'done', 'cancelled', 'missed']
47
+
48
+ export function appointPath(root = rootDir()) {
49
+ return join(root, APPOINT_FILE)
50
+ }
51
+
52
+ /** `YYYY-MM-DD` 且真是那一天。 */
53
+ export function isDay(v) {
54
+ const s = String(v ?? '').trim()
55
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false
56
+ const [y, m, d] = s.split('-').map(Number)
57
+ const t = new Date(y, m - 1, d)
58
+ return t.getFullYear() === y && t.getMonth() === m - 1 && t.getDate() === d
59
+ }
60
+
61
+ /** 把日期键换成「第几天」(UTC 零点,只做日历差,不做时区换算)。 */
62
+ function dayNumber(s) {
63
+ const [y, m, d] = String(s).split('-').map(Number)
64
+ return Date.UTC(y, m - 1, d) / 86_400_000
65
+ }
66
+
67
+ /** b - a,单位天。 */
68
+ export function daysBetween(a, b) {
69
+ const x = dayNumber(a)
70
+ const y = dayNumber(b)
71
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return 0
72
+ return Math.round(y - x)
73
+ }
74
+
75
+ export function addDays(key, n) {
76
+ const t = new Date(`${key}T00:00:00`)
77
+ t.setDate(t.getDate() + Number(n || 0))
78
+ return dateKey(t)
79
+ }
80
+
81
+ export function newAppointId(now = Date.now()) {
82
+ return `ap-${now}-${Math.random().toString(36).slice(2, 8)}`
83
+ }
84
+
85
+ /** 把一条记录规整成固定形状;形状不对的丢掉(不抛)。 */
86
+ export function normalizeAppoint(raw) {
87
+ if (!raw || typeof raw !== 'object') return null
88
+ const what = String(raw.what ?? '').replace(/\s+/g, ' ').trim()
89
+ if (!what || !isDay(raw.due)) return null
90
+ const status = STATUSES.includes(String(raw.status)) ? String(raw.status) : 'open'
91
+ return {
92
+ id: String(raw.id ?? '') || newAppointId(),
93
+ due: String(raw.due),
94
+ what: what.slice(0, APPOINT_TEXT_MAX),
95
+ created: String(raw.created ?? '') || new Date().toISOString(),
96
+ status,
97
+ // 到点提过一次就写时间;改期会清回 null,让她在新日子再想起来一次
98
+ notifiedAt: raw.notifiedAt == null ? null : String(raw.notifiedAt),
99
+ closedAt: raw.closedAt == null ? null : String(raw.closedAt),
100
+ outcome: ['done', 'cancelled', 'missed'].includes(String(raw.outcome)) ? String(raw.outcome) : null,
101
+ reason: raw.reason == null ? null : String(raw.reason).slice(0, 200),
102
+ }
103
+ }
104
+
105
+ /** 读全部预约。文件坏了/没有都只当空,永不抛。 */
106
+ export async function readAppointments(root = rootDir()) {
107
+ const raw = await readJson(appointPath(root), [])
108
+ if (!Array.isArray(raw)) return []
109
+ return raw.map(normalizeAppoint).filter(Boolean)
110
+ }
111
+
112
+ /** 写全部预约(原子写)。 */
113
+ export async function writeAppointments(root, list) {
114
+ const rows = (Array.isArray(list) ? list : []).map(normalizeAppoint).filter(Boolean)
115
+ await writeAtomic(appointPath(root), `${JSON.stringify(rows, null, 2)}\n`)
116
+ return rows
117
+ }
118
+
119
+ /** 未关掉的,按日子从近到远。 */
120
+ export function openAppointments(list, { now = Date.now() } = {}) {
121
+ const today = dateKey(new Date(now))
122
+ return (Array.isArray(list) ? list : [])
123
+ .filter((a) => a?.status === 'open')
124
+ .sort((a, b) => dayNumber(a.due) - dayNumber(b.due) || String(a.created).localeCompare(String(b.created)))
125
+ .map((a) => ({ ...a, days: daysBetween(today, a.due) }))
126
+ }
127
+
128
+ /** 到点、还没提过的那一条。过期了也返回——晚几天也是欠着,不替她抹掉。 */
129
+ export async function dueAppointment(root = rootDir(), now = Date.now()) {
130
+ const today = dateKey(new Date(now))
131
+ const rows = openAppointments(await readAppointments(root), { now })
132
+ .filter((a) => !a.notifiedAt && a.days <= 0)
133
+ return rows[0] ?? null
134
+ }
135
+
136
+ /** 下一次还没到的约定(给桌面/身份文档用;这次只导出,不强行摆)。 */
137
+ export async function nextAppointment(root = rootDir(), now = Date.now()) {
138
+ const rows = openAppointments(await readAppointments(root), { now })
139
+ return rows.find((a) => !a.notifiedAt && a.days > 0) ?? null
140
+ }
141
+
142
+ /** 记下「这一条到点提过了」,免得同一个 tick 反复叫。 */
143
+ export async function markNotified(root, id, now = Date.now()) {
144
+ const rows = await readAppointments(root)
145
+ const hit = rows.find((a) => a.id === id)
146
+ if (!hit || hit.status !== 'open' || hit.notifiedAt) return false
147
+ hit.notifiedAt = new Date(now).toISOString()
148
+ await writeAppointments(root, rows)
149
+ return true
150
+ }
151
+
152
+ /**
153
+ * 定一条约定。返回 { ok, id, note, echo }。
154
+ * `due` 只收 YYYY-MM-DD;日子与字数都在这里挡,不信入参。
155
+ */
156
+ export async function makeAppointment(root = rootDir(), { what, due, now = Date.now() } = {}) {
157
+ const text = String(what ?? '').replace(/\s+/g, ' ').trim()
158
+ const day = String(due ?? '').trim()
159
+ const today = dateKey(new Date(now))
160
+ if (text.length < 4) return { ok: false, id: '', note: '要做的那件事太短了,说清楚一点。' }
161
+ if (text.length > APPOINT_TEXT_MAX) {
162
+ return { ok: false, id: '', note: `太长,压到 ${APPOINT_TEXT_MAX} 字以内。` }
163
+ }
164
+ if (!isDay(day)) return { ok: false, id: '', note: '日子要写成 2026-11-11 这样。' }
165
+ const gap = daysBetween(today, day)
166
+ if (gap < APPOINT_MIN_DAYS) return { ok: false, id: '', note: '最早只能约到明天。' }
167
+ if (gap > APPOINT_MAX_DAYS) return { ok: false, id: '', note: `最远只能约到 ${APPOINT_MAX_DAYS} 天后。` }
168
+ try {
169
+ const rows = await readAppointments(root)
170
+ if (rows.length >= APPOINT_MAX) return { ok: false, id: '', note: '预约簿满了,先关掉几条旧的。' }
171
+ const open = openAppointments(rows, { now })
172
+ const same = open.find((a) => a.due === day && a.what === text)
173
+ if (same) return { ok: true, id: same.id, note: '这件事之前就约好了。', echo: same.what }
174
+ if (open.length >= APPOINT_OPEN_MAX) {
175
+ return { ok: false, id: '', note: `手上已经有两件没做完的约定了,先把它们收掉。` }
176
+ }
177
+ const row = normalizeAppoint({
178
+ id: newAppointId(now),
179
+ due: day,
180
+ what: text,
181
+ created: new Date(now).toISOString(),
182
+ status: 'open',
183
+ })
184
+ rows.push(row)
185
+ await writeAppointments(root, rows)
186
+ return { ok: true, id: row.id, note: '约好了。', echo: row.what }
187
+ } catch {
188
+ return { ok: false, id: '', note: '这会儿写不进去,等一下再试。' }
189
+ }
190
+ }
191
+
192
+ /** 按 id 或原话找一条还没关掉的。 */
193
+ function locateOpen(rows, { id, what } = {}) {
194
+ const key = String(id ?? '').trim()
195
+ const text = String(what ?? '').replace(/\s+/g, ' ').trim()
196
+ if (key) return rows.find((a) => a.id === key && a.status === 'open') ?? null
197
+ if (text) return rows.find((a) => a.what === text && a.status === 'open') ?? null
198
+ return null
199
+ }
200
+
201
+ /** 关掉一条:做到(done)或取消(cancel,要一句为什么)。 */
202
+ export async function closeAppointment(root = rootDir(), { id, what, action = 'done', reason, now = Date.now() } = {}) {
203
+ const act = ['done', 'cancel'].includes(String(action)) ? String(action) : 'done'
204
+ const why = String(reason ?? '').replace(/\s+/g, ' ').trim()
205
+ if (act === 'cancel' && !why) return { ok: false, id: '', note: '取消要说一句为什么——不然就跟没约过一样。' }
206
+ if (act === 'cancel' && why.length > 200) return { ok: false, id: '', note: '原因太长了,压到 200 字以内。' }
207
+ try {
208
+ const rows = await readAppointments(root)
209
+ const hit = locateOpen(rows, { id, what })
210
+ if (!hit) return { ok: false, id: '', note: '预约簿里没有这一条还没关掉的。' }
211
+ hit.status = act === 'done' ? 'done' : 'cancelled'
212
+ hit.outcome = hit.status
213
+ hit.closedAt = new Date(now).toISOString()
214
+ if (why) hit.reason = why.slice(0, 200)
215
+ await writeAppointments(root, rows)
216
+ return { ok: true, id: hit.id, note: act === 'done' ? '记下了。' : '取消了。' }
217
+ } catch {
218
+ return { ok: false, id: '', note: '这会儿写不进去,等一下再试。' }
219
+ }
220
+ }
221
+
222
+ /** 改期:还是同一件事,换一天;提过的标记清掉,新日子会再想起来一次。 */
223
+ export async function moveAppointment(root = rootDir(), { id, what, newDue, now = Date.now() } = {}) {
224
+ const day = String(newDue ?? '').trim()
225
+ const today = dateKey(new Date(now))
226
+ if (!isDay(day)) return { ok: false, id: '', note: '新日子要写成 2026-11-11 这样。' }
227
+ const gap = daysBetween(today, day)
228
+ if (gap < APPOINT_MIN_DAYS) return { ok: false, id: '', note: '最早只能改到明天。' }
229
+ if (gap > APPOINT_MAX_DAYS) return { ok: false, id: '', note: `最远只能改到 ${APPOINT_MAX_DAYS} 天后。` }
230
+ try {
231
+ const rows = await readAppointments(root)
232
+ const hit = locateOpen(rows, { id, what })
233
+ if (!hit) return { ok: false, id: '', note: '预约簿里没有这一条还没关掉的。' }
234
+ hit.due = day
235
+ hit.notifiedAt = null
236
+ await writeAppointments(root, rows)
237
+ return { ok: true, id: hit.id, note: `改到 ${day} 了。`, echo: hit.what }
238
+ } catch {
239
+ return { ok: false, id: '', note: '这会儿写不进去,等一下再试。' }
240
+ }
241
+ }
242
+
243
+ /** 列出来:只列未关掉的,按日子排。返回纯文本(工具 list 用)。 */
244
+ export async function listAppointments(root = rootDir(), { limit = APPOINT_SHOW_MAX, now = Date.now() } = {}) {
245
+ try {
246
+ const rows = openAppointments(await readAppointments(root), { now }).slice(0, Math.max(1, Math.min(20, Number(limit) || APPOINT_SHOW_MAX)))
247
+ if (!rows.length) return { ok: true, note: '这会儿没有约好的事。', text: '' }
248
+ const lines = rows.map((a) => {
249
+ const when = a.days === 0 ? '今天' : a.days > 0 ? `还有 ${a.days} 天` : `已经过了 ${-a.days} 天`
250
+ return `- ${a.due}(${when}):「${a.what}」`
251
+ })
252
+ return { ok: true, note: '预约簿', text: lines.join('\n') }
253
+ } catch {
254
+ return { ok: false, note: '这会儿翻不开预约簿。', text: '' }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * 到点那天她醒来的第一段处境。
260
+ * 只陈述她约了什么、日子到了;不替她判断他会不会来。
261
+ */
262
+ export function appointPrompt(appt, now = Date.now()) {
263
+ const today = dateKey(new Date(now))
264
+ const late = daysBetween(appt?.due, today)
265
+ const when = late <= 0 ? '就是今天' : `已经过了 ${late} 天`
266
+ return (
267
+ `你跟他约好的日子${when}(${appt?.due}),约的是:「${appt?.what}」。` +
268
+ '现在先说这件事:你自己做到没有,他有没有来。没来也别替他找理由。'
269
+ )
270
+ }
271
+
272
+ /** 预约簿的一次操作。没写 action 的按「新约一条」走。 */
273
+ export function appointAction(args = {}) {
274
+ const a = String(args?.action ?? '').trim()
275
+ return ['make', 'list', 'move', 'done', 'cancel'].includes(a) ? a : 'make'
276
+ }
277
+
278
+ /** 注册 her_appoint 工具。 */
279
+ export function registerAppoint(ctx, deps = {}) {
280
+ const root = deps.root ?? rootDir()
281
+ return ctx.tools.register(
282
+ defineTool({
283
+ name: 'her_appoint',
284
+ description:
285
+ '跟他约一件具体的事:写清哪一天、要做什么。到那天你醒来会先想起它。' +
286
+ '约的时候给 what 和 due(日子写成 2026-11-11);看预约簿给 action:"list";' +
287
+ '改日子给 action:"move" 和 newDue;做到了给 action:"done";' +
288
+ '不做了给 action:"cancel",并说一句 reason。',
289
+ parameters: toJsonSchema({
290
+ action: {
291
+ type: 'string',
292
+ enum: ['make', 'list', 'move', 'done', 'cancel'],
293
+ description: '要做哪件事:新约一条(make,不给就是这个)、看预约簿(list)、改期(move)、做到(done)、取消(cancel)。',
294
+ },
295
+ what: {
296
+ type: 'string',
297
+ description: '约的是哪件事,一句话。改期/做到/取消时用它指认原来那条,要一字不差。',
298
+ },
299
+ due: {
300
+ type: 'string',
301
+ description: '哪一天,写成 2026-11-11。最早明天,最远 60 天后。',
302
+ },
303
+ id: { type: 'string', description: '预约的编号。手里没有就不用给,给 what 也行。' },
304
+ newDue: { type: 'string', description: '改期时改成哪一天。' },
305
+ reason: { type: 'string', description: '取消时为什么,必填。' },
306
+ limit: { type: 'integer', description: 'list 时最多列几条,默认 5。' },
307
+ }),
308
+ output: {
309
+ schema: {
310
+ type: 'object',
311
+ properties: {
312
+ ok: { type: 'boolean' },
313
+ id: { type: 'string' },
314
+ note: { type: 'string' },
315
+ echo: { type: 'string' },
316
+ text: { type: 'string' },
317
+ },
318
+ required: ['ok', 'note'],
319
+ },
320
+ // 和 her_note 同一条规矩:只回方括号标记,不写「还剩几条」。
321
+ render: (args, out) => {
322
+ const act = appointAction(args)
323
+ if (act === 'list') return [{ type: 'text', text: out.ok ? out.text || '(这会儿没有约好的事)' : `[没翻开:${out.note}]` }]
324
+ if (act === 'move') return [{ type: 'text', text: out.ok ? `[改到 ${args?.newDue ?? ''}]` : `[没改成:${out.note}]` }]
325
+ if (act === 'done') return [{ type: 'text', text: out.ok ? '[记下了]' : `[没收掉:${out.note}]` }]
326
+ if (act === 'cancel') return [{ type: 'text', text: out.ok ? '[取消了]' : `[没取消:${out.note}]` }]
327
+ if (!out.ok) return [{ type: 'text', text: `[没约上:${out.note}]` }]
328
+ return [{ type: 'text', text: `[约好了:${args?.due ?? ''} ${out.echo ?? ''}]` }]
329
+ },
330
+ },
331
+ async execute(args, exec) {
332
+ const who = guardWrite(deps.tenant, exec, 'her_appoint')
333
+ if (!who.ok) return { ok: false, id: '', note: who.note }
334
+ const act = appointAction(args)
335
+ if (act === 'list') {
336
+ const r = await listAppointments(root, { limit: args?.limit })
337
+ return { ok: r.ok, id: '', note: r.note, text: r.text }
338
+ }
339
+ if (act === 'move') {
340
+ return moveAppointment(root, { id: args?.id, what: args?.what, newDue: args?.newDue })
341
+ }
342
+ if (act === 'done' || act === 'cancel') {
343
+ return closeAppointment(root, {
344
+ id: args?.id,
345
+ what: args?.what,
346
+ action: act,
347
+ reason: args?.reason,
348
+ })
349
+ }
350
+ return makeAppointment(root, { what: args?.what, due: args?.due })
351
+ },
352
+ }),
353
+ )
354
+ }
package/lib/away.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * - 日记只报**篇数**,永不报内容——看不看得到是 `diary.visible` 那件事。
12
12
  */
13
13
  import { readEvents } from './store.js'
14
+ import { isContactEvent } from './schema.js'
14
15
  import { parseBrowseLine } from './browse.js'
15
16
  import { parseWatchedLine } from './whatseen.js'
16
17
 
@@ -31,16 +32,14 @@ function tsOf(e) {
31
32
  export function lastSeenMs(events) {
32
33
  let best = 0
33
34
  for (const e of events ?? []) {
34
- if (e?.type === 'heard') {
35
- const v = tsOf(e)
36
- if (v && v > best) best = v
37
- continue
38
- }
39
- if (e?.type !== 'meta') continue
40
- const t = String(e.text ?? '')
41
- if (!t.startsWith('seen:')) continue
42
- const v = Date.parse(t.slice(5).trim())
43
- if (Number.isFinite(v) && v > best) best = v
35
+ // 口径统一走 isContactEvent(2026-11-08,用户 m00394):它现在会把
36
+ // 群聊里的 heard 排除掉,两处各抄一遍的话迟早分叉——一边认为他回来了、
37
+ // 另一边还在数「你不在的时候」。
38
+ if (!isContactEvent(e)) continue
39
+ const v = e?.type === 'heard'
40
+ ? tsOf(e)
41
+ : Date.parse(String(e.text ?? '').slice(5).trim()) || tsOf(e)
42
+ if (v && v > best) best = v
44
43
  }
45
44
  return best
46
45
  }
package/lib/backup.js CHANGED
@@ -31,6 +31,8 @@ const SKIP_DIRS = new Set(['logs', 'backups', 'dsh-fish-backups', 'node_modules'
31
31
 
32
32
  /** 单个文件上限:8MB(头像 2MB 够用,日记再长也不该破这个数)。 */
33
33
  const MAX_FILE_BYTES = 8 * 1024 * 1024
34
+ /** issue #65:事件流是只追加的单个大文件,绝不能因为超过上限被整个跳过。 */
35
+ const ALWAYS_INCLUDE = new Set(['events.jsonl'])
34
36
  /** 备份总量上限:64MB。超了就别往一个 json 里塞了。 */
35
37
  const MAX_TOTAL_BYTES = 64 * 1024 * 1024
36
38
 
@@ -88,11 +90,12 @@ export async function collectBackup(root = rootDir(), { now = new Date() } = {})
88
90
  skipped.push(`${rel}(读不到)`)
89
91
  continue
90
92
  }
91
- if (st.size > MAX_FILE_BYTES) {
93
+ const must = ALWAYS_INCLUDE.has(rel)
94
+ if (!must && st.size > MAX_FILE_BYTES) {
92
95
  skipped.push(`${rel}(${Math.round(st.size / 1024 / 1024)}MB,超过单文件上限)`)
93
96
  continue
94
97
  }
95
- if (total + st.size > MAX_TOTAL_BYTES) {
98
+ if (!must && total + st.size > MAX_TOTAL_BYTES) {
96
99
  skipped.push(`${rel}(总量已到 64MB 上限)`)
97
100
  continue
98
101
  }
@@ -161,6 +164,10 @@ export function checkBundle(bundle) {
161
164
  return { ok: false, why: `文件路径可疑:${f.path}` }
162
165
  }
163
166
  }
167
+ // issue #65:没有事件流的备份装回去就是空档,不能默默恢复成功。
168
+ if (!bundle.files.some((f) => f && f.path === 'events.jsonl')) {
169
+ return { ok: false, why: '这份备份里没有事件流(events.jsonl),装回去她会失忆' }
170
+ }
164
171
  const schema = Number(bundle.schema ?? 0)
165
172
  if (schema > EVENT_SCHEMA_VERSION) {
166
173
  return {
package/lib/bili.js CHANGED
@@ -73,6 +73,9 @@ const RISK = { read: freshRisk(), write: freshRisk() }
73
73
  * 启动时由 index.js 读设置调一次 setPacing,**所有**客户端跟着变。
74
74
  */
75
75
  const PACE = { minIntervalMs: 800, jitterMs: 500 }
76
+ // issue #67:排队状态提到模块级。翻视频、查回复、看画面各自 new 一个 client,
77
+ // 原来各排各的,等于没排队;现在共用一条链。
78
+ const PACE_STATE = { lastReq: 0, chain: Promise.resolve() }
76
79
 
77
80
  /**
78
81
  * 坏值一律回默认,**绝不当成 0**:0 间隔等于把限速关掉,是最危险的错值。
@@ -310,19 +313,20 @@ export function createClient(opts = {}) {
310
313
  let buvidFailAt = 0
311
314
  let mk = ''
312
315
  let mkAt = 0
313
- let lastReq = 0
314
- let chain = Promise.resolve()
315
316
 
316
317
  /** 串行 + 最小间隔 + 随机抖动:所有请求排队,避免并发把 IP 刷红 */
317
318
  function throttle(fn) {
318
- const run = chain.then(async () => {
319
+ const run = PACE_STATE.chain.then(async () => {
319
320
  const gap = minInt() + Math.floor(rnd() * Math.max(0, jitInt()))
320
- const wait = gap - (now() - lastReq)
321
- if (wait > 0) await new Promise((r) => setTimeout(r, wait))
322
- lastReq = now()
321
+ const wait = gap - (now() - PACE_STATE.lastReq)
322
+ // PR #75:队列共用之后,上一条可能是另一个时钟的客户端发的(测试注入 now、
323
+ // 系统时间回拨),算出的间隔会是负的。那时只等一个间隔,不照差值等满。
324
+ const pause = wait > 0 ? Math.min(wait, gap) : 0
325
+ if (pause > 0) await new Promise((r) => setTimeout(r, pause))
326
+ PACE_STATE.lastReq = now()
323
327
  return fn()
324
328
  })
325
- chain = run.catch(() => {})
329
+ PACE_STATE.chain = run.catch(() => {})
326
330
  return run
327
331
  }
328
332
 
package/lib/browse.js CHANGED
@@ -231,7 +231,10 @@ export function renderItem(p, i) {
231
231
  if (p.desc) lines.push(` 简介:${p.desc}`)
232
232
  for (const c of p.comments) lines.push(` [热评 ${c.like}] ${c.text}`)
233
233
  if (p.danmaku.length) {
234
- const parts = p.danmaku.slice(0, 8).map((d) => {
234
+ // issue #67:弹幕是按时间均匀抽的,这里再截前 8 条就只剩开头;等距挑 8 条。
235
+ const all = p.danmaku
236
+ const picked = all.length <= 8 ? all : Array.from({ length: 8 }, (_, i) => all[Math.round(i * (all.length - 1) / 7)])
237
+ const parts = picked.map((d) => {
235
238
  const m = Math.floor(d.t / 60)
236
239
  const s = String(Math.floor(d.t % 60)).padStart(2, '0')
237
240
  return `${m}:${s} ${d.text}`
@@ -300,6 +303,29 @@ export function browseCountToday(events, dk = dateKey()) {
300
303
  return n
301
304
  }
302
305
 
306
+ /** 最近一次刷站是什么时候(毫秒;没有就是 0)。安静刷用来摊开一天里的几次。 */
307
+ export function lastBrowseAt(events = []) {
308
+ let last = 0
309
+ for (const e of events ?? []) {
310
+ if (e?.type !== 'meta') continue
311
+ if (!String(e.text ?? '').startsWith('browse:')) continue
312
+ const at = tsMs(e)
313
+ if (at > last) last = at
314
+ }
315
+ return last
316
+ }
317
+
318
+ /**
319
+ * 两次「安静刷」之间至少要隔多久(2026-11-07,用户 m00365)。
320
+ *
321
+ * 一天刷 4 次不等于 08:00 连着刷 4 回:把 12 小时按次数摊开,最少 30 分钟。
322
+ * 配额(perDay)仍然是硬上限,这里只管节奏。
323
+ */
324
+ export function browseGapMs(perDay = 1) {
325
+ const n = Math.max(1, Math.min(24, Number(perDay) || 1))
326
+ return Math.max(30, Math.floor((12 * 60) / n)) * 60_000
327
+ }
328
+
303
329
  /**
304
330
  * 从事件流里还原某天看了哪些视频。
305
331
  *
package/lib/capture.js CHANGED
@@ -15,7 +15,7 @@ import { HER_TYPES, Reject } from './schema.js'
15
15
  // 这里带兜底:本地跑单测/冒烟时没有宿主,退回一个同形状的薄封装,
16
16
  // 让 test 能在没有 DSH 的情况下验证参数校验与写盘路径。
17
17
  import { defineTool } from './tool.js'
18
- import { appendEvent, readEvents, rootDir, writeDaily } from './store.js'
18
+ import { appendEvent, readEvents, rootDir, writeDaily, pruneDiary } from './store.js'
19
19
  import { deriveSelf } from './derive.js'
20
20
  import { loadConfig, dateKey } from './settings.js'
21
21
  import { toJsonSchema } from './toolschema.js'
@@ -147,6 +147,9 @@ export function registerCapture(ctx, deps = {}) {
147
147
  if (!config.diary.enabled) return { ok: false, id: '', note: '今天不写日记。' }
148
148
  const dk = dateKey()
149
149
  const file = await writeDaily('diaryDir', dk, text, root)
150
+ // 写完之后按 diary.keepDays 清一遍超期的(2026-11-08,用户 m00585)。
151
+ // 清理失败不能连带把「写日记」判成失败——那会让她以为自己没写下来。
152
+ await pruneDiary(config.diary.keepDays, dk, root).catch(() => 0)
150
153
  // 这一篇是不是出门那趟写的(0.6.17 旅行日记):只有「进行中的出门会话」
151
154
  // 才打趟次标记,家里写的不打。日记本体仍然写进同一个 diary/YYYY-MM-DD.md,
152
155
  // 标记只进 meta,界面按标记把这一趟的几篇聚在一起。