@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,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>;
|
|
@@ -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
|
+
}
|