@sparkelf/dsh-knowledge-base 0.1.36 → 0.4.3

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.
Files changed (41) hide show
  1. package/README.md +53 -0
  2. package/lib/client.js +2463 -1385
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +18210 -7883
  5. package/lib/types/client/KnowledgeMemory.d.ts +127 -0
  6. package/lib/types/client/graph/OriginBadges.d.ts +55 -0
  7. package/lib/types/client/locales.d.ts +64 -0
  8. package/lib/types/ftsIndex.d.ts +32 -0
  9. package/lib/types/graphCanvas.d.ts +1 -1
  10. package/lib/types/graphJsonProjection.d.ts +71 -0
  11. package/lib/types/graphMigration.d.ts +118 -0
  12. package/lib/types/graphModel.d.ts +194 -0
  13. package/lib/types/graphPolicy.d.ts +68 -0
  14. package/lib/types/graphTools.d.ts +30 -5
  15. package/lib/types/graphTypes.d.ts +24 -0
  16. package/lib/types/guardianSession.d.ts +135 -0
  17. package/lib/types/index.d.ts +135 -15
  18. package/lib/types/knowledgeTools.d.ts +50 -2
  19. package/lib/types/memoryBindings.d.ts +119 -0
  20. package/lib/types/memoryContext.d.ts +83 -0
  21. package/lib/types/memoryGraphBootstrap.d.ts +62 -0
  22. package/lib/types/memoryGraphWriter.d.ts +101 -0
  23. package/lib/types/memoryGuardian.d.ts +123 -0
  24. package/lib/types/memoryGuardianTool.d.ts +56 -0
  25. package/lib/types/memoryPolicy.d.ts +106 -0
  26. package/lib/types/memoryRecordTool.d.ts +39 -0
  27. package/lib/types/memoryRoutes.d.ts +85 -0
  28. package/lib/types/memorySettings.d.ts +40 -0
  29. package/lib/types/memorySkillPromotion.d.ts +62 -0
  30. package/lib/types/memoryStore.d.ts +297 -0
  31. package/lib/types/memoryTools.d.ts +71 -0
  32. package/lib/types/memoryTriggers.d.ts +65 -0
  33. package/lib/types/memoryTypes.d.ts +241 -0
  34. package/lib/types/summaryIndex.d.ts +112 -0
  35. package/lib/types/summaryWriteback.d.ts +87 -0
  36. package/lib/types/views.d.ts +25 -0
  37. package/package.json +1 -1
  38. package/skills/knowledge-graph/SKILL.md +37 -8
  39. package/skills/memory-extract/SKILL.md +43 -0
  40. package/skills/memory-guardian/SKILL.md +97 -0
  41. package/skills/memory-sop-evaluate/SKILL.md +43 -0
@@ -43,6 +43,7 @@ export declare const name = "dsh-knowledge-base";
43
43
  * reaches the next request without a restart. `webServer` serves the
44
44
  * same-origin routes the Settings panel reads. The SSH transport is reached
45
45
  * over HTTP at the ssh-manager's own route, so it is not injected here.
46
+ * `systemPrompt` is the runtime memory instruction section's registry.
46
47
  */
47
48
  export declare const inject: string[];
48
49
  /** Plugin configuration. */
