@sparkelf/dsh-knowledge-base 0.4.3 → 0.5.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.
@@ -28,7 +28,8 @@
28
28
  * @module @sparkelf/dsh-knowledge-base/graph-tools
29
29
  */
30
30
  import { type KnowledgeFileToolHost } from './knowledgeTools.ts';
31
- import { type KnowledgeGraphNode } from './graphTypes.ts';
31
+ import { type MemoryAuthority, type MemoryOrigin, type MemoryReviewStatus } from './graphModel.ts';
32
+ import { type KnowledgeGraphLink, type KnowledgeGraphNode, type KnowledgeGraphTopic } from './graphTypes.ts';
32
33
  /** The Host operations graph tools compose. Actual paths are authoritative. */
33
34
  export interface KnowledgeGraphToolHost extends Pick<KnowledgeFileToolHost, 'resolveCaller' | 'canWrite' | 'createEntry' | 'overwriteFile' | 'moveEntry' | 'statEntry' | 'refreshView' | 'appendAudit' | 'viewDir'> {
34
35
  /** Every graph the caller may read, with Host-only `actualPath`. */
@@ -47,7 +48,377 @@ export interface KnowledgeGraphToolHost extends Pick<KnowledgeFileToolHost, 'res
47
48
  kind: 'file' | 'directory';
48
49
  size?: number;
49
50
  } | undefined>;
