@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,71 @@
1
+ /**
2
+ * Projection adapter: new `.graphs/<id>/graph.json` graphs into the graph tab's
3
+ * existing DOMAIN tree (`scope -> graph -> topic -> documents`).
4
+ *
5
+ * The graph tab was built for the legacy layout, where every node was a visible
6
+ * topic folder. The new model keeps node bodies wherever the classification tree
7
+ * wants them and only records topology in `graph.json`, so it has no topic folder
8
+ * to point at. Projecting each node into a topic card keeps the existing canvas,
9
+ * tree and breadcrumb working unchanged while the authoritative topology stays in
10
+ * `graph.json`; the projection is derived, never written back.
11
+ *
12
+ * The legacy scanner stays authoritative for legacy graphs. This module is pure:
13
+ * it receives already-loaded graphs and returns browser-safe nodes, so it never
14
+ * touches the filesystem and cannot widen what the Host resolved.
15
+ *
16
+ * @module @sparkelf/dsh-knowledge-base/graph-json-projection
17
+ */
18
+ import type { LoadedGraph } from './graphModel.ts';
19
+ import type { KnowledgeGraphNode, KnowledgeGraphScopeKey } from './graphTypes.ts';
20
+ /** The folder name whose parent is the scope root that owns `.graphs/`. */
21
+ export declare const LEGACY_GRAPH_FOLDER = "\u77E5\u8BC6\u56FE\u8C31";
22
+ /** One browser-facing graph node produced from a `graph.json` manifest. */
23
+ export interface ProjectedGraphJsonNode extends KnowledgeGraphNode {
24
+ /** Distinguishes the new model from a legacy folder graph in the browser. */
25
+ format: 'graph-json';
26
+ /** New graphs are editable surfaces; kept for symmetry with read-only legacy ones. */
27
+ readOnly: boolean;
28
+ }
29
+ /** Input for one scope's projection: where it sits and which graphs were loaded. */
30
+ export interface GraphJsonScopeProjectionInput {
31
+ key: KnowledgeGraphScopeKey;
32
+ /** View-relative scope root, e.g. `global` or `department/D1`. */
33
+ viewBase: string;
34
+ /** Authoritative scope root, e.g. the same path inside the knowledge root. */
35
+ actualBase: string;
36
+ /** Department chain key; empty for global and personal. */
37
+ groupKey?: string;
38
+ /** Department display label; empty for global and personal. */
39
+ groupLabel?: string;
40
+ /** Graphs loaded from `<actualBase>/.graphs/`. */
41
+ graphs: LoadedGraph[];
42
+ }
43
+ /** The scope directory that owns `.graphs/`, from a legacy graph root. */
44
+ export declare function graphScopeBase(actualGraphRoot: string): string;
45
+ /** The view-relative path of the hidden graph store under a scope base. */
46
+ export declare function graphStorePath(viewBase: string, graphId: string): string;
47
+ /**
48
+ * Project loaded graphs into graph-tab nodes for one scope.
49
+ *
50
+ * Only edges whose two ends exist as loaded nodes are projected; a broken edge is
51
+ * a validator issue, not a canvas arrow to a card that will never render.
52
+ */
53
+ export declare function projectGraphJsonScope(input: GraphJsonScopeProjectionInput): ProjectedGraphJsonNode[];
54
+ /**
55
+ * Merge projected graphs into the scanner's tree.
56
+ *
57
+ * The scanner's own order is preserved; a scope's projected graphs are appended
58
+ * inside the matching department group (or the flat group for global/personal).
59
+ * A projected graph never replaces a legacy graph with the same display name:
60
+ * both are real sources and the browser can tell them apart by `format`.
61
+ */
62
+ export declare function mergeProjectedGraphs(tree: {
63
+ scopes: Array<{
64
+ key: KnowledgeGraphScopeKey;
65
+ groups: Array<{
66
+ key: string;
67
+ label: string;
68
+ graphs: KnowledgeGraphNode[];
69
+ }>;
70
+ }>;
71
+ }, projectedByScope: Partial<Record<KnowledgeGraphScopeKey, ProjectedGraphJsonNode[]>>): void;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Migration of the legacy knowledge-graph layout into the memory-graph layout.
3
+ *
4
+ * Legacy graphs are ordinary folders under a scope:
5
+ *
6
+ * ```text
7
+ * <scope>/知识图谱/<graph>/<topic>/index.md # topic card
8
+ * <scope>/知识图谱/<graph>/<topic>/<doc>.md # documents (nested folders allowed)
9
+ * <scope>/知识图谱/<graph>/.kg/links/*.md # hidden relations
10
+ * ```
11
+ *
12
+ * The target model separates bodies from topology:
13
+ *
14
+ * ```text
15
+ * <scope>/<classified>/<doc>.md # one body, normal document tree
16
+ * <scope>/.graphs/<graph>/graph.json # manifest: topics + node/edge refs
17
+ * <scope>/.graphs/<graph>/links/<edge>.md # optional relation bodies
18
+ * ```
19
+ *
20
+ * The planner is read-only. `applyMigration` performs the planned file
21
+ * operations, but only after the plan has no error-level issue: duplicate
22
+ * bodies are never deleted while a broken edge, a duplicate id, or an unsafe
23
+ * path is still unresolved. Every write is a temporary file followed by a
24
+ * rename; independent documents are moved, never copied.
25
+ *
26
+ * Dedupe order matches the contract: frontmatter `id`, then sha256 of the
27
+ * whole document, then the classified path (`<topic>/<doc>`), then the title.
28
+ * A title/path/id match whose body differs is a conflict for human review and
29
+ * is left in the legacy tree untouched.
30
+ *
31
+ * @module @sparkelf/dsh-knowledge-base/graph-migration
32
+ */
33
+ /** Folder whose children are legacy graphs. */
34
+ export declare const KNOWLEDGE_GRAPH_FOLDER = "\u77E5\u8BC6\u56FE\u8C31";
35
+ /** Folder that receives legacy documents with no classified copy. */
36
+ export declare const GRAPH_DOCUMENT_FOLDER = "\u56FE\u8C31\u6587\u6863";
37
+ /** Hidden folder that holds the new manifests and relation documents. */
38
+ export declare const GRAPH_STORE_FOLDER = ".graphs";
39
+ /** Where the emptied legacy graph shell is kept for one release cycle. */
40
+ export declare const GRAPH_ARCHIVE_FOLDER = ".archive/graphs";
41
+ /** Severity of one migration issue. Only `error` blocks `applyMigration`. */
42
+ export type MigrationIssueSeverity = 'error' | 'warning';
43
+ /** One problem found while planning a migration. */
44
+ export interface MigrationIssue {
45
+ code: string;
46
+ message: string;
47
+ path?: string;
48
+ severity: MigrationIssueSeverity;
49
+ }
50
+ /** Options accepted by both the planner and the applier. */
51
+ export interface MigrationOptions {
52
+ /** The scope root that contains `知识图谱/` and the classified document tree. */
53
+ scopeRoot: string;
54
+ /** Planning is always read-only; the flag is carried into the report. */
55
+ dryRun: boolean;
56
+ /** Fixed timestamp for generated manifests; defaults to now. */
57
+ now?: string;
58
+ /**
59
+ * Overwrite an existing `.graphs/<graph>/graph.json`.
60
+ *
61
+ * Only the manifest is replaced. Existing node bodies and link documents are
62
+ * never overwritten; a differing target is an error-level issue instead.
63
+ */
64
+ force?: boolean;
65
+ /** Manifest scope override, e.g. `department:data-platform`. */
66
+ scope?: string;
67
+ /** Manifest visibility override. */
68
+ visibility?: 'private' | 'department' | 'global';
69
+ }
70
+ /** The report rendered by `renderMigrationReport` and printed by the CLI. */
71
+ export interface MigrationReport {
72
+ graphs: Array<{
73
+ graphId: string;
74
+ name: string;
75
+ topics: number;
76
+ documents: number;
77
+ links: number;
78
+ }>;
79
+ matched: number;
80
+ independent: number;
81
+ conflicts: number;
82
+ brokenEdges: number;
83
+ plannedWrites: string[];
84
+ /** Independent-document moves (legacy graph -> 图谱文档/). */
85
+ plannedMoves: Array<{
86
+ from: string;
87
+ to: string;
88
+ }>;
89
+ /** Legacy graph shells that will be moved into `.archive/graphs/`. */
90
+ plannedArchives?: Array<{
91
+ from: string;
92
+ to: string;
93
+ }>;
94
+ plannedDeletes: string[];
95
+ issues: MigrationIssue[];
96
+ /** True for a plan, false once `applyMigration` has run. */
97
+ dryRun?: boolean;
98
+ /** True when every planned operation completed. */
99
+ applied?: boolean;
100
+ }
101
+ /** Plan a migration without writing anything. */
102
+ export declare function planMigration(options: MigrationOptions): Promise<MigrationReport>;
103
+ /** Whether a report contains an issue that blocks `applyMigration`. */
104
+ export declare function migrationReportHasErrors(report: MigrationReport): boolean;
105
+ /**
106
+ * Execute a previously planned migration.
107
+ *
108
+ * The report is recomputed before anything is written so the caller cannot
109
+ * apply a stale plan. Any error-level issue aborts the whole run before the
110
+ * first file operation. Writes are atomic; independent documents are moved;
111
+ * duplicate bodies and old topic cards are deleted only after the manifest has
112
+ * been written and every node body is present on disk.
113
+ */
114
+ export declare function applyMigration(options: MigrationOptions & {
115
+ report: MigrationReport;
116
+ }): Promise<MigrationReport>;
117
+ /** Render the report a human reads after a dry run or an apply. */
118
+ export declare function renderMigrationReport(report: MigrationReport): string;
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The `.graphs/` memory-graph model: manifest types, loader, validator and the
3
+ * dependency-free front-matter reader the rest of the memory graph modules use.
4
+ *
5
+ * A graph is metadata plus topology; it is not a second document store:
6
+ *
7
+ * ```text
8
+ * <scope>/.graphs/<graphId>/graph.json # manifest: nodes + edges
9
+ * <scope>/.graphs/<graphId>/links/<edgeId>.md # optional relation body
10
+ * <scope>/<node path>.md # the node body, an ordinary document
11
+ * ```
12
+ *
13
+ * The split is deliberate. The manifest only references node documents by scope
14
+ * relative path and records edge topology; every human-facing attribute (`type`,
15
+ * `authority`, `origin`, `reviewStatus`, ...) lives in the node document's front
16
+ * matter, so moving or editing a document never duplicates its body here.
17
+ *
18
+ * Failure policy: only a missing or non-JSON `graph.json` throws
19
+ * ({@link GraphLoadError}). Everything a reader can still describe — a missing
20
+ * body, a missing relation document, a duplicate id, an edge endpoint the
21
+ * manifest never declared, a path that escapes the scope — becomes a
22
+ * {@link GraphValidationIssue} on the returned graph. That keeps one bad document
23
+ * from hiding an otherwise renderable graph.
24
+ *
25
+ * @module @sparkelf/dsh-knowledge-base/graph-model
26
+ */
27
+ /** The memory meaning a node carries; independent of the document's folder. */
28
+ export type MemoryNodeType = 'policy' | 'fact' | 'procedure' | 'case' | 'skill' | 'decision' | 'topic';
29
+ /** How strongly a node overrides other memory. `redline` may only be subscribed. */
30
+ export type MemoryAuthority = 'canonical' | 'advisory' | 'redline';
31
+ /** Who authored the node body. AI content is publishable but must stay labelled. */
32
+ export type MemoryOrigin = 'human' | 'ai' | 'mixed';
33
+ /** Review state shown in the UI. */
34
+ export type MemoryReviewStatus = 'draft' | 'reviewed' | 'approved';
35
+ /** One node reference in `graph.json`; the body lives at `path`. */
36
+ export interface GraphManifestNode {
37
+ id: string;
38
+ path: string;
39
+ }
40
+ /** One edge in `graph.json`. `doc` is an optional scope-relative relation document. */
41
+ export interface GraphManifestEdge {
42
+ id: string;
43
+ from: string;
44
+ to: string;
45
+ type: string;
46
+ doc?: string;
47
+ }
48
+ /** The `graph.json` document as written on disk. */
49
+ export interface GraphManifest {
50
+ schemaVersion: 1;
51
+ id: string;
52
+ name: string;
53
+ description?: string;
54
+ scope: string;
55
+ version: number;
56
+ status: 'draft' | 'published' | 'archived';
57
+ owner?: string;
58
+ createdAt: string;
59
+ updatedAt: string;
60
+ publishedAt?: string;
61
+ tags: string[];
62
+ visibility: 'private' | 'department' | 'global';
63
+ defaultView?: {
64
+ layout?: string;
65
+ direction?: string;
66
+ };
67
+ topics?: Array<{
68
+ id: string;
69
+ title: string;
70
+ description?: string;
71
+ }>;
72
+ nodes: GraphManifestNode[];
73
+ edges: GraphManifestEdge[];
74
+ }
75
+ /** Attributes read from a node document's front matter. */
76
+ export interface GraphNodeAttributes {
77
+ id: string;
78
+ type: MemoryNodeType;
79
+ title: string;
80
+ authority: MemoryAuthority;
81
+ internalizable: boolean;
82
+ origin: MemoryOrigin;
83
+ reviewStatus: MemoryReviewStatus;
84
+ tags: string[];
85
+ sourceRefs: string[];
86
+ }
87
+ /** A node as loaded: attributes plus where its body lives and whether it was found. */
88
+ export interface LoadedGraphNode extends GraphNodeAttributes {
89
+ path: string;
90
+ missing: boolean;
91
+ }
92
+ /**
93
+ * An edge as loaded.
94
+ *
95
+ * The manifest's edge `type` is a RELATION type (for example `depends_on`), not a
96
+ * {@link MemoryNodeType}. The contract describes this interface as extending
97
+ * `GraphNodeAttributes`; carrying a relation type in `type` is the only reading
98
+ * that keeps `graph.json` authoritative for topology, so the relation type is
99
+ * exposed here and the node-only `type` field is omitted rather than narrowed to
100
+ * an enum that cannot express it.
101
+ */
102
+ export interface LoadedGraphEdge extends Omit<GraphNodeAttributes, 'type'> {
103
+ /** Relation type from `graph.json` (e.g. `depends_on`). */
104
+ type: string;
105
+ from: string;
106
+ to: string;
107
+ docPath?: string;
108
+ missing: boolean;
109
+ }
110
+ /** One non-fatal (or validation-level fatal) problem found while loading a graph. */
111
+ export interface GraphValidationIssue {
112
+ severity: 'error' | 'warning';
113
+ code: 'missing-node' | 'missing-edge-doc' | 'duplicate-id' | 'unknown-endpoint' | 'invalid-manifest' | 'invalid-frontmatter' | 'path-escape' | 'orphan-edge';
114
+ message: string;
115
+ ref?: string;
116
+ }
117
+ /** A fully loaded graph: manifest, resolved root, documents, edges and issues. */
118
+ export interface LoadedGraph {
119
+ manifest: GraphManifest;
120
+ root: string;
121
+ nodes: LoadedGraphNode[];
122
+ edges: LoadedGraphEdge[];
123
+ issues: GraphValidationIssue[];
124
+ }
125
+ /** Why {@link loadGraph} could not even read a manifest. */
126
+ export type GraphLoadErrorCode = 'manifest-missing' | 'manifest-invalid-json' | 'invalid-graph-id';
127
+ /**
128
+ * Thrown only when the graph manifest cannot be read at all.
129
+ *
130
+ * Validation problems discovered after the manifest parses are returned as
131
+ * issues on the graph instead of thrown.
132
+ */
133
+ export declare class GraphLoadError extends Error {
134
+ readonly code: GraphLoadErrorCode;
135
+ readonly graphPath: string;
136
+ constructor(code: GraphLoadErrorCode, graphPath: string, message: string);
137
+ }
138
+ /**
139
+ * Read a node document's front matter.
140
+ *
141
+ * Supported syntax is the documented subset: `key: value`, quoted strings and
142
+ * `[a, b]` inline arrays. Optional attributes fall back to `type=fact`,
143
+ * `authority=advisory`, `internalizable=true`, `origin=human`,
144
+ * `reviewStatus=draft`, `tags=[]` and `sourceRefs=[]`. `id` and `title` are
145
+ * required here because this function has no manifest or file name to fall back
146
+ * to; {@link loadGraph} supplies both when a manifest already names the node.
147
+ *
148
+ * Invalid enum values are errors rather than defaults: silently downgrading an
149
+ * unknown `authority` to `advisory` could turn a mistyped redline into
150
+ * internalizable memory.
151
+ */
152
+ export declare function parseNodeFrontMatter(source: string): {
153
+ attributes: GraphNodeAttributes | null;
154
+ body: string;
155
+ issues: GraphValidationIssue[];
156
+ };
157
+ /**
158
+ * Load one graph from `<scopeRoot>/.graphs/<graphId>/graph.json`.
159
+ *
160
+ * Node bodies resolve against `scopeRoot` (not against the graph directory), so a
161
+ * node path is exactly the path an ordinary browser shows. Missing documents,
162
+ * duplicate ids, unknown edge endpoints and unsafe paths are reported on
163
+ * {@link LoadedGraph.issues}; only a missing or non-JSON manifest throws
164
+ * {@link GraphLoadError}.
165
+ *
166
+ * @param scopeRoot - directory that owns `.graphs/`; may be relative.
167
+ * @param graphId - the `.graphs/<graphId>` directory name (one path segment).
168
+ * @returns the loaded graph, with issue severity already classified.
169
+ */
170
+ export declare function loadGraph(scopeRoot: string, graphId: string): Promise<LoadedGraph>;
171
+ /**
172
+ * Validate an already-loaded graph and return its error-level issues.
173
+ *
174
+ * Warnings (a missing optional edge document, an orphan relation file) are not
175
+ * returned: the contract's validator answers "may this graph be published", and
176
+ * those problems never make the topology unusable. Checks are recomputed from
177
+ * the loaded data so a manually constructed graph is validated as thoroughly as
178
+ * one returned by {@link loadGraph}.
179
+ */
180
+ export declare function validateGraph(graph: LoadedGraph): GraphValidationIssue[];
181
+ /**
182
+ * List the graphs under `<scopeRoot>/.graphs/`, sorted by directory id.
183
+ *
184
+ * `id` is the `.graphs/<id>` directory name, which is what {@link loadGraph}
185
+ * takes; `manifest.id` is normally identical. Directories that contain no
186
+ * readable `graph.json` are skipped rather than invented: a caller that knows a
187
+ * graph should exist can call {@link loadGraph} and receive the precise
188
+ * {@link GraphLoadError}.
189
+ */
190
+ export declare function listGraphs(scopeRoot: string): Promise<Array<{
191
+ id: string;
192
+ manifest: GraphManifest;
193
+ issueCount: number;
194
+ }>>;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Visibility and management policy for memory graphs.
3
+ *
4
+ * This module is the pure decision layer only: callers resolve the viewer's
5
+ * department subtree (`visibleDepartmentCodes`) and manageable subtree from
6
+ * DataOps, then ask one graph at a time. It never reads configuration, never
7
+ * touches the file system, and never invents a broader scope than it was handed.
8
+ *
9
+ * The rules come from the memory-graph design:
10
+ *
11
+ * - `private` belongs to its owner; administrators and super administrators do
12
+ * not see it by default (breaking the glass is a separate, audited action);
13
+ * - `global` is readable by any authenticated viewer;
14
+ * - `department` requires the graph's department code in the viewer's visible
15
+ * subtree. Department administrators understand their subtree through
16
+ * `manageableDepartmentCodes`; a plain member has neither the role nor the
17
+ * list.
18
+ *
19
+ * @module @sparkelf/dsh-knowledge-base/graph-policy
20
+ */
21
+ /** The authenticated caller asking about a graph. */
22
+ export interface GraphViewer {
23
+ userId: string;
24
+ isAdmin: boolean;
25
+ isSuperAdmin: boolean;
26
+ departmentCode?: string;
27
+ /** Visible department subtree (including the caller's own); members see only their own. */
28
+ visibleDepartmentCodes: string[];
29
+ /** Department subtree the caller may manage; empty for ordinary members. */
30
+ manageableDepartmentCodes?: string[];
31
+ }
32
+ /** The scope a graph lives in, as resolved from its manifest. */
33
+ export interface GraphScopeDescriptor {
34
+ visibility: 'private' | 'department' | 'global';
35
+ ownerId?: string;
36
+ departmentCode?: string;
37
+ }
38
+ /**
39
+ * Whether the viewer may read the graph.
40
+ *
41
+ * Private graphs are owner-only before any role check runs, so neither an
42
+ * administrator nor a super administrator can discover someone else's private
43
+ * graph through this function. Department access is exact membership: the caller
44
+ * is responsible for expanding `visibleDepartmentCodes` to the subtree, which
45
+ * keeps hierarchy logic in the one place that already knows it.
46
+ */
47
+ export declare function canViewGraph(viewer: GraphViewer, scope: GraphScopeDescriptor): boolean;
48
+ /**
49
+ * Whether the viewer may manage the graph (edit metadata, publish, change
50
+ * authority).
51
+ *
52
+ * Management always implies visibility. Private graphs stay owner-only. Global
53
+ * graphs need an administrator role. Department graphs need the department in
54
+ * `manageableDepartmentCodes`; a super administrator covers every department,
55
+ * and the two lists in {@link GraphViewer} are trusted as already-resolved
56
+ * authorization input rather than re-derived here.
57
+ */
58
+ export declare function canManageGraph(viewer: GraphViewer, scope: GraphScopeDescriptor): boolean;
59
+ /**
60
+ * Filter graphs down to the ones the viewer may read, preserving input order.
61
+ *
62
+ * Order is preserved on purpose: the caller already sorted for display, and this
63
+ * function must not introduce a second ordering rule. A denial is a removal, not
64
+ * an error; callers never receive a name they may not see.
65
+ */
66
+ export declare function filterVisibleGraphs<T extends {
67
+ scope: GraphScopeDescriptor;
68
+ }>(viewer: GraphViewer, graphs: T[]): T[];
@@ -1,12 +1,19 @@
1
1
  /**
2
2
  * Model-facing knowledge-graph tools (`kg_add` / `kg_get` / `kg_set` / `kg_del`).
3
3
  *
4
- * The four verbs mirror `kg.py`'s CLI. They operate on the P1 storage shape
5
- * (`知识图谱/<graph>/<topic>/index.md`, relations under `.kg/links/`) through the
6
- * same Host seam the HTTP routes use: one grant per graph, `canWritePath` before
7
- * every write, `readAuthorized` for every read, audit entries recorded beside the
4
+ * The four verbs mirror `kg.py`'s CLI. Two storage layouts are addressed through
5
+ * the same Host seam the HTTP routes use: one grant per graph, `canWrite` before
6
+ * every write, `readText` for every read, audit entries recorded beside the
8
7
  * caller's view, and `_trash` instead of deletion.
9
8
  *
9
+ * - **Legacy folder graphs** (`<scope>/知识图谱/<graph>/<topic>/index.md`, relations
10
+ * under `.kg/links/`) keep their original behaviour untouched.
11
+ * - **`.graphs/<id>/graph.json` graphs** (`format: 'graph-json'`) carry topology in
12
+ * the manifest and attributes in each node document's front matter. The tools
13
+ * read both, refuse duplicate ids / unknown endpoints / unsafe paths, and write
14
+ * the manifest through a temp-file rename; after every write the loaded graph is
15
+ * re-validated and the change is rolled back when the validator reports an error.
16
+ *
10
17
  * Writes are two-step by design. A call without `confirm: true` returns the exact
11
18
  * draft it would write and changes nothing; the model shows that draft to the user
12
19
  * and calls again with `confirm: true` after approval. This is the §7 trigger rule
@@ -22,6 +29,18 @@ export interface KnowledgeGraphToolHost extends Pick<KnowledgeFileToolHost, 'res
22
29
  listGraphs(): Promise<KnowledgeGraphNode[]>;
23
30
  /** Read one view-relative document through the permission-checked route. */
