rugu-core 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +9 -3
- package/package.json +54 -6
- package/src/admin/derive.js +114 -0
- package/src/admin/feed.js +325 -0
- package/src/admin/index.js +464 -0
- package/src/admin/notify.js +26 -0
- package/src/admin/params.js +17 -0
- package/src/admin/purge.js +764 -0
- package/src/admin/retention.js +223 -0
- package/src/admin/review.js +505 -0
- package/src/admin/rules.js +243 -0
- package/src/admin/simulate.js +106 -0
- package/src/admin/starmap.js +553 -0
- package/src/admin/suppress.js +384 -0
- package/src/admin/timeline.js +266 -0
- package/src/admin/views.js +839 -0
- package/src/api.js +602 -0
- package/src/backup/crypto.js +197 -0
- package/src/backup/export.js +72 -0
- package/src/backup/format.js +255 -0
- package/src/backup/index.js +299 -0
- package/src/backup/packs.js +621 -0
- package/src/backup/restore.js +318 -0
- package/src/backup/sqlite-task.js +403 -0
- package/src/backup/thread.js +48 -0
- package/src/backup/util.js +149 -0
- package/src/config/caps.js +167 -0
- package/src/config/defaults.js +1003 -0
- package/src/consolidate/communities.js +195 -0
- package/src/consolidate/correct.js +490 -0
- package/src/consolidate/echo.js +63 -0
- package/src/consolidate/generalize.js +310 -0
- package/src/consolidate/growth.js +421 -0
- package/src/consolidate/impressions.js +262 -0
- package/src/consolidate/index.js +166 -0
- package/src/consolidate/lessons.js +171 -0
- package/src/consolidate/memory.js +371 -0
- package/src/consolidate/params.js +60 -0
- package/src/consolidate/reflect.js +191 -0
- package/src/consolidate/self.js +181 -0
- package/src/consolidate/sleep.js +521 -0
- package/src/consolidate/storyline.js +199 -0
- package/src/consolidate/time.js +163 -0
- package/src/consolidate/today.js +229 -0
- package/src/consolidate/util.js +264 -0
- package/src/context/diag.js +221 -0
- package/src/context/index.js +318 -0
- package/src/context/ledger.js +570 -0
- package/src/context/look.js +241 -0
- package/src/context/pack.js +338 -0
- package/src/context/people.js +139 -0
- package/src/context/recall.js +1604 -0
- package/src/context/recollect.js +132 -0
- package/src/context/resident.js +388 -0
- package/src/context/since.js +207 -0
- package/src/context/text.js +122 -0
- package/src/context/working.js +723 -0
- package/src/contract/enums.js +56 -0
- package/src/contract/errors.js +38 -0
- package/src/contract/ids.js +67 -0
- package/src/contract/index.js +7 -0
- package/src/contract/setting.js +45 -0
- package/src/contract/types.js +395 -0
- package/src/contract/validate.js +651 -0
- package/src/core-types.js +244 -0
- package/src/discretion/egress.js +850 -0
- package/src/discretion/expire.js +53 -0
- package/src/discretion/facts.js +539 -0
- package/src/discretion/gate.js +329 -0
- package/src/discretion/glance.js +715 -0
- package/src/discretion/index.js +554 -0
- package/src/discretion/knowledge.js +485 -0
- package/src/discretion/match.js +131 -0
- package/src/discretion/norms.js +771 -0
- package/src/discretion/stage1.js +444 -0
- package/src/discretion/stage2.js +680 -0
- package/src/discretion/told.js +441 -0
- package/src/discretion/trial.js +40 -0
- package/src/discretion/util.js +217 -0
- package/src/discretion/working.js +388 -0
- package/src/dynamics/actr.js +218 -0
- package/src/dynamics/index.js +792 -0
- package/src/encode/extract.js +811 -0
- package/src/encode/index.js +620 -0
- package/src/encode/lessons.js +580 -0
- package/src/encode/parse.js +41 -0
- package/src/encode/plans.js +406 -0
- package/src/encode/prompt.js +390 -0
- package/src/encode/reconcile.js +199 -0
- package/src/encode/review.js +177 -0
- package/src/encode/segment.js +308 -0
- package/src/encode/stalled.js +137 -0
- package/src/encode/support.js +202 -0
- package/src/encode/taint.js +64 -0
- package/src/encode/tools.js +515 -0
- package/src/encode/trial.js +38 -0
- package/src/encode/util.js +264 -0
- package/src/encode/verify.js +561 -0
- package/src/encode/write.js +740 -0
- package/src/entities/impressions.js +133 -0
- package/src/entities/index.js +681 -0
- package/src/entities/links.js +213 -0
- package/src/entities/matcher.js +125 -0
- package/src/entities/normalize.js +92 -0
- package/src/entities/own.js +89 -0
- package/src/entities/params.js +22 -0
- package/src/entities/records.js +330 -0
- package/src/entities/repair.js +164 -0
- package/src/entities/resolve.js +855 -0
- package/src/index.js +10 -0
- package/src/intake/hash.js +118 -0
- package/src/intake/index.js +1862 -0
- package/src/intake/media.js +223 -0
- package/src/intake/sanitize.js +118 -0
- package/src/intake/windows.js +271 -0
- package/src/lang/index.js +508 -0
- package/src/lang/text.js +147 -0
- package/src/lang/time.js +405 -0
- package/src/lang/unicode.js +59 -0
- package/src/lang/when.js +186 -0
- package/src/lang/zh.js +664 -0
- package/src/maintenance.js +83 -0
- package/src/ports/index.js +210 -0
- package/src/ports/llm-text.js +193 -0
- package/src/retrieve/background.js +180 -0
- package/src/retrieve/cues.js +342 -0
- package/src/retrieve/fan.js +84 -0
- package/src/retrieve/fuse.js +85 -0
- package/src/retrieve/hydrate.js +171 -0
- package/src/retrieve/index.js +402 -0
- package/src/retrieve/intent.js +231 -0
- package/src/retrieve/level.js +138 -0
- package/src/retrieve/merge.js +80 -0
- package/src/retrieve/names.js +56 -0
- package/src/retrieve/outline.js +113 -0
- package/src/retrieve/params.js +46 -0
- package/src/retrieve/past.js +70 -0
- package/src/retrieve/pipeline.js +868 -0
- package/src/retrieve/prefetch.js +276 -0
- package/src/retrieve/recollect-util.js +26 -0
- package/src/retrieve/recollect.js +451 -0
- package/src/retrieve/render.js +527 -0
- package/src/retrieve/routes.js +673 -0
- package/src/retrieve/scope.js +253 -0
- package/src/retrieve/util.js +143 -0
- package/src/retrieve/working.js +884 -0
- package/src/store/db.js +277 -0
- package/src/store/expire.js +35 -0
- package/src/store/fts.js +167 -0
- package/src/store/index.js +76 -0
- package/src/store/invariants.js +49 -0
- package/src/store/jobs.js +144 -0
- package/src/store/keys.js +140 -0
- package/src/store/kv.js +60 -0
- package/src/store/migrate.js +67 -0
- package/src/store/migrations/001-store.js +81 -0
- package/src/store/migrations/002-intake.js +142 -0
- package/src/store/migrations/003-entities.js +130 -0
- package/src/store/migrations/004-encode.js +189 -0
- package/src/store/migrations/005-dynamics.js +59 -0
- package/src/store/migrations/006-discretion.js +184 -0
- package/src/store/migrations/007-context.js +57 -0
- package/src/store/migrations/008-consolidate.js +60 -0
- package/src/store/migrations/009-worker.js +54 -0
- package/src/store/migrations/010-admin.js +85 -0
- package/src/store/migrations/011-backup.js +42 -0
- package/src/store/migrations/012-discretion.js +19 -0
- package/src/store/migrations/013-discretion.js +44 -0
- package/src/store/migrations/014-discretion.js +16 -0
- package/src/store/migrations/015-intake.js +24 -0
- package/src/store/migrations/016-intake.js +16 -0
- package/src/store/migrations/017-consolidate.js +38 -0
- package/src/store/migrations/018-encode.js +30 -0
- package/src/store/migrations/019-encode.js +16 -0
- package/src/store/migrations/020-retrieve.js +20 -0
- package/src/store/migrations/021-discretion.js +20 -0
- package/src/store/migrations/022-admin.js +21 -0
- package/src/store/migrations/023-admin.js +18 -0
- package/src/store/migrations/index.js +33 -0
- package/src/store/refs.js +59 -0
- package/src/store/vectors.js +121 -0
- package/src/worker/client.js +97 -0
- package/src/worker/engine.js +529 -0
- package/src/worker/graph.js +259 -0
- package/src/worker/index.js +1898 -0
- package/src/worker/maint.js +86 -0
- package/src/worker/probes.js +25 -0
- package/src/worker/quant.js +135 -0
- package/src/worker/thread.js +57 -0
- package/src/worker/vindex.js +207 -0
- package/test/eval/memory-eval.js +475 -0
- package/test/fakes/budget.js +45 -0
- package/test/fakes/clock.js +29 -0
- package/test/fakes/embedding.js +106 -0
- package/test/fakes/index.js +9 -0
- package/test/fakes/llm.js +80 -0
- package/test/fakes/logger.js +24 -0
- package/test/fakes/ports.js +27 -0
- package/test/fakes/self-profile.js +19 -0
- package/test/fakes/test-core.js +84 -0
- package/test/fakes/tmp.js +22 -0
- package/test/fixtures/fake-platform.js +226 -0
- package/test/fixtures/paraphrase-pairs.js +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 QiuYeDx
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# rugu-core
|
|
2
|
+
|
|
3
|
+
[如故(dsh-rugu)](https://github.com/QiuYeDx/dsh-rugu)的记忆核心。一个人设只有一段人生:感知入库、认人认物、情节与事实、激活与遗忘、五路回想、分寸判断。
|
|
4
|
+
|
|
5
|
+
它不认识任何宿主和入口(零宿主依赖,Node ≥ 22.16,`node:sqlite`),由宿主实现 LLM、嵌入、重排、预算这些端口再接上来。一般不需要直接装它:在 DeepSeek Harness 里装 `dsh-rugu` 就会带上。
|
|
6
|
+
|
|
7
|
+
接口说明见仓库的 [docs/实现/模块与接口.md](https://github.com/QiuYeDx/dsh-rugu/blob/main/docs/实现/模块与接口.md)。
|
|
8
|
+
|
|
9
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "rugu-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "rugu-core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "如故的记忆核心:一个人设只有一段人生——感知入库、认人认物、情节与事实、激活与遗忘、五路回想、分寸判断。不认识任何宿主和入口。",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"memory",
|
|
7
|
+
"persona",
|
|
8
|
+
"agent-memory",
|
|
9
|
+
"rugu"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "QiuYeDx",
|
|
13
|
+
"homepage": "https://github.com/QiuYeDx/dsh-rugu#readme",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/QiuYeDx/dsh-rugu.git",
|
|
17
|
+
"directory": "packages/core"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/QiuYeDx/dsh-rugu/issues"
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "./src/index.js",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./src/index.js",
|
|
26
|
+
"./contract": "./src/contract/index.js",
|
|
27
|
+
"./testing": "./test/fakes/index.js",
|
|
28
|
+
"./testing/fake-platform": "./test/fixtures/fake-platform.js",
|
|
29
|
+
"./package.json": "./package.json",
|
|
30
|
+
"./testing/memory-eval": "./test/eval/memory-eval.js"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"src",
|
|
34
|
+
"test/fakes",
|
|
35
|
+
"test/fixtures",
|
|
36
|
+
"test/eval/memory-eval.js",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22.16"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@node-rs/jieba": "*"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"@node-rs/jieba": {
|
|
48
|
+
"optional": true
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"test": "node ../../scripts/run-tests.mjs core"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// 派生关系(隐藏的级联、彻底删除的展开、墓碑重删共用)。只读:主库上走 encode.derivedFrom(契约),
|
|
2
|
+
// 解开的备份副本上(或 encode 不可用时)用同样语义的 SQL。
|
|
3
|
+
// - 证据感知:一条记忆是从哪几条感知来的(sources.percept_id;情节另加归进它的感知;窗口是它的成员)。
|
|
4
|
+
// - 窗口成员看 members_json(intake 按(场合,visible_to)分别切窗口,D53:同一段 id 范围里可能是别的窗口)。
|
|
5
|
+
import { refOf } from '../store/refs.js';
|
|
6
|
+
|
|
7
|
+
/** 各主表「这一行是什么时候有的」那一列:墓碑按时间生效(D42),主表 id 不是 AUTOINCREMENT,删掉最新的一行之后新行会拿到同一个 id。 */
|
|
8
|
+
export const CREATED = Object.freeze({
|
|
9
|
+
percept: 'created_at', window: 'created_at', episode: 'created_at', assertion: 'created_at', entity: 'created_at',
|
|
10
|
+
impression: 'built_at', intention: 'created_at', storyline: 'updated_at', community: 'built_at', link: 'at',
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const tableCache = new WeakMap();
|
|
14
|
+
function cacheOf(db) {
|
|
15
|
+
let m = tableCache.get(db);
|
|
16
|
+
if (!m) { m = new Map(); tableCache.set(db, m); }
|
|
17
|
+
return m;
|
|
18
|
+
}
|
|
19
|
+
export function hasTable(db, name) {
|
|
20
|
+
const m = cacheOf(db);
|
|
21
|
+
if (!m.has(name)) m.set(name, !!db.get("SELECT 1 FROM sqlite_schema WHERE name = ? AND type IN ('table')", name));
|
|
22
|
+
return m.get(name);
|
|
23
|
+
}
|
|
24
|
+
export function hasColumn(db, table, col) {
|
|
25
|
+
const key = `${table}.${col}`;
|
|
26
|
+
const m = cacheOf(db);
|
|
27
|
+
if (!m.has(key)) m.set(key, hasTable(db, table) && db.all(`PRAGMA table_info(${table})`).some((c) => c.name === col));
|
|
28
|
+
return m.get(key);
|
|
29
|
+
}
|
|
30
|
+
export const parseIds = (s) => {
|
|
31
|
+
try { const v = JSON.parse(s ?? '[]'); return Array.isArray(v) ? v.filter((x) => Number.isSafeInteger(x)) : []; } catch { return []; }
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** 和 encode.derivedFrom 同样语义的 SQL(备份副本上用):别的证据 = 别的感知,或没有感知的导入 / 推断 / 她自己生成的来源。 */
|
|
35
|
+
function derivedSql(db, perceptId) {
|
|
36
|
+
if (!hasTable(db, 'sources')) return [];
|
|
37
|
+
const out = db.all(`SELECT s.owner_kind AS kind, s.owner_id AS id,
|
|
38
|
+
(SELECT count(*) FROM sources s2 WHERE s2.owner_kind = s.owner_kind AND s2.owner_id = s.owner_id
|
|
39
|
+
AND ((s2.percept_id IS NOT NULL AND s2.percept_id <> ?)
|
|
40
|
+
OR (s2.percept_id IS NULL AND s2.mode IN ('imported','inferred','self_generated')))) AS others
|
|
41
|
+
FROM sources s WHERE s.percept_id = ? GROUP BY s.owner_kind, s.owner_id`, perceptId, perceptId)
|
|
42
|
+
.map((r) => ({ ref: refOf(r.kind, r.id), onlySource: Number(r.others) === 0 }));
|
|
43
|
+
if (hasColumn(db, 'percepts', 'episode_id')) {
|
|
44
|
+
const p = db.get('SELECT episode_id FROM percepts WHERE id = ?', perceptId);
|
|
45
|
+
if (p?.episode_id && !out.some((x) => x.ref === refOf('episode', p.episode_id))) {
|
|
46
|
+
const n = Number(db.get('SELECT count(*) AS n FROM percepts WHERE episode_id = ? AND id <> ?', p.episode_id, perceptId).n);
|
|
47
|
+
out.push({ ref: refOf('episode', p.episode_id), onlySource: n === 0 });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 以这条感知为来源的记忆。
|
|
55
|
+
* @param {object} core
|
|
56
|
+
* @param {import('../store/db.js').Store} db
|
|
57
|
+
* @param {number} perceptId
|
|
58
|
+
* @returns {{ref: string, onlySource: boolean}[]}
|
|
59
|
+
*/
|
|
60
|
+
export function derivedOf(core, db, perceptId) {
|
|
61
|
+
if (db === core.store) {
|
|
62
|
+
try { const r = core.mods.encode.derivedFrom(core, perceptId); if (Array.isArray(r)) return r; } catch { /* 退回 SQL */ }
|
|
63
|
+
}
|
|
64
|
+
return derivedSql(db, perceptId);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 包含这条感知的原文窗口(看成员;没有成员记录的老窗口按 id 范围算,只在同一个场合里找)。 */
|
|
68
|
+
export function windowsContaining(db, perceptId) {
|
|
69
|
+
if (!hasTable(db, 'raw_windows')) return [];
|
|
70
|
+
const p = hasTable(db, 'percepts') ? db.get('SELECT setting_key FROM percepts WHERE id = ?', perceptId) : null;
|
|
71
|
+
const rows = p
|
|
72
|
+
? db.all('SELECT id, members_json FROM raw_windows WHERE setting_key = ? AND first_percept <= ? AND last_percept >= ?', p.setting_key, perceptId, perceptId)
|
|
73
|
+
: db.all('SELECT id, members_json FROM raw_windows WHERE first_percept <= ? AND last_percept >= ?', perceptId, perceptId);
|
|
74
|
+
const out = [];
|
|
75
|
+
for (const w of rows) {
|
|
76
|
+
const members = parseIds(w.members_json);
|
|
77
|
+
if (members.length ? members.includes(perceptId) : !!p) out.push(w.id);
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 窗口的成员感知。 */
|
|
83
|
+
export function windowMembers(db, windowId) {
|
|
84
|
+
const w = hasTable(db, 'raw_windows') ? db.get('SELECT members_json FROM raw_windows WHERE id = ?', windowId) : null;
|
|
85
|
+
if (!w) return [];
|
|
86
|
+
const members = parseIds(w.members_json);
|
|
87
|
+
if (members.length) return members;
|
|
88
|
+
return hasColumn(db, 'percepts', 'window_id') ? db.all('SELECT id FROM percepts WHERE window_id = ? ORDER BY id', windowId).map((r) => r.id) : [];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 一条记忆的证据感知。
|
|
93
|
+
* @param {import('../store/db.js').Store} db
|
|
94
|
+
* @param {{kind: string, id: number}} m
|
|
95
|
+
* @returns {number[]}
|
|
96
|
+
*/
|
|
97
|
+
export function evidencePercepts(db, m) {
|
|
98
|
+
if (m.kind === 'percept') return [m.id];
|
|
99
|
+
if (m.kind === 'window') return windowMembers(db, m.id);
|
|
100
|
+
const ids = new Set();
|
|
101
|
+
if (hasTable(db, 'sources')) {
|
|
102
|
+
for (const r of db.all('SELECT DISTINCT percept_id AS p FROM sources WHERE owner_kind = ? AND owner_id = ? AND percept_id IS NOT NULL', m.kind, m.id)) ids.add(r.p);
|
|
103
|
+
}
|
|
104
|
+
if (m.kind === 'episode' && hasColumn(db, 'percepts', 'episode_id')) {
|
|
105
|
+
for (const r of db.all('SELECT id FROM percepts WHERE episode_id = ?', m.id)) ids.add(r.id);
|
|
106
|
+
}
|
|
107
|
+
return [...ids].sort((a, b) => a - b);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 情节的种类(event / summary / diary / lapse / import)。 */
|
|
111
|
+
export function episodeKind(db, id) {
|
|
112
|
+
if (!hasColumn(db, 'episodes', 'ep_kind')) return null;
|
|
113
|
+
return db.get('SELECT ep_kind FROM episodes WHERE id = ?', id)?.ep_kind ?? null;
|
|
114
|
+
}
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// 【D171】管理页「记忆」这一路的两个只读视图:
|
|
2
|
+
// - feed:事实、经历、打算、经验按时间混排的一个列表(「全部」类型),游标翻页,筛选和单种列表同一套口径;
|
|
3
|
+
// - people:人物卡片(一个人一项,D161 的分组;名下有多少条、最近一次出现、一句印象),给 id 时是一个人的详情(各档案的名字、关系、印象、链接)。
|
|
4
|
+
// 口径不另起一套:每一种的条件、时间列、搜索、取出来的形状都直接用 views.js 里那个列表的 spec(assertions / episodes / intentions / lessons,
|
|
5
|
+
// 带 SPEC_ONLY 拿条件不取行),时间筛选和搜索用 timeline.js 的 scopeOf(D159),按人筛用 entityFilter(D161,连同他名下全部档案)。
|
|
6
|
+
// 只读:只有 SELECT,只读库也能用。SQL 一律参数化。
|
|
7
|
+
import { ContractError } from '../contract/errors.js';
|
|
8
|
+
import { scopeOf, dayCounts, limitOf, tzOf } from './timeline.js';
|
|
9
|
+
import { LIST_VIEWS, SPEC_ONLY, entityFilter, personGroups } from './views.js';
|
|
10
|
+
|
|
11
|
+
const bad = (path, message) => new ContractError('admin.feed', [{ path, message }]);
|
|
12
|
+
|
|
13
|
+
/** 混排的四种(页面的「全部」)。顺序也是同一时刻里的次序。 */
|
|
14
|
+
export const FEED_KINDS = Object.freeze(['fact', 'episode', 'intent', 'lesson']);
|
|
15
|
+
const RANK = { fact: 0, episode: 1, intent: 2, lesson: 3 };
|
|
16
|
+
const OWNER = { fact: 'assertion', episode: 'episode', intent: 'intention', lesson: 'assertion' };
|
|
17
|
+
/** 状态:shown = 没忘掉的(隐藏的照列,带标记;默认)/ active = 没隐藏也没忘掉 / hidden / forgotten / all。 */
|
|
18
|
+
export const FEED_STATES = Object.freeze(['shown', 'active', 'hidden', 'forgotten', 'all']);
|
|
19
|
+
/** 版本(事实和经验才有):current = 现在这一版(默认)/ all = 连旧版本 / old = 只看被取代的旧版本(只剩事实和经验两种)。 */
|
|
20
|
+
export const FEED_VERSIONS = Object.freeze(['current', 'all', 'old']);
|
|
21
|
+
|
|
22
|
+
function optsOf(q) {
|
|
23
|
+
const kinds = q.kinds == null ? [...FEED_KINDS] : Array.isArray(q.kinds) ? [...new Set(q.kinds)] : null;
|
|
24
|
+
if (!kinds || !kinds.length || kinds.some((k) => !FEED_KINDS.includes(k))) throw bad('kinds', `应为 ${FEED_KINDS.join(' / ')} 的非空数组`);
|
|
25
|
+
const state = q.state == null ? 'shown' : q.state;
|
|
26
|
+
if (!FEED_STATES.includes(state)) throw bad('state', `应为 ${FEED_STATES.join(' / ')}`);
|
|
27
|
+
const versions = q.versions == null ? 'current' : q.versions;
|
|
28
|
+
if (!FEED_VERSIONS.includes(versions)) throw bad('versions', `应为 ${FEED_VERSIONS.join(' / ')}`);
|
|
29
|
+
const order = q.order == null ? 'desc' : q.order;
|
|
30
|
+
if (order !== 'desc' && order !== 'asc') throw bad('order', '应为 desc / asc');
|
|
31
|
+
return {
|
|
32
|
+
kinds, state, versions, order,
|
|
33
|
+
lessonStatus: q.lessonStatus === 'verified' || q.lessonStatus === 'unverified' ? q.lessonStatus : null,
|
|
34
|
+
entityId: Number.isSafeInteger(q.entityId) ? q.entityId : null,
|
|
35
|
+
settingKey: typeof q.settingKey === 'string' && q.settingKey ? q.settingKey : null,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 状态条件(suppressions 的主键是 (owner_kind, owner_id):一次主键查找)。 */
|
|
40
|
+
function stateWhere(spec, okind, state) {
|
|
41
|
+
const sub = `SELECT 1 FROM suppressions s WHERE s.owner_kind = '${okind}' AND s.owner_id = t.id`;
|
|
42
|
+
if (state === 'shown') spec.where.push(`NOT EXISTS (${sub} AND s.state = 'forgotten')`);
|
|
43
|
+
else if (state === 'active') spec.where.push(`NOT EXISTS (${sub})`);
|
|
44
|
+
else if (state === 'hidden' || state === 'forgotten') { spec.where.push(`EXISTS (${sub} AND s.state = ?)`); spec.params.push(state); }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 这一次要合并的几路:{kind, spec}。spec 就是那个单种列表的 spec,再加上混排要的条件。 */
|
|
48
|
+
function sourcesOf(core, o) {
|
|
49
|
+
const base = { [SPEC_ONLY]: true };
|
|
50
|
+
const who = o.entityId != null ? { entityId: o.entityId } : {};
|
|
51
|
+
const out = [];
|
|
52
|
+
const want = (k) => o.kinds.includes(k);
|
|
53
|
+
if (want('fact')) {
|
|
54
|
+
const s = LIST_VIEWS.assertions(core, { ...base, ...who, ...(o.settingKey ? { settingKey: o.settingKey } : {}), ...(o.versions === 'current' ? { current: true } : {}) });
|
|
55
|
+
s.where.push("(t.kind_hint IS NULL OR t.kind_hint <> 'lesson')");
|
|
56
|
+
if (o.versions === 'old') s.where.push('t.superseded_by IS NOT NULL');
|
|
57
|
+
stateWhere(s, 'assertion', o.state);
|
|
58
|
+
out.push({ kind: 'fact', spec: s });
|
|
59
|
+
}
|
|
60
|
+
if (want('episode') && o.versions !== 'old') {
|
|
61
|
+
const s = LIST_VIEWS.episodes(core, { ...base, ...who, ...(o.settingKey ? { settingKey: o.settingKey } : {}) });
|
|
62
|
+
stateWhere(s, 'episode', o.state);
|
|
63
|
+
out.push({ kind: 'episode', spec: s });
|
|
64
|
+
}
|
|
65
|
+
// 打算没有场合(intentions 表不记):按场合筛时不列
|
|
66
|
+
if (want('intent') && o.versions !== 'old' && !o.settingKey) {
|
|
67
|
+
const s = LIST_VIEWS.intentions(core, { ...base, ...who });
|
|
68
|
+
s.search = { textSql: "coalesce(t.text, '')", fts: null };
|
|
69
|
+
stateWhere(s, 'intention', o.state);
|
|
70
|
+
out.push({ kind: 'intent', spec: s });
|
|
71
|
+
}
|
|
72
|
+
if (want('lesson')) {
|
|
73
|
+
const s = LIST_VIEWS.lessons(core, { ...base, all: o.versions !== 'current', ...(o.lessonStatus ? { status: o.lessonStatus } : {}) });
|
|
74
|
+
if (o.versions === 'old') s.where.push('t.superseded_by IS NOT NULL');
|
|
75
|
+
entityFilter(core, s.where, s.params, who, (ph) => `t.id IN (SELECT assertion_id FROM assertion_entities WHERE entity_id IN (${ph}))`);
|
|
76
|
+
if (o.settingKey) { s.where.push("t.id IN (SELECT owner_id FROM sources WHERE owner_kind = 'assertion' AND perceived_in = ?)"); s.params.push(o.settingKey); }
|
|
77
|
+
s.search = { textSql: 't.text', fts: 'assertions_fts' };
|
|
78
|
+
stateWhere(s, 'assertion', o.state);
|
|
79
|
+
out.push({ kind: 'lesson', spec: s });
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 一路在时间范围、搜索之下的全部条件(timeline 的 scopeOf;按时间排时搜索命中当 WHERE 条件)。 */
|
|
85
|
+
function scoped(core, q, src) {
|
|
86
|
+
const sc = scopeOf(core, q, src.spec);
|
|
87
|
+
if (sc.found) { sc.where.push(sc.found.cond); sc.params.push(...sc.found.args); }
|
|
88
|
+
return { ...src, where: sc.where, params: sc.params };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 一路往一个方向取的 SQL:up = 时间变大的方向。bound = {t, k, i}(合并后的次序是 (时间, 种类次序, id),不含 bound 本身)。
|
|
93
|
+
* 种类次序在一路里是常数,所以条件化成只比时间和 id 的形式,时间那一半能走索引。
|
|
94
|
+
*/
|
|
95
|
+
function seekSql(src, up, bound, n) {
|
|
96
|
+
const T = src.spec.time;
|
|
97
|
+
const conds = [...src.where];
|
|
98
|
+
const args = [...src.params];
|
|
99
|
+
if (bound) {
|
|
100
|
+
const k = RANK[src.kind];
|
|
101
|
+
const gt = up ? '>' : '<';
|
|
102
|
+
if (k === bound.k) { conds.push(`${T} ${gt}= ? AND (${T} ${gt} ? OR t.id ${gt} ?)`); args.push(bound.t, bound.t, bound.i); }
|
|
103
|
+
// 比边界那一条种类次序「靠后」的:同一时刻的都算在边界之后
|
|
104
|
+
else if ((k > bound.k) === up) { conds.push(`${T} ${gt}= ?`); args.push(bound.t); }
|
|
105
|
+
else { conds.push(`${T} ${gt} ?`); args.push(bound.t); }
|
|
106
|
+
}
|
|
107
|
+
const d = up ? 'ASC' : 'DESC';
|
|
108
|
+
return { sql: `SELECT ${src.spec.select ?? '*'}, ${T} AS _t, t.id AS _k FROM ${src.spec.from} ${conds.length ? `WHERE ${conds.join(' AND ')}` : ''} ORDER BY ${T} ${d}, t.id ${d} LIMIT ?`, args: [...args, n] };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const cmpUp = (a, b) => (a._t - b._t) || (RANK[a._kind] - RANK[b._kind]) || (a._k - b._k);
|
|
112
|
+
/** 几路一起往一个方向取 n 条(每路取 n 条再合并,按那个方向排好)。 */
|
|
113
|
+
function take(core, srcs, up, bound, n) {
|
|
114
|
+
const all = [];
|
|
115
|
+
for (const s of srcs) {
|
|
116
|
+
const { sql, args } = seekSql(s, up, bound, n);
|
|
117
|
+
for (const r of core.store.all(sql, ...args)) { r._kind = s.kind; r._src = s; all.push(r); }
|
|
118
|
+
}
|
|
119
|
+
all.sort(up ? cmpUp : (a, b) => cmpUp(b, a));
|
|
120
|
+
return all.slice(0, n);
|
|
121
|
+
}
|
|
122
|
+
const keyOf = (r) => ({ t: Number(r._t), k: RANK[r._kind], i: Number(r._k) });
|
|
123
|
+
const enc = (r, d) => { const k = keyOf(r); return Buffer.from(JSON.stringify({ v: 2, t: k.t, k: k.k, i: k.i, d })).toString('base64url'); };
|
|
124
|
+
function dec(s, d) {
|
|
125
|
+
if (typeof s !== 'string' || !s || s.length > 400) return null;
|
|
126
|
+
try {
|
|
127
|
+
const c = JSON.parse(Buffer.from(s, 'base64url').toString('utf8'));
|
|
128
|
+
return c && c.v === 2 && c.d === d && Number.isFinite(c.t) && Number.isInteger(c.k) && Number.isFinite(c.i) ? { t: c.t, k: c.k, i: c.i } : null;
|
|
129
|
+
} catch { return null; }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 一行 → 页面要的形状(四种同一套字段,各自多几样)。 */
|
|
133
|
+
function shape(core, r, stmts) {
|
|
134
|
+
const x = r._src.spec.map(r);
|
|
135
|
+
const kind = r._kind;
|
|
136
|
+
if (kind === 'fact') {
|
|
137
|
+
const s = stmts.firstSource.get(x.id);
|
|
138
|
+
const subjects = (x.entities ?? []).filter((e) => e.role === 'subject').map((e) => e.entityId);
|
|
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
|
+
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 };
|
|
142
|
+
}
|
|
143
|
+
if (kind === 'episode') {
|
|
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,
|
|
145
|
+
settingKey: x.settingKey ?? null, participants: (Array.isArray(x.participants) ? x.participants : []).filter(Number.isSafeInteger).slice(0, 8), state: x.state ?? null };
|
|
146
|
+
}
|
|
147
|
+
if (kind === 'intent') {
|
|
148
|
+
return { ref: x.ref, kind, id: x.id, text: x.text || x.act || '', act: x.act, at: x.formedAt, who: x.targetEntityId ?? null, intentState: x.state, until: x.windowEnd ?? null,
|
|
149
|
+
executions: Array.isArray(x.executions) ? x.executions.length : 0, state: x.suppression ?? null };
|
|
150
|
+
}
|
|
151
|
+
return { ref: x.ref, kind, id: x.id, text: x.text, at: x.updatedAt, status: x.status, origin: x.origin ?? null, how: x.how ?? null, tool: x.tool ?? null, settingKey: x.settingKey ?? null,
|
|
152
|
+
trap: x.trap ?? null, confirmable: !!x.confirmable, supersededBy: x.supersededBy ?? null, about: (x.about ?? []).slice(0, 6), state: x.state ?? null };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 用到的场合和人的名字(和首页同一种形状:只给用到的,不列全表)。 */
|
|
156
|
+
function namesOf(core, items) {
|
|
157
|
+
const keys = new Set();
|
|
158
|
+
const ids = new Set();
|
|
159
|
+
for (const m of items) {
|
|
160
|
+
if (m.settingKey) keys.add(m.settingKey);
|
|
161
|
+
for (const id of [m.who, ...(m.participants ?? []), ...(m.subjects ?? []), ...(m.about ?? [])]) if (Number.isSafeInteger(id)) ids.add(id);
|
|
162
|
+
}
|
|
163
|
+
const settings = {};
|
|
164
|
+
const sq = core.store.prepare('SELECT key, label, label_kind, label_hint, owner_label FROM settings WHERE key = ?');
|
|
165
|
+
for (const k of keys) {
|
|
166
|
+
const r = sq.get(k);
|
|
167
|
+
if (!r) continue;
|
|
168
|
+
const owner = typeof r.owner_label === 'string' && r.owner_label ? r.owner_label : null;
|
|
169
|
+
settings[k] = { label: owner ?? r.label ?? '', labelKind: owner ? 'name' : r.label_kind === 'description' ? 'description' : 'name', hint: r.label_hint ?? null };
|
|
170
|
+
}
|
|
171
|
+
const names = {};
|
|
172
|
+
const eq = core.store.prepare('SELECT id, display_name, is_self, authority FROM entities WHERE id = ?');
|
|
173
|
+
for (const id of ids) {
|
|
174
|
+
const r = eq.get(id);
|
|
175
|
+
if (r) names[id] = { name: r.display_name ?? null, self: !!r.is_self, principal: r.authority === 'principal' };
|
|
176
|
+
}
|
|
177
|
+
return { settings, names };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 【D171】合并的记忆列表(管理页「记忆」的「全部」,也用于单选一种:kinds 只给一种)。
|
|
182
|
+
* q:kinds(fact / episode / intent / lesson 的数组,默认四种)、state(FEED_STATES,默认 shown)、versions(FEED_VERSIONS,默认 current)、
|
|
183
|
+
* lessonStatus、entityId(连同他名下全部档案,D161)、settingKey(打算没有场合,按场合筛时不列)、from / to(毫秒,闭区间,D159 同口径:
|
|
184
|
+
* 经历和 [开始, 结束] 相交)、q(搜索,D159 的三档,按时间排)、order(desc 默认 / asc)、limit、next / prev(游标)、around(毫秒:从这一刻起往
|
|
185
|
+
* 列表方向取,desc 取这一刻和更早的,asc 取这一刻和更晚的;那一边没有就退回另一边最近的)。
|
|
186
|
+
* 次序:(时间, 种类次序, id),每种用它自己列表的时间列(事实:记下的时间;经历:结束的时间;打算:想起的时间;经验:最近改过的时间)。
|
|
187
|
+
* 翻页:游标是边界那一条的 (时间, 种类次序, id),每一路按「严格在它之后」取 limit+1 条再合并,所以几种之间、同一时刻之间都不重不漏。
|
|
188
|
+
* 代价:每页每一路一条按时间列走索引的查询(事实 assertions_recorded、经验 assertions_lesson_updated、经历 episodes_t_end、打算
|
|
189
|
+
* intentions_formed;迁移 023 加的三个),再加每条事实一次 sources 主键查找;total 只在第一页(没有游标)时算,每一路一次 count。
|
|
190
|
+
* @returns {{items: object[], total: number|null, next?: string, prev?: string, anchor?: {at: number, side: 'before'|'after'}, order: string,
|
|
191
|
+
* kinds: string[], settings: object, names: object, readOnly: boolean}}
|
|
192
|
+
*/
|
|
193
|
+
export function feed(core, q = {}) {
|
|
194
|
+
const o = optsOf(q);
|
|
195
|
+
const limit = limitOf(core, q);
|
|
196
|
+
const sq = { from: Number.isFinite(q.from) ? q.from : undefined, to: Number.isFinite(q.to) ? q.to : undefined, q: typeof q.q === 'string' ? q.q.slice(0, 200) : undefined };
|
|
197
|
+
if (sq.from != null && sq.to != null && sq.from > sq.to) throw bad('to', '结束不能早于开始');
|
|
198
|
+
const srcs = sourcesOf(core, o).map((s) => scoped(core, sq, s));
|
|
199
|
+
const fwd = o.order === 'asc'; // 列表往下 = 时间变大?
|
|
200
|
+
let rows;
|
|
201
|
+
let next;
|
|
202
|
+
let prev;
|
|
203
|
+
let anchor;
|
|
204
|
+
const pc = dec(q.prev, o.order);
|
|
205
|
+
const nc = dec(q.next, o.order);
|
|
206
|
+
if (Number.isFinite(q.around)) {
|
|
207
|
+
const T = q.around;
|
|
208
|
+
const virt = fwd ? { t: T, k: -1, i: -1 } : { t: T, k: 99, i: Number.MAX_SAFE_INTEGER };
|
|
209
|
+
let r = take(core, srcs, fwd, virt, limit + 1);
|
|
210
|
+
anchor = { at: T, side: fwd ? 'after' : 'before' };
|
|
211
|
+
if (!r.length) {
|
|
212
|
+
// 那一边没有:退回另一边最近的一页
|
|
213
|
+
r = take(core, srcs, !fwd, virt, limit).reverse();
|
|
214
|
+
anchor = { at: T, side: fwd ? 'before' : 'after' };
|
|
215
|
+
rows = r;
|
|
216
|
+
next = undefined;
|
|
217
|
+
} else {
|
|
218
|
+
rows = r.slice(0, limit);
|
|
219
|
+
next = r.length > limit ? enc(rows.at(-1), o.order) : undefined;
|
|
220
|
+
}
|
|
221
|
+
prev = rows.length && take(core, srcs, !fwd, keyOf(rows[0]), 1).length ? enc(rows[0], o.order) : undefined;
|
|
222
|
+
} else if (pc) {
|
|
223
|
+
const r = take(core, srcs, !fwd, pc, limit + 1);
|
|
224
|
+
rows = r.slice(0, limit).reverse();
|
|
225
|
+
prev = r.length > limit ? enc(rows[0], o.order) : undefined;
|
|
226
|
+
next = rows.length && take(core, srcs, fwd, keyOf(rows.at(-1)), 1).length ? enc(rows.at(-1), o.order) : undefined;
|
|
227
|
+
} else {
|
|
228
|
+
const r = take(core, srcs, fwd, nc, limit + 1);
|
|
229
|
+
rows = r.slice(0, limit);
|
|
230
|
+
next = r.length > limit ? enc(rows.at(-1), o.order) : undefined;
|
|
231
|
+
prev = nc && rows.length && take(core, srcs, !fwd, keyOf(rows[0]), 1).length ? enc(rows[0], o.order) : undefined;
|
|
232
|
+
}
|
|
233
|
+
// total:只在第一页算(翻页时页面沿用第一页的数)
|
|
234
|
+
let total = null;
|
|
235
|
+
if (!pc && !nc) {
|
|
236
|
+
total = 0;
|
|
237
|
+
for (const s of srcs) total += Number(core.store.get(`SELECT count(*) AS n FROM ${s.spec.from} ${s.where.length ? `WHERE ${s.where.join(' AND ')}` : ''}`, ...s.params).n);
|
|
238
|
+
}
|
|
239
|
+
const stmts = { firstSource: core.store.prepare("SELECT perceived_in, speaker FROM sources WHERE owner_kind = 'assertion' AND owner_id = ? ORDER BY at, id LIMIT 1") };
|
|
240
|
+
const restore = core.store.prepare('SELECT restore_until FROM suppressions WHERE owner_kind = ? AND owner_id = ?');
|
|
241
|
+
const items = rows.map((r) => {
|
|
242
|
+
const m = shape(core, r, stmts);
|
|
243
|
+
if (m.state === 'forgotten') m.restoreUntil = restore.get(OWNER[m.kind], m.id)?.restore_until ?? null;
|
|
244
|
+
return m;
|
|
245
|
+
});
|
|
246
|
+
return { items, total, ...(next ? { next } : {}), ...(prev ? { prev } : {}), ...(anchor ? { anchor } : {}), order: o.order,
|
|
247
|
+
kinds: srcs.map((s) => s.kind), ...namesOf(core, items), readOnly: !!core.readOnly };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* 【D171】合并列表的按天计数(「跳到某一天」的月历):同样的条件下某个月每天几条(四种加起来),和最早、最晚一条的时间。
|
|
252
|
+
* 每一路调 timeline.js 的 dayCounts(D159 同口径:有起止的算在结束那天)。
|
|
253
|
+
* @param {object} q month: 'YYYY-MM'、tzOffsetMin?,其余同 feed
|
|
254
|
+
*/
|
|
255
|
+
export function feedDays(core, q = {}) {
|
|
256
|
+
const o = optsOf(q);
|
|
257
|
+
if (typeof q.month !== 'string' || !/^\d{4}-(0[1-9]|1[0-2])$/.test(q.month)) throw bad('month', '应为 YYYY-MM');
|
|
258
|
+
const sq = { month: q.month, ...(Number.isInteger(q.tzOffsetMin) ? { tzOffsetMin: q.tzOffsetMin } : {}),
|
|
259
|
+
from: Number.isFinite(q.from) ? q.from : undefined, to: Number.isFinite(q.to) ? q.to : undefined, q: typeof q.q === 'string' ? q.q.slice(0, 200) : undefined };
|
|
260
|
+
const by = new Map();
|
|
261
|
+
let first = null;
|
|
262
|
+
let last = null;
|
|
263
|
+
for (const s of sourcesOf(core, o)) {
|
|
264
|
+
const d = dayCounts(core, sq, s.spec);
|
|
265
|
+
for (const x of d.items) by.set(x.day, (by.get(x.day) ?? 0) + x.n);
|
|
266
|
+
if (d.first != null && (first == null || d.first < first)) first = d.first;
|
|
267
|
+
if (d.last != null && (last == null || d.last > last)) last = d.last;
|
|
268
|
+
}
|
|
269
|
+
return { items: [...by].sort(([a], [b]) => (a < b ? -1 : 1)).map(([day, n]) => ({ day, n })), first, last, tzOffsetMin: tzOf(core, sq, Date.now()) };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 测试用:第一页每一路的查询(看 EXPLAIN QUERY PLAN 走不走索引)。 */
|
|
273
|
+
export function feedPlan(core, q = {}) {
|
|
274
|
+
const o = optsOf(q);
|
|
275
|
+
return sourcesOf(core, o).map((s) => scoped(core, {}, s)).map((s) => ({ kind: s.kind, ...seekSql(s, o.order === 'asc', null, limitOf(core, q) + 1) }));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ── 人物 ─────────────────────────────────────────────────────────────────
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 【D171】人物卡片:一个人一项(D161 的分组,和选人、按人筛同一套),不含她自己、不含场合。每项:
|
|
282
|
+
* id(代表档案)、name、aliases(也叫…)、kind、principal(是不是主人)、members、n(名下记忆条数:事实、经历、打算,和按人筛的「全部」同口径,
|
|
283
|
+
* 不含忘掉的)、lastAt(组里最近一次被提到)、impression(一句现在的印象,大家都知道的优先)。
|
|
284
|
+
* 顺序:主人在前,其余名下多的在前。给 q.id 时只给这一个人,另带 detail:每个档案的名字(在哪个场合叫什么)、关系、印象(两层)、
|
|
285
|
+
* 组里的链接(same / maybe_same / not_same 和谁定的)。
|
|
286
|
+
* 代价:一次扫经历的参与者(同 pickable),每组几次按 entity_id 的索引查找;最多 q.limit(默认 300,上限 1000)组。
|
|
287
|
+
*/
|
|
288
|
+
export function people(core, q = {}) {
|
|
289
|
+
const cap = Math.max(1, Math.min(1000, Number.isInteger(q.limit) ? q.limit : 300));
|
|
290
|
+
const groups = personGroups(core).filter((g) => !g.alive.some((r) => r.is_self));
|
|
291
|
+
const ep = new Map();
|
|
292
|
+
for (const r of core.store.all(`SELECT CAST(x.value AS INTEGER) AS pid, count(*) AS n FROM episodes t, json_each(t.participants_json) x
|
|
293
|
+
WHERE NOT EXISTS (SELECT 1 FROM suppressions s WHERE s.owner_kind = 'episode' AND s.owner_id = t.id AND s.state = 'forgotten') GROUP BY pid`)) ep.set(r.pid, Number(r.n));
|
|
294
|
+
const notForgot = (k) => `NOT EXISTS (SELECT 1 FROM suppressions s WHERE s.owner_kind = '${k}' AND s.owner_id = x.id AND s.state = 'forgotten')`;
|
|
295
|
+
const one = (ids) => {
|
|
296
|
+
const ph = ids.map(() => '?').join(', ');
|
|
297
|
+
const facts = Number(core.store.get(`SELECT count(*) AS n FROM assertions x WHERE x.superseded_by IS NULL AND x.id IN (SELECT assertion_id FROM assertion_entities WHERE entity_id IN (${ph})) AND ${notForgot('assertion')}`, ...ids).n);
|
|
298
|
+
const intents = Number(core.store.get(`SELECT count(*) AS n FROM intentions x WHERE x.target_entity_id IN (${ph}) AND ${notForgot('intention')}`, ...ids).n);
|
|
299
|
+
const eps = ids.reduce((n, id) => n + (ep.get(id) ?? 0), 0);
|
|
300
|
+
const lastAt = core.store.get(`SELECT max(last_mention_at) AS t FROM entities WHERE id IN (${ph})`, ...ids)?.t ?? null;
|
|
301
|
+
const imp = core.store.get(`SELECT text FROM entity_impressions WHERE entity_id IN (${ph}) AND is_current = 1 ORDER BY layer = 'shared' DESC, built_at DESC LIMIT 1`, ...ids);
|
|
302
|
+
return { n: facts + intents + eps, facts, episodes: eps, intents, lastAt: lastAt == null ? null : Number(lastAt), impression: imp?.text ?? null };
|
|
303
|
+
};
|
|
304
|
+
let rows = groups;
|
|
305
|
+
if (Number.isSafeInteger(q.id)) rows = groups.filter((g) => g.members.includes(q.id));
|
|
306
|
+
const items = rows.map((g) => ({ id: g.rep.id, name: g.name, aliases: g.aliases, kind: g.rep.kind, status: g.rep.status, principal: g.alive.some((r) => r.authority === 'principal'),
|
|
307
|
+
members: g.members, ...one(g.members) }));
|
|
308
|
+
items.sort((a, b) => Number(b.principal) - Number(a.principal) || b.n - a.n || (b.lastAt ?? 0) - (a.lastAt ?? 0) || a.id - b.id);
|
|
309
|
+
const out = { items: items.slice(0, cap), total: items.length, readOnly: !!core.readOnly };
|
|
310
|
+
if (Number.isSafeInteger(q.id) && items[0]) {
|
|
311
|
+
const ids = items[0].members;
|
|
312
|
+
const ph = ids.map(() => '?').join(', ');
|
|
313
|
+
const scopes = new Set();
|
|
314
|
+
const names = core.store.all(`SELECT entity_id AS entityId, text_raw AS text, scope_setting_key AS scope, count, last FROM entity_names WHERE entity_id IN (${ph}) ORDER BY count DESC, last DESC LIMIT 40`, ...ids)
|
|
315
|
+
.map((r) => { if (r.scope) scopes.add(r.scope); return { entityId: r.entityId, text: r.text, scope: r.scope || null, count: Number(r.count ?? 0), last: r.last ?? null }; });
|
|
316
|
+
const descriptors = core.store.all(`SELECT entity_id AS entityId, anchor_entity_id AS anchor, relation, text FROM entity_descriptors WHERE entity_id IN (${ph}) LIMIT 30`, ...ids);
|
|
317
|
+
const impressions = core.store.all(`SELECT entity_id AS entityId, layer, text, version, built_at AS builtAt FROM entity_impressions WHERE entity_id IN (${ph}) AND is_current = 1 ORDER BY layer, built_at DESC LIMIT 10`, ...ids);
|
|
318
|
+
const links = core.store.all(`SELECT a, b, rel, confidence, decided_by AS decidedBy, at FROM entity_links WHERE (a IN (${ph}) OR b IN (${ph})) AND rel IN ('same', 'maybe_same', 'not_same') LIMIT 40`, ...ids, ...ids);
|
|
319
|
+
const memberRows = core.store.all(`SELECT id, kind, status, display_name AS name, mention_days AS mentionDays, last_mention_at AS lastMentionAt FROM entities WHERE id IN (${ph})`, ...ids);
|
|
320
|
+
const anchorIds = [...new Set([...descriptors.map((d) => d.anchor), ...links.flatMap((l) => [l.a, l.b])].filter(Number.isSafeInteger))];
|
|
321
|
+
const nm = namesOf(core, [...[...scopes].map((settingKey) => ({ settingKey })), { subjects: anchorIds }]);
|
|
322
|
+
out.detail = { names, descriptors, impressions, links, members: memberRows, settings: nm.settings, who: nm.names };
|
|
323
|
+
}
|
|
324
|
+
return out;
|
|
325
|
+
}
|