@sparkelf/dsh-knowledge-base 0.1.36 → 0.4.2

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 (38) hide show
  1. package/README.md +34 -0
  2. package/lib/client.js +1915 -837
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +17341 -7679
  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/graphCanvas.d.ts +1 -1
  9. package/lib/types/graphJsonProjection.d.ts +71 -0
  10. package/lib/types/graphMigration.d.ts +118 -0
  11. package/lib/types/graphModel.d.ts +194 -0
  12. package/lib/types/graphPolicy.d.ts +68 -0
  13. package/lib/types/graphTools.d.ts +23 -4
  14. package/lib/types/graphTypes.d.ts +24 -0
  15. package/lib/types/guardianSession.d.ts +135 -0
  16. package/lib/types/index.d.ts +88 -14
  17. package/lib/types/knowledgeTools.d.ts +17 -1
  18. package/lib/types/memoryBindings.d.ts +119 -0
  19. package/lib/types/memoryContext.d.ts +83 -0
  20. package/lib/types/memoryGraphBootstrap.d.ts +62 -0
  21. package/lib/types/memoryGraphWriter.d.ts +101 -0
  22. package/lib/types/memoryGuardian.d.ts +123 -0
  23. package/lib/types/memoryGuardianTool.d.ts +56 -0
  24. package/lib/types/memoryPolicy.d.ts +106 -0
  25. package/lib/types/memoryRecordTool.d.ts +39 -0
  26. package/lib/types/memoryRoutes.d.ts +85 -0
  27. package/lib/types/memorySettings.d.ts +40 -0
  28. package/lib/types/memorySkillPromotion.d.ts +62 -0
  29. package/lib/types/memoryStore.d.ts +297 -0
  30. package/lib/types/memoryTools.d.ts +71 -0
  31. package/lib/types/memoryTriggers.d.ts +65 -0
  32. package/lib/types/memoryTypes.d.ts +241 -0
  33. package/lib/types/summaryIndex.d.ts +112 -0
  34. package/lib/types/summaryWriteback.d.ts +87 -0
  35. package/package.json +1 -1
  36. package/skills/memory-extract/SKILL.md +43 -0
  37. package/skills/memory-guardian/SKILL.md +97 -0
  38. package/skills/memory-sop-evaluate/SKILL.md +43 -0