24
31
  readText(viewPath: string): Promise<string>;
32
+ /**
33
+ * Read one knowledge-root-relative path that may be hidden from the view tree
34
+ * (`.graphs/<id>/graph.json`, relation docs). The Host applies the same path
35
+ * permission check as {@link readText}; absent means the Host cannot read
36
+ * hidden paths and the tool falls back to the view spelling.
37
+ */
38
+ readActual?(relPath: string): Promise<string>;
39
+ /** Stat one knowledge-root-relative path, for the hidden `.graphs` store. */
40
+ statActual?(relPath: string): Promise<{
41
+ kind: 'file' | 'directory';
42
+ size?: number;
43
+ } | undefined>;
25
44
  }
26
45
  /**
27
46
  * Build the four graph tools.
@@ -21,6 +21,12 @@ export declare const KNOWLEDGE_GRAPH_FOLDER = "\u77E5\u8BC6\u56FE\u8C31";
21
21
  export declare const KNOWLEDGE_GRAPH_META_FOLDER = ".kg";
22
22
  /** The trash folder `kg_del` moves topics into; never a topic itself. */
23
23
  export declare const KNOWLEDGE_GRAPH_TRASH_FOLDER = "_trash";
24
+ /** How a document or node was produced. Absent on content that predates the field. */
25
+ export type KnowledgeGraphOrigin = 'human' | 'ai' | 'mixed';
26
+ /** Review lifecycle. Absent means the scanner did not report one. */
27
+ export type KnowledgeGraphReviewStatus = 'draft' | 'reviewed' | 'approved';
28
+ /** Authority level. Absent means the scanner did not report one. */
29
+ export type KnowledgeGraphAuthority = 'canonical' | 'advisory' | 'redline';
24
30
  /** One document inside a topic folder, as the detail panel lists it. */
