@mfdaves/okf-mcp 0.3.2-rc.1

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.
@@ -0,0 +1,28 @@
1
+ ---
2
+ id: okf://okf-mcp/overview/okf-mcp
3
+ type: OKF Product
4
+ title: okf-mcp
5
+ description: Project-agnostic OKF CLI, graph index, MCP stdio server, and proposal-based authoring runtime.
6
+ tags: [okf, mcp, runtime, knowledge-graph]
7
+ relations:
8
+ - type: depends_on
9
+ target: okf://okf-mcp/runtime/mcp-server
10
+ - type: depends_on
11
+ target: okf://okf-mcp/runtime/indexer
12
+ - type: related_to
13
+ target: okf://okf-mcp/interfaces/http-authoring-api
14
+ - type: produces
15
+ target: okf://okf-mcp/distribution/reference-bundle
16
+ - type: configured_by
17
+ target: repo://package.json
18
+ ---
19
+
20
+ # okf-mcp
21
+
22
+ `okf-mcp` turns directories of OKF Markdown concepts into a searchable in-memory knowledge graph. It provides a command-line interface, a JSON-RPC stdio MCP server, generator plugins, remote GitHub bundles, and an optional HTTP authoring API.
23
+
24
+ The core has no runtime dependencies, database, or embedding service. Local bundle mode performs no network calls. Project mode adds configuration, typed relations, proposal storage, and guarded writes to local bundle directories.
25
+
26
+ The primary runtime entry is the [MCP stdio server](../runtime/mcp-server.md). Concept interpretation and graph construction belong to the [indexer](../runtime/indexer.md). Durable knowledge changes follow the [concept authoring workflow](../workflows/concept-authoring.md) and [authoring safety policy](../policies/authoring-safety.md).
27
+
28
+ The HTTP server is an authoring API rather than a remotely hosted MCP transport. The canonical public architectural reference is this [published reference bundle](../distribution/reference-bundle.md).
@@ -0,0 +1,38 @@
1
+ ---
2
+ id: okf://okf-mcp/policies/authoring-safety
3
+ type: OKF Policy
4
+ title: Authoring Safety
5
+ description: Invariants protecting project boundaries, concept identity, review state, and concurrent edits.
6
+ tags: [policy, safety, authoring, filesystem]
7
+ relations:
8
+ - type: related_to
9
+ target: okf://okf-mcp/runtime/file-concept-store
10
+ - type: related_to
11
+ target: okf://okf-mcp/workflows/concept-authoring
12
+ - type: related_to
13
+ target: okf://okf-mcp/workflows/concept-update
14
+ - type: configured_by
15
+ target: repo://src/authoring.js
16
+ - type: configured_by
17
+ target: repo://src/store.js
18
+ - type: checked_by
19
+ target: repo://test/okf-mcp.test.js
20
+ - type: checked_by
21
+ target: repo://test/mcp-hardening.test.js
22
+ ---
23
+
24
+ # Authoring Safety
25
+
26
+ Authoring is allowed only for local bundles declared by `okf.project.yaml`. MCP proposal mutations additionally require the explicit `--authoring` capability. Remote bundles are read only.
27
+
28
+ Concept paths must be safe relative `.md` paths inside the selected bundle. Absolute paths, parent traversal, reserved `index.md` and `log.md` targets, symbolic-link traversal, and non-directory parents are rejected.
29
+
30
+ New concepts cannot reuse an existing path URI or stable id. Updates are bound to the existing bundle, path, path URI, and canonical identity. Updating a concept cannot rename its stable URI.
31
+
32
+ Candidates must satisfy the concept format, configured relation vocabulary, and internal target integrity. External schemes such as `repo://` are allowed as opaque references.
33
+
34
+ Proposal creation never writes a concept file. Acceptance repeats validation. Updates also compare the source revision immediately before replacement and return conflicts for detected concurrent changes. After acceptance, the MCP index is rebuilt without discarding configured or runtime-loaded remote bundle state.
35
+
36
+ HTTP mutations require bearer authorization. Filesystem safeguards still apply after authentication.
37
+
38
+ The local file store is designed for one trusted project workspace. Multiple independent authoring workers require an external coordination or locking strategy.
@@ -0,0 +1,30 @@
1
+ ---
2
+ id: okf://okf-mcp/runtime/file-concept-store
3
+ type: OKF Runtime Component
4
+ title: File Concept Store
5
+ description: Local proposal and concept persistence boundary used by project authoring.
6
+ tags: [storage, proposals, authoring, filesystem]
7
+ relations:
8
+ - type: consumes
9
+ target: okf://okf-mcp/specs/concept-format
10
+ - type: related_to
11
+ target: okf://okf-mcp/workflows/concept-authoring
12
+ - type: related_to
13
+ target: okf://okf-mcp/workflows/concept-update
14
+ - type: checked_by
15
+ target: okf://okf-mcp/policies/authoring-safety
16
+ - type: configured_by
17
+ target: repo://src/store.js
18
+ ---
19
+
20
+ # File Concept Store
21
+
22
+ The file concept store is the persistence boundary for project-mode authoring. Proposal records are JSON files under `.okf-proposals` by default. Concept files remain ordinary Markdown inside configured local bundles.
23
+
24
+ Proposal states are `proposed`, `accepted`, and `rejected`. Creating or updating a proposal writes only the proposal record. Acceptance revalidates the candidate before changing a concept file.
25
+
26
+ New concepts use exclusive creation. Updates retain a SHA256 revision of the source content and check it again immediately before atomic replacement. Detected concurrent changes return a conflict and preserve the current file.
27
+
28
+ Write paths are normalized relative Markdown paths. Reserved files are rejected, bundle boundaries are enforced, and symbolic-link traversal is blocked. Update proposals are also bound to the original bundle, path, and stable concept identity.
29
+
30
+ This is a local file-backed store intended for a trusted project workspace. It is not a distributed transaction system or multi-writer database. Its invariants are defined by the [authoring safety policy](../policies/authoring-safety.md).
@@ -0,0 +1,34 @@
1
+ ---
2
+ id: okf://okf-mcp/runtime/indexer
3
+ type: OKF Runtime Component
4
+ title: OKF Indexer
5
+ description: Builds the validated in-memory document, concept, relation, and reference graph.
6
+ tags: [indexer, graph, validation, runtime]
7
+ relations:
8
+ - type: consumes
9
+ target: okf://okf-mcp/specs/concept-format
10
+ - type: produces
11
+ target: okf://okf-mcp/interfaces/mcp-tools
12
+ - type: configured_by
13
+ target: repo://src/indexer.js
14
+ - type: configured_by
15
+ target: repo://src/project.js
16
+ - type: checked_by
17
+ target: repo://test/okf-mcp.test.js
18
+ - type: checked_by
19
+ target: repo://test/conformance.test.js
20
+ ---
21
+
22
+ # OKF Indexer
23
+
24
+ The indexer loads configured bundle directories, applies include and exclude filters, parses Markdown documents with the safe YAML core schema, and builds a bounded in-memory graph. It keeps separate collections for all documents, valid concepts, reserved resources, edges, warnings, and errors.
25
+
26
+ Both canonical ids and path-derived URIs resolve through the URI map. Graph operations normalize path aliases to canonical ids before traversal.
27
+
28
+ Markdown links become `markdown_link` edges. Frontmatter relations become typed `relation` edges. Internal targets are validated, while non-OKF schemes are recorded as external references.
29
+
30
+ Validation is layered. OKF conformance checks parseable mapping frontmatter, a non-empty concept `type`, and the reserved structures of `index.md` and `log.md`. Unknown fields and unknown type values remain conformant. Project validity additionally covers missing roots, invalid paths, duplicate bundle ids, duplicate concept URIs, unsupported relation types, broken Markdown links, and broken internal targets.
31
+
32
+ Results expose `conformant`, `validForProject`, and structured diagnostics. `valid` is a compatibility alias for `validForProject`. Valid concepts continue to be served even when other files produce diagnostics.
33
+
34
+ The [concept format](../specs/concept-format.md) is the input contract. Indexed results power the discovery and graph families in the [MCP tool catalog](../interfaces/mcp-tools.md).
@@ -0,0 +1,32 @@
1
+ ---
2
+ id: okf://okf-mcp/runtime/mcp-server
3
+ type: OKF Runtime Component
4
+ title: MCP Stdio Server
5
+ description: JSON-RPC stdio MCP runtime exposing OKF resources and tools.
6
+ tags: [mcp, stdio, json-rpc, runtime]
7
+ relations:
8
+ - type: depends_on
9
+ target: okf://okf-mcp/runtime/indexer
10
+ - type: depends_on
11
+ target: okf://okf-mcp/interfaces/mcp-tools
12
+ - type: depends_on
13
+ target: okf://okf-mcp/workflows/concept-authoring
14
+ - type: configured_by
15
+ target: repo://src/mcp-server.js
16
+ - type: checked_by
17
+ target: repo://test/okf-mcp.test.js
18
+ - type: checked_by
19
+ target: repo://test/mcp-hardening.test.js
20
+ ---
21
+
22
+ # MCP Stdio Server
23
+
24
+ The MCP server reads newline-delimited JSON-RPC messages from stdin and writes responses to stdout. It implements initialization, resource listing and reading, tool listing, and tool calls without an SDK dependency. Initialization accepts only an explicit supported protocol version and rejects unsupported client versions instead of echoing them.
25
+
26
+ Each indexed Markdown document is exposed as a `text/markdown` resource. The [MCP tool catalog](../interfaces/mcp-tools.md) exposes discovery, search, graph navigation, validation, remote loading, and proposal-based authoring.
27
+
28
+ Bundle mode is read oriented. Project mode loads `okf.project.yaml`, enables configured relation types, and supplies the store required by the [authoring workflow](../workflows/concept-authoring.md). Proposal mutation tools remain disabled unless the server starts with `--authoring`. Runtime remote loading remains disabled unless it starts with `--allow-remote-tool`.
29
+
30
+ Remote GitHub bundles are fetched as Markdown and added to the in-memory index. They remain read only and never execute remote code. After an accepted local proposal, one reconstruction path rebuilds the index from configured local bundles, configured remote bundles, and runtime-loaded remote bundles, preserving remote concepts and relationships.
31
+
32
+ This component is a stdio MCP transport. The separate [HTTP authoring API](../interfaces/http-authoring-api.md) does not implement MCP over HTTP.
@@ -0,0 +1,32 @@
1
+ ---
2
+ id: okf://okf-mcp/specs/concept-format
3
+ type: OKF Data Contract
4
+ title: OKF Concept Format
5
+ description: Markdown and frontmatter contract consumed and produced by okf-mcp.
6
+ tags: [okf, contract, markdown, yaml]
7
+ relations:
8
+ - type: configured_by
9
+ target: repo://src/parser.js
10
+ - type: related_to
11
+ target: okf://okf-mcp/runtime/indexer
12
+ - type: related_to
13
+ target: okf://okf-mcp/runtime/file-concept-store
14
+ - type: checked_by
15
+ target: repo://test/okf-mcp.test.js
16
+ - type: checked_by
17
+ target: repo://test/conformance.test.js
18
+ ---
19
+
20
+ # OKF Concept Format
21
+
22
+ An OKF concept is a Markdown file with YAML frontmatter. A non-empty `type` is required. `title`, `description`, `tags`, `aliases`, and typed `relations` provide structured metadata, while the Markdown body carries the durable explanation.
23
+
24
+ The optional `id` field defines a stable `okf://` URI. Without it, the URI is derived from the bundle id and relative file path. A stable id is preferred for public concepts because it survives file moves. The path-derived URI remains an alias in the index.
25
+
26
+ Frontmatter is parsed as a YAML mapping with the safe core schema. Nested mappings, arrays, block scalars, and unknown extension keys are preserved. Duplicate mapping keys and unsupported custom tags are rejected. Unknown concept type values do not fail OKF conformance.
27
+
28
+ Files named `index.md` and `log.md` are reserved resources and are not concepts. Reserved indexes group local Markdown links under headings. Reserved logs use an H1 title followed by newest-first ISO-dated H2 sections containing list entries.
29
+
30
+ Internal `okf://` relation targets and Markdown links are checked as project rules rather than redefining minimum document conformance. Other schemes such as `repo://` are retained as opaque external references.
31
+
32
+ The [indexer](../runtime/indexer.md) validates this contract. Accepted proposals are rendered back into this format by the [file concept store](../runtime/file-concept-store.md).
@@ -0,0 +1,30 @@
1
+ ---
2
+ id: okf://okf-mcp/workflows/concept-authoring
3
+ type: OKF Workflow
4
+ title: Concept Authoring
5
+ description: Proposal-first workflow for validating, reviewing, and accepting new OKF concepts.
6
+ tags: [workflow, authoring, proposals, review]
7
+ relations:
8
+ - type: depends_on
9
+ target: okf://okf-mcp/runtime/file-concept-store
10
+ - type: consumes
11
+ target: okf://okf-mcp/specs/concept-format
12
+ - type: checked_by
13
+ target: okf://okf-mcp/policies/authoring-safety
14
+ - type: related_to
15
+ target: okf://okf-mcp/workflows/concept-update
16
+ - type: configured_by
17
+ target: repo://src/authoring.js
18
+ ---
19
+
20
+ # Concept Authoring
21
+
22
+ Concept authoring separates proposal from persistence.
23
+
24
+ First, the candidate bundle, path, frontmatter, body, links, relations, and identity are validated. A valid proposal stores the candidate Markdown and its validation result as a proposal record. It does not create the concept file.
25
+
26
+ A reviewer then inspects the proposal and either accepts or rejects it. Acceptance repeats validation against the current project index, creates the target directory when needed, and writes the new concept using exclusive file creation. The MCP server refreshes its index after a successful acceptance.
27
+
28
+ Invalid candidates never become proposals. A proposal that becomes invalid before acceptance remains inspectable and returns the current validation result.
29
+
30
+ Corrections to existing concepts follow the related [concept update workflow](concept-update.md). Both paths are governed by the [authoring safety policy](../policies/authoring-safety.md) and persist through the [file concept store](../runtime/file-concept-store.md).
@@ -0,0 +1,30 @@
1
+ ---
2
+ id: okf://okf-mcp/workflows/concept-update
3
+ type: OKF Workflow
4
+ title: Concept Update
5
+ description: Guarded proposal workflow for correcting an existing OKF concept without losing concurrent changes.
6
+ tags: [workflow, update, correction, concurrency]
7
+ relations:
8
+ - type: depends_on
9
+ target: okf://okf-mcp/workflows/concept-authoring
10
+ - type: depends_on
11
+ target: okf://okf-mcp/runtime/file-concept-store
12
+ - type: checked_by
13
+ target: okf://okf-mcp/policies/authoring-safety
14
+ - type: configured_by
15
+ target: repo://src/authoring.js
16
+ - type: configured_by
17
+ target: repo://src/store.js
18
+ ---
19
+
20
+ # Concept Update
21
+
22
+ An update begins by reading the current concept through `get_concept`. `okf_propose_update` targets that concept by canonical or path-derived URI.
23
+
24
+ The caller may provide a frontmatter patch, a list of frontmatter keys to remove, a replacement body, or a combination. Unspecified frontmatter and an omitted body are preserved. The stable concept URI cannot change through this operation.
25
+
26
+ The proposal stores the complete candidate plus the SHA256 revision of the source content. Acceptance verifies that the target still has the same bundle, path, and identity, revalidates the candidate, and compares the source revision again immediately before atomic replacement.
27
+
28
+ When a detected edit changes the source after proposal creation, acceptance returns a conflict without overwriting the current concept. The caller must read the current concept and create a new proposal.
29
+
30
+ This workflow corrects knowledge while retaining review and conflict visibility. It is governed by the [authoring safety policy](../policies/authoring-safety.md).
@@ -0,0 +1,5 @@
1
+ project: okf-mcp
2
+ bundles:
3
+ - id: okf-mcp
4
+ root: okf/bundles/okf-mcp
5
+ include: ["*.md", "**/*.md"]
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@mfdaves/okf-mcp",
3
+ "version": "0.3.2-rc.1",
4
+ "description": "Local-first Open Knowledge Format validator, graph index, CLI, and MCP stdio server.",
5
+ "homepage": "https://github.com/mfdaves/okf-mcp#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mfdaves/okf-mcp.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/mfdaves/okf-mcp/issues"
12
+ },
13
+ "type": "commonjs",
14
+ "main": "src/index.js",
15
+ "bin": {
16
+ "okf": "bin/okf-mcp.js",
17
+ "okf-mcp": "bin/okf-mcp.js"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "check": "node --test",
22
+ "self:validate": "node bin/okf-mcp.js --project okf.project.yaml validate",
23
+ "pack:check": "npm pack --dry-run",
24
+ "package:smoke": "node scripts/package-smoke.js",
25
+ "prepublishOnly": "npm run check && npm run self:validate",
26
+ "inspect": "node bin/okf-mcp.js --help",
27
+ "start": "node bin/okf-mcp.js"
28
+ },
29
+ "keywords": [
30
+ "mcp",
31
+ "okf",
32
+ "open-knowledge-format",
33
+ "markdown",
34
+ "knowledge-graph",
35
+ "agents"
36
+ ],
37
+ "license": "MIT",
38
+ "files": [
39
+ "bin",
40
+ "src",
41
+ "okf",
42
+ "okf.project.yaml",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "engines": {
47
+ "node": ">=22"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "dependencies": {
53
+ "js-yaml": "^5.2.1"
54
+ }
55
+ }
@@ -0,0 +1,334 @@
1
+ "use strict";
2
+
3
+ const path = require("path");
4
+ const yaml = require("js-yaml");
5
+ const { parseMarkdownText, normalizeSlashes } = require("./parser");
6
+ const { resolveLinkPath } = require("./indexer");
7
+
8
+ function slug(value, fallback) {
9
+ const text = String(value || fallback || "concept").trim().toLowerCase();
10
+ return text
11
+ .replace(/[^a-z0-9]+/g, "-")
12
+ .replace(/^-+|-+$/g, "") || String(fallback || "concept");
13
+ }
14
+
15
+ function normalizeConceptPath(value) {
16
+ const raw = normalizeSlashes(String(value || "").trim());
17
+ if (!raw) {
18
+ throw new Error("Concept path is required.");
19
+ }
20
+ if (raw.startsWith("/") || raw.includes("\0")) {
21
+ throw new Error("Concept path must be a safe relative path.");
22
+ }
23
+ const normalized = path.posix.normalize(raw);
24
+ if (!normalized || normalized === "." || normalized.startsWith("../") || normalized === "..") {
25
+ throw new Error("Concept path must stay inside the bundle.");
26
+ }
27
+ if (normalized.split("/").some((part) => !part || part === "." || part === "..")) {
28
+ throw new Error("Concept path contains an unsafe segment.");
29
+ }
30
+ if (!normalized.toLowerCase().endsWith(".md")) {
31
+ throw new Error("Concept path must end with .md.");
32
+ }
33
+ const base = path.posix.basename(normalized).toLowerCase();
34
+ if (base === "index.md" || base === "log.md") {
35
+ throw new Error("Concept path cannot be a reserved index.md or log.md file.");
36
+ }
37
+ return normalized;
38
+ }
39
+
40
+ function renderFrontmatter(frontmatter) {
41
+ const values = Object.fromEntries(
42
+ Object.entries(frontmatter || {}).filter((entry) => entry[1] !== undefined),
43
+ );
44
+ return yaml.dump(values, {
45
+ schema: yaml.CORE_SCHEMA,
46
+ noRefs: true,
47
+ lineWidth: -1,
48
+ sortKeys: false,
49
+ }).trimEnd();
50
+ }
51
+
52
+ function renderConceptMarkdown(input) {
53
+ const frontmatter = Object.assign({}, input && input.frontmatter ? input.frontmatter : {});
54
+ const body = String((input && input.body) || "").replace(/\r\n/g, "\n").trim();
55
+ return [
56
+ "---",
57
+ renderFrontmatter(frontmatter),
58
+ "---",
59
+ "",
60
+ body || `# ${frontmatter.title || path.posix.basename(input.path || "concept.md", ".md")}`,
61
+ "",
62
+ ].join("\n");
63
+ }
64
+
65
+ function relationFrom(value, doc) {
66
+ if (typeof value === "string") {
67
+ const parts = value.trim().split(/\s+/);
68
+ if (parts.length === 1) {
69
+ return { type: "related_to", target: parts[0], source: doc.uri };
70
+ }
71
+ return { type: parts[0], target: parts.slice(1).join(" "), source: doc.uri };
72
+ }
73
+ if (value && typeof value === "object") {
74
+ return {
75
+ type: value.type || value.kind || "related_to",
76
+ target: value.target || value.to || "",
77
+ source: doc.uri,
78
+ label: value.label || value.text || "",
79
+ description: value.description || "",
80
+ };
81
+ }
82
+ return { type: "related_to", target: "", source: doc.uri };
83
+ }
84
+
85
+ class ConceptAuthoringService {
86
+ constructor(store) {
87
+ this.store = store;
88
+ }
89
+
90
+ getBundle(id) {
91
+ const bundle = this.store.getBundles().find((entry) => entry.id === id);
92
+ if (!bundle) {
93
+ throw new Error(`Unknown writable OKF bundle: ${id || "<missing>"}`);
94
+ }
95
+ if (bundle.remote) {
96
+ throw new Error(`Cannot write concepts to remote bundle: ${id}`);
97
+ }
98
+ return bundle;
99
+ }
100
+
101
+ suggestConceptPath(input) {
102
+ const prefix = input && input.prefix ? normalizeSlashes(String(input.prefix)).replace(/^\/+|\/+$/g, "") : "";
103
+ if (prefix && (prefix === "." || prefix.startsWith("../") || prefix.includes("/../"))) {
104
+ throw new Error("Path prefix must stay inside the bundle.");
105
+ }
106
+ const typePart = slug(input && input.type, "concept");
107
+ const titlePart = slug(input && input.title, typePart);
108
+ return {
109
+ bundle: input && input.bundle,
110
+ path: normalizeConceptPath([prefix, typePart, `${titlePart}.md`].filter(Boolean).join("/")),
111
+ };
112
+ }
113
+
114
+ validateConcept(input, options) {
115
+ const bundleId = input && input.bundle;
116
+ const bundle = this.getBundle(bundleId);
117
+ const conceptPath = normalizeConceptPath(input && input.path);
118
+ const frontmatter = Object.assign({}, input && input.frontmatter ? input.frontmatter : {});
119
+ const markdown = renderConceptMarkdown({ path: conceptPath, frontmatter, body: input && input.body });
120
+ const index = this.store.getIndex();
121
+ const replace = options && options.replace;
122
+ const errors = [];
123
+ const warnings = [];
124
+ let doc = null;
125
+
126
+ function isReplacedConcept(existing) {
127
+ return Boolean(
128
+ replace
129
+ && existing
130
+ && existing.bundle === replace.bundle
131
+ && existing.path === replace.path,
132
+ );
133
+ }
134
+
135
+ try {
136
+ doc = parseMarkdownText(bundle, conceptPath, markdown, `${bundle.root}/${conceptPath}`);
137
+ } catch (error) {
138
+ errors.push({ code: "parse_error", bundle: bundleId, path: conceptPath, message: error.message });
139
+ return { valid: false, bundle: bundleId, path: conceptPath, markdown, errors, warnings };
140
+ }
141
+
142
+ doc.warnings.forEach((warning) => {
143
+ const entry = Object.assign({ bundle: bundleId }, warning);
144
+ if (entry.code === "missing_type" || entry.code === "missing_frontmatter" || entry.code === "invalid_id") {
145
+ errors.push(entry);
146
+ } else {
147
+ warnings.push(entry);
148
+ }
149
+ });
150
+
151
+ const existingAtPath = index.byUri.get(doc.pathUri);
152
+ if (existingAtPath && !isReplacedConcept(existingAtPath)) {
153
+ errors.push({ code: "duplicate_uri", bundle: bundleId, path: conceptPath, uri: doc.pathUri, message: "Concept path already exists." });
154
+ }
155
+ const existingAtUri = index.byUri.get(doc.uri);
156
+ if (doc.uri !== doc.pathUri && existingAtUri && !isReplacedConcept(existingAtUri)) {
157
+ errors.push({ code: "duplicate_uri", bundle: bundleId, path: conceptPath, uri: doc.uri, message: "Concept id already exists." });
158
+ }
159
+
160
+ doc.links.forEach((link) => {
161
+ const resolved = resolveLinkPath(bundle, doc.path, link.href);
162
+ if (!resolved) {
163
+ return;
164
+ }
165
+ if (resolved.outsideRoot) {
166
+ warnings.push({ code: "link_outside_root", bundle: bundleId, path: doc.path, href: link.href, message: "Markdown link resolves outside bundle root." });
167
+ return;
168
+ }
169
+ if (!index.byUri.has(resolved.uri) && resolved.uri !== doc.uri && resolved.uri !== doc.pathUri) {
170
+ warnings.push({ code: "broken_link", bundle: bundleId, path: doc.path, href: link.href, target: resolved.path, message: "Markdown link target does not exist in bundle." });
171
+ }
172
+ });
173
+
174
+ const relationTypes = new Set(this.store.getRelationTypes().map(String));
175
+ doc.relations.map((relation) => relationFrom(relation, doc)).forEach((relation) => {
176
+ const type = String(relation.type || "related_to");
177
+ const targetUri = String(relation.target || "").trim();
178
+ if (!targetUri) {
179
+ errors.push({ code: "missing_relation_target", bundle: bundleId, path: doc.path, relationType: type, message: "Relation has no target." });
180
+ return;
181
+ }
182
+ if (!relationTypes.has(type)) {
183
+ errors.push({ code: "invalid_relation_type", bundle: bundleId, path: doc.path, relationType: type, message: `Unsupported relation type: ${type}` });
184
+ }
185
+ if (targetUri.startsWith("okf://") && !index.byUri.has(targetUri) && targetUri !== doc.uri && targetUri !== doc.pathUri) {
186
+ errors.push({ code: "broken_relation", bundle: bundleId, path: doc.path, target: targetUri, relationType: type, message: "Relation target does not exist." });
187
+ }
188
+ });
189
+
190
+ return {
191
+ valid: errors.length === 0,
192
+ bundle: bundleId,
193
+ path: conceptPath,
194
+ uri: doc.uri,
195
+ pathUri: doc.pathUri,
196
+ markdown,
197
+ concept: {
198
+ uri: doc.uri,
199
+ pathUri: doc.pathUri,
200
+ type: doc.type,
201
+ title: doc.title,
202
+ description: doc.description,
203
+ tags: doc.tags,
204
+ aliases: doc.aliases,
205
+ },
206
+ errors,
207
+ warnings,
208
+ };
209
+ }
210
+
211
+ async proposeConcept(input) {
212
+ const validation = this.validateConcept(input || {});
213
+ if (!validation.valid) {
214
+ return { created: false, validation };
215
+ }
216
+ const proposal = await this.store.saveProposal({
217
+ op: "create",
218
+ bundle: validation.bundle,
219
+ path: validation.path,
220
+ frontmatter: Object.assign({}, input.frontmatter || {}),
221
+ body: String(input.body || ""),
222
+ markdown: validation.markdown,
223
+ message: input.message || "",
224
+ validation,
225
+ });
226
+ return { created: true, proposal };
227
+ }
228
+
229
+ resolveConcept(uri) {
230
+ const index = this.store.getIndex();
231
+ const existing = uri ? index.byUri.get(uri) : null;
232
+ if (!existing || existing.reserved || !existing.valid) {
233
+ throw new Error(`Unknown valid OKF concept: ${uri || "<missing>"}`);
234
+ }
235
+ this.getBundle(existing.bundle);
236
+ return existing;
237
+ }
238
+
239
+ validateUpdateCandidate(input, existing) {
240
+ const validation = this.validateConcept({
241
+ bundle: existing.bundle,
242
+ path: existing.path,
243
+ frontmatter: input.frontmatter,
244
+ body: input.body,
245
+ }, {
246
+ replace: {
247
+ bundle: existing.bundle,
248
+ path: existing.path,
249
+ },
250
+ });
251
+ if (validation.uri !== existing.uri) {
252
+ validation.errors.push({
253
+ code: "immutable_uri",
254
+ bundle: existing.bundle,
255
+ path: existing.path,
256
+ uri: validation.uri,
257
+ message: "Concept updates cannot change the existing concept URI.",
258
+ });
259
+ validation.valid = false;
260
+ }
261
+ return validation;
262
+ }
263
+
264
+ async proposeUpdate(input) {
265
+ const uri = input && input.uri;
266
+ if (!uri) {
267
+ throw new Error("okf_propose_update requires uri.");
268
+ }
269
+ const existing = this.resolveConcept(uri);
270
+ const patch = input && input.frontmatter === undefined ? {} : input.frontmatter;
271
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
272
+ throw new Error("frontmatter must be an object when provided.");
273
+ }
274
+ const removeKeys = input && input.removeFrontmatterKeys === undefined
275
+ ? []
276
+ : input.removeFrontmatterKeys;
277
+ if (!Array.isArray(removeKeys) || removeKeys.some((key) => typeof key !== "string" || !key.trim())) {
278
+ throw new Error("removeFrontmatterKeys must be an array of non-empty strings.");
279
+ }
280
+ if (removeKeys.includes("id")) {
281
+ throw new Error("Concept updates cannot remove the existing concept id.");
282
+ }
283
+ const hasBody = Boolean(input && Object.prototype.hasOwnProperty.call(input, "body"));
284
+ if (!Object.keys(patch).length && !removeKeys.length && !hasBody) {
285
+ throw new Error("okf_propose_update requires a frontmatter change, a removed key, or a body replacement.");
286
+ }
287
+ const frontmatter = Object.assign({}, existing.frontmatter, patch);
288
+ removeKeys.forEach((key) => {
289
+ delete frontmatter[key];
290
+ });
291
+ const body = hasBody ? String(input.body || "") : existing.body;
292
+ const validation = this.validateUpdateCandidate({ frontmatter, body }, existing);
293
+ if (!validation.valid) {
294
+ return { created: false, op: "update", validation };
295
+ }
296
+ const proposal = await this.store.saveProposal({
297
+ op: "update",
298
+ targetUri: existing.uri,
299
+ targetPathUri: existing.pathUri,
300
+ baseRevision: this.store.getContentRevision(existing.text),
301
+ bundle: validation.bundle,
302
+ path: validation.path,
303
+ frontmatter,
304
+ body,
305
+ markdown: validation.markdown,
306
+ message: input.message || "",
307
+ validation,
308
+ });
309
+ return { created: true, op: "update", proposal };
310
+ }
311
+
312
+ async listProposals(input) {
313
+ return this.store.listProposals(input || {});
314
+ }
315
+
316
+ async getProposal(input) {
317
+ return this.store.getProposal(input && input.proposalId);
318
+ }
319
+
320
+ async acceptProposal(input) {
321
+ return this.store.acceptProposal(input && input.proposalId, this);
322
+ }
323
+
324
+ async rejectProposal(input) {
325
+ return this.store.rejectProposal(input && input.proposalId, input && input.reason);
326
+ }
327
+ }
328
+
329
+ module.exports = {
330
+ ConceptAuthoringService,
331
+ normalizeConceptPath,
332
+ renderConceptMarkdown,
333
+ slug,
334
+ };