@@ -85,6 +86,12 @@ export interface Config {
85
86
  viewRoot: string;
86
87
  /** Local deployments: authoritative storage base, default `~/kb`. */
87
88
  storageRoot: string;
89
+ /** Where personal memory bindings live; empty means `<actualRoot>/.memory/users`. */
90
+ memoryUsersRoot: string;
91
+ /** Where promoted skills are written; empty means `$DSH_HOME/skills` (or `~/.dsh/skills`). */
92
+ memorySkillsRoot: string;
93
+ /** Idle minutes before a normal session notifies the memory guardian. */
94
+ memoryIdleMinutes: number;
88
95
  /** Comma-separated export spec of clients allowed to mount the NFS export. */
89
96
  permitted: string;
90
97
  /** Host serving the export, as an address or `address:/path` pseudo root. */
@@ -330,7 +337,17 @@ export declare function classifyMount(config: Config): Promise<KnowledgeMountSta
330
337
  * @param paths - candidate relative paths; omitted means walk the authoritative root.
331
338
  * @returns The sync report, or a refusal the caller should relay.
332
339
  */
333
- export declare function syncCallerView(host: Context, config: Config, paths?: string[]): Promise<(ViewDelta & SyncReportFields & {
340
+ export declare function syncCallerView(host: Context, config: Config, paths?: string[], options?: {
341
+ /**
342
+ * Called after a file that existed only in the view was imported into the
343
+ * authoritative tree. The caller owns extraction/indexing because only it knows
344
+ * the deployment's parser settings and queue.
345
+ */
346
+ onAdopted?: (adopted: {
347
+ viewPath: string;
348
+ actualRelPath: string;
349
+ }) => void | Promise<void>;
350
+ }): Promise<(ViewDelta & SyncReportFields & {
334
351
  status: number;
335
352
  error?: never;
336
353
  }) | {
@@ -840,22 +857,79 @@ export declare function createKnowledgeEntry(config: Config, relPath: string, op
840
857
  * `no such document`.
841
858
  */
842
859
  export declare function actualRelPathForView(ctx: Context, config: Config, relPath: string, caller?: KnowledgeCaller): Promise<string>;
860
+ /** Outcome of importing a file that exists only in a caller's view. */
861
+ export interface ViewAdoptionResult {
862
+ /** Whether the bytes now live at an authoritative path. */
863
+ adopted: boolean;
864
+ /** The authoritative path, relative to `actualRoot`, when adopted. */
865
+ actualRelPath?: string;
866
+ /** Why the file was not adopted. */
867
+ reason?: string;
868
+ }
869
+ /**
870
+ * Import one view-only file into the authoritative tree.
871
+ *
872
+ * A view is a hardlink mirror of `actualRoot`; a new file placed in it by a shell
873
+ * `cp` (or an editor's save-as) has no authoritative counterpart. The view sync
874
+ * treats such a file as an orphan and unlinks it, which deletes the only copy the
875
+ * reader has. This function is the alternative: copy the bytes to the authoritative
876
+ * path the view path maps to, then replace the view entry with a hardlink to that
877
+ * copy. The next sync then sees one file, DataOps keeps resolving it, and extraction
878
+ * and indexing have a real document to work on.
879
+ *
880
+ * Refuses without a write grant, without a non-empty path, or when a DIFFERENT
881
+ * authoritative file already owns the destination name — importing must never
882
+ * overwrite a document.
883
+ *
884
+ * @param host - Host context, for the caller and the write grant.
885
+ * @param config - resolved plugin config.
886
+ * @param relPath - the view-relative path (as the reader sees it).
887
+ * @param options - caller and the already-resolved view file, when known.
888
+ * @returns whether the import happened, and where.
889
+ */
890
+ export declare function adoptViewFile(host: Context, config: Config, relPath: string, options?: {
891
+ caller?: {
892
+ userId: string;
893
+ };
894
+ fullPath?: string;
895
+ }): Promise<ViewAdoptionResult>;
896
+ /**
897
+ * The canonical VIEW path a model-facing file-tool path names.
898
+ *
899
+ * The `kb_file_*` tools speak view coordinates (`global/…`, `department/…`,
900
+ * `personal/…` or a bare path). A bare path has no bucket, and the old code left
901
+ * it untouched: `createKnowledgeEntry` then wrote it at the authoritative top
902
+ * level, which the view renders as `global/…` because {@link bucketOf} treats an
903
+ * unknown head as global. That is how a personal memory write silently became a
904
+ * global document.
905
+ *
906
+ * On a team deployment a bare path belongs to the caller's PERSONAL bucket — the
907
+ * only bucket one caller owns — so it is spelled `personal/<path>`. Explicit
908
+ * scope spellings, including the localized aliases, are already canonical after
909
+ * {@link resolveScopeAlias} and are returned unchanged. A local deployment keeps
910
+ * the legacy flat tree, where there are no buckets, so nothing is prefixed.
911
+ *
912
+ * @param relPath - model-supplied path, already validated/alias-resolved or not.
913
+ * @param team - `isTeamDeployment(config)`; false keeps the flat local layout.
914
+ */
915
+ export declare function toolScopedViewPath(relPath: string, team: boolean): string;
843
916
  /**
844
- * Resolve the three knowledge-graph scope roots for one caller.
845
- *
846
- * `actualRelPathForView` is the authority for a FILE: it matches a view entry to its
847
- * source by inode. A scope directory has no view hardlink (directories cannot be hard
848
- * linked), so for `department/知识图谱` and `personal/知识图谱` it answers the view
849
- * spelling. The caller's own owner/chain segment therefore has to be composed here,
850
- * exactly as {@link bucketOf} composes it for the view: the personal root is
851
- * `personal/<uid>/知识图谱`, and the department root is
852
- * `department/<chain>/知识图谱` (legacy flat: `department/<code>/知识图谱`).
853
- *
854
- * The department view prefix is not always `department/知识图谱`: with an organization
855
- * path the view mirrors the chain, so the graph's view path carries it too. Choosing
856
- * the wrong one made every department document link point at a folder the view never
857
- * creates. The layout is picked from what exists on disk, with a legacy flat fallback.
917
+ * The AUTHORITATIVE path a model-facing file-tool path names.
918
+ *
919
+ * A view drops the personal owner segment (`personal/note.md`), but the actual
920
+ * tree keeps it (`personal/<uid>/note.md`). Writes, overwrites and existence
921
+ * checks must use this form; reads/listings stay in view coordinates and use the
922
+ * view root. Global and department paths are unchanged: their view and actual
923
+ * spellings are already identical (or handled by their own layout rules).
924
+ *
925
+ * A path that already carries the caller's own id is returned untouched, so the
926
+ * resolver is idempotent and graph tools (which pass actual paths) are safe.
927
+ *
928
+ * @param relPath - model-supplied path (view or already-actual).
929
+ * @param userId - the caller whose personal tree owns a bare/personal path.
930
+ * @param team - `isTeamDeployment(config)`; false keeps the flat local layout.
858
931
  */
932
+ export declare function toolScopedActualPath(relPath: string, userId: string, team: boolean): string;
859
933
  export declare function knowledgeGraphScopeRoots(host: Context, config: Config, caller: KnowledgeCaller): Promise<KnowledgeGraphScopeRoot[]>;
860
934
  export declare function extractBeside(config: Config, relPath: string, mineruUrl?: string, readSharedUrl?: () => Promise<string | undefined>, ctx?: Context): Promise<{
861
935
  markdown: string;
@@ -1106,6 +1180,18 @@ export declare function kbSummarizeSkillPath(): string;
1106
1180
  export declare function kbVectorizeSkillPath(): string;
1107
1181
  /** Where the bundled `knowledge-graph` skill lives. */
1108
1182
  export declare function knowledgeGraphSkillPath(): string;
1183
+ /** The guardian's own operating skill. */
1184
+ export declare const MEMORY_GUARDIAN_SKILL_NAME = "memory-guardian";
1185
+ /** The extraction subagent's skill. */
1186
+ export declare const MEMORY_EXTRACT_SKILL_NAME = "memory-extract";
1187
+ /** The SOP evaluation subagent's skill. */
1188
+ export declare const MEMORY_SOP_EVALUATE_SKILL_NAME = "memory-sop-evaluate";
1189
+ /** Where the bundled `memory-guardian` skill lives. */
1190
+ export declare function memoryGuardianSkillPath(): string;
1191
+ /** Where the bundled `memory-extract` skill lives. */
1192
+ export declare function memoryExtractSkillPath(): string;
1193
+ /** Where the bundled `memory-sop-evaluate` skill lives. */
1194
+ export declare function memorySopEvaluateSkillPath(): string;
1109
1195
  /**
1110
1196
  * Where this package's tutorial document lives, from either build layout.
1111
1197
  *
@@ -1200,3 +1286,37 @@ export declare function knowledgeBaseToolDisclosure(host: object): ToolDisclosur
1200
1286
  export declare function apply(ctx: Context, deploymentConfig: Config): void;
1201
1287
  /** Re-exported for tests and for callers that need the host shape. */
1202
1288
  export type { RemoteHost, RemoteRunner };
1289
+ export { GraphLoadError, listGraphs, loadGraph, parseNodeFrontMatter, validateGraph, } from './graphModel.ts';
1290
+ export type { GraphManifest, GraphManifestEdge, GraphManifestNode, GraphValidationIssue, LoadedGraph, LoadedGraphEdge, LoadedGraphNode, MemoryAuthority, MemoryNodeType, MemoryOrigin, MemoryReviewStatus, } from './graphModel.ts';
1291
+ export { canManageGraph, canViewGraph, filterVisibleGraphs, } from './graphPolicy.ts';
1292
+ export type { GraphScopeDescriptor, GraphViewer } from './graphPolicy.ts';
1293
+ export { BindingStore, bindingKey, } from './memoryBindings.ts';
1294
+ export type { BindingLineage, BindingMode, BindingSourceType, BindingStatus, PersonalBinding, } from './memoryBindings.ts';
1295
+ export { markUpstreamUpdates, runGuardianPass } from './memoryGuardian.ts';
1296
+ export { decideMemoryAction, runtimeInjectionTags } from './memoryPolicy.ts';
1297
+ export { diffSnapshots, parentChain, refreshDirtySummaries, scanKnowledgeTree, } from './summaryIndex.ts';
1298
+ export type { ChangeSet, ChangeSnapshot } from './summaryIndex.ts';
1299
+ export { applyMigration, planMigration, renderMigrationReport, } from './graphMigration.ts';
1300
+ export type { MigrationOptions, MigrationReport } from './graphMigration.ts';
1301
+ export { applySummaryWriteback, summarySnapshotPathFor } from './summaryWriteback.ts';
1302
+ export type { SummaryWritebackOptions, SummaryWritebackResult } from './summaryWriteback.ts';
1303
+ export { resolveMemoryContext, renderMemoryContextMarkdown } from './memoryContext.ts';
1304
+ export type { MemoryContextResult } from './memoryContext.ts';
1305
+ export { createMemoryTools } from './memoryTools.ts';
1306
+ export type { MemoryContextToolResult, MemoryGuardianToolResult, MemoryToolHost } from './memoryTools.ts';
1307
+ export { MemoryStore, MemoryStoreError, MEMORY_LOG_DIR, MEMORY_SOP_DIR, MEMORY_PREFERENCE_FILE, MEMORY_PITFALL_FILE, MEMORY_FACT_FILE, } from './memoryStore.ts';
1308
+ export type { MemoryStoreOptions, MemoryIndex, MemoryLogSummary, AppendLogOptions, AppendLogResult, PreferenceUpsertResult, PitfallUpsertResult, FactUpsertResult, SopWriteResult, SopUpdateResult, SopPatch, } from './memoryStore.ts';
1309
+ export { MemoryGraphWriter, MemoryGraphWriterError, syncPersonalMemoryGraph, PERSONAL_MEMORY_FOLDER, PERSONAL_MEMORY_GRAPH_ID, } from './memoryGraphWriter.ts';
1310
+ export type { MemoryGraphWriterOptions, PersonalMemoryGraphResult } from './memoryGraphWriter.ts';
1311
+ export { MEMORY_TYPES, PRIVACY_VALUES, FACT_KINDS, SOP_STATUSES, MEMORY_ENTRY_MARKER, isMemoryType, isPrivacy, isFactKind, isSopStatus, isSafeMemorySlug, validateMemoryEntry, assertValidMemoryEntry, parseMemoryEntries, serializeMemoryEntry, newMemoryId, } from './memoryTypes.ts';
1312
+ export type { MemoryType, Privacy, FactKind, AppId, SopStatus, MemoryEntry, Preference, Pitfall, Episodic, Fact, Sop, AnyMemoryEntry, MemoryEntryInput, MemoryValidationIssue, MemoryValidationError, } from './memoryTypes.ts';
1313
+ export { GuardianSessionStore, resolveOrCreateGuardian, sendToGuardian, GUARDIAN_SESSION_TITLE, GUARDIAN_SKILL_NAME, } from './guardianSession.ts';
1314
+ export type { GuardianReason, GuardianMessage, GuardianSessionState, GuardianAgentRef, GuardianDelivery, CreateGuardianAgentInput, GuardianSessionHost, ResolvedGuardian, GuardianSendResult, } from './guardianSession.ts';
1315
+ export { createMemoryGuardianTools } from './memoryGuardianTool.ts';
1316
+ export type { MemoryGuardianToolHost, MemoryGuardianSendArgs, MemoryGuardianSendValue } from './memoryGuardianTool.ts';
1317
+ export { installMemoryTriggers, IDLE_DEBOUNCE_MS } from './memoryTriggers.ts';
1318
+ export type { MemoryTriggerHost, MemoryTriggerSession, MemoryTriggerEvent, MemoryTriggerTimers } from './memoryTriggers.ts';
1319
+ export { createMemoryRecordTools } from './memoryRecordTool.ts';
1320
+ export type { MemoryRecordToolHost } from './memoryRecordTool.ts';
1321
+ export { promoteSopToSkill, deleteSopAfterPromotion } from './memorySkillPromotion.ts';
1322
+ export type { PromoteSopInput, DeleteSopInput, SopDraft } from './memorySkillPromotion.ts';
@@ -22,6 +22,7 @@ import type { FtsIndexStats, FtsSearchResult } from './ftsIndex.ts';
22
22
  import type { OutlineKeyFact, OutlineTocEntry } from './outlineText.ts';
23
23
  import type { OutlineSectionSubmission, OutlineSummaryKind } from './outlineGuard.ts';
24
24
  import type { OutlineSaveResult } from './ftsIndex.ts';
25
+ import { type CanonicalScope } from './scopeAliases.ts';
25
26
  import type { KnowledgeAuditEntry } from './views.ts';
26
27
  /** Error codes a tool may report to the model. */
27
28
  export type KnowledgeToolErrorCode = 'empty-path' | 'nul-byte' | 'absolute-path' | 'escapes-knowledge-root' | 'forbidden' | 'not-found' | 'exists' | 'too-large' | 'binary' | 'not-a-directory' | 'not-a-file' | 'not-configured' | 'unauthorized' | 'unreachable' | 'bad-response' | 'write-failed' | 'invalid-regex' | 'invalid-citation' | 'invalid-summary' | 'invalid';
@@ -176,6 +177,14 @@ export interface KnowledgeFileToolHost {
176
177
  }): Promise<OutlineSaveResult | undefined>;
177
178
  canRead(relPath: string): Promise<boolean>;
178
179
  canWrite(relPath: string): Promise<boolean>;
180
+ /**
181
+ * Default bucket for a path that names no scope at all.
182
+ *
183
+ * A team deployment answers `personal`: a bare relative path is the caller's
184
+ * own tree, never the shared root that the view renders as `global`. A local
185
+ * deployment omits this, keeping the legacy flat top-level path.
186
+ */
187
+ defaultScope?(): CanonicalScope | undefined;
179
188
  /** One view directory level, already filtered by `canReadPath`. */
180
189
  list(relPath: string, caller: KnowledgeToolCaller): Promise<KnowledgeFileEntry[]>;
181
190
  /** Search under one view-relative scope. */
@@ -189,12 +198,21 @@ export interface KnowledgeFileToolHost {
189
198
  createEntry(relPath: string, options: {
190
199
  directory: boolean;
191
200
  content?: string;
201
+ bytes?: Uint8Array;
192
202
  }): Promise<{
193
203
  relPath: string;
194
204
  kind: 'file' | 'directory';
195
205
  }>;
196
206
  /** Overwrite an existing file in place, preserving its inode/view hardlink. */
197
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>;
198
216
  moveEntry(from: string, to: string, caller: KnowledgeToolCaller): Promise<{
199
217
  from: string;
200
218
  to: string;
@@ -207,8 +225,31 @@ export interface KnowledgeFileToolHost {
207
225
  mineruBaseUrl?: string;
208
226
  }>;
209
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
+ }>;
210
243
  /** Enqueue one document; mirrors the manual extraction route's outcomes. */
211
- 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<{
212
253
  outcome: 'already-markdown' | 'unsupported' | 'exists' | 'queued';
213
254
  markdown?: string;
214
255
  task?: unknown;
@@ -229,8 +270,15 @@ export declare const asKnowledgeToolError: (error: unknown, path?: string) => Kn
229
270
  *
230
271
  * Empty is allowed only where the root itself is the argument (list/search/extract-all);
231
272
  * everything else is refused with the same four codes `checkLocalPath` uses.
273
+ *
274
+ * `defaultScope` decides what a path with NO bucket prefix means. When omitted
275
+ * the legacy behaviour is kept (a bare top-level path). A team deployment passes
276
+ * `personal`, so `个人记忆图谱/…` without a bucket resolves inside the caller's
277
+ * own tree instead of becoming an unowned top-level path that the view shows as
278
+ * `global`. Explicit `global/`, `department/` and `personal/` spellings (and
279
+ * their localized aliases) are never rewritten.
232
280
  */
233
- export declare const assertToolPath: (value: unknown, allowRoot?: boolean) => string;
281
+ export declare const assertToolPath: (value: unknown, allowRoot?: boolean, defaultScope?: CanonicalScope) => string;
234
282
  /**
235
283
  * Build the knowledge-base model-facing tools.
236
284
  *
@@ -0,0 +1,119 @@
1
+ /** What a binding points at. */
2
+ export type BindingSourceType = 'node' | 'edge';
3
+ /** Lifecycle of a personal binding. */
4
+ export type BindingMode = 'pending' | 'subscribe' | 'internalize';
5
+ /** Health of a binding after its source moved on or its policy changed. */
6
+ export type BindingStatus = 'active' | 'stale' | 'revoked';
7
+ /** A concrete mode a pending binding asks the guardian to apply. */
8
+ export type RequestedBindingMode = Exclude<BindingMode, 'pending'>;
9
+ /** Provenance of a personal branch. */
10
+ export interface BindingLineage {
11
+ subscribedAt?: string;
12
+ forkedFromVersion?: number;
13
+ forkedAt?: string;
14
+ divergence?: string[];
15
+ }
16
+ /**
17
+ * One user's relationship to one graph source.
18
+ *
19
+ * `localPath` has two meanings, keyed by `mode`:
20
+ *
21
+ * - `internalize`: the personal copy, relative to `<usersRoot>/<userId>`
22
+ * (`memory/<graphId>/<sourceId>.md`);
23
+ * - `subscribe`: the source document path relative to the graph scope root
24
+ * (e.g. `制度/采购制度.md`). It is a proxy reference only - no body is
25
+ * copied, and the runtime reads the department document live.
26
+ * - `pending`: absent.
27
+ *
28
+ * `requestedMode` is the hand-off used by the UI: a user writes
29
+ * `{ mode: 'pending', requestedMode: 'internalize' }` and the guardian session
30
+ * (the single writer of binding files) performs the copy on its next pass.
31
+ * Without a request, a pending binding is resolved to `subscribe`, which is
32
+ * always safe because it copies no content.
33
+ */
34
+ export interface PersonalBinding {
35
+ userId: string;
36
+ sourceType: BindingSourceType;
37
+ sourceId: string;
38
+ graphId: string;
39
+ mode: BindingMode;
40
+ sourceVersion: number;
41
+ sourceCommit?: string;
42
+ lineage: BindingLineage;
43
+ status: BindingStatus;
44
+ updatedAt: string;
45
+ localPath?: string;
46
+ requestedMode?: RequestedBindingMode;
47
+ }
48
+ /** Raised when a binding file or a binding value is unusable. */
49
+ export declare class BindingStoreError extends Error {
50
+ readonly filePath?: string;
51
+ constructor(message: string, filePath?: string);
52
+ }
53
+ /**
54
+ * Compose the binding file stem: `<sourceType>-<sourceId>`.
55
+ *
56
+ * The source id becomes part of a file name, so path separators, NUL bytes,
57
+ * leading dots and surrounding whitespace are refused rather than escaped.
58
+ * Legitimate graph ids (ASCII slugs and Chinese ids alike) are untouched.
59
+ */
60
+ export declare function bindingKey(sourceType: BindingSourceType, sourceId: string): string;
61
+ /** Relative personal copy path for an internalized binding. */
62
+ export declare function memoryRelativePath(graphId: string, sourceId: string): string;
63
+ /** Absolute personal copy path for an internalized binding. */
64
+ export declare function memoryFilePath(usersRoot: string, userId: string, graphId: string, sourceId: string): string;
65
+ /**
66
+ * Atomic UTF-8 write: write a sibling temp file, then `rename` it over the
67
+ * target. Same-directory temp + rename is atomic on POSIX file systems, and on
68
+ * Windows `rename` over an existing file is supported by Node.
69
+ */
70
+ export declare function writeFileAtomic(filePath: string, content: string, options?: {
71
+ mode?: number;
72
+ }): Promise<void>;
73
+ /**
74
+ * Binding store rooted at a users directory. Paths are injected, never read
75
+ * from global config, so tests and the runtime can point at different roots.
76
+ */
77
+ export declare class BindingStore {
78
+ private readonly usersRoot;
79
+ constructor(usersRoot: string);
80
+ /** Directory holding every binding file for one user. */
81
+ readonlyPath(userId: string): string;
82
+ /** Rebuild the list from the binding directory; no index is kept. */
83
+ list(userId: string): Promise<PersonalBinding[]>;
84
+ /** Read one binding; a missing file is `undefined`, not an error. */
85
+ get(userId: string, sourceType: BindingSourceType, sourceId: string): Promise<PersonalBinding | undefined>;
86
+ /** Create or replace one binding atomically. */
87
+ set(binding: PersonalBinding): Promise<void>;
88
+ /** Delete one binding. Removing a file that is already gone is a no-op. */
89
+ remove(userId: string, sourceType: BindingSourceType, sourceId: string): Promise<void>;
90
+ }
91
+ /** Serialize a binding into the simple YAML dialect described above. */
92
+ export declare function serializeBinding(binding: PersonalBinding): string;
93
+ /** Parse one binding file. Throws `BindingStoreError` when required fields are absent. */
94
+ export declare function parseBinding(source: string, filePath?: string): PersonalBinding;
95
+ /** Scalar values the writer understands. */
96
+ export type YamlScalar = string | number | boolean;
97
+ /** One level of nesting is enough for bindings and memory frontmatter. */
98
+ export type YamlValue = YamlScalar | YamlScalar[] | YamlRecord;
99
+ /** Ordered YAML object. `undefined` entries are omitted. */
100
+ export interface YamlRecord {
101
+ [key: string]: YamlValue | undefined;
102
+ }
103
+ /** Quote a scalar when the tiny parser (or a real YAML parser) could misread it. */
104
+ export declare function formatYamlScalar(value: YamlScalar): string;
105
+ /** Serialize a flat/nested record in the simple dialect. Arrays are inline. */
106
+ export declare function stringifySimpleYaml(record: YamlRecord): string;
107
+ /**
108
+ * Parse the simple dialect into string scalars (numbers, booleans and
109
+ * timestamps stay strings so ids like `00123` survive) plus `string[]` arrays
110
+ * and nested maps. Unknown/invalid lines are ignored; typed readers validate.
111
+ */
112
+ export declare function parseSimpleYaml(source: string): Record<string, unknown>;
113
+ /**
114
+ * A path segment is safe when it cannot leave its directory and cannot create
115
+ * a hidden file. Unicode letters, spaces inside and dots inside are accepted.
116
+ */
117
+ export declare function assertPathSegment(value: string, label: string): string;
118
+ /** Validate a `/`-separated relative path (graph-relative or user-relative). */
119
+ export declare function assertRelativePath(value: string, label: string): string;
@@ -0,0 +1,83 @@
1
+ import type { GraphManifest, LoadedGraph, MemoryAuthority, MemoryOrigin, MemoryReviewStatus } from './graphModel.ts';
2
+ import { type GraphScopeDescriptor, type GraphViewer } from './graphPolicy.ts';
3
+ import { type BindingSourceType, type BindingStatus, type PersonalBinding } from './memoryBindings.ts';
4
+ /** Default prompt budget for the resolved context. */
5
+ export declare const DEFAULT_MEMORY_CONTEXT_MAX_CHARS = 8000;
6
+ /** Marker the runtime must treat as above personal memory and preferences. */
7
+ export declare const SYSTEM_POLICY_MARKER = "system policy overrides personal memory";
8
+ /** How a memory entry reaches the personal graph. */
9
+ export type MemoryContextMode = 'subscribe' | 'internalize';
10
+ /** One resolved node/edge the runtime may inject. */
11
+ export interface MemoryContextEntry {
12
+ mode: MemoryContextMode;
13
+ graphId: string;
14
+ sourceType: BindingSourceType;
15
+ sourceId: string;
16
+ title: string;
17
+ /** Node type or relation type. */
18
+ type: string;
19
+ authority: MemoryAuthority;
20
+ origin: MemoryOrigin;
21
+ reviewStatus: MemoryReviewStatus;
22
+ /** True for a redline (direct or inherited): personal memory must not override it. */
23
+ nonOverridable: boolean;
24
+ /** Set together with `nonOverridable`. */
25
+ policyNote?: string;
26
+ status: BindingStatus;
27
+ sourceVersion: number;
28
+ sourceCommit?: string;
29
+ /** Live source path for a proxy; personal branch path for an internalized copy. */
30
+ path?: string;
31
+ /** Relation endpoints, when the source is an edge. */
32
+ from?: string;
33
+ to?: string;
34
+ body: string;
35
+ /** Budget cost used by this resolver (title + body + fixed metadata overhead). */
36
+ chars: number;
37
+ }
38
+ /** One entry omitted only because the character budget ran out. */
39
+ export interface MemoryContextDrop {
40
+ graphId: string;
41
+ sourceType: BindingSourceType;
42
+ sourceId: string;
43
+ mode: MemoryContextMode;
44
+ chars: number;
45
+ reason: 'budget';
46
+ }
47
+ /** The resolver output. */
48
+ export interface MemoryContextResult {
49
+ userId: string;
50
+ entries: MemoryContextEntry[];
51
+ dropped: MemoryContextDrop[];
52
+ charCount: number;
53
+ maxChars: number;
54
+ redlineCount: number;
55
+ /** Non-empty when at least one redline is present. */
56
+ systemPolicy: string;
57
+ }
58
+ /** Resolver input. All roots and graphs are injected; no global config is read. */
59
+ export interface MemoryContextInput {
60
+ viewer: GraphViewer;
61
+ usersRoot: string;
62
+ userId: string;
63
+ graphs: LoadedGraph[];
64
+ /** Pre-read bindings, for callers that already listed them. Omit to rebuild from disk. */
65
+ bindings?: PersonalBinding[];
66
+ /** Prompt budget; defaults to {@link DEFAULT_MEMORY_CONTEXT_MAX_CHARS}. */
67
+ maxChars?: number;
68
+ }
69
+ /**
70
+ * Adapt a loaded graph manifest to the visibility descriptor `canViewGraph`
71
+ * expects. `scope` is the machine scope (`global`, `department:<code>`,
72
+ * `personal:<uid>`); `owner` is the private-graph owner when present.
73
+ */
74
+ export declare function graphScopeDescriptor(manifest: GraphManifest): GraphScopeDescriptor;
75
+ /**
76
+ * Resolve the caller's personal memory context.
77
+ *
78
+ * @param input - viewer, roots, user id, loaded graphs and optional budget.
79
+ * @returns Priority-ordered entries, budget drops and redline counters.
80
+ */
81
+ export declare function resolveMemoryContext(input: MemoryContextInput): Promise<MemoryContextResult>;
82
+ /** Render a resolved context for a model-facing text tool result. */
83
+ export declare function renderMemoryContextMarkdown(result: MemoryContextResult): string;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Ensure the personal memory graph exists.
3
+ *
4
+ * The graph tab is a catalogue of `.graphs/<id>/graph.json` manifests. A user
5
+ * with no subscriptions yet has no personal graph at all, which reads as "the
6
+ * memory feature is missing" rather than "there is nothing in it". This creates
7
+ * an empty, private, published manifest for the caller once; it is the stable
8
+ * home the guardian will later fill with subscription proxies and internalized
9
+ * branches.
10
+ *
11
+ * Writing is deliberately best-effort at the call site: a read-only mount must
12
+ * keep the graph tab usable, so a failed bootstrap is not an error for the route.
13
+ *
14
+ * @module @sparkelf/dsh-knowledge-base/memory-graph-bootstrap
15
+ */
16
+ /** Stable graph id for the caller's personal memory graph. */
17
+ export declare const PERSONAL_MEMORY_GRAPH_ID = "personal-memory";
18
+ /** Display name shown in the graph tree. */
19
+ export declare const PERSONAL_MEMORY_GRAPH_NAME = "\u4E2A\u4EBA\u8BB0\u5FC6\u56FE\u8C31";
20
+ /** One empty manifest as it is written to disk. */
21
+ export interface PersonalMemoryGraphManifest {
22
+ schemaVersion: 1;
23
+ id: string;
24
+ name: string;
25
+ description: string;
26
+ scope: string;
27
+ version: number;
28
+ status: 'draft' | 'published';
29
+ owner: string;
30
+ createdAt: string;
31
+ updatedAt: string;
32
+ publishedAt: string;
33
+ tags: string[];
34
+ visibility: 'private';
35
+ defaultView: {
36
+ layout: string;
37
+ direction: string;
38
+ };
39
+ topics: unknown[];
40
+ nodes: unknown[];
41
+ edges: unknown[];
42
+ }
43
+ /** The manifest a fresh personal memory graph holds. */
44
+ export declare function emptyPersonalMemoryManifest(userId: string, now: string): PersonalMemoryGraphManifest;
45
+ /**
46
+ * Create `<scopeRoot>/.graphs/personal-memory/graph.json` when it is absent.
47
+ *
48
+ * @param options.scopeRoot - absolute personal scope root (`<actualRoot>/personal/<uid>`).
49
+ * @param options.userId - stable caller id; also the manifest owner.
50
+ * @param options.now - injectable clock for tests.
51
+ * @returns whether the manifest was created and its absolute path.
52
+ */
53
+ export declare function ensurePersonalMemoryGraph(options: {
54
+ scopeRoot: string;
55
+ userId: string;
56
+ now?: string;
57
+ }): Promise<{
58
+ created: boolean;
59
+ path: string;
60
+ }>;
61
+ /** Read the personal memory manifest when it exists, for tests and diagnostics. */
62
+ export declare function readPersonalMemoryGraph(scopeRoot: string): Promise<PersonalMemoryGraphManifest | undefined>;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Keeps the personal-memory graph manifest in sync with the memory files.
3
+ *
4
+ * The memory store owns the documents; this writer owns only
5
+ * `<scopeRoot>/.graphs/personal-memory/graph.json`. It never rewrites a memory
6
+ * document and never duplicates a node:
7
+ *
8
+ * ```text
9
+ * 个人记忆图谱/记忆日志/2026-11-12.md -> node memory-个人记忆图谱-记忆日志-2026-11-12
10
+ * 个人记忆图谱/偏好.md -> node memory-个人记忆图谱-偏好
11
+ * 个人记忆图谱/SOP/指标口径排查.md -> node memory-个人记忆图谱-SOP-指标口径排查
12
+ * ```
13
+ *
14
+ * Node ids are derived from the scope-relative path and kept stable across
15
+ * writes, so edges added later (daily document -> derived aggregate / SOP) do not
16
+ * dangle. Every manifest write is atomic and validated with `loadGraph` +
17
+ * `validateGraph`; if validation fails the previous manifest is restored.
18
+ *
19
+ * The graph is lazy: the first access creates an empty, valid
20
+ * `personal-memory/graph.json` so "no memories yet" still has a graph home.
21
+ *
22
+ * @module @sparkelf/dsh-knowledge-base/memory-graph-writer
23
+ */
24
+ /** Default memory tree folder inside a personal scope. */
25
+ export declare const PERSONAL_MEMORY_FOLDER = "\u4E2A\u4EBA\u8BB0\u5FC6\u56FE\u8C31";
26
+ /** Default graph id, matching the design's `personal-memory/graph.json`. */
27
+ export declare const PERSONAL_MEMORY_GRAPH_ID = "personal-memory";
28
+ /** Writer construction options. */
29
+ export interface MemoryGraphWriterOptions {
30
+ /** Personal scope root that owns `.graphs/`. */
31
+ scopeRoot: string;
32
+ /** Memory tree relative to `scopeRoot`; defaults to `个人记忆图谱`. */
33
+ memoryRoot?: string;
34
+ /** Graph directory id under `.graphs/`; defaults to `personal-memory`. */
35
+ graphId?: string;
36
+ /** Manifest `scope` string; defaults to `personal`. */
37
+ scope?: string;
38
+ now?: () => Date;
39
+ }
40
+ /** Result of one manifest reconciliation. */
41
+ export interface PersonalMemoryGraphResult {
42
+ /** Absolute path of `graph.json`. */
43
+ graphPath: string;
44
+ /** Node count after the operation. */
45
+ nodeCount: number;
46
+ /** True when the manifest was rewritten. */
47
+ changed: boolean;
48
+ }
49
+ export type MemoryGraphWriterErrorCode = 'invalid-option' | 'unsafe-path' | 'missing-memory-document' | 'invalid-graph';
50
+ export declare class MemoryGraphWriterError extends Error {
51
+ readonly code: MemoryGraphWriterErrorCode;
52
+ constructor(code: MemoryGraphWriterErrorCode, message: string);
53
+ }
54
+ /**
55
+ * Owns one personal-memory `graph.json`.
56
+ *
57
+ * A single writer is assumed (the guardian session); `registerPath` is the
58
+ * incremental hook after a store write, `removePath` after a SOP delete, and
59
+ * `syncAll` is the reconciliation pass that can be run at any time.
60
+ */
61
+ export declare class MemoryGraphWriter {
62
+ private readonly scopeRoot;
63
+ private readonly memoryRoot;
64
+ private readonly graphId;
65
+ private readonly scope;
66
+ private readonly clock;
67
+ constructor(options: MemoryGraphWriterOptions);
68
+ /** Absolute manifest path owned by this writer. */
69
+ get graphPath(): string;
70
+ /** Absolute root of the memory documents. */
71
+ get memoryPath(): string;
72
+ /** Create an empty, valid graph on first access; idempotent afterwards. */
73
+ ensureGraph(): Promise<PersonalMemoryGraphResult>;
74
+ /**
75
+ * Register one document that the store just wrote.
76
+ *
77
+ * `memoryRelativePath` is relative to the memory root (for example
78
+ * `记忆日志/2026-11-12.md` or `SOP/指标口径排查.md`). The file must exist: a
79
+ * manifest node pointing at nothing is a validator error.
80
+ */
81
+ registerPath(memoryRelativePath: string): Promise<PersonalMemoryGraphResult>;
82
+ /** Drop one document node and any edge that referenced it. */
83
+ removePath(memoryRelativePath: string): Promise<PersonalMemoryGraphResult>;
84
+ /**
85
+ * Reconcile the manifest with the memory files that exist on disk.
86
+ *
87
+ * Adds nodes for new files, removes nodes whose memory document disappeared,
88
+ * and drops edges that would no longer resolve. Nodes outside the memory root
89
+ * are left alone; the manifest stays `validateGraph`-clean.
90
+ */
91
+ syncAll(): Promise<PersonalMemoryGraphResult>;
92
+ private memoryPathsOf;
93
+ private scanMemoryPaths;
94
+ private reconcile;
95
+ private emptyManifest;
96
+ private tryLoadManifest;
97
+ private writeManifest;
98
+ private isFile;
99
+ }
100
+ /** Convenience one-shot reconciliation for wiring. */
101
+ export declare function syncPersonalMemoryGraph(options: MemoryGraphWriterOptions): Promise<PersonalMemoryGraphResult>;