@sparkelf/dsh-knowledge-base 0.4.3 → 0.5.1

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