rugu-core 0.1.0 → 0.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rugu-core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "如故的记忆核心:一个人设只有一段人生——感知入库、认人认物、情节与事实、激活与遗忘、五路回想、分寸判断。不认识任何宿主和入口。",
5
5
  "keywords": [
6
6
  "memory",
package/src/admin/feed.js CHANGED
@@ -138,7 +138,7 @@ function shape(core, r, stmts) {
138
138
  const subjects = (x.entities ?? []).filter((e) => e.role === 'subject').map((e) => e.entityId);
139
139
  return { ref: x.ref, kind, id: x.id, text: x.text, at: x.recordedAt, who: s?.speaker ?? subjects[0] ?? null, settingKey: s?.perceived_in ?? null, subjects: subjects.slice(0, 6),
140
140
  certainty: x.certainty, confidence: x.confidence, supersededBy: x.supersededBy ?? null, expiredAt: x.expiredAt ?? null, planStatus: x.planStatus ?? null,
141
- needsReview: !!x.needsReview, pinned: !!x.pinned, state: x.state ?? null };
141
+ needsReview: !!x.needsReview, pinned: !!x.pinned, kindHint: x.kindHint ?? null, state: x.state ?? null };
142
142
  }
143
143
  if (kind === 'episode') {
144
144
  return { ref: x.ref, kind, id: x.id, text: x.title || x.narrative || '', title: x.title ?? null, narrative: x.narrative ?? null, epKind: x.epKind, at: x.tEnd, tStart: x.tStart,
@@ -153,7 +153,7 @@ function shape(core, r, stmts) {
153
153
  }
154
154
 
155
155
  /** 用到的场合和人的名字(和首页同一种形状:只给用到的,不列全表)。 */
156
- function namesOf(core, items) {
156
+ export function namesOf(core, items) {
157
157
  const keys = new Set();
158
158
  const ids = new Set();
159
159
  for (const m of items) {
@@ -80,7 +80,7 @@ export function home(core, q) { return views.home(core, q ?? {}); }
80
80
  * nights:replay 痕迹按本地日聚簇取每簇最早的时刻,加上 meta 'sleep.lastAt'。
81
81
  * (b) 实时增量 {since: {inj, trace, told}} → {now, rev, cursor, traces: [[ref, t, w, d, r]], recalls: [[ts, placeKey, [[ref, layerCode]], rawN]],
82
82
  * tells: [[at, placeKey, ref, level]]}:id 大于游标的,每样最多 500 行(多了取最早的,cursor 只前进到给出的最后一行)。
83
- * (c) 看一眼 {peek: [ref…]}(最多 24 个)→ {items: [{ref, title, text, at}]}:text 截到 160 字;隐藏的、不是星的不给。
83
+ * (c) 看一眼 {peek: [ref…]}(最多 24 个)→ {items: [{ref, title, text, at}]}:text 截到 600 字;隐藏的、不是星的不给。
84
84
  * @param {import('../core-types.js').CoreContext} core
85
85
  * @param {{maxStars?: number, recallDays?: number}|{since: {inj: number, trace: number, told: number}}|{peek: string[]}} [q]
86
86
  * @returns {object}
@@ -462,3 +462,16 @@ export function feedDays(core, q) { return feedMod.feedDays(core, q ?? {}); }
462
462
  * @returns {{items: object[], total: number, readOnly: boolean, detail?: object}}
463
463
  */
464
464
  export function people(core, q) { return feedMod.people(core, q ?? {}); }
465
+
466
+ // ── 【D175】管理页「记忆 → 做梦」:夜间整理按晚列出来(只读,只读库也能用;口径见 nights.js) ─────────
467
+ import * as nightsMod from './nights.js';
468
+ /**
469
+ * 夜间整理按晚列出来:每一晚(本地日)写下的日记、改正、归纳的规律、反思的想法、对人的印象、性格的变化、总结的经验,
470
+ * 和那一晚的运行报告(调了几次模型、哪几步没做成)。
471
+ * @param {import('../core-types.js').CoreContext} core
472
+ * @param {{limit?: number, before?: number, tzOffsetMin?: number}} [q]
473
+ * @returns {{now: number, schedule: {at: string, lastAt: number|null, running: boolean, nights: number},
474
+ * items: {day: string, dayStart: number, run: object|null, counts: object, groups: object[]}[], more: boolean, next?: number,
475
+ * names: object, settings: object, readOnly: boolean}}
476
+ */
477
+ export function nights(core, q) { return nightsMod.nights(core, q ?? {}); }
@@ -0,0 +1,177 @@
1
+ // 【D175】管理页「记忆 → 做梦」:夜间整理按晚列出来,每一晚做了什么(只读,只读库也能用)。
2
+ // - 一晚 = 一个本地日:这一天里夜间整理写下的东西(日记、改正、归纳的规律、反思的想法、对人的印象、性格的变化、总结的经验)
3
+ // 按写下的时刻归到那一天;这一天的运行报告(调了几次模型、哪几步没做成)来自 meta 'sleep.history'(D175 起每晚留底,最多 30 晚),
4
+ // 没有留底的旧晚(升级前)只有产出、没有报告;最近一次的 'sleep.lastReport' 也算(升级前跑的最后一次)。
5
+ // - 不另起一套口径:产出直接查它们自己的表(和 views.js 的 checks、lessons 同样的字段),不抄文字进新表;没有迁移。
6
+ // 每一路都按时间列走已有的索引(memory_checks_at、assertions_recorded、assertions_lesson_updated、episodes_kind);
7
+ // impressions、成长版本表很小,直接扫。
8
+ // - 翻页:before(毫秒)= 只看这个时刻之前的晚;一次最多 limit(默认 7)晚;more 说前面是不是还有更早的。
9
+ // 只有 SELECT。SQL 一律参数化。
10
+ import { getMeta, getMetaJson, refOf } from '../store/index.js';
11
+ import { ContractError } from '../contract/errors.js';
12
+ import { tzOf } from './timeline.js';
13
+ import { namesOf } from './feed.js';
14
+
15
+ const DAY = 86_400_000;
16
+ /** 一晚里每一类最多列几条(总数另给)。 */
17
+ const PER_CAT = 20;
18
+ /** 找「有哪些晚」时每一路最多取多少个时刻(只取一个整数,很轻)。 */
19
+ const SCAN = 600;
20
+ const MAX_NIGHTS = 30;
21
+
22
+ const bad = (path, message) => new ContractError('admin.nights', [{ path, message }]);
23
+ const clip = (s, n) => { const c = [...String(s ?? '').replace(/\s+/g, ' ').trim()]; return c.length > n ? `${c.slice(0, n).join('')}…` : c.join(''); };
24
+ const safeJson = (s, d) => { try { return s == null ? d : JSON.parse(s); } catch { return d; } };
25
+
26
+ /** 没忘掉的(隐藏的照列):suppressions 的主键是 (owner_kind, owner_id)。 */
27
+ const alive = (kind) => `NOT EXISTS (SELECT 1 FROM suppressions s WHERE s.owner_kind = '${kind}' AND s.owner_id = t.id AND s.state = 'forgotten')`;
28
+
29
+ /** 每一路「夜里写下的东西」:时间列、表、条件(t 是表别名)。找晚和取产出共用,口径只有这一份。 */
30
+ const SOURCES = {
31
+ diary: { from: 'episodes t', time: 't.created_at', where: `t.ep_kind = 'diary' AND ${alive('episode')}` },
32
+ check: { from: 'memory_checks t', time: 't.at', where: '1' },
33
+ pattern: { from: 'assertions t', time: 't.recorded_at', where: `t.kind_hint = 'pattern' AND ${alive('assertion')}` },
34
+ insight: { from: 'assertions t', time: 't.recorded_at', where: `t.kind_hint = 'insight' AND ${alive('assertion')}` },
35
+ impression: { from: 'entity_impressions t', time: 't.built_at', where: '1' },
36
+ growth: { from: 'core_block_versions t', time: 't.created_at', where: "t.name = 'growth' AND t.created_by = 'sleep'" },
37
+ lesson: { from: 'assertions t', time: 't.updated_at',
38
+ where: `t.kind_hint = 'lesson' AND json_valid(t.value) AND json_extract(t.value, '$.origin') = 'nightly' AND ${alive('assertion')}` },
39
+ };
40
+
41
+ /** 留底的每一晚报告(升级前只有最近一次)。 */
42
+ function runsOf(core) {
43
+ const out = [];
44
+ const hist = getMetaJson(core.store, 'sleep.history');
45
+ for (const r of Array.isArray(hist) ? hist : []) if (r && Number.isFinite(r.startedAt)) out.push(r);
46
+ const last = getMetaJson(core.store, 'sleep.lastReport');
47
+ if (last && Number.isFinite(last.startedAt) && !out.some((r) => r.startedAt === last.startedAt)) out.push(last);
48
+ return out.sort((a, b) => a.startedAt - b.startedAt);
49
+ }
50
+
51
+ const STEP_DETAIL = (steps, name) => steps.find((s) => s?.name === name)?.detail ?? null;
52
+ /** 一份报告 → 管理页要的:时间、调用、哪几步没做成(failed 出错 / capped 到上限 / preset 节省档没做 / aborted 被中止)、日记缺几天。 */
53
+ function runView(r) {
54
+ const steps = Array.isArray(r.steps) ? r.steps : [];
55
+ const problems = [];
56
+ for (const s of steps) {
57
+ if (!s || typeof s.name !== 'string') continue;
58
+ if (s.capped) problems.push({ name: s.name, kind: 'capped' });
59
+ else if (s.skipped === 'saving-preset') problems.push({ name: s.name, kind: 'preset' });
60
+ else if (s.skipped === 'aborted') problems.push({ name: s.name, kind: 'aborted' });
61
+ else if (s.ok === false || /^error:/.test(String(s.skipped ?? ''))) problems.push({ name: s.name, kind: 'failed' });
62
+ }
63
+ const self = STEP_DETAIL(steps, 'self');
64
+ const num = (v) => (Number.isFinite(v) ? v : null);
65
+ return {
66
+ at: num(r.startedAt), finishedAt: num(r.finishedAt), llmCalls: num(r.llmCalls) ?? 0, llmMax: num(r.llmMax),
67
+ problems, diaryPending: num(self?.diaryPending) ?? 0,
68
+ };
69
+ }
70
+
71
+ /**
72
+ * 一个本地日范围里每一类产出:总数 + 最多 PER_CAT 条。
73
+ * @returns {{counts: object, groups: object[]}}
74
+ */
75
+ function outputsOf(core, a, b) {
76
+ const cnt = (k) => Number(core.store.get(`SELECT count(*) AS n FROM ${SOURCES[k].from} WHERE ${SOURCES[k].where} AND ${SOURCES[k].time} >= ? AND ${SOURCES[k].time} < ?`, a, b).n);
77
+ const rows = (k, cols, extra = '') => core.store.all(`SELECT ${cols} FROM ${SOURCES[k].from} WHERE ${SOURCES[k].where} AND ${SOURCES[k].time} >= ? AND ${SOURCES[k].time} < ?${extra} LIMIT ${PER_CAT}`, a, b);
78
+ const counts = {};
79
+ const groups = [];
80
+ const add = (cat, total, items) => { counts[cat] = total; if (total > 0) groups.push({ cat, total, items }); };
81
+
82
+ // 日记
83
+ add('diary', cnt('diary'), rows('diary', 't.id, t.title, t.narrative, t.t_start, t.t_end, t.created_at', ' ORDER BY t.created_at DESC').map((e) => ({
84
+ ref: refOf('episode', e.id), title: e.title || null, text: clip(e.narrative, 1200), tStart: e.t_start, tEnd: e.t_end, at: e.created_at })));
85
+
86
+ // 对照原话纠错:改了的列出来(和 views.js 的 checks 同一个口径),没改的只数个数
87
+ const checked = cnt('check');
88
+ const fact = core.store.prepare('SELECT id, text, confidence, superseded_by FROM assertions WHERE id = ?');
89
+ const factOf = (id) => { const x = id == null ? null : fact.get(id); return x ? { ref: refOf('assertion', x.id), text: clip(x.text, 400), current: x.superseded_by == null } : null; };
90
+ const changedWhere = " AND t.verdict IN ('corrected','changed','doubted')";
91
+ const changed = Number(core.store.get(`SELECT count(*) AS n FROM memory_checks t WHERE t.at >= ? AND t.at < ?${changedWhere}`, a, b).n);
92
+ counts.checked = checked;
93
+ const changedItems = changed ? core.store.all(`SELECT t.id, t.at, t.verdict, t.why, t.assertion_id, t.result_id, t.after_conf, t.reverted_at FROM memory_checks t
94
+ WHERE t.at >= ? AND t.at < ?${changedWhere} ORDER BY t.at DESC, t.id DESC LIMIT ${PER_CAT}`, a, b).map((c) => ({
95
+ id: c.id, at: c.at, verdict: c.verdict, why: c.why ? clip(c.why, 300) : null,
96
+ withdrawn: c.verdict === 'doubted' && c.result_id == null && c.after_conf === 0,
97
+ before: factOf(c.assertion_id), after: factOf(c.result_id), reverted: c.reverted_at != null,
98
+ revertable: c.reverted_at == null })) : [];
99
+ add('changed', changed, changedItems);
100
+
101
+ // 归纳的规律、反思的想法(她推断的事实)
102
+ for (const k of ['pattern', 'insight']) {
103
+ const subj = core.store.prepare("SELECT entity_id FROM assertion_entities WHERE assertion_id = ? AND role = 'subject' LIMIT 4");
104
+ add(k, cnt(k), rows(k, 't.id, t.text, t.confidence, t.superseded_by, t.recorded_at', ' ORDER BY t.recorded_at DESC, t.id DESC').map((x) => ({
105
+ ref: refOf('assertion', x.id), text: clip(x.text, 400), confidence: x.confidence, current: x.superseded_by == null, at: x.recorded_at,
106
+ subjects: subj.all(x.id).map((r) => r.entity_id) })));
107
+ }
108
+
109
+ // 对人的印象:这一晚写下的那一版;version = 1 是第一次有印象
110
+ add('impression', cnt('impression'), rows('impression', 't.id, t.entity_id, t.layer, t.text, t.version, t.is_current, t.built_at', ' ORDER BY t.built_at DESC, t.id DESC').map((x) => ({
111
+ ref: refOf('impression', x.id), who: x.entity_id, layer: x.layer, text: clip(x.text, 400), version: x.version, first: x.version === 1, current: !!x.is_current, at: x.built_at })));
112
+
113
+ // 性格(成长块)的变化
114
+ add('growth', cnt('growth'), rows('growth', 't.version, t.change_json, t.evidence_ids, t.created_at, t.revoked_at', ' ORDER BY t.version DESC').map((x) => {
115
+ const c = safeJson(x.change_json, {});
116
+ return { version: x.version, op: typeof c.op === 'string' ? c.op : null, before: typeof c.before === 'string' ? clip(c.before, 600) : null,
117
+ after: typeof c.after === 'string' ? clip(c.after, 600) : null, evidence: safeJson(x.evidence_ids, []).length, revokedAt: x.revoked_at ?? null, at: x.created_at };
118
+ }));
119
+
120
+ // 夜里回顾做事时总结的经验
121
+ add('lesson', cnt('lesson'), rows('lesson', 't.id, t.text, t.updated_at, t.certainty, t.value', ' ORDER BY t.updated_at DESC, t.id DESC').map((x) => {
122
+ const v = safeJson(x.value, {});
123
+ return { ref: refOf('assertion', x.id), text: clip(x.text, 400), status: v.status === 'verified' ? 'verified' : 'unverified', at: x.updated_at };
124
+ }));
125
+ return { counts, groups };
126
+ }
127
+
128
+ /**
129
+ * 夜间整理按晚列出来。
130
+ * q:limit(几晚,默认 7,最多 30)、before(毫秒,只看这个时刻之前的晚)、tzOffsetMin。
131
+ * @param {import('../core-types.js').CoreContext} core
132
+ * @param {{limit?: number, before?: number, tzOffsetMin?: number}} [q]
133
+ * @returns {{now: number, schedule: {at: string, lastAt: number|null, running: boolean, nights: number},
134
+ * items: {day: string, dayStart: number, run: object|null, counts: object, groups: object[]}[], more: boolean, next?: number,
135
+ * names: object, settings: object, readOnly: boolean}}
136
+ */
137
+ export function nights(core, q = {}) {
138
+ const now = core.now();
139
+ const limit = Number.isInteger(q.limit) ? Math.max(1, Math.min(MAX_NIGHTS, q.limit)) : 7;
140
+ if (q.before != null && !Number.isFinite(q.before)) throw bad('before', '应为毫秒时间');
141
+ const before = Number.isFinite(q.before) ? q.before : now + DAY;
142
+ const tz = tzOf(core, q, now);
143
+ const off = tz * 60_000;
144
+ const dayOf = (t) => Math.floor((t + off) / DAY);
145
+ const runs = runsOf(core);
146
+
147
+ // 有哪些晚:每一路取这个时刻之前最近的 SCAN 个时刻,折成本地日
148
+ const days = new Set();
149
+ for (const k of Object.keys(SOURCES)) {
150
+ const s = SOURCES[k];
151
+ for (const r of core.store.all(`SELECT ${s.time} AS x FROM ${s.from} WHERE ${s.where} AND ${s.time} < ? ORDER BY ${s.time} DESC LIMIT ${SCAN}`, before)) days.add(dayOf(Number(r.x)));
152
+ }
153
+ for (const r of runs) if (r.startedAt < before) days.add(dayOf(r.startedAt));
154
+ const sorted = [...days].sort((x, y) => y - x);
155
+ const pick = sorted.slice(0, limit);
156
+ const more = sorted.length > limit;
157
+
158
+ const items = pick.map((d) => {
159
+ const a = d * DAY - off;
160
+ const b = a + DAY;
161
+ const mine = runs.filter((r) => r.startedAt >= a && r.startedAt < b).at(-1) ?? null;
162
+ const { counts, groups } = outputsOf(core, a, b);
163
+ return { day: new Date(d * DAY).toISOString().slice(0, 10), dayStart: a, run: mine ? runView(mine) : null, counts, groups };
164
+ });
165
+
166
+ // 名字:印象里的人、规律和想法的主体
167
+ const flat = [];
168
+ for (const n of items) for (const g of n.groups) for (const x of g.items) flat.push({ who: x.who, subjects: x.subjects });
169
+ const { names, settings } = namesOf(core, flat);
170
+
171
+ const last = Number(getMeta(core.store, 'sleep.lastAt'));
172
+ return {
173
+ now,
174
+ schedule: { at: String(core.config.get().sleep?.at ?? '04:30'), lastAt: Number.isFinite(last) && last > 0 ? last : null, running: !!core.state?.consolidate?.running, nights: runs.length },
175
+ items, more, ...(more && pick.length ? { next: pick.at(-1) * DAY - off } : {}), names, settings, readOnly: !!core.readOnly,
176
+ };
177
+ }
@@ -36,7 +36,7 @@ const MOOD_POINTS = 2000;
36
36
  const HEARD_DAYS = 90;
37
37
  const LIVE_ROWS = 500;
38
38
  const PEEK_MAX = 24;
39
- const PEEK_TEXT = 160;
39
+ const PEEK_TEXT = 600;
40
40
  const WHO_MAX = 4;
41
41
 
42
42
  const bad = (path, message) => new ContractError('admin.starmap', [{ path, message }]);
@@ -648,7 +648,7 @@ export function home(core, q = {}) {
648
648
  const p = r.percept_id ? percept.get(r.percept_id) : null;
649
649
  const who = r.source_entity_id ?? p?.actor_entity_id ?? null;
650
650
  return { source: 'needToKnow', id: r.id, kind: r.kind, reason: r.reason, severity: r.severity, urgent: r.severity >= 2, at: r.created_at,
651
- settingKey: p?.setting_key ?? null, who, quote: clipText(p?.text, 80) };
651
+ settingKey: p?.setting_key ?? null, who, quote: clipText(p?.text, 300) };
652
652
  });
653
653
  const held = core.store.prepare('SELECT held_text, setting_key FROM utterances WHERE token = ?');
654
654
  for (const r of core.store.all("SELECT * FROM review_queue WHERE status = 'pending' ORDER BY created_at DESC, id DESC LIMIT ?", nTop)) {
@@ -659,12 +659,12 @@ export function home(core, q = {}) {
659
659
  if (r.kind === 'held_utterance' && typeof p.token === 'string') {
660
660
  const u = held.get(p.token);
661
661
  item.settingKey = u?.setting_key ?? null;
662
- item.quote = clipText(u?.held_text, 80);
662
+ item.quote = clipText(u?.held_text, 300);
663
663
  } else if (r.kind === 'merge') {
664
664
  item.who = Number.isSafeInteger(p.a) ? p.a : null;
665
665
  item.other = Number.isSafeInteger(p.b) ? p.b : null;
666
- } else if (r.kind === 'growth') item.quote = clipText(p.change?.after ?? p.text, 80);
667
- else if (r.kind === 'setting_rule_relax') { item.settingKey = typeof p.settingKey === 'string' ? p.settingKey : null; item.quote = clipText(p.rule?.text, 80); }
666
+ } else if (r.kind === 'growth') item.quote = clipText(p.change?.after ?? p.text, 300);
667
+ else if (r.kind === 'setting_rule_relax') { item.settingKey = typeof p.settingKey === 'string' ? p.settingKey : null; item.quote = clipText(p.rule?.text, 300); }
668
668
  else if (Number.isSafeInteger(p.entityId)) item.who = p.entityId;
669
669
  top.push(item);
670
670
  }
package/src/api.js CHANGED
@@ -452,6 +452,8 @@ function buildApi(core, { startup, files }) {
452
452
  feed: (q) => core.mods.admin.feed(core, q && typeof q === 'object' ? q : {}),
453
453
  feedDays: (q) => core.mods.admin.feedDays(core, q && typeof q === 'object' ? q : {}),
454
454
  people: (q) => core.mods.admin.people(core, q && typeof q === 'object' ? q : {}),
455
+ /** 【D175】管理页「记忆 → 做梦」:夜间整理按晚列出来(每一晚写下了什么、跑得怎么样)。只读,只读库也能用。 */
456
+ nights: (q) => core.mods.admin.nights(core, q && typeof q === 'object' ? q : {}),
455
457
  simulate: (s) => core.mods.admin.simulate(core, s),
456
458
  review: {
457
459
  list: () => core.mods.admin.listReview(core, { status: 'pending' }),
@@ -164,7 +164,7 @@ export const DEFAULTS = deepFreeze({
164
164
  timeoutMs: 60_000,
165
165
  minSpacingMs: 5000, // 两次调用至少隔 5 秒
166
166
  concurrency: 1,
167
- factTextMax: 120,
167
+ factTextMax: 300, // D177:一条事实存下来最长多少字(120 → 300)。提取的提示词里仍写「≤120字」当目标,这是兜底:模型写长了不再在半句话处截成「…」
168
168
  quoteMax: 60,
169
169
  futureQMax: 3,
170
170
  miniCardChars: 120,
@@ -225,7 +225,7 @@ export const DEFAULTS = deepFreeze({
225
225
  // 存成关于她自己的事实(kind_hint='lesson'),范围(工具、场合、人)是结构化字段,话题靠词和回想。
226
226
  lessons: {
227
227
  enabled: true,
228
- textMax: 120, trapMax: 60, howMax: 60, toolMax: 64,
228
+ textMax: 300, trapMax: 60, howMax: 60, toolMax: 64, // D177:textMax 120 → 300(和 extract.factTextMax 一样,兜底别截半句)
229
229
  sameSim: 0.5, // 和已有的一条(同一个工具、同一个范围)这么像就并进那一条,不另记
230
230
  perDay: 12, // 她一天(本地日)最多新记几条(并进已有的不算;主人教的不受这个限制)
231
231
  proofMin: 30, // 这个工具这么多分钟内「先没成、换了做法后成了」:她这时记下的这个工具的经验算验证过(宿主看到的工具结果)
@@ -589,8 +589,10 @@ export const DEFAULTS = deepFreeze({
589
589
  catchUpH: 24, // 距上次超过 24 小时,启动时补跑
590
590
  retryMin: 60, // 上次开始了没跑完(进程崩了):至少隔这么久才重跑
591
591
  // 一晚的 LLM 调用总上限(D138)。null = 各步上限之和(sleep.js 的 stepCalls:复核 1 + 纠错 correct.maxCalls + 泛化 generalize.maxCalls
592
- // + 反思 2 + 印象 2 + 回头问问 1 + 故事线和社区 2 + 她自己 1 + 经验回顾 lessons.maxCalls;完整做 14 次,节省档只做必要项 6 次)。
593
- // 写成数字就按它封顶;不管多少,「她自己」和经验回顾的名额先留出来,前面的步骤用不到
592
+ // + 反思 2 + 印象 2 + 回头问问 1 + 故事线和社区 2 + 她自己 1 + 经验回顾 lessons.maxCalls;完整做 16 次,节省档只做必要项 6 次)。
593
+ // 写成数字就按它封顶;不管多少,「她自己」和经验回顾的名额先留出来,前面的步骤用不到。
594
+ // D176:下面几个「一晚做多少」的数(纠错 correct.maxCalls、泛化 generalize.maxCalls、印象 impressions.perCall)还要乘花费档位的
595
+ // sleepScale(budget.presets[档].sleepScale,自定义可以单独改;节省 0.6 / 平衡 1 / 效果优先 2),取整、至少 1,见 consolidate/params.js
594
596
  maxLlmCalls: null,
595
597
  planGraceH: 6, // 计划的时间点过了多久没下文才标 unknown(§5.5 第 5 条、第 6 步)
596
598
  extract: { maxJobs: 100, maxMs: 10 * MIN, retryFailedDays: 7, retryMax: 3, reviewLimit: 40 }, // 第 1 步:顺手跑的提炼、补跑失败批次、复核
@@ -598,8 +600,9 @@ export const DEFAULTS = deepFreeze({
598
600
  // 第 2 步(D122):对照原话纠错。每晚挑最可能错、或最常被想起的事实,回到来源原话和之后的话核对;一次调用核 perCall 条,
599
601
  // 一晚最多 maxCalls 次(也算在 maxLlmCalls 里)。再次核对的间隔 = recheckDays × 2^连续确认次数 ÷ (1 + 最近用到的程度),
600
602
  // 至少 minRecheckDays(不是硬窗口,只决定哪天再挑它)。用到的程度看最近 usageDays 天的注入和被提起。
603
+ // D176:maxCalls 2 → 4(一晚核 8 条 → 16 条;实测线上有近 4000 条事实,8 条一晚要一年多才轮一遍);还要乘 sleepScale
601
604
  correct: {
602
- perCall: 4, maxCalls: 2, poolMax: 3000,
605
+ perCall: 4, maxCalls: 4, poolMax: 3000,
603
606
  usageDays: 14, recheckDays: 7, minRecheckDays: 1, maxStreak: 8,
604
607
  sourceLines: 3, contextLines: 2, laterLines: 5, laterFacts: 3, behaviorSamples: 2,
605
608
  lineChars: 120, whyChars: 80,
@@ -628,7 +631,8 @@ export const DEFAULTS = deepFreeze({
628
631
  sameSim: 0.6, // 和已有洞见这么像就不再写
629
632
  deadlineMs: null, // 取证据的有意回想最多等多久;null = recall.deliberate.deadlineMs
630
633
  },
631
- impressions: { perCall: 6, factsPerLayer: 30, maxChars: 160, maybeSamePerCall: 6, factsPerSide: 6 }, // 第 5 步
634
+ // D176:perCall(一晚最多更新几个人的印象,一次调用写一层)6 → 10,还要乘 sleepScale(实测线上有一百多个人,6 个一晚轮得太慢)
635
+ impressions: { perCall: 10, factsPerLayer: 30, maxChars: 500, maybeSamePerCall: 6, factsPerSide: 6 }, // 第 5 步
632
636
  followUp: { windowH: 72, perCall: 10 }, // §5.5 第 5 条「回头问问」的时间窗(之后没机会就 lapsed)
633
637
  storyline: { maxChars: 600, perCall: 5, episodesPerSetting: 12, rebuildEvery: 10, rebuildEpisodes: 20 }, // §5.8;每 10 个版本整体重写一次
634
638
  communities: { // 第 7 步(标签传播)
@@ -714,13 +718,13 @@ export const DEFAULTS = deepFreeze({
714
718
  presets: {
715
719
  loose: { mainChatRatioCap: null, dailyCalls: 3000, dailyUncachedTokens: 5_000_000, perSourceShare: 0.5,
716
720
  stage2Scope: 'all', prefetchRewrite: true, rerank: true, sleepDepth: 'full', balanceProtectDays: 1,
717
- injectShare: 0.4, injectPerSessionPerDay: null, room: 1, recollectScale: 1 },
721
+ injectShare: 0.4, injectPerSessionPerDay: null, room: 1, sleepScale: 1, recollectScale: 1 },
718
722
  saving: { mainChatRatioCap: 0.25, dailyCalls: 600, dailyUncachedTokens: 1_000_000, perSourceShare: 0.3,
719
723
  stage2Scope: 'direct', prefetchRewrite: false, rerank: true, sleepDepth: 'essential', balanceProtectDays: 3,
720
- injectShare: 0.05, injectPerSessionPerDay: 8000, room: 0.6, recollectScale: 1 },
724
+ injectShare: 0.05, injectPerSessionPerDay: 8000, room: 0.6, sleepScale: 0.6, recollectScale: 1 },
721
725
  unlimited: { mainChatRatioCap: null, dailyCalls: null, dailyUncachedTokens: null, perSourceShare: 1,
722
726
  stage2Scope: 'all', prefetchRewrite: true, rerank: true, sleepDepth: 'full', balanceProtectDays: 1,
723
- injectShare: null, injectPerSessionPerDay: null, room: 2, recollectScale: 1 },
727
+ injectShare: null, injectPerSessionPerDay: null, room: 2, sleepScale: 2, recollectScale: 1 },
724
728
  // 每档的 recollectScale 已弃用(D165):读到了也忽略(并进 room);留着只是不让旧的覆盖报未知字段
725
729
  },
726
730
  // 主人单独改过的项(管理页「花费护栏 → 自定义」或手改文件),覆盖预设。能写的键和取值见 BUDGET_OVERRIDE_KEYS / checkBudgetOverride;
@@ -829,12 +833,17 @@ const BUDGET_OVERRIDE_CHECKS = Object.freeze({
829
833
  injectPerSessionPerDay: capV,
830
834
  // 记忆给多少(D165):回想各层的条数和总字数乘它(config/caps.js)
831
835
  room: (v) => (typeof v === 'number' && Number.isFinite(v) && v >= ROOM_MIN && v <= ROOM_MAX ? null : `应为 ${ROOM_MIN}–${ROOM_MAX} 的数`),
836
+ // 夜里整理做多少(D176):纠错的次数、泛化的次数、一晚更新几个人的印象乘它(consolidate/params.js)
837
+ sleepScale: (v) => (typeof v === 'number' && Number.isFinite(v) && v >= SLEEP_SCALE_MIN && v <= SLEEP_SCALE_MAX ? null : `应为 ${SLEEP_SCALE_MIN}–${SLEEP_SCALE_MAX} 的数`),
832
838
  // 已弃用(D165):回忆的名额并进 room。读到了也忽略;留着只是不让旧的覆盖报未知字段(不在 BUDGET_OVERRIDE_KEYS 里,管理页不再显示)
833
839
  recollectScale: (v) => (typeof v === 'number' && Number.isFinite(v) ? null : '应为数(已弃用,读到了也忽略)'),
834
840
  });
835
841
  /** room(D165)的取值范围:建议 0.5–3,校验放宽到 0.3–4(手改文件的余地)。 */
836
842
  export const ROOM_MIN = 0.3;
837
843
  export const ROOM_MAX = 4;
844
+ /** sleepScale(D176,夜里整理做多少的倍数)的取值范围:建议 0.5–3,校验放宽到 0.3–4。 */
845
+ export const SLEEP_SCALE_MIN = 0.3;
846
+ export const SLEEP_SCALE_MAX = 4;
838
847
  /** 已弃用、读到了也忽略的预算项(D165:recollectScale 并进 room)。 */
839
848
  const DEPRECATED_BUDGET_KEYS = new Set(['recollectScale']);
840
849
  /** budget.overrides 能写的键(顺序就是管理页「自定义」里的顺序;已弃用的不在里面)。 */
@@ -15,7 +15,7 @@
15
15
  // 契约细节:docs/实现/模块与接口.md §4.9。内部文件:sleep(编排、第 1/2/9/10 步)、today、storyline、communities、impressions、
16
16
  // generalize、reflect、self、time、growth;params 把配置快照摆成方便用的形状,util、memory 是小工具。
17
17
  import { newRun, residentDirty } from './util.js';
18
- import { shouldSleepImpl, sleepImpl } from './sleep.js';
18
+ import { shouldSleepImpl, sleepImpl, sleepSummary as sleepSummaryImpl } from './sleep.js';
19
19
  import { todaySoFarImpl } from './today.js';
20
20
  import { storylineBatch } from './storyline.js';
21
21
  import { impressionsBatch } from './impressions.js';
@@ -55,6 +55,14 @@ export function shouldSleep(core, at) { return shouldSleepImpl(core, at); }
55
55
  */
56
56
  export async function sleep(core, opt) { return sleepImpl(core, opt ?? {}); }
57
57
 
58
+ /**
59
+ * 【D176】这套配置下夜里整理一晚最多做多少(整晚几次模型、对照原话核几条、泛化问几组、印象更新几个人),管理页「花费护栏」写给人看。
60
+ * 纯函数,不读库;不是 core 的函数(给的是配置快照),集成层从包的入口取,不经 core.mods。
61
+ * @param {object} cfg core.config.get() 的快照(或 mergeConfig 合出来的 config)
62
+ * @returns {{scale: number, depth: string, calls: number, correctFacts: number, generalizeGroups: number, impressionPeople: number}}
63
+ */
64
+ export function sleepSummary(cfg) { return sleepSummaryImpl(cfg); }
65
+
58
66
  /**
59
67
  * 今天到目前为止(§5.7,评审:UV-07):她参与过、对话空闲 today.idleMin 分钟的场合,生成一句话小结(use='summary';
60
68
  * 预算紧时直接拼接她自己说的话和话题词),写成 ep_kind='summary' 的情节,「谁知道」= 那个场合的受众。
@@ -1,9 +1,21 @@
1
1
  // consolidate 的参数:每次用都从 core.config.get() 取(热加载)。数值都在 config/defaults.js 的 sleep、today 两段
2
2
  // (唯一的来源,【建议】,beta 用诊断区的数据再调);这里只把别的段里要用的几个值一起摆成方便用的形状。
3
- import { budgetLimits } from '../config/defaults.js';
3
+ import { budgetLimits, SLEEP_SCALE_MIN, SLEEP_SCALE_MAX } from '../config/defaults.js';
4
4
 
5
5
  const HOUR = 3_600_000;
6
6
 
7
+ /**
8
+ * 夜里整理做多少的倍数(D176):花费档位的 sleepScale(预设 + 自定义);读不到、不合法按 1,夹在 SLEEP_SCALE_MIN–SLEEP_SCALE_MAX。
9
+ * @param {object} cfg core.config.get()
10
+ * @returns {number}
11
+ */
12
+ export function sleepScaleOf(cfg) {
13
+ let r = 1;
14
+ try { r = Number(budgetLimits(cfg).sleepScale); } catch { r = 1; }
15
+ if (!Number.isFinite(r) || r <= 0) r = 1;
16
+ return Math.min(SLEEP_SCALE_MAX, Math.max(SLEEP_SCALE_MIN, r));
17
+ }
18
+
7
19
  /**
8
20
  * mergeConfig 保证快照里的键是全的。
9
21
  * @param {import('../core-types.js').CoreContext} core
@@ -14,12 +26,16 @@ export function params(core) {
14
26
  const t = cfg.today;
15
27
  let depth = 'full';
16
28
  try { depth = budgetLimits(cfg).sleepDepth ?? 'full'; } catch { /* 预算配置坏了按完整做 */ }
29
+ // 一晚做多少(D176):纠错、泛化的调用次数和一晚更新几个人的印象乘 sleepScale(取整、至少 1;本来就是 0 的还是 0 = 关着)
30
+ const scale = sleepScaleOf(cfg);
31
+ const times = (n) => (n > 0 ? Math.max(1, Math.round(n * scale)) : 0);
17
32
  return {
18
33
  at: s.at,
19
34
  catchUpH: s.catchUpH,
20
35
  retryMin: s.retryMin, // 上次开始了但没跑完(进程崩了):至少隔这么久才重跑
21
36
  maxLlmCalls: s.maxLlmCalls,
22
37
  depth, // 'full' | 'essential'(节省预设:夜间整理只做必要项,§10.6)
38
+ scale, // 夜里整理做多少的倍数(D176)
23
39
  llmTimeoutMs: cfg.extract.timeoutMs,
24
40
  extract: s.extract, // 第 1 步顺手跑的提炼、补跑失败批次(防「毒批次」每晚重试)、复核
25
41
  replay: {
@@ -27,14 +43,14 @@ export function params(core) {
27
43
  withinDays: cfg.activation.events.replayWithinDays,
28
44
  w: cfg.activation.events.replay,
29
45
  },
30
- correct: s.correct, // 第 2 步的对照原话纠错(D122)
46
+ correct: { ...s.correct, maxCalls: times(s.correct.maxCalls) }, // 第 2 步的对照原话纠错(D122)
31
47
  keep: cfg.extract.keep, // 提炼的「只记需要的」封顶(D123):改正后的版本也按它
32
- generalize: s.generalize,
48
+ generalize: { ...s.generalize, maxCalls: times(s.generalize.maxCalls) },
33
49
  reflection: {
34
50
  ...s.reflection,
35
51
  deadlineMs: s.reflection.deadlineMs ?? cfg.recall.deliberate.deadlineMs, // null = 有意回想的截止时间
36
52
  },
37
- impressions: s.impressions,
53
+ impressions: { ...s.impressions, perCall: times(s.impressions.perCall) },
38
54
  thetaHi: cfg.entities.thetaHi,
39
55
  thetaLo: cfg.entities.thetaLo,
40
56
  followUp: s.followUp, // 「回头问问」的时间窗:之后没机会就 lapsed
@@ -16,7 +16,7 @@
16
16
  // 解开副本跑 integrity_check),不碰正在用的库。
17
17
  // - 跑完给所有场合的常驻区标脏(context.markResidentDirty,§10.4),新文本等下一条真实消息再换上。
18
18
  // - 同一时间只跑一个(state.consolidate.running);dispose 时中止;整体恢复进行中不开始(§12.4.5)。
19
- import { getMeta, setMeta, setMetaJson, claimNextJob, failJob, enqueueJob, refOf, parseRef } from '../store/index.js';
19
+ import { getMeta, getMetaJson, setMeta, setMetaJson, claimNextJob, failJob, enqueueJob, refOf, parseRef } from '../store/index.js';
20
20
  import { params } from './params.js';
21
21
  import {
22
22
  DAY, HOUR, MIN, errCode, localDay, localDayStart, metric, newRun, parseClock, safeJson, unit, warn, info, restoring, yieldLoop, residentDirty,
@@ -58,7 +58,7 @@ export function shouldSleepImpl(core, at) {
58
58
  return at - last >= p.catchUpH * HOUR;
59
59
  }
60
60
 
61
- /** 必要项(节省预设下也做)。第 2 步的对照原话纠错也算(D122 评审:记错的认知每一轮都被注入,一晚最多 2 次、几分钱,见 docs/花费.md)。
61
+ /** 必要项(节省预设下也做)。第 2 步的对照原话纠错也算(D122 评审:记错的认知每一轮都被注入,一晚最多 correct.maxCalls 次(乘 sleepScale,节省档 2 次)、几分钱,见 docs/花费.md)。
62
62
  * 第 11 步(D124)节省档只做纯代码的那一半(定哪些经验放进常驻区),不调模型。 */
63
63
  const ESSENTIAL = new Set([0, 1, 2, 5, 6, 7, 9, 10, 11]);
64
64
 
@@ -159,6 +159,24 @@ export function sleepCallPlan(p) {
159
159
  return { total, sum, steps, reserve };
160
160
  }
161
161
 
162
+ /**
163
+ * 【D176】这套配置(core.config.get() 的快照)下夜里整理一晚最多做多少,给管理页写给人看:整晚最多几次模型、
164
+ * 对照原话最多核几条、泛化最多问几组、印象最多更新几个人。节省档不做的(泛化)记 0。
165
+ * @param {object} cfg
166
+ * @returns {{scale: number, depth: string, calls: number, correctFacts: number, generalizeGroups: number, impressionPeople: number}}
167
+ */
168
+ export function sleepSummary(cfg) {
169
+ const p = params({ config: { get: () => cfg } });
170
+ const plan = sleepCallPlan(p);
171
+ const steps = plan.steps;
172
+ return {
173
+ scale: p.scale, depth: p.depth, calls: plan.total,
174
+ correctFacts: (steps.get(2) ?? 0) * (Number(p.correct.perCall) || 0),
175
+ generalizeGroups: (steps.get(3) ?? 0) * (Number(p.generalize.groupsPerCall) || 0),
176
+ impressionPeople: Math.max(0, Number(p.impressions.perCall) || 0),
177
+ };
178
+ }
179
+
162
180
  /** 第 n 步这次能用到第几次(run.max):不超过它自己登记的次数,也不动后面保留的名额。 */
163
181
  function stepLimit(plan, n, calls) {
164
182
  let later = 0;
@@ -384,6 +402,22 @@ const short = (d) => {
384
402
  return out;
385
403
  };
386
404
 
405
+ /** 【D175】最近每一晚的报告(管理页「记忆 → 做梦」按晚列出来):meta 'sleep.history',最多留这么多晚,同一次开始的只留一份。 */
406
+ const HISTORY_KEY = 'sleep.history';
407
+ const HISTORY_MAX = 30;
408
+ /** 一晚的报告 → 留底的样子:和 lastReport 一样只有数字和步名(detail 已经过 short)。 */
409
+ const slim = (r) => ({
410
+ startedAt: r.startedAt, finishedAt: r.finishedAt, llmCalls: r.llmCalls ?? 0, llmMax: r.llmMax ?? null, capped: [...new Set(r.capped ?? [])].slice(0, 12),
411
+ steps: (r.steps ?? []).slice(0, 16).map((s) => ({ step: s.step, name: s.name, ok: s.ok !== false, llmCalls: s.llmCalls ?? 0,
412
+ ...(s.skipped ? { skipped: String(s.skipped).slice(0, 40) } : {}), ...(s.capped ? { capped: true } : {}), ...(s.detail ? { detail: s.detail } : {}) })),
413
+ });
414
+ function pushHistory(core, report) {
415
+ const prev = getMetaJson(core.store, HISTORY_KEY);
416
+ const list = (Array.isArray(prev) ? prev : []).filter((x) => x && Number.isFinite(x.startedAt) && x.startedAt !== report.startedAt);
417
+ list.push(slim(report));
418
+ setMetaJson(core.store, HISTORY_KEY, list.slice(-HISTORY_MAX));
419
+ }
420
+
387
421
  async function runSleep(core, at, signal) {
388
422
  const p = params(core);
389
423
  const plan = sleepCallPlan(p);
@@ -495,6 +529,7 @@ async function runSleep(core, at, signal) {
495
529
  if (!signal?.aborted) {
496
530
  setMeta(core.store, 'sleep.lastAt', at);
497
531
  try { setMetaJson(core.store, 'sleep.lastReport', report); } catch { /* 报告存不下不影响 */ }
532
+ try { pushHistory(core, report); } catch { /* 留底存不下不影响 */ }
498
533
  }
499
534
  metric(core, 'sleep.runs');
500
535
  metric(core, 'sleep.llmCalls', run.calls);
package/src/index.js CHANGED
@@ -3,7 +3,9 @@
3
3
  // 配置和端口的帮手。各模块的内部函数不从这里导出,集成层只调 API(§3.5 第 2 条)。
4
4
  export { createPersonaMemory, CAPABILITIES, llmTrial } from './api.js';
5
5
  export * from './contract/index.js';
6
- export { DEFAULTS, createConfig, mergeConfig, budgetLimits, BUDGET_OVERRIDE_KEYS, checkBudgetOverride, RETENTION_MS, MODE_RANK, ROOM_MIN, ROOM_MAX } from './config/defaults.js';
6
+ export { DEFAULTS, createConfig, mergeConfig, budgetLimits, BUDGET_OVERRIDE_KEYS, checkBudgetOverride, RETENTION_MS, MODE_RANK, ROOM_MIN, ROOM_MAX, SLEEP_SCALE_MIN, SLEEP_SCALE_MAX } from './config/defaults.js';
7
+ // D176:夜里整理一晚最多做多少(随花费档位的 sleepScale)——管理页「花费护栏」据此写给人看,不在页面里重算
8
+ export { sleepSummary } from './consolidate/index.js';
7
9
  // D165:回想各层生效的上限(随花费档位的 room)——集成层据此让自己的块上限跟着核心走,不另截核心决定要给的东西
8
10
  export { recallCaps } from './config/caps.js';
9
11
  export { normalizePorts, systemClock, nullLogger, unlimitedBudget, emptySelfProfile } from './ports/index.js';