51
+ /**
52
+ * Lifecycle owner for the computed overview stores.
53
+ *
54
+ * Absent in unit tests and one-shot hosts, where each read opens a transient
55
+ * JSON store; the real Host wires one manager per plugin instance so global and
56
+ * department stores are shared and a personal store is per user.
57
+ */
58
+ overviewStores?: OverviewStoreManager;
59
+ }
60
+ /**
61
+ * Reserved `.graphs/<id>` directory of every computed overview.
62
+ *
63
+ * The overview is a **materialized read model**, never a stored graph: there is no
64
+ * `graph.json` under this directory, only the cross-graph link store. A stored
65
+ * manifest would turn the overview into an ordinary graph and let a recursive
66
+ * aggregation include itself.
67
+ */
68
+ export declare const OVERVIEW_GRAPH_ID = "__overview__";
69
+ /** Personal overview path, kept as the default spelling every caller knows. */
70
+ export declare const OVERVIEW_GRAPH_PATH: string;
71
+ /** Display name shared by the three scope-level overviews. */
72
+ export declare const OVERVIEW_GRAPH_NAME = "\u603B\u56FE";
73
+ /** Cross-graph link store inside the reserved directory. */
74
+ export declare const OVERVIEW_LINKS_FILE = "links.json";
75
+ /** Schema version of `links.json`. */
76
+ export declare const OVERVIEW_LINKS_SCHEMA_VERSION = 1;
77
+ /** The three knowledge scopes, each with its own overview. */
78
+ export declare const OVERVIEW_LEVELS: readonly ["global", "department", "personal"];
79
+ export type OverviewLevel = (typeof OVERVIEW_LEVELS)[number];
80
+ /** One scope the Host resolved for the caller, without credentials. */
81
+ export interface OverviewScopeInput {
82
+ level: OverviewLevel;
83
+ /** View-relative scope base, e.g. `global`, `department/D1`, `personal`. */
84
+ viewBase: string;
85
+ /** Authoritative scope base, e.g. `department/D1`, `personal/<uid>`. */
86
+ actualBase: string;
87
+ /** Department display label; empty for global and personal. */
88
+ groupLabel?: string;
89
+ }
90
+ /** One fully derived overview scope: paths and display grouping. */
91
+ export interface OverviewStoreScope {
92
+ level: OverviewLevel;
93
+ viewBase: string;
94
+ actualBase: string;
95
+ groupLabel: string;
96
+ /** `<viewBase>/.graphs/__overview__` — the virtual graph's view path. */
97
+ viewPath: string;
98
+ /** `<actualBase>/.graphs/__overview__` — holds only `links.json`. */
99
+ actualPath: string;
100
+ }
101
+ /** One persisted cross-graph link. */
102
+ export interface OverviewCrossLink {
103
+ id: string;
104
+ /** Readable graph the `from` node belongs to (a graph id or path). */
105
+ fromGraph: string;
106
+ /** Node id inside {@link fromGraph}. */
107
+ from: string;
108
+ /** Readable graph the `to` node belongs to (a graph id or path). */
109
+ toGraph: string;
110
+ /** Node id inside {@link toGraph}. */
111
+ to: string;
112
+ type: string;
113
+ title?: string;
114
+ authority: MemoryAuthority;
115
+ internalizable: boolean;
116
+ origin: MemoryOrigin;
117
+ reviewStatus: MemoryReviewStatus;
118
+ tags: string[];
119
+ sourceRefs: string[];
120
+ body?: string;
121
+ createdAt: string;
122
+ updatedAt: string;
123
+ }
124
+ /** One source graph in the overview answer. */
125
+ export interface OverviewGraphSummary {
126
+ id: string;
127
+ name: string;
128
+ scope: OverviewLevel;
129
+ group: string;
130
+ path: string;
131
+ format: string;
132
+ counts: {
133
+ topics: number;
134
+ links: number;
135
+ documents: number;
136
+ };
137
+ }
138
+ /** One aggregated node, namespaced as `<graphId>:<nodeId>`. */
139
+ export interface OverviewNode {
140
+ /** Namespaced id `<graphId>:<nodeId>`; unique across the overview. */
141
+ id: string;
142
+ graphId: string;
143
+ graphName: string;
144
+ scope: OverviewLevel;
145
+ nodeId: string;
146
+ type: string;
147
+ title: string;
148
+ authority?: MemoryAuthority;
149
+ reviewStatus?: MemoryReviewStatus;
150
+ tags: string[];
151
+ /** View-relative document path, for opening the source node. */
152
+ docPath: string;
153
+ }
154
+ /** One aggregated edge, with both endpoints remapped to namespaced node ids. */
155
+ export interface OverviewEdge {
156
+ /** Edge id: namespaced for a stored graph, the record id for a cross-graph link. */
157
+ id: string;
158
+ graphId: string;
159
+ edgeId: string;
160
+ from: string;
161
+ to: string;
162
+ type: string;
163
+ title?: string;
164
+ authority?: MemoryAuthority;
165
+ origin?: MemoryOrigin;
166
+ reviewStatus?: MemoryReviewStatus;
167
+ tags: string[];
168
+ sourceRefs: string[];
169
+ /** True for a link stored in `<scope>/.graphs/__overview__/links.json`. */
170
+ crossGraph: boolean;
171
+ }
172
+ /** The aggregate `kg_get` answers for one overview and the canvas consumes. */
173
+ export interface OverviewAggregate {
174
+ graph: {
175
+ id: string;
176
+ name: string;
177
+ scope: OverviewLevel;
178
+ group: string;
179
+ path: string;
180
+ format: 'overview';
181
+ computed: true;
182
+ readOnly: true;
183
+ counts: {
184
+ topics: number;
185
+ links: number;
186
+ documents: number;
187
+ };
188
+ };
189
+ graphs: OverviewGraphSummary[];
190
+ nodes: OverviewNode[];
191
+ edges: OverviewEdge[];
192
+ /** Canvas projection of {@link nodes}; ids are already namespaced. */
193
+ topics: KnowledgeGraphTopic[];
194
+ /** Canvas projection of {@link edges}; endpoints are already namespaced. */
195
+ links: KnowledgeGraphLink[];
196
+ totals: {
197
+ graphs: number;
198
+ nodes: number;
199
+ edges: number;
200
+ crossEdges: number;
201
+ };
202
+ /** Non-fatal problems (dangling or no-longer-readable cross links). */
203
+ issues: string[];
204
+ }
205
+ /**
206
+ * The storage contract of one overview scope.
207
+ *
208
+ * MVP is backed by `links.json` (`JsonOverviewStore`). The interface deliberately
209
+ * carries nothing JSON-specific: a memory-first Relate backend implements the
210
+ * same five lifecycle methods (`open` / `query` / `close` / `lastUsed` /
211
+ * `revision`) plus the two write helpers and `estimatedBytes` used by eviction.
212
+ *
213
+ * `query()` never reloads the backing bytes; `open()` is the only load point, so
214
+ * the manager can cache a store across calls. `revision()` changes whenever this
215
+ * store observed a new snapshot, which is what invalidates the aggregate cache.
216
+ */
217
+ export interface OverviewStore {
218
+ readonly scope: OverviewStoreScope;
219
+ /** Load the backing state once; idempotent. */
220
+ open(): Promise<void>;
221
+ /** The current cross-link snapshot. Does not re-read persistent bytes. */
222
+ query(): Promise<OverviewCrossLink[]>;
223
+ /** Replace the persisted cross-link snapshot. */
224
+ replace(links: readonly OverviewCrossLink[]): Promise<void>;
225
+ /** Drop in-memory state; persistent bytes stay. */
226
+ close(): void;
227
+ /** Epoch milliseconds of the last open/query/replace. */
228
+ lastUsed(): number;
229
+ /** Opaque token that changes when the store observed new content. */
230
+ revision(): string;
231
+ /** Rough in-memory footprint, for the manager's memory budget. */
232
+ estimatedBytes(): number;
233
+ /** Non-fatal parse issues from the last open. */
234
+ issues(): readonly string[];
235
+ }
236
+ /** How the manager opens a store for one scope. */
237
+ export interface OverviewStoreProvider {
238
+ open(scope: OverviewStoreScope): Promise<OverviewStore>;
239
+ }
240
+ /** Build a `links.json` store for one Host and scope. */
241
+ export declare class JsonOverviewStore implements OverviewStore {
242
+ private readonly host;
243
+ private readonly now;
244
+ /** Materialized read-model root; a getter lets the startup probe swap it. */
245
+ private readonly storeDir?;
246
+ readonly scope: OverviewStoreScope;
247
+ private links;
248
+ private storeIssues;
249
+ private used;
250
+ private rev;
251
+ /** The file this store last read, so a standalone flat layout writes back to it. */
252
+ private pathUsed;
253
+ constructor(host: KnowledgeGraphToolHost, scope: OverviewStoreScope, now?: () => number,
254
+ /** Materialized read-model root; a getter lets the startup probe swap it. */
255
+ storeDir?: string | (() => string | undefined) | undefined);
256
+ open(): Promise<void>;
257
+ query(): Promise<OverviewCrossLink[]>;
258
+ replace(links: readonly OverviewCrossLink[]): Promise<void>;
259
+ close(): void;
260
+ lastUsed(): number;
261
+ revision(): string;
262
+ estimatedBytes(): number;
263
+ issues(): readonly string[];
264
+ /**
265
+ * Persist the derived read model under the probed store root.
266
+ *
267
+ * This snapshot is not the source of truth — `links.json` is — so a failed
268
+ * write never blocks a read and a missing store root simply skips it. It gives
269
+ * the future Relate adapter a concrete, probe-tested location to replace.
270
+ */
271
+ materialize(aggregate: OverviewAggregate): Promise<void>;
272
+ }
273
+ /** The default MVP provider: one `links.json` per scope plus a JSON read-model snapshot. */
274
+ export declare class JsonOverviewStoreProvider implements OverviewStoreProvider {
275
+ private readonly host;
276
+ /** Resolved store root; read lazily so the startup probe can swap it. */
277
+ private readonly storeDir?;
278
+ constructor(host: KnowledgeGraphToolHost,
279
+ /** Resolved store root; read lazily so the startup probe can swap it. */
280
+ storeDir?: (() => string | undefined) | undefined);
281
+ open(scope: OverviewStoreScope): Promise<OverviewStore>;
50
282
  }
