@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,297 @@
1
+ /**
2
+ * Personal memory layout: raw daily logs plus the aggregate snapshots the
3
+ * guardian maintains.
4
+ *
5
+ * ```text
6
+ * <root>/
7
+ * ├── 记忆日志/YYYY-MM-DD.md # raw extraction + audit, append-only
8
+ * ├── 偏好.md # current effective preferences, one per topic
9
+ * ├── 踩坑.md # current effective pitfalls, one per error signature
10
+ * ├── 事实.md # current effective facts, grouped by app · scope
11
+ * └── SOP/<slug>.md # one executable draft per file, versioned
12
+ * ```
13
+ *
14
+ * The daily log is the only append-only surface. `偏好.md` / `踩坑.md` /
15
+ * `事实.md` are CURRENT snapshots: an upsert replaces the old effective value
16
+ * and never leaves two entries for the same key, so "what is true now" has one
17
+ * home. Old values remain auditable in the daily log. A SOP has its own
18
+ * lifecycle and version; promoting it into a skill deletes the SOP file
19
+ * (the guardian owns that step).
20
+ *
21
+ * Every write is atomic (`tmp` + `rename`, shared with `memoryBindings.ts`) and
22
+ * runs the same entry validation as the model, including the "secret means a
23
+ * credentialRef, never a value" rule. Single-writer assumption: the guardian
24
+ * session is the only process writing one personal memory root.
25
+ *
26
+ * @module @sparkelf/dsh-knowledge-base/memory-store
27
+ */
28
+ import { type AnyMemoryEntry, type AppId, type Fact, type FactInput, type FactKind, type MemoryOrigin, type MemoryEntryInput, type MemoryValidationIssue, type Pitfall, type PitfallInput, type Preference, type PreferenceInput, type Privacy, type Sop, type SopInput, type SopStatus } from './memoryTypes.ts';
29
+ /** Directory holding one append-only document per day. */
30
+ export declare const MEMORY_LOG_DIR = "\u8BB0\u5FC6\u65E5\u5FD7";
31
+ /** Directory holding one SOP draft per file. */
32
+ export declare const MEMORY_SOP_DIR = "SOP";
33
+ /** Current effective preferences; one entry per app+topic. */
34
+ export declare const MEMORY_PREFERENCE_FILE = "\u504F\u597D.md";
35
+ /** Current effective pitfalls; one entry per error signature. */
36
+ export declare const MEMORY_PITFALL_FILE = "\u8E29\u5751.md";
37
+ /** Current effective facts; grouped by app and scope. */
38
+ export declare const MEMORY_FACT_FILE = "\u4E8B\u5B9E.md";
39
+ /** Append-only tombstone/audit document for user-forgotten entries. */
40
+ export declare const MEMORY_FORGET_FILE = "\u9057\u5FD8\u8BB0\u5F55.md";
41
+ /** Marker that starts one tombstone record. */
42
+ export declare const MEMORY_FORGET_MARKER = "<!-- memory:forget -->";
43
+ /** Store construction options; `now` is injectable for deterministic tests. */
44
+ export interface MemoryStoreOptions {
45
+ now?: () => Date;
46
+ }
47
+ /** Why a store operation failed before or during a write. */
48
+ export type MemoryStoreErrorCode = 'invalid-root' | 'unsafe-path' | 'invalid-log-date' | 'invalid-memory-file' | 'duplicate-id' | 'sop-exists' | 'sop-not-found' | 'sop-terminal' | 'invalid-status-transition' | 'not-found' | 'duplicate-key' | 'invalid-patch';
49
+ export declare class MemoryStoreError extends Error {
50
+ readonly code: MemoryStoreErrorCode;
51
+ constructor(code: MemoryStoreErrorCode, message: string);
52
+ }
53
+ export interface AppendLogOptions {
54
+ /** Override the document date (`YYYY-MM-DD`); otherwise `sourceTime` or the clock decides. */
55
+ date?: string;
56
+ }
57
+ export interface AppendLogResult {
58
+ id: string;
59
+ date: string;
60
+ path: string;
61
+ }
62
+ export interface PreferenceUpsertResult {
63
+ id: string;
64
+ path: string;
65
+ created: boolean;
66
+ superseded?: string;
67
+ }
68
+ export interface PitfallUpsertResult {
69
+ id: string;
70
+ path: string;
71
+ created: boolean;
72
+ merged: boolean;
73
+ }
74
+ export interface FactUpsertResult {
75
+ id: string;
76
+ path: string;
77
+ created: boolean;
78
+ superseded?: string;
79
+ /** True when a different statement replaced the same fact key without an explicit supersede. */
80
+ conflict: boolean;
81
+ }
82
+ export interface SopWriteResult {
83
+ sop: Sop;
84
+ path: string;
85
+ }
86
+ export interface SopUpdateResult {
87
+ sop: Sop;
88
+ path: string;
89
+ }
90
+ /** Fields `updateSop` may change; everything else is immutable per version. */
91
+ export interface SopPatch {
92
+ title?: string;
93
+ trigger?: string;
94
+ steps?: string[];
95
+ tools?: string[];
96
+ successCriteria?: string[];
97
+ evidence?: string[];
98
+ status?: SopStatus;
99
+ privacy?: Privacy;
100
+ tags?: string[];
101
+ app?: AppId;
102
+ scenario?: string;
103
+ sourceLabel?: string;
104
+ sourceSeqs?: number[];
105
+ origin?: MemoryOrigin;
106
+ /** Skill name/path written when the SOP is promoted. */
107
+ promotedTo?: string[];
108
+ }
109
+ /** One entry plus the document it was read from (relative to the memory root). */
110
+ export type ListedMemoryEntry = AnyMemoryEntry & {
111
+ path: string;
112
+ };
113
+ /** Result of forgetting one entry. */
114
+ export interface ForgetEntryResult {
115
+ id: string;
116
+ /** Whether the entry existed and was removed from its source document. */
117
+ removed: boolean;
118
+ /** Whether a tombstone/audit record was appended. */
119
+ tombstoned: boolean;
120
+ }
121
+ /**
122
+ * Correctable fields of one existing entry.
123
+ *
124
+ * `id`, `type`, `createdAt`, document path, SOP slug/version and lifecycle
125
+ * status are immutable here. Merge-key fields are accepted for a correction but
126
+ * must not collide with another current entry. Unknown keys are rejected so a
127
+ * route typo cannot silently do nothing.
128
+ */
129
+ export interface MemoryEntryPatch {
130
+ privacy?: Privacy;
131
+ app?: AppId;
132
+ scenario?: string;
133
+ taskType?: string;
134
+ entities?: string[];
135
+ sourceSession?: string;
136
+ sourceTime?: string;
137
+ sourceLabel?: string;
138
+ sourceSeqs?: number[];
139
+ origin?: MemoryOrigin;
140
+ tags?: string[];
141
+ evidence?: string[];
142
+ credentialRef?: string;
143
+ supersedes?: string;
144
+ body?: string;
145
+ topic?: string;
146
+ value?: string;
147
+ errorSignature?: string;
148
+ context?: string;
149
+ solution?: string;
150
+ appliesTo?: string[];
151
+ summary?: string;
152
+ request?: string;
153
+ outcome?: string;
154
+ sopUsed?: string[];
155
+ promotedTo?: string[];
156
+ factKind?: FactKind;
157
+ key?: string;
158
+ statement?: string;
159
+ scope?: string;
160
+ title?: string;
161
+ trigger?: string;
162
+ steps?: string[];
163
+ tools?: string[];
164
+ successCriteria?: string[];
165
+ }
166
+ /** One daily log file in the index. */
167
+ export interface MemoryLogSummary {
168
+ date: string;
169
+ path: string;
170
+ entries: number;
171
+ }
172
+ /** The current personal-memory snapshot, rebuilt from files on demand. */
173
+ export interface MemoryIndex {
174
+ root: string;
175
+ preferences: Preference[];
176
+ pitfalls: Pitfall[];
177
+ facts: Fact[];
178
+ sops: Sop[];
179
+ logs: MemoryLogSummary[];
180
+ /** Parse problems in existing files; writes refuse to overwrite a file with issues. */
181
+ issues: MemoryValidationIssue[];
182
+ }
183
+ /**
184
+ * One personal memory root. All methods are async and write atomically; the
185
+ * returned paths are `/`-separated and relative to the root.
186
+ */
187
+ export declare class MemoryStore {
188
+ private readonly root;
189
+ private readonly clock;
190
+ constructor(root: string, options?: MemoryStoreOptions);
191
+ /** Absolute root this store writes under. */
192
+ get memoryRoot(): string;
193
+ private now;
194
+ private absolute;
195
+ private readDocument;
196
+ /** A write must not silently repair or clobber a file that already has issues. */
197
+ private assertWritable;
198
+ private entriesOfType;
199
+ private materialize;
200
+ /**
201
+ * Append one raw entry to the day document `记忆日志/YYYY-MM-DD.md`.
202
+ *
203
+ * The date comes from `options.date`, else the `YYYY-MM-DD` prefix of
204
+ * `sourceTime`, else the store clock. The generated id is unique; an explicit
205
+ * duplicate id in the same day document is refused.
206
+ */
207
+ appendLog(input: MemoryEntryInput, options?: AppendLogOptions): Promise<AppendLogResult>;
208
+ /**
209
+ * Merge one preference by `app + topic`.
210
+ *
211
+ * - identical content is a no-op (no new id, no duplicate);
212
+ * - a changed value replaces the current entry with a new id that records
213
+ * `supersedes`; the old value stays only in the daily log;
214
+ * - same value with changed metadata updates the existing entry in place.
215
+ */
216
+ upsertPreference(input: PreferenceInput): Promise<PreferenceUpsertResult>;
217
+ /**
218
+ * Merge one pitfall by `errorSignature` (trimmed, case-insensitive).
219
+ *
220
+ * A repeated pitfall never duplicates: the existing entry keeps its id, the
221
+ * latest solution/context wins, `appliesTo`/`evidence`/`tags` are unioned, and
222
+ * the stricter privacy label survives.
223
+ */
224
+ upsertPitfall(input: PitfallInput): Promise<PitfallUpsertResult>;
225
+ /**
226
+ * Merge one fact by `app + scope + factKind + key`.
227
+ *
228
+ * Same statement updates the existing entry in place. A different statement
229
+ * for the same key replaces it and reports `conflict: true` unless the caller
230
+ * explicitly named the entry to supersede; either way only one current entry
231
+ * for that key remains and `supersedes` records the old id.
232
+ */
233
+ upsertFact(input: FactInput): Promise<FactUpsertResult>;
234
+ /** Create a new SOP file (`draft`, version 1). An existing slug is refused. */
235
+ writeSop(input: SopInput): Promise<SopWriteResult>;
236
+ /**
237
+ * Revise one SOP, incrementing its version.
238
+ *
239
+ * `draft → testing | dropped`, `testing → promoted | dropped`; same-status
240
+ * edits are revisions. `promoted`/`dropped` are terminal.
241
+ */
242
+ updateSop(slug: string, patch: SopPatch): Promise<SopUpdateResult>;
243
+ /** Delete one SOP file (the promote-to-skill step calls this). Missing is false, not an error. */
244
+ deleteSop(slug: string): Promise<boolean>;
245
+ /** Current SOPs, sorted by slug. A corrupt SOP file is an error, not silently skipped. */
246
+ listSops(): Promise<Sop[]>;
247
+ /**
248
+ * Read the current memory index: aggregate files, SOPs and daily-log counts.
249
+ *
250
+ * Unlike a write, an index read is tolerant: entries that fail validation are
251
+ * reported in `issues` instead of blocking the rest of the snapshot.
252
+ */
253
+ readMemoryIndex(): Promise<MemoryIndex>;
254
+ /**
255
+ * List every current memory entry across the five surfaces.
256
+ *
257
+ * Aggregates (`偏好`/`踩坑`/`事实`), daily logs (`记忆日志/`), and SOP files are
258
+ * read directly; entries are deduped by id (first occurrence wins) and sorted
259
+ * newest-first by `updatedAt ?? createdAt`, then by type and id. `path` is the
260
+ * document relative to the memory root. Parse issues are tolerated here so one
261
+ * bad file cannot blank the memory page; writes still refuse them.
262
+ */
263
+ listEntries(): Promise<ListedMemoryEntry[]>;
264
+ /** Read one entry (with its document path) by exact id. */
265
+ getEntry(id: string): Promise<ListedMemoryEntry | undefined>;
266
+ /**
267
+ * Correct one existing entry in place.
268
+ *
269
+ * The id, type and createdAt are preserved; the document path, SOP slug and
270
+ * version, and SOP lifecycle status are not patchable. Merge-key fields may
271
+ * change, but a new key must not collide with another current entry. Privacy
272
+ * changes go through the same validation as writes, so `secret` still needs a
273
+ * `credentialRef`.
274
+ *
275
+ * @returns the corrected entry plus its document path.
276
+ */
277
+ updateEntry(id: string, patch: MemoryEntryPatch): Promise<ListedMemoryEntry>;
278
+ /**
279
+ * Forget one entry: append a tombstone/audit record, then remove it from its
280
+ * document (or delete the SOP file). The guardian's next dream treats the
281
+ * tombstone as a durable user deletion and must not re-extract it.
282
+ *
283
+ * A missing id is a no-op result, not an error.
284
+ */
285
+ forgetEntry(id: string): Promise<ForgetEntryResult>;
286
+ /** Locate one entry and the document that holds it. */
287
+ private findEntry;
288
+ /** Reject a correction that would create two current entries with one merge key. */
289
+ private assertMergeKeyUnique;
290
+ /** Re-render the exact document shape a located entry came from. */
291
+ private writeLocatedDocument;
292
+ /** Append one human-auditable tombstone; never includes body or credential values. */
293
+ private appendTombstone;
294
+ private readSops;
295
+ private listLogs;
296
+ private pathExists;
297
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Model-facing runtime memory tools: `memory_context` and `memory_guardian_run`.
3
+ *
4
+ * `memory_context` is read-only. It resolves the caller's personal binding
5
+ * projection through {@link resolveMemoryContext}: live proxies for subscribed
6
+ * sources, the user's own branch for internalized sources, redlines marked
7
+ * non-overridable, and a deterministic budget. It never writes.
8
+ *
9
+ * `memory_guardian_run` is the manual trigger for the guardian pass. It is a
10
+ * maintenance action, not a read: it refreshes `sourceVersion`/`sourceCommit`,
11
+ * resolves pending bindings, performs requested internalizations and revokes
12
+ * branches whose source became redline. It is denied unless the Host reports the
13
+ * `kb:config:manage` capability, and it only touches the caller's own bindings
14
+ * root (`userIds: [caller.userId]`) plus graphs the caller may manage. The
15
+ * scheduled guardian job remains the normal path; this tool exists for
16
+ * operators and for a deployment without a scheduler.
17
+ *
18
+ * Both tools take the same injected host seam as the other knowledge tools: no
19
+ * global config, no ambient session. The caller's viewer is resolved once per
20
+ * call, and the backend remains the final authority for anything the tools then
21
+ * read or write.
22
+ *
23
+ * @module @sparkelf/dsh-knowledge-base/memory-tools
24
+ */
25
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
26
+ import type { LoadedGraph } from './graphModel.ts';
27
+ import { type GraphViewer } from './graphPolicy.ts';
28
+ import { type MemoryContextResult } from './memoryContext.ts';
29
+ import { type GuardianResult } from './memoryGuardian.ts';
30
+ /** The Host operations the runtime memory tools compose. */
31
+ export interface MemoryToolHost {
32
+ /** The authenticated caller, with the department/role projection already resolved. */
33
+ resolveCaller(): Promise<GraphViewer>;
34
+ /** Root of `<usersRoot>/<userId>/bindings`; supplied by plugin configuration. */
35
+ usersRoot: string;
36
+ /** Every graph the caller may read. Implementations must not return a denied graph. */
37
+ loadGraphs(viewer: GraphViewer): Promise<LoadedGraph[]>;
38
+ /** Whether the caller holds the memory-management capability (`kb:config:manage`). */
39
+ canManage(viewer: GraphViewer): Promise<boolean> | boolean;
40
+ /** Whether personal memory is enabled for this caller; a paused user gets no personal entries. */
41
+ isMemoryEnabled?(viewer: GraphViewer): Promise<boolean> | boolean;
42
+ }
43
+ /** Result of one `memory_context` call. */
44
+ export interface MemoryContextToolResult {
45
+ ok: true;
46
+ format: 'markdown' | 'json';
47
+ rendered: string;
48
+ context: MemoryContextResult;
49
+ /** True when the user paused memory; only non-personal policy/redlines remain. */
50
+ paused?: boolean;
51
+ }
52
+ /** Per-graph guardian outcome. */
53
+ export interface MemoryGuardianGraphResult extends GuardianResult {
54
+ graphId: string;
55
+ }
56
+ /** Result of one `memory_guardian_run` call. */
57
+ export interface MemoryGuardianToolResult {
58
+ ok: true;
59
+ userId: string;
60
+ runAt: string;
61
+ graphs: MemoryGuardianGraphResult[];
62
+ totals: GuardianResult;
63
+ note?: string;
64
+ }
65
+ /**
66
+ * Build both runtime memory tools.
67
+ *
68
+ * @param host - the injected caller/graph/root seam.
69
+ * @returns Tool definitions for the disclosure coordinator.
70
+ */
71
+ export declare function createMemoryTools(host: MemoryToolHost): ToolDefinition[];
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Plugin-level memory triggers: session idle debounce and compaction notices.
3
+ *
4
+ * Both triggers do exactly one thing — deliver a message to the user's guardian
5
+ * session through {@link sendToGuardian}. There is no queue, no task table and
6
+ * no cron:
7
+ *
8
+ * - **idle**: after a session's `turn/end`, one 30-minute timer starts. Any
9
+ * `turn/start` or `user/message` clears it (the session is active again); a
10
+ * later `turn/end` starts a fresh timer. When it expires the guardian receives
11
+ * `reason=idle` with the source session id;
12
+ * - **compaction**: `compaction/start` immediately notifies the guardian with
13
+ * `reason=compaction` and the compaction id. The listener never awaits the
14
+ * send, so compaction is not blocked. The same compaction id is sent once.
15
+ *
16
+ * Guardian sessions themselves are ignored, so the guardian cannot wake itself.
17
+ * Detection is injected (`isGuardianSession`) because the durable identity is
18
+ * guardian.json; there is no preset to test.
19
+ *
20
+ * Timers and the event source are injected so the debounce can be tested with a
21
+ * deterministic clock.
22
+ *
23
+ * @module @sparkelf/dsh-knowledge-base/memory-triggers
24
+ */
25
+ import { type GuardianSessionHost } from './guardianSession.ts';
26
+ /** Default idle window: 30 minutes after the last turn ends. */
27
+ export declare const IDLE_DEBOUNCE_MS: number;
28
+ /** The session fields a trigger reads. */
29
+ export interface MemoryTriggerSession {
30
+ readonly id: string;
31
+ }
32
+ /** One `session/event` payload, structurally narrowed. */
33
+ export interface MemoryTriggerEvent {
34
+ readonly type: string;
35
+ readonly data?: unknown;
36
+ }
37
+ /** Injectable timer seam. */
38
+ export interface MemoryTriggerTimers {
39
+ setTimeout(callback: () => void, ms: number): unknown;
40
+ clearTimeout(handle: unknown): void;
41
+ }
42
+ /** Host seam implemented by the plugin wiring. */
43
+ export interface MemoryTriggerHost {
44
+ /** The owner of the current plugin process (one user per deployment). */
45
+ resolveUserId(): Promise<string>;
46
+ /** True when the session id is some user's guardian (guardian.json). */
47
+ isGuardianSession(sessionId: string): Promise<boolean>;
48
+ /** Whether memory learning is enabled for the owner; paused skips both triggers. */
49
+ isEnabled?(userId: string): Promise<boolean> | boolean;
50
+ /** `ctx.on('session/event', listener)`; returns the unsubscribe function. */
51
+ onSessionEvent(listener: (session: MemoryTriggerSession, event: MemoryTriggerEvent) => void): () => void;
52
+ /** The same guardian send path the tool uses. */
53
+ guardian: GuardianSessionHost;
54
+ timers?: MemoryTriggerTimers;
55
+ /** Override the 30-minute window in tests. */
56
+ idleMs?: number;
57
+ log?: (message: string) => void;
58
+ }
59
+ /**
60
+ * Install the idle and compaction triggers.
61
+ *
62
+ * @param host - event source, guardian send path and injected timers.
63
+ * @returns an idempotent disposer that clears every timer and unsubscribes.
64
+ */
65
+ export declare function installMemoryTriggers(host: MemoryTriggerHost): () => void;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The five-type personal memory model and its on-disk front matter.
3
+ *
4
+ * The design settled on exactly five memory types (design §15). Anything that
5
+ * looks like another type is a field or an operation instead:
6
+ *
7
+ * - a decision is an `episodic` entry or a `fact`;
8
+ * - a procedure is a `sop` (or a `pitfall` when it is a failure story);
9
+ * - an entity is metadata (`entities`), a correction is a `supersedes` write;
10
+ * - a redline is an `authority` level, not a memory type.
11
+ *
12
+ * Privacy is a separate axis shared by all five types:
13
+ * `normal | private | sensitive | secret`. `secret` is not "more private"; it
14
+ * means the memory contains a `credentialRef` and never the credential value
15
+ * itself. Personal memory defaults to `private`.
16
+ *
17
+ * Files use the same tiny YAML dialect as `memoryBindings.ts` (scalars, quoted
18
+ * strings, inline arrays, `#` comments), and each entry is delimited by
19
+ * {@link MEMORY_ENTRY_MARKER} so a daily log or aggregate file can hold many
20
+ * entries without a YAML multi-document parser.
21
+ *
22
+ * @module @sparkelf/dsh-knowledge-base/memory-types
23
+ */
24
+ import { formatYamlScalar } from './memoryBindings.ts';
25
+ /** The five memory types. No other type is added; see the design §15.1. */
26
+ export declare const MEMORY_TYPES: readonly ["preference", "pitfall", "episodic", "fact", "sop"];
27
+ export type MemoryType = typeof MEMORY_TYPES[number];
28
+ /** The privacy axis shared by every memory type (design §15.2). */
29
+ export declare const PRIVACY_VALUES: readonly ["normal", "private", "sensitive", "secret"];
30
+ export type Privacy = typeof PRIVACY_VALUES[number];
31
+ /** What kind of explicit statement a `fact` records. */
32
+ export declare const FACT_KINDS: readonly ["requirement", "decision", "clarification"];
33
+ export type FactKind = typeof FACT_KINDS[number];
34
+ /** SOP lifecycle. `promoted` and `dropped` are terminal. */
35
+ export declare const SOP_STATUSES: readonly ["draft", "testing", "promoted", "dropped"];
36
+ export type SopStatus = typeof SOP_STATUSES[number];
37
+ /** Application id is an open string; the design lists suggested values only. */
38
+ export type AppId = string;
39
+ /** Whether a memory entry was extracted automatically or explicitly requested by the user. */
40
+ export declare const MEMORY_ORIGINS: readonly ["auto", "explicit"];
41
+ export type MemoryOrigin = typeof MEMORY_ORIGINS[number];
42
+ /** Separator used to display a source snapshot without exposing a raw session id. */
43
+ export declare const MEMORY_SOURCE_LABEL_FALLBACK = "\u5386\u53F2\u4F1A\u8BDD";
44
+ /** Marker that starts one entry inside a multi-entry memory document. */
45
+ export declare const MEMORY_ENTRY_MARKER = "<!-- memory:entry -->";
46
+ /** Fields every memory entry carries. */
47
+ export interface MemoryEntry {
48
+ id: string;
49
+ type: MemoryType;
50
+ /** `private` is the personal-memory default; caller may narrow/raise it. */
51
+ privacy: Privacy;
52
+ createdAt: string;
53
+ updatedAt?: string;
54
+ app?: AppId;
55
+ scenario?: string;
56
+ taskType?: string;
57
+ entities?: string[];
58
+ sourceSession?: string;
59
+ /** When the remembered thing happened (not necessarily when it was written). */
60
+ sourceTime?: string;
61
+ /** Short user-facing title (<= 20 chars); never a tool name, path or session id. */
62
+ displayTitle?: string;
63
+ /** Human-readable source snapshot (session title / app / scenario); never a session id. */
64
+ sourceLabel?: string;
65
+ /** Evidence event positions inside the source session, when known. */
66
+ sourceSeqs?: number[];
67
+ /** `auto` for extracted memory, `explicit` when the user asked to remember it. */
68
+ origin?: MemoryOrigin;
69
+ tags?: string[];
70
+ /** Paths / session ids / other evidence pointers; never a secret value. */
71
+ evidence?: string[];
72
+ /** For `privacy: secret`: which credential holds the value, and for what. */
73
+ credentialRef?: string;
74
+ /** Id of the entry this one replaces. */
75
+ supersedes?: string;
76
+ /** Optional free body after the front matter. */
77
+ body?: string;
78
+ }
79
+ /** A soft habit, style or default value that newer preferences replace. */
80
+ export interface Preference extends MemoryEntry {
81
+ type: 'preference';
82
+ /** Merge key inside one app: one current value per topic. */
83
+ topic: string;
84
+ value: string;
85
+ }
86
+ /** A real failure with its context, fix and applicability. */
87
+ export interface Pitfall extends MemoryEntry {
88
+ type: 'pitfall';
89
+ /** Dedupe key; repeated writes with the same signature merge. */
90
+ errorSignature: string;
91
+ context: string;
92
+ solution: string;
93
+ appliesTo?: string[];
94
+ }
95
+ /** What happened in a session: request, outcome and what it graduated into. */
96
+ export interface Episodic extends MemoryEntry {
97
+ type: 'episodic';
98
+ summary: string;
99
+ request?: string;
100
+ outcome?: string;
101
+ sopUsed?: string[];
102
+ promotedTo?: string[];
103
+ }
104
+ /** Something the user explicitly required, decided or clarified. */
105
+ export interface Fact extends MemoryEntry {
106
+ type: 'fact';
107
+ factKind: FactKind;
108
+ /** Merge key inside one app/scope/factKind. */
109
+ key: string;
110
+ statement: string;
111
+ /** Free grouping label such as `驾驶舱` or `权限`. */
112
+ scope?: string;
113
+ }
114
+ /** A reusable how-to draft; promoted into a skill and then deleted. */
115
+ export interface Sop extends MemoryEntry {
116
+ type: 'sop';
117
+ slug: string;
118
+ title: string;
119
+ status: SopStatus;
120
+ /** Starts at 1 and increments on every update. */
121
+ version: number;
122
+ trigger: string;
123
+ steps: string[];
124
+ /** Tools and parameters as human-readable strings (e.g. `kb_search(limit=5)`). */
125
+ tools?: string[];
126
+ successCriteria?: string[];
127
+ /** Where the promoted skill was written (skill name/path refs). */
128
+ promotedTo?: string[];
129
+ }
130
+ /** Any of the five concrete memory entries. */
131
+ export type AnyMemoryEntry = Preference | Pitfall | Episodic | Fact | Sop;
132
+ /** Metadata accepted by a store write for every type. */
133
+ export interface MemoryMetadataInput {
134
+ id?: string;
135
+ /** Omitted -> `private` (personal-memory default). */
136
+ privacy?: Privacy;
137
+ createdAt?: string;
138
+ updatedAt?: string;
139
+ app?: AppId;
140
+ scenario?: string;
141
+ taskType?: string;
142
+ entities?: string[];
143
+ sourceSession?: string;
144
+ sourceTime?: string;
145
+ displayTitle?: string;
146
+ sourceLabel?: string;
147
+ sourceSeqs?: number[];
148
+ origin?: MemoryOrigin;
149
+ tags?: string[];
150
+ evidence?: string[];
151
+ credentialRef?: string;
152
+ supersedes?: string;
153
+ body?: string;
154
+ }
155
+ export interface PreferenceInput extends MemoryMetadataInput {
156
+ type: 'preference';
157
+ topic: string;
158
+ value: string;
159
+ }
160
+ export interface PitfallInput extends MemoryMetadataInput {
161
+ type: 'pitfall';
162
+ errorSignature: string;
163
+ context: string;
164
+ solution: string;
165
+ appliesTo?: string[];
166
+ }
167
+ export interface EpisodicInput extends MemoryMetadataInput {
168
+ type: 'episodic';
169
+ summary: string;
170
+ request?: string;
171
+ outcome?: string;
172
+ sopUsed?: string[];
173
+ promotedTo?: string[];
174
+ }
175
+ export interface FactInput extends MemoryMetadataInput {
176
+ type: 'fact';
177
+ factKind: FactKind;
178
+ key: string;
179
+ statement: string;
180
+ scope?: string;
181
+ }
182
+ export interface SopInput extends MemoryMetadataInput {
183
+ type: 'sop';
184
+ slug?: string;
185
+ title: string;
186
+ status?: SopStatus;
187
+ version?: number;
188
+ trigger: string;
189
+ steps: string[];
190
+ tools?: string[];
191
+ successCriteria?: string[];
192
+ promotedTo?: string[];
193
+ }
194
+ /** Any input accepted by `MemoryStore` write methods. */
195
+ export type MemoryEntryInput = PreferenceInput | PitfallInput | EpisodicInput | FactInput | SopInput;
196
+ /** One validation problem; `field` names the offending front-matter key. */
197
+ export interface MemoryValidationIssue {
198
+ code: 'invalid-entry' | 'invalid-value' | 'missing-field' | 'secret-value' | 'secret-requires-credential-ref' | 'unsafe-slug';
199
+ message: string;
200
+ field?: string;
201
+ }
202
+ /** Thrown by validation and by the store before anything is written. */
203
+ export declare class MemoryValidationError extends Error {
204
+ readonly issues: MemoryValidationIssue[];
205
+ constructor(issues: MemoryValidationIssue[]);
206
+ }
207
+ export declare const isMemoryType: (value: unknown) => value is MemoryType;
208
+ export declare const isPrivacy: (value: unknown) => value is Privacy;
209
+ export declare const isFactKind: (value: unknown) => value is FactKind;
210
+ export declare const isSopStatus: (value: unknown) => value is SopStatus;
211
+ export declare const isMemoryOrigin: (value: unknown) => value is MemoryOrigin;
212
+ /** A slug is one safe file name (Unicode allowed, no separators or hidden names). */
213
+ export declare function isSafeMemorySlug(value: unknown): value is string;
214
+ /**
215
+ * Validate one complete memory entry (after the store has filled id/defaults).
216
+ *
217
+ * Unknown extra fields are tolerated so a newer writer can add bookkeeping, but
218
+ * an invalid enum, missing required field, unsafe slug or plaintext secret is
219
+ * always an error.
220
+ */
221
+ export declare function validateMemoryEntry(value: unknown): MemoryValidationIssue[];
222
+ /** Assert a complete entry, throwing one aggregated {@link MemoryValidationError}. */
223
+ export declare function assertValidMemoryEntry(value: unknown): asserts value is AnyMemoryEntry;
224
+ /** Serialize one entry as a marker + front matter + optional body block. */
225
+ export declare function serializeMemoryEntry(entry: AnyMemoryEntry): string;
226
+ /**
227
+ * Parse every memory entry in one document.
228
+ *
229
+ * Text outside entry blocks (a file title, maintenance note or fact section
230
+ * heading) is ignored. A malformed block produces an issue and is skipped; the
231
+ * store decides whether that is fatal for a write or just reported by an index
232
+ * read.
233
+ */
234
+ export declare function parseMemoryEntries(source: string): {
235
+ entries: AnyMemoryEntry[];
236
+ issues: MemoryValidationIssue[];
237
+ };
238
+ /** Render a YAML scalar with the shared quoting rules (exported for tests/tools). */
239
+ export declare const formatMemoryScalar: typeof formatYamlScalar;
240
+ /** Generate a unique memory id; callers may supply their own stable id instead. */
241
+ export declare const newMemoryId: () => string;