25
31
  export interface KnowledgeGraphDocument {
26
32
  /** Human title: the document's first H1, else the file name without extension. */
@@ -33,6 +39,12 @@ export interface KnowledgeGraphDocument {
33
39
  date?: string;
34
40
  /** First paragraph after the H1, when the file has one. */
35
41
  summary?: string;
42
+ /** Optional provenance: `ai`/`mixed` renders the [AI 生成] badge. */
43
+ origin?: KnowledgeGraphOrigin;
44
+ /** Optional review lifecycle: `reviewed`/`approved` renders [已审核]. */
45
+ reviewStatus?: KnowledgeGraphReviewStatus;
46
+ /** Optional authority: `redline` renders [红线] and only permits subscription. */
47
+ authority?: KnowledgeGraphAuthority;
36
48
  }
37
49
  /** One topic: a visible folder whose `index.md` is its card. */
38
50
  export interface KnowledgeGraphTopic {
@@ -58,6 +70,12 @@ export interface KnowledgeGraphTopic {
58
70
  path: string;
59
71
  /** Documents below the topic folder, including nested document folders. */
60
72
  documents: KnowledgeGraphDocument[];
73
+ /** Optional provenance for the topic card; mirrors the node-level field. */
74
+ origin?: KnowledgeGraphOrigin;
75
+ /** Optional review lifecycle for the topic card. */
76
+ reviewStatus?: KnowledgeGraphReviewStatus;
77
+ /** Optional authority for the topic card; `redline` is subscribe-only. */
78
+ authority?: KnowledgeGraphAuthority;
61
79
  }
62
80
  /** One relation document under `<graph>/.kg/links/`. */
63
81
  export interface KnowledgeGraphLink {
@@ -96,6 +114,12 @@ export interface KnowledgeGraphNode {
96
114
  links: number;
97
115
  documents: number;
98
116
  };
117
+ /** Optional provenance for the graph row; absent on graphs scanned before it existed. */
118
+ origin?: KnowledgeGraphOrigin;
119
+ /** Optional review lifecycle for the graph row. */
120
+ reviewStatus?: KnowledgeGraphReviewStatus;
121
+ /** Optional authority for the graph row; `redline` is subscribe-only. */
122
+ authority?: KnowledgeGraphAuthority;
99
123
  /**
100
124
  * Authoritative path relative to the knowledge root, used by Host-side graph
101
125
  * tools. Stripped before the tree is sent to the browser.