@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,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>;
@@ -0,0 +1,123 @@
1
+ /** Node/edge authority, mirroring `graphModel.ts`. */
2
+ export type MemoryAuthority = 'canonical' | 'advisory' | 'redline';
3
+ /** Where the content came from. */
4
+ export type MemoryOrigin = 'human' | 'ai' | 'mixed';
5
+ /** Human review state. */
6
+ export type MemoryReviewStatus = 'draft' | 'reviewed' | 'approved';
7
+ /** A node as the guardian needs to see it. Attributes are optional; the loader defaults them. */
8
+ export interface GuardianSourceNode {
9
+ id: string;
10
+ path: string;
11
+ type?: string;
12
+ title?: string;
13
+ authority?: MemoryAuthority;
14
+ internalizable?: boolean;
15
+ origin?: MemoryOrigin;
16
+ reviewStatus?: MemoryReviewStatus;
17
+ tags?: string[];
18
+ sourceRefs?: string[];
19
+ missing?: boolean;
20
+ }
21
+ /** A relation. `docPath` points at the optional relation document in `.graphs/<id>/links/`. */
22
+ export interface GuardianSourceEdge {
23
+ id: string;
24
+ from: string;
25
+ to: string;
26
+ docPath?: string;
27
+ type?: string;
28
+ title?: string;
29
+ authority?: MemoryAuthority;
30
+ internalizable?: boolean;
31
+ origin?: MemoryOrigin;
32
+ reviewStatus?: MemoryReviewStatus;
33
+ tags?: string[];
34
+ sourceRefs?: string[];
35
+ missing?: boolean;
36
+ }
37
+ /** The manifest fields the guardian reads. Extra manifest fields are ignored. */
38
+ export interface GuardianGraphManifest {
39
+ schemaVersion?: number;
40
+ id: string;
41
+ name?: string;
42
+ description?: string;
43
+ scope?: string;
44
+ version: number;
45
+ status?: string;
46
+ owner?: string;
47
+ createdAt?: string;
48
+ updatedAt?: string;
49
+ publishedAt?: string;
50
+ tags?: string[];
51
+ visibility?: string;
52
+ commit?: string;
53
+ sourceCommit?: string;
54
+ }
55
+ /** Structural stand-in for `LoadedGraph`. */
56
+ export interface GuardianGraph {
57
+ manifest: GuardianGraphManifest;
58
+ root: string;
59
+ nodes: GuardianSourceNode[];
60
+ edges: GuardianSourceEdge[];
61
+ /** Published git commit for this graph version, when the caller has one. */
62
+ commit?: string;
63
+ }
64
+ /** Input for one guardian pass. */
65
+ export interface GuardianPassInput {
66
+ graph: GuardianGraph;
67
+ usersRoot: string;
68
+ userIds: string[];
69
+ /**
70
+ * When provided, a `department:<code>` graph is only processed for that
71
+ * department. `global` graphs and graphs without a department scope are
72
+ * always eligible. The caller resolves the user's department.
73
+ */
74
+ departmentCode?: string;
75
+ /** Injectable clock for deterministic tests. Defaults to `new Date().toISOString()`. */
76
+ now?: string;
77
+ }
78
+ /** Input for a pure upstream-version pass. */
79
+ export interface MarkUpstreamUpdatesInput {
80
+ graph: GuardianGraph;
81
+ usersRoot: string;
82
+ userIds: string[];
83
+ /** Injectable clock used for `updatedAt` in tests. */
84
+ now?: string;
85
+ }
86
+ /** Counters returned by a guardian pass. */
87
+ export interface GuardianResult {
88
+ /** Bindings created as `pending` during discovery (resolved in the same pass). */
89
+ createdPending: number;
90
+ /** Bindings that ended up as a live `subscribe` proxy. */
91
+ subscribed: number;
92
+ /** Bindings that copied a body into the personal memory tree. */
93
+ internalized: number;
94
+ /** Internalize requests refused because of redline / `internalizable: false`. */
95
+ rejectedRedline: number;
96
+ /** Bindings whose `sourceVersion` was refreshed (subscribe, pending, stale). */
97
+ upstreamUpdates: number;
98
+ /** Previously internalized branches revoked after a redline upgrade. */
99
+ revoked: number;
100
+ }
101
+ /**
102
+ * Run one guardian pass: refresh versions, discover new sources for every
103
+ * user, resolve pending bindings (nodes before edges so a relation can be
104
+ * internalized in the same pass as its endpoints), and revoke branches whose
105
+ * source became redline or non-internalizable.
106
+ */
107
+ export declare function runGuardianPass(input: GuardianPassInput): Promise<GuardianResult>;
108
+ /**
109
+ * Advance `sourceVersion` / `sourceCommit` for every binding of this graph.
110
+ *
111
+ * - `subscribe` and `pending` stay active and immediately follow the graph;
112
+ * - `internalize` becomes `stale`, keeps its local body untouched, and will not
113
+ * follow the source again until the user explicitly re-forks;
114
+ * - `revoked` bindings are left alone.
115
+ *
116
+ * Returns the number of bindings that moved to a newer version.
117
+ */
118
+ export declare function markUpstreamUpdates(input: MarkUpstreamUpdatesInput): Promise<number>;
119
+ /** Split a Markdown document into its frontmatter block and body. */
120
+ export declare function splitFrontMatter(source: string): {
121
+ frontMatter: string | null;
122
+ body: string;
123
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Model-facing `memory_guardian_send` tool.
3
+ *
4
+ * Any authenticated caller may notify their own guardian — the tool is a
5
+ * read-group surface (`kb:file:read`) because it never writes knowledge or
6
+ * another user's state. It is deliberately NOT a target-session API: the tool
7
+ * accepts only a reason, the optional source session/compaction context and a
8
+ * note, then resolves the caller's own guardian through guardian.json. There is
9
+ * no `userId` argument and no arbitrary `target` argument, so a model cannot
10
+ * address another person's guardian.
11
+ *
12
+ * Delivery uses {@link sendToGuardian}, the same path the idle/compaction
13
+ * triggers use. A busy guardian queues the message in DSH's own inbox; this
14
+ * tool adds no queue of its own and returns `queued: true` so the caller knows
15
+ * the guardian will process it after the current turn.
16
+ *
17
+ * @module @sparkelf/dsh-knowledge-base/memory-guardian-tool
18
+ */
19
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
20
+ import { type GuardianReason, type GuardianSessionHost } from './guardianSession.ts';
21
+ /** The Host seam the tool needs. */
22
+ export interface MemoryGuardianToolHost {
23
+ /** The authenticated caller. Only `userId` is used to find the guardian. */
24
+ resolveCaller(): Promise<{
25
+ userId: string;
26
+ }>;
27
+ /** The guardian session seam shared with the triggers. */
28
+ guardian: GuardianSessionHost;
29
+ /** Whether learning is enabled for this user; paused rejects notify/remember. */
30
+ isEnabled?(userId: string): Promise<boolean> | boolean;
31
+ }
32
+ /** Arguments accepted by `memory_guardian_send`. */
33
+ export interface MemoryGuardianSendArgs {
34
+ reason?: string;
35
+ sessionId?: string;
36
+ note?: string;
37
+ }
38
+ /** Result returned to the model. */
39
+ export interface MemoryGuardianSendValue {
40
+ ok: true;
41
+ reason: GuardianReason;
42
+ delivered: boolean;
43
+ queued: boolean;
44
+ /** The caller's guardian session that received the message. */
45
+ sessionId: string;
46
+ /** True when this call lazily created or recreated the guardian. */
47
+ created: boolean;
48
+ rendered: string;
49
+ }
50
+ /**
51
+ * Build the `memory_guardian_send` tool.
52
+ *
53
+ * @param host - caller resolver and the guardian session seam.
54
+ * @returns Tool definitions for the disclosure coordinator.
55
+ */
56
+ export declare function createMemoryGuardianTools(host: MemoryGuardianToolHost): ToolDefinition[];
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Memory policy: the redline and AI-provenance decisions the Host must enforce.
3
+ *
4
+ * This module is deliberately a pure function set. It never reads configuration,
5
+ * the filesystem or the caller's session; the authenticated viewer and the loaded
6
+ * node/edge are explicit arguments. That is what lets the Host call the same rule
7
+ * from the graph loader, the guardian pass and a future write route without the
8
+ * browser becoming the only guard.
9
+ *
10
+ * The policy mirrors design §6–7:
11
+ *
12
+ * - `authority: redline` and `internalizable: false` both block internalization,
13
+ * for a node and for an edge; a relation inherits the stricter policy of its two
14
+ * endpoints (`relation 任一端 redline → reject`);
15
+ * - a redline is still readable and subscribable — it is a policy that cannot be
16
+ * overridden, not a hidden node;
17
+ * - AI-generated content may be published, but only with an explicit `origin`;
18
+ * - publishing and `setAuthority` are restricted to an admin or the owner, and a
19
+ * personal edit never overrides a department/global redline.
20
+ *
21
+ * T1's `graphModel.ts` and `graphPolicy.ts` own the canonical attribute and
22
+ * viewer types; this module imports them type-only, so the policy cannot drift
23
+ * from what the loader actually produces.
24
+ *
25
+ * @module @sparkelf/dsh-knowledge-base/memory-policy
26
+ */
27
+ import type { LoadedGraphEdge, LoadedGraphNode, MemoryAuthority, MemoryOrigin, MemoryReviewStatus } from './graphModel.ts';
28
+ import type { GraphViewer } from './graphPolicy.ts';
29
+ export type { GraphViewer, MemoryAuthority, MemoryOrigin, MemoryReviewStatus };
30
+ /** The actions a caller can ask the policy about. */
31
+ export type MemoryAction = 'view' | 'subscribe' | 'internalize' | 'edit' | 'publish' | 'setAuthority';
32
+ /** The node fields the policy reads. Provenance stays optional so a legacy node
33
+ * that predates the field reaches the publish guard instead of being typed away. */
34
+ export type PolicyNode = Pick<LoadedGraphNode, 'id' | 'authority' | 'internalizable'> & Partial<Pick<LoadedGraphNode, 'origin' | 'reviewStatus'>>;
35
+ /** The edge fields the policy reads. */
36
+ export type PolicyEdge = Pick<LoadedGraphEdge, 'id' | 'authority' | 'internalizable'>;
37
+ /** One endpoint of a relation. */
38
+ export type PolicyEndpoint = Pick<LoadedGraphNode, 'authority' | 'internalizable'>;
39
+ /** The answer a Host route or guardian pass acts on. */
40
+ export interface PolicyDecision {
41
+ allowed: boolean;
42
+ /**
43
+ * Stable reason code when denied:
44
+ * `redline`, `not-internalizable`, `missing-subject`, `ambiguous-subject`,
45
+ * `missing-origin`, `admin-or-owner-required`, `owner-required`,
46
+ * `unsupported-action`.
47
+ */
48
+ reason?: string;
49
+ /** True when the subject is a redline whose policy cannot be overridden. */
50
+ nonOverridable?: boolean;
51
+ }
52
+ /** The decision input, matching the module contract. */
53
+ export interface DecideMemoryActionInput {
54
+ action: MemoryAction;
55
+ node?: PolicyNode;
56
+ edge?: PolicyEdge;
57
+ /**
58
+ * Both endpoints of `edge`, when the caller has them.
59
+ *
60
+ * A relation inherits the stricter endpoint policy, so callers that pass this
61
+ * get the design rule enforced directly. Callers that only have a projected
62
+ * edge (the loader already folded the endpoints into `edge.authority` /
63
+ * `edge.internalizable`) may omit it.
64
+ */
65
+ edgeEndpoints?: readonly PolicyEndpoint[];
66
+ viewer?: GraphViewer;
67
+ /** Whether the subject is the caller's own personal memory. */
68
+ isOwner?: boolean;
69
+ }
70
+ /** The tags a runtime injection carries for one node. */
71
+ export interface RuntimeInjectionTags {
72
+ authorityTag: string;
73
+ originTag: string;
74
+ nonOverridable: boolean;
75
+ }
76
+ /**
77
+ * The node shape {@link runtimeInjectionTags} reads.
78
+ *
79
+ * A full `LoadedGraphNode` is assignable. The optional members let a legacy node
80
+ * that predates the provenance field still be injected with the human fallback.
81
+ */
82
+ export type RuntimeInjectionNode = Pick<LoadedGraphNode, 'authority'> & Partial<Pick<LoadedGraphNode, 'origin' | 'internalizable'>>;
83
+ /**
84
+ * Decide one memory action against the subject's redline/provenance policy.
85
+ *
86
+ * The function is intentionally strict about missing context: an action that needs
87
+ * a subject denies instead of guessing, and publish/setAuthority need an explicit
88
+ * admin or owner. `view` and `subscribe` do not require a viewer here because the
89
+ * Host has already resolved graph visibility before calling; a redline remains
90
+ * viewable and subscribable, and only the runtime injection marks it
91
+ * non-overridable.
92
+ *
93
+ * @param input - action, subject, optional edge endpoints, viewer and ownership.
94
+ * @returns The decision, with a stable reason code when denied.
95
+ */
96
+ export declare function decideMemoryAction(input: DecideMemoryActionInput): PolicyDecision;
97
+ /**
98
+ * The tags a runtime injection carries for a node.
99
+ *
100
+ * A redline is marked `nonOverridable` so the runtime reads it from the
101
+ * authoritative source and ranks it above personal memory and preferences.
102
+ *
103
+ * @param node - the loaded node being injected.
104
+ * @returns Authority/origin labels and the non-overridable flag.
105
+ */
106
+ export declare function runtimeInjectionTags(node: RuntimeInjectionNode): RuntimeInjectionTags;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Guardian-only tools that write the five memory types and promote a SOP.
3
+ *
4
+ * The guardian session is the single writer of personal memory. Ordinary
5
+ * sessions may read memory through `memory_context` and notify the guardian
6
+ * through `memory_guardian_send`, but they must not call these tools; the
7
+ * execute bodies check the live session against the guardian state before
8
+ * touching a file.
9
+ *
10
+ * The tools stay close to the product vocabulary: the model supplies a type and
11
+ * the type's fields, and the store applies merging, privacy and validation.
12
+ *
13
+ * @module @sparkelf/dsh-knowledge-base/memory-record-tool
14
+ */
15
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
16
+ import { MemoryStore, type MemoryIndex } from './memoryStore.ts';
17
+ import type { MemoryGraphWriter } from './memoryGraphWriter.ts';
18
+ /** The Host seam for the guardian write tools. */
19
+ export interface MemoryRecordToolHost {
20
+ /** Authenticated caller plus the live session that is calling the tool. */
21
+ resolveCaller(): Promise<{
22
+ userId: string;
23
+ sessionId?: string;
24
+ }>;
25
+ /** Whether this session is the user's guardian session (state-file lookup). */
26
+ isGuardianSession(sessionId: string | undefined): Promise<boolean>;
27
+ /** The store for one user's personal memory. */
28
+ storeFor(userId: string): Promise<MemoryStore>;
29
+ /** The graph writer for the same user's personal-memory graph. */
30
+ graphWriterFor(userId: string): MemoryGraphWriter;
31
+ /** Root that holds one directory per DSH skill. */
32
+ skillsRootFor(userId: string): Promise<string>;
33
+ /** Whether personal memory is enabled; paused refuses writes. */
34
+ isEnabled?(userId: string): Promise<boolean> | boolean;
35
+ }
36
+ /** Build the two guardian write tools. */
37
+ export declare function createMemoryRecordTools(host: MemoryRecordToolHost): ToolDefinition[];
38
+ /** The current memory index, useful to the guardian before deciding a merge. */
39
+ export declare function readMemoryIndexFor(store: MemoryStore): Promise<MemoryIndex>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * HTTP seam for the memory management page (design §22).
3
+ *
4
+ * This module owns no routing and no identity: `index.ts` resolves the caller and
5
+ * builds the per-user stores, then hands this function the method name, the parsed
6
+ * JSON body and the three collaborators. It returns `{status, body}` so the route
7
+ * switch only has to call `writeJson`. That split is what lets the payload contract
8
+ * be tested without a live backend or an HTTP server.
9
+ *
10
+ * Scope rules:
11
+ * - every method acts ONLY on the caller's own personal memory
12
+ * (`<actualRoot>/personal/<userId>/个人记忆图谱`); a `userId` in the body is
13
+ * refused, never trusted;
14
+ * - the memory menu is a product surface over `MemoryStore`, so it uses the same
15
+ * validation, tombstone and privacy rules as the guardian;
16
+ * - list rows NEVER expose the raw session id. `memory.get` includes it under
17
+ * `source.sessionId` only because the detail drawer needs it for 「查看原文」.
18
+ *
19
+ * Methods: `memory.list`, `memory.get`, `memory.update`, `memory.forget`,
20
+ * `memory.settings`, `memory.set-enabled`.
21
+ *
22
+ * @module @sparkelf/dsh-knowledge-base/memory-routes
23
+ */
24
+ import type { MemoryGraphWriter } from './memoryGraphWriter.ts';
25
+ import { MemoryStore, type ListedMemoryEntry } from './memoryStore.ts';
26
+ import { MemorySettingsStore } from './memorySettings.ts';
27
+ import { type MemoryType, type Privacy } from './memoryTypes.ts';
28
+ /** The identity the route already resolved from the request. */
29
+ export interface MemoryRouteCaller {
30
+ userId: string;
31
+ label?: string;
32
+ }
33
+ /** Collaborators the route builds for the caller; injected so tests need no Context. */
34
+ export interface MemoryRouteInput {
35
+ method: string;
36
+ /** Parsed JSON body; methods without a body may omit it. */
37
+ body?: unknown;
38
+ caller: MemoryRouteCaller;
39
+ store: MemoryStore;
40
+ settings: MemorySettingsStore;
41
+ /** Manifest reconciliation after a write/delete; failure never undoes the memory write. */
42
+ graphWriter: Pick<MemoryGraphWriter, 'syncAll'>;
43
+ }
44
+ /** One response the route switch can pass straight to `writeJson`. */
45
+ export interface MemoryRouteResponse {
46
+ status: number;
47
+ body: Record<string, unknown>;
48
+ }
49
+ /** One row of the memory table. Deliberately no session id. */
50
+ export interface MemoryListRow {
51
+ id: string;
52
+ type: MemoryType;
53
+ /** Short human line (the detail drawer carries the full value). */
54
+ title: string;
55
+ /** Display-only source snapshot: session title, then scenario, then app. */
56
+ sourceLabel: string;
57
+ /** When the remembered thing happened; falls back to `createdAt`. */
58
+ sourceTime: string;
59
+ privacy: Privacy;
60
+ updatedAt: string;
61
+ /** Document path relative to the memory root (`偏好.md`, `SOP/<slug>.md`, ...). */
62
+ path: string;
63
+ }
64
+ /** Normalized entry + source shape returned by get/update. */
65
+ export interface MemoryEntryPayload {
66
+ entry: ListedMemoryEntry;
67
+ title: string;
68
+ content: string;
69
+ source: {
70
+ label: string;
71
+ at: string;
72
+ eventSeqs?: number[];
73
+ /** Internal locator for 「查看原文」; never rendered as text. */
74
+ sessionId?: string;
75
+ };
76
+ }
77
+ /**
78
+ * Handle one memory-management method.
79
+ *
80
+ * The caller's identity is already resolved by the route; this function validates
81
+ * it once more before touching the filesystem and never accepts a body-supplied
82
+ * user id. Expected failures return a status/body; unexpected failures throw so the
83
+ * route's outer `try` reports a real 500 instead of a misleading 400.
84
+ */
85
+ export declare function handleMemoryRoute(input: MemoryRouteInput): Promise<MemoryRouteResponse>;
@@ -0,0 +1,40 @@
1
+ /** File name inside one user's directory. */
2
+ export declare const MEMORY_SETTINGS_FILE = "settings.json";
3
+ /** Persisted settings shape. */
4
+ export interface MemorySettings {
5
+ version: 1;
6
+ /** `false` means paused: no new memories are learned. */
7
+ memoryEnabled: boolean;
8
+ }
9
+ /** The paused default for a user who has never confirmed the enable dialog. */
10
+ export declare const DEFAULT_MEMORY_SETTINGS: Readonly<MemorySettings>;
11
+ /**
12
+ * Atomic settings store over `<usersRoot>/<userId>/settings.json`.
13
+ *
14
+ * `read()` tolerates a corrupt file by returning the paused default; the next
15
+ * `setEnabled()` rewrites it. This keeps the memory page usable after a partial
16
+ * write or a hand-edited file instead of failing the whole route.
17
+ */
18
+ export declare class MemorySettingsStore {
19
+ private readonly usersRoot;
20
+ constructor(usersRoot: string);
21
+ /** Absolute settings file for one user. */
22
+ filePath(userId: string): string;
23
+ /**
24
+ * Read one user's settings.
25
+ *
26
+ * Missing, malformed, or schema-invalid content returns the paused default.
27
+ * A file with a boolean `memoryEnabled` is accepted even if `version` is
28
+ * missing, so an older/hand-written settings file does not silently turn
29
+ * memory on (the boolean still decides).
30
+ */
31
+ read(userId: string): Promise<MemorySettings>;
32
+ /** Whether learning is enabled for this user (default `false`). */
33
+ isEnabled(userId: string): Promise<boolean>;
34
+ /**
35
+ * Persist the enable/pause switch atomically.
36
+ *
37
+ * @returns the normalized settings actually written.
38
+ */
39
+ setEnabled(userId: string, enabled: boolean): Promise<MemorySettings>;
40
+ }
@@ -0,0 +1,62 @@
1
+ /** Machine-readable failure reasons for callers that branch on them. */
2
+ export type MemorySkillPromotionErrorCode = 'invalid-sop' | 'invalid-slug' | 'invalid-path' | 'invalid-time' | 'skill-missing';
3
+ /** A promotion failure the guardian session should report, not retry blindly. */
4
+ export declare class MemorySkillPromotionError extends Error {
5
+ readonly code: MemorySkillPromotionErrorCode;
6
+ constructor(code: MemorySkillPromotionErrorCode, message: string);
7
+ }
8
+ /** One evaluated SOP draft, as the guardian session holds it in memory. */
9
+ export interface SopDraft {
10
+ /** Stable SOP identity used for the audit trail and `sourceSop`. */
11
+ id: string;
12
+ /** Human title; also the body heading context when the caller includes one. */
13
+ title: string;
14
+ /** The SOP body: trigger, steps, tool choices and success criteria. */
15
+ body: string;
16
+ /** One-line skill description; defaults to the title. */
17
+ description?: string;
18
+ /** Explicit skill name. Required when the title has no ASCII words. */
19
+ slug?: string;
20
+ /** Initial version when creating; an update always increments the existing one. */
21
+ version?: number;
22
+ }
23
+ /** Input for {@link promoteSopToSkill}. */
24
+ export interface PromoteSopInput {
25
+ sop: SopDraft;
26
+ /** Directory that holds one sub-directory per skill. */
27
+ skillsRoot: string;
28
+ /** Audit timestamp; defaults to the current instant. */
29
+ now?: string | Date;
30
+ }
31
+ /** Input for {@link deleteSopAfterPromotion}. */
32
+ export interface DeleteSopInput {
33
+ /** Path of the SOP file the guardian is retiring. */
34
+ sopPath: string;
35
+ /** Absolute path returned by the successful {@link promoteSopToSkill} call. */
36
+ skillPath: string;
37
+ }
38
+ /**
39
+ * Derive a kebab-case skill name from a human title.
40
+ *
41
+ * Chinese-only titles produce an empty slug; the guardian must then pass an
42
+ * explicit English `slug` rather than getting a silent hash-based directory.
43
+ */
44
+ export declare function skillSlugFor(title: string): string;
45
+ /**
46
+ * Promote one SOP draft to a skill, creating or updating it in place.
47
+ *
48
+ * @param input - the SOP, the skills root, and the audit instant.
49
+ * @returns The absolute path of the written skill, for the audit trail.
50
+ */
51
+ export declare function promoteSopToSkill(input: PromoteSopInput): Promise<string>;
52
+ /**
53
+ * Remove the SOP file only after the promoted skill is verifiably on disk.
54
+ *
55
+ * A missing skill write is an error and leaves the SOP untouched, so the draft
56
+ * cannot be lost to a failed promotion. Deleting an already-absent SOP after a
57
+ * successful promotion is a no-op that returns false.
58
+ *
59
+ * @param input - the SOP path and the skill path that must exist.
60
+ * @returns Whether a SOP file was actually removed.
61
+ */
62
+ export declare function deleteSopAfterPromotion(input: DeleteSopInput): Promise<boolean>;