@sparkelf/dsh-knowledge-base 0.1.35 → 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.
- package/README.md +34 -0
- package/lib/client.js +2516 -1378
- package/lib/client.js.map +1 -1
- package/lib/index.js +17516 -7806
- package/lib/types/client/KnowledgeMemory.d.ts +127 -0
- package/lib/types/client/KnowledgePermissionOverview.d.ts +113 -0
- package/lib/types/client/graph/OriginBadges.d.ts +55 -0
- package/lib/types/client/locales.d.ts +66 -0
- package/lib/types/client/roleSummary.d.ts +47 -0
- package/lib/types/graph.d.ts +1 -0
- package/lib/types/graphCanvas.d.ts +1 -1
- package/lib/types/graphJsonProjection.d.ts +71 -0
- package/lib/types/graphMigration.d.ts +118 -0
- package/lib/types/graphModel.d.ts +194 -0
- package/lib/types/graphPolicy.d.ts +68 -0
- package/lib/types/graphTools.d.ts +23 -4
- package/lib/types/graphTypes.d.ts +26 -2
- package/lib/types/guardianSession.d.ts +135 -0
- package/lib/types/index.d.ts +92 -0
- package/lib/types/knowledgeTools.d.ts +17 -1
- package/lib/types/memoryBindings.d.ts +119 -0
- package/lib/types/memoryContext.d.ts +83 -0
- package/lib/types/memoryGraphBootstrap.d.ts +62 -0
- package/lib/types/memoryGraphWriter.d.ts +101 -0
- package/lib/types/memoryGuardian.d.ts +123 -0
- package/lib/types/memoryGuardianTool.d.ts +56 -0
- package/lib/types/memoryPolicy.d.ts +106 -0
- package/lib/types/memoryRecordTool.d.ts +39 -0
- package/lib/types/memoryRoutes.d.ts +85 -0
- package/lib/types/memorySettings.d.ts +40 -0
- package/lib/types/memorySkillPromotion.d.ts +62 -0
- package/lib/types/memoryStore.d.ts +297 -0
- package/lib/types/memoryTools.d.ts +71 -0
- package/lib/types/memoryTriggers.d.ts +65 -0
- package/lib/types/memoryTypes.d.ts +241 -0
- package/lib/types/summaryIndex.d.ts +112 -0
- package/lib/types/summaryWriteback.d.ts +87 -0
- package/package.json +2 -2
- package/skills/memory-extract/SKILL.md +43 -0
- package/skills/memory-guardian/SKILL.md +97 -0
- package/skills/memory-sop-evaluate/SKILL.md +43 -0
|
@@ -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;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Incremental change detection and summary refresh for the knowledge tree.
|
|
3
|
+
*
|
|
4
|
+
* The design fixes one rule that keeps this module small: the AI never decides
|
|
5
|
+
* what an edit affects. A changed document makes the document and its fixed
|
|
6
|
+
* parent chain dirty; only dirty documents are re-summarised, and directory
|
|
7
|
+
* summaries are folded from the documents summarised in that pass, in stable
|
|
8
|
+
* path order.
|
|
9
|
+
*
|
|
10
|
+
* ```text
|
|
11
|
+
* Git diff / mtime+hash
|
|
12
|
+
* → ChangeSnapshot
|
|
13
|
+
* → diffSnapshots
|
|
14
|
+
* → ChangeSet (changed / added / removed / dirtyDirectories)
|
|
15
|
+
* → refreshDirtySummaries (only dirty documents reach summarize())
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* The module owns no storage. `summarize` and `writeIndex` are injected, so the
|
|
19
|
+
* existing `kb_docs.summary` path (or an INDEX.md writer) remains the one owner
|
|
20
|
+
* of persistence. A removed document is dropped by calling `writeIndex(path,
|
|
21
|
+
* '')`; an empty summary is the "delete this entry" signal.
|
|
22
|
+
*
|
|
23
|
+
* Scope: the snapshot tracks TEXT DOCUMENTS (`.md`, `.markdown`, `.txt`,
|
|
24
|
+
* `.text`). Binary attachments are deliberately outside the summary index; the
|
|
25
|
+
* directory and file names the design reserves for graph/media state
|
|
26
|
+
* (`.graphs`, `.kg`, `.archive`, `_trash`, any other dot directory) are skipped
|
|
27
|
+
* recursively.
|
|
28
|
+
*
|
|
29
|
+
* @module @sparkelf/dsh-knowledge-base/summary-index
|
|
30
|
+
*/
|
|
31
|
+
/** One file's content identity and modification instant. */
|
|
32
|
+
export interface ChangeSnapshot {
|
|
33
|
+
files: Record<string, {
|
|
34
|
+
mtimeMs: number;
|
|
35
|
+
sha256: string;
|
|
36
|
+
}>;
|
|
37
|
+
}
|
|
38
|
+
/** The difference between two snapshots, plus the directory chain to refresh. */
|
|
39
|
+
export interface ChangeSet {
|
|
40
|
+
changed: string[];
|
|
41
|
+
added: string[];
|
|
42
|
+
removed: string[];
|
|
43
|
+
dirtyDirectories: string[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Whether a path is a document the summary index tracks.
|
|
47
|
+
*
|
|
48
|
+
* Exported so the wiring layer can apply the same definition when it maps paths
|
|
49
|
+
* to `kb_docs` rows instead of guessing from a MIME type.
|
|
50
|
+
*/
|
|
51
|
+
export declare function isSummaryDocumentPath(relPath: string): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Hash every text document under `root` and record its modification instant.
|
|
54
|
+
*
|
|
55
|
+
* Output keys are sorted, so two scans of the same tree produce equal snapshots
|
|
56
|
+
* and callers can compare them without a second ordering pass. A missing root
|
|
57
|
+
* yields an empty snapshot: the plugin may load before a workspace provisions
|
|
58
|
+
* its tree. Symbolic links are not followed, which keeps a link cycle from
|
|
59
|
+
* turning a scan into an infinite walk.
|
|
60
|
+
*/
|
|
61
|
+
export declare function scanKnowledgeTree(root: string): Promise<ChangeSnapshot>;
|
|
62
|
+
/**
|
|
63
|
+
* Compare two snapshots.
|
|
64
|
+
*
|
|
65
|
+
* Content identity is the sha256, not the mtime: touching a file without
|
|
66
|
+
* changing a byte is not a change and must not spend a summarisation call. The
|
|
67
|
+
* mtime exists so a scanner can skip re-hashing an untouched file; it is kept in
|
|
68
|
+
* the snapshot for that optimisation and for display.
|
|
69
|
+
*
|
|
70
|
+
* `dirtyDirectories` is the deterministic union of the fixed parent chain of
|
|
71
|
+
* every changed, added and removed document, sorted.
|
|
72
|
+
*/
|
|
73
|
+
export declare function diffSnapshots(previous: ChangeSnapshot, next: ChangeSnapshot): ChangeSet;
|
|
74
|
+
/**
|
|
75
|
+
* The fixed ancestor chain of a document, root-first.
|
|
76
|
+
*
|
|
77
|
+
* `a/b/c.md` answers `['a', 'a/b']`; a document at the root answers `[]`. The
|
|
78
|
+
* chain never includes the document itself and never depends on what currently
|
|
79
|
+
* exists on disk, which is what makes "which directories are dirty" a pure
|
|
80
|
+
* function of the changed path.
|
|
81
|
+
*
|
|
82
|
+
* Invalid input (absolute path, `..`, NUL) answers `[]` instead of throwing:
|
|
83
|
+
* there is no ancestor chain to refresh outside the root.
|
|
84
|
+
*/
|
|
85
|
+
export declare function parentChain(relPath: string): string[];
|
|
86
|
+
/**
|
|
87
|
+
* Re-summarise the changed/added documents, drop removed ones and rebuild the
|
|
88
|
+
* dirty directory aggregates.
|
|
89
|
+
*
|
|
90
|
+
* Only `changeSet.changed` and `changeSet.added` documents reach `summarize()`,
|
|
91
|
+
* each exactly once, in sorted path order. Removed documents are not
|
|
92
|
+
* summarised; they are dropped by calling `writeIndex(path, '')`.
|
|
93
|
+
*
|
|
94
|
+
* Directory aggregates are folded from the summaries produced in THIS pass,
|
|
95
|
+
* using the deterministic child order (`- <relPath>: <summary>`). That is the
|
|
96
|
+
* only summary source the injected API exposes; a directory with no freshly
|
|
97
|
+
* summarised child is not rewritten, so a deletion alone cannot blank an
|
|
98
|
+
* aggregate that still describes unchanged siblings. A caller that stores full
|
|
99
|
+
* child summaries should merge them at the sink.
|
|
100
|
+
*
|
|
101
|
+
* @returns `updated` - document paths summarised and written, sorted.
|
|
102
|
+
* `directories` - directory paths whose aggregate was written, sorted.
|
|
103
|
+
*/
|
|
104
|
+
export declare function refreshDirtySummaries(input: {
|
|
105
|
+
root: string;
|
|
106
|
+
changeSet: ChangeSet;
|
|
107
|
+
summarize: (relPath: string, source: string) => Promise<string>;
|
|
108
|
+
writeIndex: (relPath: string, summary: string) => Promise<void>;
|
|
109
|
+
}): Promise<{
|
|
110
|
+
updated: string[];
|
|
111
|
+
directories: string[];
|
|
112
|
+
}>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persist incremental summary refreshes into the existing knowledge index.
|
|
3
|
+
*
|
|
4
|
+
* `summaryIndex.ts` decides WHICH documents changed. This module is the write
|
|
5
|
+
* half: it reads the changed/added documents, rebuilds a deterministic extractive
|
|
6
|
+
* summary from the already-indexed chunks, updates the existing `kb_docs` row
|
|
7
|
+
* (`summary`, `summary_kind='extractive'`, `summary_version`), and refreshes the
|
|
8
|
+
* generated `index/md/<docId>.INDEX.md` when that file already exists. Removed
|
|
9
|
+
* documents have their summary cleared. The scan snapshot is written last and
|
|
10
|
+
* atomically, so a failed run is simply retried from the previous baseline.
|
|
11
|
+
*
|
|
12
|
+
* ## Why the index must be current
|
|
13
|
+
*
|
|
14
|
+
* The summary is built from the chunks SQLite already holds, with the exact
|
|
15
|
+
* `chunkText` + `buildDocumentOutline` functions the indexer uses, so the text
|
|
16
|
+
* matches what `kb_search` can cite. Before using a document this module verifies
|
|
17
|
+
* that the stored chunks are byte-identical to a fresh chunking of the source. A
|
|
18
|
+
* changed document whose row/chunks are stale (or missing entirely) is reported as
|
|
19
|
+
* `pending` and left OUT of the snapshot, so the next run retries it after
|
|
20
|
+
* `syncIndex` catches up. Nothing is guessed from a stale index.
|
|
21
|
+
*
|
|
22
|
+
* The expected call order in the plugin is:
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* await syncIndex({ actualRoot, indexPath })
|
|
26
|
+
* await applySummaryWriteback({ root: actualRoot, indexPath })
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* ## Boundaries
|
|
30
|
+
*
|
|
31
|
+
* - It does not create the SQLite schema. `kb_docs`/`kb_chunks` and `kb_index_meta`
|
|
32
|
+
* are owned by `ftsIndex.ts`; a missing `kb_docs` table is a wiring error.
|
|
33
|
+
* - It writes only the three summary columns. Section rows, TOC and the summary
|
|
34
|
+
* FTS table stay owned by `ftsIndex`/`kb_outline_save`, so a model-authored
|
|
35
|
+
* outline is never half-replaced by an extractive one.
|
|
36
|
+
* - An existing `summary_kind='llm'` summary is preserved, matching the indexer's
|
|
37
|
+
* own rule; extractive output never downgrades model-authored text.
|
|
38
|
+
*
|
|
39
|
+
* @module @sparkelf/dsh-knowledge-base/summary-writeback
|
|
40
|
+
*/
|
|
41
|
+
/** Inputs for one incremental summary write-back pass. */
|
|
42
|
+
export interface SummaryWritebackOptions {
|
|
43
|
+
/** Authoritative knowledge-tree root; the same `actualRoot` given to `syncIndex`. */
|
|
44
|
+
root: string;
|
|
45
|
+
/** SQLite index file created/owned by `ftsIndex` (`kb.sqlite`). */
|
|
46
|
+
indexPath: string;
|
|
47
|
+
/** Where the scan baseline lives; defaults to `<index dir>/summary-snapshot.json`. */
|
|
48
|
+
snapshotPath?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Optional replacement summarizer for the changed/added documents. When omitted,
|
|
51
|
+
* the deterministic extractive summary from the indexed chunks is used. The
|
|
52
|
+
* source text is the current file content, so a caller may plug in a model here.
|
|
53
|
+
*/
|
|
54
|
+
summarize?: (relPath: string, source: string) => Promise<string>;
|
|
55
|
+
}
|
|
56
|
+
/** What one write-back pass did; all path arrays are sorted. */
|
|
57
|
+
export interface SummaryWritebackResult {
|
|
58
|
+
/** Documents whose `kb_docs.summary` was rewritten. */
|
|
59
|
+
updated: string[];
|
|
60
|
+
/** Documents that disappeared from the tree; their summary was cleared. */
|
|
61
|
+
removed: string[];
|
|
62
|
+
/** Changed/added documents the index has not caught up with; retried next run. */
|
|
63
|
+
pending: string[];
|
|
64
|
+
/** Documents left untouched because a model-authored (`llm`) summary owns them. */
|
|
65
|
+
preserved: string[];
|
|
66
|
+
/** Absolute `INDEX.md` paths regenerated (only files that already existed). */
|
|
67
|
+
indexFiles: string[];
|
|
68
|
+
/** Absolute snapshot path used for this pass. */
|
|
69
|
+
snapshotPath: string;
|
|
70
|
+
/** False when the baseline was already current and nothing was written. */
|
|
71
|
+
snapshotWritten: boolean;
|
|
72
|
+
}
|
|
73
|
+
/** The default snapshot path for one index; exported for callers that inspect it. */
|
|
74
|
+
export declare function summarySnapshotPathFor(indexPath: string): string;
|
|
75
|
+
/**
|
|
76
|
+
* Run one incremental summary write-back pass.
|
|
77
|
+
*
|
|
78
|
+
* Only changed/added documents are read; only removed documents are cleared.
|
|
79
|
+
* Unchanged documents cost one hash in `scanKnowledgeTree` and nothing else. A
|
|
80
|
+
* second pass with an unchanged tree performs no database writes and no summary
|
|
81
|
+
* generation, and leaves the snapshot alone.
|
|
82
|
+
*
|
|
83
|
+
* @throws when the index file/table is missing, the source cannot be read, or a
|
|
84
|
+
* database/INDEX write fails. In every failure case the snapshot is NOT
|
|
85
|
+
* advanced, so the same changes are retried on the next pass.
|
|
86
|
+
*/
|
|
87
|
+
export declare function applySummaryWriteback(options: SummaryWritebackOptions): Promise<SummaryWritebackResult>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sparkelf/dsh-knowledge-base",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "DataOps-backed knowledge base for DeepSeek Harness: a left-sidebar destination, Settings configuration, and index tooling over a mounted NAS view.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"README.md",
|
|
44
44
|
"LICENSE",
|
|
45
45
|
"SKILL.md",
|
|
46
|
-
"
|
|
46
|
+
"万相AI使用教程.html",
|
|
47
47
|
"i18n/*.json",
|
|
48
48
|
"skills/**/SKILL.md",
|
|
49
49
|
"skills/**/i18n/*.json"
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: memory-extract
|
|
3
|
+
description: 记忆抽取子代理的工作准则:读一次会话的新增消息和工具轨迹,只提取可长期复用的偏好、踩坑、情景、事实与 SOP 候选,给出证据并避开秘密与闲聊。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# 记忆抽取子代理
|
|
7
|
+
|
|
8
|
+
你负责从一段真实的会话轨迹里挑出值得长期记住的内容。你只提候选,不最终写记忆;合并、纠偏和遗忘由守护会话决定。
|
|
9
|
+
|
|
10
|
+
## 读什么
|
|
11
|
+
|
|
12
|
+
读分配给你的会话在本次范围内的新增消息和工具轨迹。工具轨迹包括调用意图、参数、返回结果和失败重试,不要只看最后的成功消息。压缩摘要可以作为索引,但证据要回到原文。
|
|
13
|
+
|
|
14
|
+
## 只提五类
|
|
15
|
+
|
|
16
|
+
- **偏好**:用户的软习惯、输出风格、默认值、常用做法。是“倾向”,不是硬约束。
|
|
17
|
+
- **踩坑**:实际执行中遇到的错误或异常,连同上下文、解决办法和适用条件。以后遇到同样错误能直接省时间。
|
|
18
|
+
- **情景**:什么时间、什么场景、用户要求做什么、结果如何。任务过程和决策时刻值得留,但不要把整段过程复述一遍。
|
|
19
|
+
- **事实**:用户明确要求、明确拍板或明确澄清的约束。必须是用户说清楚的,不要把你自己的推断写成事实。
|
|
20
|
+
- **SOP**:可以重复使用的做法,包含触发条件、步骤、工具选择和成功标准。做法只在这一次偶然奏效、或依赖特殊环境的,不要提成 SOP。
|
|
21
|
+
|
|
22
|
+
判断标准只有一个:**它会不会改变下一次的行为**。闲聊、寒暄、一次性的查询结果、已经写在部门制度里的公共知识,都不算。
|
|
23
|
+
|
|
24
|
+
## 每条候选要带什么
|
|
25
|
+
|
|
26
|
+
用一小段话说清:它是什么、为什么值得留、在哪个消息或工具结果里能看到证据、适用于什么场景。证据要能定位到原文,不要写“根据对话”。没有证据的候选不要提。
|
|
27
|
+
|
|
28
|
+
同一个主题合并成一条,不要按消息逐条罗列。发现它和已有记忆可能重复时,指出来,让守护会话去重。
|
|
29
|
+
|
|
30
|
+
## 不做什么
|
|
31
|
+
|
|
32
|
+
- 不保存密钥、Token、密码或凭据值。如果遇到,只记“哪份凭据、什么用途、用于哪个系统”,实际值归凭据管理器。
|
|
33
|
+
- 不把联系方式、身份、账户细节等敏感内容当普通记忆;拿不准就标成 private 或 sensitive,让守护会话确认。
|
|
34
|
+
- 不把用户的玩笑、假设、临时演练当成事实。
|
|
35
|
+
- 不替用户做决定,也不把“AI 建议”写成用户的明确要求。
|
|
36
|
+
|
|
37
|
+
## 怎么交付
|
|
38
|
+
|
|
39
|
+
可以写一份临时详细报告,但回给守护会话的只要一小段结论:提了哪几类、每类最关键的几条、哪些拿不准。守护会话读完后会删除临时报告,所以不要把唯一证据只留在报告里而不写进结论。
|
|
40
|
+
|
|
41
|
+
宁少勿滥。一条真正会改变下次行为的记忆,比十条看起来很完整的复述更有价值。
|
|
42
|
+
|
|
43
|
+
每个候选带一个不超过 20 字的短标题,只写结论,不写工具名、路径、会话 id 或长解释;详细证据放在正文。
|