@@ -0,0 +1,135 @@
1
+ /** Why a guardian message was produced. */
2
+ export type GuardianReason = 'idle' | 'compaction' | 'dream' | 'manual';
3
+ /** One message to deliver to the user's guardian session. */
4
+ export interface GuardianMessage {
5
+ reason: GuardianReason;
6
+ /** The ordinary session that triggered this message (idle/compaction). */
7
+ sessionId?: string;
8
+ /** The compaction transaction that triggered this message. */
9
+ compactionId?: string;
10
+ /** Short free-form context; never a document body. */
11
+ note?: string;
12
+ }
13
+ /** Durable guardian identity. */
14
+ export interface GuardianSessionState {
15
+ version: 1;
16
+ userId: string;
17
+ sessionId: string;
18
+ /** Display-only title; never used as the identity. */
19
+ title: string;
20
+ createdAt: string;
21
+ updatedAt: string;
22
+ }
23
+ /** The live-agent facts this module needs. Structural on purpose. */
24
+ export interface GuardianAgentRef {
25
+ readonly id: string;
26
+ /** `running` means a further followup is queued behind the current turn. */
27
+ readonly status?: 'idle' | 'running';
28
+ }
29
+ /** Result of one text delivery. */
30
+ export interface GuardianDelivery {
31
+ delivered?: boolean;
32
+ queued?: boolean;
33
+ }
34
+ /** Inputs for a standard-mode session creation. */
35
+ export interface CreateGuardianAgentInput {
36
+ sessionId: string;
37
+ /** Absolute working directory required by the DSH session boundary. */
38
+ cwd: string;
39
+ title: string;
40
+ }
41
+ /** Host seam implemented by the plugin wiring against the real DSH services. */
42
+ export interface GuardianSessionHost {
43
+ /** `<actualRoot>/.memory/users` or the configured `memoryUsersRoot`. */
44
+ usersRoot: string;
45
+ /** Absolute session cwd; defaults to the host process cwd. */
46
+ cwd?: string;
47
+ /** `ctx.agents.get(sessionId)`. */
48
+ getAgent(sessionId: string): GuardianAgentRef | undefined;
49
+ /** `ctx.agentLoop.createAgent(ctx, { sessionId, meta: { cwd } })` with NO agentPreset. */
50
+ createAgent(input: CreateGuardianAgentInput): Promise<GuardianAgentRef>;
51
+ /** `ctx.agentLoop.resume(ctx, { resumeSessionId })`. */
52
+ resumeAgent(input: {
53
+ sessionId: string;
54
+ cwd: string;
55
+ }): Promise<GuardianAgentRef>;
56
+ /** Build a user message and call `agent.followup(...)`; report whether it queued. */
57
+ deliverText(agent: GuardianAgentRef, text: string): Promise<GuardianDelivery> | GuardianDelivery;
58
+ /**
59
+ * Optional title lookup used only when guardian.json is lost. The design says:
60
+ * find a unique title match before creating another guardian.
61
+ */
62
+ findByTitle?(title: string): Promise<string | undefined>;
63
+ /** Test seam: deterministic session id. Defaults to `session-<uuid>`. */
64
+ newSessionId?(): string;
65
+ /** Optional explicit rename; implementation may append `session/title`. */
66
+ setTitle?(agent: GuardianAgentRef, title: string): Promise<void> | void;
67
+ }
68
+ /** A resolved (possibly just-created) guardian. */
69
+ export interface ResolvedGuardian {
70
+ state: GuardianSessionState;
71
+ agent: GuardianAgentRef;
72
+ created: boolean;
73
+ }
74
+ /** Outcome of {@link sendToGuardian}. */
75
+ export interface GuardianSendResult {
76
+ /** The host accepted the message (`followup` returned without throwing). */
77
+ delivered: boolean;
78
+ /** The agent was busy, so the message sits in the DSH inbox behind the turn. */
79
+ queued: boolean;
80
+ /** Guardian session id the message went to. */
81
+ sessionId: string;
82
+ /** True when this call lazily created or recreated the session. */
83
+ created: boolean;
84
+ }
85
+ /** Title is display-only but stable, so an operator can recognize the session. */
86
+ export declare const GUARDIAN_SESSION_TITLE = "\u8BB0\u5FC6\u5B88\u62A4\u4F1A\u8BDD";
87
+ /** Skill the guardian must load before doing anything else. */
88
+ export declare const GUARDIAN_SKILL_NAME = "memory-guardian";
89
+ /**
90
+ * The preset first message. It intentionally stays product-level: read the
91
+ * skill, check memory state, ensure the daily dream task exists.
92
+ */
93
+ export declare function guardianSeedText(): string;
94
+ /** Render one trigger message for the guardian. */
95
+ export declare function renderGuardianMessage(message: GuardianMessage): string;
96
+ /**
97
+ * Durable guardian state under `<memoryUsersRoot>/<userId>/guardian.json`.
98
+ *
99
+ * Reads tolerate a corrupt file as "state lost": the resolver then uses the
100
+ * title fallback or creates a fresh session instead of failing every message.
101
+ * Writes are atomic (tmp + rename) and private.
102
+ */
103
+ export declare class GuardianSessionStore {
104
+ private readonly usersRoot;
105
+ /** Positive identity cache for trigger filtering; never used as the source of truth. */
106
+ private readonly knownSessions;
107
+ constructor(usersRoot: string);
108
+ /** Absolute path of one user's guardian state file. */
109
+ filePath(userId: string): string;
110
+ /** Read the state file; missing or malformed state is `undefined`. */
111
+ read(userId: string): Promise<GuardianSessionState | undefined>;
112
+ /** Create or replace the state file atomically. */
113
+ write(state: GuardianSessionState): Promise<void>;
114
+ /** Remove one user's guardian identity. Idempotent. */
115
+ remove(userId: string): Promise<void>;
116
+ /**
117
+ * Whether a session id belongs to any user's guardian. Negative answers are
118
+ * not cached because a session can become a guardian later; positive answers
119
+ * are, so the common turn-event path stays cheap.
120
+ */
121
+ isGuardianSession(sessionId: string): Promise<boolean>;
122
+ }
123
+ /**
124
+ * Resolve the user's guardian, creating it lazily when needed.
125
+ *
126
+ * Existing live agent → reuse. Persisted agent → resume. Resume failure or a
127
+ * missing state file → create one standard-mode session, write the identity
128
+ * first (so a failed seed cannot orphan it), then deliver the seed message.
129
+ */
130
+ export declare function resolveOrCreateGuardian(host: GuardianSessionHost, userId: string): Promise<ResolvedGuardian>;
131
+ /**
132
+ * Deliver one trigger message to the user's guardian, reusing the resolved
133
+ * session. This is the ONLY send path used by the tool and the triggers.
134
+ */
135
+ export declare function sendToGuardian(host: GuardianSessionHost, userId: string, message: GuardianMessage): Promise<GuardianSendResult>;
@@ -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. */
@@ -841,21 +848,42 @@ export declare function createKnowledgeEntry(config: Config, relPath: string, op
841
848
  */
842
849
  export declare function actualRelPathForView(ctx: Context, config: Config, relPath: string, caller?: KnowledgeCaller): Promise<string>;
843
850
  /**
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.
851
+ * The canonical VIEW path a model-facing file-tool path names.
852
+ *
853
+ * The `kb_file_*` tools speak view coordinates (`global/…`, `department/…`,
854
+ * `personal/…` or a bare path). A bare path has no bucket, and the old code left
855
+ * it untouched: `createKnowledgeEntry` then wrote it at the authoritative top
856
+ * level, which the view renders as `global/…` because {@link bucketOf} treats an
857
+ * unknown head as global. That is how a personal memory write silently became a
858
+ * global document.
859
+ *
860
+ * On a team deployment a bare path belongs to the caller's PERSONAL bucket — the
861
+ * only bucket one caller owns — so it is spelled `personal/<path>`. Explicit
862
+ * scope spellings, including the localized aliases, are already canonical after
863
+ * {@link resolveScopeAlias} and are returned unchanged. A local deployment keeps
864
+ * the legacy flat tree, where there are no buckets, so nothing is prefixed.
865
+ *
866
+ * @param relPath - model-supplied path, already validated/alias-resolved or not.
867
+ * @param team - `isTeamDeployment(config)`; false keeps the flat local layout.
858
868
  */
869
+ export declare function toolScopedViewPath(relPath: string, team: boolean): string;
870
+ /**
871
+ * The AUTHORITATIVE path a model-facing file-tool path names.
872
+ *
873
+ * A view drops the personal owner segment (`personal/note.md`), but the actual
874
+ * tree keeps it (`personal/<uid>/note.md`). Writes, overwrites and existence
875
+ * checks must use this form; reads/listings stay in view coordinates and use the
876
+ * view root. Global and department paths are unchanged: their view and actual
877
+ * spellings are already identical (or handled by their own layout rules).
878
+ *
879
+ * A path that already carries the caller's own id is returned untouched, so the
880
+ * resolver is idempotent and graph tools (which pass actual paths) are safe.
881
+ *
882
+ * @param relPath - model-supplied path (view or already-actual).
883
+ * @param userId - the caller whose personal tree owns a bare/personal path.
884
+ * @param team - `isTeamDeployment(config)`; false keeps the flat local layout.
885
+ */
886
+ export declare function toolScopedActualPath(relPath: string, userId: string, team: boolean): string;
859
887
  export declare function knowledgeGraphScopeRoots(host: Context, config: Config, caller: KnowledgeCaller): Promise<KnowledgeGraphScopeRoot[]>;
860
888
  export declare function extractBeside(config: Config, relPath: string, mineruUrl?: string, readSharedUrl?: () => Promise<string | undefined>, ctx?: Context): Promise<{
861
889
  markdown: string;
@@ -1106,6 +1134,18 @@ export declare function kbSummarizeSkillPath(): string;
1106
1134
  export declare function kbVectorizeSkillPath(): string;
1107
1135
  /** Where the bundled `knowledge-graph` skill lives. */
1108
1136
  export declare function knowledgeGraphSkillPath(): string;
1137
+ /** The guardian's own operating skill. */
1138
+ export declare const MEMORY_GUARDIAN_SKILL_NAME = "memory-guardian";
1139
+ /** The extraction subagent's skill. */
1140
+ export declare const MEMORY_EXTRACT_SKILL_NAME = "memory-extract";
1141
+ /** The SOP evaluation subagent's skill. */
1142
+ export declare const MEMORY_SOP_EVALUATE_SKILL_NAME = "memory-sop-evaluate";
1143
+ /** Where the bundled `memory-guardian` skill lives. */
1144
+ export declare function memoryGuardianSkillPath(): string;
1145
+ /** Where the bundled `memory-extract` skill lives. */
1146
+ export declare function memoryExtractSkillPath(): string;
1147
+ /** Where the bundled `memory-sop-evaluate` skill lives. */
1148
+ export declare function memorySopEvaluateSkillPath(): string;
1109
1149
  /**
1110
1150
  * Where this package's tutorial document lives, from either build layout.
1111
1151
  *
@@ -1200,3 +1240,37 @@ export declare function knowledgeBaseToolDisclosure(host: object): ToolDisclosur
1200
1240
  export declare function apply(ctx: Context, deploymentConfig: Config): void;
1201
1241
  /** Re-exported for tests and for callers that need the host shape. */
1202
1242
  export type { RemoteHost, RemoteRunner };
1243
+ export { GraphLoadError, listGraphs, loadGraph, parseNodeFrontMatter, validateGraph, } from './graphModel.ts';
1244
+ export type { GraphManifest, GraphManifestEdge, GraphManifestNode, GraphValidationIssue, LoadedGraph, LoadedGraphEdge, LoadedGraphNode, MemoryAuthority, MemoryNodeType, MemoryOrigin, MemoryReviewStatus, } from './graphModel.ts';
1245
+ export { canManageGraph, canViewGraph, filterVisibleGraphs, } from './graphPolicy.ts';
1246
+ export type { GraphScopeDescriptor, GraphViewer } from './graphPolicy.ts';
1247
+ export { BindingStore, bindingKey, } from './memoryBindings.ts';
1248
+ export type { BindingLineage, BindingMode, BindingSourceType, BindingStatus, PersonalBinding, } from './memoryBindings.ts';
1249
+ export { markUpstreamUpdates, runGuardianPass } from './memoryGuardian.ts';
1250
+ export { decideMemoryAction, runtimeInjectionTags } from './memoryPolicy.ts';
1251
+ export { diffSnapshots, parentChain, refreshDirtySummaries, scanKnowledgeTree, } from './summaryIndex.ts';
1252
+ export type { ChangeSet, ChangeSnapshot } from './summaryIndex.ts';
1253
+ export { applyMigration, planMigration, renderMigrationReport, } from './graphMigration.ts';
1254
+ export type { MigrationOptions, MigrationReport } from './graphMigration.ts';
1255
+ export { applySummaryWriteback, summarySnapshotPathFor } from './summaryWriteback.ts';
1256
+ export type { SummaryWritebackOptions, SummaryWritebackResult } from './summaryWriteback.ts';
1257
+ export { resolveMemoryContext, renderMemoryContextMarkdown } from './memoryContext.ts';
1258
+ export type { MemoryContextResult } from './memoryContext.ts';
1259
+ export { createMemoryTools } from './memoryTools.ts';
1260
+ export type { MemoryContextToolResult, MemoryGuardianToolResult, MemoryToolHost } from './memoryTools.ts';
1261
+ export { MemoryStore, MemoryStoreError, MEMORY_LOG_DIR, MEMORY_SOP_DIR, MEMORY_PREFERENCE_FILE, MEMORY_PITFALL_FILE, MEMORY_FACT_FILE, } from './memoryStore.ts';
1262
+ export type { MemoryStoreOptions, MemoryIndex, MemoryLogSummary, AppendLogOptions, AppendLogResult, PreferenceUpsertResult, PitfallUpsertResult, FactUpsertResult, SopWriteResult, SopUpdateResult, SopPatch, } from './memoryStore.ts';
1263
+ export { MemoryGraphWriter, MemoryGraphWriterError, syncPersonalMemoryGraph, PERSONAL_MEMORY_FOLDER, PERSONAL_MEMORY_GRAPH_ID, } from './memoryGraphWriter.ts';
1264
+ export type { MemoryGraphWriterOptions, PersonalMemoryGraphResult } from './memoryGraphWriter.ts';
1265
+ 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';
1266
+ export type { MemoryType, Privacy, FactKind, AppId, SopStatus, MemoryEntry, Preference, Pitfall, Episodic, Fact, Sop, AnyMemoryEntry, MemoryEntryInput, MemoryValidationIssue, MemoryValidationError, } from './memoryTypes.ts';
1267
+ export { GuardianSessionStore, resolveOrCreateGuardian, sendToGuardian, GUARDIAN_SESSION_TITLE, GUARDIAN_SKILL_NAME, } from './guardianSession.ts';
1268
+ export type { GuardianReason, GuardianMessage, GuardianSessionState, GuardianAgentRef, GuardianDelivery, CreateGuardianAgentInput, GuardianSessionHost, ResolvedGuardian, GuardianSendResult, } from './guardianSession.ts';
1269
+ export { createMemoryGuardianTools } from './memoryGuardianTool.ts';
1270
+ export type { MemoryGuardianToolHost, MemoryGuardianSendArgs, MemoryGuardianSendValue } from './memoryGuardianTool.ts';
1271
+ export { installMemoryTriggers, IDLE_DEBOUNCE_MS } from './memoryTriggers.ts';
1272
+ export type { MemoryTriggerHost, MemoryTriggerSession, MemoryTriggerEvent, MemoryTriggerTimers } from './memoryTriggers.ts';
1273
+ export { createMemoryRecordTools } from './memoryRecordTool.ts';
1274
+ export type { MemoryRecordToolHost } from './memoryRecordTool.ts';
1275
+ export { promoteSopToSkill, deleteSopAfterPromotion } from './memorySkillPromotion.ts';
1276
+ 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. */
@@ -229,8 +238,15 @@ export declare const asKnowledgeToolError: (error: unknown, path?: string) => Kn
229
238
  *
230
239
  * Empty is allowed only where the root itself is the argument (list/search/extract-all);
231
240
  * everything else is refused with the same four codes `checkLocalPath` uses.
241
+ *
242
+ * `defaultScope` decides what a path with NO bucket prefix means. When omitted
243
+ * the legacy behaviour is kept (a bare top-level path). A team deployment passes
244
+ * `personal`, so `个人记忆图谱/…` without a bucket resolves inside the caller's
245
+ * own tree instead of becoming an unowned top-level path that the view shows as
246
+ * `global`. Explicit `global/`, `department/` and `personal/` spellings (and
247
+ * their localized aliases) are never rewritten.
232
248
  */
233
- export declare const assertToolPath: (value: unknown, allowRoot?: boolean) => string;
249
+ export declare const assertToolPath: (value: unknown, allowRoot?: boolean, defaultScope?: CanonicalScope) => string;
234
250
  /**
235
251
  * Build the knowledge-base model-facing tools.
236
252
  *
@@ -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>;