2026-04-07 v1.7.0¶
Interface Document (v1.7.0)¶
This document is the canonical interface handover for the current codebase. It was rebuilt from source verification, not appended to legacy sections.
2026-07-11 v1.8.0 - Coverage-driven graph answer contracts¶
The conversation response now exposes two additive contracts:
interface AgentConversationResponse {
graphAnswerPlan?: GraphAnswerPlan;
graphAnswerCoverage?: GraphAnswerCoverageReview;
}
The same fields are available in AgentConversationTrace, KnowledgeRun, knowledge-run workflow artifacts, and exported knowledgeRunReports summaries.
GraphAnswerPlan contains the anchor, intent/depth, evidence-backed claims, required roles, relation-edge provenance, and omitted candidates. GraphAnswerCoverageReview records required, covered, and missing claim IDs plus a normalized coverage score.
graph_answer_plan_coverage is an additive AnswerReleaseGateId. It may trigger revision when required graph claims are absent. Character count and sentence count are not release gates.
Public evidence is shaped through src/learning/ragPublicText.ts: authoring/control instructions, Markdown table scaffolding, heading syntax, and fenced renderer source are removed before presentation. This shaping must not remove the factual lead or bypass claim coverage.
Compatibility: all new response fields remain optional; existing clients may continue consuming assistantMessage, answer, blocks, citations, and release review.
2026-07-18 calibration and expansion addendum¶
AgentConversationTrace.graphExpansion is an additive replay contract containing enabled, reason, maxSteps, executedSteps, maxNeighbors, selectedNeighborCount, and maxPathDepth. Ordinary queries expose a disabled 0-step policy; only explicit deep/research wording enables the bounded 1-step policy.
Required-claim coverage now uses deterministic multilingual concept normalization and clause polarity agreement. It remains a conservative release gate, not an open-ended semantic-entailment service. evaluateGraphAnswerCoverageCalibration() reports precision, recall, and false-positive/false-negative case IDs against the versioned corpus.
The frontend projects plan, coverage, and expansion summaries only into the Grounding Inspector. The assistant answer renderer does not consume these internal planning fields.
0.0 Multi-Platform Build Contract Addendum (v1.7.0)¶
This addendum captures the build/runtime contracts that now matter to the Git LFS migration and to cross-platform delivery safety.
Canonical companion docs:
docs/en/lfs_asset_migration_plan.mddocs/en/multi_platform_build_flow_audit.mddocs/en/sidecar_supply_strategy.md
Current build-contract conclusions:
- The default frontend build contract is runtime-first via
npm run build. - Explicit full-mode is still supported, and desktop
tauri:build:fullnow preserves full-mode through TauribeforeBuildCommandby routing throughscripts/run-tauri-frontend-build.js. - Android build tooling baseline is JDK 21+ for both local helper verification and current CI/release setup.
- Capacitor packaging and Tauri Android packaging must be treated separately from mobile runtime capability:
- Capacitor native runtime can locally build graph payloads when Filesystem APIs are available.
- Tauri Android runtime exposes native
build_graph_runtimeand reportssupports_build=true. - Desktop sidecar/bootstrap remains an active build contract; the current migration direction is supply hardening, not architecture deletion.
- Current Godot bootstrap is provider-neutral at the download-contract layer: pinned GitHub Releases URLs and generic HTTPS object-storage mirror URLs both fit the same URL + SHA256 + cache model.
- Release CI now includes a minimal Godot mirror-seeding slice: it maintains a project-controlled GitHub Releases mirror tag and downloads mirror-first while retaining upstream fallback as a transitional safety rail.
Build-surface files verified for this addendum:
package.jsonbuild_apk.batcapacitor.config.tsscripts/copy-assets.jsscripts/run-tauri-build.jsscripts/run-tauri-frontend-build.jsscripts/run-tauri-android.jsscripts/verify-tauri-android-prereqs.jssrc-tauri/tauri.conf.jsonsrc-tauri/tauri.android.conf.jsonsrc-tauri/src/lib.rssrc/frontend/storage_provider.jssrc/frontend/source_manager.js.github/workflows/release-desktop-multi-os.yml.github/workflows/npm-publish.yml
0.0A Knowledge Runtime Contract Addendum (2026-06-06)¶
This addendum records the current code-backed knowledge runtime contracts without changing the public API.
Current contract surfaces:
KnowledgeQueryRequest.scopeacceptsKnowledgeCorpusScopewith workspace, corpus, document, atom, source-path-prefix, and language constraints.AgentConversationResponseremains backward-compatible:assistantMessageis still valid for legacy clients,answer,citations,knowledgePoints,memoryActions,summary, andtraceexpose grounded conversation state,- optional
assistantBlockscarries richer typed reply sections for clients that can render them. AgentConversationKnowledgePointmay now include grouped/document-augmented fields such asatomIds,documentId,sourcePath,citations,matchedSpans, andmatchCount.- Scoped query resolution may now expose
scopeSource: planner_scope_recoverywhen a title-like recovery path intentionally leaves the original explicit corpus boundary and switches to a document-only recovery scope. /api/knowledge/conversationsupports the current conversation path, including stream-first clients and sync fallback behavior./api/knowledge/conversation-memory/{list,add,search,delete,feedback}exposes scoped conversation memory operations./api/knowledge/workspace-readinessexposes workspace/corpus readiness for scoped runtime decisions.POST /api/knowledge/export/workspaceexposes deterministic workspace export bundles backed by resource, index, workspace, session, workflow, memory, and render-materialization state.- Runtime governance endpoints and payloads expose graphdb/vector rollout context, including
rolloutProfile, graphdb connector health, vector acceleration strictness, and runbook checks. - The Knowledge Workspace frontend contract now also includes an in-pane scope selector, a compact
/api/knowledge/conversationstatus strip, grouped file-first hit rendering, and matched-span evidence rendering in the focus pane. assistantBlocksare no longer only thin transport wrappers around the same plain answer string. Tauri-capable clients should now expect intent-aware overview / explanation / evidence / memory / action sections while still treatingassistantMessageas the compatibility fallback.
0.0B Knowledge Workspace and DAG Alignment Addendum (2026-06-10)¶
- The Knowledge Workspace runtime now includes durable workflow-artifact paths for
flashcard_batchandknowledge_run, exposed through/api/knowledge/workflow-artifactsand/api/knowledge/workflow-artifacts/review-follow-up. - Runtime compatibility remains additive:
assistantMessagestays valid,answer,assistantBlocks,knowledgeRun, groupedknowledgePoints, citations, memory actions, and trace coexist with legacy clients.- The codebase already contains a real DAG-backed learning substrate:
KnowledgeAtomRelationEdgeTemporalEdge- path queries
- prerequisite-driven mastery/session flows
KnowledgeQueryItem.relationPath- Current architecture reading:
- graph-backed retrieval and learning-path/session logic are implemented,
- graph-native answer planning is not yet complete because retrieval and answer synthesis still lack a dedicated graph-conditioned context-assembly layer.
- Current product-surface reading:
- grouped file-first knowledge hits and right-pane source highlighting are implemented,
- the visible answer area is now contracted at the composer/frontend boundary:
answeranddirectAnswerstay targeted, while graph paths, citations, memory notes, diagnostics, and durable artifacts move to secondary evidence/export surfaces.
0.0C Agent Knowledge DAG Answer Contract Addendum (2026-06-17)¶
- Agent knowledge graph context refers to the project's existing DAG-shaped learning substrate, not a generic graph database replacement.
AgentConversationGraphContext.connectionPathsis an optional additive field for explicit store-backed atom paths.- Each path carries source/target atom identity, ordered atom IDs/titles, edge relation kinds, and length.
- Clients and exports must continue to accept graph contexts without this field.
- Conversation compatibility remains unchanged:
assistantMessageis still valid, whileanswer,assistantBlocks, groupedknowledgePoints, citations, memory actions, workflow artifacts, andtrace.graphContextremain additive. - Evidence-pane rendering and workspace export may expose connection paths as secondary inspection material; public answer rendering should remain targeted to the user's question.
- Future graph-native answer planning should be implemented as bounded graph-conditioned context assembly between retrieval and answer synthesis, using
KnowledgeAtom,RelationEdge,TemporalEdge, evidence spans, and store-level path operations. - If graph ops are unavailable or fail, the runtime must fail open to the current retrieval-grounded answer path with observable diagnostics.
0.0D Final Reply Review and Evidence Provenance Addendum (2026-06-19)¶
AnswerReleaseReviewis now a first-class additive runtime contract rather than a planning placeholder.AnswerReleaseDecisionremainsrelease|revise|abstain.- Gate coverage currently includes
evidence_sufficiency,graph_support_sufficiency,claim_grounding_alignment,query_intent_alignment,claim_structured_consistency,claim_attribute_consistency,claim_containment_consistency,claim_composition_consistency,claim_purpose_consistency,claim_dependency_consistency,claim_subject_consistency,claim_state_consistency,claim_polarity_consistency,claim_graph_causal_consistency,claim_graph_order_consistency,claim_graph_comparison_consistency,public_surface_contraction,internal_diagnostic_leakage, andabstention_hygiene. src/learning/conversationComposer.tsmust pass the scoped draft answer, grouped knowledge points, citations, resolved scope, and optional graph context throughreviewAnswerRelease(...)before exposing the publicanswer/directAnswersurface.src/learning/KnowledgeLearningPlatform.ts, workspace export, and frontend reply rendering must treat answer-release telemetry as additive inspection material:- public answer text,
- review decision,
- failed gate IDs,
- leaked internal fragments,
- per-gate diagnostics.
- Evidence-pane source projection is now explicitly layered:
src/frontend/markdown_runtime.jsannotates rendered markdown blocks withdata-agent-markdown-source-start-line,data-agent-markdown-source-end-line, anddata-agent-markdown-source-kind,- graph focus prefers
source_line_provenancewhen rendered-node source ranges overlap trusted evidence spans, - after selecting the node, graph focus projects the matched evidence fragment into inline highlight markup inside that node,
- it falls back to markdown
line_windowanchors when rendered-source metadata is absent but citation line metadata is still trustworthy, - it falls back to
snippet_fallbackwhen line metadata is stale or low-overlap, - it exposes additive
highlightStrategy,sourceProvenanceBlockCount,sourceProvenanceAttributedNodeCount, andinlineHighlightCountdiagnostics instead of pretending the projection is exact. - The screenshot-backed acceptance path is now part of the formal runtime contract:
- reference failure image:
E:\微信传输\WeChat Files\wxid_zywfbxxiwwir22\FileStorage\Temp\1781782257390.jpg - regression case:
waterglass_explicit_scope_compact_zh - verifier:
scripts/verify-knowledge-workspace-runtime.js - acceptance rule: the public answer must not leak
No scoped knowledge points matched,retrieval_candidates_below_threshold, or the meta-documentary fragment本技术文档旨在when scoped evidence exists. - Remaining architecture gap:
- broaden contradiction coverage from the current lexical + query-intent + structured + structured-comparison + attribute + containment + composition + purpose + dependency + location + subject + state + polarity + graph-causal + graph-order + graph-comparison + temporal-validity stack into richer claim-vs-citation / claim-vs-evidence contradiction classes,
- push source-to-render provenance beyond the current block-level mapping plus snippet-projected inline highlights so right-pane highlighting can become source-authenticated at the character-offset level rather than merely bounded.
Compatibility rules:
- New response fields must remain additive and optional.
- Existing endpoint names and legacy fields must remain stable unless a compatibility shim and tests land in the same change.
- Godot/mobile render paths must continue to consume PNG-first materialized artifacts; direct SVG import must not become a required runtime dependency.
- graphdb and ANN status wording must distinguish operational baselines from production closure until release-grade thresholds and repeated evidence exist.
- Release runbooks should use
verify:foundation:release-evidenceafter generating sqlite and ANN release reports to confirm latest evidence freshness, required runtime modes, and release gates before treating host evidence as current. Useverify:foundation:release-evidence:strictwhen repeated evidence is required, andverify:foundation:release-evidence:multi-hostwhen a release window requires host diversity. Foundation readiness exposes the default and strict commands throughfoundation_release_evidence_freshnessandfoundation_release_evidence_history; the current Windows host passes the strict gate with sqlite3/3and ANN3/3, but each release host/window must regenerate enough fresh reports that satisfy the current release contract, and multi-host release windows must cover enough distinct host keys.
0.0E Knowledge Workspace RSE and Hosted Runtime Addendum (2026-07-03)¶
- Mermaid syntax recovery is now a two-owner contract:
src/notemd/MermaidProcessor.tsmay normalize malformed quoted bracketed-node labels while repairing Mermaid blocks at source,src/reader_renderer.tsmay apply the same per-line normalization inside the local fallback renderer path before Mermaid parse/render.- This quoted-label normalization is intentionally line-scoped. It must not cross line boundaries and must not break the existing dangling-bracket label repair path.
AgentConversationGraphContextmay now carry optionalanchorGraphProfilewith:atomIdtitleinDegreeoutDegreecentralitypredecessorWindowandsuccessorWindowentries may now also carry optionalinDegree,outDegree, andcentrality.- Public answer synthesis and deterministic
reviseflows may now consume bounded graph-derived path and degree context fromgraphContext, but citation lists, raw diagnostics, and full graph telemetry remain secondary surfaces. graphContextis now also the bounded RSE/document-augmentation contract for this slice:- model-visible fields stay limited to
evidenceSourceRefs,connectionPaths,anchorGraphProfile, and bounded predecessor/successor windows, - full graph state, raw diagnostics, and developer telemetry are not part of the main public-answer context budget.
- Hosted Guided Learning may reuse a cached
Graph/PathEngineruntime keyed by the current source-graph signature. This is a pane-local performance optimization only: - it must not change main-graph ownership,
- it must not imply native Godot window embedding,
- cache invalidation remains snapshot/signature-based unless future graph mutation paths require a stronger contract.
src/frontend/hosted_future_path_runtime.jsis now the dedicated cache/telemetry owner for hosted Future Path runtime reuse:- it records cache hit/miss/build counters,
- it records source node/edge counts plus resolve/build timing,
- the latest snapshot is exposed through
NoteConnectionWorkspacePanes.getHostedFuturePathRuntimeDiagnostics()andwindow.__NC_LAST_AGENT_GODOT_FUTURE_PATH_RUNTIME_DIAGNOSTICS. - Guided Learning pending behavior is now a two-stage contract:
- on first open, if local graph target plus source graph snapshot are already available, the pane may render an immediate hosted Future Path projection before
/api/knowledge/pathreturns, - the pending status remains visible until the backend response replaces or enriches the pane payload.
src/frontend/agent_workspace.jsnow dedupes identical in-flight/api/knowledge/pathrequests by normalized payload while preserving the same pending-pane contract.- The local references under
ref/enterprise_agent_platformandref/codexare now part of the documented design evidence set for this slice. They remain external references only; no runtime dependency is introduced. - Boundary rule:
- Mermaid syntax healing stays in
MermaidProcessor.tsandreader_renderer.ts, not inPathBridge, - hosted runtime reuse must not become a mutable cross-graph singleton,
- public answers must not inject unbounded graph telemetry just because richer graph state exists locally.
- Compatibility rule: all graph-profile and runtime-reuse fields remain optional/additive. Clients that ignore them must remain valid.
0. Fast Track Links (Godot + NoteMD + Markdown)¶
Before starting the next integrated feature slice, execute against these docs first:
- Workflow baseline: Diataxis How-To: Godot + NoteMD + Markdown Workflows
- Field-level contract baseline: Diataxis Reference: Godot + NoteMD + Markdown Interfaces
0. Verification Scope¶
Verified against implementation files:
src/server.tssrc/utils/RuntimePaths.tssrc/index.tssrc/core/NoteConnection.tssrc/core/types.tssrc/core/Graph.tssrc/core/PathEngine.tssrc/backend/config.tssrc/backend/FileLoader.tssrc/backend/GraphBuilder.tssrc/backend/utils/frontmatterParser.tssrc/backend/utils/WorkerRuntime.tssrc/core/PathBridge.tssrc-tauri/src/lib.rssrc/frontend/source_manager.jssrc/frontend/path_app.jssrc/frontend/path_worker.jssrc/frontend/i18n.jssrc/frontend/index.htmlpath_mode/scripts/ws_client.gdpath_mode/scripts/path_mode_ui.gdpath_mode/scripts/path_renderer.gdpath_mode/scripts/learning_state_machine.gdpath_mode/scripts/tree_view_panel.gd
Audit flow:
- Fully reread previous
Interface Document.md. - Re-extract interfaces from source.
- Remove obsolete items and correct mismatches.
- Rebuild as complete English section followed by complete Chinese section.
0.1 Rendering Compatibility Constraint (Godot + Mermaid)¶
- Godot runtime Mermaid consumption is PNG-only for authoritative rendering output.
- SVG payload is retained only for diagnostics/debug snapshots and must not be used as runtime fallback in Godot.
- Reason: current Godot SVG handling can fail non-deterministically (text/layout/raster instability across devices).
- Change-control rule: any future Godot renderer optimization must preserve PNG decode as the primary path (
pngBase64required); missing PNG is a hard failure. - Obsidian compatibility baseline: canonical Mermaid markdown is fenced code whose opening line is three backticks followed by
mermaid, and whose closing line is three backticks. - Any inline-concatenated pattern where a math delimiter is immediately followed by a Mermaid opening fence is malformed input and outside the canonical compatibility baseline.
- Reader runtime guardrail: markdown reader performs a lightweight self-check on open and auto-heals that malformed pattern to newline-split form before parsing/rendering.
0.2 NoteMD Module Interface Contracts (v1.6.0)¶
NoteMD is integrated additively and does not replace existing graph/path APIs.
Backend module namespace (src/notemd/)¶
- Core interfaces/constants:
types.ts,constants.ts - LLM and prompts:
LlmProvider.ts,PromptManager.ts - Processing primitives:
FileProcessor.ts,MermaidProcessor.ts,FormulaFixer.ts - Batch/content utilities:
Translator.ts,BatchProcessor.ts,DuplicateDetector.ts,ContentGenerator.ts - Facade service:
NotemdService.ts,index.ts
HTTP API contract (src/server.ts)¶
GET /api/notemd/settingsPOST|PUT /api/notemd/settingsPOST /api/notemd/process-filePOST /api/notemd/process-folderPOST /api/notemd/test-llmPOST /api/notemd/generate-contentPOST /api/notemd/translate-filePOST /api/notemd/translate-folderPOST /api/notemd/fix-mermaidPOST /api/notemd/fix-formulasPOST /api/notemd/check-duplicatesPOST /api/notemd/extract-conceptsPOST /api/notemd/cancel
Safety and lifecycle guarantees¶
- KB-root jail validation is enforced for NoteMD file/folder operations.
- Long-running operations support SSE progress and cancellation.
- Tauri/Godot bridge contracts expose
open_notemdwithout changing existing graph bridge semantics.
0.3 v1.6.0 Interface Delta (Compared to v1.3.0)¶
- Added runtime-capability hydration bridge contract in frontend/runtime integration:
invoke('get_runtime_capabilities')invoke('get_sidecar_runtime_config')- Added sidecar runtime config command contract in Rust runtime:
get_sidecar_runtime_config- Added stricter frontend runtime bridge readiness sequencing (
whenReady) before path-mode flows. - Added contract-level policy gates for pathbridge strict schema, storage provider abstraction, mobile runtime capability boundaries, and SBOM/attestation verification scripts.
2026-07-19 v1.8.0 Executable Graph Answer Contract¶
AgentConversationTrace.graphAnswerPlan and graphAnswerCoverage now describe executed behavior, not only diagnostics. In RAG turns, the composer realizes ordered required claims before supplemental RAG clauses. Final coverage is recalculated after release revision, and revision preserves required plan statements.
Required claims are all nonredundant claims with confidence greater than 0.75; a fallback lead claim is required when no claim crosses that boundary. Same-role cardinality is not a deduplication rule. Plan evidence with citation IDs participates in claim-level citation validation.
Runtime expectations may set requireCompleteGraphAnswerCoverage and requireGraphAnswerPlanOrder. The verifier then requires every required claim ID in final coverage and requires normalized public statements to occur in plan order.
2026-07-19 final owner and compatibility clarification¶
The executable path is owned in sequence by graphContextAssembler.ts (bounded subgraph), graphAnswerPlan.ts (semantic claim contract), conversationComposer.ts (public realization), and answerReleaseReview.ts (final release invariants). graphAnswerFacts.ts is a shared fact-selection policy used by composition and revision; it does not generate prose or add an orchestration layer.
public_surface_contraction remains an AnswerReleaseGateId for wire compatibility. Its current behavior protects public-surface structure and leakage hygiene; it must not be interpreted or reimplemented as a 900-character, fixed-sentence, or single-direct_support limit.
Clause shaping is owned by ragEvidenceQuality.ts and graphAnswerPlan.ts. Segmentation preserves decimal points and mathematical notation; ranking uses terminal completeness, delimiter balance, math density, documentary penalty, and continuous length decay. The selected public clause may differ from the raw evidence text, but evidenceRefs retain that raw provenance. These scores rank already selected evidence; they do not prove relevance or entailment.
Supplemental RAG clauses are semantically deduplicated at the composer boundary, while release review removes only literal-equivalent or contained duplicates so conflicting dates, quantities, endpoints, and locations are not silently collapsed. Current verification requires complete required-claim ID coverage, plan order, no repeated long clause, and no public Markdown list/bold scaffolding. The repository-wide baseline is 124/124 Jest suites, 1,155 tests passed, and 26 skipped, with TypeScript, production/Vite build, Water Glass runtime acceptance, Diataxis, MkDocs, and diff hygiene passing.
1. Runtime and Path Contracts¶
1.1 Runtime path resolution (src/utils/RuntimePaths.ts)¶
interface RuntimePaths {
projectRoot: string;
frontendDir: string;
runtimeDataDir: string;
kbRoot: string;
}
Resolution priorities:
projectRootfrom candidate directories with existence checks.frontendDir:NOTE_CONNECTION_FRONTEND_DIR<projectRoot>/dist/src/frontend<projectRoot>/src/frontendkbRoot:NOTE_CONNECTION_KB_ROOT<projectRoot>/Knowledge_Base- CWD fallbacks
1.2 Tauri sidecar env injection (src-tauri/src/lib.rs)¶
Rust sets:
NOTE_CONNECTION_PROJECT_ROOTNOTE_CONNECTION_KB_ROOTNOTE_CONNECTION_FRONTEND_DIR
Effective KB root in this project:
E:\Knowledge_project\NoteConnection_app\Knowledge_Base
1.3 Graph artifact paths¶
Active graph artifacts:
dist/src/frontend/data.jsdist/src/frontend/graph_data.json
Target cache artifacts:
dist/src/frontend/data_<target>.jsdist/src/frontend/graph_data_<target>.json
CLI timestamped artifacts:
dist/src/frontend/data_cli_<suffix>.jsdist/src/frontend/graph_data_cli_<suffix>.json
2. Core Type Interfaces¶
2.1 Graph types (src/core/types.ts)¶
interface NoteNode {
id: string;
label: string;
inDegree: number;
outDegree: number;
content?: string;
x?: number;
y?: number;
centrality?: number;
rank?: number;
clusterId?: string;
metadata?: {
tags?: string[];
prerequisites?: string[];
next?: string[];
filepath?: string;
[key: string]: any;
};
}
interface NoteEdge {
source: string;
target: string;
type?: string;
weight?: number;
}
interface GraphData {
nodes: NoteNode[];
edges: NoteEdge[];
}
2.2 Build API types (src/core/NoteConnection.ts)¶
interface BuildOptions {
targetPath?: string;
maxWorkers?: number;
enableGPU?: boolean;
enableGPULayout?: boolean;
memorySavingMode?: boolean;
deepDebug?: boolean;
projectRoot?: string;
outputPrefix?: string;
onLog?: (msg: string) => void;
}
interface GraphBuildResult {
graph: Graph;
data: any;
stats: {
nodeCount: number;
edgeCount: number;
fileCount: number;
};
}
2.3 Backend config (src/backend/config.ts)¶
interface AppConfig {
matchingStrategy: "exact-phrase" | "fuzzy";
clusteringStrategy: "label-propagation" | "folder";
fuzzyThreshold: number;
enableTags: boolean;
enableStatisticalInference: boolean;
enableVectorSimilarity: boolean;
enableHybridInference: boolean;
enableGPU: boolean;
enableGPULayout?: boolean;
memorySavingMode: boolean;
deepDebug: boolean;
maxWorkers?: number;
exclusionList: string[];
}
2.4 Worker runtime resolution (src/backend/utils/WorkerRuntime.ts)¶
interface WorkerRuntimeResolution {
workerPath: string | null;
isTsNode: boolean;
candidates: string[];
}
3. Build and Graph Pipeline Interfaces¶
3.1 File loading (src/backend/FileLoader.ts)¶
interface RawFile {
filepath: string;
filename: string;
content: string;
}
FileLoader.loadFiles(dirPath: string, extensions = [".md"]): Promise<RawFile[]>
Behavior:
- Recursive directory scan.
- Batched concurrent reads.
- Empty array when directory does not exist.
3.2 Frontmatter parsing (src/backend/utils/frontmatterParser.ts)¶
interface ParsedMetadata {
tags: string[];
prerequisites: string[];
next: string[];
[key: string]: any;
}
FrontmatterParser.parse(content: string): ParsedMetadata
FrontmatterParser.extractTags(content: string): string[]
Supported formats: YAML list, inline array, single value, and [[WikiLink]] cleanup.
3.3 Graph core (src/core/Graph.ts)¶
Primary methods:
addNode(node)getNode(id)hasNode(id)addEdge(source, target, type?, weight?)getOutgoingEdges(id)getIncomingEdges(id)getNeighbors(id)getNodes()getEdges()toJSON()getPredecessors(id)getSuccessors(id)getShortestPath(source, target)
3.4 Graph building orchestration (src/backend/GraphBuilder.ts)¶
Pipeline stages:
- Node initialization (+ metadata/tags)
- Explicit dependency edges (
prerequisites,next) - Keyword matching (parallel workers or sequential fallback)
- Statistical inference
- Vector similarity (
VectorSpaceorVectorSpaceGPU) - Hybrid inference
- Clustering
- Graph metrics
- Cycle detection + topological rank assignment
- Backend layout compute (
LayoutEngine.computeLayout)
Parallel keyword matching contract:
- Worker path from
resolveWorkerRuntimePath. - Falls back to sequential matching when workers fail/unavailable.
3.5 Top-level build output (src/index.ts)¶
Output rules:
- Standard writes active files:
graph_data.jsondata.js(lite payload)- Target builds also write cache copies:
data_<target>.jsgraph_data_<target>.json- CLI mode (
outputPrefix) writesdata_cli_*andgraph_data_cli_*without overwriting active data.
4. Frontend Source Loading Interfaces¶
Source loader: src/frontend/source_manager.js
4.1 Folder and KB path loading¶
Primary API path:
GET /api/kb-pathGET /api/folders
Tauri fallback path:
invoke("get_kb_path")invoke("get_folders")
Dropdown contract:
- Always includes synthetic
ALL_FOLDERS. - Real options come from directories under current KB root.
4.2 Cache check/restore modal contract¶
- Check:
GET /api/check-cache?target=<id> - If cache exists, user decision is required:
Load ExistingRegenerate- Restore:
GET /api/restore-cache?target=<id>
4.3 Single-flight load/build contract¶
Client-side guards:
isLoadInProgressloadBtn.dataset.sourceManagerBound- Session reload guard
nc_reload_guard
Build payload:
{
"target": "ALL_FOLDERS | <folderName>",
"maxWorkers": 4,
"enableGPU": true,
"enableGPULayout": true,
"memorySavingMode": false,
"deepDebug": false
}
4.4 Path mode ownership in Tauri (src/frontend/path_app.js)¶
In Tauri mode:
#path-toolbaris hidden.- Web Path Mode settings group is hidden.
- Layout is backend/runtime-forced to
orbital.
In browser mode:
- Web toolbar remains active for Mode/Strategy/Layout/Complete/History/Exit.
5. Server HTTP API Interfaces (src/server.ts)¶
Base URL: http://localhost:3000
5.1 GET APIs¶
| Endpoint | Query | Success Response | Notes |
|---|---|---|---|
/api/folders |
none | { "folders": string[] } |
Directories under current KB root. |
/api/content |
path |
{ "content": string } |
Reads file content. |
/api/kb-path |
none | { "kbPath": string } |
Current KB root. |
/api/check-cache |
target |
null or { "date": string, "size": number, "source"?: "active" } |
ALL_FOLDERS checks active cache. |
/api/restore-cache |
target |
{ "success": boolean, "deduped"?: true, "error"?: string } |
Includes short-window dedupe. |
Additional static behavior:
- Non-
/api/*.jsand*.jsonpaths are served from frontend output dir.
5.2 POST APIs¶
| Endpoint | Body | Success Response | Notes |
|---|---|---|---|
/api/build |
{ target, maxWorkers, enableGPU, enableGPULayout, memorySavingMode, deepDebug } |
{ "success": true } or { "success": true, "deduped": true } |
Same in-flight payload dedupes; different payload returns 409. |
/api/kb-path |
{ "kbPath": string } |
{ "success": true, "kbPath": string } |
Updates runtime KB root. |
5.3 Build dedupe semantics¶
- Active build + same payload: wait and return deduped success.
- Active build + different payload:
409conflict.
5.4 CLI option parsing notes¶
- Supports
--path,--gpu,--no-gpu,--workers. - Also reads npm env flags and
NOTE_CONNECTION_GPU. - Recommended npm script style for GPU is env flag (
NOTE_CONNECTION_GPU=1) to avoid npm unknown-config warnings.
6. Tauri Rust Command and Event Interfaces (src-tauri/src/lib.rs)¶
6.1 Invokable commands¶
| Command | Signature | Return |
|---|---|---|
get_kb_path |
() -> Result<String, String> |
Default KB path <projectRoot>/Knowledge_Base. |
get_user_language |
() -> Result<String, String> |
Current language (currently defaults to "en"). |
get_folders |
() -> Result<Vec<String>, String> |
Sorted KB folder names. |
set_user_language |
(app, lang) -> Result<(), String> |
Menu language update with idempotent guard. |
check_cache |
(app, target) -> Result<Option<Value>, String> |
Cache metadata or None. |
restore_cache |
(app, target) -> Result<bool, String> |
true if restore succeeded. |
6.2 Menu and emitted events¶
Menu actions:
change_kbreset_kbdocsabout
Emitted frontend event:
kb-path-changedwith payload path string
6.3 Sidecar and Godot process contracts¶
- Sidecar process:
server - Godot process launched with:
--path E:\Knowledge_project\NoteConnection_app\path_mode
7. PathBridge WebSocket Protocol (src/core/PathBridge.ts)¶
Bridge server: ws://127.0.0.1:9876
Client tagging:
- Query param
clientis parsed for diagnostics. - Examples:
ws://127.0.0.1:9876/?client=godotws://localhost:9876?client=frontend
Message envelope:
Supported message types:
nodeClickrequestPathpathResultmarkCompleteswitchCenteropenReaderunmarkCompletecompletionSynctoggleCollapseexpandPrereqscollapsePrereqscollapseAllconfigureexitPathMode
Known payload keys include:
{ nodeId }{ newCenterId, autoReconstruct? }{ completedIds, timestamp? }
Current implementation broadcasts recognized messages to connected clients.
8. Path Worker and Path Payload Interfaces¶
8.1 Path worker (src/frontend/path_worker.js)¶
Inbound messages:
initData->{ nodes, links }computePath->{ mode, strategy, layout, targetId, centralId, collapsedIds, completedIds, forcedExpansionIds, expansionOrder, stickyClaimEnabled }
Outbound messages:
pathResult->{ nodes, edges, treeLayout }
8.2 Path payload sent from web path app to Godot (src/frontend/path_app.js)¶
{
"type": "pathResult",
"payload": {
"central": { "id": "", "label": "", "inDegree": 0, "outDegree": 0 },
"peripherals": [{ "id": "", "label": "", "relation": "prerequisite|association" }],
"progress": { "completed": 0, "total": 0 },
"totalNodes": 0,
"pathNodes": [{ "id": "", "label": "", "parentId": null }],
"treeLayout": { "nodes": [], "edges": [] },
"completedIds": [],
"mode": "orbital"
}
}
When treeLayout is null/empty, Godot falls back to legacy linear rendering path.
9. Godot Interface Contracts¶
9.1 WS client (path_mode/scripts/ws_client.gd)¶
Core constants:
WS_URL = "ws://127.0.0.1:9876/?client=godot"RECONNECT_DELAY = 3.0
Signals:
data_received(data)connecteddisconnectedpath_result(data)path_update(data)switch_center(new_center_id)completion_sync(completed_ids, timestamp)
Send helpers:
send_node_clicksend_mark_completesend_open_readersend_switch_centersend_configuresend_toggle_collapsesend_expand_prereqssend_collapse_prereqssend_collapse_allsend_exit_path_mode
9.2 Path UI (path_mode/scripts/path_mode_ui.gd)¶
Signals:
mark_complete_pressedsidebar_toggled(visible)completed_node_clicked(node_id)return_pressedreturn_to_node(node_id)tree_node_clicked(node_id)unmark_requested(node_id)mark_node_requested(node_id)node_toggle_requested(node_id)node_expand_prereqs_requested(node_id)node_collapse_prereqs_requested(node_id)collapse_all_requested()settings_updated(settings)exit_requested
Runtime config emitted to backend:
{ "mode": "domain|diffusion", "strategy": "foundational|core", "layout": "orbital", "targetId": "<optional>" }
9.3 Learning state machine (path_mode/scripts/learning_state_machine.gd)¶
States:
IDLEVIEWINGTRANSITIONINGREADING
Signals:
state_changedcentral_changednode_completednode_unmarkedpath_complete
Persistence path:
user://orbital_progress.json
9.4 Path renderer (path_mode/scripts/path_renderer.gd)¶
Signals:
node_clicked(node_id)node_double_clicked(node_id)transition_complete()
Critical handlers:
render_path(path_data)_on_ws_data_received(data)_on_settings_updated(settings)-> sendsconfigure_request_switch_center(target_id)-> sendsswitchCenter_on_mark_node_requested(node_id)-> sendsmarkComplete_on_unmark_requested(node_id)-> sendsunmarkComplete_on_exit_requested()-> sendsexitPathMode
9.5 Tree panel (path_mode/scripts/tree_view_panel.gd)¶
Signals relayed upward:
node_navigate_requestednode_mark_complete_requestednode_unmark_requestednode_toggle_requestednode_expand_prereqs_requestednode_collapse_prereqs_requestedcollapse_all_requestedfullscreen_requested(expand)
10. Web vs Tauri Path Mode Ownership Matrix¶
| Interface Area | Browser Mode | Tauri Mode |
|---|---|---|
Path toolbar (#path-toolbar) |
Visible and interactive | Hidden by path_app.js |
| Mode control | Web select (#learning-mode) |
Godot PathModeUI |
| Strategy control | Web select (#strategy) |
Godot PathModeUI |
| Layout control | Web select (#layout-style) |
Backend/Godot forced to orbital |
| Diffusion target picker | Web modal (#node-select-modal) |
Godot target popup |
| Complete action | Web button (#btn-mark-complete) |
Godot button |
| History action | Web sidebar/popup | Godot history popup |
| Exit action | Web button (#btn-exit-path) |
Godot exit flow + exitPathMode bridge message |
This is the current Bridge-first migration contract.
11. Corrected / Removed Legacy Mismatches¶
- Removed duplicated mixed-language blocks and rebuilt strict EN/ZH separation.
- Replaced stale API text with exact
server.tscontracts. - Corrected Godot WebSocket URL requirement:
- valid:
ws://127.0.0.1:9876/?client=godot - Documented actual build/cache dedupe semantics.
- Documented actual Tauri command names and return shapes.
- Added missing path worker payload and Godot signal contracts.
- Clarified Tauri path-control ownership migration to Godot.
12. Handover Checklist¶
- Folder list source must be current KB root (
/api/foldersor Rust fallback). - Cache choice prompt must appear when target cache exists.
- One click should produce one load/build flow only.
- Active graph files must be read from
dist/src/frontend. - Mode/strategy changes should emit
configureand producepathResult. - Godot should receive non-empty
treeLayoutin normal path updates. - Tauri mode should hide web path toolbar; browser mode should keep it.
13. Interface Update Log Placement¶
- Canonical bilingual update logs are centrally archived in
export.md. - This document focuses on interface contracts; historical migration logs are no longer placed at file beginning.
- Related interface delta versions:
2026-03-02 v1.5.1: Interface Delta: Tauri Runtime Parity Update
Archived Interface Delta Block (traceability)¶
2026-03-02 v1.5.1¶
Interface Delta: Tauri Runtime Parity Update¶
This section records interface changes added after v1.4.5, keeping all previous handover content unchanged below.
A. Sidecar HTTP API (Node)¶
GET /api/available-targets- Purpose: return selectable learning/build targets merged from:
- physical subfolders under
Knowledge_Base - cached artifacts like
data_<target>.js,graph_data_<target>.json
- physical subfolders under
- Response:
B. Tauri Commands (Rust IPC)¶
get_available_targets() -> string[]-
Contract: same merged target semantics as
/api/available-targets. -
read_node_content(file_path: string) -> Result<string, string> - Contract:
- Accepts relative paths and absolute paths.
- Enforces KB-root boundary (rejects files outside configured
Knowledge_Base). - Supports legacy desktop-style paths containing
.../Knowledge_Base/...by rebasing to current configured KB root.
C. Runtime Capability Contract Update¶
get_runtime_capabilities()now returnssupports_content_api: trueon Android.- Rationale: content reads are now available through Rust
read_node_contentcommand even when sidecar is disabled.
D. Frontend Behavior Contract Changes¶
source_manager.js- Sidecar path prefers
/api/available-targetsand falls back to/api/folders. - Rust path prefers
get_available_targetsand falls back toget_folders. -
In
supports_build=falseruntime (mobile):- Source list is filtered to cached targets only.
ALL_FOLDERSis shown only if active cache exists.- Load button is disabled if no cache is available.
-
reader.js - Content loading fallback order:
- sidecar
/api/content(desktop/web path) - Rust command
read_node_content(Tauri fallback/mobile-safe) - localized unavailable/error messaging
- sidecar
E. Verification Interface Baseline¶
npm run test:migrationpassed (35 tests).npm run test:tauripassed (14 tests).npm run tauri:android:buildpassed.