283
+ /** Where the store goes when the KB root cannot satisfy the probe. */
284
+ export declare const OVERVIEW_STORE_FALLBACK_DIR = "/var/lib/dataops/kb-overview";
285
+ /** One probe check per capability the backend must provide. */
286
+ export interface OverviewStoreProbeChecks {
287
+ open: boolean;
288
+ write: boolean;
289
+ fsync: boolean;
290
+ read: boolean;
291
+ lock: boolean;
292
+ }
293
+ /** Outcome of the startup compatibility probe. */
294
+ export interface OverviewStoreProbeResult {
295
+ /** Directory the store should actually use. */
296
+ dir: string;
297
+ /** Directory the configuration asked for. */
298
+ requested: string;
299
+ /** True when {@link dir} is the local fallback rather than the requested root. */
300
+ fallback: boolean;
301
+ /** True only when every capability passed in the directory actually used. */
302
+ ok: boolean;
303
+ checks: OverviewStoreProbeChecks;
304
+ error?: string;
305
+ }
306
+ /**
307
+ * Probe the configured overview store root and fall back when it is unusable.
308
+ *
309
+ * A KB root may be a read-only NAS, an unmounted share, or a filesystem without
310
+ * the lock/fsync semantics a store needs. The probe never assumes availability:
311
+ * it creates a file, fsyncs it, reads it back and takes an exclusive lock, then
312
+ * removes both artifacts. A failed requested root moves the store to
313
+ * {@link OVERVIEW_STORE_FALLBACK_DIR}; reads keep working either way.
314
+ */
315
+ export declare function probeOverviewStoreDir(requested: string, fallbackDir?: string): Promise<OverviewStoreProbeResult>;
316
+ /** Manager knobs; every value is overridable and the defaults stay inside the policy. */
317
+ export interface OverviewStoreManagerOptions {
318
+ /** Idle TTL per level, clamped to 5–10 / 15–30 / 30–60 minutes. */
319
+ ttlMs?: Partial<Record<OverviewLevel, number>>;
320
+ /** Hard cap on cached stores; idle LRU entries are evicted first. */
321
+ maxStores?: number;
322
+ /** Soft memory budget for cached link snapshots; idle LRU entries are evicted first. */
323
+ memoryBudgetBytes?: number;
324
+ /** Injectable clock, so lifecycle tests do not sleep. */
325
+ now?: () => number;
326
+ }
327
+ /**
328
+ * Lifecycle owner for every overview store.
329
+ *
330
+ * The approved model is per scope: global and department stores are shared by
331
+ * everyone allowed to read that scope, while a personal store belongs to exactly
332
+ * one user. Stores load on first use, stay open while an operation holds a
333
+ * reference, and are evicted by idle TTL, LRU count and the memory budget.
334
+ *
335
+ * `rebuild()` opens the replacement completely before swapping it into the map
336
+ * and closing the old one, so a reader never observes a half-built store. A future
337
+ * auth/logout hook calls {@link closePersonal}; plugin disposal calls
338
+ * {@link closeAll}.
339
+ */
340
+ export declare class OverviewStoreManager {
341
+ private readonly provider;
342
+ private readonly entries;
343
+ private readonly ttlMs;
344
+ private readonly maxStores;
345
+ private readonly memoryBudgetBytes;
346
+ private readonly now;
347
+ constructor(provider: OverviewStoreProvider, options?: OverviewStoreManagerOptions);
348
+ /** Key a store by level + authoritative base; personal therefore includes the uid. */
349
+ private keyOf;
350
+ /** Open (or reuse) one store and take a reference. */
351
+ acquire(scope: OverviewStoreScope): Promise<OverviewStore>;
352
+ /** Drop one reference; eviction happens on the next sweep. */
353
+ release(store: OverviewStore): void;
354
+ /**
355
+ * Close every personal store that belongs to one user.
356
+ *
357
+ * The future managed-auth logout/revocation hook calls this; the JSON MVP also
358
+ * relies on it when a caller disappears, so a shared process never keeps another
359
+ * user's personal snapshot alive.
360
+ */
361
+ closePersonal(userId: string): void;
362
+ /** Plugin disposal / process exit: close every store once. */
363
+ closeAll(): void;
364
+ /**
365
+ * Replace one scope's store atomically.
366
+ *
367
+ * The new store is opened in full first; only then does the map switch to it and
368
+ * the old store close. A failed open leaves readers on the old snapshot.
369
+ */
370
+ rebuild(scope: OverviewStoreScope): Promise<OverviewStore>;
371
+ /** Evict idle stores by TTL, then by LRU count, then by memory budget. */
372
+ sweep(at?: number): void;
373
+ /** Cached store count, for diagnostics and tests. */
374
+ size(): number;
375
+ /** Cached footprint, for diagnostics and tests. */
376
+ cachedBytes(): number;
377
+ private evictToCount;
378
+ private evictOneIdleLru;
379
+ }
380
+ /** Whether a graph row is one of the computed overviews. */
381
+ export declare function isOverviewGraph(graph: Pick<KnowledgeGraphNode, 'id' | 'path' | 'computed'>): boolean;
382
+ /** Turn Host-resolved graph roots into overview scopes. */
383
+ export declare function overviewScopesFromRoots(roots: ReadonlyArray<{
384
+ key: OverviewLevel;
385
+ actualPath: string;
386
+ viewPath: string;
387
+ groupLabel?: string;
388
+ }>): OverviewScopeInput[];
389
+ /** Derive the store scope of one overview row. */
390
+ export declare function overviewStoreScopeOf(graph: Pick<KnowledgeGraphNode, 'path' | 'actualPath' | 'scope' | 'group'>): OverviewStoreScope;
391
+ /** Complete one scope input into its store coordinates. */
392
+ export declare function overviewStoreScope(input: OverviewScopeInput): OverviewStoreScope;
393
+ /** The synthetic graph row one scope's overview publishes. */
394
+ export declare function overviewGraphNode(scope: OverviewStoreScope, aggregate?: OverviewAggregate): KnowledgeGraphNode;
395
+ /** The default scope: the caller's personal overview. */
396
+ export declare function personalOverviewScope(host: KnowledgeGraphToolHost): Promise<OverviewStoreScope>;
397
+ /**
398
+ * Build the overview from already readable graphs and the cross-link store.
399
+ *
400
+ * Pure and permission-agnostic: every graph in `graphs` has already passed
401
+ * `canReadPath` and belongs to `scope.level`; a cross link is included only when
402
+ * BOTH endpoint graphs are present in that list. A hidden graph is therefore
403
+ * neither named nor counted.
404
+ */
405
+ export declare function buildOverviewAggregate(scope: OverviewStoreScope, graphs: readonly KnowledgeGraphNode[], crossLinks?: readonly OverviewCrossLink[], storeIssues?: readonly string[]): OverviewAggregate;
406
+ /**
407
+ * Load (or reuse) one scope's overview aggregate.
408
+ *
409
+ * The cache key covers the scope, every readable graph's identity/counts/attributes
410
+ * and the cross-link snapshot, so a refresh or write changes the answer without a
411
+ * TTL; {@link invalidateOverviewCache} still drops it eagerly on the write seams.
412
+ * The store manager supplies the per-scope snapshot, so the same function serves
413
+ * the global, department and personal overviews without mixing users' stores.
414
+ */
415
+ export declare function loadOverviewAggregate(host: KnowledgeGraphToolHost, graphs: readonly KnowledgeGraphNode[], scopeInput?: OverviewScopeInput | OverviewStoreScope): Promise<OverviewAggregate>;
416
+ /** The personal-only compatibility wrapper used by tests and early callers. */
417
+ export declare function appendOverviewGraph(host: KnowledgeGraphToolHost, graphs: readonly KnowledgeGraphNode[]): Promise<KnowledgeGraphNode[]>;
418
+ /** The `host.listGraphs()` answer plus one synthesized row per resolved scope. */
419
+ export declare function appendOverviewGraphs(host: KnowledgeGraphToolHost, graphs: readonly KnowledgeGraphNode[], scopes: readonly OverviewScopeInput[]): Promise<KnowledgeGraphNode[]>;
420
+ /** Drop every cached aggregate for one host; called on the write seams and refresh. */
421
+ export declare function invalidateOverviewCache(host: KnowledgeGraphToolHost): void;
51
422
  /**
52
423
  * Build the four graph tools.
53
424
  *
@@ -76,6 +76,18 @@ export interface KnowledgeGraphTopic {
76
76
  reviewStatus?: KnowledgeGraphReviewStatus;
77
77
  /** Optional authority for the topic card; `redline` is subscribe-only. */
