dsh-ta 0.3.0 → 0.4.0
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/CHANGELOG.md +90 -0
- package/README.md +160 -107
- package/cordis.patch.yml +5 -35
- package/docs/RELEASE.md +62 -49
- package/docs/USAGE.md +6 -7
- package/docs/presets.example.yml +7 -43
- package/index.js +3 -164
- package/package.json +5 -28
- package/src/client/client.js +3176 -0
- package/{config.js → src/host/config.js} +39 -3
- package/src/host/constants.js +7 -0
- package/src/host/gates.js +34 -0
- package/src/host/identity.js +145 -0
- package/{im → src/host/im}/bindings.js +1 -1
- package/src/host/index.js +173 -0
- package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
- package/src/host/maintenance/collect.js +362 -0
- package/src/host/maintenance/completions.js +56 -0
- package/src/host/maintenance/consumption.js +67 -0
- package/src/host/maintenance/cursors.js +53 -0
- package/src/host/maintenance/engine.js +392 -0
- package/src/host/maintenance/llm.js +381 -0
- package/src/host/maintenance/lock.js +105 -0
- package/src/host/maintenance/prompts.js +255 -0
- package/src/host/maintenance/runs.js +47 -0
- package/src/host/maintenance/schedule.js +173 -0
- package/src/host/maintenance/session-cleanup.js +289 -0
- package/src/host/maintenance/session-watcher.js +107 -0
- package/src/host/maintenance/sleep.js +3 -0
- package/src/host/maintenance/stages.js +241 -0
- package/src/host/maintenance/state.js +192 -0
- package/src/host/prompts.js +96 -0
- package/src/host/records.js +175 -0
- package/src/host/runtime-manager.js +281 -0
- package/{runtime.js → src/host/runtime.js} +6 -8
- package/src/host/settings/defaults.js +55 -0
- package/{settings → src/host/settings}/home.js +4 -3
- package/{settings/routes.js → src/host/settings/http.js} +5 -137
- package/{settings → src/host/settings}/im.js +18 -1
- package/{settings → src/host/settings}/lifecycle.js +29 -43
- package/src/host/settings/persona.js +113 -0
- package/src/host/settings/routes.js +229 -0
- package/{settings → src/host/settings}/status.js +70 -42
- package/src/host/state/appraisals.js +56 -0
- package/src/host/state/feel.js +78 -0
- package/src/host/state/index.js +9 -0
- package/src/host/state/mood.js +103 -0
- package/src/host/state/notes.js +18 -0
- package/{life.js → src/host/state/outing.js} +13 -136
- package/src/host/state/values.js +9 -0
- package/{stickers → src/host/stickers}/tool.js +1 -1
- package/src/host/storage/fs.js +29 -0
- package/src/host/storage/index.js +8 -0
- package/src/host/storage/paths.js +20 -0
- package/src/host/storage/revision.js +5 -0
- package/src/host/storage/session-state.js +38 -0
- package/src/host/storage/time.js +127 -0
- package/src/host/tools/index.js +152 -0
- package/src/host/tools/read.js +252 -0
- package/src/host/tools/shared.js +23 -0
- package/src/host/tools/wiki.js +35 -0
- package/src/host/tools/write.js +164 -0
- package/{usage → src/host/usage}/aggregate.js +4 -1
- package/{usage → src/host/usage}/ledger.js +47 -21
- package/client.js +0 -2554
- package/gates.js +0 -18
- package/identity.js +0 -97
- package/prompts.js +0 -28
- package/runtime-manager.js +0 -153
- package/settings/defaults.js +0 -41
- package/settings/persona.js +0 -203
- package/settings/schedule.js +0 -156
- package/storage.js +0 -122
- package/tools.js +0 -540
- /package/{im → src/host/im}/say.js +0 -0
- /package/{memory → src/host/memory}/capture.js +0 -0
- /package/{memory → src/host/memory}/messages.js +0 -0
- /package/{memory → src/host/memory}/outbox.js +0 -0
- /package/{reme.js → src/host/reme.js} +0 -0
- /package/{settings → src/host/settings}/errors.js +0 -0
- /package/{stickers → src/host/stickers}/load.js +0 -0
- /package/{stickers → src/host/stickers}/select.js +0 -0
- /package/{stickers → src/host/stickers}/serve.js +0 -0
- /package/{usage → src/host/usage}/pricing.js +0 -0
- /package/{usage → src/host/usage}/serve.js +0 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 维护素材收集:聊天、出门、日记、笔记、ReMe、纠正、情绪。
|
|
3
|
+
*
|
|
4
|
+
* 约束(见修复方案 §3.2):
|
|
5
|
+
* - 聊天只取 cwd=TA_HOME 的普通 ta 会话,按 session × 本地日切片;
|
|
6
|
+
* - 每片 ≤ 4,000 字、总素材 ≤ 12,000 字,超出按时间倒序截断;
|
|
7
|
+
* - 只用 captureMessage(已过滤非 user/plugin/runtime-context);
|
|
8
|
+
* - 每个素材有稳定 id,已消费素材仍进候选,但带 consumedFor 标明。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createHash } from 'node:crypto'
|
|
12
|
+
import { readFileSync, readdirSync } from 'node:fs'
|
|
13
|
+
import { resolve } from 'node:path'
|
|
14
|
+
import { captureMessage } from '../memory/messages.js'
|
|
15
|
+
import {
|
|
16
|
+
addLocalDays, internalSessionIds, localClockText, localDateText, sha256Revision, startOfLocalDay,
|
|
17
|
+
} from '../storage/index.js'
|
|
18
|
+
import { advanceCursor, lastSeqOf } from './cursors.js'
|
|
19
|
+
import { consumedTargets } from './consumption.js'
|
|
20
|
+
|
|
21
|
+
export const CHAT_BUCKET_LIMIT = 4000
|
|
22
|
+
export const MATERIAL_TOTAL_LIMIT = 12000
|
|
23
|
+
export const MAX_SESSIONS_PER_RUN = 20
|
|
24
|
+
export const MAX_MESSAGES_PER_BUCKET = 400
|
|
25
|
+
|
|
26
|
+
const IM_SESSION_PREFIX = 'dsh-im-session-'
|
|
27
|
+
|
|
28
|
+
export function isImSessionId(sessionId) {
|
|
29
|
+
return String(sessionId ?? '').startsWith(IM_SESSION_PREFIX)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function readTextIfFile(path) {
|
|
33
|
+
try {
|
|
34
|
+
return readFileSync(path, 'utf8')
|
|
35
|
+
} catch {
|
|
36
|
+
return null
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function hashOf(text) {
|
|
41
|
+
return createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function fileMaterial(config, relative, content, { kind, untrusted = false, extra = {} } = {}) {
|
|
45
|
+
const text = String(content ?? '').trim()
|
|
46
|
+
if (!text) return null
|
|
47
|
+
return {
|
|
48
|
+
id: extra.id ?? `file:${relative}@${sha256Revision(text)}`,
|
|
49
|
+
kind,
|
|
50
|
+
chars: text.length,
|
|
51
|
+
text,
|
|
52
|
+
path: relative,
|
|
53
|
+
untrusted,
|
|
54
|
+
...extra,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function headerOf(record) {
|
|
59
|
+
return record?.header ?? record ?? {}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 收集聊天素材。
|
|
64
|
+
*
|
|
65
|
+
* 返回 { materials, cursors, warnings };cursors 只在调用方确认整次运行成功后才写回。
|
|
66
|
+
*/
|
|
67
|
+
export async function collectChatMaterials({
|
|
68
|
+
config, query, cursors, consumption, nowMs = Date.now(), runDate, imMode = 'owner',
|
|
69
|
+
}) {
|
|
70
|
+
const warnings = []
|
|
71
|
+
const nextCursors = { version: 1, sessions: { ...(cursors?.sessions ?? {}) } }
|
|
72
|
+
const materials = []
|
|
73
|
+
if (!query || typeof query.filterSessions !== 'function' || typeof query.listEvents !== 'function') {
|
|
74
|
+
return { materials, cursors: nextCursors, warnings: ['sessionQuery 不可用,聊天素材被跳过'] }
|
|
75
|
+
}
|
|
76
|
+
const windowStart = startOfLocalDay(config, runDate)
|
|
77
|
+
let records = []
|
|
78
|
+
try {
|
|
79
|
+
records = await query.filterSessions([{ kind: 'cwd', values: [config.taHome] }])
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return { materials, cursors: nextCursors, warnings: [`会话列举失败:${error?.message ?? error}`] }
|
|
82
|
+
}
|
|
83
|
+
const internal = internalSessionIds(config)
|
|
84
|
+
const eligible = []
|
|
85
|
+
for (const record of records) {
|
|
86
|
+
const header = headerOf(record)
|
|
87
|
+
if (typeof header.id !== 'string' || !header.id) continue
|
|
88
|
+
if (header.origin !== undefined) continue
|
|
89
|
+
if (header.agentPreset !== 'ta') continue
|
|
90
|
+
if (internal.has(header.id)) continue
|
|
91
|
+
const imSession = isImSessionId(header.id)
|
|
92
|
+
if (imSession && imMode !== 'owner') continue
|
|
93
|
+
eligible.push({ header, imSession, createdAt: Number(header.createdAt) || 0 })
|
|
94
|
+
}
|
|
95
|
+
eligible.sort((left, right) => right.createdAt - left.createdAt)
|
|
96
|
+
const selected = eligible.slice(0, MAX_SESSIONS_PER_RUN)
|
|
97
|
+
if (eligible.length > selected.length) {
|
|
98
|
+
warnings.push(`会话超过 ${MAX_SESSIONS_PER_RUN} 个,只取最近创建的 ${MAX_SESSIONS_PER_RUN} 个`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
for (const { header } of selected) {
|
|
102
|
+
const sessionId = header.id
|
|
103
|
+
let events = []
|
|
104
|
+
try {
|
|
105
|
+
events = await query.listEvents(sessionId)
|
|
106
|
+
} catch (error) {
|
|
107
|
+
warnings.push(`会话 ${sessionId} 事件列举失败:${error?.message ?? error}`)
|
|
108
|
+
continue
|
|
109
|
+
}
|
|
110
|
+
if (!Array.isArray(events) || events.length === 0) continue
|
|
111
|
+
const lastSeq = lastSeqOf(cursors, sessionId)
|
|
112
|
+
const candidates = events.filter(event => (
|
|
113
|
+
event
|
|
114
|
+
&& ['user/message', 'assistant/message'].includes(event.type)
|
|
115
|
+
&& Number.isSafeInteger(event.seq)
|
|
116
|
+
&& event.seq > lastSeq
|
|
117
|
+
&& Number.isFinite(event.time)
|
|
118
|
+
&& event.time >= windowStart
|
|
119
|
+
))
|
|
120
|
+
// 从最新消息往前取,控制单次读会话事件的成本。
|
|
121
|
+
const capped = candidates.slice(-MAX_MESSAGES_PER_BUCKET)
|
|
122
|
+
const truncatedMessages = capped.length < candidates.length
|
|
123
|
+
const messages = []
|
|
124
|
+
for (const event of capped) {
|
|
125
|
+
try {
|
|
126
|
+
const window = await query.readEvent({ sessionId, seq: event.seq })
|
|
127
|
+
const message = captureMessage(window?.target ?? event, sessionId)
|
|
128
|
+
if (!message) continue
|
|
129
|
+
const text = message.content?.[0]?.text
|
|
130
|
+
if (!text) continue
|
|
131
|
+
messages.push({
|
|
132
|
+
seq: event.seq,
|
|
133
|
+
time: event.time,
|
|
134
|
+
role: message.role,
|
|
135
|
+
text,
|
|
136
|
+
})
|
|
137
|
+
} catch (error) {
|
|
138
|
+
warnings.push(`会话 ${sessionId} #${event.seq} 读取失败:${error?.message ?? error}`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const maxSeq = Math.max(...events.map(event => (Number.isSafeInteger(event.seq) ? event.seq : -1)))
|
|
142
|
+
advanceCursor(nextCursors, sessionId, { lastSeq: maxSeq, at: new Date(nowMs).toISOString() })
|
|
143
|
+
if (messages.length === 0) continue
|
|
144
|
+
|
|
145
|
+
const byDate = new Map()
|
|
146
|
+
for (const message of messages) {
|
|
147
|
+
const date = localDateText(config, message.time)
|
|
148
|
+
const bucket = byDate.get(date) ?? []
|
|
149
|
+
bucket.push(message)
|
|
150
|
+
byDate.set(date, bucket)
|
|
151
|
+
}
|
|
152
|
+
for (const [date, bucket] of byDate) {
|
|
153
|
+
const lines = bucket
|
|
154
|
+
.sort((left, right) => left.seq - right.seq)
|
|
155
|
+
.map(message => {
|
|
156
|
+
const clock = localClockText(config, message.time)
|
|
157
|
+
const speaker = message.role === 'user' ? '对方' : '我'
|
|
158
|
+
return `[${clock}] ${speaker}:${message.text.replace(/\s+/g, ' ').trim()}`
|
|
159
|
+
})
|
|
160
|
+
let kept = lines
|
|
161
|
+
let truncated = truncatedMessages
|
|
162
|
+
let text = kept.join('\n')
|
|
163
|
+
while (text.length > CHAT_BUCKET_LIMIT && kept.length > 1) {
|
|
164
|
+
kept = kept.slice(1)
|
|
165
|
+
truncated = true
|
|
166
|
+
text = kept.join('\n')
|
|
167
|
+
}
|
|
168
|
+
const id = `chat:${sessionId}:${date}`
|
|
169
|
+
materials.push({
|
|
170
|
+
id,
|
|
171
|
+
kind: 'chat',
|
|
172
|
+
chars: text.length,
|
|
173
|
+
text,
|
|
174
|
+
sessionId,
|
|
175
|
+
date,
|
|
176
|
+
truncated,
|
|
177
|
+
consumedFor: consumedTargets(consumption, id),
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return { materials, cursors: nextCursors, warnings }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function collectOutingMaterials(config, { runDate } = {}) {
|
|
185
|
+
const materials = []
|
|
186
|
+
let names = []
|
|
187
|
+
try {
|
|
188
|
+
names = readdirSync(resolve(config.taHome, 'outings'))
|
|
189
|
+
} catch {
|
|
190
|
+
return materials
|
|
191
|
+
}
|
|
192
|
+
for (const name of names.sort()) {
|
|
193
|
+
if (!/^\d{4}-\d{2}-\d{2}-.*\.md$/.test(name)) continue
|
|
194
|
+
const relative = `outings/${name}`
|
|
195
|
+
const text = readTextIfFile(resolve(config.taHome, relative))
|
|
196
|
+
if (!text) continue
|
|
197
|
+
const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? ''
|
|
198
|
+
const date = /^date:\s*(.+)$/m.exec(frontmatter)?.[1]?.trim() ?? name.slice(0, 10)
|
|
199
|
+
if (runDate && date !== runDate && name.slice(0, 10) !== runDate) continue
|
|
200
|
+
const id = /^id:\s*(.+)$/m.exec(frontmatter)?.[1]?.trim()
|
|
201
|
+
const untrusted = /^untrusted:\s*true$/m.test(frontmatter)
|
|
202
|
+
const material = fileMaterial(config, relative, text, {
|
|
203
|
+
kind: 'outing',
|
|
204
|
+
untrusted,
|
|
205
|
+
extra: { date },
|
|
206
|
+
})
|
|
207
|
+
if (material) {
|
|
208
|
+
if (id) material.id = `outing:${id}`
|
|
209
|
+
materials.push(material)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return materials
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 周更素材:最近 7 天的日记,按文件 hash 生成稳定 id。 */
|
|
216
|
+
export function collectDiaryMaterials(config, { dates = [], exclude = new Set() } = {}) {
|
|
217
|
+
const materials = []
|
|
218
|
+
for (const date of dates) {
|
|
219
|
+
if (exclude.has(date)) continue
|
|
220
|
+
const relative = `diary/${date}.md`
|
|
221
|
+
const text = readTextIfFile(resolve(config.taHome, relative))
|
|
222
|
+
if (!text) continue
|
|
223
|
+
const material = fileMaterial(config, relative, text, { kind: 'diary', extra: { date } })
|
|
224
|
+
if (material) materials.push(material)
|
|
225
|
+
}
|
|
226
|
+
return materials
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function collectNoteMaterials(config) {
|
|
230
|
+
const relative = 'notes/note.md'
|
|
231
|
+
const text = readTextIfFile(resolve(config.taHome, relative))
|
|
232
|
+
if (!text) return []
|
|
233
|
+
const lines = text.split(/\r?\n/).filter(Boolean).slice(-80)
|
|
234
|
+
const trimmed = lines.join('\n').trim()
|
|
235
|
+
if (!trimmed) return []
|
|
236
|
+
const material = fileMaterial(config, relative, trimmed, { kind: 'note' })
|
|
237
|
+
return material ? [material] : []
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function collectCorrectionMaterials(config, { consumption } = {}) {
|
|
241
|
+
let value
|
|
242
|
+
try {
|
|
243
|
+
value = JSON.parse(readTextIfFile(resolve(config.taHome, 'state/pending-corrections.json')) ?? '{}')
|
|
244
|
+
} catch {
|
|
245
|
+
return []
|
|
246
|
+
}
|
|
247
|
+
const items = Array.isArray(value?.items) ? value.items : []
|
|
248
|
+
return items
|
|
249
|
+
.filter(item => item && item.integrated !== true && typeof item.text === 'string' && item.text.trim())
|
|
250
|
+
.map(item => {
|
|
251
|
+
const id = typeof item.id === 'string' && item.id ? item.id : `correction:${hashOf(item.text).slice(0, 12)}`
|
|
252
|
+
const text = item.text.trim()
|
|
253
|
+
return {
|
|
254
|
+
id,
|
|
255
|
+
kind: 'correction',
|
|
256
|
+
chars: text.length,
|
|
257
|
+
text: `${item.kind ? `[${item.kind}] ` : ''}${text}`,
|
|
258
|
+
consumedFor: consumedTargets(consumption, id),
|
|
259
|
+
}
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function collectAppraisalMaterials(config, { runDate, consumption } = {}) {
|
|
264
|
+
const text = readTextIfFile(resolve(config.taHome, 'state/appraisals.jsonl'))
|
|
265
|
+
if (!text) return []
|
|
266
|
+
const materials = []
|
|
267
|
+
for (const line of text.split(/\r?\n/)) {
|
|
268
|
+
if (!line.trim()) continue
|
|
269
|
+
try {
|
|
270
|
+
const value = JSON.parse(line)
|
|
271
|
+
if (!value || typeof value !== 'object') continue
|
|
272
|
+
const at = Date.parse(value.at ?? '')
|
|
273
|
+
if (!Number.isFinite(at)) continue
|
|
274
|
+
if (runDate && localDateText(config, at) !== runDate) continue
|
|
275
|
+
const id = typeof value.id === 'string' && value.id ? value.id : `appraisal:${hashOf(line).slice(0, 12)}`
|
|
276
|
+
const summary = [value.event, value.why].filter(part => typeof part === 'string' && part.trim()).join(';')
|
|
277
|
+
if (!summary) continue
|
|
278
|
+
materials.push({
|
|
279
|
+
id,
|
|
280
|
+
kind: 'appraisal',
|
|
281
|
+
chars: summary.length,
|
|
282
|
+
text: `${summary}(${value.label ?? ''}${Number.isFinite(value.valence) ? `,valence ${value.valence}` : ''})`.trim(),
|
|
283
|
+
consumedFor: consumedTargets(consumption, id),
|
|
284
|
+
})
|
|
285
|
+
} catch {
|
|
286
|
+
/* 损坏行跳过 */
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return materials
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 按总预算裁剪:保留非聊天素材,聊天素材按时间从新到旧吃剩余预算。
|
|
294
|
+
* 返回 { materials, dropped }。
|
|
295
|
+
*/
|
|
296
|
+
export function trimMaterialsToBudget(materials, { limit = MATERIAL_TOTAL_LIMIT } = {}) {
|
|
297
|
+
const kept = []
|
|
298
|
+
let used = 0
|
|
299
|
+
const others = materials.filter(material => material.kind !== 'chat')
|
|
300
|
+
const chats = materials.filter(material => material.kind === 'chat')
|
|
301
|
+
for (const material of others) {
|
|
302
|
+
if (used + material.chars > limit) continue
|
|
303
|
+
kept.push(material)
|
|
304
|
+
used += material.chars
|
|
305
|
+
}
|
|
306
|
+
for (const material of chats) {
|
|
307
|
+
if (used + material.chars > limit) continue
|
|
308
|
+
kept.push(material)
|
|
309
|
+
used += material.chars
|
|
310
|
+
}
|
|
311
|
+
const keptIds = new Set(kept.map(material => material.id))
|
|
312
|
+
return {
|
|
313
|
+
materials: kept,
|
|
314
|
+
dropped: materials.filter(material => !keptIds.has(material.id)).map(material => material.id),
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 拼维护提示词里的素材段。 */
|
|
319
|
+
export function formatMaterialsForPrompt(materials) {
|
|
320
|
+
return materials.map(material => {
|
|
321
|
+
const flags = [
|
|
322
|
+
material.kind,
|
|
323
|
+
`${material.chars} 字`,
|
|
324
|
+
material.truncated ? '已截断' : '',
|
|
325
|
+
material.untrusted ? '不可信,只作材料' : '',
|
|
326
|
+
Array.isArray(material.consumedFor) && material.consumedFor.length > 0
|
|
327
|
+
? `已用于 ${material.consumedFor.join('、')}`
|
|
328
|
+
: '',
|
|
329
|
+
].filter(Boolean)
|
|
330
|
+
return `### 素材 ${material.id}(${flags.join(',')})\n${material.text}`
|
|
331
|
+
}).join('\n\n')
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 日常维护的素材收集入口。
|
|
336
|
+
*/
|
|
337
|
+
export async function collectAllMaterials({
|
|
338
|
+
config, query, cursors, consumption, nowMs = Date.now(), runDate, imMode = 'owner', weekly = false,
|
|
339
|
+
}) {
|
|
340
|
+
const chat = await collectChatMaterials({
|
|
341
|
+
config, query, cursors, consumption, nowMs, runDate, imMode,
|
|
342
|
+
})
|
|
343
|
+
const materials = [
|
|
344
|
+
...chat.materials,
|
|
345
|
+
...collectAppraisalMaterials(config, { runDate, consumption }),
|
|
346
|
+
...collectCorrectionMaterials(config, { consumption }),
|
|
347
|
+
...collectOutingMaterials(config, { runDate }),
|
|
348
|
+
...collectNoteMaterials(config),
|
|
349
|
+
]
|
|
350
|
+
if (weekly) {
|
|
351
|
+
const dates = []
|
|
352
|
+
for (let offset = 1; offset <= 7; offset += 1) dates.push(addLocalDays(runDate, -offset))
|
|
353
|
+
materials.push(...collectDiaryMaterials(config, { dates, exclude: new Set([runDate]) }))
|
|
354
|
+
}
|
|
355
|
+
const trimmed = trimMaterialsToBudget(materials)
|
|
356
|
+
return {
|
|
357
|
+
materials: trimmed.materials,
|
|
358
|
+
dropped: trimmed.dropped,
|
|
359
|
+
cursors: chat.cursors,
|
|
360
|
+
warnings: chat.warnings,
|
|
361
|
+
}
|
|
362
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 薄触发会话的维护完成记录:只有这里的 success=true 才允许删除会话。
|
|
3
|
+
*/
|
|
4
|
+
import { readFileSync } from 'node:fs'
|
|
5
|
+
import { resolve } from 'node:path'
|
|
6
|
+
import { writeAtomic } from '../storage/index.js'
|
|
7
|
+
|
|
8
|
+
export const COMPLETIONS_FILE = 'state/maintenance-completions.jsonl'
|
|
9
|
+
const COMPLETION_LIMIT = 200
|
|
10
|
+
|
|
11
|
+
export function completionsPath(config) {
|
|
12
|
+
return resolve(config.taHome, COMPLETIONS_FILE)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function readCompletions(config) {
|
|
16
|
+
let text = ''
|
|
17
|
+
try {
|
|
18
|
+
text = readFileSync(completionsPath(config), 'utf8')
|
|
19
|
+
} catch {
|
|
20
|
+
return []
|
|
21
|
+
}
|
|
22
|
+
const records = []
|
|
23
|
+
for (const line of text.split(/\r?\n/)) {
|
|
24
|
+
if (!line.trim()) continue
|
|
25
|
+
try {
|
|
26
|
+
const value = JSON.parse(line)
|
|
27
|
+
if (value && typeof value === 'object') records.push(value)
|
|
28
|
+
} catch {
|
|
29
|
+
/* 损坏行跳过 */
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return records
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function appendCompletion(config, entry) {
|
|
36
|
+
const record = {
|
|
37
|
+
sessionId: String(entry?.sessionId ?? ''),
|
|
38
|
+
runId: String(entry?.runId ?? ''),
|
|
39
|
+
runDate: String(entry?.runDate ?? ''),
|
|
40
|
+
status: String(entry?.status ?? 'failed'),
|
|
41
|
+
success: entry?.success === true,
|
|
42
|
+
finishedAt: typeof entry?.finishedAt === 'string' ? entry.finishedAt : new Date().toISOString(),
|
|
43
|
+
}
|
|
44
|
+
if (!record.sessionId || !record.runId) return null
|
|
45
|
+
const kept = [...readCompletions(config), record].slice(-COMPLETION_LIMIT)
|
|
46
|
+
writeAtomic(completionsPath(config), kept.map(item => JSON.stringify(item)).join('\n') + '\n')
|
|
47
|
+
return record
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 某会话最近一次维护完成记录;没有则 null。 */
|
|
51
|
+
export function latestCompletion(config, sessionId) {
|
|
52
|
+
const id = String(sessionId ?? '')
|
|
53
|
+
if (!id) return null
|
|
54
|
+
const records = readCompletions(config).filter(item => item.sessionId === id)
|
|
55
|
+
return records.length ? records[records.length - 1] : null
|
|
56
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 素材消费账本 state/material-consumption.json。
|
|
3
|
+
*
|
|
4
|
+
* 消费粒度是 (materialId, targetFile):同一素材写进日记不代表 RECENT 已经用过。
|
|
5
|
+
* 只有成功写出 artifact 才记账;失败阶段不消费素材。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readFileSync } from 'node:fs'
|
|
9
|
+
import { resolve } from 'node:path'
|
|
10
|
+
import { writeAtomic } from '../storage/index.js'
|
|
11
|
+
|
|
12
|
+
export const CONSUMPTION_FILE = 'state/material-consumption.json'
|
|
13
|
+
|
|
14
|
+
export function consumptionPath(config) {
|
|
15
|
+
return resolve(config.taHome, CONSUMPTION_FILE)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function emptyConsumption() {
|
|
19
|
+
return { version: 1, materials: {} }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function readConsumption(config) {
|
|
23
|
+
try {
|
|
24
|
+
const value = JSON.parse(readFileSync(consumptionPath(config), 'utf8'))
|
|
25
|
+
if (!value || typeof value !== 'object' || !value.materials || typeof value.materials !== 'object') {
|
|
26
|
+
return emptyConsumption()
|
|
27
|
+
}
|
|
28
|
+
return { version: 1, materials: value.materials }
|
|
29
|
+
} catch {
|
|
30
|
+
return emptyConsumption()
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function writeConsumption(config, ledger) {
|
|
35
|
+
writeAtomic(consumptionPath(config), JSON.stringify(ledger, null, 2) + '\n')
|
|
36
|
+
return ledger
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function consumedTargets(ledger, materialId) {
|
|
40
|
+
const entry = ledger?.materials?.[materialId]
|
|
41
|
+
if (!entry || typeof entry !== 'object' || !entry.artifacts) return []
|
|
42
|
+
return Object.keys(entry.artifacts)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function isConsumedFor(ledger, materialId, target) {
|
|
46
|
+
return consumedTargets(ledger, materialId).includes(target)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 记录一次成功消费;返回账本条目。 */
|
|
50
|
+
export function markConsumed(ledger, materialId, target, {
|
|
51
|
+
runId, at = new Date().toISOString(), sourceHash,
|
|
52
|
+
} = {}) {
|
|
53
|
+
if (typeof materialId !== 'string' || !materialId) throw new Error('materialId is required')
|
|
54
|
+
if (typeof target !== 'string' || !target) throw new Error('target is required')
|
|
55
|
+
const materials = ledger.materials ??= {}
|
|
56
|
+
const entry = materials[materialId] ??= { firstRun: null, lastRun: null, lastSeenAt: null, artifacts: {} }
|
|
57
|
+
entry.firstRun ??= runId ?? null
|
|
58
|
+
entry.lastRun = runId ?? entry.lastRun ?? null
|
|
59
|
+
entry.lastSeenAt = at
|
|
60
|
+
entry.artifacts ??= {}
|
|
61
|
+
entry.artifacts[target] = {
|
|
62
|
+
runId: runId ?? null,
|
|
63
|
+
at,
|
|
64
|
+
...(sourceHash ? { sourceHash } : {}),
|
|
65
|
+
}
|
|
66
|
+
return entry
|
|
67
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话读取游标 state/session-cursors.json。
|
|
3
|
+
*
|
|
4
|
+
* 维护不再全量扫描历史:每个会话只读 lastSeq 之后的事件。
|
|
5
|
+
* 游标只在整次运行成功(或已明确消费)后由引擎写回;失败重试仍从旧游标读。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readFileSync } from 'node:fs'
|
|
9
|
+
import { resolve } from 'node:path'
|
|
10
|
+
import { writeAtomic } from '../storage/index.js'
|
|
11
|
+
|
|
12
|
+
export const CURSORS_FILE = 'state/session-cursors.json'
|
|
13
|
+
|
|
14
|
+
export function cursorsPath(config) {
|
|
15
|
+
return resolve(config.taHome, CURSORS_FILE)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function emptyCursors() {
|
|
19
|
+
return { version: 1, sessions: {} }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function readSessionCursors(config) {
|
|
23
|
+
try {
|
|
24
|
+
const value = JSON.parse(readFileSync(cursorsPath(config), 'utf8'))
|
|
25
|
+
if (!value || typeof value !== 'object' || !value.sessions || typeof value.sessions !== 'object') {
|
|
26
|
+
return emptyCursors()
|
|
27
|
+
}
|
|
28
|
+
return { version: 1, sessions: value.sessions }
|
|
29
|
+
} catch {
|
|
30
|
+
return emptyCursors()
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function writeSessionCursors(config, cursors) {
|
|
35
|
+
writeAtomic(cursorsPath(config), JSON.stringify(cursors, null, 2) + '\n')
|
|
36
|
+
return cursors
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function lastSeqOf(cursors, sessionId) {
|
|
40
|
+
const value = cursors?.sessions?.[sessionId]?.lastSeq
|
|
41
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : -1
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function advanceCursor(cursors, sessionId, { lastSeq, at = new Date().toISOString() }) {
|
|
45
|
+
if (!Number.isSafeInteger(lastSeq) || lastSeq < 0) return cursors
|
|
46
|
+
const sessions = cursors.sessions ??= {}
|
|
47
|
+
const previous = lastSeqOf({ sessions }, sessionId)
|
|
48
|
+
sessions[sessionId] = {
|
|
49
|
+
lastSeq: Math.max(previous, lastSeq),
|
|
50
|
+
lastReadAt: at,
|
|
51
|
+
}
|
|
52
|
+
return cursors
|
|
53
|
+
}
|