@sparkelf/dsh-knowledge-base 0.4.2 → 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.
@@ -19,10 +19,17 @@
19
19
  * and calls again with `confirm: true` after approval. This is the §7 trigger rule
20
20
  * (user sovereignty) expressed in the tool protocol rather than in a hook.
21
21
  *
22
+ * `kg_add` also creates a graph: `kind: 'graph'` writes a new
23
+ * `.graphs/<id>/graph.json` under the caller's writable scope, so a model can seed
24
+ * a knowledge graph instead of being stuck at "no readable graph". Creating a graph
25
+ * follows the same draft → confirm protocol, id validation, `canWrite` check and
26
+ * audit record as every other write.
27
+ *
22
28
  * @module @sparkelf/dsh-knowledge-base/graph-tools
23
29
  */
24
30
  import { type KnowledgeFileToolHost } from './knowledgeTools.ts';
25
- 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';
26
33
  /** The Host operations graph tools compose. Actual paths are authoritative. */
27
34
  export interface KnowledgeGraphToolHost extends Pick<KnowledgeFileToolHost, 'resolveCaller' | 'canWrite' | 'createEntry' | 'overwriteFile' | 'moveEntry' | 'statEntry' | 'refreshView' | 'appendAudit' | 'viewDir'> {
28
35
  /** Every graph the caller may read, with Host-only `actualPath`. */
@@ -41,7 +48,377 @@ export interface KnowledgeGraphToolHost extends Pick<KnowledgeFileToolHost, 'res
41
48
  kind: 'file' | 'directory';
42
49
  size?: number;
43
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>;
44
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>;
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;
45
422
  /**
46
423
  * Build the four graph tools.
47
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;
@@ -337,7 +359,17 @@ export declare function classifyMount(config: Config): Promise<KnowledgeMountSta
337
359
  * @param paths - candidate relative paths; omitted means walk the authoritative root.
338
360
  * @returns The sync report, or a refusal the caller should relay.
339
361
  */
340
- export declare function syncCallerView(host: Context, config: Config, paths?: string[]): Promise<(ViewDelta & SyncReportFields & {
362
+ export declare function syncCallerView(host: Context, config: Config, paths?: string[], options?: {
363
+ /**
364
+ * Called after a file that existed only in the view was imported into the
365
+ * authoritative tree. The caller owns extraction/indexing because only it knows
366
+ * the deployment's parser settings and queue.
367
+ */
368
+ onAdopted?: (adopted: {
369
+ viewPath: string;
370
+ actualRelPath: string;
371
+ }) => void | Promise<void>;
372
+ }): Promise<(ViewDelta & SyncReportFields & {
341
373
  status: number;
342
374
  error?: never;
343
375
  }) | {
@@ -847,6 +879,42 @@ export declare function createKnowledgeEntry(config: Config, relPath: string, op
847
879
  * `no such document`.
848
880
  */
849
881
  export declare function actualRelPathForView(ctx: Context, config: Config, relPath: string, caller?: KnowledgeCaller): Promise<string>;
882
+ /** Outcome of importing a file that exists only in a caller's view. */
883
+ export interface ViewAdoptionResult {
884
+ /** Whether the bytes now live at an authoritative path. */
885
+ adopted: boolean;
886
+ /** The authoritative path, relative to `actualRoot`, when adopted. */
887
+ actualRelPath?: string;
888
+ /** Why the file was not adopted. */
889
+ reason?: string;
890
+ }
891
+ /**
892
+ * Import one view-only file into the authoritative tree.
893
+ *
894
+ * A view is a hardlink mirror of `actualRoot`; a new file placed in it by a shell
895
+ * `cp` (or an editor's save-as) has no authoritative counterpart. The view sync
896
+ * treats such a file as an orphan and unlinks it, which deletes the only copy the
897
+ * reader has. This function is the alternative: copy the bytes to the authoritative
898
+ * path the view path maps to, then replace the view entry with a hardlink to that
899
+ * copy. The next sync then sees one file, DataOps keeps resolving it, and extraction
900
+ * and indexing have a real document to work on.
901
+ *
902
+ * Refuses without a write grant, without a non-empty path, or when a DIFFERENT
903
+ * authoritative file already owns the destination name — importing must never
904
+ * overwrite a document.
905
+ *
906
+ * @param host - Host context, for the caller and the write grant.
907
+ * @param config - resolved plugin config.
908
+ * @param relPath - the view-relative path (as the reader sees it).
909
+ * @param options - caller and the already-resolved view file, when known.
910
+ * @returns whether the import happened, and where.
911
+ */
912
+ export declare function adoptViewFile(host: Context, config: Config, relPath: string, options?: {
913
+ caller?: {
914
+ userId: string;
915
+ };
916
+ fullPath?: string;
917
+ }): Promise<ViewAdoptionResult>;
850
918
  /**
851
919
  * The canonical VIEW path a model-facing file-tool path names.
852
920
  *
@@ -198,12 +198,21 @@ export interface KnowledgeFileToolHost {
198
198
  createEntry(relPath: string, options: {
199
199
  directory: boolean;
200
200
  content?: string;
201
+ bytes?: Uint8Array;
201
202
  }): Promise<{
202
203
  relPath: string;
203
204
  kind: 'file' | 'directory';
204
205
  }>;
205
206
  /** Overwrite an existing file in place, preserving its inode/view hardlink. */
206
207
  overwriteFile(relPath: string, content: string): Promise<void>;
208
+ /**
209
+ * Overwrite an existing BINARY file in place, preserving its inode/view hardlink.
210
+ *
211
+ * Separate from {@link overwriteFile} because a text body and a byte body are not
212
+ * interchangeable: decoding bytes as UTF-8 replaces every non-text byte. Omitting it
213
+ * makes a base64 overwrite fail with a clear error instead of writing a broken file.
214
+ */
215
+ overwriteFileBytes?(relPath: string, bytes: Uint8Array): Promise<void>;
207
216
  moveEntry(from: string, to: string, caller: KnowledgeToolCaller): Promise<{
208
217
  from: string;
209
218
  to: string;
@@ -216,8 +225,31 @@ export interface KnowledgeFileToolHost {
216
225
  mineruBaseUrl?: string;
217
226
  }>;
218
227
  parkWrite(caller: KnowledgeToolCaller, relPath: string, content: string): Promise<void>;
228
+ /**
229
+ * Index one document that was just written and report whether it is searchable.
230
+ *
231
+ * Called only for text formats, where indexing is the whole pipeline: a document
232
+ * with a reader (PDF/DOCX/XLSX) goes through {@link enqueueExtraction} instead,
233
+ * whose worker indexes the derived Markdown once it exists. Omitting the method
234
+ * makes a tool report `skipped` rather than claiming a write was indexed.
235
+ */
236
+ indexAfterWrite?(relPath: string): Promise<{
237
+ status: 'indexed' | 'indexing' | 'skipped' | 'failed';
238
+ docId?: number;
239
+ chunks?: number;
240
+ indexedAt?: number;
241
+ reason?: string;
242
+ }>;
219
243
  /** Enqueue one document; mirrors the manual extraction route's outcomes. */
220
- enqueueExtraction(relPath: string, caller: KnowledgeToolCaller): Promise<{
244
+ enqueueExtraction(relPath: string, caller: KnowledgeToolCaller, options?: {
245
+ /**
246
+ * Replace an existing derived `.md` sibling.
247
+ *
248
+ * Set when the source was overwritten: the sibling beside it describes the old
249
+ * bytes, and the create-only extraction path would refuse to touch it.
250
+ */
251
+ replaceSibling?: boolean;
252
+ }): Promise<{
221
253
  outcome: 'already-markdown' | 'unsupported' | 'exists' | 'queued';
222
254
  markdown?: string;
223
255
  task?: unknown;
@@ -33,6 +33,17 @@ export interface ViewDelta {
33
33
  unlinked: string[];
34
34
  /** Paths left alone because the view already matched. */
35
35
  unchanged: number;
36
+ /**
37
+ * View paths that existed only in the view and were imported into the
38
+ * authoritative tree instead of being deleted.
39
+ *
40
+ * A file can land in a view without going through this plugin (a shell `cp`, an
41
+ * editor's save-as). The view is the reader's only writable surface, so treating
42
+ * such a file as an orphan would silently destroy the user's document on the next
43
+ * sync. `adoptOrphan` decides, per path, whether it is imported; these are the
44
+ * paths where that succeeded.
45
+ */
46
+ adopted?: string[];
36
47
  /**
37
48
  * Directories removed because a revoke emptied them.
38
49
  *
@@ -107,6 +118,20 @@ export interface ViewSyncOptions extends ViewOptions {
107
118
  * a permission decision, and must not delete the reader's links.
108
119
  */
109
120
  trustResolvedSet?: boolean;
121
+ /**
122
+ * Import one view-only file into the authoritative tree before it is unlinked.
123
+ *
124
+ * Called only for a regular file the resolved set does not name, and only when the
125
+ * prune pass is otherwise about to delete it. Returning true means the file now
126
+ * lives at the authoritative path (and, ideally, that the view entry was relinked
127
+ * to it), so the view keeps it. Returning false falls through to the ordinary
128
+ * unlink, which stays the answer for a file the caller may not write or may not
129
+ * import.
130
+ *
131
+ * The callback owns permission and destination decisions: `syncView` only knows
132
+ * about files and links, not about DataOps grants or bucket layouts.
133
+ */
134
+ adoptOrphan?: (relPath: string, fullPath: string) => Promise<boolean>;
110
135
  }
111
136
  /**
112
137
  * The three top-level buckets every view exposes, in display order.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparkelf/dsh-knowledge-base",
3
- "version": "0.4.2",
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",