78
78
  authority?: KnowledgeGraphAuthority;
79
+ /**
80
+ * Overview projection only: the graph this node was aggregated from.
81
+ *
82
+ * A topic inside the synthesized `总图` carries the namespaced id
83
+ * `<graphId>:<nodeId>`; these two fields let a click navigate back to the real
84
+ * graph and node instead of treating the copy as an editable topic.
85
+ */
86
+ sourceGraphId?: string;
87
+ /** Overview projection only: the node id inside {@link sourceGraphId}. */
88
+ sourceNodeId?: string;
89
+ /** Overview projection only: the source graph's scope, for the scope filter. */
90
+ scope?: KnowledgeGraphScopeKey;
79
91
  }
80
92
  /** One relation document under `<graph>/.kg/links/`. */
81
93
  export interface KnowledgeGraphLink {
@@ -91,6 +103,13 @@ export interface KnowledgeGraphLink {
91
103
  body: string;
92
104
  /** File name under `<graph>/.kg/links/`, used by the Host-side del tool. */
93
105
  file?: string;
106
+ /**
107
+ * Overview projection only: endpoints belong to different source graphs.
108
+ *
109
+ * The canvas draws these dashed and keeps them visible without enabling the
110
+ * ordinary cross-link toggle, because crossing graphs is the overview's point.
111
+ */
112
+ crossGraph?: boolean;
94
113
  }
95
114
  /** One graph node under a scope. */
96
115
  export interface KnowledgeGraphNode {
@@ -125,6 +144,22 @@ export interface KnowledgeGraphNode {
125
144
  * tools. Stripped before the tree is sent to the browser.
126
145
  */
127
146
  actualPath?: string;
147
+ /**
148
+ * True for the synthesized overview (`总图`).
149
+ *
150
+ * A computed graph has no `.graphs/<id>/graph.json`: the Host builds it at read
151
+ * time from the graphs the caller may read. It is excluded from every recursive
152
+ * aggregation so the overview never contains itself.
153
+ */
154
+ computed?: boolean;
155
+ /**
156
+ * True when the graph is a derived, read-only view.
157
+ *
158
+ * Legacy folder graphs are also read-only for their graph-level metadata, and
159
+ * the Host marks those rows `readOnly` too; `computed` is what distinguishes the
160
+ * synthesized overview from a stored graph.
161
+ */
162
+ readOnly?: boolean;
128
163
  }
129
164
  /** One group inside a scope: the department chain for 部门, empty elsewhere. */
130
165
  export interface KnowledgeGraphGroup {
@@ -144,6 +144,28 @@ export interface Config {
144
144
  publishDir: string;
145
145
  /** Sidecar directory for the SQLite FTS5 index (outside the agent-visible tree). */
146
146
  indexDir?: string;
147
+ /**
148
+ * Root for the materialized overview store (Relate/SQLite/JSON backend).
149
+ *
150
+ * Empty means `<actualRoot>/.overview`; the startup probe falls back to
151
+ * `/var/lib/dataops/kb-overview` when the KB root is not writable (a NAS may be
152
+ * read-only, unmounted, or not support the required lock/fsync semantics).
153
+ */
154
+ overviewStoreDir?: string;
155
+ /** Master switch for the computed 总图 rows and tool resolution. Default true. */
156
+ overviewEnabled?: boolean;
157
+ /** Local fallback when `overviewStoreDir` cannot pass the startup probe. */
158
+ overviewStoreFallbackDir?: string;
159
+ /** Idle TTL per level in minutes; clamped to the approved ranges by the manager. */
160
+ overviewTtlMinutes?: {
161
+ personal: number;
162
+ department: number;
163
+ global: number;
164
+ };
165
+ /** LRU cap on cached overview stores. */
166
+ overviewMaxStores?: number;
167
+ /** Soft memory budget in MiB for cached overview snapshots. */
168
+ overviewMemoryBudgetMB?: number;
147
169
  /** Optional hybrid retrieval. Disabled by default; no provider is called unless enabled. */
148
170
  retrieval: {
149
171
  vector: import('./embeddings.ts').VectorRetrievalConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparkelf/dsh-knowledge-base",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "DataOps-backed knowledge base for DeepSeek Harness: a left-sidebar destination, Settings configuration, and index tooling over a mounted NAS view.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -34,6 +34,71 @@ description: 读写团队知识库里的知识图谱:主题卡、关系文档
34
34
  - 图谱页把每个节点投影成一张卡片;空图谱也会出现在图谱树里,加上第一个节点后画布就有内容。
35
35
  - `.graphs/` 是隐藏目录,不要用文件树或 shell 直接编辑;新建用 `kg_add kind=graph`,改拓扑用 `kg_add` / `kg_set` / `kg_del`。
36
36
 
37
+ ### 总图(三级 computed / read-only)
38
+
39
+ `总图` 是**物化读模型**,不是磁盘上的 `graph.json`。它分三级,每个调用者按自己的范围看到:
40
+
41
+ ```text
42
+ global/.graphs/__overview__/links.json # 全局总图;共享
43
+ department/<chain>/.graphs/__overview__/links.json # 部门总图;同部门共享
44
+ personal/<uid>/.graphs/__overview__/links.json # 个人总图;按用户
45
+ ```
46
+
47
+ - 三级的源数据仍是各自的 `graph.json`;`__overview__` 目录下**没有** `graph.json`,只有跨图关系。
48
+ - `kg_get {"graph":"总图"}` 默认解析到**个人总图**;要读其它级,用 `global/__overview__`、`department/__overview__`、`personal/__overview__`(也接受 `<级>/总图`)。
49
+ - 每次返回该级的 `graphs[]` 图谱摘要、`nodes[]`(id 形如 `<graphId>:<nodeId>`,带 graphId/type/title/authority/reviewStatus/docPath)、
50
+ `edges[]`(端点已重映射;跨图边 `crossGraph:true`)。
51
+ - 每一级只聚合该级、调用者可读的图谱,且永远排除该级 `总图` 自身;边只有在两端图谱都可读时才出现,不会泄露另一侧的名称或计数。
52
+ - `总图` 只读:`kg_set` 被拒绝;`kg_add kind=node` 被拒绝(请把节点加到源图谱,`总图` 会自动出现它)。
53
+ - 跨图关系用 `kg_add` 写入**同级**的 `links.json`:
54
+
55
+ ```json
56
+ {"kind":"edge","graph":"personal/__overview__","id":"policy-to-role",
57
+ "fromGraph":"personal/.graphs/procurement","from":"policy-1",
58
+ "toGraph":"personal/.graphs/hr","to":"role-1","type":"governs"}
59
+ ```
60
+
61
+ 先不带 `confirm` 拿草稿,用户确认后加 `"confirm":true`。`id` 是跨图边 id,必须唯一;`from`/`to` 仍然是**节点 id**,不是图谱 id。
62
+ 两个端点图谱都必须可读、与本总图同级、节点必须存在,否则返回 `not-found`;重复 id 返回 `exists`;
63
+ `authority`/`origin`/`reviewStatus`/`tags`/`sourceRefs` 与普通边同规则校验。
64
+ - `kg_del {"graph":"总图","id":"<跨图边 id>"}` 把这条关系移到该级 `.graphs/__overview__/_trash/links/`,不真删。
65
+ - 图谱页里三级 `总图` 都显示 `[计算] [只读]`;画布按来源图谱分簇,跨图边走虚线,点击节点跳到源图谱的对应节点。
66
+
67
+ #### 存储与生命周期(为 Relate 预留)
68
+
69
+ MVP 用 JSON 后端(`JsonOverviewStore`),**不安装原生 Relate 依赖**。存储层统一为 `OverviewStore` 接口:
70
+
71
+ ```text
72
+ open() 按需加载一次
73
+ query() 读取当前跨图关系快照(不重复读盘)
74
+ close() 释放内存,不删盘
75
+ lastUsed() 最近使用时间
76
+ revision() 内容版本,聚合缓存据此失效
77
+ replace(links) 写回(MVP 的写方法)
78
+ estimatedBytes() 内存预算估算
79
+ ```
80
+
81
+ `OverviewStoreManager` 负责生命周期,未来把 provider 换成内存优先的 Relate 后端即可:
82
+
83
+ - **按需加载 + 引用计数**:`acquire` 打开/复用并加引用,`release` 减引用;没有操作时不加载。
84
+ - **空闲 TTL**(可配置,构造时按范围钳制):个人 5–10 分钟(默认 10)、部门 15–30(默认 20)、全局 30–60(默认 45)。
85
+ - **LRU 上限与内存预算淘汰**:只淘汰空闲(引用为 0)的 store;预算超了先淘汰最久未用的。
86
+ - **重建原子切换**:`rebuild()` 先把新 store 完整构建/加载,再换入 map,最后关闭旧 store;读者不会看到半成品。
87
+ - **共享与隔离**:全局/部门按 scope 共享一个 store;个人按 `userId` 独立,绝不把所有用户塞进一个 store。
88
+ - **登出/撤权**:调用 `closePersonal(userId)` 立即关闭该用户个人 store;插件 dispose / 进程退出调用 `closeAll()`。
89
+ - 以上默认值都是 `OverviewStoreManager` 构造参数,部署可按内存与访问频率调整;上限不允许突破约定区间。
90
+
91
+ #### 存储目录与兼容性 probe
92
+
93
+ - 物化 store 默认放 `<kbRoot>/.overview/`(`overviewStoreDir` 可改);`overviewEnabled:false` 可整体关闭三级总图;
94
+ `overviewStoreFallbackDir`、`overviewTtlMinutes.*`、`overviewMaxStores`、`overviewMemoryBudgetMB` 可调;**不假设 NAS 可用**。
95
+ - 启动时对目标目录做 open / write / fsync / read / lock 五项 probe;任一项失败自动 fallback 到本地
96
+ `/var/lib/dataops/kb-overview`,并把 `{requested, dir, fallback, ok, checks}` 写日志(warn/info)。
97
+ - `links.json` 仍是跨图关系的持久真相;store 目录只放派生的物化快照,probe 失败不影响读取,也不阻塞 `kg_get`。
98
+ - 两个盒子是两家公司的独立实例:总图只在**本实例**的可读图谱内聚合,不做跨盒聚合,也不共享个人 store。
99
+ - MVP 不安装原生 Relate 依赖;第五阶段把 `OverviewStoreProvider` 换成 Relate 适配器,管理器的 TTL/LRU/预算/
100
+ 原子重建/close 契约不变。
101
+
37
102
  ## 2. 主题卡与关系文档
38
103
 
39
104
  主题卡好例子:
@@ -82,8 +147,8 @@ updated: 2026-10-31
82
147
 
83
148
  | 动作 | 做什么 |
84
149
  |---|---|
85
- | `kg_add` | `kind: graph` 新建 graph-json 图谱;`kind: topic` 新增一条线(文件夹 + 卡);`kind: link` 新增一条关系;`kind: node` / `kind: edge` 给 graph-json 图谱加节点/关系 |
86
- | `kg_get` | 不带 `graph`/`id` 返回全部图谱总览;带 `graph` 返回该图谱;带 `graph`+`id` 返回卡、文档、关系 |
150
+ | `kg_add` | `kind: graph` 新建 graph-json 图谱;`kind: topic` 新增一条线(文件夹 + 卡);`kind: link` 新增一条关系;`kind: node` / `kind: edge` 给 graph-json 图谱加节点/关系;`graph:"总图"` + `kind:"edge"` 新增跨图关系 |
151
+ | `kg_get` | 不带 `graph`/`id` 返回全部图谱总览;带 `graph` 返回该图谱;带 `graph`+`id` 返回卡、文档、关系;`graph:"总图"` 返回聚合总图 |
87
152
  | `kg_set` | 改一个主题的 `status` / `depth` / `title` / `domain` / 摘要 / 正文;graph-json 图谱改节点/关系字段 |
88
153
  | `kg_del` | 把主题移到 `<graph>/_trash/`;有关联关系时需 `force: true` 一并移走,**不真删** |
89
154
 
@@ -111,6 +176,7 @@ updated: 2026-10-31
111
176
  4. **寻址**:`kg_get` 不带 id 看总览 → 按名称找 graph → `kg_get {graph,id}` 读一条线;不要用 `find`/`map` 另造工具。
112
177
  5. **沉淀**:把一次会话的结论写成文档(`kb_file_write` 到主题文件夹),再用 `kg_set` 更新卡摘要;图谱不复制文档内容。
113
178
  6. **复盘**:`kg_get` 总览 → 对每条线读 `kg_get {graph,id}` → 把 `status`/`depth` 调整回真实状态;`kg_del` 只移 `_trash`,不删。
179
+ 7. **跨图关联**:`kg_get {graph:"总图"}`(或 `global/__overview__` / `department/__overview__`)确认两个图谱同级且可读 → `kg_add {graph:"总图",kind:"edge",id,fromGraph,toGraph,from,to,type}` 草稿 → 用户确认 → `confirm:true`;不要为了跨图关系改任一图谱的 `graph.json`。
114
180
 
115
181
  ## 4. 扫历史会话(shell,不配工具)
116
182